file_path
stringclasses
1 value
content
stringlengths
0
219k
from _2017.nn.network import * from _2017.nn.part1 import * from _2017.nn.part2 import * class LayOutPlan(Scene): def construct(self): title = OldTexText("Plan") title.scale(1.5) title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS - 1) h_line.next_to(title, DOWN) items = BulletedList( "Recap", "Intuitive walkthrough", "Derivatives in \\\\ computational graphs", ) items.to_edge(LEFT, buff = LARGE_BUFF) self.add(items) rect = ScreenRectangle() rect.set_width(FRAME_WIDTH - items.get_width() - 2) rect.next_to(items, RIGHT, MED_LARGE_BUFF) self.play( Write(title), ShowCreation(h_line), ShowCreation(rect), run_time = 2 ) for i in range(len(items)): self.play(items.fade_all_but, i) self.wait(2) class TODOInsertFeedForwardAnimations(TODOStub): CONFIG = { "message" : "Insert Feed Forward Animations" } class TODOInsertStepsDownCostSurface(TODOStub): CONFIG = { "message" : "Insert Steps Down Cost Surface" } class TODOInsertDefinitionOfCostFunction(TODOStub): CONFIG = { "message" : "Insert Definition of cost function" } class TODOInsertGradientNudging(TODOStub): CONFIG = { "message" : "Insert GradientNudging" } class InterpretGradientComponents(GradientNudging): CONFIG = { "network_mob_config" : { "layer_to_layer_buff" : 3, }, "stroke_width_exp" : 2, "n_decimals" : 6, "n_steps" : 3, "start_cost" : 3.48, "delta_cost" : -0.21, } def construct(self): self.setup_network() self.add_cost() self.add_gradient() self.change_weights_repeatedly() self.ask_about_high_dimensions() self.circle_magnitudes() self.isolate_particular_weights() self.shift_cost_expression() self.tweak_individual_weights() def setup_network(self): self.network_mob.scale(0.55) self.network_mob.to_corner(UP+RIGHT) self.color_network_edges() def add_cost(self): rect = SurroundingRectangle(self.network_mob) rect.set_color(RED) arrow = Vector(DOWN, color = RED) arrow.shift(rect.get_bottom()) cost = DecimalNumber(self.start_cost) cost.set_color(RED) cost.next_to(arrow, DOWN) cost_expression = OldTex( "C(", "w_0, w_1, \\dots, w_{13{,}001}", ")", "=" ) for tex in "()": cost_expression.set_color_by_tex(tex, RED) cost_expression.next_to(cost, DOWN) cost_group = VGroup(cost_expression, cost) cost_group.arrange(RIGHT) cost_group.next_to(arrow, DOWN) self.add(rect, arrow, cost_group) self.set_variables_as_attrs( cost, cost_expression, cost_group, network_rect = rect ) def change_weights_repeatedly(self): decimals = self.grad_vect.decimals grad_terms = self.grad_vect.contents edges = VGroup(*reversed(list( it.chain(*self.network_mob.edge_groups) ))) cost = self.cost for x in range(self.n_steps): self.move_grad_terms_into_position( grad_terms.copy(), *self.get_weight_adjustment_anims(edges, cost) ) self.play(*self.get_decimal_change_anims(decimals)) def ask_about_high_dimensions(self): grad_vect = self.grad_vect words = OldTexText( "Direction in \\\\ ${13{,}002}$ dimensions?!?") words.set_color(YELLOW) words.move_to(grad_vect).to_edge(DOWN) arrow = Arrow( words.get_top(), grad_vect.get_bottom(), buff = SMALL_BUFF ) randy = Randolph() randy.scale(0.6) randy.next_to(words, LEFT) randy.shift_onto_screen() self.play( Write(words, run_time = 2), GrowArrow(arrow), ) self.play(FadeIn(randy)) self.play(randy.change, "confused", words) self.play(Blink(randy)) self.wait() self.play(*list(map(FadeOut, [randy, words, arrow]))) def circle_magnitudes(self): rects = VGroup() for decimal in self.grad_vect.decimals: rects.add(SurroundingRectangle(VGroup(*decimal[-8:]))) rects.set_color(WHITE) self.play(LaggedStartMap(ShowCreation, rects)) self.play(FadeOut(rects)) def isolate_particular_weights(self): vect_contents = self.grad_vect.contents w_terms = self.cost_expression[1] edges = self.network_mob.edge_groups edge1 = self.network_mob.layers[1].neurons[3].edges_in[0].copy() edge2 = self.network_mob.layers[1].neurons[9].edges_in[15].copy() VGroup(edge1, edge2).set_stroke(width = 4) d1 = DecimalNumber(3.2) d2 = DecimalNumber(0.1) VGroup(edge1, d1).set_color(YELLOW) VGroup(edge2, d2).set_color(MAROON_B) new_vect_contents = VGroup( OldTex("\\vdots"), d1, OldTex("\\vdots"), d2, OldTex("\\vdots"), ) new_vect_contents.arrange(DOWN) new_vect_contents.move_to(vect_contents) new_w_terms = OldTex( "\\dots", "w_n", "\\dots", "w_k", "\\dots" ) new_w_terms.move_to(w_terms, DOWN) new_w_terms[1].set_color(d1.get_color()) new_w_terms[3].set_color(d2.get_color()) for d, edge in (d1, edge1), (d2, edge2): d.arrow = Arrow( d.get_right(), edge.get_center(), color = d.get_color() ) self.play( FadeOut(vect_contents), FadeIn(new_vect_contents), FadeOut(w_terms), FadeIn(new_w_terms), edges.set_stroke, GREY_B, 0.35, ) self.play(GrowArrow(d1.arrow)) self.play(ShowCreation(edge1)) self.wait() self.play(GrowArrow(d2.arrow)) self.play(ShowCreation(edge2)) self.wait(2) self.cost_expression.remove(w_terms) self.cost_expression.add(new_w_terms) self.set_variables_as_attrs( edge1, edge2, new_w_terms, new_decimals = VGroup(d1, d2) ) def shift_cost_expression(self): self.play(self.cost_group.shift, DOWN+0.5*LEFT) def tweak_individual_weights(self): cost = self.cost cost_num = cost.number edges = VGroup(self.edge1, self.edge2) decimals = self.new_decimals changes = (1.0, 1./32) wn = self.new_w_terms[1] wk = self.new_w_terms[3] number_line_template = NumberLine( x_min = -1, x_max = 1, tick_frequency = 0.25, numbers_with_elongated_ticks = [], color = WHITE ) for term in wn, wk, cost: term.number_line = number_line_template.copy() term.brace = Brace(term.number_line, DOWN, buff = SMALL_BUFF) group = VGroup(term.number_line, term.brace) group.next_to(term, UP) term.dot = Dot() term.dot.set_color(term.get_color()) term.dot.move_to(term.number_line.get_center()) term.dot.save_state() term.dot.move_to(term) term.dot.set_fill(opacity = 0) term.words = OldTexText("Nudge this weight") term.words.scale(0.7) term.words.next_to(term.number_line, UP, MED_SMALL_BUFF) groups = [ VGroup(d, d.arrow, edge, w) for d, edge, w in zip(decimals, edges, [wn, wk]) ] for group in groups: group.save_state() for i in range(2): group1, group2 = groups[i], groups[1-i] change = changes[i] edge = edges[i] w = group1[-1] added_anims = [] if i == 0: added_anims = [ GrowFromCenter(cost.brace), ShowCreation(cost.number_line), cost.dot.restore ] self.play( group1.restore, group2.fade, 0.7, GrowFromCenter(w.brace), ShowCreation(w.number_line), w.dot.restore, Write(w.words, run_time = 1), *added_anims ) for x in range(2): func = lambda a : interpolate( cost_num, cost_num-change, a ) self.play( ChangingDecimal(cost, func), cost.dot.shift, change*RIGHT, w.dot.shift, 0.25*RIGHT, edge.set_stroke, None, 8, rate_func = lambda t : wiggle(t, 4), run_time = 2, ) self.wait() self.play(*list(map(FadeOut, [ w.dot, w.brace, w.number_line, w.words ]))) ###### def move_grad_terms_into_position(self, grad_terms, *added_anims): cost_expression = self.cost_expression w_terms = self.cost_expression[1] points = VGroup(*[ VectorizedPoint() for term in grad_terms ]) points.arrange(RIGHT) points.replace(w_terms, dim_to_match = 0) grad_terms.generate_target() grad_terms.target[len(grad_terms)/2].rotate(np.pi/2) grad_terms.target.arrange(RIGHT) grad_terms.target.set_width(cost_expression.get_width()) grad_terms.target.next_to(cost_expression, DOWN) words = OldTexText("Nudge weights") words.scale(0.8) words.next_to(grad_terms.target, DOWN) self.play( MoveToTarget(grad_terms), FadeIn(words) ) self.play( Transform( grad_terms, points, remover = True, lag_ratio = 0.5, run_time = 1 ), FadeOut(words), *added_anims ) def get_weight_adjustment_anims(self, edges, cost): start_cost = cost.number target_cost = start_cost + self.delta_cost w_terms = self.cost_expression[1] return [ self.get_edge_change_anim(edges), LaggedStartMap( Indicate, w_terms, rate_func = there_and_back, run_time = 1.5, ), ChangingDecimal( cost, lambda a : interpolate(start_cost, target_cost, a), run_time = 1.5 ) ] class GetLostInNotation(PiCreatureScene): def construct(self): morty = self.pi_creature equations = VGroup( OldTex( "\\delta", "^L", "=", "\\nabla_a", "C", "\\odot \\sigma'(", "z", "^L)" ), OldTex( "\\delta", "^l = ((", "w", "^{l+1})^T", "\\delta", "^{l+1}) \\odot \\sigma'(", "z", "^l)" ), OldTex( "{\\partial", "C", "\\over \\partial", "b", "_j^l} =", "\\delta", "_j^l" ), OldTex( "{\\partial", "C", " \\over \\partial", "w", "_{jk}^l} = ", "a", "_k^{l-1}", "\\delta", "_j^l" ), ) for equation in equations: equation.set_color_by_tex_to_color_map({ "\\delta" : YELLOW, "C" : RED, "b" : MAROON_B, "w" : BLUE, "z" : TEAL, }) equation.set_color_by_tex("nabla", WHITE) equations.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) circle = Circle(radius = 3*FRAME_X_RADIUS) circle.set_fill(WHITE, 0) circle.set_stroke(WHITE, 0) self.play( Write(equations), morty.change, "confused", equations ) self.wait() self.play(morty.change, "pleading") self.wait(2) ## movers = VGroup(*equations.family_members_with_points()) random.shuffle(movers.submobjects) for mover in list(movers): if mover.is_subpath: movers.remove(mover) continue mover.set_stroke(WHITE, width = 0) mover.target = Circle() mover.target.scale(0.5) mover.target.set_fill(mover.get_color(), opacity = 0) mover.target.set_stroke(BLACK, width = 1) mover.target.move_to(mover) self.play( LaggedStartMap( MoveToTarget, movers, run_time = 2, ), morty.change, "pondering", ) self.wait() class TODOInsertPreviewLearning(TODOStub): CONFIG = { "message" : "Insert PreviewLearning" } class ShowAveragingCost(PreviewLearning): CONFIG = { "network_scale_val" : 0.8, "stroke_width_exp" : 1, "start_examples_time" : 5, "examples_per_adjustment_time" : 2, "n_adjustments" : 5, "time_per_example" : 1./15, "image_height" : 1.2, } def construct(self): self.setup_network() self.setup_diff_words() self.show_many_examples() def setup_network(self): self.network_mob.scale(self.network_scale_val) self.network_mob.to_edge(DOWN) self.network_mob.shift(LEFT) self.color_network_edges() def setup_diff_words(self): last_layer_copy = self.network_mob.layers[-1].deepcopy() last_layer_copy.add(self.network_mob.output_labels.copy()) last_layer_copy.shift(1.5*RIGHT) double_arrow = DoubleArrow( self.network_mob.output_labels, last_layer_copy, color = RED ) brace = Brace( VGroup(self.network_mob.layers[-1], last_layer_copy), UP ) cost_words = brace.get_text("Cost of \\\\ one example") cost_words.set_color(RED) self.add(last_layer_copy, double_arrow, brace, cost_words) self.set_variables_as_attrs( last_layer_copy, double_arrow, brace, cost_words ) self.last_layer_copy = last_layer_copy def show_many_examples(self): training_data, validation_data, test_data = load_data_wrapper() average_words = OldTexText("Average over all training examples") average_words.next_to(LEFT, RIGHT) average_words.to_edge(UP) self.add(average_words) n_start_examples = int(self.start_examples_time/self.time_per_example) n_examples_per_adjustment = int(self.examples_per_adjustment_time/self.time_per_example) for train_in, train_out in training_data[:n_start_examples]: self.show_one_example(train_in, train_out) self.wait(self.time_per_example) #Wiggle all edges edges = VGroup(*it.chain(*self.network_mob.edge_groups)) reversed_edges = VGroup(*reversed(edges)) self.play(LaggedStartMap( ApplyFunction, edges, lambda edge : ( lambda m : m.rotate(np.pi/12).set_color(YELLOW), edge, ), rate_func = lambda t : wiggle(t, 4), run_time = 3, )) #Show all, then adjust words = OldTexText( "Each step \\\\ uses every \\\\ example\\\\", "$\\dots$theoretically", alignment = "" ) words.set_color(YELLOW) words.scale(0.8) words.to_corner(UP+LEFT) for x in range(self.n_adjustments): if x < 2: self.play(FadeIn(words[x])) for train_in, train_out in training_data[:n_examples_per_adjustment]: self.show_one_example(train_in, train_out) self.wait(self.time_per_example) self.play(LaggedStartMap( ApplyMethod, reversed_edges, lambda m : (m.rotate, np.pi), run_time = 1, lag_ratio = 0.2, )) if x >= 2: self.wait() #### def show_one_example(self, train_in, train_out): if hasattr(self, "curr_image"): self.remove(self.curr_image) image = MNistMobject(train_in) image.set_height(self.image_height) image.next_to( self.network_mob.layers[0].neurons, UP, aligned_edge = LEFT ) self.add(image) self.network_mob.activate_layers(train_in) index = np.argmax(train_out) self.last_layer_copy.neurons.set_fill(opacity = 0) self.last_layer_copy.neurons[index].set_fill(WHITE, opacity = 1) self.add(self.last_layer_copy) self.curr_image = image class FocusOnOneExample(TeacherStudentsScene): def construct(self): self.teacher_says("Focus on just \\\\ one example") self.wait(2) class WalkThroughTwoExample(ShowAveragingCost): CONFIG = { "random_seed" : 0, } def setup(self): np.random.seed(self.random_seed) random.seed(self.random_seed) self.setup_bases() def construct(self): self.force_skipping() self.setup_network() self.setup_diff_words() self.show_single_example() self.single_example_influencing_weights() self.expand_last_layer() self.show_activation_formula() self.three_ways_to_increase() self.note_connections_to_brightest_neurons() self.fire_together_wire_together() self.show_desired_increase_to_previous_neurons() self.only_keeping_track_of_changes() self.show_other_output_neurons() self.show_recursion() def show_single_example(self): two_vect = get_organized_images()[2][0] two_out = np.zeros(10) two_out[2] = 1.0 self.show_one_example(two_vect, two_out) for layer in self.network_mob.layers: layer.neurons.set_fill(opacity = 0) self.activate_network(two_vect) self.wait() def single_example_influencing_weights(self): two = self.curr_image two.save_state() edge_groups = self.network_mob.edge_groups def adjust_edge_group_anim(edge_group): return LaggedStartMap( ApplyFunction, edge_group, lambda edge : ( lambda m : m.rotate(np.pi/12).set_color(YELLOW), edge ), rate_func = wiggle, run_time = 1, ) self.play( two.next_to, edge_groups[0].get_corner(DOWN+RIGHT), DOWN, adjust_edge_group_anim(edge_groups[0]) ) self.play( ApplyMethod( two.next_to, edge_groups[1].get_corner(UP+RIGHT), UP, path_arc = np.pi/6, ), adjust_edge_group_anim(VGroup(*reversed(edge_groups[1]))) ) self.play( ApplyMethod( two.next_to, edge_groups[2].get_corner(DOWN+RIGHT), DOWN, path_arc = -np.pi/6, ), adjust_edge_group_anim(edge_groups[2]) ) self.play(two.restore) self.wait() def expand_last_layer(self): neurons = self.network_mob.layers[-1].neurons alt_neurons = self.last_layer_copy.neurons output_labels = self.network_mob.output_labels alt_output_labels = self.last_layer_copy[-1] edges = self.network_mob.edge_groups[-1] movers = VGroup( neurons, alt_neurons, output_labels, alt_output_labels, *edges ) to_fade = VGroup(self.brace, self.cost_words, self.double_arrow) for mover in movers: mover.save_state() mover.generate_target() mover.target.scale(2) neurons[2].save_state() neurons.target.to_edge(DOWN, MED_LARGE_BUFF) output_labels.target.next_to(neurons.target, RIGHT, MED_SMALL_BUFF) alt_neurons.target.next_to(neurons.target, RIGHT, buff = 2) alt_output_labels.target.next_to(alt_neurons.target, RIGHT, MED_SMALL_BUFF) n_pairs = it.product( self.network_mob.layers[-2].neurons, neurons.target ) for edge, (n1, n2) in zip(edges, n_pairs): r1 = n1.get_width()/2.0 r2 = n2.get_width()/2.0 c1 = n1.get_center() c2 = n2.get_center() vect = c2 - c1 norm = get_norm(vect) unit_vect = vect / norm edge.target.put_start_and_end_on( c1 + unit_vect*r1, c2 - unit_vect*r2 ) self.play( FadeOut(to_fade), *list(map(MoveToTarget, movers)) ) self.show_decimals(neurons) self.cannot_directly_affect_activations() self.show_desired_activation_nudges(neurons, output_labels, alt_output_labels) self.focus_on_one_neuron(movers) def show_decimals(self, neurons): decimals = VGroup() for neuron in neurons: activation = neuron.get_fill_opacity() decimal = DecimalNumber(activation, num_decimal_places = 1) decimal.set_width(0.7*neuron.get_width()) decimal.move_to(neuron) if activation > 0.8: decimal.set_color(BLACK) decimals.add(decimal) self.play(Write(decimals, run_time = 2)) self.wait() self.decimals = decimals def cannot_directly_affect_activations(self): words = OldTexText("You can only adjust weights and biases") words.next_to(self.curr_image, RIGHT, MED_SMALL_BUFF, UP) edges = VGroup(*self.network_mob.edge_groups.family_members_with_points()) random.shuffle(edges.submobjects) for edge in edges: edge.generate_target() edge.target.set_stroke( random.choice([BLUE, RED]), 2*random.random()**2, ) self.play( LaggedStartMap( Transform, edges, lambda e : (e, e.target), run_time = 4, rate_func = there_and_back, ), Write(words, run_time = 2) ) self.play(FadeOut(words)) def show_desired_activation_nudges(self, neurons, output_labels, alt_output_labels): arrows = VGroup() rects = VGroup() for i, neuron, label in zip(it.count(), neurons, alt_output_labels): activation = neuron.get_fill_opacity() target_val = 1 if i == 2 else 0 diff = abs(activation - target_val) arrow = Arrow( ORIGIN, diff*neuron.get_height()*DOWN, color = RED, ) arrow.move_to(neuron.get_right()) arrow.shift(0.175*RIGHT) if i == 2: arrow.set_color(BLUE) arrow.rotate(np.pi) arrows.add(arrow) rect = SurroundingRectangle(VGroup(neuron, label)) if i == 2: rect.set_color(BLUE) else: rect.set_color(RED) rects.add(rect) self.play( output_labels.shift, SMALL_BUFF*RIGHT, LaggedStartMap(GrowArrow, arrows, run_time = 1) ) self.wait() #Show changing activations anims = [] def get_decimal_update(start, end): return lambda a : interpolate(start, end, a) for i in range(10): target = 1.0 if i == 2 else 0.01 anims += [neurons[i].set_fill, WHITE, target] decimal = self.decimals[i] anims.append(ChangingDecimal( decimal, get_decimal_update(decimal.number, target), num_decimal_places = 1 )) anims.append(UpdateFromFunc( self.decimals[i], lambda m : m.set_fill(WHITE if m.number < 0.8 else BLACK) )) self.play( *anims, run_time = 3, rate_func = there_and_back ) two_rect = rects[2] eight_rect = rects[8].copy() non_two_rects = VGroup(*[r for r in rects if r is not two_rect]) self.play(ShowCreation(two_rect)) self.wait() self.remove(two_rect) self.play(ReplacementTransform(two_rect.copy(), non_two_rects)) self.wait() self.play(LaggedStartMap(FadeOut, non_two_rects, run_time = 1)) self.play(LaggedStartMap( ApplyFunction, arrows, lambda arrow : ( lambda m : m.scale(0.5).set_color(YELLOW), arrow, ), rate_func = wiggle )) self.play(ShowCreation(two_rect)) self.wait() self.play(ReplacementTransform(two_rect, eight_rect)) self.wait() self.play(FadeOut(eight_rect)) self.arrows = arrows def focus_on_one_neuron(self, expanded_mobjects): network_mob = self.network_mob neurons = network_mob.layers[-1].neurons labels = network_mob.output_labels two_neuron = neurons[2] neurons.remove(two_neuron) two_label = labels[2] labels.remove(two_label) expanded_mobjects.remove(*two_neuron.edges_in) two_decimal = self.decimals[2] self.decimals.remove(two_decimal) two_arrow = self.arrows[2] self.arrows.remove(two_arrow) to_fade = VGroup(*it.chain( network_mob.layers[:2], network_mob.edge_groups[:2], expanded_mobjects, self.decimals, self.arrows )) self.play(FadeOut(to_fade)) self.wait() for mob in expanded_mobjects: if mob in [neurons, labels]: mob.scale(0.5) mob.move_to(mob.saved_state) else: mob.restore() for d, a, n in zip(self.decimals, self.arrows, neurons): d.scale(0.5) d.move_to(n) a.scale(0.5) a.move_to(n.get_right()) a.shift(SMALL_BUFF*RIGHT) labels.shift(SMALL_BUFF*RIGHT) self.set_variables_as_attrs( two_neuron, two_label, two_arrow, two_decimal, ) def show_activation_formula(self): rhs = OldTex( "=", "\\sigma(", "w_0", "a_0", "+", "w_1", "a_1", "+", "\\cdots", "+", "w_{n-1}", "a_{n-1}", "+", "b", ")" ) equals = rhs[0] sigma = VGroup(rhs[1], rhs[-1]) w_terms = rhs.get_parts_by_tex("w_") a_terms = rhs.get_parts_by_tex("a_") plus_terms = rhs.get_parts_by_tex("+") b = rhs.get_part_by_tex("b", substring = False) dots = rhs.get_part_by_tex("dots") w_terms.set_color(BLUE) b.set_color(MAROON_B) sigma.set_color(YELLOW) rhs.to_corner(UP+RIGHT) sigma.save_state() sigma.shift(DOWN) sigma.set_fill(opacity = 0) prev_neurons = self.network_mob.layers[-2].neurons edges = self.two_neuron.edges_in neuron_copy = VGroup( self.two_neuron.copy(), self.two_decimal.copy(), ) self.play( neuron_copy.next_to, equals.get_left(), LEFT, self.curr_image.to_corner, UP+LEFT, Write(equals) ) self.play( ReplacementTransform(edges.copy(), w_terms), Write(VGroup(*plus_terms[:-1])), Write(dots), run_time = 1.5 ) self.wait() self.play(ReplacementTransform( prev_neurons.copy(), a_terms, path_arc = np.pi/2 )) self.wait() self.play( Write(plus_terms[-1]), Write(b) ) self.wait() self.play(sigma.restore) self.wait() for mob in b, w_terms, a_terms: self.play( mob.shift, MED_SMALL_BUFF*DOWN, rate_func = there_and_back, lag_ratio = 0.5, run_time = 1.5 ) self.wait() self.set_variables_as_attrs( rhs, w_terms, a_terms, b, lhs = neuron_copy ) def three_ways_to_increase(self): w_terms = self.w_terms a_terms = self.a_terms b = self.b increase_words = VGroup( OldTexText("Increase", "$b$"), OldTexText("Increase", "$w_i$"), OldTexText("Change", "$a_i$"), ) for words in increase_words: words.set_color_by_tex_to_color_map({ "b" : b.get_color(), "w_" : w_terms.get_color(), "a_" : a_terms.get_color(), }) increase_words.arrange( DOWN, aligned_edge = LEFT, buff = LARGE_BUFF ) increase_words.to_edge(LEFT) mobs = [b, w_terms[0], a_terms[0]] for words, mob in zip(increase_words, mobs): self.play( Write(words[0], run_time = 1), ReplacementTransform(mob.copy(), words[1]) ) self.wait() self.increase_words = increase_words def note_connections_to_brightest_neurons(self): w_terms = self.w_terms a_terms = self.a_terms increase_words = self.increase_words prev_neurons = self.network_mob.layers[-2].neurons edges = self.two_neuron.edges_in prev_activations = np.array([n.get_fill_opacity() for n in prev_neurons]) sorted_indices = np.argsort(prev_activations.flatten()) bright_neurons = VGroup() dim_neurons = VGroup() edges_to_bright_neurons = VGroup() for i in sorted_indices[:5]: dim_neurons.add(prev_neurons[i]) for i in sorted_indices[-4:]: bright_neurons.add(prev_neurons[i]) edges_to_bright_neurons.add(edges[i]) bright_edges = edges_to_bright_neurons.copy() bright_edges.set_stroke(YELLOW, 4) added_words = OldTexText("in proportion to $a_i$") added_words.next_to( increase_words[1], DOWN, 1.5*SMALL_BUFF, LEFT ) added_words.set_color(YELLOW) terms_rect = SurroundingRectangle( VGroup(w_terms[0], a_terms[0]), color = WHITE ) self.play(LaggedStartMap( ApplyFunction, edges, lambda edge : ( lambda m : m.rotate(np.pi/12).set_stroke(YELLOW), edge ), rate_func = wiggle )) self.wait() self.play( ShowCreation(bright_edges), ShowCreation(bright_neurons) ) self.play(LaggedStartMap( ApplyMethod, bright_neurons, lambda m : (m.shift, MED_LARGE_BUFF*LEFT), rate_func = there_and_back )) self.wait() self.play( ReplacementTransform(bright_edges[0].copy(), w_terms[0]), ReplacementTransform(bright_neurons[0].copy(), a_terms[0]), ShowCreation(terms_rect) ) self.wait() for x in range(2): self.play(LaggedStartMap(ShowCreationThenDestruction, bright_edges)) self.play(LaggedStartMap(ShowCreation, bright_edges)) self.play(LaggedStartMap( ApplyMethod, dim_neurons, lambda m : (m.shift, MED_LARGE_BUFF*LEFT), rate_func = there_and_back )) self.play(FadeOut(terms_rect)) self.wait() self.play( self.curr_image.shift, MED_LARGE_BUFF*RIGHT, rate_func = wiggle ) self.wait() self.play(Write(added_words)) self.wait() self.set_variables_as_attrs( bright_neurons, bright_edges, in_proportion_to_a = added_words ) def fire_together_wire_together(self): bright_neurons = self.bright_neurons bright_edges = self.bright_edges two_neuron = self.two_neuron two_decimal = self.two_decimal two_activation = two_decimal.number def get_edge_animation(): return LaggedStartMap( ShowCreationThenDestruction, bright_edges, lag_ratio = 0.7 ) neuron_arrows = VGroup(*[ Vector(MED_LARGE_BUFF*RIGHT).next_to(n, LEFT) for n in bright_neurons ]) two_neuron_arrow = Vector(MED_LARGE_BUFF*DOWN) two_neuron_arrow.next_to(two_neuron, UP) VGroup(neuron_arrows, two_neuron_arrow).set_color(YELLOW) neuron_rects = VGroup(*list(map( SurroundingRectangle, bright_neurons ))) two_neuron_rect = SurroundingRectangle(two_neuron) seeing_words = OldTexText("Seeing a 2") seeing_words.scale(0.8) thinking_words = OldTexText("Thinking about a 2") thinking_words.scale(0.8) seeing_words.next_to(neuron_rects, UP) thinking_words.next_to(two_neuron_arrow, RIGHT) morty = Mortimer() morty.scale(0.8) morty.to_corner(DOWN+RIGHT) words = OldTexText(""" ``Neurons that \\\\ fire together \\\\ wire together'' """) words.to_edge(RIGHT) self.play(FadeIn(morty)) self.play( Write(words), morty.change, "speaking", words ) self.play(Blink(morty)) self.play( get_edge_animation(), morty.change, "pondering", bright_edges ) self.play(get_edge_animation()) self.play( LaggedStartMap(GrowArrow, neuron_arrows), get_edge_animation(), ) self.play( GrowArrow(two_neuron_arrow), morty.change, "raise_right_hand", two_neuron ) self.play( ApplyMethod(two_neuron.set_fill, WHITE, 1), ChangingDecimal( two_decimal, lambda a : interpolate(two_activation, 1, a), num_decimal_places = 1, ), UpdateFromFunc( two_decimal, lambda m : m.set_color(WHITE if m.number < 0.8 else BLACK), ), LaggedStartMap(ShowCreation, bright_edges), run_time = 2, ) self.wait() self.play( LaggedStartMap(ShowCreation, neuron_rects), Write(seeing_words, run_time = 2), morty.change, "thinking", seeing_words ) self.wait() self.play( ShowCreation(two_neuron_rect), Write(thinking_words, run_time = 2), morty.look_at, thinking_words ) self.wait() self.play(LaggedStartMap(FadeOut, VGroup( neuron_rects, two_neuron_rect, seeing_words, thinking_words, words, morty, neuron_arrows, two_neuron_arrow, bright_edges, ))) self.play( ApplyMethod(two_neuron.set_fill, WHITE, two_activation), ChangingDecimal( two_decimal, lambda a : interpolate(1, two_activation, a), num_decimal_places = 1, ), UpdateFromFunc( two_decimal, lambda m : m.set_color(WHITE if m.number < 0.8 else BLACK), ), ) def show_desired_increase_to_previous_neurons(self): increase_words = self.increase_words two_neuron = self.two_neuron two_decimal = self.two_decimal edges = two_neuron.edges_in prev_neurons = self.network_mob.layers[-2].neurons positive_arrows = VGroup() negative_arrows = VGroup() all_arrows = VGroup() positive_edges = VGroup() negative_edges = VGroup() positive_neurons = VGroup() negative_neurons = VGroup() for neuron, edge in zip(prev_neurons, edges): value = self.get_edge_value(edge) arrow = self.get_neuron_nudge_arrow(edge) arrow.move_to(neuron.get_left()) arrow.shift(SMALL_BUFF*LEFT) all_arrows.add(arrow) if value > 0: positive_arrows.add(arrow) positive_edges.add(edge) positive_neurons.add(neuron) else: negative_arrows.add(arrow) negative_edges.add(edge) negative_neurons.add(neuron) for s_edges in positive_edges, negative_edges: s_edges.alt_position = VGroup(*[ Line(LEFT, RIGHT, color = s_edge.get_color()) for s_edge in s_edges ]) s_edges.alt_position.arrange(DOWN, MED_SMALL_BUFF) s_edges.alt_position.to_corner(DOWN+RIGHT, LARGE_BUFF) added_words = OldTexText("in proportion to $w_i$") added_words.set_color(self.w_terms.get_color()) added_words.next_to( increase_words[-1], DOWN, SMALL_BUFF, aligned_edge = LEFT ) self.play(LaggedStartMap( ApplyFunction, prev_neurons, lambda neuron : ( lambda m : m.scale(0.5).set_color(YELLOW), neuron ), rate_func = wiggle )) self.wait() for positive in [True, False]: if positive: arrows = positive_arrows s_edges = positive_edges neurons = positive_neurons color = self.positive_edge_color else: arrows = negative_arrows s_edges = negative_edges neurons = negative_neurons color = self.negative_edge_color s_edges.save_state() self.play(Transform(s_edges, s_edges.alt_position)) self.wait(0.5) self.play(s_edges.restore) self.play( LaggedStartMap(GrowArrow, arrows), neurons.set_stroke, color ) self.play(ApplyMethod( neurons.set_fill, color, 1, rate_func = there_and_back, )) self.wait() self.play( two_neuron.set_fill, None, 0.8, ChangingDecimal( two_decimal, lambda a : two_neuron.get_fill_opacity() ), run_time = 3, rate_func = there_and_back ) self.wait() self.play(*[ ApplyMethod( edge.set_stroke, None, 3*edge.get_stroke_width(), rate_func = there_and_back, run_time = 2 ) for edge in edges ]) self.wait() self.play(Write(added_words, run_time = 1)) self.play(prev_neurons.set_stroke, WHITE, 2) self.set_variables_as_attrs( in_proportion_to_w = added_words, prev_neuron_arrows = all_arrows, ) def only_keeping_track_of_changes(self): arrows = self.prev_neuron_arrows prev_neurons = self.network_mob.layers[-2].neurons rect = SurroundingRectangle(VGroup(arrows, prev_neurons)) words1 = OldTexText("No direct influence") words1.next_to(rect, UP) words2 = OldTexText("Just keeping track") words2.move_to(words1) edges = self.network_mob.edge_groups[-2] self.play(ShowCreation(rect)) self.play(Write(words1)) self.play(LaggedStartMap( Indicate, prev_neurons, rate_func = wiggle )) self.wait() self.play(LaggedStartMap( ShowCreationThenDestruction, edges )) self.play(Transform(words1, words2)) self.wait() self.play(FadeOut(VGroup(words1, rect))) def show_other_output_neurons(self): two_neuron = self.two_neuron two_decimal = self.two_decimal two_arrow = self.two_arrow two_label = self.two_label two_edges = two_neuron.edges_in prev_neurons = self.network_mob.layers[-2].neurons neurons = self.network_mob.layers[-1].neurons prev_neuron_arrows = self.prev_neuron_arrows arrows_to_fade = VGroup(prev_neuron_arrows) output_labels = self.network_mob.output_labels quads = list(zip(neurons, self.decimals, self.arrows, output_labels)) self.revert_to_original_skipping_status() self.play( two_neuron.restore, two_decimal.scale, 0.5, two_decimal.move_to, two_neuron.saved_state, two_arrow.scale, 0.5, two_arrow.next_to, two_neuron.saved_state, RIGHT, 0.5*SMALL_BUFF, two_label.scale, 0.5, two_label.next_to, two_neuron.saved_state, RIGHT, 1.5*SMALL_BUFF, FadeOut(VGroup(self.lhs, self.rhs)), *[e.restore for e in two_edges] ) for neuron, decimal, arrow, label in quads[:2] + quads[2:5]: plusses = VGroup() new_arrows = VGroup() for edge, prev_arrow in zip(neuron.edges_in, prev_neuron_arrows): plus = OldTex("+").scale(0.5) plus.move_to(prev_arrow) plus.shift(2*SMALL_BUFF*LEFT) new_arrow = self.get_neuron_nudge_arrow(edge) new_arrow.move_to(plus) new_arrow.shift(2*SMALL_BUFF*LEFT) plusses.add(plus) new_arrows.add(new_arrow) self.play( FadeIn(VGroup(neuron, decimal, arrow, label)), LaggedStartMap(ShowCreation, neuron.edges_in), ) self.play( ReplacementTransform(neuron.edges_in.copy(), new_arrows), Write(plusses, run_time = 2) ) arrows_to_fade.add(new_arrows, plusses) prev_neuron_arrows = new_arrows all_dots_plus = VGroup() for arrow in prev_neuron_arrows: dots_plus = OldTex("\\cdots +") dots_plus.scale(0.5) dots_plus.move_to(arrow.get_center(), RIGHT) dots_plus.shift(2*SMALL_BUFF*LEFT) all_dots_plus.add(dots_plus) arrows_to_fade.add(all_dots_plus) self.play( LaggedStartMap( FadeIn, VGroup(*it.starmap(VGroup, quads[5:])), ), LaggedStartMap( FadeIn, VGroup(*[n.edges_in for n in neurons[5:]]) ), Write(all_dots_plus), run_time = 3, ) self.wait(2) ## words = OldTexText("Propagate backwards") words.to_edge(UP) words.set_color(BLUE) target_arrows = prev_neuron_arrows.copy() target_arrows.next_to(prev_neurons, RIGHT, SMALL_BUFF) rect = SurroundingRectangle(VGroup( self.network_mob.layers[-1], self.network_mob.output_labels )) rect.set_fill(BLACK, 1) rect.set_stroke(BLACK, 0) self.play(Write(words)) self.wait() self.play( FadeOut(self.network_mob.edge_groups[-1]), FadeIn(rect), ReplacementTransform(arrows_to_fade, VGroup(target_arrows)), ) self.prev_neuron_arrows = target_arrows def show_recursion(self): network_mob = self.network_mob words_to_fade = VGroup( self.increase_words, self.in_proportion_to_w, self.in_proportion_to_a, ) edges = network_mob.edge_groups[1] neurons = network_mob.layers[2].neurons prev_neurons = network_mob.layers[1].neurons for neuron in neurons: neuron.edges_in.save_state() self.play( FadeOut(words_to_fade), FadeIn(prev_neurons), LaggedStartMap(ShowCreation, edges), ) self.wait() for neuron, arrow in zip(neurons, self.prev_neuron_arrows): edge_copies = neuron.edges_in.copy() for edge in edge_copies: edge.set_stroke(arrow.get_color(), 2) edge.rotate(np.pi) self.play( edges.set_stroke, None, 0.15, neuron.edges_in.restore, ) self.play(ShowCreationThenDestruction(edge_copies)) self.remove(edge_copies) #### def get_neuron_nudge_arrow(self, edge): value = self.get_edge_value(edge) height = np.sign(value)*0.1 + 0.1*value arrow = Vector(height*UP, color = edge.get_color()) return arrow def get_edge_value(self, edge): value = edge.get_stroke_width() if Color(edge.get_stroke_color()) == Color(self.negative_edge_color): value *= -1 return value class WriteHebbian(Scene): def construct(self): words = OldTexText("Hebbian theory") words.set_width(FRAME_WIDTH - 1) words.to_edge(UP) self.play(Write(words)) self.wait() class NotANeuroScientist(TeacherStudentsScene): def construct(self): quote = OldTexText("``Neurons that fire together wire together''") quote.to_edge(UP) self.add(quote) asterisks = OldTexText("***") asterisks.next_to(quote.get_corner(UP+RIGHT), RIGHT, SMALL_BUFF) asterisks.set_color(BLUE) brain = SVGMobject(file_name = "brain") brain.set_height(1.5) self.add(brain) double_arrow = DoubleArrow(LEFT, RIGHT) double_arrow.next_to(brain, RIGHT) q_marks = OldTexText("???") q_marks.next_to(double_arrow, UP) network = NetworkMobject(Network(sizes = [6, 4, 4, 5])) network.set_height(1.5) network.next_to(double_arrow, RIGHT) group = VGroup(brain, double_arrow, q_marks, network) group.next_to(self.students, UP, buff = 1.5) self.add(group) self.add(ContinualEdgeUpdate( network, stroke_width_exp = 0.5, color = [BLUE, RED], )) rect = SurroundingRectangle(group) no_claim_words = OldTexText("No claims here...") no_claim_words.next_to(rect, UP) no_claim_words.set_color(YELLOW) brain_outline = brain.copy() brain_outline.set_fill(opacity = 0) brain_outline.set_stroke(BLUE, 3) brain_anim = ShowCreationThenDestruction(brain_outline) words = OldTexText("Definitely not \\\\ a neuroscientist") words.next_to(self.teacher, UP, buff = 1.5) words.shift_onto_screen() arrow = Arrow(words.get_bottom(), self.teacher.get_top()) self.play( Write(words), GrowArrow(arrow), self.teacher.change, "guilty", words, run_time = 1, ) self.play_student_changes(*3*["sassy"]) self.play( ShowCreation(rect), Write(no_claim_words, run_time = 1), brain_anim ) self.wait() self.play(brain_anim) self.play(FocusOn(asterisks)) self.play(Write(asterisks, run_time = 1)) for x in range(2): self.play(brain_anim) self.wait() class ConstructGradientFromAllTrainingExamples(Scene): CONFIG = { "image_height" : 0.9, "eyes_height" : 0.25, "n_examples" : 6, "change_scale_val" : 0.8, } def construct(self): self.setup_grid() self.setup_weights() self.show_two_requesting_changes() self.show_all_examples_requesting_changes() self.average_together() self.collapse_into_gradient_vector() def setup_grid(self): h_lines = VGroup(*[ Line(LEFT, RIGHT).scale(0.85*FRAME_X_RADIUS) for x in range(6) ]) h_lines.arrange(DOWN, buff = 1) h_lines.set_stroke(GREY_B, 2) h_lines.to_edge(DOWN, buff = MED_LARGE_BUFF) h_lines.to_edge(LEFT, buff = 0) v_lines = VGroup(*[ Line(UP, DOWN).scale(FRAME_Y_RADIUS - MED_LARGE_BUFF) for x in range(self.n_examples + 1) ]) v_lines.arrange(RIGHT, buff = 1.4) v_lines.set_stroke(GREY_B, 2) v_lines.to_edge(LEFT, buff = 2) # self.add(h_lines, v_lines) self.h_lines = h_lines self.v_lines = v_lines def setup_weights(self): weights = VGroup(*list(map(Tex, [ "w_0", "w_1", "w_2", "\\vdots", "w_{13{,}001}" ]))) for i, weight in enumerate(weights): weight.move_to(self.get_grid_position(i, 0)) weights.to_edge(LEFT, buff = MED_SMALL_BUFF) brace = Brace(weights, RIGHT) weights_words = brace.get_text("All weights and biases") self.add(weights, brace, weights_words) self.set_variables_as_attrs( weights, brace, weights_words, dots = weights[-2] ) def show_two_requesting_changes(self): two = self.get_example(get_organized_images()[2][0], 0) self.two = two self.add(two) self.two_changes = VGroup() for i in list(range(3)) + [4]: weight = self.weights[i] bubble, change = self.get_requested_change_bubble(two) weight.save_state() weight.generate_target() weight.target.next_to(two, RIGHT, aligned_edge = DOWN) self.play( MoveToTarget(weight), two.eyes.look_at_anim(weight.target), FadeIn(bubble), Write(change, run_time = 1), ) if random.random() < 0.5: self.play(two.eyes.blink_anim()) else: self.wait() if i == 0: added_anims = [ FadeOut(self.brace), FadeOut(self.weights_words), ] elif i == 4: dots_copy = self.dots.copy() added_anims = [ dots_copy.move_to, self.get_grid_position(3, 0) ] self.first_column_dots = dots_copy else: added_anims = [] self.play( FadeOut(bubble), weight.restore, two.eyes.look_at_anim(weight.saved_state), change.restore, change.scale, self.change_scale_val, change.move_to, self.get_grid_position(i, 0), *added_anims ) self.two_changes.add(change) self.wait() def show_all_examples_requesting_changes(self): training_data, validation_data, test_data = load_data_wrapper() data = training_data[:self.n_examples-1] examples = VGroup(*[ self.get_example(t[0], j) for t, j in zip(data, it.count(1)) ]) h_dots = OldTex("\\dots") h_dots.next_to(examples, RIGHT, MED_LARGE_BUFF) more_h_dots = VGroup(*[ OldTex("\\dots").move_to( self.get_grid_position(i, self.n_examples) ) for i in range(5) ]) more_h_dots.shift(MED_LARGE_BUFF*RIGHT) more_h_dots[-2].rotate(-np.pi/4) more_v_dots = VGroup(*[ self.dots.copy().move_to( self.get_grid_position(3, j) ) for j in range(1, self.n_examples) ]) changes = VGroup(*[ self.get_random_decimal().move_to( self.get_grid_position(i, j) ) for i in list(range(3)) + [4] for j in range(1, self.n_examples) ]) for change in changes: change.scale(self.change_scale_val) self.play( LaggedStartMap(FadeIn, examples), LaggedStartMap(ShowCreation, self.h_lines), LaggedStartMap(ShowCreation, self.v_lines), Write( h_dots, run_time = 2, rate_func = squish_rate_func(smooth, 0.7, 1) ) ) self.play( Write(changes), Write(more_v_dots), Write(more_h_dots), *[ example.eyes.look_at_anim(random.choice(changes)) for example in examples ] ) for x in range(2): self.play(random.choice(examples).eyes.blink_anim()) k = self.n_examples - 1 self.change_rows = VGroup(*[ VGroup(two_change, *changes[k*i:k*(i+1)]) for i, two_change in enumerate(self.two_changes) ]) for i in list(range(3)) + [-1]: self.change_rows[i].add(more_h_dots[i]) self.all_eyes = VGroup(*[ m.eyes for m in [self.two] + list(examples) ]) self.set_variables_as_attrs( more_h_dots, more_v_dots, h_dots, changes, ) def average_together(self): rects = VGroup() arrows = VGroup() averages = VGroup() for row in self.change_rows: rect = SurroundingRectangle(row) arrow = Arrow(ORIGIN, RIGHT) arrow.next_to(rect, RIGHT) rect.arrow = arrow average = self.get_colored_decimal(3*np.mean([ m.number for m in row if isinstance(m, DecimalNumber) ])) average.scale(self.change_scale_val) average.next_to(arrow, RIGHT) row.target = VGroup(average) rects.add(rect) arrows.add(arrow) averages.add(average) words = OldTexText("Average over \\\\ all training data") words.scale(0.8) words.to_corner(UP+RIGHT) arrow_to_averages = Arrow( words.get_bottom(), averages.get_top(), color = WHITE ) dots = self.dots.copy() dots.move_to(VGroup(*averages[-2:])) look_at_anims = self.get_look_at_anims self.play(Write(words, run_time = 1), *look_at_anims(words)) self.play(ShowCreation(rects[0]), *look_at_anims(rects[0])) self.play( ReplacementTransform(rects[0].copy(), arrows[0]), rects[0].set_stroke, WHITE, 1, ReplacementTransform( self.change_rows[0].copy(), self.change_rows[0].target ), *look_at_anims(averages[0]) ) self.play(GrowArrow(arrow_to_averages)) self.play( LaggedStartMap(ShowCreation, VGroup(*rects[1:])), *look_at_anims(rects[1]) ) self.play( LaggedStartMap( ReplacementTransform, VGroup(*rects[1:]).copy(), lambda m : (m, m.arrow), lag_ratio = 0.7, ), VGroup(*rects[1:]).set_stroke, WHITE, 1, LaggedStartMap( ReplacementTransform, VGroup(*self.change_rows[1:]).copy(), lambda m : (m, m.target), lag_ratio = 0.7, ), Write(dots), *look_at_anims(averages[1]) ) self.blink(3) self.wait() averages.add(dots) self.set_variables_as_attrs( rects, arrows, averages, arrow_to_averages ) def collapse_into_gradient_vector(self): averages = self.averages lb, rb = brackets = OldTex("[]") brackets.scale(2) brackets.stretch_to_fit_height(1.2*averages.get_height()) lb.next_to(averages, LEFT, SMALL_BUFF) rb.next_to(averages, RIGHT, SMALL_BUFF) brackets.set_fill(opacity = 0) shift_vect = 2*LEFT lhs = OldTex( "-", "\\nabla", "C(", "w_1,", "w_2,", "\\dots", "w_{13{,}001}", ")", "=" ) lhs.next_to(lb, LEFT) lhs.shift(shift_vect) minus = lhs[0] w_terms = lhs.get_parts_by_tex("w_") dots_term = lhs.get_part_by_tex("dots") eta = OldTex("\\eta") eta.move_to(minus, RIGHT) eta.set_color(MAROON_B) to_fade = VGroup(*it.chain( self.h_lines, self.v_lines, self.more_h_dots, self.more_v_dots, self.change_rows, self.first_column_dots, self.rects, self.arrows, )) arrow = self.arrow_to_averages self.play(LaggedStartMap(FadeOut, to_fade)) self.play( brackets.shift, shift_vect, brackets.set_fill, WHITE, 1, averages.shift, shift_vect, Transform(arrow, Arrow( arrow.get_start(), arrow.get_end() + shift_vect, buff = 0, color = arrow.get_color(), )), FadeIn(VGroup(*lhs[:3])), FadeIn(VGroup(*lhs[-2:])), *self.get_look_at_anims(lhs) ) self.play( ReplacementTransform(self.weights, w_terms), ReplacementTransform(self.dots, dots_term), *self.get_look_at_anims(w_terms) ) self.blink(2) self.play( GrowFromCenter(eta), minus.shift, MED_SMALL_BUFF*LEFT ) self.wait() #### def get_example(self, in_vect, index): result = MNistMobject(in_vect) result.set_height(self.image_height) eyes = Eyes(result, height = self.eyes_height) result.eyes = eyes result.add(eyes) result.move_to(self.get_grid_position(0, index)) result.to_edge(UP, buff = LARGE_BUFF) return result def get_grid_position(self, i, j): x = VGroup(*self.v_lines[j:j+2]).get_center()[0] y = VGroup(*self.h_lines[i:i+2]).get_center()[1] return x*RIGHT + y*UP def get_requested_change_bubble(self, example_mob): change = self.get_random_decimal() words = OldTexText("Change by") change.next_to(words, RIGHT) change.save_state() content = VGroup(words, change) bubble = SpeechBubble(height = 1.5, width = 3) bubble.add_content(content) group = VGroup(bubble, content) group.shift( example_mob.get_right() + SMALL_BUFF*RIGHT \ -bubble.get_corner(DOWN+LEFT) ) return VGroup(bubble, words), change def get_random_decimal(self): return self.get_colored_decimal( 0.3*(random.random() - 0.5) ) def get_colored_decimal(self, number): result = DecimalNumber(number) if result.number > 0: plus = OldTex("+") plus.next_to(result, LEFT, SMALL_BUFF) result.add_to_back(plus) result.set_color(BLUE) else: result.set_color(RED) return result def get_look_at_anims(self, mob): return [eyes.look_at_anim(mob) for eyes in self.all_eyes] def blink(self, n): for x in range(n): self.play(random.choice(self.all_eyes).blink_anim()) class WatchPreviousScene(TeacherStudentsScene): def construct(self): screen = ScreenRectangle(height = 4.5) screen.to_corner(UP+LEFT) self.play( self.teacher.change, "raise_right_hand", screen, self.change_students( *["thinking"]*3, look_at = screen ), ShowCreation(screen) ) self.wait(10) class OpenCloseSGD(Scene): def construct(self): term = OldTex( "\\langle", "\\text{Stochastic gradient descent}", "\\rangle" ) alt_term0 = OldTex("\\langle /") alt_term0.move_to(term[0], RIGHT) term.save_state() center = term.get_center() term[0].move_to(center, RIGHT) term[2].move_to(center, LEFT) term[1].scale(0.0001).move_to(center) self.play(term.restore) self.wait(2) self.play(Transform(term[0], alt_term0)) self.wait(2) class OrganizeDataIntoMiniBatches(Scene): CONFIG = { "n_rows" : 5, "n_cols" : 12, "example_height" : 1, "random_seed" : 0, } def construct(self): self.seed_random_libraries() self.add_examples() self.shuffle_examples() self.divide_into_minibatches() self.one_step_per_batch() def seed_random_libraries(self): random.seed(self.random_seed) np.random.seed(self.random_seed) def add_examples(self): examples = self.get_examples() self.arrange_examples_in_grid(examples) for example in examples: example.save_state() alt_order_examples = VGroup(*examples) for mob in examples, alt_order_examples: random.shuffle(mob.submobjects) self.arrange_examples_in_grid(examples) self.play(LaggedStartMap( FadeIn, alt_order_examples, lag_ratio = 0.2, run_time = 4 )) self.wait() self.examples = examples def shuffle_examples(self): self.play(LaggedStartMap( ApplyMethod, self.examples, lambda m : (m.restore,), lag_ratio = 0.3, run_time = 3, path_arc = np.pi/3, )) self.wait() def divide_into_minibatches(self): examples = self.examples examples.sort(lambda p : -p[1]) rows = Group(*[ Group(*examples[i*self.n_cols:(i+1)*self.n_cols]) for i in range(self.n_rows) ]) mini_batches_words = OldTexText("``Mini-batches''") mini_batches_words.to_edge(UP) mini_batches_words.set_color(YELLOW) self.play( rows.space_out_submobjects, 1.5, rows.to_edge, UP, 1.5, Write(mini_batches_words, run_time = 1) ) rects = VGroup(*[ SurroundingRectangle( row, stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.25, ) for row in rows ]) self.play(LaggedStartMap( FadeIn, rects, lag_ratio = 0.7, rate_func = there_and_back )) self.wait() self.set_variables_as_attrs(rows, rects, mini_batches_words) def one_step_per_batch(self): rows = self.rows brace = Brace(rows[0], UP, buff = SMALL_BUFF) text = brace.get_text( "Compute gradient descent step (using backprop)", buff = SMALL_BUFF ) def indicate_row(row): row.sort(lambda p : p[0]) return LaggedStartMap( ApplyFunction, row, lambda row : ( lambda m : m.scale(0.75).set_color(YELLOW), row ), rate_func = wiggle ) self.play( FadeOut(self.mini_batches_words), GrowFromCenter(brace), Write(text, run_time = 2), ) self.play(indicate_row(rows[0])) brace.add(text) for last_row, row in zip(rows, rows[1:-1]): self.play( last_row.shift, UP, brace.next_to, row, UP, SMALL_BUFF ) self.play(indicate_row(row)) self.wait() ### def get_examples(self): n_examples = self.n_rows*self.n_cols height = self.example_height training_data, validation_data, test_data = load_data_wrapper() return Group(*[ MNistMobject( t[0], rect_kwargs = {"stroke_width" : 2} ).set_height(height) for t in training_data[:n_examples] ]) # return Group(*[ # Square( # color = BLUE, # stroke_width = 2 # ).set_height(height) # for x in range(n_examples) # ]) def arrange_examples_in_grid(self, examples): examples.arrange_in_grid( n_rows = self.n_rows, buff = SMALL_BUFF ) class SGDSteps(ExternallyAnimatedScene): pass class GradientDescentSteps(ExternallyAnimatedScene): pass class SwimmingInTerms(TeacherStudentsScene): def construct(self): terms = VGroup( OldTexText("Cost surface"), OldTexText("Stochastic gradient descent"), OldTexText("Mini-batches"), OldTexText("Backpropagation"), ) terms.arrange(DOWN) terms.to_edge(UP) self.play( LaggedStartMap(FadeIn, terms), self.change_students(*["horrified"]*3) ) self.wait() self.play( terms[-1].next_to, self.teacher.get_corner(UP+LEFT), UP, FadeOut(VGroup(*terms[:-1])), self.teacher.change, "raise_right_hand", self.change_students(*["pondering"]*3) ) self.wait() class BackpropCode(ExternallyAnimatedScene): pass class BackpropCodeAddOn(PiCreatureScene): def construct(self): words = OldTexText( "The code you'd find \\\\ in Nielsen's book" ) words.to_corner(DOWN+LEFT) morty = self.pi_creature morty.next_to(words, UP) self.add(words) for mode in ["pondering", "thinking", "happy"]: self.play( morty.change, "pondering", morty.look, UP+LEFT ) self.play(morty.look, LEFT) self.wait(2) class CannotFollowCode(TeacherStudentsScene): def construct(self): self.student_says( "I...er...can't follow\\\\ that code at all.", target_mode = "confused", index = 1 ) self.play(self.students[1].change, "sad") self.play_student_changes( "angry", "sad", "angry", look_at = self.teacher.eyes ) self.play(self.teacher.change, "hesitant") self.wait(2) self.teacher_says( "Let's get to the \\\\ calculus then", target_mode = "hooray", added_anims = [self.change_students(*3*["plain"])], run_time = 1 ) self.wait(2) class EOCWrapper(Scene): def construct(self): title = OldTexText("Essence of calculus") title.to_edge(UP) screen = ScreenRectangle(height = 6) screen.next_to(title, DOWN) self.add(title) self.play(ShowCreation(screen)) self.wait() class SimplestNetworkExample(PreviewLearning): CONFIG = { "random_seed" : 6, "z_color" : GREEN, "cost_color" : RED, "desired_output_color" : YELLOW, "derivative_scale_val" : 0.85, } def construct(self): self.seed_random_libraries() self.collapse_ordinary_network() self.show_weights_and_biases() self.focus_just_on_last_two_layers() self.label_neurons() self.show_desired_output() self.show_cost() self.show_activation_formula() self.introduce_z() self.break_into_computational_graph() self.show_preceding_layer_in_computational_graph() self.show_number_lines() self.ask_about_w_sensitivity() self.show_derivative_wrt_w() self.show_chain_of_events() self.show_chain_rule() self.name_chain_rule() self.indicate_everything_on_screen() self.prepare_for_derivatives() self.compute_derivatives() self.get_lost_in_formulas() self.fire_together_wire_together() self.organize_chain_rule_rhs() self.show_average_derivative() self.show_gradient() self.transition_to_derivative_wrt_b() self.show_derivative_wrt_b() self.show_derivative_wrt_a() self.show_previous_weight_and_bias() self.animate_long_path() def seed_random_libraries(self): np.random.seed(self.random_seed) random.seed(self.random_seed) def collapse_ordinary_network(self): network_mob = self.network_mob config = dict(self.network_mob_config) config.pop("include_output_labels") config.update({ "edge_stroke_width" : 3, "edge_propogation_color" : YELLOW, "edge_propogation_time" : 1, "neuron_radius" : 0.3, }) simple_network = Network(sizes = [1, 1, 1, 1]) simple_network_mob = NetworkMobject(simple_network, **config) self.color_network_edges() s_edges = simple_network_mob.edge_groups for edge, weight_matrix in zip(s_edges, simple_network.weights): weight = weight_matrix[0][0] width = 2*abs(weight) color = BLUE if weight > 0 else RED edge.set_stroke(color, width) def edge_collapse_anims(edges, left_attachment_target): return [ ApplyMethod( e.put_start_and_end_on_with_projection, left_attachment_target.get_right(), e.get_end() ) for e in edges ] neuron = simple_network_mob.layers[0].neurons[0] self.play( ReplacementTransform(network_mob.layers[0], neuron), *edge_collapse_anims(network_mob.edge_groups[0], neuron) ) for i, layer in enumerate(network_mob.layers[1:]): neuron = simple_network_mob.layers[i+1].neurons[0] prev_edges = network_mob.edge_groups[i] prev_edge_target = simple_network_mob.edge_groups[i] if i+1 < len(network_mob.edge_groups): edges = network_mob.edge_groups[i+1] added_anims = edge_collapse_anims(edges, neuron) else: added_anims = [FadeOut(network_mob.output_labels)] self.play( ReplacementTransform(layer, neuron), ReplacementTransform(prev_edges, prev_edge_target), *added_anims ) self.remove(network_mob) self.add(simple_network_mob) self.network_mob = simple_network_mob self.network = self.network_mob.neural_network self.feed_forward(np.array([0.5])) self.wait() def show_weights_and_biases(self): network_mob = self.network_mob edges = VGroup(*[eg[0] for eg in network_mob.edge_groups]) neurons = VGroup(*[ layer.neurons[0] for layer in network_mob.layers[1:] ]) expression = OldTex( "C", "(", "w_1", ",", "b_1", ",", "w_2", ",", "b_2", ",", "w_3", ",", "b_3", ")" ) expression.shift(2*UP) expression.set_color_by_tex("C", RED) w_terms = expression.get_parts_by_tex("w_") for w, edge in zip(w_terms, edges): w.set_color(edge.get_color()) b_terms = expression.get_parts_by_tex("b_") variables = VGroup(*it.chain(w_terms, b_terms)) other_terms = VGroup(*[m for m in expression if m not in variables]) random.shuffle(variables.submobjects) self.play(ReplacementTransform(edges.copy(), w_terms)) self.wait() self.play(ReplacementTransform(neurons.copy(), b_terms)) self.wait() self.play(Write(other_terms)) for x in range(2): self.play(LaggedStartMap( Indicate, variables, rate_func = wiggle, run_time = 4, )) self.wait() self.play( FadeOut(other_terms), ReplacementTransform(w_terms, edges), ReplacementTransform(b_terms, neurons), ) self.remove(expression) def focus_just_on_last_two_layers(self): to_fade = VGroup(*it.chain(*list(zip( self.network_mob.layers[:2], self.network_mob.edge_groups[:2], )))) for mob in to_fade: mob.save_state() self.play(LaggedStartMap( ApplyMethod, to_fade, lambda m : (m.fade, 0.9) )) self.wait() self.prev_layers = to_fade def label_neurons(self): neurons = VGroup(*[ self.network_mob.layers[i].neurons[0] for i in (-1, -2) ]) decimals = VGroup() a_labels = VGroup() a_label_arrows = VGroup() superscripts = ["L", "L-1"] superscript_rects = VGroup() for neuron, superscript in zip(neurons, superscripts): decimal = self.get_neuron_activation_decimal(neuron) label = OldTex("a^{(%s)}"%superscript) label.next_to(neuron, DOWN, buff = LARGE_BUFF) superscript_rect = SurroundingRectangle(VGroup(*label[1:])) arrow = Arrow( label[0].get_top(), neuron.get_bottom(), buff = SMALL_BUFF, color = WHITE ) decimal.save_state() decimal.set_fill(opacity = 0) decimal.move_to(label) decimals.add(decimal) a_labels.add(label) a_label_arrows.add(arrow) superscript_rects.add(superscript_rect) self.play( Write(label, run_time = 1), GrowArrow(arrow), ) self.play(decimal.restore) opacity = neuron.get_fill_opacity() self.play( neuron.set_fill, None, 0, ChangingDecimal( decimal, lambda a : interpolate(opacity, 0.01, a) ), UpdateFromFunc( decimal, lambda d : d.set_fill(WHITE if d.number < 0.8 else BLACK) ), run_time = 2, rate_func = there_and_back, ) self.wait() not_exponents = OldTexText("Not exponents") not_exponents.next_to(superscript_rects, DOWN, MED_LARGE_BUFF) not_exponents.set_color(YELLOW) self.play( LaggedStartMap( ShowCreation, superscript_rects, lag_ratio = 0.8, run_time = 1.5 ), Write(not_exponents, run_time = 2) ) self.wait() self.play(*list(map(FadeOut, [not_exponents, superscript_rects]))) self.set_variables_as_attrs( a_labels, a_label_arrows, decimals, last_neurons = neurons ) def show_desired_output(self): neuron = self.network_mob.layers[-1].neurons[0].copy() neuron.shift(2*RIGHT) neuron.set_fill(opacity = 1) decimal = self.get_neuron_activation_decimal(neuron) rect = SurroundingRectangle(neuron) words = OldTexText("Desired \\\\ output") words.next_to(rect, UP) y_label = OldTex("y") y_label.next_to(neuron, DOWN, LARGE_BUFF) y_label.align_to(self.a_labels, DOWN) y_label_arrow = Arrow( y_label, neuron, color = WHITE, buff = SMALL_BUFF ) VGroup(words, rect, y_label).set_color(self.desired_output_color) self.play(*list(map(FadeIn, [neuron, decimal]))) self.play( ShowCreation(rect), Write(words, run_time = 1) ) self.wait() self.play( Write(y_label, run_time = 1), GrowArrow(y_label_arrow) ) self.wait() self.set_variables_as_attrs( y_label, y_label_arrow, desired_output_neuron = neuron, desired_output_decimal = decimal, desired_output_rect = rect, desired_output_words = words, ) def show_cost(self): pre_a = self.a_labels[0].copy() pre_y = self.y_label.copy() cost_equation = OldTex( "C_0", "(", "\\dots", ")", "=", "(", "a^{(L)}", "-", "y", ")", "^2" ) cost_equation.to_corner(UP+RIGHT) C0, a, y = [ cost_equation.get_part_by_tex(tex) for tex in ("C_0", "a^{(L)}", "y") ] y.set_color(YELLOW) cost_word = OldTexText("Cost") cost_word.next_to(C0[0], LEFT, LARGE_BUFF) cost_arrow = Arrow( cost_word, C0, buff = SMALL_BUFF ) VGroup(C0, cost_word, cost_arrow).set_color(self.cost_color) expression = OldTex( "\\text{For example: }" "(", "0.00", "-", "0.00", ")", "^2" ) numbers = expression.get_parts_by_tex("0.00") non_numbers = VGroup(*[m for m in expression if m not in numbers]) expression.next_to(cost_equation, DOWN, aligned_edge = RIGHT) decimals = VGroup( self.decimals[0], self.desired_output_decimal ).copy() decimals.generate_target() for d, n in zip(decimals.target, numbers): d.replace(n, dim_to_match = 1) d.set_color(n.get_color()) self.play( ReplacementTransform(pre_a, a), ReplacementTransform(pre_y, y), ) self.play(LaggedStartMap( FadeIn, VGroup(*[m for m in cost_equation if m not in [a, y]]) )) self.play( MoveToTarget(decimals), FadeIn(non_numbers) ) self.wait() self.play( Write(cost_word, run_time = 1), GrowArrow(cost_arrow) ) self.play(C0.shift, MED_SMALL_BUFF*UP, rate_func = wiggle) self.wait() self.play(*list(map(FadeOut, [decimals, non_numbers]))) self.set_variables_as_attrs( cost_equation, cost_word, cost_arrow ) def show_activation_formula(self): neuron = self.network_mob.layers[-1].neurons[0] edge = self.network_mob.edge_groups[-1][0] pre_aL, pre_aLm1 = self.a_labels.copy() formula = OldTex( "a^{(L)}", "=", "\\sigma", "(", "w^{(L)}", "a^{(L-1)}", "+", "b^{(L)}", ")" ) formula.next_to(neuron, UP, MED_LARGE_BUFF, RIGHT) aL, equals, sigma, lp, wL, aLm1, plus, bL, rp = formula wL.set_color(edge.get_color()) weight_label = wL.copy() bL.set_color(MAROON_B) bias_label = bL.copy() sigma_group = VGroup(sigma, lp, rp) sigma_group.save_state() sigma_group.set_fill(opacity = 0) sigma_group.shift(DOWN) self.play( ReplacementTransform(pre_aL, aL), Write(equals) ) self.play(ReplacementTransform( edge.copy(), wL )) self.wait() self.play(ReplacementTransform(pre_aLm1, aLm1)) self.wait() self.play(Write(VGroup(plus, bL), run_time = 1)) self.wait() self.play(sigma_group.restore) self.wait() weighted_sum_terms = VGroup(wL, aLm1, plus, bL) self.set_variables_as_attrs( formula, weighted_sum_terms ) def introduce_z(self): terms = self.weighted_sum_terms terms.generate_target() terms.target.next_to( self.formula, UP, buff = MED_LARGE_BUFF, aligned_edge = RIGHT ) terms.target.shift(MED_LARGE_BUFF*RIGHT) equals = OldTex("=") equals.next_to(terms.target[0][0], LEFT) z_label = OldTex("z^{(L)}") z_label.next_to(equals, LEFT) z_label.align_to(terms.target, DOWN) z_label.set_color(self.z_color) z_label2 = z_label.copy() aL_start = VGroup(*self.formula[:4]) aL_start.generate_target() aL_start.target.align_to(z_label, LEFT) z_label2.next_to(aL_start.target, RIGHT, SMALL_BUFF) z_label2.align_to(aL_start.target[0], DOWN) rp = self.formula[-1] rp.generate_target() rp.target.next_to(z_label2, RIGHT, SMALL_BUFF) rp.target.align_to(aL_start.target, DOWN) self.play(MoveToTarget(terms)) self.play(Write(z_label), Write(equals)) self.play( ReplacementTransform(z_label.copy(), z_label2), MoveToTarget(aL_start), MoveToTarget(rp), ) self.wait() zL_formula = VGroup(z_label, equals, *terms) aL_formula = VGroup(*list(aL_start) + [z_label2, rp]) self.set_variables_as_attrs(z_label, zL_formula, aL_formula) def break_into_computational_graph(self): network_early_layers = VGroup(*it.chain( self.network_mob.layers[:2], self.network_mob.edge_groups[:2] )) wL, aL, plus, bL = self.weighted_sum_terms top_terms = VGroup(wL, aL, bL).copy() zL = self.z_label.copy() aL = self.formula[0].copy() y = self.y_label.copy() C0 = self.cost_equation[0].copy() targets = VGroup() for mob in top_terms, zL, aL, C0: mob.generate_target() targets.add(mob.target) y.generate_target() top_terms.target.arrange(RIGHT, buff = MED_LARGE_BUFF) targets.arrange(DOWN, buff = LARGE_BUFF) targets.center().to_corner(DOWN+LEFT) y.target.next_to(aL.target, LEFT, LARGE_BUFF, DOWN) top_lines = VGroup(*[ Line( term.get_bottom(), zL.target.get_top(), buff = SMALL_BUFF ) for term in top_terms.target ]) z_to_a_line, a_to_c_line, y_to_c_line = all_lines = [ Line( m1.target.get_bottom(), m2.target.get_top(), buff = SMALL_BUFF ) for m1, m2 in [ (zL, aL), (aL, C0), (y, C0) ] ] for mob in [top_lines] + all_lines: yellow_copy = mob.copy().set_color(YELLOW) mob.flash = ShowCreationThenDestruction(yellow_copy) self.play(MoveToTarget(top_terms)) self.wait() self.play(MoveToTarget(zL)) self.play( ShowCreation(top_lines, lag_ratio = 0), top_lines.flash ) self.wait() self.play(MoveToTarget(aL)) self.play( network_early_layers.fade, 1, ShowCreation(z_to_a_line), z_to_a_line.flash ) self.wait() self.play(MoveToTarget(y)) self.play(MoveToTarget(C0)) self.play(*it.chain(*[ [ShowCreation(line), line.flash] for line in (a_to_c_line, y_to_c_line) ])) self.wait(2) comp_graph = VGroup() comp_graph.wL, comp_graph.aLm1, comp_graph.bL = top_terms comp_graph.top_lines = top_lines comp_graph.zL = zL comp_graph.z_to_a_line = z_to_a_line comp_graph.aL = aL comp_graph.y = y comp_graph.a_to_c_line = a_to_c_line comp_graph.y_to_c_line = y_to_c_line comp_graph.C0 = C0 comp_graph.digest_mobject_attrs() self.comp_graph = comp_graph def show_preceding_layer_in_computational_graph(self): shift_vect = DOWN comp_graph = self.comp_graph comp_graph.save_state() comp_graph.generate_target() comp_graph.target.shift(shift_vect) rect = SurroundingRectangle(comp_graph.aLm1) attrs = ["wL", "aLm1", "bL", "zL"] new_terms = VGroup() for attr in attrs: term = getattr(comp_graph, attr) tex = term.get_tex() if "L-1" in tex: tex = tex.replace("L-1", "L-2") else: tex = tex.replace("L", "L-1") new_term = OldTex(tex) new_term.set_color(term.get_color()) new_term.move_to(term) new_terms.add(new_term) new_edges = VGroup( comp_graph.top_lines.copy(), comp_graph.z_to_a_line.copy(), ) new_subgraph = VGroup(new_terms, new_edges) new_subgraph.next_to(comp_graph.target, UP, SMALL_BUFF) self.wLm1 = new_terms[0] self.zLm1 = new_terms[-1] prev_neuron = self.network_mob.layers[1] prev_neuron.restore() prev_edge = self.network_mob.edge_groups[1] prev_edge.restore() self.play( ShowCreation(rect), FadeIn(prev_neuron), ShowCreation(prev_edge) ) self.play( ReplacementTransform( VGroup(prev_neuron, prev_edge).copy(), new_subgraph ), UpdateFromAlphaFunc( new_terms, lambda m, a : m.set_fill(opacity = a) ), MoveToTarget(comp_graph), rect.shift, shift_vect ) self.wait(2) self.play( FadeOut(new_subgraph), FadeOut(prev_neuron), FadeOut(prev_edge), comp_graph.restore, rect.shift, -shift_vect, rect.set_stroke, BLACK, 0 ) VGroup(prev_neuron, prev_edge).fade(1) self.remove(rect) self.wait() self.prev_comp_subgraph = new_subgraph def show_number_lines(self): comp_graph = self.comp_graph wL, aLm1, bL, zL, aL, C0 = [ getattr(comp_graph, attr) for attr in ["wL", "aLm1", "bL", "zL", "aL", "C0"] ] wL.val = self.network.weights[-1][0][0] aL.val = self.decimals[0].number zL.val = sigmoid_inverse(aL.val) C0.val = (aL.val - 1)**2 number_line = UnitInterval( unit_size = 2, stroke_width = 2, tick_size = 0.075, color = GREY_B, ) for mob in wL, zL, aL, C0: mob.number_line = number_line.deepcopy() if mob is wL: mob.number_line.next_to(mob, UP, MED_LARGE_BUFF, LEFT) else: mob.number_line.next_to(mob, RIGHT) if mob is C0: mob.number_line.x_max = 0.5 for tick_mark in mob.number_line.tick_marks[1::2]: mob.number_line.tick_marks.remove(tick_mark) mob.dot = Dot(color = mob.get_color()) mob.dot.move_to( mob.number_line.number_to_point(mob.val) ) if mob is wL: path_arc = 0 dot_spot = mob.dot.get_bottom() else: path_arc = -0.7*np.pi dot_spot = mob.dot.get_top() if mob is C0: mob_spot = mob[0].get_corner(UP+RIGHT) tip_length = 0.15 else: mob_spot = mob.get_corner(UP+RIGHT) tip_length = 0.2 mob.arrow = Arrow( mob_spot, dot_spot, path_arc = path_arc, tip_length = tip_length, buff = SMALL_BUFF, ) mob.arrow.set_color(mob.get_color()) mob.arrow.set_stroke(width = 5) self.play(ShowCreation( mob.number_line, lag_ratio = 0.5 )) self.play( ShowCreation(mob.arrow), ReplacementTransform( mob.copy(), mob.dot, path_arc = path_arc ) ) self.wait() def ask_about_w_sensitivity(self): wL, aLm1, bL, zL, aL, C0 = [ getattr(self.comp_graph, attr) for attr in ["wL", "aLm1", "bL", "zL", "aL", "C0"] ] aLm1_val = self.last_neurons[1].get_fill_opacity() bL_val = self.network.biases[-1][0] get_wL_val = lambda : wL.number_line.point_to_number( wL.dot.get_center() ) get_zL_val = lambda : get_wL_val()*aLm1_val+bL_val get_aL_val = lambda : sigmoid(get_zL_val()) get_C0_val = lambda : (get_aL_val() - 1)**2 def generate_dot_update(term, val_func): def update_dot(dot): dot.move_to(term.number_line.number_to_point(val_func())) return dot return update_dot dot_update_anims = [ UpdateFromFunc(term.dot, generate_dot_update(term, val_func)) for term, val_func in [ (zL, get_zL_val), (aL, get_aL_val), (C0, get_C0_val), ] ] def shake_dot(run_time = 2, rate_func = there_and_back): self.play( ApplyMethod( wL.dot.shift, LEFT, rate_func = rate_func, run_time = run_time ), *dot_update_anims ) wL_line = Line(wL.dot.get_center(), wL.dot.get_center()+LEFT) del_wL = OldTex("\\partial w^{(L)}") del_wL.scale(self.derivative_scale_val) del_wL.brace = Brace(wL_line, UP, buff = SMALL_BUFF) del_wL.set_color(wL.get_color()) del_wL.next_to(del_wL.brace, UP, SMALL_BUFF) C0_line = Line(C0.dot.get_center(), C0.dot.get_center()+MED_SMALL_BUFF*RIGHT) del_C0 = OldTex("\\partial C_0") del_C0.scale(self.derivative_scale_val) del_C0.brace = Brace(C0_line, UP, buff = SMALL_BUFF) del_C0.set_color(C0.get_color()) del_C0.next_to(del_C0.brace, UP, SMALL_BUFF) for sym in del_wL, del_C0: self.play( GrowFromCenter(sym.brace), Write(sym, run_time = 1) ) shake_dot() self.wait() self.set_variables_as_attrs( shake_dot, del_wL, del_C0, ) def show_derivative_wrt_w(self): del_wL = self.del_wL del_C0 = self.del_C0 cost_word = self.cost_word cost_arrow = self.cost_arrow shake_dot = self.shake_dot wL = self.comp_graph.wL dC_dw = OldTex( "{\\partial C_0", "\\over", "\\partial w^{(L)} }" ) dC_dw[0].set_color(del_C0.get_color()) dC_dw[2].set_color(del_wL.get_color()) dC_dw.scale(self.derivative_scale_val) dC_dw.to_edge(UP, buff = MED_SMALL_BUFF) dC_dw.shift(3.5*LEFT) full_rect = SurroundingRectangle(dC_dw) full_rect_copy = full_rect.copy() words = OldTexText("What we want") words.next_to(full_rect, RIGHT) words.set_color(YELLOW) denom_rect = SurroundingRectangle(dC_dw[2]) numer_rect = SurroundingRectangle(dC_dw[0]) self.play( ReplacementTransform(del_C0.copy(), dC_dw[0]), ReplacementTransform(del_wL.copy(), dC_dw[2]), Write(dC_dw[1], run_time = 1) ) self.play( FadeOut(cost_word), FadeOut(cost_arrow), ShowCreation(full_rect), Write(words, run_time = 1), ) self.wait(2) self.play( FadeOut(words), ReplacementTransform(full_rect, denom_rect) ) self.play(Transform(dC_dw[2].copy(), del_wL, remover = True)) shake_dot() self.play(ReplacementTransform(denom_rect, numer_rect)) self.play(Transform(dC_dw[0].copy(), del_C0, remover = True)) shake_dot() self.wait() self.play(ReplacementTransform(numer_rect, full_rect_copy)) self.play(FadeOut(full_rect_copy)) self.wait() self.dC_dw = dC_dw def show_chain_of_events(self): comp_graph = self.comp_graph wL, zL, aL, C0 = [ getattr(comp_graph, attr) for attr in ["wL", "zL", "aL", "C0"] ] del_wL = self.del_wL del_C0 = self.del_C0 zL_line = Line(ORIGIN, MED_LARGE_BUFF*LEFT) zL_line.shift(zL.dot.get_center()) del_zL = OldTex("\\partial z^{(L)}") del_zL.set_color(zL.get_color()) del_zL.brace = Brace(zL_line, DOWN, buff = SMALL_BUFF) aL_line = Line(ORIGIN, MED_SMALL_BUFF*LEFT) aL_line.shift(aL.dot.get_center()) del_aL = OldTex("\\partial a^{(L)}") del_aL.set_color(aL.get_color()) del_aL.brace = Brace(aL_line, DOWN, buff = SMALL_BUFF) for sym in del_zL, del_aL: sym.scale(self.derivative_scale_val) sym.brace.stretch_about_point( 0.5, 1, sym.brace.get_top(), ) sym.shift( sym.brace.get_bottom()+SMALL_BUFF*DOWN \ -sym[0].get_corner(UP+RIGHT) ) syms = [del_wL, del_zL, del_aL, del_C0] for s1, s2 in zip(syms, syms[1:]): self.play( ReplacementTransform(s1.copy(), s2), ReplacementTransform(s1.brace.copy(), s2.brace), ) self.shake_dot(run_time = 1.5) self.wait(0.5) self.wait() self.set_variables_as_attrs(del_zL, del_aL) def show_chain_rule(self): dC_dw = self.dC_dw del_syms = [ getattr(self, attr) for attr in ("del_wL", "del_zL", "del_aL", "del_C0") ] dz_dw = OldTex( "{\\partial z^{(L)}", "\\over", "\\partial w^{(L)}}" ) da_dz = OldTex( "{\\partial a^{(L)}", "\\over", "\\partial z^{(L)}}" ) dC_da = OldTex( "{\\partial C0}", "\\over", "\\partial a^{(L)}}" ) dz_dw[2].set_color(self.del_wL.get_color()) VGroup(dz_dw[0], da_dz[2]).set_color(self.z_color) dC_da[0].set_color(self.cost_color) equals = OldTex("=") group = VGroup(equals, dz_dw, da_dz, dC_da) group.arrange(RIGHT, SMALL_BUFF) group.scale(self.derivative_scale_val) group.next_to(dC_dw, RIGHT) for mob in group[1:]: target_y = equals.get_center()[1] y = mob[1].get_center()[1] mob.shift((target_y - y)*UP) self.play(Write(equals, run_time = 1)) for frac, top_sym, bot_sym in zip(group[1:], del_syms[1:], del_syms): self.play(Indicate(top_sym, rate_func = wiggle)) self.play( ReplacementTransform(top_sym.copy(), frac[0]), FadeIn(frac[1]), ) self.play(Indicate(bot_sym, rate_func = wiggle)) self.play(ReplacementTransform( bot_sym.copy(), frac[2] )) self.wait() self.shake_dot() self.wait() self.chain_rule_equation = VGroup(dC_dw, *group) def name_chain_rule(self): graph_parts = self.get_all_comp_graph_parts() equation = self.chain_rule_equation rect = SurroundingRectangle(equation) group = VGroup(equation, rect) group.generate_target() group.target.to_corner(UP+LEFT) words = OldTexText("Chain rule") words.set_color(YELLOW) words.next_to(group.target, DOWN) self.play(ShowCreation(rect)) self.play( MoveToTarget(group), Write(words, run_time = 1), graph_parts.scale, 0.7, graph_parts.get_bottom() ) self.wait(2) self.play(*list(map(FadeOut, [rect, words]))) def indicate_everything_on_screen(self): everything = VGroup(*self.get_top_level_mobjects()) everything = VGroup(*[m for m in everything.family_members_with_points() if not m.is_subpath]) self.play(LaggedStartMap( Indicate, everything, rate_func = wiggle, lag_ratio = 0.2, run_time = 5 )) self.wait() def prepare_for_derivatives(self): zL_formula = self.zL_formula aL_formula = self.aL_formula az_formulas = VGroup(zL_formula, aL_formula) cost_equation = self.cost_equation desired_output_words = self.desired_output_words az_formulas.generate_target() az_formulas.target.to_edge(RIGHT) index = 4 cost_eq = cost_equation[index] z_eq = az_formulas.target[0][1] x_shift = (z_eq.get_center() - cost_eq.get_center())[0]*RIGHT cost_equation.generate_target() Transform( VGroup(*cost_equation.target[1:index]), VectorizedPoint(cost_eq.get_left()) ).update(1) cost_equation.target[0].next_to(cost_eq, LEFT, SMALL_BUFF) cost_equation.target.shift(x_shift) self.play( FadeOut(self.all_comp_graph_parts), FadeOut(self.desired_output_words), MoveToTarget(az_formulas), MoveToTarget(cost_equation) ) def compute_derivatives(self): cost_equation = self.cost_equation zL_formula = self.zL_formula aL_formula = self.aL_formula chain_rule_equation = self.chain_rule_equation.copy() dC_dw, equals, dz_dw, da_dz, dC_da = chain_rule_equation derivs = VGroup(dC_da, da_dz, dz_dw) deriv_targets = VGroup() for deriv in derivs: deriv.generate_target() deriv_targets.add(deriv.target) deriv_targets.arrange(DOWN, buff = MED_LARGE_BUFF) deriv_targets.next_to(dC_dw, DOWN, LARGE_BUFF) for deriv in derivs: deriv.equals = OldTex("=") deriv.equals.next_to(deriv.target, RIGHT) #dC_da self.play( MoveToTarget(dC_da), Write(dC_da.equals) ) index = 4 cost_rhs = VGroup(*cost_equation[index+1:]) dC_da.rhs = cost_rhs.copy() two = dC_da.rhs[-1] two.scale(1.5) two.next_to(dC_da.rhs[0], LEFT, SMALL_BUFF) dC_da.rhs.next_to(dC_da.equals, RIGHT) dC_da.rhs.shift(0.7*SMALL_BUFF*UP) cost_equation.save_state() self.play( cost_equation.next_to, dC_da.rhs, DOWN, MED_LARGE_BUFF, LEFT ) self.wait() self.play(ReplacementTransform( cost_rhs.copy(), dC_da.rhs, path_arc = np.pi/2, )) self.wait() self.play(cost_equation.restore) self.wait() #show_difference neuron = self.last_neurons[0] decimal = self.decimals[0] double_arrow = DoubleArrow( neuron.get_right(), self.desired_output_neuron.get_left(), buff = SMALL_BUFF, color = RED ) moving_decimals = VGroup( self.decimals[0].copy(), self.desired_output_decimal.copy() ) minus = OldTex("-") minus.move_to(moving_decimals) minus.scale(0.7) minus.set_fill(opacity = 0) moving_decimals.submobjects.insert(1, minus) moving_decimals.generate_target(use_deepcopy = True) moving_decimals.target.arrange(RIGHT, buff = SMALL_BUFF) moving_decimals.target.scale(1.5) moving_decimals.target.next_to( dC_da.rhs, DOWN, buff = MED_LARGE_BUFF, aligned_edge = RIGHT, ) moving_decimals.target.set_fill(WHITE, 1) self.play(ReplacementTransform( dC_da.rhs.copy(), double_arrow )) self.wait() self.play(MoveToTarget(moving_decimals)) opacity = neuron.get_fill_opacity() for target_o in 0, opacity: self.wait(2) self.play( neuron.set_fill, None, target_o, *[ ChangingDecimal(d, lambda a : neuron.get_fill_opacity()) for d in (decimal, moving_decimals[0]) ] ) self.play(*list(map(FadeOut, [double_arrow, moving_decimals]))) #da_dz self.play( MoveToTarget(da_dz), Write(da_dz.equals) ) a_rhs = VGroup(*aL_formula[2:]) da_dz.rhs = a_rhs.copy() prime = OldTex("'") prime.move_to(da_dz.rhs[0].get_corner(UP+RIGHT)) da_dz.rhs[0].shift(0.5*SMALL_BUFF*LEFT) da_dz.rhs.add_to_back(prime) da_dz.rhs.next_to(da_dz.equals, RIGHT) da_dz.rhs.shift(0.5*SMALL_BUFF*UP) aL_formula.save_state() self.play( aL_formula.next_to, da_dz.rhs, DOWN, MED_LARGE_BUFF, LEFT ) self.wait() self.play(ReplacementTransform( a_rhs.copy(), da_dz.rhs, )) self.wait() self.play(aL_formula.restore) self.wait() #dz_dw self.play( MoveToTarget(dz_dw), Write(dz_dw.equals) ) z_rhs = VGroup(*zL_formula[2:]) dz_dw.rhs = z_rhs[1].copy() dz_dw.rhs.next_to(dz_dw.equals, RIGHT) dz_dw.rhs.shift(SMALL_BUFF*UP) zL_formula.save_state() self.play( zL_formula.next_to, dz_dw.rhs, DOWN, MED_LARGE_BUFF, LEFT, ) self.wait() rect = SurroundingRectangle(VGroup(*zL_formula[2:4])) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.play(ReplacementTransform( z_rhs[1].copy(), dz_dw.rhs, )) self.wait() self.play(zL_formula.restore) self.wait() self.derivative_equations = VGroup(dC_da, da_dz, dz_dw) def get_lost_in_formulas(self): randy = Randolph() randy.flip() randy.scale(0.7) randy.to_edge(DOWN) randy.shift(LEFT) self.play(FadeIn(randy)) self.play(randy.change, "pleading", self.chain_rule_equation) self.play(Blink(randy)) self.play(randy.change, "maybe") self.play(Blink(randy)) self.play(FadeOut(randy)) def fire_together_wire_together(self): dz_dw = self.derivative_equations[2] rhs = dz_dw.rhs rhs_copy = rhs.copy() del_wL = dz_dw[2].copy() rect = SurroundingRectangle(VGroup(dz_dw, dz_dw.rhs)) edge = self.network_mob.edge_groups[-1][0] edge.save_state() neuron = self.last_neurons[1] decimal = self.decimals[1] def get_decimal_anims(): return [ ChangingDecimal(decimal, lambda a : neuron.get_fill_opacity()), UpdateFromFunc( decimal, lambda m : m.set_color( WHITE if neuron.get_fill_opacity() < 0.8 \ else BLACK ) ) ] self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.play( del_wL.next_to, edge, UP, SMALL_BUFF ) self.play( edge.set_stroke, None, 10, rate_func = wiggle, run_time = 3, ) self.wait() self.play(rhs.shift, MED_LARGE_BUFF*UP, rate_func = wiggle) self.play( rhs_copy.move_to, neuron, rhs_copy.set_fill, None, 0 ) self.remove(rhs_copy) self.play( neuron.set_fill, None, 0, *get_decimal_anims(), run_time = 3, rate_func = there_and_back ) self.wait() #Fire together wire together opacity = neuron.get_fill_opacity() self.play( neuron.set_fill, None, 0.99, *get_decimal_anims() ) self.play(edge.set_stroke, None, 8) self.play( neuron.set_fill, None, opacity, *get_decimal_anims() ) self.play(edge.restore, FadeOut(del_wL)) self.wait(3) def organize_chain_rule_rhs(self): fracs = self.derivative_equations equals_group = VGroup(*[frac.equals for frac in fracs]) rhs_group = VGroup(*[frac.rhs for frac in reversed(fracs)]) chain_rule_equation = self.chain_rule_equation equals = OldTex("=") equals.next_to(chain_rule_equation, RIGHT) rhs_group.generate_target() rhs_group.target.arrange(RIGHT, buff = SMALL_BUFF) rhs_group.target.next_to(equals, RIGHT) rhs_group.target.shift(SMALL_BUFF*UP) right_group = VGroup( self.cost_equation, self.zL_formula, self.aL_formula, self.network_mob, self.decimals, self.a_labels, self.a_label_arrows, self.y_label, self.y_label_arrow, self.desired_output_neuron, self.desired_output_rect, self.desired_output_decimal, ) self.play( MoveToTarget(rhs_group, path_arc = np.pi/2), Write(equals), FadeOut(fracs), FadeOut(equals_group), right_group.to_corner, DOWN+RIGHT ) self.wait() rhs_group.add(equals) self.chain_rule_rhs = rhs_group def show_average_derivative(self): dC0_dw = self.chain_rule_equation[0] full_derivative = OldTex( "{\\partial C", "\\over", "\\partial w^{(L)}}", "=", "\\frac{1}{n}", "\\sum_{k=0}^{n-1}", "{\\partial C_k", "\\over", "\\partial w^{(L)}}" ) full_derivative.set_color_by_tex_to_color_map({ "partial C" : self.cost_color, "partial w" : self.del_wL.get_color() }) full_derivative.to_edge(LEFT) dCk_dw = VGroup(*full_derivative[-3:]) lhs = VGroup(*full_derivative[:3]) rhs = VGroup(*full_derivative[4:]) lhs_brace = Brace(lhs, DOWN) lhs_text = lhs_brace.get_text("Derivative of \\\\ full cost function") rhs_brace = Brace(rhs, UP) rhs_text = rhs_brace.get_text("Average of all \\\\ training examples") VGroup( full_derivative, lhs_brace, lhs_text, rhs_brace, rhs_text ).to_corner(DOWN+LEFT) mover = dC0_dw.copy() self.play(Transform(mover, dCk_dw)) self.play(Write(full_derivative, run_time = 2)) self.remove(mover) for brace, text in (rhs_brace, rhs_text), (lhs_brace, lhs_text): self.play( GrowFromCenter(brace), Write(text, run_time = 2), ) self.wait(2) self.cycle_through_altnernate_training_examples() self.play(*list(map(FadeOut, [ VGroup(*full_derivative[3:]), lhs_brace, lhs_text, rhs_brace, rhs_text, ]))) self.dC_dw = lhs def cycle_through_altnernate_training_examples(self): neurons = VGroup( self.desired_output_neuron, *self.last_neurons ) decimals = VGroup( self.desired_output_decimal, *self.decimals ) group = VGroup(neurons, decimals) group.save_state() for x in range(20): for n, d in zip(neurons, decimals): o = np.random.random() if n is self.desired_output_neuron: o = np.round(o) n.set_fill(opacity = o) Transform( d, self.get_neuron_activation_decimal(n) ).update(1) self.wait(0.2) self.play(group.restore, run_time = 0.2) def show_gradient(self): dC_dw = self.dC_dw dC_dw.generate_target() terms = VGroup( OldTex("{\\partial C", "\\over", "\\partial w^{(1)}"), OldTex("{\\partial C", "\\over", "\\partial b^{(1)}"), OldTex("\\vdots"), dC_dw.target, OldTex("{\\partial C", "\\over", "\\partial b^{(L)}"), ) for term in terms: if isinstance(term, Tex): term.set_color_by_tex_to_color_map({ "partial C" : RED, "partial w" : BLUE, "partial b" : MAROON_B, }) terms.arrange(DOWN, buff = MED_LARGE_BUFF) lb, rb = brackets = OldTex("[]") brackets.scale(3) brackets.stretch_to_fit_height(1.1*terms.get_height()) lb.next_to(terms, LEFT, buff = SMALL_BUFF) rb.next_to(terms, RIGHT, buff = SMALL_BUFF) vect = VGroup(lb, terms, rb) vect.set_height(5) lhs = OldTex("\\nabla C", "=") lhs[0].set_color(RED) lhs.next_to(vect, LEFT) VGroup(lhs, vect).to_corner(DOWN+LEFT, buff = LARGE_BUFF) terms.remove(dC_dw.target) self.play( MoveToTarget(dC_dw), Write(vect, run_time = 1) ) terms.add(dC_dw) self.play(Write(lhs)) self.wait(2) self.play(FadeOut(VGroup(lhs, vect))) def transition_to_derivative_wrt_b(self): all_comp_graph_parts = self.all_comp_graph_parts all_comp_graph_parts.scale( 1.3, about_point = all_comp_graph_parts.get_bottom() ) comp_graph = self.comp_graph wL, bL, zL, aL, C0 = [ getattr(comp_graph, attr) for attr in ["wL", "bL", "zL", "aL", "C0"] ] path_to_C = VGroup(wL, zL, aL, C0) top_expression = VGroup( self.chain_rule_equation, self.chain_rule_rhs ) rect = SurroundingRectangle(top_expression) self.play(ShowCreation(rect)) self.play(FadeIn(comp_graph), FadeOut(rect)) for x in range(2): self.play(LaggedStartMap( Indicate, path_to_C, rate_func = there_and_back, run_time = 1.5, lag_ratio = 0.7, )) self.wait() def show_derivative_wrt_b(self): comp_graph = self.comp_graph dC0_dw = self.chain_rule_equation[0] dz_dw = self.chain_rule_equation[2] aLm1 = self.chain_rule_rhs[0] left_term_group = VGroup(dz_dw, aLm1) dz_dw_rect = SurroundingRectangle(dz_dw) del_w = dC0_dw[2] del_b = OldTex("\\partial b^{(L)}") del_b.set_color(MAROON_B) del_b.replace(del_w) dz_db = OldTex( "{\\partial z^{(L)}", "\\over", "\\partial b^{(L)}}" ) dz_db.set_color_by_tex_to_color_map({ "partial z" : self.z_color, "partial b" : MAROON_B }) dz_db.replace(dz_dw) one = OldTex("1") one.move_to(aLm1, RIGHT) arrow = Arrow( dz_db.get_bottom(), one.get_bottom(), path_arc = np.pi/2, color = WHITE, ) arrow.set_stroke(width = 2) wL, bL, zL, aL, C0 = [ getattr(comp_graph, attr) for attr in ["wL", "bL", "zL", "aL", "C0"] ] path_to_C = VGroup(bL, zL, aL, C0) def get_path_animation(): return LaggedStartMap( Indicate, path_to_C, rate_func = there_and_back, run_time = 1.5, lag_ratio = 0.7, ) zL_formula = self.zL_formula b_in_z_formula = zL_formula[-1] z_formula_rect = SurroundingRectangle(zL_formula) b_in_z_rect = SurroundingRectangle(b_in_z_formula) self.play(get_path_animation()) self.play(ShowCreation(dz_dw_rect)) self.play(FadeOut(dz_dw_rect)) self.play( left_term_group.shift, DOWN, left_term_group.fade, 1, ) self.remove(left_term_group) self.chain_rule_equation.remove(dz_dw) self.chain_rule_rhs.remove(aLm1) self.play(Transform(del_w, del_b)) self.play(FadeIn(dz_db)) self.play(get_path_animation()) self.wait() self.play(ShowCreation(z_formula_rect)) self.wait() self.play(ReplacementTransform(z_formula_rect, b_in_z_rect)) self.wait() self.play( ReplacementTransform(b_in_z_formula.copy(), one), FadeOut(b_in_z_rect) ) self.play( ShowCreation(arrow), ReplacementTransform( dz_db.copy(), one, path_arc = arrow.path_arc ) ) self.wait(2) self.play(*list(map(FadeOut, [dz_db, arrow, one]))) self.dz_db = dz_db def show_derivative_wrt_a(self): denom = self.chain_rule_equation[0][2] numer = VGroup(*self.chain_rule_equation[0][:2]) del_aLm1 = OldTex("\\partial a^{(L-1)}") del_aLm1.scale(0.8) del_aLm1.move_to(denom) dz_daLm1 = OldTex( "{\\partial z^{(L)}", "\\over", "\\partial a^{(L-1)}}" ) dz_daLm1.scale(0.8) dz_daLm1.next_to(self.chain_rule_equation[1], RIGHT, SMALL_BUFF) dz_daLm1.shift(0.7*SMALL_BUFF*UP) dz_daLm1[0].set_color(self.z_color) dz_daLm1_rect = SurroundingRectangle(dz_daLm1) wL = self.zL_formula[2].copy() wL.next_to(self.chain_rule_rhs[0], LEFT, SMALL_BUFF) arrow = Arrow( dz_daLm1.get_bottom(), wL.get_bottom(), path_arc = np.pi/2, color = WHITE, ) comp_graph = self.comp_graph path_to_C = VGroup(*[ getattr(comp_graph, attr) for attr in ["aLm1", "zL", "aL", "C0"] ]) def get_path_animation(): return LaggedStartMap( Indicate, path_to_C, rate_func = there_and_back, run_time = 1.5, lag_ratio = 0.7, ) zL_formula = self.zL_formula z_formula_rect = SurroundingRectangle(zL_formula) a_in_z_rect = SurroundingRectangle(VGroup(*zL_formula[2:4])) wL_in_z = zL_formula[2] for x in range(3): self.play(get_path_animation()) self.play( numer.shift, SMALL_BUFF*UP, Transform(denom, del_aLm1) ) self.play( FadeIn(dz_daLm1), VGroup(*self.chain_rule_equation[-2:]).shift, SMALL_BUFF*RIGHT, ) self.wait() self.play(ShowCreation(dz_daLm1_rect)) self.wait() self.play(ReplacementTransform( dz_daLm1_rect, z_formula_rect )) self.wait() self.play(ReplacementTransform(z_formula_rect, a_in_z_rect)) self.play( ReplacementTransform(wL_in_z.copy(), wL), FadeOut(a_in_z_rect) ) self.play( ShowCreation(arrow), ReplacementTransform( dz_daLm1.copy(), wL, path_arc = arrow.path_arc ) ) self.wait(2) self.chain_rule_rhs.add(wL, arrow) self.chain_rule_equation.add(dz_daLm1) def show_previous_weight_and_bias(self): to_fade = self.chain_rule_rhs comp_graph = self.comp_graph prev_comp_subgraph = self.prev_comp_subgraph prev_comp_subgraph.scale(0.8) prev_comp_subgraph.next_to(comp_graph, UP, SMALL_BUFF) prev_layer = VGroup( self.network_mob.layers[1], self.network_mob.edge_groups[1], ) for mob in prev_layer: mob.restore() prev_layer.next_to(self.last_neurons, LEFT, buff = 0) self.remove(prev_layer) self.play(LaggedStartMap(FadeOut, to_fade, run_time = 1)) self.play( ShowCreation(prev_comp_subgraph, run_time = 1), self.chain_rule_equation.to_edge, RIGHT ) self.play(FadeIn(prev_layer)) ### neuron = self.network_mob.layers[1].neurons[0] decimal = self.get_neuron_activation_decimal(neuron) a_label = OldTex("a^{(L-2)}") a_label.replace(self.a_labels[1]) arrow = self.a_label_arrows[1].copy() VGroup(a_label, arrow).shift( neuron.get_center() - self.last_neurons[1].get_center() ) self.play( Write(a_label, run_time = 1), Write(decimal, run_time = 1), GrowArrow(arrow), ) def animate_long_path(self): comp_graph = self.comp_graph path_to_C = VGroup( self.wLm1, self.zLm1, *[ getattr(comp_graph, attr) for attr in ["aLm1", "zL", "aL", "C0"] ] ) for x in range(2): self.play(LaggedStartMap( Indicate, path_to_C, rate_func = there_and_back, run_time = 1.5, lag_ratio = 0.4, )) self.wait(2) ### def get_neuron_activation_decimal(self, neuron): opacity = neuron.get_fill_opacity() decimal = DecimalNumber(opacity, num_decimal_places = 2) decimal.set_width(0.85*neuron.get_width()) if decimal.number > 0.8: decimal.set_fill(BLACK) decimal.move_to(neuron) return decimal def get_all_comp_graph_parts(self): comp_graph = self.comp_graph result = VGroup(comp_graph) for attr in "wL", "zL", "aL", "C0": sym = getattr(comp_graph, attr) result.add( sym.arrow, sym.number_line, sym.dot ) del_sym = getattr(self, "del_" + attr) result.add(del_sym, del_sym.brace) self.all_comp_graph_parts = result return result class IsntThatOverSimplified(TeacherStudentsScene): def construct(self): self.student_says( "Isn't that over-simplified?", target_mode = "raise_right_hand", run_time = 1 ) self.play_student_changes( "pondering", "raise_right_hand", "pondering" ) self.wait() self.teacher_says( "Not that much, actually!", run_time = 1, target_mode = "hooray" ) self.wait(2) class GeneralFormulas(SimplestNetworkExample): CONFIG = { "layer_sizes" : [3, 3, 2], "network_mob_config" : { "include_output_labels" : False, "neuron_to_neuron_buff" : LARGE_BUFF, "neuron_radius" : 0.3, }, "edge_stroke_width" : 4, "stroke_width_exp" : 0.2, "random_seed" : 9, } def setup(self): self.seed_random_libraries() self.setup_bases() def construct(self): self.setup_network_mob() self.show_all_a_labels() self.only_show_abstract_a_labels() self.add_desired_output() self.show_cost() self.show_example_weight() self.show_values_between_weight_and_cost() self.show_weight_chain_rule() self.show_derivative_wrt_prev_activation() self.show_multiple_paths_from_prev_layer_neuron() self.show_previous_layer() def setup_network_mob(self): self.color_network_edges() self.network_mob.to_edge(LEFT) self.network_mob.shift(DOWN) in_vect = np.random.random(self.layer_sizes[0]) self.network_mob.activate_layers(in_vect) self.remove(self.network_mob.layers[0]) self.remove(self.network_mob.edge_groups[0]) def show_all_a_labels(self): Lm1_neurons = self.network_mob.layers[-2].neurons L_neurons = self.network_mob.layers[-1].neurons all_arrows = VGroup() all_labels = VGroup() all_decimals = VGroup() all_subscript_rects = VGroup() for neurons in L_neurons, Lm1_neurons: is_L = neurons is L_neurons vect = LEFT if is_L else RIGHT s = "L" if is_L else "L-1" arrows = VGroup() labels = VGroup() decimals = VGroup() subscript_rects = VGroup() for i, neuron in enumerate(neurons): arrow = Arrow(ORIGIN, vect) arrow.next_to(neuron, -vect) arrow.set_fill(WHITE) label = OldTex("a^{(%s)}_%d"%(s, i)) label.next_to(arrow, -vect, SMALL_BUFF) rect = SurroundingRectangle(label[-1], buff = 0.5*SMALL_BUFF) decimal = self.get_neuron_activation_decimal(neuron) neuron.arrow = arrow neuron.label = label neuron.decimal = decimal arrows.add(arrow) labels.add(label) decimals.add(decimal) subscript_rects.add(rect) all_arrows.add(arrows) all_labels.add(labels) all_decimals.add(decimals) all_subscript_rects.add(subscript_rects) start_labels, start_arrows = [ VGroup(*list(map(VGroup, [group[i][0] for i in (0, 1)]))).copy() for group in (all_labels, all_arrows) ] for label in start_labels: label[0][-1].set_color(BLACK) self.add(all_decimals) self.play(*it.chain( list(map(Write, start_labels)), [GrowArrow(a[0]) for a in start_arrows] )) self.wait() self.play( ReplacementTransform(start_labels, all_labels), ReplacementTransform(start_arrows, all_arrows), ) self.play(LaggedStartMap( ShowCreationThenDestruction, VGroup(*all_subscript_rects.family_members_with_points()), lag_ratio = 0.7 )) self.wait() self.set_variables_as_attrs( L_neurons, Lm1_neurons, all_arrows, all_labels, all_decimals, all_subscript_rects, ) def only_show_abstract_a_labels(self): arrows_to_fade = VGroup() labels_to_fade = VGroup() labels_to_change = VGroup() self.chosen_neurons = VGroup() rects = VGroup() for x, layer in enumerate(self.network_mob.layers[-2:]): for y, neuron in enumerate(layer.neurons): if (x == 0 and y == 1) or (x == 1 and y == 0): tex = "k" if x == 0 else "j" neuron.label.generate_target() self.replace_subscript(neuron.label.target, tex) self.chosen_neurons.add(neuron) labels_to_change.add(neuron.label) rects.add(SurroundingRectangle( neuron.label.target[-1], buff = 0.5*SMALL_BUFF )) else: labels_to_fade.add(neuron.label) arrows_to_fade.add(neuron.arrow) self.play( LaggedStartMap(FadeOut, labels_to_fade), LaggedStartMap(FadeOut, arrows_to_fade), run_time = 1 ) for neuron, rect in zip(self.chosen_neurons, rects): self.play( MoveToTarget(neuron.label), ShowCreation(rect) ) self.play(FadeOut(rect)) self.wait() self.wait() def add_desired_output(self): layer = self.network_mob.layers[-1] desired_output = layer.deepcopy() desired_output.shift(3*RIGHT) desired_output_decimals = VGroup() arrows = VGroup() labels = VGroup() for i, neuron in enumerate(desired_output.neurons): neuron.set_fill(opacity = i) decimal = self.get_neuron_activation_decimal(neuron) neuron.decimal = decimal neuron.arrow = Arrow(ORIGIN, LEFT, color = WHITE) neuron.arrow.next_to(neuron, RIGHT) neuron.label = OldTex("y_%d"%i) neuron.label.next_to(neuron.arrow, RIGHT) neuron.label.set_color(self.desired_output_color) desired_output_decimals.add(decimal) arrows.add(neuron.arrow) labels.add(neuron.label) rect = SurroundingRectangle(desired_output, buff = 0.5*SMALL_BUFF) words = OldTexText("Desired output") words.next_to(rect, DOWN) VGroup(words, rect).set_color(self.desired_output_color) self.play( FadeIn(rect), FadeIn(words), ReplacementTransform(layer.copy(), desired_output), FadeIn(labels), *[ ReplacementTransform(n1.decimal.copy(), n2.decimal) for n1, n2 in zip(layer.neurons, desired_output.neurons) ] + list(map(GrowArrow, arrows)) ) self.wait() self.set_variables_as_attrs( desired_output, desired_output_decimals, desired_output_rect = rect, desired_output_words = words, ) def show_cost(self): aj = self.chosen_neurons[1].label.copy() yj = self.desired_output.neurons[0].label.copy() cost_equation = OldTex( "C_0", "=", "\\sum_{j = 0}^{n_L - 1}", "(", "a^{(L)}_j", "-", "y_j", ")", "^2" ) cost_equation.to_corner(UP+RIGHT) cost_equation[0].set_color(self.cost_color) aj.target = cost_equation.get_part_by_tex("a^{(L)}_j") yj.target = cost_equation.get_part_by_tex("y_j") yj.target.set_color(self.desired_output_color) to_fade_in = VGroup(*[m for m in cost_equation if m not in [aj.target, yj.target]]) sum_part = cost_equation.get_part_by_tex("sum") self.play(*[ ReplacementTransform(mob, mob.target) for mob in (aj, yj) ]) self.play(LaggedStartMap(FadeIn, to_fade_in)) self.wait(2) self.play(LaggedStartMap( Indicate, sum_part, rate_func = wiggle, )) self.wait() for mob in aj.target, yj.target, cost_equation[-1]: self.play(Indicate(mob)) self.wait() self.set_variables_as_attrs(cost_equation) def show_example_weight(self): edges = self.network_mob.edge_groups[-1] edge = self.chosen_neurons[1].edges_in[1] faded_edges = VGroup(*[e for e in edges if e is not edge]) faded_edges.save_state() for faded_edge in faded_edges: faded_edge.save_state() w_label = OldTex("w^{(L)}_{jk}") subscripts = VGroup(*w_label[-2:]) w_label.scale(1.2) w_label.add_background_rectangle() w_label.next_to(ORIGIN, UP, SMALL_BUFF) w_label.rotate(edge.get_angle()) w_label.shift(edge.get_center()) w_label.set_color(BLUE) edges.save_state() edges.generate_target() for e in edges.target: e.rotate(-e.get_angle()) edges.target.arrange(DOWN) edges.target.move_to(edges) edges.target.to_edge(UP) self.play(MoveToTarget(edges)) self.play(LaggedStartMap( ApplyFunction, edges, lambda e : ( lambda m : m.rotate(np.pi/12).set_color(YELLOW), e ), rate_func = wiggle )) self.play(edges.restore) self.play(faded_edges.fade, 0.9) for neuron in self.chosen_neurons: self.play(Indicate(neuron), Animation(neuron.decimal)) self.play(Write(w_label)) self.wait() self.play(Indicate(subscripts)) for x in range(2): self.play(Swap(*subscripts)) self.wait() self.set_variables_as_attrs(faded_edges, w_label) def show_values_between_weight_and_cost(self): z_formula = OldTex( "z^{(L)}_j", "=", "w^{(L)}_{j0}", "a^{(L-1)}_0", "+", "w^{(L)}_{j1}", "a^{(L-1)}_1", "+", "w^{(L)}_{j2}", "a^{(L-1)}_2", "+", "b^{(L)}_j" ) compact_z_formula = OldTex( "z^{(L)}_j", "=", "\\cdots", "", "+" "w^{(L)}_{jk}", "a^{(L-1)}_k", "+", "\\cdots", "", "", "", ) for expression in z_formula, compact_z_formula: expression.to_corner(UP+RIGHT) expression.set_color_by_tex_to_color_map({ "z^" : self.z_color, "w^" : self.w_label.get_color(), "b^" : MAROON_B, }) w_part = z_formula.get_parts_by_tex("w^")[1] aLm1_part = z_formula.get_parts_by_tex("a^{(L-1)}")[1] a_formula = OldTex( "a^{(L)}_j", "=", "\\sigma(", "z^{(L)}_j", ")" ) a_formula.set_color_by_tex("z^", self.z_color) a_formula.next_to(z_formula, DOWN, MED_LARGE_BUFF) a_formula.align_to(self.cost_equation, LEFT) aL_part = a_formula[0] to_fade = VGroup( self.desired_output, self.desired_output_decimals, self.desired_output_rect, self.desired_output_words, *[ VGroup(n.arrow, n.label) for n in self.desired_output.neurons ] ) self.play( FadeOut(to_fade), self.cost_equation.next_to, a_formula, DOWN, MED_LARGE_BUFF, self.cost_equation.to_edge, RIGHT, ReplacementTransform(self.w_label[1].copy(), w_part), ReplacementTransform( self.chosen_neurons[0].label.copy(), aLm1_part ), ) self.play(Write(VGroup(*[m for m in z_formula if m not in [w_part, aLm1_part]]))) self.wait() self.play(ReplacementTransform( self.chosen_neurons[1].label.copy(), aL_part )) self.play( Write(VGroup(*a_formula[1:3] + [a_formula[-1]])), ReplacementTransform( z_formula[0].copy(), a_formula.get_part_by_tex("z^") ) ) self.wait() self.set_variables_as_attrs(z_formula, compact_z_formula, a_formula) def show_weight_chain_rule(self): chain_rule = self.get_chain_rule( "{\\partial C_0", "\\over", "\\partial w^{(L)}_{jk}}", "=", "{\\partial z^{(L)}_j", "\\over", "\\partial w^{(L)}_{jk}}", "{\\partial a^{(L)}_j", "\\over", "\\partial z^{(L)}_j}", "{\\partial C_0", "\\over", "\\partial a^{(L)}_j}", ) terms = VGroup(*[ VGroup(*chain_rule[i:i+3]) for i in range(4,len(chain_rule), 3) ]) rects = VGroup(*[ SurroundingRectangle(term, buff = 0.5*SMALL_BUFF) for term in terms ]) rects.set_color_by_gradient(GREEN, WHITE, RED) self.play(Transform( self.z_formula, self.compact_z_formula )) self.play(Write(chain_rule)) self.wait() self.play(LaggedStartMap( ShowCreationThenDestruction, rects, lag_ratio = 0.7, run_time = 3 )) self.wait() self.set_variables_as_attrs(chain_rule) def show_derivative_wrt_prev_activation(self): chain_rule = self.get_chain_rule( "{\\partial C_0", "\\over", "\\partial a^{(L-1)}_k}", "=", "\\sum_{j=0}^{n_L - 1}", "{\\partial z^{(L)}_j", "\\over", "\\partial a^{(L-1)}_k}", "{\\partial a^{(L)}_j", "\\over", "\\partial z^{(L)}_j}", "{\\partial C_0", "\\over", "\\partial a^{(L)}_j}", ) formulas = VGroup(self.z_formula, self.a_formula, self.cost_equation) n = chain_rule.index_of_part_by_tex("sum") self.play(ReplacementTransform( self.chain_rule, VGroup(*chain_rule[:n] + chain_rule[n+1:]) )) self.play(Write(chain_rule[n], run_time = 1)) self.wait() self.set_variables_as_attrs(chain_rule) def show_multiple_paths_from_prev_layer_neuron(self): neurons = self.network_mob.layers[-1].neurons labels, arrows, decimals = [ VGroup(*[getattr(n, attr) for n in neurons]) for attr in ("label", "arrow", "decimal") ] edges = VGroup(*[n.edges_in[1] for n in neurons]) labels[0].generate_target() self.replace_subscript(labels[0].target, "0") paths = [ VGroup( self.chosen_neurons[0].label, self.chosen_neurons[0].arrow, self.chosen_neurons[0], self.chosen_neurons[0].decimal, edges[i], neurons[i], decimals[i], arrows[i], labels[i], ) for i in range(2) ] path_lines = VGroup() for path in paths: points = [path[0].get_center()] for mob in path[1:]: if isinstance(mob, DecimalNumber): continue points.append(mob.get_center()) path_line = VMobject() path_line.set_points_as_corners(points) path_lines.add(path_line) path_lines.set_color(YELLOW) chain_rule = self.chain_rule n = chain_rule.index_of_part_by_tex("sum") brace = Brace(VGroup(*chain_rule[n:]), DOWN, buff = SMALL_BUFF) words = brace.get_text("Sum over layer L", buff = SMALL_BUFF) cost_aL = self.cost_equation.get_part_by_tex("a^{(L)}") self.play( MoveToTarget(labels[0]), FadeIn(labels[1]), GrowArrow(arrows[1]), edges[1].restore, FadeOut(self.w_label), ) for x in range(5): anims = [ ShowCreationThenDestruction( path_line, run_time = 1.5, time_width = 0.5, ) for path_line in path_lines ] if x == 2: anims += [ FadeIn(words), GrowFromCenter(brace) ] self.play(*anims) self.wait() for path, path_line in zip(paths, path_lines): label = path[-1] self.play( LaggedStartMap( Indicate, path, rate_func = wiggle, run_time = 1, ), ShowCreation(path_line), Animation(label) ) self.wait() group = VGroup(label, cost_aL) self.play( group.shift, MED_SMALL_BUFF*UP, rate_func = wiggle ) self.play(FadeOut(path_line)) self.wait() def show_previous_layer(self): mid_neurons = self.network_mob.layers[1].neurons layer = self.network_mob.layers[0] edges = self.network_mob.edge_groups[0] faded_edges = self.faded_edges to_fade = VGroup( self.chosen_neurons[0].label, self.chosen_neurons[0].arrow, ) for neuron in layer.neurons: neuron.add(self.get_neuron_activation_decimal(neuron)) all_edges_out = VGroup(*[ VGroup(*[n.edges_in[i] for n in mid_neurons]).copy() for i in range(len(layer.neurons)) ]) all_edges_out.set_stroke(YELLOW, 3) deriv = VGroup(*self.chain_rule[:3]) deriv_rect = SurroundingRectangle(deriv) mid_neuron_outlines = mid_neurons.copy() mid_neuron_outlines.set_fill(opacity = 0) mid_neuron_outlines.set_stroke(YELLOW, 5) def get_neurons_decimal_anims(neuron): return [ ChangingDecimal( neuron.decimal, lambda a : neuron.get_fill_opacity(), ), UpdateFromFunc( neuron.decimal, lambda m : m.set_fill( WHITE if neuron.get_fill_opacity() < 0.8 else BLACK ) ) ] self.play(ShowCreation(deriv_rect)) self.play(LaggedStartMap( ShowCreationThenDestruction, mid_neuron_outlines )) self.play(*it.chain(*[ [ ApplyMethod(n.set_fill, None, random.random()), ] + get_neurons_decimal_anims(n) for n in mid_neurons ]), run_time = 4, rate_func = there_and_back) self.play(faded_edges.restore) self.play( LaggedStartMap( GrowFromCenter, layer.neurons, run_time = 1 ), LaggedStartMap(ShowCreation, edges), FadeOut(to_fade) ) for x in range(3): for edges_out in all_edges_out: self.play(ShowCreationThenDestruction(edges_out)) self.wait() #### def replace_subscript(self, label, tex): subscript = label[-1] new_subscript = OldTex(tex)[0] new_subscript.replace(subscript, dim_to_match = 1) label.remove(subscript) label.add(new_subscript) return label def get_chain_rule(self, *tex): chain_rule = OldTex(*tex) chain_rule.scale(0.8) chain_rule.to_corner(UP+LEFT) chain_rule.set_color_by_tex_to_color_map({ "C_0" : self.cost_color, "z^" : self.z_color, "w^" : self.w_label.get_color() }) return chain_rule class ThatsPrettyMuchIt(TeacherStudentsScene): def construct(self): self.teacher_says( "That's pretty \\\\ much it!", target_mode = "hooray", run_time = 1, ) self.wait(2) class PatYourselfOnTheBack(TeacherStudentsScene): def construct(self): self.teacher_says( "Pat yourself on \\\\ the back!", target_mode = "hooray" ) self.play_student_changes(*["hooray"]*3) self.wait(3) class ThatsALotToThinkAbout(TeacherStudentsScene): def construct(self): self.teacher_says( "That's a lot to \\\\ think about!", target_mode = "surprised" ) self.play_student_changes(*["thinking"]*3) self.wait(4) class LayersOfComplexity(Scene): def construct(self): chain_rule_equations = self.get_chain_rule_equations() chain_rule_equations.to_corner(UP+RIGHT) brace = Brace(chain_rule_equations, LEFT) arrow = Vector(LEFT, color = RED) arrow.next_to(brace, LEFT) gradient = OldTex("\\nabla C") gradient.scale(2) gradient.set_color(RED) gradient.next_to(arrow, LEFT) self.play(LaggedStartMap(FadeIn, chain_rule_equations)) self.play(GrowFromCenter(brace)) self.play(GrowArrow(arrow)) self.play(Write(gradient)) self.wait() def get_chain_rule_equations(self): w_deriv = OldTex( "{\\partial C", "\\over", "\\partial w^{(l)}_{jk}}", "=", "a^{(l-1)}_k", "\\sigma'(z^{(l)}_j)", "{\\partial C", "\\over", "\\partial a^{(l)}_j}", ) lil_rect = SurroundingRectangle( VGroup(*w_deriv[-3:]), buff = 0.5*SMALL_BUFF ) a_deriv = OldTex( "\\sum_{j = 0}^{n_{l+1} - 1}", "w^{(l+1)}_{jk}", "\\sigma'(z^{(l+1)}_j)", "{\\partial C", "\\over", "\\partial a^{(l+1)}_j}", ) or_word = OldTexText("or") last_a_deriv = OldTex("2(a^{(L)}_j - y_j)") a_deriv.next_to(w_deriv, DOWN, LARGE_BUFF) or_word.next_to(a_deriv, DOWN) last_a_deriv.next_to(or_word, DOWN, MED_LARGE_BUFF) big_rect = SurroundingRectangle(VGroup(a_deriv, last_a_deriv)) arrow = Arrow( lil_rect.get_corner(DOWN+LEFT), big_rect.get_top(), ) result = VGroup( w_deriv, lil_rect, arrow, big_rect, a_deriv, or_word, last_a_deriv ) for expression in w_deriv, a_deriv, last_a_deriv: expression.set_color_by_tex_to_color_map({ "C" : RED, "z^" : GREEN, "w^" : BLUE, "b^" : MAROON_B, }) return result class SponsorFrame(PiCreatureScene): def construct(self): morty = self.pi_creature screen = ScreenRectangle(height = 5) screen.to_corner(UP+LEFT) url = OldTexText("http://3b1b.co/crowdflower") url.move_to(screen, UP+LEFT) screen.shift(LARGE_BUFF*DOWN) arrow = Arrow(LEFT, RIGHT, color = WHITE) arrow.next_to(url, RIGHT) t_shirt_words = OldTexText("Free T-Shirt") t_shirt_words.scale(1.5) t_shirt_words.set_color(YELLOW) t_shirt_words.next_to(morty, UP, aligned_edge = RIGHT) human_in_the_loop = OldTexText("Human-in-the-loop approach") human_in_the_loop.next_to(screen, DOWN) self.play( morty.change, "hooray", t_shirt_words, Write(t_shirt_words, run_time = 2) ) self.wait() self.play( morty.change, "raise_right_hand", screen, ShowCreation(screen) ) self.play( t_shirt_words.scale, 1./1.5, t_shirt_words.next_to, arrow, RIGHT ) self.play(Write(url)) self.play(GrowArrow(arrow)) self.wait(2) self.play(morty.change, "thinking", url) self.wait(3) self.play(Write(human_in_the_loop)) self.play(morty.change, "happy", url) self.play(morty.look_at, screen) self.wait(7) t_shirt_words_outline = t_shirt_words.copy() t_shirt_words_outline.set_fill(opacity = 0) t_shirt_words_outline.set_stroke(GREEN, 3) self.play( morty.change, "hooray", t_shirt_words, LaggedStartMap(ShowCreation, t_shirt_words_outline), ) self.play(FadeOut(t_shirt_words_outline)) self.play(LaggedStartMap( Indicate, url, rate_func = wiggle, color = PINK, run_time = 3 )) self.wait(3) class NN3PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Randall Hunt", "Burt Humburg", "CrypticSwarm", "Juan Benet", "David Kedmey", "Michael Hardwicke", "Nathan Weeks", "Marcus Schiebold", "Ali Yahya", "William", "Mayank M. Mehrotra", "Lukas Biewald", "Samantha D. Suplee", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Markus Persson", "Yoni Nazarathy", "Ed Kellett", "Joseph John Cox", "Luc Ritchie", "1stViewMaths", "Jacob Magnuson", "Mark Govea", "Dagan Harrington", "Clark Gaebel", "Eric Chow", "Mathias Jansson", "Robert Teed", "Pedro Perez Sanchez", "David Clark", "Michael Gardner", "Harsev Singh", "Mads Elvheim", "Erik Sundell", "Xueqi Li", "Dr. David G. Stork", "Tianyu Ge", "Ted Suzman", "Linh Tran", "Andrew Busey", "John Haley", "Ankalagon", "Eric Lavault", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], "max_patron_group_size" : 25, "patron_scale_val" : 0.7, } class Thumbnail(PreviewLearning): CONFIG = { "layer_sizes" : [8, 6, 6, 4], "network_mob_config" : { "neuron_radius" : 0.3, "neuron_to_neuron_buff" : MED_SMALL_BUFF, "include_output_labels" : False, }, "stroke_width_exp" : 1, "max_stroke_width" : 5, "title" : "Backpropagation", "network_scale_val" : 0.8, } def construct(self): self.color_network_edges() network_mob = self.network_mob network_mob.scale( self.network_scale_val, about_point = network_mob.get_bottom() ) network_mob.activate_layers(np.random.random(self.layer_sizes[0])) for edge in it.chain(*network_mob.edge_groups): arrow = Arrow( edge.get_end(), edge.get_start(), buff = 0, tip_length = 0.1, color = edge.get_color() ) network_mob.add(arrow.tip) arrow = Vector( 3*LEFT, tip_length = 0.75, rectangular_stem_width = 0.2, color = BLUE, ) arrow.next_to(network_mob.edge_groups[1], UP, MED_LARGE_BUFF) network_mob.add(arrow) self.add(network_mob) title = OldTexText(self.title) title.scale(2) title.to_edge(UP) self.add(title) class SupplementThumbnail(Thumbnail): CONFIG = { "title" : "Backpropagation \\\\ calculus", "network_scale_val" : 0.7, } def construct(self): Thumbnail.construct(self) self.network_mob.to_edge(DOWN, buff = MED_SMALL_BUFF) for layer in self.network_mob.layers: for neuron in layer.neurons: partial = OldTex("\\partial") partial.move_to(neuron) self.remove(neuron) self.add(partial)
#!/usr/bin/env python # -*- coding: utf-8 -*- from manim_imports_ext import * class SimpleVelocityGraph(GraphScene): CONFIG = { # "frame_rate" : 4000, # "domino_thickness" : 7.5438, # "domino_spacing" : 8.701314282, "data_files" : [ "data07.txt", "data13.txt", # "data11.txt", ], "colors" : [WHITE, BLUE, YELLOW, GREEN, MAROON_B], "x_axis_label" : "$t$", "y_axis_label" : "$v$", "x_min" : 0, "x_max" : 1.8, "x_tick_frequency" : 0.1, "x_labeled_nums" : np.arange(0, 1.8, 0.2), "y_tick_frequency" : 100, "y_min" : 0, "y_max" : 1000, "y_labeled_nums" : list(range(0, 1000, 200)), "x_axis_width" : 12, "graph_origin" : 2.5*DOWN + 5*LEFT, "trailing_average_length" : 20, "include_domino_thickness" : False, } def construct(self): self.setup_axes() # self.save_all_images() for data_file, color in zip(self.data_files, self.colors): self.init_data(data_file) self.draw_dots(color) self.add_label_to_last_dot( "%s %s %.2f"%( data_file[4:6], "hard" if self.friction == "low" else "felt", self.domino_spacing, ), color ) self.draw_lines(color) def save_all_images(self): indices = list(range(1, 20)) for i1, i2 in it.combinations(indices, 2): to_remove = VGroup() for index in i1, i2: index_str = ("%.2f"%float(0.01*index))[-2:] data_file = "data%s.txt"%index_str self.init_data(data_file) color = WHITE if self.friction == "low" else BLUE self.draw_dots(color) self.add_label_to_last_dot( "%s %s %.2f"%( data_file[4:6], "hard" if self.friction == "low" else "felt", self.domino_spacing, ), color ) self.draw_lines(color) to_remove.add(self.dots, self.lines, self.label) self.save_image("dominos_%d_vs_%d"%(i1, i2)) self.remove(to_remove) def init_data(self, data_file): file_name = os.path.join( os.path.dirname(os.path.realpath(__file__)), "dominos", data_file ) file = open(file_name, "r") frames, notes = [], [] for line in file: line = line.replace(" ", ",") line = line.replace("\n", "") entries = [s for s in line.split(",") if s is not ""] if len(entries) == 0: continue if entries[0] == "framerate": frame_rate = float(entries[1]) elif entries[0] == "domino spacing": domino_spacing = float(entries[1]) elif entries[0] == "domino thickness": domino_thickness = float(entries[1]) elif entries[0] == "friction": self.friction = entries[1] else: try: frames.append(int(entries[0])) except: continue #How to treat? # frames.append(frames[-1] + (frames[-1] - frames[-2])) if len(entries) > 1: notes.append(entries[1]) else: notes.append("") frames = np.array(frames) self.times = (frames - frames[0])/float(frame_rate) delta_times = self.times[1:] - self.times[:-1] if self.include_domino_thickness: distance = domino_spacing+domino_thickness else: distance = domino_spacing self.velocities = distance/delta_times self.notes = notes n = self.trailing_average_length self.velocities = np.array([ np.mean(self.velocities[max(0, i-n):i]) for i in range(len(self.velocities)) ]) self.domino_spacing = domino_spacing self.domino_thickness = domino_thickness def draw_dots(self, color = WHITE): dots = VGroup() for time, v, note in zip(self.times, self.velocities, self.notes): dot = Dot(color = color) dot.scale(0.5) dot.move_to(self.coords_to_point(time, v)) self.add(dot) dots.add(dot) if note == "twist": dot.set_color(RED) self.dots = dots def add_label_to_last_dot(self, label, color = WHITE): dot = self.dots[-1] label = OldTexText(label) label.scale(0.75) label.next_to(dot, UP, buff = MED_SMALL_BUFF) label.set_color(color) label.shift_onto_screen() self.label = label self.add(label) def draw_lines(self, color = WHITE, stroke_width = 2): lines = VGroup() for d1, d2 in zip(self.dots, self.dots[1:]): line = Line(d1.get_center(), d2.get_center()) lines.add(line) lines.set_stroke(color, stroke_width) self.add(lines, self.dots) self.lines = lines ALL_VELOCITIES = { 10 : [ 0.350308642, 0.3861880046, 0.8665243271, 0.9738947062, 0.8087560386, 1.067001275, 0.9059117965, 1.113855622, 0.9088626493, 1.504155436, 1.347926731, 1.274067732, 1.242854491, 1.118319973, 1.177303094, 1.202676006, 0.9965029762, 1.558775605, 1.472405453, 1.357765612, 1.200089606, 1.285810292, 1.138860544, 1.322373618, 1.51230804, 1.148233882, 1.276983219, 1.150601375, 1.492090018, 1.210502531, 1.221097739, 1.141189502, 1.364405053, 1.608189241, 1.223775585, 1.174824561, 1.069045338, 1.468530702, 1.733048654, 1.328670635, 1.118319973, 1.143528005, 1.010945048, 1.430876068, 1.395104167, 1.018324209, 1.405646516, 1.120565596, 1.24562872, 1.65590999, 1.276983219, 1.282854406, 1.338229416, 1.240092593, 0.9982856291, 1.811823593, 1.328670635, 1.167451185, 1.27991208, 1.221097739, 1.022054335, 1.160169785, 1.805960086, 0.9965029762, 1.449458874, 1.603568008, 1.234605457, 1.210502531, 1.192396724, 1.020185862, 1.496090259, 1.322373618, 1.291763117, 1.210502531, 0.9807410662, 1.341446314, 1.391625104, 1.480216622, 1.148233882, 1.125084005, 1.670783433, 1.118319973, 1.174824561, 1.395104167, 1.167451185, 1.182291667, 1.696175279, 1.306889149, 1.430876068, 1.048950501, 1.823665577, 1.24562872, ], 13 : [ 0.2480920273, 0.3532654568, 0.549163523, 0.5979017857, 0.6643353175, 0.8495940117, 1.037573598, 0.897413562, 1.410977665, 0.9180833562, 1.303328143, 0.9324004456, 2.026785714, 0.9721980256, 1.339835934, 1.002770291, 2.3797086, 1.235972684, 1.508900406, 1.239174685, 1.374486864, 1.181040564, 1.144309638, 1.195803571, 1.265400605, 1.223328462, 1.678320802, 1.198800573, 0.7958759211, 1.573425752, 1.046655205, 2.009753902, 1.42782516, 1.289276088, 1.347384306, 1.299786491, 1.06530385, 1.339835934, 1.242393321, 1.053571429, 1.317689886, 1.626943635, 1.112375415, 1.362739113, 0.9110884354, 1.578618576, 1.853959025, 1.504155436, 1.158163265, 1.262061817, 1.060579664, 1.122820255, 1.594404762, 1.27552381, 1.382431874, 1.109794498, 1.303328143, 1.160974341, 1.296264034, 1.092058056, 1.077300515, 1.462756662, 1.317689886, 1.390469269, 1.099589491, 1.649384236, 1.467243646, 1.402702137, 1.092058056, 1.201812635, 1.258740602, 1.321329913, 1.272131459, 1.175236925, 1.181040564, 1.296264034, 1.24562872, 1.358867695, 1.332371667, 1.296264034, 1.217102872, 1.169490045, 1.114968365, 1.528183478, 1.374486864, 1.223328462, 1.324990107, 1.268757105, 1.169490045, 1.578618576, ], 14 : [ 0.4905860806, 0.6236263736, 0.71391258, 0.8436004031, 1.048950501, 0.9585599771, 1.138860544, 1.210940325, 1.27552381, 1.282363079, 1.166637631, 1.242393321, 1.163799096, 1.166637631, 1.42357568, 1.382431874, 1.278934301, 1.390469269, 1.181040564, 1.107225529, 1.08462909, 1.160974341, 1.374486864, 1.382431874, 1.355018211, 1.25543682, 1.192821518, 0.9360497624, 1.449458874, 1.370548506, 1.485470275, 1.471758242, 1.149811126, 1.217102872, 1.152581756, 1.402702137, 1.155365769, 1.141578588, 1.248881015, 1.074879615, 1.453864525, 1.303328143, 1.248881015, 1.169490045, 1.214013778, 1.220207726, 1.310469667, 1.42357568, 1.163799096, 1.220207726, 1.141578588, 1.207882395, 1.104668426, 1.328670635, 1.25543682, 1.239174685, 1.169490045, 1.149811126, 1.000672445, 1.144309638, 1.232787187, 1.268757105, 1.306889149, 1.538011024, 1.355018211, 1.347384306, 1.223328462, 1.149811126, 1.158163265, 1.24562872, 1.485470275, 1.339835934, 1.314069859, 1.235972684, 1.265400605, 1.181040564, 1.638087084, 1.568266979, 1.299786491, 1.278934301, 1.336093376, 1.089570452, 1.004876951, 1.089570452, 1.282363079, 1.449458874, 1.370548506, 1.265400605, 1.143215651, ], 15 : [ 1.087094156, 1.223328462, 1.563141923, 1.394523115, 1.268757105, 1.513675407, 1.436400686, 1.094557045, 0.9761661808, 1.072469571, 1.178131597, 1.366632653, 1.258740602, 1.25543682, 1.285810292, 1.235972684, 1.347384306, 1.239174685, 1.195803571, 1.186901808, 1.141578588, 1.152581756, 1.136155412, 1.102123107, 1.242393321, 1.347384306, 1.278934301, 1.366632653, 1.351190476, 0.9882674144, 1.1898543, 1.351190476, 1.169490045, 1.292760618, 1.638087084, 1.436400686, 1.328670635, 1.242393321, 1.355018211, 1.303328143, 1.186901808, 1.112375415, 1.432100086, 1.1898543, 1.324990107, 1.074879615, 1.214013778, 1.20483987, 1.158163265, 1.112375415, 1.220207726, 1.402702137, 1.268757105, 1.282363079, 1.289276088, 1.292760618, 1.183963932, 1.252150337, 1.42782516, 1.292760618, 1.026440834, 1.268757105, 1.268757105, 1.285810292, 1.347384306, 1.272131459, 1.220207726, 1.296264034, 1.25543682, 1.494754464, 1.347384306, 1.214013778, 1.169490045, 1.147053786, 1.082175178, 1.109794498, 1.382431874, 1.24562872, 1.201812635, 1.328670635, 1.122820255, 1.220207726, 1.192821518, 1.563141923, 1.41935142, 1.336093376, 1.406827731, 1.258740602, 1.186901808, 1.232787187, 1.107225529, ], } # Felt: 8,9,10,11,12,13 # Hardwood 1-7, 14,15 class ContrastTwoGraphs(SimpleVelocityGraph): CONFIG = { "velocities1_index" : 13, "velocities2_index" : 14, "x_min" : -1, "x_max" : 10, "y_min" : -0.25, "y_max" : 2, "x_axis_label" : "", "y_axis_label" : "", "x_labeled_nums" : [], "y_labeled_nums" : [], "y_tick_frequency" : 0.25, "x_tick_frequency" : 12, "moving_average_n" : 20, } def construct(self): self.setup_axes() velocities1 = ALL_VELOCITIES[self.velocities1_index] velocities2 = ALL_VELOCITIES[self.velocities2_index] self.n_data_points = len(velocities1) graph1 = self.get_velocity_graph(velocities1) graph2 = self.get_velocity_graph(velocities2) smoothed_graph1 = self.get_smoothed_velocity_graph(velocities1) smoothed_graph2 = self.get_smoothed_velocity_graph(velocities2) for graph in graph1, smoothed_graph1: self.color_graph(graph) for graph in graph2, smoothed_graph2: self.color_graph(graph, BLUE, RED) for graph in graph1, graph2, smoothed_graph1, smoothed_graph2: graph.axes = self.axes.deepcopy() graph.add_to_back(graph.axes) lower_left = self.axes.get_corner(DOWN+LEFT) self.remove(self.axes) felt = OldTexText("Felt") hardwood = OldTexText("Hardwood") hardwood.set_color(RED) words = VGroup(felt, hardwood) self.force_skipping() #Show jaggediness graph1.scale(0.5).to_edge(UP) graph2.scale(0.5).to_edge(DOWN) felt.next_to(graph1, LEFT, buff = 0.75) hardwood.next_to(graph2, LEFT, buff = 0.75) self.play( ShowCreation(graph1, run_time = 3, rate_func=linear), Write(felt) ) self.play( ShowCreation(graph2, run_time = 4, rate_func=linear), Write(hardwood) ) self.wait() for g, sg in (graph1, smoothed_graph1), (graph2, smoothed_graph2): sg_copy = sg.deepcopy() sg_copy.scale(0.5) sg_copy.shift(g.get_center()) mover = VGroup(*it.chain(*list(zip(g.dots, g.lines)))) target = VGroup(*it.chain(*list(zip(sg_copy.dots, sg_copy.lines)))) for m, t in zip(mover, target): m.target = t self.play(LaggedStartMap( MoveToTarget, mover, rate_func = lambda t : 0.3*wiggle(t), run_time = 3, lag_ratio = 0.2, )) twists = OldTexText("Twists?") variable_distances = OldTexText("Variable distances") for word in twists, variable_distances: word.to_corner(UP+RIGHT) self.play(Write(twists)) self.wait() self.play(ReplacementTransform(twists, variable_distances)) self.wait(3) self.play(FadeOut(variable_distances)) self.revert_to_original_skipping_status() self.play( graph1.scale, 2, graph1.move_to, lower_left, DOWN+LEFT, graph2.scale, 2, graph2.move_to, lower_left, DOWN+LEFT, FadeOut(words) ) self.wait() return #Show moving averages self.play(FadeOut(graph2)) dots = graph1.dots dot1, dot2 = dots[21], dots[41] rect = Rectangle( width = dot2.get_center()[0] - dot1.get_center()[0], height = FRAME_Y_RADIUS - self.x_axis.get_center()[1], stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.5 ) rect.move_to(dot2.get_center(), RIGHT) rect.to_edge(UP, buff = 0) pre_rect = rect.copy() pre_rect.stretch_to_fit_width(0) pre_rect.move_to(rect, RIGHT) arrow = Vector(DOWN) arrow.next_to(dot2, UP, SMALL_BUFF) self.play(GrowArrow(arrow)) self.play( dot2.shift, MED_SMALL_BUFF*UP, dot2.set_color, PINK, rate_func = wiggle ) self.wait() self.play( FadeOut(arrow), ReplacementTransform(pre_rect, rect), ) self.wait() self.play( Transform(graph1, smoothed_graph1, run_time = 2), Animation(rect) ) self.play(FadeOut(rect)) self.wait() self.play(FadeIn(graph2)) self.play(Transform(graph2, smoothed_graph2)) felt.next_to(dot2, UP, MED_LARGE_BUFF) hardwood.next_to(felt, DOWN, LARGE_BUFF) self.play( LaggedStartMap(FadeIn, felt), LaggedStartMap(FadeIn, hardwood), run_time = 1 ) self.wait() #Compare regions dot_group1 = VGroup( *graph1.dots[35:75] + graph2.dots[35:75] ) dot_group2 = VGroup( *graph1.dots[75:] + graph2.dots[75:] ) dot_group3 = VGroup( *graph1.dots[35:] + graph2.dots[35:] ) rect1 = SurroundingRectangle(dot_group1) rect2 = SurroundingRectangle(dot_group2) rect3 = SurroundingRectangle(dot_group3) self.play(ShowCreation(rect1)) for x in range(2): self.play(LaggedStartMap( ApplyMethod, dot_group1, lambda m : (m.scale, 0.5), rate_func = wiggle, lag_ratio = 0.05, run_time = 3, )) self.wait() self.play(ReplacementTransform(rect1, rect2)) for x in range(2): self.play(LaggedStartMap( ApplyMethod, dot_group2, lambda m : (m.scale, 0.5), rate_func = wiggle, lag_ratio = 0.05, run_time = 3, )) self.wait() self.play(ReplacementTransform(rect1, rect3)) for x in range(2): self.play(LaggedStartMap( ApplyMethod, dot_group3, lambda m : (m.scale, 0.5), rate_func = wiggle, lag_ratio = 0.05, run_time = 3, )) self.wait() ### def color_graph(self, graph, color1 = BLUE, color2 = WHITE, n_starts = 20): graph.set_color(color2) VGroup(*graph.dots[:11] + graph.lines[:10]).set_color(color1) def get_smoothed_velocity_graph(self, velocities): n = self.moving_average_n smoothed_vs = np.array([ np.mean(velocities[max(0, i-n):i]) for i in range(len(velocities)) ]) return self.get_velocity_graph(smoothed_vs) def get_velocity_graph(self, velocities): n = len(velocities) dots = VGroup(self.get_dot(1, velocities[0])) lines = VGroup() for x in range(1, n): dots.add(self.get_dot(x+1, velocities[x])) lines.add(Line( dots[-2].get_center(), dots[-1].get_center(), )) graph = VGroup(dots, lines) graph.dots = dots graph.lines = lines return graph def get_dot(self, x, y): dot = Dot(radius = 0.05) dot.move_to(self.coords_to_point( x * float(self.x_max) / self.n_data_points, y )) return dot class ShowAllSteadyStateVelocities(SimpleVelocityGraph): CONFIG = { "x_axis_label" : "\\text{Domino spacing}", "x_min" : 0, "x_max" : 40, "x_axis_width" : 9, "x_tick_frequency" : 5, "x_labeled_nums" : list(range(0, 50, 10)), "y_min" : 0, "y_max" : 400, "y_labeled_nums" : [], # "y_labeled_nums" : range(200, 1400, 200), } def construct(self): self.setup_axes() for index in range(1, 20): index_str = ("%.2f"%float(0.01*index))[-2:] data_file = "data%s.txt"%index_str self.init_data(data_file) color = WHITE if self.friction == "low" else BLUE label = OldTexText( index_str, color = color ) label.scale(0.5) label.set_color(color) dot = Dot(color = color) dot.scale(0.5) dot.move_to(self.coords_to_point( self.domino_spacing, self.velocities[-1] - 400 )) label.next_to( dot, random.choice([LEFT, RIGHT]), SMALL_BUFF ) self.add(dot) self.add(label) print(index_str, self.velocities[-1], self.friction) class Test(Scene): def construct(self): shift_val = 1.5 domino1 = Rectangle( width = 0.5, height = 3, stroke_width = 0, fill_color = GREEN, fill_opacity = 1 ) domino1.shift(LEFT) domino2 = domino1.copy() domino2.set_fill(BLUE_E) domino2.shift(shift_val*RIGHT) spacing = shift_val - domino2.get_width() dominos = VGroup(domino1, domino2) for domino in dominos: line = DashedLine(domino.get_left(), domino.get_right()) dot = Dot(domino.get_center()) domino.add(line, dot) arc1 = Arc( radius = domino1.get_height(), start_angle = np.pi/2, angle = -np.arcsin(spacing / domino1.get_height()) ) arc1.shift(domino1.get_corner(DOWN+RIGHT)) arc2 = Arc( radius = domino1.get_height()/2, start_angle = np.pi/2, angle = -np.arcsin(2*spacing/domino1.get_height()) ) arc2.shift(domino1.get_right()) arc2.set_color(BLUE) arcs = VGroup(arc1, arc2) for arc, vect in zip(arcs, [DOWN+RIGHT, RIGHT]): arc_copy = arc.copy() point = domino1.get_bounding_box_point(vect) arc_copy.add_line_to([point]) arc_copy.set_stroke(width = 0) arc_copy.set_fill( arc.get_stroke_color(), 0.2, ) self.add(arc_copy) domino1_ghost = domino1.copy() domino1_ghost.fade(0.8) self.add(domino1_ghost, dominos, arcs) self.play(Rotate( domino1, angle = arc1.angle, about_point = domino1.get_corner(DOWN+RIGHT), rate_func = there_and_back, run_time = 3, )) self.play(Rotate( domino1, angle = arc2.angle, about_point = domino1.get_right(), rate_func = there_and_back, run_time = 3, )) print(arc1.angle, arc2.angle)
from manim_imports_ext import * class CircleDivisionImage(Scene): CONFIG = { "random_seed": 0, "n": 0, } def construct(self): # tex = OldTex("e^{\\tau i}") # tex = OldTex("\\sin(2\\theta) \\over \\sin(\\theta)\\cos(\\theta)") # tex = OldTex("") # tex.set_height(FRAME_HEIGHT - 2) # if tex.get_width() > (FRAME_WIDTH - 2): # tex.set_width(FRAME_WIDTH - 2) # self.add(tex) n = self.n # angles = list(np.arange(0, TAU, TAU / 9)) # for i in range(len(angles)): # angles[i] += 1 * np.random.random() # random.shuffle(angles) # angles = angles[:n + 1] # angles.sort() # arcs = VGroup(*[ # Arc( # start_angle=a1, # angle=(a2 - a1), # ) # for a1, a2 in zip(angles, angles[1:]) # ]) # arcs.set_height(FRAME_HEIGHT - 1) # arcs.set_stroke(YELLOW, 3) circle = Circle() circle.set_stroke(YELLOW, 5) circle.set_height(FRAME_HEIGHT - 1) alphas = np.arange(0, 1, 1 / 10) alphas += 0.025 * np.random.random(10) # random.shuffle(alphas) alphas = alphas[:n + 1] points = [circle.point_from_proportion(3 * alpha % 1) for alpha in alphas] dots = VGroup(*[Dot(point) for point in points]) for dot in dots: dot.scale(1.5) dot.set_stroke(BLACK, 2, background=True) dots.set_color(BLUE) lines = VGroup(*[ Line(p1, p2) for p1, p2 in it.combinations(points, 2) ]) lines.set_stroke(WHITE, 3) self.add(circle, lines, dots) class PatronImage1(CircleDivisionImage): CONFIG = {"n": 0} class PatronImage2(CircleDivisionImage): CONFIG = {"n": 1} class PatronImage4(CircleDivisionImage): CONFIG = {"n": 2} class PatronImage8(CircleDivisionImage): CONFIG = {"n": 3} class PatronImage16(CircleDivisionImage): CONFIG = {"n": 4} class PatronImage31(CircleDivisionImage): CONFIG = {"n": 5} class PatronImage57(CircleDivisionImage): CONFIG = {"n": 6} class PatronImage99(CircleDivisionImage): CONFIG = {"n": 7} class PatronImage163(CircleDivisionImage): CONFIG = {"n": 8} class PatronImage256(CircleDivisionImage): CONFIG = {"n": 9}
from manim_imports_ext import * class TelestrationContribution(Scene): def construct(self): # Object creators def get_beer(): beer = SVGMobject(file_name="beer") beer.set_stroke(width=0) beer[0].set_fill(GREY_C) beer[1].set_fill(WHITE) beer[2].set_fill("#ff9900") return beer def get_muscle(): muscle = SVGMobject("muscle") muscle.set_fill(GREY_BROWN) muscle.set_stroke(WHITE, 2) return muscle def get_cat(): cat = SVGMobject("sitting_cat") cat.set_fill(GREY_C) cat.set_stroke(WHITE, 0) return cat def get_fat_cat(): cat = SVGMobject("fat_cat") cat.flip() cat.set_stroke(WHITE, 0) cat.set_fill(GREY_C, 1) return cat def get_person(): person = SVGMobject("person") person.set_fill(GREY_C, 1) person.set_stroke(WHITE, 1) return person # Beer makes you stronger beer = get_beer() arrow = OldTex("\\Rightarrow") arrow.set_width(1) muscle = get_muscle() imply_group = VGroup(beer, arrow, muscle) imply_group.arrange(RIGHT, buff=0.5) news = Rectangle(height=7, width=6) news.set_fill(GREY_E, 1) imply_group.set_width(news.get_width() - 1) imply_group.next_to(news.get_top(), DOWN) lines = VGroup(*[Line(LEFT, RIGHT) for x in range(12)]) lines.arrange(DOWN, buff=0.3) lines.set_width(news.get_width() - 1, stretch=True) lines.next_to(imply_group, DOWN, MED_LARGE_BUFF) lines[-1].stretch(0.5, 0, about_edge=LEFT) news.add(lines) q_marks = OldTex("???")[0] q_marks.space_out_submobjects(1.5) q_marks.replace(imply_group, dim_to_match=1) self.add(news) self.play(Write(q_marks)) self.wait() beer.save_state() beer.move_to(imply_group) self.play( FadeOut(q_marks, lag_ratio=0.1), FadeInFromDown(beer) ) self.play( Restore(beer), FadeIn(arrow, 0.2 * LEFT), DrawBorderThenFill(muscle) ) news.add(imply_group) self.wait(2) # Doubt randy = Randolph() randy.to_corner(DL) randy.change("confused") bangs = OldTex("!?!") bangs.scale(2) bangs.next_to(randy, UP) self.play( FadeIn(randy), news.scale, 0.8, {"about_edge": UP}, news.shift, RIGHT, ) self.play(Blink(randy)) self.play() self.play( randy.change, "angry", imply_group, Write(bangs, run_time=1) ) self.wait() self.play(Blink(randy)) self.wait() # Axes axes = Axes( x_min=0, x_max=15, y_min=0, y_max=10, ) axes.center() axes.set_height(FRAME_HEIGHT - 1) news.remove(imply_group) news.remove(lines) beer.generate_target() beer.target.set_height(0.75) beer.target.next_to(axes.x_axis.get_end(), UR, SMALL_BUFF) self.play( FadeOut(news), LaggedStartMap( FadeOutAndShift, VGroup(randy, bangs, arrow, muscle), lambda m: (m, DOWN) ), Uncreate(lines), MoveToTarget(beer, run_time=2), ShowCreation(axes), ) # Cat labels lil_cat = get_cat() lil_cat.set_height(0.5) lil_cat.next_to(axes.c2p(0, 0), LEFT, aligned_edge=DOWN) fat_cat = get_fat_cat() fat_cat.set_height(1.5) fat_cat.next_to(axes.c2p(0, 10), LEFT, aligned_edge=UP) self.play(FadeIn(lil_cat)) self.play(TransformFromCopy(lil_cat, fat_cat)) # Data data = VGroup() n_data_points = 50 for x in np.linspace(1, 15, n_data_points): x += np.random.random() - 0.5 y = (x * 10 / 15) + (np.random.random() - 0.5) * 5 if y < 0.5: y = 0.5 if y > 15: y -= 1 dot = Dot(axes.c2p(x, y)) dot.set_height(0.1) data.add(dot) data.set_color(BLUE) line = Line(axes.c2p(0, 0.5), axes.c2p(15, 10)) self.play(ShowIncreasingSubsets(data, run_time=4)) self.play(ShowCreation(line)) self.wait() graph = VGroup(axes, lil_cat, fat_cat, beer, data, line) graph.save_state() # Write article article = Rectangle(height=4, width=3) article.set_fill(GREY_E, 1) article.to_edge(RIGHT) arrow = Vector(RIGHT) arrow.set_color(YELLOW) arrow.next_to(article, LEFT) lines = VGroup(*[Line(LEFT, RIGHT) for x in range(20)]) lines.arrange(DOWN) for line in (lines[9], lines[19]): line.stretch(random.random() * 0.7, 0, about_edge=LEFT) lines[10:].shift(SMALL_BUFF * DOWN) lines.set_height(article.get_height() - 1, stretch=True) lines.set_width(article.get_width() - 0.5, stretch=True) lines.move_to(article) self.play( DrawBorderThenFill(article), ShowCreation(lines, run_time=2), ShowCreation(arrow), graph.set_height, 3, graph.next_to, arrow, LEFT, ) article.add(lines) self.wait() new_article = article.copy() new_arrow = arrow.copy() likes = VGroup(*[SVGMobject("like") for x in range(3)]) likes.set_stroke(width=0) likes.set_fill(BLUE) likes.arrange(RIGHT) likes.match_width(new_article) likes.next_to(new_article, UP) self.play(VGroup(graph, arrow, article).next_to, new_arrow, LEFT) self.play( ShowCreation(new_arrow), TransformFromCopy(article, new_article, path_arc=30 * DEGREES), ) self.play(LaggedStartMap(FadeInFrom, likes, lambda m: (m, DOWN))) self.wait() self.add(new_article, graph) new_article.generate_target() new_article.target.set_height(FRAME_HEIGHT, stretch=True) new_article.target.set_width(FRAME_WIDTH, stretch=True) new_article.target.center() new_article.target.set_stroke(width=0) self.play( Restore(graph, run_time=2), MoveToTarget(new_article, run_time=2), FadeOut(arrow), FadeOut(new_arrow), FadeOut(article), FadeOut(likes), ) self.wait() # Replace cats with people lil_person = get_person() lil_person.replace(lil_cat, dim_to_match=1) big_person = get_person() big_person.replace(fat_cat, dim_to_match=1) self.play( FadeOut(lil_cat, LEFT), FadeIn(lil_person, RIGHT), ) self.play( FadeOut(fat_cat, LEFT), FadeIn(big_person, RIGHT), ) self.wait() cross = Cross(big_person) self.play(ShowCreation(cross)) muscle = get_muscle() muscle.set_width(1.5) muscle.move_to(big_person) self.play( FadeIn(muscle, RIGHT), FadeOut(big_person, LEFT), FadeOut(cross, LEFT), ) self.wait() cross = Cross(new_article) cross.set_stroke(RED, 30) self.play(ShowCreation(cross)) self.wait()
from manim_imports_ext import * def boolian_linear_combo(bools): return reduce(op.xor, [b * n for n, b in enumerate(bools)], 0) def string_to_bools(message): # For easter eggs on the board as_int = int.from_bytes(message.encode(), 'big') bits = "{0:b}".format(as_int) bits = (len(message) * 8 - len(bits)) * '0' + bits return [bool(int(b)) for b in bits] def layer_mobject(mobject, nudge=1e-6): for i, sm in enumerate(mobject.family_members_with_points()): sm.shift(i * nudge * OUT) def int_to_bit_coords(n, min_dim=3): bits = "{0:b}".format(n) bits = (min_dim - len(bits)) * '0' + bits return np.array(list(map(int, bits))) def bit_coords_to_int(bits): return sum([(2**n) * b for n, b in enumerate(reversed(bits))]) def get_vertex_sphere(height=0.4, color=GREY, resolution=(21, 21)): sphere = Sphere(resolution=resolution) sphere.set_height(height) sphere.set_color(color) return sphere def get_bit_string(bit_coords): result = VGroup(*[Integer(int(b)) for b in bit_coords]) result.arrange(RIGHT, buff=SMALL_BUFF) result.set_stroke(BLACK, 4, background=True) return result class Chessboard(SGroup): CONFIG = { "shape": (8, 8), "height": 7, "depth": 0.25, "colors": [GREY_B, GREY_E], "gloss": 0.2, "square_resolution": (3, 3), "top_square_resolution": (5, 5), } def __init__(self, **kwargs): super().__init__(**kwargs) nr, nc = self.shape cube = Cube(square_resolution=self.square_resolution) # Replace top square with something slightly higher res top_square = Square3D(resolution=self.top_square_resolution) top_square.replace(cube[0]) cube.replace_submobject(0, top_square) self.add(*[cube.copy() for x in range(nc * nr)]) self.arrange_in_grid(nr, nc, buff=0) self.set_height(self.height) self.set_depth(self.depth, stretch=True) for i, j in it.product(range(nr), range(nc)): color = self.colors[(i + j) % 2] self[i * nc + j].set_color(color) self.center() self.set_gloss(self.gloss) class Coin(Group): CONFIG = { "disk_resolution": (4, 51), "height": 1, "depth": 0.1, "color": GOLD_D, "tails_color": RED, "include_labels": True, "numeric_labels": False, } def __init__(self, **kwargs): super().__init__(**kwargs) res = self.disk_resolution self.top = Disk3D(resolution=res, gloss=0.2) self.bottom = self.top.copy() self.top.shift(OUT) self.bottom.shift(IN) self.edge = Cylinder(height=2, resolution=(res[1], 2)) self.add(self.top, self.bottom, self.edge) self.rotate(90 * DEGREES, OUT) self.set_color(self.color) self.bottom.set_color(RED) if self.include_labels: chars = "10" if self.numeric_labels else "HT" labels = VGroup(*[TexText(c) for c in chars]) for label, vect in zip(labels, [OUT, IN]): label.shift(1.02 * vect) label.set_height(0.8) labels[1].rotate(PI, RIGHT) labels.apply_depth_test() labels.set_stroke(width=0) self.add(*labels) self.labels = labels self.set_height(self.height) self.set_depth(self.depth, stretch=True) def is_heads(self): return self.top.get_center()[2] > self.bottom.get_center()[2] def flip(self, axis=RIGHT): super().flip(axis) return self class CoinsOnBoard(Group): CONFIG = { "proportion_of_square_height": 0.7, "coin_config": {}, } def __init__(self, chessboard, **kwargs): super().__init__(**kwargs) prop = self.proportion_of_square_height for cube in chessboard: coin = Coin(**self.coin_config) coin.set_height(prop * cube.get_height()) coin.next_to(cube, OUT, buff=0) self.add(coin) def flip_at_random(self, p=0.5): bools = np.random.random(len(self)) < p self.flip_by_bools(bools) return self def flip_by_message(self, message): self.flip_by_bools(string_to_bools(message)) return self def flip_by_bools(self, bools): for coin, head in zip(self, bools): if coin.is_heads() ^ head: coin.flip() return self def get_bools(self): return [coin.is_heads() for coin in self] class Key(SVGMobject): CONFIG = { "file_name": "key", "fill_color": YELLOW_D, "fill_opacity": 1, "stroke_color": YELLOW_D, "stroke_width": 0, "gloss": 0.5, "depth_test": True, } def __init__(self, **kwargs): super().__init__(**kwargs) self.rotate(PI / 2, OUT) class FlipCoin(Animation): CONFIG = { "axis": RIGHT, "run_time": 1, "shift_dir": OUT, } def __init__(self, coin, **kwargs): super().__init__(coin, **kwargs) self.shift_vect = coin.get_height() * self.shift_dir / 2 def interpolate_mobject(self, alpha): coin = self.mobject for sm, start_sm in self.families: sm.match_points(start_sm) coin.rotate(alpha * PI, axis=self.axis) coin.shift(4 * alpha * (1 - alpha) * self.shift_vect) return coin # Scenes class IntroducePuzzle(Scene): CONFIG = { "camera_class": ThreeDCamera, } def construct(self): # Setup frame = self.camera.frame chessboard = Chessboard() chessboard.move_to(ORIGIN, OUT) grid = NumberPlane( x_range=(0, 8), y_range=(0, 8), faded_line_ratio=0 ) grid.match_height(chessboard) grid.next_to(chessboard, OUT, 1e-8) low_grid = grid.copy() low_grid.next_to(chessboard, IN, 1e-8) grid.add(low_grid) grid.set_stroke(GREY, width=2) grid.set_gloss(0.5) grid.prepare_for_nonlinear_transform(0) coins = CoinsOnBoard(chessboard) coins.set_gloss(0.2) coins_to_flip = Group() head_bools = string_to_bools('3b1b :)') for coin, heads in zip(coins, head_bools): if not heads: coins_to_flip.add(coin) coins_to_flip.shuffle() count_label = VGroup( Integer(0, edge_to_fix=RIGHT), OldTexText("Coins") ) count_label.arrange(RIGHT, aligned_edge=DOWN) count_label.to_corner(UL) count_label.fix_in_frame() # Draw board and coins frame.set_euler_angles(-25 * DEGREES, 70 * DEGREES, 0) self.play( FadeIn(chessboard), ShowCreationThenDestruction(grid, lag_ratio=0.01), frame.set_theta, 0, frame.set_phi, 45 * DEGREES, run_time=3, ) self.wait() self.add(count_label) self.play( ShowIncreasingSubsets(coins), UpdateFromFunc(count_label[0], lambda m, c=coins: m.set_value(len(c))), rate_func=bezier([0, 0, 1, 1]), run_time=2, ) self.wait() self.play(LaggedStartMap(FlipCoin, coins_to_flip, run_time=6, lag_ratio=0.1)) self.add(coins) self.wait() # Show key key = Key() key.rotate(PI / 4, RIGHT) key.move_to(3 * OUT) key.scale(0.8) key.to_edge(LEFT, buff=1) k = boolian_linear_combo(head_bools) ^ 63 # To make the flip below the actual solution key_cube = Cube(square_resolution=(6, 6)) key_cube.match_color(chessboard[k]) key_cube.replace(chessboard[k], stretch=True) chessboard.replace_submobject(k, key_cube) key_square = key_cube[0] chessboard.generate_target() chessboard.save_state() for i, cube in enumerate(chessboard.target): if i == k: cube[0].set_color(MAROON_E) else: cube.set_color(interpolate_color(cube.get_color(), BLACK, 0.8)) key.generate_target() key.target.rotate(PI / 4, LEFT) key.target.set_width(0.7 * key_square.get_width()) key.target.next_to(key_square, IN, buff=SMALL_BUFF) self.play(FadeIn(key, LEFT)) self.wait() self.play( FadeOut(coins, lag_ratio=0.01), MoveToTarget(chessboard), ) ks_top = key_square.get_top() self.play( Rotate(key_square, PI / 2, axis=LEFT, about_point=ks_top), MoveToTarget(key), frame.set_phi, 60 * DEGREES, run_time=2, ) self.play( Rotate(key_square, PI / 2, axis=RIGHT, about_point=ks_top), run_time=2, ) chessboard.saved_state[k][0].match_color(key_square) self.play( chessboard.restore, FadeIn(coins), frame.set_phi, 0 * DEGREES, frame.move_to, 2 * LEFT, run_time=3 ) # State goal goal = OldTexText( "Communicate where\\\\the key is", " by turning\\\\over one coin.", alignment="" ) goal.next_to(count_label, DOWN, LARGE_BUFF, LEFT) goal.fix_in_frame() goal[1].set_color(YELLOW) self.play(FadeIn(goal[0])) self.wait() self.play(FadeIn(goal[1])) self.wait() coin = coins[63] rect = SurroundingRectangle(coin, color=TEAL) rect.set_opacity(0.5) rect.save_state() rect.replace(chessboard) rect.set_stroke(width=0) rect.set_fill(opacity=0) self.play(Restore(rect, run_time=2)) self.add(coin, rect) self.play(FlipCoin(coin), FadeOut(rect)) class PrisonerPuzzleSetting(PiCreatureScene): CONFIG = { "camera_config": { "background_color": GREY_E } } def create_pi_creatures(self): p1 = PiCreature(color=BLUE_C, height=2) p2 = PiCreature(color=RED, height=2) warden = PiCreature(color=GREY_BROWN, height=2.5) warden.flip() result = VGroup(p1, p2, warden) result.arrange(RIGHT, buff=2, aligned_edge=DOWN) warden.shift(RIGHT) result.center().to_edge(DOWN, buff=1.5) return result def construct(self): pis = self.pi_creatures p1, p2, warden = self.pi_creatures names = VGroup( OldTexText("Prisoner 1\\\\(you)"), OldTexText("Prisoner 2"), OldTexText("Warden"), ) for name, pi in zip(names, pis): name.match_color(pi.body) name.next_to(pi, DOWN) question = OldTexText( "Why do mathematicians\\\\always set their puzzles\\\\in prisons?", alignment="" ) question.to_corner(UR) self.remove(warden) warden.look_at(p2.eyes) self.play( LaggedStartMap(FadeIn, pis[:2], run_time=1.5, lag_ratio=0.3), LaggedStartMap(FadeIn, names[:2], run_time=1.5, lag_ratio=0.3), ) self.play( p1.change, "sad", p2.change, "pleading", warden.eyes ) self.play( FadeIn(warden), FadeIn(names[2]), ) self.play(warden.change, "conniving", p2.eyes) self.wait() self.play(FadeIn(question, lag_ratio=0.1)) self.wait(3) self.play(FadeOut(question)) self.wait(2) class FromCoinToSquareMaps(ThreeDScene): CONFIG = { "messages": [ "Please, ", "go watch", "Stand-up", "Maths on", "YouTube." ], "flip_lag_ratio": 0.05, } def construct(self): messages = self.messages board1 = Chessboard() board1.set_width(5.5) board1.to_corner(DL) board2 = board1.copy() board2.to_corner(DR) coins = CoinsOnBoard(board1) bools = string_to_bools(messages[0]) for coin, head in zip(coins, bools): if not head: coin.flip(RIGHT) for cube in board2: cube.original_color = cube.get_color() arrow = Arrow(board1.get_right(), board2.get_left()) arrow.tip.set_stroke(width=0) title1 = OldTexText("Pattern of coins") title2 = OldTexText("Individual square") for title, board in [(title1, board1), (title2, board2)]: title.scale(0.5 / title[0][0].get_height()) title.next_to(board, UP, MED_LARGE_BUFF) title2.align_to(title1, UP) def get_special_square(coins=coins, board=board2): bools = [coin.is_heads() for coin in coins] return board[boolian_linear_combo(bools)] self.add(board1) self.add(title1) self.add(coins) self.play( GrowArrow(arrow), FadeIn(board2, 2 * LEFT) ) square = get_special_square() rect = SurroundingRectangle(square, buff=0) rect.set_color(PINK) rect.next_to(square, OUT, buff=0.01) self.play( square.set_color, MAROON_C, ShowCreation(rect), FadeIn(title2) ) for message in messages[1:]: new_bools = string_to_bools(message) coins_to_flip = Group() for coin, to_heads in zip(coins, new_bools): if coin.is_heads() ^ to_heads: coins_to_flip.add(coin) coins_to_flip.shuffle() self.play(LaggedStartMap( FlipCoin, coins_to_flip, lag_ratio=self.flip_lag_ratio, run_time=1, )) new_square = get_special_square() self.play( square.set_color, square.original_color, new_square.set_color, MAROON_C, rect.move_to, new_square, OUT, rect.shift, 0.01 * OUT, ) square = new_square self.wait() class FromCoinToSquareMapsSingleFlips(FromCoinToSquareMaps): CONFIG = { "messages": [ "FlipBits", "BlipBits", "ClipBits", "ChipBits", "ChipBats", "ChipRats", ] } class DiagramOfProgression(ThreeDScene): def construct(self): # Setup panels P1_COLOR = BLUE_C P2_COLOR = RED rect = Rectangle(4, 2) rect.set_fill(GREY_E, 1) panels = Group() for x in range(4): panels.add(Group(rect.copy())) panels.arrange_in_grid(buff=1) panels[::2].shift(0.5 * LEFT) panels.set_width(FRAME_WIDTH - 2) panels.center().to_edge(DOWN) p1_shift = panels[1].get_center() - panels[0].get_center() panels[1].move_to(panels[0]) chessboard = Chessboard() chessboard.set_height(0.9 * panels[0].get_height()) coins = CoinsOnBoard( chessboard, coin_config={ "disk_resolution": (2, 25), } ) coins.flip_by_message("Tau > Pi") for panel in panels[1:]: cb = chessboard.copy() co = coins.copy() cb.next_to(panel.get_right(), LEFT) co.next_to(cb, OUT, 0) panel.chessboard = cb panel.coins = co panel.add(cb, co) kw = { "tex_to_color_map": { "Prisoner 1": P1_COLOR, "Prisoner 2": P2_COLOR, } } titles = VGroup( OldTexText("Prisoners conspire", **kw), OldTexText("Prisoner 1 sees key", **kw), OldTexText("Prisoner 1 flips coin", **kw), OldTexText("Prisoner 2 guesses key square", **kw), ) for panel, title in zip(panels, titles): title.next_to(panel, UP) panel.title = title panel.add(title) # Darken first chessboard for coin in panels[1].coins: coin.remove(coin.edge) if coin.is_heads(): coin.remove(coin.bottom) coin.remove(coin.labels[1]) else: coin.remove(coin.top) coin.remove(coin.labels[0]) coin.set_opacity(0.25) # Add characters prisoner1 = PiCreature(color=P1_COLOR) prisoner2 = PiCreature(color=P2_COLOR) pis = VGroup(prisoner1, prisoner2) pis.arrange(RIGHT, buff=1) pis.set_height(1.5) p0_pis = pis.copy() p0_pis.set_height(2.0, about_edge=DOWN) p0_pis[1].flip() p0_pis.next_to(panels[0].get_bottom(), UP, SMALL_BUFF) p0_pis[0].change("pondering", p0_pis[1].eyes) p0_pis[1].change("speaking", p0_pis[0].eyes) panels[0].add(p0_pis) p1_pi = pis[0].copy() p1_pi.next_to(panels[1].get_corner(DL), UR, SMALL_BUFF) p1_pi.change("happy") key = Key() key.set_height(0.5) key.next_to(p1_pi, UP) key.set_color(YELLOW) key_cube = panels[1].chessboard[18] key_square = Square() key_square.replace(key_cube) key_square.set_stroke(width=3) key_square.match_color(key) p1_pi.look_at(key_square) key_arrow = Arrow( key.get_right() + SMALL_BUFF * UP, key_square.get_corner(UL), path_arc=-45 * DEGREES, buff=SMALL_BUFF ) key_arrow.tip.set_stroke(width=0) key_arrow.match_color(key) panels[1].add(p1_pi, key) p2_pi = pis[0].copy() p2_pi.next_to(panels[2].get_corner(DL), UR, SMALL_BUFF) p2_pi.change("tease") flip_coin = panels[2].coins[38] panels[3].coins[38].flip() flip_square = Square() flip_square.replace(panels[2].chessboard[38]) flip_square.set_stroke(BLUE, 5) for coin in panels[2].coins: if coin is not flip_coin: coin.remove(coin.edge) if coin.is_heads(): coin.remove(coin.bottom) coin.remove(coin.labels[1]) else: coin.remove(coin.top) coin.remove(coin.labels[0]) coin.set_opacity(0.25) panels[2].add(p2_pi) p3_pi = pis[1].copy() p3_pi.next_to(panels[3].get_corner(DL), UR, SMALL_BUFF) p3_pi.shift(MED_LARGE_BUFF * RIGHT) p3_pi.change("confused") panels[3].add(p3_pi) # Animate each panel in self.play(FadeIn(panels[1], DOWN)) self.play( ShowCreation(key_arrow), FadeInFromLarge(key_square), ) panels[1].add(key_arrow, key_square) self.wait() self.play(FadeIn(panels[2], UP)) self.play( ShowCreation(flip_square), FlipCoin(flip_coin), p2_pi.look_at, flip_coin, ) self.wait() self.play(FadeIn(panels[3], LEFT)) self.wait() self.play( FadeIn(panels[0], LEFT), panels[1].shift, p1_shift, ) self.wait() class ImpossibleVariations(FromCoinToSquareMaps): CONFIG = { "messages": [ "FlipBits", "BlipBits", "ClipBits", "ChipBits", "ChipBats", "ChipRats", "ChipVats", "ChipFats", "ChapFats", ] } def construct(self): # Definitions frame = self.camera.frame title = OldTexText("Describe any square\\\\with one flip") title.set_height(1.2) title.to_edge(UP) title.fix_in_frame() messages = it.cycle(self.messages) left_board = Chessboard() right_board = Chessboard() for board, vect in (left_board, LEFT), (right_board, RIGHT): board.set_width(4.5) board.to_corner(DOWN + vect, buff=LARGE_BUFF) coins = CoinsOnBoard(left_board) coins.flip_by_message(next(messages)) arrow = Arrow(left_board.get_right(), right_board.get_left()) # Prepare for colorings for cube in right_board: cube.original_color = cube.get_color() def get_special_square(board=right_board, coins=coins): return board[boolian_linear_combo(coins.get_bools())] frame.set_phi(45 * DEGREES) # Introduce boards self.add(title) group = Group(*left_board, *coins, *right_board) self.play( LaggedStartMap(FadeInFromLarge, group, lambda m: (m, 1.3), lag_ratio=0.01), GrowArrow(arrow) ) # Flip one at a time square = Square() square.set_stroke(TEAL, 3) square.replace(right_board[0]) square.move_to(right_board[0], OUT) self.moving_square = square self.colored_square = right_board[0] for x in range(8): self.set_board_message(next(messages), left_board, coins, get_special_square) self.wait() # To 6x6 to_fade = Group() for grid in left_board, right_board, coins: for n, mob in enumerate(grid): row = n // 8 col = n % 8 if not ((0 < row < 7) and (0 < col < 7)): to_fade.add(mob) cross = Cross(title) cross.fix_in_frame() cross.set_stroke(RED, 8) cross.shift(2 * LEFT) imp_words = OldTexText("Impossible!") imp_words.fix_in_frame() imp_words.next_to(title, RIGHT, buff=1.5) imp_words.shift(2 * LEFT) imp_words.set_height(0.7) imp_words.set_color(RED) self.play(to_fade.set_opacity, 0.05) self.play( title.shift, 2 * LEFT, FadeIn(cross, 2 * RIGHT), FadeIn(imp_words, LEFT) ) self.wait() self.play(to_fade.set_opacity, 1) # Remove a square to_remove = Group( left_board[63], right_board[63], coins[63] ) remove_words = OldTexText("Remove one\\\\square") remove_words.set_color(RED) remove_words.to_corner(DOWN, buff=1.5) remove_words.fix_in_frame() self.play( FadeIn(remove_words, DOWN), FadeOut(to_remove, 3 * IN), ) def set_board_message(self, message, left_board, coins, get_special_square): new_bools = string_to_bools(message) coins_to_flip = Group() for coin, to_heads in zip(coins, new_bools): if coin.is_heads() ^ to_heads: coins_to_flip.add(coin) coins_to_flip.shuffle() self.play(LaggedStartMap( FlipCoin, coins_to_flip, lag_ratio=self.flip_lag_ratio, run_time=1, )) new_colored_square = get_special_square() self.play( new_colored_square.set_color, BLUE, self.colored_square.set_color, self.colored_square.original_color, self.moving_square.move_to, get_special_square(), OUT, ) self.colored_square = new_colored_square class ErrorCorrectionMention(Scene): def construct(self): # Setup board message = "Do math!" error_message = "Do meth!" board = Chessboard() board.set_width(5) board.to_corner(DL) coins = CoinsOnBoard(board) coins.flip_by_message(message) bools = coins.get_bools() right_board = board.copy() right_board.to_corner(DR) right_board.set_opacity(0.5) right_board[boolian_linear_combo(bools)].set_color(BLUE, 1) arrow = Arrow(board.get_right(), right_board.get_left()) words = OldTexText("Feels a bit like ", "Error correction codes", "$\\dots$") words.scale(1.2) words.to_edge(UP) self.add(board, coins, right_board) self.add(arrow) self.add(words) # Go from board diagram to bit string bits = VGroup() for coin in coins: bit = Integer(1 if coin.is_heads() else 0) bit.replace(coin, dim_to_match=1) bits.add(bit) coin.generate_target() coin.target.rotate(90 * DEGREES, RIGHT) coin.target.set_opacity(0) bits_rect = SurroundingRectangle(bits, buff=MED_SMALL_BUFF) bits_rect.set_stroke(YELLOW, 2) data_label = OldTexText("Data") data_label.next_to(bits_rect, UP) data_label.set_color(YELLOW) meaning_label = OldTexText(f"``{message}''") error_meaning_label = OldTexText(f"``{error_message}''") for label in meaning_label, error_meaning_label: label.scale(1.5) label.next_to(arrow, RIGHT) error_meaning_label[0][5].set_color(RED) message_label = OldTexText("Message") message_label.set_color(BLUE) message_label.next_to(meaning_label, UP, buff=1.5) message_label.to_edge(RIGHT, LARGE_BUFF) message_arrow = Arrow( message_label.get_bottom(), meaning_label.get_top(), ) message_arrow = Arrow( message_label.get_left(), meaning_label.get_top(), path_arc=70 * DEGREES, ) self.play( LaggedStartMap(MoveToTarget, coins), LaggedStartMap(FadeOut, board), Write(bits), run_time=3 ) self.play( words[1].set_x, 0, FadeOut(words[0], LEFT), FadeOut(words[2], LEFT), ) self.play( ShowCreation(bits_rect), FadeIn(data_label, DOWN) ) self.play( FadeOut(right_board), FadeIn(message_label, DOWN), ShowCreation(message_arrow), FadeIn(meaning_label) ) self.wait() # Describe ECC error_index = 8 * 4 + 5 error_bit = bits[error_index] error_bit_rect = SurroundingRectangle(error_bit) error_bit_rect.set_stroke(RED, 2) self.play( FadeInFromLarge(error_bit_rect), error_bit.set_value, 1 - error_bit.get_value(), error_bit.set_color, RED, ) meaning_label.save_state() self.play( Transform(meaning_label, error_meaning_label) ) self.wait() # Ask about correction question = OldTexText("How can you\\\\detect the error?") question.next_to(bits_rect, RIGHT, aligned_edge=UP) self.play(Write(question)) self.wait(2) ecc = VGroup() for bit in int_to_bit_coords(boolian_linear_combo(bools), 6): ecc.add(Integer(bit).match_height(bits[0])) ecc.arrange(RIGHT, buff=0.2) ecc.set_color(GREEN) ecc.next_to(bits, RIGHT, MED_LARGE_BUFF, aligned_edge=DOWN) ecc_rect = SurroundingRectangle(ecc, buff=MED_SMALL_BUFF) ecc_rect.set_stroke(GREEN, 2) ecc_name = words[1] ecc_name.generate_target() ecc_name.target[-1].set_opacity(0) ecc_name.target.scale(0.75) ecc_name.target.next_to(ecc_rect) ecc_name.target.match_color(ecc) frame = self.camera.frame self.play( MoveToTarget(ecc_name), ShowIncreasingSubsets(ecc), ShowCreation(ecc_rect), ApplyMethod(frame.move_to, DOWN, run_time=2) ) self.wait() # Show correction at play lines = VGroup() for bit in bits: line = Line(ecc_rect.get_top(), bit.get_center()) line.set_stroke(GREEN, 1, opacity=0.7) lines.add(line) alert = OldTex("!!!")[0] alert.arrange(RIGHT, buff=SMALL_BUFF) alert.scale(1.5) alert.set_color(RED) alert.next_to(ecc_rect, UP) self.play(LaggedStartMap( ShowCreationThenFadeOut, lines, lag_ratio=0.02, run_time=3 )) self.play(FadeIn(alert, DOWN, lag_ratio=0.2)) self.wait() self.play(ShowCreation(lines, lag_ratio=0)) for line in lines: line.generate_target() line.target.become(lines[error_index]) self.play(LaggedStartMap(MoveToTarget, lines, lag_ratio=0, run_time=1)) self.play( error_bit.set_value, 0, Restore(meaning_label) ) self.play( FadeOut(lines), FadeOut(alert), FadeOut(error_bit_rect), error_bit.set_color, WHITE, ) self.wait() # Hamming name hamming_label = OldTexText("e.g. Hamming codes") hamming_label.move_to(ecc_name, LEFT) self.play( Write(hamming_label), FadeOut(ecc_name, DOWN) ) self.wait() class StandupMathsWrapper(Scene): CONFIG = { "title": "Solution on Stand-up Maths" } def construct(self): fsr = FullScreenFadeRectangle() fsr.set_fill(GREY_E, 1) self.add(fsr) title = OldTexText(self.title) title.scale(1.5) title.to_edge(UP) rect = ScreenRectangle(height=6) rect.set_stroke(WHITE, 2) rect.set_fill(BLACK, 1) rect.next_to(title, DOWN) rb = AnimatedBoundary(rect) self.add(rect, rb) self.play(Write(title)) self.wait(30) class ComingUpWrapper(StandupMathsWrapper): CONFIG = { "title": "Coming up" } class TitleCard(Scene): def construct(self): n = 6 board = Chessboard(shape=(n, n)) for square in board: square.set_color(interpolate_color(square.get_color(), BLACK, 0.25)) # board[0].set_opacity(0) grid = NumberPlane( x_range=(0, n), y_range=(0, n), faded_line_ratio=0 ) grid.match_height(board) grid.next_to(board, OUT, 1e-8) low_grid = grid.copy() low_grid.next_to(board, IN, 1e-8) grid.add(low_grid) grid.set_stroke(GREY, width=1) grid.set_gloss(0.5) grid.prepare_for_nonlinear_transform(0) grid.rotate(PI, RIGHT) frame = self.camera.frame frame.set_phi(45 * DEGREES) text = OldTexText("The impossible\\\\chessboard puzzle") # text.set_width(board.get_width() - 0.5) text.set_width(FRAME_WIDTH - 2) text.set_stroke(BLACK, 10, background=True) text.fix_in_frame() self.play( ApplyMethod(frame.set_phi, 0, run_time=5), ShowCreationThenDestruction(grid, lag_ratio=0.02, run_time=3), LaggedStartMap(FadeIn, board, run_time=3, lag_ratio=0), Write(text, lag_ratio=0.1, run_time=3, stroke_color=BLUE_A), ) self.wait(2) class WhatAreWeDoingHere(TeacherStudentsScene): def construct(self): self.student_says( "Wait, what are we\\\\doing here then?", target_mode="sassy", added_anims=[self.change_students("hesitant", "angry", "sassy")], run_time=2 ) self.play(self.teacher.change, "tease") self.wait(6) class HowCanWeVisualizeSolutions(TeacherStudentsScene): def construct(self): self.teacher_says( "How can we\\\\visualize solutions", bubble_config={ "height": 3, "width": 4, "fill_opacity": 0, }, added_anims=[self.change_students("pondering", "thinking", "pondering")] ) self.look_at(self.screen), self.wait(1) self.play_student_changes("thinking", "erm", "confused") self.wait(5) class TwoSquareCase(ThreeDScene): CONFIG = { "coin_names": ["c_0", "c_1"] } def construct(self): frame = self.camera.frame # Transition to just two square chessboard = Chessboard() chessboard.shift(2 * IN + UP) coins = CoinsOnBoard(chessboard) coins.flip_by_message("To 2 bits") to_remove = Group(*it.chain(*zip(chessboard[:1:-1], coins[:1:-1]))) small_board = chessboard[:2] coin_pair = coins[:2] small_group = Group(small_board, coin_pair) frame.set_phi(45 * DEGREES) two_square_words = OldTexText("What about a 2-square board?") two_square_words.fix_in_frame() two_square_words.set_height(0.5) two_square_words.center().to_edge(UP) self.add(chessboard, coins) self.play( Write(two_square_words, run_time=1), LaggedStartMap( FadeOut, to_remove, lambda m: (m, DOWN), run_time=2, lag_ratio=0.01 ), small_group.center, small_group.set_height, 1.5, frame.set_phi, 10 * DEGREES, run_time=2 ) self.wait(3) coins = coin_pair # Show two locations for the key key = Key() key.set_width(0.7 * small_board[0].get_width()) key.move_to(small_board[0]) key.shift(0.01 * OUT) coin_pair.shift(0.04 * OUT) s0_top = small_board[0][0].get_top() s1_top = small_board[1][0].get_top() s0_rot_group = Group(small_board[0][0], coin_pair[0]) s1_rot_group = Group(small_board[1][0], coin_pair[1]) self.add(key) angle = 170 * DEGREES self.play( Rotate(s0_rot_group, angle, LEFT, about_point=s0_top), Rotate(s1_rot_group, angle, LEFT, about_point=s1_top), frame.set_phi, 45 * DEGREES, ) self.wait() self.play( key.match_x, small_board[1], path_arc=PI, path_arc_axis=UP, ) self.wait() self.play( Rotate(s0_rot_group, angle, RIGHT, about_point=s0_top), Rotate(s1_rot_group, angle, RIGHT, about_point=s1_top), frame.set_phi, 0, run_time=2, ) self.wait() # Show four states pointing to two message states = VGroup(*[ OldTexText(letters, tex_to_color_map={"H": GOLD, "T": RED_D}) for letters in ["TT", "HT", "TH", "HH"] ]) states.set_height(0.8) states.arrange(DOWN, buff=1) states.to_edge(LEFT) self.play( FadeOut(two_square_words), FlipCoin(coins[1]), FadeIn(states[0]) ) self.play( FlipCoin(coins[0]), FadeIn(states[1]) ) self.play( FlipCoin(coins[0]), FlipCoin(coins[1]), FadeIn(states[2]) ) self.play( FlipCoin(coins[0]), FadeIn(states[3]) ) self.wait() key_copy = key.copy() key_copy.match_x(small_board[0]) small_board_copy = small_board.copy() small_boards = Group(small_board_copy, small_board) for board, vect in zip(small_boards, [UP, DOWN]): board.generate_target() board.target.set_opacity(0.7) board.target.shift(2 * vect) board.target.set_depth(0.01, stretch=True) self.add(key, key_copy, *small_boards) self.play( FadeOut(coins), MoveToTarget(small_board), MaintainPositionRelativeTo(key, small_board), MoveToTarget(small_board_copy), MaintainPositionRelativeTo(key_copy, small_board_copy), ) self.add(*small_boards, key, key_copy) arrows = VGroup() for i in range(4): arrows.add(Arrow(states[i].get_right(), small_boards[i // 2].get_left())) arrows.set_opacity(0.75) self.play(LaggedStartMap(GrowArrow, arrows, lag_ratio=0.3)) self.wait() # Show one flip changing interpretation coins.next_to(states, LEFT, buff=1.5) def get_state(coins=coins): bools = [c.is_heads() for c in coins] return sum([b * (2**n) for n, b in enumerate(reversed(bools))]) n = 3 state_rect = SurroundingRectangle(states[n]) board_rects = VGroup() for board in small_boards: br = SurroundingRectangle(board, buff=0) br.move_to(board, OUT) br.set_stroke(YELLOW, 3) board_rects.add(br) self.play( ApplyMethod(frame.shift, 4.5 * LEFT, run_time=1), FadeIn(coins), FadeIn(state_rect), FadeIn(board_rects[1]), arrows[n].set_color, YELLOW, arrows[n].set_opacity, 1, ) self.wait() self.play( FlipCoin(coins[1]), FadeOut(board_rects[1]), FadeIn(board_rects[0]), state_rect.move_to, states[1], arrows[3].match_style, arrows[0], arrows[1].match_style, arrows[3], ) self.wait() self.play( FlipCoin(coins[0]), state_rect.move_to, states[0], arrows[0].match_style, arrows[1], arrows[1].match_style, arrows[3], ) self.wait() self.play( FlipCoin(coins[0]), state_rect.move_to, states[1], arrows[0].match_style, arrows[1], arrows[1].match_style, arrows[0], ) self.wait() # Erase H and T, replace with 1 and 0 bin_states = VGroup(*[ OldTexText(letters, tex_to_color_map={"1": GOLD, "0": RED_D}) for letters in ["00", "10", "01", "11"] ]) for bin_state, state in zip(bin_states, states): for bit, letter in zip(bin_state, state): bit.replace(letter, dim_to_match=1) bin_coins = CoinsOnBoard(small_board, coin_config={"numeric_labels": True}) bin_coins[1].flip() bin_coins.move_to(coins) self.play( FadeOut(coins, IN), FadeIn(bin_coins), ) self.play( LaggedStartMap(GrowFromCenter, Group(*bin_states.family_members_with_points())), LaggedStartMap(ApplyMethod, Group(*states.family_members_with_points()), lambda m: (m.scale, 0)), ) self.wait() # Add labels c_labels = VGroup(*[ OldTex(name) for name in self.coin_names ]) arrow_kw = { "tip_config": { "width": 0.2, "length": 0.2, }, "buff": 0.1, "color": GREY_B, } # s_label_arrows = VGroup() # for high_square, low_square, label in zip(*small_boards, s_labels): # label.move_to(Group(high_square, low_square)) # label.arrows = VGroup( # Arrow(label.get_bottom(), low_square.get_top(), **arrow_kw), # Arrow(label.get_top(), high_square.get_bottom(), **arrow_kw), # ) # s_label_arrows.add(*label.arrows) # self.play( # FadeIn(label), # *map(GrowArrow, label.arrows) # ) c_label_arrows = VGroup() for label, coin in zip(c_labels, bin_coins): label.next_to(coin, UP, LARGE_BUFF) arrow = Arrow(label.get_bottom(), coin.get_top(), **arrow_kw) c_label_arrows.add(arrow) self.play( FadeIn(label), GrowArrow(arrow) ) self.wait() # Coin 1 communicates location bit1_rect = SurroundingRectangle( VGroup( bin_states[0][1], bin_states[-1][1], ), buff=SMALL_BUFF, ) coin1_rect = SurroundingRectangle( Group(c_labels[1], bin_coins[1]), buff=SMALL_BUFF, ) for rect in bit1_rect, coin1_rect: rect.insert_n_curves(100) nd = int(12 * get_norm(rect.get_area_vector())) rect.become(DashedVMobject(rect, num_dashes=nd)) rect.set_stroke(WHITE, 2) kw = { "stroke_width": 2, "stroke_color": YELLOW, "buff": 0.05, } zero_rects, one_rects = [ VGroup( SurroundingRectangle(bin_states[0][1], **kw), SurroundingRectangle(bin_states[1][1], **kw), ), VGroup( SurroundingRectangle(bin_states[2][1], **kw), SurroundingRectangle(bin_states[3][1], **kw), ), ] self.play( ShowCreation(bit1_rect), ShowCreation(coin1_rect), FadeOut(state_rect), ) self.wait() self.play(board_rects[0].stretch, 0.5, 0, {"about_edge": LEFT}) self.play(ShowCreation(zero_rects)) self.wait() self.play( FadeOut(board_rects[0]), FadeOut(zero_rects), FadeIn(board_rects[1]) ) self.play( board_rects[1].stretch, 0.5, 0, {"about_edge": RIGHT} ) self.play( FlipCoin(bin_coins[1]), arrows[1].match_style, arrows[0], arrows[3].match_style, arrows[1], ) self.play(ShowCreation(one_rects[1])) self.wait() # Talk about null bit null_word = OldTexText("Null bit") null_word.next_to(bin_coins[0], DOWN, buff=1.5, aligned_edge=LEFT) null_arrow = Arrow(null_word.get_top(), bin_coins[0].get_bottom()) self.play( Write(null_word), GrowArrow(null_arrow) ) self.wait() for i in (0, 1, 0): self.play( FlipCoin(bin_coins[0]), arrows[3 - i].match_style, arrows[0], arrows[2 + i].match_style, arrows[3 - i], FadeOut(one_rects[1 - i]), FadeIn(one_rects[i]), ) self.wait() # Written mathematically frame.generate_target() frame.target.set_height(10, about_edge=DOWN) rule_words = OldTexText("Rule: Just look at coin 1") rule_words.set_height(0.6) rule_words.next_to(frame.target.get_corner(UL), DR, buff=0.5) rule_arrow = Vector(1.5 * RIGHT) rule_arrow.next_to(rule_words, RIGHT) rule_arrow.set_color(BLUE) rule_equation = OldTex("K", "=", self.coin_names[1]) rule_equation_long = OldTex( "K", "=", "0", "\\cdot", self.coin_names[0], "+", "1", "\\cdot", self.coin_names[1], ) for equation in rule_equation, rule_equation_long: equation.set_color_by_tex("S", YELLOW) equation.set_height(0.7) equation.next_to(rule_arrow, RIGHT) s_labels = VGroup( OldTex("K", "= 0"), OldTex("K", "= 1"), ) for label, board in zip(s_labels, small_boards): label.set_height(0.5) label.next_to(board, UP) label.set_color_by_tex("S", YELLOW) self.play( MoveToTarget(frame), FadeIn(rule_words, 2 * DOWN) ) self.wait() for label in s_labels: self.play(Write(label)) self.wait() self.play( GrowArrow(rule_arrow), FadeIn(rule_equation, LEFT), ) self.wait() mid_equation = rule_equation_long[2:-1] mid_equation.save_state() mid_equation.scale(0, about_edge=LEFT) self.play( Transform(rule_equation[:2], rule_equation_long[:2]), Transform(rule_equation[2], rule_equation_long[-1]), Restore(mid_equation), ) self.wait() self.remove(bin_coins) for mob in self.mobjects: for submob in mob.get_family(): if isinstance(submob, TexSymbol): submob.set_stroke(BLACK, 8, background=True) self.add(bin_coins) class TwoSquaresAB(TwoSquareCase): CONFIG = { "coin_names": ["a", "b"] } class IGotThis(TeacherStudentsScene): def construct(self): self.student_says( "Pssh, I got this", target_mode="tease", look_at=self.screen, added_anims=[self.teacher.change, "happy", self.screen], run_time=2, ) self.play_student_changes( "thinking", "pondering", look_at=self.screen ) self.wait(6) class WalkingTheSquare(ThreeDScene): def construct(self): # Setup objects plane = NumberPlane( x_range=(-2, 2, 1), y_range=(-2, 2, 1), height=15, width=15, faded_line_ratio=3, axis_config={"include_tip": False} ) plane.move_to(1.5 * DOWN) plane.add_coordinate_labels() plane.x_axis.add_numbers([0]) board = Chessboard(shape=(1, 2)) board.set_height(1.5) board.move_to(plane.c2p(-0.75, 0.75)) coins = CoinsOnBoard( board, coin_config={"numeric_labels": True} ) coins.flip(RIGHT) coords = [(0, 0), (0, 1), (1, 0), (1, 1)] coord_labels = VGroup() dots = VGroup() for x, y in coords: label = OldTex(f"({x}, {y})") point = plane.c2p(x, y) label.next_to(point, UR, buff=0.25) dot = Dot(point, radius=0.075) dot.set_color(GREY) dots.add(dot) coord_labels.add(label) active_dot = Dot(radius=0.15, color=YELLOW) active_dot.move_to(plane.c2p(0, 0)) # Walk around square self.play(Write(plane)) self.play( FadeIn(board), FadeIn(coins), FadeIn(active_dot), FadeIn(coord_labels[0]), ) edges = VGroup() for i, j, c in [(0, 1, 1), (1, 3, 0), (3, 2, 1), (2, 0, 0)]: edge = Line(plane.c2p(*coords[i]), plane.c2p(*coords[j])) edge.set_stroke(PINK, 3) edges.add(edge) anims = [ FlipCoin(coins[c]), ShowCreation(edge), ApplyMethod(active_dot.move_to, dots[j]) ] if j != 0: anims += [ FadeInFromPoint(coord_labels[j], coord_labels[i].get_center()), ] self.add(edge, dots[i], active_dot) self.play(*anims) self.add(edges, dots, active_dot) self.wait() # Show a few more flips self.play( FlipCoin(coins[0]), active_dot.move_to, dots[2], ) self.play( FlipCoin(coins[1]), active_dot.move_to, dots[3], ) self.play( FlipCoin(coins[1]), active_dot.move_to, dots[2], ) self.wait() # Circles illustrating scheme low_rect = SurroundingRectangle( VGroup(edges[3], coord_labels[0], coord_labels[2], plane.x_axis.numbers[-1]), buff=0.25, ) low_rect.round_corners() low_rect.insert_n_curves(30) low_rect.set_stroke(YELLOW, 3) high_rect = low_rect.copy() high_rect.shift(dots[1].get_center() - dots[0].get_center()) key = Key() key.set_color(YELLOW) key.set_gloss(0) key.match_width(board[0]) key.next_to(board[0], UP, SMALL_BUFF) s_labels = VGroup( OldTex("\\text{Key} = 0").next_to(low_rect, UP, SMALL_BUFF), OldTex("\\text{Key} = 1").next_to(high_rect, UP, SMALL_BUFF), ) self.play( ShowCreation(low_rect), ) self.play( FadeIn(key, DOWN), FadeIn(s_labels[0], DOWN), ) self.play( FlipCoin(coins[0]), active_dot.move_to, dots[0], ) self.wait(0.5) self.play( FlipCoin(coins[0]), active_dot.move_to, dots[2], ) self.wait() self.play( TransformFromCopy(low_rect, high_rect), FadeIn(s_labels[1], DOWN), low_rect.set_stroke, GREY, 1, FlipCoin(coins[1]), active_dot.move_to, dots[3], key.match_x, board[1], ) self.wait() self.play( FlipCoin(coins[0]), active_dot.move_to, dots[1], ) self.wait() self.play( FlipCoin(coins[1]), active_dot.move_to, dots[0], key.match_x, board[0], high_rect.match_style, low_rect, low_rect.match_style, high_rect, ) self.wait() class ThreeSquareCase(ThreeDScene): CONFIG = { "coin_names": ["c_0", "c_1", "c_2"] } def construct(self): # Show sequence of boards boards = Group( Chessboard(shape=(1, 2), height=0.25 * 1), Chessboard(shape=(1, 3), height=0.25 * 1), Chessboard(shape=(2, 2), height=0.25 * 2), Chessboard(shape=(8, 8), height=0.25 * 8), ) dots = OldTex("\\dots") group = Group(*boards[:3], dots, boards[3]) group.arrange(RIGHT) group.set_width(FRAME_WIDTH - 1) board_groups = Group() for board in boards: board.coins = CoinsOnBoard(board, coin_config={"numeric_labels": True}) board_groups.add(Group(board, board.coins)) boards[0].coins.flip_at_random() boards[1].coins.flip_by_bools([False, True, False]) boards[2].coins.flip_at_random() boards[3].coins.flip_by_message("3 Fails!") def get_board_transform(i, bgs=board_groups): return TransformFromCopy( bgs[i], bgs[i + 1], path_arc=PI / 2, run_time=2, ) frame = self.camera.frame frame.save_state() frame.scale(0.5) frame.move_to(boards[:2]) self.add(board_groups[0]) self.play(get_board_transform(0)) turn_animation_into_updater(Restore(frame, run_time=4)) self.add(frame) self.play(get_board_transform(1)) self.play( Write(dots), get_board_transform(2), ) self.wait() # Isolate 3 square board board_group = board_groups[1] board = boards[1] coins = board.coins title = OldTexText("Three square case") title.set_height(0.7) title.to_edge(UP) board_group.generate_target() board_group.target.set_width(4) board_group.target.move_to(DOWN, OUT) self.save_state() self.play( MoveToTarget(board_group, rate_func=squish_rate_func(smooth, 0.5, 1)), Write(title), LaggedStartMap(FadeOut, Group( board_groups[0], board_groups[2], dots, board_groups[3], ), lambda m: (m, DOWN)), run_time=2, ) self.wait() # Try 0*c0 + 1*c1 + 2*c2 s_sum = OldTex( "0", "\\cdot", self.coin_names[0], "+", "1", "\\cdot", self.coin_names[1], "+", "2", "\\cdot", self.coin_names[2], ) s_sum.set_height(0.6) c_sum = s_sum.copy() s_sum.center().to_edge(UP) c_sum.next_to(s_sum, DOWN, LARGE_BUFF) coin_copies = Group() for i in range(3): part = c_sum.get_part_by_tex(self.coin_names[i], substring=False) coin_copy = coins[i].copy() coin_copy.set_height(1.2 * c_sum[0].get_height()) coin_copy.move_to(part) coin_copy.align_to(c_sum, UP) part.set_opacity(0) coin_copies.add(coin_copy) self.play( FadeOut(title), FadeIn(s_sum[:3]), FadeIn(c_sum[:2]), ) self.play(TransformFromCopy(coins[0], coin_copies[0])) self.wait() self.play( FadeIn(s_sum[3:7]), FadeIn(c_sum[3:6]), ) self.play(TransformFromCopy(coins[1], coin_copies[1])) self.wait() self.play( FadeIn(s_sum[7:11]), FadeIn(c_sum[7:10]), ) self.play(TransformFromCopy(coins[2], coin_copies[2])) self.wait() self.add(s_sum, c_sum, coin_copies) rhs = VGroup(OldTex("="), Integer(1)) rhs.arrange(RIGHT) rhs[1].set_color(YELLOW) rhs.match_height(c_sum[0]) rhs.next_to(c_sum, RIGHT, aligned_edge=UP) braces = VGroup( Brace(c_sum[0:3], DOWN), Brace(c_sum[0:7], DOWN), Brace(c_sum[0:11], DOWN), ) for brace, n in zip(braces, [0, 1, 1]): brace.add(brace.get_tex(n)) self.play(GrowFromCenter(braces[0])) self.wait() self.play(ReplacementTransform(braces[0], braces[1])) self.wait() self.play(ReplacementTransform(braces[1], braces[2])) self.play( TransformFromCopy(braces[2][-1], rhs[1], path_arc=-PI / 2), Write(rhs[0]), ) self.play(FadeOut(braces[2])) self.wait() # Show values of S s_labels = VGroup(*[ OldTex(f"K = {n}") for n in range(3) ]) for label, square in zip(s_labels, board): label.next_to(square, UP) label.set_width(0.8 * square.get_width()) label.set_color(YELLOW) key = Key(depth_test=False) key.set_stroke(BLACK, 3, background=True) key.set_width(0.8 * board[0].get_width()) key.move_to(board[0]) self.play( coins.next_to, board, DOWN, coins.match_z, coins, board.set_opacity, 0.75, FadeIn(key), FadeIn(s_labels[0]) ) self.wait(0.5) for i in (1, 2): self.play( ApplyMethod(key.move_to, board[i], path_arc=-45 * DEGREES), s_labels[i - 1].set_fill, GREY, 0.25, FadeIn(s_labels[i]), ) self.wait(0.5) # Mod 3 label mod3_label = OldTexText("(mod 3)") mod3_label.match_height(s_sum) mod3_label.set_color(BLUE) mod3_label.next_to(s_sum, RIGHT, buff=0.75) rhs_rhs = OldTex("\\equiv 0") rhs_rhs.match_height(rhs) rhs_rhs.next_to(rhs, RIGHT) self.play(Write(mod3_label)) self.wait() self.play( FlipCoin(coins[2]), FlipCoin(coin_copies[2]), rhs[1].set_value, 3, ) self.wait() self.play(Write(rhs_rhs)) self.wait() self.play( rhs[1].set_value, 0, FadeOut(rhs_rhs) ) # Show a few flips for i in [2, 1, 0, 2, 1, 2, 0]: bools = coins.get_bools() bools[i] = not bools[i] new_sum = sum([n * b for n, b in enumerate(bools)]) % 3 self.play( FlipCoin(coins[i]), FlipCoin(coin_copies[i]), rhs[1].set_value, new_sum, ) self.wait() # Show general sum general_sum = OldTex(r"\sum ^{63}_{n=0}n\cdot c_n") mod_64 = OldTexText("(mod 64)") mod_64.next_to(general_sum, DOWN) general_sum.add(mod_64) general_sum.to_corner(UL) self.play(FadeIn(general_sum)) self.wait() self.play(FadeOut(general_sum)) # Walk through 010 example board.flip_by_bools([False, False, True]) self.play( s_labels[2].set_fill, GREY, 0.25, s_labels[0].set_fill, YELLOW, 1, ApplyMethod(key.move_to, board[0], path_arc=30 * DEGREES) ) self.wait() self.play( FlipCoin(coins[1]), FlipCoin(coin_copies[1]), rhs[1].set_value, 0, ) self.wait() square = Square() square.set_stroke(YELLOW, 3) square.replace(board[0]) square[0].move_to(board[0], OUT) self.play(ShowCreation(square)) self.wait() self.play(FadeOut(square)) # Walk through alternate flip on 010 example self.play( FlipCoin(coins[1]), FlipCoin(coin_copies[1]), rhs[1].set_value, 1, ) morty = Mortimer(height=1.5, mode="hooray") morty.to_corner(DR) bubble = SpeechBubble(height=2, width=2) bubble.pin_to(morty) bubble.write("There's another\\\\way!") self.play( FadeIn(morty), ShowCreation(bubble), Write(bubble.content, run_time=1), ) self.play(Blink(morty)) self.play( FadeOut(VGroup(morty, bubble, bubble.content)) ) self.play( FlipCoin(coins[2]), FlipCoin(coin_copies[2]), rhs[1].set_value, 3, ) self.wait() self.play(rhs[1].set_value, 0) self.wait() class ThreeSquaresABC(ThreeSquareCase): CONFIG = { "coin_names": ["a", "b", "c"] } class FailedMod3Addition(Scene): def construct(self): coin = Coin(height=0.5, numeric_labels=True) csum = Group( OldTex("0 \\cdot"), coin.deepcopy().flip(), OldTex(" + 1 \\cdot"), coin.deepcopy().flip(), OldTex("+ 2 \\cdot"), coin.deepcopy(), OldTex("="), Integer(2, color=YELLOW), ) csum.arrange(RIGHT, buff=SMALL_BUFF) csum[-1].shift(SMALL_BUFF * RIGHT) coins = csum[1:7:2] csum[-1].add_updater(lambda m, coins=coins: m.set_value(coins[1].is_heads() + 2 * coins[2].is_heads())) self.add(csum) for coin in coins[::-1]: rect = SurroundingRectangle(coin) self.play(ShowCreation(rect)) self.play(FlipCoin(coin)) self.wait() self.play(FlipCoin(coin), FadeOut(rect)) self.wait() self.embed() class TreeOfThreeFlips(ThreeDScene): def construct(self): # Setup sums csum = Group( OldTex("0 \\cdot"), Coin(numeric_labels=True), OldTex("+\\,1 \\cdot"), Coin(numeric_labels=True), OldTex("+\\,2 \\cdot"), Coin(numeric_labels=True), OldTex("="), Integer(0) ) csum.coins = csum[1:7:2] csum.coins.set_height(1.5 * csum[0].get_height()) csum.coins.flip(RIGHT) csum.coins[1].flip(RIGHT) csum.arrange(RIGHT, buff=0.1) csum[-1].align_to(csum[0], DOWN) csum[-1].shift(SMALL_BUFF * RIGHT) csum.to_edge(LEFT) csum_rect = SurroundingRectangle(csum, buff=SMALL_BUFF) csum_rect.set_stroke(WHITE, 1) # Set rhs values def set_rhs_target(cs, colors=[RED, GREEN, BLUE]): bools = [c.is_heads() for c in cs.coins] value = sum([n * b for n, b in enumerate(bools)]) % 3 cs[-1].generate_target() cs[-1].target.set_value(value) cs[-1].target.set_color(colors[value]) return cs[-1] rhs = set_rhs_target(csum) rhs.become(rhs.target) # Create copies new_csums = Group() for i in range(3): new_csum = csum.deepcopy() new_csum.coins = new_csum[1:7:2] new_csums.add(new_csum) new_csums.arrange(DOWN, buff=1.5) new_csums.next_to(csum, RIGHT, buff=3) # Arrows arrows = VGroup() for i, ncs in enumerate(new_csums): arrow = Arrow(csum_rect.get_right(), ncs.get_left()) label = OldTexText(f"Flip coin {i}") label.set_height(0.3) label.set_fill(GREY_A) label.set_stroke(BLACK, 3, background=True) label.next_to(ORIGIN, UP, buff=0) label.rotate(arrow.get_angle(), about_point=ORIGIN) label.shift(arrow.get_center()) arrow.label = label arrows.add(arrow) arrows.set_color(GREY) # Initial state label is_label = OldTexText( "Initial state: 010", tex_to_color_map={"0": RED_D, "1": GOLD_D} ) is_label.set_height(0.4) is_label.next_to(csum_rect, UP, aligned_edge=LEFT) # Show three flips self.add(csum) self.add(csum_rect) self.add(is_label) self.wait() anims = [] for i, arrow, ncs in zip(it.count(), arrows, new_csums): anims += [ GrowArrow(arrow), FadeIn(arrow.label, lag_ratio=0.2), ] self.play(LaggedStart(*anims)) for indices in [[0], [1, 2]]: self.play(*[ TransformFromCopy(csum, new_csums[i], path_arc=30 * DEGREES, run_time=2) for i in indices ]) self.wait() for i in indices: ncs = new_csums[i] ncs.coins[i].flip() rhs = set_rhs_target(ncs) ncs.coins[i].flip() self.play( FlipCoin(ncs.coins[i]), MoveToTarget(rhs) ) # Put key in square 2 board = Chessboard(shape=(1, 3), square_resolution=(5, 5)) board.set_gloss(0.5) board.set_width(3) board.set_depth(0.25, stretch=True) board.space_out_submobjects(factor=1.001) board.next_to(ORIGIN, LEFT) board.to_edge(UP) board.shift(IN) board.rotate(60 * DEGREES, LEFT) opening_square = board[2][0] opening_square_top = opening_square.get_corner(UP + IN) key = Key() key.to_corner(UL, buff=LARGE_BUFF) key.shift(OUT) key.generate_target() key.target.scale(0.3) key.target.rotate(60 * DEGREES, LEFT) key.target.move_to(board[2][0]) self.play( FadeIn(board, DOWN), FadeIn(key) ) self.play( MoveToTarget(key, path_arc=30 * DEGREES), Rotate(opening_square, 90 * DEGREES, LEFT, about_point=opening_square_top), ) self.play( Rotate(opening_square, 90 * DEGREES, RIGHT, about_point=opening_square_top), key.next_to, board[1], RIGHT, buff=0.01, ) self.wait() self.remove(key) self.play(Rotate(board, 0 * DEGREES, RIGHT, run_time=0)) self.play(Rotate(board, 60 * DEGREES, RIGHT)) # Put coins on coins = csum.coins.copy() for coin, cube in zip(coins, board): coin.generate_target() coin.target.next_to(cube, OUT, buff=0) self.play(LaggedStartMap(MoveToTarget, coins, run_time=2)) self.wait() class SeventyFivePercentChance(Scene): def construct(self): # Setup column rows = [] n_shown = 5 coins = Group() nums = VGroup() for n in it.chain(range(n_shown), range(64 - n_shown, 64)): coin = Coin(numeric_labels=True) coin.set_height(0.7) if (random.random() < 0.5 or (n == 2)) and (n != 62): coin.flip() num = Integer(n) row = Group( coin, OldTex("\\cdot"), num, OldTex("+"), ) VGroup(*row[1:]).set_stroke(BLACK, 3, background=True) row.arrange(RIGHT, buff=MED_SMALL_BUFF) rows.append(row) coins.add(coin) nums.add(num) vdots = OldTex("\\vdots") rows = Group(*rows[:n_shown], vdots, *rows[n_shown:]) rows.arrange(DOWN, buff=MED_SMALL_BUFF, aligned_edge=LEFT) vdots.match_x(rows[0][2]) rows.set_height(7) rows.to_edge(RIGHT) rows[-1][-1].set_opacity(0) nums = VGroup(*nums[:n_shown], vdots, *nums[n_shown:]) self.play(Write(nums)) self.wait() self.play( LaggedStartMap(FadeIn, rows, lag_ratio=0.1, run_time=3), Animation(nums.copy(), remover=True), ) self.wait() # Show desired sums brace = Brace(rows, LEFT) b_label = brace.get_text("Sum mod 64") sum_label = OldTexText("=\\, 53 (say)") sum_label.next_to(b_label, DOWN) want_label = OldTexText("Need to encode 55 (say)") want_label.next_to(sum_label, DOWN, buff=0.25, aligned_edge=RIGHT) want_label.set_color(YELLOW) need_label = OldTexText("Must add 2") need_label.next_to(want_label, DOWN, buff=0.25) need_label.set_color(BLUE) for label in b_label, sum_label, want_label, need_label: label.set_stroke(BLACK, 7, background=True) self.play( GrowFromCenter(brace), FadeIn(b_label, RIGHT) ) self.wait(2) self.play(FadeIn(sum_label, 0.25 * UP)) self.wait(2) self.play(LaggedStart( FadeIn(want_label, UP), FadeIn(need_label, UP), lag_ratio=0.3 )) self.wait() # Show attempts s_rect = SurroundingRectangle(rows[2]) self.play(ShowCreation(s_rect)) self.wait() self.play(FlipCoin(rows[2][0])) self.wait(2) self.play( s_rect.move_to, rows[-2], s_rect.stretch, 1.1, 0, ) self.wait() self.play(FlipCoin(rows[-2][0])) self.wait() class ModNStrategy(ThreeDScene): def construct(self): # Board n_shown = 5 board = Chessboard() coins = CoinsOnBoard(board, coin_config={"numeric_labels": True}) coins.flip_by_message(r"75% odds") nums = VGroup() for n, square in enumerate(board): num = Integer(n) num.set_height(0.4 * square.get_height()) num.next_to(square, OUT, buff=0) nums.add(num) nums.set_stroke(BLACK, 3, background=True) coins.generate_target() for coin in coins.target: coin.set_opacity(0.2) coin[-2:].set_opacity(0) self.add(board) self.add(coins) self.wait() self.play( MoveToTarget(coins), FadeIn(nums, lag_ratio=0.1) ) self.wait() # # Compress # square_groups = Group(*[ # Group(square, coin, num) # for square, coin, num in zip(board, coins, nums) # ]) # segments = Group( # square_groups[:n_shown], # square_groups[n_shown:-n_shown], # square_groups[-n_shown:], # ) # segments.generate_target() # dots = OldTex("\\cdots") # dots.center() # segments.target[0].next_to(dots, LEFT) # segments.target[2].next_to(dots, RIGHT) # segments.target[1].scale(0) # segments.target[1].move_to(dots) # self.play( # Write(dots), # MoveToTarget(segments), # ) # self.wait() # self.remove(segments[1]) # # Raise coins # coins = Group(*coins[:n_shown], *coins[-n_shown:]) # nums = VGroup(*nums[:n_shown], *nums[-n_shown:]) # board = Group(*board[:n_shown], *board[-n_shown:]) # self.play( # coins.shift, UP, # coins.set_opacity, 1, # ) # Setup sum mid_coins = coins[n_shown:-n_shown] mid_nums = nums[n_shown:-n_shown] coins = Group(*coins[:n_shown], *coins[-n_shown:]) nums = VGroup(*nums[:n_shown], *nums[-n_shown:]) nums.generate_target() coins.generate_target() coins.target.set_opacity(1) full_sum = Group() to_fade_in = VGroup() for num, coin in zip(nums.target, coins.target): coin.set_height(0.7) num.set_height(0.5) summand = Group( coin, OldTex("\\cdot"), num, OldTex("+"), ) to_fade_in.add(summand[1], summand[3]) VGroup(*summand[1:]).set_stroke(BLACK, 3, background=True) summand.arrange(RIGHT, buff=MED_SMALL_BUFF) full_sum.add(summand) dots = OldTex("\\dots") full_sum = Group(*full_sum[:n_shown], dots, *full_sum[n_shown:]) full_sum.arrange(RIGHT, buff=MED_SMALL_BUFF) full_sum.set_width(FRAME_WIDTH - 1) full_sum[-1][-1].scale(0, about_edge=LEFT) full_sum.move_to(UP) brace = Brace(full_sum, DOWN) s_label = VGroup( OldTexText("Sum (mod 64) = "), Integer(53), ) s_label[1].set_color(BLUE) s_label[1].match_height(s_label[0][0][0]) s_label.arrange(RIGHT) s_label[1].align_to(s_label[0][0][0], DOWN) s_label.next_to(brace, DOWN) words = OldTexText("Can't know if a flip will add or subtract") words.to_edge(UP) for mob in mid_coins, mid_nums: mob.generate_target() mob.target.move_to(dots) mob.target.scale(0) mob.target.set_opacity(0) self.play( FadeOut(board, IN), MoveToTarget(mid_coins, remover=True), MoveToTarget(mid_nums, remover=True), MoveToTarget(nums), MoveToTarget(coins), Write(dots), FadeIn(to_fade_in, lag_ratio=0.1), run_time=2 ) self.play( GrowFromCenter(brace), FadeIn(s_label, 0.25 * UP) ) self.wait() self.play(Write(words, run_time=1)) self.wait() # Do some flips s_label[1].add_updater(lambda m: m.set_value(m.get_value() % 64)) for x in range(10): n = random.randint(-n_shown, n_shown - 1) coin = coins[n] n = n % 64 diff_label = Integer(n, include_sign=True) if not coin.is_heads(): diff_label.set_color(GREEN) else: diff_label.set_color(RED) diff_label.set_value(-diff_label.get_value()) diff_label.next_to(coin, UP, aligned_edge=LEFT) self.play( ChangeDecimalToValue( s_label[1], s_label[1].get_value() + n, rate_func=squish_rate_func(smooth, 0.5, 1) ), FlipCoin(coin), FadeIn(diff_label, 0.5 * DOWN) ) self.play(FadeOut(diff_label)) self.wait() class ShowCube(ThreeDScene): def construct(self): # Camera stuffs frame = self.camera.frame light = self.camera.light_source light.move_to([-10, -10, 20]) # Plane and axes plane = NumberPlane( x_range=(-2, 2, 1), y_range=(-2, 2, 1), height=15, width=15, faded_line_ratio=3, axis_config={"include_tip": False} ) plane.add_coordinate_labels() plane.coordinate_labels.set_stroke(width=0) axes = ThreeDAxes( x_range=(-2, 2, 1), y_range=(-2, 2, 1), z_range=(-2, 2, 1), height=15, width=15, depth=15, ) axes.apply_depth_test() # Vertices and edges vert_coords = [ (n % 2, (n // 2) % 2, (n // 4) % 2) for n in range(8) ] verts = [] coord_labels = VGroup() coord_labels_2d = VGroup() for coords in vert_coords: vert = axes.c2p(*coords) verts.append(vert) x, y, z = coords label = OldTex(f"({x}, {y}, {z})") label.set_height(0.3) label.next_to(vert, UR, SMALL_BUFF) label.rotate(89 * DEGREES, RIGHT, about_point=vert) coord_labels.add(label) if z == 0: label_2d = OldTex(f"({x}, {y})") label_2d.set_height(0.3) label_2d.next_to(vert, UR, SMALL_BUFF) coord_labels_2d.add(label_2d) edge_indices = [ (0, 1), (0, 2), (1, 3), (2, 3), (0, 4), (1, 5), (2, 6), (3, 7), (4, 5), (4, 6), (5, 7), (6, 7), ] # Vertex and edge drawings spheres = SGroup() for vert in verts: sphere = Sphere( radius=0.1, resolution=(9, 9), ) sphere.set_gloss(0.3) sphere.set_color(GREY) sphere.move_to(vert) spheres.add(sphere) edges = SGroup() for i, j in edge_indices: edge = Line3D( verts[i], verts[j], resolution=(5, 51), width=0.04, gloss=0.5, ) edge.set_color(GREY_BROWN) edges.add(edge) # Setup highlight animations def highlight(n, spheres=spheres, coord_labels=coord_labels): anims = [] for k, sphere, cl in zip(it.count(), spheres, coord_labels): if k == n: sphere.save_state() cl.save_state() sphere.generate_target() cl.generate_target() cl.target.set_fill(YELLOW) sphere.target.set_color(YELLOW) Group(cl.target, sphere.target).scale(1.5, about_point=sphere.get_center()) anims += [ MoveToTarget(sphere), MoveToTarget(cl), ] elif sphere.get_color() == Color(YELLOW): anims += [ Restore(sphere), Restore(cl), ] return AnimationGroup(*anims) # Setup 2d case frame.move_to(1.5 * UP) self.add(plane) self.play( LaggedStartMap(FadeIn, coord_labels_2d), LaggedStartMap(GrowFromCenter, spheres[:4]), LaggedStartMap(GrowFromCenter, edges[:4]), ) self.wait() # Transition to 3d case frame.generate_target() frame.target.set_euler_angles(-25 * DEGREES, 70 * DEGREES) frame.target.move_to([1, 2, 0]) frame.target.set_height(10) to_grow = Group(*edges[4:], *spheres[4:], *coord_labels[4:]) to_grow.save_state() to_grow.set_depth(0, about_edge=IN, stretch=True) rf = squish_rate_func(smooth, 0.5, 1) self.play( MoveToTarget(frame), ShowCreation(axes.z_axis), Restore(to_grow, rate_func=rf), FadeOut(coord_labels_2d, rate_func=rf), *[ FadeInFromPoint(cl, cl2.get_center(), rate_func=squish_rate_func(smooth, 0.5, 1)) for cl, cl2 in zip(coord_labels[:4], coord_labels_2d) ], run_time=3 ) frame.start_time = self.time frame.scene = self frame.add_updater(lambda m: m.set_theta( -25 * DEGREES * math.cos((m.scene.time - m.start_time) * PI / 60) )) self.add(axes.z_axis) self.add(edges) self.add(spheres) self.play( LaggedStart(*[Indicate(s, color=GREEN) for s in spheres], run_time=2, lag_ratio=0.1), LaggedStart(*[Indicate(c, color=GREEN) for c in coord_labels], run_time=2, lag_ratio=0.1), ) # Add chessboard board = Chessboard( shape=(1, 3), height=1, square_resolution=(5, 5), ) board.move_to(plane.c2p(-1, 0), DOWN + IN) coins = CoinsOnBoard(board, coin_config={"numeric_labels": True}) self.play( FadeIn(board), FadeIn(coins), highlight(7) ) # Walk along a few edges for ci in [1, 2, 0, 1, 2, 1, 0, 1]: coin = coins[ci] curr_n = sum([(2**k) * c.is_heads() for k, c in enumerate(coins)]) coin.flip() new_n = sum([(2**k) * c.is_heads() for k, c in enumerate(coins)]) coin.flip() line = Line(verts[curr_n], verts[new_n]) line.set_stroke(YELLOW, 3) self.play( FlipCoin(coin), highlight(new_n), ShowCreationThenDestruction(line) ) self.wait() # Color the corners self.play( highlight(-1), edges.set_color, GREY, 0.5, ) colors = [RED, GREEN, BLUE_D] title = OldTexText("Strategy", "\\, $\\Leftrightarrow$ \\,", "Coloring") title[2].set_submobject_colors_by_gradient(*colors) title.set_stroke(BLACK, 5, background=True) title.set_height(0.7) title.to_edge(UP) title.shift(LEFT) title.fix_in_frame() color_label_templates = [ OldTex(char, color=color).rotate(PI / 2, RIGHT).match_depth(coord_labels[0]) for char, color in zip("RGB", colors) ] coord_labels.color_labels = VGroup(*[VMobject() for cl in coord_labels]) def get_coloring_animation(ns, spheres=spheres, coord_labels=coord_labels, colors=colors, color_label_templates=color_label_templates, ): anims = [] new_color_labels = VGroup() for n, sphere, coord_label, old_color_label in zip(ns, spheres, coord_labels, coord_labels.color_labels): color = colors[int(n)] sphere.generate_target() coord_label.generate_target() sphere.target.set_color(color) coord_label.target.set_fill(color) color_label = color_label_templates[n].copy() color_label.next_to(coord_label, RIGHT, SMALL_BUFF) anims += [ MoveToTarget(sphere), MoveToTarget(coord_label), FadeIn(color_label, 0.25 * IN), FadeOut(old_color_label, 0.25 * OUT), ] new_color_labels.add(color_label) coord_labels.color_labels = new_color_labels return LaggedStart(*anims, run_time=2) self.play( FadeIn(title, DOWN), get_coloring_animation(np.random.randint(0, 3, 8)), ) self.wait() for x in range(4): self.play(get_coloring_animation(np.random.randint(0, 3, 8))) self.wait() # Some specific color examples S0 = OldTex("\\text{Key} = 0") S0.to_edge(LEFT) S0.shift(UP) S0.fix_in_frame() self.play( FadeIn(S0, DOWN), get_coloring_animation([0] * 8) ) self.wait(5) bit_sum = OldTex("\\text{Key} = \\,&c_0 + c_1") bit_sum.scale(0.8) bit_sum.to_edge(LEFT) bit_sum.shift(UP) bit_sum.fix_in_frame() self.play( FadeIn(bit_sum, DOWN), FadeOut(S0, UP), get_coloring_animation([sum(coords[:2]) for coords in vert_coords]) ) self.wait(6) bit_sum_with_coefs = OldTex( "\\text{Key} = \\,&(0\\cdot c_0 + 1\\cdot c_1 + 2\\cdot c_2) \\\\ &\\quad \\mod 3" ) bit_sum_with_coefs.scale(0.8) bit_sum_with_coefs.move_to(bit_sum, LEFT) bit_sum_with_coefs.fix_in_frame() self.play( FadeIn(bit_sum_with_coefs, DOWN), FadeOut(bit_sum, UP), get_coloring_animation([np.dot(coords, [0, 1, 2]) % 3 for coords in vert_coords]) ) self.wait(4) # Focus on (0, 0, 0) self.play( FlipCoin(coins), coord_labels[1:].set_opacity, 0.2, coord_labels.color_labels[1:].set_opacity, 0.2, spheres[1:].set_opacity, 0.2, ) self.wait(2) lines = VGroup() for n in [1, 2, 4]: line = Line(verts[0], verts[n], buff=0.1) line.set_stroke(YELLOW, 3) coin = coins[int(np.log2(n))] self.play( ShowCreationThenDestruction(line), spheres[n].set_opacity, 1, coord_labels[n].set_opacity, 1, coord_labels.color_labels[n].set_opacity, 1, FlipCoin(coin) ) line.reverse_points() self.add(line, coord_labels) self.play( FlipCoin(coin), ShowCreation(line) ) lines.add(line) self.wait(10) # Focus on (0, 1, 0) self.play( FlipCoin(coins[1]), Uncreate(lines[1]), FadeOut(lines[::2]), Group( spheres[0], coord_labels[0], coord_labels.color_labels[0], spheres[1], coord_labels[1], coord_labels.color_labels[1], spheres[4], coord_labels[4], coord_labels.color_labels[4], ).set_opacity, 0.2, ) self.wait(3) lines = VGroup() curr_n = 2 for n in [1, 2, 4]: new_n = n ^ curr_n line = Line(verts[curr_n], verts[new_n], buff=0.1) line.set_stroke(YELLOW, 3) coin = coins[int(np.log2(n))] self.play( ShowCreationThenDestruction(line), spheres[new_n].set_opacity, 1, coord_labels[new_n].set_opacity, 1, coord_labels.color_labels[new_n].set_opacity, 1, FlipCoin(coin) ) line.reverse_points() self.add(line, coord_labels) self.play( FlipCoin(coin), ShowCreation(line) ) lines.add(line) self.wait(10) self.play( LaggedStartMap(Uncreate, lines), spheres.set_opacity, 1, coord_labels.set_opacity, 1, coord_labels.color_labels.set_opacity, 1, FadeOut(bit_sum_with_coefs), ) self.wait() for x in range(8): self.play(get_coloring_animation(np.random.randint(0, 3, 8))) self.wait() # Count all strategies count = OldTexText("$3^8$ total strategies") count64 = OldTexText("$64^{(2^{64})}$ total strategies") for words in count, count64: words.to_edge(LEFT, buff=MED_SMALL_BUFF) words.shift(UP) words.fix_in_frame() full_board = Chessboard() full_board.set_height(6) full_board.next_to(axes.c2p(0, 0, 0), np.array([-1, 1, 1]), buff=0) full_board.shift(SMALL_BUFF * UP + LEFT) full_coins = CoinsOnBoard(full_board, coin_config={"numeric_labels": True}) full_coins.flip_by_message("64^ 2^64") self.play(FadeIn(count, DOWN)) self.wait(4) self.remove(board, coins) frame.clear_updaters() frame.generate_target() frame.target.set_euler_angles(0, 45 * DEGREES) frame.target.shift(2 * UP) self.play( count.shift, UP, count.set_opacity, 0.5, ShowIncreasingSubsets(full_board, run_time=4), ShowIncreasingSubsets(full_coins, run_time=4), FadeIn(count64, DOWN), MoveToTarget(frame, run_time=5) ) messages = [ "Or, use ", "Burnside", "to count", "modulo ", "symmetry", ] for message in messages: bools = string_to_bools(message) to_flip = Group() for head, coin in zip(bools, full_coins): if head ^ coin.is_heads(): to_flip.add(coin) self.play( LaggedStartMap(FlipCoin, to_flip, run_time=1) ) self.wait(0.5) frame.generate_target() frame.target.shift(2 * DOWN) frame.target.set_euler_angles(-15 * DEGREES, 70 * DEGREES) self.play( MoveToTarget(frame, run_time=3), LaggedStartMap(FadeOut, full_board), LaggedStartMap(FadeOut, full_coins), FadeOut(count), FadeOut(count64), ) frame.add_updater(lambda m, dt: m.increment_theta(0.01 * dt)) self.wait(30) class CubeSupplement(ThreeDScene): CONFIG = { "try_different_strategies": False, } def construct(self): # Map 8 states to square choices boards = Group(*[Chessboard(shape=(1, 3)) for x in range(8)]) boards.arrange(DOWN, buff=0.5 * boards[0].get_height()) boards.set_height(7) boards.to_edge(LEFT) coin_sets = Group(*[ CoinsOnBoard(board, coin_config={"numeric_labels": True}) for board in boards ]) vert_coords = [[n // 4, (n // 2) % 2, n % 2] for n in range(7, -1, -1)] for coords, coins in zip(vert_coords, coin_sets): coins.flip_by_bools(coords) def get_choice_boards(values, boards): choices = VGroup() for value, board in zip(values, boards): choice = VGroup(*[Square() for x in range(3)]) choice.arrange(RIGHT, buff=0) choice.match_height(board) choice.next_to(board, RIGHT, buff=1.25) choice.set_fill(GREY_D, 1) choice.set_stroke(WHITE, 1) choice[value].set_fill(TEAL) choices.add(choice) return choices colors = [RED, GREEN, BLUE_D] color_words = ["Red", "Green", "Blue"] s_values = [sum([n * v for n, v in enumerate(cs)]) % 3 for cs in vert_coords] choice_boards = get_choice_boards(s_values, boards) c_labels = VGroup() s_arrows = VGroup() for value, board, choice_board in zip(s_values, boards, choice_boards): arrow = Vector(RIGHT) arrow.next_to(board, RIGHT, SMALL_BUFF) c_label = OldTexText(color_words[value], color=colors[value]) c_label.next_to(choice_board, RIGHT) c_labels.add(c_label) s_arrows.add(arrow) choice_board.generate_target() choice_board.target[value].set_fill(colors[value]) self.play( LaggedStartMap(FadeIn, boards, lag_ratio=0.25), LaggedStartMap(FadeIn, coin_sets, lag_ratio=0.25), run_time=3 ) self.play( LaggedStartMap(GrowArrow, s_arrows, lag_ratio=0.25), LaggedStartMap(FadeIn, choice_boards, lambda m: (m, LEFT), lag_ratio=0.25), ) self.wait() # Fork if self.try_different_strategies: for x in range(5): values = list(np.arange(8) % 3) random.shuffle(values) new_cboards = get_choice_boards(values, boards) self.play( LaggedStartMap(FadeOut, choice_boards, lambda m: (m, 0.25 * UP)), LaggedStartMap(FadeIn, new_cboards, lambda m: (m, 0.25 * DOWN)), ) choice_boards = new_cboards self.wait(2) else: # Associate choices with colors self.play( LaggedStartMap(MoveToTarget, choice_boards), LaggedStartMap(FadeIn, c_labels), ) self.wait() class TryDifferentCaseThreeStrategies(CubeSupplement): CONFIG = { "try_different_strategies": True, } class CubeEdgeDescription(Scene): CONFIG = { "camera_config": {"background_color": GREY_E} } def construct(self): bits = VGroup(*[ VGroup(*[ Integer(int(b)) for b in string_to_bools(char) ]).arrange(RIGHT, buff=SMALL_BUFF) for char in "hi" ]) bits.arrange(DOWN, buff=LARGE_BUFF) arrow = Arrow( bits[0][7].get_bottom(), bits[1][7].get_top(), buff=SMALL_BUFF, tip_config={"length": 0.15, "width": 0.15} ) arrow.set_color(BLUE) words = OldTexText("Bit flip") words.set_color(BLUE) words.next_to(arrow, LEFT) bf_group = VGroup(bits, arrow, words) parens = OldTex("()")[0] parens.scale(2) parens.match_height(bf_group, stretch=True) parens[0].next_to(bf_group, LEFT, SMALL_BUFF) parens[1].next_to(bf_group, RIGHT, SMALL_BUFF) bf_group.add(parens) bf_group.to_edge(UP) cube_words = OldTexText("Edge of an\\\\n-dimensional cube") top_group = VGroup( bf_group, Vector(RIGHT), cube_words ) top_group.arrange(RIGHT) top_group.to_edge(UP) self.add(bf_group) self.play( TransformFromCopy(*bits), GrowArrow(arrow), FadeIn(words, 0.25 * UP) ) self.wait() self.play( GrowArrow(top_group[1]), FadeIn(cube_words, LEFT) ) self.wait() class EdgeColoringExample(Scene): def construct(self): words = VGroup( OldTexText( "Color edges\\\\red or blue", tex_to_color_map={"red": RED, "blue": BLUE} ), OldTexText("Prove there is a\\\\monochromatic triangle", alignment=""), ) words.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) words.to_edge(RIGHT) words.to_edge(UP, buff=LARGE_BUFF) def get_graph(words=words): points = compass_directions(6) points *= 3 verts = VGroup(*[Dot(p, radius=0.1) for p in points]) verts.set_fill(GREY_B, 1) edges = VGroup(*[ Line(p1, p2, color=random.choice([RED, BLUE])) for p1, p2 in it.combinations(points, 2) ]) graph = VGroup(verts, edges) graph.set_height(6) graph.next_to(words, LEFT, LARGE_BUFF) graph.set_y(0) graph.set_stroke(background=True) return graph graph = get_graph() self.add(words) self.add(graph) self.wait() for x in range(2): new_graph = get_graph() self.play( ShowCreation( new_graph, lag_ratio=0.1, run_time=3, ), ApplyMethod( graph[1].set_stroke, None, 0, run_time=2, ) ) graph = new_graph self.wait(4) class GrahamsConstantAlt(Scene): def construct(self): # lhs = OldTex("g_{64}", "=") # lhs[0][1:].scale(0.7, about_edge=DL) lhs = OldTex("") lhs.scale(2) rhs = VGroup() for ndots in [1, 3, 6, 7, 9, 12]: row = VGroup(*[ OldTex("2"), OldTex("\\uparrow\\uparrow"), VGroup(*[ OldTex("\\cdot") for x in range(ndots) ]).arrange(RIGHT, buff=0.2), OldTex("\\uparrow\\uparrow"), OldTex("3"), ]) row.arrange(RIGHT, buff=MED_SMALL_BUFF) if ndots == 1: rc = row.get_center() row[:2].move_to(rc, RIGHT) row[2].set_opacity(0) row[3:].move_to(rc, LEFT) row.add(Brace(row[1:-1], DOWN, buff=SMALL_BUFF)) rhs.add(row) rhs.replace_submobject(0, Integer(12)) # rhs[0][-1].set_opacity(0) rhs.replace_submobject(3, OldTex("\\vdots")) rhs.arrange(UP) rhs.next_to(lhs, RIGHT) rbrace = Brace(rhs[1:], RIGHT) rbrace_tex = rbrace.get_text("7 times") equation = VGroup(lhs, rhs, rbrace, rbrace_tex) equation.center().to_edge(LEFT, buff=LARGE_BUFF) self.add(lhs, rhs[0]) self.play(TransformFromCopy(rhs[0], rhs[1]),) self.play(TransformFromCopy(rhs[1], rhs[2])) self.play( Write(rhs[3]), TransformFromCopy(rhs[2], rhs[4]), ) self.play( TransformFromCopy(rhs[4], rhs[5]), GrowFromCenter(rbrace), Write(rbrace_tex) ) self.wait() class ThinkAboutNewTrick(PiCreatureScene, ThreeDScene): def construct(self): randy = self.pi_creature board = Chessboard(shape=(1, 3)) board.set_height(1.5) coins = CoinsOnBoard(board) coins.flip_at_random() self.add(board, coins) self.play(randy.change, "confused", board) for x in range(4): self.play(FlipCoin(random.choice(coins))) if x == 1: self.play(randy.change, "maybe") else: self.wait() class AttemptAColoring(ThreeDScene): def construct(self): # Setup cube short_vert_height = 0.3 tall_vert_height = 0.4 vert_coords = np.array(list(map(int_to_bit_coords, range(8)))) vert_coords = vert_coords - 0.5 vert_coords = vert_coords * 4 vert_coords[:, 2] *= 1.25 # Stretch in the z cube = Group() cube.verts = SGroup() cube.edges = VGroup() cube.add(cube.verts, cube.edges) for n, coords in enumerate(vert_coords): vert = Sphere(resolution=(21, 21)) vert.set_height(short_vert_height) vert.rotate(90 * DEGREES, RIGHT) vert.move_to(coords) cube.verts.add(vert) vert.edges = VGroup() for m, coords2 in enumerate(vert_coords): if sum(int_to_bit_coords(n ^ m)) == 1: edge = Line(coords, coords2) cube.edges.add(edge) vert.edges.add(edge) vert.edges.apply_depth_test() cube.edges.set_color(GREY) cube.edges.apply_depth_test() cube.rotate(30 * DEGREES, DOWN) cube.to_edge(RIGHT) cube.set_height(4) self.play( ShowCreation(cube.edges, lag_ratio=0.1), LaggedStartMap(FadeInFromLarge, cube.verts, lambda m: (m, 0.2)), run_time=2, ) # Setup cube color def get_colored_vertices(values, verts=cube.verts): color_choices = [RED, GREEN, BLUE_D] color_label_choices = ["R", "G", "B"] vert_targets = SGroup() labels = VGroup() for n, vert in zip(values, verts): color = color_choices[n] v_target = vert.copy() if n == -1: v_target.set_height(short_vert_height) v_target.set_color(GREY) label = VectorizedPoint() else: v_target.set_color(color) v_target.set_height(tall_vert_height) label = OldTex(color_label_choices[n]) label.set_color(color) label.set_stroke(BLACK, 3, background=True) label.next_to(vert, UR, buff=0) vert_targets.add(v_target) labels.add(label) return vert_targets, labels new_verts, color_labels = get_colored_vertices(np.arange(0, 8) % 3) for vert, label in zip(cube.verts, color_labels): vert.label = label self.play( Transform(cube.verts, new_verts), Write(color_labels), run_time=2, ) self.wait() def get_color_change_animations(values, verts=cube.verts, labels=color_labels, gcv=get_colored_vertices): new_verts, new_labels = gcv(values) old_labels = labels.copy() labels.become(new_labels) return [ Transform(verts, new_verts), LaggedStartMap(FadeOut, old_labels, lambda m: (m, 0.5 * UP), lag_ratio=0.03), LaggedStartMap(FadeIn, labels, lambda m: (m, 0.5 * DOWN), lag_ratio=0.03), ] # Prepare a few colorings mod3_strategy = [ np.dot(int_to_bit_coords(n), [0, 1, 2]) % 3 for n in range(8) ] sum_bits = [sum(int_to_bit_coords(n)) % 3 for n in range(8)] self.play(*get_color_change_animations(sum_bits)) self.wait() self.play(*get_color_change_animations(mod3_strategy)) self.wait() # Pull out vertices with their neighbors # first just one, then all of them. trees = Group() tree_targets = Group() for n, vert in enumerate(cube.verts): tree = Group() tree.root = vert.copy() tree.root.origin = tree.root.get_center() tree.edges = VGroup() tree.leafs = Group() tree.labels = Group() for mask in [1, 2, 4]: leaf = cube.verts[n ^ mask] leaf.origin = leaf.get_center() label = leaf.label.copy() label.original = leaf.label tree.edges.add(Line(vert.get_center(), leaf.get_center())) tree.leafs.add(leaf.copy()) tree.labels.add(label) tree.edges.apply_depth_test() tree.edges.match_style(vert.edges) tree.edges.save_state() tree.add(tree.root, tree.edges, tree.leafs, tree.labels) trees.add(tree) tree.generate_target(use_deepcopy=True) for edge, leaf, label, y in zip(tree.target.edges, tree.target.leafs, tree.target.labels, [0.4, 0, -0.4]): start = vert.get_center() end = start + RIGHT + y * UP edge.set_points_as_corners([start, end]) leaf.move_to(edge.get_end()) label.next_to(leaf, RIGHT, buff=SMALL_BUFF) label.scale(0.7) tree_targets.add(tree.target) tree_targets.arrange_in_grid(4, 2, buff=LARGE_BUFF) tree_targets[1::2].shift(0.5 * RIGHT) tree_targets.set_height(6) tree_targets.center() tree_targets.to_corner(DL) self.play( MoveToTarget(trees[0]), run_time=3, ) self.wait() self.play( LaggedStartMap( MoveToTarget, trees[1:], lag_ratio=0.3, ), run_time=6, ) self.add(trees) self.wait() # Show what we want want_rect = SurroundingRectangle(trees, buff=MED_SMALL_BUFF) want_rect.set_stroke(WHITE, 1) want_label = OldTexText("What we want") want_label.next_to(want_rect, UP) trees.save_state() anims = [] for tree in trees: anims.append(ApplyMethod(tree.root.set_color, GREY)) colors = [RED, GREEN, BLUE_D] letters = ["R", "G", "B"] for color, letter, leaf, label in zip(colors, letters, tree.leafs, tree.labels): new_label = OldTexText(letter) new_label.set_fill(color) new_label.replace(label, dim_to_match=1) old_label = label.copy() label.become(new_label) anims += [ FadeIn(label, 0.1 * LEFT), FadeOut(old_label, 0.1 * RIGHT), ApplyMethod(leaf.set_color, color), ] cube.verts.generate_target() cube.verts.save_state() cube.verts.target.set_color(GREY) for vert in cube.verts.target: vert.scale(0.75) self.play( ShowCreation(want_rect), Write(want_label), LaggedStart(*anims, lag_ratio=0.001, run_time=3), FadeOut(color_labels), MoveToTarget(cube.verts), ) self.add(trees) self.wait() # Try to fit these back onto the cube # First attempt def restore_tree(tree, **kwargs): anims = [] for mob in [tree.root, *tree.leafs]: anims.append(ApplyMethod(mob.move_to, mob.origin)) for label in tree.labels: label.generate_target() label.target.replace(label.original, dim_to_match=1) anims.append(MoveToTarget(label)) anims.append(Restore(tree.edges)) return AnimationGroup(*anims, **kwargs) tree_copies = trees.deepcopy() self.play(restore_tree(tree_copies[0], run_time=2)) self.wait() self.play(restore_tree(tree_copies[1], run_time=2)) self.wait() frame = self.camera.frame self.play( UpdateFromAlphaFunc( frame, lambda m, a: m.move_to(0.1 * wiggle(a, 6) * RIGHT), ), FadeOut(tree_copies[0]), FadeOut(tree_copies[1]), ) # Second attempt def restore_vertex(n, verts=cube.verts, labels=color_labels): return AnimationGroup( Transform(verts[n], verts.saved_state[n]), FadeIn(labels[n], DOWN) ) for i in [0, 4, 2, 1]: self.play(restore_vertex(i)) self.wait() self.play(ShowCreationThenFadeAround(cube.verts[4])) for i in [6, 5]: self.play(restore_vertex(i)) self.wait() q_marks = VGroup(*[Tex("???") for x in range(2)]) q_marks[0].next_to(cube.verts[7], UP, SMALL_BUFF) q_marks[1].next_to(cube.verts[3], UP, SMALL_BUFF) self.play(Write(q_marks)) self.wait() # Mention it'll never work nv_label = OldTexText("It'll never work!") nv_label.set_height(0.5) nv_label.next_to(cube, UP, buff=0.75) cube_copy = cube.deepcopy() self.remove(cube) self.add(cube_copy) new_verts, new_labels = get_colored_vertices([-1] * 8) self.play( Transform(cube_copy.verts, new_verts), FadeOut(q_marks), FadeOut(color_labels[:3]), FadeOut(color_labels[4:7]), ) self.add(cube_copy) self.play(FadeIn(nv_label, DOWN)) for vert in cube_copy.verts: vert.generate_target() vert.target.scale(0.01) vert.target.set_opacity(0) self.play( LaggedStartMap(Uncreate, cube_copy.edges), LaggedStartMap(MoveToTarget, cube_copy.verts), ) # Highlight symmetry rects = VGroup() for tree in trees: t_rect = SurroundingRectangle( Group(tree.leafs, tree.labels), buff=SMALL_BUFF ) t_rect.set_stroke(YELLOW, 2) rects.add(t_rect) self.play(LaggedStartMap(ShowCreationThenFadeOut, rects, lag_ratio=0.025, run_time=3)) self.wait() # Show implication implies = OldTex("\\Rightarrow") implies.set_height(0.7) implies.next_to(want_rect, RIGHT) number_labels = VGroup(*[ OldTexText("Number of ", f"{color} vertices") for color in ["red", "green", "blue"] ]) for color, label in zip(colors, number_labels): label[1].set_color(color) number_labels.set_height(0.5) number_labels.arrange(DOWN, buff=1.5, aligned_edge=LEFT) number_labels.next_to(implies, RIGHT, MED_LARGE_BUFF) vert_eqs = VGroup(*[Tex("=") for x in range(2)]) vert_eqs.scale(1.5) vert_eqs.rotate(90 * DEGREES) vert_eqs[0].move_to(number_labels[0:2]) vert_eqs[1].move_to(number_labels[1:3]) rhss = VGroup() for label in number_labels: rhs = OldTex("= \\frac{8}{3}") rhs.scale(1.25) rhs.next_to(label, RIGHT) rhss.add(rhs) self.play( Write(implies), FadeOut(nv_label), ) self.play( GrowFromCenter(vert_eqs), FadeIn(number_labels[0], DOWN), FadeIn(number_labels[1]), FadeIn(number_labels[2], UP), ) self.wait() self.play(Write(rhss)) self.wait(2) self.play( LaggedStartMap( FadeOut, VGroup(*number_labels, *vert_eqs, *rhss, *implies), ), ShowCreation(cube.edges, lag_ratio=0.1), LaggedStartMap(FadeInFromLarge, cube.verts, lambda m: (m, 0.2)), ) self.add(cube) new_verts, color_labels = get_colored_vertices(mod3_strategy) true_trees = trees.saved_state self.play( Transform(cube.verts, new_verts), FadeIn(color_labels), FadeOut(trees), FadeOut(want_label) ) self.play(FadeIn(true_trees)) self.wait() # Count colors for edge in cube.edges: edge.insert_n_curves(10) red_total = Integer(height=0.6) red_total.next_to(want_rect, UP) red_total.set_color(RED) self.play(FadeIn(red_total)) all_label_rects = VGroup() for n in range(8): tree = true_trees[n] vert = cube.verts[n] neighbor_highlights = VGroup() new_edges = VGroup() label_rects = VGroup() for mask, label in zip([1, 2, 4], tree.labels): neighbor = cube.verts[n ^ mask] edge = Line(vert, neighbor, buff=0) edge.set_stroke(YELLOW, 5) edge.insert_n_curves(10) new_edges.add(edge) if neighbor.get_color() == Color(RED): circ = Circle() circ.set_stroke(YELLOW, 3) circ.replace(neighbor) neighbor_highlights.add(circ) rect = SurroundingRectangle(label, buff=0.025) rect.set_stroke(YELLOW, 2) label_rects.add(rect) new_edges.apply_depth_test() new_edges.shift(0.01 * OUT) new_tree_edges = tree.edges.copy() new_tree_edges.set_stroke(YELLOW, 3) new_tree_edges.shift(0.01 * OUT) self.play( *map(ShowCreation, [*new_edges, *new_tree_edges]), ) for highlight, rect in zip(neighbor_highlights, label_rects): self.play( FadeInFromLarge(highlight, 1.2), FadeInFromLarge(rect, 1.2), run_time=0.25 ) red_total.increment_value() self.wait(0.25) self.play( FadeOut(neighbor_highlights), FadeOut(new_edges), FadeOut(new_tree_edges), ) all_label_rects.add(*label_rects) self.wait() # Show count to 8 new_verts = get_colored_vertices([-1] * 8)[0] self.play( FadeOut(true_trees), FadeOut(all_label_rects), FadeOut(red_total), FadeOut(color_labels), Transform(cube.verts, new_verts), ) self.play(FadeIn(trees)) label_rects = VGroup() for tree in trees: rect = SurroundingRectangle(tree.labels[0], buff=0.025) rect.match_style(all_label_rects[0]) label_rects.add(rect) self.play( ShowIncreasingSubsets(label_rects, rate_func=linear), UpdateFromFunc( red_total, lambda m, lr=label_rects: m.set_value(len(lr)) ) ) self.wait() # Show red corners r_verts = SGroup(cube.verts[3], cube.verts[4]).copy() r_labels = VGroup() r_edge_groups = VGroup() for r_vert in r_verts: r_label = OldTex("R") r_label.set_color(RED) r_label.next_to(r_vert, UR, buff=0) r_labels.add(r_label) r_vert.set_height(tall_vert_height) r_vert.set_color(RED) edges = VGroup() for edge in r_vert.edges: to_r_edge = edge.copy() to_r_edge.reverse_points() to_r_edge.set_stroke(YELLOW, 3) to_r_edge.shift(0.01 * OUT) edges.add(to_r_edge) edges.apply_depth_test() r_edge_groups.add(edges) self.play( LaggedStartMap(FadeInFromLarge, r_verts), LaggedStartMap(FadeInFromLarge, r_labels), run_time=1, ) self.wait() for edges in r_edge_groups: self.play(ShowCreationThenDestruction(edges, lag_ratio=0.1)) self.wait() rhs = OldTex("=", "3", "\\, (\\text{\\# Red corners})") rhs[2].set_color(RED) rhs.match_height(red_total) rhs[:2].match_height(red_total, about_edge=RIGHT) rhs.next_to(red_total, RIGHT) self.play(Write(rhs)) self.wait() three = rhs[1] three.generate_target() three.target.move_to(red_total, RIGHT) over = OldTex("/") over.match_height(three) over.next_to(three.target, LEFT, MED_SMALL_BUFF) self.play( MoveToTarget(three, path_arc=90 * DEGREES), red_total.next_to, over, LEFT, MED_SMALL_BUFF, FadeIn(over, UR), rhs[2].move_to, three, LEFT, ) self.wait() np_label = OldTexText("Not possible!") np_label.set_height(0.6) np_label.next_to(rhs, RIGHT, LARGE_BUFF) self.play(Write(np_label)) self.wait() class TryTheProofYourself(TeacherStudentsScene): def construct(self): self.teacher_says( "Can you predict\\\\the proof?", target_mode="hooray", bubble_config={ "height": 3, "width": 3, }, ) self.teacher.bubble.set_fill(opacity=0) self.play_student_changes( "pondering", "thinking", "confused", look_at=self.screen, ) self.wait(3) self.play_student_changes("thinking", "pondering", "erm", look_at=self.screen) self.wait(4) self.play_student_changes("tease", "pondering", "thinking", look_at=self.screen) self.wait(5) class HighDimensionalCount(ThreeDScene): def construct(self): # Definitions N = 6 colors = [RED, GREEN, BLUE_D, YELLOW, PINK, TEAL] coords = np.array([0, 1, 1, 1, 0, 0]) # Add chess board board = Chessboard(shape=(2, 3)) board.set_height(2) board.to_corner(UL) grid = NumberPlane( x_range=(0, 3), y_range=(0, 2), faded_line_ratio=0 ) grid.match_height(board) grid.match_width(board, stretch=True) grid.next_to(board, OUT, 1e-8) grid.set_gloss(0.5) coins = CoinsOnBoard(board, coin_config={"numeric_labels": True}) coins.flip_by_bools(coords) coin_labels = VGroup() for i, coin in zip(coords, coins): coin_labels.add(coin.labels[1 - i]) self.play( ShowCreationThenFadeOut(grid, lag_ratio=0.1), FadeIn(board), FadeIn(coins, lag_ratio=0.1), run_time=2 ) # Setup corners def get_vert(height=0.4, color=RED): return get_vertex_sphere(height, color) def get_vert_label(coords): args = ["("] for coord in coords: args.append(str(coord)) args.append(",") args[-1] = ")" return OldTex(*args) def get_board_with_highlights(n, height=1, N=N, colors=colors): board = VGroup(*[Square() for x in range(N)]) board.arrange_in_grid(2, 3, buff=0) board.set_fill(GREY_E, 1) board.set_stroke(WHITE, 1) board.set_height(height) board[n].set_fill(colors[n]) return board vert = get_vert() vert_label = get_vert_label(coords) vert_board = get_board_with_highlights(0) vert_label.next_to(vert, LEFT) vert_board.next_to(vert_label, DOWN, MED_LARGE_BUFF) neighbors = SGroup() for color in colors: neighbors.add(get_vert(color=color)) neighbors.arrange(DOWN, buff=0.75) neighbors.next_to(vert, RIGHT, buff=2) neighbor_labels = VGroup() edges = VGroup() neighbor_boards = VGroup() for n, neighbor in enumerate(neighbors): edge = Line( vert.get_center(), neighbor.get_center(), buff=vert.get_height() / 2, ) new_coords = list(coords) new_coords[n] ^= 1 label = get_vert_label(new_coords) label.next_to(neighbor, RIGHT) label.add(SurroundingRectangle(label[2 * n + 1], buff=0.05)) n_board = get_board_with_highlights(n, height=0.7) n_board.next_to(label, RIGHT) neighbor_boards.add(n_board) edges.add(edge) neighbor_labels.add(label) vertex_group = Group( vert_board, vert_label, vert, edges, neighbors, neighbor_labels, neighbor_boards ) vertex_group.to_corner(DL) # Show coords with states cl_mover = coin_labels.copy() cl_mover.generate_target() for m1, m2 in zip(cl_mover.target, vert_label[1::2]): m1.replace(m2) self.play( MoveToTarget(cl_mover), ) self.play( FadeIn(vert_label), FadeOut(cl_mover) ) self.play(FadeIn(vert_board)) self.wait() self.play( ShowIncreasingSubsets(neighbor_labels), ShowCreation(edges), ) self.wait() self.play(LaggedStartMap( TransformFromCopy, neighbor_boards, lambda m, b=vert_board: (b, m) )) self.wait() # Show one vertex self.play(FadeInFromLarge(vert)) self.play(LaggedStartMap( TransformFromCopy, neighbors, lambda m, v=vert: (v, m) )) self.wait() # Isolate vertex edges.apply_depth_test() tree = Group(vert, edges, neighbors) tree.generate_target() tree.target[0].scale(0.5) tree.target[2].scale(0.5) tree.target[2].arrange(DOWN, buff=0) tree.target[2].next_to(vert, RIGHT, MED_LARGE_BUFF) for edge, nv in zip(tree.target[1], tree.target[2]): new_edge = Line( vert.get_center(), nv.get_center(), ) edge.become(new_edge) edge.set_stroke(WHITE, 2) tree.target.rotate(-90 * DEGREES) tree.target.center() short_label = vert_label[1::2] short_label.generate_target() short_label.target.arrange(RIGHT, buff=SMALL_BUFF) short_label.target.match_width(tree.target) short_label.target.next_to(tree.target, UP) short_label.target.set_fill(GREY_A) self.play( MoveToTarget(tree), MoveToTarget(short_label), LaggedStartMap(FadeOut, Group( vert_label[0::2], vert_board, *neighbor_labels, *neighbor_boards, *board, *coins, )), run_time=2, ) tree.add(short_label) # Show all vertices def get_bit_string(n, template=short_label): bits = VGroup(*map(Integer, int_to_bit_coords(n, min_dim=6))) bits.arrange(RIGHT, buff=0.075) bits.match_height(template) bits.set_color(GREY_A) return bits new_trees = Group() for n in [0, 1, 62, 63]: new_tree = tree.copy() bits = get_bit_string(n) bits.move_to(new_tree[3]) new_tree.replace_submobject(3, bits) new_trees.add(new_tree) for new_tree, color in zip(new_trees, [YELLOW, GREEN, RED, BLUE_D]): new_tree[0].set_color(color) new_trees.arrange(RIGHT, buff=MED_LARGE_BUFF) new_trees.move_to(tree) new_trees[:2].to_edge(LEFT) new_trees[2:].to_edge(RIGHT) dots = VGroup(*[Tex("\\dots") for x in range(2)]) dots.scale(2) dots[0].move_to(Group(new_trees[1], tree)) dots[1].move_to(Group(new_trees[2], tree)) top_brace = Brace(new_trees, UP, buff=MED_LARGE_BUFF) total_label = top_brace.get_text("$2^n$ total vertices", buff=MED_LARGE_BUFF) low_brace = Brace(tree, DOWN) neighbors_label = low_brace.get_text("n neighbors") self.play( GrowFromCenter(low_brace), Write(neighbors_label, run_time=1) ) self.wait() self.play( GrowFromCenter(dots), GrowFromCenter(top_brace), LaggedStartMap( TransformFromCopy, new_trees, lambda m, t=tree: (t, m) ), Write(total_label, run_time=1), run_time=2, ) self.wait() # Count red neighbors middle_tree = tree frame = self.camera.frame self.play(frame.move_to, UP) count = Integer(1) count.set_color(RED) count.scale(1.5) count.next_to(total_label, UP, LARGE_BUFF, aligned_edge=LEFT) two_to_n_label = OldTex("2^n") two_to_n_label.scale(1.5) two_to_n_label.set_color(RED) two_to_n_label.move_to(count, LEFT) n_arrows = VGroup() for tree in [*new_trees[:2], middle_tree, *new_trees[2:]]: arrow = Vector( [-1, -2, 0], tip_config={"width": 0.2, "length": 0.2} ) arrow.match_height(tree[1]) arrow.next_to(tree[2][0], UR, buff=0) arrow.set_color(RED) n_arrows.add(arrow) self.add(n_arrows[0], count) self.wait() self.add(n_arrows[1]) count.increment_value() self.wait() self.play( ChangeDecimalToValue(count, 63, rate_func=rush_into), LaggedStartMap(FadeIn, n_arrows[2:], lag_ratio=0.5), run_time=3 ) self.remove(count) self.add(two_to_n_label) self.wait() rhs = OldTex("=", "n", "\\cdot", "(\\text{\\# Red vertices})") rhs.scale(1.5) rhs.next_to(two_to_n_label, RIGHT) rhs.shift(0.05 * DOWN) rhs.set_color_by_tex("Red", RED) highlighted_edges = VGroup(*middle_tree[1], new_trees[2][1]).copy() highlighted_edges.set_stroke(YELLOW, 3) highlighted_edges.shift(0.01 * OUT) edge_anim = ShowCreationThenFadeOut( highlighted_edges, lag_ratio=0.3 ) self.play(edge_anim) self.play(Write(rhs), run_time=1) self.play(edge_anim) self.wait(2) # Conclusion pairs = VGroup(VGroup(OldTex("n"), OldTex("2^n"))) pairs.set_color(YELLOW) for n in range(1, 10): pairs.add(VGroup(Integer(n), Integer(2**n))) for pair in pairs: pair.arrange(RIGHT, buff=0.75, aligned_edge=DOWN) line = Line(LEFT, RIGHT) line.set_stroke(WHITE, 1) line.set_width(2) line.next_to(pair, DOWN, aligned_edge=LEFT) line.shift(SMALL_BUFF * LEFT) pair.add(line) pairs.add(pair) pairs.arrange(DOWN, aligned_edge=LEFT, buff=0.25) pairs.set_height(7) pairs.to_edge(LEFT) pairs.shift(UP) marks = VGroup() for n, pair in zip(it.count(1), pairs[1:]): if sum(int_to_bit_coords(n)) == 1: mark = Checkmark() else: mark = Exmark() mark.move_to(pair[1], LEFT) mark.shift(RIGHT) marks.add(mark) v_line = Line(UP, DOWN) v_line.set_height(7) v_line.set_stroke(WHITE, 1) v_line.set_x((pairs[0][0].get_right() + pairs[0][1].get_left())[0] / 2) v_line.match_y(pairs) pairs.add(v_line) new_trees.generate_target() new_trees.target[:2].move_to(middle_tree, RIGHT) shift_vect = new_trees.target[0].get_center() - new_trees[0].get_center() self.play( MoveToTarget(new_trees), top_brace.match_width, new_trees.target, {"about_edge": RIGHT}, total_label.shift, shift_vect * 0.5, n_arrows[:2].shift, shift_vect, FadeOut(middle_tree, RIGHT), FadeOut(n_arrows[2], RIGHT), FadeOut(dots[0], 2 * RIGHT), Write(pairs) ) self.play(LaggedStartMap( FadeIn, marks, lambda m: (m, 0.2 * LEFT), lag_ratio=0.4, run_time=5, )) self.wait() class SimpleRect(Scene): def construct(self): rect = SurroundingRectangle( VGroup(Integer(4), Integer(16), Integer(0)).arrange(RIGHT, MED_LARGE_BUFF), ) self.play(ShowCreation(rect)) self.wait(2) self.play(FadeOut(rect)) class WhenIsItHopeless(Scene): def construct(self): boards = Group( Chessboard(shape=(1, 3)), Chessboard(shape=(2, 2)), Chessboard(shape=(2, 3)), Chessboard(shape=(2, 3)), Chessboard(shape=(2, 4)), Chessboard(shape=(2, 4)), Chessboard(shape=(3, 3)), Chessboard(shape=(3, 4)), Chessboard(shape=(3, 4)), Chessboard(shape=(3, 4)), ) last_board = None last_coins = None last_words = None for n, board in zip(it.count(3), boards): board.scale(1 / board[0].get_height()) coins = CoinsOnBoard(board) coins.flip_at_random() diff = len(board) - n if diff > 0: board[-diff:].set_opacity(0) coins[-diff:].set_opacity(0) if sum(int_to_bit_coords(n)) == 1: words = OldTexText("Maybe possible") words.set_color(GREEN) else: words = OldTexText("Futile!") words.set_color(RED) words.scale(1.5) words.next_to(board, UP, MED_LARGE_BUFF) if n == 3: self.play( FadeIn(board), FadeIn(coins), FadeIn(words, DOWN), ) else: self.play( ReplacementTransform(last_board, board), ReplacementTransform(last_coins, coins), FadeOut(last_words), FadeIn(words, DOWN), ) self.wait() last_board = board last_coins = coins last_words = words class FourDCubeColoringFromTrees(ThreeDScene): def construct(self): # Camera stuffs frame = self.camera.frame light = self.camera.light_source light.move_to([-25, -20, 20]) # Setup cube colors = [RED, GREEN, BLUE_D, YELLOW] cube = self.get_hypercube() for n, vert in enumerate(cube.verts): code = boolian_linear_combo(int_to_bit_coords(n, 4)) cube.verts[n].set_color(colors[code]) # Create trees trees = Group() original_trees = Group() for vert in cube.verts: tree = Group( vert, vert.edges, vert.neighbors, ).copy() original = tree.copy() original[0].set_color(GREY) original[0].scale(0) original_trees.add(original) trees.add(tree) for tree in trees: tree[0].set_color(GREY) tree[0].rotate(90 * DEGREES, LEFT) sorted_verts = Group(*tree[2]) sorted_verts.submobjects.sort(key=lambda m: m.get_color().hex) sorted_verts.arrange(DOWN, buff=SMALL_BUFF) sorted_verts.next_to(tree[0], RIGHT, buff=0.75) for edge, neighbor in zip(tree[1], tree[2]): edge.become(Line3D( tree[0].get_center(), neighbor.get_center(), resolution=edge.resolution, )) neighbor.rotate(90 * DEGREES, LEFT) trees.arrange_in_grid(4, 4, buff=MED_LARGE_BUFF) for i in range(4): trees[i::4].shift(0.5 * i * RIGHT) trees.center() trees.set_height(6) trees.rotate(PI / 2, RIGHT) trees.move_to(10 * LEFT, LEFT) frame.set_phi(90 * DEGREES) frame.move_to(5 * LEFT) self.add(trees) self.wait() # Show transition anims = [] for tree, original in zip(trees, original_trees): anims.append(Transform(tree, original)) self.play( frame.set_euler_angles, 20 * DEGREES, 70 * DEGREES, frame.move_to, ORIGIN, LaggedStart(*anims, lag_ratio=0.2), run_time=8, ) self.remove(trees) self.add(cube) frame.add_updater(lambda m, dt: m.increment_theta(2 * dt * DEGREES)) self.wait(30) def get_hypercube(self, dim=4, width=4): hc_points = self.get_hypercube_points(dim, width) cube = Group() cube.verts = SGroup() cube.edges = SGroup() cube.add(cube.verts, cube.edges) for point in hc_points: vert = get_vertex_sphere(resolution=(25, 13)) vert.rotate(PI / 2, UP) vert.move_to(point) cube.verts.add(vert) vert.edges = SGroup() vert.neighbors = SGroup() for n in range(2**dim): for power in range(dim): k = n ^ (1 << power) edge = Line3D( hc_points[n], hc_points[k], width=0.05, resolution=(31, 31) ) cube.edges.add(edge) cube.verts[n].edges.add(edge) cube.verts[n].neighbors.add(cube.verts[k]) return cube def get_hypercube_points(self, dim=4, width=4): all_coords = [ int_to_bit_coords(n, dim).astype(float) for n in range(2**dim) ] vertex_holder = Mobject() vertex_holder.set_points([ sum([c * v for c, v in zip(reversed(coords), [RIGHT, UP, OUT])]) for coords in all_coords ]) vertex_holder.center() if dim == 4: vertex_holder.get_points()[8:] *= 2 vertex_holder.set_width(width) return vertex_holder.get_points() class IntroduceHypercube(FourDCubeColoringFromTrees): def construct(self): # Camera stuffs frame = self.camera.frame light = self.camera.light_source light.move_to([-25, -20, 20]) # Setup cubes cubes = [ self.get_hypercube(dim=d) for d in range(5) ] def reconnect_edges(cube): for vert in cube.verts: for edge, neighbor in zip(vert.edges, vert.neighbors): edge.become(Line3D( vert.get_center(), neighbor.get_center(), resolution=edge.resolution )) # Show increasing dimensions label = VGroup(Integer(0), OldTex("D")) label.arrange(RIGHT, buff=SMALL_BUFF) label.scale(1.5) label.to_edge(UP) label.fix_in_frame() def get_cube_intro_anim(n, cubes=cubes, reconnect_edges=reconnect_edges, label=label): if n == 0: return GrowFromCenter(cubes[n]) self.remove(cubes[n - 1]) cubes[n].save_state() for v1, v2 in zip(cubes[n].verts, it.cycle(cubes[n - 1].verts)): v1.move_to(v2) reconnect_edges(cubes[n]) if n == 1: cubes[n].edges.scale(0) return AnimationGroup( Restore(cubes[n]), ChangeDecimalToValue(label[0], n), ) self.play( FadeIn(label, DOWN), get_cube_intro_anim(0) ) self.wait() for n in [1, 2]: self.play(get_cube_intro_anim(n)) self.wait() self.play( get_cube_intro_anim(3), ApplyMethod( frame.set_euler_angles, -20 * DEGREES, 75 * DEGREES, run_time=3 ) ) frame.add_updater(lambda m, dt: m.increment_theta(dt * DEGREES)) self.wait(4) # Flatten cube flat_cube = self.get_hypercube(3) for n, vert in enumerate(flat_cube.verts): point = vert.get_center() if n < 4: point *= 1.5 else: point *= 0.75 point[2] = 0 vert.move_to(point) reconnect_edges(flat_cube) plane = NumberPlane(x_range=(-10, 10), y_range=(-10, 10), faded_line_ratio=0) plane.set_opacity(0.25) plane.apply_depth_test() plane.axes.shift(0.01 * OUT) plane.shift(0.02 * IN) cubes[3].save_state() self.add(cubes[3], plane) self.play( FadeIn(plane, run_time=2), Transform(cubes[3], flat_cube, run_time=2), ) self.wait(7) self.play( Restore(cubes[3], run_time=2), FadeOut(plane) ) self.play(get_cube_intro_anim(4), run_time=3) self.wait(10) # Highlight some neighbor groups colors = [RED, GREEN, BLUE_D, YELLOW] for x in range(6): vert = random.choice(cubes[4].verts) neighbors = vert.neighbors.copy() neighbors.save_state() neighbors.generate_target() new_edges = VGroup() for neighbor, color in zip(neighbors.target, colors): neighbor.set_color(color) edge = Line( vert.get_center(), neighbor.get_center(), buff=vert.get_height() / 2, ) edge.set_stroke(color, 5) new_edges.add(edge) self.remove(vert.neighbors) self.play( ShowCreation(new_edges, lag_ratio=0.2), MoveToTarget(neighbors), ) self.wait(1) self.play( FadeOut(new_edges), Restore(neighbors), ) self.remove(neighbors) self.add(vert.neighbors) # Show valid coloring cubes[4].generate_target() for n, vert in enumerate(cubes[4].target[0]): code = boolian_linear_combo(int_to_bit_coords(n, 4)) vert.set_color(colors[code]) self.play(MoveToTarget(cubes[4], lag_ratio=0.2, run_time=3)) self.wait(15) # Animations for Matt class WantAdditionToBeSubtraction(ThreeDScene): def construct(self): # Add sum coins = CoinsOnBoard( Chessboard(shape=(1, 4)), coin_config={"numeric_labels": True}, ) for coin in coins[0], coins[2]: coin.flip() coefs = VGroup(*[Tex(f"X_{i}") for i in range(len(coins))]) full_sum = Group() to_fade = VGroup() for coin, coef in zip(coins, coefs): coin.set_height(0.7) coef.set_height(0.5) summand = Group(coin, OldTex("\\cdot"), coef, OldTex("+")) to_fade.add(*summand[1::2]) summand.arrange(RIGHT, buff=0.2) full_sum.add(summand) full_sum.add(OldTex("\\dots")) full_sum.arrange(RIGHT, buff=0.2) to_fade.add(full_sum[-1]) some_label = OldTexText("Some kind of ``numbers''") some_label.next_to(full_sum, DOWN, buff=2) arrows = VGroup(*[ Arrow(some_label.get_top(), coef.get_bottom()) for coef in coefs ]) for coin in coins: coin.save_state() coin.rotate(90 * DEGREES, UP) coin.set_opacity(0) self.play( LaggedStartMap(Restore, coins, lag_ratio=0.3), run_time=1 ) self.play( FadeIn(to_fade), LaggedStartMap(FadeInFromPoint, coefs, lambda m: (m, some_label.get_top())), LaggedStartMap(GrowArrow, arrows), Write(some_label, run_time=1) ) self.wait() self.play(FadeOut(some_label), FadeOut(arrows)) # Show a flip add_label = OldTex("+X_2", color=GREEN) sub_label = OldTex("-X_2", color=RED) for label in add_label, sub_label: label.next_to(coins[2], UR) label.match_height(coefs[2]) self.play( FlipCoin(coins[2]), FadeIn(label, 0.5 * DOWN) ) self.play(FadeOut(label)) # What we want want_label = OldTexText("Want: ", "$X_i = -X_i$") eq = OldTexText("$X_i + X_i = 0$") want_label.next_to(full_sum, DOWN, LARGE_BUFF) eq.next_to(want_label[1], DOWN, aligned_edge=LEFT) self.play(FadeIn(want_label)) self.wait() self.play(FadeIn(eq, UP)) self.wait() class BitVectorSum(ThreeDScene): def construct(self): # Setup board = Chessboard(shape=(1, 4)) board.set_height(1) coins = CoinsOnBoard(board, coin_config={"numeric_labels": True}) coins[2].flip() all_coords = [np.array([b0, b1]) for b0, b1 in it.product(range(2), range(2))] bit_vectors = VGroup(*[ IntegerMatrix(coords.reshape((2, 1))).set_height(1) for coords in all_coords ]) bit_vectors.arrange(RIGHT, buff=2) bit_vectors.to_edge(UP) bit_vectors.set_stroke(BLACK, 4, background=True) arrows = VGroup( Arrow(board[0].get_corner(UL), bit_vectors[0].get_corner(DR)), Arrow(board[1].get_corner(UP), bit_vectors[1].get_corner(DOWN)), Arrow(board[2].get_corner(UP), bit_vectors[2].get_corner(DOWN)), Arrow(board[3].get_corner(UR), bit_vectors[3].get_corner(DL)), ) # Show vectors self.add(board) self.add(coins) for arrow, vector in zip(arrows, bit_vectors): self.play( GrowArrow(arrow), FadeInFromPoint(vector, arrow.get_start()), ) self.wait() # Move coins coin_copies = coins.copy() cdots = VGroup() plusses = VGroup() for cc, vector in zip(coin_copies, bit_vectors): dot = OldTex("\\cdot") dot.next_to(vector, LEFT, MED_SMALL_BUFF) cdots.add(dot) plus = OldTex("+") plus.next_to(vector, RIGHT, MED_SMALL_BUFF) plusses.add(plus) cc.next_to(dot, LEFT, MED_SMALL_BUFF) plusses[-1].set_opacity(0) for coin, cc, dot, plus in zip(coins, coin_copies, cdots, plusses): self.play( TransformFromCopy(coin, cc), Write(dot), ) self.play(Write(plus)) self.wait() # Show sum eq = OldTex("=") eq.move_to(plusses[-1]) def get_rhs(coins=coins, bit_vectors=bit_vectors, all_coords=all_coords, eq=eq): bit_coords = sum([ (b * coords) for coords, b in zip(all_coords, coins.get_bools()) ]) % 2 n = bit_coords_to_int(bit_coords) result = bit_vectors[n].copy() result.next_to(eq, RIGHT) result.n = n return result def get_rhs_anim(rhs, bit_vectors=bit_vectors): bv_copies = bit_vectors.copy() bv_copies.generate_target() for bv in bv_copies.target: bv.move_to(rhs) bv.set_opacity(0) bv_copies.target[rhs.n].set_opacity(1) return AnimationGroup( MoveToTarget(bv_copies, remover=True), ShowIncreasingSubsets(Group(rhs), int_func=np.floor) ) rhs = get_rhs() mod2_label = OldTexText("(Add mod 2)") mod2_label.next_to(rhs, DOWN, MED_LARGE_BUFF) mod2_label.to_edge(RIGHT) self.play( Write(eq), get_rhs_anim(rhs), FadeIn(mod2_label), FadeOut(board), FadeOut(coins), FadeOut(arrows), ) self.wait(2) # Show some flips for x in range(8): i = random.randint(0, 3) rect = SurroundingRectangle(Group(coin_copies[i], bit_vectors[i])) old_rhs = rhs coins[i].flip() rhs = get_rhs() self.play( ShowCreation(rect), FlipCoin(coin_copies[i]), FadeOut(old_rhs, RIGHT), FadeIn(rhs, LEFT), ) self.play(FadeOut(rect)) self.wait(2) class ExampleSquareAsBinaryNumber(Scene): def construct(self): # Setup board = Chessboard() nums = VGroup() bin_nums = VGroup() for n, square in enumerate(board): bin_num = VGroup(*[ Integer(int(b)) for b in int_to_bit_coords(n, min_dim=6) ]) bin_num.arrange(RIGHT, buff=SMALL_BUFF) bin_num.set_width((square.get_width() * 0.8)) num = Integer(n) num.set_height(square.get_height() * 0.4) for mob in num, bin_num: mob.move_to(square, OUT) mob.set_stroke(BLACK, 4, background=True) num.generate_target() num.target.replace(bin_num, stretch=True) num.target.set_opacity(0) bin_num.save_state() bin_num.replace(num, stretch=True) bin_num.set_opacity(0) nums.add(num) bin_nums.add(bin_num) # Transform to binary self.add(board, nums) self.wait() original_nums = nums.copy() self.play(LaggedStart(*[ AnimationGroup(MoveToTarget(num), Restore(bin_num)) for num, bin_num in zip(nums, bin_nums) ]), lag_ratio=0.1) self.remove(nums) nums = original_nums self.wait(2) self.play( bin_nums.set_stroke, None, 0, bin_nums.set_opacity, 0.1, ) self.wait() # Count n = 43 self.play( board[n].set_color, MAROON_E, Animation(bin_nums[n]), ) last = VMobject() shown_nums = VGroup() for k in [0, 8, 16, 24, 32, 40, 41, 42, 43]: nums[k].set_fill(YELLOW) self.add(nums[k]) self.play(last.set_fill, WHITE, run_time=0.5) last = nums[k] shown_nums.add(last) if k == 40: self.wait() self.wait() self.play(LaggedStartMap(FadeOut, shown_nums[:-1])) self.wait() self.play( FadeOut(last), bin_nums[n].set_opacity, 1, bin_nums[n].set_fill, YELLOW ) self.wait() class SkipSkipYesYes(Scene): def construct(self): board = Chessboard() board.next_to(ORIGIN, DOWN) words = VGroup( OldTexText("Skip"), OldTexText("Skip"), OldTexText("Yes"), OldTexText("Yes"), ) words.add(*words.copy()) words.set_width(board[0].get_width() * 0.8) for word, square in zip(words, board): word.move_to(square) word.set_y(0, UP) for group in words[:4], words[4:]: self.play(ShowIncreasingSubsets(group, rate_func=double_smooth, run_time=2)) self.play(FadeOut(group)) self.wait() class ShowCurrAndTarget(Scene): CONFIG = { "bit_strings": [ "011010", "110001", "101011", ] } def construct(self): words = VGroup( OldTexText("Current: "), OldTexText("Need to\\\\change:"), OldTexText("Target: "), ) words.arrange(DOWN, buff=0.75, aligned_edge=RIGHT) words.to_corner(UL) def get_bit_aligned_bit_string(bit_coords): result = VGroup(*[Integer(int(b)) for b in bit_coords]) for i, bit in enumerate(result): bit.move_to(ORIGIN, LEFT) bit.shift(i * RIGHT * 0.325) result.set_stroke(BLACK, 4, background=True) return result bit_strings = VGroup(*[ get_bit_aligned_bit_string(bs) for bs in self.bit_strings ]) for word, bs in zip(words, bit_strings): bs.next_to(word.family_members_with_points()[-1], RIGHT, aligned_edge=DOWN) words[1].set_fill(YELLOW) bit_strings[1].set_fill(YELLOW) self.add(words[::2]) self.add(bit_strings[::2]) self.wait() self.play(FadeIn(words[1])) curr_rect = None for n in reversed(range(6)): rect = SurroundingRectangle(Group( bit_strings[0][n], bit_strings[2][n], buff=0.05, )) rect.stretch(0.9, 0) rect.set_stroke(WHITE, 1) if curr_rect is None: curr_rect = rect self.play(ShowCreation(curr_rect)) else: self.play(Transform(curr_rect, rect, run_time=0.25)) self.wait(0.75) self.play(FadeIn(bit_strings[1][n])) self.play(FadeOut(curr_rect)) class ShowCurrAndTargetAlt(ShowCurrAndTarget): CONFIG = { "bit_strings": [ "110100", "010101", "100001", ] } class EulerDiagram(Scene): def construct(self): colors = [RED, GREEN, BLUE] vects = compass_directions(3, UP) circles = VGroup(*[ Circle( radius=2, fill_color=color, stroke_color=color, fill_opacity=0.5, stroke_width=3, ).shift(1.2 * vect) for vect, color in zip(vects, colors) ]) bit_coords = list(map(int_to_bit_coords, range(8))) bit_strings = VGroup(*map(get_bit_string, bit_coords)) bit_strings.center() r1 = 2.2 r2 = 1.4 bit_strings[0].next_to(circles[0], LEFT).shift(UP) bit_strings[1].shift(r1 * vects[0]) bit_strings[2].shift(r1 * vects[1]) bit_strings[3].shift(r2 * (vects[0] + vects[1])) bit_strings[4].shift(r1 * vects[2]) bit_strings[5].shift(r2 * (vects[0] + vects[2])) bit_strings[6].shift(r2 * (vects[1] + vects[2])) self.add(circles) for circle in circles: circle.save_state() for coords, bstring in zip(bit_coords[1:], bit_strings[1:]): for circ, coord in zip(circles, reversed(coords)): circ.generate_target() if coord: circ.target.become(circ.saved_state) else: circ.target.set_opacity(0.1) self.play( FadeIn(bstring), *map(MoveToTarget, circles), run_time=0.25, ) self.wait(0.75) self.wait() self.play(FadeIn(bit_strings[0], DOWN)) self.wait() class ShowBoardRegions(ThreeDScene): def construct(self): # Setup board = Chessboard() nums = VGroup() pre_bin_nums = VGroup() bin_nums = VGroup() for n, square in enumerate(board): bin_num = VGroup(*[ Integer(int(b), fill_color=GREY_A) for b in int_to_bit_coords(n, min_dim=6) ]) bin_num.arrange(RIGHT, buff=SMALL_BUFF) bin_num.set_width((square.get_width() * 0.8)) num = Integer(n) num.set_height(square.get_height() * 0.4) for mob in num, bin_num: mob.move_to(square, OUT) mob.set_stroke(BLACK, 4, background=True) bin_num.align_to(square, DOWN) bin_num.shift(SMALL_BUFF * UP) pre_bin_num = num.copy() pre_bin_num.generate_target() pre_bin_num.target.replace(bin_num, stretch=True) pre_bin_num.target.set_opacity(0) num.generate_target() num.target.scale(0.7) num.target.align_to(square, UP) num.target.shift(SMALL_BUFF * DOWN) bin_num.save_state() bin_num.replace(num, stretch=True) bin_num.set_opacity(0) nums.add(num) bin_nums.add(bin_num) pre_bin_nums.add(pre_bin_num) # Transform to binary self.add(board) self.play( ShowIncreasingSubsets(nums, run_time=4, rate_func=bezier([0, 0, 1, 1])) ) self.wait() self.play( LaggedStart(*[ AnimationGroup( MoveToTarget(num), MoveToTarget(pbn), Restore(bin_num), ) for num, pbn, bin_num in zip(nums, pre_bin_nums, bin_nums) ], lag_ratio=1.5 / 64), ) self.remove(pre_bin_nums) self.wait(2) # Build groups to highlight one_groups = VGroup() highlights = VGroup() for i in reversed(range(6)): one_group = VGroup() highlight = VGroup() for bin_num, square in zip(bin_nums, board): boundary_square = Square() # boundary_square.set_stroke(YELLOW, 4) boundary_square.set_stroke(BLUE, 4) boundary_square.set_fill(BLUE, 0.5) boundary_square.replace(square) boundary_square.move_to(square, OUT) bit = bin_num[i] if bit.get_value() == 1: one_group.add(bit) highlight.add(boundary_square) one_group.save_state() one_groups.add(one_group) highlights.add(highlight) # Highlight hit_groups curr_highlight = None for one_group, highlight in zip(one_groups, highlights): one_group.generate_target() one_group.target.set_fill(YELLOW) one_group.target.set_stroke(YELLOW, 2) if curr_highlight is None: self.play(MoveToTarget(one_group)) self.wait() self.play(LaggedStartMap(DrawBorderThenFill, highlight, lag_ratio=0.1, run_time=3)) curr_highlight = highlight else: self.add(one_group, curr_highlight) self.play( MoveToTarget(one_group), Transform(curr_highlight, highlight) ) self.wait() self.play(Restore(one_group)) self.wait() self.play(FadeOut(curr_highlight)) class ShowFinalStrategy(Scene): CONFIG = { "show_with_lines": False, } def construct(self): # Setup board and such board = Chessboard() board.to_edge(RIGHT) coins = CoinsOnBoard(board, coin_config={"numeric_labels": True}) coins.flip_by_message("3b1b :)") encoding_lines = VGroup(*[Line(ORIGIN, 0.5 * RIGHT) for x in range(6)]) encoding_lines.arrange(LEFT, buff=SMALL_BUFF) encoding_lines.next_to(board, LEFT, LARGE_BUFF) encoding_lines.shift(UP) code_words = OldTexText("Encoding") code_words.next_to(encoding_lines, DOWN) add_words = OldTexText("Check the parity\\\\of these coins") add_words.next_to(board, LEFT, LARGE_BUFF, aligned_edge=UP) self.add(board, coins) self.add(encoding_lines) self.add(code_words) # Set up groups fade_groups = Group() line_groups = VGroup() mover_groups = VGroup() count_mobs = VGroup() one_groups = VGroup() bits = VGroup() for i in range(6): bit = Integer(0) bit.next_to(encoding_lines[i], UP, SMALL_BUFF) bits.add(bit) count_mob = Integer(0) count_mob.set_color(RED) count_mob.next_to(add_words, DOWN, MED_SMALL_BUFF) count_mobs.add(count_mob) line_group = VGroup() fade_group = Group() mover_group = VGroup() one_rect_group = VGroup() count = 0 for n, coin in enumerate(coins): if bool(n & (1 << i)): line_group.add(Line( coin.get_center(), bit.get_center(), )) mover_group.add(coin.labels[1 - int(coin.is_heads())].copy()) if coin.is_heads(): one_rect_group.add(SurroundingRectangle(coin)) count += 1 else: fade_group.add(coin) bit.set_value(count % 2) fade_group.save_state() line_group.set_stroke(BLUE, width=1, opacity=0.5) fade_groups.add(fade_group) line_groups.add(line_group) mover_groups.add(mover_group) one_groups.add(one_rect_group) # Animate for lines, fades, movers, og, cm, bit in zip(line_groups, fade_groups, mover_groups, one_groups, count_mobs, bits): self.play( FadeIn(add_words), fades.set_opacity, 0.1, ) if self.show_with_lines: for mover in movers: mover.generate_target() mover.target.replace(bit) mover.target.set_opacity(0) bit.save_state() bit.replace(movers[0]) bit.set_opacity(0) self.play( LaggedStartMap(ShowCreation, lines, run_time=2), LaggedStartMap(MoveToTarget, movers, lag_ratio=0.01), Restore(bit) ) self.remove(movers) self.add(bit) self.play( FadeOut(lines) ) else: self.play( ShowIncreasingSubsets(og), UpdateFromFunc(cm, lambda m: m.set_value(len(og))) ) self.play(FadeInFromPoint(bit, cm.get_center())) self.play( FadeOut(og), FadeOut(cm), ) self.play( FadeOut(add_words), Restore(fades), ) self.remove(fades) self.add(coins) self.wait() class ShowFinalStrategyWithFadeLines(ShowFinalStrategy): CONFIG = { "show_with_lines": True, } class Thumbnail(FourDCubeColoringFromTrees): def construct(self): # Board board = Chessboard( shape=(8, 8), # shape=(6, 6), square_resolution=(5, 5), top_square_resolution=(7, 7), ) board.set_gloss(0.3) k = 16 board[k].set_color(YELLOW) board.set_height(7) coins = CoinsOnBoard( board, coin_config={ # "disk_resolution": (80, 51), "disk_resolution": (2, 12), } ) coins.flip_by_message("A colab!") board_group = Group(board, coins) board_group.set_width(FRAME_WIDTH / 2 - 2) board_group.set_x(-FRAME_WIDTH / 4) self.add(board_group) # Hypercube cube = self.get_hypercube(width=2) colors = [BLUE_D, TEAL, GREEN, YELLOW] for n, vert in enumerate(cube.verts): code = boolian_linear_combo(int_to_bit_coords(n, 4)) cube.verts[n].set_color(colors[code]) cube.set_width(FRAME_WIDTH / 2 - 2) cube.set_x(FRAME_WIDTH / 4) cube.set_z(0, OUT) cube.rotate(7 * DEGREES, UP) self.add(cube) Group(cube, board_group).to_edge(UP, LARGE_BUFF) v_line = Line(UP, DOWN) v_line.set_height(FRAME_HEIGHT) v_line.set_stroke(GREY_A, 3) self.add(v_line) titles = VGroup(Text("From chessboards"), Text("to hypercubes")) titles.match_width(board_group) for title, mob in zip(titles, [board_group, cube]): title.match_x(mob) titles.to_edge(DOWN) self.add(titles) return # Instructions message = OldTexText( "Flip one coin\\\\to describe a\\\\", "unique square", alignment="", ) message[1].set_color(YELLOW) message.scale(1.25) message.to_edge(LEFT) message.shift(1.25 * DOWN) message.fix_in_frame() arrow = Arrow( message.get_corner(UR), message.get_corner(UR) + 3 * RIGHT + UP, path_arc=-70 * DEGREES, ) arrow.fix_in_frame() arrow.shift(1.5 * LEFT) arrow.set_color(YELLOW) # self.add(message) # self.add(arrow) class ChessEndScreen(PatreonEndScreen): CONFIG = { "scroll_time": 25, }
from manim_imports_ext import * from _2020.sir import * class LastFewMonths(Scene): def construct(self): words = OldTexText("Last ", "few\\\\", "months:") words.set_height(4) underlines = VGroup() for word in words: underline = Line(LEFT, RIGHT) underline.match_width(word) underline.next_to(word, DOWN, SMALL_BUFF) underlines.add(underline) underlines[0].stretch(1.4, 0, about_edge=LEFT) underlines.set_color(BLUE) # self.play(ShowCreation(underlines)) self.play(ShowIncreasingSubsets(words, run_time=0.75, rate_func=linear)) self.wait() class UnemploymentTitle(Scene): def construct(self): words = OldTexText("Unemployment claims\\\\per week in the US")[0] words.set_width(FRAME_WIDTH - 1) words.to_edge(UP) arrow = Arrow( words.get_bottom(), words.get_bottom() + 3 * RIGHT + 3 * DOWN, stroke_width=10, tip_length=0.5, ) arrow.set_color(BLUE_E) words.set_color(BLACK) self.play( ShowIncreasingSubsets(words), ShowCreation(arrow), ) self.wait() class ExplainTracing(Scene): def construct(self): # Words words = VGroup( OldTexText("Testing, ", "Testing, ", "Testing!"), OldTexText("Contact Tracing"), ) words[0].set_color(GREEN) words[1].set_color(BLUE_B) words.set_width(FRAME_WIDTH - 2) words.arrange(DOWN, buff=1) self.play(ShowIncreasingSubsets(words[0], rate_func=linear)) self.wait() self.play(Write(words[1], run_time=1)) self.wait() self.play( words[1].to_edge, UP, FadeOut(words[0], 6 * UP) ) ct_word = words[1][0] # Groups clusters = VGroup() for x in range(4): cluster = VGroup() for y in range(4): cluster.add(Randolph()) cluster.arrange_in_grid(buff=LARGE_BUFF) clusters.add(cluster) clusters.scale(0.5) clusters.arrange_in_grid(buff=2) clusters.set_height(4) self.play(FadeIn(clusters)) pis = VGroup() boxes = VGroup() for cluster in clusters: for pi in cluster: pis.add(pi) box = SurroundingRectangle(pi, buff=0.05) boxes.add(box) pi.box = box boxes.set_stroke(WHITE, 1) sicky = clusters[0][2] covid_words = OldTexText("COVID-19\\\\Positive!") covid_words.set_color(RED) arrow = Vector(RIGHT, color=RED) arrow.next_to(sicky, LEFT) covid_words.next_to(arrow, LEFT, SMALL_BUFF) self.play( sicky.change, "sick", sicky.set_color, "#9BBD37", FadeIn(covid_words, RIGHT), GrowArrow(arrow), ) self.play(ShowCreation(sicky.box)) self.wait(2) anims = [] for pi in clusters[0]: if pi is not sicky: anims.append(ApplyMethod(pi.change, "tired")) anims.append(ShowCreation(pi.box)) self.play(*anims) self.wait() self.play(VFadeIn( boxes[4:], run_time=2, rate_func=there_and_back_with_pause, )) self.wait() self.play(FadeOut( VGroup( covid_words, arrow, *boxes[:4], *pis, ), lag_ratio=0.1, run_time=3, )) self.play(ct_word.move_to, 2 * UP) # Underlines implies = OldTex("\\Downarrow") implies.scale(2) implies.next_to(ct_word, DOWN, MED_LARGE_BUFF) loc_tracking = OldTexText("Location Tracking") loc_tracking.set_color(GREY_BROWN) loc_tracking.match_height(ct_word) loc_tracking.next_to(implies, DOWN, MED_LARGE_BUFF) q_marks = OldTex("???") q_marks.scale(2) q_marks.next_to(implies, RIGHT) cross = Cross(implies) cross.set_stroke(RED, 7) self.play( Write(implies), FadeIn(loc_tracking, UP) ) self.play(FadeIn(q_marks, lag_ratio=0.1)) self.wait() parts = VGroup(ct_word[:7], ct_word[7:]) lines = VGroup() for part in parts: line = Line(part.get_left(), part.get_right()) line.align_to(part[0], DOWN) line.shift(0.1 * DOWN) lines.add(line) ct_word.set_stroke(BLACK, 2, background=True) self.add(lines[1], ct_word) self.play(ShowCreation(lines[1])) self.wait() self.play(ShowCreation(lines[0])) self.wait() self.play( ShowCreation(cross), FadeOut(q_marks, RIGHT), FadeOut(lines), ) self.wait() dp_3t = OldTexText("DP-3T") dp_3t.match_height(ct_word) dp_3t.move_to(loc_tracking) dp_3t_long = OldTexText("Decentralized Privacy-Preserving Proximity Tracing") dp_3t_long.next_to(dp_3t, DOWN, LARGE_BUFF) arrow = Vector(UP) arrow.set_stroke(width=8) arrow.move_to(implies) self.play( FadeInFromDown(dp_3t), FadeOut(loc_tracking), FadeOut(implies), FadeOut(cross), ShowCreation(arrow) ) self.play(Write(dp_3t_long)) self.wait() class ContactTracingMisnomer(Scene): def construct(self): # Word play words = OldTexText("Contact ", "Tracing") words.scale(2) rects = VGroup(*[ SurroundingRectangle(word, buff=0.2) for word in words ]) expl1 = OldTexText("Doesn't ``trace'' you...") expl2 = OldTexText("...or your contacts") expls = VGroup(expl1, expl2) colors = [RED, BLUE] self.add(words) for vect, rect, expl, color in zip([UP, DOWN], reversed(rects), expls, colors): arrow = Vector(-vect) arrow.next_to(rect, vect, SMALL_BUFF) expl.next_to(arrow, vect, SMALL_BUFF) rect.set_color(color) arrow.set_color(color) expl.set_color(color) self.play( FadeIn(expl, -vect), GrowArrow(arrow), ShowCreation(rect), ) self.wait() self.play(Write( VGroup(*self.mobjects), rate_func=lambda t: smooth(1 - t), run_time=3, )) class ContactTracingWords(Scene): def construct(self): words = OldTexText("Contact\\\\", "Tracing") words.set_height(4) for word in words: self.add(word) self.wait() self.wait() return self.play(ShowIncreasingSubsets(words)) self.wait() self.play( words.set_height, 1, words.to_corner, UL, ) self.wait() class WanderingDotsWithLines(Scene): def construct(self): sim = SIRSimulation( city_population=20, person_type=DotPerson, person_config={ "color_map": { "S": GREY, "I": GREY, "R": GREY, }, "infection_ring_style": { "stroke_color": YELLOW, }, "max_speed": 0.5, }, infection_time=100, ) for person in sim.people: person.set_status("S") person.infection_start_time += random.random() lines = VGroup() max_dist = 1.25 def update_lines(lines): lines.remove(*lines.submobjects) for p1 in sim.people: for p2 in sim.people: if p1 is p2: continue dist = get_norm(p1.get_center() - p2.get_center()) if dist < max_dist: line = Line(p1.get_center(), p2.get_center()) alpha = (max_dist - dist) / max_dist line.set_stroke( interpolate_color(WHITE, RED, alpha), width=4 * alpha ) lines.add(line) lines.add_updater(update_lines) self.add(lines) self.add(sim) self.wait(10) for person in sim.people: person.set_status("I") person.infection_start_time += random.random() self.wait(50) class WhatAboutPeopleWithoutPhones(TeacherStudentsScene): def construct(self): self.student_says( "What about people\\\\without phones?", target_mode="sassy", added_anims=[self.teacher.change, "guilty"] ) self.play_student_changes("angry", "angry", "sassy") self.wait() self.play(self.teacher.change, "tease") self.wait() words = VectorizedPoint() words.scale(1.5) words.to_corner(UL) self.play( FadeInFromDown(words), RemovePiCreatureBubble(self.students[2]), *[ ApplyMethod(pi.change, "pondering", words) for pi in self.pi_creatures ] ) self.wait(5) class PiGesture1(Scene): def construct(self): randy = Randolph(mode="raise_right_hand", height=2) bubble = randy.get_bubble( bubble_type=SpeechBubble, height=2, width=3, ) bubble.write("This one's\\\\great") bubble.content.scale(0.8) bubble.content.set_color(BLACK) bubble.set_color(BLACK) bubble.set_fill(opacity=0) randy.set_stroke(BLACK, 5, background=True) self.add(randy, bubble, bubble.content) class PiGesture2(Scene): def construct(self): randy = Randolph(mode="raise_left_hand", height=2) randy.look(UL) # randy.flip() randy.set_color(GREY_BROWN) bubble = randy.get_bubble( bubble_type=SpeechBubble, height=2, width=3, direction=LEFT, ) bubble.write("So is\\\\this one") bubble.content.scale(0.8) bubble.content.set_color(BLACK) bubble.set_color(BLACK) bubble.set_fill(opacity=0) randy.set_stroke(BLACK, 5, background=True) self.add(randy, bubble, bubble.content) class PiGesture3(Scene): def construct(self): randy = Randolph(mode="hooray", height=2) randy.flip() bubble = randy.get_bubble( bubble_type=SpeechBubble, height=2, width=3, direction=LEFT, ) bubble.write("And this\\\\one") bubble.content.scale(0.8) bubble.content.set_color(BLACK) bubble.set_color(BLACK) bubble.set_fill(opacity=0) randy.set_stroke(BLACK, 5, background=True) self.add(randy, bubble, bubble.content) class AppleGoogleCoop(Scene): def construct(self): logos = Group( self.get_apple_logo(), self.get_google_logo(), ) for logo in logos: logo.set_height(2) apple, google = logos logos.arrange(RIGHT, buff=3) arrows = VGroup() for vect, u in zip([UP, DOWN], [0, 1]): m1, m2 = logos[u], logos[1 - u] arrows.add(Arrow( m1.get_edge_center(vect), m2.get_edge_center(vect), path_arc=-90 * DEGREES, buff=MED_LARGE_BUFF, stroke_width=10, )) self.play(LaggedStart( Write(apple), FadeIn(google), lag_ratio=0.7, )) self.wait() self.play(ShowCreation(arrows, run_time=2)) self.wait() def get_apple_logo(self): result = SVGMobject("apple_logo") result.set_color("#b3b3b3") return result def get_google_logo(self): result = ImageMobject("google_logo_black") return result class LocationTracking(Scene): def construct(self): question = OldTexText( "Would you like this company to track\\\\", "and occasionally sell your location?" ) question.to_edge(UP, buff=LARGE_BUFF) slider = Rectangle(width=1.25, height=0.5) slider.round_corners(radius=0.25) slider.set_fill(GREEN, 1) slider.next_to(question, DOWN, buff=MED_LARGE_BUFF) dot = Dot(radius=0.25) dot.set_fill(GREY_C, 1) dot.set_stroke(WHITE, 3) dot.move_to(slider, RIGHT) morty = Mortimer() morty.next_to(slider, RIGHT) morty.to_edge(DOWN) bubble = morty.get_bubble( height=2, width=3, direction=LEFT, ) answer = OldTexText("Um...", "no.") answer.set_height(0.4) answer.set_color(YELLOW) bubble.add_content(answer) self.add(morty) self.play( FadeInFromDown(question), Write(slider), FadeIn(dot), ) self.play(morty.change, "confused", slider) self.play(Blink(morty)) self.play( FadeIn(bubble), Write(answer[0]), ) self.wait() self.play( dot.move_to, slider, LEFT, slider.set_fill, {"opacity": 0}, FadeIn(answer[1]), morty.change, "sassy" ) self.play(Blink(morty)) self.wait(2) self.play(Blink(morty)) self.wait(2) class MoreLinks(Scene): def construct(self): words = OldTexText("See more links\\\\in the description.") words.scale(2) words.to_edge(UP, buff=2) arrows = VGroup(*[ Vector(1.5 * DOWN, stroke_width=10) for x in range(4) ]) arrows.arrange(RIGHT, buff=0.75) arrows.next_to(words, DOWN, buff=0.5) for arrow, color in zip(arrows, [BLUE_D, BLUE_C, BLUE_E, GREY_BROWN]): arrow.set_color(color) self.play(Write(words)) self.play(LaggedStartMap(ShowCreation, arrows)) self.wait() class LDMEndScreen(PatreonEndScreen): CONFIG = { "scroll_time": 20, "specific_patrons": [ "1stViewMaths", "Aaron", "Adam Dřínek", "Adam Margulies", "Aidan Shenkman", "Alan Stein", "Albin Egasse", "Alex Mijalis", "Alexander Mai", "Alexis Olson", "Ali Yahya", "Andreas Snekloth Kongsgaard", "Andrew Busey", "Andrew Cary", "Andrew R. Whalley", "Aravind C V", "Arjun Chakroborty", "Arthur Zey", "Ashwin Siddarth", "Augustine Lim", "Austin Goodman", "Avi Finkel", "Awoo", "Axel Ericsson", "Ayan Doss", "AZsorcerer", "Barry Fam", "Bartosz Burclaf", "Ben Delo", "Benjamin Bailey", "Bernd Sing", "Bill Gatliff", "Boris Veselinovich", "Bradley Pirtle", "Brandon Huang", "Brendan Shah", "Brian Cloutier", "Brian Staroselsky", "Britt Selvitelle", "Britton Finley", "Burt Humburg", "Calvin Lin", "Carl-Johan R. Nordangård", "Charles Southerland", "Charlie N", "Chris Connett", "Chris Druta", "Christian Kaiser", "cinterloper", "Clark Gaebel", "Colwyn Fritze-Moor", "Corey Ogburn", "D. Sivakumar", "Dan Herbatschek", "Daniel Brown", "Daniel Herrera C", "Darrell Thomas", "Dave B", "Dave Cole", "Dave Kester", "dave nicponski", "David B. Hill", "David Clark", "David Gow", "Delton Ding", "Dominik Wagner", "Eduardo Rodriguez", "Emilio Mendoza", "emptymachine", "Eric Younge", "Eryq Ouithaqueue", "Federico Lebron", "Fernando Via Canel", "Frank R. Brown, Jr.", "gary", "Giovanni Filippi", "Goodwine", "Hal Hildebrand", "Heptonion", "Hitoshi Yamauchi", "Isaac Gubernick", "Ivan Sorokin", "Jacob Baxter", "Jacob Harmon", "Jacob Hartmann", "Jacob Magnuson", "Jalex Stark", "Jameel Syed", "James Beall", "Jason Hise", "Jayne Gabriele", "Jean-Manuel Izaret", "Jeff Dodds", "Jeff Linse", "Jeff Straathof", "Jeffrey Wolberg", "Jimmy Yang", "Joe Pregracke", "Johan Auster", "John C. Vesey", "John Camp", "John Haley", "John Le", "John Luttig", "John Rizzo", "John V Wertheim", "jonas.app", "Jonathan Heckerman", "Jonathan Wilson", "Joseph John Cox", "Joseph Kelly", "Josh Kinnear", "Joshua Claeys", "Joshua Ouellette", "Juan Benet", "Julien Dubois", "Kai-Siang Ang", "Kanan Gill", "Karl Niu", "Kartik Cating-Subramanian", "Kaustuv DeBiswas", "Killian McGuinness", "kkm", "Klaas Moerman", "Kristoffer Börebäck", "Kros Dai", "L0j1k", "Lael S Costa", "LAI Oscar", "Lambda GPU Workstations", "Laura Gast", "Lee Redden", "Linh Tran", "Luc Ritchie", "Ludwig Schubert", "Lukas Biewald", "Lukas Zenick", "Magister Mugit", "Magnus Dahlström", "Magnus Hiie", "Manoj Rewatkar - RITEK SOLUTIONS", "Mark B Bahu", "Mark Heising", "Mark Hopkins", "Mark Mann", "Martin Price", "Mathias Jansson", "Matt Godbolt", "Matt Langford", "Matt Roveto", "Matt Russell", "Matteo Delabre", "Matthew Bouchard", "Matthew Cocke", "Maxim Nitsche", "Michael Bos", "Michael Hardel", "Michael W White", "Mirik Gogri", "Molly Mackinlay", "Mustafa Mahdi", "Márton Vaitkus", "Nero Li", "Nicholas Cahill", "Nikita Lesnikov", "Nitu Kitchloo", "Oleg Leonov", "Oliver Steele", "Omar Zrien", "Omer Tuchfeld", "Patrick Gibson", "Patrick Lucas", "Pavel Dubov", "Pesho Ivanov", "Petar Veličković", "Peter Ehrnstrom", "Peter Francis", "Peter Mcinerney", "Pierre Lancien", "Pradeep Gollakota", "Rafael Bove Barrios", "Raghavendra Kotikalapudi", "Randy C. Will", "rehmi post", "Rex Godby", "Ripta Pasay", "Rish Kundalia", "Roman Sergeychik", "Roobie", "Ryan Atallah", "Samuel Judge", "SansWord Huang", "Scott Gray", "Scott Walter, Ph.D.", "soekul", "Solara570", "Spyridon Michalakis", "Stephen Shanahan", "Steve Huynh", "Steve Muench", "Steve Sperandeo", "Steven Siddals", "Stevie Metke", "Sundar Subbarayan", "supershabam", "Suteerth Vishnu", "Suthen Thomas", "Tal Einav", "Taras Bobrovytsky", "Tauba Auerbach", "Ted Suzman", "Terry Hayes", "THIS IS THE point OF NO RE tUUurRrhghgGHhhnnn", "Thomas J Sargent", "Thomas Tarler", "Tianyu Ge", "Tihan Seale", "Tim Erbes", "Tim Kazik", "Tomasz Legutko", "Tyler Herrmann", "Tyler Parcell", "Tyler VanValkenburg", "Tyler Veness", "Ubiquity Ventures", "Vassili Philippov", "Vasu Dubey", "Veritasium", "Vignesh Ganapathi Subramanian", "Vinicius Reis", "Vladimir Solomatin", "Wooyong Ee", "Xuanji Li", "Yana Chernobilsky", "Yavor Ivanov", "Yetinother", "YinYangBalance.Asia", "Yu Jun", "Yurii Monastyrshyn", "Zachariah Rosenberg", ], }
from manim_imports_ext import * import scipy.stats CASE_DATA = [ 9, 15, 30, 40, 56, 66, 84, 102, 131, 159, 173, 186, 190, 221, 248, 278, 330, 354, 382, 461, 481, 526, 587, 608, 697, 781, 896, 999, 1124, 1212, 1385, 1715, 2055, 2429, 2764, 3323, 4288, 5364, 6780, 8555, 10288, 12742, 14901, 17865, 21395, # 25404, # 29256, # 33627, # 38170, # 45421, # 53873, ] SICKLY_GREEN = "#9BBD37" class IntroducePlot(Scene): def construct(self): axes = self.get_axes() self.add(axes) # Dots dots = VGroup() for day, nc in zip(it.count(1), CASE_DATA): dot = Dot() dot.set_height(0.075) dot.x = day dot.y = nc dot.axes = axes dot.add_updater(lambda d: d.move_to(d.axes.c2p(d.x, d.y))) dots.add(dot) dots.set_color(YELLOW) # Rescale y axis origin = axes.c2p(0, 0) axes.y_axis.tick_marks.save_state() for tick in axes.y_axis.tick_marks: tick.match_width(axes.y_axis.tick_marks[0]) axes.y_axis.add( axes.h_lines, axes.small_h_lines, axes.tiny_h_lines, axes.tiny_ticks, ) axes.y_axis.stretch(25, 1, about_point=origin) dots.update() self.add(axes.small_y_labels) self.add(axes.tiny_y_labels) # Add title title = self.get_title(axes) self.add(title) # Introduce the data day = 10 self.add(*dots[:day + 1]) dot = Dot() dot.match_style(dots[day]) dot.replace(dots[day]) count = Integer(CASE_DATA[day]) count.add_updater(lambda m: m.next_to(dot, UP)) count.add_updater(lambda m: m.set_stroke(BLACK, 5, background=True)) v_line = Line(DOWN, UP) v_line.set_stroke(YELLOW, 1) v_line.add_updater( lambda m: m.put_start_and_end_on( axes.c2p( axes.x_axis.p2n(dot.get_center()), 0, ), dot.get_bottom(), ) ) self.add(dot) self.add(count) self.add(v_line) for new_day in range(day + 1, len(dots)): new_dot = dots[new_day] new_dot.update() line = Line(dot.get_center(), new_dot.get_center()) line.set_stroke(PINK, 3) self.add(line, dot) self.play( dot.move_to, new_dot.get_center(), dot.set_color, RED, ChangeDecimalToValue(count, CASE_DATA[new_day]), ShowCreation(line), ) line.rotate(PI) self.play( dot.set_color, YELLOW, Uncreate(line), run_time=0.5 ) self.add(dots[new_day]) day = new_day if day == 27: self.add( axes.y_axis, axes.tiny_y_labels, axes.tiny_h_lines, axes.tiny_ticks, title ) self.play( axes.y_axis.stretch, 0.2, 1, {"about_point": origin}, VFadeOut(axes.tiny_y_labels), VFadeOut(axes.tiny_h_lines), VFadeOut(axes.tiny_ticks), MaintainPositionRelativeTo(dot, dots[new_day]), run_time=2, ) self.add(axes, title, *dots[:new_day]) if day == 36: self.add(axes.y_axis, axes.small_y_labels, axes.small_h_lines, title) self.play( axes.y_axis.stretch, 0.2, 1, {"about_point": origin}, VFadeOut(axes.small_y_labels), VFadeOut(axes.small_h_lines), MaintainPositionRelativeTo(dot, dots[new_day]), run_time=2, ) self.add(axes, title, *dots[:new_day]) count.add_background_rectangle() count.background_rectangle.stretch(1.1, 0) self.add(count) # Show multiplications last_label = VectorizedPoint(dots[25].get_center()) last_line = VMobject() for d1, d2 in zip(dots[25:], dots[26:]): line = Line( d1.get_top(), d2.get_corner(UL), path_arc=-90 * DEGREES, ) line.set_stroke(PINK, 2) label = VGroup( OldTex("\\times"), DecimalNumber( axes.y_axis.p2n(d2.get_center()) / axes.y_axis.p2n(d1.get_center()), ) ) label.arrange(RIGHT, buff=SMALL_BUFF) label.set_height(0.25) label.next_to(line.point_from_proportion(0.5), UL, SMALL_BUFF) label.match_color(line) label.add_background_rectangle() label.save_state() label.move_to(last_label) label.set_opacity(0) self.play( ShowCreation(line), Restore(label), last_label.move_to, label.saved_state, VFadeOut(last_label), FadeOut(last_line), ) last_line = line last_label = label self.wait() self.play( FadeOut(last_label), FadeOut(last_line), ) # def get_title(self, axes): title = OldTexText( "Recorded COVID-19 cases\\\\outside mainland China", tex_to_color_map={"COVID-19": RED} ) title.next_to(axes.c2p(0, 1e3), RIGHT, LARGE_BUFF) title.to_edge(UP) title.add_background_rectangle() return title def get_axes(self, width=12, height=6): n_cases = len(CASE_DATA) axes = Axes( x_range=(0, n_cases), y_range=(0, 25000, 1000), width=width, height=height, ) axes.center() axes.to_edge(DOWN, buff=LARGE_BUFF) # Add dates text_pos_pairs = [ ("Mar 6", 0), ("Feb 23", -12), ("Feb 12", -23), ("Feb 1", -34), ("Jan 22", -44), ] labels = VGroup() extra_ticks = VGroup() for text, pos in text_pos_pairs: label = OldTexText(text) label.set_height(0.2) label.rotate(45 * DEGREES) axis_point = axes.c2p(n_cases + pos, 0) label.move_to(axis_point, UR) label.shift(MED_SMALL_BUFF * DOWN) label.shift(SMALL_BUFF * RIGHT) labels.add(label) tick = Line(UP, DOWN) tick.set_stroke(GREEN, 3) tick.set_height(0.25) tick.move_to(axis_point) extra_ticks.add(tick) axes.x_labels = labels axes.extra_x_ticks = extra_ticks axes.add(labels, extra_ticks) # Adjust y ticks axes.y_axis.ticks.stretch(0.5, 0) axes.y_axis.ticks[0::5].stretch(2, 0) # Add y_axis_labels def get_y_labels(axes, y_values): labels = VGroup() for y in y_values: try: label = OldTexText(f"{y}k") label.set_height(0.25) tick = axes.y_axis.ticks[y] always(label.next_to, tick, LEFT, SMALL_BUFF) labels.add(label) except IndexError: pass return labels main_labels = get_y_labels(axes, range(5, 30, 5)) axes.y_labels = main_labels axes.add(main_labels) axes.small_y_labels = get_y_labels(axes, range(1, 6)) tiny_labels = VGroup() tiny_ticks = VGroup() for y in range(200, 1000, 200): tick = axes.y_axis.ticks[0].copy() point = axes.c2p(0, y) tick.move_to(point) label = Integer(y) label.set_height(0.25) always(label.next_to, tick, LEFT, SMALL_BUFF) tiny_labels.add(label) tiny_ticks.add(tick) axes.tiny_y_labels = tiny_labels axes.tiny_ticks = tiny_ticks # Horizontal lines axes.h_lines = VGroup() axes.small_h_lines = VGroup() axes.tiny_h_lines = VGroup() group_range_pairs = [ (axes.h_lines, 5e3 * np.arange(1, 6)), (axes.small_h_lines, 1e3 * np.arange(1, 5)), (axes.tiny_h_lines, 200 * np.arange(1, 5)), ] for group, _range in group_range_pairs: for y in _range: group.add( Line( axes.c2p(0, y), axes.c2p(n_cases, y), ) ) group.set_stroke(WHITE, 1, opacity=0.5) return axes class Thumbnail(IntroducePlot): def construct(self): axes = self.get_axes() self.add(axes) dots = VGroup() data = CASE_DATA data.append(25398) for day, nc in zip(it.count(1), CASE_DATA): dot = Dot() dot.set_height(0.2) dot.x = day dot.y = nc dot.axes = axes dot.add_updater(lambda d: d.move_to(d.axes.c2p(d.x, d.y))) dots.add(dot) dots.set_color(YELLOW) dots.set_submobject_colors_by_gradient(BLUE, GREEN, RED) self.add(dots) title = OldTexText("COVID-19") title.set_height(1) title.set_color(RED) title.to_edge(UP, buff=LARGE_BUFF) subtitle = OldTexText("and exponential growth") subtitle.match_width(title) subtitle.next_to(title, DOWN) # self.add(title) # self.add(subtitle) title = OldTexText("The early warning\\\\of ", "COVID-19\\\\") title.set_color_by_tex("COVID", RED) title.set_height(2.5) title.to_edge(UP, buff=LARGE_BUFF) self.add(title) # self.remove(words) # words = OldTexText("Exponential growth") # words.move_to(ORIGIN, DL) # words.apply_function( # lambda p: [ # p[0], p[1] + np.exp(0.2 * p[0]), p[2] # ] # ) # self.add(words) self.embed() class IntroQuestion(Scene): def construct(self): questions = VGroup( OldTexText("What is exponential growth?"), OldTexText("Where does it come from?"), OldTexText("What does it imply?"), OldTexText("When does it stop?"), ) questions.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) for question in questions: self.play(FadeIn(question, RIGHT)) self.wait() self.play(LaggedStartMap( FadeOutAndShift, questions, lambda m: (m, DOWN), )) class ViralSpreadModel(Scene): CONFIG = { "num_neighbors": 5, "infection_probability": 0.3, "random_seed": 1, } def construct(self): # Init population randys = self.get_randys() self.add(*randys) # Show the sicko self.show_patient0(randys) # Repeatedly spread for x in range(20): self.spread_infection(randys) def get_randys(self): randys = VGroup(*[ Randolph() for x in range(150) ]) for randy in randys: randy.set_height(0.5) randys.arrange_in_grid(10, 15, buff=0.5) randys.set_height(FRAME_HEIGHT - 1) for i in range(0, 10, 2): randys[i * 15:(i + 1) * 15].shift(0.25 * RIGHT) for randy in randys: randy.shift(0.2 * random.random() * RIGHT) randy.shift(0.2 * random.random() * UP) randy.infected = False randys.center() return randys def show_patient0(self, randys): patient0 = random.choice(randys) patient0.infected = True circle = Circle() circle.set_stroke(SICKLY_GREEN) circle.replace(patient0) circle.scale(1.5) self.play( patient0.change, "sick", patient0.set_color, SICKLY_GREEN, ShowCreationThenFadeOut(circle), ) def spread_infection(self, randys): E = self.num_neighbors inf_p = self.infection_probability cough_anims = [] new_infection_anims = [] for randy in randys: if randy.infected: cough_anims.append(Flash( randy, color=SICKLY_GREEN, num_lines=16, line_stroke_width=1, flash_radius=0.5, line_length=0.1, )) random.shuffle(cough_anims) self.play(LaggedStart( *cough_anims, run_time=1, lag_ratio=1 / len(cough_anims), )) newly_infected = [] for randy in randys: if randy.infected: distances = [ get_norm(r2.get_center() - randy.get_center()) for r2 in randys ] for i in np.argsort(distances)[1:E + 1]: r2 = randys[i] if random.random() < inf_p and not r2.infected and r2 not in newly_infected: newly_infected.append(r2) r2.generate_target() r2.target.change("sick") r2.target.set_color(SICKLY_GREEN) new_infection_anims.append(MoveToTarget(r2)) random.shuffle(new_infection_anims) self.play(LaggedStart(*new_infection_anims, run_time=1)) for randy in newly_infected: randy.infected = True class GrowthEquation(Scene): def construct(self): # Add labels N_label = OldTexText("$N_d$", " = Number of cases on a given day", ) E_label = OldTexText("$E$", " = Average number of people someone infected is exposed to each day") p_label = OldTexText("$p$", " = Probability of each exposure becoming an infection") N_label[0].set_color(YELLOW) E_label[0].set_color(BLUE) p_label[0].set_color(TEAL) labels = VGroup( N_label, E_label, p_label ) labels.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) labels.set_width(FRAME_WIDTH - 1) labels.to_edge(UP) for label in labels: self.play(FadeInFromDown(label)) self.wait() delta_N = OldTex("\\Delta", "N_d") delta_N.set_color(YELLOW) eq = OldTex("=") eq.center() delta_N.next_to(eq, LEFT) delta_N_brace = Brace(delta_N, DOWN) delta_N_text = delta_N_brace.get_text("Change over a day") nep = OldTex("E", "\\cdot", "p", "\\cdot", "N_d") nep[4].match_color(N_label[0]) nep[0].match_color(E_label[0]) nep[2].match_color(p_label[0]) nep.next_to(eq, RIGHT) self.play(FadeIn(delta_N), FadeIn(eq)) self.play( GrowFromCenter(delta_N_brace), FadeIn(delta_N_text, 0.5 * UP), ) self.wait() self.play(LaggedStart( TransformFromCopy(N_label[0], nep[4]), TransformFromCopy(E_label[0], nep[0]), TransformFromCopy(p_label[0], nep[2]), FadeIn(nep[1]), FadeIn(nep[3]), lag_ratio=0.2, run_time=2, )) self.wait() self.play(ShowCreationThenFadeAround( nep[-1], surrounding_rectangle_config={"color": RED}, )) # Recursive equation lhs = OldTex("N_{d + 1}", "=") lhs[0].set_color(YELLOW) lhs.move_to(eq, RIGHT) lhs.shift(DOWN) rhs = VGroup( nep[-1].copy(), OldTex("+"), nep.copy(), ) rhs.arrange(RIGHT) rhs.next_to(lhs, RIGHT) self.play( FadeOut(delta_N_brace), FadeOut(delta_N_text), FadeIn(lhs, UP), ) self.play(FadeIn(rhs[:2])) self.play(TransformFromCopy(nep, rhs[2])) self.wait() alt_rhs = OldTex( "(", "1", "+", "E", "\\cdot", "p", ")", "N_d", tex_to_color_map={ "E": BLUE, "p": TEAL, "N_d": YELLOW, } ) new_lhs = lhs.copy() new_lhs.shift(DOWN) alt_rhs.next_to(new_lhs, RIGHT) self.play(TransformFromCopy(lhs, new_lhs)) self.play( TransformFromCopy(rhs[0], alt_rhs[7].copy()), TransformFromCopy(rhs[2][4], alt_rhs[7]), ) self.play( TransformFromCopy(rhs[1][0], alt_rhs[2]), TransformFromCopy(rhs[2][0], alt_rhs[3]), TransformFromCopy(rhs[2][1], alt_rhs[4]), TransformFromCopy(rhs[2][2], alt_rhs[5]), TransformFromCopy(rhs[2][3], alt_rhs[6]), FadeIn(alt_rhs[0]), FadeIn(alt_rhs[1]), ) self.wait() # Comment on factor brace = Brace(alt_rhs[:7], DOWN) text = OldTexText("For example, ", "1.15") text.next_to(brace, DOWN) self.play( GrowFromCenter(brace), FadeIn(text, 0.5 * UP) ) self.wait() # Show exponential eq_group = VGroup( delta_N, eq, nep, lhs, rhs, new_lhs, alt_rhs, brace, text, ) self.clear() self.add(labels, eq_group) self.play(ShowCreationThenFadeAround( VGroup(delta_N, eq, nep), surrounding_rectangle_config={"color": RED}, )) self.play(ShowCreationThenFadeAround( VGroup(new_lhs, alt_rhs, brace, text), surrounding_rectangle_config={"color": RED}, )) self.wait() self.play(eq_group.to_edge, LEFT, LARGE_BUFF) exp_eq = OldTex( "N_d = (1 + E \\cdot p)^{d} \\cdot N_0", tex_to_color_map={ "N_d": YELLOW, "E": BLUE, "p": TEAL, "{d}": YELLOW, "N_0": YELLOW, } ) exp_eq.next_to(alt_rhs, RIGHT, buff=3) arrow = Arrow(alt_rhs.get_right(), exp_eq.get_left()) self.play( GrowArrow(arrow), FadeIn(exp_eq, 2 * LEFT) ) self.wait() # Discuss factor in front of N ep = nep[:3] ep_rect = SurroundingRectangle(ep) ep_rect.set_stroke(RED, 2) ep_label = OldTexText("This factor will decrease") ep_label.next_to(ep_rect, UP, aligned_edge=LEFT) ep_label.set_color(RED) self.play( ShowCreation(ep_rect), FadeIn(ep_label, lag_ratio=0.1), ) self.wait() self.play( FadeOut(ep_rect), FadeOut(ep_label), ) # Add carrying capacity factor to p p_factors = OldTex( "\\left(1 - {N_d \\over \\text{pop. size}} \\right)", tex_to_color_map={"N_d": YELLOW}, ) p_factors.next_to(nep, RIGHT, buff=3) p_factors_rect = SurroundingRectangle(p_factors) p_factors_rect.set_stroke(TEAL, 2) p_arrow = Arrow( p_factors_rect.get_corner(UL), nep[2].get_top(), path_arc=75 * DEGREES, color=TEAL, ) self.play( ShowCreation(p_factors_rect), ShowCreation(p_arrow) ) self.wait() self.play(Write(p_factors)) self.wait() self.play( FadeOut(p_factors), FadeOut(p_arrow), FadeOut(p_factors_rect), ) # Ask about ep shrinking ep_question = OldTexText("What makes this shrink?") ep_question.set_color(RED) ep_question.next_to(ep_rect, UP, aligned_edge=LEFT) E_line = Underline(E_label) E_line.set_color(BLUE) p_line = Underline(p_label) p_line.set_color(TEAL) self.play( ShowCreation(ep_rect), FadeIn(ep_question, LEFT) ) self.wait() for line in E_line, p_line: self.play(ShowCreation(line)) self.wait() self.play(FadeOut(line)) self.wait() # Show alternate projections ep_value = DecimalNumber(0.15) ep_value.next_to(ep_rect, UP) self.play( FadeOut(ep_question), FadeIn(ep_value), FadeOut(text[0]), text[1].next_to, brace, DOWN, ) eq1 = OldTex("(", "1.15", ")", "^{61}", "\\cdot", "21{,}000", "=") eq2 = OldTex("(", "1.05", ")", "^{61}", "\\cdot", "21{,}000", "=") eq1_rhs = Integer((1.15**61) * (21000)) eq2_rhs = Integer((1.05**61) * (21000)) for eq, rhs in (eq1, eq1_rhs), (eq2, eq2_rhs): eq[1].set_color(RED) eq.move_to(nep) eq.to_edge(RIGHT, buff=3) rhs.next_to(eq, RIGHT) rhs.align_to(eq[-2], UP) self.play(FadeIn(eq1)) for tex in ["21{,}000", "61"]: self.play(ShowCreationThenFadeOut( Underline( eq1.get_part_by_tex(tex), stroke_color=YELLOW, stroke_width=2, buff=SMALL_BUFF, ), run_time=2, )) value = eq1_rhs.get_value() eq1_rhs.set_value(0) self.play(ChangeDecimalToValue(eq1_rhs, value)) self.wait() eq1.add(eq1_rhs) self.play( eq1.shift, DOWN, FadeIn(eq2), ) new_text = OldTexText("1.05") new_text.move_to(text[1]) self.play( ChangeDecimalToValue(ep_value, 0.05), FadeOut(text[1]), FadeIn(new_text), ) self.wait() eq2_rhs.align_to(eq1_rhs, RIGHT) value = eq2_rhs.get_value() eq2_rhs.set_value(0) self.play(ChangeDecimalToValue(eq2_rhs, value)) self.wait() # Pi creature quote morty = Mortimer() morty.set_height(1) morty.next_to(eq2_rhs, UP) bubble = SpeechBubble( direction=RIGHT, height=2.5, width=5, ) bubble.next_to(morty, UL, buff=0) bubble.write("The only thing to fear\\\\is the lack of fear itself.") self.add(morty) self.add(bubble) self.add(bubble.content) self.play( labels.set_opacity, 0.5, VFadeIn(morty), morty.change, "speaking", FadeIn(bubble), Write(bubble.content), ) self.play(Blink(morty)) self.wait() class RescaleToLogarithmic(IntroducePlot): def construct(self): # Setup axes axes = self.get_axes(width=10) title = self.get_title(axes) dots = VGroup() for day, nc in zip(it.count(1), CASE_DATA): dot = Dot() dot.set_height(0.075) dot.move_to(axes.c2p(day, nc)) dots.add(dot) dots.set_color(YELLOW) self.add(axes, axes.h_lines, dots, title) # Create logarithmic y axis log_y_axis = NumberLine( x_min=0, x_max=9, ) log_y_axis.rotate(90 * DEGREES) log_y_axis.move_to(axes.c2p(0, 0), DOWN) labels_text = [ "10", "100", "1k", "10k", "100k", "1M", "10M", "100M", "1B", ] log_y_labels = VGroup() for text, tick in zip(labels_text, log_y_axis.tick_marks[1:]): label = OldTexText(text) label.set_height(0.25) always(label.next_to, tick, LEFT, SMALL_BUFF) log_y_labels.add(label) # Animate the rescaling to a logarithmic plot logarithm_title = OldTexText("(Logarithmic scale)") logarithm_title.set_color(TEAL) logarithm_title.next_to(title, DOWN) logarithm_title.add_background_rectangle() def scale_logarithmically(p): result = np.array(p) y = axes.y_axis.p2n(p) result[1] = log_y_axis.n2p(np.log10(y))[1] return result log_h_lines = VGroup() for exponent in range(0, 9): for mult in range(2, 12, 2): y = mult * 10**exponent line = Line( axes.c2p(0, y), axes.c2p(axes.x_max, y), ) log_h_lines.add(line) log_h_lines.set_stroke(WHITE, 0.5, opacity=0.5) log_h_lines[4::5].set_stroke(WHITE, 1, opacity=1) movers = [dots, axes.y_axis.tick_marks, axes.h_lines, log_h_lines] for group in movers: group.generate_target() for mob in group.target: mob.move_to(scale_logarithmically(mob.get_center())) log_y_labels.suspend_updating() log_y_labels.save_state() for exponent, label in zip(it.count(1), log_y_labels): label.set_y(axes.y_axis.n2p(10**exponent)[1]) label.set_opacity(0) self.add(log_y_axis) log_y_axis.save_state() log_y_axis.tick_marks.set_opacity(0) log_h_lines.set_opacity(0) self.wait() self.add(log_h_lines, title, logarithm_title) self.play( MoveToTarget(dots), MoveToTarget(axes.y_axis.tick_marks), MoveToTarget(axes.h_lines), MoveToTarget(log_h_lines), VFadeOut(axes.y_labels), VFadeOut(axes.y_axis.tick_marks), VFadeOut(axes.h_lines), Restore(log_y_labels), FadeIn(logarithm_title), run_time=2, ) self.play(Restore(log_y_axis)) self.wait() # Walk up y axis brace = Brace( log_y_axis.tick_marks[1:3], RIGHT, buff=SMALL_BUFF, ) brace_label = brace.get_tex( "\\times 10", buff=SMALL_BUFF ) VGroup(brace, brace_label).set_color(TEAL) brace_label.set_stroke(BLACK, 8, background=True) self.play( GrowFromCenter(brace), FadeIn(brace_label) ) brace.add(brace_label) for i in range(2, 5): self.play( brace.next_to, log_y_axis.tick_marks[i:i + 2], {"buff": SMALL_BUFF} ) self.wait(0.5) self.play(FadeOut(brace)) self.wait() # Show order of magnitude jumps remove_anims = [] for i, j in [(7, 27), (27, 40)]: line = Line(dots[i].get_center(), dots[j].get_center()) rect = Rectangle() rect.set_fill(TEAL, 0.5) rect.set_stroke(width=0) rect.replace(line, stretch=True) label = OldTexText(f"{j - i} days") label.next_to(rect, UP, SMALL_BUFF) label.set_color(TEAL) rect.save_state() rect.stretch(0, 0, about_edge=LEFT) self.play( Restore(rect), FadeIn(label, LEFT) ) self.wait() remove_anims += [ ApplyMethod( rect.stretch, 0, 0, {"about_edge": RIGHT}, remover=True, ), FadeOut(label, RIGHT), ] self.wait() # Linear regression def c2p(x, y): xp = axes.x_axis.n2p(x) yp = log_y_axis.n2p(np.log10(y)) return np.array([xp[0], yp[1], 0]) reg = scipy.stats.linregress( range(7, len(CASE_DATA)), np.log10(CASE_DATA[7:]) ) x_max = axes.x_max axes.y_axis = log_y_axis reg_line = Line( c2p(0, 10**reg.intercept), c2p(x_max, 10**(reg.intercept + reg.slope * x_max)), ) reg_line.set_stroke(TEAL, 3) self.add(reg_line, dots) dots.set_stroke(BLACK, 3, background=True) self.play( LaggedStart(*remove_anims), ShowCreation(reg_line) ) # Describe linear regression reg_label = OldTexText("Linear regression") reg_label.move_to(c2p(25, 10), DOWN) reg_arrows = VGroup() for prop in [0.4, 0.6, 0.5]: reg_arrows.add( Arrow( reg_label.get_top(), reg_line.point_from_proportion(prop), buff=SMALL_BUFF, ) ) reg_arrow = reg_arrows[0].copy() self.play( Write(reg_label, run_time=1), Transform(reg_arrow, reg_arrows[1], run_time=2), VFadeIn(reg_arrow), ) self.play(Transform(reg_arrow, reg_arrows[2])) self.wait() # Label slope slope_label = OldTexText("$\\times 10$ every $16$ days (on average)") slope_label.set_color(BLUE) slope_label.set_stroke(BLACK, 8, background=True) slope_label.rotate(reg_line.get_angle()) slope_label.move_to(reg_line.get_center()) slope_label.shift(MED_LARGE_BUFF * UP) self.play(FadeIn(slope_label, lag_ratio=0.1)) self.wait() # R^2 label R2_label = VGroup( OldTex("R^2 = "), DecimalNumber(0, num_decimal_places=3) ) R2_label.arrange(RIGHT, aligned_edge=DOWN) R2_label.next_to(reg_label[0][-1], RIGHT, LARGE_BUFF, aligned_edge=DOWN) self.play( ChangeDecimalToValue(R2_label[1], reg.rvalue**2, run_time=2), UpdateFromAlphaFunc( R2_label, lambda m, a: m.set_opacity(a), ) ) self.wait() rect = SurroundingRectangle(R2_label, buff=0.15) rect.set_stroke(YELLOW, 3) rect.set_fill(BLACK, 0) self.add(rect, R2_label) self.play(ShowCreation(rect)) self.play( rect.set_stroke, WHITE, 2, rect.set_fill, GREY_E, 1, ) self.wait() self.play( FadeOut(rect), FadeOut(R2_label), FadeOut(reg_label), FadeOut(reg_arrow), ) # Zoom out extended_x_axis = NumberLine( x_min=axes.x_axis.x_max, x_max=axes.x_axis.x_max + 90, unit_size=get_norm( axes.x_axis.n2p(1) - axes.x_axis.n2p(0) ), numbers_with_elongated_ticks=[], ) extended_x_axis.move_to(axes.x_axis.get_right(), LEFT) self.play( self.camera.frame.scale, 2, {"about_edge": DL}, self.camera.frame.shift, 2.5 * DOWN + RIGHT, log_h_lines.stretch, 3, 0, {"about_edge": LEFT}, ShowCreation(extended_x_axis, rate_func=squish_rate_func(smooth, 0.5, 1)), run_time=3, ) self.play( reg_line.scale, 3, {"about_point": reg_line.get_start()} ) self.wait() # Show future projections target_ys = [1e6, 1e7, 1e8, 1e9] last_point = dots[-1].get_center() last_label = None last_rect = None date_labels_text = [ "Apr 5", "Apr 22", "May 9", "May 26", ] for target_y, date_label_text in zip(target_ys, date_labels_text): log_y = np.log10(target_y) x = (log_y - reg.intercept) / reg.slope line = Line(last_point, c2p(x, target_y)) rect = Rectangle().replace(line, stretch=True) rect.set_stroke(width=0) rect.set_fill(TEAL, 0.5) label = OldTexText(f"{int(x) - axes.x_max} days") label.scale(1.5) label.next_to(rect, UP, SMALL_BUFF) date_label = OldTexText(date_label_text) date_label.set_height(0.25) date_label.rotate(45 * DEGREES) axis_point = axes.c2p(int(x), 0) date_label.move_to(axis_point, UR) date_label.shift(MED_SMALL_BUFF * DOWN) date_label.shift(SMALL_BUFF * RIGHT) v_line = DashedLine( axes.c2p(x, 0), c2p(x, target_y), ) v_line.set_stroke(WHITE, 2) if target_y is target_ys[-1]: self.play(self.camera.frame.scale, 1.1, {"about_edge": LEFT}) if last_label: self.play( ReplacementTransform(last_label, label), ReplacementTransform(last_rect, rect), ) else: rect.save_state() rect.stretch(0, 0, about_edge=LEFT) self.play(Restore(rect), FadeIn(label, LEFT)) self.wait() self.play( ShowCreation(v_line), FadeIn(date_label), ) last_label = label last_rect = rect self.wait() self.play( FadeOut(last_label, RIGHT), ApplyMethod( last_rect.stretch, 0, 0, {"about_edge": RIGHT}, remover=True ), ) # Show alternate petering out possibilities def get_dots_along_curve(curve): x_min = int(axes.x_axis.p2n(curve.get_start())) x_max = int(axes.x_axis.p2n(curve.get_end())) result = VGroup() for x in range(x_min, x_max): prop = binary_search( lambda p: axes.x_axis.p2n( curve.point_from_proportion(p), ), x, 0, 1, ) prop = prop or 0 point = curve.point_from_proportion(prop) dot = Dot(point) dot.shift(0.02 * (random.random() - 0.5)) dot.set_height(0.075) dot.set_color(RED) result.add(dot) dots.remove(dots[0]) return result def get_point_from_y(y): log_y = np.log10(y) x = (log_y - reg.intercept) / reg.slope return c2p(x, 10**log_y) p100k = get_point_from_y(1e5) p100M = get_point_from_y(1e8) curve1 = VMobject() curve1.append_points([ dots[-1].get_center(), p100k, p100k + 5 * RIGHT, ]) curve2 = VMobject() curve2.append_points([ dots[-1].get_center(), p100M, p100M + 5 * RIGHT + 0.25 * UP, ]) proj_dots1 = get_dots_along_curve(curve1) proj_dots2 = get_dots_along_curve(curve2) for proj_dots in [proj_dots1, proj_dots2]: self.play(FadeIn(proj_dots, lag_ratio=0.1)) self.wait() self.play(FadeOut(proj_dots, lag_ratio=0.1)) class LinRegNote(Scene): def construct(self): text = OldTexText("(Starting from when\\\\there were 100 cases)") text.set_stroke(BLACK, 8, background=True) self.add(text) class CompareCountries(Scene): def construct(self): # Introduce sk_flag = ImageMobject(os.path.join("flags", "kr")) au_flag = ImageMobject(os.path.join("flags", "au")) flags = Group(sk_flag, au_flag) flags.set_height(3) flags.arrange(RIGHT, buff=LARGE_BUFF) flags.next_to(ORIGIN, UP) labels = VGroup() case_numbers = [6593, 64] for flag, cn in zip(flags, case_numbers): label = VGroup(Integer(cn), OldTexText("cases")) label.arrange(RIGHT, buff=MED_SMALL_BUFF) label[1].align_to(label[0][-1], DOWN) label.scale(1.5) label.next_to(flag, DOWN, MED_LARGE_BUFF) label[0].set_value(0) labels.add(label) self.play(LaggedStartMap(FadeInFromDown, flags, lag_ratio=0.25)) self.play( ChangeDecimalToValue(labels[0][0], case_numbers[0]), ChangeDecimalToValue(labels[1][0], case_numbers[1]), UpdateFromAlphaFunc( labels, lambda m, a: m.set_opacity(a), ) ) self.wait() # Compare arrow = Arrow( labels[1][0].get_bottom(), labels[0][0].get_bottom(), path_arc=-90 * DEGREES, ) arrow_label = OldTexText("100x better") arrow_label.set_color(YELLOW) arrow_label.next_to(arrow, DOWN) alt_arrow_label = OldTexText("1 month behind") alt_arrow_label.set_color(RED) alt_arrow_label.next_to(arrow, DOWN) self.play(ShowCreation(arrow)) self.play(FadeIn(arrow_label, 0.5 * UP)) self.wait(2) self.play( FadeIn(alt_arrow_label, 0.5 * UP), FadeOut(arrow_label, 0.5 * DOWN), ) self.wait(2) class SARSvs1918(Scene): def construct(self): titles = VGroup( OldTexText("2002 SARS outbreak"), OldTexText("1918 Spanish flu"), ) images = Group( ImageMobject("sars_icon"), ImageMobject("spanish_flu"), ) for title, vect, color, image in zip(titles, [LEFT, RIGHT], [YELLOW, RED], images): image.set_height(4) image.move_to(vect * FRAME_WIDTH / 4) image.to_edge(UP) title.scale(1.25) title.next_to(image, DOWN, MED_LARGE_BUFF) title.set_color(color) title.underline = Underline(title) title.underline.set_stroke(WHITE, 1) title.add_to_back(title.underline) titles[1].underline.match_y(titles[0].underline) n_cases_labels = VGroup( OldTexText("8,096 cases"), OldTexText("$\\sim$513{,}000{,}000 cases"), ) for n_cases_label, title in zip(n_cases_labels, titles): n_cases_label.scale(1.25) n_cases_label.next_to(title, DOWN, MED_LARGE_BUFF) for image, title, label in zip(images, titles, n_cases_labels): self.play( FadeIn(image, DOWN), Write(title), run_time=1, ) self.play(FadeIn(label, UP)) self.wait() class ViralSpreadModelWithShuffling(ViralSpreadModel): def construct(self): # Init population randys = self.get_randys() self.add(*randys) # Show the sicko self.show_patient0(randys) # Repeatedly spread for x in range(15): self.spread_infection(randys) self.shuffle_randys(randys) def shuffle_randys(self, randys): indices = list(range(len(randys))) np.random.shuffle(indices) anims = [] for i, randy in zip(indices, randys): randy.generate_target() randy.target.move_to(randys[i]) anims.append(MoveToTarget( randy, path_arc=30 * DEGREES, )) self.play(LaggedStart( *anims, lag_ratio=1 / len(randys), run_time=3 )) class SneezingOnNeighbors(Scene): def construct(self): randys = VGroup(*[PiCreature() for x in range(3)]) randys.set_height(1) randys.arrange(RIGHT) self.add(randys) self.play( randys[1].change, "sick", randys[1].set_color, SICKLY_GREEN, ) self.play( Flash( randys[1], color=SICKLY_GREEN, flash_radius=0.8, ), randys[0].change, "sassy", randys[1], randys[2].change, "angry", randys[1], ) self.play( randys[0].change, "sick", randys[0].set_color, SICKLY_GREEN, randys[2].change, "sick", randys[2].set_color, SICKLY_GREEN, ) self.play( Flash( randys[1], color=SICKLY_GREEN, flash_radius=0.8, ) ) self.play( randys[0].change, "sad", randys[1], randys[2].change, "tired", randys[1], ) self.play( Flash( randys[1], color=SICKLY_GREEN, flash_radius=0.8, ) ) self.play( randys[0].change, "angry", randys[1], randys[2].change, "angry", randys[1], ) self.wait() class ViralSpreadModelWithClusters(ViralSpreadModel): def construct(self): randys = self.get_randys() self.add(*randys) self.show_patient0(randys) for x in range(6): self.spread_infection(randys) def get_randys(self): cluster = VGroup(*[Randolph() for x in range(16)]) cluster.arrange_in_grid(4, 4) cluster.set_height(1) cluster.space_out_submobjects(1.3) clusters = VGroup(*[cluster.copy() for x in range(12)]) clusters.arrange_in_grid(3, 4, buff=LARGE_BUFF) clusters.set_height(FRAME_HEIGHT - 1) for cluster in clusters: for randy in cluster: randy.infected = False self.add(clusters) self.clusters = clusters return VGroup(*it.chain(*clusters)) class ViralSpreadModelWithClustersAndTravel(ViralSpreadModelWithClusters): CONFIG = { "random_seed": 2, } def construct(self): randys = self.get_randys() self.add(*randys) self.show_patient0(randys) for x in range(20): self.spread_infection(randys) self.travel_between_clusters() self.update_frame(ignore_skipping=True) def travel_between_clusters(self): reps = VGroup(*[ random.choice(cluster) for cluster in self.clusters ]) targets = list(reps) random.shuffle(targets) anims = [] for rep, target in zip(reps, targets): rep.generate_target() rep.target.move_to(target) anims.append(MoveToTarget( rep, path_arc=30 * DEGREES, )) self.play(LaggedStart(*anims, run_time=3)) class ShowLogisticCurve(Scene): def construct(self): # Init axes axes = self.get_axes() self.add(axes) # Add ODE ode = OldTex( "{dN \\over dt} =", "c", "\\left(1 - {N \\over \\text{pop.}}\\right)", "N", tex_to_color_map={"N": YELLOW} ) ode.set_height(0.75) ode.center() ode.to_edge(RIGHT) ode.shift(1.5 * UP) self.add(ode) # Show curve curve = axes.get_graph( lambda x: 8 * smooth(x / 10) + 0.2, ) curve.set_stroke(YELLOW, 3) curve_title = OldTexText("Logistic curve") curve_title.set_height(0.75) curve_title.next_to(curve.get_end(), UL) self.play(ShowCreation(curve, run_time=3)) self.play(FadeIn(curve_title, lag_ratio=0.1)) self.wait() # Early part line = Line( curve.point_from_proportion(0), curve.point_from_proportion(0.25), ) rect = Rectangle() rect.set_stroke(width=0) rect.set_fill(TEAL, 0.5) rect.replace(line, stretch=True) exp_curve = axes.get_graph( lambda x: 0.15 * np.exp(0.68 * x) ) exp_curve.set_stroke(RED, 3) rect.save_state() rect.stretch(0, 0, about_edge=LEFT) self.play(Restore(rect)) self.play(ShowCreation(exp_curve, run_time=4)) # Show capacity line = DashedLine( axes.c2p(0, 8.2), axes.c2p(axes.x_max, 8.2), ) line.set_stroke(BLUE, 2) self.play(ShowCreation(line)) self.wait() self.play(FadeOut(rect), FadeOut(exp_curve)) # Show inflection point infl_point = axes.input_to_graph_point(5, curve) infl_dot = Dot(infl_point) infl_dot.set_stroke(WHITE, 3) curve_up_part = curve.copy() curve_up_part.pointwise_become_partial(curve, 0, 0.4) curve_up_part.set_stroke(GREEN) curve_down_part = curve.copy() curve_down_part.pointwise_become_partial(curve, 0.4, 1) curve_down_part.set_stroke(RED) for part in curve_up_part, curve_down_part: part.save_state() part.stretch(0, 1) part.set_y(axes.c2p(0, 0)[1]) pre_dot = curve.copy() pre_dot.pointwise_become_partial(curve, 0.375, 0.425) infl_name = OldTexText("Inflection point") infl_name.next_to(infl_dot, LEFT) self.play(ReplacementTransform(pre_dot, infl_dot, path_arc=90 * DEGREES)) self.add(curve_up_part, infl_dot) self.play(Restore(curve_up_part)) self.add(curve_down_part, infl_dot) self.play(Restore(curve_down_part)) self.wait() self.play(Write(infl_name, run_time=1)) self.wait() # Show tangent line x_tracker = ValueTracker(0) tan_line = Line(LEFT, RIGHT) tan_line.set_width(5) tan_line.set_stroke(YELLOW, 2) def update_tan_line(line): x1 = x_tracker.get_value() x2 = x1 + 0.001 p1 = axes.input_to_graph_point(x1, curve) p2 = axes.input_to_graph_point(x2, curve) angle = angle_of_vector(p2 - p1) line.rotate(angle - line.get_angle()) line.move_to(p1) tan_line.add_updater(update_tan_line) dot = Dot() dot.scale(0.75) dot.set_fill(BLUE, 0.75) dot.add_updater( lambda m: m.move_to(axes.input_to_graph_point( x_tracker.get_value(), curve )) ) self.play( ShowCreation(tan_line), FadeInFromLarge(dot), ) self.play( x_tracker.set_value, 5, run_time=6, ) self.wait() self.play( x_tracker.set_value, 9.9, run_time=6, ) self.wait() # Define growth factor gf_label = OldTex( "\\text{Growth factor} =", "{\\Delta N_d \\over \\Delta N_{d - 1}}", tex_to_color_map={ "\\Delta": WHITE, "N_d": YELLOW, "N_{d - 1}": BLUE, } ) gf_label.next_to(infl_dot, RIGHT, LARGE_BUFF) numer_label = OldTexText("New cases one day") denom_label = OldTexText("New cases the\\\\previous day") for label, tex, vect in (numer_label, "N_d", UL), (denom_label, "N_{d - 1}", DL): part = gf_label.get_part_by_tex(tex) label.match_color(part) label.next_to(part, vect, LARGE_BUFF) label.shift(2 * RIGHT) arrow = Arrow( label.get_corner(vect[1] * DOWN), part.get_corner(vect[1] * UP) + 0.25 * LEFT, buff=0.1, ) arrow.match_color(part) label.add_to_back(arrow) self.play( FadeIn(gf_label[0], RIGHT), FadeIn(gf_label[1:], LEFT), FadeOut(ode) ) self.wait() for label in numer_label, denom_label: self.play(FadeIn(label, lag_ratio=0.1)) self.wait() # Show example growth factors self.play(x_tracker.set_value, 1) eq = OldTex("=") eq.next_to(gf_label, RIGHT) gf = DecimalNumber(1.15) gf.set_height(0.4) gf.next_to(eq, RIGHT) def get_growth_factor(): x1 = x_tracker.get_value() x0 = x1 - 0.2 x2 = x1 + 0.2 p0, p1, p2 = [ axes.input_to_graph_point(x, curve) for x in [x0, x1, x2] ] return (p2[1] - p1[1]) / (p1[1] - p0[1]) gf.add_updater(lambda m: m.set_value(get_growth_factor())) self.add(eq, gf) self.play( x_tracker.set_value, 5, run_time=6, rate_func=linear, ) self.wait() self.play( x_tracker.set_value, 9, run_time=6, rate_func=linear, ) def get_axes(self): axes = Axes( x_min=0, x_max=13, y_min=0, y_max=10, y_axis_config={ "unit_size": 0.7, "include_tip": False, } ) axes.center() axes.to_edge(DOWN) x_label = OldTexText("Time") x_label.next_to(axes.x_axis, UP, aligned_edge=RIGHT) y_label = OldTexText("N cases") y_label.next_to(axes.y_axis, RIGHT, aligned_edge=UP) axes.add(x_label, y_label) return axes class SubtltyOfGrowthFactorShift(Scene): def construct(self): # Set up totals total_title = OldTexText("Totals") total_title.add(Underline(total_title)) total_title.to_edge(UP) total_title.scale(1.25) total_title.shift(LEFT) total_title.set_color(YELLOW) total_title.shift(LEFT) data = CASE_DATA[-4:] data.append(int(data[-1] + 1.15 * (data[-1] - data[-2]))) totals = VGroup(*[Integer(value) for value in data]) totals.scale(1.25) totals.arrange(DOWN, buff=0.6, aligned_edge=LEFT) totals.next_to(total_title, DOWN, buff=0.6) totals[-1].set_color(BLUE) # Set up dates dates = VGroup( OldTexText("March 3, 2020"), OldTexText("March 4, 2020"), OldTexText("March 5, 2020"), OldTexText("March 6, 2020"), ) for date, total in zip(dates, totals): date.scale(0.75) date.set_color(GREY_B) date.next_to(total, LEFT, buff=0.75, aligned_edge=DOWN) # Set up changes change_arrows = VGroup() change_labels = VGroup() for t1, t2 in zip(totals, totals[1:]): arrow = Arrow( t1.get_right(), t2.get_right(), path_arc=-150 * DEGREES, buff=0.1, max_tip_length_to_length_ratio=0.15, ) arrow.shift(MED_SMALL_BUFF * RIGHT) arrow.set_stroke(width=3) change_arrows.add(arrow) diff = t2.get_value() - t1.get_value() label = Integer(diff, include_sign=True) label.set_color(GREEN) label.next_to(arrow, RIGHT) change_labels.add(label) change_labels[-1].set_color(BLUE) change_title = OldTexText("Changes") change_title.add(Underline(change_title).shift(0.128 * UP)) change_title.scale(1.25) change_title.set_color(GREEN) change_title.move_to(change_labels) change_title.align_to(total_title, UP) # Set up growth factors gf_labels = VGroup() gf_arrows = VGroup() for c1, c2 in zip(change_labels, change_labels[1:]): arrow = Arrow( c1.get_right(), c2.get_right(), path_arc=-150 * DEGREES, buff=0.1, max_tip_length_to_length_ratio=0.15, ) arrow.set_stroke(width=1) gf_arrows.add(arrow) line = Line(LEFT, RIGHT) line.match_width(c2) line.set_stroke(WHITE, 2) numer = c2.deepcopy() denom = c1.deepcopy() frac = VGroup(numer, line, denom) frac.arrange(DOWN, buff=SMALL_BUFF) frac.scale(0.7) frac.next_to(arrow, RIGHT) eq = OldTex("=") eq.next_to(frac, RIGHT) gf = DecimalNumber(c2.get_value() / c1.get_value()) gf.next_to(eq, RIGHT) gf_labels.add(VGroup(frac, eq, gf)) gf_title = OldTexText("Growth factors") gf_title.add(Underline(gf_title)) gf_title.scale(1.25) gf_title.move_to(gf_labels[0][-1]) gf_title.align_to(total_title, DOWN) # Add things self.add(dates, total_title) self.play( LaggedStartMap( FadeInFrom, totals[:-1], lambda m: (m, UP), ) ) self.wait() self.play( ShowCreation(change_arrows[:-1]), LaggedStartMap( FadeInFrom, change_labels[:-1], lambda m: (m, LEFT), ), FadeIn(change_title), ) self.wait() self.play( ShowCreation(gf_arrows[:-1]), LaggedStartMap(FadeIn, gf_labels[:-1]), FadeIn(gf_title), ) self.wait() # Show hypothetical new value self.play(LaggedStart( FadeIn(gf_labels[-1]), FadeIn(gf_arrows[-1]), FadeIn(change_labels[-1]), FadeIn(change_arrows[-1]), FadeIn(totals[-1]), )) self.wait() # Change it alt_change = data[-2] - data[-3] alt_total = data[-2] + alt_change alt_gf = 1 self.play( ChangeDecimalToValue(gf_labels[-1][-1], alt_gf), ChangeDecimalToValue(gf_labels[-1][0][0], alt_change), ChangeDecimalToValue(change_labels[-1], alt_change), ChangeDecimalToValue(totals[-1], alt_total), ) self.wait() class ContrastRandomShufflingWithClustersAndTravel(Scene): def construct(self): background = FullScreenFadeRectangle() background.set_fill(GREY_E) self.add(background) squares = VGroup(*[Square() for x in range(2)]) squares.set_width(FRAME_WIDTH / 2 - 1) squares.arrange(RIGHT, buff=0.75) squares.to_edge(DOWN) squares.set_fill(BLACK, 1) squares.stretch(0.8, 1) self.add(squares) titles = VGroup( OldTexText("Random shuffling"), OldTexText("Clusters with travel"), ) for title, square in zip(titles, squares): title.scale(1.4) title.next_to(square, UP) titles[1].align_to(titles[0], UP) self.play(LaggedStartMap( FadeInFrom, titles, lambda m: (m, 0.25 * DOWN), )) self.wait() class ShowVaryingExpFactor(Scene): def construct(self): factor = DecimalNumber(0.15) rect = BackgroundRectangle(factor, buff=SMALL_BUFF) rect.set_fill(BLACK, 1) arrow = Arrow( factor.get_right(), factor.get_right() + 4 * RIGHT + 0.5 * DOWN, ) self.add(rect, factor, arrow) for value in [0.05, 0.25, 0.15]: self.play( ChangeDecimalToValue(factor, value), run_time=3, ) self.wait() class ShowVaryingBaseFactor(ShowLogisticCurve): def construct(self): factor = DecimalNumber(1.15) rect = BackgroundRectangle(factor, buff=SMALL_BUFF) rect.set_fill(BLACK, 1) self.add(rect, factor) for value in [1.05, 1.25, 1.15]: self.play( ChangeDecimalToValue(factor, value), run_time=3, ) self.wait() class ShowVaryingExpCurve(ShowLogisticCurve): def construct(self): axes = self.get_axes() self.add(axes) curve = axes.get_graph(lambda x: np.exp(0.15 * x)) curve.set_stroke([BLUE, YELLOW, RED]) curve.make_jagged() self.add(curve) self.camera.frame.scale(2, about_edge=DOWN) self.camera.frame.shift(DOWN) rect = FullScreenFadeRectangle() rect.set_stroke(WHITE, 3) rect.set_fill(opacity=0) self.add(rect) for value in [0.05, 0.25, 0.15]: new_curve = axes.get_graph(lambda x: np.exp(value * x)) new_curve.set_stroke([BLUE, YELLOW, RED]) new_curve.make_jagged() self.play( Transform(curve, new_curve), run_time=3, ) class EndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "1stViewMaths", "Adam Dřínek", "Aidan Shenkman", "Alan Stein", "Alex Mijalis", "Alexis Olson", "Ali Yahya", "Andrew Busey", "Andrew Cary", "Andrew R. Whalley", "Aravind C V", "Arjun Chakroborty", "Arthur Zey", "Austin Goodman", "Avi Finkel", "Awoo", "AZsorcerer", "Barry Fam", "Bernd Sing", "Boris Veselinovich", "Bradley Pirtle", "Brian Staroselsky", "Britt Selvitelle", "Britton Finley", "Burt Humburg", "Calvin Lin", "Charles Southerland", "Charlie N", "Chenna Kautilya", "Chris Connett", "Christian Kaiser", "cinterloper", "Clark Gaebel", "Colwyn Fritze-Moor", "Cooper Jones", "Corey Ogburn", "D. Sivakumar", "Daniel Herrera C", "Dave B", "Dave Kester", "dave nicponski", "David B. Hill", "David Clark", "David Gow", "Delton Ding", "Dominik Wagner", "Douglas Cantrell", "emptymachine", "Eric Younge", "Eryq Ouithaqueue", "Federico Lebron", "Frank R. Brown, Jr.", "Giovanni Filippi", "Hal Hildebrand", "Hitoshi Yamauchi", "Ivan Sorokin", "Jacob Baxter", "Jacob Harmon", "Jacob Hartmann", "Jacob Magnuson", "Jake Vartuli - Schonberg", "Jameel Syed", "Jason Hise", "Jayne Gabriele", "Jean-Manuel Izaret", "Jeff Linse", "Jeff Straathof", "John C. Vesey", "John Haley", "John Le", "John V Wertheim", "Jonathan Heckerman", "Jonathan Wilson", "Joseph John Cox", "Joseph Kelly", "Josh Kinnear", "Joshua Claeys", "Juan Benet", "Kai-Siang Ang", "Kanan Gill", "Karl Niu", "Kartik Cating-Subramanian", "Kaustuv DeBiswas", "Killian McGuinness", "Kros Dai", "L0j1k", "Lambda GPU Workstations", "Lee Redden", "Linh Tran", "Luc Ritchie", "Ludwig Schubert", "Lukas Biewald", "Magister Mugit", "Magnus Dahlström", "Manoj Rewatkar - RITEK SOLUTIONS", "Mark Heising", "Mark Mann", "Martin Price", "Mathias Jansson", "Matt Godbolt", "Matt Langford", "Matt Roveto", "Matt Russell", "Matteo Delabre", "Matthew Bouchard", "Matthew Cocke", "Mia Parent", "Michael Hardel", "Michael W White", "Mirik Gogri", "Mustafa Mahdi", "Márton Vaitkus", "Nicholas Cahill", "Nikita Lesnikov", "Oleg Leonov", "Oliver Steele", "Omar Zrien", "Owen Campbell-Moore", "Patrick Lucas", "Peter Ehrnstrom", "Peter Mcinerney", "Pierre Lancien", "Quantopian", "Randy C. Will", "rehmi post", "Rex Godby", "Ripta Pasay", "Rish Kundalia", "Roman Sergeychik", "Roobie", "Ryan Atallah", "Samuel Judge", "SansWord Huang", "Scott Gray", "Scott Walter, Ph.D.", "Sebastian Garcia", "soekul", "Solara570", "Steve Huynh", "Steve Sperandeo", "Steven Braun", "Steven Siddals", "Stevie Metke", "supershabam", "Suteerth Vishnu", "Suthen Thomas", "Tal Einav", "Tauba Auerbach", "Ted Suzman", "Thomas J Sargent", "Thomas Tarler", "Tianyu Ge", "Tihan Seale", "Tyler VanValkenburg", "Vassili Philippov", "Veritasium", "Vinicius Reis", "Xuanji Li", "Yana Chernobilsky", "Yavor Ivanov", "YinYangBalance.Asia", "Yu Jun", "Yurii Monastyrshyn", ] }
from manim_imports_ext import * MONSTER_SIZE = 808017424794512875886459904961710757005754368000000000 BABY_MONSTER_SIZE = 4154781481226426191177580544000000 def get_monster(height=3): monster = SVGMobject("monster") monster.set_fill(GREY_BROWN) monster.set_stroke(BLACK, 0.1) monster.set_height(height) return monster def get_baby_monster(): return get_monster().stretch(0.7, 1) def blink_monster(monster): monster.generate_target() left_eye_points = monster.target[0].get_points()[498:528] right_eye_points = monster.target[0].get_points()[582:612] for points in left_eye_points, right_eye_points: points[:, 1] = points[0, 1] return MoveToTarget(monster, rate_func=squish_rate_func(there_and_back, 0.4, 0.6)) def get_size_bars(mob, stroke_width=3, buff=SMALL_BUFF): bars = VGroup(*[Line(UP, DOWN) for x in range(2)]) bars.match_height(mob) bars[0].next_to(mob, LEFT, buff=buff) bars[1].next_to(mob, RIGHT, buff=buff) bars.set_stroke(WHITE, stroke_width) return bars def get_monster_size_label(): size_label = OldTexText("{:,}".format(MONSTER_SIZE))[0] size_parts = VGroup(*[ size_label[i:i + 12] for i in range(0, len(size_label), 12) ]) size_parts.arrange(DOWN, buff=SMALL_BUFF, aligned_edge=LEFT) return size_label def get_snowflake(height=2): snowflake = SVGMobject("snowflake") snowflake.set_fill(GREY_C, 1) snowflake.set_gloss(1) snowflake.set_shadow(0.2) snowflake.set_stroke(WHITE, 1) snowflake.set_height(height) return snowflake def get_cube(color=BLUE_D, opacity=1, height=2, frame=None): poor_cube = Cube() cube = Cube(square_resolution=(10, 10)) cube.set_color(color, opacity) cube.center() for face, p_face in zip(cube, poor_cube): face.add(*[ Line3D(p_face.get_points()[i], p_face.get_points()[j], width=0.02, color=GREY_B) for i, j in [(0, 1), (1, 3), (3, 2), (2, 0)] ]) cube.set_height(height) return cube def get_glassy_cube(frame): verts = np.array(list(it.product(*3 * [[-1, 1]]))) edges = [ (v1, v2) for v1, v2 in it.combinations(verts, 2) if sum(v1 == v2) == 2 ] corner_dots = Group(*[ Sphere(resolution=(51, 26),).set_height(0.25).move_to(vert) for vert in verts ]) corner_dots.set_color(GREY_B) edge_rods = Group(*[ Line3D(v1, v2) for v1, v2 in edges ]) faces = Cube(square_resolution=(10, 10)) faces.set_height(2) faces.set_color(BLUE_E, 0.3) faces.add_updater(lambda m, f=frame: m.sort(lambda p: np.dot(p, [np.sign(f.euler_angles[0]) * 0.2, -1, 0.2]))) cube = Group(corner_dots, edge_rods, faces) cube.corner_dots = corner_dots cube.edge_rods = edge_rods cube.faces = faces return cube def get_rot_icon(degrees, mobject, mini_mob_height=1.25): mini_mob = mobject.copy() temp_height = 1.75 mini_mob.set_height(temp_height) mini_mob.set_stroke(width=0) mini_mob.center() angle = min(degrees * DEGREES, 170 * DEGREES) arc1 = Arrow( RIGHT, rotate_vector(RIGHT, angle), path_arc=angle, buff=0 ) arc2 = arc1.copy().rotate(PI, about_point=ORIGIN) label = Integer(degrees, unit="^\\circ") label.set_height(0.25) half_vect = rotate_vector(RIGHT, angle / 2) label.next_to(half_vect, half_vect, buff=MED_SMALL_BUFF) icon = VGroup(mini_mob, arc1, arc2, label) icon.scale(mini_mob_height / temp_height) return icon def get_flip_icon(angle, mobject, opacity=0.75, mini_mob_height=1.25): mini_mob = mobject.copy() mini_mob.set_stroke(width=0) mini_mob.set_fill(opacity=opacity) mini_mob.set_height(mini_mob_height) mini_mob.center() sym_line = DashedLine(LEFT, RIGHT) sym_line.set_stroke(WHITE, 2) sym_line.set_width(1.2 * mini_mob_height) sym_line.rotate(angle) sym_line.move_to(mini_mob) back_line = sym_line.copy() back_line.set_stroke(BLACK, 5) return VGroup(mini_mob, back_line, sym_line) def get_permutation_arrows(mobs, permutation, arc=PI / 2): arrows = VGroup() for i in range(len(permutation)): j = permutation[i] u = -1 if mobs[i].get_x() < mobs[j].get_x() else 1 arrow = Arrow( mobs[i].get_edge_center(u * UP), mobs[j].get_edge_center(u * UP), buff=SMALL_BUFF, path_arc=arc, ) arrow.insert_n_curves(10) arrow.set_stroke(BLACK, 2, background=True) arrow.set_fill(BLUE, 0.8) arrows.add(arrow) return arrows def permutation_animation(mobs, perm=None, arc=PI / 2, lag_factor=3, run_time=None): if perm is None: targets = list(mobs) random.shuffle(targets) else: targets = [mobs[i] for i in perm] kw = {"lag_ratio": lag_factor / len(mobs)} if run_time is not None: kw["run_time"] = run_time return LaggedStart( *[ ApplyMethod(m1.move_to, m2, path_arc=arc) for m1, m2 in zip(mobs, targets) ], **kw ) def get_named_image(name, height=3): image = ImageMobject(name) image.set_height(height) name = OldTexText(name) name.match_width(image) name.next_to(image, DOWN) group = Group(image, name) return group # Scenes class Thumbnail(Scene): def construct(self): monster = get_monster() monster.set_height(7) monster.to_edge(LEFT) monster.set_gloss(0.2) words = VGroup( OldTexText("The"), OldTexText("Monster"), OldTexText("Group"), ) words.scale(3.5) words.arrange(DOWN, buff=0.5, aligned_edge=LEFT) words.set_stroke(BLACK, 3, background=True) words.to_edge(RIGHT) self.add(monster) self.add(words) class AltThumbnail(ThreeDScene): def construct(self): 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_B, 3) self.add(lines) mob_width = FRAME_WIDTH / 3 - 1 titles = VGroup(Text("Symmetry"), Text("Abstraction"), Text("Monsters")) titles.set_width(mob_width + 0.5) for title, x in zip(titles, [-1, 0, 1]): title.set_x(x * FRAME_WIDTH / 3) title.to_edge(UP) self.add(titles) 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_width(mob_width) cubes.match_x(titles[0]) cubes.set_y(-0.5) cubes.set_color(BLUE_D) cubes.set_shadow(0.65) cubes.set_gloss(0.5) self.add(cubes) eq = OldTex("f(gh)", "=", "(fg)h") eq[1].rotate(90 * DEGREES) eq.arrange(DOWN) eq.match_height(cubes) eq.center() eq.match_y(cubes) self.add(eq) monster = get_monster() monster.set_fill(GREY_BROWN) monster.set_gloss(0.5) monster.set_width(mob_width) monster.match_x(titles[2]) monster.match_y(cubes) self.add(monster) class AskAboutFavoriteMegaNumber(TeacherStudentsScene): CONFIG = { "background_color": BLACK, } def construct(self): self.remove(self.pi_creatures) # YouTubers title = OldTexText("What's your favorite number $> 1{,}000{,}000$?") title.set_width(FRAME_WIDTH - 1) title.to_edge(UP) images = Group( ImageMobject("standupmaths"), ImageMobject("singingbanana"), ImageMobject("Ben Sparks"), ImageMobject("Zoe Griffiths"), ImageMobject("tomrocksmaths"), ImageMobject("James Tanton"), ImageMobject("blackpenredpen"), ImageMobject("Eddie Woo"), ) images.arrange_in_grid(2, 4, buff=MED_LARGE_BUFF) images.set_width(FRAME_WIDTH - 2) images.next_to(title, DOWN, MED_LARGE_BUFF) self.play( FadeIn(title, DOWN), LaggedStartMap( FadeIn, images, lambda m: (m, -0.1 * m.get_center()), lag_ratio=0.3, run_time=5, ) ) self.wait() # Pi Creatures self.teacher_says( "And we want\\\\you to join!", target_mode="surprised", bubble_config={ "height": 3, "width": 4, }, added_anims=[ VFadeIn(self.pi_creatures), images.scale, 0.2, images.space_out_submobjects, 10, images.set_opacity, 0, ], ) self.remove(images) self.play_student_changes("guilty", "hooray", "wave_2") self.wait(5) class IntroduceMonsterSize(Scene): def construct(self): # Show number max_width = FRAME_WIDTH - 1 size_label = OldTexText("{:,}".format(MONSTER_SIZE))[0] size_label.set_width(max_width) n_syms = len(size_label) partials = VGroup() for n in range(len(size_label) + 1): partial = size_label[:n].copy() partial.set_height(1.5) if partial.get_width() > max_width: partial.set_width(max_width) partial.center() partial.set_color(interpolate_color(BLUE, YELLOW, n / n_syms)) partials.add(partial) self.play( UpdateFromAlphaFunc( size_label, lambda m, a: m.set_submobjects( partials[int(a * n_syms)].submobjects ), run_time=6, rate_func=bezier([0, 0, 1, 1]) ) ) self.wait() # Show factorization factors = OldTex( r"= 2^{46} \cdot 3^{20} \cdot 5^{9} \cdot 7^{6} \cdot 11^{2} \cdot 13^{3} \cdot 17 \cdot 19 \cdot 23 \cdot 29 \cdot 31 \cdot 41 \cdot 47 \cdot 59 \cdot 71" ) factors.set_width(max_width) approx = OldTex("\\approx 8\\times 10^{53}") approx.set_height(0.8) approx.move_to(DOWN) factors.next_to(approx, UP, buff=MED_LARGE_BUFF) self.play( size_label.next_to, factors, UP, MED_LARGE_BUFF, FadeIn(factors, 0.5 * DOWN), Write(approx), ) self.wait() value_group = VGroup(size_label, factors, approx) # Jupiter jupiter = TexturedSurface(Sphere(), "JupiterTexture") jupiter.rotate(90 * DEGREES, RIGHT) jupiter.set_height(3.5) jupiter.to_edge(DOWN) jupiter.add_updater(lambda m, dt: m.rotate(-0.1 * dt, UP)) jupiter.set_shadow(0.9) self.play( UpdateFromAlphaFunc(jupiter, lambda m, a: m.set_opacity(a)), ApplyMethod(value_group.to_edge, UP, run_time=2) ) self.wait(4) # Alternate intelligences alien = SVGMobject("alien") alien.set_height(3) alien.to_corner(DL) alien.set_stroke(GREEN, width=0) alien.set_fill(GREEN_E, 1) server = SVGMobject("server_stack") server.set_height(3) server.to_corner(DR) server.set_stroke(BLACK, 2) server.set_fill(GREY, 1) server.set_gloss(0.5) alien_words = OldTexText("Interesting!") alien_words.set_color(GREEN) alien_words.next_to(alien, UR, buff=-MED_SMALL_BUFF) server_words = OldTexText("Very interesting\\\\indeed!") server_words.next_to(server, LEFT) self.play( FadeOut(jupiter, DOWN), DrawBorderThenFill(alien), ) self.play(Write(server)) self.wait() for words in alien_words, server_words: self.play(Write(words, run_time=1)) self.wait() # What is it? question = OldTexText("What is it?") question.scale(2) question.move_to(UP) self.play( LaggedStartMap( FadeOut, VGroup(factors, approx, alien_words, alien, server_words, server), lambda m: (m, DOWN), ), ApplyMethod(size_label.move_to, 0.5 * DOWN, run_time=2), FadeIn(question, UP, run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1)), ) self.wait() monster = get_monster() monster.next_to(size_label, UP) monster.to_edge(RIGHT, buff=2) m_size_bars = get_size_bars(monster, buff=MED_SMALL_BUFF, stroke_width=5) self.play( question.shift, 2 * LEFT, DrawBorderThenFill(monster), run_time=2, ) self.play(ShowCreation(m_size_bars, lag_ratio=0.4)) self.wait(2) self.play(LaggedStart(*[ FadeOut(mob, DOWN) for mob in self.mobjects ])) class IntroduceGroupTheory(Scene): def construct(self): # Title over_title = OldTexText("An introduction\\\\to") over_title.scale(2.5) over_title.move_to(ORIGIN, DOWN) title = OldTexText("Group theory") title.scale(2.5) title.next_to(over_title, DOWN, buff=0.5) arrows = VGroup(Vector(DOWN), Vector(UP)) arrows.arrange(RIGHT, buff=SMALL_BUFF) arrows.scale(2) arrows.next_to(title, DOWN, buff=MED_LARGE_BUFF) sym_amb = SVGMobject("symmetry_ambigram") sym_amb.set_stroke(width=0) sym_amb.set_fill(BLUE, 1) sym_amb.match_width(title) sym_amb.next_to(arrows, DOWN) sym_amb_ghost = sym_amb.copy() sym_amb_ghost.set_fill(WHITE, 0.2) self.add(over_title, title) self.wait() self.play( title.scale, 2.0 / 2.5, title.to_edge, UP, FadeOut(over_title, UP) ) self.play(FadeIn(title, DOWN)) self.play( LaggedStartMap(GrowArrow, arrows, run_time=1), Write(sym_amb, run_time=2) ) self.add(sym_amb_ghost, sym_amb) self.play(Rotate(sym_amb, PI, run_time=2)) self.remove(sym_amb_ghost) self.wait() # Symmetries of a face face = ImageMobject("average_face") face.set_height(5) sym_word = OldTexText("Symmetric") sym_word.scale(2) sym_word.to_edge(UP) face.next_to(sym_word, DOWN, buff=MED_LARGE_BUFF) sym_word.save_state() sym_word.replace(sym_amb) sym_word.set_opacity(0) face_citation = OldTexText("``Average face'' from the Face Research Lab\\\\DeBruine, Lisa \\& Jones, Benedict (2017)") face_citation.set_height(0.4) face_citation.next_to(face, DOWN) face_citation.to_corner(DL) sym_line = DashedLine(face.get_top(), face.get_bottom()) sym_line.scale(1.05) sym_line.set_stroke(WHITE, 2) self.play( FadeIn(face, DOWN), FadeIn(face_citation), LaggedStartMap(FadeOut, VGroup(*arrows, title), lambda m: (m, UP)), sym_amb.replace, sym_word.saved_state, {"stretch": True}, sym_amb.set_opacity, 0, Restore(sym_word), ) self.remove(sym_amb) self.wait() self.play(ShowCreation(sym_line), FadeOut(face_citation)) sym_line.rotate(PI) self.play(ApplyMethod(face.stretch, -1, 0, run_time=2)) self.wait() sym_to_action = OldTexText("Symmetry", " $\\Rightarrow$ ", "\\emph{Action}") sym_to_action.set_color_by_tex("Action", YELLOW) sym_to_action.replace(sym_word, dim_to_match=1) self.play( ReplacementTransform(sym_word[0], sym_to_action[0]), Write(sym_to_action[1]), FadeIn(sym_to_action[2], LEFT), ) self.play(ApplyMethod(face.stretch, -1, 0, run_time=2)) self.wait() # Symmetries of a snowflake snowflake = get_snowflake() snowflake.set_height(5) snowflake.next_to(sym_to_action, DOWN, MED_LARGE_BUFF) self.play( FadeOut(face), Uncreate(sym_line), ShowCreationThenFadeOut(snowflake.copy().set_stroke(WHITE, 2).set_fill(opacity=0)), FadeIn(snowflake, run_time=2), ) def get_flake_rot_icon(degrees, snowflake=snowflake): return get_rot_icon(degrees, snowflake) def get_flake_flip_icon(angle, snowflake=snowflake): return get_flip_icon(angle, snowflake) rot_icons = VGroup( get_flake_rot_icon(60), get_flake_rot_icon(120), ) flip_icons = VGroup( get_flake_flip_icon(60 * DEGREES), get_flake_flip_icon(30 * DEGREES), ) for icons, vect in [(rot_icons, LEFT), (flip_icons, RIGHT)]: icons.arrange(DOWN, buff=MED_LARGE_BUFF) icons.to_edge(vect) self.play( FadeIn(rot_icons[0]), Rotate(snowflake, 60 * DEGREES) ) self.wait() self.play( FadeIn(rot_icons[1]), Rotate(snowflake, 120 * DEGREES) ) self.wait() sym_line = DashedLine(snowflake.get_bottom(), snowflake.get_top()) sym_line.scale(1.1) sym_line.set_stroke(WHITE, 2) sym_line.set_angle(60 * DEGREES) sym_line.move_to(snowflake) self.play( ShowCreation(sym_line), FadeIn(flip_icons[0]), ) self.play( Rotate(snowflake, PI, axis=rotate_vector(RIGHT, 60 * DEGREES)), ) self.play( sym_line.set_angle, 30 * DEGREES, sym_line.move_to, snowflake, FadeIn(flip_icons[1]), ) self.play( Rotate(snowflake, PI, axis=rotate_vector(RIGHT, 30 * DEGREES)), ) # Collection of all snowflake symmetries rot_icons.generate_target() flip_icons.generate_target() d6_group = VGroup( get_flake_rot_icon(0), rot_icons.target[0], rot_icons.target[1], get_flake_rot_icon(180), get_flake_rot_icon(-120), get_flake_rot_icon(-60), get_flake_flip_icon(0), flip_icons.target[1], flip_icons.target[0], get_flake_flip_icon(90 * DEGREES), get_flake_flip_icon(120 * DEGREES), get_flake_flip_icon(150 * DEGREES), ) d6_group.arrange_in_grid(2, 6) d6_group.set_width(FRAME_WIDTH - 2) d6_group.set_gloss(0) d6_group.set_shadow(0) for mob in d6_group.get_family(): if isinstance(mob, SVGMobject): mob.set_fill(GREY_C, 1) mob.set_stroke(WHITE, 0.25) self.play( MoveToTarget(rot_icons), MoveToTarget(flip_icons), ApplyMethod(snowflake.scale, 0, remover=True), ApplyMethod(sym_line.scale, 0, remover=True), ) self.play(LaggedStartMap(FadeIn, d6_group)) self.remove(rot_icons, flip_icons) self.wait() # Name groups group_name = OldTexText("Group", "$^*$") group_name.scale(2) group_name.to_edge(UP) footnote = OldTexText("$^*$er...kind of. Keep watching") footnote.set_height(0.3) footnote.to_corner(UR) footnote.add(group_name[1]) footnote.set_color(YELLOW) group_name.remove(group_name[1]) d6_rect = SurroundingRectangle(d6_group) d6_rect.set_stroke(BLUE, 2) self.play( FadeOut(sym_to_action, UP), FadeIn(group_name, DOWN), ShowCreation(d6_rect), ) self.play( FadeIn( footnote, rate_func=there_and_back_with_pause, run_time=3, remover=True ) ) self.wait() anims = [] for icon, deg in zip(d6_group[1:], [60, 120, 180, -120, -60]): anims.append(Rotate(icon[0], deg * DEGREES)) for icon, deg in zip(d6_group[6:], range(0, 180, 30)): anims.append(Rotate(icon[0], PI, axis=rotate_vector(RIGHT, deg * DEGREES))) random.shuffle(anims) self.play(LaggedStart(*anims, lag_ratio=0.3, run_time=5)) self.play(LaggedStart(*reversed(anims), lag_ratio=0.3, run_time=5)) # Identity id_rect = SurroundingRectangle(d6_group[0]) id_words = OldTexText("The do-nothing", "\\\\action", alignment="") id_words.to_corner(UL) id_arrow = Arrow(id_words[1].get_bottom(), id_rect.get_top(), buff=0.2) id_arrow.match_color(id_rect) self.play( ShowCreation(id_rect) ) self.play( FadeIn(id_words, lag_ratio=0.1), GrowArrow(id_arrow), ) self.wait() # Count d6 rects = VGroup(id_rect, *map(SurroundingRectangle, d6_group[1:])) counter = Integer(0) counter.set_height(0.8) counter.next_to(d6_rect, DOWN, MED_LARGE_BUFF) counter.set_color(YELLOW) counter.add_updater(lambda m, rects=rects: m.set_value(len(rects))) self.add(counter) self.play( FadeOut(id_words), FadeOut(id_arrow), ShowIncreasingSubsets(rects, int_func=np.ceil, run_time=2), UpdateFromAlphaFunc(counter, lambda m, a: m.set_opacity(a)) ) self.wait() d6_name = OldTex("D_6") d6_name.scale(2) d6_name.move_to(counter) d6_name.set_color(BLUE) self.play( FadeOut(rects, lag_ratio=0.1), FadeOut(counter, 0.2 * UP), FadeIn(d6_name, 0.2 * DOWN), ) self.wait() # Name C2 face_group = Group(face, face.deepcopy()) face_group.set_height(4) face_group.arrange(RIGHT, buff=LARGE_BUFF) face_group.next_to(group_name, DOWN, MED_LARGE_BUFF) sym_line = DashedLine(2 * UP, 2 * DOWN) sym_line.set_stroke(WHITE, 2) sym_line.move_to(face_group[1]) sym_line.set_height(face_group[1].get_height() * 1.1) face_group[1].add(sym_line) self.play( d6_rect.replace, face_group, {"stretch": True}, d6_rect.scale, 1.1, FadeOut(d6_group), FadeOut(d6_name, DOWN), *[ FadeIn(f, -0.5 * f.get_center()) for f in face_group ], ) self.play(face_group[1].stretch, -1, 0) self.wait() z2_name = OldTex("C_2") z2_name.match_color(d6_name) z2_name.match_height(d6_name) z2_name.next_to(d6_rect, DOWN, MED_LARGE_BUFF) self.play(Write(z2_name)) self.wait() class ZooOfGroups(ThreeDScene): def construct(self): self.camera.light_source.move_to([-10, 5, 20]) dot_pair = VGroup(Dot(), Dot()) dot_pair.set_height(0.5) dot_pair.arrange(RIGHT, buff=LARGE_BUFF) dot_pair.set_color(GREY_B) snowflake = get_snowflake(height=2) k4_axes = Group( Line3D(LEFT, RIGHT, color=RED), Line3D(DOWN, UP, color=GREEN), Line3D(IN, OUT, color=BLUE), ) k4_axes.set_height(3) quat_group = OldTex("\\{1, -1, i , -i\\\\j, -j, k, -k\\}") cube = get_cube(color=BLUE_D, opacity=1) cube.rotate(15 * DEGREES, OUT) cube.rotate(80 * DEGREES, LEFT) sphere = Sphere() sphere = Group( sphere, SurfaceMesh(sphere, resolution=(21, 11)) ) sphere[1].set_stroke(WHITE, 0.5, 0.5) sphere.rotate(90 * DEGREES, LEFT) sphere.rotate(0.2 * DEGREES, RIGHT) sphere[0].sort_faces_back_to_front() sphere.rotate(90 * DEGREES, UP) sphere.set_height(3) circle = Circle() circle.set_height(3) monster_object = OldTex("196{,}", "883") monster_object.arrange(DOWN, buff=0, aligned_edge=LEFT) monster_object.set_height(1.5) monster_object.add(Eyes(monster_object)) monster_object[-1].scale(0.8, about_edge=DR) qubit = OldTex( "\\alpha|0\\rangle + \\beta|1\\rangle", tex_to_color_map={"\\alpha": BLUE, "\\beta": YELLOW} ) qubit.set_height(1) qubit.set_height(1) groups = Group( Group(OldTex("C_2"), dot_pair), Group(OldTex("D_6"), snowflake), Group(OldTex("K_4"), k4_axes), Group(OldTex("Q_8"), quat_group), Group(OldTex("S_4"), cube), Group(OldTex("SO(3)"), sphere), Group(OldTex("\\mathds{R}^+ / \\mathds{Z}"), circle), Group(OldTex("SU(2)"), qubit), Group(get_monster(), monster_object), ) for group in groups: group[0].set_height(1) group.arrange(RIGHT, buff=LARGE_BUFF) groups[-1][0].scale(2) groups.arrange_in_grid(3, 3) groups.set_width(FRAME_WIDTH - 1) groups[:3].shift(0.5 * UP) groups[-3:].shift(0.5 * DOWN) self.play(LaggedStart(*[ FadeIn(group[0], -0.5 * group.get_center()) for group in groups ])) self.play(LaggedStart(*[ FadeInFromLarge(group[1]) for group in groups ])) self.play(LaggedStart( Rotate(dot_pair, PI), Blink(monster_object[-1]), Rotate(cube, PI / 2, axis=cube[0].get_center() - cube[-1].get_center()), Rotate(snowflake, 120 * DEGREES), Rotate(k4_axes, PI, axis=RIGHT), Rotate(sphere, 170 * DEGREES, axis=UP), run_time=3, lag_ratio=0.1, )) self.wait() self.play( groups[-1].scale, 3, groups[-1].center, groups[-1].space_out_submobjects, 1.5, *[ FadeOut(mob, mob.get_center() - groups[-1].get_center()) for mob in groups[:-1] ] ) self.play(monster_object[-1].look_at, groups[-1][0]) self.play(Blink(monster_object[-1])) self.play(blink_monster(groups[-1][0])) self.wait() class SymmetriesOfACube(ThreeDScene): def construct(self): # Setup frame = self.camera.frame light = self.camera.light_source light.move_to(5 * LEFT + 20 * DOWN + 10 * OUT) plane = NumberPlane(x_range=(-10, 10), y_range=(-10, 10)) plane.shift(IN) cube = get_cube(color=BLUE_D, opacity=1) cube.set_gloss(0.5) cube.set_shadow(0.2) frame.set_euler_angles( phi=70 * DEGREES, theta=-30 * DEGREES, ) frame.add_updater(lambda m, dt, sc=self: m.set_theta(-30 * DEGREES * np.cos(sc.time * 0.05))) self.add(frame) self.add(plane) self.add(cube) # Ask about structure question = OldTexText("What structure is being preserved?") question.set_height(0.7) question.to_edge(UP) question.fix_in_frame() def get_rotation(deg, axis, cube=cube): return Rotate(cube, deg * DEGREES, axis=axis, run_time=1.5) pairs = [ (90, UP), (90, RIGHT), (90, OUT), (120, [1, 1, 1]), (120, [1, -1, 1]), (180, UP), ] for deg, axis in pairs: self.play(get_rotation(deg, axis)) if axis is pairs[1][1]: self.play(FadeIn(question, DOWN)) self.wait() # Count cube symmetries count_label = OldTexText("24 ", "symmetries") count_label.set_color_by_tex("24", YELLOW) count_label.set_height(0.7) count_label.fix_in_frame() count_label.to_edge(UP) self.play( FadeIn(count_label, DOWN), FadeOut(question, UP), ) self.play(get_rotation(120, [1, -1, -1])) self.wait() self.play(get_rotation(90, LEFT)) self.wait() self.play(get_rotation(120, [1, -1, -1])) self.wait() self.play(get_rotation(180, OUT)) self.wait() # Bigger group reflection_plane = Square3D(resolution=(10, 10)) reflection_plane.set_width(4) reflection_plane.move_to(cube) reflection_plane.set_color(GREY, opacity=0.75) reflection_plane.rotate(PI / 2, DOWN) cross24 = Cross(count_label[0]) cross24.fix_in_frame() label48 = OldTex("48") label48.set_color(GREEN) label48.match_height(count_label[0]) label48.move_to(count_label[0], DOWN) label48.fix_in_frame() self.play(FadeInFromLarge(reflection_plane)) self.play( ShowCreation(cross24), ApplyMethod(cube.stretch, -1, 0), ) self.wait() self.play( Rotate(reflection_plane, PI / 2, axis=UP) ) self.play( ApplyMethod(cube.stretch, -1, 2), ) self.wait() self.play(Rotate(reflection_plane, PI / 4, UP)) self.play( cube.stretch, -1, 2, cube.rotate, PI / 2, UP, ) self.wait() self.add(count_label[0], cross24) self.play( count_label[0].shift, 2 * LEFT, cross24.shift, 2 * LEFT, FadeIn(label48, UP), ) self.play( reflection_plane.rotate, PI / 4, UP, reflection_plane.rotate, PI / 2, OUT, ) self.play( cube.stretch, -1, 1, ) self.wait() self.play(FadeOut(reflection_plane)) self.wait() # Permute faces cross48 = Cross(label48) cross48.fix_in_frame() self.play(ShowCreation(cross48)) label48.add(cross48) label24 = count_label[0] label24.add(cross24) count_label.remove(label24) def explostion_transform(self=self, cube=cube): cube_copy = cube.copy() self.play( cube.space_out_submobjects, 1.5, cube.shift, 0.5 * OUT, ) exploded_cube_copy = cube.copy() self.play(LaggedStart(*[ Rotate( face, axis=face.get_center() - cube.get_center(), angle=random.choice([0, PI / 2, -PI / 2, PI]) ) for face in cube ])) perm = list(range(6)) random.shuffle(perm) globals()['perm'] = perm # TODO self.play(LaggedStart(*[ Transform(face, cube[perm[i]]) for i, face in enumerate(cube) ], lag_ratio=0.1)) cube.become(exploded_cube_copy) self.play(Transform(cube, cube_copy)) self.wait() for x in range(3): explostion_transform() # Largest size count = Integer(188743680) count.fix_in_frame() old_counts = VGroup(label24, label48) old_counts.generate_target() old_counts.target.to_edge(LEFT) count.match_height(old_counts) count.next_to(old_counts.target, RIGHT, buff=LARGE_BUFF) count.set_color(BLUE_B) self.play( MoveToTarget(old_counts), FadeIn(count), count_label.next_to, count, RIGHT, ) for x in range(3): explostion_transform() self.wait(2) class WeirdCubeSymmetryUnderbrace(Scene): def construct(self): brace = Brace(Line(LEFT, RIGHT).set_width(3), DOWN) tex = brace.get_tex("(8^6)(6!)") VGroup(brace, tex).set_color(WHITE) VGroup(brace, tex).set_stroke(BLACK, 8, background=True) self.play( GrowFromCenter(brace), FadeIn(tex, 0.25 * UP) ) self.wait() class PermutationGroups(Scene): def construct(self): # Setup question = OldTexText("What about no structure?") question.scale(1.5) question.to_edge(UP) perm_words = OldTexText("All ", "permutations") perm_words.scale(1.5) perm_words.next_to(question, DOWN, buff=0.7) perm_words.set_color(BLUE) dots = VGroup(*[Dot() for x in range(6)]) dots.set_fill(GREY_B) dots.set_height(0.5) dots.arrange(RIGHT, buff=LARGE_BUFF) dots.shift(DOWN) alt_dots = dots.copy() self.add(question) self.play(ShowIncreasingSubsets(dots)) # Permutations def get_permutation(self=self, dots=dots, arc=PI / 2): perm = list(range(len(dots))) random.shuffle(perm) arrows = get_permutation_arrows(dots, perm, arc) for i, dot in enumerate(dots): dot.target = dots[perm[i]] arrows.set_opacity(0) return Succession( UpdateFromAlphaFunc(arrows, lambda m, a: m.set_opacity(a)), LaggedStartMap(MoveToTarget, dots, path_arc=arc, lag_ratio=0.15, run_time=2), UpdateFromAlphaFunc(arrows, lambda m, a: m.set_opacity(1 - a)), ) permutations = Succession(*[ get_permutation() for x in range(20) ]) animated_perm_mob = cycle_animation(permutations) self.add(animated_perm_mob) self.wait(5) self.play(FadeIn(perm_words, UP)) self.wait(10) # Count perms perm_count = OldTex("6!") perm_count.match_height(perm_words[0]) perm_count.match_color(perm_words[0]) perm_count.move_to(perm_words[0], RIGHT) full_count = Integer(720, edge_to_fix=RIGHT) full_count.match_height(perm_count) full_count.move_to(perm_count, DR) full_count.shift(0.7 * RIGHT) full_count.match_color(perm_count) equals = OldTex("=") equals.scale(1.5) equals.next_to(full_count, LEFT) equals.match_color(perm_count) perm_count.next_to(equals, LEFT) full_count.set_value(0) self.remove(animated_perm_mob) dots = alt_dots self.add(alt_dots) self.play( FadeIn(full_count, LEFT), FadeOut(perm_words[0], RIGHT), perm_words[1].shift, 0.7 * RIGHT, ) all_perms = list(it.permutations(range(6))) arrows = VGroup() self.add(arrows) self.play( ChangeDecimalToValue(full_count, 720), UpdateFromAlphaFunc( arrows, lambda m, a, dots=dots, all_perms=all_perms: m.set_submobjects( get_permutation_arrows(dots, all_perms[int(np.round(719 * a))]) ) ), run_time=20, ) self.play( FadeIn(perm_count, RIGHT), Write(equals), ) self.wait(2) perm_label = VGroup(perm_count, equals, full_count, perm_words[1]) # Revisit snowflake symmetries dots.generate_target() for dot, point in zip(dots.target, compass_directions(6, UP)): dot.move_to(2 * point) self.play( FadeOut(arrows), FadeOut(perm_label, UP), FadeOut(question, 0.5 * UP), MoveToTarget(dots), ) lines = VGroup() for d1, d2 in it.combinations(dots, 2): lines.add(Line( d1.get_center(), d2.get_center(), buff=d1.get_width() / 4, )) lines.set_stroke(WHITE, 2) hexy = VGroup(dots, lines) hexy.unlock_unit_normal() self.play(LaggedStartMap(ShowCreation, lines)) self.wait() self.play(Rotate(hexy, 60 * DEGREES)) self.wait() self.play(Rotate(hexy, -120 * DEGREES)) self.wait() self.play(Rotate(hexy, PI, axis=UP)) self.wait() self.play(Rotate(hexy, PI, axis=rotate_vector(RIGHT, 60 * DEGREES))) self.wait() # Back to a row dots.generate_target() dots.target.arrange(RIGHT, buff=LARGE_BUFF) dots.target.move_to(0.5 * DOWN) for line in lines: line.generate_target() line.target.set_angle(0) line.target.set_stroke(WHITE, 0, 0) perm_label.to_edge(UP, buff=LARGE_BUFF) self.play( MoveToTarget(dots), FadeIn(perm_label), LaggedStartMap(MoveToTarget, lines, run_time=1.5) ) # Bump it up to 12 new_dots = dots.copy() new_dots.shift(1.5 * DOWN) new_perm_label = VGroup( OldTex("12!"), OldTex("="), Integer(math.factorial(12)), OldTexText("permutations")[0], ) new_perm_label.arrange(RIGHT) new_perm_label.match_height(perm_label) new_perm_label.set_color(YELLOW) new_perm_label.move_to(perm_label) new_perm_label[0].align_to(perm_label[2][0], DOWN) old_full_count_center = full_count.get_center() self.play( ChangeDecimalToValue( perm_label[2], new_perm_label[2].get_value(), run_time=3 ), UpdateFromAlphaFunc( perm_label[2], lambda m, a: m.move_to(interpolate( old_full_count_center, new_perm_label[2].get_center(), a )).set_color(interpolate_color(BLUE, YELLOW, a)) ), ShowIncreasingSubsets(new_dots), *[ ReplacementTransform(perm_label[i], new_perm_label[i]) for i in [0, 1, 3] ] ) self.remove(perm_label) perm_label = new_perm_label self.add(perm_label) dots.add(*new_dots) self.wait() for x in range(5): perm = list(range(12)) random.shuffle(perm) self.play(LaggedStart(*[ Transform(dots[i], dots[perm[i]], path_arc=PI / 2) for i in range(12) ])) self.wait() # Show 101 dots new_perm_label = VGroup( OldTex("101!"), OldTex("\\approx"), OldTex("9.43 \\times 10^{159}"), OldTexText("permutations")[0] ) new_perm_label.arrange(RIGHT) new_perm_label.match_height(perm_label) new_perm_label[2].align_to(new_perm_label[0], DOWN) new_perm_label[3].shift(SMALL_BUFF * DOWN) new_perm_label.move_to(perm_label, RIGHT) new_dots = VGroup(*[dots[0].copy() for x in range(101)]) new_dots.arrange_in_grid(7, 13) new_dots.set_height(5) new_dots.to_edge(DOWN) self.play( FadeOut(perm_label), FadeIn(new_perm_label), ReplacementTransform(dots, new_dots[-len(dots):]), ShowIncreasingSubsets(new_dots[:-len(dots)], run_time=2) ) self.add(new_dots) perm_label = new_perm_label dots = new_dots labels = VGroup() for i, dot in enumerate(new_dots): label = Integer(i + 1, fill_color=BLACK) label.replace(dot, dim_to_match=1) label.scale(0.3) labels.add(label) labels.set_stroke(width=0) self.play(FadeIn(labels)) self.remove(labels) for dot, label in zip(dots, labels): dot.add(label) for x in range(6): self.play(permutation_animation(dots, lag_factor=1)) self.wait(0.5) # Name S_n perm_label[3].generate_target() new_perm_label = VGroup( OldTex("n!").match_height(perm_label[0]), perm_label[3].target, ) new_perm_label.arrange(RIGHT, buff=MED_LARGE_BUFF) new_perm_label[0].align_to(new_perm_label[1][-1], DOWN) new_perm_label.next_to(perm_label[0], RIGHT, MED_LARGE_BUFF) new_perm_label[0].save_state() new_perm_label[0].replace(perm_label[0], stretch=True) new_perm_label[0].set_opacity(0) Sn_name = OldTex("S_n") Sn_name.match_height(new_perm_label) Sn_name.next_to(new_perm_label, RIGHT, buff=LARGE_BUFF) Sn_name.set_color(YELLOW) self.play( perm_label[0].replace, new_perm_label[0], {"stretch": True}, perm_label[0].set_opacity, 0, FadeOut(perm_label[1:3], RIGHT), MoveToTarget(perm_label[3]), Restore(new_perm_label[0]), ) self.play(FadeIn(Sn_name, LEFT)) self.remove(perm_label) perm_label = new_perm_label self.add(perm_label) self.play(permutation_animation(dots)) # Down to a square new_dots = dots[:4] faders = dots[4:] new_dots.generate_target() for dot in new_dots.target: dot.set_height(0.8) new_dots.target.arrange_in_grid(2, 2, buff=LARGE_BUFF) new_dots.target.center() self.play( MoveToTarget(new_dots), FadeOut(faders), ) dots = new_dots for x in range(2): self.play(permutation_animation(dots, [2, 0, 3, 1], lag_factor=0)) self.wait() class IsItUseful(TeacherStudentsScene): def construct(self): self.student_says( "Is any of\\\\this useful?", index=2, target_mode="sassy", added_anims=[self.teacher.change, "guilty"] ) self.play_student_changes("angry", "confused") self.wait(3) self.teacher_says("Extremely!") self.play_student_changes("pondering", "thinking", "pondering", look_at=self.screen) self.wait(4) class SolutionsToPolynomials(Scene): def construct(self): # Show quintic shuffling colors = list(Color(BLUE).range_to(YELLOW, 5)) quintic = OldTex( "x^5 - x - 1", "=", "(x - r_0)", "(x - r_1)", "(x - r_2)", "(x - r_3)", "(x - r_4)", tex_to_color_map={ f"r_{i}": colors[i] for i in range(5) } ) root_syms = VGroup(*[quintic.get_part_by_tex(f"r_{i}") for i in range(5)]) quintic.set_width(FRAME_WIDTH - 1) quintic.to_edge(UP) plane = ComplexPlane(x_range=(-2, 2), y_range=(-2, 2)) plane.set_height(6) plane.to_edge(DOWN, buff=MED_SMALL_BUFF) plane.add_coordinate_labels() for label in plane.coordinate_labels: label.scale(0.7, about_edge=UR) def get_root_dots(roots, plane=plane, colors=colors): return VGroup(*[ Dot( plane.n2p(root), radius=0.1, color=color, ).set_stroke(BLACK, 2, background=True) for root, color in zip(roots, colors) ]) root_dots = get_root_dots([ 1.1673, 0.181232 + 1.08395j, 0.181232 - 1.08395j, -0.764884 + 0.352472j, -0.764884 - 0.352472j, ]) self.add(quintic) self.add(plane) self.play(LaggedStart(*[ ReplacementTransform(rs.copy(), rd) for rs, rd in zip(root_syms, root_dots) ], run_time=3, lag_ratio=0.3)) self.wait() root_syms.save_state() root_dots.save_state() for x in range(5): perm = list(range(5)) random.shuffle(perm) self.play(*[ permutation_animation(mob, perm, arc=30 * DEGREES, lag_factor=0.5) for mob in [root_syms, root_dots] ]) self.wait(0.5) self.play( Restore(root_syms, path_arc=60 * DEGREES), Restore(root_dots, path_arc=60 * DEGREES), ) # Down to quadratic quadratic_lhs = OldTex("x^2 - x - 1") quadratic_lhs.match_height(quintic[0]) quadratic_lhs.move_to(quintic[0], RIGHT) self.play( FadeOut(quintic[0], UP), FadeIn(quadratic_lhs, DOWN), FadeOut(quintic[8:], UP), MaintainPositionRelativeTo(root_dots, plane), UpdateFromAlphaFunc(root_dots, lambda m, a: m.set_opacity(1 - a)), plane.to_edge, LEFT, ) self.remove(root_dots) root_dots.set_opacity(1) root_dots.save_state() quad_root_dots = get_root_dots([ (1 + u * np.sqrt(5)) / 2 for u in [-1, 1] ]) self.play(LaggedStart(*[ ReplacementTransform(root_sym.copy(), root_dot) for root_dot, root_sym in zip(quad_root_dots, root_syms) ])) self.wait() # Quadratic formula quadratic_formula = OldTex( "{-b \\pm \\sqrt{\\,b^2 - 4ac} \\over 2a}", ) quadratic_formula.set_height(1.5) quadratic_formula.to_edge(RIGHT, buff=LARGE_BUFF) quad_form_name = OldTexText("Quadratic formula") quad_form_name.set_height(0.5) quad_form_name.next_to(quadratic_formula, DOWN, LARGE_BUFF) quad_form_name.set_color(GREY_B) self.play( Write(quadratic_formula), FadeIn(quad_form_name, DOWN) ) self.wait() # Cubic cubic_lhs = OldTex("x^3 - x - 1") cubic_lhs.replace(quadratic_lhs) cubic_root_dots = get_root_dots([ 1.3247, -0.66236 + 0.56228j, -0.66236 - 0.56228j, ]) cubic_formula = OldTex( r"\sqrt[3]{-\frac{q}{2}+\sqrt{\frac{q^{2}}{4}+\frac{p^{3}}{27}}}+\sqrt[3]{-\frac{q}{2}-\sqrt{\frac{q^{2}}{4}+\frac{p^{3}}{27}}}", ) cubic_formula.replace(quadratic_formula, dim_to_match=1) cubic_formula.to_edge(RIGHT, buff=MED_SMALL_BUFF) cubic_formula.scale(0.8, about_edge=RIGHT) cubic_form_name = OldTexText("Cubic formula (reduced)") cubic_form_name.replace(quad_form_name, dim_to_match=1) cubic_form_name.match_style(quad_form_name) self.play( ReplacementTransform(quad_root_dots, cubic_root_dots), FadeIn(quintic[8:11], DOWN), FadeIn(cubic_lhs, DOWN), FadeOut(quadratic_lhs, UP), ) self.play( LaggedStart( FadeOut(quadratic_formula, 2 * RIGHT), FadeOut(quad_form_name, 2 * RIGHT), ), LaggedStart( FadeIn(cubic_formula, 2 * LEFT), FadeIn(cubic_form_name, 2 * LEFT), ), ) self.wait() # Quartic (largely copied from above) quartic_lhs = OldTex("x^4 - x - 1") quartic_lhs.replace(quadratic_lhs) quartic_root_dots = get_root_dots([ 1.2207, -0.72449, -0.24813 + 1.0340j, -0.24813 - 1.0340j, ]) quartic_formula = OldTex(r""" r_{i}&=-\frac{b}{4 a}-S \pm \frac{1}{2} \sqrt{-4 S^{2}-2 p \pm \frac{q}{S}}\\\\ &\text{Where}\\\\ p&=\frac{8 a c-3 b^{2}}{8 a^{2}} \qquad \qquad q=\frac{b^{3}-4 a b c+8 a^{2} d}{8 a^{3}}\\\\ S&=\frac{1}{2} \sqrt{-\frac{2}{3} p+\frac{1}{3 a}\left(Q+\frac{\Delta_{0}}{Q}\right)}\\\\ Q&=\sqrt[3]{\frac{\Delta_{1}+\sqrt{\Delta_{1}^{2}-4 \Delta_{0}^{3}}}{2}}\\\\ \Delta_{0}&=c^{2}-3 b d+12 a e\\\\ \Delta_{1}&=2 c^{3}-9 b c d+27 b^{2} e+27 a d^{2}-72 a c e\\\\ """) quartic_formula.set_height(6) quartic_formula.next_to(plane, RIGHT, LARGE_BUFF) self.play( FadeOut(cubic_formula, 2 * RIGHT), FadeOut(cubic_form_name, 2 * RIGHT), ReplacementTransform(cubic_root_dots, quartic_root_dots), FadeIn(quintic[11:14], DOWN), FadeIn(quartic_lhs, DOWN), FadeOut(cubic_lhs, UP), ) self.play( Write(quartic_formula, run_time=3), ) self.wait(2) # Back to quintic self.play( ReplacementTransform(quartic_root_dots, root_dots), FadeIn(quintic[0], DOWN), FadeOut(quartic_lhs, UP), FadeIn(quintic[14:], DOWN), FadeOut(quartic_formula, 0.1 * DOWN, lag_ratio=0.01), ) # Wonder about the quintic mathy = PiCreature(color=GREY) mathy.flip() mathy.next_to(quintic, DOWN, buff=1.5) mathy.to_edge(RIGHT) self.play( VFadeIn(mathy), mathy.change, "confused", root_syms, ) self.play(Blink(mathy)) self.wait() self.play( mathy.change, "pondering", root_syms[3] ) self.play(Blink(mathy)) self.wait() mathy.add_updater(lambda m, sym=root_syms[3]: m.look_at(sym)) # Show a few permutations s5_name = OldTex("S_5") s5_name.scale(1.5) s5_name.next_to(plane, RIGHT, MED_LARGE_BUFF, aligned_edge=UP) s5_name.shift(DOWN) s5_lines = VGroup() for dot in root_dots: line = Line(s5_name.get_left(), dot.get_center()) line.match_color(dot) line.set_stroke(width=1) line.dot = dot line.start = line.get_start() s5_lines.add(line) s5_lines.set_stroke(opacity=0.5) self.play( FadeIn(s5_name), ShowCreation(s5_lines, lag_ratio=0.5), ) for line in s5_lines: line.add_updater(lambda m: m.put_start_and_end_on(m.start, m.dot.get_center())) self.add(*s5_lines) for x in range(5): perm = list(range(5)) random.shuffle(perm) self.play(*[ permutation_animation(mob, perm, arc=30 * DEGREES, lag_factor=0.5) for mob in [root_syms, root_dots] ]) self.wait(0.5) self.play( VFadeOut(s5_lines), Restore(root_syms), Restore(root_dots), FadeOut(mathy), ) # No formula r0_value = OldTex( "r_0", "=", "1.1673\\dots", ) r0_value.set_color_by_tex("r_0", BLUE) r0_value.scale(1.5) r0_value.next_to(plane, RIGHT, MED_LARGE_BUFF) r0_value.shift(DOWN) self.play( LaggedStart(*[ AnimationGroup( ShowCreationThenFadeAround(dot), ShowCreationThenFadeAround(sym), ) for sym, dot in zip(root_syms, root_dots) ], lag_ratio=0.3, run_time=3), ) self.play(TransformFromCopy(root_syms[0], r0_value[0])) self.play(Write(r0_value[1:])) self.add(r0_value) self.wait() # Arithmetic symbols symbols = VGroup(*[ OldTex(s) for s in ["+", "-", "\\times", "/", "\\sqrt[n]{\\qquad}"] ]) symbols[:4].arrange_in_grid(2, 2) symbols[4].next_to(symbols[:4], RIGHT, MED_LARGE_BUFF) symbols.move_to(s5_name) symbols.to_edge(RIGHT) symbols_rect = SurroundingRectangle(symbols, buff=MED_SMALL_BUFF) symbols_rect.set_stroke(BLUE, 2) arrow = Arrow(symbols_rect.get_corner(DL), r0_value[2][3].get_top()) cross = Cross(arrow) cross.stretch(0.5, 1) self.play( FadeIn(symbols, lag_ratio=0.2, run_time=1.5), ShowCreation(symbols_rect), ) self.wait() self.play(GrowArrow(arrow)) self.play(ShowCreation(cross)) self.wait() class MentionGroupsInPhysics(TeacherStudentsScene): def construct(self): # Intro self.teacher_says("Groups are ubiquitous\\\\in physics.") self.play_student_changes("thinking", "happy", "hesitant") self.wait(4) noether = ImageMobject("EmmyNoether") noether.set_height(3) noether.to_corner(UL) nt_label = OldTexText("Noether's theorem") nt_label.set_height(0.5) nt_label.move_to(self.hold_up_spot, DOWN) self.play( FadeIn(nt_label, DOWN), FadeIn(noether, DOWN), FadeOut(VGroup(self.teacher.bubble, self.teacher.bubble.content)), self.teacher.change, "raise_right_hand", ) self.play_student_changes("pondering", "pondering", "thinking", look_at=nt_label) # Theorem nt_label.generate_target() nt_label.target.center().to_edge(UP) rule = VGroup( OldTexText("Conservation law", color=BLUE), OldTex("\\Leftrightarrow"), OldTexText("Symmetry", color=YELLOW), ) rule.set_height(0.5) rule.arrange(RIGHT) rule.next_to(nt_label.target, DOWN, MED_LARGE_BUFF) self.look_at( nt_label.target, added_anims=[MoveToTarget(nt_label)] ) self.play( self.teacher.change, "happy", rule, *[ FadeIn(part, rule.get_center() - part.get_center()) for part in rule ], ) self.wait(2) # Examples examples = VGroup( OldTexText("Momentum", " $\\Leftrightarrow$ ", "Translation in space"), OldTexText("Energy", " $\\Leftrightarrow$ ", "Translation in time"), ) examples.arrange(DOWN, buff=MED_LARGE_BUFF) examples.next_to(rule, DOWN, buff=MED_LARGE_BUFF) for example in examples: example[0].set_color(BLUE) example[2].set_color(YELLOW) example.shift((rule[1].get_x() - example[1].get_x()) * RIGHT) self.play( self.teacher.change, "raise_right_hand", FadeIn(examples[0], UP), self.change_students("confused", "erm", "pondering") ) self.look_at(rule) self.wait() self.play(FadeIn(examples[1], UP)) self.wait(4) self.play_student_changes("thinking", "maybe", "thinking") self.wait(4) class AmbientDodecSymmetries(ThreeDScene): def construct(self): pass class NotGroupsGroupAction(Scene): def construct(self): words = VGroup( OldTexText("Group"), OldTexText("Group", " action"), ) words.scale(2) words.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) words.to_corner(UL) group, group_action = words cross = Cross(group) self.add(group) self.wait() self.play(ShowCreation(cross)) self.play( TransformFromCopy(group[0], group_action[0]), Animation(cross.copy(), remover=True) ) self.play(Write(group_action[1])) self.wait() class ElementsAsAbstractions(TeacherStudentsScene): def construct(self): # Three self.teacher_says("Three") self.wait() s_copies = self.students.copy() s_copies.scale(0.3) bubble = self.students[0].get_bubble( s_copies, width=5, height=4, ) self.play( self.students[0].change, "pondering", Write(bubble), FadeIn(bubble.content, lag_ratio=0.3), ) self.wait(2) numeral = Integer(3) numeral.replace(bubble.content, dim_to_match=1) bubble.content.generate_target() for pi in bubble.content.target: pi.change("horrified") pi.shift(UP) pi.set_opacity(0) self.play(MoveToTarget(bubble.content)) self.remove(bubble.content) self.play( Write(numeral), self.students[0].change, "happy", numeral, ) self.look_at(numeral) self.wait(2) # Element of D6 self.camera.light_source.set_x(0) snowflake = get_snowflake() rot_icon = get_rot_icon(60, snowflake) inclusion = VGroup( rot_icon, OldTex("\\in").scale(2), OldTex("D_6").scale(2), ) inclusion.arrange(RIGHT) inclusion.next_to(self.hold_up_spot, UL, MED_LARGE_BUFF) self.play( LaggedStart( FadeOut(self.teacher.bubble), FadeOut(self.teacher.bubble.content), FadeOut(bubble), FadeOut(numeral), FadeIn(inclusion, DOWN), ), self.teacher.change, "raise_right_hand", ) self.look_at(inclusion) self.wait() self.play(Rotate(rot_icon[0], 60 * DEGREES)) self.wait() rot_icon.generate_target() rot_icon.target.to_corner(UL) r_sym = OldTex("r").scale(2) r_sym.move_to(rot_icon, RIGHT) self.look_at( rot_icon.target, added_anims=[MoveToTarget(rot_icon)], ) self.look_at( r_sym, added_anims=[Write(r_sym)] ) self.play_all_student_changes( "confused", look_at=r_sym, ) self.wait(2) inclusion.remove(rot_icon) inclusion.add(r_sym) # Back to 3 numeral.move_to(self.hold_up_spot, DOWN) self.play( inclusion.to_edge, LEFT, inclusion.set_color, GREY_B, Write(numeral), self.change_students(*3 * ["pondering"], look_at=numeral), self.teacher.change, "tease", numeral, ) self.wait(2) # Operations add = OldTex("3", "+", "5", "=", "8") mult = OldTex("3", "\\cdot", "5", "=", "15") ops = VGroup(add, mult) ops.match_height(numeral) ops.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) ops.to_corner(UR, buff=LARGE_BUFF) self.remove(numeral) self.play( LaggedStart(*[ TransformFromCopy(numeral[0], form[0]) for form in ops ]), *[ ApplyMethod(pi.look_at, ops) for pi in self.pi_creatures ] ) self.play( LaggedStart(*[ Write(form[1:]) for form in ops ]) ) self.wait(3) # Literal forms quincunx = VGroup(*[Dot() for x in range(5)]) quincunx[:4].arrange_in_grid() quincunx.space_out_submobjects(0.7) triplet = VGroup(quincunx[0], quincunx[3], quincunx[4]).copy() triplet.set_color(BLUE) octet = VGroup(*[Dot() for x in range(9)]) octet.arrange_in_grid(3, 3) octet.remove(octet[4]) octet.space_out_submobjects(0.5) sum_dots = VGroup(triplet, quincunx, octet) for sd, sym in zip(sum_dots, ops[0][0::2]): sd.move_to(sym) octet.shift(SMALL_BUFF * RIGHT) quincunx_trip = VGroup(*[quincunx.copy() for x in range(3)]) quincunx_trip.arrange(RIGHT, buff=MED_LARGE_BUFF) for quin in quincunx_trip: rect = SurroundingRectangle(quin) rect.set_stroke(BLUE, 3) quin.add(rect) quincunx_trip.move_to(ops[1][2], RIGHT) fifteen = VGroup(*[Dot() for x in range(15)]) fifteen.arrange_in_grid(3, 5) fifteen.space_out_submobjects(0.5) fifteen.move_to(ops[1][4], LEFT) mult_dots = VGroup(quincunx_trip, fifteen) self.play( FadeOut(ops[0][0::2], UP), FadeIn(sum_dots, DOWN), ) self.play( FadeOut(VGroup(*ops[1][:3], ops[1][4]), UP), FadeIn(mult_dots, DOWN), self.change_students(*3 * ["erm"], look_at=mult_dots), ) self.wait(4) self.play( LaggedStart(*[ ApplyMethod(mob.scale, 0, remover=True) for mob in [*sum_dots, *mult_dots] ]), LaggedStart(*[ FadeIn(mob) for mob in [*ops[0][0::2], *ops[1][:3], ops[1][4]] ]), self.change_students(*3 * ["happy"]), ) self.wait(2) # Show group sum flip_icon = get_flip_icon(0, snowflake) rhs_icon = get_flip_icon(30 * DEGREES, snowflake) rot_icon.generate_target() group_prod = VGroup( rot_icon.target, OldTex("\\times").scale(2), flip_icon, OldTex("=").scale(2), rhs_icon ) group_prod.set_gloss(0) for icon in group_prod[::2]: icon[0].set_stroke(width=0) icon[0].set_fill(GREY_A, 1) group_prod.arrange(RIGHT) group_prod.to_edge(UP) self.play( FadeOut(ops, RIGHT), FadeOut(inclusion, LEFT), MoveToTarget(rot_icon), LaggedStartMap(FadeIn, group_prod[1:], lag_ratio=0.5, run_time=2), self.change_students( "sassy", "erm", "confused", look_at=group_prod, ), self.teacher.change, "raise_right_hand", ) group_prod.replace_submobject(0, rot_icon) self.add(group_prod) self.wait(2) # Show successive actions snowflake = get_snowflake() snowflake.move_to(0.5 * UP) snowflake.match_x(group_prod[1]) alt_flake = snowflake.copy() alt_flake.match_x(rhs_icon) self.play( TransformFromCopy(rot_icon[0], snowflake) ) def get_numbers(flake): vect = 1.2 * (flake.get_top() - flake.get_center()) points = VGroup(*[ VectorizedPoint(rotate_vector(vect, angle)) for angle in np.arange(0, TAU, TAU / 6) ]) points.move_to(flake) numbers = VGroup(*[Integer(i + 1) for i in range(6)]) numbers.scale(0.5) for num, point in zip(numbers, points): num.point = point num.add_updater(lambda m: m.move_to(m.point)) flake.add(points) return numbers sn_nums = get_numbers(snowflake) as_nums = get_numbers(alt_flake) self.play( FadeIn(sn_nums, lag_ratio=0.1), self.change_students(*3 * ["pondering"], look_at=snowflake) ) self.add(*sn_nums) self.play( Rotate(snowflake, PI, RIGHT), ShowCreationThenFadeAround(flip_icon), ) self.wait() self.play( Rotate(snowflake, 60 * DEGREES), ShowCreationThenFadeAround(rot_icon), ) self.wait() self.look_at( alt_flake, added_anims=[TransformFromCopy(rhs_icon[0], alt_flake)] ) self.play(FadeIn(as_nums, lag_ratio=0.1)) self.add(*as_nums) line = rhs_icon.submobjects[-1].copy() line.scale(2) line.set_stroke(YELLOW, 3) line.move_to(alt_flake) self.play(ShowCreation(line)) self.play( Rotate(alt_flake, PI, axis=line.get_vector()) ) self.play( FadeOut(line), self.change_students(*3 * ["thinking"]) ) self.wait(3) class MultiplicationTable(Scene): def construct(self): # Grid grid = VGroup(*[Square() for x in range(64)]) grid.arrange_in_grid(8, 8, buff=0) grid.set_stroke(WHITE, 2) grid.set_height(6.5) grid.to_edge(DOWN, buff=0.5) self.add(grid) # Action icons square = Square() square.rotate(45 * DEGREES) square.set_height(1) square.set_fill(BLUE_D, 1) icons = VGroup( *[ get_rot_icon(deg, square) for deg in [0, 90, 180, -90] ] + [ get_flip_icon(angle, square, opacity=1) for angle in np.arange(0, PI, PI / 4) ] ) icons[0].remove(icons[0][-1]) icons.match_height(grid[0]) icons.scale(0.8) for icon in icons: icon[0].rotate(-45 * DEGREES) left_icons = icons.copy() top_icons = icons.copy() for icon_group, grid_group, vect in [(left_icons, grid[0::8], LEFT), (top_icons, grid[:8], UP)]: for gs, icon in zip(grid_group, icon_group): icon.shift(gs.get_edge_center(vect) - icon[0].get_center()) icon.shift(0.6 * gs.get_width() * vect) for icon in top_icons: icon[0].set_fill(GREY_BROWN) self.add(left_icons, top_icons) # Figure out full table def pmult(perm1, perm2): return [perm1[i] for i in perm2] r = [1, 2, 3, 0] s = [3, 2, 1, 0] r2 = pmult(r, r) r3 = pmult(r2, r) perms = [ list(range(4)), r, r2, r3, s, pmult(r, s), pmult(r2, s), pmult(r3, s), ] table = np.zeros((8, 8), dtype=int) table_icons = VGroup() for n, square in enumerate(grid): i = n // 8 j = n % 8 perm = pmult(perms[i], perms[j]) index = perms.index(perm) table[i, j] = index icon = icons[index].copy() icon[0].set_color(BLUE_E) icon.set_opacity(1) icon.shift(square.get_center() - icon[0].get_center()) pre_icon = VGroup(icon.copy(), icon.copy()) pre_icon.save_state() pre_icon.set_opacity(0) pre_icon[0].move_to(left_icons[i]) pre_icon[1].move_to(top_icons[j]) icon.pre_icon = pre_icon table_icons.add(icon) # Show all product sorted_icons = list(table_icons) frame = self.camera.frame frame.save_state() frame.scale(0.6) frame.move_to(top_icons.get_top() + MED_SMALL_BUFF * UL, UP) turn_animation_into_updater(Restore(frame, run_time=20, rate_func=bezier([0, 0, 1, 1]))) self.add(frame) for sorted_index, icon in enumerate(sorted_icons): n = table_icons.submobjects.index(icon) i = n // 8 j = n % 8 rects = VGroup( SurroundingRectangle(left_icons[i]), SurroundingRectangle(top_icons[j]), grid[n].copy().set_fill(GREEN_E, 0.5) ) rects.set_stroke(YELLOW, 2) self.add(rects, *self.mobjects) self.add(icon) if sorted_index < 8: pass # Don't wait elif sorted_index < 24: self.wait(1) else: self.wait(0.15) self.remove(rects) self.add(table_icons) self.wait(2) # Symbolically symbols = VGroup( OldTex("1"), OldTex("r"), OldTex("r^2"), OldTex("r^3"), OldTex("s"), OldTex("rs"), OldTex("r^2 s"), OldTex("r^3 s"), ) symbols.set_height(0.4 * grid[0].get_height()) left_symbols = symbols.copy() top_symbols = symbols.copy() for symbol_group, icon_group in [(left_symbols, left_icons), (top_symbols, top_icons)]: for symbol, icon in zip(symbol_group, icon_group): symbol.move_to(icon[0], DOWN) table_symbols = VGroup() for n, icon in enumerate(table_icons): i = n // 8 j = n % 8 symbol = symbols[table[i, j]].copy() symbol.move_to(icon[0], DOWN) table_symbols.add(symbol) self.play( LaggedStart(*[ ApplyMethod(mob.scale, 0, remover=True) for mob in [*left_icons, *top_icons, *table_icons] ]), LaggedStart(*[ GrowFromCenter(mob) for mob in [*left_symbols, *top_symbols, *table_symbols] ]), ) self.wait() # Show some products last_rects = VGroup() for x in range(10): n = random.randint(0, 63) i = n // 8 j = n % 8 rects = VGroup( SurroundingRectangle(left_symbols[i]), SurroundingRectangle(top_symbols[j]), grid[n].copy().set_stroke(YELLOW, 4).set_fill(YELLOW, 0.5) ) self.add(rects, *self.mobjects) self.play( FadeOut(last_rects), FadeIn(rects), ) self.wait(2) last_rects = rects self.play(FadeOut(last_rects)) self.wait() class UsualMultiplicationTable(Scene): def construct(self): # Setup grid grid = VGroup(*[ VGroup(*[Square() for x in range(4)]).arrange(RIGHT, buff=0) for y in range(4) ]).arrange(DOWN, buff=0) grid.set_height(6) grid.to_edge(DOWN, buff=0.5) grid.set_fill(GREY_E, 1) dots = VGroup( *[Tex("\\dots").scale(2).next_to(row, RIGHT) for row in grid[:-1]], *[Tex("\\vdots").scale(2).next_to(square, DOWN) for square in grid[-1][:-1]], OldTex("\\ddots").scale(2).next_to(grid[-1][-1], DR), ) self.add(grid) # Setup abstract dots table_dots = VGroup() for i, row in zip(it.count(1), grid): for j, square in zip(it.count(1), row): dots = VGroup(*[Dot() for x in range(i * j)]) dots.arrange_in_grid(i, j, buff=SMALL_BUFF) dots.scale(0.9) dots.move_to(square) table_dots.add(dots) left_dots = table_dots[0::4].copy() left_dots.shift(grid[0][0].get_width() * LEFT) left_dots.set_color(BLUE) top_dots = table_dots[0:4].copy() top_dots.shift(grid[0][0].get_height() * UP) top_dots.set_color(RED) dot_groups = VGroup(left_dots, top_dots, table_dots) # Numerals sym_groups = VGroup() for dot_group in dot_groups: sym_group = VGroup() for dots in dot_group: numeral = Integer(len(dots)) numeral.set_height(0.6) numeral.move_to(dots) numeral.match_color(dots) sym_group.add(numeral) sym_groups.add(sym_group) left_syms, top_syms, table_syms = sym_groups # Add symbols self.add(left_syms, top_syms) self.play(LaggedStart(*[ AnimationGroup( Transform(ls_copies[i].copy(), table_syms[4 * i + j].copy(), remover=True), Transform(ts_copies[j].copy(), table_syms[4 * i + j].copy(), remover=True), ) for i, j in it.product(range(4), range(4)) ], lag_ratio=0.3)) self.add(table_syms) self.wait() # To dots self.play( FadeOut(sym_groups), FadeIn(dot_groups), ) self.wait() # Show a few products last_rects = VGroup() ns = random.sample(range(16), 5) for n in ns: i = n // 4 j = n % 4 rects = VGroup( SurroundingRectangle(left_dots[i]), SurroundingRectangle(top_dots[j]), grid[i][j].copy().set_fill(YELLOW, 0.5), ) rects.set_stroke(YELLOW, 4) self.play(FadeIn(rects), FadeOut(last_rects), run_time=0.5) self.wait() last_rects = rects self.play(FadeOut(last_rects)) # Back to syms self.play( dot_groups.fade, 0.8, FadeIn(sym_groups), ) self.wait() # Benefits frame = self.camera.frame frame.generate_target() frame.target.set_x(grid.get_right()[0]) frame.target.scale(1.1) benefit = VGroup( OldTexText("Abstraction").scale(1.5), Vector(DOWN), OldTexText("Less cumbersome").scale(1.5), ) benefit.arrange(DOWN) benefit.next_to(grid, RIGHT, buff=LARGE_BUFF) turn_animation_into_updater(MoveToTarget(frame, run_time=3)) self.add(frame) self.play(Write(benefit[0])) self.play(GrowArrow(benefit[1])) self.play(FadeIn(benefit[2], UP)) self.wait() class MentionTheMonster(Scene): def construct(self): monster = get_monster() monster.set_height(6) self.add(monster) self.wait() self.play(blink_monster(monster)) self.wait() size_label = get_monster_size_label() size_label.match_height(monster) size_label.to_edge(RIGHT, buff=LARGE_BUFF) self.play( ApplyMethod(monster.next_to, size_label, LEFT, LARGE_BUFF, run_time=2), ShowIncreasingSubsets(size_label, run_time=6) ) self.play(blink_monster(monster)) self.wait() class FrustratedAtGroups(TeacherStudentsScene): def construct(self): formula = OldTex(r"|G|=|Z(G)|+\sum i\left[G: C_{G}\left(x_{i}\right)\right]") formula.move_to(self.hold_up_spot, DOWN) formula.shift(0.5 * UL) self.play( self.teacher.change, "raise_right_hand", FadeIn(formula, DOWN), ) self.play_student_changes("confused", "horrified", "pleading") self.look_at(formula.get_left()) self.wait(2) self.look_at(formula.get_right()) self.wait(2) class WikiPageOnGroups(ExternallyAnimatedScene): pass class AnalogyWithCounts(Scene): def construct(self): # Setup line = Line(LEFT, RIGHT) words = OldTexText("Abstraction of") words.match_width(line) words.scale(0.9) words.next_to(line, UP, SMALL_BUFF) line.add(words) line.rotate(-90 * DEGREES) line.scale(0.5) diagrams = VGroup(*[ VGroup(mob1, line.copy(), mob2) for mob1, mob2 in [ (OldTexText("Groups"), OldTexText("Symmetry actions")), (OldTex("D_6"), get_snowflake(height=1)), (OldTexText("Numbers"), OldTexText("Counts")), (OldTex("9").scale(1.5), VGroup(*[Dot() for x in range(9)]).arrange_in_grid(buff=SMALL_BUFF)), ] ]) for diagram, vect in zip(diagrams, [LEFT, LEFT, RIGHT, RIGHT]): diagram[0].set_color(YELLOW) diagram[2].set_fill(BLUE) diagram.arrange(DOWN) diagram.scale(1.5) diagram.shift(3.5 * vect - diagram[1].get_center()) # Show diagrams self.add(diagrams[0][0]) self.play( Write(diagrams[0][1]), FadeIn(diagrams[0][2], 2 * UP), ) self.wait() self.play(*[ AnimationGroup( ReplacementTransform( m2.copy().replace(m1, stretch=True).set_opacity(0), m2, ), Transform( m1.copy(), m1.copy().replace(m2, stretch=True).set_opacity(0), remover=True ) ) for m1, m2 in zip(diagrams[0], diagrams[2]) ]) self.wait() self.play( FadeOut(diagrams[0]), FadeIn(diagrams[1]), ) flake = diagrams[1][2] self.add(flake) self.play( FadeOut(diagrams[2]), FadeIn(diagrams[3]), Rotate(flake, 60 * DEGREES), ) self.play(Rotate(flake, PI, UP)) self.play(Rotate(flake, -120 * DEGREES)) self.play(Rotate(flake, PI, RIGHT)) self.play(Rotate(flake, 120 * DEGREES)) self.play(Rotate(flake, PI, UP)) self.play( VFadeOut(diagrams[1]), Rotate(flake, 180 * DEGREES), FadeIn(diagrams[0]), FadeOut(diagrams[3]), FadeIn(diagrams[2]), ) self.wait(2) class ButWhy(TeacherStudentsScene): def construct(self): self.student_says( "But, why?", target_mode="maybe", added_anims=[LaggedStart( ApplyMethod(self.teacher.change, "guilty"), ApplyMethod(self.students[0].change, "confused"), ApplyMethod(self.students[1].change, "sassy"), lag_ratio=0.5, )] ) self.wait(3) class CubeRotations(ThreeDScene): def construct(self): # Set frame motion frame = self.camera.frame frame.set_euler_angles(phi=80 * DEGREES) frame.add_updater(lambda m, sc=self: m.set_euler_angles(theta=-20 * DEGREES * np.cos(0.1 * sc.time))) self.add(frame) # Setup cube cube = get_glassy_cube(frame) cube.set_height(3) axes = ThreeDAxes(axis_config={"include_tip": False}) axes.apply_depth_test() self.add(axes) self.add(cube) # Apply rotations quats = self.get_quaternions() self.wait() for quat in quats: angle, axis = angle_axis_from_quaternion(quat) line = Line3D(-5 * axis, 5 * axis, prefered_creation_axis=0) line.set_color(YELLOW) if angle < 1e-6: line.scale(0) # line.apply_depth_test() deg_label = Integer(int(np.round(angle / DEGREES)), unit="^\\circ") deg_label.scale(2) deg_label.to_edge(UP) deg_label.shift(2 * LEFT) deg_label.fix_in_frame() self.add(line, *self.mobjects) self.play(ShowCreation(line), FadeIn(deg_label)) self.play(Rotate(cube, angle, axis=axis)) line.scale(-1) self.play(Uncreate(line), FadeOut(deg_label)) def get_quaternions(self, n_rotations=30): ijk = [ quaternion_from_angle_axis(90 * DEGREES, axis) for axis in [RIGHT, UP, OUT] ] result = [] for x in range(n_rotations): n = random.randint(1, 10) curr = quaternion_from_angle_axis(0, RIGHT) for y in range(n): curr = quaternion_mult(curr, random.choice(ijk)) result.append(curr) # Add on those rotations around diagonals for the end for oi in [OUT, IN]: for vect in [UL, UR, DR, DL]: result.append(quaternion_from_angle_axis(120 * DEGREES, vect + oi)) return result class QuadrupletShufflings(CubeRotations): def construct(self): # Background bg_rect = FullScreenFadeRectangle() bg_rect.set_fill(GREY_E, 1) bg_rect.set_stroke(width=0) self.add(bg_rect) # Setup dots dots = VGroup(*[Dot() for x in range(4)]) dots.set_height(0.5) dots.arrange(RIGHT, buff=MED_LARGE_BUFF) dots.set_color(GREY_B) for n, dot in enumerate(dots): label = Integer(n + 1) label.set_height(0.25) label.set_color(BLACK) label.move_to(dot) dot.add(label) self.add(dots) self.wait() # Permutations for quat in self.get_quaternions(): perm = self.quaternion_to_perm(quat) arrows = get_permutation_arrows(dots, perm) self.play(FadeIn(arrows)) self.play(permutation_animation(dots, perm, lag_factor=0.2, run_time=1)) self.play(FadeOut(arrows)) def quaternion_to_perm(self, quat): angle, axis = angle_axis_from_quaternion(quat) base_vects = [UL, UR, DR, DL] rot_vects = [ rotate_vector(v + OUT, angle, axis) for v in base_vects ] perm = [] for vect in rot_vects: if vect[2] < 0: vect *= -1 vect[2] = 0 i = np.argmin([get_norm(vect - bv) for bv in base_vects]) perm.append(i) return perm class EightShufflingsOfOrderThree(Scene): def construct(self): bg_rect = FullScreenFadeRectangle() bg_rect.set_fill(GREY_E, 1) bg_rect.set_stroke(width=0) self.add(bg_rect) # Setup dots dots_template = VGroup(*[Dot() for x in range(4)]) dots_template.set_height(0.5) dots_template.arrange(RIGHT, buff=MED_SMALL_BUFF) dots_template.set_color(GREY_B) for n, dot in enumerate(dots_template): label = Integer(n + 1) label.set_height(0.25) label.set_color(BLACK) label.move_to(dot) dot.add(label) all_dots = VGroup(*[dots_template.copy() for x in range(8)]) all_dots.arrange_in_grid(4, 2, buff=1.25) VGroup(all_dots[0::2], all_dots[1::2]).arrange(RIGHT, buff=2) d_gen = iter(all_dots) for trip in it.combinations(range(4), 3): trip = np.array(trip) perm1 = np.array(list(range(4))) perm2 = np.array(list(range(4))) perm1[trip] = trip[[1, 2, 0]] perm2[trip] = trip[[2, 0, 1]] for perm in [perm1, perm2]: dots = next(d_gen) arrows = get_permutation_arrows(dots, perm) dots.add(arrows) dots.perm = perm for i in trip: dots[i].set_stroke(YELLOW, 1) dots[i][1].set_stroke(width=0) self.play(ShowIncreasingSubsets(all_dots, run_time=4, rate_func=linear)) self.wait() for x in range(3): self.play(*[ permutation_animation(dots, dots.perm, lag_factor=0) for dots in all_dots ]) self.wait() class Isomorphism(Scene): def construct(self): # Frame frame = self.camera.frame frame.focal_distance = 20 # Rotation equation def get_rot_icon(angle=0, axis=OUT, frame=frame): cube = get_glassy_cube(frame) cube.set_height(1) arc_arrows = VGroup(*[ Arrow( u * RIGHT, u * rotate_vector(RIGHT, 160 * DEGREES), buff=0, path_arc=160 * DEGREES, width=0.05, ) for u in [1, -1] ]) arc_arrows.set_color(GREY_B) axis_line = DashedLine(IN, OUT) axis_line.set_stroke(YELLOW, 2) rot_icon = Group(arc_arrows, axis_line, cube) rot_icon.set_gloss(0.5) rot_icon.apply_depth_test() rot_icon.rotate(angle, axis) rot_icon.rotate(-15 * DEGREES, OUT) rot_icon.rotate(75 * DEGREES, LEFT) return rot_icon rot_icon_equation = Group( get_rot_icon(90 * DEGREES, UP), OldTex("\\times").scale(2), get_rot_icon(90 * DEGREES, RIGHT), OldTex("=").scale(2), get_rot_icon(0, OUT), ) rot_icons = rot_icon_equation[0::2] rot_icon_equation.arrange(RIGHT, buff=LARGE_BUFF) rot_icon_equation.shift(1.5 * UP) icon_labels = VGroup(*[ OldTexText(f"$180^\\circ$ about\\\\{axis} axis") for axis in "xyz" ]) for icon, label in zip(rot_icon_equation[0::2], icon_labels): icon[-1][-1].set_opacity(0.5) label.scale(0.8) label.move_to(icon) label.to_edge(UP) icon.add(label) # Permutation equation dots = VGroup(*[Dot() for x in range(4)]) dots.set_height(0.4) dots.set_color(GREY_B) dots.arrange(RIGHT) # for n, dot in enumerate(dots): # label = Integer(n + 1) # label.set_color(BLACK) # label.set_height(0.6 * dot.get_height()) # label.move_to(dot) # dot.add(label) perms = [ [1, 0, 3, 2], [3, 2, 1, 0], [2, 3, 0, 1], ] perm_terms = VGroup() for perm in perms: perm_term = VGroup(dots.copy(), get_permutation_arrows(dots, perm)) perm_term.perm = perm perm_terms.add(perm_term) perm_equation = VGroup( perm_terms[0], OldTex("\\times").scale(2), perm_terms[1], OldTex("=").scale(2), perm_terms[2], ) perm_equation.arrange(RIGHT, buff=LARGE_BUFF) perm_equation.move_to(2 * DOWN) # Bijection lines bij_lines = VGroup() for m1, m2 in zip(rot_icons, perm_terms): line = Line(m1.get_bottom(), m2.get_top(), buff=0.2) line.set_angle(-PI / 2, about_point=line.get_center()) bij_lines.add(line) bij_lines.set_color(GREEN) rot_icons[-1].match_x(bij_lines[2]) # Add terms self.add(rot_icons) for rot_icon, line, perm_term in zip(rot_icons, bij_lines, perm_terms): self.play( # FadeIn(rot_icon), GrowFromPoint(line, line.get_top()), FadeIn(perm_term, 2 * UP), ) self.wait() self.play(Write(VGroup( *rot_icon_equation[1::2], *perm_equation[1::2], ))) self.wait(2) # Composition rot_anims = [ AnimationGroup( Rotate(rot_icon[2], PI, axis=rot_icon[1].get_vector()), ShowCreationThenFadeAround(rot_icon[-1]), ) for rot_icon in rot_icons ] perm_anims = [ permutation_animation(perm_term[0], perm_term.perm, lag_factor=0.1) for perm_term in perm_terms ] self.play(rot_anims[1]) self.play(rot_anims[0]) self.wait() self.play(rot_anims[2]) self.wait() self.play(LaggedStartMap(ShowCreation, bij_lines, lag_ratio=0.5)) self.wait() self.play(perm_anims[1]) self.play(perm_anims[0]) self.wait() self.play(perm_anims[2]) self.wait() class IsomorphismWord(Scene): def construct(self): word = OldTexText("``Isomorphism''") word.scale(2) word.to_edge(UP) self.play(FadeIn(word, DOWN)) self.wait() class AskAboutCubeDiagonals(QuadrupletShufflings): def construct(self): # Setup frame = self.camera.frame frame.set_euler_angles(phi=80 * DEGREES) frame.add_updater(lambda m, sc=self: m.set_euler_angles(theta=-20 * DEGREES * np.cos(0.1 * sc.time))) cube = get_glassy_cube(frame) cube.set_height(3) axes = ThreeDAxes(axis_config={"include_tip": False}) colors = [RED, GREEN, BLUE, YELLOW] diagonals = Group(*[ Line3D(vect + OUT, -vect - OUT, color=color) for color, vect in zip(colors, [UL, UR, DR, DL]) ]) diagonals.match_height(cube.edge_rods) diag_markers = Group(*[ Line3D(ORIGIN, UP, color=color) for color in colors ]) diag_markers.arrange(RIGHT, buff=MED_LARGE_BUFF) diag_markers.to_corner(UL, buff=LARGE_BUFF) diag_markers.fix_in_frame() # Color corners cds = cube.corner_dots for diag in diagonals: globals()['diag'] = diag Group(*[ cds[np.argmin([get_norm(cd.get_center() - diag.get_points()[i]) for cd in cds])] for i in [0, -1] ]).match_color(diag) cube.add_to_back(diagonals) # Rotations self.add(axes, cube) self.add(diag_markers) self.add(frame) for quat in self.get_quaternions(): angle, axis = angle_axis_from_quaternion(quat) perm = self.quaternion_to_perm(quat) perm_arrows = get_permutation_arrows(diag_markers, perm) perm_arrows.fix_in_frame() self.play(FadeIn(perm_arrows)) self.play( Rotate(cube, angle, axis=axis), permutation_animation(diag_markers, perm, lag_factor=0.1), run_time=2, ) self.play(FadeOut(perm_arrows)) self.wait() inv_perm = self.quaternion_to_perm(quaternion_conjugate(quat)) diag_markers.set_submobjects([diag_markers[i] for i in inv_perm]) class S4WithMultipleChildren(Scene): def construct(self): # Setup bg_rect = FullScreenFadeRectangle() bg_rect.set_fill(GREY_E, 1) self.add(bg_rect) s_rects = VGroup(*[ScreenRectangle() for x in range(3)]) s_rects.arrange(RIGHT, buff=MED_LARGE_BUFF) s_rects.set_width(FRAME_WIDTH - 1) s_rects.set_stroke(WHITE, 2) s_rects.set_fill(BLACK, 1) s_rects.move_to(DOWN) self.add(s_rects) s4_label = OldTex("S_4") s4_label.scale(2) s4_label.to_edge(UP) lines = VGroup(*[ Line(rect.get_top(), s4_label.get_bottom(), buff=0.2) for rect in s_rects ]) # Arising self.play(LaggedStartMap(ShowCreation, lines, lag_ratio=0.5)) self.play(FadeIn(s4_label, DOWN)) self.wait(2) # Triplets three = Integer(3) three.scale(2) three.move_to(s4_label) pis = VGroup(*[Randolph(color=c) for c in [BLUE_C, BLUE_E, BLUE_D]]) pis.arrange(RIGHT) vects = VGroup(*[Vector(RIGHT) for x in range(3)]) vects.arrange(RIGHT, buff=SMALL_BUFF) vects.rotate(30 * DEGREES) vects.set_color(TEAL) triangle = RegularPolygon(3) triangle.set_stroke(BLUE_B, 4) triangle.add(*[Dot(vert, color=BLUE_D) for vert in triangle.get_vertices()]) triangle.set_stroke(background=True) triplets = VGroup(pis, vects, triangle) for trip, rect in zip(triplets, s_rects): trip.set_width(0.8 * rect.get_width()) if trip.get_height() > 0.8 * rect.get_height(): trip.set_height(0.8 * rect.get_height()) trip.move_to(rect) self.play( FadeOut(s4_label, UP), FadeIn(three, DOWN), LaggedStartMap(FadeIn, pis, lag_ratio=0.5, run_time=1), ) for trip in triplets[1:]: self.play(FadeIn(trip, lag_ratio=0.5)) self.play(Blink(pis[0])) self.play(Blink(pis[2])) # Back to s4 self.play( FadeOut(three, DOWN), FadeIn(s4_label, UP), FadeOut(triplets, lag_ratio=0.2, run_time=2), ) self.wait() class AutQ8(Scene): def construct(self): tex = OldTex("\\text{Aut}(Q_8)", tex_to_color_map={"Q_8": BLUE}) tex.scale(2) self.play(Write(tex)) self.wait() class GroupsBeyondActions(Scene): def construct(self): groups = OldTexText("Groups") sym_acts = OldTexText("Symmetric\\\\Actions") others = OldTexText("Other things\\\\which ``multiply''") VGroup(groups, sym_acts, others).scale(1.5) line = Line(UP, DOWN) sym_acts.set_color(BLUE) others.set_color(interpolate_color(GREY_BROWN, WHITE, 0.5)) VGroup( groups, line, sym_acts ).arrange(DOWN, buff=MED_LARGE_BUFF) line.add_updater(lambda m: m.put_start_and_end_on( groups.get_bottom() + 0.3 * DOWN, sym_acts.get_top() + 0.3 * UP, )) others.move_to(sym_acts) others.to_edge(RIGHT) others_line = Line(groups.get_bottom(), others.get_top(), buff=0.3) self.add(groups, line, sym_acts) self.wait() self.play( sym_acts.to_edge, LEFT, LARGE_BUFF, FadeIn(others, 2 * UL), ShowCreation(others_line), run_time=2, ) self.wait() class RAddToRMult(ExternallyAnimatedScene): pass class AskAboutAllTheGroups(TeacherStudentsScene): def construct(self): # Ask question = OldTexText("What are all the groups", "?") self.teacher_holds_up(question) self.play_student_changes("pondering", "thinking", "erm") self.wait(2) question.generate_target() question.target.to_corner(UL) self.teacher_says( "Now you can\\\\ask something\\\\more sophisticated.", target_mode="hooray", added_anims=[ MoveToTarget(question, run_time=2), self.change_students( "erm", "pondering", "pondering", look_at=question.target ) ] ) self.wait(2) self.play( RemovePiCreatureBubble( self.teacher, target_mode="tease", look_at=question.get_right(), ), question.set_x, 0, ) # Add up to isomorphism caveat = OldTexText("up to \\emph{isomorphism}") caveat.next_to(question, DOWN) caveat.set_color(YELLOW) self.play( Write(caveat, run_time=1), question[1].next_to, caveat[0][-1], RIGHT, SMALL_BUFF, DOWN, question[1].match_color, caveat, self.change_students(*3 * ["thinking"], look_at=question) ) question.add(caveat) self.wait(2) self.look_at(self.screen) self.wait(2) self.look_at(question) # Alt question sym_question = OldTexText("What are all the\\\\", "symmetric", " things", "?") self.teacher_holds_up(sym_question) cross = Cross(sym_question) self.look_at( cross, added_anims=[ ShowCreation(cross), self.change_students("erm", "sassy", "hesitant") ] ) self.wait() abs_question = OldTexText("What are all the", " \\emph{ways}\\\\", "things ", "can be ", "symmetric", "?") new_words = VGroup(abs_question[1], abs_question[3]) new_words.match_color(caveat) abs_question.move_to(sym_question) abs_question.shift_onto_screen() self.play( *[ ReplacementTransform(sym_question[i], abs_question[j], path_arc=10 * DEGREES) for i, j in [(0, 0), (1, 4), (2, 2), (3, 5)] ], FadeOut(cross), self.change_students("happy", "thinking", "tease"), ) self.play( self.teacher.change, "speaking", abs_question, Write(new_words), ) self.look_at(abs_question) self.wait(2) # Formula suggestions = VGroup(*[ OldTexText("Some ", word, "?", tex_to_color_map={word: color}) for word, color in [ ("formula", RED), ("procedure", MAROON_B), ("algorithm", PINK), ] ]) for words in suggestions: words.move_to(abs_question, UP) words.to_edge(LEFT, buff=LARGE_BUFF) self.play( FadeIn(suggestions[0], DOWN), self.change_students(*3 * ["pondering"], look_at=suggestions), self.teacher.change, "happy", ) self.wait() for words1, words2 in zip(suggestions, suggestions[1:]): self.play( FadeOut(words1[1], UP), FadeIn(words2[1], DOWN), ReplacementTransform(words1[2], words2[2]) ) self.remove(words1) self.add(words2) self.wait() self.wait(3) self.play( FadeOut( VGroup(question, abs_question, suggestions[-1]), 0.5 * DOWN, lag_ratio=0.02, run_time=2, ) ) class ThisQuestionIsHard(Scene): def construct(self): # Setup line line = NumberLine(x_range=(0, 1, 0.1), width=12) line.shift(UP) arrows = VGroup( Arrow(line.n2p(0.5), line.n2p(0), fill_color=GREEN), Arrow(line.n2p(0.5), line.n2p(1), fill_color=RED), ) arrows.shift(2.5 * DOWN) words = VGroup(OldTexText("Easier"), OldTexText("Harder")) for word, arrow in zip(words, arrows): word.match_color(arrow) word.next_to(arrow, DOWN, SMALL_BUFF) self.add(line) self.add(arrows) self.add(words) # Add problems problems = VGroup( OldTex("1 + 1"), VGroup( OldTex("\\frac{2^{289}+1}{2^{17}+1}=2^{a_{1}}+\\ldots+2^{a_{k}}"), OldTex("a_1 < \\ldots < a_k"), OldTex("a_1, \\dots, a_k \\in \\mathds{Z}^+"), ), VGroup( OldTex("{a \\over b + c} + {b \\over c + a} + {c \\over b + c} = 4"), OldTex("a, b, c \\in \\mathds{Z}^+"), ), VGroup( OldTex("x^n + y^n = z^n"), OldTex("x, y, z \\in \\mathds{Z}"), ), ) colors = Color(GREEN).range_to(RED, 4) for prob, x, color in zip(problems, [0, 0.3, 0.7, 1], colors): triangle = Triangle() triangle.set_height(0.2) triangle.set_stroke(width=0) triangle.set_fill(color, 1) triangle.move_to(line.n2p(x), UP) prob.arrange(DOWN) prob.scale(0.5) prob.next_to(triangle, DOWN) prob.add(triangle) prob.set_color(color) self.add(problems) # Group question tri = Triangle(start_angle=-90 * DEGREES) tri.set_height(0.3) tri.set_stroke(width=0) tri.set_fill(GREY_B, 1) tri.move_to(line.n2p(0.5), DOWN) question = OldTexText("What are all\\\\the groups?") question.next_to(tri, UP) ext_line = line.copy() ext_line.move_to(line.get_right(), LEFT) frame = self.camera.frame self.play( DrawBorderThenFill(tri), FadeIn(question, DOWN) ) question.add(tri) self.play(question.move_to, line.n2p(0.9), DOWN) self.wait() self.play( ShowCreation(ext_line), question.move_to, line.n2p(1.3), DOWN, ApplyMethod(frame.scale, 1.3, {"about_edge": LEFT}, run_time=2) ) self.wait() class AmbientSnowflakeSymmetries(Scene): def construct(self): title = OldTex("D_6") title.scale(3) title.to_edge(LEFT, buff=1) title.set_color(BLUE) self.add(title) snowflake = get_snowflake() snowflake.set_height(5) snowflake.set_stroke(width=0) snowflake.move_to(2 * RIGHT) self.add(snowflake) for n in range(10): if random.choice([True, False]): deg = random.choice([-120, -60, 60, 120]) icon = get_rot_icon(deg, snowflake, snowflake.get_height()) anim = Rotate(snowflake, deg * DEGREES) else: deg = random.choice(range(30, 180, 30)) angle = deg * DEGREES icon = get_flip_icon(angle, snowflake, mini_mob_height=snowflake.get_height()) anim = Rotate(snowflake, PI, axis=rotate_vector(RIGHT, angle)) icon.shift(snowflake.get_center() - icon[0].get_center()) self.play(anim, FadeIn(icon[1:])) self.play(FadeOut(icon[1:])) class IntroduceSimpleGroups(Scene): def construct(self): # Setup bg_rect = FullScreenFadeRectangle(fill_color=GREY_E, fill_opacity=1) self.add(bg_rect) groups = OldTexText("Groups") groups.scale(2) groups.to_edge(UP) inf_groups = OldTexText("Infinite groups") fin_groups = OldTexText("Finite groups") children = VGroup(inf_groups, fin_groups) children.scale(1.5) children.arrange(RIGHT, buff=2) children.next_to(groups, DOWN, buff=2) child_lines = VGroup(*[ Line(groups.get_bottom(), child.get_top(), buff=0) for child in children ]) child_lines.set_stroke(WHITE, 2) s_rects = VGroup(*[ ScreenRectangle(height=3).move_to(child) for child in children ]) s_rects.next_to(children, DOWN) s_rects.set_fill(BLACK, 1) # Introductions self.add(groups) self.wait() self.play( ShowCreation(child_lines[0]), FadeIn(inf_groups, 2 * UR), FadeIn(s_rects[0]) ) self.wait(2) self.play( ShowCreation(child_lines[1]), FadeIn(fin_groups, 2 * UL), FadeIn(s_rects[1]), ) self.wait() self.add(s_rects, fin_groups) self.play( Uncreate(child_lines), FadeOut(inf_groups, 3 * LEFT), FadeOut(s_rects[0], 3 * LEFT), FadeOut(groups, 2 * UP), fin_groups.move_to, groups, s_rects[1].replace, bg_rect, s_rects[1].set_stroke, {"width": 0}, run_time=2, ) self.remove(s_rects, bg_rect) # Comparison titles bg_rects = VGroup(*[ Rectangle( height=FRAME_HEIGHT, width=FRAME_WIDTH / 3, fill_color=color, fill_opacity=1, stroke_width=0 ) for color in [GREY_D, GREY_E, BLACK] ]) bg_rects.arrange(RIGHT, buff=0) bg_rects.center() fin_groups.generate_target() titles = VGroup( OldTexText("Integers").scale(1.5), OldTexText("Molecules").scale(1.5), fin_groups.target, ) sub_titles = VGroup(*[ OldTexText("break down into\\\\", word) for word in ("primes", "atoms", "simple groups") ]) for rect, title, sub_title in zip(bg_rects, titles, sub_titles): title.move_to(rect, UP) title.shift(0.5 * DOWN) sub_title.next_to(title, DOWN) sub_title[1].set_color(BLUE) sub_title.align_to(sub_titles[0], UP) # Comparison diagrams H_sphere = Sphere() H_sphere.set_height(0.5) H_sphere.set_color(RED) H_atom = Group( H_sphere, OldTexText("H").scale(0.5).move_to(H_sphere) ) O_sphere = Sphere() O_sphere.set_height(1) O_sphere.set_color(BLUE) O_atom = Group( O_sphere, OldTexText("O").scale(0.75).move_to(O_sphere) ) H2O = Group( O_atom.copy(), H_atom.copy().move_to([-0.45, 0.35, 0]), H_atom.copy().move_to([0.45, 0.35, 0]), ) trees = Group( VGroup( Integer(60), VGroup(*map(Integer, [2, 2, 3, 5])), ), Group( H2O, Group(H_atom.copy(), H_atom.copy(), O_atom.copy()) ), VGroup( OldTex("S_4"), VGroup(*[ OldTex( "C_" + str(n), fill_color=(RED_B if n == 2 else BLUE) ) for n in [2, 2, 2, 3] ]), ) ) for tree, rect in zip(trees, bg_rects): root, children = tree children.arrange(RIGHT, buff=0.35) children.next_to(root, DOWN, buff=1.2) lines = VGroup() for child in children: lines.add(Line(root.get_bottom(), child.get_top(), buff=0.1)) tree.add(lines) tree.move_to(rect) tree.shift(DOWN) # Slice screen self.add(bg_rects, fin_groups) for rect in bg_rects: rect.save_state() rect.shift(LEFT) rect.set_fill(BLACK, 1) self.play( MoveToTarget(fin_groups), LaggedStartMap(Restore, bg_rects, lag_ratio=0.3) ) # Breakdowns for title, sub_title, tree in zip(titles, sub_titles, trees): root, children, lines = tree self.play( FadeIn(title), FadeIn(root), ) globals()['root'] = root self.play( ShowCreation(lines), LaggedStart(*[ GrowFromPoint(child, root) for child in children ]), FadeIn(sub_title) ) self.wait() # Theorem theorem_name = OldTexText("(Jordan–Hölder Theorem)") theorem_name.scale(0.7) theorem_name.next_to(sub_titles[2], DOWN) self.play(Write(theorem_name, run_time=1)) self.wait() class SymmetriesOfCirleAndLine(Scene): def construct(self): line = NumberLine((0, 100, 1)) line.move_to(2 * UP) circle = Circle(radius=1) circle_ticks = VGroup(*[ Line(0.95 * vect, 1.05 * vect) for vect in compass_directions(12) ]) circle.add(circle_ticks) circle.set_stroke(BLUE, 3) circle.scale(1.5) circle.next_to(line, DOWN, buff=2) circle.shift(RIGHT) R_label = OldTex("\\mathds{R}") RmodZ = OldTex("\\mathds{R} / \\mathds{Z}") R_label.set_height(0.9) R_label.next_to(line, UP, MED_LARGE_BUFF) RmodZ.set_height(0.9) RmodZ.next_to(circle, LEFT, LARGE_BUFF) R_label.match_x(RmodZ) self.add(line) self.add(circle) self.add(R_label) self.add(RmodZ) # Rotations and shifts for n in range(10): x = interpolate(-20, 20, random.random()) self.play( line.shift, x * RIGHT, Rotate(circle, -x / PI), run_time=2, ) self.wait() self.embed() class QuinticImpliesCyclicDecomposition(Scene): def construct(self): # Title title = OldTexText("Quintic formula") title.scale(1.5) title.to_edge(UP) details = OldTexText( "Solve ", "$a_5 x^5 + a_4 x^4 + a_3 x^3 + a_2 x^2 + a_1 x + a_0$\\\\", " using only ", "+, -, $\\times$, $/$, and $\\sqrt[n]{\\quad}$" ) details[1].set_color(BLUE) details[3].set_color(TEAL) details.match_width(title) details.scale(1.2) details.next_to(title, DOWN) self.clear() self.add(title) self.wait() self.play(FadeIn(details, 0.5 * UP)) self.wait() full_title = VGroup(title, details) # Show Implication implies = OldTex("\\Downarrow").scale(2) implies.next_to(details, DOWN, LARGE_BUFF) s5 = OldTex("S_5") prime_children = VGroup( OldTex("C_{p_1}"), OldTex("C_{p_2}"), OldTex("\\vdots"), OldTex("C_{p_n}"), ) prime_children.set_color(RED_B) real_children = VGroup( OldTex("A_5"), OldTex("C_2"), ) real_children.set_color(GREEN) for children, buff in (prime_children, MED_LARGE_BUFF), (real_children, LARGE_BUFF): children.arrange(DOWN, buff=buff, aligned_edge=LEFT) children.next_to(s5, RIGHT, buff=0.5 + 0.25 * len(children)) children.lines = VGroup() for child in children: children.lines.add( Line(s5.get_right(), child.get_left(), buff=0.1) ) prime_children[2].shift(SMALL_BUFF * RIGHT) VGroup( s5, prime_children.lines, prime_children, real_children.lines, real_children, ).next_to(implies, DOWN) # Show decomps implies.save_state() implies.stretch(0, 1, about_edge=UP) self.play( Restore(implies), GrowFromPoint(s5, implies.get_top()), ) self.play( LaggedStartMap(ShowCreation, prime_children.lines, lag_ratio=0.3), LaggedStartMap( FadeIn, prime_children, lambda m: (m, s5.get_right() - m.get_center()), lag_ratio=0.3, ) ) self.wait() self.play( FadeOut(prime_children, RIGHT), *[ ApplyMethod(line.scale, 0, {"about_point": line.get_end()}, remover=True) for line in prime_children.lines ], LaggedStartMap(ShowCreation, real_children.lines, lag_ratio=0.3), LaggedStartMap( FadeIn, real_children, lambda m: (m, s5.get_right() - m.get_center()), lag_ratio=0.3, ) ) self.play(ShowCreationThenFadeAround(real_children[0])) # Reverse implication title_rect = SurroundingRectangle(full_title) title_rect.set_stroke(RED, 2) not_exists = OldTexText("No\\\\such\\\\thing") not_exists.match_height(title_rect) not_exists.set_color(RED) not_exists.next_to(title_rect, LEFT) full_title.add(title_rect, not_exists) self.play( Rotate(implies, PI), VFadeIn(title_rect), VFadeIn(not_exists), full_title.shift, 0.5 * RIGHT, ) class CommentOnNontrivialFactFromGroupDecomposition(TeacherStudentsScene): def construct(self): self.student_says( "I...don't\\\\get it.", target_mode="confused", index=2, look_at=self.screen, added_anims=[self.teacher.change, "guilty"], ) self.play_student_changes("maybe", "tired", look_at=self.screen) self.wait(4) fp_words = OldTexText("Fact about\\\\polynomials") fp_words.scale(1.25) as_words = OldTexText("``Atomic structure''\\\\of a group") as_words.scale(1.25) implies = OldTex("\\Rightarrow").scale(2) self.teacher_holds_up( fp_words, added_anims=[ RemovePiCreatureBubble(self.students[2]), ] ) self.play_student_changes("pondering", "hesitant", "plain", look_at=fp_words) self.wait() as_words.next_to(fp_words, LEFT, buff=1.5) implies.move_to(midpoint(as_words.get_right(), fp_words.get_left())) self.play( FadeIn(as_words, RIGHT), Write(implies), self.change_students(*3 * ["pondering"], look_at=as_words) ) self.wait(5) class TwoStepsToAllFiniteGroups(Scene): def construct(self): # List title = OldTexText("How to categorize all finite groups") title.scale(1.5) title.add(Underline(title)) title.to_edge(UP) steps = VGroup( OldTexText("1. ", "Find all the ", "simple groups", "."), OldTexText("2. ", "Find all the ", "ways to\\\\", "combine ", "simple groups", "."), ) steps[1][3:].next_to(steps[1][1], DOWN, SMALL_BUFF, aligned_edge=LEFT) steps.arrange(DOWN, aligned_edge=LEFT, buff=2) steps.set_y(-0.5) steps.to_edge(LEFT) for step in steps: step.set_color_by_tex("simple groups", TEAL) self.add(title) self.wait() self.play(LaggedStartMap( FadeIn, VGroup(steps[0][0], steps[1][0]), lambda m: (m, RIGHT), lag_ratio=0.4, )) self.wait() self.play(FadeIn(steps[0][1:], lag_ratio=0.1)) self.wait() self.play( TransformFromCopy(steps[0][1], steps[1][1]), TransformFromCopy(steps[0][2], steps[1][4]), FadeIn(VGroup(*[steps[1][i] for i in (2, 3, 5)])), ) self.wait() # Periodic table table = VGroup(*[ VGroup(*[ Square() for x in range(n) ]).arrange(DOWN, buff=0) for n in [7, 6, *[4] * 10, *[6] * 5, 7] ]) table.arrange(RIGHT, buff=0, aligned_edge=DOWN) table.set_width(4) table.to_edge(RIGHT) table.match_y(steps[0]) table.set_stroke(GREY_A, 2) table_arrow = Arrow( steps[0].get_right(), table.get_left(), buff=0.5, ) self.play( GrowArrow(table_arrow), FadeIn(table, lag_ratio=0.1, run_time=3), ) self.wait() # Chemistry chem_words = OldTexText("All of chemistry") chem_words.match_y(steps[1]) chem_words.match_x(table) chem_words.set_color(RED) chem_arrow = Arrow( steps[1].get_right(), chem_words.get_left(), buff=0.5 ) self.play( GrowArrow(chem_arrow), Write(chem_words), ) self.wait() # Found all simples top_group = VGroup(steps[0], table_arrow, table) bottom_group = VGroup(steps[1], chem_arrow, chem_words) frame = self.camera.frame top_rect = SurroundingRectangle(top_group, buff=MED_LARGE_BUFF) top_rect.set_stroke(GREEN, 4) check = Checkmark() check.set_height(0.7) check.next_to(top_rect, UP, aligned_edge=LEFT) check.shift(RIGHT) self.play( frame.scale, 1.1, bottom_group.shift, 0.5 * DOWN, bottom_group.set_opacity, 0.5, ShowCreation(top_rect), FadeOut(title, UP), ) self.play(Write(check)) self.wait() proof_words = OldTexText("(prove you have them all.)") proof_words.next_to(steps[0], DOWN) proof_words.set_color(GREY_A) self.play(Write(proof_words, run_time=2)) self.wait() # What was involved stats = VGroup( OldTexText("1955-2004"), OldTexText("$10{,}000+$ pages"), OldTexText("100's of mathematicians"), OldTexText("Plenty of computation"), ) stats.arrange_in_grid(buff=1.5, aligned_edge=LEFT) stats.next_to(top_rect, DOWN, buff=LARGE_BUFF) for stat in stats: dot = Dot() dot.next_to(stat, LEFT) stat.add(dot) turn_animation_into_updater(ApplyMethod(frame.shift, DOWN, run_time=3)) self.add(frame) for stat in stats: self.play(FadeIn(stat), bottom_group.set_opacity, 0) self.wait(0.5) self.remove(bottom_group) # 2004 paper mention stats.generate_target() stats.target.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) stats.target.move_to(stats, UL) last_paper = OldTexText( "The Classification of Quasithin Groups\\\\", "Aschbacher and Smith (2004)\\\\", "(12{,}000 pages!)", ) last_paper.scale(0.7) last_paper[:-1].set_color(YELLOW) last_paper.move_to(stats, RIGHT) last_paper.shift(RIGHT) self.play( FadeIn(last_paper, DOWN), MoveToTarget(stats), ) self.wait() # Quote quote = OldTexText( """ ``...undoubtedly one of the most\\\\ extraordinary theorems that pure\\\\ mathematics has ever seen.''\\\\ """, "-Richard Elwes", alignment="", ) quote.scale(0.9) quote[0].set_color(YELLOW) quote[-1].shift(MED_SMALL_BUFF * DR) quote.move_to(last_paper, LEFT) self.play( FadeIn(quote), FadeOut(last_paper), ) self.wait() class ClassificationOfSimpleGroups(Scene): def construct(self): # Title class_title = OldTexText("Classification of finite simple groups") class_title.set_width(FRAME_WIDTH - 4) class_title.add(Underline(class_title).set_color(GREY_B)) class_title.to_edge(UP) self.add(class_title) # 18 families square_template = Square(side_length=0.3) square_template.set_stroke(GREY_B, 2) square_template.set_fill(BLUE_E, 0.5) families_grid = VGroup(*[ VGroup(*[square_template.copy() for x in range(8)]) for y in range(18) ]) for family in families_grid: family.arrange(DOWN, buff=0) dots = OldTex("\\vdots") dots.next_to(family, DOWN) family.add(dots) families_grid.arrange(RIGHT, buff=MED_SMALL_BUFF) families_grid.to_edge(LEFT) families_grid.set_y(-1) families_title = OldTexText("18 infinite families") families_title.set_color(BLUE) families_title.next_to(families_grid, UP, MED_LARGE_BUFF) self.play( FadeIn(families_title), FadeIn(families_grid, lag_ratio=0.1, run_time=4), ) self.wait() # Analogize to periodic table families_grid.generate_target() families_grid.save_state() families_grid.target.arrange(RIGHT, buff=0) families_grid.target.move_to(families_grid) faders = VGroup(*[ column[:n] for column, n in zip(families_grid.target, [ 0, 1, *[3] * 10, *[1] * 5, 0, ]) ]) faders.set_opacity(0) self.play(MoveToTarget(families_grid, lag_ratio=0.001)) self.wait(2) self.play(Restore(families_grid)) # Sporadic sporadics = VGroup(*[square_template.copy() for x in range(26)]) buff = 0.1 sporadics[:20].arrange_in_grid(10, 2, buff=buff) sporadics[20:].arrange(DOWN, buff=buff) sporadics[20:].next_to(sporadics[:20], RIGHT, buff) sporadics.next_to(families_grid, RIGHT, buff=1.5, aligned_edge=UP) sporadics.set_fill(YELLOW_E) pre_sporadics_title = OldTexText("26", " leftovers") sporadics_title = OldTexText("26", " ``sporadic''\\\\groups") for title in pre_sporadics_title, sporadics_title: title.set_color(YELLOW) title.next_to(sporadics, UP, MED_LARGE_BUFF) sporadics_title.shift(MED_SMALL_BUFF * DOWN) self.play( FadeIn(pre_sporadics_title, DOWN), ShowIncreasingSubsets(sporadics, run_time=3), ) self.wait() self.play( ReplacementTransform(pre_sporadics_title[0], sporadics_title[0]), FadeOut(pre_sporadics_title[1], UP), FadeIn(sporadics_title[1], DOWN), ) self.wait() # Show prime cyclic groups families_grid.save_state() column = families_grid[0] def prepare_column(column): column.generate_target() column.target.set_height(FRAME_HEIGHT) column.target.move_to(5 * LEFT) column.target.to_edge(UP) column.target[-1].scale(0.5, about_point=column.target[-2].get_bottom()) prepare_column(column) self.play( MoveToTarget(column), FadeOut(families_grid[1:], lag_ratio=0.1), FadeOut(families_title), FadeOut(class_title, UP), FadeOut(sporadics, 2 * RIGHT), FadeOut(sporadics_title, 2 * RIGHT), ) # C5 c_names = VGroup(*[ OldTex(f"C_{{{p}}}") for p in [2, 3, 5, 7, 11, 13, 17, 19] ]) def put_in_square(mob, square, factor=0.4): mob.set_height(factor * square.get_height()) mob.move_to(square) def put_names_in_column(names, column): for name, square in zip(names, column): put_in_square(name, square) put_names_in_column(c_names, column) self.play(FadeIn(c_names, lag_ratio=0.1)) self.wait() pentagon = RegularPolygon(5) pentagon.set_height(3) pentagon.set_fill(TEAL_E, 0.5) pentagon.set_stroke(WHITE, 1) pentagon.move_to(2 * RIGHT) c_names.save_state() c5 = c_names[2] c5.generate_target() c5.target.scale(2) c5.target.next_to(pentagon, UP, LARGE_BUFF) self.play( MoveToTarget(c5), DrawBorderThenFill(pentagon, run_time=1), ) pcenter = center_of_mass(pentagon.get_vertices()) for n in [1, -2, 2]: self.play(Rotate(pentagon, n * TAU / 5, about_point=pcenter)) self.wait(0.5) self.play( Restore(c_names), FadeOut(pentagon) ) c_names.generate_target() c_names.target.replace(families_grid.saved_state[0]) c_names.target.scale(0.9) c_names.target.set_opacity(0) families_grid[1:].fade(1) self.play( Restore(families_grid), MoveToTarget(c_names, remover=True) ) # Alternating column = families_grid[1] prepare_column(column) self.play( MoveToTarget(column), FadeOut(families_grid[0]), FadeOut(families_grid[2:], lag_ratio=0.1), ) a_names = VGroup(*[ OldTex(f"A_{{{n}}}") for n in range(5, 5 + len(column) - 1) ]) put_names_in_column(a_names, column) self.play(FadeIn(a_names, lag_ratio=0.1)) dots = VGroup(*[Dot() for x in range(5)]) dots.set_height(0.5) dots.arrange(RIGHT, buff=MED_LARGE_BUFF) dots.set_submobject_colors_by_gradient(RED, YELLOW) dots.move_to(RIGHT) a5 = a_names[0] a5.save_state() a5.generate_target() a5.target.scale(2) a5.target.next_to(dots, UP, buff=1.5) self.play( FadeIn(dots, lag_ratio=0.1), MoveToTarget(a5), ) for x in range(5): perm = list(range(5)) swaps = 1 # Lie while swaps % 2 == 1: random.shuffle(perm) swaps = 0 for i, j in it.combinations(perm, 2): if j < i: swaps += 1 arrows = get_permutation_arrows(dots, perm) self.play( FadeIn(arrows), permutation_animation(dots, perm, lag_factor=0.1), ) self.play(FadeOut(arrows)) self.wait() self.play( FadeOut(dots, lag_ratio=0.1), Restore(a5), ) self.wait() a_names.generate_target() a_names.target.replace(families_grid.saved_state[1]) a_names.target.scale(0.9) a_names.target.fade(1) self.play( Restore(families_grid), MoveToTarget(a_names, remover=True), FadeIn(families_title), FadeIn(class_title), ) # Others others_rect = SurroundingRectangle(families_grid[2:]) others_rect.set_stroke(YELLOW, 2) others_name = OldTexText("Groups of\\\\Lie type") others_name.set_color(YELLOW) others_name.next_to(others_rect, RIGHT) self.play(ShowCreation(others_rect)) self.play(FadeIn(others_name)) self.wait() self.play(FadeOut(others_name), FadeOut(others_rect)) # Back to sporadics self.play( ShowIncreasingSubsets(sporadics), FadeIn(sporadics_title), ) self.wait() # Look closer at sporadics sporadics.generate_target() sporadics.target.rotate(PI, axis=UL) sporadics.target.set_width(FRAME_WIDTH - 1) sporadics.target.center().to_edge(DOWN) sporadics_title.save_state() sporadics.save_state() self.play( sporadics_title.scale, 1.25, sporadics_title.center, sporadics_title.to_edge, UP, MoveToTarget(sporadics), FadeOut(families_grid, LEFT), FadeOut(families_title, LEFT), FadeOut(class_title, UP), ) # Monster monster = get_monster() put_in_square(monster, sporadics[0], 0.9) monster_name = OldTexText("Monster", " group") monster_name.next_to(sporadics[0], UP, LARGE_BUFF) monster_name.shift_onto_screen() monster_arrow = Arrow(monster_name.get_bottom(), monster.get_top()) size_label = OldTexText("{:,}".format(MONSTER_SIZE))[0] size_label.scale(0.8) size_label.move_to(monster_name, LEFT) self.play( sporadics[0].set_fill, {"opacity": 0}, FadeIn(monster) ) self.play( Write(monster_name), GrowArrow(monster_arrow), ) self.wait() # sporadics_title.generate_target() # sporadics_title.target.scale(1 / 1.5) # sporadics_title.target.to_corner(UR) self.play( monster_name.shift, 0.6 * UP, ShowIncreasingSubsets(size_label, run_time=2), # MoveToTarget(sporadics_title, run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1)) ) self.wait() # Baby monster full_monster_label = VGroup(monster_name, size_label) full_monster_label.save_state() full_monster_label.generate_target() full_monster_label.target.to_edge(UP, buff=MED_SMALL_BUFF) full_monster_label.target.set_opacity(0.7) baby_name = OldTexText("Baby monster group") baby_name.move_to(size_label, LEFT) baby_arrow = Arrow(baby_name.get_bottom(), sporadics[1].get_corner(UR) + SMALL_BUFF * DL) baby_arrow.set_stroke(BLACK, 6, background=True) baby_size_label = OldTexText("{:,}".format(BABY_MONSTER_SIZE))[0] baby_size_label.scale(0.8) baby_size_label.move_to(baby_name, LEFT) baby_monster = get_baby_monster() baby_monster.set_width(0.9 * sporadics[1].get_width()) baby_monster.move_to(sporadics[1]) baby_monster.shift(SMALL_BUFF * DOWN) self.remove(monster_arrow) self.play( MoveToTarget(full_monster_label), TransformFromCopy(monster_arrow, baby_arrow), FadeIn(baby_name, DOWN), sporadics[1].set_fill, {"opacity": 0}, FadeIn(baby_monster), FadeOut(sporadics_title, UP), ) self.wait() self.play( baby_name.shift, 0.6 * UP, ShowIncreasingSubsets(baby_size_label, run_time=2) ) self.wait() # 20 vs. 6 top_20 = sporadics[:20] top_20.generate_target() top_20.target.shift(2 * UP) top_20.target[1:].set_fill(GREEN, 0.8) self.play( MoveToTarget(top_20), MaintainPositionRelativeTo(monster, sporadics[0]), MaintainPositionRelativeTo(baby_monster, sporadics[1]), UpdateFromAlphaFunc(baby_monster, lambda m, a: m.set_opacity(1 - a), remover=True), ApplyMethod(baby_arrow.scale, 0, {"about_point": baby_arrow.get_start()}, remover=True), FadeOut(baby_size_label, UP), FadeOut(baby_name, UP), full_monster_label.set_fill, WHITE, 1, ) monster_name.generate_target() monster_name.target.arrange(DOWN, buff=MED_SMALL_BUFF, aligned_edge=LEFT) monster_name.target.next_to(sporadics[0], UP, SMALL_BUFF, aligned_edge=LEFT) happy_family_name = OldTexText("``Happy family''") happy_family_name.set_height(0.7) happy_family_name.to_edge(UP) happy_family_name.set_color(GREEN) self.play( MoveToTarget(monster_name), FadeOut(size_label, DOWN), FadeIn(happy_family_name, UP), ) self.wait() pariahs = sporadics[20:] pariahs_name = OldTexText("``Pariahs''") pariahs_name.set_height(0.7) pariahs_name.next_to(pariahs, UP, MED_LARGE_BUFF) pariahs_name.set_color(YELLOW) self.play( FadeIn(pariahs_name, UP), pariahs.set_fill, YELLOW, 0.7, ) self.wait() class ImSorryWhat(TeacherStudentsScene): def construct(self): self.student_says( "I'm sorry, what?!", target_mode="sassy", look_at=self.screen, ) self.play_student_changes("angry", "maybe", "sassy", look_at=self.screen) self.wait(3) self.play_student_changes("pleading", "confused", "erm", look_at=self.screen) self.wait(5) class TellMeTheresAChildrensBook(TeacherStudentsScene): def construct(self): self.student_says( "Please tell me\\\\there's a children's\\\\book about this!", target_mode="surprised", added_anims=[self.teacher.change, "tease"] ) self.play_student_changes("happy", "coin_flip_1", look_at=self.screen) self.look_at(self.screen) self.wait(5) class AskWhatTheMonsterActsOn(Scene): def construct(self): # Setup question = OldTexText( "The monster group describes the symmetries of ", "$\\underline{\\qquad\\qquad\\qquad}$", ) question[1].set_color(YELLOW) question.to_edge(UP) monster = get_monster() monster.set_height(5) monster.to_corner(DL) self.add(monster) self.play(FadeIn(question, DOWN)) self.wait() # Dimension counts dim_words = VGroup(*[ OldTexText( "Something in\\\\", "{:,}".format(n), " dimensions", "?" ) for n in [2, 3, 4, 5, 196883] ]) dim_words.scale(1.25) dim_words.to_edge(RIGHT, buff=LARGE_BUFF) dim_words.set_y(1.5) final_words = dim_words[-1] dim = Integer(196883, edge_to_fix=ORIGIN) dim.replace(final_words[1]) dim.match_style(final_words[1]) final_words.replace_submobject(1, dim) final_words[-1].set_opacity(0) cross = Cross(dim_words) cross.set_stroke(RED, 8) for dim_word in dim_words[:-1]: cross.replace(dim_word[1], stretch=True) self.add(dim_word) self.wait() self.play(ShowCreation(cross, run_time=0.5)) self.wait(0.5) self.remove(dim_word, cross) penult = dim_words[-2] dim.set_value(0) for i in 0, 2: final_words[i].save_state() final_words[i].replace(penult[i]) self.play( Restore(final_words[0]), Restore(final_words[2]), FadeOut(penult[3]), ChangingDecimal( dim, lambda a: interpolate(5, 196883, a), run_time=8, rate_func=rush_from, ), UpdateFromAlphaFunc( Mobject(), lambda m, a, fw=final_words: fw.set_color(interpolate_color(WHITE, YELLOW, a)), remover=True ) ) final_words.add(dim) self.add(final_words) self.wait() self.play(blink_monster(monster)) self.wait() # Elements of the monster in_sym = OldTex("\\in") in_sym.scale(2.5) monster.generate_target() monster.target.center().to_edge(RIGHT) in_sym.next_to(monster.target, LEFT, MED_LARGE_BUFF) self.play( MoveToTarget(monster), FadeOut(question, 3 * RIGHT), FadeOut(final_words, 2 * RIGHT), FadeIn(in_sym, 3 * LEFT), ) matrix = IntegerMatrix( np.random.randint(0, 2, size=(6, 6)), v_buff=0.8, h_buff=0.8, ) matrix.set_height(4) matrix.next_to(in_sym, LEFT, MED_LARGE_BUFF) mob_matrix = matrix.get_mob_matrix() groups_to_dots = [ (mob_matrix[4, :4], OldTex("\\vdots")), (mob_matrix[:4, 4], OldTex("\\ldots")), (VGroup(mob_matrix[4, 4]), OldTex("\\ddots")), ] for group, dots in groups_to_dots: for elem in group: dots_copy = dots.copy() dots_copy.move_to(elem) elem.set_submobjects(dots_copy) braces = VGroup( Brace(matrix.get_entries(), DOWN), Brace(matrix.get_entries(), LEFT), ) braces[1].shift(MED_SMALL_BUFF * LEFT) for brace in braces: brace.add(brace.get_text("196{,}882")) braces.set_color(BLUE) gigs_label = OldTexText("Each element $\\approx$ 4.5 Gigabytes of data!") gigs_label.next_to(matrix, UP, MED_LARGE_BUFF) self.play(Write(matrix, run_time=1)) self.play( LaggedStartMap(GrowFromCenter, braces, lag_ratio=0.5, run_time=1), FadeIn(gigs_label, DOWN) ) self.play(blink_monster(monster)) self.wait() class MonsterQuotes(Scene): def construct(self): images = [ get_named_image("John Conway"), get_named_image("Richard Borcherds"), ] quotes = [ OldTexText( """ ``Nothing has given me the feeling\\\\ that I understand why the monster\\\\ is there.''\\\\ """, alignment="", ), OldTexText( """ ``The monster simple group . . . appears\\\\ to rely on numerous bizarre coincidences\\\\ to exist.''\\\\ """, alignment="", ), ] faders = [] self.clear() for image, quote, color in zip(images, quotes, [YELLOW, WHITE]): quote[0].set_color(color) image.set_height(5) image.to_edge(LEFT) image[1].set_color(GREY_B) quote.next_to(image, RIGHT, buff=1, aligned_edge=UP) quote.shift(DOWN) quote.shift_onto_screen() self.play( FadeIn(image, DOWN), FadeIn(quote, lag_ratio=0.1, run_time=3), *faders, ) self.wait(4) faders = [FadeOut(image, UP), FadeOut(quote)] class MonstrousMoonshine(Scene): def construct(self): # Time line decades = list(range(1970, 2030, 10)) timeline = NumberLine( (decades[0], decades[-1], 1), numbers_with_elongated_ticks=decades, tick_size=0.075, width=13, ) timeline.add_numbers(decades, group_with_commas=False) timeline.move_to(DOWN) self.add(timeline) triangle = Triangle() triangle.rotate(PI) triangle.set_height(0.25) triangle.set_fill(BLUE_C, 1) triangle.set_stroke(WHITE, 0) triangle.move_to(timeline.n2p(2020), DOWN) self.add(triangle) self.play( triangle.move_to, timeline.n2p(1978), DOWN, run_time=3, ) # McKay mckay = get_named_image("John McKay") mckay[0].flip() mckay.next_to(triangle, UP) self.play(FadeIn(mckay, DOWN)) self.wait() theories = VGroup( OldTexText("Finite group theory"), OldTexText("Galois theory"), ) theories.arrange(RIGHT, buff=1.5) theories.next_to(mckay, RIGHT, LARGE_BUFF) theories_line, theories_arrow = [ func( *[theory.get_top() for theory in theories], path_arc=-90 * DEGREES, buff=0.2, ).shift(0.25 * UP) for func in [Line, Arrow] ] theories_line.set_stroke(BLUE_C, 6) theories_arrow.set_fill(BLUE_C) self.play(FadeIn(theories[0], LEFT)) self.play( GrowFromPoint(theories[1], theories_line.get_start(), path_arc=-90 * DEGREES), ShowCreationThenFadeOut(theories_line, run_time=2), FadeIn(theories_arrow, rate_func=squish_rate_func(smooth, 0.3, 1), run_time=2) ) self.wait() theories_group = VGroup(theories, theories_arrow) # j function j_func = OldTex( "j(\\tau) =q^{-1}+744+196{,}884 q+21{,}493{,}760 q^{2}+864{,}299{,}970 q^{3}+\\cdots\\\\", "\\big(q = e^{2\\pi i \\tau}\\big)", tex_to_color_map={ "\\tau": TEAL, "q": BLUE, "196{,}884": WHITE, } ) j_func.scale(0.7) j_func[-5:].shift([-0.5, -0.25, 0]) j_func.next_to(mckay, RIGHT, aligned_edge=DOWN) j_func.shift(0.5 * UP) special_num = j_func.get_part_by_tex("196{,}884") special_num_underline = Underline(special_num) special_num_underline.set_stroke(YELLOW, 3) self.play( theories_group.scale, 0.5, {"about_edge": UL}, theories_group.to_edge, UP, Write(j_func) ) self.wait() self.play( ShowCreation(special_num_underline), special_num.set_color, YELLOW, ) self.wait() j_coloring = ImageMobject("J_Invariant_Coloring") j_coloring.set_width(FRAME_WIDTH) j_coloring.to_edge(DOWN, buff=0) j_coloring.set_opacity(0.25) self.add(j_coloring, *self.mobjects) self.play(FadeIn(j_coloring)) self.wait(0.5) self.play(FadeOut(j_coloring), FadeOut(special_num_underline)) self.wait() # Conway conway = get_named_image("John Conway") conway[0].flip() conway.move_to(mckay) conway.to_edge(RIGHT) moonshine = OldTexText("Moonshine!") moonshine.set_height(0.6) moonshine.next_to(conway, LEFT, MED_LARGE_BUFF, aligned_edge=UP) moonshine.set_color(YELLOW) self.play( FadeOut(timeline, DOWN), FadeOut(triangle, DOWN), j_func.to_edge, DOWN, FadeOut(theories_group), FadeIn(conway, DOWN), ) self.play(Write(moonshine)) self.wait() # Conjecture conjecture = OldTexText("Monstrous ", "moonshine\\\\", " conjecture") conjecture_icon = VGroup( get_monster().set_height(1), OldTex("\\leftrightarrow"), OldTex("j(\\tau)", tex_to_color_map={"\\tau": TEAL}), ) conjecture_icon.arrange(RIGHT, buff=SMALL_BUFF) conjecture_icon.set_height(1.5) conjecture_icon.next_to(timeline.n2p(1979), UP, MED_LARGE_BUFF) conjecture.next_to(conjecture_icon, UP, MED_LARGE_BUFF) self.play( FadeIn(timeline, DOWN), FadeIn(triangle, DOWN), FadeOut(mckay, UP), Transform( moonshine, moonshine.copy().replace(conjecture[1], stretch=True).fade(1), remover=True, ), ReplacementTransform( conjecture[1].copy().replace(moonshine, stretch=True).fade(1), conjecture[1], ), Write(conjecture[0::2]), ) self.play( FadeIn(conjecture_icon, lag_ratio=0.1), triangle.move_to, timeline.n2p(1979), DOWN, ) self.play(blink_monster(conjecture_icon[0])) self.wait() conjecture_group = VGroup(conjecture, conjecture_icon) # Borcherds borcherds = get_named_image("Richard Borcherds") borcherds.next_to(timeline.n2p(1992), UP, MED_LARGE_BUFF) self.play( conjecture_group.scale, 0.5, {"about_edge": DOWN}, triangle.move_to, timeline.n2p(1992), DOWN, FadeOut(conway, RIGHT), FadeIn(borcherds, 2 * LEFT) ) self.wait(2) self.play( triangle.move_to, timeline.n2p(1998), DOWN, MaintainPositionRelativeTo(borcherds, triangle), ) medal = ImageMobject("Fields Medal") medal.set_height(1) medal.move_to(borcherds.get_corner(UR), LEFT) self.play(FadeIn(medal, DOWN)) self.wait() class StringTheory(Scene): def construct(self): monster = get_monster() monster.set_height(4) arrow = OldTex("\\leftrightarrow").scale(2) n = 10 points = compass_directions(n) freqs = np.random.random(n) + 0.3 string = VMobject() string.set_stroke([BLUE, TEAL, BLUE, TEAL, BLUE, TEAL, BLUE], 4) def update_string(string, points=points, freqs=freqs, sc=self): for point, freq in zip(points, freqs): point[:] = normalize(point) * (1 + 0.2 * np.sin(TAU * freq * sc.time)) string.set_points_smoothly([*points, points[0]]) string.add_updater(update_string) arrow.next_to(string, LEFT, LARGE_BUFF) monster.next_to(arrow, LEFT, LARGE_BUFF) # self.camera.frame.move_to(arrow) self.camera.frame.scale(0.5) st_name = OldTexText("String theory") st_name.scale(1.5) st_name.next_to(string, UP, LARGE_BUFF) sg_name = OldTexText("Sporadic groups") sg_name.scale(1.5) sg_name.next_to(monster, DOWN) self.add(monster) self.add(arrow) self.add(string) self.wait(2) self.play(Write(sg_name)) self.play(Write(st_name)) for x in range(4): self.play(blink_monster(monster)) self.wait(5) class MonsterThanks(PatreonEndScreen): pass
from _2019.clacks.question import BlocksAndWallExampleMass1e2 from _2019.clacks.solution1 import CircleDiagramFromSlidingBlocks1e2 class Clacks1(BlocksAndWallExampleMass1e2): CONFIG = { "counter_label": "Number of collisions: ", "sliding_blocks_config": { "block1_config": { "mass": 1e0, "velocity": -2.0, "sheen_factor": 0.0, "stroke_width": 1, "fill_color": "#cccccc", }, "block2_config": { "fill_color": "#cccccc", "sheen_factor": 0.0, "stroke_width": 1, }, }, "wait_time": 15, } class Clacks100(Clacks1): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e2, "fill_color": "#ff6d58", "velocity": -0.5, "distance": 5, }, }, "wait_time": 33, } class Clacks1e4(Clacks1): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e4, "fill_color": "#44c5ae", "distance": 5, "velocity": -0.7, }, }, "wait_time": 32, } class Clacks1e6(Clacks1): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e6, "fill_color": "#2fb9de", "velocity": -0.5, "distance": 5, }, }, "wait_time": 26, } class SlowClacks100(Clacks1): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e2, "fill_color": "#ff6666", "velocity": -0.25, "distance": 4.5, }, }, "wait_time": 65, } class Clacks100VectorEvolution(CircleDiagramFromSlidingBlocks1e2): CONFIG = { "BlocksAndWallSceneClass": SlowClacks100, "show_dot": False, "show_vector": True, }
from manim_imports_ext import * class NewSceneName(ThreeDScene): def construct(self): pass
from manim_imports_ext import * SICKLY_GREEN = "#9BBD37" COLOR_MAP = { "S": BLUE, "I": RED, "R": GREY_D, } def update_time(mob, dt): mob.time += dt class Person(VGroup): CONFIG = { "status": "S", # S, I or R "height": 0.2, "color_map": COLOR_MAP, "infection_ring_style": { "stroke_color": RED, "stroke_opacity": 0.8, "stroke_width": 0, }, "infection_radius": 0.5, "infection_animation_period": 2, "symptomatic": False, "p_symptomatic_on_infection": 1, "max_speed": 1, "dl_bound": [-FRAME_WIDTH / 2, -FRAME_HEIGHT / 2], "ur_bound": [FRAME_WIDTH / 2, FRAME_HEIGHT / 2], "gravity_well": None, "gravity_strength": 1, "wall_buffer": 1, "wander_step_size": 1, "wander_step_duration": 1, "social_distance_factor": 0, "social_distance_color_threshold": 2, "n_repulsion_points": 10, "social_distance_color": YELLOW, "max_social_distance_stroke_width": 5, "asymptomatic_color": YELLOW, } def __init__(self, **kwargs): super().__init__(**kwargs) self.time = 0 self.last_step_change = -1 self.change_anims = [] self.velocity = np.zeros(3) self.infection_start_time = np.inf self.infection_end_time = np.inf self.repulsion_points = [] self.num_infected = 0 self.center_point = VectorizedPoint() self.add(self.center_point) self.add_body() self.add_infection_ring() self.set_status(self.status, run_time=0) # Updaters self.add_updater(update_time) self.add_updater(lambda m, dt: m.update_position(dt)) self.add_updater(lambda m, dt: m.update_infection_ring(dt)) self.add_updater(lambda m: m.progress_through_change_anims()) def add_body(self): body = self.get_body() body.set_height(self.height) body.move_to(self.get_center()) self.add(body) self.body = body def get_body(self, status): person = SVGMobject(file_name="person") person.set_stroke(width=0) return person def set_status(self, status, run_time=1): start_color = self.color_map[self.status] end_color = self.color_map[status] if status == "I": self.infection_start_time = self.time self.infection_ring.set_stroke(width=0, opacity=0) if random.random() < self.p_symptomatic_on_infection: self.symptomatic = True else: self.infection_ring.set_color(self.asymptomatic_color) end_color = self.asymptomatic_color if self.status == "I": self.infection_end_time = self.time self.symptomatic = False anims = [ UpdateFromAlphaFunc( self.body, lambda m, a: m.set_color(interpolate_color( start_color, end_color, a )), run_time=run_time, ) ] for anim in anims: self.push_anim(anim) self.status = status def push_anim(self, anim): anim.suspend_mobject_updating = False anim.begin() anim.start_time = self.time self.change_anims.append(anim) return self def pop_anim(self, anim): anim.update(1) anim.finish() self.change_anims.remove(anim) def add_infection_ring(self): self.infection_ring = Circle( radius=self.height / 2, ) self.infection_ring.set_style(**self.infection_ring_style) self.add(self.infection_ring) self.infection_ring.time = 0 return self def update_position(self, dt): center = self.get_center() total_force = np.zeros(3) # Gravity if self.wander_step_size != 0: if (self.time - self.last_step_change) > self.wander_step_duration: vect = rotate_vector(RIGHT, TAU * random.random()) self.gravity_well = center + self.wander_step_size * vect self.last_step_change = self.time if self.gravity_well is not None: to_well = (self.gravity_well - center) dist = get_norm(to_well) if dist != 0: total_force += self.gravity_strength * to_well / (dist**3) # Potentially avoid neighbors if self.social_distance_factor > 0: repulsion_force = np.zeros(3) min_dist = np.inf for point in self.repulsion_points: to_point = point - center dist = get_norm(to_point) if 0 < dist < min_dist: min_dist = dist if dist > 0: repulsion_force -= self.social_distance_factor * to_point / (dist**3) sdct = self.social_distance_color_threshold self.body.set_stroke( self.social_distance_color, width=clip( (sdct / min_dist) - sdct, # 2 * (sdct / min_dist), 0, self.max_social_distance_stroke_width ), background=True, ) total_force += repulsion_force # Avoid walls wall_force = np.zeros(3) for i in range(2): to_lower = center[i] - self.dl_bound[i] to_upper = self.ur_bound[i] - center[i] # Bounce if to_lower < 0: self.velocity[i] = abs(self.velocity[i]) self.set_coord(self.dl_bound[i], i) if to_upper < 0: self.velocity[i] = -abs(self.velocity[i]) self.set_coord(self.ur_bound[i], i) # Repelling force wall_force[i] += max((-1 / self.wall_buffer + 1 / to_lower), 0) wall_force[i] -= max((-1 / self.wall_buffer + 1 / to_upper), 0) total_force += wall_force # Apply force self.velocity += total_force * dt # Limit speed speed = get_norm(self.velocity) if speed > self.max_speed: self.velocity *= self.max_speed / speed # Update position self.shift(self.velocity * dt) def update_infection_ring(self, dt): ring = self.infection_ring if not (self.infection_start_time <= self.time <= self.infection_end_time + 1): return self ring_time = self.time - self.infection_start_time period = self.infection_animation_period alpha = (ring_time % period) / period ring.set_height(interpolate( self.height, self.infection_radius, smooth(alpha), )) ring.set_stroke( width=interpolate( 0, 5, there_and_back(alpha), ), opacity=min([ min([ring_time, 1]), min([self.infection_end_time + 1 - self.time, 1]), ]), ) return self def progress_through_change_anims(self): for anim in self.change_anims: if anim.run_time == 0: alpha = 1 else: alpha = (self.time - anim.start_time) / anim.run_time anim.interpolate(alpha) if alpha >= 1: self.pop_anim(anim) def get_center(self): return self.center_point.get_points()[0] class DotPerson(Person): def get_body(self): return Dot() class PiPerson(Person): CONFIG = { "mode_map": { "S": "guilty", "I": "sick", "R": "tease", } } def get_body(self): return Randolph() def set_status(self, status, run_time=1): super().set_status(status) target = self.body.copy() target.change(self.mode_map[status]) target.set_color(self.color_map[status]) transform = Transform(self.body, target) transform.begin() def update(body, alpha): transform.update(alpha) body.move_to(self.center_point) anims = [ UpdateFromAlphaFunc(self.body, update, run_time=run_time), ] for anim in anims: self.push_anim(anim) return self class SIRSimulation(VGroup): CONFIG = { "n_cities": 1, "city_population": 100, "box_size": 7, "person_type": PiPerson, "person_config": { "height": 0.2, "infection_radius": 0.6, "gravity_strength": 1, "wander_step_size": 1, }, "p_infection_per_day": 0.2, "infection_time": 5, "travel_rate": 0, "limit_social_distancing_to_infectious": False, } def __init__(self, **kwargs): super().__init__(**kwargs) self.time = 0 self.add_updater(update_time) self.add_boxes() self.add_people() self.add_updater(lambda m, dt: m.update_statusses(dt)) def add_boxes(self): boxes = VGroup() for x in range(self.n_cities): box = Square() box.set_height(self.box_size) box.set_stroke(WHITE, 3) boxes.add(box) boxes.arrange_in_grid(buff=LARGE_BUFF) self.add(boxes) self.boxes = boxes def add_people(self): people = VGroup() for box in self.boxes: dl_bound = box.get_corner(DL) ur_bound = box.get_corner(UR) box.people = VGroup() for x in range(self.city_population): person = self.person_type( dl_bound=dl_bound, ur_bound=ur_bound, **self.person_config ) person.move_to([ interpolate(lower, upper, random.random()) for lower, upper in zip(dl_bound, ur_bound) ]) person.box = box box.people.add(person) people.add(person) # Choose a patient zero random.choice(people).set_status("I") self.add(people) self.people = people def update_statusses(self, dt): for box in self.boxes: s_group, i_group = [ list(filter( lambda m: m.status == status, box.people )) for status in ["S", "I"] ] for s_person in s_group: for i_person in i_group: dist = get_norm(i_person.get_center() - s_person.get_center()) if dist < s_person.infection_radius and random.random() < self.p_infection_per_day * dt: s_person.set_status("I") i_person.num_infected += 1 for i_person in i_group: if (i_person.time - i_person.infection_start_time) > self.infection_time: i_person.set_status("R") # Travel if self.travel_rate > 0: path_func = path_along_arc(45 * DEGREES) for person in self.people: if random.random() < self.travel_rate * dt: new_box = random.choice(self.boxes) person.box.people.remove(person) new_box.people.add(person) person.box = new_box person.dl_bound = new_box.get_corner(DL) person.ur_bound = new_box.get_corner(UR) person.old_center = person.get_center() person.new_center = new_box.get_center() anim = UpdateFromAlphaFunc( person, lambda m, a: m.move_to(path_func( m.old_center, m.new_center, a, )), run_time=1, ) person.push_anim(anim) # Social distancing centers = np.array([person.get_center() for person in self.people]) if self.limit_social_distancing_to_infectious: repelled_centers = np.array([ person.get_center() for person in self.people if person.symptomatic ]) else: repelled_centers = centers if len(repelled_centers) > 0: for center, person in zip(centers, self.people): if person.social_distance_factor > 0: diffs = np.linalg.norm(repelled_centers - center, axis=1) person.repulsion_points = repelled_centers[np.argsort(diffs)[1:person.n_repulsion_points + 1]] def get_status_counts(self): return np.array([ len(list(filter( lambda m: m.status == status, self.people ))) for status in "SIR" ]) def get_status_proportions(self): counts = self.get_status_counts() return counts / sum(counts) class SIRGraph(VGroup): CONFIG = { "color_map": COLOR_MAP, "height": 7, "width": 5, "update_frequency": 0.5, "include_braces": False, } def __init__(self, simulation, **kwargs): super().__init__(**kwargs) self.simulation = simulation self.data = [simulation.get_status_proportions()] * 2 self.add_axes() self.add_graph() self.add_x_labels() self.time = 0 self.last_update_time = 0 self.add_updater(update_time) self.add_updater(lambda m: m.update_graph()) self.add_updater(lambda m: m.update_x_labels()) def add_axes(self): axes = Axes( y_min=0, y_max=1, y_axis_config={ "tick_frequency": 0.1, }, x_min=0, x_max=1, axis_config={ "include_tip": False, }, ) origin = axes.c2p(0, 0) axes.x_axis.set_width(self.width, about_point=origin, stretch=True) axes.y_axis.set_height(self.height, about_point=origin, stretch=True) self.add(axes) self.axes = axes def add_graph(self): self.graph = self.get_graph(self.data) self.add(self.graph) def add_x_labels(self): self.x_labels = VGroup() self.x_ticks = VGroup() self.add(self.x_ticks, self.x_labels) def get_graph(self, data): axes = self.axes i_points = [] s_points = [] for x, props in zip(np.linspace(0, 1, len(data)), data): i_point = axes.c2p(x, props[1]) s_point = axes.c2p(x, sum(props[:2])) i_points.append(i_point) s_points.append(s_point) r_points = [ axes.c2p(0, 1), axes.c2p(1, 1), *s_points[::-1], axes.c2p(0, 1), ] s_points.extend([ *i_points[::-1], s_points[0], ]) i_points.extend([ axes.c2p(1, 0), axes.c2p(0, 0), i_points[0], ]) points_lists = [s_points, i_points, r_points] regions = VGroup(VMobject(), VMobject(), VMobject()) for region, status, points in zip(regions, "SIR", points_lists): region.set_points_as_corners(points) region.set_stroke(width=0) region.set_fill(self.color_map[status], 1) regions[0].set_fill(opacity=0.5) return regions def update_graph(self): if (self.time - self.last_update_time) > self.update_frequency: self.data.append(self.simulation.get_status_proportions()) self.graph.become(self.get_graph(self.data)) self.last_update_time = self.time def update_x_labels(self): tick_height = 0.03 * self.graph.get_height() tick_template = Line(DOWN, UP) tick_template.set_height(tick_height) def get_tick(x): tick = tick_template.copy() tick.move_to(self.axes.c2p(x / self.time, 0)) return tick def get_label(x, tick): label = Integer(x) label.set_height(tick_height) label.next_to(tick, DOWN, buff=0.5 * tick_height) return label self.x_labels.set_submobjects([]) self.x_ticks.set_submobjects([]) if self.time < 15: tick_range = range(1, int(self.time) + 1) elif self.time < 50: tick_range = range(5, int(self.time) + 1, 5) elif self.time < 100: tick_range = range(10, int(self.time) + 1, 10) else: tick_range = range(20, int(self.time) + 1, 20) for x in tick_range: tick = get_tick(x) label = get_label(x, tick) self.x_ticks.add(tick) self.x_labels.add(label) # TODO, if I care, refactor if 10 < self.time < 15: alpha = (self.time - 10) / 5 for tick, label in zip(self.x_ticks, self.x_labels): if label.get_value() % 5 != 0: label.set_opacity(1 - alpha) tick.set_opacity(1 - alpha) if 45 < self.time < 50: alpha = (self.time - 45) / 5 for tick, label in zip(self.x_ticks, self.x_labels): if label.get_value() % 10 == 5: label.set_opacity(1 - alpha) tick.set_opacity(1 - alpha) def add_v_line(self, line_time=None, color=YELLOW, stroke_width=3): if line_time is None: line_time = self.time axes = self.axes v_line = Line( axes.c2p(1, 0), axes.c2p(1, 1), stroke_color=color, stroke_width=stroke_width, ) v_line.add_updater( lambda m: m.move_to( axes.c2p(line_time / max(self.time, 1e-6), 0), DOWN, ) ) self.add(v_line) class GraphBraces(VGroup): CONFIG = { "update_frequency": 0.5, } def __init__(self, graph, simulation, **kwargs): super().__init__(**kwargs) axes = self.axes = graph.axes self.simulation = simulation ys = np.linspace(0, 1, 4) self.lines = VGroup(*[ Line(axes.c2p(1, y1), axes.c2p(1, y2)) for y1, y2 in zip(ys, ys[1:]) ]) self.braces = VGroup(*[Brace(line, RIGHT) for line in self.lines]) self.labels = VGroup( OldTexText("Susceptible", color=COLOR_MAP["S"]), OldTexText("Infectious", color=COLOR_MAP["I"]), OldTexText("Removed", color=COLOR_MAP["R"]), ) self.max_label_height = graph.get_height() * 0.05 self.add(self.braces, self.labels) self.time = 0 self.last_update_time = -1 self.add_updater(update_time) self.add_updater(lambda m: m.update_braces()) self.update(0) def update_braces(self): if (self.time - self.last_update_time) <= self.update_frequency: return self.last_update_time = self.time lines = self.lines braces = self.braces labels = self.labels axes = self.axes props = self.simulation.get_status_proportions() ys = np.cumsum([0, props[1], props[0], props[2]]) epsilon = 1e-6 for i, y1, y2 in zip([1, 0, 2], ys, ys[1:]): lines[i].set_points_as_corners([ axes.c2p(1, y1), axes.c2p(1, y2), ]) height = lines[i].get_height() braces[i].set_height( max(height, epsilon), stretch=True ) braces[i].next_to(lines[i], RIGHT) label_height = clip(height, epsilon, self.max_label_height) labels[i].scale(label_height / labels[i][0][0].get_height()) labels[i].next_to(braces[i], RIGHT) return self class ValueSlider(NumberLine): CONFIG = { "x_min": 0, "x_max": 1, "tick_frequency": 0.1, "numbers_with_elongated_ticks": [], "numbers_to_show": np.linspace(0, 1, 6), "decimal_number_config": { "num_decimal_places": 1, }, "stroke_width": 5, "width": 8, "marker_color": BLUE, } def __init__(self, name, value, **kwargs): super().__init__(**kwargs) self.set_width(self.width, stretch=True) self.add_numbers() self.marker = ArrowTip(start_angle=-90 * DEGREES) self.marker.move_to(self.n2p(value), DOWN) self.marker.set_color(self.marker_color) self.add(self.marker) # self.label = DecimalNumber(value) # self.label.next_to(self.marker, UP) # self.add(self.label) self.name = OldTexText(name) self.name.scale(1.25) self.name.next_to(self, DOWN) self.name.match_color(self.marker) self.add(self.name) def get_change_anim(self, new_value, **kwargs): start_value = self.p2n(self.marker.get_bottom()) # m2l = self.label.get_center() - self.marker.get_center() def update(mob, alpha): interim_value = interpolate(start_value, new_value, alpha) mob.marker.move_to(mob.n2p(interim_value), DOWN) # mob.label.move_to(mob.marker.get_center() + m2l) # mob.label.set_value(interim_value) return UpdateFromAlphaFunc(self, update, **kwargs) # Scenes class Test(Scene): def construct(self): path_func = path_along_arc(45 * DEGREES) person = PiPerson(height=1, gravity_strength=0.2) person.gravity_strength = 0 person.old_center = person.get_center() person.new_center = 4 * RIGHT self.add(person) self.wait() self.play(UpdateFromAlphaFunc( person, lambda m, a: m.move_to(path_func( m.old_center, m.new_center, a, )), run_time=3, rate_func=there_and_back, )) self.wait(3) self.wait(3) class RunSimpleSimulation(Scene): CONFIG = { "simulation_config": { "person_type": PiPerson, "n_cities": 1, "city_population": 100, "person_config": { "infection_radius": 0.75, "social_distance_factor": 0, "gravity_strength": 0.2, "max_speed": 0.5, }, "travel_rate": 0, "infection_time": 5, }, "graph_config": { "update_frequency": 1 / 15, }, "graph_height_to_frame_height": 0.5, "graph_width_to_frame_height": 0.75, "include_graph_braces": True, } def setup(self): self.add_simulation() self.position_camera() self.add_graph() self.add_sliders() self.add_R_label() self.add_total_cases_label() def construct(self): self.run_until_zero_infections() def wait_until_infection_threshold(self, threshold): self.wait_until(lambda: self.simulation.get_status_counts()[1] > threshold) def run_until_zero_infections(self): while True: self.wait(5) if self.simulation.get_status_counts()[1] == 0: self.wait(5) break def add_R_label(self): label = VGroup( OldTex("R = "), DecimalNumber(), ) label.arrange(RIGHT) boxes = self.simulation.boxes label.set_width(0.25 * boxes.get_width()) label.next_to(boxes.get_corner(DL), DR) self.add(label) all_R0_values = [] def update_label(label): if (self.time - label.last_update_time) < label.update_period: return label.last_update_time = self.time values = [] for person in self.simulation.people: if person.status == "I": prop = (person.time - person.infection_start_time) / self.simulation.infection_time if prop > 0.1: values.append(person.num_infected / prop) if len(values) > 0: all_R0_values.append(np.mean(values)) average = np.mean(all_R0_values[-20:]) label[1].set_value(average) label.last_update_time = 0 label.update_period = 1 label.add_updater(update_label) def add_total_cases_label(self): label = VGroup( OldTexText("\\# Active cases = "), Integer(1), ) label.arrange(RIGHT) label[1].align_to(label[0][0][1], DOWN) label.set_color(RED) boxes = self.simulation.boxes label.set_width(0.5 * boxes.get_width()) label.next_to(boxes, UP, buff=0.03 * boxes.get_width()) label.add_updater( lambda m: m[1].set_value(self.simulation.get_status_counts()[1]) ) self.total_cases_label = label self.add(label) def add_simulation(self): self.simulation = SIRSimulation(**self.simulation_config) self.add(self.simulation) def position_camera(self): frame = self.camera.frame boxes = self.simulation.boxes min_height = boxes.get_height() + 1 min_width = 3 * boxes.get_width() if frame.get_height() < min_height: frame.set_height(min_height) if frame.get_width() < min_width: frame.set_width(min_width) frame.next_to(boxes.get_right(), LEFT, buff=-0.1 * boxes.get_width()) def add_graph(self): frame = self.camera.frame frame_height = frame.get_height() graph = SIRGraph( self.simulation, height=self.graph_height_to_frame_height * frame_height, width=self.graph_width_to_frame_height * frame_height, **self.graph_config, ) graph.move_to(frame, UL) graph.shift(0.05 * DR * frame_height) self.add(graph) self.graph = graph if self.include_graph_braces: self.graph_braces = GraphBraces( graph, self.simulation, update_frequency=graph.update_frequency ) self.add(self.graph_braces) def add_sliders(self): pass class RunSimpleSimulationWithDots(RunSimpleSimulation): CONFIG = { "simulation_config": { "person_type": DotPerson, } } class LargerCity(RunSimpleSimulation): CONFIG = { "simulation_config": { "person_type": DotPerson, "city_population": 1000, "person_config": { "infection_radius": 0.25, "social_distance_factor": 0, "gravity_strength": 0.2, "max_speed": 0.25, "height": 0.2 / 3, "wall_buffer": 1 / 3, "social_distance_color_threshold": 2 / 3, }, } } class LargerCity2(LargerCity): CONFIG = { "random_seed": 1, } class LargeCityHighInfectionRadius(LargerCity): CONFIG = { "simulation_config": { "person_config": { "infection_radius": 0.5, }, }, "graph_config": { "update_frequency": 1 / 60, }, } class LargeCityLowerInfectionRate(LargerCity): CONFIG = { "p_infection_per_day": 0.1, } class SimpleSocialDistancing(RunSimpleSimulation): CONFIG = { "simulation_config": { "person_type": PiPerson, "n_cities": 1, "city_population": 100, "person_config": { "infection_radius": 0.75, "social_distance_factor": 2, "gravity_strength": 0.1, }, "travel_rate": 0, "infection_time": 5, }, } class DelayedSocialDistancing(RunSimpleSimulation): CONFIG = { "delay_time": 8, "target_sd_factor": 2, "sd_probability": 1, "random_seed": 1, } def construct(self): self.wait(self.delay_time) self.change_social_distance_factor( self.target_sd_factor, self.sd_probability, ) self.graph.add_v_line() self.play(self.sd_slider.get_change_anim(self.target_sd_factor)) self.run_until_zero_infections() def change_social_distance_factor(self, new_factor, prob): for person in self.simulation.people: if random.random() < prob: person.social_distance_factor = new_factor def add_sliders(self): slider = ValueSlider( self.get_sd_slider_name(), value=0, x_min=0, x_max=2, tick_frequency=0.5, numbers_with_elongated_ticks=[], numbers_to_show=range(3), decimal_number_config={ "num_decimal_places": 0, } ) slider.match_width(self.graph) slider.next_to(self.graph, DOWN, buff=0.2 * self.graph.get_height()) self.add(slider) self.sd_slider = slider def get_sd_slider_name(self): return f"Social Distance Factor\\\\({int(100 * self.sd_probability)}$\\%$ of population)" class DelayedSocialDistancingDot(DelayedSocialDistancing): CONFIG = { "simulation_config": { "person_type": DotPerson, } } class DelayedSocialDistancingLargeCity(DelayedSocialDistancing, LargerCity): CONFIG = { "trigger_infection_count": 50, "simulation_config": { 'city_population': 900, } } def construct(self): self.wait_until_infection_threshold(self.trigger_infection_count) self.change_social_distance_factor( self.target_sd_factor, self.sd_probability, ) self.graph.add_v_line() self.play(self.sd_slider.get_change_anim(self.target_sd_factor)) self.run_until_zero_infections() class DelayedSocialDistancingLargeCity90p(DelayedSocialDistancingLargeCity): CONFIG = { "sd_probability": 0.9, } class DelayedSocialDistancingLargeCity90pAlt(DelayedSocialDistancingLargeCity): CONFIG = { "sd_probability": 0.9, "random_seed": 5, } class DelayedSocialDistancingLargeCity70p(DelayedSocialDistancingLargeCity): CONFIG = { "sd_probability": 0.7, } class DelayedSocialDistancingLargeCity50p(DelayedSocialDistancingLargeCity): CONFIG = { "sd_probability": 0.5, } class DelayedSocialDistancingWithDots(DelayedSocialDistancing): CONFIG = { "person_type": DotPerson, } class DelayedSocialDistancingProbHalf(DelayedSocialDistancing): CONFIG = { "sd_probability": 0.5, } class ReduceInfectionDuration(LargerCity): CONFIG = { "trigger_infection_count": 50, } def construct(self): self.wait_until_infection_threshold(self.trigger_infection_count) self.play(self.slider.get_change_anim(1)) self.simulation.infection_time = 1 self.graph.add_v_line() self.run_until_zero_infections() def add_sliders(self): slider = ValueSlider( "Infection duration", value=5, x_min=0, x_max=5, tick_frequency=1, numbers_with_elongated_ticks=[], numbers_to_show=range(6), decimal_number_config={ "num_decimal_places": 0, }, marker_color=RED, ) slider.match_width(self.graph) slider.next_to(self.graph, DOWN, buff=0.2 * self.graph.get_height()) self.add(slider) self.slider = slider class SimpleTravel(RunSimpleSimulation): CONFIG = { "simulation_config": { "person_type": DotPerson, "n_cities": 12, "city_population": 100, "person_config": { "infection_radius": 0.75, "social_distance_factor": 0, "gravity_strength": 0.5, }, "travel_rate": 0.02, "infection_time": 5, }, } def add_sliders(self): slider = ValueSlider( "Travel rate", self.simulation.travel_rate, x_min=0, x_max=0.02, tick_frequency=0.005, numbers_with_elongated_ticks=[], numbers_to_show=np.arange(0, 0.03, 0.01), decimal_number_config={ "num_decimal_places": 2, } ) slider.match_width(self.graph) slider.next_to(self.graph, DOWN, buff=0.2 * self.graph.get_height()) self.add(slider) self.tr_slider = slider class SimpleTravel2(SimpleTravel): CONFIG = { "random_seed": 1, } class SimpleTravelLongInfectionPeriod(SimpleTravel): CONFIG = { "simulation_config": { "infection_time": 10, } } class SimpleTravelDelayedSocialDistancing(DelayedSocialDistancing, SimpleTravel): CONFIG = { "target_sd_factor": 2, "sd_probability": 0.7, "delay_time": 15, "trigger_infection_count": 50, } def construct(self): self.wait_until_infection_threshold(self.trigger_infection_count) self.change_social_distance_factor( self.target_sd_factor, self.sd_probability, ) self.graph.add_v_line() self.play(self.sd_slider.get_change_anim(self.target_sd_factor)) self.run_until_zero_infections() def add_sliders(self): SimpleTravel.add_sliders(self) DelayedSocialDistancing.add_sliders(self) buff = 0.1 * self.graph.get_height() self.tr_slider.scale(0.8, about_edge=UP) self.tr_slider.next_to(self.graph, DOWN, buff=buff) self.sd_slider.scale(0.8) self.sd_slider.marker.set_color(YELLOW) self.sd_slider.name.set_color(YELLOW) self.sd_slider.next_to(self.tr_slider, DOWN, buff=buff) class SimpleTravelDelayedSocialDistancing70p(SimpleTravelDelayedSocialDistancing): pass class SimpleTravelDelayedSocialDistancing99p(SimpleTravelDelayedSocialDistancing): CONFIG = { "sd_probability": 0.99, } class SimpleTravelDelayedSocialDistancing20p(SimpleTravelDelayedSocialDistancing): CONFIG = { "sd_probability": 0.20, } class SimpleTravelDelayedSocialDistancing50p(SimpleTravelDelayedSocialDistancing): CONFIG = { "sd_probability": 0.50, "random_seed": 1, } class SimpleTravelDelayedSocialDistancing50pThreshold100(SimpleTravelDelayedSocialDistancing): CONFIG = { "sd_probability": 0.50, "trigger_infection_count": 100, "random_seed": 5, } class SimpleTravelDelayedSocialDistancing70pThreshold100(SimpleTravelDelayedSocialDistancing): CONFIG = { "sd_probability": 0.70, "trigger_infection_count": 100, } class SimpleTravelSocialDistancePlusZeroTravel(SimpleTravelDelayedSocialDistancing): CONFIG = { "sd_probability": 1, "target_travel_rate": 0, } def construct(self): self.wait_until_infection_threshold(self.trigger_infection_count) self.change_social_distance_factor( self.target_sd_factor, self.sd_probability, ) self.simulation.travel_rate = self.target_travel_rate self.graph.add_v_line() self.play( self.tr_slider.get_change_anim(self.simulation.travel_rate), self.sd_slider.get_change_anim(self.target_sd_factor), ) self.run_until_zero_infections() class SecondWave(SimpleTravelSocialDistancePlusZeroTravel): def run_until_zero_infections(self): self.wait_until(lambda: self.simulation.get_status_counts()[1] < 10) self.change_social_distance_factor(0, 1) self.simulation.travel_rate = 0.02 self.graph.add_v_line() self.play( self.tr_slider.get_change_anim(0.02), self.sd_slider.get_change_anim(0), ) super().run_until_zero_infections() class SimpleTravelSocialDistancePlusZeroTravel99p(SimpleTravelSocialDistancePlusZeroTravel): CONFIG = { "sd_probability": 0.99, } class SimpleTravelDelayedTravelReduction(SimpleTravelDelayedSocialDistancing): CONFIG = { "trigger_infection_count": 50, "target_travel_rate": 0.002, } def construct(self): self.wait_until_infection_threshold(self.trigger_infection_count) self.simulation.travel_rate = self.target_travel_rate self.graph.add_v_line() self.play(self.tr_slider.get_change_anim(self.simulation.travel_rate)) self.run_until_zero_infections() class SimpleTravelDelayedTravelReductionThreshold100(SimpleTravelDelayedTravelReduction): CONFIG = { "random_seed": 2, "trigger_infection_count": 100, } class SimpleTravelDelayedTravelReductionThreshold100TargetHalfPercent(SimpleTravelDelayedTravelReduction): CONFIG = { "random_seed": 2, "trigger_infection_count": 100, "target_travel_rate": 0.005, } class SimpleTravelDelayedTravelReductionThreshold100TargetHalfPercent2(SimpleTravelDelayedTravelReductionThreshold100TargetHalfPercent): CONFIG = { "random_seed": 1, "sd_probability": 0.5, } def setup(self): super().setup() for x in range(2): random.choice(self.simulation.people).set_status("I") class SimpleTravelLargeCity(SimpleTravel, LargerCity): CONFIG = { "simulation_config": { "n_cities": 12, "travel_rate": 0.02, } } class SimpleTravelLongerDelayedSocialDistancing(SimpleTravelDelayedSocialDistancing): CONFIG = { "trigger_infection_count": 100, } class SimpleTravelLongerDelayedTravelReduction(SimpleTravelDelayedTravelReduction): CONFIG = { "trigger_infection_count": 100, } class SocialDistanceAfterFiveDays(DelayedSocialDistancing): CONFIG = { "sd_probability": 0.7, "delay_time": 5, "simulation_config": { "travel_rate": 0 }, } class QuarantineInfectious(RunSimpleSimulation): CONFIG = { "trigger_infection_count": 10, "target_sd_factor": 3, "infection_time_before_quarantine": 1, } def construct(self): self.wait_until_infection_threshold(self.trigger_infection_count) self.add_quarantine_box() self.set_quarantine_updaters() self.run_until_zero_infections() def add_quarantine_box(self): boxes = self.simulation.boxes q_box = boxes[0].copy() q_box.set_color(RED_E) q_box.set_width(boxes.get_width() / 3) q_box.next_to( boxes, LEFT, aligned_edge=DOWN, buff=0.25 * q_box.get_width() ) label = OldTexText("Quarantine zone") label.set_color(RED) label.match_width(q_box) label.next_to(q_box, DOWN, buff=0.1 * q_box.get_width()) self.add(q_box) self.add(label) self.q_box = q_box def set_quarantine_updaters(self): def quarantine_if_ready(simulation): for person in simulation.people: send_to_q_box = all([ not person.is_quarantined, person.symptomatic, (person.time - person.infection_start_time) > self.infection_time_before_quarantine, ]) if send_to_q_box: person.box = self.q_box person.dl_bound = self.q_box.get_corner(DL) person.ur_bound = self.q_box.get_corner(UR) person.old_center = person.get_center() person.new_center = self.q_box.get_center() point = VectorizedPoint(person.get_center()) person.push_anim(ApplyMethod(point.move_to, self.q_box.get_center(), run_time=0.5)) person.push_anim(MaintainPositionRelativeTo(person, point)) person.move_to(self.q_box.get_center()) person.is_quarantined = True for person in self.simulation.people: person.is_quarantined = False # person.add_updater(quarantine_if_ready) self.simulation.add_updater(quarantine_if_ready) class QuarantineInfectiousLarger(QuarantineInfectious, LargerCity): CONFIG = { "trigger_infection_count": 50, } class QuarantineInfectiousLargerWithTail(QuarantineInfectiousLarger): def construct(self): super().construct() self.simulation.clear_updaters() self.wait(25) class QuarantineInfectiousTravel(QuarantineInfectious, SimpleTravel): CONFIG = { "trigger_infection_count": 50, } def add_sliders(self): pass class QuarantineInfectious80p(QuarantineInfectious): CONFIG = { "simulation_config": { "person_config": { "p_symptomatic_on_infection": 0.8, } } } class QuarantineInfectiousLarger80p(QuarantineInfectiousLarger): CONFIG = { "simulation_config": { "person_config": { "p_symptomatic_on_infection": 0.8, } } } class QuarantineInfectiousTravel80p(QuarantineInfectiousTravel): CONFIG = { "simulation_config": { "person_config": { "p_symptomatic_on_infection": 0.8, } } } class QuarantineInfectious50p(QuarantineInfectious): CONFIG = { "simulation_config": { "person_config": { "p_symptomatic_on_infection": 0.5, } } } class QuarantineInfectiousLarger50p(QuarantineInfectiousLarger): CONFIG = { "simulation_config": { "person_config": { "p_symptomatic_on_infection": 0.5, } } } class QuarantineInfectiousTravel50p(QuarantineInfectiousTravel): CONFIG = { "simulation_config": { "person_config": { "p_symptomatic_on_infection": 0.5, } } } class CentralMarket(DelayedSocialDistancing): CONFIG = { "sd_probability": 0.7, "delay_time": 5, "simulation_config": { "person_type": DotPerson, "travel_rate": 0 }, "shopping_frequency": 0.05, "shopping_time": 1, } def setup(self): super().setup() for person in self.simulation.people: person.last_shopping_trip = -3 person.is_shopping = False square = Square() square.set_height(0.2) square.set_color(WHITE) square.move_to(self.simulation.boxes[0].get_center()) self.add(square) self.simulation.add_updater( lambda m, dt: self.add_travel_anims(m, dt) ) def construct(self): self.run_until_zero_infections() def add_travel_anims(self, simulation, dt): shopping_time = self.shopping_time for person in simulation.people: time_since_trip = person.time - person.last_shopping_trip if time_since_trip > shopping_time: if random.random() < dt * self.shopping_frequency: person.last_shopping_trip = person.time point = VectorizedPoint(person.get_center()) anim1 = ApplyMethod( point.move_to, person.box.get_center(), path_arc=45 * DEGREES, run_time=shopping_time, rate_func=there_and_back_with_pause, ) anim2 = MaintainPositionRelativeTo(person, point, run_time=shopping_time) person.push_anim(anim1) person.push_anim(anim2) def add_sliders(self): pass class CentralMarketLargePopulation(CentralMarket, LargerCity): pass class CentralMarketLowerInfection(CentralMarketLargePopulation): CONFIG = { "simulation_config": { "p_infection_per_day": 0.1, } } class CentralMarketVeryFrequentLargePopulationDelayedSocialDistancing(CentralMarketLowerInfection): CONFIG = { "sd_probability": 0.7, "trigger_infection_count": 25, "simulation_config": { "person_type": DotPerson, }, "target_sd_factor": 2, } def construct(self): self.wait_until_infection_threshold(self.trigger_infection_count) self.graph.add_v_line() for person in self.simulation.people: person.social_distance_factor = self.target_sd_factor self.run_until_zero_infections() class CentralMarketLessFrequent(CentralMarketVeryFrequentLargePopulationDelayedSocialDistancing): CONFIG = { "target_shopping_frequency": 0.01, "trigger_infection_count": 100, "random_seed": 1, "simulation_config": { 'city_population': 900, }, } def construct(self): self.wait_until(lambda: self.simulation.get_status_counts()[1] > self.trigger_infection_count) for person in self.simulation.people: person.social_distance_factor = 2 # Decrease shopping rate self.graph.add_v_line() self.change_slider() self.run_until_zero_infections() def change_slider(self): self.play(self.shopping_slider.get_change_anim(self.target_shopping_frequency)) self.shopping_frequency = self.target_shopping_frequency def add_sliders(self): slider = ValueSlider( "Shopping frequency", value=self.shopping_frequency, x_min=0, x_max=0.05, tick_frequency=0.01, numbers_with_elongated_ticks=[], numbers_to_show=np.arange(0, 0.06, 0.01), decimal_number_config={ "num_decimal_places": 2, } ) slider.match_width(self.graph) slider.next_to(self.graph, DOWN, buff=0.2 * self.graph.get_height()) self.add(slider) self.shopping_slider = slider class CentralMarketDownToZeroFrequency(CentralMarketLessFrequent): CONFIG = { "target_shopping_frequency": 0, } class CentralMarketQuarantine(QuarantineInfectiousLarger, CentralMarketLowerInfection): CONFIG = { "random_seed": 1, } def construct(self): self.wait_until_infection_threshold(self.trigger_infection_count) self.graph.add_v_line() self.add_quarantine_box() self.set_quarantine_updaters() self.run_until_zero_infections() class CentralMarketQuarantine80p(CentralMarketQuarantine): CONFIG = { "simulation_config": { "person_config": { "p_symptomatic_on_infection": 0.8, } } } class CentralMarketTransitionToLowerInfection(CentralMarketLessFrequent): CONFIG = { "target_p_infection_per_day": 0.05, # From 0.1 "trigger_infection_count": 100, "random_seed": 1, "simulation_config": { 'city_population': 900, }, } def change_slider(self): self.play(self.infection_slider.get_change_anim(self.target_p_infection_per_day)) self.simulation.p_infection_per_day = self.target_p_infection_per_day def add_sliders(self): slider = ValueSlider( "Infection rate", value=self.simulation.p_infection_per_day, x_min=0, x_max=0.2, tick_frequency=0.05, numbers_with_elongated_ticks=[], numbers_to_show=np.arange(0, 0.25, 0.05), decimal_number_config={ "num_decimal_places": 2, }, marker_color=RED, ) slider.match_width(self.graph) slider.next_to(self.graph, DOWN, buff=0.2 * self.graph.get_height()) self.add(slider) self.infection_slider = slider class CentralMarketTransitionToLowerInfectionAndLowerFrequency(CentralMarketTransitionToLowerInfection): CONFIG = { "random_seed": 2, } def change_slider(self): super().change_slider() self.shopping_frequency = self.target_shopping_frequency # Filler animations class TableOfContents(Scene): def construct(self): chapters = VGroup( OldTexText("Basic setup"), OldTexText("Identify and isolate"), OldTexText("Social distancing"), OldTexText("Travel restrictions"), OldTexText("$R$"), OldTexText("Central hubs"), ) chapters.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) chapters.set_height(FRAME_HEIGHT - 1) chapters.to_edge(LEFT, buff=LARGE_BUFF) for chapter in chapters: dot = Dot() dot.next_to(chapter, LEFT, SMALL_BUFF) chapter.add(dot) chapter.save_state() self.add(chapters) for chapter in chapters: non_chapter = [c for c in chapters if c is not chapter] chapter.target = chapter.saved_state.copy() chapter.target.scale(1.5, about_edge=LEFT) chapter.target.set_fill(YELLOW, 1) for nc in non_chapter: nc.target = nc.saved_state.copy() nc.target.scale(0.8, about_edge=LEFT) nc.target.set_fill(WHITE, 0.5) self.play(*map(MoveToTarget, chapters)) self.wait() self.play(*map(Restore, chapters)) self.wait() class DescribeModel(Scene): def construct(self): # Setup words words = OldTexText( "Susceptible", "Infectious", "Recovered", ) words.scale(0.8 / words[0][0].get_height()) colors = [ COLOR_MAP["S"], COLOR_MAP["I"], interpolate_color(COLOR_MAP["R"], WHITE, 0.5), ] initials = VGroup() for i, word, color in zip(it.count(), words, colors): initials.add(word[0][0]) word.set_color(color) word.move_to(2 * i * DOWN) word.to_edge(LEFT) words.to_corner(UL) # Rearrange initials initials.save_state() initials.arrange(RIGHT, buff=SMALL_BUFF) initials.set_color(WHITE) title = VGroup(initials, OldTexText("Model")) title[1].match_height(title[0]) title.arrange(RIGHT, buff=MED_LARGE_BUFF) title.center() title.to_edge(UP) self.play(FadeInFromDown(title)) self.wait() self.play( Restore( initials, path_arc=-90 * DEGREES, ), FadeOut(title[1]) ) self.wait() # Show each category pi = PiPerson( height=3, max_speed=0, infection_radius=5, ) pi.color_map["R"] = words[2].get_color() pi.center() pi.body.change("pondering", initials[0]) word_anims = [] for word in words: word_anims.append(LaggedStartMap( FadeInFrom, word[1:], lambda m: (m, 0.2 * LEFT), )) self.play( Succession( FadeInFromDown(pi), ApplyMethod(pi.body.change, "guilty"), ), word_anims[0], run_time=2, ) words[0].pi = pi.copy() self.play( words[0].pi.set_height, 1, words[0].pi.next_to, words[0], RIGHT, ) self.play(Blink(pi.body)) pi.set_status("I") point = VectorizedPoint(pi.get_center()) self.play( point.shift, 3 * RIGHT, MaintainPositionRelativeTo(pi, point), word_anims[1], run_time=2, ) words[1].pi = pi.copy() self.play( words[1].pi.set_height, 1, words[1].pi.next_to, words[1], RIGHT, ) self.wait(3) pi.set_status("R") self.play( word_anims[2], Animation(pi, suspend_mobject_updating=False) ) words[2].pi = pi.copy() self.play( words[2].pi.set_height, 1, words[2].pi.next_to, words[2], RIGHT, ) self.wait() # Show rules i_pi = PiPerson( height=1.5, max_speed=0, infection_radius=6, status="S", ) i_pi.set_status("I") s_pis = VGroup() for vect in [RIGHT, UP, LEFT, DOWN]: s_pi = PiPerson( height=1.5, max_speed=0, infection_radius=6, status="S", ) s_pi.next_to(i_pi, vect, MED_LARGE_BUFF) s_pis.add(s_pi) VGroup(i_pi, s_pis).to_edge(RIGHT) circle = Circle(radius=3) circle.move_to(i_pi) dashed_circle = DashedVMobject(circle, num_dashes=30) dashed_circle.set_color(RED) self.play( FadeOut(pi), FadeIn(s_pis), FadeIn(i_pi), ) anims = [] for s_pi in s_pis: anims.append(ApplyMethod(s_pi.body.look_at, i_pi.body.eyes)) self.play(*anims) self.add(VGroup(i_pi, *s_pis)) self.wait() self.play(ShowCreation(dashed_circle)) self.wait() shuffled = list(s_pis) random.shuffle(shuffled) for s_pi in shuffled: s_pi.set_status("I") self.wait(3 * random.random()) self.wait(2) self.play(FadeOut(s_pis), FadeOut(dashed_circle)) # Let time pass clock = Clock() clock.next_to(i_pi.body, UP, buff=LARGE_BUFF) self.play( VFadeIn(clock), ClockPassesTime( clock, run_time=5, hours_passed=5, ), ) i_pi.set_status("R") self.wait(1) self.play(Blink(i_pi.body)) self.play(FadeOut(clock)) # Removed removed = OldTexText("Removed") removed.match_color(words[2]) removed.match_height(words[2]) removed.move_to(words[2], DL) self.play( FadeOut(words[2], UP), FadeIn(removed, DOWN), ) self.play( i_pi.body.change, 'pleading', removed, ) self.play(Blink(i_pi.body)) self.wait() class SubtlePangolin(Scene): def construct(self): pangolin = SVGMobject(file_name="pangolin") pangolin.set_height(0.5) pangolin.set_fill(GREY_BROWN, opacity=0) pangolin.set_stroke(GREY_BROWN, width=1) self.play(ShowCreationThenFadeOut(pangolin)) self.play(FadeOut(pangolin)) self.embed() class DoubleRadiusInGroup(Scene): def construct(self): radius = 1 pis = VGroup(*[ PiPerson( height=0.5, max_speed=0, wander_step_size=0, infection_radius=4 * radius, ) for x in range(49) ]) pis.arrange_in_grid() pis.set_height(FRAME_HEIGHT - 1) sicky = pis[24] sicky.set_status("I") circle = Circle(radius=radius) circle.move_to(sicky) dashed_circle = DashedVMobject(circle, num_dashes=30) dashed_circle2 = dashed_circle.copy() dashed_circle2.scale(2) self.add(pis) self.play(ShowCreation(dashed_circle, lag_ratio=0)) self.play(ShowCreation(dashed_circle2, lag_ratio=0)) anims = [] for pi in pis: if pi.status == "S": anims.append(ApplyMethod( pi.body.change, "pleading", sicky.body.eyes )) random.shuffle(anims) self.play(LaggedStart(*anims)) self.wait(10) class CutPInfectionInHalf(Scene): def construct(self): # Add people sicky = PiPerson( height=1, infection_radius=4, max_speed=0, wander_step_size=0, ) normy = sicky.deepcopy() normy.next_to(sicky, RIGHT) normy.body.look_at(sicky.body.eyes) circ = Circle(radius=4) d_circ = DashedVMobject(circ, num_dashes=30) d_circ.set_color(RED) d_circ.move_to(sicky) sicky.set_status("I") self.add(sicky, normy) self.add(d_circ) self.play(d_circ.scale, 0.5) self.wait() # Prob label eq = VGroup( OldTex("P(\\text{Infection}) = "), DecimalNumber(0.2), ) eq.arrange(RIGHT, buff=0.2) eq.to_edge(UP) arrow = Vector(0.5 * RIGHT) arrow.next_to(eq, RIGHT) new_rhs = eq[1].copy() new_rhs.next_to(arrow, RIGHT) new_rhs.set_color(YELLOW) self.play(FadeIn(eq)) self.play( TransformFromCopy(eq[1], new_rhs), GrowArrow(arrow) ) self.play(ChangeDecimalToValue(new_rhs, 0.1)) self.wait(2) # Each day clock = Clock() clock.set_height(1) clock.next_to(normy, UR, buff=0.7) def get_clock_run(clock): return ClockPassesTime( clock, hours_passed=1, run_time=1, ) self.play( VFadeIn(clock), get_clock_run(clock), ) # Random choice choices = VGroup() for x in range(9): choices.add(Checkmark()) for x in range(1): choices.add(Exmark()) choices.arrange(DOWN) choices.set_height(3) choices.next_to(clock, DOWN) rect = SurroundingRectangle(choices[0]) self.add(choices, rect) def show_random_choice(scene, rect, choices): for x in range(10): rect.move_to(random.choice(choices[:-1])) scene.wait(0.1) show_random_choice(self, rect, choices) for x in range(6): self.play(get_clock_run(clock)) show_random_choice(self, rect, choices) rect.move_to(choices[-1]) normy.set_status("I") self.add(normy) self.play( FadeOut(clock), FadeOut(choices), FadeOut(rect), ) self.wait(4) class KeyTakeaways(Scene): def construct(self): takeaways = VGroup(*[ OldTexText( text, alignment="", ) for text in [ """ Changes in how many people slip through the tests\\\\ cause disproportionately large changes to the total\\\\ number of people infected. """, """ Social distancing slows the spread, but\\\\ even small imperfections prolong it. """, """ Reducing transit between communities, late in the game,\\\\ has a very limited effect. """, """ Shared central locations dramatically speed up\\\\ the spread. """, ] ]) takeaway = OldTexText( "The growth rate is very sensitive to:\\\\", "- \\# Daily interactions\\\\", "- Probability of infection\\\\", "- Duration of illness\\\\", alignment="", ) takeaway[1].set_color(GREEN_D) takeaway[2].set_color(GREEN_C) takeaway[3].set_color(GREEN_B) takeaway.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) takeaways.add_to_back(takeaway) takeaways.scale(1.25) titles = VGroup() for i in range(len(takeaways)): title = OldTexText("Key takeaway \\#") num = Integer(i + 1) num.next_to(title, RIGHT, buff=SMALL_BUFF) title.add(num) titles.add(title) titles.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) titles.to_edge(LEFT) titles.set_color(GREY_D) h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH - 1) h_line.to_edge(UP, buff=1.5) for takeaway in takeaways: takeaway.next_to(h_line, DOWN, buff=0.75) max_width = FRAME_WIDTH - 2 if takeaway.get_width() > max_width: takeaway.set_width(max_width) takeaways[3].shift(0.25 * UP) self.add(titles) self.wait() for title, takeaway in zip(titles, takeaways): other_titles = VGroup(*titles) other_titles.remove(title) self.play(title.set_color, WHITE, run_time=0.5) title.save_state() temp_h_line = h_line.copy() self.play( title.scale, 1.5, title.to_edge, UP, title.set_x, 0, title.set_color, YELLOW, FadeOut(other_titles), ShowCreation(temp_h_line), ) self.play(FadeIn(takeaway, lag_ratio=0.1, run_time=2, rate_func=linear)) self.wait(2) temp_h_line.rotate(PI) self.play( Restore(title), FadeIn(other_titles), Uncreate(temp_h_line), FadeOut(takeaway, DOWN, lag_ratio=0.25 / len(takeaway.family_members_with_points())) ) self.wait() self.embed() class AsymptomaticCases(Scene): def construct(self): pis = VGroup(*[ PiPerson( height=1, infection_radius=2, wander_step_size=0, max_speed=0, ) for x in range(5) ]) pis.arrange(RIGHT, buff=2) pis.to_edge(DOWN, buff=2) sneaky = pis[1] sneaky.p_symptomatic_on_infection = 0 self.add(pis) for pi in pis: if pi is sneaky: pi.color_map["I"] = YELLOW pi.mode_map["I"] = "coin_flip_1" else: pi.color_map["I"] = RED pi.mode_map["I"] = "sick" pi.set_status("I") self.wait(0.1) self.wait(2) label = OldTexText("Never isolated") label.set_height(0.8) label.to_edge(UP) label.set_color(YELLOW) arrow = Arrow( label.get_bottom(), sneaky.body.get_top(), buff=0.5, max_tip_length_to_length_ratio=0.5, stroke_width=6, max_stroke_width_to_length_ratio=10, ) self.play( FadeInFromDown(label), GrowArrow(arrow), ) self.wait(13) class WeDontHaveThat(TeacherStudentsScene): def construct(self): self.student_says( "But we don't\\\\have that!", target_mode="angry", added_anims=[self.teacher.change, "guilty"] ) self.play_all_student_changes( "angry", look_at=self.teacher.eyes ) self.wait(5) class IntroduceSocialDistancing(Scene): def construct(self): pis = VGroup(*[ PiPerson( height=2, wander_step_size=0, gravity_well=None, social_distance_color_threshold=5, max_social_distance_stroke_width=10, dl_bound=[-FRAME_WIDTH / 2 + 1, -2], ur_bound=[FRAME_WIDTH / 2 - 1, 2], ) for x in range(3) ]) pis.arrange(RIGHT, buff=0.25) pis.move_to(DOWN) pi1, pi2, pi3 = pis slider = ValueSlider( "Social distance factor", 0, x_min=0, x_max=5, tick_frequency=1, numbers_to_show=range(6), marker_color=YELLOW, ) slider.center() slider.to_edge(UP) self.add(slider) def update_pi(pi): pi.social_distance_factor = 4 * slider.p2n(slider.marker.get_center()) for pi in pis: pi.add_updater(update_pi) pi.repulsion_points = [ pi2.get_center() for pi2 in pis if pi2 is not pi ] self.add(pis) self.play( FadeIn(slider), *[ ApplyMethod(pi1.body.look_at, pi2.body.eyes) for pi1, pi2 in zip(pis, [*pis[1:], pis[0]]) ] ) self.add(*pis) self.wait() self.play(slider.get_change_anim(3)) self.wait(4) for i, vect in (0, RIGHT), (2, LEFT): pis.suspend_updating() pis[1].generate_target() pis[1].target.next_to(pis[i], vect, SMALL_BUFF) pis[1].target.body.look_at(pis[i].body.eyes) self.play( MoveToTarget(pis[1]), path_arc=PI, ) pis.resume_updating() self.wait(5) self.wait(5) self.embed() class FastForwardBy2(Scene): CONFIG = { "n": 2, } def construct(self): n = self.n triangles = VGroup(*[ ArrowTip(start_angle=0) for x in range(n) ]) triangles.arrange(RIGHT, buff=0.01) label = VGroup(OldTex("\\times"), Integer(n)) label.set_height(0.4) label.arrange(RIGHT, buff=SMALL_BUFF) label.next_to(triangles, RIGHT, buff=SMALL_BUFF) for mob in triangles, label: mob.set_color(GREY_A) mob.set_stroke(BLACK, 4, background=True) self.play( LaggedStartMap( FadeInFrom, triangles, lambda m: (m, 0.4 * LEFT), ), FadeIn(label, 0.2 * LEFT), run_time=1, ) self.play( FadeOut(label), FadeOut(triangles), ) class FastForwardBy4(FastForwardBy2): CONFIG = { "n": 4, } class DontLetThisHappen(Scene): def construct(self): text = OldTexText("Don't let\\\\this happen!") text.scale(1.5) text.set_stroke(BLACK, 5, background=True) arrow = Arrow( text.get_top(), text.get_top() + 2 * UR + 0.5 * RIGHT, path_arc=-120 * DEGREES, ) self.add(text) self.play( Write(text, run_time=1), ShowCreation(arrow), ) self.wait() class ThatsNotHowIBehave(TeacherStudentsScene): def construct(self): self.student_says( "That's...not\\\\how I behave.", target_mode="sassy", look_at=self.screen, ) self.play( self.teacher.change, "guilty", self.change_students("erm", "erm", "sassy") ) self.look_at(self.screen) self.wait(20) class BetweenNothingAndQuarantineWrapper(Scene): def construct(self): self.add(FullScreenFadeRectangle( fill_color=GREY_E, fill_opacity=1, )) rects = VGroup(*[ ScreenRectangle() for x in range(3) ]) rects.arrange(RIGHT) rects.set_width(FRAME_WIDTH - 1) self.add(rects) rects.set_fill(BLACK, 1) rects.set_stroke(WHITE, 2) titles = VGroup( OldTexText("Do nothing"), OldTexText("Quarantine\\\\", "80$\\%$ of cases"), OldTexText("Quarantine\\\\", "all cases"), ) for title, rect in zip(titles, rects): title.next_to(rect, UP) q_marks = OldTex("???") q_marks.scale(2) q_marks.move_to(rects[1]) self.add(rects) self.play(LaggedStartMap( FadeInFromDown, VGroup(titles[0], titles[2], titles[1]), lag_ratio=0.3, )) self.play(Write(q_marks)) self.wait() class DarkerInterpretation(Scene): def construct(self): qz = OldTexText("Quarantine zone") qz.set_color(RED) qz.set_width(2) line = Line(qz.get_left(), qz.get_right()) new_words = OldTexText("Deceased") new_words.replace(qz, dim_to_match=1) new_words.set_color(RED) self.add(qz) self.wait() self.play(ShowCreation(line)) self.play( FadeOut(qz), FadeOut(line), FadeIn(new_words) ) self.wait() class SARS2002(TeacherStudentsScene): def construct(self): image = ImageMobject("sars_icon") image.set_height(3.5) image.move_to(self.hold_up_spot, DR) image.shift(RIGHT) name = OldTexText("2002 SARS Outbreak") name.next_to(image, LEFT, MED_LARGE_BUFF, aligned_edge=UP) n_cases = VGroup( Integer(0, edge_to_fix=UR), OldTexText("total cases") ) n_cases.arrange(RIGHT) n_cases.scale(1.25) n_cases.next_to(name, DOWN, buff=2) arrow = Arrow(name.get_bottom(), n_cases.get_top()) n_cases.shift(MED_SMALL_BUFF * RIGHT) self.play( self.teacher.change, "raise_right_hand", FadeIn(image, DOWN, run_time=2), self.change_students( "pondering", "thinking", "pondering", look_at=image, ) ) self.play( FadeIn(name, RIGHT), ) self.play( GrowArrow(arrow), UpdateFromAlphaFunc( n_cases, lambda m, a: m.set_opacity(a), ), ChangeDecimalToValue(n_cases[0], 8098), self.change_students(look_at=n_cases), ) self.wait() self.play_all_student_changes( "thinking", look_at=n_cases, ) self.play(self.teacher.change, "tease") self.wait(6) self.embed() class QuarteringLines(Scene): def construct(self): lines = VGroup( Line(UP, DOWN), Line(LEFT, RIGHT), ) lines.set_width(FRAME_WIDTH) lines.set_height(FRAME_HEIGHT, stretch=True) lines.set_stroke(WHITE, 3) self.play(ShowCreation(lines)) self.wait() class Eradicated(Scene): def construct(self): word = OldTexText("Eradicated") word.set_color(GREEN) self.add(word) class LeftArrow(Scene): def construct(self): arrow = Vector(2 * LEFT) self.play(GrowArrow(arrow)) self.wait() self.play(FadeOut(arrow)) class IndicationArrow(Scene): def construct(self): vect = Vector( 0.5 * DR, max_tip_length_to_length_ratio=0.4, max_stroke_width_to_length_ratio=10, stroke_width=5, ) vect.set_color(YELLOW) self.play(GrowArrow(vect)) self.play(FadeOut(vect)) class REq(Scene): def construct(self): mob = OldTex("R_0 = ")[0] mob[1].set_color(BLACK) mob[2].shift(mob[1].get_width() * LEFT * 0.7) self.add(mob) class IntroduceR0(Scene): def construct(self): # Infect pis = VGroup(*[ PiPerson( height=0.5, infection_radius=1.5, wander_step_size=0, max_speed=0, ) for x in range(5) ]) pis[:4].arrange(RIGHT, buff=2) pis[:4].to_edge(DOWN, buff=2) sicky = pis[4] sicky.move_to(2 * UP) sicky.set_status("I") pis[1].set_status("R") for anim in pis[1].change_anims: pis[1].pop_anim(anim) count = VGroup( OldTexText("Infection count: "), Integer(0) ) count.arrange(RIGHT, aligned_edge=DOWN) count.to_corner(UL) self.add(pis) self.add(count) self.wait(2) for pi in pis[:4]: point = VectorizedPoint(sicky.get_center()) self.play( point.move_to, pi.get_right() + 0.25 * RIGHT, MaintainPositionRelativeTo(sicky, point), run_time=0.5, ) if pi.status == "S": count[1].increment_value() count[1].set_color(WHITE) pi.set_status("I") self.play( Flash( sicky.get_center(), color=RED, line_length=0.3, flash_radius=0.7, ), count[1].set_color, RED, ) self.wait() # Attach count to sicky self.play( point.move_to, 2 * UP, MaintainPositionRelativeTo(sicky, point), ) count_copy = count[1].copy() self.play( count_copy.next_to, sicky.body, UR, count_copy.set_color, WHITE, ) self.wait() # Zeros zeros = VGroup() for pi in pis[:4]: if pi.status == "I": zero = Integer(0) zero.next_to(pi.body, UR) zeros.add(zero) # R label R_label = OldTexText("Average :=", " $R$") R_label.set_color_by_tex("R", YELLOW) R_label.next_to(count, DOWN, buff=1.5) arrow = Arrow(R_label[0].get_top(), count.get_bottom()) self.play( LaggedStartMap(FadeInFromDown, zeros), GrowArrow(arrow), FadeIn(R_label), ) brace = Brace(R_label[1], DOWN) name = OldTexText("``Effective reproductive number''") name.set_color(YELLOW) name.next_to(brace, DOWN) name.to_edge(LEFT) self.play( GrowFromCenter(brace), FadeIn(name, 0.5 * UP), ) self.wait(5) # R0 brr = OldTexText("``Basic reproductive number''") brr.set_color(TEAL) brr.move_to(name, LEFT) R0 = OldTex("R_0") R0.move_to(R_label[1], UL) R0.set_color(TEAL) for pi in pis[:4]: pi.set_status("S") self.play( FadeOut(R_label[1], UP), FadeOut(name, UP), FadeIn(R0, DOWN), FadeIn(brr, DOWN), FadeOut(zeros), FadeOut(count_copy), brace.match_width, R0, {"stretch": True}, brace.match_x, R0, ) self.wait() # Copied from above count[1].set_value(0) for pi in pis[:4]: point = VectorizedPoint(sicky.get_center()) self.play( point.move_to, pi.body.get_right() + 0.25 * RIGHT, MaintainPositionRelativeTo(sicky, point), run_time=0.5, ) count[1].increment_value() count[1].set_color(WHITE) pi.set_status("I") self.play( Flash( sicky.get_center(), color=RED, line_length=0.3, flash_radius=0.7, ), count[1].set_color, RED, ) self.play( point.move_to, 2 * UP, MaintainPositionRelativeTo(sicky, point), ) self.wait(4) class HowR0IsCalculatedHere(Scene): def construct(self): words = VGroup( OldTexText("Count ", "\\# transfers"), OldTexText("for every infectious case") ) words.arrange(DOWN) words[1].set_color(RED) words.to_edge(UP) estimate = OldTexText("Estimate") estimate.move_to(words[0][0], RIGHT) lp, rp = parens = OldTex("(", ")") parens.match_height(words) lp.next_to(words, LEFT, SMALL_BUFF) rp.next_to(words, RIGHT, SMALL_BUFF) average = OldTexText("Average") average.scale(1.5) average.next_to(parens, LEFT, SMALL_BUFF) words.save_state() words[1].move_to(words[0]) words[0].set_opacity(0) self.add(FullScreenFadeRectangle(fill_color=GREY_E, fill_opacity=1).scale(2)) self.wait() self.play(Write(words[1], run_time=1)) self.wait() self.add(words) self.play(Restore(words)) self.wait() self.play( FadeOut(words[0][0], UP), FadeIn(estimate, DOWN), ) self.wait() self.play( Write(parens), FadeIn(average, 0.5 * RIGHT), self.camera.frame.shift, LEFT, ) self.wait() self.embed() class R0Rect(Scene): def construct(self): rect = SurroundingRectangle(OldTexText("R0 = 2.20")) rect.set_stroke(YELLOW, 4) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) class DoubleInfectionRadius(Scene): CONFIG = { "random_seed": 1, } def construct(self): c1 = Circle(radius=0.25, color=RED) c2 = Circle(radius=0.5, color=RED) arrow = Vector(RIGHT) c1.next_to(arrow, LEFT) c2.next_to(arrow, RIGHT) title = OldTexText("Double the\\\\infection radius") title.next_to(VGroup(c1, c2), UP) self.add(c1, title) self.wait() self.play( GrowArrow(arrow), TransformFromCopy(c1, c2), ) self.wait() c2.label = OldTexText("4x area") c2.label.scale(0.5) c2.label.next_to(c2, DOWN) for circ, count in (c1, 4), (c2, 16): dots = VGroup() for x in range(count): dot = Dot(color=BLUE) dot.set_stroke(BLACK, 2, background=True) dot.set_height(0.05) vect = rotate_vector(RIGHT, TAU * random.random()) vect *= 0.9 * random.random() * circ.get_height() / 2 dot.move_to(circ.get_center() + vect) dots.add(dot) circ.dot = dots anims = [ShowIncreasingSubsets(dots)] if hasattr(circ, "label"): anims.append(FadeIn(circ.label, 0.5 * UP)) self.play(*anims) self.wait() class PInfectionSlider(Scene): def construct(self): slider = ValueSlider( "Probability of infection", 0.2, x_min=0, x_max=0.2, numbers_to_show=np.arange(0.05, 0.25, 0.05), decimal_number_config={ "num_decimal_places": 2, }, tick_frequency=0.05, ) self.add(slider) self.wait() self.play(slider.get_change_anim(0.1)) self.wait() self.play(slider.get_change_anim(0.05)) self.wait() class R0Categories(Scene): def construct(self): # Titles titles = VGroup( OldTex("R > 1", color=RED), OldTex("R = 1", color=YELLOW), OldTex("R < 1", color=GREEN), ) titles.scale(1.25) titles.arrange(RIGHT, buff=2.7) titles.to_edge(UP) v_lines = VGroup() for t1, t2 in zip(titles, titles[1:]): v_line = Line(UP, DOWN) v_line.set_height(FRAME_HEIGHT) v_line.set_x(midpoint(t1.get_right(), t2.get_left())[0]) v_lines.add(v_line) self.add(titles) self.add(v_lines) # Names names = VGroup( OldTexText("Epidemic", color=RED), OldTexText("Endemic", color=YELLOW), OldTexText("...Hypodemic?", color=GREEN), ) for name, title in zip(names, titles): name.next_to(title, DOWN, MED_LARGE_BUFF) # Doubling dots dot = Dot(color=RED) dot.next_to(names[0], DOWN, LARGE_BUFF) rows = VGroup(VGroup(dot)) lines = VGroup() for x in range(4): new_row = VGroup() new_lines = VGroup() for dot in rows[-1]: dot.children = [dot.copy(), dot.copy()] new_row.add(*dot.children) new_row.arrange(RIGHT) max_width = 4 if new_row.get_width() > max_width: new_row.set_width(max_width) new_row.next_to(rows[-1], DOWN, LARGE_BUFF) for dot in rows[-1]: for child in dot.children: new_lines.add(Line( dot.get_center(), child.get_center(), buff=0.2, )) rows.add(new_row) lines.add(new_lines) for row, line_row in zip(rows[:-1], lines): self.add(row) anims = [] for dot in row: for child in dot.children: anims.append(TransformFromCopy(dot, child)) for line in line_row: anims.append(ShowCreation(line)) self.play(*anims) self.play(FadeIn(names[0], UP)) self.wait() exp_tree = VGroup(rows, lines) # Singleton dots mid_rows = VGroup() mid_lines = VGroup() for row in rows: dot = Dot(color=RED) dot.match_y(row) mid_rows.add(dot) for d1, d2 in zip(mid_rows[:-1], mid_rows[1:]): d1.child = d2 mid_lines.add(Line( d1.get_center(), d2.get_center(), buff=0.2, )) for dot, line in zip(mid_rows[:-1], mid_lines): self.add(dot) self.play( TransformFromCopy(dot, dot.child), ShowCreation(line) ) self.play(FadeIn(names[1], UP)) self.wait() # Inverted tree exp_tree_copy = exp_tree.copy() exp_tree_copy.rotate(PI) exp_tree_copy.match_x(titles[2]) self.play(TransformFromCopy(exp_tree, exp_tree_copy)) self.play(FadeIn(names[2], UP)) self.wait() class RealR0Estimates(Scene): def construct(self): labels = VGroup( OldTexText("COVID-19\\\\", "$R_0 \\approx 2$"), OldTexText("1918 Spanish flu\\\\", "$R_0 \\approx 2$"), OldTexText("Usual seasonal flu\\\\", "$R_0 \\approx 1.3$"), ) images = Group( ImageMobject("COVID-19_Map"), ImageMobject("spanish_flu"), ImageMobject("Influenza"), ) for image in images: image.set_height(3) images.arrange(RIGHT, buff=0.5) images.to_edge(UP, buff=2) for label, image in zip(labels, images): label.next_to(image, DOWN) for label, image in zip(labels, images): self.play( FadeIn(image, DOWN), FadeIn(label, UP), ) self.wait() self.embed() class WhyChooseJustOne(TeacherStudentsScene): def construct(self): self.student_says( "Why choose\\\\just one?", target_mode="sassy", added_anims=[self.teacher.change, "thinking"], run_time=1, ) self.play( self.change_students( "confused", "confused", "sassy", ), ) self.wait(2) self.teacher_says( "For science!", target_mode="hooray", look_at=self.students[2].eyes, ) self.play_student_changes("hesitant", "hesitant", "hesitant") self.wait(3) self.embed() class NickyCaseMention(Scene): def construct(self): words = OldTexText( "Artwork by Nicky Case\\\\", "...who is awesome." ) words.scale(1) words.to_edge(LEFT) arrow = Arrow( words.get_top(), words.get_top() + 2 * UR + RIGHT, path_arc=-90 * DEGREES, ) self.play( Write(words[0]), ShowCreation(arrow), run_time=1, ) self.wait(2) self.play(Write(words[1]), run_time=1) self.wait() class PonderingRandy(Scene): def construct(self): randy = Randolph() self.play(FadeIn(randy)) self.play(randy.change, "pondering") for x in range(3): self.play(Blink(randy)) self.wait(2) class WideSpreadTesting(Scene): def construct(self): # Add dots dots = VGroup(*[ DotPerson( height=0.2, infection_radius=0.6, max_speed=0, wander_step_size=0, p_symptomatic_on_infection=0.8, ) for x in range(600) ]) dots.arrange_in_grid(20, 30) dots.set_height(FRAME_HEIGHT - 1) self.add(dots) sick_dots = VGroup() for x in range(36): sicky = random.choice(dots) sicky.set_status("I") sick_dots.add(sicky) self.wait(0.1) self.wait(2) healthy_dots = VGroup() for dot in dots: if dot.status != "I": healthy_dots.add(dot) # Show Flash rings = self.get_rings(ORIGIN, FRAME_WIDTH + FRAME_HEIGHT, 0.1) rings.shift(7 * LEFT) for i, ring in enumerate(rings): ring.shift(0.05 * i**1.2 * RIGHT) self.play(LaggedStartMap( FadeIn, rings, lag_ratio=3 / len(rings), run_time=2.5, rate_func=there_and_back, )) # Quarantine box = Square() box.set_height(2) box.to_corner(DL) box.shift(LEFT) anims = [] points = VGroup() points_target = VGroup() for dot in sick_dots: point = VectorizedPoint(dot.get_center()) point.generate_target() points.add(point) points_target.add(point.target) dot.push_anim(MaintainPositionRelativeTo(dot, point, run_time=3)) anims.append(MoveToTarget(point)) points_target.arrange_in_grid() points_target.set_width(box.get_width() - 1) points_target.move_to(box) self.play( ShowCreation(box), LaggedStartMap(MoveToTarget, points, lag_ratio=0.05), self.camera.frame.shift, LEFT, run_time=3, ) self.wait(9) def get_rings(self, center, max_radius, delta_r): radii = np.arange(0, max_radius, delta_r) rings = VGroup(*[ Circle( radius=r, stroke_opacity=0.75 * (1 - fdiv(r, max_radius)), stroke_color=TEAL, stroke_width=100 * delta_r, ) for r in radii ]) rings.move_to(center) return rings class VirusSpreading(Scene): def construct(self): virus = SVGMobject(file_name="virus") virus.set_fill(RED_E, 1) virus.set_stroke([RED, WHITE], width=0) height = 3 virus.set_height(height) self.play(DrawBorderThenFill(virus)) viruses = VGroup(virus) for x in range(8): height *= 0.8 anims = [] new_viruses = VGroup() for virus in viruses: children = [virus.copy(), virus.copy()] for child in children: child.set_height(height) child.set_color(interpolate_color( RED_E, GREY_D, 0.7 * random.random(), )) child.shift([ (random.random() - 0.5) * 3, (random.random() - 0.5) * 3, 0, ]) anims.append(TransformFromCopy(virus, child)) new_viruses.add(child) new_viruses.center() self.remove(viruses) self.play(*anims, run_time=0.5) viruses.set_submobjects(list(new_viruses)) self.wait() # Eliminate for virus in viruses: virus.generate_target() virus.target.scale(3) virus.target.set_color(WHITE) virus.target.set_opacity(0) self.play(LaggedStartMap( MoveToTarget, viruses, run_time=8, lag_ratio=3 / len(viruses) )) class GraciousPi(Scene): def construct(self): morty = Mortimer() morty.flip() self.play(FadeIn(morty)) self.play(morty.change, "hesitant") self.play(Blink(morty)) self.wait() self.play(morty.change, "gracious", morty.get_bottom()) self.play(Blink(morty)) self.wait(2) self.play(Blink(morty)) self.wait(2) class SIREndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "1stViewMaths", "Adam Dřínek", "Aidan Shenkman", "Alan Stein", "Alex Mijalis", "Alexis Olson", "Ali Yahya", "Andrew Busey", "Andrew Cary", "Andrew R. Whalley", "Aravind C V", "Arjun Chakroborty", "Arthur Zey", "Ashwin Siddarth", "Austin Goodman", "Avi Finkel", "Awoo", "Axel Ericsson", "Ayan Doss", "AZsorcerer", "Barry Fam", "Ben Delo", "Bernd Sing", "Boris Veselinovich", "Bradley Pirtle", "Brandon Huang", "Brian Staroselsky", "Britt Selvitelle", "Britton Finley", "Burt Humburg", "Calvin Lin", "Charles Southerland", "Charlie N", "Chenna Kautilya", "Chris Connett", "Christian Kaiser", "cinterloper", "Clark Gaebel", "Colwyn Fritze-Moor", "Cooper Jones", "Corey Ogburn", "D. Sivakumar", "Dan Herbatschek", "Daniel Herrera C", "Dave B", "Dave Kester", "dave nicponski", "David B. Hill", "David Clark", "David Gow", "Delton Ding", "Dominik Wagner", "Eddie Landesberg", "emptymachine", "Eric Younge", "Eryq Ouithaqueue", "Farzaneh Sarafraz", "Federico Lebron", "Frank R. Brown, Jr.", "Giovanni Filippi", "Goodwine Carlos", "Hal Hildebrand", "Hitoshi Yamauchi", "Ivan Sorokin", "Jacob Baxter", "Jacob Harmon", "Jacob Hartmann", "Jacob Magnuson", "Jake Vartuli - Schonberg", "Jalex Stark", "Jameel Syed", "Jason Hise", "Jayne Gabriele", "Jean-Manuel Izaret", "Jeff Linse", "Jeff Straathof", "Jimmy Yang", "John C. Vesey", "John Camp", "John Haley", "John Le", "John Rizzo", "John V Wertheim", "Jonathan Heckerman", "Jonathan Wilson", "Joseph John Cox", "Joseph Kelly", "Josh Kinnear", "Joshua Claeys", "Juan Benet", "Kai-Siang Ang", "Kanan Gill", "Karl Niu", "Kartik Cating-Subramanian", "Kaustuv DeBiswas", "Killian McGuinness", "Kros Dai", "L0j1k", "Lael S Costa", "LAI Oscar", "Lambda GPU Workstations", "Lee Redden", "Linh Tran", "lol I totally forgot I had a patreon", "Luc Ritchie", "Ludwig Schubert", "Lukas Biewald", "Magister Mugit", "Magnus Dahlström", "Manoj Rewatkar - RITEK SOLUTIONS", "Mark B Bahu", "Mark Heising", "Mark Mann", "Martin Price", "Mathias Jansson", "Matt Godbolt", "Matt Langford", "Matt Roveto", "Matt Russell", "Matteo Delabre", "Matthew Bouchard", "Matthew Cocke", "Maxim Nitsche", "Mia Parent", "Michael Hardel", "Michael W White", "Mirik Gogri", "Mustafa Mahdi", "Márton Vaitkus", "Nate Heckmann", "Nicholas Cahill", "Nikita Lesnikov", "Oleg Leonov", "Oliver Steele", "Omar Zrien", "Owen Campbell-Moore", "Patrick Lucas", "Pavel Dubov", "Petar Veličković", "Peter Ehrnstrom", "Peter Mcinerney", "Pierre Lancien", "Pradeep Gollakota", "Quantopian", "Rafael Bove Barrios", "Randy C. Will", "rehmi post", "Rex Godby", "Ripta Pasay", "Rish Kundalia", "Roman Sergeychik", "Roobie", "Ryan Atallah", "Samuel Judge", "SansWord Huang", "Scott Gray", "Scott Walter, Ph.D.", "soekul", "Solara570", "Steve Huynh", "Steve Sperandeo", "Steven Siddals", "Stevie Metke", "Still working on an upcoming skeptical humanist SciFi novels- Elux Luc", "supershabam", "Suteerth Vishnu", "Suthen Thomas", "Tal Einav", "Taras Bobrovytsky", "Tauba Auerbach", "Ted Suzman", "Thomas J Sargent", "Thomas Tarler", "Tianyu Ge", "Tihan Seale", "Tyler VanValkenburg", "Vassili Philippov", "Veritasium", "Vignesh Ganapathi Subramanian", "Vinicius Reis", "Xuanji Li", "Yana Chernobilsky", "Yavor Ivanov", "YinYangBalance.Asia", "Yu Jun", "Yurii Monastyrshyn", ], } # For assembling script # SCENES_IN_ORDER = [ WILL_BE_SCENES_IN_ORDER = [ # Quarantining QuarantineInfectious, QuarantineInfectiousLarger, QuarantineInfectiousLarger80p, QuarantineInfectiousTravel, QuarantineInfectiousTravel80p, QuarantineInfectiousTravel50p, # Social distancing SimpleSocialDistancing, DelayedSocialDistancing, # Maybe remove? DelayedSocialDistancingLargeCity, # Probably don't use SimpleTravelSocialDistancePlusZeroTravel, SimpleTravelDelayedSocialDistancing99p, SimpleTravelDelayedTravelReductionThreshold100TargetHalfPercent, SimpleTravelDelayedSocialDistancing50pThreshold100, SimpleTravelDelayedTravelReductionThreshold100, # Maybe don't use # Describing R0 LargerCity2, LargeCityHighInfectionRadius, LargeCityLowerInfectionRate, SimpleTravelDelayedSocialDistancing99p, # Need to re-render # Market CentralMarketLargePopulation, CentralMarketLowerInfection, CentralMarketVeryFrequentLargePopulationDelayedSocialDistancing, CentralMarketLessFrequent, CentralMarketTransitionToLowerInfection, CentralMarketTransitionToLowerInfectionAndLowerFrequency, CentralMarketQuarantine, CentralMarketQuarantine80p, ] to_run_later = [ CentralMarketTransitionToLowerInfectionAndLowerFrequency, SimpleTravelDelayedTravelReduction, CentralMarketLargePopulation, CentralMarketLowerInfection, CentralMarketVeryFrequentLargePopulationDelayedSocialDistancing, CentralMarketLessFrequent, CentralMarketTransitionToLowerInfection, CentralMarketTransitionToLowerInfectionAndLowerFrequency, CentralMarketQuarantine, CentralMarketQuarantine80p, SecondWave, ]
from manim_imports_ext import * import math class StreamIntro(Scene): def construct(self): # Add logo logo = Logo() spikes = VGroup(*[ spike for layer in logo.spike_layers for spike in layer ]) self.add(*logo.family_members_with_points()) # Add label label = OldTexText("The lesson will\\\\begin shortly") label.scale(2) label.next_to(logo, DOWN) self.add(label) self.camera.frame.move_to(DOWN) for spike in spikes: point = spike.get_start() spike.angle = angle_of_vector(point) anims = [] for spike in spikes: anims.append(Rotate( spike, spike.angle * 28 * 2, about_point=ORIGIN, rate_func=linear, )) self.play(*anims, run_time=60 * 5) self.wait(20) class OldStreamIntro(Scene): def construct(self): morty = Mortimer() morty.flip() morty.set_height(2) morty.to_corner(DL) self.play(PiCreatureSays( morty, "The lesson will\\\\begin soon.", bubble_config={ "height": 2, "width": 3, }, target_mode="hooray", )) bound = AnimatedBoundary(morty.bubble.content, max_stroke_width=1) self.add(bound, morty.bubble, morty.bubble.content) self.remove(morty.bubble.content) morty.bubble.set_fill(opacity=0) self.camera.frame.scale(0.6, about_edge=DL) self.play(Blink(morty)) self.wait(5) self.play(Blink(morty)) self.wait(3) return text = OldTexText("The lesson will\\\\begin soon.") text.set_height(1.5) text.to_corner(DL, buff=LARGE_BUFF) self.add(text) class QuadraticFormula(TeacherStudentsScene): def construct(self): formula = OldTex( "\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}", ) formula.next_to(self.students, UP, buff=MED_LARGE_BUFF, aligned_edge=LEFT) self.add(formula) self.play_student_changes( "angry", "tired", "sad", look_at=formula, ) self.teacher_says( "It doesn't have\\\\to be this way.", bubble_config={ "width": 4, "height": 3, } ) self.wait(5) self.play_student_changes( "pondering", "thinking", "erm", look_at=formula ) self.wait(12) class SimplerQuadratic(Scene): def construct(self): tex = OldTex("m \\pm \\sqrt{m^2 - p}") tex.set_stroke(BLACK, 12, background=True) tex.scale(1.5) self.add(tex) class CosGraphs(Scene): def construct(self): axes = Axes( x_min=-0.75 * TAU, x_max=0.75 * TAU, y_min=-1.5, y_max=1.5, x_axis_config={ "tick_frequency": PI / 4, "include_tip": False, }, y_axis_config={ "tick_frequency": 0.5, "include_tip": False, "unit_size": 1.5, } ) graph1 = axes.get_graph(np.cos) graph2 = axes.get_graph(lambda x: np.cos(x)**2) graph1.set_stroke(YELLOW, 5) graph2.set_stroke(BLUE, 5) label1 = OldTex("\\cos(x)") label2 = OldTex("\\cos^2(x)") label1.match_color(graph1) label1.set_height(0.75) label1.next_to(axes.input_to_graph_point(-PI, graph1), DOWN) label2.match_color(graph2) label2.set_height(0.75) label2.next_to(axes.input_to_graph_point(PI, graph2), UP) for mob in [graph1, graph2, label1, label2]: mc = mob.copy() mc.set_stroke(BLACK, 10, background=True) self.add(mc) self.add(axes) self.add(graph1) self.add(graph2) self.add(label1) self.add(label2) self.embed() class SineWave(Scene): def construct(self): w_axes = self.get_wave_axes() square, circle, c_axes = self.get_edge_group() self.add(w_axes) self.add(square, circle, c_axes) theta_tracker = ValueTracker(0) c_dot = Dot(color=YELLOW) c_line = Line(DOWN, UP, color=GREEN) w_dot = Dot(color=YELLOW) w_line = Line(DOWN, UP, color=GREEN) def update_c_dot(dot, axes=c_axes, tracker=theta_tracker): theta = tracker.get_value() dot.move_to(axes.c2p( np.cos(theta), np.sin(theta), )) def update_c_line(line, axes=c_axes, tracker=theta_tracker): theta = tracker.get_value() x = np.cos(theta) y = np.sin(theta) if y == 0: y = 1e-6 line.put_start_and_end_on( axes.c2p(x, 0), axes.c2p(x, y), ) def update_w_dot(dot, axes=w_axes, tracker=theta_tracker): theta = tracker.get_value() dot.move_to(axes.c2p(theta, np.sin(theta))) def update_w_line(line, axes=w_axes, tracker=theta_tracker): theta = tracker.get_value() x = theta y = np.sin(theta) if y == 0: y = 1e-6 line.put_start_and_end_on( axes.c2p(x, 0), axes.c2p(x, y), ) def get_partial_circle(circle=circle, tracker=theta_tracker): result = circle.copy() theta = tracker.get_value() result.pointwise_become_partial( circle, 0, clip(theta / TAU, 0, 1), ) result.set_stroke(RED, width=3) return result def get_partial_wave(axes=w_axes, tracker=theta_tracker): theta = tracker.get_value() graph = axes.get_graph(np.sin, x_min=0, x_max=theta, step_size=0.025) graph.set_stroke(BLUE, 3) return graph def get_h_line(axes=w_axes, tracker=theta_tracker): theta = tracker.get_value() return Line( axes.c2p(0, 0), axes.c2p(theta, 0), stroke_color=RED ) c_dot.add_updater(update_c_dot) c_line.add_updater(update_c_line) w_dot.add_updater(update_w_dot) w_line.add_updater(update_w_line) partial_circle = always_redraw(get_partial_circle) partial_wave = always_redraw(get_partial_wave) h_line = always_redraw(get_h_line) self.add(partial_circle) self.add(partial_wave) self.add(h_line) self.add(c_line, c_dot) self.add(w_line, w_dot) sin_label = OldTex( "\\sin\\left(\\theta\\right)", tex_to_color_map={"\\theta": RED} ) sin_label.next_to(w_axes.get_top(), UR) self.add(sin_label) self.play( theta_tracker.set_value, 1.25 * TAU, run_time=15, rate_func=linear, ) def get_wave_axes(self): wave_axes = Axes( x_min=0, x_max=1.25 * TAU, y_min=-1.0, y_max=1.0, x_axis_config={ "tick_frequency": TAU / 8, "unit_size": 1.0, }, y_axis_config={ "tick_frequency": 0.5, "include_tip": False, "unit_size": 1.5, } ) wave_axes.y_axis.add_numbers( -1, 1, num_decimal_places=1 ) wave_axes.to_edge(RIGHT, buff=MED_SMALL_BUFF) pairs = [ (PI / 2, "\\frac{\\pi}{2}"), (PI, "\\pi"), (3 * PI / 2, "\\frac{3\\pi}{2}"), (2 * PI, "2\\pi"), ] syms = VGroup() for val, tex in pairs: sym = OldTex(tex) sym.scale(0.5) sym.next_to(wave_axes.c2p(val, 0), DOWN, MED_SMALL_BUFF) syms.add(sym) wave_axes.add(syms) theta = OldTex("\\theta") theta.set_color(RED) theta.next_to(wave_axes.x_axis.get_end(), UP) wave_axes.add(theta) return wave_axes def get_edge_group(self): axes_max = 1.25 radius = 1.5 axes = Axes( x_min=-axes_max, x_max=axes_max, y_min=-axes_max, y_max=axes_max, axis_config={ "tick_frequency": 0.5, "include_tip": False, "numbers_with_elongated_ticks": [-1, 1], "tick_size": 0.05, "unit_size": radius, }, ) axes.to_edge(LEFT, buff=MED_LARGE_BUFF) background = SurroundingRectangle(axes, buff=MED_SMALL_BUFF) background.set_stroke(WHITE, 1) background.set_fill(GREY_E, 1) circle = Circle(radius=radius) circle.move_to(axes) circle.set_stroke(WHITE, 1) nums = VGroup() for u in 1, -1: num = Integer(u) num.set_height(0.2) num.set_stroke(BLACK, 3, background=True) num.next_to(axes.c2p(u, 0), DOWN + u * RIGHT, SMALL_BUFF) nums.add(num) axes.add(nums) return background, circle, axes class CosWave(SineWave): CONFIG = { "include_square": False, } def construct(self): w_axes = self.get_wave_axes() square, circle, c_axes = self.get_edge_group() self.add(w_axes) self.add(square, circle, c_axes) theta_tracker = ValueTracker(0) c_dot = Dot(color=YELLOW) c_line = Line(DOWN, UP, color=GREEN) w_dot = Dot(color=YELLOW) w_line = Line(DOWN, UP, color=GREEN) def update_c_dot(dot, axes=c_axes, tracker=theta_tracker): theta = tracker.get_value() dot.move_to(axes.c2p( np.cos(theta), np.sin(theta), )) def update_c_line(line, axes=c_axes, tracker=theta_tracker): theta = tracker.get_value() x = np.cos(theta) y = np.sin(theta) line.set_points_as_corners([ axes.c2p(0, y), axes.c2p(x, y), ]) def update_w_dot(dot, axes=w_axes, tracker=theta_tracker): theta = tracker.get_value() dot.move_to(axes.c2p(theta, np.cos(theta))) def update_w_line(line, axes=w_axes, tracker=theta_tracker): theta = tracker.get_value() x = theta y = np.cos(theta) if y == 0: y = 1e-6 line.set_points_as_corners([ axes.c2p(x, 0), axes.c2p(x, y), ]) def get_partial_circle(circle=circle, tracker=theta_tracker): result = circle.copy() theta = tracker.get_value() result.pointwise_become_partial( circle, 0, clip(theta / TAU, 0, 1), ) result.set_stroke(RED, width=3) return result def get_partial_wave(axes=w_axes, tracker=theta_tracker): theta = tracker.get_value() graph = axes.get_graph(np.cos, x_min=0, x_max=theta, step_size=0.025) graph.set_stroke(PINK, 3) return graph def get_h_line(axes=w_axes, tracker=theta_tracker): theta = tracker.get_value() return Line( axes.c2p(0, 0), axes.c2p(theta, 0), stroke_color=RED ) def get_square(line=c_line): square = Square() square.set_stroke(WHITE, 1) square.set_fill(MAROON_B, opacity=0.5) square.match_width(line) square.move_to(line, DOWN) return square def get_square_graph(axes=w_axes, tracker=theta_tracker): theta = tracker.get_value() graph = axes.get_graph( lambda x: np.cos(x)**2, x_min=0, x_max=theta, step_size=0.025 ) graph.set_stroke(MAROON_B, 3) return graph c_dot.add_updater(update_c_dot) c_line.add_updater(update_c_line) w_dot.add_updater(update_w_dot) w_line.add_updater(update_w_line) h_line = always_redraw(get_h_line) partial_circle = always_redraw(get_partial_circle) partial_wave = always_redraw(get_partial_wave) self.add(partial_circle) self.add(partial_wave) self.add(h_line) self.add(c_line, c_dot) self.add(w_line, w_dot) if self.include_square: self.add(always_redraw(get_square)) self.add(always_redraw(get_square_graph)) cos_label = OldTex( "\\cos\\left(\\theta\\right)", tex_to_color_map={"\\theta": RED} ) cos_label.next_to(w_axes.get_top(), UR) self.add(cos_label) self.play( theta_tracker.set_value, 1.25 * TAU, run_time=15, rate_func=linear, ) class CosSquare(CosWave): CONFIG = { "include_square": True } class ComplexNumberPreview(Scene): def construct(self): plane = ComplexPlane(axis_config={"stroke_width": 4}) plane.add_coordinates() z = complex(2, 1) dot = Dot() dot.move_to(plane.n2p(z)) label = OldTex("2+i") label.set_color(YELLOW) dot.set_color(YELLOW) label.next_to(dot, UR, SMALL_BUFF) label.set_stroke(BLACK, 5, background=True) line = Line(plane.n2p(0), plane.n2p(z)) arc = Arc(start_angle=0, angle=np.log(z).imag, radius=0.5) self.add(plane) self.add(line, arc) self.add(dot) self.add(label) self.embed() class ComplexMultiplication(Scene): def construct(self): # Add plane plane = ComplexPlane() plane.add_coordinates() z = complex(2, 1) z_dot = Dot(color=PINK) z_dot.move_to(plane.n2p(z)) z_label = OldTex("z") z_label.next_to(z_dot, UR, buff=0.5 * SMALL_BUFF) z_label.match_color(z_dot) self.add(plane) self.add(z_dot) self.add(z_label) # Show 1 one_vect = Vector(RIGHT) one_vect.set_color(YELLOW) one_vect.target = Vector(plane.n2p(z)) one_vect.target.match_style(one_vect) z_rhs = OldTex("=", "z \\cdot 1") z_rhs[1].match_color(one_vect) z_rhs.next_to(z_label, RIGHT, 1.5 * SMALL_BUFF, aligned_edge=DOWN) z_rhs.set_stroke(BLACK, 3, background=True) one_label, i_label = [l for l in plane.coordinate_labels if l.get_value() == 1] self.play(GrowArrow(one_vect)) self.wait() self.add(one_vect, z_dot) self.play( MoveToTarget(one_vect), TransformFromCopy(one_label, z_rhs), ) self.wait() # Show i i_vect = Vector(UP, color=GREEN) zi_point = plane.n2p(z * complex(0, 1)) i_vect.target = Vector(zi_point) i_vect.target.match_style(i_vect) i_vect_label = OldTex("z \\cdot i") i_vect_label.match_color(i_vect) i_vect_label.set_stroke(BLACK, 3, background=True) i_vect_label.next_to(zi_point, UL, SMALL_BUFF) self.play(GrowArrow(i_vect)) self.wait() self.play( MoveToTarget(i_vect), TransformFromCopy(i_label, i_vect_label), run_time=1, ) self.wait() self.play( TransformFromCopy(one_vect, i_vect.target, path_arc=-90 * DEGREES), ) self.wait() # Transform plane plane.generate_target() for mob in plane.target.family_members_with_points(): if isinstance(mob, Line): mob.set_stroke(GREY, opacity=0.5) new_plane = ComplexPlane(faded_line_ratio=0) self.remove(plane) self.add(plane, new_plane, *self.mobjects) new_plane.generate_target() new_plane.target.apply_complex_function(lambda w, z=z: w * z) self.play( MoveToTarget(plane), MoveToTarget(new_plane), run_time=6, rate_func=there_and_back_with_pause ) self.wait() # Show Example Point w = complex(2, -1) w_dot = Dot(plane.n2p(w), color=WHITE) one_vects = VGroup(*[Vector(RIGHT) for x in range(2)]) one_vects.arrange(RIGHT, buff=0) one_vects.move_to(plane.n2p(0), LEFT) one_vects.set_color(YELLOW) new_i_vect = Vector(DOWN) new_i_vect.move_to(plane.n2p(2), UP) new_i_vect.set_color(GREEN) vects = VGroup(*one_vects, new_i_vect) vects.set_opacity(0.8) w_group = VGroup(*vects, w_dot) w_group.target = VGroup( one_vect.copy().set_opacity(0.8), one_vect.copy().shift(plane.n2p(z)).set_opacity(0.8), i_vect.copy().rotate(PI, about_point=ORIGIN).shift(2 * plane.n2p(z)).set_opacity(0.8), Dot(plane.n2p(w * z), color=WHITE) ) self.play(FadeInFromLarge(w_dot)) self.wait() self.play(ShowCreation(vects)) self.wait() self.play( MoveToTarget(plane), MoveToTarget(new_plane), MoveToTarget(w_group), run_time=2, path_arc=np.log(z).imag, ) self.wait() class RotatePiCreature(Scene): def construct(self): randy = Randolph(mode="thinking") randy.set_height(6) plane = ComplexPlane(x_min=-12, x_max=12) plane.add_coordinates() self.camera.frame.move_to(3 * RIGHT) self.add(randy) self.wait() self.play(Rotate(randy, 30 * DEGREES, run_time=3)) self.wait() self.play(Rotate(randy, -30 * DEGREES)) self.add(plane, randy) self.play( ShowCreation(plane), randy.set_opacity, 0.75, ) self.wait() dots = VGroup() for mob in randy.family_members_with_points(): for point in mob.get_anchors(): dot = Dot(point) dot.set_height(0.05) dots.add(dot) self.play(ShowIncreasingSubsets(dots)) self.wait() label = VGroup( OldTex("(x + iy)"), Vector(DOWN), OldTex("(\\cos(30^\\circ) + i\\sin(30^\\circ))", "(x + iy)"), ) label[2][0].set_color(YELLOW) label.arrange(DOWN) label.to_corner(DR) label.shift(3 * RIGHT) for mob in label: mob.add_background_rectangle() self.play(FadeIn(label)) self.wait() randy.add(dots) self.play(Rotate(randy, 30 * DEGREES), run_time=3) self.wait() class ExpMeaning(Scene): CONFIG = { "include_circle": True } def construct(self): # Plane plane = ComplexPlane(y_min=-6, y_max=6) plane.shift(1.5 * DOWN) plane.add_coordinates() if self.include_circle: circle = Circle(radius=1) circle.set_stroke(RED, 1) circle.move_to(plane.n2p(0)) plane.add(circle) # Equation equation = OldTex( "\\text{exp}(i\\theta) = ", "1 + ", "i\\theta + ", "{(i\\theta)^2 \\over 2} + ", "{(i\\theta)^3 \\over 6} + ", "{(i\\theta)^4 \\over 24} + ", "\\cdots", tex_to_color_map={ "\\theta": YELLOW, "i": GREEN, }, ) equation.add_background_rectangle(buff=MED_SMALL_BUFF, opacity=1) equation.to_edge(UL, buff=0) # Label theta_tracker = ValueTracker(0) theta_label = VGroup( OldTex("\\theta = "), DecimalNumber(0, num_decimal_places=4) ) theta_decimal = theta_label[1] theta_decimal.add_updater( lambda m, tt=theta_tracker: m.set_value(tt.get_value()) ) theta_label.arrange(RIGHT, buff=SMALL_BUFF) theta_label.set_color(YELLOW) theta_label.add_to_back(BackgroundRectangle( theta_label, buff=MED_SMALL_BUFF, fill_opacity=1, )) theta_label.next_to(equation, DOWN, aligned_edge=LEFT, buff=0) # Vectors def get_vectors(n_vectors=20, plane=plane, tracker=theta_tracker): last_tip = plane.n2p(0) z = complex(0, tracker.get_value()) vects = VGroup() colors = color_gradient([GREEN, YELLOW, RED], 6) for i, color in zip(range(n_vectors), it.cycle(colors)): vect = Vector(complex_to_R3(z**i / math.factorial(i))) vect.set_color(color) vect.shift(last_tip) last_tip = vect.get_end() vects.add(vect) return vects vectors = always_redraw(get_vectors) dot = Dot() dot.set_height(0.03) dot.add_updater(lambda m, vs=vectors: m.move_to(vs[-1].get_end())) self.add(plane) self.add(vectors) self.add(dot) self.add(equation) self.add(theta_label) self.play( theta_tracker.set_value, 1, run_time=3, rate_func=smooth, ) self.wait() for target in PI, TAU: self.play( theta_tracker.set_value, target, run_time=10, ) self.wait() self.embed() class ExpMeaningWithoutCircle(ExpMeaning): CONFIG = { "include_circle": False, } class PositionAndVelocityExample(Scene): def construct(self): plane = NumberPlane() self.add(plane) self.embed() class EulersFormula(Scene): def construct(self): kw = {"tex_to_color_map": {"\\theta": YELLOW}} formula = OldTex( "&e^{i\\theta} = \\\\ &\\cos\\left(\\theta\\right) + i\\cdot\\sin\\left(\\theta\\right)", )[0] formula[:4].scale(2, about_edge=UL) formula[:4].shift(SMALL_BUFF * RIGHT + MED_LARGE_BUFF * UP) VGroup(formula[2], formula[8], formula[17]).set_color(YELLOW) formula.scale(1.5) formula.set_stroke(BLACK, 5, background=True) self.add(formula) class EtoILimit(Scene): def construct(self): tex = OldTex( "\\lim_{n \\to \\infty} \\left(1 + \\frac{it}{n}\\right)^n", )[0] VGroup(tex[3], tex[12], tex[14]).set_color(YELLOW) tex[9].set_color(BLUE) tex.scale(1.5) tex.set_stroke(BLACK, 5, background=True) # self.add(tex) text = OldTexText("Interest rate\\\\of ", "$\\sqrt{-1}$") text[1].set_color(BLUE) text.scale(1.5) text.set_stroke(BLACK, 5, background=True) self.add(text) class ImaginaryInterestRates(Scene): def construct(self): plane = ComplexPlane(x_min=-20, x_max=20, y_min=-20, y_max=20) plane.add_coordinate_labels() circle = Circle(radius=1) circle.set_stroke(YELLOW, 1) self.add(plane, circle) frame = self.camera.frame frame.save_state() frame.generate_target() frame.target.set_width(25) frame.target.move_to(8 * RIGHT + 2 * DOWN) dt_tracker = ValueTracker(1) def get_vectors(tracker=dt_tracker, plane=plane, T=8): dt = tracker.get_value() last_z = 1 vects = VGroup() for t in np.arange(0, T, dt): next_z = last_z + complex(0, 1) * last_z * dt vects.add(Arrow( plane.n2p(last_z), plane.n2p(next_z), buff=0, )) last_z = next_z vects.set_submobject_colors_by_gradient(YELLOW, GREEN, BLUE) return vects vects = get_vectors() line = Line() line.add_updater(lambda m, v=vects: m.put_start_and_end_on( ORIGIN, v[-1].get_start() if len(v) > 0 else RIGHT, )) self.add(line) self.play( ShowIncreasingSubsets( vects, rate_func=linear, int_func=np.ceil, ), MoveToTarget( frame, rate_func=squish_rate_func(smooth, 0.5, 1), ), run_time=8, ) self.wait() self.play(FadeOut(line)) self.remove(vects) vects = always_redraw(get_vectors) self.add(vects) self.play( Restore(frame), dt_tracker.set_value, 0.2, run_time=5, ) self.wait() self.play(dt_tracker.set_value, 0.01, run_time=3) vects.clear_updaters() self.wait() theta_tracker = ValueTracker(0) def get_arc(tracker=theta_tracker): theta = tracker.get_value() arc = Arc( radius=1, stroke_width=3, stroke_color=RED, start_angle=0, angle=theta ) return arc arc = always_redraw(get_arc) dot = Dot() dot.add_updater(lambda m, arc=arc: m.move_to(arc.get_end())) label = VGroup( DecimalNumber(0, num_decimal_places=3), OldTexText("Years") ) label.arrange(RIGHT, aligned_edge=DOWN) label.move_to(3 * LEFT + 1.5 * UP) label[0].set_color(RED) label[0].add_updater(lambda m, tt=theta_tracker: m.set_value(tt.get_value())) self.add(BackgroundRectangle(label), label, arc, dot) for n in range(1, 5): target = n * PI / 2 self.play( theta_tracker.set_value, target, run_time=3 ) self.wait(2) class Logs(Scene): def construct(self): log = OldTex( "&\\text{log}(ab) = \\\\ &\\text{log}(a) + \\text{log}(b)", tex_to_color_map={"a": BLUE, "b": YELLOW}, alignment="", ) log.scale(1.5) log.set_stroke(BLACK, 5, background=True) self.add(log) class LnX(Scene): def construct(self): sym = OldTex("\\ln(x)") sym.scale(3) sym.shift(UP) sym.set_stroke(BLACK, 5, background=True) word = OldTexText("Natural?") word.scale(1.5) word.set_color(YELLOW) word.set_stroke(BLACK, 5, background=True) word.next_to(sym, DOWN, buff=0.5) arrow = Arrow(word.get_top(), sym[0][1].get_bottom()) self.add(sym, word, arrow) class HarmonicSum(Scene): def construct(self): axes = Axes( x_min=0, x_max=13, y_min=0, y_max=1.25, y_axis_config={ "unit_size": 4, "tick_frequency": 0.25, } ) axes.to_corner(DL, buff=1) axes.x_axis.add_numbers() axes.y_axis.add_numbers( *np.arange(0.25, 1.25, 0.25), num_decimal_places=2, ) self.add(axes) graph = axes.get_graph(lambda x: 1 / x, x_min=0.1, x_max=15) graph_fill = graph.copy() graph_fill.add_line_to(axes.c2p(15, 0)) graph_fill.add_line_to(axes.c2p(1, 0)) graph_fill.add_line_to(axes.c2p(1, 1)) graph.set_stroke(WHITE, 3) graph_fill.set_fill(BLUE_E, 0.5) graph_fill.set_stroke(width=0) self.add(graph, graph_fill) bars = VGroup() bar_labels = VGroup() for x in range(1, 15): line = Line(axes.c2p(x, 0), axes.c2p(x + 1, 1 / x)) bar = Rectangle() bar.set_fill(GREEN_E, 1) bar.replace(line, stretch=True) bars.add(bar) label = OldTex(f"1 \\over {x}") label.set_height(0.7) label.next_to(bar, UP, SMALL_BUFF) bar_labels.add(label) bars.set_submobject_colors_by_gradient(GREEN_C, GREEN_E) bars.set_stroke(WHITE, 1) bars.set_fill(opacity=0.25) self.add(bars) self.add(bar_labels) self.embed() class PowerTower(Scene): def construct(self): mob = OldTex("4 = x^{x^{{x^{x^{x^{\cdot^{\cdot^{\cdot}}}}}}}}") mob[0][-1].shift(0.1 * DL) mob[0][-2].shift(0.05 * DL) mob.set_height(4) mob.set_stroke(BLACK, 5, background=True) self.add(mob) class ItoTheI(Scene): def construct(self): tex = OldTex("i^i") # tex = OldTex("\\sqrt{-1}^{\\sqrt{-1}}") tex.set_height(3) tex.set_stroke(BLACK, 8, background=True) self.add(tex) class ComplexExponentialPlay(Scene): def setup(self): self.transform_alpha = 0 def construct(self): # Plane plane = ComplexPlane( x_min=-2 * FRAME_WIDTH, x_max=2 * FRAME_WIDTH, y_min=-2 * FRAME_HEIGHT, y_max=2 * FRAME_HEIGHT, ) plane.add_coordinates() self.add(plane) # R Dot r_dot = Dot(color=YELLOW) def update_r_dot(dot, point_tracker=self.mouse_drag_point): point = point_tracker.get_location() if abs(point[0]) < 0.1: point[0] = 0 if abs(point[1]) < 0.1: point[1] = 0 dot.move_to(point) r_dot.add_updater(update_r_dot) self.mouse_drag_point.move_to(plane.n2p(1)) # Transformed sample dots def func(z, dot=r_dot, plane=plane): r = plane.p2n(dot.get_center()) result = np.exp(r * z) if abs(result) > 20: result *= 20 / abs(result) return result sample_dots = VGroup() dot_template = Dot(radius=0.05) dot_template.set_opacity(0.8) spacing = 0.05 for x in np.arange(-7, 7, spacing): dot = dot_template.copy() dot.set_color(TEAL) dot.z = x dot.move_to(plane.n2p(dot.z)) sample_dots.add(dot) for y in np.arange(-6, 6, spacing): dot = dot_template.copy() dot.set_color(MAROON) dot.z = complex(0, y) dot.move_to(plane.n2p(dot.z)) sample_dots.add(dot) special_values = [1, complex(0, 1), -1, complex(0, -1)] special_dots = VGroup(*[ list(filter(lambda d: abs(d.z - x) < 0.01, sample_dots))[0] for x in special_values ]) for dot in special_dots: dot.set_fill(opacity=1) dot.scale(1.2) dot.set_stroke(WHITE, 2) sample_dots.save_state() def update_sample(sample, f=func, plane=plane, scene=self): sample.restore() sample.apply_function_to_submobject_positions( lambda p: interpolate( p, plane.n2p(f(plane.p2n(p))), scene.transform_alpha, ) ) return sample sample_dots.add_updater(update_sample) # Sample lines x_line = Line(plane.n2p(plane.x_min), plane.n2p(plane.x_max)) y_line = Line(plane.n2p(plane.y_min), plane.n2p(plane.y_max)) y_line.rotate(90 * DEGREES) x_line.set_color(GREEN) y_line.set_color(PINK) axis_lines = VGroup(x_line, y_line) for line in axis_lines: line.insert_n_curves(50) axis_lines.save_state() def update_axis_liens(lines=axis_lines, f=func, plane=plane, scene=self): lines.restore() lines.apply_function( lambda p: interpolate( p, plane.n2p(f(plane.p2n(p))), scene.transform_alpha, ) ) lines.make_smooth() axis_lines.add_updater(update_axis_liens) # Labels labels = VGroup( OldTex("f(1)"), OldTex("f(i)"), OldTex("f(-1)"), OldTex("f(-i)"), ) for label, dot in zip(labels, special_dots): label.set_height(0.3) label.match_color(dot) label.set_stroke(BLACK, 3, background=True) label.add_background_rectangle(opacity=0.5) def update_labels(labels, dots=special_dots, scene=self): for label, dot in zip(labels, dots): label.next_to(dot, UR, 0.5 * SMALL_BUFF) label.set_opacity(self.transform_alpha) labels.add_updater(update_labels) # Titles title = OldTex( "f(x) =", "\\text{exp}(r\\cdot x)", tex_to_color_map={"r": YELLOW} ) title.to_corner(UL) title.set_stroke(BLACK, 5, background=True) brace = Brace(title[1:], UP, buff=SMALL_BUFF) e_pow = OldTex("e^{rx}", tex_to_color_map={"r": YELLOW}) e_pow.add_background_rectangle() e_pow.next_to(brace, UP, buff=SMALL_BUFF) title.add(brace, e_pow) r_eq = VGroup( OldTex("r=", tex_to_color_map={"r": YELLOW}), DecimalNumber(1) ) r_eq.arrange(RIGHT, aligned_edge=DOWN) r_eq.next_to(title, DOWN, aligned_edge=LEFT) r_eq[0].set_stroke(BLACK, 5, background=True) r_eq[1].set_color(YELLOW) r_eq[1].add_updater(lambda m: m.set_value(plane.p2n(r_dot.get_center()))) self.add(title) self.add(r_eq) # self.add(axis_lines) self.add(sample_dots) self.add(r_dot) self.add(labels) # Animations def update_transform_alpha(mob, alpha, scene=self): scene.transform_alpha = alpha frame = self.camera.frame frame.set_height(10) r_dot.clear_updaters() r_dot.move_to(plane.n2p(1)) self.play( UpdateFromAlphaFunc( VectorizedPoint(), update_transform_alpha, ) ) self.play(r_dot.move_to, plane.n2p(2)) self.wait() self.play(r_dot.move_to, plane.n2p(PI)) self.wait() self.play(r_dot.move_to, plane.n2p(np.log(2))) self.wait() self.play(r_dot.move_to, plane.n2p(complex(0, np.log(2))), path_arc=90 * DEGREES, run_time=2) self.wait() self.play(r_dot.move_to, plane.n2p(complex(0, PI / 2))) self.wait() self.play(r_dot.move_to, plane.n2p(np.log(2)), run_time=2) self.wait() self.play(frame.set_height, 14) self.play(r_dot.move_to, plane.n2p(complex(np.log(2), PI)), run_time=3) self.wait() self.play(r_dot.move_to, plane.n2p(complex(np.log(2), TAU)), run_time=3) self.wait() self.embed() def on_mouse_scroll(self, point, offset): frame = self.camera.frame if self.zoom_on_scroll: factor = 1 + np.arctan(10 * offset[1]) frame.scale(factor, about_point=ORIGIN) else: self.transform_alpha = clip(self.transform_alpha + 5 * offset[1], 0, 1) class LDMEndScreen(PatreonEndScreen): CONFIG = { "scroll_time": 20, } class ProbDiagram(Scene): def construct(self): square = Square(side_length=1) square.move_to(ORIGIN, DL) square.set_stroke(width=0) square.set_fill(BLUE_E, 1) frame = self.camera.frame frame.set_height(1.5) frame.move_to(square) tri = Polygon(ORIGIN, UP, UR) tri.set_fill(BLUE_E, 1) tri.set_stroke(width=0) tris = VGroup(tri) N = 1000 for n in range(1, N): tri = Polygon( ORIGIN, RIGHT + UP / n, RIGHT + UP / (n + 1), ) tri.set_stroke(width=0) color = BLUE_E if (n % 2 == 0) else RED_D tri.set_fill(color, 1) tris.add(tri) self.add(tris)
from manim_imports_ext import * from _2020.chess import string_to_bools def get_background(color=GREY_E): background = FullScreenRectangle() background.set_fill(color, 1) background.set_stroke(width=0) return background def get_bit_grid(n_rows, n_cols, bits=None, buff=MED_SMALL_BUFF, height=4): bit_pair = VGroup(Integer(0), Integer(1)) bit_mobs = VGroup(*[ bit_pair.copy() for x in range(n_rows * n_cols) ]) bit_mobs.arrange_in_grid(n_rows, n_cols, buff=buff) bit_mobs.set_height(height) if bits is None: bits = np.random.randint(0, 2, len(bit_mobs)) for bit_mob, bit in zip(bit_mobs, bits): bit_mob[1 - bit].set_opacity(0) bit_mobs.n_rows = n_rows bit_mobs.n_cols = n_cols return bit_mobs def get_bit_mob_value(bit_mob): return int(bit_mob[1].get_fill_opacity() > bit_mob[0].get_fill_opacity()) def bit_grid_to_bits(bit_grid): return list(map(get_bit_mob_value, bit_grid)) def toggle_bit(bit): for sm in bit: sm.set_fill(opacity=1 - sm.get_fill_opacity()) return bit def hamming_syndrome(bits): return reduce( lambda i1, i2: i1 ^ i2, [i for i, b in enumerate(bits) if b], 0, ) def string_to_bits(message): return [int(b) for b in string_to_bools(message)] def int_to_bit_string(number, n_bits=None): result = "{:b}".format(number) if n_bits is not None: result = (n_bits - len(result)) * "0" + result return result def get_image_bits(image, bit_height=0.15, buff=MED_SMALL_BUFF): bit = Integer(0) small_buff = (buff / bit.get_height()) * bit_height bit.set_height(bit_height) bits = get_bit_grid( n_rows=int(image.get_height() / (bit.get_height() + small_buff)), n_cols=int(image.get_width() / (bit.get_width() + small_buff)), buff=buff ) bits.replace(image) return bits def get_sound_wave(): sound = VGroup(*[ Line(DOWN, UP).set_height( (0.3 + 0.8 * random.random()) * abs(np.sin(x)) ) for x in np.linspace(0, 3 * PI, 100) ]) sound.arrange(RIGHT, buff=0.05) return sound def get_sender_and_receiver(height=2): sender = Randolph(height=height) receiver = Mortimer(height=height) sender.name = OldTexText("Sender") receiver.name = OldTexText("Receiver") pis = VGroup(sender, receiver) names = VGroup(sender.name, receiver.name) sender.to_corner(DL) receiver.to_corner(DR) pis.shift(UP) for name, pi in zip(names, pis): name.next_to(pi, DOWN) return pis, names def get_ones(block): result = VGroup() for bit in block: if isinstance(bit, Integer): value = bit.get_value() else: value = get_bit_mob_value(bit) if value == 1: result.add(bit) return result def get_one_rects(block, buff=SMALL_BUFF): rects = VGroup() for bit in get_ones(block): rect = SurroundingRectangle(bit, buff=buff) rect.set_stroke(YELLOW, 3) rect.set_fill(YELLOW, 0.2) rects.add(rect) return rects def get_ones_counter(label, one_rects, buff=MED_LARGE_BUFF): counter = Integer() counter.match_color(one_rects[0]) counter.match_height(label[1]) counter.next_to(label[1], RIGHT, buff=buff, aligned_edge=DOWN) f_always(counter.set_value, lambda: len(one_rects)) return counter def get_bit_grid_boxes(bit_grid, color=GREY_B, stroke_width=2): width = get_norm(bit_grid[1].get_center() - bit_grid[0].get_center()) height = get_norm(bit_grid[bit_grid.n_cols].get_center() - bit_grid[0].get_center()) return VGroup(*[ Rectangle( height=height, width=width, stroke_color=color, stroke_width=stroke_width, ).move_to(bit) for bit in bit_grid ]) def get_grid_position_labels(boxes, height=0.25): labels = VGroup() for n, box in enumerate(boxes): label = Integer(n) label.set_height(height) label.move_to(box, DR) label.shift(SMALL_BUFF * UL) labels.add(label) return labels def get_bit_n_sublist(input_list, n, bit_value=1): return [ elem for i, elem in enumerate(input_list) if bool(i & (1 << n)) ^ bool(1 - bit_value) ] def get_bit_n_subgroup(mob, n, bit_value=1): """ If we enumerate mob, this returns a subgroup of all elements whose index has a binary representation with the n'th bit equal to bit_value """ return VGroup(*get_bit_n_sublist(mob, n, bit_value)) # Special animations def image_reveal_animation(image, bit_height=0.1): box = SurroundingRectangle(image) box.set_fill(BLACK, 1) box.set_stroke(width=0) bits = get_image_bits(image, bit_height=bit_height) return AnimationGroup( Animation(image), ApplyMethod( box.stretch, 0, 1, {"about_edge": DOWN}, remover=True, rate_func=linear, ), LaggedStartMap( VFadeInThenOut, bits, run_time=1, lag_ratio=3 / len(bits) ) ) def toggle_bit_anim(bit, target_color=None, **kwargs): original = bit.copy() original[1 - get_bit_mob_value(original)].rotate(PI) toggle_bit(bit) if target_color is not None: bit.set_color(target_color) if "path_arc" not in kwargs: kwargs["path_arc"] = PI return TransformFromCopy(original, bit, **kwargs) def zap_anim(bit, bolt_height=0.75): bolt = SVGMobject("lightning_bolt") bolt[0].add_line_to(bolt[0].get_start()) bolt.set_fill(RED_B, 1) bolt.set_stroke(width=0) bolt.set_height(bolt_height) bolt.move_to(bit.get_center(), DL) outline = bolt.deepcopy() outline.set_stroke(RED_D, 2) outline.set_fill(opacity=0) return AnimationGroup( Succession( GrowFromPoint(bolt, bolt.get_corner(UR), rate_func=rush_into), FadeOut(bolt, run_time=0.5), ), Succession( ShowCreation(outline), FadeOut(outline), ), run_time=1, ) def scan_anim(point, bits, final_stroke_width=0, run_time=3, lag_factor=3, show_robot=True, robot_height=0.5): lines = VGroup(*[ Line( point, bit.get_center(), stroke_color=[GREEN, BLUE][get_bit_mob_value(bit)], stroke_width=1, ) for bit in bits ]) anims = [ LaggedStartMap( lambda m, **kw: Succession( ShowCreation(m), ApplyMethod(m.set_stroke, None, final_stroke_width), **kw ), lines, lag_ratio=lag_factor / len(bits), run_time=run_time, remover=bool(final_stroke_width) ) ] if show_robot: robot = SVGMobject("robot") robot.set_stroke(width=0) robot.set_color(GREY) robot.set_gloss(1) robot.set_height(robot_height) robot.move_to(point, UP) anims.append(FadeIn(robot)) return AnimationGroup(*anims) def focus_scan_anim_lines(scanim, point, final_stroke_width=1): lines = scanim.mobject[0] for line in lines: line.generate_target() line.target.put_start_and_end_on(line.get_start(), point) line.target.set_stroke(width=final_stroke_width) return AnimationGroup(*[ MoveToTarget(line) for line in lines ]) def get_xor(height=0.35, color=BLUE_B, stroke_width=4): xor = VGroup( Line(UP, DOWN), Line(LEFT, RIGHT), Circle(), ) xor.set_stroke(color, stroke_width) xor.set_height(height) return xor # Scenes class Thumbnail(Scene): def construct(self): phrases = VGroup( OldTexText("One Bit is Wrong"), OldTexText("(according to an extended Hamming Code)"), OldTexText("Can you tell which?"), ) for phrase in phrases: phrase.set_width(12) phrases[0].to_edge(UP) phrases[1].set_width(10) phrases[1].set_color(GREY_C) phrases[1].next_to(phrases[0], DOWN, SMALL_BUFF) phrases[2].to_edge(DOWN, buff=MED_SMALL_BUFF) phrases[0].set_color(BLUE_B) phrases[2].set_color(BLUE_C) bit_values = [ 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, ] bits = get_bit_grid(2, 8, bits=bit_values, buff=MED_LARGE_BUFF) boxes = get_bit_grid_boxes(bits) pos_labels = get_grid_position_labels(boxes) pos_labels.set_color(GREY_B) for bit, box in zip(bits, boxes): bit.set_height(0.7 * box.get_height()) group = VGroup(boxes, bits, pos_labels) group.set_width(10) group.next_to(phrases[1], DOWN) self.add(phrases) self.add(group) class AltThumbnail(Scene): def construct(self): background = self.get_background() self.add(background) bits = get_bit_grid(4, 4) bits.arrange_in_grid(h_buff=0.7, v_buff=0.5) boxes = get_bit_grid_boxes(bits) boxes.set_fill(BLACK, 1) boxes[0].set_fill(TEAL_E) parity_boxes = VGroup(*(boxes[2**n] for n in range(4))) parity_boxes.set_fill(BLUE_E, 1) group = VGroup(boxes, bits) group.to_edge(DOWN, buff=LARGE_BUFF) grouped_blocks = VGroup(*(boxes.copy() for x in range(4))) grouped_blocks.arrange_in_grid(buff_ratio=0.4) grouped_blocks.match_height(boxes) grouped_blocks.match_y(boxes) for n, gb in enumerate(grouped_blocks): gb.set_fill(BLACK) for k, box in enumerate(gb): if (k & (2**n)): box.set_fill(BLUE_E) grouped_blocks.to_edge(RIGHT, LARGE_BUFF) all_blocks = VGroup(group, grouped_blocks) all_blocks.arrange(RIGHT, buff=1.0).to_edge(DOWN, LARGE_BUFF) all_blocks.set_height(6).center() self.add(group) self.add(grouped_blocks) return # title = Text("Hamming codes", font_size=72) title.to_edge(UP) shadow = VGroup() for w in np.linspace(50, 0, 50): tc = title.copy() tc.set_stroke(BLACK, width=w, opacity=0.02) tc.set_fill(opacity=0) shadow.add(tc) self.add(shadow) self.add(title) return # words = OldTexText("Parity bits", font_size=72) words.next_to(boxes, LEFT, LARGE_BUFF) words.to_edge(UP) words.move_to(boxes.get_corner(UL), DR) words.shift(0.5 * UL) lines = VGroup() for n, v in zip(range(4), [UP, UP, LEFT, LEFT]): lines.add(Line(words.get_corner(DR), boxes[2**n].get_corner(v), buff=0.0)) lines.set_stroke(BLUE_B) self.add(words) self.add(lines) def get_background(self, n=25, k=100): choices = (Integer(0), Integer(1)) background = VGroup(*(random.choice(choices).copy() for x in range(n * k))) background.arrange_in_grid(n, k) background.set_height(FRAME_HEIGHT) background.set_opacity(0.25) background.set_fill(border_width=0) return background class DiskOfBits(Scene): def construct(self): # Setup disc bits = get_bit_grid(2**5, 2**6, height=6) inner_r = 1 outer_r = 3 annulus = Annulus( inner_radius=inner_r * 0.93, outer_radius=outer_r * 1.02, fill_color=GREY_D, ) annulus.set_gloss(0.5) for bit in bits: point = bit.get_center() norm = get_norm(point) to_inner = inner_r - norm to_outer = norm - outer_r sdf = 10 * max(to_inner, to_outer) if 0 < sdf < 0.5: bit.scale(1 - sdf) elif sdf > 0: bits.remove(bit) disc = VGroup(annulus, bits) # Setup scratch scratch_line = Line(disc.get_top(), disc.get_right()) scratch_line.set_stroke(RED, width=2, opacity=0.75) flipped_bits = VGroup() for bit in bits: point = bit.get_center() norm = abs(point[0] + point[1] - 3) alpha = 1 - clip(norm / 0.2, 0, 1) if alpha > 0.25: bit.generate_target() bit.target.set_stroke(width=1) bit.target.set_color(RED) flipped_bits.add(bit) # Add disc light = self.camera.light_source light.move_to([0, -10, 10]) random_bits = bits.copy() random_bits.sort(lambda p: -get_norm(p)) self.add(annulus) self.play( LaggedStartMap(FadeIn, random_bits, lag_ratio=10 / len(bits)), light.move_to, [-10, 10, 10], run_time=1, ) self.clear() self.add(disc) # Show scratch self.play( LaggedStartMap(MoveToTarget, flipped_bits), ShowCreationThenDestruction(scratch_line), run_time=2, ) # Flip 'em' self.play(LaggedStartMap(toggle_bit_anim, flipped_bits)) self.wait() # Show image in and image out disc.generate_target() disc.target.scale(0.5) in_image = ImageMobject("Mona_Lisa") in_image.to_edge(LEFT) in_image.shift(UP) in_words = OldTexText("What was\\\\encoded") in_words.next_to(in_image, DOWN) out_image = in_image.copy() out_image.to_edge(RIGHT) out_words = OldTexText("What is\\\\decoded") out_words.next_to(out_image, DOWN) in_arrow = Arrow( in_image.get_right(), disc.target.get_left() + 0.2 * UP, buff=MED_SMALL_BUFF, ) out_arrow = Arrow( disc.target.get_right() + 0.2 * UP, out_image.get_left(), buff=MED_SMALL_BUFF, ) for arrow in in_arrow, out_arrow: arrow.set_fill(GREY_B) self.play( MoveToTarget(disc), GrowArrow(out_arrow), ) in_bits = get_bit_grid(40, 33) in_bits.replace(in_image, stretch=True) in_bits.set_fill(GREY_B) out_bits = in_bits.copy() out_bits.move_to(out_image) out_image_blocker = SurroundingRectangle(out_image) out_image_blocker.set_fill(BLACK, 1) out_image_blocker.set_stroke(width=0) self.add(out_image, out_image_blocker, out_bits, out_words) self.play( LaggedStart( *[ Succession( GrowFromPoint( out_bit, random.choice(bits).get_center(), ), FadeOut(out_bit), ) for out_bit in out_bits ], lag_ratio=3 / len(out_bits), run_time=12, ), ApplyMethod( out_image_blocker.stretch, 0, 1, {"about_edge": DOWN}, run_time=12, rate_func=bezier([0, 0, 1, 1]), ), FadeIn(out_words, UP), ) self.wait() self.play( TransformFromCopy(out_image, in_image), ReplacementTransform( in_words.copy().replace(out_words).set_opacity(0), in_words, ), ) self.play( LaggedStart( *[ Succession( FadeIn(in_bit), Transform(in_bit, random.choice(bits)), FadeOut(in_bit), ) for in_bit in in_bits ], lag_ratio=3 / len(in_bits), run_time=12, ), GrowArrow(in_arrow), ) self.wait() # Pi Creature randy = Randolph() randy.set_height(1.5) randy.to_edge(DOWN) randy.shift(2 * LEFT) self.play(FadeIn(randy)) self.play(randy.change, "maybe") self.play(Blink(randy)) self.play(randy.change, "confused") self.wait(2) self.play(Blink(randy)) self.wait() class TripleRedundancy(Scene): def construct(self): # Show different file types image = ImageMobject("Claude_Shannon") image.set_height(6) image.to_edge(DOWN) video = ImageMobject("ZoeyInGrass") video.set_opacity(0) sound = get_sound_wave() text = OldTexText( """ Fourscore and seven years ago\\\\ our fathers brought forth, on this\\\\ continent, a new nation, conceived\\\\ in liberty, and dedicated to the\\\\ proposition that all men are created\\\\ equal. Now we are engaged$\\dots$ """, alignment="" ) code = ImageMobject("Hamming_Code_Snippet") files = Group(video, sound, text, code, image) for file in files: file.match_width(image) file.move_to(image, UP) brace = Brace(image, UP) file_word = OldTexText("Original File") file_word.set_height(0.5) file_word.next_to(brace, UP) self.play( GrowFromCenter(brace), FadeIn(file_word), image_reveal_animation(video), ) video.set_opacity(0) self.wait(2) for f1, f2 in zip(files, files[1:]): self.play(FadeOut(f1), FadeIn(f2)) self.wait() # Show bits bits = get_image_bits(image) for bit, value in zip(bits, string_to_bits(";)Hi")): bit[1 - value].set_opacity(0) bit[value].set_opacity(1) bits.generate_target() bits.target.arrange(RIGHT) bits.target.set_height(0.5) bits.target.arrange(RIGHT, buff=SMALL_BUFF) bits.target.to_edge(LEFT) bits.target.shift(UP) last_shown_bit_index = 31 dots = OldTexText("\\dots") dots.next_to(bits.target[last_shown_bit_index], RIGHT, aligned_edge=DOWN, buff=SMALL_BUFF) new_brace = Brace(VGroup(bits.target[0], dots), UP) file_rect = SurroundingRectangle(VGroup(bits.target[0], dots)) file_rect.set_stroke(BLUE, 4) self.play( FadeOut(image), FadeIn(bits, lag_ratio=1 / len(bits)) ) self.play( MoveToTarget(bits), Transform(brace, new_brace), file_word.next_to, new_brace, UP, SMALL_BUFF, run_time=3, ) self.play( FadeOut(bits[last_shown_bit_index + 1:last_shown_bit_index + 5]), FadeIn(dots), FadeOut(brace), FadeIn(file_rect), file_word.next_to, file_rect, UP, ) self.remove(*bits[last_shown_bit_index + 1:]) bits.remove(*bits[last_shown_bit_index + 1:]) self.add(bits) self.wait() # Show redundant copies bits.add(dots) copies = VGroup(bits.copy(), bits.copy()) copies.arrange(DOWN, buff=MED_SMALL_BUFF) copies.next_to(bits, DOWN, buff=MED_SMALL_BUFF) copies.set_color(BLUE) copies_rect = SurroundingRectangle(copies, buff=SMALL_BUFF) copies_rect.set_stroke(BLUE_E, 4) copies_word = OldTexText("Redundant copies") copies_word.scale(file_word[0][0].get_height() / copies_word[0][0].get_height()) copies_word.match_color(copies) copies_word.next_to(copies_rect, DOWN) self.play(LaggedStart(*[ TransformFromCopy(bits, bits_copy) for bits_copy in copies ], lag_ratio=0.5)) self.play( ShowCreation(copies_rect), FadeIn(copies_word, UP), copies.set_color, WHITE, ) self.wait() # Show a correction flipper_index = 7 flipper = bits[flipper_index] self.play( zap_anim(flipper), toggle_bit_anim(flipper), ) self.play() self.wait() bit_groups = [bits, *copies] scan_rect = SurroundingRectangle( VGroup(*[group[0] for group in bit_groups]) ) scan_rect.set_stroke(GREEN, 5) self.add(scan_rect) for i in range(flipper_index + 1): self.play( scan_rect.match_x, bits[i], run_time=0.25 ) self.wait(0.25) bangs = OldTexText("!!!")[0] bangs.scale(1.5) bangs.set_color(RED) bangs.next_to(scan_rect, UP) self.play( LaggedStartMap( FadeIn, bangs, lambda m: (m, DOWN), run_time=1, ), scan_rect.set_color, RED ) self.wait() flipper_rect = SurroundingRectangle(flipper, buff=SMALL_BUFF) flipper_rect.set_stroke(GREEN, 4) flipper_rect.set_fill(GREEN, 0.5) self.play( ReplacementTransform(bangs, flipper_rect) ) self.play( toggle_bit_anim(flipper), FadeOut(flipper_rect), scan_rect.set_color, GREEN, ) for i in range(flipper_index + 1, flipper_index + 5): self.play( scan_rect.match_x, bits[i], run_time=0.25 ) self.wait(0.25) self.play(FadeOut(scan_rect, 0.2 * RIGHT, run_time=0.5)) # Show 2/3 of transmission block rects = VGroup(file_rect, copies_rect) rects.generate_target() for rect, width in zip(rects.target, [1, 2]): rect.set_width(width, stretch=True) rect.set_height(0.75, stretch=True) rect.set_fill(rect.get_stroke_color(), opacity=1) rects.target[0].set_color(BLUE) rects.target[1].set_color(BLUE_E) rects.target.set_stroke(width=0) rects.target.arrange(RIGHT, buff=0) rects.target.set_width(12, stretch=True) rects.target.move_to(UP) braces = VGroup(*[Brace(rect, UP, buff=SMALL_BUFF) for rect in rects.target]) frac_labels = VGroup(*[ DecimalNumber(100 * frac, unit="\\%", num_decimal_places=1) for frac in [1 / 3, 2 / 3] ]) for rect, label in zip(rects.target, frac_labels): label.move_to(rect) redundancy_word = OldTexText("Redundancy") redundancy_word.match_height(copies_word) redundancy_word.match_color(copies_word) redundancy_word.next_to(braces[1], UP, SMALL_BUFF) self.play( bits.replace, rects.target[0], {"stretch": True}, bits.set_opacity, 0, copies.replace, rects.target[1], {"stretch": True}, copies.set_opacity, 0, MoveToTarget(rects), LaggedStartMap(GrowFromCenter, braces), file_word.next_to, braces[0], UP, SMALL_BUFF, ReplacementTransform(copies_word, redundancy_word), run_time=2, ) self.play(Write(frac_labels)) self.wait() # Show failure for some two-bit errors bits = get_bit_grid(3, 1, [0, 0, 0], height=3, buff=SMALL_BUFF) bits.next_to(rects, DOWN, buff=MED_LARGE_BUFF) self.play(FadeIn(bits)) self.play( LaggedStart(zap_anim(bits[0]), zap_anim(bits[2]), lag_ratio=0.5), LaggedStart(toggle_bit_anim(bits[0]), toggle_bit_anim(bits[2]), lag_ratio=0.5), run_time=1.5, ) self.wait() self.play(FadeOut(bits)) # Shrink bars rects.generate_target() p = 9 / 256 rects.target[0].set_width(1 - p, stretch=True) rects.target[1].set_width(p, stretch=True) rects.target.arrange(RIGHT, buff=0) rects.target.match_width(rects, stretch=True) rects.target.move_to(rects) braces.generate_target() for rect, brace in zip(rects.target, braces.target): brace.become(Brace(rect, UP, buff=SMALL_BUFF, min_num_quads=1)) f_always(frac_labels[0].move_to, rects[0].get_center) f_always(frac_labels[1].move_to, rects[1].get_center) rl_width = frac_labels[1].get_width() f_always(frac_labels[1].set_width, lambda: min(0.95 * rects[1].get_width(), rl_width)) self.play( MoveToTarget(rects), MoveToTarget(braces), ChangeDecimalToValue(frac_labels[0], 100 * (1 - p)), ChangeDecimalToValue(frac_labels[1], 100 * p), file_word.next_to, braces.target[0], UP, SMALL_BUFF, redundancy_word.next_to, braces.target[1], UP, SMALL_BUFF, redundancy_word.to_edge, RIGHT, run_time=3, ) self.wait() ratio_group = VGroup(rects, braces, frac_labels, file_word, redundancy_word) ratio_group.clear_updaters() # Show space division for a (256, 247) Hamming code bits = get_bit_grid( 16, 16, bits=string_to_bits("There are 10 kinds of people...."), buff=0.2, height=5 ) bits.to_edge(DOWN, buff=MED_SMALL_BUFF) bits.shift(2 * LEFT) ecc_bits = bits[-9:] ecc_rect = SurroundingRectangle(ecc_bits, buff=0.05) ecc_rect.set_stroke(BLUE_E, 2) ecc_rect.set_fill(BLUE_E, 0.5) block_label = OldTexText("256 bit block") ecc_label = OldTexText("9 redundancy bits") message_label = OldTexText("247 message bits") block_label.next_to(bits, RIGHT, LARGE_BUFF) block_label.shift(UP) ecc_label.next_to(ecc_bits, RIGHT, LARGE_BUFF) ecc_label.to_edge(DOWN, buff=MED_SMALL_BUFF) ecc_label.set_color(BLUE) message_label.move_to(VGroup(block_label, ecc_label)) message_label.align_to(block_label, LEFT) message_label.set_color(YELLOW) self.play( ratio_group.to_edge, UP, LaggedStartMap(FadeIn, bits, lag_ratio=1 / len(bits)), Write(block_label), ) self.wait() self.play( ReplacementTransform( SurroundingRectangle(bits, color=BLUE, stroke_opacity=0), ecc_rect ), Write(ecc_label) ) self.wait() self.play( LaggedStartMap( VFadeInThenOut, bits[:-9].copy().set_fill(color=YELLOW), lag_ratio=0.1 / len(bits), run_time=3, ), Write(message_label), ) self.wait() # Show correction flipper = random.choice(bits) self.play( zap_anim(flipper), toggle_bit_anim(flipper), ) self.play(flipper.set_color, RED) point = bits.get_corner(DL) + 1.5 * LEFT + UP scanim = scan_anim(point, bits, final_stroke_width=0.2) lines, robot = scanim.mobject self.play(scanim) self.play(*[ Succession( ApplyMethod(line.put_start_and_end_on, point, flipper.get_center()), ApplyMethod(line.set_stroke, None, 1) ) for line in lines ]) self.play( toggle_bit_anim(flipper), FadeOut(lines), FadeOut(robot), ) self.play(flipper.set_color, WHITE) # Show two errors two_error_label = OldTexText("Two errors") two_error_label.next_to(bits, LEFT, buff=MED_LARGE_BUFF, aligned_edge=UP) two_error_label.set_color(RED) flippers = VGroup(*random.sample(list(bits), 2)) self.play( FadeIn(two_error_label), LaggedStart(*[zap_anim(f) for f in flippers], lag_ratio=0.5), LaggedStartMap(toggle_bit_anim, flippers, lag_ratio=0.5), ) self.play(flippers.set_color, RED) self.wait() scanim = scan_anim(point, bits, final_stroke_width=0.2) bangs = OldTexText("!!!")[0] bangs.set_color(RED) bangs.next_to(point, UL, SMALL_BUFF) q_marks = OldTexText("???")[0] q_marks.replace(bangs, dim_to_match=1) q_marks.match_style(bangs) self.play(scanim) self.play( LaggedStartMap( FadeIn, bangs, lambda m: (m, 0.25 * DOWN), lag_ratio=0.2, run_time=1, ), ) self.wait() self.play(ReplacementTransform(bangs, q_marks, lag_ratio=0.2)) self.wait() class TimeLine(Scene): def construct(self): # Time line decades = list(range(1920, 2030, 10)) timeline = NumberLine( (decades[0], decades[-1], 2), numbers_with_elongated_ticks=decades, width=13 ) timeline.add_numbers( decades, group_with_commas=False, height=0.2, ) timeline.numbers.set_stroke(BLACK, 4, background=True) # Events def get_event(timeline, date, words, direction=UP): arrow = Vector(-direction) arrow.set_fill(GREY_A, 0.75) arrow.shift(timeline.n2p(date) - arrow.get_end()) arrow.shift(SMALL_BUFF * direction) label = OldTexText(words) label.scale(0.7) label.next_to(arrow.get_start(), np.sign(direction[1]) * UP, SMALL_BUFF) label.set_color(GREY_A) label.set_stroke(BLACK, 4, background=True) event = VGroup(label, arrow) return event events = VGroup( get_event(timeline, 1947, "Hamming codes", 1.5 * UP), get_event(timeline, 1948, "Shannon's paper\\\\on information theory", DOWN + 0.2 * LEFT), # get_event(timeline, 1949, "Gorlay codes", 0.7 * UP), get_event(timeline, 1960, "Reed-Solomon\\\\codes", 0.7 * UP), get_event(timeline, 1993, "Turbo codes", UP), get_event(timeline, 1995, "Shor codes\\\\(quantum)", DOWN), ) # Title title = OldTexText("Error correction codes") title.set_color(YELLOW) title.set_height(0.5) title.to_edge(UP) title_underline = Underline(title) title_underline.match_color(title) title.add(title_underline) title.fix_in_frame() # Introduce time line frame = self.camera.frame frame.save_state() frame.scale(0.5, about_point=timeline.n2p(1945)) frame.shift(0.5 * UP) self.play( Write(timeline), Write(timeline.numbers.copy(), remover=True), LaggedStart( *[Animation(Mobject()) for x in range(1)], *[ AnimationGroup( Write(event[0], run_time=1), GrowArrow(event[1]), ) for event in events ], lag_ratio=0.75, ), FadeIn(title, DOWN), Restore(frame, run_time=6), ) self.wait(2) # Isolate Hamming hamming_word = events[0][0] rs_word = events[2][0] self.play( hamming_word.scale, 2, {"about_edge": DL}, hamming_word.set_fill, WHITE, LaggedStart(*[ ApplyMethod(mob.set_opacity, 0.5) for mob in events[1:] ]), FadeOut(VGroup(title, title_underline)) ) invent_words = OldTexText("How to invent") invent_words.match_height(hamming_word[0][0]) invent_words.next_to(events[0], UP, buff=0.3) invent_words.set_color(BLUE) self.play(Write(invent_words)) self.wait() hamming_word.generate_target() hamming_word.target.scale(0.5, about_edge=UL) hamming_word.target.set_opacity(0.5) hamming_arrow = events[0][1] self.play( MoveToTarget(hamming_word), FadeOut(invent_words), hamming_arrow.put_start_and_end_on, hamming_word.target.get_bottom(), hamming_arrow.get_end(), hamming_arrow.set_opacity, 0.5, rs_word.scale, 1.5, {"about_edge": DOWN}, rs_word.set_opacity, 1, events[2][1].set_opacity, 1, ) self.wait() class WhatCDsActuallyUse(Scene): def construct(self): arrow = Vector(2 * RIGHT + UP) words = OldTexText("What CDs/DVDs\\\\actually use") words.next_to(arrow.get_end(), RIGHT) arrow.set_color(YELLOW) words.set_color(YELLOW) self.play( GrowFromPoint(words, arrow.get_start()), GrowArrow(arrow) ) self.wait() class ListOfRelevantMathTopics(Scene): def construct(self): topics = VGroup( OldTexText("$L^1$ norm"), OldTexText("Sphere packing"), OldTexText("Finite sporadic groups (see Golay codes)"), OldTexText("Finite fields"), OldTexText("Galois extensions"), OldTexText("Lagrange interpolation (see Reed-Solomon)"), OldTexText("Discrete Fourier Transform"), OldTex("\\dots") ) topics.arrange(RIGHT, buff=LARGE_BUFF) brown = interpolate_color(GREY_BROWN, WHITE, 0.25) for topic, color in zip(topics, it.cycle([BLUE_C, BLUE_D, BLUE_B, brown])): topic.set_color(color) topics.move_to(ORIGIN, LEFT) topics.to_edge(UP) self.play(topics.shift, (topics.get_width() - 5) * LEFT, run_time=12) self.wait() class Reinvention(TeacherStudentsScene): def construct(self): self.play( self.teacher.change, "raise_right_hand", self.change_students(*3 * ["pondering"]), ) self.wait(3) self.student_says( "I see where\\\\this is going", index=0, target_mode="tease", ) self.look_at(self.students[0].bubble) self.play(self.students[0].change, "thinking") self.wait(6) class EaterWrapper(Scene): def construct(self): bg_rect = FullScreenRectangle() bg_rect.set_fill(GREY_E, 1) bg_rect.set_stroke(BLACK, 0) self.add(bg_rect) title = OldTexText("Ben Eater implementing Hamming codes") title.set_width(FRAME_WIDTH - 2) title.to_edge(UP) self.add(title) screen_rect = ScreenRectangle() screen_rect.set_fill(BLACK, 1) screen_rect.set_height(6) screen_rect.next_to(title, DOWN, MED_LARGE_BUFF) self.add(screen_rect) self.add(AnimatedBoundary(screen_rect)) self.wait(16) class DataGettingZapped(Scene): CONFIG = { "random_seed": 1, } def construct(self): # Setup bit array # bits = get_bit_grid(50, 100) bits = get_bit_grid(25, 50) bits.set_color(GREY_B) bits.set_height(FRAME_HEIGHT - 0.25) image = ImageMobject("LowResMandelbrot") image.replace(bits, dim_to_match=0) threshold = 0.1 for bit in bits: try: rgb = image.point_to_rgb(bit.get_center()) if get_norm(rgb) > threshold: value = 1 else: value = 0 bit[value].set_opacity(1) bit[1 - value].set_opacity(0) except Exception: pass self.add(bits) # Zippity zap bolt = SVGMobject("lightning_bolt") bolt[0].add_line_to(bolt[0].get_start()) bolt.set_fill(RED_B, 1) bolt.set_stroke(width=0) bolt.set_height(0.5) def strike_anim(bit, bolt=bolt, **kwargs): bolt = bolt.copy() bolt.move_to(bit.get_center(), DL) bits.remove(bit) bit.generate_target() bit.target.set_color(RED) bit.target.set_stroke(RED, 1) for sm in bit.target: sm.set_opacity(1 - sm.get_fill_opacity()) outline = bolt.deepcopy() outline.set_stroke(RED_D, 2) outline.set_fill(opacity=0) return AnimationGroup( Succession( GrowFromPoint(bolt, bolt.get_corner(UR), rate_func=rush_into), FadeOut(bolt, run_time=0.5), ), Succession( ShowCreation(outline), FadeOut(outline), ), MoveToTarget(bit), ) for count in range(20): self.play(LaggedStart(*[ strike_anim(random.choice(bits)) for x in range(int(random.expovariate(0.5)) + 1) ], lag_ratio=0.25)) self.wait(random.expovariate(2)) class AmbientErrorCorrection(Scene): CONFIG = { "N": 8, "bit_grid_height": 7, } def construct(self): N = self.N size = (2**(N // 2), 2**(N // 2)) bits = get_bit_grid( *size, bits=string_to_bits("Claude Shannon was a total boss!"), height=self.bit_grid_height, ) bits.move_to(2 * RIGHT) point = 2.5 * LEFT + 2.5 * DOWN last_block = VMobject() for x in range(10): block = get_bit_grid(*size, height=self.bit_grid_height) block.move_to(2 * RIGHT) syndrome = hamming_syndrome(bit_grid_to_bits(block)) if random.random() < 0.5: syndrome = 0 toggle_bit(block[syndrome]) scanim = scan_anim( point, bits, final_stroke_width=0.2, run_time=3, lag_factor=1, show_robot=(x == 0), ) self.play( FadeIn(block, 6 * RIGHT), FadeOut(last_block, 6 * LEFT), run_time=2 ) self.play(scanim, run_time=1) if syndrome: flipper = block[syndrome] bangs = OldTex("!!!") bangs.scale(2) bangs.next_to(point, UL) bangs.set_color(RED) self.play( Write(bangs, run_time=0.5), focus_scan_anim_lines(scanim, flipper.get_center()), flipper.set_color, RED, ) self.play( toggle_bit_anim(flipper, target_color=WHITE), ApplyMethod(scanim.mobject[0].set_stroke, None, 0, 0, remover=True), FadeOut(bangs), ) else: check = Checkmark() check.scale(2) check.next_to(point, UL) self.play(FadeIn(check, 0.5 * DOWN)) self.play(FadeOut(check), FadeOut(scanim.mobject[0])) last_block = block class AmbientErrorCorrection6(AmbientErrorCorrection): CONFIG = { "N": 6 } class AmbientErrorCorrection4(AmbientErrorCorrection): CONFIG = { "N": 4, "bit_grid_height": 5, } class ImpossibleToReasonable(Scene): def construct(self): group = VGroup( OldTexText("Impossible"), Vector(RIGHT, color=GREY_B), OldTexText("Utterly reasonable"), ) group.arrange(RIGHT) group.scale(1.5) group.to_edge(UP) line = Line(LEFT, RIGHT) line.set_width(FRAME_WIDTH) line.set_stroke(GREY, 2) line.next_to(group, DOWN, SMALL_BUFF) self.add(line) self.play(FadeIn(group[0], 0.5 * UP)) self.wait() self.play( GrowArrow(group[1]), FadeIn(group[2], LEFT), ) self.wait() class HammingAtBell(Scene): def construct(self): # Setup hamming_image = ImageMobject("Richard_Hamming") hamming_name = OldTexText("Richard Hamming") hamming_name.match_width(hamming_image) hamming_name.next_to(hamming_image, DOWN, MED_SMALL_BUFF) hamming = Group(hamming_image, hamming_name) hamming.to_corner(DR) hamming.shift(2 * LEFT) bell_logo = ImageMobject("BellSystemLogo") bell_logo.set_height(3) bell_logo.next_to(hamming, LEFT, buff=2) bell_logo.to_edge(UP) bell_logo_outline = SVGMobject("BellSystemLogo") bell_logo_outline.match_height(bell_logo) bell_logo_outline.set_stroke(GREY_B, 1) bell_logo_outline.set_fill(BLACK, 0) bell_logo_outline.move_to(bell_logo) punchcard = SVGMobject("punchcard") punchcard.set_stroke(width=0) punchcard.set_fill(GREY_B, 1) punchcard.next_to(bell_logo, DOWN, LARGE_BUFF) punchcard.remove(*punchcard[23:]) years = OldTexText("1940s") years.scale(2) years.to_edge(UP) # Introductions self.play(Write(years)) self.play(FadeIn(hamming[0], RIGHT)) self.play(Write(hamming[1])) self.play( FadeOut(years), ShowCreationThenFadeOut(bell_logo_outline, lag_ratio=0.1, run_time=4), FadeIn(bell_logo, run_time=3), ) self.play( FadeIn(punchcard[0]), Write(punchcard[1:], lag_ratio=0.5, run_time=4) ) self.add(punchcard) self.wait() # Zap some bits random.seed(3) bits = random.sample(list(punchcard[1:]), 4) for bit in bits: bit.generate_target() bit.target.set_color(RED) if random.random() < 0.5: bit.target.stretch(0.2, 1, about_edge=DOWN) else: bit.target.shift(1.2 * bit.get_width() * LEFT) self.play( MoveToTarget(bit), zap_anim(bit) ) self.wait() # Frustration curse = OldTexText("\\$*@\\#*!!?!")[0] curse.set_color(RED) curse.next_to(hamming, UP) self.play(ShowIncreasingSubsets(curse)) self.wait() class MultiplePerspectives(Scene): def construct(self): # Background background = VGroup(*[ Rectangle().set_fill(color, 1) for color in [GREY_E, BLACK, GREY_E] ]) background.set_stroke(width=0) background.arrange(RIGHT, buff=0) background.set_height(FRAME_HEIGHT) background.set_width(FRAME_WIDTH, stretch=True) self.add(background) # Names names = VGroup( OldTexText("Parity checks"), OldTexText("Xor of indices"), OldTexText("Matrix"), ) names.set_height(0.6) for name, rect in zip(names, background): name.match_x(rect) names[0].shift(SMALL_BUFF * DOWN) names.to_edge(DOWN, buff=1) # Objects parity_groups = VGroup() for n in range(4): pg = VGroup(*[Square() for x in range(16)]) pg.arrange_in_grid(4, 4, buff=0) pg.set_height(0.7) pg.set_stroke(GREY_A, 2) get_bit_n_subgroup(pg, n).set_fill(BLUE, 0.8) parity_groups.add(pg) parity_groups.arrange_in_grid(2, 2) code = ImageMobject("Hamming_Code_Snippet") ints = list(random.sample(list(range(16)), 4)) ints.sort() xor_sum = reduce(op.xor, ints) bits = [int_to_bit_string(n, n_bits=4) for n in [*ints, xor_sum]] column = Group(*map(TexText, bits)) column.arrange(DOWN, SMALL_BUFF) column[-1].set_color(YELLOW) column[-1].shift(MED_SMALL_BUFF * DOWN) line = Line(LEFT, RIGHT) line.set_stroke(GREY_B) line.set_width(column.get_width() + 0.75) line.move_to(column[-2:], RIGHT) xor = get_xor() xor.next_to(line, UP, SMALL_BUFF, LEFT) column.add(line, xor) code.set_width(2 * column.get_width()) code.next_to(column, UP) column.add(code) matrix = IntegerMatrix( [ [1, 1, 0, 1], [1, 0, 1, 1], [1, 0, 0, 0], [0, 1, 1, 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ], v_buff=0.6, h_buff=0.75, ) objs = Group(parity_groups, column, matrix) for name, obj in zip(names, objs): obj.match_width(names[0]) obj.next_to(name, UP, LARGE_BUFF) matrix.scale(0.7, about_edge=DOWN) # Introduce anims = [] for name, obj in zip(names, objs): anims.append(AnimationGroup( FadeIn(name, 0.25 * UP), FadeIn(obj, lag_ratio=0, run_time=2), )) self.play(LaggedStart(*anims, lag_ratio=0.4)) self.wait() for name, obj in zip(names, objs): obj.add(name) self.add(background[0]) self.play( FadeOut(background), objs[0].set_x, 0, FadeOut(objs[1], 5 * RIGHT), FadeOut(objs[2], 2 * RIGHT), run_time=2 ) self.wait() class SetupSixteenBitExample(Scene): def construct(self): # Title title = OldTexText("Reinventing Hamming Codes") title.scale(1.5) title.to_edge(UP) title.set_color(BLUE) self.play(Write(title)) # Simple but not too simple block = get_bit_grid(4, 4, bits=string_to_bits(":)")) block.move_to(0.5 * DOWN) top_row = block[:4] top_row.save_state() top_row.center() simple_words = OldTexText("Simple\\\\", "but not too\\\\simple") simple_words.scale(1.5) simple_words.next_to(block[4:12], LEFT, buff=LARGE_BUFF) top_simp = simple_words[0] top_simp.save_state() top_simp.set_y(0) self.play( FadeIn(top_simp), ShowIncreasingSubsets(top_row), ) self.play( Restore(top_simp), Restore(top_row), FadeIn(simple_words[1:]), LaggedStartMap(FadeIn, block[4:]) ) self.add(block) self.add(simple_words) boxes = get_bit_grid_boxes(block, color=GREEN) bits_word = OldTexText("bits") bits_word.set_height(0.7) bits_word.next_to(boxes, LEFT, buff=LARGE_BUFF) counter = Integer(0, edge_to_fix=RIGHT) counter.match_height(bits_word) counter.next_to(bits_word, LEFT, buff=0.35) bit_count_group = VGroup(bits_word, counter) bit_count_group.set_color(YELLOW) self.play( FadeOut(simple_words), FadeIn(bits_word), UpdateFromAlphaFunc( counter, lambda m, a: m.set_fill(opacity=a) ), UpdateFromFunc( counter, lambda c: c.set_value(len(boxes)) ), ShowIncreasingSubsets(boxes, run_time=2) ) # Enumerate bits block.generate_target() block.target.space_out_submobjects(1.5) block.target.center() new_boxes = get_bit_grid_boxes(block.target, color=GREY_B) h_buff = get_norm(block.target[0].get_center() - block.target[4].get_center()) for box in new_boxes: box.set_height(h_buff, stretch=True) p_labels = VGroup() for n, box in enumerate(new_boxes): label = Integer(n) label.set_height(0.25) label.set_color(YELLOW) label.move_to(box, DR) label.shift(SMALL_BUFF * UL) p_labels.add(label) self.play( MoveToTarget(block), Transform(boxes, new_boxes), FadeOut(title, UP), FadeOut(VGroup(counter, bits_word), LEFT), ) self.play(FadeIn(p_labels, lag_ratio=0.07, run_time=3)) self.wait() # Data bits r_boxes = VGroup(*[boxes[2**n] for n in range(4)]).copy() r_bits = VGroup(*[block[2**n] for n in range(4)]) d_bits = VGroup(*[b for b in block if b not in r_bits]) d_label = OldTexText("12 bits\\\\of data") d_label.set_height(1.5) d_label.next_to(boxes, RIGHT, aligned_edge=UP, buff=LARGE_BUFF) d_label.set_color(BLUE) d_lines = VGroup(*[ Line( d_label.get_left(), bit.get_center(), color=(TEAL if get_bit_mob_value(bit) else YELLOW) ) for bit in d_bits ]) d_lines.set_stroke(width=1) self.play( FadeOut(r_bits), d_bits.set_color, BLUE, FadeIn(d_label), p_labels.set_color, WHITE, ) self.play(LaggedStartMap(ShowCreationThenFadeOut, d_lines)) self.wait() # Redundancy bits r_label = OldTexText("4 bits for\\\\", "redundancy") r_label.match_height(d_label) r_label.next_to(boxes, LEFT, aligned_edge=UP, buff=MED_LARGE_BUFF) r_label.set_color(GREEN) r_boxes.set_fill(GREEN, 0.5) self.add(r_boxes, p_labels) self.play( FadeIn(r_label, 0.2 * RIGHT), LaggedStartMap(FadeIn, r_boxes, run_time=2) ) self.wait() # Can't cram in copies d_bit_copies = d_bits.copy() d_bit_copies.generate_target() for n, box in enumerate(r_boxes): group = d_bit_copies.target[3 * n:3 * (n + 1)] group.arrange_in_grid(2, 2, buff=SMALL_BUFF) group.set_width(0.4 * box.get_width()) group.move_to(box) group.set_color(YELLOW) self.play(ShowCreationThenDestruction(Underline(r_label[1]))) self.play(MoveToTarget(d_bit_copies, lag_ratio=0.1, run_time=4, rate_func=linear)) self.wait() self.play( UpdateFromAlphaFunc( d_bit_copies, lambda m, a: m.shift(0.03 * np.sin(7 * TAU * a) * RIGHT).fade(a), remover=True ) ) # Set true redundancy bits highlights = boxes.copy() highlights.set_stroke(YELLOW, 6) for n in range(4): h_group = get_bit_n_subgroup(highlights, n) bit = r_bits[n] if get_bit_mob_value(bit) == 1: toggle_bit(bit) self.play( FadeIn(h_group, lag_ratio=0.2), FadeIn(bit) ) anims = [FadeOut(h_group)] if n in [2, 3]: anims.append(toggle_bit_anim(bit)) self.play(*anims) # Might expect them to come at the end movers = [d_bits, r_bits] for mover in movers: mover.save_state() mover.generate_target() for b1, b2 in zip(it.chain(d_bits.target, r_bits.target), block): b1.move_to(b2) for box, bit in zip(r_boxes, r_bits): box.bit = bit box.add_updater(lambda m: m.move_to(m.bit)) self.add(*r_boxes) self.play( *[ MoveToTarget(mover, lag_ratio=0.1, run_time=3, path_arc=20 * DEGREES) for mover in movers ], ) self.wait() self.play(*[ Restore(mover, lag_ratio=0.1, run_time=3, path_arc=20 * DEGREES) for mover in movers ]) r_boxes.clear_updaters() self.wait() power_of_2_rects = VGroup(*[ SurroundingRectangle(p_labels[2**n]) for n in range(4) ]) self.play(LaggedStartMap(ShowCreationThenFadeOut, power_of_2_rects)) # Correct to 11 bits cross = Cross(d_label[0][:2]) c_label = OldTexText("Er...11 bits") c_label.match_width(d_label) c_label.next_to(d_label, DOWN, buff=MED_LARGE_BUFF) c_label.set_color(RED) q_mark = OldTex("?") q_mark.replace(block[0]) q_mark.set_color(RED) self.play(ShowCreation(cross)) self.play(Write(c_label)) self.wait() self.play( FadeOut(block[0]), Write(q_mark), ) randy = Randolph() randy.to_corner(DL) self.play( VFadeIn(randy), randy.change, "confused", q_mark ) self.play(Blink(randy)) self.wait(2) self.play(Blink(randy)) self.wait() def old_functions(self): # Show redundancy and message redundancy_words = OldTexText("Separate some for\\\\redundancy") redundancy_words.next_to(block[-4:], LEFT, buff=LARGE_BUFF, aligned_edge=UP) redundancy_words.set_color(BLUE) vect = redundancy_words.get_center() - bit_count_group.get_center() self.play( FadeOut(bit_count_group, vect), FadeIn(redundancy_words, -vect), ApplyMethod(boxes[-4:].set_color, BLUE, lag_ratio=0.2), ApplyMethod(block[-4:].set_color, BLUE, lag_ratio=0.2), ) self.wait() message_words = OldTexText("Leave the rest\\\\for a message") message_words.next_to(block[:-4], LEFT) message_words.match_x(redundancy_words) message_words.set_color(YELLOW) message_words.save_state() message_words.replace(redundancy_words) message_words.set_opacity(0) self.play( Restore(message_words), boxes[:-4].set_color, YELLOW, ) for x in range(10): bits = list(block[:-4]) random.shuffle(bits) for bit in bits: if random.random() < 0.5: toggle_bit(bit) self.wait(0.2 / 12) self.wait() # Show correction flipper = random.choice(block) scanim = scan_anim( block.get_corner(DR) + 2 * RIGHT, block, final_stroke_width=0.5, lag_factor=1, ) self.play( zap_anim(flipper), toggle_bit_anim(flipper, target_color=RED) ) self.wait() self.play(scanim) self.play(focus_scan_anim_lines(scanim, flipper.get_center())) self.play( toggle_bit_anim(flipper, target_color=WHITE), FadeOut(scanim.mobject) ) class SenderReceiverDynamic(PiCreatureScene): def construct(self): # Sender and receiver sender_word = OldTexText("Sender") receiver_word = OldTexText("Receiver") words = VGroup(sender_word, receiver_word) words.scale(1.5) words.set_y(-2) sender_word.to_edge(LEFT) receiver_word.to_edge(RIGHT) sender, receiver = pis = self.pi_creatures for pi, word in zip(pis, words): pi.set_height(2) pi.next_to(word, UP) self.clear() for pi in pis: self.play( VFadeIn(pi), pi.change, "pondering", ORIGIN, ) for word in words: self.play(Write(word, run_time=1)) self.wait() # Message block = get_bit_grid(4, 4) block.set_height(1.5) block.next_to(pis[0].get_corner(UR), UR) self.play( sender.change, "raise_right_hand", FadeIn(block, DOWN, lag_ratio=0.01), ) self.add(sender, block) block.save_state() self.play( block.move_to, sender, block.scale, 0.5, sender.change, "gracious", sender, ) self.play(LaggedStart( ApplyMethod(block[1].set_color, GREEN), toggle_bit_anim(block[2], target_color=GREEN), ApplyMethod(block[4].set_color, GREEN), toggle_bit_anim(block[8], target_color=GREEN), )) self.wait() block.generate_target() block.target.scale(2) block.target.next_to(receiver, UL) self.play( MoveToTarget(block, run_time=3, path_arc=-30 * DEGREES), receiver.change, "tease", receiver.get_corner(UL) + UP, sender.change, "happy", receiver.get_corner(UL) + UP, ) self.play(scan_anim(receiver.get_corner(UL), block, lag_factor=1, show_robot=False)) self.wait() # Replace with machines underlines = VGroup(*[Underline(word) for word in words]) underlines.set_color(YELLOW) servers = VGroup(*[SVGMobject("server_stack") for x in range(2)]) servers.set_color(GREY) servers.set_stroke(BLACK, 2) servers.set_gloss(0.5) for server, pi in zip(servers, pis): server.move_to(pi) self.play( LaggedStartMap(ShowCreationThenFadeOut, underlines, lag_ratio=0.7), *[ ApplyMethod(pi.change, "thinking", pi) for pi in pis ], ) self.wait() self.play( *it.chain(*[ [ pi.change, "horrified", pi.shift, 2 * UP, pi.set_opacity, 0 ] for pi in pis ]), FadeIn(servers, 2 * DOWN) ) self.remove(pis) bits_copy = block.copy() bits_copy.arrange(RIGHT, buff=SMALL_BUFF) bits_copy.set_width(0.7 * servers[1].get_width()) bits_copy.move_to(servers[1], LEFT) bits_copy.shift(SMALL_BUFF * RIGHT) self.play( LaggedStart(*[ TransformFromCopy(b1, b2) for b1, b2 in zip(block, bits_copy) ], run_time=3), ) # Sent and received sent_block = block.copy() sent_block.next_to(servers[0], UR) sent_block.match_y(block) wire = VGroup( SurroundingRectangle(sent_block), Line(sent_block.get_right(), block.get_left(), buff=SMALL_BUFF / 2), SurroundingRectangle(block), ) wire.set_stroke(GREY, 2) noise_word = OldTexText("Potential noise") noise_word.scale(0.75) noise_word.set_color(RED) noise_word.next_to(wire[1], UP, SMALL_BUFF) small_words = VGroup( OldTexText("sent"), OldTexText("received"), ) for word, mob in zip(small_words, [sent_block, block]): word.next_to(mob, UP, buff=0.35) self.play( ShowCreation(wire[0]), FadeIn(small_words[0], 0.5 * DOWN), FadeIn(sent_block), ) self.play( Transform(sent_block.copy(), block, remover=True, lag_ratio=0.01), ShowCreation(wire[1]), FadeIn(noise_word, lag_ratio=0.1) ) self.play( ShowCreation(wire[2]), FadeIn(small_words[1], 0.5 * DOWN) ) # Past and future cross_lines = VGroup(*[ Line( word.get_left(), word.get_right(), stroke_width=5, stroke_color=RED, ) for word in words ]) time_words = VGroup( OldTexText("Past"), OldTexText("Future"), ) time_words.set_color(BLUE) for w1, w2 in zip(words, time_words): w2.match_height(w1) w2.next_to(w1, DOWN) self.play( LaggedStartMap(ShowCreation, cross_lines, lag_ratio=0.7), LaggedStartMap(ApplyMethod, words, lambda m: (m.set_opacity, 0.75), lag_ratio=0.7), run_time=1, ) self.play( LaggedStartMap(FadeIn, time_words, lambda m: (m, UP), lag_ratio=0.3) ) self.wait(2) def create_pi_creatures(self): return VGroup(Randolph(), Mortimer()) class ParityChecks(Scene): def construct(self): # Show detection block = get_bit_grid(4, 4, bits=string_to_bits(":)")) block.move_to(3 * LEFT) point = block.get_corner(DR) + 2 * RIGHT + UP scanim = scan_anim(point, block, final_stroke_width=0.5, run_time=2, lag_factor=2) lines, robot = scanim.mobject detection_words = OldTexText("Error detected!") detection_words.set_color(RED) detection_subwords = OldTexText("But I have no idea where!") detection_words.next_to(robot.get_top(), UR, SMALL_BUFF) detection_subwords.move_to(detection_words, DL) self.add(block) self.play(scanim) self.play( GrowFromPoint(detection_words, robot.get_top()) ) self.wait() self.play( detection_words.shift, 0.75 * UP, FadeIn(detection_subwords, 0.5 * DOWN), ) self.wait() title = OldTexText("Parity Check")[0] title.set_color(YELLOW) title.set_stroke(BLACK, 3, background=True) title.add(Underline(title).shift(0.05 * UP)) title.scale(1.5) title.to_edge(UP) self.play(Write(title)) self.wait() self.play( LaggedStart( FadeOut(scanim.mobject), FadeOut(detection_words), FadeOut(detection_subwords), ), block.move_to, DOWN, ) # Single bit vs. message pb_rect = SurroundingRectangle(block[0]) pb_rect.set_stroke(GREEN, 3) ms_rect = SurroundingRectangle(block) ms_blob = Polygon( pb_rect.get_corner(UR) + 0.05 * RIGHT, ms_rect.get_corner(UR), ms_rect.get_corner(DR), ms_rect.get_corner(DL), pb_rect.get_corner(DL) + 0.05 * DOWN, pb_rect.get_corner(DR) + 0.05 * DR, ) ms_blob.set_stroke(BLUE, 3) pb_words = OldTexText("Reserve one special bit") pb_words.next_to(pb_rect, LEFT) pb_words.match_color(pb_rect) ms_words = OldTexText("The rest carry\\\\a message", alignment="") ms_words.next_to(ms_blob, RIGHT, aligned_edge=UP) ms_words.align_to(pb_words, UP) ms_words.match_color(ms_blob) self.play( FadeIn(pb_words), ShowCreation(pb_rect), ) self.wait() self.play( FadeIn(ms_words), ShowCreation(ms_blob), ) # Wave of flips k = 3 for n in range(1, len(block) + k): if n < len(block): toggle_bit(block[n]) if 1 <= n - k < len(block): toggle_bit(block[n - k]) self.wait(0.05) # Count 1's number_ones_label = OldTexText("\\# ", "of 1's: ") number_ones_label.set_height(0.7) number_ones_label.to_edge(UP) number_ones_label.shift(LEFT) one_rects = get_one_rects(block) one_counter = get_ones_counter(number_ones_label, one_rects) self.play( FadeIn(number_ones_label, DOWN), FadeOut(title, UP), ) self.add(one_counter) self.play(ShowIncreasingSubsets(one_rects, run_time=1, rate_func=bezier([0, 0, 1, 1]))) self.wait() # Show need to flip want_even_label = OldTexText("Want this\\\\to be even") want_even_label.next_to(one_counter, RIGHT, buff=1.5) want_even_arrow = Arrow( want_even_label.get_left(), one_counter.get_right() ) want_even_label.shift_onto_screen() self.play( GrowArrow(want_even_arrow), FadeIn(want_even_label), ) self.wait() self.play( LaggedStartMap( Indicate, one_rects, scale_factor=1.1, color=RED, lag_ratio=0.2, run_time=2, ) ) self.wait() pb = block[0] pb_center = pb.get_center() self.play(pb.next_to, pb_words, DOWN) self.play(toggle_bit_anim(pb)) self.play(pb.move_to, pb_center) one_rects.become(get_one_rects(block)) self.play(DrawBorderThenFill(one_rects[0])) # Show case with no need to flip self.play( FadeOut(block), FadeOut(one_rects), FadeOut(one_counter), ) new_block = get_bit_grid(4, 4, bits=string_to_bits("<3")) new_block.replace(block) block = new_block self.play(ShowIncreasingSubsets(block)) one_rects = get_one_rects(block) one_counter = get_ones_counter(number_ones_label, one_rects) self.add(one_counter) self.play(ShowIncreasingSubsets(one_rects)) check = Checkmark() check.scale(2) check.next_to(pb, UP) self.play(Write(check, run_time=0.5)) self.play(FadeOut(check)) self.wait() # Sender and receiver self.play(LaggedStart(*map(FadeOut, [ number_ones_label, one_counter, want_even_arrow, want_even_label, pb_words, pb_rect, ms_words, ms_blob, one_rects ]))) pis, names = get_sender_and_receiver() sender, receiver = pis block.generate_target() block.target.scale(0.5) block.target.next_to(sender, UR) r_block = block.target.copy() r_block.next_to(receiver, UL) n_block = r_block.copy() n_block.move_to(VGroup(block.target, r_block)) arrows = VGroup( Arrow(block.target.get_right(), n_block.get_left()), Arrow(n_block.get_right(), r_block.get_left()), ) noise_word = OldTexText("Noise") noise_arrow = Vector(0.7 * DOWN) noise_arrow.next_to(n_block, UP) noise_word.next_to(noise_arrow, UP) noise_label = VGroup(noise_word, noise_arrow) noise_label.set_color(RED) flipper_index = 7 self.play( ApplyMethod(sender.change, "raise_right_hand", block.target), VFadeIn(sender), FadeIn(names), FadeIn(receiver), MoveToTarget(block), ) self.play( TransformFromCopy(block, n_block), GrowArrow(arrows[0]), FadeIn(noise_label), ) self.play( toggle_bit_anim(n_block[flipper_index], target_color=RED), zap_anim(n_block[flipper_index]), ) toggle_bit(r_block[flipper_index]) self.play( TransformFromCopy(n_block, r_block), GrowArrow(arrows[1]), receiver.change, "pondering", r_block, ) # Recount the 1's blocks = (block, r_block) one_rects_pair = VGroup(*[get_one_rects(b, buff=0.05) for b in blocks]) label_pair = VGroup(*[ OldTexText("\\#", " 1's:").next_to(b, UP, buff=MED_LARGE_BUFF) for b in blocks ]) one_counter_pair = VGroup(*[ get_ones_counter(label, rect, buff=MED_SMALL_BUFF) for label, rect in zip(label_pair, one_rects_pair) ]) self.add(label_pair, one_counter_pair) self.play(*[ ShowIncreasingSubsets(group) for group in one_rects_pair ]) self.wait() bangs = OldTex("!!!") bangs.set_color(RED) bangs.next_to(receiver, UP) self.play( FadeIn(bangs, DOWN), receiver.change, "horrified", r_block, ) self.play(Blink(receiver)) self.wait() # Define parity and parity bit parity_rects = VGroup( SurroundingRectangle(VGroup(block, one_counter_pair[0]), buff=MED_SMALL_BUFF), SurroundingRectangle(VGroup(r_block, one_counter_pair[1]), buff=MED_SMALL_BUFF), ) parity_rects[0].set_stroke(BLUE, 2) parity_rects[1].set_stroke(RED, 2) parity_labels = VGroup(*[ OldTexText( "Parity: ", word, tex_to_color_map={word: color} ).next_to(rect, UP) for word, color, rect in zip( ["Even", "Odd"], [BLUE, RED], parity_rects, ) ]) for label, rect in zip(parity_labels, parity_rects): self.play( FadeIn(label, DOWN), ShowCreation(rect), ) self.play(LaggedStart(*[ ShowCreationThenFadeOut(Underline(label[0], color=YELLOW)) for label in parity_labels ], lag_ratio=0.3)) self.wait() self.play(Blink(sender)) self.play(Blink(receiver)) for bit, label, rect in zip([0, 1], parity_labels, parity_rects): bit_mob = get_bit_grid(1, 1, bits=[bit])[0] bit_mob.match_height(label[1]) bit_mob.match_color(label[1]) bit_mob.move_to(label[1], LEFT) x_shift = (rect.get_center() - VGroup(label[0], bit_mob).get_center()) * RIGHT bit_mob.shift(x_shift) self.play( label[1].replace, bit_mob, {"stretch": True}, label[1].set_opacity, 0, FadeIn(bit_mob), label[0].shift, x_shift, ) label.replace_submobject(1, bit_mob) pb_rect = SurroundingRectangle(block[0], buff=0.05) pb_rect.set_stroke(GREEN, 3) pb_label = OldTexText("Parity bit") pb_label.move_to(pb_rect) pb_label.to_edge(LEFT, buff=MED_SMALL_BUFF) pb_label.shift(UP) pb_label.match_color(pb_rect) pb_arrow = Arrow( pb_label.get_bottom() + SMALL_BUFF * DOWN, pb_rect.get_left(), buff=SMALL_BUFF, fill_color=GREEN ) self.play( Write(pb_label, run_time=1), GrowArrow(pb_arrow), ShowCreation(pb_rect), ) for color in [RED, BLUE]: self.play( toggle_bit_anim(block[0]), toggle_bit_anim(parity_labels[0][1], target_color=color), parity_rects[0].set_color, color, ) self.wait() parity_descriptors = VGroup( parity_rects, parity_labels, pb_rect, pb_label, pb_arrow, ) self.play(FadeOut(parity_descriptors, lag_ratio=0.1)) # More than 1 error new_filpper_indices = [8, 13] n_flippers = VGroup(*[n_block[fi] for fi in new_filpper_indices]) r_flippers = VGroup(*[r_block[fi] for fi in new_filpper_indices]) for bit in r_flippers: toggle_bit(bit) new_one_rects_pair = VGroup(*[get_one_rects(b, buff=0.05) for b in blocks]) new_one_counter_pair = VGroup(*[ get_ones_counter(label, rect, buff=MED_SMALL_BUFF) for label, rect in zip(label_pair, new_one_rects_pair) ]) for bit in r_flippers: toggle_bit(bit) self.play( LaggedStartMap( toggle_bit_anim, n_flippers, target_color=RED, ), LaggedStartMap(toggle_bit_anim, r_flippers), LaggedStart(*map(zap_anim, n_flippers)), receiver.change, "maybe", FadeOut(one_rects_pair[1]), FadeOut(one_counter_pair[1]), ) self.remove(one_rects_pair, one_counter_pair) one_rects_pair = new_one_rects_pair one_counter_pair = new_one_counter_pair self.add(one_rects_pair, one_counter_pair) self.play( ShowIncreasingSubsets(one_rects_pair[1]) ) for x in range(2): self.play(Blink(receiver)) self.play(Blink(sender)) self.wait() # Even number of errors self.play( FadeOut(one_rects_pair[1]), FadeOut(one_counter_pair[1]), FadeOut(bangs), receiver.change, "pondering", r_block, ) temp_rect = SurroundingRectangle( n_flippers[1], buff=0.05, color=GREEN, ) temp_rect.flip() self.play( ShowCreationThenFadeOut(temp_rect), toggle_bit_anim(n_flippers[1], target_color=WHITE), toggle_bit_anim(r_flippers[1]), ) self.wait() self.play(Blink(receiver)) one_counter_pair.set_opacity(1) self.add(one_counter_pair) one_rects_pair[1].set_submobjects( get_one_rects(r_block, buff=0.05).submobjects ) self.play( ShowIncreasingSubsets(one_rects_pair[1]) ) self.play(receiver.change, "hooray", r_block) self.wait() self.play(receiver.change, "erm") self.wait() class ChangeAnywhereToOneBit(Scene): CONFIG = { "random_seed": 3, } def construct(self): title = VGroup( OldTexText("Change anywhere"), Vector(RIGHT), OldTexText("One bit of information"), ) title.arrange(RIGHT) title.set_width(FRAME_WIDTH - 1) title.to_edge(UP) self.add(title) grid = get_bit_grid(4, 4) grid.set_height(4) grid.match_x(title[0]) grid.set_y(-1) self.add(grid) one_rects = get_one_rects(grid) self.add(one_rects) parity_words = VGroup( OldTexText("Even \\# of 1s", color=BLUE_B), OldTexText("Odd \\# of 1s", color=TEAL_D), ) parity_words.scale(1.5) parity_words.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=RIGHT) parity_words.match_x(title[2]) parity_words.match_y(grid) self.add(parity_words) def get_parity_rect(n, words=parity_words): return SurroundingRectangle(words[n % 2]) p_rect = get_parity_rect(len(one_rects)) self.add(p_rect) # Random changes for x in range(10): bit = random.choice(grid) self.play(toggle_bit_anim(bit)) one_rects.set_submobjects(get_one_rects(grid)) p_rect.become(get_parity_rect(len(one_rects))) self.wait() class OddNumberCountTo101(Scene): def construct(self): group = VGroup( *[Integer(2 * n + 1) for n in range(1, 50)], ) group.set_color(RED) group.scale(2) for mob in group[:2]: self.add(mob) self.wait() self.remove(mob) self.play(ShowSubmobjectsOneByOne(group[2:]), run_time=6, rate_func=bezier([0, 0, 1, 1])) self.wait() class ComplainAboutParityCheckWeakness(TeacherStudentsScene): def construct(self): self.embed() self.screen.set_fill(BLACK, 1) self.add(self.screen) self.play( PiCreatureSays( self.students[1], "Wait, it fails\\\\for two flips?", target_mode="sassy", bubble_config={ "height": 3, "width": 3, } ), self.teacher.change, "guilty", ) self.wait() self.play( PiCreatureSays( self.students[2], "Weak!", target_mode="angry", bubble_config={"direction": LEFT} ), self.students[0].change, "hesitant" ) self.wait() self.play(self.teacher.change, "tease") self.wait() self.play_student_changes( "thinking", "pondering", "pondering", look_at=self.screen, added_anims=[ FadeOut(self.students[1].bubble), FadeOut(self.students[1].bubble.content), FadeOut(self.students[2].bubble), FadeOut(self.students[2].bubble.content), ] ) self.wait() class ArrayOfValidMessages(Scene): def construct(self): # Messages title = OldTexText("All possible messages") title.to_edge(UP) nr = 22 nc = 46 dots = VGroup(*[Dot() for x in range(nr * nc)]) dots.arrange_in_grid(nr, nc) dots.set_color(GREY_C) dots.set_height(6) dots.to_edge(DOWN) shuffled_dots = dots.copy() shuffled_dots.shuffle() self.add(title) self.play(Write(shuffled_dots, remover=True, run_time=6, lag_ratio=5 / len(dots))) self.add(dots) self.wait() # Valid messages subset = OldTex("\\subset") subset.set_height(0.4) subset.to_edge(UP) valid_label = OldTexText("Valid messages") valid_label.set_color(YELLOW) valid_label.next_to(subset, LEFT) valid_dots = VGroup() for row in range(0, nr, 3): for col in range(0, nc, 3): valid_dot = dots[row * nc + col] valid_dot.generate_target() valid_dot.target.scale(2) valid_dot.target.set_color(YELLOW) valid_dots.add(valid_dot) self.play( LaggedStartMap(MoveToTarget, valid_dots, run_time=3), Write(subset), FadeIn(valid_label, LEFT), title.next_to, subset, RIGHT, ) self.wait() # Words analogy example_words = VGroup( OldTexText("Hello world", color=YELLOW), OldTexText("Helho world", color=GREY_B), ) example_words.scale(1.25) index = 12 * nc + 21 example_dots = VGroup(dots[index], dots[index + 1]).copy() example_groups = VGroup() for word, dot in zip(example_words, example_dots): arrow = Vector(0.7 * DOWN) arrow.next_to(dot, UP, SMALL_BUFF) word.next_to(arrow, UP, SMALL_BUFF) example_group = VGroup(word, arrow, dot) example_groups.add(example_group) fade_rect = SurroundingRectangle(dots) fade_rect.set_stroke(BLACK, 0) fade_rect.set_fill(BLACK, 0.7) self.play( FadeIn(fade_rect), FadeIn(example_groups[0]) ) self.wait() self.play( zap_anim(example_words[0][0][3:5]), Transform(*example_groups), ) self.wait() self.play(FadeOut(example_groups[0]), FadeOut(fade_rect)) # Corrections valid_centers = [vd.get_center() for vd in valid_dots] lines = VGroup() for dot in dots: dc = dot.get_center() norms = [get_norm(dc - vc) for vc in valid_centers] line = Line(dc, valid_centers[np.argmin(norms)]) line.set_stroke(WHITE, 1) lines.add(line) shuffled_lines = VGroup(*lines) shuffled_lines.shuffle() self.play(ShowCreation(shuffled_lines, lag_ratio=10 / len(lines), run_time=5)) self.wait() # Mandering path between valid messages self.add(fade_rect, valid_dots) self.play(FadeIn(fade_rect)) path = [RIGHT, UP, UP, RIGHT, RIGHT, RIGHT, UP, UP, RIGHT, RIGHT, DOWN] dist = get_norm(dots[1].get_center() - dots[0].get_center()) curr = dots[index].get_center() arrows = VGroup() for vect in path: new = curr + dist * vect arrows.add(Arrow(curr, new, buff=0, fill_color=RED)) curr = new for arrow in arrows: self.play(GrowArrow(arrow), run_time=0.5) self.wait() class RobustForLessThanNErrors(Scene): def construct(self): words = OldTexText( "Robust for ", "$\\le N$", " errors", ) words.to_edge(UP) words[1].set_color(YELLOW) words[2].shift(0.15 * RIGHT) N = words[1][-1] num = Integer(1) num.set_color(YELLOW) num.move_to(N, LEFT) num.set_value(1) self.play(Write(words, run_time=2)) self.wait() self.remove(N) self.add(num) self.play(ChangeDecimalToValue(num, 20, run_time=3)) self.remove(num) self.add(N) self.wait() class TwentyQuestions(Scene): def construct(self): # Hamming's insight bits = [ 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, ] block = get_bit_grid(4, 4, bits=bits) hamming = ImageMobject("Richard_Hamming") hamming.set_height(3) hamming.to_corner(DL) bulb = Lightbulb() bulb.next_to(hamming.get_corner(UR), UP) self.add(block) self.play(FadeIn(hamming, 0.5 * RIGHT)) self.play(Write(bulb, run_time=1, stroke_width=5)) self.wait() # Preview parity checks parity_word = OldTexText("Parity check") parity_word.set_height(0.7) parity_word.set_color(BLUE) parity_word.move_to(block, UP) parity_word.set_opacity(0) back_rects = VGroup(*[ SurroundingRectangle(bit, buff=MED_SMALL_BUFF / 2).scale(0) for bit in get_bit_n_subgroup(block, 0) ]) back_rects.set_stroke(width=0) back_rects.set_fill(BLUE_E, 1) last_one_rects = VMobject() self.add(back_rects, block) for n, vect in zip(it.count(), [UP, UP, RIGHT, RIGHT]): block.generate_target() block.target.set_color(WHITE) color_group = get_bit_n_subgroup(block.target, n) color_group.set_color(BLUE) one_rects = get_one_rects(color_group) rects = VGroup(*[ SurroundingRectangle(bit, buff=MED_SMALL_BUFF / 2) for bit in color_group ]) rects.match_style(back_rects) self.play( FadeOut(last_one_rects), MoveToTarget(block), parity_word.next_to, color_group, vect, MED_LARGE_BUFF, parity_word.set_opacity, 1, Transform(back_rects, rects), ) self.play(ShowIncreasingSubsets(one_rects)) last_one_rects = one_rects self.play( FadeOut(back_rects), FadeOut(last_one_rects), FadeOut(parity_word), block.set_color, WHITE, ) # Expand to grid block.generate_target() block.target.space_out_submobjects(1.5) block.target.to_edge(LEFT, buff=LARGE_BUFF) boxes = get_bit_grid_boxes(block.target) p_labels = get_grid_position_labels(boxes) p_labels.set_color(GREY_C) self.play( FadeOut(hamming, LEFT), FadeOut(bulb, 1.5 * LEFT), MoveToTarget(block), ) self.play( ShowCreation(boxes, lag_ratio=0.2), FadeIn(p_labels, lag_ratio=0.2), ) # Set up questions q_labels = VGroup(*[ OldTexText(f"Q{n}:") for n in range(1, 5) ]) q_labels.set_height(0.5) q_labels.arrange(DOWN, buff=1.25) q_labels.next_to(boxes, RIGHT, buff=2) questions = VGroup() for n, q_label in enumerate(q_labels): m_grids = VGroup(boxes.copy(), boxes.copy()) m_grids.set_height(1) m_grids.set_width(1, stretch=True) colors = [GREY_BROWN, BLUE] for k, m_grid in enumerate(m_grids): get_bit_n_subgroup(m_grid, n, k).set_fill(colors[k], 0.75) vs = OldTexText("or") question = VGroup(m_grids[0], vs, m_grids[1]) question.arrange(RIGHT) question.next_to(q_label, RIGHT, buff=MED_SMALL_BUFF) question.add_to_back(q_label) questions.add(question) questions.to_edge(RIGHT, buff=MED_LARGE_BUFF) for question in questions: question.save_state() q_center = question.get_center() for mob in question: if mob is not question[0]: mob.move_to(q_center) mob.set_fill(opacity=0) mob.set_stroke(width=0) self.play( LaggedStartMap(Restore, questions, lag_ratio=0.25), run_time=3, ) self.wait() questions.save_state() # Focus on question 1 h_rects = boxes.copy() h_rects.set_fill(BLUE, 0.5) h_groups = VGroup(*[ get_bit_n_subgroup(h_rects, n) for n in range(4) ]) pc_words = OldTexText("Parity check\\\\these 8 bits") pc_words.next_to(boxes, RIGHT, aligned_edge=UP) pc_words.shift(DOWN) pc_words.set_color(BLUE) block.save_state() self.add(h_groups[0], block, p_labels) self.play( questions[1:].fade, 0.9, FadeIn(h_groups[0], lag_ratio=0.3, run_time=3), get_bit_n_subgroup(block, 0, 0).fade, 0.9, Write(pc_words, run_time=1) ) self.wait() # Scan first group def get_sub_scanim(n, boxes=boxes, block=block, **kwargs): return scan_anim( boxes.get_corner(DR) + UR, get_bit_n_subgroup(block, n), lag_factor=0.5, run_time=2, **kwargs ) scanim = get_sub_scanim(0) robot = scanim.mobject[-1] bangs = OldTex("!!!") bangs.set_color(RED) bangs.next_to(robot, UR, buff=SMALL_BUFF) check = Checkmark() check.next_to(robot, UR, buff=SMALL_BUFF) for mob in (bangs, check): mob.scale(1.5, about_edge=DL) q1_rect = SurroundingRectangle(questions[0][3]) self.play(scanim) self.play(FadeIn(bangs, 0.1 * DOWN, lag_ratio=0.2)) self.wait() self.play(ShowCreation(q1_rect)) self.wait() self.play( get_sub_scanim(0, show_robot=False), FadeOut(bangs) ) self.play(FadeIn(check, 0.2 * DOWN)) self.wait() self.play( q1_rect.move_to, questions[0][1], ) self.play( LaggedStartMap( ShowCreationThenFadeOut, get_bit_n_subgroup(h_rects, 0, 0).copy().set_fill(GREY_BROWN, 0.5) ) ) self.wait() self.play(LaggedStart(*map(FadeOut, [ robot, check, q1_rect, ]))) # Comment over in pi creature scene pass # Highlight parity bit frame = self.camera.frame frame.save_state() ecc_rects = VGroup(*[ h_group[0] for h_group in h_groups ]) pb_label = OldTexText("Parity bit") pb_label.next_to(ecc_rects[0], UP, MED_LARGE_BUFF) pb_arrow = Arrow( pb_label.get_bottom() + MED_SMALL_BUFF * LEFT, block[1].get_top(), buff=0.1 ) pb_label.set_color(GREEN) pb_arrow.set_color(GREEN) pb_arrow.set_stroke(BLACK, 5, background=True) h_groups[0].remove(ecc_rects[0]) self.add(ecc_rects[0], block, p_labels) self.play( frame.set_height, 9, {"about_edge": DOWN}, FadeIn(pb_label, 0.5 * DOWN), GrowArrow(pb_arrow), ecc_rects[0].set_color, GREEN, ) self.wait() self.play(ShowCreationThenFadeAround(p_labels[1])) self.wait() one_rects = get_one_rects(get_bit_n_subgroup(block, 0)) counter = get_ones_counter(boxes[-2:], one_rects) counter.scale(0.5) self.add(counter) self.play(ShowIncreasingSubsets(one_rects)) self.wait() self.play(toggle_bit_anim(block[1])) one_rects.set_submobjects( get_one_rects(get_bit_n_subgroup(block, 0)).submobjects ) self.wait() # Back to all questions self.play( LaggedStart(*map(FadeOut, [ one_rects, counter, pb_arrow, pb_label, pc_words, h_groups[0] ])), frame.restore, ) toggle_bit(block.saved_state[1]) # Dumb hack self.play( questions.restore, block.restore, ) # Focus on question 2 self.play( questions[0].fade, 0.9, questions[2:].fade, 0.9, get_bit_n_subgroup(block, 1, 0).fade, 0.9, ecc_rects[0].fade, 0.5, ) self.add(h_groups[1], block, p_labels) self.play(FadeIn(h_groups[1], lag_ratio=0.2, run_time=2)) pb_label.next_to(boxes[2], UP, SMALL_BUFF) h_groups[1].remove(ecc_rects[1]) self.add(ecc_rects[1], block, p_labels) self.play( FadeIn(pb_label, 0.25 * LEFT), ecc_rects[1].set_color, GREEN, ) self.wait() # Apply second parity check one_rects = get_one_rects(get_bit_n_subgroup(block, 1)) counter = get_ones_counter(boxes[-2:], one_rects) counter.scale(0.5) self.add(counter) self.play( ShowIncreasingSubsets(one_rects) ) self.wait() self.play(LaggedStart(*map(FadeOut, [ one_rects, counter, pb_label, ]))) # Find error in right half scanim = get_sub_scanim(1) robot = scanim.mobject[-1] self.play( zap_anim(block[6]), toggle_bit_anim(block[6], target_color=RED) ) self.play(scanim) self.play(FadeIn(bangs, 0.1 * DOWN, lag_ratio=0.1)) self.wait() q2_rect = q1_rect.copy() q2_rect.move_to(questions[1][3]) self.play(ShowCreation(q2_rect)) self.wait() self.play( toggle_bit_anim(block[6], target_color=WHITE), FadeOut(bangs), ) self.play(get_sub_scanim(1, show_robot=False)) self.play(FadeIn(check, 0.2 * DOWN)) self.wait() self.play(q2_rect.move_to, questions[1][1]) self.play( ShowCreationThenFadeOut( get_bit_n_subgroup(boxes.copy(), 1, 0).set_fill(GREY_BROWN, 0.5), lag_ratio=0.5, run_time=2, ) ) self.wait() self.play( FadeOut(h_groups[1]), FadeOut(robot), FadeOut(check), FadeOut(q2_rect), block.restore, Transform(questions[0], questions.saved_state[0]), ecc_rects[0].set_fill, GREEN, 0.5, ) # Mention two errors? # How to use Q1 with Q2 q1_rect.move_to(questions[0][3]) q2_rect.move_to(questions[1][3]) q1_highlight, q2_highlight = [ get_bit_n_subgroup(h_rects, n).copy().set_fill(BLUE, 0.5) for n in [0, 1] ] q2_highlight.set_fill(opacity=0) q2_highlight.set_stroke(YELLOW, 7) self.add(q1_highlight, block, p_labels) self.play( FadeIn(q1_highlight, lag_ratio=0.2), ShowCreation(q1_rect), get_bit_n_subgroup(block, 0, 0).fade, 0.9, *map(FadeOut, ecc_rects[:2]), ) self.wait() self.play( FadeIn(q2_highlight, lag_ratio=0.2), ShowCreation(q2_rect), get_bit_n_subgroup(block, 1, 0)[1::2].fade, 0.9, ) self.wait(2) self.play( q1_rect.move_to, questions[0][1], q1_highlight.move_to, boxes, LEFT, q1_highlight.set_fill, GREY_BROWN, block.restore, FadeOut(q2_highlight), ) self.play(get_bit_n_subgroup(block, 0).fade, 0.9) self.wait() self.play( FadeIn(q2_highlight, lag_ratio=0.2), block[::4].fade, 0.9, ) self.wait(2) self.play( q1_highlight.move_to, boxes, RIGHT, q1_highlight.set_fill, BLUE, q2_highlight.move_to, boxes, LEFT, block.restore, q1_rect.move_to, questions[0][3], q2_rect.move_to, questions[1][1], ) self.play( block[::4].fade, 0.9, get_bit_n_subgroup(block, 1).fade, 0.9, ) self.wait(2) self.play( q1_rect.move_to, questions[0][1], q1_highlight.move_to, boxes, LEFT, q1_highlight.set_fill, GREY_BROWN, block[1::4].fade, 0.9, Transform(block[0::4], block.saved_state[0::4]), ) self.wait() morty = Mortimer(height=2) morty.flip() morty.next_to(boxes, RIGHT, buff=0.5, aligned_edge=DOWN) words = OldTexText("Or no error\\\\at all!") words.next_to(morty, UP) self.play( VFadeIn(morty), morty.change, "shruggie", questions[0], FadeIn(words, DOWN) ) self.play(Blink(morty)) self.wait(2) self.play( LaggedStart(*map(FadeOut, [ q1_highlight, q2_highlight[1::2], words, morty, ])), block.restore, ) self.wait() column_highlight = q2_highlight[0::2] # Choosing a column self.play( q1_rect.move_to, questions[0][3], column_highlight.move_to, boxes[1], UP, ) self.wait() self.play( q1_rect.move_to, questions[0][1], q2_rect.move_to, questions[1][3], column_highlight.move_to, boxes[2], UP, ) self.wait() self.play( q1_rect.move_to, questions[0][3], column_highlight.move_to, boxes[3], UP, ) self.wait() # Bring back the parity highlights self.add(*ecc_rects[:2], block, p_labels) self.play( LaggedStart(*map(FadeOut, [ column_highlight, q1_rect, q2_rect ])), *map(FadeIn, ecc_rects[:2]), ) self.wait() for n in [2, 3]: self.play(Transform(questions[n], questions.saved_state[n])) self.wait() # Question 3 self.add(h_groups[2], block, p_labels) self.play( get_bit_n_subgroup(block, 2, 0).fade, 0.9, FadeIn(h_groups[2], lag_ratio=0.2, run_time=2), questions[:2].fade, 0.9, questions[3].fade, 0.9, ) self.wait() h_groups[2].remove(ecc_rects[2]) self.add(ecc_rects[2], block, p_labels) self.play( ecc_rects[2].set_color, GREEN, ShowCreationThenFadeOut(SurroundingRectangle(boxes[4], buff=0)) ) self.wait() one_rects = get_one_rects(get_bit_n_subgroup(block, 2)) self.play(ShowIncreasingSubsets(one_rects)) self.wait() temp_check = Checkmark() temp_check.set_height(0.4) temp_check.next_to(block[4], UL, buff=0) self.play(Write(temp_check)) self.play(FadeOut(temp_check)) self.play(FadeOut(one_rects)) self.play( block.restore, FadeOut(h_groups[2]), ) self.wait() # Question 4 self.add(h_groups[3], block, p_labels) self.play( questions[2].fade, 0.9, Transform(questions[3], questions.saved_state[3]), get_bit_n_subgroup(block, 3, 0).fade, 0.9, FadeIn(h_groups[3], lag_ratio=0.2, run_time=2), ) self.wait() h_groups[3].remove(ecc_rects[3]) self.add(ecc_rects[3], block, p_labels) self.play( ecc_rects[3].set_color, GREEN, ShowCreationThenFadeOut(SurroundingRectangle(boxes[8], buff=0)) ) one_rects = get_one_rects(get_bit_n_subgroup(block, 3)) self.play(ShowIncreasingSubsets(one_rects)) self.wait() self.play(toggle_bit_anim(block[8])) toggle_bit(block.saved_state[8]) one_rects.set_submobjects(get_one_rects(get_bit_n_subgroup(block, 3))) self.wait() self.play(FadeOut(one_rects, lag_ratio=0.2)) self.play( block.restore, questions.restore, FadeOut(h_groups[3], lag_ratio=0.2), ) self.wait() # Point out rolls of questions braces = VGroup( Brace(questions[:2], LEFT), Brace(questions[2:], LEFT), ) for brace, text in zip(braces, ["column", "row"]): brace.words = brace.get_text(f"Which\\\\{text}?") for brace in braces: self.play( GrowFromCenter(brace), FadeIn(brace.words, 0.25 * RIGHT) ) self.wait() # Example with error at 3 q_rects = VGroup() for question, answer in zip(questions, [1, 1, 0, 0]): q_rects.add(SurroundingRectangle(question[1 + 2 * answer])) self.play( zap_anim(block[3]), toggle_bit_anim(block[3], target_color=RED), ) self.wait() target_square = SurroundingRectangle(boxes[3::4], buff=0, stroke_width=5) for n in range(4): highlight = get_bit_n_subgroup(h_rects.copy(), n) one_rects = get_one_rects(get_bit_n_subgroup(block, n)) self.add(highlight, block, p_labels) self.play( FadeIn(highlight), ShowCreation(q_rects[n]), ShowIncreasingSubsets(one_rects), ) self.wait() self.play( FadeOut(highlight), FadeOut(one_rects), ) if n == 1: self.play(FadeIn(target_square)) elif n == 3: self.play(target_square.replace, boxes[3], {"stretch": True}) self.wait() self.play( toggle_bit_anim(block[3], target_color=WHITE) ) self.wait() # Binary counting for n in range(1, 16): target_square.generate_target() target_square.target.move_to(boxes[n]) for k, q_rect in enumerate(q_rects): index = 3 if((1 << k) & n) else 1 q_rect.generate_target() q_rect.target.move_to(questions[k][index]) self.play(*map(MoveToTarget, [target_square, *q_rects]), run_time=0.5) self.wait() # Bit 0 for q_rect, question in zip(q_rects, questions): q_rect.generate_target() q_rect.target.move_to(question[1]) self.play( target_square.move_to, boxes[0], LaggedStartMap(MoveToTarget, q_rects), ) self.wait() for n in range(4): group = get_bit_n_subgroup(h_rects.copy(), n) self.play(FadeIn(group, lag_ratio=0.2)) self.wait(0.5) self.play(FadeOut(group)) self.wait() randy = Randolph(height=2) randy.next_to(boxes, RIGHT, buff=MED_LARGE_BUFF, aligned_edge=DOWN) ne_word = OldTexText("No error?") ne_word.next_to(randy, UP, buff=MED_LARGE_BUFF) ne_word.shift(0.2 * RIGHT) ez_word = OldTexText("or error\\\\at bit 0?") ez_word.set_color(RED) ez_word.move_to(ne_word, DOWN) self.play( VFadeIn(randy), randy.change, 'pondering', questions, FadeOut(braces), *[ FadeOut(brace.words) for brace in braces ] ) self.play(FadeIn(ne_word, 0.5 * DOWN)) self.play(Blink(randy)) self.wait() self.play( ne_word.next_to, ez_word, UP, MED_LARGE_BUFF, FadeIn(ez_word, 0.25 * DOWN), randy.change, "confused", target_square, ) self.play(Blink(randy)) for x in range(2): self.play(toggle_bit_anim(block[0])) self.play(randy.change, "pondering", questions) # Count through again for n in [*range(0, 16), 0]: target_square.move_to(boxes[n]) for k, q_rect in enumerate(q_rects): index = 3 if((1 << k) & n) else 1 q_rect.move_to(questions[k][index]) randy.look_at(target_square) self.wait(0.5) # Highlight no error ne_rect = SurroundingRectangle(ne_word) ne_rect.set_stroke(GREY_B, 2) ne_comment = OldTexText("17th outcome") ne_comment.set_color(GREY_B) ne_comment.next_to(ne_rect, UP) self.play( ShowCreation(ne_rect), FadeIn(ne_comment, 0.25 * DOWN), randy.change, "maybe", ne_comment, ) for x in range(2): self.play(Blink(randy)) self.wait(2) # Nix bit 0 zero_rect = SurroundingRectangle(boxes[0], buff=0) zero_rect.set_fill(BLACK, 1) zero_rect.set_stroke(BLACK, 0) zero_rect.scale(0.98) self.play( GrowFromCenter(zero_rect), boxes[0].set_stroke, {"width": 0}, FadeOut(target_square), randy.change, "raise_left_hand", zero_rect, ) ne_word.generate_target() ne_word.target[0][-1].set_opacity(0) ne_word.target.next_to(randy, UP, MED_LARGE_BUFF) ne_word.target.set_color(YELLOW) self.play( MoveToTarget(ne_word), LaggedStart(*map(FadeOut, [ne_rect, ne_comment, ez_word])) ) for n in range(4): highlight = get_bit_n_subgroup(h_rects.copy(), n) one_rects = get_one_rects(get_bit_n_subgroup(block, n)) self.add(highlight, block, p_labels, zero_rect, one_rects) self.wait() self.remove(highlight, one_rects) # (15, 11) setup stat_words = VGroup( OldTexText("15", "-bit block"), OldTexText("11", " bits of\\\\message", alignment=""), OldTexText("4 bits of\\\\redundancy", alignment=""), ) stat_words.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) stat_words[0].set_color(YELLOW) stat_words[2].set_color(GREEN) stat_words.next_to(boxes, RIGHT, buff=MED_LARGE_BUFF, aligned_edge=UP) stat_words.shift(0.5 * DOWN) self.play( LaggedStart(*map(FadeOut, [*q_rects, ne_word])), randy.change, "tease", stat_words, FadeIn(stat_words[0], 0.5 * LEFT) ) self.play(Blink(randy)) self.play( FadeIn(stat_words[1], 0.5 * LEFT), LaggedStart(*[ toggle_bit_anim(bit) for i, bit in enumerate(block) if i not in [0, 1, 2, 4, 8] ]) ) self.play( LaggedStart(*[ toggle_bit_anim(bit) for i, bit in enumerate(block) if i not in [0, 1, 2, 4, 8] ]) ) self.wait() self.play( FadeIn(stat_words[2], 0.5 * LEFT), LaggedStart(*map(ShowCreationThenFadeAround, [ block[2**n] for n in range(4) ])) ) self.play(Blink(randy)) code_name = OldTexText("(", "15", ", ", "11", ")", " Hamming code") code_name.set_height(0.8) code_name.to_edge(UP) code_name.shift(UP) self.play( ApplyMethod(frame.set_height, 9, {"about_edge": DOWN}, run_time=2), TransformFromCopy(stat_words[0][0], code_name[1]), TransformFromCopy(stat_words[1][0], code_name[3]), LaggedStart(*map(FadeIn, [ code_name[i] for i in [0, 2, 4, 5] ])), ) self.wait() # Bring back bit zero self.play( LaggedStart(*map(FadeOut, [ *stat_words, randy, *questions, code_name, ])), ApplyMethod(frame.match_x, block), run_time=2 ) old_zero_rect = zero_rect zero_rect = old_zero_rect.copy() zero_rect.set_stroke(YELLOW, 2) zero_rect.set_fill(YELLOW, 0.5) zero_rect.save_state() zero_rect.stretch(0, 1, about_edge=UP) zero_words = OldTexText("Can we put this bit to work?") zero_words.set_height(0.7) zero_words.next_to(zero_rect, UP, MED_LARGE_BUFF) zero_words.match_x(block) zero_words.set_color(YELLOW) self.add(zero_rect, block, p_labels) block[0].set_opacity(0) self.play( FadeOut(old_zero_rect), Restore(zero_rect), Write(zero_words) ) self.wait() # Parity check the whole block pc_words = OldTexText("Parity check\\\\ \\emph{the whole block}") pc_words.set_height(1.2) pc_words.next_to(boxes, LEFT, buff=MED_LARGE_BUFF) one_rects = get_one_rects(block) counter = get_ones_counter(boxes[-2:], one_rects) counter.scale(0.5) self.play( Write(pc_words, run_time=1), ShowCreationThenFadeOut(h_rects.copy()), ) self.wait() ecc_bits = VGroup(*[block[2**n] for n in range(4)]) for x in range(2): self.play(LaggedStartMap(toggle_bit_anim, ecc_bits, lag_ratio=0.25, run_time=1)) self.wait() self.add(counter) self.play(ShowIncreasingSubsets(one_rects)) self.wait() block[0][1].set_opacity(1) self.play(Write(block[0])) one_rects.set_submobjects(get_one_rects(block)) self.wait() self.play(*map(FadeOut, [one_rects, counter])) # Walk through single and two bit errors self.play( zap_anim(block[9]), toggle_bit_anim(block[9], target_color=RED), ) one_rects.set_submobjects(get_one_rects(block)) counter.set_opacity(1) self.add(counter) self.play(ShowIncreasingSubsets(one_rects)) self.wait() self.play( zap_anim(block[5]), toggle_bit_anim(block[5], target_color=RED), ) one_rects.set_submobjects(get_one_rects(block)) self.wait() self.play(FadeOut(one_rects), FadeOut(counter)) for n in [2, 3]: group = get_bit_n_subgroup(h_rects.copy(), n) group.set_fill(opacity=0) group.set_stroke(BLUE, 10) self.play(ShowCreation(group, lag_ratio=0.5)) self.play(FadeOut(group)) self.wait() scanim = scan_anim(boxes.get_corner(DR) + 2 * UR, block, lag_factor=0.5, run_time=2) robot = scanim.mobject[-1] robot.set_color(GREY_B) robot.scale(2, about_edge=UP) ded_words = OldTexText("At least\\\\2 errors!") ded_words.set_color(RED) ded_words.next_to(robot, UR, buff=SMALL_BUFF) self.play(scanim) self.play(FadeIn(ded_words, 0.5 * DOWN)) self.wait() # Extended name new_title = OldTexText("Extended Hamming Code") new_title.replace(zero_words, dim_to_match=1) self.play( FadeIn(new_title, DOWN), FadeOut(zero_words, UP), FadeOut(pc_words), ) self.wait() class WhatIfTheresAndArrowInECCBits(TeacherStudentsScene): def construct(self): self.student_says( "What if an\\\\error-correction bit\\\\needs to be corrected?", bubble_config={'width': 5, 'height': 4, "direction": LEFT}, added_anims=[self.teacher.change, "happy"] ) self.play_student_changes("confused", "confused") self.look_at(self.screen) self.wait(2) self.teacher_says("Try it!", target_mode="hooray") self.play_student_changes(*3 * ["pondering"], look_at=self.screen) self.wait(2) self.play_student_changes(*3 * ["thinking"], look_at=self.screen) self.wait(8) class ErrorAtECCBit(Scene): def construct(self): bits = get_bit_grid(4, 4, height=6) toggle_bit(bits[1]) toggle_bit(bits[4]) boxes = get_bit_grid_boxes(bits) pos_labels = get_grid_position_labels(boxes) ecc_boxes = VGroup(*[boxes[2**n] for n in range(4)]) ecc_boxes.set_fill(GREEN, 0.5) bangs = OldTexText("!!!") bangs.set_color(RED) bangs.next_to(boxes[2], UP, SMALL_BUFF) self.add(boxes, ecc_boxes, pos_labels, bits) self.wait() self.play(LaggedStartMap(Rotate, ecc_boxes, lambda m: (m, PI))) self.wait() self.play( zap_anim(bits[2]), toggle_bit_anim(bits[2], target_color=RED), ) self.play(Write(bangs)) self.wait() for bit in bits: bit.remove(bit[1 - get_bit_mob_value(bit)]) for n in range(4): bits.generate_target() bits.target.set_opacity(1) get_bit_n_subgroup(bits.target, n, 0).set_opacity(0) self.play(MoveToTarget(bits)) self.wait() self.play(bits.set_opacity, 1) self.wait() class HalfAsPowerful(TeacherStudentsScene): def construct(self): self.student_says( "Shouldn't that be\\\\only half as good?", target_mode="sassy", added_anims=[self.teacher.change, "happy"] ) self.play_student_changes( "pondering", "pondering", look_at=self.screen, added_anims=[self.teacher.change, "tease"] ) self.look_at(self.screen) self.wait(8) class WhatAboutTwoErrors(TeacherStudentsScene): def construct(self): self.student_says( "What about\\\\2 errors?", ) self.play(self.teacher.change, "guilty") self.look_at(self.screen) self.play_student_changes("erm", "confused") self.look_at(self.screen) self.wait(4) class BlockSize256(Scene): def construct(self): N = 8 frame = self.camera.frame # Bit block bits = string_to_bits("You decoded an easter egg. Nice!") block = get_bit_grid(2**(N // 2), 2**(N // 2), bits=bits) block.set_height(6) block.to_edge(LEFT, buff=LARGE_BUFF) boxes = get_bit_grid_boxes(block) parity_boxes = VGroup(*[boxes[2**k] for k in range(N)]) parity_boxes.set_fill(GREEN, 0.8) bit_boxes = VGroup(*[VGroup(box, bit) for bit, box in zip(block, boxes)]) to_fade = VGroup() to_keep = VGroup() for i, bb in enumerate(bit_boxes): if i >= 64 or (i % 16) >= 4: to_fade.add(bb.copy()) else: to_keep.add(bb.copy()) to_fade.save_state() to_fade.fade(1) frame.save_state() frame.replace(to_keep, dim_to_match=1) frame.scale(1.2) self.add(to_keep) self.play( Restore(frame), Restore(to_fade, lag_ratio=0.1), run_time=5, ) self.clear() self.add(boxes) self.add(block) # Add title title = OldTexText("$256 = 2^8$ bits") title.set_height(0.7) title.next_to(boxes, UP, MED_LARGE_BUFF) title.set_x(0) self.play( frame.move_to, 0.5 * UP, Write(title) ) self.wait() # Parity groups parity_groups = VGroup() for k in range(N): group = boxes.copy() group.set_fill(BLACK, opacity=0) group.set_stroke(GREY_B, 1) group.set_height(1.5) get_bit_n_subgroup(group, k).set_fill(BLUE_E, 1) parity_groups.add(group) parity_groups.arrange_in_grid(2, 4, buff=MED_LARGE_BUFF) parity_groups.set_width(7) VGroup(parity_groups[:4], parity_groups[4:]).arrange(DOWN, buff=1.5) parity_groups.to_edge(RIGHT) # Question labels q_labels = VGroup(*[TexText(f"Q{i + 1}") for i in range(N)]) for label, group in zip(q_labels, parity_groups): label.set_height(0.3) label.next_to(group, UP, SMALL_BUFF) # Add questions self.play( LaggedStartMap(FadeIn, q_labels, lambda m: (m, DOWN), lag_ratio=0.3, run_time=5), LaggedStartMap(FadeIn, parity_groups, lambda m: (m, DOWN), lag_ratio=0.3, run_time=5), ) self.wait() # Isolate one square pos = 69 # Why not? bits = "{0:b}".format(pos) bits = (N - len(bits)) * '0' + bits bits = bits[::-1] yes_no_group = VGroup() boxes.save_state() possible_positions = list(range(2**N)) for k, bit, group in zip(it.count(), bits, parity_groups): bit_value = int(bit) if bit_value: word = OldTexText("Yes", color=GREEN) else: word = OldTexText("No", color=RED) word.next_to(group, DOWN) yes_no_group.add(word) intersect_positions = get_bit_n_sublist(range(2**N), k, bit_value) globals()['intersect_positions'] = intersect_positions possible_positions = list(filter( lambda i: i in intersect_positions, possible_positions, )) boxes.generate_target() boxes.target.match_style(boxes.saved_state) globals()['possible_positions'] = possible_positions globals()['boxes'] = boxes VGroup(*[boxes.target[i] for i in possible_positions]).set_fill(BLUE, 1) self.play( FadeIn(word), MoveToTarget(boxes) ) self.wait() # Highlight parity bits parity_bits_label = OldTexText("8 parity bits") parity_bits_label.next_to(boxes, UP, aligned_edge=LEFT) parity_bits_label.set_color(GREEN) self.play( FadeIn(parity_bits_label, DOWN), title.to_edge, RIGHT ) self.add(parity_boxes, block) self.play( LaggedStartMap(Rotate, parity_boxes, lambda m: (m, TAU)), ) self.add(boxes, block) # Un-highlight isolated point self.play( boxes[pos].set_fill, BLACK, 0, FadeOut(yes_no_group) ) # Message bits message_bits = VGroup(*[ bit for i, bit in enumerate(block) if i not in [2**k for k in range(N)] ]) message_bits.shuffle() self.play( LaggedStart(*[ toggle_bit_anim(bit) for bit in message_bits ], lag_ratio=0.01, run_time=3) ) self.wait() # Write redundant redundant_label = OldTexText("``Redundant''") redundant_label.set_color(GREEN) redundant_label.next_to(parity_bits_label[-1][-1], RIGHT, MED_LARGE_BUFF, DOWN) self.play(Write(redundant_label)) block.save_state() for k in range(N): block.target = block.saved_state.copy() get_bit_n_subgroup(block.target, k, 0).set_fill(opacity=0) self.play(MoveToTarget(block)) self.wait(0.5) self.play(Restore(block)) self.wait() class WellAlmost(TeacherStudentsScene): def construct(self): self.teacher_says("Well...\\\\almost", target_mode="hesitant") self.play_student_changes("angry", "sassy", "confused") self.wait(3) class ChecksSpellOutPositionInBinary(Scene): def construct(self): N = 4 pos = 7 # Setup block random.seed(0) bits = [random.choice([0, 1]) for n in range(2**N)] bits[1] = 0 bits[2] = 1 bits[4] = 0 bits[8] = 0 block = get_bit_grid(2**(N // 2), 2**(N // 2), bits=bits) block.set_height(5) block.to_edge(LEFT, buff=LARGE_BUFF) boxes = get_bit_grid_boxes(block) VGroup(*[boxes[2**n] for n in range(N)]).set_fill(GREY_D, 1) pos_labels = VGroup(*map(Integer, range(2**N))) pos_labels.set_height(0.2) for label, box, bit_label in zip(pos_labels, boxes, block): label.move_to(box, DR) label.shift(0.1 * UL) label.set_color(GREY_A) bit_label.scale(0.8) self.add(boxes) self.add(block) self.add(pos_labels) self.play( zap_anim(block[pos]), toggle_bit_anim(block[pos]), ) # Setup questions parity_groups = VGroup() for n in range(N): group = boxes.copy() group.set_height(1) group.set_width(1, stretch=True) group.set_fill(BLACK, 0) get_bit_n_subgroup(group, n).set_fill(BLUE_D, 1) parity_groups.add(group) parity_groups.arrange(DOWN, buff=MED_LARGE_BUFF) parity_groups.set_height(6) parity_groups.to_edge(RIGHT, buff=3) q_labels = VGroup(*[TexText(f"Q{n + 1}:") for n in range(N)]) for label, group in zip(q_labels, parity_groups): label.next_to(group, LEFT, MED_SMALL_BUFF) self.play( FadeIn(parity_groups), FadeIn(q_labels), ) # Binary search down bits_word = "{0:b}".format(pos) bits_word = (N - len(bits_word)) * '0' + bits_word bits = list(map(int, bits_word[::-1])) boxes.save_state() yes_no_words = VGroup() possible_positions = list(range(2**N)) for n, bit, group in zip(it.count(), bits, parity_groups): if bit: word = OldTexText("Yes", color=GREEN) else: word = OldTexText("No", color=RED) word.next_to(group, RIGHT) yes_no_words.add(word) possible_positions = list(filter( lambda i: i in get_bit_n_sublist(range(2**N), n, bit_value=bit), possible_positions, )) boxes.target = boxes.saved_state.copy() VGroup(*[boxes.target[i] for i in possible_positions]).set_fill(BLUE_D, 0.8) self.play( FadeIn(word, 0.5 * LEFT), MoveToTarget(boxes), ) self.wait() # Spell answer in binary binary_answers = VGroup(*[ Integer(bit).move_to(word).match_color(word) for bit, word in zip(bits, yes_no_words) ]) self.play( LaggedStartMap(GrowFromCenter, binary_answers), LaggedStartMap(ApplyMethod, yes_no_words, lambda m: (m.scale, 0), remover=True), ) # Show value of 7 frame = self.camera.frame binary_pos_label = binary_answers.copy() binary_pos_label.generate_target() binary_pos_label.target.arrange(LEFT, buff=SMALL_BUFF, aligned_edge=DOWN) equation = VGroup( Integer(7, color=BLUE), OldTex("\\rightarrow"), binary_pos_label.target, ) equation.arrange(RIGHT) equation.to_edge(UP, buff=0) arrow = Arrow(equation.get_left(), equation.get_right(), buff=0) arrow.next_to(equation, DOWN, SMALL_BUFF) trans_words = OldTexText("Decimal to binary") trans_words.match_width(arrow) trans_words.next_to(arrow, DOWN, SMALL_BUFF) self.play( MoveToTarget(binary_pos_label), frame.move_to, 0.5 * UP ) self.play( Write(equation[:-1]), Write(trans_words), GrowArrow(arrow), run_time=1, ) self.wait() bin_group = VGroup(*equation[:-1], binary_pos_label, arrow, trans_words) # Spell out binary bin_equation = OldTex( "{7} = {0} \\cdot 8 + {1} \\cdot 4 + {1} \\cdot 2 + {1} \\cdot 1", tex_to_color_map={ "{0}": RED, "{1}": GREEN, "{7}": BLUE, } ) bin_equation.move_to(bin_group, UP) bit_parts = list(it.chain(*[ bin_equation.get_parts_by_tex(f"{{{d}}}") for d in [0, 1] ])) self.play( bin_group.next_to, bin_equation, DOWN, LARGE_BUFF, *[ ApplyMethod(m1.copy().replace, m2, {"dim_to_match": 1}, remover=True, run_time=1.5) for m1, m2 in zip(binary_pos_label[::-1], bit_parts) ], ApplyMethod(equation[0].copy().replace, bin_equation[0], remover=True, run_time=1.5) ) self.add(bin_equation[0], *bit_parts) self.play(FadeIn(VGroup(*[ part for part in bin_equation if part.get_tex() not in ["{0}", "{1}", "{7}"] ]), lag_ratio=0.1)) self.add(bin_equation) self.wait() # Error at 7 toggle_bit(block[pos]) self.play( zap_anim(block[pos]), toggle_bit_anim(block[pos], target_color=RED), ) self.wait() # Four parity checks for n, label, group, word in zip(it.count(), q_labels, parity_groups, yes_no_words): boxes.target = boxes.saved_state.copy() get_bit_n_subgroup(boxes.target, n).set_fill(BLUE, 0.8) rect = SurroundingRectangle(VGroup(label, group, word), buff=MED_SMALL_BUFF) one_rects = get_one_rects(get_bit_n_subgroup(block, n)) self.play( MoveToTarget(boxes), ShowCreation(rect), ShowIncreasingSubsets(one_rects) ) self.play( FadeOut(one_rects), FadeOut(rect), ) self.wait(0.5) self.play(Restore(boxes)) self.wait() # Other examples toggle_bit(block[7]) block[7].set_color(WHITE) bit_parts = VGroup(*bit_parts) to_save = VGroup( equation[0], bin_equation[0], bit_parts, binary_pos_label, binary_answers, ) to_save.save_state() ns = random.sample(list(range(16)), 10) for n in ns: toggle_bit(block[n]) block[n].set_color(YELLOW) nc1 = Integer(n) nc1.replace(equation[0], 1) nc1.match_color(equation[0]) equation[0].set_opacity(0) nc2 = nc1.copy() nc2.replace(bin_equation[0], 1) bin_equation[0].set_fill(0) new_bits = int_to_bit_string(n, 4) new_bit_mobs = VGroup() for b1, b2, b3, value in zip(reversed(bit_parts), binary_pos_label, binary_answers, reversed(new_bits)): new_mob = OldTex(value) new_mob.set_color(GREEN if int(value) else RED) for b in (b1, b2, b3): nmc = new_mob.copy() nmc.replace(b, 1) b.set_opacity(0) new_bit_mobs.add(nmc) self.play(*[ Animation(mob, remover=True, run_time=1) for mob in [new_bit_mobs, nc1, nc2] ]) toggle_bit(block[n]) block[n].set_color(WHITE) to_save.restore() self.wait() # Remove 7 stuff self.play( FadeOut(VGroup( *bin_group, *bin_equation, *binary_answers ), lag_ratio=0.1), block[pos].set_color, WHITE, ) question_group = VGroup(q_labels, parity_groups) # Show numbers 0 through 15 pos_labels_movers = pos_labels.copy() bin_pos_groups = VGroup() arrows = VGroup() bin_labels = VGroup() for n, label in enumerate(pos_labels_movers): label.scale(2) arrow = OldTex("\\rightarrow") bits_word = "{0:b}".format(n) bits_word = (N - len(bits_word)) * '0' + bits_word bin_label = VGroup(*[Tex(b) for b in bits_word]) bin_label.arrange(RIGHT, buff=SMALL_BUFF, aligned_edge=DOWN) pos_group = VGroup(label, arrow, bin_label) pos_group.arrange(RIGHT, buff=MED_SMALL_BUFF) bin_pos_groups.add(pos_group) arrows.add(pos_group[1]) bin_labels.add(bin_label) bin_pos_groups.arrange_in_grid(8, 2, fill_rows_first=False) bin_pos_groups.set_height(7) bin_pos_groups.to_edge(RIGHT) bin_pos_groups.set_y(0.5) self.play( FadeOut(question_group), FadeIn(arrows, lag_ratio=0.02), TransformFromCopy(pos_labels, pos_labels_movers), ) self.play(ShowIncreasingSubsets(bin_labels, run_time=3, rate_func=bezier([0, 0, 1, 1]))) self.wait() # Put bin labels in boxes for label, box in zip(bin_labels, boxes): label.generate_target() label.target.set_width(0.7 * box.get_width()) label.target.move_to(box, DOWN) label.target.shift(SMALL_BUFF * UP) for bit in block: bit.generate_target() bit.target.scale(0.5, about_edge=UP), bit.target.fade(0.5) kw = { "run_time": 5, "lag_ratio": 0.3, } self.play( LaggedStartMap(MoveToTarget, bin_labels, **kw), LaggedStartMap(FadeOut, arrows, **kw), LaggedStartMap(FadeOut, pos_labels_movers, **kw), LaggedStartMap(FadeOut, pos_labels, **kw), LaggedStartMap(MoveToTarget, block, **kw), ) self.wait() # Show confusion randy = Randolph() randy.flip() randy.to_corner(DR, buff=LARGE_BUFF) self.play( VFadeIn(randy), randy.change, "maybe", boxes, ) self.play(PiCreatureBubbleIntroduction( randy, "Wait...", target_mode="confused", bubble_type=ThoughtBubble, look_at=boxes.get_top(), )) self.play(Blink(randy)) self.wait() self.play(LaggedStart(*map(ShowCreationThenFadeAround, bin_labels), lag_ratio=0)) self.play(randy.change, "maybe") self.play( LaggedStart(*[ShowCreationThenFadeOut(SurroundingRectangle(b, color=GREEN)) for b in block], lag_ratio=0), randy.look_at, boxes.get_bottom(), ) self.play(Blink(randy)) self.play( randy.change, 'pondering', boxes, FadeOut(randy.bubble), FadeOut(randy.bubble.content), ) for x in range(2): self.wait() self.play(Blink(randy)) self.play(randy.change, "thinking") self.play(FadeOut(randy)) # Go through parity group 1 (and setup others) bit_arrow_groups = VGroup() for n in range(N): arrow_group = VGroup() for bin_label in bin_labels: char = bin_label[-(n + 1)] arrow = Triangle(start_angle=-PI / 2) arrow.stretch(0.8, 0) arrow.set_height(0.8 * char.get_height()) arrow.next_to(char, UP, buff=0.05) arrow.set_stroke(width=0) if char.get_tex() == '0': arrow.set_fill(GREY, 1) else: arrow.set_fill(BLUE, 1) arrow_group.add(arrow) bit_arrow_groups.add(arrow_group) highlight_groups = VGroup() for n in range(N): highlight_group = boxes.copy() highlight_group.set_fill(BLACK, 0) get_bit_n_subgroup(highlight_group, n).set_fill(BLUE, 0.5) highlight_groups.add(highlight_group) questions = VGroup() for n in range(N): chars = ["\\underline{\\phantom{0}}" for x in range(4)] chars[-(n + 1)] = "\\underline{1}" question = OldTexText( f""" If there's an error, does\\\\ its position look like\\\\ """, " ".join(chars), "?" ) question.scale(1.25) question[1:].scale(1.5, about_edge=UP) question[1:].shift(SMALL_BUFF * DOWN) question[1].set_color(BLUE) question.next_to(boxes, RIGHT, LARGE_BUFF) questions.add(question) self.play( LaggedStartMap(FadeIn, bit_arrow_groups[0], lag_ratio=0.3, run_time=3), FadeOut(block), ) self.play(Transform(boxes, highlight_groups[0])) self.wait() self.play(Write(questions[0])) self.wait() # Go through parity groups 2-4 bit_arrows = bit_arrow_groups[0] for n in range(1, N): self.play(boxes.set_fill, BLACK, 0) self.play( Transform(bit_arrows, bit_arrow_groups[n]), FadeOut(questions[n - 1]) ) self.wait() self.play( Transform(boxes, highlight_groups[n]), FadeIn(questions[n]) ) self.wait() # Organize questions questions.generate_target() questions.target.arrange(DOWN, buff=LARGE_BUFF) questions.target.set_height(FRAME_HEIGHT - 1) questions.target.next_to(boxes, RIGHT, buff=1.5) questions.target.match_y(frame) questions[:N - 1].set_opacity(0) self.play( MoveToTarget(questions), Restore(boxes), FadeOut(bit_arrows), ) fade_anims = [] for n in range(N): rect = SurroundingRectangle(questions[n]) rect.set_stroke(BLUE, 2) self.play( FadeIn(highlight_groups[n]), FadeIn(rect), *fade_anims ) fade_anims = [ FadeOut(highlight_groups[n]), FadeOut(rect), ] self.play(*fade_anims) # Note power of 2 points parity_arrows = VGroup(Vector(DOWN), Vector(DOWN), Vector(RIGHT), Vector(RIGHT)) parity_arrows[0].next_to(boxes[1], UP, SMALL_BUFF) parity_arrows[1].next_to(boxes[2], UP, SMALL_BUFF) parity_arrows[2].next_to(boxes[4], LEFT, SMALL_BUFF) parity_arrows[3].next_to(boxes[8], LEFT, SMALL_BUFF) parity_arrows.set_color(GREEN) parity_groups = VGroup() for n, question in enumerate(questions): pg = boxes.copy() pg.set_width(pg.get_height(), stretch=True) pg.set_height(0.8 * question.get_height()) pg.set_fill(BLACK, 0) get_bit_n_subgroup(pg, n).set_fill(BLUE, 0.8) pg.next_to(question, RIGHT, LARGE_BUFF) parity_groups.add(pg) self.play( LaggedStartMap(GrowArrow, parity_arrows), ApplyMethod(frame.set_x, -1, run_time=2) ) self.wait() rects = VGroup(*[boxes[2**n].copy() for n in range(N)]) rects.set_fill(BLUE, 0.8) self.add(rects, bin_label) self.play( LaggedStartMap(VFadeInThenOut, rects, lag_ratio=0.5, run_time=5), LaggedStartMap(FadeIn, parity_groups, lag_ratio=0.5, run_time=5), ) self.wait() self.add(rects, bin_label) self.play( LaggedStartMap(VFadeInThenOut, rects, lag_ratio=0.5, run_time=5), ) self.wait() class PowerOfTwoPositions(Scene): def construct(self): block = get_bit_grid(4, 4) block.set_height(5) block.to_edge(LEFT, buff=LARGE_BUFF) boxes = get_bit_grid_boxes(block) numbers = VGroup(*[ Integer(n).move_to(box) for n, box in enumerate(boxes) ]) self.add(numbers) self.wait() for n in range(4): numbers[2**n].scale(1.5) numbers[2**n].set_color(YELLOW) self.wait(0.25) self.wait() class OneGroupPerParityBit(Scene): def construct(self): N = 4 block = get_bit_grid(2**(N // 2), 2**(N // 2)) block.set_height(5) block.to_edge(LEFT, buff=LARGE_BUFF) boxes = get_bit_grid_boxes(block) pos_labels = get_grid_position_labels(boxes) for bit in block: bit.scale(0.7) parity_boxes = VGroup(*[boxes[2**n] for n in range(N)]) parity_boxes.set_fill(GREEN, 0.8) block.save_state() self.add(boxes, pos_labels, block) for n in range(4): block.restore() get_bit_n_subgroup(block, n, 0).set_fill(opacity=0) self.wait(1.5) class LetsWalkThroughAnExample(TeacherStudentsScene): def construct(self): self.student_says( "Can we walk through\\\\a full example?", index=1, added_anims=[self.teacher.change, "happy"] ) self.play_student_changes("hooray", None, "hooray") self.wait(5) self.teacher_says( "But of\\\\course!", target_mode="tease" ) self.play_student_changes("happy", "coin_flip_1", "happy") self.wait(4) class FullExampleWithNewEnd(Scene): CONFIG = { "random_seed": 3, } def construct(self): # Pull bits out of an image image = ImageMobject("Tom_In_Bowtie") image.set_height(6) image.to_edge(LEFT, buff=LARGE_BUFF) bits = get_image_bits(image) bits.match_height(image) bits.generate_target() bits.target.arrange_in_grid(n_cols=11, h_buff=SMALL_BUFF, v_buff=MED_SMALL_BUFF) bits.target.next_to(image, RIGHT, LARGE_BUFF, UP) for bit, bt in zip(bits, bits.target): bit.save_state() bit.target = bt bit.fade(0.9) words = OldTexText("11-bit\\\\chunks") words.scale(1.5) words.to_edge(RIGHT) lines = VGroup() for bit in bits.target[10:200:11]: line = Line(RIGHT, LEFT) line.set_stroke(BLUE, 1) line.bit = bit line.word = words[0][0] line.add_updater(lambda m: m.put_start_and_end_on( m.word.get_left() + SMALL_BUFF * LEFT, m.bit.get_right() + SMALL_BUFF * RIGHT, )) lines.add(line) self.add(image) self.add(bits) self.save_state() self.play( LaggedStartMap( Succession, bits, lambda m: (Restore(m), MoveToTarget(m)), lag_ratio=3 / len(bits), ), Write(words, rate_func=squish_rate_func(smooth, 0.5, 0.7)), ShowCreation(lines, lag_ratio=0.1, rate_func=squish_rate_func(smooth, 0.5, 1)), run_time=8 ) for line, bit in zip(lines, bits[10::11]): line.bit = bit for bit in bits: if bit.get_center()[1] < -FRAME_HEIGHT / 2: bits.remove(bit) self.wait() # Show many 16 bit blocks bits.generate_target() bits.target.scale(1.5) bits.target.arrange_in_grid(n_cols=11, h_buff=SMALL_BUFF, v_buff=LARGE_BUFF) bits.target.move_to(bits, UR) box_groups = VGroup() box_arrows = VGroup() for bit in bits.target[0:77:11]: boxes = VGroup(*[Square() for x in range(16)]) boxes.arrange_in_grid(4, 4, buff=0) boxes.set_height(0.8) boxes.next_to(bit, LEFT, buff=1.5) boxes.set_stroke(GREY_B, 2) arrow = Arrow(bit.get_left(), boxes.get_right()) box_arrows.add(arrow) box_groups.add(boxes) self.play( FadeOut(image, 2 * LEFT), MoveToTarget(bits, run_time=2), LaggedStartMap(FadeIn, box_groups, run_time=4), LaggedStartMap(GrowArrow, box_arrows, run_time=4), ) self.wait() # Isolate to one box first_bits = bits[:11] first_boxes = box_groups[0] first_bits.generate_target() first_bits.target.set_height(0.6) first_bits.target.to_edge(UP) first_bits.target.set_x(-3) first_boxes.generate_target() first_boxes.target.set_height(5) first_boxes.target.next_to(first_bits.target, DOWN, LARGE_BUFF) self.play( MoveToTarget(first_bits), MoveToTarget(first_boxes), LaggedStart(*map(FadeOut, [ *bits[11:], box_arrows, box_groups[1:], *lines, words, ]), lag_ratio=0.01), run_time=2 ) bits = first_bits boxes = first_boxes # Try it yourself morty = Mortimer() morty.to_edge(DR) self.play( PiCreatureSays(morty, "Try it\\\\yourself", target_mode="hooray"), VFadeIn(morty) ) self.play(Blink(morty)) self.wait(2) self.play(LaggedStart( FadeOut(morty), FadeOut(morty.bubble), FadeOut(morty.bubble.content), )) # Fill block N = 4 ecc_boxes = VGroup(*[boxes[2**n] for n in range(N)]) message_boxes = VGroup(*[ box for box in boxes[1:] if box not in ecc_boxes ]) pos_labels = get_grid_position_labels(boxes, height=0.2) pos_labels.set_color(GREY_B) self.play( ecc_boxes.set_fill, GREEN, 0.7, boxes[0].set_fill, YELLOW, 0.5, FadeIn(pos_labels, lag_ratio=0.1) ) self.wait() self.play(LaggedStart(*[ ApplyMethod(bit.move_to, box) for bit, box in zip(bits, message_boxes) ], run_time=4, lag_ratio=0.3)) self.wait() # Organize bits properly bit_template = bits[0].copy() if get_bit_mob_value(bit_template) == 1: toggle_bit(bit_template) new_bits = [None] * 16 for i in [0, 1, 2, 4, 8]: new_bits[i] = bit_template.copy() new_bits[i].move_to(boxes[i]) bits_iter = iter(bits) for i, new_bit in enumerate(new_bits): if new_bit is None: new_bits[i] = next(bits_iter) bits = VGroup(*new_bits) # Show parity groups boxes.save_state() self.add(boxes, pos_labels, bits) for bit in bits: for part in bit: if part.get_fill_opacity() > 0: part.set_fill(opacity=1) bit.save_state() VGroup(*bits[:3], bits[4], bits[8]).set_opacity(0) for n in range(N): boxes.generate_target() boxes.target.set_fill(BLACK, 0) get_bit_n_subgroup(boxes.target, n).set_fill(BLUE, 0.8) for k in range(n): boxes.target[2**k].set_fill(GREEN, 0.5) one_rects = get_one_rects(get_bit_n_subgroup(bits, n)) counter = get_ones_counter(boxes[10:12], one_rects, buff=1.5) counter.match_height(bits[0]) self.play(MoveToTarget(boxes)) self.add(counter) self.play(ShowIncreasingSubsets(one_rects)) self.wait() self.play(Restore(bits[2**n])) if counter.get_value() % 2 == 1: rect_copy = one_rects[0].copy() rect_copy.move_to(bits[2**n]) one_rects.add(rect_copy) bits[2**n][0].set_opacity(1) toggle_bit(bits[2**n]) self.add(rect_copy) self.wait() self.play( LaggedStartMap(FadeOut, VGroup(*one_rects, counter), run_time=1), ) self.play(Restore(boxes)) # Final parity check one_rects = get_one_rects(bits) counter = get_ones_counter(boxes[10:12], one_rects, buff=1.5) counter.match_height(bits[0]) self.add(counter) self.play(ShowIncreasingSubsets(one_rects)) self.wait() self.play(Restore(bits[0])) self.play(LaggedStartMap(FadeOut, VGroup(*one_rects, counter))) self.wait() # Send as a message block_group = VGroup(boxes, pos_labels, bits) pis, names = get_sender_and_receiver() randy, morty = pis line = Line(randy.get_corner(UR), morty.get_corner(UL), buff=MED_SMALL_BUFF) line.add( Dot().move_to(line.get_start(), RIGHT), Dot().move_to(line.get_end(), LEFT), ) line.set_stroke(GREY, 2) line_label = OldTexText("Noisy channel") line_label.next_to(line, DOWN, SMALL_BUFF) line_label.set_color(RED) self.play( VFadeIn(pis), FadeIn(names, DOWN), randy.change, "raise_right_hand", block_group.set_height, 1, block_group.move_to, randy.get_corner(UR), DOWN, block_group.shift, 0.1 * UP, ) self.play( ShowCreation(line), Write(line_label) ) self.play(Blink(randy)) self.play( block_group.match_x, line, randy.change, "happy", morty.eyes, ) # Possible changes black_box = SurroundingRectangle(block_group, buff=0) black_box.set_fill(GREY_D, 1) black_box.set_stroke(WHITE, 2) change_words = VGroup( OldTexText("Maybe flip 0 bits"), OldTexText("Maybe flip 1 bit"), OldTexText("Maybe flip 2 bits"), ) colors = [WHITE, RED_B, RED] for word, color in zip(change_words, colors): word.next_to(black_box, UP) word.set_color(color) morty_arrow = Vector(DOWN) morty_arrow.next_to(morty, UP) self.play( GrowArrow(morty_arrow), morty.change, "pondering", morty_arrow ) self.play(ShowCreationThenFadeAround(morty)) self.play(Blink(morty)) self.wait() self.play( morty_arrow.next_to, block_group, UP, FadeIn(black_box), morty.look_at, black_box, ) self.play(Blink(randy)) self.wait() self.play(Blink(randy)) self.play( FadeIn(change_words[0], 0.25 * DOWN), FadeOut(morty_arrow, UP), morty.change, "confused", change_words[0], ) for i in [1, 2]: self.play( FadeIn(change_words[i], 0.25 * DOWN), change_words[:i].shift, UP, ) self.wait() self.play(Blink(morty)) error_pos = 10 toggle_bit(bits[error_pos]) self.add(block_group, black_box) self.play( FadeOut(black_box), FadeOut(change_words), ) self.play( block_group.set_x, line.get_end()[0], morty.change, "pondering", line.get_end() + UP, ) self.play( Uncreate(line), FadeOut(line_label, DOWN), FadeOut(randy, DL), FadeOut(morty, DR), FadeOut(names, DOWN), block_group.set_height, 5, block_group.set_y, 0, block_group.to_edge, RIGHT, ) self.wait() # Try it! try_it_words = OldTexText("Try it\\\\yourself!") try_it_words.scale(2) try_it_words.next_to(boxes, LEFT, buff=2) self.play(FadeIn(try_it_words, RIGHT)) self.wait() self.play(FadeOut(try_it_words, LEFT)) # Do parity checks working_grid = boxes.copy() working_grid.to_edge(LEFT) working_grid_words = OldTexText("Possibilities") working_grid_words.set_color(BLUE) working_grid_words.next_to(working_grid, UP) working_grid.set_fill(BLUE, 0.7) working_pos_labels = get_grid_position_labels(working_grid) counter = Integer(0) counter.set_height(0.7) counter.set_color(YELLOW) counter.next_to(boxes, LEFT, MED_LARGE_BUFF) counter.counted = VGroup() counter.add_updater(lambda m: m.set_value(len(m.counted))) for n in range(N): off_bits = get_bit_n_subgroup(bits, n, 0) on_bits = get_bit_n_subgroup(bits, n, 1) rects = get_one_rects(on_bits) counter.counted = rects self.play(FadeOut(off_bits)) self.add(counter) self.play(ShowIncreasingSubsets(rects)) to_fade = get_bit_n_subgroup(working_grid, n, 1 - (len(rects) % 2)) if n == 0: to_fade.set_fill(BLACK, 0) self.play( FadeIn(working_grid), FadeIn(working_pos_labels), FadeIn(working_grid_words), ) else: self.play(to_fade.set_fill, BLACK, 0) self.wait() self.play( FadeOut(counter), FadeOut(rects), FadeIn(off_bits), ) # Move working grid self.add(working_grid, block_group) self.play( ApplyMethod(working_grid.move_to, boxes, run_time=2), FadeOut(working_grid_words), FadeOut(working_pos_labels), ) # Full parity check rects = get_one_rects(bits) counter.counted = rects self.add(counter) self.play(ShowIncreasingSubsets(rects)) self.wait() self.play(FadeOut(rects), FadeOut(counter)) # Correct error bit self.play(toggle_bit_anim(bits[error_pos])) self.play(FadeOut(working_grid)) self.wait() # Show 11 message bits block_group.generate_target() block_group.target.center() block_group.target.to_edge(DOWN) VGroup(*[ block_group.target[2][i] for i in [0, 1, 2, 4, 8] ]).set_color(GREY_C) self.play(MoveToTarget(block_group)) message_bits = VGroup(*[ bit for i, bit in enumerate(bits) if i not in [0, 1, 2, 4, 8] ]) message_bits.generate_target() message_bits.target.arrange(RIGHT, buff=SMALL_BUFF) message_bits.target.to_edge(UP) for mb, mt in zip(message_bits, message_bits.target): mb.target = mt self.play(LaggedStartMap( MoveToTarget, message_bits, lag_ratio=0.3, run_time=4, )) self.wait() def old_parity_checks(self): questions = VGroup(*[boxes.copy() for x in range(4)]) questions.set_height(1) questions.arrange(DOWN, buff=0.5) questions.set_height(6) questions.to_edge(LEFT, buff=1) counter = Integer(0, color=YELLOW) counter.match_height(bits[0]) counter.next_to(boxes, LEFT, LARGE_BUFF) boxes.save_state() self.add(boxes, pos_labels, bits) results = VGroup() for n, question in enumerate(questions): question.set_fill(BLACK, 0) get_bit_n_subgroup(question, n).set_fill(BLUE, 0.7) one_rects = get_one_rects(get_bit_n_subgroup(bits, n)) counter.set_value(len(one_rects)) boxes.generate_target() boxes.target.match_style(question) self.play(MoveToTarget(boxes)) self.play(FadeIn(one_rects)) if counter.get_value() % 2 == 0: result = Integer(0, color=GREEN) else: result = Integer(1, color=RED) result.next_to(question, RIGHT) results.add(result) counter_mover = counter.copy() counter_mover.generate_target() counter_mover.target.replace(result, stretch=True) counter_mover.target.fade(1) result.save_state() result.replace(counter, stretch=True) result.fade(1) self.play( ReplacementTransform(boxes.copy().set_fill(opacity=0), question), MoveToTarget(counter_mover, remover=True), Restore(result), FadeOut(one_rects), FadeOut(counter), ) self.wait() one_rects = get_one_rects(bits) counter.set_value(len(one_rects)) words = OldTexText("Likely one error") words.next_to(counter, DOWN, LARGE_BUFF, aligned_edge=RIGHT) self.play( boxes.set_fill, BLACK, 0, FadeIn(counter), FadeIn(one_rects), ) self.wait() self.play(FadeIn(words, 0.1 * UP)) self.wait() self.play( FadeOut(VGroup(counter, words, one_rects), lag_ratio=0.2) ) # Read result final_result = results.copy() final_result.arrange(LEFT, buff=SMALL_BUFF) equation = VGroup( final_result, OldTex("\\rightarrow"), Integer(10) ) equation.arrange(RIGHT) equation.to_edge(UP) self.play(TransformFromCopy(results, final_result, run_time=3, lag_ratio=0.3)) self.play( Write(equation[1]), FadeIn(equation[2], LEFT), ) self.wait() boxes.generate_target() boxes.target[10].set_fill(BLUE, 0.7) self.play(MoveToTarget(boxes)) self.play(toggle_bit_anim(bits[10])) self.wait() self.play( LaggedStartMap( FadeOut, VGroup(*equation, *questions, *results), lambda m: (m, DOWN), ), Restore(boxes), ) class ByHandVsSoftwareVsHardware(Scene): def construct(self): self.add(get_background(GREY_E)) rects = VGroup(*[ScreenRectangle() for x in range(3)]) rects.set_stroke(GREY_B) rects.set_fill(BLACK, 1) rects.arrange(RIGHT, buff=MED_LARGE_BUFF) rects.set_width(FRAME_WIDTH - 1) rects[0].shift(UP) rects[2].shift(DOWN) self.add(rects) labels = VGroup( OldTexText("By hand"), OldTexText("In software"), OldTexText("In hardware"), ) for label, rect in zip(labels, rects): label.next_to(rect, DOWN) randy = Randolph(height=1.25) randy.next_to(rects[0], UP, SMALL_BUFF) self.play( LaggedStartMap( FadeIn, labels, lambda m: (m, 0.5 * UP), lag_ratio=0.4, ), randy.change, 'thinking', rects[0], ) self.play(Blink(randy)) self.wait() randy.generate_target() randy.target.next_to(rects[1], UP, SMALL_BUFF) randy.target.change("hooray", rects[1]) self.play( MoveToTarget(randy, path_arc=-45 * DEGREES) ) self.play(Blink(randy)) self.play(randy.change, 'thinking', rects[1]) self.play(Blink(randy)) self.wait() class EndScreen(Scene): def construct(self): self.add(get_background(GREY_E)) rects = VGroup(*[ScreenRectangle() for x in range(2)]) rects.set_stroke(WHITE, 1) rects.set_fill(BLACK, 1) rects.set_height(3) rects.arrange(RIGHT, buff=1) rects.shift(UP) self.add(rects) labels = VGroup( OldTexText("Part 2\\\\", "the elegance of it all"), OldTexText("Ben Eater\\\\", "doing this on breadboards"), ) for label, rect in zip(labels, rects): label[0].scale(1.5, about_edge=DOWN) label.scale(0.9) label.next_to(rect, DOWN) self.add(labels) self.add(AnimatedBoundary(rects[0])) self.wait() self.add(AnimatedBoundary(rects[1])) self.wait(19) # Part 2 class Thumbnail2(AltThumbnail): def construct(self): self.add(self.get_background()) # Test # code = ImageMobject("HammingCodeOneLine") code = Code(""" reduce( lambda x, y: x^y, (i for (i, bit) in enumerate(block) if bit) ) """, alignment="LEFT") code.set_width(FRAME_WIDTH - 3) br = SurroundingRectangle(code, buff=MED_SMALL_BUFF) br.set_fill(BLACK, 1) br.set_stroke(GREY_B, 2) code = Group(br, code) code.set_width(10) code.to_edge(DOWN) self.add(code) words = Text("One line", font_size=90) words.next_to(code, UP) words.set_stroke(BLACK, 20, background=True) self.add(words) class Part1Wrapper(Scene): def construct(self): self.add(get_background()) rect = ScreenRectangle() rect.set_fill(BLACK, 1) rect.set_stroke(GREY_B, 2) rect.set_height(6) rect.to_edge(DOWN) title = OldTexText("Part 1") title.set_height(0.7) title.to_edge(UP) self.add(rect) self.add(AnimatedBoundary(rect, max_stroke_width=2, cycle_rate=0.25)) self.play(Write(title)) self.wait(35) class AskHowItsImplemented(TeacherStudentsScene): def construct(self): self.student_says("How do you\\\\implement this?") self.play( self.teacher.change, "happy", self.change_students("pondering", "confused"), ) self.look_at(self.screen) self.wait(6) class ScaleUp(Scene): def construct(self): square_template = Square() square_template.set_stroke(GREY_B, 2) square_template.set_height(1) zero = Integer(0) one = Integer(1) last_grid = None last_parity_groups = None last_words = None for N in range(4, 13): grid = VGroup(*[square_template.copy() for x in range(2**N)]) grid.arrange_in_grid( 2**int(math.floor(N / 2)), 2**int(math.ceil(N / 2)), buff=0 ) grid.set_width(5.5) if N > 8: grid.set_stroke(width=1) elif N > 10: grid.set_stroke(width=0.25) grid.set_stroke(background=True) grid[0].set_fill(YELLOW, 0.6) for n in range(N): grid[2**n].set_fill(GREEN, 0.7) parity_groups = VGroup() for n in range(N): group = grid.copy() group.set_fill(BLACK, 0) get_bit_n_subgroup(group, n).set_fill(BLUE, 0.8) parity_groups.add(group) parity_groups.arrange_in_grid(n_cols=2, buff=1.5) parity_groups.set_width(5) max_height = 7 if parity_groups.get_height() > max_height: parity_groups.set_height(max_height) parity_groups.to_edge(RIGHT, buff=0.5) random.seed(0) for square in grid: bit = random.choice([zero, one]).copy() bit.replace(square, dim_to_match=1) bit.scale(0.5) square.add(bit) redun = "{:.3}".format((N + 1) / (2**N)) words = OldTex( f""" {{ {{{N + 1}}} \\text{{ parity bits}} \\over {2**N} \\text{{ bits per block}} }} \\approx {redun} """, tex_to_color_map={ f"{{{N + 1}}}": GREEN, f"{2**N}": WHITE, f"{redun}": YELLOW, }, fill_color=GREY_A ) words.to_corner(UL, buff=MED_SMALL_BUFF) grid.next_to(words, DOWN, aligned_edge=LEFT) if last_grid is None: self.add(grid) self.add(parity_groups) self.add(words) else: self.play( ReplacementTransform(last_grid, grid[:2**(N - 1)]), FadeIn(grid[2**(N - 1):], lag_ratio=0.1, run_time=2), FadeOut(last_parity_groups), LaggedStartMap(FadeIn, parity_groups, lag_ratio=0.2, run_time=2), FadeOut(last_words, UP), FadeIn(words, DOWN), ) self.wait() last_grid = grid last_parity_groups = parity_groups last_words = words class MillionRatio(Scene): def construct(self): # Largely copied from above N = 20 words = OldTex( """ {21 \\text{ parity bits} \\over 1{,}048{,}576 \\text{ bits per block} } \\approx 0.00002 """, tex_to_color_map={ "21": GREEN, "1{,}048{,}576": WHITE, "0.00002": YELLOW, }, fill_color=GREY_A ) words.to_corner(UL, buff=MED_SMALL_BUFF) self.add(words) st = Square() st.set_stroke(GREY, 0.5) grid = VGroup(*[st.copy() for x in range(2**(16))]) grid.arrange_in_grid(buff=0) grid.set_height(6) grid.next_to(words, DOWN, aligned_edge=LEFT) self.add(grid) k = 17 positions = VGroup(*[ OldTex(int_to_bit_string(n, n_bits=20)) for n in [*range(k), *range(2**N - k // 2, 2**N)] ]) positions.replace_submobject(-k // 2, OldTex("\\vdots")) positions.arrange(DOWN) positions.set_height(7) positions.to_edge(RIGHT) for n in [0, 1, 2, 4, 8, 16]: positions[n].set_color(GREEN_B) brace = Brace(positions, LEFT, buff=SMALL_BUFF) p_label = OldTexText("$2^{20}$\\\\positions") p_label.next_to(brace, LEFT, SMALL_BUFF) self.play( ShowIncreasingSubsets(positions, run_time=3), GrowFromPoint(brace, brace.get_top(), run_time=3, rate_func=squish_rate_func(smooth, 0.5, 1)), FadeIn(p_label, 0.5 * RIGHT, run_time=3, rate_func=squish_rate_func(smooth, 0.5, 1)), ) self.wait() grid.set_stroke(background=True) for n in range(16): grid.set_fill(BLACK, 0) get_bit_n_subgroup(grid, n).set_fill(BLUE, 0.8) self.wait(0.5) class BurstErrors(Scene): def construct(self): # Setup bl = 8 nb = 4 bits = get_bit_grid(1, bl * nb, bits=string_to_bits("3b1b")) bits.set_height(0.5) bits.arrange(RIGHT, buff=SMALL_BUFF) bits.move_to(DOWN) self.add(bits) colors = [BLUE, YELLOW, MAROON_B, TEAL] block_words = VGroup(*[ OldTexText(f"Block {n}", fill_color=color) for n, color in zip(range(nb), colors) ]) block_words.set_height(0.5) block_words.arrange(RIGHT, buff=LARGE_BUFF) block_words.move_to(2 * UP) self.add(block_words) # Add lines lines = VGroup() for n, bit in enumerate(bits): words = block_words[n // bl] line = Line() line.match_color(words) line.set_stroke(width=2) line.words = words line.bit = bit bit.line = line underline = Underline(bit) underline.set_stroke(words.get_color(), 4) bit.add(underline) line.add_updater(lambda m: m.put_start_and_end_on( m.words.get_bottom() + SMALL_BUFF * DOWN, m.bit.get_top(), )) lines.add(line) self.play(LaggedStartMap(ShowCreation, lines, suspend_mobject_updating=True)) self.wait() # Show burst error error_bits = bits[9:13] error_words = OldTexText("Burst of errors") error_words.next_to(error_bits, DOWN) error_words.set_color(RED) ruined_words = OldTexText("Ruined") ruined_words.set_color(RED) ruined_words.next_to(block_words[1], UP) strike = Line(LEFT, RIGHT) strike.replace(block_words[1]) strike.set_color(RED) self.play( LaggedStartMap(toggle_bit_anim, error_bits, target_color=RED), LaggedStart(*map(zap_anim, error_bits)), Write(error_words) ) self.play( ShowCreation(strike), FadeIn(ruined_words, 0.5 * DOWN) ) self.wait() self.play( FadeOut(ruined_words, 0.2 * UP), FadeOut(error_words, 0.2 * DOWN), FadeOut(strike), LaggedStartMap(toggle_bit_anim, error_bits, target_color=WHITE), run_time=1, ) for bit in error_bits: bit[-1].set_color(YELLOW) # Rearrange new_order = VGroup() for i in range(bl): for j in range(nb): new_order.add(bits[bl * j + i]) new_order.generate_target() new_order.target.arrange(RIGHT, buff=SMALL_BUFF) new_order.target.replace(bits) self.play(MoveToTarget(new_order, run_time=3, path_arc=30 * DEGREES)) self.wait() # New burst error_bits = new_order[9:13] self.play( LaggedStartMap(toggle_bit_anim, error_bits, target_color=RED), LaggedStart(*map(zap_anim, error_bits)), Write(error_words), ) non_error_lines = VGroup() for line in lines: if line.bit not in error_bits: non_error_lines.add(line) self.play(non_error_lines.set_stroke, {"width": 1, "opacity": 0.5}) self.wait() error_words = VGroup(*[TexText("1 error", fill_color=GREEN) for x in range(4)]) for ew, bw in zip(error_words, block_words): ew.next_to(bw, UP, MED_LARGE_BUFF) self.play(LaggedStartMap(FadeIn, error_words, lambda m: (m, DOWN))) self.wait() class BinaryCounting(Scene): def construct(self): def get_bit_grids(bit_values): left_bits = get_bit_grid(4, 1, buff=LARGE_BUFF, bits=bit_values, height=6) left_bits.move_to(3 * LEFT) right_bits = get_bit_grid(1, 4, buff=SMALL_BUFF, bits=bit_values, height=0.6) right_bits.set_submobjects(list(reversed(right_bits))) right_bits.move_to(RIGHT + 2 * UP) return VGroup(left_bits, right_bits) bit_grids = get_bit_grids([0, 0, 0, 0]) brace = Brace(bit_grids[1], UP) counter = Integer(0, edge_to_fix=ORIGIN) counter.match_height(bit_grids[1]) counter.set_color(BLUE) counter.next_to(brace, UP) boxes = VGroup(*[Square() for x in range(16)]) boxes.arrange_in_grid(4, 4, buff=0) boxes.set_height(4) boxes.next_to(bit_grids[1], DOWN, LARGE_BUFF) boxes.set_stroke(GREY_B, 2) pos_labels = get_grid_position_labels(boxes) self.add(bit_grids) self.add(brace) self.add(counter) self.add(boxes) self.add(pos_labels) for n in range(16): bit_values = list(map(int, int_to_bit_string(n, n_bits=4))) boxes.generate_target() boxes.target.set_fill(BLACK, 0) boxes.target[n].set_fill(BLUE, 0.8) anims = [ ChangeDecimalToValue(counter, n), MoveToTarget(boxes) ] for grid in bit_grids: for bit, bv in zip(grid, reversed(bit_values)): if get_bit_mob_value(bit) != bv: anims.append(toggle_bit_anim(bit)) self.play(*anims, run_time=0.5) self.wait() class ReviewOfXOR(Scene): CONFIG = { "random_seed": 2, } def construct(self): # Setup equations xor = get_xor() equations = VGroup() for n in range(4): bits = list(map(int, int_to_bit_string(n, n_bits=2))) equation = VGroup( Integer(bits[0]), xor.copy(), Integer(bits[1]), OldTex("="), Integer(op.xor(*bits)), ) equation.set_height(0.6) equation.arrange(RIGHT) equations.add(equation) equations.arrange(DOWN, buff=LARGE_BUFF) # Intro xor equation = equations[1] equation.save_state() equation.center() equation[3:].set_opacity(0) arrow = Vector(0.7 * DOWN) arrow.next_to(equation[1], UP, SMALL_BUFF) xor_word = OldTexText("xor") xor_word_long = OldTexText("``exclusive or''") xor_words = VGroup(xor_word, xor_word_long) xor_words.scale(1.5) xor_words.match_color(xor) xor_words.next_to(arrow, UP) self.add(equation) self.play( FadeIn(equation[1], 0.5 * UP), GrowArrow(arrow), Write(xor_word), ) self.wait() self.play( xor_word.next_to, xor_word_long, UP, MED_SMALL_BUFF, FadeIn(xor_word_long, DOWN), ) self.wait() self.play( FadeOut(arrow), xor_words.to_corner, UL, Restore(equation), FadeIn(equations[2], UP), ) self.wait() self.play( FadeIn(equations[0], DOWN), FadeIn(equations[3], UP), ) self.wait() # Parity of two bits parity_words = OldTexText("Parity of\\\\two bits") parity_words.set_color(YELLOW) parity_words.scale(1.5) parity_words.to_edge(RIGHT, buff=MED_LARGE_BUFF) arrows = VGroup() for equation in equations: globals()['equation'] = equation new_arrows = VGroup(*[ Arrow(equation[i].get_top(), equation[4].get_top(), path_arc=-60 * DEGREES) for i in [0, 2] ]) new_arrows.set_color(YELLOW) arrows.add(new_arrows) self.play( LaggedStartMap(DrawBorderThenFill, arrows), FadeIn(parity_words) ) self.wait() # Addition mod 2 mod2_words = OldTexText("Addition\\\\mod 2") mod2_words.scale(1.5) mod2_words.move_to(parity_words, RIGHT) mod2_words.set_color(BLUE) self.play( FadeIn(mod2_words, DOWN), FadeOut(parity_words, UP), FadeOut(arrows) ) self.wait() # xor of two bit strings row_len = 8 bit_strings = VGroup(*[ Integer(random.choice([0, 1]), edge_to_fix=ORIGIN) for x in range(row_len * 3) ]) bit_strings.arrange_in_grid( 3, row_len, h_buff=SMALL_BUFF, v_buff=MED_LARGE_BUFF, fill_rows_first=False ) bit_strings.scale(equation[0][0].get_height() / bit_strings[0].get_height()) rows = VGroup(*[bit_strings[i::3] for i in range(3)]) rows[0].next_to(rows[1], UP, buff=0.25) line = Line(LEFT, RIGHT) line.set_width(bit_strings.get_width() + 1) line.move_to(bit_strings[-2:], RIGHT) line.set_stroke(GREY_B, 3) line_xor = xor.copy() line_xor.set_height(0.5) line_xor.next_to(line, UP, aligned_edge=LEFT) for b1, b2, b3 in zip(*[row for row in rows]): b3.set_value(b1.get_value() ^ b2.get_value()) b2.match_x(b1) b3.match_x(b1) equations.generate_target() for n, eq in enumerate(equations.target): for k, b1 in enumerate(eq[0::2]): target_bit = bit_strings[3 * n + k] target_bit.set_value(b1.get_value()) b1.become(target_bit) eq[1].become(line_xor) eq[3].fade(1) self.play( MoveToTarget(equations, run_time=2), FadeOut(mod2_words), FadeIn(bit_strings[12:], run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1), lag_ratio=0.1), ShowCreation(line, run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1)) ) self.remove(equations) self.add(bit_strings, line_xor) self.wait() # Highlight columns last_rect = VMobject() for b1, b2, b3 in zip(*[row for row in rows]): rect = SurroundingRectangle(VGroup(b1, b2, b3), buff=SMALL_BUFF) rect.set_stroke(BLUE, 2) self.play(FadeIn(rect), FadeOut(last_rect)) last_rect = rect self.play(FadeOut(last_rect)) # Add more rows new_rows = VGroup(*[rows[0].copy() for x in range(3)]) new_rows.arrange(DOWN, buff=0.2) new_rows.next_to(rows, UP, buff=0.2) for row in new_rows: for bit in row: bit.set_value(random.choice([0, 1])) self.play( LaggedStartMap(FadeIn, new_rows, lambda m: (m, DOWN)), FadeOut(xor_words), FadeOut(rows[2]) ) # Compute parities parity_words = OldTexText("Computes\\\\parity\\\\of each\\\\column", alignment="") parity_words.set_color(YELLOW) parity_words.to_corner(UL) self.add(parity_words) for tup in zip(*[*new_rows, *rows]): rects = VGroup() for bit in tup[:-1]: if bit.get_value() == 1: rect = SurroundingRectangle(bit) rect.set_stroke(YELLOW, 2) rect.set_fill(YELLOW, 0.5) rects.add(rect) tup[-1].set_value(len(rects) % 2) tup[-1].set_color(YELLOW) self.add(rects, *tup) self.wait() self.remove(rects) self.wait() # Simpler sum self.play(FadeOut( VGroup(new_rows, rows[0][4:], rows[1][4:], rows[2][4:]), lag_ratio=0.1, )) for b1, b2, b3 in zip(*[row[:4] for row in rows]): b3.set_value(b1.get_value() ^ b2.get_value()) self.wait(0.25) arrows = VGroup() integers = VGroup() for row, n in zip(rows, [3, 5, 6]): arrow = Vector(0.75 * RIGHT) arrow.next_to(row[:4], RIGHT, buff=0.2) integer = Integer(n) integer.match_height(row[0]) integer.match_color(row[0]) integer.next_to(arrow, RIGHT, buff=0.2) self.play( GrowArrow(arrow), FadeIn(integer, LEFT) ) arrows.add(arrow) integers.add(integer) class ButWhy(TeacherStudentsScene): def construct(self): self.student_says( "Hang on...\\\\why?", target_mode="confused", added_anims=[self.teacher.change, "tease"] ) self.play_student_changes( "maybe", "erm", "confused", look_at=self.screen, ) self.wait(6) class WhyPointToError(Scene): def construct(self): rect = SurroundingRectangle(OldTexText("0000").scale(2)) rect.to_edge(RIGHT) rect.set_stroke(RED, 3) words = OldTexText("Why do these\\\\point to an error?") arrow = Vector(0.7 * RIGHT) arrow.next_to(rect, LEFT) words.next_to(arrow, LEFT) words.set_color(RED) bit = Integer(0).scale(2) bit.next_to(words, UP, buff=0.45) bit.shift(1.11 * words.get_width() * LEFT) self.play( Write(words), ShowCreation(rect), ) self.play(GrowArrow(arrow)) self.wait() self.play( rect.become, SurroundingRectangle(bit).match_style(rect), FadeOut(arrow) ) self.wait() class SimplePointer(Scene): def construct(self): arrow = Arrow(ORIGIN, [-4, 1.5, 0]) arrow.center() arrow.set_fill(GREY_B) self.play(DrawBorderThenFill(arrow)) self.wait() class ArrowPair(Scene): def construct(self): arrows = VGroup( Vector(LEFT), Vector(LEFT), ) arrows.scale(1.5) arrows.arrange(DOWN, buff=2) arrows[0].shift(4 * LEFT) arrows.set_fill(YELLOW) self.play(*map(GrowArrow, arrows)) self.wait() class PythonXorExample(ExternallyAnimatedScene): pass class HammingCodesWithXOR(Scene): def construct(self): # Setup bits = get_bit_grid(4, 4, bits=string_to_bits(":)")) bits.to_edge(LEFT, buff=1.5) boxes = get_bit_grid_boxes(bits) block = VGroup(boxes, bits) block.set_height(6) for bit in bits: bit.set_height(0.7) bin_pos_labels = VGroup() dec_pos_labels = VGroup() for n, box, bit in zip(it.count(), boxes, bits): bin_label = VGroup( *[Integer(int(c)) for c in int_to_bit_string(n, n_bits=4)] ) bin_label.arrange(RIGHT, buff=SMALL_BUFF, aligned_edge=DOWN) bin_label.set_color(GREY_B) bin_label.set_width(0.7 * box.get_width()) bin_label.move_to(box, DOWN) bin_label.shift(SMALL_BUFF * UP) bin_pos_labels.add(bin_label) dec_label = Integer(n) dec_label.match_height(bin_label) dec_label.match_style(bin_label[0]) dec_label.move_to(bin_label, DR) dec_pos_labels.add(dec_label) bit.generate_target() bit.target.scale(0.9) bit.target.move_to(box, UP) bit.target.shift(MED_SMALL_BUFF * DOWN) # Enumerate self.add(block) kw = {"lag_ratio": 0.3, "run_time": 2} self.play(LaggedStartMap(FadeIn, dec_pos_labels, **kw)) self.wait() kw["lag_ratio"] = 0.1 self.play( LaggedStartMap(FadeOut, dec_pos_labels, **kw), LaggedStartMap(FadeIn, bin_pos_labels, **kw), LaggedStartMap(MoveToTarget, bits, **kw), ) self.wait() # Highlight ones summands = VGroup() for bit, box, label in zip(bits, boxes, bin_pos_labels): for mob in bit, box, label: mob.save_state() mob.generate_target() if get_bit_mob_value(bit) == 1: box.target.set_fill(BLUE, 0.7) summands.add(label.copy()) else: bit.target.fade(0.5) label.target.fade(0.5) self.play(*[ LaggedStartMap(MoveToTarget, mob, lag_ratio=0.02) for mob in [boxes, bits, bin_pos_labels] ]) self.wait() # Arrange sum summands.generate_target() summands.target.arrange(DOWN, buff=SMALL_BUFF) summands.target.set_width(1.5) summands.target.set_color(WHITE) summands.target.to_edge(RIGHT, buff=1.5) summands.target.to_edge(UP) line = Line(LEFT, RIGHT) xor = get_xor() line.set_width(summands.target.get_width() + 0.75) line.next_to(summands.target, DOWN, aligned_edge=RIGHT, buff=SMALL_BUFF) xor.next_to(line, UP, aligned_edge=LEFT) self.play( MoveToTarget(summands, run_time=2), ShowCreation(line), ShowCreation(xor), ) self.wait() # Perform xor result = VGroup() rect_columns = VGroup() for tup in zip(*summands): rects = get_one_rects(tup) result_bit = get_bit_grid(1, 1, bits=[len(rects) % 2])[0] result_bit.replace(tup[-1], dim_to_match=1) result_bit.shift(1.5 * result_bit.get_height() * DOWN) result_bit.set_color(YELLOW) result.add(result_bit) rect_columns.add(rects) pre_result = VGroup() for summand in summands: pr = result.copy() pr.save_state() pr.move_to(summand) pr.fade(1) pre_result.add(pr) self.play(LaggedStartMap(Restore, pre_result, lag_ratio=0.05, remover=True)) self.add(result) self.wait() self.play(ShowCreationThenFadeOut(SurroundingRectangle(result, stroke_color=BLUE))) self.wait() for n, rects, result_bit in zip(it.count(), reversed(rect_columns), reversed(result)): faders = VGroup() for bit_vect in [*summands, result]: for k, bit in enumerate(reversed(bit_vect)): if k != n: bit.generate_target() bit.target.fade(0.7) faders.add(bit) for group in bits, bin_pos_labels: sg = get_bit_n_subgroup(group, n, 0) sg.generate_target() sg.target.fade(1) faders.add(sg) faders.save_state() self.play(LaggedStartMap(MoveToTarget, faders, lag_ratio=0, run_time=1)) new_rects = VGroup() for bit, pos in zip(get_bit_n_subgroup(bits, n), get_bit_n_subgroup(bin_pos_labels, n)): if get_bit_mob_value(bit) == 1: nr = SurroundingRectangle(pos[3 - n], buff=0.05) nr.set_fill(YELLOW, 0.25) new_rects.add(nr) self.play( ShowIncreasingSubsets(rects), ShowIncreasingSubsets(new_rects), ) self.wait() self.play( faders.restore, FadeOut(rects), FadeOut(new_rects), ) self.wait() # Sender manipulations (Doing more by hand than should here...sorry) parity_highlights = VGroup(*[boxes[2**n].copy() for n in range(4)]) parity_highlights.set_stroke(GREEN, 8) parity_highlights.set_fill(BLACK, 0) self.play(ShowCreation(parity_highlights)) words = OldTexText("Try to make\\\\this 0000") words.set_color(GREEN) words.next_to(boxes, RIGHT, MED_LARGE_BUFF) words.to_edge(DOWN, buff=1) arrow = Arrow(words.get_right(), result.get_left(), buff=0.1) arrow.get_lp = words.get_right arrow.get_rp = result.get_left arrow.add_updater(lambda m: m.put_start_and_end_on( m.get_lp() + SMALL_BUFF * RIGHT, m.get_rp() + SMALL_BUFF * LEFT, )) self.play( Write(words), DrawBorderThenFill(arrow), ) self.wait() strike = Cross(summands[0]) strike.set_stroke(RED, 8) self.play(ShowCreation(strike)) self.add(summands[0], strike) bits[2].generate_target() toggle_bit(bits[2].target) bits[2].target.fade(0.5) self.play( boxes[2].set_fill, BLACK, 0, MoveToTarget(bits[2]), bin_pos_labels[2].fade, 0.5, toggle_bit_anim(result[2]), FadeOut(summands[0]), FadeOut(strike), ) summands.remove(summands[0]) self.wait() toggle_bit(bits[8].saved_state) self.play( boxes[8].set_fill, BLUE, 0.7, Restore(bits[8]), Restore(bin_pos_labels[8]), ) new_term = bin_pos_labels[8].copy() new_term.generate_target() new_term.target.set_color(WHITE) new_term.target.replace(summands[2]) self.play( MoveToTarget(new_term), summands[:3].move_to, summands[1], DOWN, ) self.play(toggle_bit_anim(result[0])) self.wait() summands.set_submobjects([*summands[:3], new_term, *summands[3:]]) self.play(FadeOut(words), FadeOut(arrow), FadeOut(parity_highlights)) # Show 0 -> 1 error pos = 11 self.play( Restore(bits[pos]), Restore(bin_pos_labels[pos]), ) self.play(toggle_bit_anim(bits[pos], target_color=RED)) self.wait() new_term = bin_pos_labels[pos].copy() new_term.generate_target() new_term.target.set_color(RED) new_term.target.replace(summands[5]) bottom_group = VGroup(summands[5:], xor, line, result) bottom_group.save_state() self.play( MoveToTarget(new_term), bottom_group.move_to, summands[6], UR, ) self.wait(0.25) nt_copy = new_term.copy() self.play( nt_copy.replace, result, nt_copy.fade, 1, *[ toggle_bit_anim(b1, path_arc=0) for b1, b2 in zip(result, new_term) if b2.get_value() == 1 ] ) self.remove(nt_copy) self.wait() self.play( Restore(bottom_group), FadeOut(new_term), toggle_bit_anim(bits[pos], target_color=WHITE) ) self.play( bits[pos].fade, 0.5, bin_pos_labels[pos].fade, 0.5, ) # Show 1 -> 0 error pos = 6 self.play( toggle_bit_anim(bits[pos], target_color=RED), zap_anim(bits[pos]), ) self.wait() new_term = bin_pos_labels[pos].copy() new_term.generate_target() new_term.target.set_color(RED) new_term.target.replace(summands[3]) bottom_group = VGroup(summands[3:], xor, line, result) bottom_group.save_state() self.play( MoveToTarget(new_term), bottom_group.move_to, summands[4], UR, ) for bit in result: bit[0].set_opacity(1) bit[1].set_opacity(0) nt_copy = new_term.copy() self.play( nt_copy.move_to, result, nt_copy.fade, 1, *[ toggle_bit_anim(b1, path_arc=0) for b1, b2 in zip(result, new_term) if b2.get_value() == 1 ] ) self.remove(nt_copy) self.wait() brace = Brace(VGroup(summands[2], new_term), LEFT, buff=SMALL_BUFF) brace_bits = summands[2].copy() for bb in brace_bits: bb.set_value(0) brace_bits.next_to(brace, LEFT) self.play(GrowFromCenter(brace)) self.play( Transform(summands[2].copy(), brace_bits, remover=True), ReplacementTransform(new_term.copy(), brace_bits), ) self.wait() arrow = Arrow(result.get_left(), bin_pos_labels[pos].get_corner(DR), path_arc=-30 * DEGREES, buff=0.1) self.play(DrawBorderThenFill(arrow)) self.wait() self.play(toggle_bit_anim(bits[pos], target_color=WHITE)) self.play( Restore(bottom_group), FadeOut(new_term), FadeOut(brace), FadeOut(brace_bits), FadeOut(arrow), ) self.wait() class HammingSyndromePython(ExternallyAnimatedScene): pass class WhatAboutTwoBitDetection(TeacherStudentsScene): def construct(self): self.student_says( "What about\\\\detecting\\\\two bit errors?" ) self.play( self.change_students("angry", "maybe", "raise_left_hand"), self.teacher.change, "guilty", ) self.look_at(self.screen) self.wait(4) self.play(self.teacher.change, "happy") self.play_student_changes("confused", "erm", "pondering") self.wait(3) class ConflictingViewsOnXor(TeacherStudentsScene): def construct(self): self.clear() self.add(self.pi_creatures) self.student_says( "Um...can you\\\\say that again?", target_mode="confused", index=2, added_anims=[self.teacher.change, "guilty"] ) self.play_student_changes("pondering", "pondering", look_at=self.screen) self.wait(2) self.student_says( "Why didn't you\\\\just use xors\\\\from the start?", target_mode="sassy", index=1, ) self.look_at(self.students[1].bubble) self.wait(5) class CompareXorToParityChecks(Scene): def construct(self): # Title bg_rect = FullScreenRectangle() bg_rect.set_fill(GREY_E, 1) bg_rect.set_stroke(width=0) self.add(bg_rect) title = OldTexText("One algorithm, multiple perspectives") title.scale(1.5) title.to_edge(UP) title.add_to_back(Underline(title)) self.add(title) # Options rects = VGroup(*[ScreenRectangle() for x in range(3)]) rects.set_fill(BLACK, 1) rects.set_stroke(GREY_B, 3) rects.set_height(3) rects.arrange(RIGHT, buff=1) rects.shift(-rects[:2].get_center()) labels = VGroup( OldTexText("Multiple parity checks"), OldTexText("One big xor"), OldTexText("Matrix product"), ) for label, rect in zip(labels, rects): label.next_to(rect, DOWN) labels.set_color(BLUE) self.add(rects[:2]) self.add(labels[:2]) self.play(Write(title, run_time=2)) self.wait(2) # Hardware/software labels hw_label = OldTexText("(nicer for hardware)") sw_label = OldTexText("(nicer for software)") for l1, l2 in zip(labels, [hw_label, sw_label]): l2.next_to(l1, DOWN) self.play(FadeIn(hw_label, 0.25 * UP)) self.wait() self.play(FadeIn(sw_label, 0.25 * UP)) self.wait() # Third view icons = Group( ImageMobject("ParityCheckIcon"), ImageMobject("XorViewIcon"), ) for icon, rect in zip(icons, rects): icon.replace(rect) icon.scale(0.95) groups = Group( Group(rects[0], labels[0], icons[0], hw_label), Group(rects[1], labels[1], icons[1], sw_label), Group(rects[2], labels[2]), ) groups.generate_target() groups.target[:2].arrange(DOWN, buff=LARGE_BUFF) groups.target[:2].match_height(groups.target[2]) groups.target[2].next_to(groups.target[:2], RIGHT, LARGE_BUFF) groups.target.set_height(5) groups.target.center() groups.target.to_edge(DOWN, buff=1) groups[2].set_opacity(0) self.play(MoveToTarget(groups)) self.wait() class LogTitle(Scene): def construct(self): title = OldTexText("$\\text{log}_2(256) = 8$ parity checks") title.set_height(0.7) title.to_edge(UP) underline = Underline(title[0][:4]) underline.set_color(YELLOW) self.add(title) self.wait() self.play(ShowCreationThenFadeOut(underline)) self.wait() class MatrixProduct(Scene): def construct(self): title = OldTexText("(7, 4) Hamming code") title.set_height(0.7) title.to_edge(UP) title.set_color(GREY_A) encoder_matrix = np.array([ [1, 1, 0, 1], [1, 0, 1, 1], [1, 0, 0, 0], [0, 1, 1, 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ]) message_matrix = np.array([1, 0, 1, 1]).reshape((4, 1)) result_matrix = np.dot(encoder_matrix, message_matrix) % 2 kw = {"v_buff": 0.6, "h_buff": 0.75} encoder, message, result = [ IntegerMatrix(matrix, **kw) for matrix in [encoder_matrix, message_matrix, result_matrix] ] equation = VGroup( encoder, message, OldTex("="), result ) equation.arrange(RIGHT, buff=MED_LARGE_BUFF) equation.to_edge(LEFT, buff=2) # Labels message_label = OldTexText("Content") message_label.move_to(message) message_label.to_edge(DOWN) message_arrow = Arrow( message_label.get_top(), message.get_bottom(), ) message_label.set_color(YELLOW) message_arrow.set_color(YELLOW) brace = Brace(result, RIGHT) brace_text = brace.get_text("Error-resistant\\\\block") brace.set_color(BLUE) brace_text.set_color(BLUE) # Animate self.add(title) self.add(equation) self.play(FadeIn(message_label, UP), GrowArrow(message_arrow)) self.play(GrowFromCenter(brace), FadeIn(brace_text, LEFT)) equation.set_fill(opacity=0.8) for n in range(encoder.mob_matrix.shape[0]): row = VGroup(*encoder.mob_matrix[n, :]).copy() col = VGroup(*message.elements).copy() rhs = result.mob_matrix[n, 0].copy() mult_group = VGroup(row, col, rhs) mult_group.set_fill(YELLOW, 1) self.play( ShowIncreasingSubsets(row), ShowIncreasingSubsets(col), FadeIn(rhs), ) self.wait() self.remove(mult_group) class TooManyErrorsTripUpHamming(Scene): def construct(self): title = OldTexText( "$>2$ Errors"," $\\Rightarrow$ ", "Invalid decoding" ) title.set_height(0.7) title[2].set_color(RED) title.to_edge(UP) self.add(title) block = get_bit_grid(8, 8, bits=string_to_bits("EpicFail"), height=5.5) block.next_to(title, DOWN, MED_LARGE_BUFF) self.add(block) # Animations errors = random.sample(list(range(64)), 3) kw = {"lag_ratio": 0.5} self.play( LaggedStart(*[ zap_anim(block[pos]) for pos in errors ], **kw), LaggedStart(*[ toggle_bit_anim(block[pos], target_color=RED) for pos in errors ], **kw), ) scanim = scan_anim(block.get_corner(DR) + UR, block, run_time=5, lag_factor=1) self.play(scanim) self.play(ShowCreationThenFadeOut(Underline(title[2], color=RED))) self.wait() class LouisPasteurQuote(Scene): def construct(self): quote = OldTexText("``Luck favors a\\\\prepared mind''") quote.scale(2) quote.set_stroke(BLACK, 8, background=True) self.play(Write(quote)) self.wait() class ReedSolomonPreview(Scene): def construct(self): # Setup title = OldTexText("Reed-Solomon basic idea") title.set_height(0.5) title.to_edge(UP, buff=MED_SMALL_BUFF) axes = Axes( x_range=(-1, 10, 1), y_range=(-1, 8, 1), width=12, height=7, ) axes.to_edge(DOWN, buff=SMALL_BUFF) axes.set_color(GREY_B) cubic = axes.get_graph( lambda x: -0.05 * x * (x - 2) * (x - 4) * (x - 8) + 2 ) cubic.set_stroke(TEAL, 3) self.add(title) self.add(axes) # Data dots = VGroup(*[ Dot(axes.input_to_graph_point(x, cubic)) for x in range(0, 8) ]) dots[:4].set_color(YELLOW) dots[4:].set_color(BLUE) # Input words input_words = OldTexText("Input data") poly_words = OldTexText("Polynomial\\\\fit") redundant_words = OldTexText("Redundancy") input_words.next_to(dots[:4], UP, buff=2) input_words.set_color(YELLOW) input_arrows = VGroup(*[ Arrow(input_words.get_bottom(), dot.get_center()) for dot in dots[:4] ]) input_arrows.set_fill(YELLOW) poly_words.next_to(dots[5], LEFT) poly_words.shift(0.5 * UR) poly_words.match_color(cubic) redundant_words.move_to(dots[4:].get_center(), LEFT) redundant_words.shift(2 * DR + DOWN) redundant_words.set_color(BLUE) redundant_arrows = VGroup(*[ Arrow(redundant_words.get_corner(UL), dot.get_center()) for dot in dots[4:] ]) redundant_arrows.set_color(BLUE) # Animations kw = {"lag_ratio": 0.5} self.play( FadeIn(input_words), LaggedStartMap(FadeIn, dots[:4], lambda m: (m, UP), **kw), LaggedStartMap(GrowArrow, input_arrows, **kw), ) self.add(cubic, *dots[:4]) self.play( ShowCreation(cubic), Write(poly_words) ) self.wait() self.play( FadeIn(redundant_words), LaggedStartMap(FadeIn, dots[4:], lambda m: (m, DR), **kw), LaggedStartMap(GrowArrow, redundant_arrows, **kw), ) self.wait() self.play(LaggedStartMap( FadeOut, VGroup(*reversed(self.mobjects)), lambda m: (m, 0.2 * normalize(m.get_center())), lag_ratio=0.1, run_time=2, )) self.wait() class HammingThinking(Scene): def construct(self): hamming = ImageMobject("Richard_Hamming") hamming.set_height(3) hamming.to_corner(DL) randy = Randolph() randy.set_opacity(0) randy.move_to(hamming) self.add(hamming) self.wait() self.play(PiCreatureBubbleIntroduction( randy, "What's the most efficient\\\\I could conceivably be?", bubble_type=ThoughtBubble, )) self.wait() class RandomWalks(Scene): CONFIG = { "random_seed": 1, } def construct(self): # Setup N_PATHS = 25 frame = self.camera.frame frame.set_height(2 * FRAME_HEIGHT) frame.shift(2 * RIGHT) idea_spot = 10 * RIGHT + 3 * UP idea_dot = Dot(idea_spot) idea_dot.set_color(YELLOW) bulb = Lightbulb() bulb.next_to(idea_dot, UP) start_point = 7 * LEFT + 3 * DOWN start_dot = Dot(start_point, color=WHITE) start_dot.scale(2) self.add(idea_dot, bulb, start_dot) # Paths paths = VGroup(*[VGroup() for n in range(N_PATHS)]) for path in paths: path.add(Line(start_point, start_point)) path.set_stroke(WHITE, 3, 0.5) path_dots = VGroup() for path in paths: # dot = Randolph( # mode="thinking", height=0.25, # # color=random.choice([BLUE_B, BLUE_C, BLUE_D, GREY_BROWN]) # ) dot = Dot(color=BLUE) dot.set_stroke(BLACK, 3, background=True) dot.path = path dot.add_updater(lambda m: m.move_to(m.path[-1].get_end())) path_dots.add(dot) self.add(paths) self.add(path_dots) # Perform search magic_path = None while magic_path is None: new_segments = VGroup() for path in paths: start = path[-1].get_end() # Choose random direction based on loosely sniffing out idea spot R_vect = start - idea_spot R_vect = rotate_vector(10 * R_vect, TAU * random.random()) point = idea_spot + R_vect to_point = point - start angle = angle_of_vector(to_point) if -3 * PI / 2 < angle <= -PI / 2: vect = DOWN elif -PI / 2 < angle <= PI / 2: vect = RIGHT elif PI / 2 < angle <= 3 * PI / 2: vect = UP else: vect = LEFT end = start + vect new_segment = Line(start, end) new_segment.match_style(path) new_segments.add(new_segment) path.add(new_segment) if np.isclose(end, idea_spot).all(): magic_path = path.copy() self.play( LaggedStartMap(ShowCreation, new_segments, lag_ratio=10 / N_PATHS), run_time=0.5, ) self.add(paths) # Highlight magic path magic_path.set_stroke(YELLOW, 5, 1) self.play( paths.fade, 0.7, ShowCreation(magic_path, run_time=2), ) self.wait() fake_path = VMobject() fake_path.start_new_path(start_point) for segment in magic_path: fake_path.add_line_to(segment.get_end()) fake_path.match_style(magic_path) line = Line(start_point, idea_spot) line.match_style(magic_path) line.set_stroke(TEAL, 8) self.add(fake_path, start_dot) self.play( ApplyMethod(magic_path.set_opacity, 0.5), Transform(fake_path, line, run_time=2), paths.fade, 0.5, path_dots.fade, 0.5, ) self.wait(4) class ThinkingInTermsOfBits(Scene): def construct(self): word = OldTexText("Information") word.scale(2) word.next_to(ORIGIN, LEFT, buff=0.7) bits = get_bit_grid(11, 8, bits=string_to_bits("Information")) bits.set_height(6) bits.next_to(ORIGIN, RIGHT, buff=0.7) bits.set_color(GREY_A) for bit in bits: toggle_bit(bit) bits.shuffle() self.add(word) self.add(bits) self.play(LaggedStartMap( toggle_bit_anim, bits, lag_ratio=5 / len(bits), run_time=3, )) self.wait(2) class SimpleHoldUpBackground(TeacherStudentsScene): def construct(self): self.play(self.teacher.change, "raise_right_hand", 3 * UP) self.play_student_changes("pondering", "thinking", "tease", look_at=3 * UP) self.wait(4) self.play_student_changes("tease", "hesitant", "happy", look_at=3 * UP) self.wait(5) class HammingEndScreen(PatreonEndScreen): CONFIG = { "scroll_time": 25 } # Extras class TwoErrorGrids(Scene): def construct(self): grid = VGroup(*[Square() for x in range(16)]) grid.arrange_in_grid(buff=0) grid.set_stroke(WHITE, 1) grid.set_height(1) grids = VGroup(*[grid.copy() for x in range(16)]) grids.arrange_in_grid(buff=MED_LARGE_BUFF) grids.set_height(7) grids.to_edge(RIGHT) self.add(grids) vects = [ np.array(tup) for tup in it.product(*[[0, 1]] * 4) ] def vect_to_int(vect): return sum([b * (1 << i) for i, b in enumerate(reversed(vect))]) for vect in vects: label = VGroup(*map(Integer, vect)) label.arrange(RIGHT, buff=SMALL_BUFF) label.to_edge(LEFT) self.add(label) error_int = vect_to_int(vect) for i, grid in enumerate(grids): grid[i].set_fill(YELLOW, 1) grid[i ^ error_int].set_fill(TEAL, 1) self.wait() grids.set_fill(opacity=0) self.remove(label)
from manim_imports_ext import * SICKLY_GREEN = "#9BBD37" class WomanIcon(SVGMobject): CONFIG = { "fill_color": GREY_B, "stroke_width": 0, } def __init__(self, **kwargs): super().__init__("woman_icon", **kwargs) self.remove(self[0]) class PersonIcon(SVGMobject): CONFIG = { "fill_color": GREY_B, "stroke_width": 0, } def __init__(self, **kwargs): super().__init__("person", **kwargs) class Population(VGroup): def __init__(self, count, **kwargs): super().__init__(**kwargs) icon = PersonIcon() self.add(*(icon.copy() for x in range(count))) self.arrange_in_grid() def get_covid_clipboard(disease_name="SARS\\\\CoV-2", sign="+", report="Detected", color=GREEN): clipboard = SVGMobject("clipboard") clipboard.set_stroke(width=0) clipboard.set_fill(interpolate_color(GREY_BROWN, WHITE, 0.5), 1) clipboard.set_width(2.5) result = OldTexText( sign + "\\\\", disease_name + "\\\\", report, ) result[0].scale(1.5, about_point=result[1].get_top()) result[0].set_fill(color) result[0].set_stroke(color, 2) result[2].set_width(1.2 * result[1].get_width()) result[-1].set_fill(color) result.set_width(clipboard.get_width() * 0.7) result.move_to(clipboard) result.shift(0.2 * DOWN) clipboard.add(result) return clipboard # Scenes class Thumbnail1(Scene): def construct(self): # New bg = FullScreenFadeRectangle() bg.set_fill(BLACK, 1) bg.set_gloss(0.2) self.add(bg) pre_pop = VGroup(*(WomanIcon() for x in range(5 * 6))) pre_pop.arrange_in_grid(5, 6, fill_rows_first=False) pre_pop.set_height(4) pre_pop[:5].shift(MED_LARGE_BUFF * LEFT) pre_pop[:5].set_fill(YELLOW) pre_pop[5:].set_fill(GREY_C) post_pop = pre_pop.copy() post_pop.set_opacity(0.1) for icon in (*post_pop[:4], *post_pop[5::5]): rect = SurroundingRectangle(icon, buff=0.01) rect.set_stroke(GREEN, 5) icon.set_opacity(1) plus = OldTex("+") plus.set_color(GREEN) plus.set_width(rect.get_width() / 2) plus.move_to(rect.get_corner(UR)) plus.shift(0.05 * UR) icon.set_stroke(BLACK, 2, background=True) icon.push_self_into_submobjects() icon.add_to_back(rect, plus) icon.set_stroke(background=True) for pop in pre_pop, post_pop: colon = OldTex(":", font_size=96) colon.move_to(pop[:10]) pop.add(colon) arrow = Arrow(LEFT, RIGHT, thickness=0.1) arrow.scale(1.75) group = VGroup(pre_pop, arrow, post_pop) group.arrange(RIGHT, buff=1.0) group.to_edge(UP) post_pop.align_to(pre_pop, DOWN) self.add(group) # Or try something else... self.remove(group) randy = Randolph(color=SICKLY_GREEN, mode="sick") randy.set_height(4) randy.next_to(ORIGIN, RIGHT, buff=0.5).to_edge(UP) clipboard.set_height(4) clipboard.next_to(ORIGIN, LEFT, buff=0.5).to_edge(UP) self.add(randy) self.add(clipboard) # new_bayes_rule = OldTexText( "Post = (Prior)(Bayes factor)", tex_to_color_map={ "(Prior)": YELLOW, "(Bayes factor)": BLUE, } ) new_bayes_rule.set_width(FRAME_WIDTH - 1) new_bayes_rule.move_to(2 * DOWN) self.add(new_bayes_rule) new_rule_words = OldTexText("Bayes rule redesigned") new_rule_words.scale(1.75) new_rule_words.next_to(new_bayes_rule, DOWN, MED_LARGE_BUFF) new_rule_words.set_fill(GREY_A) self.add(new_rule_words) self.embed() return # Old title = OldTexText("Interpreting medical tests", font_size=90) title.to_edge(UP) self.add(title) factor = OldTex( "{P(+ \\,|\\, \\text{Virus}) \\over P(+ \\,|\\, \\text{No virus})}", tex_to_color_map={ "+": GREEN, "\\text{Virus}": YELLOW, "\\text{No virus}": GREY_B, } ) factor.scale(2) rect = SurroundingRectangle(factor, buff=MED_SMALL_BUFF) rect.set_stroke(BLUE, 3) factor.add(rect) self.add(factor) clipboard = get_covid_clipboard("Virus") clipboard[2][0].set_stroke(GREEN, 8) clipboard[2].scale(0.9) clipboard.set_height(4) clipboard.next_to(factor, LEFT, LARGE_BUFF) VGroup(clipboard, factor).next_to(title, DOWN, buff=0.7) self.add(clipboard) brace = Brace(factor, DOWN, buff=0.4) brace.stretch(1.5, 1, about_edge=UP) text = brace.get_text("How much your belief should change", buff=0.4) text.scale(1.5, about_edge=UP) text.shift_onto_screen() text.match_color(rect) brace.add(text) self.add(brace) self.embed() class Thumbnail2(Scene): def construct(self): dots = Dot().get_grid(9 * 5, 16 * 5, buff=MED_LARGE_BUFF) dots.set_height(FRAME_HEIGHT) dots.set_color(GREY_D) VGroup(*random.sample(list(dots), 50)).set_fill(YELLOW, 1) # self.add(dots) title = Text("A better Bayes rule?") title.set_width(FRAME_WIDTH - 2) title.to_edge(UP, buff=1) title.set_stroke(BLACK, 25, background=True) self.add(title) formula = OldTex( "O(H | E)", "=", "O(H)", "{P(E | H) \\over P(E | \\neg H)", tex_to_color_map={"H": YELLOW, "E": BLUE} ) formula.set_width(FRAME_WIDTH - 4) formula.set_y(-1) H = formula.get_part_by_tex("H") E = formula.get_part_by_tex("E") hyp_label = Text("Hypothesis", color=YELLOW, font_size=24) hyp_label.next_to(H, UP, buff=1).shift_onto_screen() ev_label = Text("Evidence", color=BLUE, font_size=24) ev_label.next_to(E, DOWN, buff=1) self.add(hyp_label, ev_label) self.add(Arrow(hyp_label, H, buff=0.1, color=YELLOW)) self.add(Arrow(ev_label, E, buff=0.1, color=BLUE)) p_rect = SurroundingRectangle(formula[6:9]) p_rect.set_stroke(GREY_B, 2) p_label = Text("Prior") p_label.next_to(p_rect, UP) # self.add(p_rect, p_label) rect = SurroundingRectangle(formula[9:]) rect.set_stroke(GREEN, 3) rect.set_fill(BLACK, 1) rect_label = Text("Bayes factor", color=GREEN) rect_label.match_width(rect) rect_label.next_to(rect, DOWN) self.add(BackgroundRectangle(formula[:9])) self.add(rect) self.add(rect_label) self.add(formula) # VGroup(formula, rect, rect_label).to_edge(DOWN) class Thumbnail3(Scene): def construct(self): bg = FullScreenFadeRectangle() bg.set_fill(BLACK, 1) # bg.set_gloss(0.4) self.add(bg) # Just the clipboard clipboard = get_covid_clipboard("Cancer", color=GREEN) clipboard[2][0].set_stroke(GREEN, 8) clipboard[2].scale(0.9) clipboard.set_height(7) clipboard.center().to_edge(LEFT, buff=1.0) self.add(clipboard) clipback = VMobject() clipback.set_points(clipboard[1].get_subpaths()[0]) clipback.set_stroke(BLACK, 0) clipback.set_fill(GREY_E, 1) clipback.refresh_triangulation() clipboard.refresh_triangulation() self.add(clipback, clipboard) # Title words = VGroup( VGroup( OldTex("90\\%").scale(1.8).set_color(GREEN), OldTexText("test accuracy", alignment="") ).arrange(DOWN, aligned_edge=LEFT, buff=SMALL_BUFF), VGroup( OldTex("9\\%").scale(1.8).set_color(RED), OldTexText("chance it's true", alignment="") ).arrange(DOWN, aligned_edge=LEFT, buff=SMALL_BUFF), Text("...how?") ) words.arrange(DOWN, buff=0.5, aligned_edge=LEFT) # words.set_width(FRAME_WIDTH - clipboard.get_width() - 1.5) words.set_height(FRAME_HEIGHT - 2) words.to_edge(RIGHT, buff=1.0) words.set_stroke(BLACK, 10, background=True) self.add(words) VGroup(*[m for m in self.mobjects if isinstance(m, VMobject)]).refresh_triangulation() class Thumbnail4(Scene): def construct(self): top_words = Text("False Positive Rate") top_words.set_width(FRAME_WIDTH - 1) top_words.to_edge(UP) self.add(top_words) # is_not = Text("is NOT") is_not = OldTex("\\ne") is_not.set_color(RED) is_not.set_height(2.5) is_not.set_stroke(RED, 8) self.add(is_not) prob = Text( "P(Healthy | Positive)", t2c={ "Healthy": YELLOW, "Positive": GREEN, } ) prob.set_width(FRAME_WIDTH - 1) prob.to_edge(DOWN) self.add(prob) class MathAsDesign(Scene): def construct(self): # Setup design_word = OldTexText("Designed?", font_size=72) design_word.to_edge(UP) e_formula = OldTex( "e", "^{\\pi", "i}", "=", "-1", font_size=96, ) e_formula[1].set_color(GREY_B) e_formula[2].set_color(YELLOW) e_formula[4].set_color(BLUE) l_formula = OldTex( "\\sum_{n = 0}^{\\infty} \\frac{(-1)^n}{2n + 1} = \\frac{\\pi}{4}", font_size=72, ) buff = 1.5 formulas = VGroup(e_formula, l_formula) formulas.arrange(DOWN, buff=buff) formulas.next_to(design_word, DOWN, buff=buff) original_ly = l_formula.get_y() l_formula.center() self.play(Write(l_formula, run_time=1)) self.wait() self.play(FadeIn(design_word, 0.2 * UP, scale=1.1)) self.wait() alt_l_formula = VGroup( VGroup( OldTex("\\pm").set_height(0.8), OldTex("k \\text{ odd}", font_size=36) ).arrange(DOWN, SMALL_BUFF), OldTex("\\frac{1}{k}"), OldTex("="), VGroup( Sector( angle=PI / 2, fill_color=BLUE, fill_opacity=1, stroke_color=WHITE, stroke_width=2, ), Sector( start_angle=PI / 2, angle=3 * PI / 2, fill_color=GREY_E, fill_opacity=1, stroke_color=WHITE, stroke_width=2, ), ).set_height(1) ) alt_l_formula.arrange(RIGHT) alt_l_formula.match_height(l_formula) alt_l_formula.next_to(l_formula.get_center(), RIGHT, LARGE_BUFF) self.play( l_formula.next_to, l_formula.get_center(), LEFT, LARGE_BUFF, FadeIn(alt_l_formula, shift=2 * RIGHT) ) self.wait(2) # Euler's formula e_formula.next_to(e_formula.get_y() * UP, LEFT, buff=1.5) self.play( l_formula.scale, 0.7, l_formula.set_y, original_ly, alt_l_formula.scale, 0.7, alt_l_formula.set_y, original_ly, FadeIn(e_formula, scale=1.1) ) alt_e_formula = VGroup( OldTexText("exp", font_size=96), OldTex("(", font_size=96), Arrow(0.5 * RIGHT, 0.5 * LEFT, path_arc=PI, buff=0, color=GREY_B), Dot(radius=0.05, color=WHITE), Vector(0.75 * UP, fill_color=YELLOW), OldTex(")", font_size=96), OldTex("=", font_size=96), Vector(LEFT, fill_color=BLUE), ) alt_e_formula.arrange(RIGHT, buff=MED_SMALL_BUFF) alt_e_formula[0].shift(0.15 * RIGHT) alt_e_formula[4:].shift(0.15 * LEFT) alt_e_formula.scale(0.8) alt_e_formula.next_to(e_formula.get_y() * UP, RIGHT, buff=1.0) alt_e_formula.shift(0.2 * DOWN) anims = [] for i, j in enumerate([0, 2, 4, 6, 7]): src = e_formula[i].copy() dst = alt_e_formula[j] src.generate_target() src.target.replace(dst, stretch=True) src.target.set_opacity(0) dst.save_state() dst.replace(src, stretch=True) dst.set_opacity(0) anims.append(MoveToTarget(src, remover=True)) anims.append(Restore(dst)) anims.extend([ FadeIn(alt_e_formula[1], shift=0.5 * UP, scale=3), FadeIn(alt_e_formula[5], shift=0.5 * UP, scale=3), GrowFromPoint(alt_e_formula[3], e_formula[1:3].get_center()), ]) self.play(*anims) self.wait() class NewBayesRuleAndMedicalTests(Scene): def construct(self): # Mention paradox paradox_name = OldTexText("Medical Test Paradox", font_size=60) paradox_name.to_corner(UL) paradox_name.shift(MED_SMALL_BUFF * DOWN) paradox_line = Underline(paradox_name) paradox_line.set_stroke(GREY_B, 2) clipboard = get_covid_clipboard("Virus", color=BLUE) clipboard.set_height(3) clipboard.next_to(paradox_line, DOWN, LARGE_BUFF) clipboard[2][0].shift(SMALL_BUFF * DOWN) clipboard[2][0].set_stroke(BLUE, 4) clipboard[2].set_opacity(0) self.play( FadeIn(paradox_name, lag_ratio=0.1), ShowCreation(paradox_line), FadeIn(clipboard, DOWN), ) clipboard[2].set_opacity(1) self.play( Write(clipboard[2], run_time=1) ) self.wait() # Show Bayes rule bayes_title = OldTexText("Bayes' rule", font_size=60) bayes_title.move_to(paradox_name, UL) bayes_title.to_edge(RIGHT, buff=1.5) bayes_underline = Underline(bayes_title) bayes_underline.scale(1.5) bayes_underline.set_stroke(GREY_B, 2) bayes_underline.match_y(paradox_line) formula = OldTex( "P(H|E) = {P(H)P(E|H) \\over P(E)}", tex_to_color_map={ "H": YELLOW, "E": BLUE, }, ) formula.next_to(bayes_underline, DOWN, buff=LARGE_BUFF) self.play( Write(bayes_title, run_time=1), GrowFromCenter(bayes_underline), FadeIn(formula, shift=0.5 * DOWN, scale=1.2) ) self.wait() # Show high accuracy accuracy_words = OldTexText("High accuracy") accuracy_words.next_to(paradox_line, DOWN, MED_LARGE_BUFF) accuracy_words.set_color(GREEN) population = Population(100) population.arrange_in_grid(buff=LARGE_BUFF) population.set_height(5) population.next_to(accuracy_words, DOWN) marks = VGroup() for icon in population: icon.generate_target() if random.random() < 0.025: mark = Exmark() icon.target.set_opacity(0.5) else: mark = Checkmark() mark.set_height(icon.get_height() / 2) mark.move_to(icon.get_corner(UL)) marks.add(mark) accuracy_group = VGroup(accuracy_words, population, marks) self.play( FadeIn(accuracy_words), FadeIn(population, lag_ratio=0.01), clipboard.scale, 0.5, clipboard.to_corner, DR, ) self.play( ShowIncreasingSubsets(marks, run_time=2), LaggedStartMap(MoveToTarget, population, run_time=2), ) self.wait() # Show test result randy = Randolph(height=2) randy.next_to(population, RIGHT, MED_LARGE_BUFF, aligned_edge=DOWN) clipboard.generate_target() clipboard.target.set_height(2) clipboard.target.next_to(randy.get_corner(UR), RIGHT) self.play( VFadeIn(randy), randy.change, "guilty", clipboard.target, MoveToTarget(clipboard), formula.match_width, bayes_underline, formula.next_to, bayes_underline, DOWN, MED_SMALL_BUFF, ) self.play(randy.change, "horrified", clipboard) self.play(Blink(randy)) self.wait() # Show low predictive value prob_expression = OldTex( "P(\\text{Sick} \\text{ given } +) = ", tex_to_color_map={ "+": BLUE, "\\text{Sick}": YELLOW, } ) prob = DecimalNumber(0.9, font_size=60) prob.next_to(prob_expression, RIGHT) prob.set_color(WHITE) prob.set_opacity(0) prob_expression.add(prob) p_line = Underline(prob) p_line.shift(0.1 * DOWN) p_line.scale(1.5) p_line.set_stroke(WHITE, 2) prob_expression.add(p_line) prob_expression.next_to(VGroup(randy, clipboard), UP, aligned_edge=LEFT) self.play( FadeIn(prob_expression), randy.change, "pondering", prob_expression ) self.play( ChangeDecimalToValue(prob, 0.09), UpdateFromAlphaFunc(prob, lambda m, a: m.set_opacity(a)), run_time=2 ) self.play(Blink(randy)) self.play( randy.change, "confused", prob, ChangeDecimalToValue(prob, 0.01), ) self.play(Blink(randy)) self.wait() predictive_group = VGroup( randy, clipboard, prob_expression, prob, ) # Accurate does not imply predictive implication = OldTexText( "Accurate ", "$\\Rightarrow$", " Predictive", ) implication.set_color_by_tex("Accurate", GREEN) implication.set_color_by_tex("Predictive", YELLOW) implication.match_width(paradox_line) implication.next_to(paradox_line, DOWN) strike = Line(DL, UR).replace(implication[1], stretch=True) strike.set_stroke(RED, 4) self.play( FadeIn(implication, scale=1.1), accuracy_group.scale, 0.8, {"about_edge": DOWN}, randy.change, 'pondering', implication, ) self.play(ShowCreation(strike)) self.wait() implication.add(strike) paradox_group = VGroup(paradox_name, paradox_line, implication) # Get rid of medical test stuff p_rect = SurroundingRectangle(paradox_group, buff=MED_SMALL_BUFF) p_rect.set_stroke(WHITE, 2) p_rect.set_fill(GREY_E, 1) self.add(p_rect, paradox_group), self.play( FadeOut(accuracy_group, DL), FadeOut(predictive_group, 2 * DL), DrawBorderThenFill(p_rect) ) paradox_group.add_to_back(p_rect) self.wait() # Alternate framing odds_formula = OldTex( "O(H|E) = O(H){P(E|H) \\over P(E|\\neg H)}", tex_to_color_map={ "H": YELLOW, "E": BLUE, "\\neg": RED, } ) odds_formula.match_height(formula) odds_formula.next_to(formula, DOWN, LARGE_BUFF) odds_formula.shift_onto_screen() bf_rect = SurroundingRectangle(odds_formula[7:], buff=0.025) bf_rect.set_stroke(TEAL, 2) bf_name = OldTexText("Bayes\\\\factor", font_size=36) bf_name.match_color(bf_rect) bf_name.next_to(bf_rect, DOWN, buff=0.2) odds_formula.add(bf_rect, bf_name) arrow = Vector(1.5 * RIGHT) arrow.next_to(formula, LEFT) self.play( paradox_group.next_to, arrow, LEFT, GrowArrow(arrow), ) self.wait() self.play( VGroup(paradox_group, arrow).next_to, odds_formula[0], LEFT, FadeIn(odds_formula, DOWN) ) self.wait() # Reflections on this formula morty = Mortimer(height=2.2) morty.to_corner(DR) morty.shift(2 * LEFT) randy = Randolph(height=2) randy.next_to(morty, LEFT, LARGE_BUFF, aligned_edge=DOWN) bubble = ThoughtBubble() bubble.pin_to(morty) self.play( LaggedStart(*( ShowCreationThenFadeOut(SurroundingRectangle(mob, color=BLUE)) for mob in (formula, odds_formula) ), lag_ratio=0.4, run_time=3), VFadeIn(randy), randy.change, "confused", formula, ) self.play(Blink(randy)) self.wait() self.add(bubble, odds_formula) odds_formula.save_state() self.play( VFadeIn(morty), morty.change, "maybe", bubble[-1], randy.look_at, bubble, FadeIn(bubble, lag_ratio=0.5), odds_formula.move_to, bubble.get_bubble_center(), odds_formula.shift, 0.2 * LEFT + 0.1 * DOWN, FadeOut(arrow, scale=0.5), paradox_group.scale, 0.5, paradox_group.to_corner, DL, ) self.play(Blink(morty)) self.play(Blink(randy)) self.wait(2) self.play(randy.change, "pondering") self.play(Blink(randy)) self.wait() paradox_group.generate_target() paradox_group.target.scale(1.5) paradox_group.target.next_to(randy.get_corner(UL), UP) paradox_group.target.shift(LEFT) self.play( FadeOut(bubble, lag_ratio=0.4), Restore(odds_formula), morty.change, 'tease', paradox_group.target, randy.change, 'raise_left_hand', paradox_group.target, MoveToTarget(paradox_group), ) self.play(Blink(morty)) self.wait() return # Unprocessed # Show rule formula = OldTex( "P(H|E) = {P(H)P(E|H) \\over P(E)}", tex_to_color_map={ "H": YELLOW, "E": BLUE, }, font_size=60 ) h_part = formula.get_part_by_tex("H") hyp_word = OldTexText("Hypothesis", color=YELLOW) hyp_word.next_to(h_part, UP, LARGE_BUFF) hyp_arrow = Arrow(hyp_word.get_bottom(), h_part.get_top(), buff=0.1) e_part = formula.get_part_by_tex("E") ev_word = OldTexText("Evidence", color=BLUE) ev_word.next_to(e_part, DOWN, LARGE_BUFF) ev_arrow = Arrow(ev_word.get_top(), e_part.get_bottom(), buff=0.1) self.play( ShowCreation(h_line), FadeIn(formula, scale=1.1), ) self.play( LaggedStart( FadeIn(hyp_word, shift=0.25 * UP, scale=1.1), FadeIn(ev_word, shift=0.25 * DOWN, scale=1.1), ), LaggedStart( GrowArrow(hyp_arrow), GrowArrow(ev_arrow), ), ) self.wait() formula_annoations = VGroup(hyp_word, hyp_arrow, ev_word, ev_arrow) # Randys pis = VGroup(Randolph(), Randolph()) pis.set_height(2) pis[1].flip() pis[1].set_color(TEAL_E) pis.arrange(RIGHT, buff=5) pis.to_corner(DL) self.play( VFadeIn(pis[0]), pis[0].change, "hooray", formula ) self.play(Blink(pis[0])) self.play( VFadeIn(pis[1]), pis[1].change, "maybe", formula ) self.play(Blink(pis[1])) self.wait() # Sweep aside title.add(h_line) formula.generate_target() formula.target.scale(0.6) formula.target.to_corner(DR) self.play( VFadeOut(formula_annoations), MaintainPositionRelativeTo(formula_annoations, formula), MoveToTarget(formula), title.scale, 0.7, title.next_to, formula.target, UP, FadeOut(pis, DOWN), ) # Question the formulas self.play(FadeIn(morty)) self.play(morty.change, "hesitant", formula) self.play(Blink(morty)) self.wait() formulas = VGroup(formula, odds_formula) self.play( LaggedStart( *( ShowCreationThenFadeOut(Underline(mob, color=GREY_BROWN)) for mob in formulas ), lag_ratio=0.3 ), morty.change, "raise_right_hand", formula, ) self.play(Blink(morty)) self.wait() mover = VGroup(paradox_group, title, formula, odds_formula, arrow) bubbles = VGroup(*(ThoughtBubble(height=1, width=1) for x in range(2))) bubbles.set_fill(GREY_E, 1) for bubble, form in zip(bubbles, formulas): bubble.move_to(form, RIGHT) self.play( morty.change, "raise_left_hand", bubble, mover.to_edge, LEFT, LaggedStartMap(DrawBorderThenFill, bubbles, lag_ratio=0.7, run_time=2), ) self.play(Blink(morty)) self.wait() self.play( Rotate(arrow, PI), morty.change, "pondering", paradox_group, ) arrow2 = Arrow(formula.get_left(), paradox_group.get_corner(UR)) self.play(GrowArrow(arrow2)) self.play(Blink(morty)) self.wait(2) self.play( LaggedStart(*( FadeOut(mob, RIGHT) for mob in [arrow2, arrow, title, formula, odds_formula, *bubbles] )), morty.change, "raise_right_hand", paradox_group.next_to, morty.get_corner(UR), UP, paradox_group.shift_onto_screen, ) self.wait() class SamplePopulationBreastCancer(Scene): def construct(self): # Introduce population title = OldTexText( "Sample of ", "$1{,}000$", " women", font_size=72, ) title.add(Underline(title, color=GREY_B)) title.to_edge(UP, buff=MED_SMALL_BUFF) self.add(title) woman = WomanIcon() globals()['woman'] = woman population = VGroup(*[woman.copy() for x in range(1000)]) population.arrange_in_grid( 25, 40, buff=LARGE_BUFF, fill_rows_first=False, ) population.set_height(6) population.next_to(title, DOWN) counter = Integer(1000, edge_to_fix=UL) counter.replace(title[1]) counter.set_value(0) title[1].set_opacity(0) self.play( ShowIncreasingSubsets(population), ChangeDecimalToValue(counter, 1000), run_time=5 ) self.remove(counter) title[1].set_opacity(1) self.wait() # Show true positives rects = VGroup(Rectangle(), Rectangle()) rects.set_height(6) rects[0].set_width(4, stretch=True) rects[1].set_width(8, stretch=True) rects[0].set_stroke(YELLOW, 3) rects[1].set_stroke(GREY, 3) rects.arrange(RIGHT) rects.center().to_edge(DOWN, buff=MED_SMALL_BUFF) positive_cases = population[:10] negative_cases = population[10:] positive_cases.generate_target() positive_cases.target.move_to(rects[0]) positive_cases.target.set_color(YELLOW) negative_cases.generate_target() negative_cases.target.set_height(rects[1].get_height() * 0.8) negative_cases.target.move_to(rects[1]) positive_words = OldTexText(r"1\% ", "Have breast cancer", font_size=36) positive_words.set_color(YELLOW) positive_words.next_to(rects[0], UP, SMALL_BUFF) negative_words = OldTexText(r"99\% ", "Do not have cancer", font_size=36) negative_words.set_color(GREY_B) negative_words.next_to(rects[1], UP, SMALL_BUFF) self.play( MoveToTarget(positive_cases), MoveToTarget(negative_cases), Write(positive_words, run_time=1), Write(negative_words, run_time=1), FadeIn(rects), ) self.wait() # Show screening scan_lines = VGroup(*( Line( # FRAME_WIDTH * LEFT / 2, FRAME_HEIGHT * DOWN / 2, icon.get_center(), stroke_width=1, stroke_color=interpolate_color(BLUE, GREEN, random.random()) ) for icon in population )) self.play( LaggedStartMap( ShowCreationThenFadeOut, scan_lines, lag_ratio=1 / len(scan_lines), run_time=3, ) ) self.wait() # Test results on cancer population tpr_words = OldTexText("9 True positives", font_size=36) fnr_words = OldTexText("1 False negative", font_size=36) tnr_words = OldTexText("901 True negatives", font_size=36) fpr_words = OldTexText("89 False positives", font_size=36) tpr_words.set_color(GREEN_B) fnr_words.set_color(RED_D) tnr_words.set_color(RED_B) fpr_words.set_color(GREEN_D) tp_cases = positive_cases[:9] fn_cases = positive_cases[9:] tpr_words.next_to(tp_cases, UP) fnr_words.next_to(fn_cases, DOWN) signs = VGroup() for woman in tp_cases: sign = OldTex("+") sign.set_color(GREEN_B) sign.match_height(woman) sign.next_to(woman, RIGHT, SMALL_BUFF) woman.sign = sign signs.add(sign) for woman in fn_cases: sign = OldTex("-") sign.set_color(RED) sign.match_width(signs[0]) sign.next_to(woman, RIGHT, SMALL_BUFF) woman.sign = sign signs.add(sign) boxes = VGroup() for n, woman in enumerate(positive_cases): box = SurroundingRectangle(woman, buff=0) box.set_stroke(width=2) if woman in tp_cases: box.set_color(GREEN) else: box.set_color(RED) woman.box = box boxes.add(box) self.play( FadeIn(tpr_words, shift=0.2 * UP), ShowIncreasingSubsets(signs[:9]), ShowIncreasingSubsets(boxes[:9]), ) self.wait() self.play( FadeIn(fnr_words, shift=0.2 * DOWN), Write(signs[9:]), ShowCreation(boxes[9:]), ) self.wait() # Test results on cancer-free population negative_cases.sort(lambda p: -p[1]) num_fp = int(len(negative_cases) * 0.09) fp_cases = negative_cases[:num_fp] tn_cases = negative_cases[num_fp:] new_boxes = VGroup() for n, woman in enumerate(negative_cases): box = SurroundingRectangle(woman, buff=0) box.set_stroke(width=2) if woman in fp_cases: box.set_color(GREEN) else: box.set_color(RED) woman.box = box new_boxes.add(box) fpr_words.next_to(fp_cases, UP, buff=SMALL_BUFF) tnr_words.next_to(tn_cases, DOWN, buff=0.2) self.play( FadeIn(fpr_words, shift=0.2 * UP), ShowIncreasingSubsets(new_boxes[:num_fp]) ) self.wait() self.play( FadeIn(tnr_words, shift=0.2 * DOWN), ShowIncreasingSubsets(new_boxes[num_fp:]) ) self.wait() # Consolidate boxes self.remove(boxes, new_boxes, population) for woman in population: woman.add(woman.box) self.add(population) # Limit view to positive cases for cases, nr, rect in zip([tp_cases, fp_cases], [3, 7], rects): cases.save_state() cases.generate_target() for case in cases.target: case[-1].set_stroke(width=3) case[-1].scale(1.1) cases.target.arrange_in_grid( n_rows=nr, buff=0.5 * cases[0].get_width() ) cases.target.scale(0.5 / cases.target[0].get_height()) cases.target.move_to(rect) fp_cases.target.shift(0.4 * DOWN) positive_words.save_state() negative_words.save_state() tpr_words.save_state() fpr_words.save_state() self.play( MoveToTarget(tp_cases), MoveToTarget(fp_cases), tpr_words.next_to, tp_cases.target, UP, fpr_words.next_to, fp_cases.target, UP, FadeOut(signs), positive_words[0].set_opacity, 0, negative_words[0].set_opacity, 0, positive_words[1].match_x, rects[0], negative_words[1].match_x, rects[1], LaggedStart( FadeOut(fn_cases, shift=DOWN), FadeOut(fnr_words, shift=DOWN), FadeOut(tn_cases, shift=DOWN), FadeOut(tnr_words, shift=DOWN), ), ) self.wait() # Emphasize groups counts self.play( ShowCreationThenFadeOut(SurroundingRectangle( tpr_words[0][:1], stroke_width=2, stroke_color=WHITE, buff=0.05, )), LaggedStartMap(Indicate, tp_cases, color=YELLOW, lag_ratio=0.3, run_time=1), ) self.wait() self.play( ShowCreationThenFadeOut(SurroundingRectangle( fpr_words[0][:2], stroke_width=2, stroke_color=WHITE, buff=0.05, )), LaggedStartMap( Indicate, fp_cases, color=GREEN_A, lag_ratio=0.05, run_time=3 ) ) self.wait() # Final equation equation = OldTex( "P(", "\\text{Have cancer }", "|", "\\text{ positive test})", "\\approx", "\\frac{9}{9 + 89}", "\\approx \\frac{1}{11}" ) equation.set_color_by_tex("cancer", YELLOW) equation.set_color_by_tex("positive", GREEN) equation.to_edge(UP, buff=SMALL_BUFF) self.play( FadeIn(equation[:-1], shift=UP), FadeOut(title, shift=UP), ) self.wait() self.play(Write(equation[-1])) self.wait() # Label PPV frame = self.camera.frame frame.save_state() ppv_words = OldTexText( "Positive\\\\", "Predictive\\\\", "Value\\\\", alignment="", ) ppv_words.next_to(equation, RIGHT, LARGE_BUFF, DOWN) for word in ppv_words: word[0].set_color(BLUE) ppv_rhs = OldTex( "={\\text{TP} \\over \\text{TP} + \\text{FP}}", tex_to_color_map={ "\\text{TP}": GREEN_B, "\\text{FP}": GREEN_C, } ) ppv_rhs.next_to(ppv_words, RIGHT) ppv_rhs.shift(1.5 * LEFT) self.play(frame.scale, 1.1, {"about_edge": DL}) self.play(ShowIncreasingSubsets(ppv_words)) self.wait() self.play( equation.shift, 1.5 * LEFT + 0.5 * UP, ppv_words.shift, 1.5 * LEFT, FadeIn(ppv_rhs, lag_ratio=0.1), frame.scale, 1.1, {"about_edge": DL}, ) self.wait() # Go back to earlier state self.play( frame.restore, frame.shift, 0.5 * DOWN, LaggedStartMap(FadeOut, VGroup(equation, ppv_words, ppv_rhs)), LaggedStartMap(Restore, VGroup( tpr_words, tp_cases, fpr_words, fp_cases, )), run_time=3, ) self.play( LaggedStartMap(FadeIn, VGroup( fnr_words, fn_cases, tnr_words, tn_cases, )), ) self.wait() # Fade rects fade_rects = VGroup(*( BackgroundRectangle( VGroup(rect, words), fill_opacity=0.9, fill_color=BLACK, buff=SMALL_BUFF, ) for rect, words in zip(rects, [positive_words, negative_words]) )) # Sensitivity sens_eq = OldTex( "\\text{Sensitivity}", "= {9 \\over 10}", "= 90\\%" ) sens_eq.next_to(rects[0], LEFT, MED_LARGE_BUFF, aligned_edge=UP) sens_eq.shift(DOWN) fnr_eq = OldTex( "\\text{False Negative Rate}", "= 10\\%" ) fnr_eq.set_color(RED) fnr_eq.scale(0.9) equiv = OldTex("\\Leftrightarrow") equiv.scale(1.5) equiv.rotate(90 * DEGREES) equiv.next_to(sens_eq, DOWN, MED_LARGE_BUFF) fnr_eq.next_to(equiv, DOWN, MED_LARGE_BUFF) self.play( frame.shift, 5 * LEFT, FadeIn(fade_rects[1]), Write(sens_eq[0]), ) self.wait() self.play( TransformFromCopy(tpr_words[0][0], sens_eq[1][1]), Write(sens_eq[1][0]), Write(sens_eq[1][2:]), ) self.play(Write(sens_eq[2])) self.wait() self.play( FadeIn(equiv, shift=0.5 * DOWN), FadeIn(fnr_eq, shift=1.0 * DOWN), ) self.wait() # Transition to right side fade_rects[0].stretch(5, 0, about_edge=RIGHT) self.play( ApplyMethod(frame.shift, 10 * RIGHT, run_time=4), FadeIn(fade_rects[0], run_time=2), FadeOut(fade_rects[1], run_time=2), ) # Specificity spec_eq = OldTex( "\\text{Specificity}", "= {901 \\over 990}", "\\approx 91\\%" ) spec_eq.next_to(rects[1], RIGHT, MED_LARGE_BUFF, aligned_edge=DOWN) spec_eq.shift(UP) fpr_eq = OldTex( "\\text{False Positive Rate}", "= 9\\%" ) fpr_eq.set_color(GREEN) fpr_eq.scale(0.9) equiv2 = OldTex("\\Leftrightarrow") equiv2.scale(1.5) equiv2.rotate(90 * DEGREES) equiv2.next_to(spec_eq, UP, MED_LARGE_BUFF) fpr_eq.next_to(equiv2, UP, MED_LARGE_BUFF) self.play(Write(spec_eq[0])) self.wait() self.play( Write(spec_eq[1][0]), TransformFromCopy( tnr_words[0][:3], spec_eq[1][1:4], run_time=2, path_arc=30 * DEGREES, ), Write(spec_eq[1][4:]), ) self.wait() self.play(Write(spec_eq[2])) self.wait() self.play( FadeIn(equiv2, shift=0.5 * UP), FadeIn(fpr_eq, shift=1.0 * UP), ) self.wait() # Reset to show both kinds of accuracy eqs = [sens_eq, spec_eq] for eq, word in zip(eqs, [positive_words, negative_words]): eq.generate_target() eq.target[1].set_opacity(0) eq.target[2].move_to(eq.target[1], LEFT), eq.target.next_to(word, UP, buff=0.3) self.play( FadeOut(fade_rects[0]), frame.shift, 5 * LEFT, frame.scale, 1.1, {"about_edge": DOWN}, MoveToTarget(sens_eq), MoveToTarget(spec_eq), *map(FadeOut, (fnr_eq, fpr_eq, equiv, equiv2)), run_time=2, ) self.wait() self.play( VGroup( fn_cases, fnr_words, fp_cases, fpr_words, ).set_opacity, 0.2, rate_func=there_and_back_with_pause, run_time=3 ) class LearnAboutPositiveResult(Scene): def construct(self): doctors = VGroup( SVGMobject("female_doctor"), SVGMobject("male_doctor"), ) for doc in doctors: doc.remove(doc[0]) doc.set_height(3) doctors.set_stroke(width=0) doctors.set_fill(GREY_C) doctors.set_gloss(0.5) doctors.arrange(RIGHT, buff=3) doctors.move_to(DOWN) self.add(doctors) bubbles = VGroup(*(ThoughtBubble(height=2, width=2) for x in range(2))) bubbles[1].flip() for bubble, doc in zip(bubbles, doctors): bubble.pin_to(doc) icon = WomanIcon() icon.set_height(0.5) bubble.add_content(icon) bubble.add(icon) self.play(LaggedStartMap(FadeIn, bubbles)) clipboard = get_covid_clipboard("Cancer") clipboard.move_to(DOWN) clipboard[2].set_opacity(0) self.play(FadeIn(clipboard, UP)) self.play(clipboard[2].set_opacity, 1) self.wait() class AskWhatTheParadoxIs(TeacherStudentsScene): def construct(self): # Image image = ImageMobject("ppv_image") image.replace(self.screen) image.set_opacity(0) outline = SurroundingRectangle(image, buff=0) outline.set_stroke(WHITE, 2) outline.set_fill(BLACK, 1) image = Group(outline, image) image.set_height(3.5, about_edge=UL) # What's the paradox? self.add(image) self.student_says( "How's that\\\\a paradox?", target_mode="sassy", look_at=self.teacher.eyes, index=2, added_anims=[ self.students[0].change, "pondering", image, self.students[1].change, "pondering", image, ] ) self.play(self.teacher.change, 'guilty') self.wait(3) # Consider test accuracy self.teacher_says( "Consider the\\\\", "test accuracy" ) self.wait(3) # Test accuracy split lower_words = self.teacher.bubble.content[1].copy() top_words = OldTexText("Test Accuracy", font_size=72) top_words.to_corner(UR) top_words.shift(LEFT) sens_spec = VGroup( OldTexText("Sensitivity", color=YELLOW), OldTexText("Specificity", color=BLUE_D), ) sens_spec.scale(1) sens_spec.arrange(RIGHT, buff=1.0) sens_spec.next_to(top_words, DOWN, LARGE_BUFF) lines = VGroup(*( Line(top_words.get_bottom(), word.get_top(), buff=0.1, color=word.get_color()) for word in sens_spec )) globals()['top_words'] = top_words self.play( TransformFromCopy(lower_words, top_words[0]), RemovePiCreatureBubble( self.teacher, target_mode="raise_right_hand", look_at=top_words, ), *(ApplyMethod(pi.look_at, top_words) for pi in self.students) ) self.play( LaggedStartMap(ShowCreation, lines), LaggedStart(*( FadeIn(word, shift=word.get_center() - top_words.get_center()) for word in sens_spec )), run_time=1, ) self.wait(4) class MedicalTestsMatter(Scene): def construct(self): randy = Randolph(height=3) randy.to_corner(DL) randy.shift(2 * RIGHT) clipboard = get_covid_clipboard() clipboard.next_to(randy, RIGHT) clipboard.set_y(0) clipboard_words = VGroup( OldTex("-", color=RED), OldTexText("SARS\\\\CoV-2"), OldTexText("Not Detected", color=RED), ) for m1, m2 in zip(clipboard_words, clipboard[2]): m1.replace(m2, 0) clipboard.remove(clipboard[2]) self.add(randy) self.play( FadeIn(clipboard, shift=LEFT), randy.change, 'guilty' ) self.play( Write(clipboard_words), randy.change, "hooray", clipboard, ) self.play(Blink(randy)) question = OldTexText("What does\\\\really this mean?") question.next_to(clipboard, RIGHT, buff=1.5) question.shift(1.5 * UP) q_arrow = Arrow( question.get_bottom(), clipboard.get_right(), path_arc=-30 * DEGREES, buff=0.3, ) self.play( FadeIn(question, shift=0.25 * UP), DrawBorderThenFill(q_arrow), randy.change, "confused", ) self.play(randy.look_at, clipboard.get_top()) self.play(Blink(randy)) self.play(randy.look_at, clipboard.get_center()) self.wait(3) class GigerenzerSession(Scene): def construct(self): # Gigerenzer intro years = OldTexText("2006-2007", font_size=72) years.to_edge(UP) image = ImageMobject("Gerd_Gigerenzer") image.set_height(4) image.flip() name = OldTexText("Gerd Gigerenzer", font_size=72) name.next_to(image, DOWN) image_group = Group(image, name) self.play(FadeIn(years, shift=0.5 * UP)) self.wait() self.play( FadeIn(image), Write(name) ) self.wait() # Seminar words title = OldTexText("Statistics Seminar", font_size=72) title.to_edge(UP) title_underline = Underline(title, buff=SMALL_BUFF) title_underline.scale(1.1) title_underline.set_stroke(GREY_B) self.play( FadeIn(title, shift=0.5 * UP), FadeOut(years, shift=0.5 * UP), ) self.play(ShowCreation(title_underline)) title.add(title_underline) # Docs doctors = ImageMobject("doctor_pair", height=2) doctors.to_corner(DL, buff=1) doctors_label = OldTexText("Practicing Gynecologists") doctors_label.match_width(doctors) doctors_label.next_to(doctors, DOWN) doctors_label.set_fill(GREY_A) self.play( FadeIn(doctors, scale=1.1), Write(doctors_label, run_time=1), image_group.scale, 0.75, image_group.to_corner, DR, ) self.wait() # Description of patient prompt = OldTexText( """ A 50-year-old woman, no symptoms, participates\\\\ in routine mammography screening. """, """She tests positive,\\\\ is alarmed, and wants to know from you whether she\\\\ has breast cancer for certain or what the chances are.\\\\ \\quad \\\\ """, """ Apart from the screening results, you know nothing\\\\ else about this woman.\\\\ """, alignment="", font_size=36, ) prompt.next_to(title_underline, DOWN, MED_LARGE_BUFF) prompt[2].shift(0.5 * UP) no_symptoms_part = prompt[0][18:28] no_symptoms_underline = Underline( no_symptoms_part, buff=0, stroke_width=3, stroke_color=YELLOW, ) clipboard = SVGMobject( "clipboard", stroke_width=0, fill_color=interpolate_color(GREY_BROWN, WHITE, 0.2) ) clipboard.next_to(prompt, DOWN) clipboard.set_width(2.5) clipboard_contents = VGroup( OldTexText("+", color=GREEN, font_size=96, stroke_width=3), OldTexText("Cancer\\\\detected", color=GREY_A), ) clipboard_contents.arrange(DOWN) clipboard_contents.set_width(0.7 * clipboard.get_width()) clipboard_contents.move_to(clipboard) clipboard_contents.shift(0.1 * DOWN) clipboard.add(clipboard_contents) self.play(FadeIn(prompt[0], lag_ratio=0.01)) self.wait() self.play(ShowCreationThenFadeOut(no_symptoms_underline)) self.wait() self.play( FadeIn(prompt[1], lag_ratio=0.01), prompt[0].set_opacity, 0.5, ) self.play( FadeIn(clipboard, shift=0.5 * UP, scale=1.1), image_group.scale, 0.75, {"about_edge": DR}, ) self.wait() self.play( FadeIn(prompt[2], lag_ratio=0.01), prompt[1].set_opacity, 0.5, clipboard.scale, 0.7, {"about_edge": DOWN}, ) self.wait() # Push prompt lower prompt.generate_target() prompt.target.set_opacity(0.8) prompt.target.replace(image_group, 0) prompt.target.scale(1.5, about_edge=RIGHT) h_line = DashedLine(FRAME_WIDTH * LEFT / 2, FRAME_WIDTH * RIGHT / 2) h_line.set_stroke(GREY_C) h_line.next_to(clipboard, UP) h_line.set_x(0) self.play( FadeOut(title, shift=UP), MoveToTarget(prompt), ShowCreation(h_line), FadeOut(image_group, shift=DR), clipboard.shift, 0.5 * LEFT, ) # Test statistics stats = VGroup( OldTexText("Prevalence: ", "1\\%"), OldTexText("Sensitivity: ", "90\\%"), OldTexText("Specificity: ", "91\\%"), ) stats.arrange(DOWN, buff=0.5, aligned_edge=LEFT) stats.to_corner(UL, buff=LARGE_BUFF) colors = [YELLOW, GREEN_B, GREY_B] for stat, color in zip(stats, colors): stat[0].set_color(color) stat[1].align_to(stats[0][1], LEFT) for stat in stats: self.play(FadeIn(stat[0], shift=0.25 * UP)) self.play(Write(stat[1])) self.wait() self.wait() # Show randy knowing the answer randy = Randolph(height=2) randy.flip() randy.next_to(h_line, UP) randy.to_edge(RIGHT) bubble = randy.get_bubble( height=2, width=2, ) bubble.shift(0.2 * LEFT) bubble.write("$\\frac{1}{11}$") self.play(FadeIn(randy)) self.play( randy.change, "thinking", ShowCreation(bubble), Write(bubble.content), ) self.play(Blink(randy)) self.wait() # Show population dot = Dot() globals()['dot'] = dot dots = VGroup(*(dot.copy() for x in range(1000))) dots.arrange_in_grid(25, 40, buff=SMALL_BUFF) dots.set_height(4) dots.to_corner(UR) dots.set_fill(GREY_D) VGroup(*random.sample(list(dots), 10)).set_fill(YELLOW) cross = Cross(dots) cross.set_stroke(RED, 30) self.play( LaggedStartMap(FadeOut, VGroup(randy, bubble, bubble.content)), ShowIncreasingSubsets(dots, run_time=2) ) self.wait() self.play(ShowCreation(cross)) self.play(FadeOut(dots), FadeOut(cross)) self.wait() self.play(LaggedStart(*( ShowCreationThenFadeOut(SurroundingRectangle( stat[1], color=stat[0].get_color() )) for stat in stats ))) # Ask question question = OldTexText( "How many women who test positive\\\\actually have breast cancer?", font_size=36 ) question.to_corner(UR) question.shift(LEFT) self.play(FadeIn(question, lag_ratio=0.1)) choices = VGroup( OldTexText("A) 9 in 10"), OldTexText("B) 8 in 10"), OldTexText("C) 1 in 10"), OldTexText("D) 1 in 100"), ) choices.arrange_in_grid(2, 2, h_buff=1.0, v_buff=0.5, aligned_edge=LEFT) choices.next_to(question, DOWN, buff=0.75) choices.set_fill(GREY_A) self.play(LaggedStart(*( FadeIn(choice, scale=1.2) for choice in choices ), lag_ratio=0.3)) self.wait() # Comment on choices a_rect = SurroundingRectangle(choices[0]) a_rect.set_color(BLUE) q_mark = OldTex("?") q_mark.match_height(a_rect) q_mark.next_to(a_rect, LEFT) q_mark.match_color(a_rect) q_mark2 = q_mark.copy() q_mark2.move_to(doctors, UR) c_rect = SurroundingRectangle(choices[2]) c_rect.set_color(GREEN) checkmark = Checkmark().next_to(c_rect, LEFT) self.play( ShowCreation(a_rect), Write(q_mark2) ) self.play(TransformFromCopy(q_mark2, q_mark)) self.wait() # One fifth of doctors curr_doc_group = Group( doctors, clipboard, doctors_label, q_mark2, ) new_doctors = VGroup( SVGMobject("female_doctor"), SVGMobject("female_doctor"), SVGMobject("female_doctor"), SVGMobject("male_doctor"), SVGMobject("male_doctor"), ) for doc in new_doctors: doc.remove(doc[0]) doc.set_stroke(width=0) doc.set_fill(GREY_B) new_doctors.arrange_in_grid(2, 2, buff=MED_LARGE_BUFF) new_doctors[4].move_to(new_doctors[:4]) new_doctors.set_height(2.75) new_doctors.move_to(doctors, UP) marks = VGroup() for n, doc in enumerate(new_doctors): mark = Checkmark() if n == 0 else Exmark() mark.move_to(doc.get_corner(UL)) mark.shift(SMALL_BUFF * DR) marks.add(mark) new_doctors[0].set_color(GREEN) self.play( LaggedStartMap(FadeOut, curr_doc_group, scale=0.5, run_time=1), FadeIn(new_doctors, lag_ratio=0.1) ) self.play( ReplacementTransform(a_rect, c_rect), FadeOut(q_mark), Write(checkmark) ) self.wait() class OldGigerenzerMaterial(Scene): def construct(self): # Test sensitivity prompt.generate_target() prompt.target.set_opacity(0.8) prompt.target.match_height(clipboard) prompt.target.scale(0.65) prompt.target.next_to(clipboard, RIGHT, MED_LARGE_BUFF) sensitivity_words = OldTex("90", "\\%", "\\text{ Sensitivity}") sensitivity_words.to_edge(UP) self.play( FadeIn(sensitivity_words), FadeOut(title, shift=UP), MoveToTarget(prompt), ShowCreation(h_line) ) woman = WomanIcon() women = VGroup(*[woman.copy() for x in range(100)]) women.arrange_in_grid(h_buff=2, v_buff=1) women.set_height(3) women.next_to(sensitivity_words, DOWN) women_rect = SurroundingRectangle(women, buff=0.15) women_rect.set_stroke(YELLOW, 2) with_bc_label = OldTexText( "Women\\\\with\\\\breast\\\\cancer", font_size=36, color=women_rect.get_color() ) with_bc_label.next_to(women_rect, LEFT) women.generate_target() signs = VGroup() for n, woman in enumerate(women.target): if n < 90: sign = OldTex("+", color=GREEN) woman.set_color(GREEN) else: sign = OldTex("-", color=RED) woman.set_color(RED) sign.match_width(woman) sign.move_to(woman.get_corner(UR), LEFT) signs.add(sign) self.play( FadeIn(women_rect), FadeIn(with_bc_label), FadeIn(women, lag_ratio=0.01), ) self.wait() self.play( MoveToTarget(women), FadeIn(signs, lag_ratio=0.01) ) self.wait() sens_group = VGroup( sensitivity_words, with_bc_label, women_rect, women, signs ) # Specificity specificity_words = OldTex("91", "\\%", "\\text{ Specificity}") specificity_words.move_to(sensitivity_words) spec_women = women.copy() spec_women.set_fill(GREY_C) spec_rect = women_rect.copy() spec_rect.set_color(interpolate_color(GREY_BROWN, WHITE, 0.5)) wo_bc_label = OldTexText( "Women\\\\ \\emph{without} \\\\breast\\\\cancer", font_size=36, ) wo_bc_label.next_to(spec_rect, LEFT) wo_bc_label.match_color(spec_rect) spec_group = VGroup( specificity_words, wo_bc_label, spec_rect, spec_women, ) spec_group.next_to(ORIGIN, RIGHT, buff=1) spec_group.to_edge(UP) self.play( sens_group.next_to, ORIGIN, LEFT, {"buff": 2}, sens_group.to_edge, UP, FadeIn(spec_group, shift=RIGHT), ) self.wait() spec_women.generate_target() spec_signs = VGroup() for n, woman in enumerate(spec_women.target): if n < 9: sign = OldTex("+", color=GREEN) woman.set_color(GREEN) else: sign = OldTex("-", color=RED) woman.set_color(RED) sign.match_width(woman) sign.move_to(woman.get_corner(UR), LEFT) spec_signs.add(sign) self.play( MoveToTarget(spec_women), FadeIn(spec_signs, lag_ratio=0.01) ) self.wait() spec_group.add(spec_signs) # False negatives/False positives fnr = OldTex( "\\leftarrow", "10", "\\%", " \\text{ false negative}", font_size=36, ) fnr.next_to(women[-1], RIGHT, buff=0.3) fpr = OldTex( "9", "\\%", "\\text{ false positive}", "\\rightarrow", font_size=36, ) fpr.next_to(spec_women[0], LEFT, buff=0.3) self.play(FadeIn(fnr, shift=0.2 * RIGHT, scale=2)) self.play(FadeIn(fpr, shift=0.2 * LEFT, scale=2)) class AskIfItsAParadox(TeacherStudentsScene): def construct(self): # Add fact stats = VGroup( OldTexText("Sensitivity: ", "90\\%"), OldTexText("Specificity: ", "91\\%"), OldTexText("Prevalence: ", "1\\%"), ) stats.arrange(DOWN, buff=0.25, aligned_edge=LEFT) for stat, color in zip(stats, [GREEN_B, GREY_B, YELLOW]): stat[0].set_color(color) stat[1].align_to(stats[0][1], LEFT) brace = Brace(stats, UP) prob = OldTex( "P(\\text{Cancer} \\,|\\, +) \\approx \\frac{1}{11}", tex_to_color_map={ "\\text{Cancer}": YELLOW, "+": GREEN, } ) prob.next_to(brace, UP, buff=SMALL_BUFF) fact = VGroup(stats, brace, prob) fact.to_corner(UL) box = SurroundingRectangle(fact, buff=MED_SMALL_BUFF) box.set_fill(BLACK, 0.5) box.set_stroke(WHITE, 2) fact.add_to_back(box) fact.to_edge(UP, buff=SMALL_BUFF) self.add(fact) # Commentary self.student_says( "I'm sorry, is that\\\\a paradox?", target_mode="sassy", index=1 ) self.play_student_changes( "angry", "sassy", "angry", added_anims=[self.teacher.change, "guilty"] ) self.wait(2) p_triangle = SVGMobject("PenroseTriangle") p_triangle.remove(p_triangle[0]) p_triangle.set_fill(opacity=0) p_triangle.set_stroke(GREY_B, 3) p_triangle.set_gloss(1) p_triangle.set_height(3) p_triangle.next_to(self.students[2].get_corner(UR), UP) p_triangle = CurvesAsSubmobjects(p_triangle[0]) self.play( self.students[0].change, "thinking", p_triangle, RemovePiCreatureBubble( self.students[1], target_mode="tease", look_at=p_triangle, ), self.students[2].change, "raise_right_hand", p_triangle, self.teacher.change, "tease", p_triangle, ShowCreation(p_triangle, run_time=2, lag_ratio=0.01), ) self.wait(3) # Veridical paradox v_paradox = OldTexText("``Veridical paradox''", font_size=72) v_paradox.move_to(self.hold_up_spot, DOWN) v_paradox.to_edge(UP) v_paradox.shift(0.5 * LEFT) vp_line = Underline(v_paradox) self.play( FadeIn(v_paradox, shift=UP), self.change_students(*3 * ["pondering"], look_at=v_paradox), FadeOut(p_triangle, shift=UP), self.teacher.change, "raise_right_hand", v_paradox ) self.play(ShowCreation(vp_line)) self.wait() definition = OldTexText( "- Provably true\\\\", "- Seems false", alignment="", ) definition.next_to(v_paradox, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) for part in definition: self.play(FadeIn(part, shift=0.25 * RIGHT)) self.wait() self.wait(5) class GoalsOfEstimation(TeacherStudentsScene): def construct(self): # Goal goal = OldTexText("Goal: Quick estimations") goal.to_edge(UP) goal_line = Underline(goal) self.look_at(goal, added_anims=[FadeIn(goal, shift=0.5 * UP)]) self.play( ShowCreation(goal_line), self.change_students( *3 * ["pondering"], look_at=goal_line, ) ) self.wait() # Generators def generate_stats(prev, sens, spec, bottom=self.hold_up_spot): stats = VGroup( OldTexText("Prevalence: ", f"{prev}\\%"), OldTexText("Sensitivity: ", f"{sens}\\%"), OldTexText("Specificity: ", f"{spec}\\%"), ) stats.arrange(DOWN, buff=0.25, aligned_edge=LEFT) for stat, color in zip(stats, [YELLOW, GREEN_B, GREY_B]): stat[0].set_color(color) stat[1].align_to(stats[0][1], LEFT) rect = SurroundingRectangle(stats, buff=0.2) rect.set_fill(BLACK, 1) rect.set_stroke(GREY_B, 2) stats.add_to_back(rect) stats.move_to(bottom, DOWN) return stats def generate_answer(ans_tex): return OldTex( "P(\\text{Cancer} \\,|\\, {+})", ans_tex, tex_to_color_map={ "\\text{Cancer}": YELLOW, "{+}": GREEN, } ) stats = [ generate_stats(1, 90, 91), generate_stats(10, 90, 91), generate_stats(0.1, 90, 91), generate_stats(1, 90, 99), ] # Question and answer self.teacher_holds_up(stats[0]) self.wait() self.student_says( generate_answer("\\approx \\frac{1}{11}"), target_mode="hooray", index=0, run_time=1, ) self.wait(3) stats[1].to_edge(RIGHT) self.play( FadeOut(stats[0]), self.teacher.change, "raise_left_hand", stats[1], FadeIn(stats[1], shift=0.5 * UP), RemovePiCreatureBubble(self.students[0]), ) self.play(ShowCreationThenFadeAround(stats[1][1][1])) self.play_student_changes( "pondering", "thinking", "confused", look_at=stats[1] ) self.wait() self.student_says( generate_answer("\\text{ is} \\\\ \\text{a little over } 50\\%"), bubble_config={"width": 4, "height": 3}, index=1, target_mode="speaking", run_time=1, added_anims=[ self.students[2].change, "erm", goal, self.teacher.change, "happy", self.students[1].eyes, ] ) self.wait(2) self.play( FadeOut(stats[1], 0.5 * UP), FadeIn(stats[2], 0.5 * UP), RemovePiCreatureBubble(self.students[1]), self.teacher.change, "raise_right_hand", stats[2], self.change_students(*3 * ["pondering"], look_at=stats[2]) ) self.play(ShowCreationThenFadeAround(stats[2][1][1])) self.wait(2) self.student_says( generate_answer("\\approx \\frac{1}{100}"), bubble_config={"width": 4, "height": 3}, index=0, target_mode="tease", run_time=1, ) self.look_at(self.students[0].bubble.content) self.wait(2) stats[3].to_edge(RIGHT) self.play( FadeOut(stats[2], 0.5 * UP), FadeIn(stats[3], 0.5 * UP), self.teacher.change, "raise_left_hand", RemovePiCreatureBubble(self.students[0]), *(ApplyMethod(pi.look_at, stats[3]) for pi in self.pi_creatures) ) self.play(ShowCreationThenFadeAround(stats[3][1][1])) self.play( ShowCreationThenFadeAround( stats[3][3][1], surrounding_rectangle_config={"color": TEAL}, ), self.teacher.change, "tease", stats[3] ) self.play_student_changes( "pondering", "thinking", "confused", look_at=self.teacher.get_bottom(), ) self.wait(2) self.student_says( generate_answer("\\text{ is} \\\\ \\text{a little below } 50\\%"), bubble_config={"width": 4, "height": 3}, index=1, target_mode="speaking", run_time=1, added_anims=[ self.students[0].change, "erm", goal, self.students[2].change, "confused", goal, self.teacher.change, "happy", self.students[1].eyes, ] ) self.wait(2) self.play_student_changes( "thinking", "hooray", "thinking", look_at=self.students[1].bubble.content, ) self.wait(3) class QuickEstimatesAndMisconceptions(Scene): def construct(self): titles = VGroup( OldTexText("Quick\\\\estimations"), OldTexText("Combating\\\\misconceptions"), ) for title, u in zip(titles, [-1, 1]): title.set_x(u * FRAME_WIDTH / 4) titles.to_edge(UP, buff=MED_SMALL_BUFF) circles = VGroup( Circle(color=BLUE), Circle(color=RED), ) circles[1].flip() circles.set_height(4) circles.set_stroke(width=3) circles.set_fill(opacity=0.5) for circle, title, u in zip(circles, titles, [-1, 1]): circle.set_x(u) title.set_color( interpolate_color(circle.get_color(), WHITE, 0.5) ) title.next_to(circle, UP) title.shift(u * RIGHT) self.play( LaggedStartMap(FadeIn, titles, shift=0.2 * UP), LaggedStartMap(DrawBorderThenFill, circles), run_time=1.5, ) self.wait() arrow = OldTex("\\leftrightarrow", font_size=72) arrow.move_to(circles) self.play( circles[0].next_to, arrow, LEFT, circles[1].next_to, arrow, RIGHT, titles[0].shift, 0.7 * LEFT, titles[1].shift, 0.7 * RIGHT, GrowFromCenter(arrow), ) self.wait(2) self.play( FadeOut(arrow, DOWN), circles[0].shift, 2.0 * RIGHT, circles[1].shift, 2.0 * LEFT, titles[0].shift, 1.0 * RIGHT, titles[1].shift, 1.0 * LEFT, ) self.wait() titles[1].save_state() self.play( FadeOut(titles[0]), FadeOut(circles[0]), titles[1].match_x, circles[1] ) self.wait() circles[0].save_state() titles[0].save_state() circles[0].next_to(circles[1], LEFT, MED_LARGE_BUFF) titles[0].next_to(circles[0], UP) self.play( FadeIn(titles[0]), FadeIn(circles[0]), ) self.wait() bayes_factor = OldTexText("Bayes\\\\factor", font_size=72) bayes_factor.move_to(circles[0]) self.play(Write(bayes_factor)) self.wait() restoration_group = VGroup(circles[0], titles[0], titles[1]) self.add(restoration_group, bayes_factor) self.play( bayes_factor.move_to, VGroup(circles[0].saved_state, circles[1]), LaggedStartMap(Restore, restoration_group) ) self.wait() class WhatDoYouTellThem(Scene): def construct(self): text = OldTexText("What do you tell them?", font_size=72) text.set_color(BLUE) self.play(Write(text)) self.wait(5) class AccuracyImage(Scene): def construct(self): sens = 90 spec = 91 stats = VGroup( OldTexText("Sensitivity: ", f"{sens}\\%"), OldTexText("Specificity: ", f"{spec}\\%"), ) stats.arrange(DOWN, buff=0.25, aligned_edge=LEFT) for stat, color in zip(stats, [GREEN_B, GREY_B]): stat[0].set_color(color) stat[1].align_to(stats[0][1], LEFT) rect = SurroundingRectangle(stats, buff=0.2) rect.set_fill(GREY_E, 1) rect.set_stroke(GREY_B, 2) stats.add_to_back(rect) self.add(stats) class SamplePopulation10PercentPrevalence(Scene): def construct(self): # Setup test accuracy figures accuracy_figures = VGroup( OldTexText( "90\\% Sensitivity,", " 10\\% False negative rate", font_size=36 ), OldTexText( "91\\% Specificity,", " 9\\% False positive rate", font_size=36 ), ) accuracy_figures.arrange(RIGHT, buff=LARGE_BUFF) accuracy_figures.to_edge(UP) for color, text in zip([YELLOW, GREY], accuracy_figures): text.add(Underline(text, color=color, stroke_width=2)) # Show population population = VGroup(*[WomanIcon() for x in range(100)]) population.arrange_in_grid(fill_rows_first=False) population.set_height(5) population.next_to(accuracy_figures, DOWN, LARGE_BUFF) cancer_cases = population[:10] healthy_cases = population[10:] cancer_cases.set_fill(YELLOW) healthy_cases.set_fill(GREY) population.generate_target() reordered_pop = VGroup(*population) reordered_pop.shuffle() for m1, m2 in zip(reordered_pop, population.target): m1.move_to(m2) population.target[:10].next_to(accuracy_figures[0], DOWN, MED_LARGE_BUFF) population.target[10:].next_to(accuracy_figures[1], DOWN, MED_LARGE_BUFF) pop_words = OldTexText("100", " patients") wc_words = OldTexText("10", " with cancer") wo_words = OldTexText("90", " without cancer") pop_words.next_to(population, DOWN) wc_words.next_to(population.target[:10], DOWN) wo_words.next_to(population.target[10:], DOWN) for words in wc_words, wo_words: words.save_state() words[0].replace(pop_words[0], stretch=True) words[1].replace(pop_words[1], stretch=True) words.set_opacity(0) title = OldTexText("Picture a concrete population", font_size=72) title.to_edge(UP) self.add(title) self.play( FadeIn(population, lag_ratio=0.05, run_time=3), FadeIn(pop_words), ) self.wait() self.play( MoveToTarget(population, run_time=2), Restore(wc_words), Restore(wo_words), FadeOut(pop_words), title.shift, 0.25 * UP, ) self.wait() # Show test stats self.play( FadeOut(title, shift=UP), FadeIn(accuracy_figures[0], 0.5 * UP) ) # Show test results c_boxes = VGroup(*( SurroundingRectangle(icon, buff=0) for icon in cancer_cases )) h_boxes = VGroup(*( SurroundingRectangle(icon, buff=0) for icon in healthy_cases )) all_boxes = VGroup(c_boxes, h_boxes) all_boxes.set_stroke(width=3) c_boxes[:9].set_stroke(GREEN) c_boxes[9:].set_stroke(RED) h_boxes.set_stroke(RED) false_positives = healthy_cases[0:80:10] false_positive_boxes = h_boxes[0:80:10] false_positive_boxes.set_stroke(GREEN) for n, box in enumerate(c_boxes): tex = "+" if n < 9 else "-" sign = OldTex(tex, font_size=36) sign.next_to(box, RIGHT, SMALL_BUFF) sign.match_color(box) box.add(sign) for box in false_positive_boxes: sign = OldTex("+", font_size=36) sign.next_to(box, UP, SMALL_BUFF) sign.match_color(box) box.add(sign) for i, boxes in (0, c_boxes), (1, h_boxes): if i == 1: self.play(FadeIn(accuracy_figures[1])) self.play(ShowCreationThenFadeOut(SurroundingRectangle( accuracy_figures[i][i], buff=SMALL_BUFF, stroke_color=GREEN, ))) self.wait() self.play(ShowIncreasingSubsets(boxes)) self.wait() for icon, box in zip(cancer_cases, c_boxes): icon.add(box) for icon, box in zip(healthy_cases, h_boxes): icon.add(box) self.remove(all_boxes) self.add(population) # Filter down to positive cases new_wc_words = OldTexText("9 ", "with cancer") new_wo_words = OldTexText("8 ", "without cancer") for nw, w in (new_wc_words, wc_words), (new_wo_words, wo_words): nw[0].set_color(GREEN) nw.move_to(w) self.play( cancer_cases[:9].move_to, cancer_cases, FadeOut(cancer_cases[9:]), ReplacementTransform(wc_words, new_wc_words), ) self.wait() self.play( false_positives.move_to, healthy_cases, FadeOut(VGroup(*( case for case in healthy_cases if case not in false_positives ))), ReplacementTransform(wo_words, new_wo_words), ) self.wait() # Rearrange true positives false_positives.generate_target() false_positives.target.shift(DOWN) true_positives = cancer_cases[:9] true_positives.generate_target() for case in true_positives.target: box = case[-1] sign = box[-1] sign.next_to(case[:-1], UP, SMALL_BUFF) true_positives.target.arrange( RIGHT, buff=get_norm(false_positives[0].get_right() - false_positives[1].get_left()), ) true_positives.target.match_y(false_positives.target) true_positives.target.match_x(new_wc_words) self.play( MoveToTarget(true_positives), MoveToTarget(false_positives), new_wc_words.next_to, true_positives.target, DOWN, new_wo_words.next_to, false_positives.target, DOWN, ) self.wait() # Show final fraction answer = OldTex( "{9 \\over 9 + 8} \\approx 0.53", font_size=72, )[0] answer.next_to(accuracy_figures, DOWN, LARGE_BUFF) nine1 = new_wc_words[0].copy() nine2 = new_wc_words[0].copy() eight = new_wo_words[0].copy() self.play( nine1.replace, answer[0], nine2.replace, answer[2], eight.replace, answer[4], Write(answer[1:5:2]), ) self.wait() self.play(Write(answer[5:])) self.wait() class NinePercentOfNinety(Scene): def construct(self): mob = OldTex("(0.09)(90) = 8.1", tex_to_color_map={"8.1": GREEN}) mob.scale(2) self.add(mob) class MoreExamples(TeacherStudentsScene): def construct(self): self.teacher_says( "More examples!", target_mode="hooray", added_anims=[self.change_students("tired", "erm", "happy", run_time=2)] ) self.wait(3) class SamplePopulationOneInThousandPrevalence(Scene): def construct(self): # Add prevalence title titles = VGroup(*( OldTexText( f"What if prevalence is {n} in {k}?", tex_to_color_map={ n: YELLOW, k: GREY_B, } ) for n, k in [("{1}", "{1,000}"), ("{10}", "{10,000}")] )) titles.to_edge(UP) self.add(titles[0]) # Show population dots1k, dots10k = [ VGroup(*(Dot() for x in range(n))).set_fill(GREY_D) for n in [1000, 10000] ] dots1k[:1].set_fill(YELLOW) dots10k[:10].set_fill(YELLOW) for dots, n, m in [(dots1k, 20, 50), (dots10k, 100, 100)]: sorter = VGroup(*dots) sorter.shuffle() sorter.arrange_in_grid(n, m, buff=SMALL_BUFF) sorter.set_width(FRAME_WIDTH - 1) if sorter.get_height() > 6: sorter.set_height(6) sorter.to_edge(DOWN) self.play(FadeIn(dots1k, lag_ratio=0.05, run_time=2)) self.wait() self.play( Transform(dots1k, dots10k[0::10]), ) self.play( FadeIn(dots10k), ReplacementTransform(titles[0][0::2], titles[1][0::2]), FadeOut(titles[0][1::2], 0.5 * UP), FadeIn(titles[1][1::2], 0.5 * UP), ) self.remove(dots1k) # Split the group cancer_cases = dots10k[:10] cancer_cases.generate_target() cancer_cases.target.arrange_in_grid( buff=cancer_cases[0].get_width() / 2, ) cancer_cases.target.set_height(2) cancer_cases.target.set_y(0) cancer_cases.target.to_edge(LEFT, buff=LARGE_BUFF) non_cancer_cases = dots10k[10:] non_cancer_cases.generate_target() non_cancer_cases.target.to_edge(RIGHT) c_count = titles[1][1].copy() c_count.generate_target() c_count.target.next_to(cancer_cases.target, UP, MED_LARGE_BUFF) nc_count = Integer(9990) nc_count.set_color(GREY_B) nc_count.set_opacity(0) nc_count.move_to(titles[1][3]) self.play( MoveToTarget(cancer_cases), MoveToTarget(non_cancer_cases), MoveToTarget(c_count), nc_count.set_opacity, 1, nc_count.next_to, non_cancer_cases.target, UP, FadeOut(titles[1]), ) self.wait() # Show test results tp_cases = cancer_cases[:9] fp_cases = VGroup(*random.sample(list(non_cancer_cases), 900)) for case in it.chain(tp_cases, fp_cases): box = SurroundingRectangle( case, buff=0.1 * case.get_width() ) box.set_stroke(GREEN, 3) case.box = box tn_cases = VGroup(*( case for case in non_cancer_cases if case not in fp_cases )) tp_label = OldTexText("$9$ True Positives") tp_label.set_color(GREEN) tp_label.move_to(c_count) tp_label.shift_onto_screen() fp_label = OldTexText("$\\sim 900$ False Positives") fp_label.set_color(GREEN_D) fp_label.move_to(nc_count) self.play( FadeOut(c_count), FadeIn(tp_label), LaggedStart(*( ShowCreation(case.box) for case in tp_cases )), cancer_cases[9].set_opacity, 0.25 ) self.wait() self.play( FadeOut(nc_count), FadeIn(fp_label), LaggedStart(*( ShowCreation(case.box) for case in fp_cases ), lag_ratio=0.001), tn_cases.set_opacity, 0.25, run_time=2, ) self.wait() for case in it.chain(tp_cases, fp_cases): case.add(case.box) # Organize false positives center = fp_cases.get_center() fp_cases.sort(lambda p: get_norm(p - center)) fp_cases.generate_target() fp_cases.target.arrange_in_grid( buff=fp_cases[0].get_width() / 4, ) fp_cases.target.set_height(6) fp_cases.target.to_corner(DR) new_center = fp_cases.target.get_center() fp_cases.target.sort(lambda p: get_norm(p - new_center)) self.play( MoveToTarget(fp_cases, run_time=4), FadeOut(tn_cases, run_time=1), FadeOut(cancer_cases[9]), ) self.wait() # Final fraction final_frac = OldTex( "{{9} \\over {9} + {900}} \\approx 0.01", tex_to_color_map={ "{9}": GREEN, "{900}": GREEN_D, } ) final_frac.scale(1.5) final_frac.next_to(tp_cases, DOWN, LARGE_BUFF) final_frac.to_edge(LEFT, LARGE_BUFF) self.play(FadeIn(final_frac, lag_ratio=0.2)) self.wait() class AltShowUpdatingPrior(Scene): def construct(self): N = 100 post_denom = 11 N_str = "{:,}".format(N) # Show prior woman = WomanIcon() population = VGroup(*[woman.copy() for x in range(N)]) population.arrange_in_grid() population.set_fill(GREY) population[0].set_fill(YELLOW) population.set_height(5) prior_prob = OldTexText("1", " in ", N_str) prior_prob.set_color_by_tex("1", YELLOW) prior_prob.set_color_by_tex(N_str, GREY_B) prior_prob.next_to(population, UP, MED_LARGE_BUFF) prior_brace = Brace(prior_prob, UP, buff=SMALL_BUFF) prior_words = prior_brace.get_text("Prior") prior_words.add_updater(lambda m: m.next_to(prior_brace, UP, SMALL_BUFF)) thousand_part = prior_prob.get_part_by_tex(N_str) pop_count = Integer(N, edge_to_fix=UL) pop_count.replace(thousand_part) pop_count.match_color(thousand_part) pop_count.set_value(0) prior_prob.replace_submobject(2, pop_count) VGroup(population, prior_prob, prior_brace, prior_words).to_corner(UL) self.add(prior_prob) # Before word before_words = OldTexText( "Probability of having the disease\\\\ ", "\\emph{before} taking a test" ) before_words.set_color(BLUE_B) before_words.next_to(prior_words, RIGHT, buff=3, aligned_edge=UP) before_arrow1 = Arrow(before_words[0][0].get_left(), prior_prob.get_right() + MED_SMALL_BUFF * RIGHT) before_arrow2 = Arrow(before_words[0][0].get_left(), prior_words.get_right()) before_arrow1.match_color(before_words) before_arrow2.match_color(before_words) self.play( FadeIn(before_words, lag_ratio=0.1), GrowArrow(before_arrow1), ShowIncreasingSubsets(population, run_time=2), ChangeDecimalToValue(pop_count, len(population), run_time=2), ) self.wait() self.play( GrowFromCenter(prior_brace), FadeIn(prior_words, shift=0.5 * UP), ReplacementTransform(before_arrow1, before_arrow2) ) self.wait() # Update arrow update_arrow = Arrow(2 * LEFT, 2 * RIGHT) update_arrow.set_thickness(0.1) update_arrow.center() update_arrow.match_y(pop_count) update_words = OldTexText("See positive test", tex_to_color_map={"positive": GREEN}) update_words.next_to(update_arrow, UP, SMALL_BUFF) low_update_words = OldTexText("Update probability", font_size=36) low_update_words.next_to(update_arrow, DOWN, MED_SMALL_BUFF) # Posterior post_pop = population[:post_denom].copy() post_pop.arrange_in_grid( buff=get_norm(population[1].get_left() - population[0].get_right()) ) post_pop.match_height(population) post_pop.next_to( update_arrow, RIGHT, buff=abs(population.get_right()[0] - update_arrow.get_left()[0]) ) post_pop.align_to(population, UP) def give_pop_plusses(pop): for icon in pop: plus = OldTex("+") plus.set_color(GREEN) plus.set_width(icon.get_width() / 2) plus.move_to(icon.get_corner(UR)) icon.add(plus) give_pop_plusses(post_pop) post_prob = prior_prob.copy() post_prob[2].set_value(post_denom) post_prob.next_to(post_pop, UP, buff=MED_LARGE_BUFF) roughly = OldTexText("(roughly)", font_size=24) roughly.next_to(post_prob, RIGHT, buff=0.2) post_prob[2].set_value(0) self.play( FadeIn(update_words, lag_ratio=0.2), FadeOut(before_words), ReplacementTransform(before_arrow2, update_arrow, path_arc=30 * DEGREES), FadeIn(low_update_words, lag_ratio=0.2), ) self.add(post_prob) self.play( ShowIncreasingSubsets(post_pop, run_time=1), ChangeDecimalToValue(post_prob[2], post_denom, run_time=1), FadeIn(roughly), ) self.wait() post_brace = Brace(post_prob, UP, buff=SMALL_BUFF) post_words = post_brace.get_text("Posterior") post_words.add_updater(lambda m: m.next_to(post_brace, UP, SMALL_BUFF)) post_words.update(0) self.play( GrowFromCenter(post_brace), FadeIn(post_words, shift=0.5 * UP) ) self.wait() post_group = VGroup( update_arrow, update_words, post_pop, post_prob, post_brace, post_words, ) post_group.save_state() return # Change prior and posterior pop100, pop11, pop10, pop2 = pops = [ VGroup(*[woman.copy() for x in range(n)]) for n in [100, 11, 10, 2] ] for pop in pops: pop.arrange_in_grid() pop.set_fill(GREY) pop[0].set_fill(YELLOW) pop.scale( post_pop[0].get_height() / pop[0].get_height() ) pop100.replace(population) pop11.move_to(post_pop, UP) pop11.shift(0.2 * LEFT) pop10.move_to(population, UP) pop10.shift(0.4 * LEFT) pop2.move_to(post_pop, UP) pop2.shift(0.3 * LEFT) give_pop_plusses(pop11) give_pop_plusses(pop2) def replace_population_anims(old_pop, new_pop, count, brace): count.set_value(len(new_pop)) brace.generate_target() brace.target.match_width( Line(brace.get_left(), count.get_right()), about_edge=LEFT, stretch=True, ) count.set_value(len(old_pop)) return [ FadeOut(old_pop, lag_ratio=0.1), ShowIncreasingSubsets(new_pop), ChangeDecimalToValue(count, len(new_pop)), MoveToTarget(brace) ] self.play( *replace_population_anims(population, pop100, prior_prob[2], prior_brace) ) self.play( *replace_population_anims(post_pop, pop11, post_prob[2], post_brace), ) self.wait(2) self.play( *replace_population_anims(pop100, pop10, prior_prob[2], prior_brace), prior_words.shift, 0.1 * LEFT ) self.play( *replace_population_anims(pop11, pop2, post_prob[2], post_brace) ) self.wait(2) class NewContrastThreeContexts(Scene): def construct(self): # Background bg_rect = FullScreenFadeRectangle() bg_rect.set_fill(GREY_E, 1) self.add(bg_rect) # Scene templates screens = VGroup(*( ScreenRectangle() for x in range(3) )) screens.set_stroke(WHITE, 2) screens.set_fill(BLACK, 1) screens.arrange(DOWN, buff=LARGE_BUFF) screens.set_height(FRAME_HEIGHT - 1) screens.next_to(ORIGIN, RIGHT) self.add(screens) # Prevalence values dots_template = VGroup(*(Dot() for x in range(1000))) dots_template.arrange_in_grid(20, 50, buff=SMALL_BUFF) dots_template.set_fill(GREY_B) dot_groups = VGroup() for screen, n in zip(screens, [1, 10, 100]): dots = dots_template.copy() dots.match_width(screen) dots.scale(0.9) dots.move_to(screen, DOWN) dots.shift(0.1 * UP) for dot in random.sample(list(dots), n): dot.set_fill(YELLOW) dot_groups.add(dots) prevalence_labels = VGroup( OldTexText("Prevalence: ", "0.1\\%"), OldTexText("Prevalence: ", "1\\%"), OldTexText("Prevalence: ", "10\\%"), ) for label, dots in zip(prevalence_labels, dot_groups): label.scale(0.75) label[1].set_color(YELLOW) label.next_to(dots, UP, buff=0.15) self.add(prevalence_labels) self.add(dot_groups) # Words words = VGroup( OldTexText("Same", " test"), OldTexText("Same", " accuracy"), OldTexText("Same", " result"), ) words.scale(1.5) words.arrange(DOWN, aligned_edge=LEFT, buff=MED_LARGE_BUFF) words.to_edge(LEFT) words.set_stroke(BLACK, 3, background=True) for word in words[:2]: self.add(word) self.wait() # Show receiving results def get_positive_result(): woman = WomanIcon() clipboard = SVGMobject( "clipboard", stroke_width=0, fill_color=interpolate_color(GREY_BROWN, WHITE, 0.2) ) clipboard.set_width(1) clipboard.next_to(woman, LEFT) content = OldTexText("+\\\\", "Cancer\\\\detected") content[0].scale(2, about_edge=DOWN) content[0].set_color(GREEN) content[0].set_stroke(GREEN, 3) content[0].shift(SMALL_BUFF * UP) content.set_width(0.7 * clipboard.get_width()) content.move_to(clipboard) content.shift(SMALL_BUFF * DOWN) clipboard.add(content) result = VGroup(woman, clipboard) result.scale(0.7) return result globals()['get_positive_result'] = get_positive_result positive_results = VGroup(*( get_positive_result() for screen in screens )) positive_results.generate_target() positive_results.set_opacity(0) for screen, result in zip(screens, positive_results.target): result.set_height(screen.get_height() * 0.5) result.next_to(screen, RIGHT, MED_LARGE_BUFF, aligned_edge=DOWN) result.shift(0.25 * UP) self.add(words[2]) self.play(MoveToTarget(positive_results)) self.wait() # Different results probs = VGroup(*( Integer(0, unit="\\%").next_to(result, UP) for result in positive_results )) probs.set_fill(GREEN) result_change_anims = [ ChangeDecimalToValue(probs[0], 1), ChangeDecimalToValue(probs[1], 9), ChangeDecimalToValue(probs[2], 53), UpdateFromAlphaFunc( Mobject(), lambda m, a, probs=probs: probs.set_opacity(a), remover=True, ), ] # Odds prior_probs = VGroup(*(pl[1] for pl in prevalence_labels)) prior_odds = VGroup( OldTexText("1:999"), OldTexText("1:99"), OldTexText("1:9"), ) prior_odds.set_color(YELLOW) for po, pp in zip(prior_odds, prior_probs): po.match_height(pp) po.scale(0.8) po.move_to(pp, LEFT) post_odds = VGroup( OldTexText("10:999"), OldTexText("10:99"), OldTexText("10:9"), ) for po, prob in zip(post_odds, probs): po.match_color(prob) po.match_height(prob) po.scale(0.8) po.move_to(prob, LEFT) # Show updates arrows = VGroup(*( Arrow( prior.get_corner(UR), post.get_corner(UL), buff=0.1, path_arc=-45 * DEGREES, ) for prior, post in zip(prior_odds, post_odds) )) arrows.set_color(BLUE) # What test accuracy does ta_words = VGroup( OldTexText("Test", " accuracy"), OldTexText("\\emph{alone} ", "does not"), OldTexText("determine", "."), OldTexText("\\,", "your chances"), ) ta_words[2][1].set_opacity(0) ta_words[1].set_color_by_tex("not", RED) up_words = VGroup( OldTexText("Test", " accuracy"), OldTexText("determine", "s"), OldTexText("how", " your chances"), OldTexText("are", " \\emph{updated}"), ) up_words[3][1].set_color(BLUE) up_words[3].shift(SMALL_BUFF * UP) up_words[0].shift(SMALL_BUFF * DOWN) for group in ta_words, up_words: group.arrange(DOWN, buff=0.3, aligned_edge=LEFT) group.scale(1.5) group.to_edge(LEFT) group.set_stroke(BLACK, 3, background=True) self.play(*result_change_anims) self.play( FadeOut(words[0][0]), FadeOut(words[1][0]), FadeOut(words[2]), ReplacementTransform(words[0][1], ta_words[0][0]), ReplacementTransform(words[1][1], ta_words[0][1]), LaggedStartMap(FadeIn, ta_words[1:]), ) self.add(ta_words) self.wait() self.play( FadeOut(prior_probs, 0.25 * UP), FadeOut(probs, 0.25 * UP), FadeIn(prior_odds, 0.25 * UP), FadeIn(post_odds, 0.25 * UP), ) self.play( ReplacementTransform(ta_words[0], up_words[0]), ReplacementTransform(ta_words[2], up_words[1]), FadeIn(up_words[2][0], scale=2), ReplacementTransform(ta_words[3][1], up_words[2][1]), FadeOut(ta_words[1], scale=0.5), ) self.play( Write(up_words[3]), LaggedStartMap(DrawBorderThenFill, arrows), ) self.wait() class BayesFactor(Scene): def construct(self): # Test sensitivity woman = WomanIcon() bc_pop = VGroup(*[woman.copy() for x in range(100)]) bc_pop.arrange_in_grid(h_buff=1.5, v_buff=1) bc_pop.set_height(4) bc_pop.next_to(ORIGIN, LEFT, MED_LARGE_BUFF) bc_rect = SurroundingRectangle(bc_pop, buff=0.15) bc_rect.set_stroke(YELLOW, 2) with_bc_label = OldTexText( "Patients with\\\\breast cancer", font_size=36, color=bc_rect.get_color() ) with_bc_label.next_to(bc_rect, UP) bc_pop.generate_target() bc_signs = VGroup() for n, icon in enumerate(bc_pop.target): if n < 90: sign = OldTex("+", color=GREEN) icon.set_color(GREEN) else: sign = OldTex("-", color=RED) icon.set_color(RED) sign.match_width(icon) sign.move_to(icon.get_corner(UR), LEFT) bc_signs.add(sign) sens_brace = Brace(bc_pop[:90], LEFT, buff=MED_SMALL_BUFF) sens_word = sens_brace.get_text("90\\% Sens.") sens_word.set_color(GREEN) fnr_brace = Brace(bc_pop[90:], LEFT, buff=MED_SMALL_BUFF) fnr_word = fnr_brace.get_text("10\\% FNR") fnr_word.set_color(RED_E) bc_group = VGroup( with_bc_label, bc_rect, bc_pop, bc_signs, sens_brace, sens_word, fnr_brace, fnr_word, ) # Specificity (too much copy paste) nc_pop = bc_pop.copy() nc_pop.next_to(ORIGIN, RIGHT, MED_LARGE_BUFF) nc_rect = SurroundingRectangle(nc_pop, buff=0.15) nc_rect.set_stroke(GREY_B, 2) without_bc_label = OldTexText( "Patients without\\\\breast cancer", font_size=36, color=nc_rect.get_color() ) without_bc_label.next_to(nc_rect, UP) nc_pop.generate_target() nc_signs = VGroup() for n, icon in enumerate(nc_pop.target): if 0 < n < 10: sign = OldTex("+", color=GREEN) icon.set_color(GREEN) else: sign = OldTex("-", color=RED) icon.set_color(RED) sign.match_width(icon) sign.move_to(icon.get_corner(UR), LEFT) nc_signs.add(sign) spec_brace = Brace(nc_pop[10:], RIGHT, buff=MED_SMALL_BUFF) spec_word = spec_brace.get_text("91\\% Spec.") spec_word.set_color(RED) fpr_brace = Brace(nc_pop[:10], RIGHT, buff=MED_SMALL_BUFF) fpr_word = fpr_brace.get_text("9\\% FPR") fpr_word.set_color(GREEN_D) nc_group = VGroup( without_bc_label, nc_rect, nc_pop, nc_signs, spec_brace, spec_word, fpr_brace, fpr_word, ) # Draw groups self.play(LaggedStart( FadeIn(with_bc_label), ShowCreation(bc_rect), ShowIncreasingSubsets(bc_pop), FadeIn(without_bc_label), ShowCreation(nc_rect), ShowIncreasingSubsets(nc_pop), )) self.play(LaggedStart( MoveToTarget(bc_pop), FadeIn(bc_signs, lag_ratio=0.02), GrowFromCenter(sens_brace), FadeIn(sens_word, shift=0.2 * LEFT), GrowFromCenter(fnr_brace), FadeIn(fnr_word, shift=0.2 * LEFT), )) self.play(LaggedStart( MoveToTarget(nc_pop), FadeIn(nc_signs, lag_ratio=0.02), GrowFromCenter(spec_brace), FadeIn(spec_word, shift=0.2 * RIGHT), GrowFromCenter(fpr_brace), FadeIn(fpr_word, shift=0.2 * RIGHT), )) self.wait() groups = VGroup(bc_group, nc_group) # Highlight relevant parts fade_rects = VGroup(*(BackgroundRectangle(group) for group in groups)) fade_rects.set_fill(BLACK, 0.8) self.play(FadeIn(fade_rects[1])) self.play(LaggedStart(*( ShowCreationThenFadeOut(Underline(word)) for word in [sens_word, fnr_word] ), lag_ratio=0.4)) self.play( FadeIn(fade_rects[0]), FadeOut(fade_rects[1]), ) self.play(LaggedStart(*( ShowCreationThenFadeOut(Underline(word)) for word in [spec_word, fpr_word] ), lag_ratio=0.4)) self.wait() self.play(FadeOut(fade_rects[0])) # None of these are your answer title = OldTex( "\\text{None of these tell you }", "P(\\text{Cancer} \\,|\\, +)", tex_to_color_map={ "\\text{Cancer}": YELLOW, "+": GREEN, }, font_size=72, ) title.to_edge(UP) title_underline = Underline(title) self.play( FadeIn(title, lag_ratio=0.1), groups.to_edge, DOWN, ) self.play(ShowCreation(title_underline)) self.wait() title.add(title_underline) # Ask about update strength question = OldTexText("How strongly\\\\does it update?") question.set_height(1) question.to_corner(UL) question.save_state() question.replace(title, 1) question.set_opacity(0) self.play( Restore(question), title.replace, question.saved_state, 0, title.set_opacity, 0, ) self.remove(title) self.wait() # Write Bayes factor frac = VGroup( sens_word.copy(), OldTex("\\qquad \\over \\qquad"), fpr_word.copy(), ) frac[1].match_width(frac[0], stretch=True) frac.arrange(DOWN, SMALL_BUFF) frac.next_to(question, RIGHT, LARGE_BUFF) mid_rhs = OldTex( "= {P(+ \\,|\\, \\text{Cancer}) \\over P(+ \\,|\\, \\text{No cancer})}", tex_to_color_map={ "+": GREEN, "\\text{Cancer}": YELLOW, "\\text{No cancer}": GREY_B, } ) mid_rhs.next_to(frac, RIGHT) rhs = OldTex("= 10", font_size=72) rhs.next_to(mid_rhs, RIGHT) for part in frac[0::2]: part.save_state() frac[0].replace(sens_word) frac[2].replace(fpr_word) s_rect = SurroundingRectangle(frac[0]) self.play(ShowCreation(s_rect)) self.play( Restore(frac[0]), s_rect.move_to, frac[0].saved_state, s_rect.set_opacity, 0, Write(frac[1]), Restore(frac[2]), ) self.wait(2) self.play(Write(mid_rhs)) self.wait() self.play(Write(rhs)) self.wait() # Name the Bayes factor bf_name = OldTexText("Bayes\\\\Factor ", font_size=72) equals = OldTex("=", font_size=72).next_to(frac, LEFT) bf_name.next_to(equals, LEFT) lr_name = OldTexText("Likelihood\\\\ratio") lr_name.next_to(equals, LEFT) self.play( FadeOut(question, UP), FadeIn(bf_name, UP), FadeIn(equals, UP), ) self.wait() self.play( FadeOut(bf_name, UP), FadeIn(lr_name, UP), ) self.wait() self.play( FadeIn(bf_name, DOWN), FadeOut(lr_name, DOWN), ) self.wait(5) class RuleOfThumb(Scene): def construct(self): # Add Bayes factor t2c = { "+": GREEN, "\\text{Cancer}": YELLOW, "\\text{No cancer}": GREY_B, "=": WHITE, "\\over": WHITE, "{90\\%": GREEN, "9\\%}": GREEN, "1\\%}": TEAL, "{10}": GREEN, } frac_part = OldTex( """ {P(+ \\, | \\, \\text{Cancer}) \\over P(+ \\, | \\, \\text{No cancer})} """, tex_to_color_map=t2c ) frac_part.add(SurroundingRectangle( frac_part, buff=0.1, stroke_width=1, stroke_color=GREY_B )) ex_part = OldTex( "\\text{e.g. } {90\\% \\over 9\\%} = {10}", tex_to_color_map=t2c ) ex_part.next_to(frac_part, RIGHT, LARGE_BUFF) brace = Brace(frac_part, UP, buff=SMALL_BUFF) bf_label = brace.get_text("Bayes factor") bf_label.set_color(GREEN) bf_group = VGroup(frac_part, ex_part, brace, bf_label) bf_group.to_corner(DL) self.add(bf_group) # Lightbulb bulb = Lightbulb() condition = OldTexText("If Prior $\\ll$ 1 \\dots", tex_to_color_map={"Prior": YELLOW}) condition.next_to(bulb, RIGHT, buff=MED_LARGE_BUFF, aligned_edge=DOWN) bulb_group = VGroup(bulb, condition) bulb_group.center().to_edge(UP) self.play(DrawBorderThenFill(bulb, run_time=1)) self.play(FadeIn(condition, lag_ratio=0.1)) self.wait() # Equation equation = OldTexText( "Posterior", " $\\approx$ ", "(", "Prior", ")", "(", "Bayes factor", ")", tex_to_color_map={ "Prior": YELLOW, "Bayes factor": GREEN, } ) equation.next_to(bulb_group, DOWN, LARGE_BUFF) self.play(Write(equation[:2]), run_time=1) self.wait() self.play( FadeIn(equation.get_parts_by_tex("(")), FadeIn(equation.get_parts_by_tex(")")), TransformFromCopy( condition.get_part_by_tex("Prior"), equation.get_part_by_tex("Prior") ), TransformFromCopy( bf_label[0], equation.get_part_by_tex("Bayes factor"), ), ) self.wait() # 1% example ex_rhs = OldTex( "\\left({1 \\over 100}\\right)({10}) = {1 \\over 10}", tex_to_color_map={ "1 \\over 100": YELLOW, "{10}": GREEN, } ) ex_rhs.next_to(equation, DOWN, MED_LARGE_BUFF) ex_rhs.shift(RIGHT) ex_lhs = OldTex("{1 \\over 11} \\approx") ex_lhs.next_to(ex_rhs, LEFT) self.play(FadeIn(ex_rhs, DOWN)) self.wait() self.play(Write(ex_lhs)) self.wait() # 10% example randy = Randolph(height=2) randy.next_to(bf_label, UP, SMALL_BUFF) self.play( FadeOut(ex_lhs), FadeOut(ex_rhs), VFadeIn(randy), randy.change, "hesitant", ) self.play(Blink(randy)) self.wait() ex2_rhs = OldTex( "(10\\%)({10}) = 100\\%", tex_to_color_map={ "10\\%": YELLOW, "{10}": GREEN, "=": WHITE, } ) ex2_rhs.move_to(ex_rhs, LEFT) ex2_rhs.shift(0.15 * RIGHT) eq_index = ex2_rhs.index_of_part_by_tex("=") self.play( Write(ex2_rhs[:eq_index]), randy.change, "confused", ) self.play(Blink(randy)) self.play(Write(ex2_rhs[eq_index:])) self.wait() self.play(Blink(randy)) ex2_lhs = OldTex("53\\%", "\\approx") ex2_lhs.next_to(ex2_rhs, LEFT) ex2_lhs.align_to(equation.get_part_by_tex("\\approx"), RIGHT) approx_part = ex2_lhs.get_part_by_tex("\\approx") approx_part.scale(1.2, about_edge=DL) strike = Line(DL, UR).replace(approx_part, stretch=True) strike.set_stroke(RED, 6) strike.stretch(0.7, 0) strike.stretch(1.5, 1) self.play( Write(ex2_lhs, run_time=1), randy.look_at, ex2_lhs, ) self.play( randy.change, "sad", ex2_lhs, ShowCreation(strike, run_time=0.3) ) self.play(Blink(randy)) self.wait() self.play( randy.change, "tired", ex2_lhs, ) self.play(Blink(randy)) self.wait() ex2 = VGroup(ex2_lhs, strike, ex2_rhs) # This statement is actually true morty = Mortimer() morty.replace(randy, dim_to_match=1) morty.to_edge(RIGHT, buff=1.5) self.play( VFadeIn(morty), morty.change, "tease", equation, FadeOut(ex2, UP), FadeOut(VGroup(bulb, condition), UP), equation.match_y, randy, randy.change, "erm", ) self.play(Blink(morty)) eq = OldTex("=") approx = equation.get_part_by_tex("\\approx") eq.replace(approx) self.play( PiCreatureSays( morty, "This equation\\\\is precisely true!", bubble_config={"height": 2, "width": 3}, look_at=randy.eyes, ), GrowFromPoint(eq, morty.get_corner(UL)), FadeOut(approx, 0.25 * DL), randy.change, "confused", morty.eyes, ) self.play(Blink(randy)) self.play(Blink(morty)) self.wait(3) class ProbabilityVsOdds(Scene): def construct(self): # Show titles and division titles = VGroup( OldTexText("Probability"), OldTexText("Odds"), ) for title, u in zip(titles, [-1, 1]): title.scale(1.5) title.to_edge(UP) title.set_x(FRAME_WIDTH * u / 4) h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH) h_line.next_to(titles, DOWN, SMALL_BUFF) h_line.set_x(0) v_line = Line(UP, DOWN) v_line.set_height(FRAME_HEIGHT) v_line.center() VGroup(h_line, v_line).set_stroke(GREY, 2) titles.save_state() for title in titles: title.set_x(0) titles[1].set_opacity(0) self.add(titles) self.wait() self.play( Restore(titles), ShowCreation(v_line), ) self.play(ShowCreation(h_line)) self.wait() # Function definitions def get_people_row(n_all, n_pos=1): icon = SVGMobject("person") icon.set_fill(GREY) icon.set_stroke(WHITE, 1) icon.set_height(1) people = VGroup(*(icon.copy() for x in range(n_all))) people.arrange(RIGHT, buff=SMALL_BUFF) people[:n_pos].set_fill(YELLOW) return people def get_prob_counts(people, n_pos, n_all): pos_brace = Brace(people[:n_pos], UP, buff=SMALL_BUFF) all_brace = Brace(people, DOWN, buff=SMALL_BUFF) pos_label = Integer(n_pos, color=YELLOW) all_label = Integer(n_all) pos_label.next_to(pos_brace, UP) all_label.next_to(all_brace, DOWN) return VGroup( VGroup(pos_brace, pos_label), VGroup(all_brace, all_label), ) def get_odds_counts(people, n_pos, n_neg): pos_brace = Brace(people[:n_pos], UP, buff=SMALL_BUFF) neg_brace = Brace(people[n_pos:], UP, buff=SMALL_BUFF) pos_label = Integer(n_pos, color=YELLOW) neg_label = Integer(n_neg, color=GREY_B) pos_label.next_to(pos_brace, UP) neg_label.next_to(neg_brace, UP) return VGroup( VGroup(pos_brace, pos_label), VGroup(neg_brace, neg_label), ) def get_prob_label(n_pos, n_all): result = VGroup( Integer(n_pos, color=YELLOW), OldTex("/"), Integer(n_all), ) result.scale(1.5) result.arrange(RIGHT, buff=0.1) return result def get_odds_label(n_pos, n_neg): result = VGroup( Integer(n_pos, color=YELLOW), OldTex(":"), Integer(n_neg, color=GREY_B), ) result.scale(1.5) result.arrange(RIGHT, buff=0.2) return result # Show probability people = get_people_row(5) people.match_x(titles[0]) people.shift(DOWN) prob_counts = get_prob_counts(people, 1, 5) prob = get_prob_label(1, 5) prob.next_to(people, UP, MED_LARGE_BUFF) self.play( FadeIn(people, lag_ratio=0.3), Write(prob) ) self.wait() self.play( prob.shift, 1.5 * UP, TransformFromCopy(prob[0], prob_counts[0][1]), GrowFromCenter(prob_counts[0][0]), ) self.play( TransformFromCopy(prob[2], prob_counts[1][1]), GrowFromCenter(prob_counts[1][0]), ) self.wait() # Transition to odds right_people = people.copy() right_people.match_x(titles[1]) odds = get_odds_label(1, 4) odds.match_x(right_people) odds.match_y(prob) arrow = Arrow(prob.get_right(), odds.get_left(), buff=1) arrow.set_thickness(0.1) odds_count = get_odds_counts(right_people, 1, 4) self.play( TransformFromCopy(people, right_people), TransformFromCopy( odds.copy().replace(prob).set_opacity(0), odds ), GrowArrow(arrow), ) self.wait() self.play( TransformFromCopy(odds[0], odds_count[0][1]), GrowFromCenter(odds_count[0][0]), ) self.play( TransformFromCopy(odds[2], odds_count[1][1]), GrowFromCenter(odds_count[1][0]), ) self.wait() self.play(ShowCreationThenFadeAround(odds[1])) self.wait() # Other examples people.add(prob_counts) right_people.add(odds_count) def get_example(n_pos, n_all): new_prob = OldTex( f"{int(100 * n_pos / n_all)}\\%", font_size=72 ) new_odds = get_odds_label(n_pos, n_all - n_pos) new_odds.next_to(new_prob, RIGHT, buff=1.5) arrow = Arrow( new_prob.get_right(), new_odds.get_left(), thickness=0.05 ) arrow.set_fill(GREY_A) example = VGroup(new_prob, arrow, new_odds) example.scale(0.5) return example def generate_example_movement(prob, arrow, odds, example): mover = VGroup(prob, arrow.copy(), odds) return ReplacementTransform(mover, example) def transition_to_new_example(n_pos, n_all, example, scene=self, people=people, right_people=right_people, prob=prob, odds=odds, arrow=arrow ): new_people = get_people_row(n_all, n_pos) new_people.set_x(-FRAME_WIDTH / 4) new_right_people = new_people.copy() new_right_people.set_x(FRAME_WIDTH / 4) new_prob = OldTex( f"{int(100 * n_pos / n_all)}\\%", font_size=72 ) new_odds = get_odds_label(n_pos, n_all - n_pos) new_prob.move_to(prob) new_odds.move_to(odds) scene.play( generate_example_movement(prob, arrow, odds, example), FadeOut(people), FadeOut(right_people), FadeIn(new_prob), FadeIn(new_odds), FadeIn(new_people), FadeIn(new_right_people), ) return { "people": new_people, "right_people": new_right_people, "prob": new_prob, "odds": new_odds, } examples = VGroup(*( get_example(n, k) for n, k in [(1, 10), (1, 5), (1, 2), (4, 5), (9, 10)] )) examples.arrange(UP) examples.to_edge(DOWN) kw = {} for n, k, ei in (1, 2, 1), (1, 10, 2), (4, 5, 0), (9, 10, 3): kw = transition_to_new_example( n, k, examples[ei], **kw ) self.wait(2) self.remove(arrow) self.play( generate_example_movement( kw["prob"], arrow, kw["odds"], examples[4], ), FadeOut(kw["people"]), FadeOut(kw["right_people"]), ) # Show ranges left_range = UnitInterval((0, 1, 0.1), width=5) left_range.set_y(1.5) left_range.match_x(titles[0]) right_range = NumberLine((0, 5), width=5, include_tip=True) right_range.match_y(left_range) right_range.match_x(titles[1]) dots = OldTex("\\dots") dots.next_to(right_range, RIGHT) right_range.add(dots) right_range.add(*( right_range.get_tick( 1 / n, right_range.tick_size * (1 / n)**0.5, ).set_opacity((1 / n)**0.5) for n in range(2, 100) )) left_range.add_numbers([0, 0.2, 0.5, 0.8, 1]) right_range.add_numbers() left_ticker = ArrowTip(angle=-90 * DEGREES) left_ticker.set_fill(BLUE) left_ticker.move_to(left_range.n2p(0.5), DOWN) right_ticker = left_ticker.copy() right_ticker.set_color(RED) right_ticker.move_to(right_range.n2p(1), DOWN) self.play( Write(left_range), Write(right_range), run_time=1 ) self.play( FadeIn(left_ticker, shift=DOWN), FadeIn(right_ticker, shift=DOWN), ) rect = SurroundingRectangle(examples[0]) rect.set_opacity(0) prob = ValueTracker(0.5) left_ticker.add_updater( lambda m: m.move_to(left_range.n2p(prob.get_value()), DOWN) ) right_ticker.add_updater( lambda m: m.move_to(right_range.n2p( prob.get_value() / (1 - prob.get_value()) ), DOWN) ) for i, p in enumerate([0.1, 0.2, 0.5, 0.8, 0.9]): self.play( prob.set_value, p, rect.become, SurroundingRectangle(examples[i]), ) self.wait() self.play( FadeOut(rect), ApplyMethod(prob.set_value, 0.5, run_time=4), ) self.wait() class OddsComments(Scene): def construct(self): morty = Mortimer() morty.to_corner(DR) randy = Randolph() randy.next_to(morty, LEFT, buff=2) self.play(FadeIn(morty)) self.play( PiCreatureSays( morty, "The chances are\\\\1 to 1", run_time=1 ), FadeIn(randy) ) self.play(Blink(morty)) self.play( PiCreatureSays(randy, "The chances are\\\\2 to 1", run_time=1), RemovePiCreatureBubble(morty, target_mode="happy") ) self.play(Blink(morty)) self.play(Blink(randy)) self.wait() class NewSnazzyBayesRuleSteps(Scene): def construct(self): # Add title title = OldTexText( "Bayes' rule, the snazzy way", font_size=72 ) title.to_edge(UP) title.set_stroke(BLACK, 2, background=True) underline = Underline(title) underline.scale(1.2) underline.shift(0.2 * UP) underline.set_stroke(GREY, 3) self.add(underline, title) # Completely accurate accurate_words = OldTexText( *"Completely accurate\\\\ Not even approximating things".split(" "), font_size=72, arg_separator=" " ) accurate_words.set_color(BLUE) for word in accurate_words: self.add(word) self.wait(0.05 * len(word)) # Population population = VGroup(*( WomanIcon() for x in range(100) )) population.arrange_in_grid(h_buff=1, v_buff=0.5, fill_rows_first=False) population.set_height(5) population.to_corner(DR) population[0].set_color(YELLOW) # Step labels step_labels = VGroup( OldTexText("Step 1)"), OldTexText("Step 2)"), OldTexText("Step 3)"), ) step_labels.arrange(DOWN, buff=1.5, aligned_edge=LEFT) step_labels.next_to(title, DOWN, MED_LARGE_BUFF) step_labels.to_edge(LEFT) step1, step2, step3 = steps = VGroup( OldTexText("Express the prior with odds"), OldTexText("Compute Bayes' factor"), OldTexText("Multiply"), ) colors = [YELLOW, GREEN, BLUE] for step, label, color in zip(steps, step_labels, colors): step.set_color(color) step.next_to(label, RIGHT) self.play( LaggedStartMap(FadeIn, step_labels, shift=0.5 * RIGHT), LaggedStartMap(FadeIn, steps, shift=RIGHT), FadeOut(accurate_words), ) self.wait() # Step 2 details tex_to_color_map = { "+": GREEN, "\\text{Cancer}": YELLOW, "\\text{No cancer}": GREY_B, "=": WHITE, "\\over": WHITE, "{90\\%": GREEN, "9\\%}": GREEN, "1\\%}": TEAL, "10": WHITE, } bf_computation = OldTex( """ { P(+ \\, | \\, \\text{Cancer}) \\over P(+ \\, | \\, \\text{No cancer}) } = {90\\% \\over 9\\%} = 10 """, tex_to_color_map=tex_to_color_map ) bf_computation[-1].scale(1.2) bf_computation.scale(0.6) bf_computation.next_to(step2, DOWN, aligned_edge=LEFT) bf_computation.save_state() bf_computation.scale(1.5) bf_computation.next_to(steps[1], RIGHT, LARGE_BUFF) lr_words = OldTexText("``Likelihood ratio''", font_size=30) lr_words.next_to(bf_computation[-1], RIGHT, MED_LARGE_BUFF, DOWN) lr_words.set_color(GREY_A) sens_part = bf_computation.get_part_by_tex("90\\%") sens_word = OldTexText("Sensitivity") sens_word.next_to(sens_part, UP, buff=1) sens_arrow = Arrow(sens_word.get_bottom(), sens_part.get_top(), buff=0.1) fpr_part = bf_computation.get_part_by_tex("9\\%") fpr_word = OldTexText("FPR") fpr_word.next_to(fpr_part, DOWN, buff=1) fpr_arrow = Arrow(fpr_word.get_top(), fpr_part.get_bottom(), buff=0.1) self.play(FadeIn(bf_computation, lag_ratio=0.1)) self.wait() self.play( Indicate(sens_part), FadeIn(sens_word), GrowArrow(sens_arrow) ) self.wait() self.play( Indicate(fpr_part), FadeIn(fpr_word), GrowArrow(fpr_arrow), ) self.wait(2) self.play( Restore(bf_computation), FadeOut(VGroup(sens_word, sens_arrow, fpr_word, fpr_arrow)) ) # Step 1 details step1_subtext = OldTexText("E.g.", " 1\\% ", " $\\rightarrow$ ", "1:99") step1_subtext.set_color(GREY_A) step1_subtext.scale(0.9) step1_subtext.next_to(step1, DOWN, aligned_edge=LEFT) self.play( FadeIn(step1_subtext[:2]), ShowIncreasingSubsets(population), ) self.wait() self.play( TransformFromCopy(step1_subtext[1], step1_subtext[3]), Write(step1_subtext[2]), ) self.play(ShowCreationThenFadeAround(step1_subtext[3])) self.wait() # Step 3 multiplication = OldTex( "(", "1:99", ")", "\\times", "10", "=", "10:99", "\\rightarrow", "{10 \\over 109}", "\\approx", "{1 \\over 11}", font_size=36, ) multiplication.next_to(step3, DOWN, aligned_edge=LEFT) odds_rect = SurroundingRectangle(step1_subtext[-1], color=YELLOW) bf_rect = SurroundingRectangle(bf_computation[-1], color=GREEN) self.play( ShowCreation(odds_rect), ShowCreation(bf_rect), ) self.play( Write(VGroup(*(multiplication[i] for i in [0, 2, 3]))), TransformFromCopy(step1_subtext[-1], multiplication[1]), odds_rect.move_to, multiplication[1], odds_rect.set_opacity, 0, TransformFromCopy(bf_computation[-1], multiplication[4]), bf_rect.move_to, multiplication[4], bf_rect.set_opacity, 0, ) self.remove(odds_rect, bf_rect) self.wait() self.play( FadeIn(multiplication.get_part_by_tex("=")), TransformFromCopy( multiplication.get_part_by_tex("1:99"), multiplication.get_part_by_tex("10:99"), path_arc=30 * DEGREES, ), ) self.wait() self.play( FadeIn(multiplication.get_part_by_tex("\\rightarrow")), FadeIn(multiplication.get_part_by_tex("10 \\over 109")), ) self.play( FadeIn(multiplication.get_part_by_tex("\\approx")), FadeIn(multiplication.get_part_by_tex("1 \\over 11")), ) self.wait() # 10% prior example prior_odds = step1_subtext[1:] alt_prior_odds = OldTex( "10\\%", "\\rightarrow", "\\text{1:9}" ) alt_prior_odds.match_height(prior_odds) alt_prior_odds.move_to(prior_odds, LEFT) alt_prior_odds.match_style(prior_odds) self.play( FadeOut(multiplication, shift=DOWN), FadeOut(prior_odds, shift=DOWN), ) self.play( FadeIn(alt_prior_odds[0], scale=2), ) self.play( population[:10].set_color, YELLOW, LaggedStartMap( ShowCreationThenFadeOut, VGroup(*( SurroundingRectangle(person, buff=0.05) for person in population[:10] )) ) ) self.wait() self.play( Write(alt_prior_odds[1]), FadeIn(alt_prior_odds[2], shift=0.5 * RIGHT) ) self.wait() new_multiplication = OldTex( "(1:9)", "\\times", "10", "=", "10:9", "\\rightarrow", "{10 \\over 19}", "\\approx", "0.53", font_size=36, ) new_multiplication.move_to(multiplication, LEFT) rects = VGroup( SurroundingRectangle(alt_prior_odds.get_part_by_tex("1:9"), color=YELLOW), SurroundingRectangle(bf_computation.get_part_by_tex("10"), color=GREEN), SurroundingRectangle(new_multiplication.get_part_by_tex("10:9"), color=RED), ) self.play( FadeIn(rects[:2], lag_ratio=0.6, run_time=1.5) ) self.play( ReplacementTransform(rects[0], rects[2]), ReplacementTransform(rects[1], rects[2]), FadeIn(new_multiplication[:5]), ) self.wait() alt_rhs = OldTex("> 1:1", font_size=36) alt_rhs.next_to(new_multiplication[4], RIGHT) self.play( FadeOut(rects[2]), Write(alt_rhs) ) self.wait() self.play( FadeOut(alt_rhs, shift=0.5 * UP), FadeIn(new_multiplication[5:7], shift=0.5 * UP), ) self.wait() self.play(Write(new_multiplication[7:])) self.wait() # Return to original prior self.play( FadeOut(new_multiplication, shift=DOWN), FadeOut(alt_prior_odds, shift=DOWN), FadeIn(prior_odds, shift=DOWN) ) self.play(population[1:].set_color, GREY_B) self.play(Indicate(population[0], color=RED)) self.play(LaggedStartMap( Indicate, population[1:], color=GREY_A, lag_ratio=0.01 )) self.wait() # Change test accuracy new_bf_computation = OldTex( """ { P(+ \\, | \\, \\text{Cancer}) \\over P(+ \\, | \\, \\text{No cancer}) } = {90\\% \\over 1\\%} = 90 """, tex_to_color_map=tex_to_color_map ) new_bf_computation.replace(bf_computation) new_bf_computation[-2:].scale(1.5, about_edge=LEFT) rects = VGroup(*( SurroundingRectangle(bf_computation[i:j], buff=0.05) for (i, j) in [(5, 8), (14, 15)] )) rects.set_color(RED) self.play(ShowCreation(rects)) self.wait() self.play( FadeOut(bf_computation), FadeIn(new_bf_computation[:-2]) ) self.play(FadeOut(rects)) self.wait() self.play(Write(new_bf_computation[-2:])) self.wait() # New posterior (largely copy-pasted) final_multiplication = OldTex( "(1:99)", "\\times", "90", "=", "90:99", "\\rightarrow", "{90 \\over 189}", "\\approx", "0.48", font_size=36, ) final_multiplication.move_to(multiplication, LEFT) rects = VGroup( SurroundingRectangle(step1_subtext.get_part_by_tex("1:99"), color=YELLOW), SurroundingRectangle(new_bf_computation.get_parts_by_tex("90")[1], color=GREEN), SurroundingRectangle(final_multiplication.get_part_by_tex("90:99"), color=RED), ) self.play( FadeIn(rects[:2], lag_ratio=0.6, run_time=1.5) ) self.play( ReplacementTransform(rects[0], rects[2]), ReplacementTransform(rects[1], rects[2]), FadeIn(final_multiplication[:5]), ) self.wait() alt_rhs = OldTex("< 1:1", font_size=36) alt_rhs.next_to(final_multiplication[4], RIGHT) self.play( FadeOut(rects[2]), Write(alt_rhs) ) self.wait() self.play( FadeOut(alt_rhs, shift=0.5 * UP), FadeIn(final_multiplication[5:7], shift=0.5 * UP), ) self.wait() self.play(Write(final_multiplication[7:])) self.wait() class AskWhyItWorks(TeacherStudentsScene): def construct(self): self.student_says( "Huh? Why does\\\\that work?", target_mode="confused", ) self.play_student_changes( "pondering", "erm", "confused", look_at=self.screen, ) self.play(self.teacher.change, "happy") self.wait(3) class WhyTheBayesFactorTrickWorks(Scene): def construct(self): # Setup before and after titles = VGroup( OldTexText("Before test"), OldTexText("After test"), ) titles.scale(1.25) for title, u in zip(titles, [-1, 1]): title.set_x(u * FRAME_WIDTH / 4) title.to_edge(UP, buff=MED_SMALL_BUFF) h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH) h_line.next_to(titles, DOWN) h_line.set_x(0) v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) lines = VGroup(h_line, v_line) lines.set_stroke(GREY, 2) self.add(titles) self.add(lines) # Show population before population = VGroup(*(WomanIcon() for x in range(100))) population.arrange_in_grid(h_buff=0.7, fill_rows_first=False) population.set_height(5) population[:10].set_fill(YELLOW) population[:10].shift(MED_SMALL_BUFF * LEFT) population.match_x(titles[0]) population.to_edge(DOWN, buff=MED_LARGE_BUFF) w_tex = "(\\text{\\# With})" wo_tex = "(\\text{\\# Without})" t2c = { w_tex: YELLOW, wo_tex: GREY_B, } odds = OldTex(w_tex, ":", wo_tex, tex_to_color_map=t2c) odds.next_to(population, UP, buff=MED_LARGE_BUFF) odds.match_x(titles[0]) self.add(population) self.add(odds) self.play( ShowCreationThenDestruction(Underline(odds[0])), LaggedStartMap( ShowCreationThenFadeOut, VGroup(*( SurroundingRectangle(icon, stroke_width=1, buff=0.05) for icon in population[:10] )) ), ) self.play( ShowCreationThenDestruction(Underline(odds[2])), LaggedStartMap( ShowCreationThenFadeOut, VGroup(*( SurroundingRectangle(icon, color=GREY, stroke_width=1, buff=0.05) for icon in population[10:] )), lag_ratio=0.01 ), ) self.wait() # Turn odds into fraction frac = OldTex( w_tex, "\\over", wo_tex, tex_to_color_map=t2c, font_size=36 ) frac.next_to(h_line, DOWN, MED_LARGE_BUFF) frac.match_x(titles[0]) self.play( ReplacementTransform(odds, frac), population.set_height, 4.5, population.next_to, frac, DOWN, MED_LARGE_BUFF, ) self.wait() # Show filtration pop_copy = population.copy() pop_copy.match_x(titles[1]) tp_cases = pop_copy[:9] fn_cases = pop_copy[9:10] fp_cases = pop_copy[10::10] tn_cases = VGroup(*( case for case in pop_copy[10:] if case not in fp_cases )) VGroup(fn_cases, tn_cases).set_opacity(0.1) VGroup(tp_cases, tp_cases).set_stroke(GREEN, 3, background=True) pos_boxes = VGroup() for case in it.chain(tp_cases, fp_cases): box = SurroundingRectangle(case, buff=0.025) box.set_stroke(GREEN, 0) plus = OldTex("+", font_size=24) plus.move_to(box.get_corner(UR)) plus.shift(DR * plus.get_height() / 4) plus.set_color(GREEN) box.add(plus) pos_boxes.add(box) self.play( TransformFromCopy(population, pop_copy), path_arc=30 * DEGREES ) self.play(LaggedStartMap(DrawBorderThenFill, pos_boxes)) self.wait() # Final fraction t2c.update({ "\\text{Cancer}": YELLOW, "\\text{No cancer}": GREY, "+": GREEN, "\\cdot": WHITE, }) final_frac = OldTex( w_tex, "\\cdot P(+ \\,|\\, \\text{Cancer})", "\\over", wo_tex, "\\cdot P(+ \\,|\\, \\text{No cancer})", tex_to_color_map=t2c, font_size=36, ) final_frac.match_x(pop_copy) final_frac.match_y(frac) left_brace = Brace(tp_cases, LEFT) right_brace = Brace(fp_cases, RIGHT, min_num_quads=1) big_left_brace = Brace(VGroup(tp_cases, fn_cases), LEFT) big_right_brace = Brace(VGroup(fp_cases, tn_cases), RIGHT) big_left_brace.set_opacity(0) big_right_brace.set_opacity(0) self.play(*( TransformFromCopy( frac.get_part_by_tex(tex), final_frac.get_part_by_tex(tex) ) for tex in (w_tex, "\\over") )) self.wait() self.play( TransformFromCopy(big_left_brace, left_brace), Write(final_frac[1:7]) ) self.wait() self.play(*( TransformFromCopy( frac.get_part_by_tex(tex), final_frac.get_part_by_tex(tex) ) for tex in (wo_tex,) )) self.play( TransformFromCopy(big_right_brace, right_brace), Write(final_frac[9:]) ) self.wait() self.add(final_frac) # Circle likelihood ratio likelihood_ratio = VGroup( final_frac[2:7], final_frac[10:] ) lr_rect = SurroundingRectangle(likelihood_ratio) lr_rect.set_stroke(BLUE, 3) self.play(ShowCreation(lr_rect)) self.wait() class ReframeWhatTestsDo(TeacherStudentsScene): def construct(self): # Question question = OldTexText("What do tests tell you?") self.teacher_holds_up(question) self.wait() question.generate_target() question.target.set_height(0.6) question.target.center() question.target.to_edge(UP) self.play( MoveToTarget(question), *[ ApplyMethod(pi.change, "pondering", question.target) for pi in self.pi_creatures ] ) self.wait(2) # Possible answers answers = VGroup( OldTexText("Tests", " determine", " if you have", " a disease."), OldTexText("Tests", " determine", " your chances of having", " a disease."), OldTexText("Tests", " update", " your chances of having", " a disease."), ) students = self.students answers.set_color(BLUE_C) answers.arrange(DOWN) answers.next_to(question, DOWN, MED_LARGE_BUFF) answers[1][2].set_fill(GREY_A) answers[2][2].set_fill(GREY_A) answers[2][1].set_fill(YELLOW) def add_strike_anim(words): strike = Line() strike.replace(words, dim_to_match=0) strike.set_stroke(RED, 5) anim = ShowCreation(strike) words.add(strike) return anim self.play( GrowFromPoint(answers[0], students[0].get_corner(UR)), students[0].change, "raise_right_hand", answers[0], students[1].change, "sassy", students[0].eyes, students[2].change, "sassy", students[0].eyes, ) self.wait() self.play( add_strike_anim(answers[0]), students[0].change, "guilty", ) self.wait() answers[1][2].save_state() answers[1][2].replace(answers[0][2], stretch=True) answers[1][2].set_opacity(0) self.play( TransformFromCopy( answers[0][:2], answers[1][:2], ), TransformFromCopy( answers[0][3], answers[1][3], ), Restore(answers[1][2]), students[0].set_opacity, 0.5, students[0].change, "pondering", answers[1], students[1].change, "raise_right_hand", answers[1], students[2].change, "pondering", answers[1], ) self.wait(2) self.play( add_strike_anim(answers[1]), students[1].change, "guilty", ) self.wait(2) answers[2][1].save_state() answers[2][1].replace(answers[1][1], stretch=True) answers[2][1].set_opacity(0) self.play( *( TransformFromCopy( answers[1][i], answers[2][i], ) for i in [0, 2, 3] ), Restore(answers[2][1]), students[0].change, "pondering", answers[1], students[1].set_opacity, 0.5, students[1].change, "pondering", answers[1], students[2].change, "raise_left_hand", answers[1], ) self.play( self.teacher.change, "happy", students[2].eyes, ) self.wait() # The fundamental reframing new_title = OldTexText( "The Fundamental Reframing", font_size=72, ) new_title.add(Underline(new_title)) new_title.to_edge(UP) self.play( Write(new_title), FadeOut(question), self.students[2].change, "hooray", new_title, answers.shift, 0.5 * DOWN, ) self.wait(3) class PrevalenceVsPrior(Scene): def construct(self): # Prior and prevalence eq = OldTexText( "Prevalence = Prior", tex_to_color_map={ "Prevalence": WHITE, "Prior": YELLOW, } ) eq.shift(UP) prior = eq[2] prev = eq[0] strike = Line(eq.get_left(), eq.get_right()) strike.set_stroke(RED, 4) not_words = OldTexText("Not necessarily!") not_words.set_color(RED) not_words.match_width(eq) not_words.next_to(eq, DOWN, MED_LARGE_BUFF) factors = VGroup( OldTexText("Prevalence"), OldTexText("Symptoms"), OldTexText("Contacts\\\\", "(if contagious)"), ) factors.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) factors.shift(prev.get_center() - factors[0].get_center()) prior.generate_target() prior.target.match_y(factors[1]) prior.target.shift(0.5 * RIGHT) arrows = VGroup(*( Arrow( factor.get_right(), prior.target.get_corner(LEFT + u * UP), buff=0.1, max_tip_length_to_length_ratio=0.25, ) for u, factor in zip([1, 0, -1], factors) )) population = Population(100) population.set_height(7) population.to_edge(LEFT) population.set_fill(GREY_C) random.choice(population).set_color(YELLOW) self.play(Write(prev)) self.play(ShowIncreasingSubsets(population, run_time=3)) self.wait() self.play(Write(eq[1:])) self.wait() self.play( ShowCreation(strike), FadeIn(not_words, shift=0.2 * DOWN, rate_func=squish_rate_func(smooth, 0.3, 1)) ) self.wait() self.play( Uncreate(strike), MoveToTarget(prior), ReplacementTransform(eq[1], arrows), LaggedStartMap(FadeIn, factors[1:], shift=0.25 * DOWN), FadeOut(not_words, shift=DOWN) ) self.remove(prev) self.add(factors) self.wait() # Symptoms randy = Randolph(height=1.5) randy.to_corner(UR) randy.shift(LEFT) self.play(FadeIn(randy)) self.play( ShowCreationThenFadeOut(Underline(factors[1], color=RED)), randy.change, "sick", randy.set_color, SICKLY_GREEN, ) self.wait() # Contagion (implicit) self.play( ShowCreationThenFadeOut(Underline(factors[2][0], color=RED)), ShowCreationThenFadeOut(Underline(factors[2][1], color=RED)), ) self.wait() self.play( LaggedStartMap( FadeOut, VGroup( randy, prior, *arrows, *factors, ), shift=DOWN, ) ) class WhatAboutANegativeResult(Scene): def construct(self): # Test results h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH) h_line.set_stroke(GREY_B, 2) randys = VGroup(Randolph(), Randolph()) randys.set_height(2) clipboards = VGroup( get_covid_clipboard("Cancer", "+", "Detected", GREEN), get_covid_clipboard("Cancer", "$-$", "Not Detected", RED), ) for randy, clipboard, y in zip(randys, clipboards, [2, -2]): randy.set_y(y) randy.to_edge(LEFT) clipboard.match_height(randy) clipboard.next_to(randy, RIGHT) self.add(randys, h_line) self.play( FadeIn(clipboards[0], LEFT), randys[0].change, "horrified", clipboards[0], randys[1].change, "guilty", clipboards[0], ) self.play(Blink(randys[0])) self.play( FadeIn(clipboards[1], LEFT), randys[1].change, "hooray", clipboards[1] ) self.play(Blink(randys[1])) self.wait() # Formulas t2c = { "+": GREEN, "-": RED, "=": WHITE, "\\approx": WHITE, "\\over": WHITE, "\\text{Cancer}": YELLOW, "\\text{No cancer}": GREY_B, "90\\%": GREEN, "9\\%": GREEN_D, "10\\%": RED_D, "91\\%": RED, } equations = VGroup( OldTex( "={P(+ \\,|\\, \\text{Cancer}) \\over P(+ \\,|\\, \\text{No cancer})}", "={90\\% \\over 9\\%} = 10", tex_to_color_map=t2c, ), OldTex( "={P(- \\,|\\, \\text{Cancer}) \\over P(- \\,|\\, \\text{No cancer})}", "={10\\% \\over 91\\%} \\approx {1 \\over 9}", tex_to_color_map=t2c, ), ) for equation, clipboard in zip(equations, clipboards): bf = OldTexText("Bayes\\\\Factor") bf.next_to(equation, LEFT) equation.add_to_back(bf) equation.next_to(clipboard, RIGHT, MED_LARGE_BUFF) self.play( *( FadeIn(equation, lag_ratio=0.1, run_time=2) for equation in equations ), randys[0].change, "pondering", equations[0], randys[1].change, "thinking", equations[0], ) self.wait() # Highlight parts eq = equations[1] frac_parts = VGroup(eq[2:7], eq[8:13]) rects = VGroup(*( SurroundingRectangle(part, buff=0.1, stroke_color=TEAL, stroke_width=3) for part in frac_parts )) self.play(ShowCreationThenFadeOut(rects[0])) self.wait() self.play(ShowCreationThenFadeOut(rects[1])) self.wait() fnr = eq.get_part_by_tex("10\\%") fnr_word = OldTexText("FNR", font_size=36) fnr_word.next_to(fnr, UP, buff=0.8) fnr_arrow = Arrow(fnr_word.get_bottom(), fnr.get_top(), buff=0.1) spec = eq.get_part_by_tex("91\\%") spec_word = OldTexText("Specificity", font_size=36) spec_word.next_to(spec, DOWN, buff=0.8) spec_arrow = Arrow(spec_word.get_top(), spec.get_bottom(), buff=0.1) self.play( FadeIn(fnr_word, 0.5 * UP), GrowArrow(fnr_arrow), ) self.play( FadeIn(spec_word, 0.5 * DOWN), GrowArrow(spec_arrow), ) self.wait() for randy in randys: self.play(Blink(randy)) self.wait() class BayesTheorem(Scene): def construct(self): # Add title title = OldTexText("The usual version of Bayes' rule", font_size=60) title.to_edge(UP, buff=MED_SMALL_BUFF) title_line = Underline(title) title_line.set_stroke(GREY, 2) title_line.shift(SMALL_BUFF * UP) title.add(title_line) # Population prior = 1 / 12 sensitivity = 0.8 specificity = 0.9 rects = VGroup(*[Square() for x in range(4)]) rects.set_stroke(WHITE, 2) rects[:2].set_stroke(YELLOW) rects.set_fill(GREY_D, 1) rects.set_height(3) rects.set_width(3, stretch=True) rects.move_to(3.5 * LEFT + DOWN) rects[:2].stretch(prior, 0, about_edge=LEFT) rects[2:].stretch(1 - prior, 0, about_edge=RIGHT) rects[0].stretch(sensitivity, 1, about_edge=UP) rects[1].stretch(1 - sensitivity, 1, about_edge=DOWN) rects[2].stretch(1 - specificity, 1, about_edge=UP) rects[3].stretch(specificity, 1, about_edge=DOWN) rects[0].set_fill(GREEN_D) rects[1].set_fill(interpolate_color(RED_E, BLACK, 0.5)) rects[2].set_fill(GREEN_E, 0.75) rects[3].set_fill(interpolate_color(RED_E, BLACK, 0.75)) icons = VGroup(*(WomanIcon() for x in range(120))) icons.arrange_in_grid( 10, 12, h_buff=1, v_buff=0.5, fill_rows_first=False, ) icons.replace(rects, dim_to_match=1) icons.scale(0.98) icons.set_fill(GREY_C) icons[:10].set_fill(YELLOW) # Add terminology t2c = { "\\text{Disease}": YELLOW, "\\text{D}": YELLOW, "\\text{$\\neg$D}": GREY_B, "\\text{Not sick}": GREY_B, "{+}": GREEN, "{-}": RED, "\\text{Prior}": YELLOW, "\\text{Sensitivity}": GREEN, "\\text{FPR}": GREEN_D, "\\text{TP}": GREEN, "\\text{FP}": GREEN_D, "(": WHITE, ")": WHITE, "\\over": WHITE, } kw = { "tex_to_color_map": t2c, "font_size": 30, } braces = VGroup( Brace(rects[1], DOWN, buff=SMALL_BUFF), *( Brace(rect, u * RIGHT, buff=SMALL_BUFF) for rect, u in zip(rects, [-1, -1, 1, 1]) ) ) braces.set_fill(GREY_B) terms = VGroup( OldTexText("Prior"), OldTexText("Sens."), OldTexText("FNR"), OldTexText("FPR"), OldTexText("Spec."), ) terms[0].set_color(YELLOW) symbols = VGroup( OldTex("P(\\text{D})", **kw), OldTex("P({+} | \\text{D})", **kw), OldTex("P({-} | \\text{D})", **kw), OldTex("P({+} | \\text{$\\neg$D})", **kw), OldTex("P({-} | \\text{$\\neg$D})", **kw), ) for term, symbol, brace in zip(terms, symbols, braces): term.scale(0.75) term.next_to(brace, brace.direction, buff=SMALL_BUFF) symbol.next_to(brace, brace.direction, buff=SMALL_BUFF) pop_group = VGroup(rects, icons, braces, symbols) pop_group.save_state() pop_group.set_height(5) pop_group.center().to_edge(DOWN) # Formula with jargon lhs = OldTex("P(\\text{Disease} \\text{ given } {+})", **kw) lhs.scale(48 / 30) term_formula = OldTex( """ {(\\text{Prior})(\\text{Sensitivity}) \\over (\\text{Prior})(\\text{Sensitivity}) + (1 - \\text{Prior})(\\text{FPR}) """, **kw, ) tp_formula = OldTex("{\\text{TP} \\over \\text{TP} + \\text{FP}}", **kw) tp_formula.scale(1.25) prob_formula = OldTex( """ P(\\text{D}) P({+} \\,|\\, \\text{D}) \\over P(\\text{D}) P({+} \\,|\\, \\text{D}) + """, """ P(\\text{$\\neg$D}) P({+} \\,|\\, \\text{$\\neg$D}) """, **kw ) simple_prob_formula = OldTex( "P(\\text{D}) P({+} \\,|\\, \\text{D}) \\over P({+})", **kw ) simple_prob_formula.scale(48 / 30) equals = VGroup(*(OldTex("=") for x in range(4))) equals[2:].scale(1.5).rotate(90 * DEGREES) formula = VGroup(lhs, equals[0], tp_formula, equals[1], term_formula) formula.arrange(RIGHT) formula.next_to(title, DOWN, MED_LARGE_BUFF) prob_group = VGroup( equals[2], prob_formula, equals[3], simple_prob_formula, ) prob_group.arrange(DOWN, buff=0.35) prob_group.next_to(term_formula, DOWN, buff=0.35) # Show population self.add(title) self.play(FadeIn(lhs, DL)) self.play(Write(equals[0])) self.wait() self.play(ShowIncreasingSubsets(icons, run_time=2)) self.add(*pop_group) self.play( FadeIn(rects), LaggedStartMap(GrowFromCenter, braces), LaggedStartMap(FadeIn, symbols), run_time=1, ) self.wait() pop_to_fade = VGroup(*icons[8:]) pop_to_fade.remove(*icons[10::10]) self.play( FadeIn(tp_formula), pop_to_fade.set_opacity, 0.1, symbols.set_opacity, 0.25, braces.set_fill, GREY_E, 1, ) self.wait() # Show formula piece by piece prob_formula.save_state() prob_formula.move_to(term_formula, LEFT) srkw = {"buff": 0.025} blank_rects = VGroup( SurroundingRectangle(VGroup(prob_formula[0:10]), **srkw), SurroundingRectangle(VGroup(prob_formula[11:21]), **srkw), SurroundingRectangle(VGroup(prob_formula[22:]), **srkw), ) blank_rects.set_stroke(GREEN, 2) blank_rects.set_fill(GREEN, 0.2) self.play( Write(equals[1]), LaggedStartMap(FadeIn, VGroup( prob_formula.get_part_by_tex("\\over"), prob_formula[21], *blank_rects )) ) self.wait() self.play( symbols[0].set_opacity, 1, braces[0].set_fill, GREY_B, FadeIn(prob_formula[0:4]), ) self.wait() self.play( symbols[1].set_opacity, 1, braces[1].set_fill, GREY_B, FadeIn(prob_formula[4:10]), ) self.wait() self.play( TransformFromCopy(prob_formula[0:10], prob_formula[11:21]) ) self.wait() self.play( FadeIn(prob_formula[22:26]) ) self.wait() self.play( FadeIn(prob_formula[26:]), braces[3].set_fill, GREY_B, symbols[3].set_opacity, 1, ) self.wait() self.play(FadeOut(blank_rects)) self.wait() # Words over symbols self.play( pop_group.replace, pop_group.saved_state, Restore(prob_formula), FadeIn(term_formula, scale=2), FadeIn(equals[2], DOWN), ) terms[2::2].set_opacity(0.2) self.play( FadeOut(symbols), FadeIn(terms), ) self.wait() # Show confused randy = Randolph(height=2) randy.to_edge(DOWN) randy.shift(RIGHT) self.play( VFadeIn(randy), randy.change, 'maybe', prob_formula ) self.play(Blink(randy)) self.play(randy.change, 'confused', prob_formula) self.wait() self.play(Blink(randy)) self.wait() self.play( randy.change, 'pondering', pop_group, ) self.play(Blink(randy)) self.wait() # Show simplify denominator denom_rects = VGroup( SurroundingRectangle(prob_formula[11:], buff=0.025), SurroundingRectangle(simple_prob_formula[11:], buff=0.05), ) denom_rects.set_stroke(GREY_B, 2) self.play( ShowCreation(denom_rects[0]), randy.look_at, denom_rects[0], ) self.wait() self.play( TransformFromCopy(*denom_rects), FadeIn(simple_prob_formula, DOWN), FadeIn(equals[3], DOWN), randy.change, 'erm', simple_prob_formula ) self.play(FadeOut(denom_rects)) self.play(Blink(randy)) self.wait() self.play(randy.change, "thinking") self.play(Blink(randy)) self.wait() self.play(ShowCreation(denom_rects[1])) self.play( TransformFromCopy(*reversed(denom_rects)), randy.change, "sassy", denom_rects[0], ) self.wait() self.play(Blink(randy)) self.wait() class ContrastTwoFormulas(Scene): def construct(self): # Talk through odds formula t2c = { "\\text{D}": YELLOW, "\\text{$\\neg$D}": GREY_B, "{+}": GREEN, "(": WHITE, ")": WHITE, "\\over": WHITE, "O": WHITE, "=": WHITE, "\\text{Prior}": YELLOW, "\\text{Sensitivity}": GREEN, "\\text{Sens.}": GREEN, "\\text{FPR}": GREEN_D, } kw = {"tex_to_color_map": t2c} odds_formula = OldTex( "O(\\text{D} | {+}) =" "O(\\text{D})" "{P({+} | \\text{D}) \\over P({+} | \\text{$\\neg$D})}", **kw ) odds_formula.scale(1.25) bf_part = odds_formula[11:] post_part = odds_formula[:6] prior_part = odds_formula[7:11] post_words = OldTexText( "Odds of having the disease\\\\ \\emph{given} a positive test result", tex_to_color_map={ "disease": YELLOW, "positive": GREEN, } ) post_words.next_to(post_part, UP, buff=1.5) post_words.shift(LEFT) post_arrow = Arrow(post_words.get_bottom(), post_part[:2].get_top(), buff=0.2) prior_words = OldTexText("Prior odds") prior_words.next_to(prior_part, DOWN, buff=1.5) prior_words.shift(LEFT) prior_arrow = Arrow(prior_words.get_top(), prior_part[:2].get_bottom(), buff=0.2) bf_rect = SurroundingRectangle(bf_part, buff=0.1) bf_rect.set_stroke(TEAL, 2) bf_words = OldTexText("Bayes factor") bf_words.next_to(bf_rect, UP) bf_words.match_color(bf_rect) self.play(Write(odds_formula)) self.wait() self.play( FadeIn(post_words, lag_ratio=0.1), GrowArrow(post_arrow), ) self.wait() self.play( FadeIn(prior_words), GrowArrow(prior_arrow), ) self.wait() VGroup(bf_rect, bf_words).shift(SMALL_BUFF * RIGHT) self.play( FadeIn(bf_words, 0.25 * UP), ShowCreation(bf_rect), bf_part.shift, SMALL_BUFF * RIGHT, ) self.wait() # Sweep aside to_fade = VGroup(post_words, post_arrow, prior_words, prior_arrow) odds_formula.add(bf_rect, bf_words) v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) v_line.set_stroke(GREY_B, 2) titles = VGroup( OldTexText("Using probability"), OldTexText("Using odds"), ) titles.scale(1.25) for title, u in zip(titles, [-1, 1]): title.set_x(u * FRAME_WIDTH / 4) titles.to_edge(UP) self.play( ShowCreation(v_line), FadeOut(to_fade, shift=UR, scale=0.5), odds_formula.scale, 0.7, odds_formula.next_to, titles[1], DOWN, LARGE_BUFF, FadeIn(titles[0], LEFT), FadeIn(titles[1], RIGHT), ) self.wait() # Contrast with usual formula prob_formula = OldTex( """ P(\\text{D} | {+}) = {P(\\text{D}) P({+} \\,|\\, \\text{D}) \\over P(\\text{D}) P({+} \\,|\\, \\text{D}) + P(\\text{$\\neg$D}) P({+} \\,|\\, \\text{$\\neg$D})} """, **kw ) prob_rhs = prob_formula[7:] prob_formula.set_width(FRAME_WIDTH / 2 - 1) prob_formula.set_x(-FRAME_WIDTH / 4) prob_formula.match_y(bf_part) self.play(FadeIn(prob_formula, shift=0.25 * DOWN, scale=1.2)) self.wait() # Use term-based formulas term_formula = OldTex( """ {(\\text{Prior})(\\text{Sensitivity}) \\over (\\text{Prior})(\\text{Sensitivity}) + (1 - \\text{Prior})(\\text{FPR}) """, **kw ) term_formula.replace(prob_rhs, 0) bf_terms = OldTex( "\\text{Sensitivity} \\over \\text{FPR}", **kw ) bf_terms.replace(bf_part, 0) self.play( FadeOut(prob_rhs, 0.5 * UP), FadeIn(term_formula, 0.5 * UP), FadeOut(bf_part, 0.5 * UP), FadeIn(bf_terms, 0.5 * UP), ) self.wait() # Comment on prior/test separation kw2 = { "tex_to_color_map": { "Prior": YELLOW, "test accuracy": GREEN, "separate": GREY_A, "intermingled": GREY_A, } } pt_comments = VGroup( OldTexText("Prior and test accuracy\\\\are intermingled", **kw2), OldTexText("Prior and test accuracy\\\\are separate", **kw2), ) for comment, formula in zip(pt_comments, [prob_formula, odds_formula]): comment.match_x(formula) pt_comments.set_y(-2) self.play(Write(pt_comments[1], run_time=1)) self.play( VGroup(bf_terms, bf_rect, bf_words).shift, 0.25 * UR, prior_part.shift, 0.25 * UL, rate_func=there_and_back_with_pause, run_time=2, ) self.wait() self.play( TransformFromCopy(pt_comments[1][:-1], pt_comments[0][:-1], path_arc=-20 * DEGREES), GrowFromPoint(pt_comments[0][-1], pt_comments[1][-1].get_left(), path_arc=20 * DEGREES), run_time=1, ) words_to_move = VGroup( *term_formula.get_parts_by_tex("\\text{Prior}"), *term_formula.get_parts_by_tex("\\text{Sensitivity}"), *term_formula.get_parts_by_tex("\\text{FPR}"), ) self.play(LaggedStart(*( ApplyMethod( part.shift, 0.25 * vect, rate_func=there_and_back_with_pause, run_time=2, ) for part, vect in zip(words_to_move, [UP, DOWN, DOWN, UP, DOWN, DOWN]) ), lag_ratio=0.05)) self.wait() # Comment on multiple updates kw["tex_to_color_map"].update({ "{E_1}": GREEN, "{E_2}": BLUE, }) mult_formula = OldTex( "O(\\text{D} | {E_1}, {E_2}) =", "O(\\text{D})\\,\\,", "{P({E_1} | \\text{D}) \\over P({E_1} | \\text{$\\neg$D})}\\,\\,", "{P({E_2} | \\text{D}, {E_1}) \\over P({E_2} | \\text{$\\neg$D}, {E_1})}", **kw ) mult_formula.set_width(FRAME_WIDTH / 2 - 1) mult_formula.next_to(odds_formula, DOWN, buff=1.5) new_bf_parts = VGroup(mult_formula[14:27], mult_formula[27:]) new_bf_rects = VGroup(*( SurroundingRectangle(part, buff=0.05) for part in new_bf_parts )) new_bf_rects[0].set_stroke(GREEN, 2) new_bf_rects[1].set_stroke(BLUE, 2) new_bf_labels = VGroup() for n, rect in zip(it.count(1), new_bf_rects): words = OldTexText(f"Bayes\\\\Factor {n}", font_size=28) parens = OldTex(*"()") parens.set_height(1.2 * words.get_height(), stretch=True) parens[0].next_to(words, LEFT, buff=0) parens[1].next_to(words, RIGHT, buff=0) words.add(parens) words.match_color(rect) words.next_to(rect, UP, MED_SMALL_BUFF) new_bf_labels.add(words) words.save_state() new_bf_labels.match_y(new_bf_parts) for part in new_bf_parts: part.save_state() part.set_color(BLACK) clipboards = VGroup(*( get_covid_clipboard("Disease").set_height(1.5).next_to(rect, DOWN) for rect in new_bf_rects )) sick_randy = Randolph(height=1.5) sick_randy.move_to(clipboards[1]) self.play( FadeOut(pt_comments), FadeIn(mult_formula, lag_ratio=0.1), FadeIn(new_bf_labels, lag_ratio=0.1), FadeIn(new_bf_rects, lag_ratio=0.1), ) self.wait() self.play( LaggedStartMap(FadeIn, clipboards, shift=0.5 * DOWN, lag_ratio=0.3) ) self.wait() self.play( FadeIn(sick_randy, 0.5 * DOWN), FadeOut(clipboards[1], 0.5 * DOWN), ) self.play( sick_randy.change, "sick", sick_randy.set_color, SICKLY_GREEN, ) self.play(Blink(sick_randy)) self.wait() for i in (0, 1): new_bf_parts[i].restore() self.play( Restore(new_bf_labels[i]), FadeIn(new_bf_parts[i]), sick_randy.look_at, new_bf_labels[i], ) self.wait() self.play(Blink(sick_randy)) self.wait() to_fade = VGroup(mult_formula, new_bf_labels, new_bf_rects, clipboards[0], sick_randy) self.play(LaggedStartMap(FadeOut, to_fade, shift=DOWN)) # Comment randy = Randolph(height=1.5) morty = Mortimer(height=1.5) pis = VGroup(randy, morty) pis.arrange(RIGHT, buff=2) pis.to_corner(DR) pis.to_edge(DOWN) self.play(FadeIn(pis)) self.play(PiCreatureSays( randy, "How accurate is\\\\the test?", bubble_config={"height": 2, "width": 3}, content_introduction_class=FadeIn, bubble_creation_class=FadeIn, target_mode="raise_left_hand", look_at=morty.eyes, run_time=1, )) content = OldTexText("Bayes factor 100", tex_to_color_map={"$+$": GREEN}) self.play(PiCreatureSays( morty, content, target_mode="hooray", bubble_config={"height": 2, "width": 3}, content_introduction_class=FadeIn, bubble_creation_class=FadeIn, look_at=randy.eyes, run_time=1 )) for x in range(2): self.play(Blink(randy)) self.play(Blink(morty)) self.wait() class ConfusedByFPR(Scene): def construct(self): # Background br = FullScreenFadeRectangle() br.set_fill(GREY_E, 1) self.add(br) # State FPR randy = Randolph(height=2.5, color=BLUE_C) randy.to_corner(DL, buff=LARGE_BUFF) clipboard = get_covid_clipboard("Cancer") clipboard.set_height(2) clipboard.next_to(randy.get_corner(UR), RIGHT) doctor = SVGMobject("female_doctor") doctor.remove(doctor[0]) doctor.set_stroke(width=0) doctor.set_fill(GREY_B) doctor.set_height(2.5) doctor.to_corner(DR, buff=LARGE_BUFF) fpr_words = OldTexText( "This test's\\\\false positive rate\\\\is 9\\%", tex_to_color_map={ "false positive rate": GREEN, "9\\%": WHITE, } ) bubble = SpeechBubble(height=3, width=4) bubble.pin_to(doctor) bubble.add_content(fpr_words) self.add(randy) self.add(doctor) self.play( FadeIn(clipboard, LEFT), randy.change, "guilty" ) self.play( DrawBorderThenFill(bubble), Write(fpr_words) ) self.play(Blink(randy)) self.wait() # Misinterpret false_prob = OldTex( "P(\\text{Test is false}) = 9\\%", tex_to_color_map={"9\\%": WHITE} ) thought_bubble = ThoughtBubble(height=3, width=4) thought_bubble.pin_to(randy) thought_bubble.add_content(false_prob) cross = Cross(thought_bubble[-1]) self.play( randy.change, 'confused', false_prob, DrawBorderThenFill(thought_bubble), FadeIn(false_prob), clipboard.shift, DOWN, ) self.play(Blink(randy)) self.play( ShowCreation(cross), randy.change, "maybe", cross, ) self.wait() # Sweep away self.play( randy.change, "hesitant", LaggedStartMap( FadeOut, VGroup(thought_bubble, false_prob, cross), scale=0.5, run_time=1, ) ) # Mention Bayes factor instead bf_words = OldTexText( "This test's\\\\positive Bayes factor\\\\is 10", tex_to_color_map={ "positive Bayes factor": YELLOW, "10": WHITE, } ) bf_words.replace(fpr_words, 1) anims = [] for m1, m2 in zip(fpr_words, bf_words): m1.generate_target() m1.target.replace(m2, stretch=True) m1.target.set_opacity(0) anims.append(MoveToTarget(m1, remover=True)) m2.save_state() m2.replace(m1, stretch=True) m2.set_opacity(0) anims.append(Restore(m2)) self.play(*anims) self.play(randy.change, "pondering") self.play(Blink(randy)) self.wait() class ShowContrastingMethods(Scene): def construct(self): # Prepare stats stats = VGroup( OldTexText("Prior: ", "2\\%"), OldTexText("Sensitivity: ", "90\\%"), OldTexText("Specificity: ", "99\\%"), ) stats.arrange(DOWN, aligned_edge=LEFT) colors = [YELLOW, GREEN, BLUE] for stat, color in zip(stats, colors): stat[0].set_color(color) stat[1].align_to(stats[-1][1], LEFT) stat_rect = SurroundingRectangle(stats, buff=0.2) stat_rect.set_fill(GREY_E, 1) stat_rect.set_stroke(WHITE, 2) stats.add_to_back(stat_rect) stats.set_height(1.5) # Setup division h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH) h_line.set_stroke(GREY, 2) titles = VGroup( OldTexText("Using odds"), OldTexText("Using probability"), ) titles.set_fill(GREY_A) titles[0].to_edge(UP) titles[1].next_to(ORIGIN, DOWN, MED_SMALL_BUFF) for title in titles: line = Underline(title) line.shift(0.1 * UP) line.set_stroke(GREY_B, 2) title.add(line) stats_pair = VGroup(stats, stats.copy()) anims = [] for sp, u in zip(stats_pair, [1, -1]): y = u * FRAME_HEIGHT / 4 sp.set_y(y) sp.shift(0.5 * DOWN) sp.to_edge(LEFT) anims.append(FadeIn(sp, shift=y * UP)) self.play( ShowCreation(h_line), FadeIn(titles), *anims ) # Bayes factor method prior_odds = OldTexText("Prior odds = ", "2:99") bf_eq = VGroup( OldTexText("Bayes\\\\Factor"), OldTex( "= {90\\% \\over 1\\%} = 90", tex_to_color_map={"90\\%": GREEN, "1\\%": BLUE} ), ) bf_eq.arrange(RIGHT, buff=SMALL_BUFF) steps = VGroup(prior_odds, bf_eq) steps.scale(0.9) steps.arrange(DOWN, buff=0.75, aligned_edge=LEFT) steps.next_to(stats, RIGHT, buff=1.0) p_rect = SurroundingRectangle(stats[1][1], buff=0.05) ss_rect = SurroundingRectangle(VGroup(stats[2][1], stats[3][1]), buff=0.05) ss_rect.set_stroke(GREEN) p_rect.match_width(ss_rect, stretch=True, about_edge=LEFT) p_arrow = Arrow(p_rect.get_right(), prior_odds.get_left(), buff=0.1) p_arrow.match_color(p_rect) ss_arrow = Arrow(ss_rect.get_right(), bf_eq.get_left(), buff=0.1) ss_arrow.match_color(ss_rect) ans = OldTex("\\text{180:99} \\approx 2:1 \\rightarrow {2 \\over 3}") ans.scale(0.9) ans.next_to(steps, RIGHT, buff=1.0) globals()['ans'] = ans ans_arrows = VGroup(*( Arrow(step.get_right(), ans.get_left(), buff=0.1) for step in steps )) # PPV formula ppv_formula = OldTex( """ \\text{PPV} = {(0.02)(0.9) \\over (0.02)(0.9) + (1 - 0.02)(0.01)} \\approx 0.647 """, tex_to_color_map={ "0.02": YELLOW, "0.9": GREEN, "0.01": BLUE, } ) ppv_formula.scale(0.9) ppv_formula.next_to(stats_pair[1], RIGHT, LARGE_BUFF) self.play( FadeIn(steps, RIGHT), ShowCreation(p_rect), ShowCreation(ss_rect), GrowArrow(p_arrow), GrowArrow(ss_arrow), ) self.play( FadeIn(ppv_formula, RIGHT) ) self.play( *map(GrowArrow, ans_arrows), FadeIn(ans, RIGHT) ) self.wait() class FailedPromises(TeacherStudentsScene): def construct(self): self.student_says( "Are you still doing\\\\``Probabilities\\\\of probabilities''?", bubble_config={ "height": 3.5, "width": 4.5, }, index=0, target_mode="sassy", added_anims=[self.teacher.change, "guilty"] ) self.students[0].bubble = None self.student_says( "And what about\\\\Differential equations?", bubble_config={ "height": 3, "width": 4, "direction": LEFT, }, index=2, target_mode="angry", added_anims=[self.students[1].change, "hesitant"], ) self.wait(3) class MentionPart2(Scene): def construct(self): self.add(FullScreenFadeRectangle(fill_color=GREY_E, fill_opacity=1)) tweet = ImageMobject("twitter_covid_test_poll") tweet.set_height(5) tweet.to_edge(LEFT) words = OldTexText( "Possible follow-up\\\\breaking this down", alignment="", font_size=60 ) words.to_edge(RIGHT) words.align_to(tweet, UP) arrow = Arrow(words.get_bottom() + SMALL_BUFF * DOWN, tweet.get_right(), path_arc=-45 * DEGREES) low_words = OldTexText("How would you answer?") low_words.match_x(words) low_words.align_to(tweet, DOWN) low_words.set_color(BLUE) self.add(words) self.play( FadeIn(tweet, shift=LEFT, scale=1.2), DrawBorderThenFill(arrow), ) self.wait() self.play(Write(low_words, run_time=1)) self.wait() class EndScreen(PatreonEndScreen): pass # Everything above has been combed through after the rewrite class OldBayesFactorCode(Scene): def construct(self): # Show test statistics def get_prob_bars(p_positive): rects = VGroup(Square(), Square()) rects.set_width(0.2, stretch=True) rects.set_stroke(WHITE, 2) rects[0].stretch(p_positive, 1, about_edge=UP) rects[1].stretch(1 - p_positive, 1, about_edge=DOWN) rects[0].set_fill(GREEN, 1) rects[1].set_fill(RED_E, 1) braces = VGroup(*[ Brace(rect, LEFT, buff=SMALL_BUFF) for rect in rects ]) positive_percent = int(p_positive * 100) percentages = VGroup( OldTexText(f"{positive_percent}\\% +", color=GREEN), OldTexText(f"{100 - positive_percent}\\% $-$", color=RED), ) percentages.scale(0.7) for percentage, brace in zip(percentages, braces): percentage.next_to(brace, LEFT, SMALL_BUFF) result = VGroup( rects, braces, percentages, ) return result boxes = VGroup( Square(color=YELLOW), Square(color=GREY_B) ) boxes.set_height(3) labels = VGroup( OldTexText("With cancer"), OldTexText("Without cancer"), ) for box, label in zip(boxes, labels): label.next_to(box, UP) label.match_color(box) box.push_self_into_submobjects() box.add(label) boxes.arrange(DOWN, buff=0.5) boxes.to_edge(RIGHT) sens_bars = get_prob_bars(0.9) spec_bars = get_prob_bars(0.09) bar_groups = VGroup(sens_bars, spec_bars) for bars, box in zip(bar_groups, boxes): bars.shift(box[0].get_right() - bars[0].get_center()) bars.shift(0.75 * LEFT) box.add(bars) self.play( FadeIn(boxes[0], lag_ratio=0.1), post_group.scale, 0.1, {"about_point": FRAME_HEIGHT * DOWN / 2} ) self.wait() self.play( FadeIn(boxes[1], lag_ratio=0.1) ) self.wait() # Pull out Bayes factor ratio = VGroup( sens_bars[2][0].copy(), OldTex("\\phantom{90\\%+} \\over \\phantom{9\\%+}"), spec_bars[2][0].copy(), *Tex("=", "10"), ) ratio.generate_target() ratio.target[:3].arrange(DOWN, buff=0.2) ratio.target[3:].arrange(RIGHT, buff=0.2) ratio.target[3:].next_to(ratio.target[:3], RIGHT, buff=0.2) ratio.target.center() ratio[1].scale(0) ratio[3:].scale(0) new_boxes = VGroup(boxes[0][0], boxes[1][0]).copy() new_boxes.generate_target() for box, part in zip(new_boxes.target, ratio.target[::2]): box.replace(part, stretch=True) box.scale(1.2) box.set_stroke(width=2) self.play( MoveToTarget(ratio), MoveToTarget(new_boxes), ) self.wait() for part, box in zip(ratio[0:3:2], new_boxes): part.add(box) self.remove(new_boxes) self.add(ratio) bayes_factor_label = OldTexText("``Bayes factor''") bayes_factor_label.next_to(ratio, UP, LARGE_BUFF) self.play(Write(bayes_factor_label)) self.wait() # Show updated result bayes_factor_label.generate_target() bayes_factor_label.target.scale(0.8) bayes_factor_label.target.next_to( post_group.saved_state[0], DOWN, buff=LARGE_BUFF, ) self.play( MoveToTarget(bayes_factor_label), ratio.scale, 0.8, ratio.next_to, bayes_factor_label.target, DOWN, Restore(post_group), FadeOut(boxes, shift=2 * RIGHT), ) self.wait() class AskAboutHowItsSoLow(TeacherStudentsScene): def construct(self): question = OldTexText( "How can it be 1 in 11\\\\" "if the test is accurate more\\\\" "than 90\\% of the time?", tex_to_color_map={ "1 in 11": BLUE, "90\\%": YELLOW, } ) self.student_says( question, index=1, target_mode="maybe", ) self.play_student_changes( "confused", "maybe", "confused", look_at=question, ) self.wait() self.play(self.teacher.change, "tease", question) self.wait(2) class HowDoesUpdatingWork(TeacherStudentsScene): def construct(self): students = self.students teacher = self.teacher self.student_says( "Where are these\\\\numbers coming\\\\from?", target_mode="raise_right_hand" ) self.play( teacher.change, "happy", self.change_students("confused", "erm", "raise_right_hand"), ) self.look_at(self.screen) self.wait(3) sample_pop = OldTexText("Sample populations (most intuitive)") bayes_factor = OldTexText("Bayes' factor (most fun)") for words in sample_pop, bayes_factor: words.move_to(self.hold_up_spot, DOWN) words.shift_onto_screen() bayes_factor.set_fill(YELLOW) self.play( RemovePiCreatureBubble(students[2]), teacher.change, "raise_right_hand", FadeIn(sample_pop, shift=UP, scale=1.5), self.change_students( "pondering", "thinking", "pondering", look_at=sample_pop, ) ) self.wait(2) self.play( FadeIn(bayes_factor, shift=UP, scale=1.5), sample_pop.shift, UP, teacher.change, "hooray", self.change_students( "thinking", "confused", "erm", ) ) self.look_at(bayes_factor) self.wait(3) class HighlightBayesFactorOverlay(Scene): def construct(self): rect = Rectangle(height=2, width=3) rect.set_stroke(BLUE, 3) words = OldTexText("How to\\\\use this") words.next_to(rect, DOWN, buff=1.5) words.shift(2 * RIGHT) words.match_color(rect) arrow = Arrow( words.get_left(), rect.get_bottom(), path_arc=-60 * DEGREES ) arrow.match_color(words) self.play( FadeIn(words, scale=1.1), DrawBorderThenFill(arrow), ) self.play( ShowCreation(rect), ) self.wait() class CompressedBayesFactorSteps(Scene): def construct(self): steps = OldTexText( "Step 1) ", "Express the prior with odds\\\\", "Step 2) ", "Compute the Bayes factor\\\\", "Step 3) ", "Multiply\\\\", alignment="", ) steps[1].set_color(YELLOW) steps[3].set_color(GREEN) steps[5].set_color(BLUE) steps.set_width(FRAME_WIDTH - 2) self.add(steps) class LookOverTweet(Scene): def construct(self): # Tweet bg_rect = FullScreenFadeRectangle() bg_rect.set_fill(GREY_E, 1) self.add(bg_rect) tweet = ImageMobject("twitter_covid_test_poll") tweet.set_height(6) tweet.to_edge(LEFT) self.play(FadeIn(tweet, shift=UP, scale=1.2)) self.wait() # Tweet highlights lines = VGroup( Line((-3.9, 1.7), (0.3, 1.7)), Line((-3.4, 0.1), (-0.7, 0.1)), VGroup( Line((0.2, 0.1), (0.8, 0.1)), Line((-6.4, -0.3), (-4, -0.3)), ), ) lines.set_color(RED) rects = VGroup(*(Rectangle(3.2, 0.37) for x in range(4))) rects.arrange(DOWN, buff=0.08) rects.set_stroke(BLUE, 3) rects.set_fill(BLUE, 0.25) rects.move_to((-4.8, -1.66, 0.)) # Population icon = SVGMobject("person") icon.set_stroke(width=0) globals()['icon'] = icon population = VGroup(*(icon.copy() for x in range(1000))) population.scale(1 / population[0].get_height()) population.arrange_in_grid( 30, 33, buff=MED_LARGE_BUFF, ) population.set_width(4) population.to_edge(RIGHT) population.set_fill(GREY_B) population[random.randint(0, 1000)].set_fill(YELLOW) pop_title = OldTexText("1", " in ", "1,000") pop_title[0].set_color(YELLOW) pop_title.next_to(population, UP) self.play( FadeIn(pop_title, shift=0.25 * UP), ShowIncreasingSubsets(population), ShowCreation(lines[0]) ) self.wait() pop_group = VGroup(population, pop_title) # Positive result clipboard = SVGMobject("clipboard") clipboard.set_stroke(width=0) clipboard.set_fill(interpolate_color(GREY_BROWN, WHITE, 0.5), 1) clipboard.set_width(2.5) clipboard.move_to(population) clipboard.to_edge(UP) result = OldTexText( "+\\\\", "SARS\\\\CoV-2\\\\", "Detected" ) result[0].scale(1.5, about_edge=DOWN) result[0].set_fill(GREEN) result[0].set_stroke(GREEN, 2) result[-1].set_fill(GREEN) result.set_width(clipboard.get_width() * 0.7) result.move_to(clipboard) result.shift(0.2 * DOWN) clipboard.add(result) self.play( pop_group.scale, 0.4, pop_group.to_edge, DOWN, FadeIn(clipboard, DOWN), ) self.wait() # FPR, FRN self.play(ShowCreation(lines[1])) self.wait() self.play(ShowCreation(lines[2])) self.wait() # Answer choices rect = rects[0].copy() self.play(DrawBorderThenFill(rect)) self.wait() for r2 in rects[1:]: self.play(Transform(rect, r2)) self.wait() self.play(FadeOut(rect)) # Focus on FPR rect = Rectangle() rect.match_width(lines[1]) rect.scale(1.02) rect.set_height(0.4, stretch=True) rect.match_style(lines[1]) rect.move_to(lines[1], DOWN) rect.set_fill(RED, 0.2) self.play( FadeOut(lines[0]), FadeOut(lines[2]), DrawBorderThenFill(rect) ) # Randy randy = Randolph(height=2) randy.flip() randy.next_to(tweet, RIGHT, LARGE_BUFF, DOWN) bubble = randy.get_bubble(height=3, width=3, direction=RIGHT) bubble.flip() bubble.write("99\\%\\\\right?") self.play( FadeIn(randy), FadeOut(clipboard, RIGHT), FadeOut(pop_group, 0.5 * RIGHT), ) self.play( randy.change, "maybe", DrawBorderThenFill(bubble), Write(bubble.content), ) self.play(Blink(randy)) self.wait() class DisambiguateFPR(Scene): def construct(self): # Add title title = OldTexText( "1\\% False Positive Rate", isolate=["F", "P", "R"], font_size=72 ) title.to_edge(UP) title.set_color(GREY_A) underline = Underline(title) underline.match_color(title) morty = Mortimer() morty.to_corner(DR) morty.look_at(title) self.add(title) self.play( PiCreatureSays( morty, "It's a confusing term!", target_mode="surprised", run_time=1, ) ) self.play( Blink(morty), ShowCreation(underline), ) self.play(morty.change, "angry") self.play(Blink(morty)) # Draw out grid word_grid = VGroup( OldTexText("True positives", color=GREEN), OldTexText("False negatives", color=RED_E), OldTexText("False positives", color=GREEN_D), OldTexText("True negatives", color=RED), ) word_box = SurroundingRectangle(word_grid) word_box.set_stroke(WHITE, 2) word_box.stretch(2, 1) word_grid.arrange_in_grid( v_buff=1.0, h_buff=0.5, fill_rows_first=False ) word_grid.move_to(2 * DOWN) globals()['word_box'] = word_box word_boxes = VGroup(*( word_box.copy().move_to(word).match_color(word) for word in word_grid )) group_boxes = VGroup( SurroundingRectangle(word_boxes[:2], color=YELLOW), SurroundingRectangle(word_boxes[2:], color=GREY_B), ) group_titles = VGroup( OldTexText("Have COVID-19", font_size=36), OldTexText("Don't have COVID-19", font_size=36), ) for box, gt in zip(group_boxes, group_titles): gt.next_to(box, UP) gt.match_color(box) icon = SVGMobject("person", stroke_width=0, fill_color=GREY_B) globals()['icon'] = icon with_pop = VGroup(*(icon.copy() for x in range(1))) with_pop.set_color(YELLOW) without_pop = VGroup(*(icon.copy() for x in range(999))) with_pop.set_height(0.5) with_pop.move_to(group_boxes[0]) without_pop.arrange_in_grid(n_rows=20) without_pop.replace(group_boxes[1], dim_to_match=1) without_pop.scale(0.9) self.play( ShowCreation(group_boxes, lag_ratio=0.3), DrawBorderThenFill(with_pop), ShowIncreasingSubsets(without_pop), FadeIn(group_titles, lag_ratio=0.3), FadeOut(morty), FadeOut(morty.bubble), FadeOut(morty.bubble.content), ) self.wait() arrow = Vector(DOWN) arrow.next_to(group_titles[1], UP) self.play(GrowArrow(arrow)) self.wait() self.play( LaggedStartMap(Write, word_grid[2:], lag_ratio=0.9), LaggedStartMap(ShowCreation, word_boxes[2:], lag_ratio=0.9), without_pop.set_opacity, 0.3, run_time=1, ) self.wait() # Two reasonable fractions tp, fn, fp, tn = ( word for word, box in zip(word_grid, word_boxes) ) def create_fraction(m1, m2, scale_factor=0.75): result = VGroup( m1.copy(), OldTex("\\quad \\over \\quad"), m1.copy(), OldTex("+"), m2.copy() ) result[0::2].scale(scale_factor) result[2:].arrange(RIGHT, buff=SMALL_BUFF) result[1].match_width(result[2:], stretch=True) result[1].next_to(result[2:], UP, SMALL_BUFF) result[0].next_to(result[1], UP, SMALL_BUFF) return result def fraction_anims(m1, m2, fraction): return [ TransformFromCopy(m1, fraction[0]), TransformFromCopy(m1, fraction[2]), TransformFromCopy(m2, fraction[4]), GrowFromPoint( fraction[1], VGroup(m1, m2).get_center(), ), GrowFromPoint( fraction[3], VGroup(m1, m2).get_center(), ), ] frac1 = create_fraction(fp, tp) frac2 = create_fraction(fp, tn) fracs = VGroup(frac1, frac2) fracs.arrange(RIGHT, buff=3) fracs.to_edge(UP, buff=1.5) title.add(underline) fpr = OldTexText( "1\\% ", "F", "", "P", "", "R", "", font_size=72 ) fpr.add(Underline(fpr)) fpr[-1].set_width(0) fpr.match_style(title) fpr.next_to(frac2, UP, MED_LARGE_BUFF) frac2.save_state() frac2.set_x(0) self.play( FadeOut(arrow), LaggedStart(*fraction_anims(fp, tn, frac2)) ) self.wait(2) self.play( ReplacementTransform(title, fpr), Restore(frac2) ) self.play( LaggedStartMap(Write, word_grid[:2], lag_ratio=0), LaggedStartMap(ShowCreation, word_boxes[:2], lag_ratio=0), with_pop.set_opacity, 0.2, run_time=1, ) self.play( LaggedStart(*fraction_anims(fp, tp, frac1)), fn.set_opacity, 0.5, tn.set_opacity, 0.5, ) self.wait() comment = OldTexText("What we actually want") comment.next_to(frac1, UP, buff=0.75) self.play(FadeIn(comment, 0.5 * UP)) self.wait() # Prep for Bayes calculation right_brace = Brace(word_boxes[2], RIGHT, buff=SMALL_BUFF) left_brace = Brace(word_boxes[1], LEFT, buff=SMALL_BUFF) fpr.generate_target() fpr.target.scale(48 / 72) fpr.target.next_to(right_brace, RIGHT) fnr = OldTexText("10\\% FNR") fnr.next_to(left_brace, LEFT) VGroup(left_brace, right_brace, fnr).set_color(GREY_A) self.play( MoveToTarget(fpr), GrowFromCenter(left_brace), GrowFromCenter(right_brace), FadeIn(fnr), FadeOut(comment), FadeOut(fracs), fn.set_opacity, 1.0, tn.set_opacity, 1.0, ) prior_title = OldTexText("Prior: 1 in 1,000", font_size=72) prior_title.to_edge(UP) self.play(FadeIn(prior_title, UP)) self.wait() # Show population counts full_pop = VGroup( OldTexText("Imagine"), Integer(10000), OldTexText("People") ) full_pop.arrange(RIGHT, aligned_edge=DOWN) full_pop.set_color(GREY_A) full_pop.next_to(prior_title, DOWN, MED_LARGE_BUFF) self.play( FadeIn(full_pop[0::2]), CountInFrom(full_pop[1], 0), FadeOut(with_pop), FadeOut(without_pop), ) self.wait() def move_number_above_word(number, word, target_count, buff=MED_SMALL_BUFF, scene=self): mover = number.copy() mover.original_bottom = mover.get_bottom() start_count = number.get_value() scene.play( UpdateFromAlphaFunc( mover, lambda m, a, word=word, sc=start_count, tc=target_count, buff=buff: m.set_color( interpolate_color(GREY_A, word.get_color(), a) ).set_value( interpolate(sc, tc, a), ).move_to( interpolate( m.original_bottom, word.get_top() + buff * UP, a ), DOWN, ) ) ) return mover with_count = move_number_above_word(full_pop[1], group_titles[0], 10, buff=0.3) self.wait() without_count = move_number_above_word(full_pop[1], group_titles[1], 9990) self.wait() self.play(word_grid.shift, 0.25 * DOWN) tp_count = move_number_above_word(with_count, word_grid[0], 9, SMALL_BUFF) fn_count = move_number_above_word(with_count, word_grid[1], 1, SMALL_BUFF) self.wait() fp_count = move_number_above_word(without_count, word_grid[2], 100, SMALL_BUFF) tn_count = move_number_above_word(without_count, word_grid[3], 9890, buff=0.05) self.wait() faders = VGroup( with_count, without_count, group_titles, fpr, fnr, fn, tn, fn_count, tn_count, ) braces = VGroup(left_brace, right_brace) self.play(faders.set_opacity, 0.3, FadeOut(braces)) self.wait() # Show posterior prior_group = VGroup(prior_title, full_pop) prior_group.generate_target() prior_group.target.to_edge(LEFT) prior_group.target.shift(0.5 * DOWN) arrow = Vector(0.8 * RIGHT) arrow.next_to(prior_group.target[0], RIGHT) post_word = OldTexText("Posterior:", font_size=72) post_word.set_color(BLUE) post_word.next_to(arrow, RIGHT) post_word.align_to(prior_group.target[0][0][0], DOWN) post_frac = create_fraction(tp_count, fp_count, scale_factor=1) post_frac.next_to(post_word, RIGHT, MED_LARGE_BUFF) rhs = OldTex("\\approx", "8.3\\%") rhs.next_to(post_frac, RIGHT) self.play( MoveToTarget(prior_group), GrowArrow(arrow), Write(post_word, run_time=1), ) self.play(*fraction_anims(tp_count, fp_count, post_frac)) self.wait() self.play(Write(rhs)) self.wait() class BayesFactorForCovidExample(Scene): def construct(self): # Titles titles = VGroup( OldTexText("Prior odds", color=YELLOW), OldTexText("Bayes factor", color=GREEN), OldTexText("Posterior odds", color=BLUE), ) titles.scale(1.25) titles[0].shift(FRAME_WIDTH * LEFT / 3) titles[2].shift(FRAME_WIDTH * RIGHT / 3) titles.to_edge(UP) v_lines = VGroup(*( Line(UP, DOWN).set_height(FRAME_HEIGHT).move_to( FRAME_WIDTH * x * RIGHT / 6, ) for x in (-1, 1) )) self.add(titles, v_lines) # Prior odds prior_odds = OldTexText( "1", "\\,:\\,", "999", tex_to_color_map={"1": YELLOW} ) prior_odds.next_to(titles[0], DOWN, buff=1) population = Population(1000) population.set_width(FRAME_WIDTH / 5) population[0].set_color(YELLOW) population[0].next_to(population[1:], LEFT, MED_LARGE_BUFF) colon = OldTex(":") colon.move_to(midpoint(population[0].get_right(), population[1:].get_left())) pop_ratio = VGroup(population[0], colon, population[1:]) pop_ratio.next_to(prior_odds, DOWN, MED_LARGE_BUFF) self.play( FadeIn(prior_odds, shift=0.2 * DOWN, scale=1.2), FadeIn(pop_ratio, lag_ratio=0.01), ) self.wait() # Bayes factor bf_lhs = OldTex( """ { P(+ \\,|\\, \\text{COVID}) \\over P(+ \\,|\\, \\text{No COVID}) } """, tex_to_color_map={ "+": GREEN, "\\text{COVID}": YELLOW, "\\text{No COVID}": GREY_A, } ) bf_lhs.next_to(titles[1], DOWN) bf_rhs = OldTex( "= {90\\%", "\\over", "1\\%}", tex_to_color_map={ "90\\%": GREEN_D, "1\\%": GREEN, } ) bf = VGroup(bf_lhs, bf_rhs) bf.arrange(RIGHT) bf.set_width(0.9 * FRAME_WIDTH / 3) bf.next_to(titles[1], DOWN, MED_LARGE_BUFF) eq_90 = OldTex("=", "90") eq_90.next_to(bf, DOWN, MED_LARGE_BUFF) eq_90[1].save_state() eq_90[1].replace(bf_rhs[1:], stretch=True) eq_90[1].set_opacity(0) eq_90[1].set_color(GREEN) self.play( FadeIn(bf_lhs, lag_ratio=0.1), FadeIn(bf_rhs[0::2], lag_ratio=0.1), ) self.wait() self.play(Write(bf_rhs[1])) self.wait() self.play(Write(bf_rhs[3])) self.wait() self.play( TransformFromCopy(bf_rhs[0], eq_90[0]), Restore(eq_90[1]) ) self.wait() # Posterior post_odds = OldTex("90", ":", "999") post_odds.match_x(titles[2]) post_odds.match_y(prior_odds) arrow = Vector(DOWN) arrow.next_to(post_odds, DOWN) fraction = OldTex( "{90", "\\over", "90", "+", "999}", "\\approx", "8.3\\%" ) fraction.next_to(arrow, DOWN) self.play(LaggedStart( TransformFromCopy(eq_90[1], post_odds[0]), TransformFromCopy(prior_odds[1:], post_odds[1:]), lag_ratio=0.4 )) self.wait() self.play( GrowArrow(arrow), FadeIn(fraction, DOWN) ) # Approximate approx1 = OldTex("\\approx", "90", ":", "1,000") approx2 = OldTex("\\approx", "9", ":", "100") approx3 = OldTex("\\approx 9\\%") approx1.next_to(arrow, DOWN) approx2.move_to(approx1) arrow2 = arrow.copy() arrow2.next_to(approx2, DOWN) approx3.next_to(arrow2, DOWN) self.play( FadeOut(fraction, 0.5 * DOWN), FadeIn(approx1, 0.5 * DOWN), ) self.wait() self.play( ReplacementTransform(approx1, approx2) ) self.wait() self.play( GrowArrow(arrow2), FadeIn(approx3, DOWN) ) self.wait() class WhyIsThisWrong(TeacherStudentsScene): def construct(self): # Ask question tweet = ImageMobject("twitter_covid_test_poll") tweet.replace(self.screen, dim_to_match=0) tweet.to_edge(UP) tweet.scale(0.9, about_edge=UP) self.add(tweet) self.student_says( "Bayes' rule says\\\\ 8.5\\%, right?", target_mode="hooray", index=1, ) self.wait() self.play( PiCreatureSays( self.teacher, "Well...", bubble_config={"height": 2, "width": 2}, target_mode="hesitant", ), self.change_students("confused", "erm", "pondering") ) self.wait(3) # Highlight symptoms self.play( RemovePiCreatureBubble(self.students[1]), RemovePiCreatureBubble(self.teacher, target_mode="raise_right_hand"), tweet.move_to, self.hold_up_spot, DR, tweet.shift, RIGHT, ) underline = Line((-1.3, 2.65), (2.1, 2.65)) underline.shift(RIGHT) underline.set_stroke(RED, 3) self.play( ShowCreation(underline), self.teacher.look_at, underline, *(ApplyMethod(pi.change, "pondering", underline) for pi in self.students), ) self.wait() # Change prior ineq = OldTexText("Prior > $\\frac{1}{1,000}$", font_size=72) ineq.next_to(tweet, LEFT, LARGE_BUFF) self.play(Write(ineq)) self.look_at(ineq) self.wait() # More severe symptoms for pi in self.students: pi.generate_target() pi.target.change("sick") pi.target.set_color(SICKLY_GREEN) pi.target.look(DR) self.play( LaggedStartMap(MoveToTarget, self.students, lag_ratio=0.3), self.teacher.change, "erm" ) clipboard = get_covid_clipboard() clipboard.to_corner(UL) self.play( FadeIn(clipboard, UP), FadeOut(ineq, UP), *(ApplyMethod(pi.look_at, clipboard) for pi in self.pi_creatures), ) self.wait() percent = OldTex("8.3 \\%", font_size=72) percent.next_to(clipboard, RIGHT, buff=0.6) percent_cross = Cross(percent, stroke_width=8) self.play( FadeIn(percent), self.teacher.change, "tease" ) self.play(ShowCreation(percent_cross)) self.wait() self.student_says( "What's the appropriate\\\\math here?", index=1, added_anims=[ FadeOut(tweet), FadeOut(underline), self.teacher.change, "happy" ] ) self.wait(2) class TotalPopulationVsSymptomatic(Scene): def construct(self): # Titles v_line = Line(UP, DOWN).set_height(2 * FRAME_HEIGHT) v_line.to_edge(UP) self.add(v_line) titles = VGroup( OldTexText("Population"), OldTexText("Population", " \\emph{with symptoms}"), ) titles[1][1].set_color(BLUE) for title, u in zip(titles, [-1, 1]): title.move_to(u * RIGHT * FRAME_WIDTH / 4) titles.to_edge(UP) self.add(titles[0]) # Actual populations full_pop = VGroup(*(Dot() for x in range(10000))) full_pop.arrange_in_grid( buff=full_pop[0].get_width() ) full_pop.set_width(FRAME_WIDTH / 2 - 1) full_pop.next_to(titles[0], DOWN) full_pop.to_edge(DOWN, buff=SMALL_BUFF) covid_pop = full_pop[:10] covid_pop.set_fill(YELLOW) covid_pop.save_state() covid_pop.scale(8, about_edge=UL) covid_pop.shift(DOWN) full_pop_words = VGroup( OldTexText("10 ", "with COVID", color=YELLOW), OldTexText("9990 ", "without COVID", color=GREY_B), ) full_pop_words.arrange(RIGHT, buff=LARGE_BUFF) full_pop_words.scale(0.7) full_pop_words.next_to(full_pop, UP, SMALL_BUFF, LEFT) self.play( FadeIn(full_pop_words[0]), Write(covid_pop), run_time=1 ) self.play( FadeIn(full_pop_words[1]), ShowIncreasingSubsets(full_pop[10:]), Restore(covid_pop), ) self.wait() # Mention symptoms self.play( TransformFromCopy(titles[0][0], titles[1][0]), FadeInFromPoint(titles[1][1], titles[0].get_center()), ) self.wait() arrow = Vector(DOWN).next_to(titles[1][1], DOWN) arrow.set_color(BLUE) prop_ex = OldTex("\\sim \\frac{1}{50}", "\\text{, say}") prop_ex[0].set_color(BLUE) prop_ex.next_to(arrow, DOWN) self.play( GrowArrow(arrow), FadeIn(prop_ex, DOWN) ) self.wait() # Symptomatic population left_sym_pop = VGroup(*random.sample(list(full_pop[10:]), 200)) sym_pop = left_sym_pop.copy() sym_pop.generate_target() buff = get_norm(full_pop[1].get_left() - full_pop[0].get_right()) sym_pop.target.arrange_in_grid(buff=buff) sym_pop.target.set_width(3.5) sym_pop.target.match_x(titles[1]) sym_pop.target.align_to(full_pop, UP) sym_pop.target.shift(DOWN) sym_pop.target.set_color(BLUE) sym_pop_label = OldTexText("$\\sim 200$", " without COVID") sym_pop_label.set_color(GREY_B) sym_pop_label.scale(0.7) sym_pop_label.next_to(sym_pop.target, UP, buff=0.2) self.play( sym_pop.set_color, BLUE, MoveToTarget(sym_pop, lag_ratio=0.01, run_time=2), prop_ex.to_edge, DOWN, FadeOut(arrow), Write(sym_pop_label), ) self.wait() sym_covid_pop = covid_pop[:5].copy() sym_covid_pop.generate_target() sym_covid_pop.target.arrange(DOWN, buff=buff) sym_covid_pop.target.scale( sym_pop[0].get_height() / sym_covid_pop[0].get_height() ) sym_covid_pop.target.next_to(sym_pop, LEFT, aligned_edge=UP) sym_covid_pop_label = OldTexText("5", " with COVID") sym_covid_pop_label.scale(0.7) sym_covid_pop_label.next_to(sym_covid_pop.target, UP, buff=0.2) sym_covid_pop_label.set_color(YELLOW) self.play(ShowCreationThenFadeAround(sym_pop_label)) self.play( VGroup(sym_pop, sym_pop_label).to_edge, RIGHT, MoveToTarget(sym_covid_pop), FadeIn(sym_covid_pop_label), ) self.wait() # Apply test left_movers = VGroup( full_pop, full_pop_words, titles[0], v_line, ) right_movers = VGroup( titles[1], sym_covid_pop, sym_covid_pop_label, sym_pop, sym_pop_label, ) v_line_copy = v_line.copy() left_vect = (FRAME_WIDTH + SMALL_BUFF) * LEFT / 2 self.play( LaggedStartMap( ApplyMethod, left_movers, lambda m: (m.shift, left_vect), lag_ratio=0.05, ), ApplyMethod( right_movers.shift, left_vect, rate_func=squish_rate_func(smooth, 0.3, 1), ), FadeOut(prop_ex), run_time=2, ) self.wait() # With test result right_title = OldTexText( "Population ", "\\emph{with symptoms}\\\\", "and a positive test result" ) right_title.set_color_by_tex("symptoms", BLUE) right_title.set_color_by_tex("positive", GREEN) right_title.set_x(FRAME_WIDTH / 4) right_title.to_edge(UP) titles.add(right_title) self.play( ShowCreation(v_line_copy), FadeIn(right_title), ) self.wait() right_vect = FRAME_WIDTH * RIGHT / 2 pc_pop = sym_covid_pop.copy() pn_pop = VGroup(*random.sample(list(sym_pop), 2)).copy() pn_pop.generate_target() buff = get_norm(sym_pop[1].get_left() - sym_pop[0].get_right()) pn_pop.target.arrange(DOWN, buff=buff) pn_pop.target.next_to(sym_pop_label, DOWN) pn_pop.target.shift(right_vect) pn_pop.target.scale(1.5, about_edge=UP) black_rect = BackgroundRectangle(pc_pop[-1], fill_opacity=1) black_rect.stretch(0.5, 1, about_edge=DOWN) pc_pop.add(black_rect) pc_pop.set_opacity(0) pc_pop_label = OldTexText("4.5 with COVID", color=YELLOW) pn_pop_label = OldTexText("~2 without COVID", color=GREY_B) labels = VGroup(pc_pop_label, pn_pop_label) labels.scale(0.7) labels.set_opacity(0) pc_pop_label.move_to(sym_covid_pop_label) pn_pop_label.move_to(sym_pop_label) def get_test_rects(mob): return VGroup(*( SurroundingRectangle( part, color=GREEN, buff=buff / 2, stroke_width=2, ) for part in mob )) self.play( pc_pop_label.shift, right_vect, pc_pop_label.set_opacity, 1, pc_pop.shift, right_vect, pc_pop.set_opacity, 1, pc_pop.scale, 1.5, {"about_edge": UP} ) pc_pop_rects = get_test_rects(pc_pop[:5]) self.play(FadeIn(pc_pop_rects, lag_ratio=0.3)) self.wait() self.play( pn_pop_label.shift, right_vect, pn_pop_label.set_opacity, 1, MoveToTarget(pn_pop), ) pn_pop_rects = get_test_rects(pn_pop) self.play(FadeIn(pn_pop_rects, lag_ratio=0.3)) self.wait() # Final fraction equation = OldTex( "{4.5 \\over 4.5 + {2}} \\approx 69.2\\%", tex_to_color_map={ "4.5": YELLOW, "{2}": GREY_B, } ) equation.move_to(FRAME_WIDTH * RIGHT / 4) equation.to_edge(DOWN, buff=LARGE_BUFF) self.play(FadeIn(equation, lag_ratio=0.1)) self.wait() # Zoom out frame = self.camera.frame self.play( frame.scale, 1.5, {"about_edge": UR}, run_time=3, ) self.wait() # Prepare population groups to move pop_groups = VGroup( VGroup( full_pop, full_pop_words, ), VGroup( sym_covid_pop, sym_covid_pop_label, sym_pop, sym_pop_label, ), VGroup( pc_pop, pc_pop_label, pc_pop_rects, pn_pop, pn_pop_label, pn_pop_rects, equation ), ) pop_groups.generate_target() for group in pop_groups.target: group.scale(0.5, about_edge=DOWN) group.shift(4.5 * DOWN) pop_groups.target[0][0].set_opacity(0.5) h_line = Line(pop_groups.get_left(), pop_groups.get_right()) h_line.next_to(pop_groups.target, UP) h_line.set_stroke(WHITE, 1) # Relevant odds labels def get_odds_label(n, k, n_color=YELLOW, k_color=GREY_B): result = VGroup( OldTexText("Odds = "), Integer(n, color=n_color, edge_to_fix=UR), OldTexText(":"), Integer(k, color=k_color, edge_to_fix=UL), ) result.scale(1.5) result.arrange(RIGHT, buff=0.25) result[3].align_to(result[1], UP) return result odds_labels = VGroup( get_odds_label(1, 999), get_odds_label(25, 1000), get_odds_label(40, 90), ) for label, title in zip(odds_labels, titles): label.move_to(title, UP) label.shift(2 * DOWN) odds_underlines = VGroup(*( Underline(label[1:]) for label in odds_labels )) odds_arrows = VGroup(*( Arrow(o1.get_right(), o2.get_left()) for o1, o2 in zip(odds_labels, odds_labels[1:]) )) odds_arrows.set_fill(GREY_B) for arrow in odds_arrows: arrow.set_angle(0) self.play( MoveToTarget(pop_groups), FadeIn(odds_labels[0]), ShowCreation(h_line), ) for i in (1, 2): self.play( FadeIn(odds_labels[i][0], RIGHT), FadeIn(odds_underlines[i], RIGHT), GrowArrow(odds_arrows[i - 1]), ) self.wait() # Bayes factors bf_labels = VGroup( OldTexText( "Bayes factor for symptoms", tex_to_color_map={"for symptoms": BLUE} ), OldTexText( "Bayes factor positive test", tex_to_color_map={"positive test": GREEN} ), ) for label, title in zip(bf_labels, titles[1:]): label.move_to(title, UP) label.shift(4.5 * DOWN) t2c = { "\\text{COVID}": YELLOW, "\\text{No COVID}": GREY_B, "\\text{Symp}": BLUE, "+": GREEN, "=": WHITE, } bf_equations = VGroup( OldTex( """ {P(\\text{Symp} \\,|\\, \\text{COVID}) \\over P(\\text{Symp} \\,|\\, \\text{No COVID})} = {50\\% \\over 2\\%} = 25 """, tex_to_color_map=t2c, ), OldTex( """ {P(+ \\,|\\, \\text{COVID}) \\over P(+ \\,|\\, \\text{No COVID})} = {90\\% \\over 1\\%} = 90 """, tex_to_color_map=t2c, ), ) for label, eq in zip(bf_labels, bf_equations): eq.scale(0.75) eq[-1].scale(2, about_edge=LEFT) eq.next_to(label, DOWN, buff=0.75) assumption_brace = Brace(bf_equations[0][-3:], DOWN) assumption_word = OldTexText("Assumption") assumption_word.next_to(assumption_brace, DOWN) self.play( Write(bf_labels[0]), FadeIn(bf_equations[0][:-3]), ) self.wait() self.play( GrowFromCenter(assumption_brace), FadeIn(assumption_word, shift=0.2 * DOWN), FadeIn(bf_equations[0][-3:]), ) self.wait() self.play(ShowCreationThenFadeOut(odds_underlines[0])) new_left_odds = get_odds_label(1, 1000)[1:] new_left_odds.move_to(odds_labels[0][1:], UL) approx = OldTex("\\approx", font_size=72) approx.rotate(90 * DEGREES) approx.next_to(odds_labels[0][1:], DOWN, buff=0.5) self.play( FadeIn(approx, 0.25 * DOWN), odds_labels[0][1:].next_to, approx, DOWN, {"buff": 0.5}, FadeIn(new_left_odds, 0.5 * DOWN), odds_arrows[0].scale, 0.7, {"about_edge": RIGHT}, ) self.wait() curr_odds = new_left_odds.copy() self.play( curr_odds.move_to, odds_labels[1][1:], UR, path_arc=-30 * DEGREES ) self.play(ChangeDecimalToValue(curr_odds[0], 25)) self.wait() new_odds = curr_odds.copy() new_odds[0].set_value(1) new_odds[2].set_value(40) self.play( FadeOut(curr_odds, 0.5 * UP), FadeIn(new_odds, 0.5 * UP), ) curr_odds = new_odds self.wait() self.play( Write(bf_labels[1]), FadeIn(bf_equations[1]), ) self.wait() mid_odds = curr_odds.copy() self.add(mid_odds) self.play( curr_odds.move_to, odds_labels[2][1:], UR, path_arc=-30 * DEGREES ) self.play( ChangeDecimalToValue(curr_odds[0], 90) ) self.wait() new_odds = curr_odds.copy() new_odds[0].set_value(9) new_odds[2].set_value(4) self.play( FadeOut(curr_odds, 0.5 * UP), FadeIn(new_odds, 0.5 * UP), ) curr_odds = new_odds self.wait() # Posterior as a probability final_frac = OldTex( "{{9} \\over {9} + {4}} \\approx 69.2\\%", tex_to_color_map={ "{9}": YELLOW, "{4}": GREY_B, } ) final_frac.next_to(odds_labels[2], DOWN, buff=0.4) self.play(FadeIn(final_frac, lag_ratio=0.2)) self.wait() # Get rid of population self.play( LaggedStartMap(FadeOut, pop_groups, shift=DOWN, lag_ratio=0.3), FadeOut(h_line), ) # Change symptom Bayes factor old_assumption = bf_equations[0][-3:] new_assumption = OldTex("2") new_assumption.replace(old_assumption, 1) new_assumption.scale(0.8) new_assumption.set_color(BLUE) change_word = OldTexText("Change this", font_size=72) change_word.next_to(assumption_word, DOWN, buff=1.5) change_word.shift(LEFT) change_word.set_color(RED) change_arrow = Arrow(change_word.get_top(), assumption_word.get_bottom()) change_arrow.match_color(change_word) self.play( Write(change_word, run_time=1), GrowArrow(change_arrow), ) self.wait() self.play( FadeOut(old_assumption, shift=0.5 * UP), FadeIn(new_assumption, shift=0.5 * UP), assumption_brace.set_width, 1.5 * new_assumption.get_width(), {"stretch": True}, FadeOut(mid_odds), FadeOut(curr_odds), FadeOut(final_frac), ) self.wait() # New odds calculation curr_odds = new_left_odds.copy() self.play( curr_odds.move_to, mid_odds, UP, curr_odds.shift, SMALL_BUFF * RIGHT, FadeOut(odds_underlines[1]), path_arc=-30 * DEGREES, ) self.play(ChangeDecimalToValue(curr_odds[2], 500)) self.wait() mid_odds = curr_odds.copy() self.add(mid_odds) self.play( curr_odds.move_to, odds_labels[2][1:], UR, curr_odds.shift, 0.35 * RIGHT, FadeOut(odds_underlines[2]), path_arc=-30 * DEGREES, ) self.play(ChangeDecimalToValue(curr_odds[0], 90)) self.wait() new_odds = curr_odds.copy() new_odds[0].set_value(9) new_odds[2].set_value(50) new_odds.move_to(curr_odds, LEFT) self.play( FadeIn(new_odds, shift=0.5 * UP), FadeOut(curr_odds, shift=0.5 * UP), ) curr_odds = new_odds self.wait() # Prob calculation new_final_frac = OldTex( "{{9} \\over {9} + {50}} \\approx 15.3\\%", tex_to_color_map={ "{9}": YELLOW, "{50}": GREY_B, } ) new_final_frac.replace(final_frac, 1) self.play(FadeIn(new_final_frac, lag_ratio=0.3)) self.wait() class ContrastTextbookAndRealWorld(Scene): def construct(self): pass class TwoMissteps(Scene): def construct(self): words = VGroup( OldTexText( "Misstep 1: ", "Fail to consider the prevalence." ), OldTexText( "Misstep 2: ", "Assume prior = prevalence" ), ) words[0][0].set_color(YELLOW) words[1][0].set_color(BLUE) words.scale(1.5) words.arrange(DOWN, buff=1, aligned_edge=LEFT) words.to_edge(LEFT) self.add(words) # Embed self.embed()
from manim_imports_ext import * class EarthMorph(Scene): CONFIG = { "camera_class": ThreeDCamera, } def construct(self): torus1 = Torus(r1=1, r2=1) torus2 = Torus(r1=3, r2=1) sphere = Sphere(radius=3, resolution=torus1.resolution) earths = [ TexturedSurface(surface, "EarthTextureMap", "NightEarthTextureMap") for surface in [sphere, torus1, torus2] ] for mob in earths: mob.mesh = SurfaceMesh(mob) mob.mesh.set_stroke(BLUE, 1, opacity=0.5) earth = earths[0] self.camera.frame.set_euler_angles( theta=-30 * DEGREES, phi=70 * DEGREES, ) self.add(earth) self.play(ShowCreation(earth.mesh, lag_ratio=0.01, run_time=3)) for mob in earths: mob.add(mob.mesh) earth.save_state() self.play(Rotate(earth, PI / 2), run_time=2) for mob in earths[1:]: mob.rotate(PI / 2) self.play( Transform(earth, earths[1]), run_time=3 ) light = self.camera.light_source frame = self.camera.frame self.play( Transform(earth, earths[2]), frame.increment_phi, -10 * DEGREES, frame.increment_theta, -20 * DEGREES, run_time=3 ) frame.add_updater(lambda m, dt: m.increment_theta(-0.1 * dt)) self.add(light) light.save_state() self.play(light.move_to, 3 * IN, run_time=5) self.play(light.shift, 10 * OUT, run_time=5) self.wait(4)
from manim_imports_ext import * import scipy.stats CMARK_TEX = "\\text{\\ding{51}}" XMARK_TEX = "\\text{\\ding{55}}" COIN_COLOR_MAP = { "H": BLUE_E, "T": RED_E, } class Histogram(Group): CONFIG = { "height": 5, "width": 10, "y_max": 1, "y_axis_numbers_to_show": range(20, 120, 20), "y_axis_label_height": 0.25, "y_tick_freq": 0.2, "x_label_freq": 1, "include_h_lines": True, "h_line_style": { "stroke_width": 1, "stroke_color": GREY_B, # "stroke_behind": True, }, "bar_style": { "stroke_width": 1, "stroke_color": WHITE, "fill_opacity": 1, }, "bar_colors": [BLUE, GREEN] } def __init__(self, data, **kwargs): super().__init__(**kwargs) self.data = data self.add_axes() if self.include_h_lines: self.add_h_lines() self.add_bars(data) self.add_x_axis_labels() self.add_y_axis_labels() def add_axes(self): n_bars = len(self.data) axes_config = { "x_min": 0, "x_max": n_bars, "x_axis_config": { "unit_size": self.width / n_bars, "include_tip": False, }, "y_min": 0, "y_max": self.y_max, "y_axis_config": { "unit_size": self.height / self.y_max, "include_tip": False, "tick_frequency": self.y_tick_freq, }, } axes = Axes(**axes_config) axes.center() self.axes = axes self.add(axes) def add_h_lines(self): axes = self.axes axes.h_lines = VGroup() for tick in axes.y_axis.tick_marks: line = Line(**self.h_line_style) line.match_width(axes.x_axis) line.move_to(tick.get_center(), LEFT) axes.h_lines.add(line) axes.add(axes.h_lines) def add_bars(self, data): self.bars = self.get_bars(data) self.add(self.bars) def add_x_axis_labels(self): axes = self.axes axes.x_labels = VGroup() for x, bar in list(enumerate(self.bars))[::self.x_label_freq]: label = Integer(x) label.set_height(0.25) label.next_to(bar, DOWN) axes.x_labels.add(label) axes.add(axes.x_labels) def add_y_axis_labels(self): axes = self.axes labels = VGroup() for value in self.y_axis_numbers_to_show: label = Integer(value, unit="\\%") label.set_height(self.y_axis_label_height) label.next_to(axes.y_axis.n2p(0.01 * value), LEFT) labels.add(label) axes.y_labels = labels axes.y_axis.add(labels) # Bar manipulations def get_bars(self, data): portions = np.array(data).astype(float) total = portions.sum() if total == 0: portions[:] = 0 else: portions /= total bars = VGroup() for x, prop in enumerate(portions): bar = Rectangle() width = get_norm(self.axes.c2p(1, 0) - self.axes.c2p(0, 0)) height = get_norm(self.axes.c2p(0, 1) - self.axes.c2p(0, 0)) bar.set_width(width) bar.set_height(height * prop, stretch=True) bar.move_to(self.axes.c2p(x, 0), DL) bars.add(bar) bars.set_submobject_colors_by_gradient(*self.bar_colors) bars.set_style(**self.bar_style) return bars # Images of randomness def get_random_process(choices, shuffle_time=2, total_time=3, change_rate=0.05, h_buff=0.1, v_buff=0.1): content = choices[0] container = Square() container.set_opacity(0) container.set_width(content.get_width() + 2 * h_buff, stretch=True) container.set_height(content.get_height() + 2 * v_buff, stretch=True) container.move_to(content) container.add(content) container.time = 0 container.last_change_time = 0 def update(container, dt): container.time += dt t = container.time change = all([ (t % total_time) < shuffle_time, container.time - container.last_change_time > change_rate ]) if change: mob = container.submobjects[0] new_mob = random.choice(choices) new_mob.match_height(mob) new_mob.move_to(container, DL) new_mob.shift(2 * np.random.random() * h_buff * RIGHT) new_mob.shift(2 * np.random.random() * v_buff * UP) container.set_submobjects([new_mob]) container.last_change_time = container.time container.add_updater(update) return container def get_die_faces(): dot = Dot() dot.set_width(0.15) dot.set_color(BLUE_B) square = Square() square.round_corners(0.25) square.set_stroke(WHITE, 2) square.set_fill(GREY_E, 1) square.set_width(0.6) edge_groups = [ (ORIGIN,), (UL, DR), (UL, ORIGIN, DR), (UL, UR, DL, DR), (UL, UR, ORIGIN, DL, DR), (UL, UR, LEFT, RIGHT, DL, DR), ] arrangements = VGroup(*[ VGroup(*[ dot.copy().move_to(square.get_bounding_box_point(ec)) for ec in edge_group ]) for edge_group in edge_groups ]) square.set_width(1) faces = VGroup(*[ VGroup(square.copy(), arrangement) for arrangement in arrangements ]) faces.arrange(RIGHT) return faces def get_random_die(**kwargs): return get_random_process(get_die_faces(), **kwargs) def get_random_card(height=1, **kwargs): cards = DeckOfCards() cards.set_height(height) return get_random_process(cards, **kwargs) # Coins def get_coin(symbol, color=None): if color is None: color = COIN_COLOR_MAP.get(symbol, GREY_E) coin = VGroup() circ = Circle() circ.set_fill(color, 1) circ.set_stroke(WHITE, 1) circ.set_height(1) label = OldTexText(symbol) label.set_height(0.5 * circ.get_height()) label.move_to(circ) coin.add(circ, label) coin.symbol = symbol return coin def get_random_coin(**kwargs): return get_random_process([get_coin("H"), get_coin("T")], **kwargs) def get_prob_coin_label(symbol="H", color=None, p=0.5, num_decimal_places=2): label = OldTex("P", "(", "00", ")", "=",) coin = get_coin(symbol, color) template = label.get_part_by_tex("00") coin.replace(template) label.replace_submobject(label.index_of_part(template), coin) rhs = DecimalNumber(p, num_decimal_places=num_decimal_places) rhs.next_to(label, RIGHT, buff=MED_SMALL_BUFF) label.add(rhs) return label def get_q_box(mob): box = SurroundingRectangle(mob) box.set_stroke(WHITE, 1) box.set_fill(GREY_E, 1) q_marks = OldTex("???") max_width = 0.8 * box.get_width() max_height = 0.8 * box.get_height() if q_marks.get_width() > max_width: q_marks.set_width(max_width) if q_marks.get_height() > max_height: q_marks.set_height(max_height) q_marks.move_to(box) box.add(q_marks) return box def get_coin_grid(bools, height=6): coins = VGroup(*[ get_coin("H" if heads else "T") for heads in bools ]) coins.arrange_in_grid() coins.set_height(height) return coins def get_prob_positive_experience_label(include_equals=False, include_decimal=False, include_q_mark=False): label = OldTex( "P", "(", "00000", ")", ) pe = OldTexText("Positive\\\\experience") pe.set_color(GREEN) pe.replace(label[2], dim_to_match=0) label.replace_submobject(2, pe) VGroup(label[1], label[3]).match_height( pe, stretch=True, about_edge=DOWN, ) if include_equals: eq = OldTex("=").next_to(label, RIGHT) label.add(eq) if include_decimal: decimal = DecimalNumber(0.95) decimal.next_to(label, RIGHT) decimal.set_color(YELLOW) label.decimal = decimal label.add(decimal) if include_q_mark: q_mark = OldTex("?") q_mark.relative_mob = label[-1] q_mark.add_updater( lambda m: m.next_to(m.relative_mob, RIGHT, SMALL_BUFF) ) label.add(q_mark) return label def get_beta_dist_axes(y_max=20, y_unit=2, label_y=False, **kwargs): config = { "x_min": 0, "x_max": 1, "x_axis_config": { "unit_size": 0.1, "tick_frequency": 0.1, "include_tip": False, }, "y_min": 0, "y_max": y_max, "y_axis_config": { "unit_size": 1, "tick_frequency": y_unit, "include_tip": False, }, } result = Axes(**config) origin = result.c2p(0, 0) kw = { "about_point": origin, "stretch": True, } result.x_axis.set_width(11, **kw) result.y_axis.set_height(6, **kw) x_vals = np.arange(0, 1, 0.2) + 0.2 result.x_axis.add_numbers( *x_vals, num_decimal_places=1 ) if label_y: result.y_axis.add_numbers( *np.arange(y_unit, y_max, y_unit) ) label = OldTexText("Probability density") label.scale(0.5) label.next_to(result.y_axis.get_top(), UR, SMALL_BUFF) label.next_to(result.y_axis, UP, SMALL_BUFF) label.align_to(result.y_axis.numbers, LEFT) result.add(label) result.y_axis_label = label result.to_corner(DR, LARGE_BUFF) return result def scaled_pdf_axes(scale_factor=3.5): axes = get_beta_dist_axes( label_y=True, y_unit=1, ) axes.y_axis.numbers.set_submobjects([ *axes.y_axis.numbers[:5], *axes.y_axis.numbers[4::5] ]) sf = scale_factor axes.y_axis.stretch(sf, 1, about_point=axes.c2p(0, 0)) for number in axes.y_axis.numbers: number.stretch(1 / sf, 1) axes.y_axis_label.to_edge(LEFT) axes.y_axis_label.add_background_rectangle(opacity=1) axes.set_stroke(background=True) return axes def close_off_graph(axes, graph): x_max = axes.x_axis.p2n(graph.get_end()) graph.add_line_to(axes.c2p(x_max, 0)) graph.add_line_to(axes.c2p(0, 0)) return graph def get_beta_graph(axes, n_plus, n_minus, **kwargs): dist = scipy.stats.beta(n_plus + 1, n_minus + 1) graph = axes.get_graph(dist.pdf, **kwargs) close_off_graph(axes, graph) graph.set_stroke(BLUE, 2) graph.set_fill(BLUE_E, 1) return graph def get_beta_label(n_plus, n_minus, point=ORIGIN): template = OldTexText("Beta(", "00", ",", "00", ")") template.scale(1.5) a_label = Integer(n_plus + 1) a_label.set_color(GREEN) b_label = Integer(n_minus + 1) b_label.set_color(RED) for i, label in (1, a_label), (3, b_label): label.match_height(template[i]) label.move_to(template[i], DOWN) template.replace_submobject(i, label) template.save_state() template.arrange(RIGHT, buff=0.15) for t1, t2 in zip(template, template.saved_state): t1.align_to(t2, DOWN) return template def get_plusses_and_minuses(n_rows=15, n_cols=20, p=0.95): result = VGroup() for x in range(n_rows * n_cols): if random.random() < p: mob = OldTex(CMARK_TEX) mob.set_color(GREEN) mob.is_plus = True else: mob = OldTex(XMARK_TEX) mob.set_color(RED) mob.is_plus = False mob.set_width(1) result.add(mob) result.arrange_in_grid(n_rows, n_cols) result.set_width(5.5) return result def get_checks_and_crosses(bools, width=12): result = VGroup() for positive in bools: if positive: mob = OldTex(CMARK_TEX) mob.set_color(GREEN) else: mob = OldTex(XMARK_TEX) mob.set_color(RED) mob.positive = positive mob.set_width(0.5) result.add(mob) result.arrange(RIGHT, buff=MED_SMALL_BUFF) result.set_width(width) return result def get_underlines(marks): underlines = VGroup() for mark in marks: underlines.add(Underline(mark)) for line in underlines: line.align_to(underlines[-1], DOWN) return underlines def get_random_checks_and_crosses(n=50, s=0.95, width=12): return get_checks_and_crosses( bools=(np.random.random(n) < s), width=width ) def get_random_num_row(s, n=10): values = np.random.random(n) nums = VGroup() syms = VGroup() for x, value in enumerate(values): num = DecimalNumber(value) num.set_height(0.25) num.move_to(x * RIGHT) num.positive = (num.get_value() < s) if num.positive: num.set_color(GREEN) sym = OldTex(CMARK_TEX) else: num.set_color(RED) sym = OldTex(XMARK_TEX) sym.match_color(num) sym.match_height(num) sym.positive = num.positive sym.next_to(num, UP) nums.add(num) syms.add(sym) row = VGroup(nums, syms) row.nums = nums row.syms = syms row.n_positive = sum([m.positive for m in nums]) row.set_width(10) row.center().to_edge(UP) return row def get_prob_review_label(n_positive, n_negative, s=0.95): label = OldTex( "P(", f"{n_positive}\\,{CMARK_TEX}", ",\\,", f"{n_negative}\\,{XMARK_TEX}", "\\,|\\,", "s = {:.2f}".format(s), ")", ) label.set_color_by_tex_to_color_map({ CMARK_TEX: GREEN, XMARK_TEX: RED, "0.95": YELLOW, }) return label def get_binomial_formula(n, k, p): n_mob = Integer(n, color=WHITE) k_mob = Integer(k, color=GREEN) nmk_mob = Integer(n - k, color=RED) p_mob = DecimalNumber(p, color=YELLOW) n_str = "N" * len(n_mob) k_str = "K" * len(k_mob) p_str = "P" * len(k_mob) nmk_str = "M" * len(nmk_mob) formula = OldTex( "\\left(", "{" + n_str, "\\over", k_str + "}", "\\right)", "(", p_str, ")", "^{" + k_str + "}", "(1 - ", p_str, ")", "^{" + nmk_str + "}", ) parens = VGroup(formula[0], formula[4]) parens.space_out_submobjects(0.7) formula.remove(formula.get_part_by_tex("\\over")) pairs = ( (n_mob, n_str), (k_mob, k_str), (nmk_mob, nmk_str), (p_mob, p_str), ) for mob, tex in pairs: parts = formula.get_parts_by_tex(tex) for part in parts: mob_copy = mob.copy() i = formula.index_of_part_by_tex(tex) mob_copy.match_height(part) mob_copy.move_to(part, DOWN) formula.replace_submobject(i, mob_copy) terms = VGroup( formula[:4], formula[4:7], formula[7], formula[8:11], formula[11], ) ys = [term.get_y() for term in terms] terms.arrange(RIGHT, buff=SMALL_BUFF) terms[0].shift(SMALL_BUFF * LEFT) for term, y in zip(terms, ys): term.set_y(y) return formula def get_check_count_label(nc, nx, include_rect=True): result = VGroup( Integer(nc), OldTex(CMARK_TEX, color=GREEN), Integer(nx), OldTex(XMARK_TEX, color=RED), ) result.arrange(RIGHT, buff=SMALL_BUFF) result[2:].shift(SMALL_BUFF * RIGHT) if include_rect: rect = SurroundingRectangle(result) rect.set_stroke(WHITE, 1) rect.set_fill(GREY_E, 1) result.add_to_back(rect) return result def reverse_smooth(t): return smooth(1 - t) def get_region_under_curve(axes, graph, min_x, max_x): props = [ binary_search( function=lambda a: axes.x_axis.p2n(graph.pfp(a)), target=x, lower_bound=axes.x_min, upper_bound=axes.x_max, ) for x in [min_x, max_x] ] region = graph.copy() region.pointwise_become_partial(graph, *props) region.add_line_to(axes.c2p(max_x, 0)) region.add_line_to(axes.c2p(min_x, 0)) region.add_line_to(region.get_start()) region.set_stroke(GREEN, 2) region.set_fill(GREEN, 0.5) region.axes = axes region.graph = graph region.min_x = min_x region.max_x = max_x return region
from manim_imports_ext import * from _2020.beta.helpers import * import scipy.stats OUTPUT_DIRECTORY = "bayes/beta1" # Scenes class BarChartTest(Scene): def construct(self): bar_chart = BarChart() bar_chart.to_edge(DOWN) self.add(bar_chart) class Thumbnail1(Scene): def construct(self): p1 = "$96\\%$" p2 = "$93\\%$" n1 = "50" n2 = "200" t2c = { p1: BLUE, p2: YELLOW, n1: BLUE_C, n2: YELLOW, } kw = {"tex_to_color_map": t2c} text = VGroup( OldTexText(f"{p1} with {n1} reviews", **kw), OldTexText("vs.", **kw), OldTexText(f"{p2} with {n2} reviews", **kw), ) text.scale(2) text.arrange(DOWN, buff=LARGE_BUFF) text.set_width(FRAME_WIDTH - 1) self.add(text) class AltThumbnail1(Scene): def construct(self): N = 20 n_trials = 10000 p = 0.7 outcomes = (np.random.random((N, n_trials)) < p).sum(0) counts = [] for k in range(N + 1): counts.append((outcomes == k).sum()) hist = Histogram( counts, y_max=0.3, y_tick_freq=0.05, y_axis_numbers_to_show=[10, 20, 30], x_label_freq=10, ) hist.set_width(FRAME_WIDTH - 1) hist.bars.set_submobject_colors_by_gradient(YELLOW, YELLOW, GREEN, BLUE) hist.bars.set_stroke(WHITE, 2) title = OldTexText("Binomial distribution") title.set_width(12) title.to_corner(UR, buff=0.8) title.add_background_rectangle() self.add(hist) self.add(title) class Thumbnail2(Scene): def construct(self): axes = self.get_axes() graph = get_beta_graph(axes, 2, 2) # sub_graph = axes.get_graph( # lambda x: (1 - x) * graph.underlying_function(x) # ) # sub_graph.add_line_to(axes.c2p(1, 0)) # sub_graph.add_line_to(axes.c2p(0, 0)) # sub_graph.set_stroke(YELLOW, 4) # sub_graph.set_fill(YELLOW_D, 1) new_graph = get_beta_graph(axes, 9, 2) new_graph.set_stroke(GREEN, 4) new_graph.set_fill(GREEN, 0.5) self.add(axes) self.add(graph) self.add(new_graph) arrow = Arrow( axes.input_to_graph_point(0.5, graph), axes.input_to_graph_point(0.8, new_graph), path_arc=-90 * DEGREES, buff=0.3 ) self.add(arrow) formula = OldTex( "P(H|D) = {P(H)P(D|H) \\over P(D)}", tex_to_color_map={ "H": YELLOW, "D": GREEN, } ) formula.next_to(axes.c2p(0, 3), RIGHT, LARGE_BUFF) formula.set_height(1.5) formula.to_edge(LEFT) formula.to_edge(UP, LARGE_BUFF) formula.add_to_back(BackgroundRectangle(formula[:4], buff=0.25)) self.add(formula) def get_axes(self, y_max=3, y_height=4.5, y_unit=0.5): axes = get_beta_dist_axes(y_max=y_max, y_unit=y_unit) axes.y_axis.set_height(y_height, about_point=axes.c2p(0, 0)) axes.to_edge(DOWN) axes.scale(0.9) return axes class Thumbnail3(Thumbnail2): def construct(self): axes = self.get_axes(y_max=4, y_height=6) axes.set_height(7) graph = get_beta_graph(axes, 9, 2) self.add(axes) self.add(graph) label = OldTex( "\\text{Beta}(10, 3)", tex_to_color_map={ "10": GREEN, "3": RED, } ) label = get_beta_label(9, 2) label.set_height(1.25) label.next_to(axes.c2p(0, 3), RIGHT, LARGE_BUFF) self.add(label) class HighlightReviewParts(Scene): CONFIG = { "reverse_order": False, } def construct(self): # Setup up rectangles rects = VGroup(*[Rectangle() for x in range(3)]) rects.set_stroke(width=0) rects.set_fill(GREY, 0.5) rects.set_height(1.35, stretch=True) rects.set_width(9.75, stretch=True) rects[0].move_to([-0.2, 0.5, 0]) rects[1].next_to(rects[0], DOWN, buff=0) rects[2].next_to(rects[1], DOWN, buff=0) rects[2].set_height(1, stretch=True, about_edge=UP) inv_rects = VGroup() for rect in rects: fsr = FullScreenFadeRectangle() fsr.append_points(rect.get_points()[::-1]) inv_rects.add(fsr) inv_rects.set_fill(BLACK, 0.85) # Set up labels ratings = [100, 96, 93] n_reviews = [10, 50, 200] colors = [PINK, BLUE, YELLOW] review_labels = VGroup() for rect, rating, nr, color in zip(rects, ratings, n_reviews, colors): label = OldTex( f"{nr}", "\\text{ reviews }", f"{rating}", "\\%", ) label[2:].set_color(color) label.set_height(1) label.next_to(rect, UP, aligned_edge=RIGHT) label.set_stroke(BLACK, 4, background=True) fix_percent(label[3][0]) review_labels.add(label) # Animations curr_fsr = inv_rects[0] curr_label = None tuples = list(zip(inv_rects, review_labels)) if self.reverse_order: tuples = reversed(tuples) curr_fsr = inv_rects[-1] for fsr, label in tuples: if curr_fsr is fsr: self.play(VFadeIn(fsr)) else: self.play( Transform(curr_fsr, fsr), MoveToTarget(curr_label), ) first, second = label[2:], label[:2] if self.reverse_order: first, second = second, first self.add(first) self.wait(2) self.add(second) self.wait(2) label.generate_target() label.target.scale(0.3) if curr_label is None: label.target.to_corner(UR) label.target.shift(MED_LARGE_BUFF * LEFT) else: label.target.next_to(curr_label, DOWN) curr_label = label self.play(MoveToTarget(curr_label)) self.wait() br = BackgroundRectangle(review_labels, buff=0.25) br.set_fill(BLACK, 0.85) br.set_width(FRAME_WIDTH) br.set_height(FRAME_HEIGHT, stretch=True) br.center() self.add(br, review_labels) self.play( FadeOut(curr_fsr), FadeIn(br), ) self.wait() class ShowThreeCases(Scene): def construct(self): titles = self.get_titles() reviews = self.get_reviews(titles) for review in reviews: review.match_x(reviews[2]) # Introduce everything self.play(LaggedStartMap( FadeInFrom, titles, lambda m: (m, DOWN), lag_ratio=0.2 )) self.play(LaggedStart(*[ LaggedStartMap( FadeInFromLarge, review, lag_ratio=0.1 ) for review in reviews ], lag_ratio=0.1)) self.add(reviews) self.wait() self.play(ShowCreationThenFadeAround(reviews[2])) self.wait() # Suspicious of 100% randy = Randolph() randy.flip() randy.set_height(2) randy.next_to( reviews[0], RIGHT, LARGE_BUFF, aligned_edge=UP, ) randy.look_at(reviews[0]) self.play(FadeIn(randy)) self.play(randy.change, "sassy") self.play(Blink(randy)) self.wait() self.play(FadeOut(randy)) # Low number means it could be a fluke. review = reviews[0] review.generate_target() review.target.scale(2) review.target.arrange(RIGHT) review.target.move_to(review) self.play(MoveToTarget(review)) alt_negs = [1, 2, 1, 0] alt_reviews = VGroup() for k in alt_negs: alt_reviews.add(self.get_plusses_and_minuses(titles[0], 1, 10, k)) for ar in alt_reviews: for m1, m2 in zip(ar, review): m1.replace(m2) alt_percents = VGroup(*[ OldTex(str(10 * (10 - k)) + "\\%") for k in alt_negs ]) hundo = titles[0][0] for ap in alt_percents: fix_percent(ap.family_members_with_points()[-1]) ap.match_style(hundo) ap.match_height(hundo) ap.move_to(hundo, RIGHT) last_review = review last_percent = hundo for ar, ap in zip(alt_reviews, alt_percents): self.play( FadeIn(ar, 0.5 * DOWN, lag_ratio=0.2), FadeOut(last_review), FadeIn(ap, 0.5 * DOWN), FadeOut(last_percent, 0.5 * UP), run_time=1.5 ) last_review = ar last_percent = ap self.remove(last_review, last_percent) self.add(titles, *reviews) # How do you think about the tradeoff? p1 = titles[1][0] p2 = titles[2][0] nums = VGroup(p1, p2) lower_reviews = reviews[1:] lower_reviews.generate_target() lower_reviews.target.arrange(LEFT, buff=1.5) lower_reviews.target.center() nums.generate_target() for nt, review in zip(nums.target, lower_reviews.target): nt.next_to(review, UP, MED_LARGE_BUFF) nums.target[0].match_y(nums.target[1]) self.clear() self.play( MoveToTarget(lower_reviews), MoveToTarget(nums), FadeOut(titles[1][1:]), FadeOut(titles[2][1:]), FadeOut(titles[0]), FadeOut(reviews[0]), run_time=2, ) greater_than = OldTex(">") greater_than.scale(2) greater_than.move_to(midpoint( reviews[2].get_right(), reviews[1].get_left(), )) less_than = greater_than.copy().flip() less_than.match_height(nums[0][0]) less_than.match_y(nums, DOWN) nums.generate_target() nums.target[1].next_to(less_than, LEFT, MED_LARGE_BUFF) nums.target[0].next_to(less_than, RIGHT, MED_LARGE_BUFF) squares = VGroup(*[ SurroundingRectangle( submob, buff=0.01, stroke_color=GREY_B, stroke_width=1, ) for submob in reviews[2] ]) squares.shuffle() self.play( LaggedStartMap( ShowCreationThenFadeOut, squares, lag_ratio=0.5 / len(squares), run_time=3, ), Write(greater_than), ) self.wait() self.play( MoveToTarget(nums), TransformFromCopy( greater_than, less_than, ) ) self.wait() def get_titles(self): titles = VGroup( OldTexText( "$100\\%$ \\\\", "10 reviews" ), OldTexText( "$96\\%$ \\\\", "50 reviews" ), OldTexText( "$93\\%$ \\\\", "200 reviews" ), ) colors = [PINK, BLUE, YELLOW] for title, color in zip(titles, colors): fix_percent(title[0][-1]) title[0].set_color(color) titles.scale(1.25) titles.arrange(DOWN, buff=1.5) titles.to_corner(UL) return titles def get_reviews(self, titles): return VGroup( self.get_plusses_and_minuses( titles[0], 5, 2, 0, ), self.get_plusses_and_minuses( titles[1], 5, 10, 2, ), self.get_plusses_and_minuses( titles[2], 8, 25, 14, ), ) def get_plusses_and_minuses(self, title, n_rows, n_cols, n_minus): check = OldTex(CMARK_TEX, color=GREEN) cross = OldTex(XMARK_TEX, color=RED) checks = VGroup(*[ check.copy() for x in range(n_rows * n_cols) ]) checks.arrange_in_grid(n_rows=n_rows, n_cols=n_cols) checks.scale(0.5) # if checks.get_height() > title.get_height(): # checks.match_height(title) checks.next_to(title, RIGHT, LARGE_BUFF) for check in random.sample(list(checks), n_minus): mob = cross.copy() mob.replace(check, dim_to_match=0) check.become(mob) return checks class PreviewThreeVideos(Scene): def construct(self): # Write equations equations = VGroup( OldTex("{10", "\\over", "10}", "=", "100\\%"), OldTex("{48", "\\over", "50}", "=", "96\\%"), OldTex("{186", "\\over", "200}", "=", "93\\%"), ) equations.arrange(RIGHT, buff=3) equations.to_edge(UP) colors = [PINK, BLUE, YELLOW] for eq, color in zip(equations, colors): eq[-1].set_color(color) fix_percent(eq[-1][-1]) vs_labels = VGroup(*[TexText("vs.") for x in range(2)]) for eq1, eq2, vs in zip(equations, equations[1:], vs_labels): vs.move_to(midpoint(eq1.get_right(), eq2.get_left())) self.add(equations) self.add(vs_labels) # Show topics title = OldTexText("To be explained:") title.set_height(0.7) title.next_to(equations, DOWN, LARGE_BUFF) title.to_edge(LEFT) title.add(Underline(title)) topics = VGroup( OldTexText("Binomial distributions"), OldTexText("Bayesian updating"), OldTexText("Probability density functions"), OldTexText("Beta distribution"), ) topics.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) topics.next_to(title, DOWN, MED_LARGE_BUFF) topics.to_edge(LEFT, buff=LARGE_BUFF) bullets = VGroup() for topic in topics: bullet = Dot() bullet.next_to(topic, LEFT) bullets.add(bullet) self.play( Write(title), Write(bullets), run_time=1, ) self.play(LaggedStart(*[ FadeIn(topic, lag_ratio=0.1) for topic in topics ], run_time=3, lag_ratio=0.3)) self.wait() # Show videos images = [ ImageMobject(os.path.join( consts.VIDEO_DIR, OUTPUT_DIRECTORY, "images", name )) for name in ["Thumbnail1", "Thumbnail2", "Thumbnail3"] ] thumbnails = Group() for image in images: image.set_width(FRAME_WIDTH / 3 - 1) rect = SurroundingRectangle(image, buff=0) rect.set_stroke(WHITE, 3) rect.set_fill(BLACK, 1) thumbnails.add(Group(rect, image)) thumbnails.arrange(RIGHT, buff=LARGE_BUFF) for topic, i in zip(topics, [0, 1, 1, 2]): thumbnail = thumbnails[i] topic.generate_target() topic.target.scale(0.6) topic.target.next_to(thumbnail, DOWN, aligned_edge=LEFT) topics[2].target.next_to( topics[1].target, DOWN, aligned_edge=LEFT, ) self.play( FadeOut(title, LEFT), FadeOut(bullets, LEFT), LaggedStartMap(MoveToTarget, topics), LaggedStartMap(FadeIn, thumbnails), ) self.wait() tn_groups = Group( Group(thumbnails[0], topics[0]), Group(thumbnails[1], topics[1], topics[2]), Group(thumbnails[2], topics[3]), ) setup_words = OldTexText("Set up the model") analysis_words = OldTexText("Analysis") for words in [setup_words, analysis_words]: words.scale(topics[0][0].get_height() / words[0][0].get_height()) words.set_color(YELLOW) setup_words.move_to(topics[0], UL) analysis_words.next_to(topics[3], DOWN, aligned_edge=LEFT) def set_opacity(mob, alpha): for sm in mob.family_members_with_points(): sm.set_opacity(alpha) return mob self.play(ApplyFunction(lambda m: set_opacity(m, 0.2), tn_groups[1:])) self.play( FadeIn(setup_words, lag_ratio=0.1), topics[0].next_to, setup_words, DOWN, {"aligned_edge": LEFT}, ) tn_groups[0].add(setup_words) self.wait(2) for i in 0, 1: self.play( ApplyFunction(lambda m: set_opacity(m, 0.2), tn_groups[i]), ApplyFunction(lambda m: set_opacity(m, 1), tn_groups[i + 1]), ) self.wait(2) self.play(FadeIn(analysis_words, 0.25 * UP)) tn_groups[2].add(analysis_words) self.wait(2) self.play( FadeOut(setup_words), FadeOut(topics[0]), FadeOut(tn_groups[1]), FadeOut(tn_groups[2]), FadeOut(vs_labels, UP), FadeOut(equations, UP), ApplyFunction(lambda m: set_opacity(m, 1), thumbnails[0]), ) thumbnails[0].generate_target() # thumbnails[0].target.set_width(FRAME_WIDTH) # thumbnails[0].target.center() thumbnails[0].target.to_edge(UP) self.play(MoveToTarget(thumbnails[0], run_time=4)) self.wait() class LetsLookAtOneAnswer(TeacherStudentsScene): def construct(self): self.remove(self.background) self.teacher_says( "Let me show you\\\\one answer.", added_anims=[ self.change_students("pondering", "thinking", "pondering") ] ) self.look_at(self.screen) self.play_all_student_changes("thinking", look_at=self.screen) self.wait(4) class LaplacesRuleOfSuccession(Scene): def construct(self): # Setup title = OldTexText("How to read a rating") title.set_height(0.75) title.to_edge(UP) underline = Underline(title) underline.scale(1.2) self.add(title, underline) data = get_checks_and_crosses(11 * [True] + [False], width=10) data.shift(DOWN) underlines = get_underlines(data) real_data = data[:10] fake_data = data[10:] def get_review_label(num, denom): result = VGroup( Integer(num, color=GREEN), OldTexText("out of"), Integer(denom), ) result.arrange(RIGHT) result.set_height(0.6) return result review_label = get_review_label(10, 10) review_label.next_to(data[:10], UP, MED_LARGE_BUFF) # Show initial review self.add(review_label) self.add(underlines[:10]) self.play( ShowIncreasingSubsets(real_data, int_func=np.ceil), CountInFrom(review_label[0], 0), rate_func=lambda t: smooth(t, 3), ) self.wait() # Fake data fd_rect = SurroundingRectangle(VGroup(fake_data, underlines[10:])) fd_rect.set_stroke(WHITE, 2) fd_rect.set_fill(GREY_E, 1) fd_label = OldTexText("Pretend you see\\\\two more") fd_label.next_to(fd_rect, DOWN) fd_label.shift_onto_screen() self.play( FadeIn(fd_label, UP), DrawBorderThenFill(fd_rect), ShowCreation(underlines[10:]) ) self.wait() for mark in data[10:]: self.play(Write(mark)) self.wait() # Update rating review_center = VectorizedPoint(review_label.get_center()) pretend_label = OldTexText("Pretend that it's") pretend_label.match_width(review_label) pretend_label.next_to(review_label, UP, MED_LARGE_BUFF) pretend_label.match_x(data) pretend_label.set_color(BLUE_D) old_review_label = VGroup(Integer(0), OldTexText("out of"), Integer(0)) old_review_label.become(review_label) self.add(old_review_label, review_label) self.play( review_center.set_x, data.get_center()[0], MaintainPositionRelativeTo(review_label, review_center), UpdateFromAlphaFunc( review_label[0], lambda m, a: m.set_value(int(interpolate(10, 11, a))) ), UpdateFromAlphaFunc( review_label[2], lambda m, a: m.set_value(int(interpolate(10, 12, a))) ), FadeIn(pretend_label, LEFT), old_review_label.scale, 0.5, old_review_label.set_opacity, 0.5, old_review_label.to_edge, LEFT, ) self.wait() # Show fraction eq = OldTex( "{11", "\\over", "12}", "\\approx", "91.7\\%" ) fix_percent(eq[-1][-1]) eq.set_color_by_tex("11", GREEN) eq.next_to(pretend_label, RIGHT) eq.to_edge(RIGHT, buff=MED_LARGE_BUFF) self.play(Write(eq)) self.wait() self.play(ShowCreationThenFadeAround(eq)) self.wait() # Remove clutter old_review_label.generate_target() old_review_label.target.next_to(title, DOWN, LARGE_BUFF) old_review_label.target.to_edge(LEFT) old_review_label.target.set_opacity(1) arrow = Vector(0.5 * RIGHT) arrow.next_to(old_review_label.target, RIGHT) self.play( MoveToTarget(old_review_label), FadeIn(arrow), eq.next_to, arrow, RIGHT, FadeOut( VGroup( fake_data, underlines, pretend_label, review_label, fd_rect, fd_label, ), DOWN, lag_ratio=0.01, ), real_data.match_width, old_review_label.target, real_data.next_to, old_review_label.target, DOWN, ) self.wait() # Show 48 of 50 case # Largely copied from above...not great data = get_checks_and_crosses( 48 * [True] + 2 * [False] + [True, False], width=FRAME_WIDTH - 1, ) data.shift(DOWN) underlines = get_underlines(data) review_label = get_review_label(48, 50) review_label.next_to(data, UP, MED_LARGE_BUFF) true_data = data[:-2] fake_data = data[-2:] fd_rect.replace(fake_data, stretch=True) fd_rect.stretch(1.2, 0) fd_rect.stretch(2.2, 1) fd_rect.shift(0.025 * DOWN) fd_label.next_to(fd_rect, DOWN, LARGE_BUFF) fd_label.shift_onto_screen() fd_arrow = Arrow(fd_label.get_top(), fd_rect.get_corner(DL)) self.play( FadeIn(underlines[:-2]), ShowIncreasingSubsets(true_data, int_func=np.ceil), CountInFrom(review_label[0], 0), UpdateFromAlphaFunc( review_label, lambda m, a: m.set_opacity(a), ), ) self.wait() self.play( FadeIn(fd_label), GrowArrow(fd_arrow), FadeIn(fd_rect), Write(fake_data), Write(underlines[-2:]), ) self.wait() # Pretend it's 49 / 52 old_review_label = VGroup(Integer(0), OldTexText("out of"), Integer(0)) old_review_label.become(review_label) review_center = VectorizedPoint(review_label.get_center()) self.play( review_center.set_x, data.get_center()[0] + 3, MaintainPositionRelativeTo(review_label, review_center), UpdateFromAlphaFunc( review_label[0], lambda m, a: m.set_value(int(interpolate(48, 49, a))) ), UpdateFromAlphaFunc( review_label[2], lambda m, a: m.set_value(int(interpolate(50, 52, a))) ), old_review_label.scale, 0.5, old_review_label.to_edge, LEFT, ) self.wait() arrow2 = Vector(0.5 * RIGHT) arrow2.next_to(old_review_label, RIGHT) eq2 = OldTex( "{49", "\\over", "52}", "\\approx", "94.2\\%" ) fix_percent(eq2[-1][-1]) eq2[0].set_color(GREEN) eq2.next_to(arrow2, RIGHT) eq2.save_state() eq2[1].set_opacity(0) eq2[3:].set_opacity(0) eq2[0].replace(review_label[0]) eq2[2].replace(review_label[2]) self.play( Restore(eq2, run_time=1.5), FadeIn(arrow2), ) self.wait() faders = VGroup( fd_rect, fd_arrow, fd_label, fake_data, underlines, review_label, ) self.play( FadeOut(faders), true_data.match_width, old_review_label, true_data.next_to, old_review_label, DOWN, ) # 200 review case final_review_label = get_review_label(186, 200) final_review_label.match_height(old_review_label) final_review_label.move_to(old_review_label, LEFT) final_review_label.shift( arrow2.get_center() - arrow.get_center() ) data = get_checks_and_crosses([True] * 186 + [False] * 14 + [True, False]) data[:200].arrange_in_grid(10, 20, buff=0) data[-2:].next_to(data[:200], DOWN, buff=0) data.set_width(FRAME_WIDTH / 2 - 1) data.to_edge(RIGHT, buff=MED_SMALL_BUFF) data.to_edge(DOWN) for mark in data: mark.scale(0.5) true_data = data[:-2] fake_data = data[-2:] self.play( UpdateFromAlphaFunc( final_review_label, lambda m, a: m.set_opacity(a), ), CountInFrom(final_review_label[0], 0), ShowIncreasingSubsets(true_data), ) self.wait() arrow3 = Vector(0.5 * RIGHT) arrow3.next_to(final_review_label, RIGHT) eq3 = OldTex( "{187", "\\over", "202}", "\\approx", "92.6\\%" ) fix_percent(eq3[-1][-1]) eq3[0].set_color(GREEN) eq3.next_to(arrow3, RIGHT) self.play( GrowArrow(arrow3), FadeIn(eq3), Write(fake_data) ) self.wait() self.play( true_data.match_width, final_review_label, true_data.next_to, final_review_label, DOWN, FadeOut(fake_data) ) self.wait() # Make a selection rect = SurroundingRectangle(VGroup(eq2, old_review_label)) rect.set_stroke(YELLOW, 2) self.play( ShowCreation(rect), eq2[-1].set_color, YELLOW, ) self.wait() # Retitle name = OldTexText("Laplace's rule of succession") name.match_height(title) name.move_to(title) name.set_color(TEAL) self.play( FadeInFromDown(name), FadeOut(title, UP), underline.match_width, name, ) self.wait() class AskWhy(TeacherStudentsScene): def construct(self): self.student_says( "Wait...why?", look_at=self.screen, ) self.play( self.students[0].change, "confused", self.screen, self.students[1].change, "confused", self.screen, self.teacher.change, "tease", self.students[2].eyes, ) self.wait(3) self.student_says( "Is that really\\\\the answer?", target_mode="raise_right_hand", added_anims=[self.teacher.change, "thinking"], ) self.wait(2) self.teacher_says("Let's dive in!", target_mode="hooray") self.play_all_student_changes("hooray") self.wait(3) class BinomialName(Scene): def construct(self): text = OldTexText("Probabilities of probabilities\\\\", "Part 1") text.set_width(FRAME_WIDTH - 1) text[0].set_color(BLUE) self.add(text[0]) self.play(Write(text[1], run_time=2)) self.wait(2) class WhatsTheModel(Scene): CONFIG = { "random_seed": 5, } def construct(self): self.add_questions() self.introduce_buyer_and_seller() for x in range(3): self.play(*self.experience_animations(self.seller, self.buyer)) self.wait() self.add_probability_label() self.bring_up_goal() def add_questions(self): questions = VGroup( OldTexText("What's the model?"), OldTexText("What are you optimizing?"), ) for question, vect in zip(questions, [LEFT, RIGHT]): question.move_to(vect * FRAME_WIDTH / 4) questions.arrange(DOWN, buff=LARGE_BUFF) questions.scale(1.5) # Intro questions self.play(FadeIn(questions[0])) self.play(FadeIn(questions[1], UP)) self.wait() questions[1].save_state() self.questions = questions def introduce_buyer_and_seller(self): if hasattr(self, "questions"): questions = self.questions added_anims = [ questions[0].to_edge, UP, questions[1].set_opacity, 0.5, questions[1].scale, 0.25, questions[1].to_corner, UR, ] else: added_anims = [] seller = Randolph(mode="coin_flip_1") seller.to_edge(LEFT) seller.label = OldTexText("Seller") buyer = Mortimer() buyer.to_edge(RIGHT) buyer.label = OldTexText("Buyer") VGroup(buyer, seller).shift(DOWN) labels = VGroup() for pi in seller, buyer: pi.set_height(2) pi.label.scale(1.5) pi.label.next_to(pi, DOWN, MED_LARGE_BUFF) labels.add(pi.label) buyer.make_eye_contact(seller) self.play( LaggedStartMap( FadeInFromDown, VGroup(seller, buyer, *labels), lag_ratio=0.2 ), *added_anims ) self.wait() self.buyer = buyer self.seller = seller def add_probability_label(self): seller = self.seller buyer = self.buyer label = get_prob_positive_experience_label() label.add(OldTex("=").next_to(label, RIGHT)) rhs = DecimalNumber(0.75) rhs.next_to(label, RIGHT) rhs.align_to(label[0], DOWN) label.add(rhs) label.scale(1.5) label.next_to(seller, UP, MED_LARGE_BUFF, aligned_edge=LEFT) rhs.set_color(YELLOW) brace = Brace(rhs, UP) success_rate = brace.get_text("Success rate")[0] s_sym = brace.get_tex("s").scale(1.5, about_edge=DOWN) success_rate.match_color(rhs) s_sym.match_color(rhs) self.add(label) self.play( GrowFromCenter(brace), FadeIn(success_rate, 0.5 * DOWN) ) self.wait() self.play( TransformFromCopy(success_rate[0], s_sym), FadeOut(success_rate, 0.1 * RIGHT, lag_ratio=0.1), ) for x in range(2): self.play(*self.experience_animations(seller, buyer, arc=30 * DEGREES)) self.wait() grey_box = SurroundingRectangle(rhs, buff=SMALL_BUFF) grey_box.set_stroke(GREY_E, 0.5) grey_box.set_fill(GREY_D, 1) lil_q_marks = OldTex("???") lil_q_marks.scale(0.5) lil_q_marks.next_to(buyer, UP) self.play( FadeOut(rhs, 0.5 * DOWN), FadeIn(grey_box, 0.5 * UP), FadeIn(lil_q_marks, DOWN), buyer.change, "confused", grey_box, ) rhs.set_opacity(0) for x in range(2): self.play(*self.experience_animations(seller, buyer, arc=30 * DEGREES)) self.play(buyer.change, "confused", lil_q_marks) self.play(Blink(buyer)) self.prob_group = VGroup( label, grey_box, brace, s_sym, ) self.buyer_q_marks = lil_q_marks def bring_up_goal(self): prob_group = self.prob_group questions = self.questions questions.generate_target() questions.target[1].replace(questions[0], dim_to_match=1) questions.target[1].match_style(questions[0]) questions.target[0].replace(questions[1], dim_to_match=1) questions.target[0].match_style(questions[1]) prob_group.generate_target() prob_group.target.scale(0.5) prob_group.target.next_to(self.seller, RIGHT) self.play( FadeOut(self.buyer_q_marks), self.buyer.change, "pondering", questions[0], self.seller.change, "pondering", questions[0], MoveToTarget(prob_group), MoveToTarget(questions), ) self.play(self.seller.change, "coin_flip_1") for x in range(3): self.play(*self.experience_animations(self.seller, self.buyer)) self.wait() # def experience_animations(self, seller, buyer, arc=-30 * DEGREES, p=0.75): positive = (random.random() < p) words = OldTexText( "Positive\\\\experience" if positive else "Negative\\\\experience" ) words.set_color(GREEN if positive else RED) if positive: new_mode = random.choice([ "hooray", "coin_flip_1", ]) else: new_mode = random.choice([ "tired", "angry", "sad", ]) words.move_to(seller.get_corner(UR)) result = [ ApplyMethod( words.move_to, buyer.get_corner(UL), path_arc=arc, run_time=2 ), VFadeInThenOut(words, run_time=2), ApplyMethod( buyer.change, new_mode, seller.eyes, run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1), ), ApplyMethod( seller.change, "coin_flip_2", buyer.eyes, rate_func=there_and_back, ), ] return result class IsSellerOne100(Scene): def construct(self): self.add_review() self.show_probability() self.show_simulated_reviews() def add_review(self): reviews = VGroup(*[Tex(CMARK_TEX) for x in range(10)]) reviews.arrange(RIGHT) reviews.scale(2) reviews.set_color(GREEN) reviews.next_to(ORIGIN, UP) blanks = VGroup(*[ Line(LEFT, RIGHT).match_width(rev).next_to(rev, DOWN, SMALL_BUFF) for rev in reviews ]) blanks.shift(0.25 * reviews[0].get_width() * LEFT) label = OldTexText( " out of ", ) tens = VGroup(*[Integer(10) for x in range(2)]) tens[0].next_to(label, LEFT) tens[1].next_to(label, RIGHT) tens.set_color(GREEN) label.add(tens) label.scale(2) label.next_to(reviews, DOWN, LARGE_BUFF) self.add(label) self.add(blanks) tens[0].to_count = reviews self.play( ShowIncreasingSubsets(reviews, int_func=np.ceil), UpdateFromAlphaFunc( tens[0], lambda m, a: m.set_color( interpolate_color(RED, GREEN, a) ).set_value(len(m.to_count)) ), run_time=2, rate_func=bezier([0, 0, 1, 1]), ) self.wait() self.review_group = VGroup(reviews, blanks, label) def show_probability(self): review_group = self.review_group prob_label = get_prob_positive_experience_label() prob_label.add(OldTex("=").next_to(prob_label, RIGHT)) rhs = DecimalNumber(1) rhs.next_to(prob_label, RIGHT) rhs.set_color(YELLOW) prob_label.add(rhs) prob_label.scale(2) prob_label.to_corner(UL) q_mark = OldTex("?") q_mark.set_color(YELLOW) q_mark.match_height(rhs) q_mark.reference = rhs q_mark.add_updater(lambda m: m.next_to(m.reference, RIGHT)) rhs_rect = SurroundingRectangle(rhs, buff=0.2) rhs_rect.set_color(RED) not_necessarily = OldTexText("Not necessarily!") not_necessarily.set_color(RED) not_necessarily.scale(1.5) not_necessarily.next_to(prob_label, DOWN, 1.5) arrow = Arrow( not_necessarily.get_top(), rhs_rect.get_corner(DL), buff=MED_SMALL_BUFF, ) arrow.set_color(RED) rhs.set_value(0) self.play( ChangeDecimalToValue(rhs, 1), UpdateFromAlphaFunc( prob_label, lambda m, a: m.set_opacity(a), ), FadeIn(q_mark), ) self.wait() self.play( ShowCreation(rhs_rect), Write(not_necessarily), ShowCreation(arrow), review_group.to_edge, DOWN, run_time=1, ) self.wait() self.play( ChangeDecimalToValue(rhs, 0.95), FadeOut(rhs_rect), FadeOut(arrow), FadeOut(not_necessarily), ) self.wait() self.prob_label_group = VGroup( prob_label, rhs, q_mark, ) def show_simulated_reviews(self): prob_label_group = self.prob_label_group review_group = self.review_group # Set up decimals random.seed(2) decimals = VGroup() for x in range(10): dec = DecimalNumber() decimals.add(dec) def randomize_decimals(decimals): for dec in decimals: value = random.random() dec.set_value(value) if value > 0.95: dec.set_color(RED) else: dec.set_color(WHITE) randomize_decimals(decimals) decimals.set_height(0.3) decimals.arrange(RIGHT, buff=MED_LARGE_BUFF) decimals.next_to(ORIGIN, DOWN) decimals[0].set_value(0.42) decimals[0].set_color(WHITE) decimals[1].set_value(0.97) decimals[1].set_color(RED) random_label = OldTexText("Random number\\\\in [0, 1]") random_label.scale(0.7) random_label.next_to(decimals[0], DOWN) random_label.set_color(GREY_B) arrows = VGroup() for dec in decimals: arrow = Vector(0.4 * UP) arrow.next_to(dec, UP) arrows.add(arrow) # Set up marks def get_marks(decs, arrows): marks = VGroup() for dec, arrow in zip(decs, arrows): if dec.get_value() < 0.95: mark = OldTex(CMARK_TEX) mark.set_color(GREEN) else: mark = OldTex(XMARK_TEX) mark.set_color(RED) mark.set_height(0.5) mark.next_to(arrow, UP) marks.add(mark) return marks marks = get_marks(decimals, arrows) lt_p95 = OldTex("< 0.95") gte_p95 = OldTex("\\ge 0.95") for label in lt_p95, gte_p95: label.match_height(decimals[0]) lt_p95.next_to(decimals[0], RIGHT, MED_SMALL_BUFF) gte_p95.next_to(decimals[1], RIGHT, MED_SMALL_BUFF) lt_p95.set_color(GREEN) gte_p95.set_color(RED) # Introduce simulation review_group.save_state() self.play( review_group.scale, 0.25, review_group.to_corner, UR, Write(random_label), CountInFrom(decimals[0], 0), ) self.wait() self.play(FadeIn(lt_p95, LEFT)) self.play( GrowArrow(arrows[0]), FadeIn(marks[0], DOWN) ) self.wait() self.play( FadeOut(lt_p95, 0.5 * RIGHT), FadeIn(gte_p95, 0.5 * LEFT), ) self.play( random_label.match_x, decimals[1], CountInFrom(decimals[1], 0), UpdateFromAlphaFunc( decimals[1], lambda m, a: m.set_opacity(a), ), ) self.play( GrowArrow(arrows[1]), FadeIn(marks[1], DOWN), ) self.wait() self.play( LaggedStartMap( CountInFrom, decimals[2:], ), UpdateFromAlphaFunc( decimals[2:], lambda m, a: m.set_opacity(a), ), FadeOut(gte_p95), run_time=1, ) self.add(decimals) self.play( LaggedStartMap(GrowArrow, arrows[2:]), LaggedStartMap(FadeInFromDown, marks[2:]), run_time=1 ) self.add(arrows, marks) self.wait() # Add new rows decimals.arrows = arrows decimals.add_updater(lambda d: d.next_to(d.arrows, DOWN)) added_anims = [FadeOut(random_label)] rows = VGroup(marks) for x in range(3): self.play( arrows.shift, DOWN, UpdateFromFunc(decimals, randomize_decimals), *added_anims, ) added_anims = [] new_marks = get_marks(decimals, arrows) self.play(LaggedStartMap(FadeInFromDown, new_marks)) self.wait() rows.add(new_marks) # Create a stockpile of new rows added_rows = VGroup() decimals.clear_updaters() decimals.save_state() for x in range(100): randomize_decimals(decimals) added_rows.add(get_marks(decimals, arrows)) decimals.restore() # Compress rows rows.generate_target() for group in rows.target, added_rows: group.scale(0.3) for row in group: row.arrange(RIGHT, buff=SMALL_BUFF) group.arrange(DOWN, buff=0.2) rows.target.next_to(prob_label_group, DOWN, MED_LARGE_BUFF) rows.target.set_x(-3.5) nr = 15 added_rows[:nr].move_to(rows.target, UP) added_rows[nr:2 * nr].move_to(rows.target, UP) added_rows[nr:2 * nr].shift(3.5 * RIGHT) added_rows[2 * nr:3 * nr].move_to(rows.target, UP) added_rows[2 * nr:3 * nr].shift(7 * RIGHT) added_rows = added_rows[4:3 * nr] self.play( MoveToTarget(rows), FadeOut(decimals), FadeOut(arrows), ) self.play(ShowIncreasingSubsets(added_rows), run_time=3) # Show scores all_rows = VGroup(*rows, *added_rows) scores = VGroup() ten_rects = VGroup() for row in all_rows: score = Integer(sum([ mark.get_color() == Color(GREEN) for mark in row ])) score.match_height(row) score.next_to(row, RIGHT) if score.get_value() == 10: score.set_color(TEAL) ten_rects.add(SurroundingRectangle(score)) scores.add(score) ten_rects.set_stroke(YELLOW, 2) self.play(FadeIn(scores)) self.wait() self.play(LaggedStartMap(ShowCreation, ten_rects)) self.play(LaggedStartMap(FadeOut, ten_rects)) self.wait(2) # Show alternate possibilities prob = DecimalNumber(0.95) prob.set_color(YELLOW) template = prob_label_group[0][-1] prob.match_height(template) prob.move_to(template, LEFT) rect = BackgroundRectangle(template, buff=SMALL_BUFF) rect.set_fill(BLACK, 1) self.add(rect) self.add(prob) self.play( LaggedStartMap(FadeOutAndShift, all_rows, lag_ratio=0.01), LaggedStartMap(FadeOutAndShift, scores, lag_ratio=0.01), Restore(review_group), ) for value in [0.9, 0.99, 0.8, 0.95]: self.play(ChangeDecimalToValue(prob, value)) self.wait() # No longer used def show_random_numbers(self): prob_label_group = self.prob_label_group random.seed(2) rows = VGroup(*[ VGroup(*[ Integer( random.randint(0, 99) ).move_to(0.85 * x * RIGHT) for x in range(10) ]) for y in range(10 * 2) ]) rows.arrange_in_grid(n_cols=2, buff=MED_LARGE_BUFF) rows[:10].shift(LEFT) rows.set_height(5.5) rows.center().to_edge(DOWN) lt_95 = VGroup(*[ mob for row in rows for mob in row if mob.get_value() < 95 ]) square = Square() square.set_stroke(width=0) square.set_fill(YELLOW, 0.5) square.set_width(1.5 * rows[0][0].get_height()) # highlights = VGroup(*[ # square.copy().move_to(mob) # for row in rows # for mob in row # if mob.get_value() < 95 # ]) row_rects = VGroup(*[ SurroundingRectangle(row) for row in rows if all([m.get_value() < 95 for m in row]) ]) row_rects.set_stroke(GREEN, 2) self.play( LaggedStartMap( ShowIncreasingSubsets, rows, run_time=3, lag_ratio=0.25, ), FadeOut(self.review_group, DOWN), prob_label_group.set_height, 0.75, prob_label_group.to_corner, UL, ) self.wait() # self.add(highlights, rows) self.play( # FadeIn(highlights) lt_95.set_fill, BLUE, lt_95.set_stroke, BLUE, 2, {"background": True}, ) self.wait() self.play(LaggedStartMap(ShowCreation, row_rects)) self.wait() class LookAtAllPossibleSuccessRates(Scene): def construct(self): axes = get_beta_dist_axes(y_max=6, y_unit=1) dist = scipy.stats.beta(10, 2) graph = axes.get_graph(dist.pdf) graph.set_stroke(BLUE, 3) flat_graph = graph.copy() flat_graph.get_points()[:, 1] = axes.c2p(0, 0)[1] flat_graph.set_stroke(YELLOW, 3) x_labels = axes.x_axis.numbers x_labels.set_opacity(0) sellers = VGroup(*[ self.get_example_seller(label.get_value()) for label in x_labels ]) sellers.arrange(RIGHT, buff=LARGE_BUFF) sellers.set_width(FRAME_WIDTH - 1) sellers.to_edge(UP, buff=LARGE_BUFF) sellers.generate_target() for seller, label in zip(sellers.target, x_labels): seller.next_to(label, DOWN) seller[0].set_opacity(0) seller[1].set_opacity(0) seller[2].replace(label, dim_to_match=1) x_label = OldTexText("All possible success rates") x_label.next_to(axes.c2p(0.5, 0), UP) x_label.shift(2 * LEFT) y_axis_label = OldTexText( "A kind of probability\\\\", "of probabilities" ) y_axis_label.scale(0.75) y_axis_label.next_to(axes.y_axis, RIGHT) y_axis_label.to_edge(UP) y_axis_label[1].set_color(YELLOW) graph_label = OldTexText( "Some notion of likelihood\\\\", "for each one" ) graph_label[1].align_to(graph_label[0], LEFT) graph_label.next_to(graph.get_boundary_point(UP), UP) graph_label.shift(0.5 * DOWN) graph_label.to_edge(RIGHT) x_axis_line = Line(axes.c2p(0, 0), axes.c2p(1, 0)) x_axis_line.set_stroke(YELLOW, 3) shuffled_sellers = VGroup(*sellers) shuffled_sellers.shuffle() self.play(GrowFromCenter(shuffled_sellers[0])) self.play(LaggedStartMap( FadeInFromPoint, shuffled_sellers[1:], lambda m: (m, sellers.get_center()) )) self.wait() self.play( MoveToTarget(sellers), FadeIn(axes), run_time=2, ) self.play( x_label.shift, 4 * RIGHT, UpdateFromAlphaFunc( x_label, lambda m, a: m.set_opacity(a), rate_func=there_and_back, ), ShowCreation(x_axis_line), run_time=3, ) self.play(FadeOut(x_axis_line)) self.wait() self.play( FadeInFromDown(graph_label), ReplacementTransform(flat_graph, graph), ) self.wait() self.play(FadeInFromDown(y_axis_label)) # Show probabilities x_tracker = ValueTracker(0.5) prob_label = get_prob_positive_experience_label(True, True, True) prob_label.next_to(axes.c2p(0, 2), RIGHT, MED_LARGE_BUFF) prob_label.decimal.tracker = x_tracker prob_label.decimal.add_updater( lambda m: m.set_value(m.tracker.get_value()) ) v_line = Line(DOWN, UP) v_line.set_stroke(YELLOW, 2) v_line.tracker = x_tracker v_line.graph = graph v_line.axes = axes v_line.add_updater( lambda m: m.put_start_and_end_on( m.axes.x_axis.n2p(m.tracker.get_value()), m.axes.input_to_graph_point(m.tracker.get_value(), m.graph), ) ) self.add(v_line) for x in [0.95, 0.8, 0.9]: self.play( x_tracker.set_value, x, run_time=4, ) self.wait() def get_example_seller(self, success_rate): randy = Randolph(mode="coin_flip_1", height=1) label = OldTex("s = ") decimal = DecimalNumber(success_rate) decimal.match_height(label) decimal.next_to(label[-1], RIGHT) label.set_color(YELLOW) decimal.set_color(YELLOW) VGroup(label, decimal).next_to(randy, DOWN) result = VGroup(randy, label, decimal) result.randy = randy result.label = label result.decimal = decimal return result class AskAboutUnknownProbabilities(Scene): def construct(self): # Setup unknown_title, prob_title = titles = self.get_titles() v_line = Line(UP, DOWN) v_line.set_height(FRAME_HEIGHT) v_line.set_stroke([WHITE, GREY_B], 3) h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH) h_line.next_to(titles, DOWN) processes = VGroup( get_random_coin(shuffle_time=1), get_random_die(shuffle_time=1.5), get_random_card(shuffle_time=2), ) processes.arrange(DOWN, buff=0.7) processes.next_to(unknown_title, DOWN, LARGE_BUFF) processes_rect = BackgroundRectangle(processes) processes_rect.set_fill(BLACK, 1) prob_labels = VGroup( OldTex("P(", "00", ")", "=", "1 / 2"), OldTex("P(", "00", ")", "=", "1 / 6}"), OldTex("P(", "00", ")", "=", "1 / 52}"), ) prob_labels.scale(1.5) prob_labels.arrange(DOWN, aligned_edge=LEFT) prob_labels.match_x(prob_title) for pl, pr in zip(prob_labels, processes): pl.match_y(pr) content = pr[1].copy() content.replace(pl[1], dim_to_match=0) pl.replace_submobject(1, content) # Putting numbers to the unknown number_rects = VGroup(*[ SurroundingRectangle(pl[-1]) for pl in prob_labels ]) number_rects.set_stroke(YELLOW, 2) for pl in prob_labels: pl.save_state() pl[:3].match_x(prob_title) pl[3:].match_x(prob_title) pl.set_opacity(0) self.add(processes) self.play( LaggedStartMap(FadeInFromDown, titles), LaggedStart( ShowCreation(v_line), ShowCreation(h_line), lag_ratio=0.1, ), LaggedStartMap(Restore, prob_labels), run_time=1 ) self.wait(10) # self.play( # LaggedStartMap( # ShowCreationThenFadeOut, # number_rects, # run_time=3, # ) # ) # self.wait(2) # Highlight coin flip fade_rects = VGroup(*[ VGroup( BackgroundRectangle(pl, buff=MED_SMALL_BUFF), BackgroundRectangle(pr, buff=MED_SMALL_BUFF), ) for pl, pr in zip(prob_labels, processes) ]) fade_rects.set_fill(BLACK, 0.8) prob_half = prob_labels[0] half = prob_half[-1] half_underline = Line(LEFT, RIGHT) half_underline.set_width(half.get_width() + MED_SMALL_BUFF) half_underline.next_to(half, DOWN, buff=SMALL_BUFF) half_underline.set_stroke(YELLOW, 3) self.play( FadeIn(fade_rects[1]), FadeIn(fade_rects[2]), ) self.wait(2) self.play( FadeIn(fade_rects[0]), FadeOut(fade_rects[1]), ) self.wait(3) self.play( FadeOut(fade_rects[0]), FadeOut(fade_rects[2]), ) self.wait(4) # Transition to question processes.suspend_updating() self.play( LaggedStart( FadeOut(unknown_title, UP), FadeOut(prob_title, UP), lag_ratio=0.2, ), FadeOut(h_line, UP, lag_ratio=0.1), FadeOut(processes, LEFT, lag_ratio=0.1), FadeOut(prob_labels[1]), FadeOut(prob_labels[2]), v_line.rotate, 90 * DEGREES, v_line.shift, 0.6 * FRAME_HEIGHT * UP, prob_half.center, prob_half.to_edge, UP, run_time=2, ) self.clear() self.add(prob_half) arrow = Vector(UP) arrow.next_to(half, DOWN) question = OldTexText("What exactly does\\\\this mean?") question.next_to(arrow, DOWN) self.play( GrowArrow(arrow), FadeIn(question, UP), ) self.wait(2) self.play( FadeOut(question, RIGHT), Rotate(arrow, 90 * DEGREES), VFadeOut(arrow), ) # Show long run averages self.show_many_coins(20, 50) self.show_many_coins(40, 100) # Make probability itself unknown q_marks = OldTex("???") q_marks.set_color(YELLOW) q_marks.replace(half, dim_to_match=0) randy = Randolph(mode="confused") randy.center() randy.look_at(prob_half) self.play( FadeOut(half, UP), FadeIn(q_marks, DOWN), ) self.play(FadeIn(randy)) self.play(Blink(randy)) self.wait() # self.embed() def get_titles(self): unknown_label = OldTexText("Random process") prob_label = OldTexText("Long-run frequency") titles = VGroup(unknown_label, prob_label) titles.scale(1.25) unknown_label.move_to(FRAME_WIDTH * LEFT / 4) prob_label.move_to(FRAME_WIDTH * RIGHT / 4) titles.to_edge(UP, buff=MED_SMALL_BUFF) titles.set_color(BLUE) return titles def show_many_coins(self, n_rows, n_cols): coin_choices = VGroup( get_coin("H"), get_coin("T"), ) coin_choices.set_stroke(width=0) coins = VGroup(*[ random.choice(coin_choices).copy() for x in range(n_rows * n_cols) ]) def organize_coins(coin_group): coin_group.scale(1 / coin_group[0].get_height()) coin_group.arrange_in_grid(n_rows=n_rows) coin_group.set_width(FRAME_WIDTH - 1) coin_group.to_edge(DOWN, MED_LARGE_BUFF) organize_coins(coins) sorted_coins = VGroup() for coin in coins: coin.generate_target() sorted_coins.add(coin.target) sorted_coins.submobjects.sort(key=lambda m: m.symbol) organize_coins(sorted_coins) self.play(LaggedStartMap( FadeInFrom, coins, lambda m: (m, 0.2 * DOWN), run_time=3, rate_func=linear )) self.wait() self.play(LaggedStartMap( MoveToTarget, coins, path_arc=30 * DEGREES, run_time=2, lag_ratio=1 / len(coins), )) self.wait() self.play(FadeOut(coins)) class AskProbabilityOfCoins(Scene): def construct(self): condition = VGroup( OldTexText("If you've seen"), Integer(80, color=BLUE_C), get_coin("H").set_height(0.5), OldTexText("and"), Integer(20, color=RED_C), get_coin("T").set_height(0.5), ) condition.arrange(RIGHT) condition.to_edge(UP) self.add(condition) question = OldTex( "\\text{What is }", "P(", "00", ")", "?" ) coin = get_coin("H") coin.replace(question.get_part_by_tex("00")) question.replace_submobject( question.index_of_part_by_tex("00"), coin ) question.next_to(condition, DOWN) self.add(question) values = ["H"] * 80 + ["T"] * 20 random.shuffle(values) coins = VGroup(*[ get_coin(symbol) for symbol in values ]) coins.arrange_in_grid(10, 10, buff=MED_SMALL_BUFF) coins.set_width(5) coins.next_to(question, DOWN, MED_LARGE_BUFF) self.play( ShowIncreasingSubsets(coins), run_time=8, rate_func=bezier([0, 0, 1, 1]) ) self.wait() self.embed() class RunCarFactory(Scene): def construct(self): # Factory factory = SVGMobject(file_name="factory") factory.set_fill(GREY_D) factory.set_stroke(width=0) factory.flip() factory.set_height(6) factory.to_edge(LEFT) self.add(factory) # Dumb hack points = factory[0].get_points() l1 = Line(points[-200], points[-216]) l2 = Line(points[-300], points[-318]) for line in l1, l2: square = Square() square.set_fill(BLACK, 1) square.set_stroke(width=0) square.replace(line) factory.add(square) rect = Rectangle() rect.match_style(factory) rect.set_height(1.1) rect.set_width(6.75, stretch=True) rect.move_to(factory, DL) # Get cars car = Car(color=interpolate_color(BLUE_E, GREY_C, 0.5)) car.set_height(0.9) for tire in car.get_tires(): tire.set_fill(GREY_C) tire.set_stroke(BLACK) car.randy.set_opacity(0) car.move_to(rect.get_corner(DR)) cars = VGroup() n_cars = 20 for x in range(n_cars): cars.add(car.copy()) for car in cars[4], cars[6]: scratch = VMobject() scratch.start_new_path(UP) scratch.add_line_to(0.25 * DL) scratch.add_line_to(0.25 * UR) scratch.add_line_to(DOWN) scratch.set_stroke([RED_A, RED_C], [0.1, 2, 2, 0.1]) scratch.set_height(0.25) scratch.move_to(car) scratch.shift(0.1 * DOWN) car.add(scratch) self.add(cars, rect) self.play(LaggedStartMap( MoveCar, cars, lambda m: (m, m.get_corner(DR) + 10 * RIGHT), lag_ratio=0.3, rate_func=linear, run_time=1.5 * n_cars, )) self.remove(cars) class CarFactoryNumbers(Scene): def construct(self): # Test words denom_words = OldTexText( "in a test of 100 cars", tex_to_color_map={"100": BLUE}, ) denom_words.to_corner(UR) numer_words = OldTexText( "2 defects found", tex_to_color_map={"2": RED} ) numer_words.move_to(denom_words, LEFT) self.play(Write(denom_words, run_time=1)) self.wait() self.play( denom_words.next_to, numer_words, DOWN, {"aligned_edge": LEFT}, FadeIn(numer_words), ) self.wait() # Question words question = VGroup( OldTexText("How do you plan"), OldTexText("for"), Integer(int(1e6), color=BLUE), OldTexText("cars?") ) question[1:].arrange(RIGHT, aligned_edge=DOWN) question[2].shift( (question[2][1].get_bottom()[1] - question[2][0].get_bottom()[1]) * UP ) question[1:].next_to(question[0], DOWN, aligned_edge=LEFT) question.next_to(denom_words, DOWN, LARGE_BUFF, aligned_edge=LEFT) self.play( UpdateFromAlphaFunc( question, lambda m, a: m.set_opacity(a), ), CountInFrom(question[2], 0, run_time=1.5) ) self.wait() class ComplainAboutSimplisticModel(TeacherStudentsScene): def construct(self): axes = self.get_experience_graph() self.add(axes) self.play( self.teacher.change, "raise_right_hand", axes, self.change_students( "pondering", "erm", "sassy", look_at=axes, ), ShowCreation( axes.graph, run_time=3, rate_func=linear, ), ) self.wait(2) student = self.students[2] bubble = SpeechBubble( direction=LEFT, height=3, width=5, ) bubble.pin_to(student) bubble.write("What about something\\\\like this?") self.play( axes.next_to, student, UL, VFadeOut(axes.graph), FadeIn(bubble), Write(bubble.content, run_time=1), student.change, "raise_left_hand", self.students[0].change, "thinking", axes, self.students[1].change, "thinking", axes, self.teacher.change, "happy", ) new_graph = VMobject() new_graph.set_points_as_corners([ axes.c2p(0, 0.75), axes.c2p(2, 0.9), axes.c2p(4, 0.5), axes.c2p(6, 0.75), axes.c2p(8, 0.55), axes.c2p(10, 0.95), ]) new_graph.make_smooth() new_graph.set_stroke([YELLOW, RED, GREEN], 2) self.play( ShowCreation(new_graph), *[ ApplyMethod(pi.look_at, new_graph) for pi in self.pi_creatures ] ) self.wait(3) def get_experience_graph(self): axes = Axes( x_min=-1, x_max=10, y_min=0, y_max=1.25, y_axis_config={ "unit_size": 5, "tick_frequency": 0.25, "include_tip": False, } ) axes.set_stroke(GREY_B, 1) axes.set_height(3) y_label = OldTexText("Experience quality") y_label.scale(0.5) y_label.next_to(axes.y_axis.get_top(), RIGHT, SMALL_BUFF) axes.add(y_label) lines = VGroup() for x in range(10): lines.add( Line(axes.c2p(x, 0), axes.c2p(x + 0.9, 0)) ) lines.set_stroke(RED, 3) for line in lines: if random.random() < 0.5: line.set_y(axes.c2p(0, 1)[1]) line.set_stroke(GREEN) axes.add(lines) axes.graph = lines rect = BackgroundRectangle(axes, buff=0.25) rect.set_stroke(WHITE, 1) rect.set_fill(BLACK, 1) axes.add_to_back(rect) axes.to_corner(UR) return axes class ComingUpWrapper(Scene): def construct(self): background = FullScreenFadeRectangle() background.set_fill(GREY_E, 1) title = OldTexText("What's coming...") title.scale(1.5) title.to_edge(UP) rect = ScreenRectangle() rect.set_height(6) rect.set_stroke(WHITE) rect.set_fill(BLACK, 1) rect.next_to(title, DOWN) self.add(background, rect) self.play(FadeInFromDown(title)) self.wait() class PreviewBeta(Scene): def construct(self): axes = get_beta_dist_axes(label_y=True) axes.y_axis.remove(axes.y_axis.numbers) marks = get_plusses_and_minuses(p=0.75) marks.next_to(axes.y_axis.get_top(), DR, buff=0.75) beta_label = get_beta_label(0, 0) beta_label.next_to(marks, UR, buff=LARGE_BUFF) beta_label.to_edge(UP) bl_left = beta_label.get_left() beta_container = VGroup() graph_container = VGroup() n_graphs = 2 for x in range(n_graphs): graph_container.add(VMobject()) def get_counts(marks): is_plusses = [m.is_plus for m in marks] p = sum(is_plusses) n = len(is_plusses) - p return p, n def update_beta(container): counts = get_counts(marks) new_label = get_beta_label(*counts) new_label.move_to(bl_left, LEFT) container.set_submobjects([new_label]) return container def update_graph(container): counts = get_counts(marks) new_graph = get_beta_graph(axes, *counts) new_graphs = [*container[1:], new_graph] for g, a in zip(new_graphs, np.linspace(0.2, 1, n_graphs)): g.set_opacity(a) container.set_submobjects(new_graphs) return container self.add(axes) self.play( ShowIncreasingSubsets(marks), UpdateFromFunc( beta_container, update_beta, ), UpdateFromFunc( graph_container, update_graph, ), run_time=15, rate_func=bezier([0, 0, 1, 1]), ) self.wait() class AskInverseQuestion(WhatsTheModel): def construct(self): self.force_skipping() self.introduce_buyer_and_seller() self.bs_group = VGroup( self.buyer, self.seller, self.buyer.label, self.seller.label, ) self.bs_group.to_edge(DOWN) self.revert_to_original_skipping_status() self.add_probability_label() self.show_many_review_animations() self.ask_question() def add_probability_label(self): label = get_prob_positive_experience_label(True, True, False) label.decimal.set_value(0.95) label.next_to(self.seller, UP, aligned_edge=LEFT, buff=MED_LARGE_BUFF) self.add(label) self.probability_label = label def show_many_review_animations(self): for x in range(7): self.play(*self.experience_animations( self.seller, self.buyer, arc=30 * DEGREES, p=0.95, )) def ask_question(self): pis = [self.buyer, self.seller] labels = VGroup( self.get_prob_review_label(10, 0), self.get_prob_review_label(48, 2), self.get_prob_review_label(186, 14), ) labels.arrange(DOWN) labels.to_edge(UP) labels[0].save_state() labels[0].set_opacity(0) words = labels[0][-3:-1] words.set_opacity(1) words.scale(1.5) words.center().to_edge(UP) self.play( FadeInFromDown(words), ) self.wait() self.play( Restore(labels[0]), *[ ApplyMethod(pi.change, 'pondering', labels) for pi in pis ] ) self.play(Blink(pis[0])) self.play(Blink(pis[1])) self.play(LaggedStartMap(FadeInFromDown, labels[1:])) self.wait(2) # Succinct short_label = OldTex( "P(\\text{data} | s)", tex_to_color_map={ "\\text{data}": GREY_B, "s": YELLOW } ) short_label.scale(2) short_label.next_to(labels, DOWN, LARGE_BUFF), rect = SurroundingRectangle(short_label, buff=MED_SMALL_BUFF) bs_group = self.bs_group bs_group.add(self.probability_label) self.play( FadeIn(short_label, UP), bs_group.scale, 0.5, {"about_edge": DOWN}, ) self.play(ShowCreation(rect)) self.wait() def get_prob_review_label(self, n_positive, n_negative): label = OldTex( "P(", f"{n_positive}\\,{CMARK_TEX}", ",\\,", f"{n_negative}\\,{XMARK_TEX}", "\\,\\text{ Given that }", "s = 0.95", ")", ) label.set_color_by_tex_to_color_map({ CMARK_TEX: GREEN, XMARK_TEX: RED, "0.95": YELLOW, }) return label class SimulationsOf10Reviews(Scene): CONFIG = { "s": 0.95, "histogram_height": 5, "histogram_width": 10, } def construct(self): # Add s label s_label = OldTex("s = 0.95") s_label.set_height(0.3) s_label.to_corner(UL, buff=MED_SMALL_BUFF) s_label.set_color(YELLOW) self.add(s_label) self.camera.frame.shift(LEFT) s_label.shift(LEFT) # Add random row np.random.seed(0) row = get_random_num_row(self.s) count = self.get_count(row) count.add_updater( lambda m: m.set_value( sum([s.positive for s in row.syms]) ) ) def update_nums(nums): for num in nums: num.set_value(np.random.random()) row.nums.save_state() row.nums.set_color(WHITE) self.play( UpdateFromFunc(row.nums, update_nums), run_time=2, ) row.nums.restore() self.wait() self.add(count) self.play( ShowIncreasingSubsets(row.syms), run_time=2, rate_func=linear, ) count.clear_updaters() self.wait() # Histogram data = np.zeros(11) histogram = self.get_histogram(data) stacks = VGroup() for bar in histogram.bars: stacks.add(VGroup(bar.copy())) def put_into_histogram(row_count_group): row, count = row_count_group count.clear_updaters() index = int(count.get_value()) stack = stacks[index] row.set_width(stack.get_width() - SMALL_BUFF) row.next_to(stack, UP, SMALL_BUFF) count.replace(histogram.axes.x_labels[index]) stack.add(row) return row_count_group # Random samples in histogram self.play( FadeIn(histogram), ApplyFunction( put_into_histogram, VGroup(row, count), ) ) self.wait() for x in range(2): row = get_random_num_row(self.s) count = self.get_count(row) group = VGroup(row, count) self.play(FadeIn(group, lag_ratio=0.2)) self.wait(0.5) self.play( ApplyFunction( put_into_histogram, VGroup(row, count), ) ) # More! for x in range(40): row = get_random_num_row(self.s) count = self.get_count(row) lower_group = VGroup(row, count).copy() put_into_histogram(lower_group) self.add(row, count, lower_group) self.wait(0.1) self.remove(row, count) data = np.array([len(stack) - 1 for stack in stacks]) self.add(row, count) self.play( FadeOut(stacks), FadeOut(count), histogram.bars.become, histogram.get_bars(data), histogram.axes.y_labels.set_opacity, 1, histogram.axes.h_lines.set_opacity, 1, histogram.axes.y_axis.set_opacity, 1, ) self.remove(stacks) arrow = Vector(0.5 * DOWN) arrow.set_stroke(width=5) arrow.set_color(YELLOW) arrow.next_to(histogram.bars[10], UP, SMALL_BUFF) def update(dummy): new_row = get_random_num_row(self.s) row.become(new_row) count = sum([m.positive for m in new_row.nums]) data[count] += 1 histogram.bars.become(histogram.get_bars(data)) arrow.next_to(histogram.bars[count], UP, SMALL_BUFF) self.add(arrow) self.play( UpdateFromFunc(Group(row, arrow, histogram.bars), update), run_time=10, ) # def get_histogram(self, data): histogram = Histogram( data, bar_colors=[RED, RED, BLUE, GREEN], height=self.histogram_height, width=self.histogram_width, ) histogram.to_edge(DOWN) histogram.axes.y_labels.set_opacity(0) histogram.axes.h_lines.set_opacity(0) return histogram def get_count(self, row): count = Integer() count.set_height(0.75) count.next_to(row, DOWN, buff=0.65) count.set_value(sum([s.positive for s in row.syms])) return count class SimulationsOf10ReviewsSquished(SimulationsOf10Reviews): CONFIG = { "histogram_height": 2, "histogram_width": 11, } def get_histogram(self, data): hist = super().get_histogram(data) hist.to_edge(UP, buff=1.5) return hist class SimulationsOf50Reviews(Scene): CONFIG = { "s": 0.95, "histogram_config": { "x_label_freq": 5, "y_axis_numbers_to_show": range(10, 70, 10), "y_max": 0.6, "y_tick_freq": 0.1, "height": 5, "bar_colors": [BLUE], }, "random_seed": 1, } def construct(self): self.add_s_label() data = np.zeros(51) histogram = self.get_histogram(data) row = self.get_row() count = self.get_count(row) original_count = count.get_value() count.set_value(0) self.add(histogram) self.play( ShowIncreasingSubsets(row), ChangeDecimalToValue(count, original_count) ) # Run many samples arrow = Vector(0.5 * DOWN) arrow.set_stroke(width=5) arrow.set_color(YELLOW) arrow.next_to(histogram.bars[10], UP, SMALL_BUFF) total_data_label = VGroup( OldTexText("Total samples: "), Integer(1), ) total_data_label.arrange(RIGHT) total_data_label.next_to(row, DOWN) total_data_label.add_updater( lambda m: m[1].set_value(data.sum()) ) def update(dummy, n_added_data_points=0): new_row = self.get_row() row.become(new_row) num_positive = sum([m.positive for m in new_row]) count.set_value(num_positive) data[num_positive] += 1 if n_added_data_points: values = np.random.random((n_added_data_points, 50)) counts = (values < self.s).sum(1) for i in range(len(data)): data[i] += (counts == i).sum() histogram.bars.become(histogram.get_bars(data)) histogram.bars.set_fill(GREY_C) histogram.bars[48].set_fill(GREEN) arrow.next_to(histogram.bars[num_positive], UP, SMALL_BUFF) self.add(arrow, total_data_label) group = VGroup(histogram.bars, row, count, arrow) self.play( UpdateFromFunc(group, update), run_time=4 ) self.play( UpdateFromFunc( group, lambda m: update(m, 1000) ), run_time=4 ) random.seed(0) np.random.seed(0) update(group) self.wait() # Show 48 bar axes = histogram.axes y = choose(50, 48) * (self.s)**48 * (1 - self.s)**2 line = DashedLine( axes.c2p(0, y), axes.c2p(51, y), ) label = OldTex("{:.1f}\\%".format(100 * y)) fix_percent(label.family_members_with_points()[-1]) label.next_to(line, RIGHT) self.play( ShowCreation(line), FadeInFromPoint(label, line.get_start()) ) def add_s_label(self): s_label = OldTex("s = 0.95") s_label.set_height(0.3) s_label.to_corner(UL, buff=MED_SMALL_BUFF) s_label.shift(0.8 * DOWN) s_label.set_color(YELLOW) self.add(s_label) def get_histogram(self, data): histogram = Histogram( data, **self.histogram_config ) histogram.to_edge(DOWN) return histogram def get_row(self, n=50): row = get_random_checks_and_crosses(n, self.s) row.move_to(3.5 * UP) return row def get_count(self, row): count = Integer(sum([m.positive for m in row])) count.set_height(0.3) count.next_to(row, RIGHT) return count class ShowBinomialFormula(SimulationsOf50Reviews): CONFIG = { "histogram_config": { "x_label_freq": 5, "y_axis_numbers_to_show": range(10, 40, 10), "y_max": 0.3, "y_tick_freq": 0.1, "height": 2.5, "bar_colors": [BLUE], }, "random_seed": 0, } def construct(self): # Add histogram dist = scipy.stats.binom(50, self.s) data = np.array([ dist.pmf(x) for x in range(0, 51) ]) histogram = self.get_histogram(data) histogram.bars.set_fill(GREY_C) histogram.bars[48].set_fill(GREEN) self.add(histogram) row = self.get_row() self.add(row) # Formula prob_label = get_prob_review_label(48, 2) eq = OldTex("=") formula = get_binomial_formula(50, 48, self.s) equation = VGroup( prob_label, eq, formula, ) equation.arrange(RIGHT) equation.next_to(histogram, UP, LARGE_BUFF) equation.to_edge(RIGHT) prob_label.save_state() arrow = Vector(DOWN) arrow.next_to(histogram.bars[48], UP, SMALL_BUFF) prob_label.next_to(arrow, UP) self.play( FadeIn(prob_label), GrowArrow(arrow), ) for mob in prob_label[1::2]: line = Underline(mob) line.match_color(mob) self.play(ShowCreationThenDestruction(line)) self.wait(0.5) self.play( Restore(prob_label), FadeIn(equation[1:], lag_ratio=0.1), ) self.wait() self.explain_n_choose_k(row, formula) # Circle formula parts rect1 = SurroundingRectangle(formula[4:8]) rect2 = SurroundingRectangle(formula[8:]) rect1.set_stroke(GREEN, 2) rect2.set_stroke(RED, 2) for rect in rect1, rect2: self.play(ShowCreation(rect)) self.wait() self.play(FadeOut(rect)) # Show numerical answer eq2 = OldTex("=") value = DecimalNumber(dist.pmf(48), num_decimal_places=5) rhs = VGroup(eq2, value) rhs.arrange(RIGHT) rhs.match_y(eq) rhs.to_edge(RIGHT, buff=MED_SMALL_BUFF) self.play( FadeIn(value, LEFT), FadeIn(eq2), equation.next_to, eq2, LEFT, ) self.wait() # Show alternate values of k n = 50 for k in it.chain(range(47, 42, -1), range(43, 51), [49, 48]): new_prob_label = get_prob_review_label(k, n - k) new_prob_label.replace(prob_label) prob_label.become(new_prob_label) new_formula = get_binomial_formula(n, k, self.s) new_formula.replace(formula) formula.set_submobjects(new_formula) value.set_value(dist.pmf(k)) histogram.bars.set_fill(GREY_B) histogram.bars[k].set_fill(GREEN) arrow.next_to(histogram.bars[k], UP, SMALL_BUFF) new_row = get_checks_and_crosses((n - k) * [False] + k * [True]) new_row.replace(row) row.become(new_row) self.wait(0.5) # Name it as the Binomial distribution long_equation = VGroup(prob_label, eq, formula, eq2, value) bin_name = OldTexText("Binomial", " Distribution") bin_name.scale(1.5) bin_name.next_to(histogram, UP, MED_LARGE_BUFF) underline = Underline(bin_name[0]) underline.set_stroke(PINK, 2) nck_rect = SurroundingRectangle(formula[:4]) nck_rect.set_stroke(PINK, 2) self.play( long_equation.next_to, self.slots, DOWN, MED_LARGE_BUFF, long_equation.to_edge, RIGHT, FadeIn(bin_name, DOWN), ) self.wait() self.play(ShowCreationThenDestruction(underline)) self.wait() bools = [True] * 50 bools[random.randint(0, 49)] = False bools[random.randint(0, 49)] = False row.become(get_checks_and_crosses(bools).replace(row)) self.play(ShowIncreasingSubsets(row, run_time=4)) self.wait() # Show likelihood and posterior labels likelihood_label = OldTex( "P(", "\\text{data}", "\\,|\\,", "\\text{success rate}", ")", ) posterior_label = OldTex( "P(", "\\text{success rate}", "\\,|\\,", "\\text{data}", ")", ) for label in (likelihood_label, posterior_label): label.set_color_by_tex_to_color_map({ "data": GREEN, "success": YELLOW, }) likelihood_label.next_to( prob_label, DOWN, LARGE_BUFF, aligned_edge=LEFT ) right_arrow = Vector(RIGHT) right_arrow.next_to(likelihood_label, RIGHT) ra_label = OldTexText("But we want") ra_label.match_width(right_arrow) ra_label.next_to(right_arrow, UP, SMALL_BUFF) posterior_label.next_to(right_arrow, RIGHT) self.play( FadeIn(likelihood_label, UP), bin_name.set_height, 0.4, bin_name.set_y, histogram.axes.c2p(0, .25)[1] ) self.wait() self.play( GrowArrow(right_arrow), FadeIn(ra_label, 0.5 * LEFT), ) anims = [] for i, j in enumerate([0, 3, 2, 1, 4]): anims.append( TransformFromCopy( likelihood_label[i], posterior_label[j], path_arc=-45 * DEGREES, run_time=2, ) ) self.play(*anims) self.add(posterior_label) self.wait() # Prepare for new plot histogram.add(bin_name) always(arrow.next_to, histogram.bars[48], UP, SMALL_BUFF) self.play( FadeOut(likelihood_label), FadeOut(posterior_label), FadeOut(right_arrow), FadeOut(ra_label), FadeOut(row, UP), FadeOut(self.slots, UP), histogram.scale, 0.7, histogram.to_edge, UP, arrow.scale, 0.5, arrow.set_stroke, None, 4, long_equation.center, run_time=1.5, ) self.add(arrow) # x_labels = histogram.axes.x_labels # underline = Underline(x_labels) # underline.set_stroke(GREEN, 3) # self.play( # LaggedStartMap( # ApplyFunction, x_labels, # lambda mob: ( # lambda m: m.scale(1.5).set_color(GREEN), # mob, # ), # rate_func=there_and_back, # ), # ShowCreationThenDestruction(underline), # ) # num_checks = OldTex("\\# " + CMARK_TEX) # num_checks.set_color(GREEN) # num_checks.next_to( # x_labels, RIGHT, # MED_LARGE_BUFF, # aligned_edge=DOWN, # ) # self.play(Write(num_checks)) # self.wait() low_axes = get_beta_dist_axes(y_max=0.3, y_unit=0.1, label_y=False) low_axes.y_axis.set_height( 2, about_point=low_axes.c2p(0, 0), stretch=True, ) low_axes.to_edge(DOWN) low_axes.x_axis.numbers.set_color(YELLOW) y_label_copies = histogram.axes.y_labels.copy() y_label_copies.set_height(0.6 * low_axes.get_height()) y_label_copies.next_to(low_axes, LEFT, 0, aligned_edge=UP) y_label_copies.shift(SMALL_BUFF * UP) low_axes.y_axis.add(y_label_copies) low_axes.y_axis.set_opacity(0) # Show alternate values of s s_tracker = ValueTracker(self.s) s_tip = ArrowTip(start_angle=-90 * DEGREES) s_tip.set_color(YELLOW) s_tip.axis = low_axes.x_axis s_tip.st = s_tracker s_tip.add_updater( lambda m: m.next_to(m.axis.n2p(m.st.get_value()), UP, buff=0) ) pl_decimal = DecimalNumber(self.s) pl_decimal.set_color(YELLOW) pl_decimal.replace(prob_label[-2][2:]) prob_label[-2][2:].set_opacity(0) s_label = VGroup(prob_label[-2][:2], pl_decimal).copy() sl_rect = SurroundingRectangle(s_label) sl_rect.set_stroke(YELLOW, 2) self.add(pl_decimal) self.play( ShowCreation(sl_rect), Write(low_axes), ) self.play( s_label.next_to, s_tip, UP, 0.2, ORIGIN, s_label[1], ReplacementTransform(sl_rect, s_tip) ) always(s_label.next_to, s_tip, UP, 0.2, ORIGIN, s_label[1]) decimals = VGroup(pl_decimal, s_label[1], formula[5], formula[9]) decimals.s_tracker = s_tracker histogram.s_tracker = s_tracker histogram.n = n histogram.rhs_value = value def update_decimals(decs): for dec in decs: dec.set_value(decs.s_tracker.get_value()) def update_histogram(hist): new_dist = scipy.stats.binom(hist.n, hist.s_tracker.get_value()) new_data = np.array([ new_dist.pmf(x) for x in range(0, 51) ]) new_bars = hist.get_bars(new_data) new_bars.match_style(hist.bars) hist.bars.become(new_bars) hist.rhs_value.set_value(new_dist.pmf(48)) bar_copy = histogram.bars[48].copy() value.initial_config["num_decimal_places"] = 3 value.set_value(value.get_value()) bar_copy.next_to(value, RIGHT, aligned_edge=DOWN) bar_copy.add_updater( lambda m: m.set_height( max( histogram.bars[48].get_height() * 0.75, 1e-6, ), stretch=True, about_edge=DOWN, ) ) self.add(bar_copy) self.add(histogram) self.add(decimals) for s in [0.95, 0.5, 0.99, 0.9]: self.play( s_tracker.set_value, s, UpdateFromFunc(decimals, update_decimals), UpdateFromFunc(histogram, update_histogram), UpdateFromFunc(value, lambda m: m), UpdateFromFunc(s_label, lambda m: m.update), run_time=5, ) self.wait() # Plot def func(x): return scipy.stats.binom(50, x).pmf(48) + 1e-5 graph = low_axes.get_graph(func, step_size=0.05) graph.set_stroke(BLUE, 3) v_line = Line(DOWN, UP) v_line.axes = low_axes v_line.st = s_tracker v_line.graph = graph v_line.add_updater( lambda m: m.put_start_and_end_on( m.axes.c2p(m.st.get_value(), 0), m.axes.input_to_graph_point( m.st.get_value(), m.graph, ), ) ) v_line.set_stroke(GREEN, 2) dot = Dot() dot.line = v_line dot.set_height(0.05) dot.add_updater(lambda m: m.move_to(m.line.get_end())) self.play( ApplyMethod( histogram.bars[48].stretch, 2, 1, {"about_edge": DOWN}, rate_func=there_and_back, run_time=2, ), ) self.wait() self.play(low_axes.y_axis.set_opacity, 1) self.play( FadeIn(graph), FadeOut(s_label), FadeOut(s_tip), ) self.play( TransformFromCopy(histogram.bars[48], v_line), FadeIn(dot), ) self.add(histogram) decimals.remove(decimals[1]) for s in [0.9, 0.96, 1, 0.8, 0.96]: self.play( s_tracker.set_value, s, UpdateFromFunc(decimals, update_decimals), UpdateFromFunc(histogram, update_histogram), UpdateFromFunc(value, lambda m: m), run_time=5, ) self.wait() # Write formula clean_form = OldTex( "P(", "\\text{data}", "\\,|\\,", "{s}", ")", "=", "c", "\\cdot", "{s}", "^{\\#" + CMARK_TEX + "}", "(1 - ", "{s}", ")", "^{\\#" + XMARK_TEX + "}", tex_to_color_map={ "{s}": YELLOW, "\\#" + CMARK_TEX: GREEN, "\\#" + XMARK_TEX: RED, } ) clean_form.next_to(formula, DOWN, MED_LARGE_BUFF) clean_form.save_state() clean_form[:6].align_to(equation[1], RIGHT) clean_form[6].match_x(formula[2]) clean_form[7].set_opacity(0) clean_form[7].next_to(clean_form[6], RIGHT, SMALL_BUFF) clean_form[8:11].match_x(formula[4:8]) clean_form[11:].match_x(formula[8:]) clean_form.saved_state.move_to(clean_form, LEFT) fade_rects = VGroup( BackgroundRectangle(equation[:2]), BackgroundRectangle(formula), BackgroundRectangle(VGroup(eq2, bar_copy)), ) fade_rects.set_fill(BLACK, 0.8) fade_rects[1].set_fill(opacity=0) pre_c = formula[:4].copy() pre_s = formula[4:8].copy() pre_1ms = formula[8:].copy() self.play( FadeIn(fade_rects), FadeIn(clean_form[:6]) ) self.play(ShowCreationThenFadeAround(clean_form[3])) self.wait() for cf, pre in (clean_form[6], pre_c), (clean_form[8:11], pre_s), (clean_form[11:], pre_1ms): self.play( GrowFromPoint(cf, pre.get_center()), pre.move_to, cf, pre.scale, 0, ) self.remove(pre) self.wait() self.wait() self.play(Restore(clean_form)) # Show with 480 and 20 top_fade_rect = BackgroundRectangle(histogram) top_fade_rect.shift(SMALL_BUFF * DOWN) top_fade_rect.scale(1.5, about_edge=DOWN) top_fade_rect.set_fill(BLACK, 0) new_formula = get_binomial_formula(500, 480, 0.96) new_formula.move_to(formula) def func500(x): return scipy.stats.binom(500, x).pmf(480) + 1e-5 graph500 = low_axes.get_graph(func500, step_size=0.05) graph500.set_stroke(TEAL, 3) self.play( top_fade_rect.set_opacity, 1, fade_rects.set_opacity, 1, FadeIn(new_formula) ) self.clear() self.add(new_formula, clean_form, low_axes, graph, v_line, dot) self.add(low_axes.y_axis) self.play(TransformFromCopy(graph, graph500)) self.wait() y_axis = low_axes.y_axis y_axis.save_state() sf = 3 y_axis.stretch(sf, 1, about_point=low_axes.c2p(0, 0)) for label in y_label_copies: label.stretch(1 / sf, 1) v_line.suspend_updating() v_line.graph = graph500 self.play( Restore(y_axis, rate_func=reverse_smooth), graph.stretch, sf, 1, {"about_edge": DOWN}, graph500.stretch, sf, 1, {"about_edge": DOWN}, ) v_line.resume_updating() self.add(v_line, dot) sub_decimals = VGroup(new_formula[5], new_formula[9]) sub_decimals.s_tracker = s_tracker for s in [0.94, 0.98, 0.96]: self.play( s_tracker.set_value, s, UpdateFromFunc(sub_decimals, update_decimals), run_time=5, ) self.wait() def explain_n_choose_k(self, row, formula): row.add_updater(lambda m: m) brace = Brace(formula[:4], UP, buff=SMALL_BUFF) words = brace.get_text("``50 choose 48''") slots = self.slots = VGroup() for sym in row: line = Underline(sym) line.scale(0.9) slots.add(line) for slot in slots: slot.match_y(slots[0]) formula[1].counted = slots k_rect = SurroundingRectangle(formula[2]) k_rect.set_stroke(GREEN, 2) checks = VGroup() for sym in row: if sym.positive: checks.add(sym) self.play( GrowFromCenter(brace), FadeInFromDown(words), ) self.wait() self.play(FadeOut(words)) formula.save_state() self.play( ShowIncreasingSubsets(slots), UpdateFromFunc( formula[1], lambda m: m.set_value(len(m.counted)) ), run_time=2, ) formula.restore() self.add(formula) self.wait() self.play( LaggedStartMap( ApplyMethod, checks, lambda m: (m.shift, 0.3 * DOWN), rate_func=there_and_back, lag_ratio=0.05, ), ShowCreationThenFadeOut(k_rect), run_time=2, ) self.remove(checks) self.add(row) self.wait() # Example orderings row_target = VGroup() for sym in row: sym.generate_target() row_target.add(sym.target) row_target.sort(submob_func=lambda m: -int(m.positive)) row_target.arrange( RIGHT, buff=get_norm(row[0].get_right() - row[1].get_left()) ) row_target.move_to(row) self.play( LaggedStartMap( MoveToTarget, row, path_arc=30 * DEGREES, lag_ratio=0, ), ) self.wait() row.sort() self.play(Swap(*row[-3:-1])) self.add(row) self.wait() # All orderings nck_count = Integer(2) nck_count.next_to(brace, UP) nck_top = nck_count.get_top() always(nck_count.move_to, nck_top, UP) combs = list(it.combinations(range(50), 48)) bool_lists = [ [i in comb for i in range(50)] for comb in combs ] row.counter = nck_count row.bool_lists = bool_lists def update_row(r): i = r.counter.get_value() - 1 new_row = get_checks_and_crosses(r.bool_lists[i]) new_row.replace(r, dim_to_match=0) r.set_submobjects(new_row) row.add_updater(update_row) self.add(row) self.play( ChangeDecimalToValue(nck_count, choose(50, 48)), run_time=10, ) row.clear_updaters() self.wait() self.play( FadeOut(nck_count), FadeOut(brace), ) class StateIndependence(Scene): def construct(self): row = get_random_checks_and_crosses() row.to_edge(UP) # self.add(row) arrows = VGroup() for m1, m2 in zip(row, row[1:]): arrow = Arrow( m1.get_bottom() + 0.025 * DOWN, m2.get_bottom(), path_arc=145 * DEGREES, max_stroke_width_to_length_ratio=10, max_tip_length_to_length_ratio=0.5, ) arrow.tip.rotate(-10 * DEGREES) arrow.shift(SMALL_BUFF * DOWN) arrow.set_color(YELLOW) arrows.add(arrow) words = OldTexText("No influence") words.set_height(0.25) words.next_to(arrows[0], DOWN) self.play( ShowCreation(arrows[0]), FadeIn(words) ) for i in range(10): self.play( words.next_to, arrows[i + 1], DOWN, FadeOut(arrows[i]), ShowCreation(arrows[i + 1]) ) last_arrow = arrows[i + 1] self.play( FadeOut(words), FadeOut(last_arrow), ) class IllustrateBinomialSetupWithCoins(Scene): def construct(self): coins = [ get_coin("H"), get_coin("T"), ] coin_row = VGroup() for x in range(12): coin_row.add(random.choice(coins).copy()) coin_row.arrange(RIGHT) coin_row.to_edge(UP) first_coin = get_random_coin(shuffle_time=2, total_time=2) first_coin.move_to(coin_row[0]) brace = Brace(coin_row, UP) brace_label = brace.get_text("$N$ times") prob_label = OldTex( "P(\\# 00 = k)", tex_to_color_map={ "00": WHITE, "k": GREEN, } ) heads = get_coin("H") template = prob_label.get_part_by_tex("00") heads.replace(template) prob_label.replace_submobject( prob_label.index_of_part(template), heads, ) prob_label.set_height(1) prob_label.next_to(coin_row, DOWN, LARGE_BUFF) self.camera.frame.set_height(1.5 * FRAME_HEIGHT) self.add(first_coin) for x in range(4): self.wait() first_coin.suspend_updating() self.wait() first_coin.resume_updating() self.remove(first_coin) self.play( ShowIncreasingSubsets(coin_row, int_func=np.ceil), GrowFromPoint(brace, brace.get_left()), FadeIn(brace_label, 3 * LEFT) ) self.wait() self.play(FadeIn(prob_label, lag_ratio=0.1)) self.wait() class WriteLikelihoodFunction(Scene): def construct(self): formula = OldTex( "f({s}) = (\\text{const.})", "{s}^{\\#" + CMARK_TEX + "}", "(1 - {s})^{\\#" + XMARK_TEX, "}", tex_to_color_map={ "{s}": YELLOW, "\\#" + CMARK_TEX: GREEN, "\\#" + XMARK_TEX: RED, } ) formula.scale(2) rect1 = SurroundingRectangle(formula[3:6]) rect2 = SurroundingRectangle(formula[6:]) self.play(FadeInFromDown(formula)) self.wait() self.play(ShowCreationThenFadeOut(rect1)) self.wait() self.play(ShowCreationThenFadeOut(rect2)) self.wait() self.add(formula) self.embed() class Guess96Percent(Scene): def construct(self): randy = Randolph() randy.set_height(1) bubble = SpeechBubble(height=2, width=3) bubble.pin_to(randy) words = OldTexText("96$\\%$, right?") fix_percent(words[0][2]) bubble.add_content(words) arrow = Vector(2 * RIGHT + DOWN) arrow.next_to(randy, RIGHT) arrow.shift(2 * UP) self.play( FadeIn(randy), ShowCreation(bubble), Write(words), ) self.play(randy.change, "shruggie", randy.get_right() + RIGHT) self.play(ShowCreation(arrow)) for x in range(2): self.play(Blink(randy)) self.wait() self.embed() class LikelihoodGraphFor10of10(ShowBinomialFormula): CONFIG = { "histogram_config": { "x_label_freq": 2, "y_axis_numbers_to_show": range(25, 125, 25), "y_max": 1, "y_tick_freq": 0.25, "height": 2, "bar_colors": [BLUE], }, } def construct(self): # Add histogram dist = scipy.stats.binom(10, self.s) data = np.array([ dist.pmf(x) for x in range(0, 11) ]) histogram = self.get_histogram(data) histogram.bars.set_fill(GREY_C) histogram.bars[10].set_fill(GREEN) histogram.to_edge(UP) x_label = OldTex("\\#" + CMARK_TEX) x_label.set_color(GREEN) x_label.next_to(histogram.axes.x_axis.get_end(), RIGHT) histogram.add(x_label) self.add(histogram) arrow = Vector(DOWN) arrow.next_to(histogram.bars[10], UP, SMALL_BUFF) self.add(arrow) # Add formula prob_label = get_prob_review_label(10, 0) eq = OldTex("=") formula = get_binomial_formula(10, 10, self.s) eq2 = OldTex("=") value = DecimalNumber(dist.pmf(10), num_decimal_places=2) equation = VGroup(prob_label, eq, formula, eq2, value) equation.arrange(RIGHT) equation.next_to(histogram, DOWN, MED_LARGE_BUFF) # Add lower axes low_axes = get_beta_dist_axes(y_max=1, y_unit=0.25, label_y=False) low_axes.y_axis.set_height( 2, about_point=low_axes.c2p(0, 0), stretch=True, ) low_axes.to_edge(DOWN) low_axes.x_axis.numbers.set_color(YELLOW) y_label_copies = histogram.axes.y_labels.copy() y_label_copies.set_height(0.7 * low_axes.get_height()) y_label_copies.next_to(low_axes, LEFT, 0, aligned_edge=UP) y_label_copies.shift(SMALL_BUFF * UP) low_axes.y_axis.add(y_label_copies) # Add lower plot s_tracker = ValueTracker(self.s) def func(x): return x**10 graph = low_axes.get_graph(func, step_size=0.05) graph.set_stroke(BLUE, 3) v_line = Line(DOWN, UP) v_line.axes = low_axes v_line.st = s_tracker v_line.graph = graph v_line.add_updater( lambda m: m.put_start_and_end_on( m.axes.c2p(m.st.get_value(), 0), m.axes.input_to_graph_point( m.st.get_value(), m.graph, ), ) ) v_line.set_stroke(GREEN, 2) dot = Dot() dot.line = v_line dot.set_height(0.05) dot.add_updater(lambda m: m.move_to(m.line.get_end())) # Show simpler formula brace = Brace(formula, DOWN, buff=SMALL_BUFF) simpler_formula = OldTex("s", "^{10}") simpler_formula.set_color_by_tex("s", YELLOW) simpler_formula.set_color_by_tex("10", GREEN) simpler_formula.next_to(brace, DOWN) rects = VGroup( BackgroundRectangle(formula[:4]), BackgroundRectangle(formula[8:]), ) rects.set_opacity(0.75) self.wait() self.play(FadeIn(equation)) self.wait() self.play( FadeIn(rects), GrowFromCenter(brace), FadeIn(simpler_formula, UP) ) self.wait() # Show various values of s pl_decimal = DecimalNumber(self.s) pl_decimal.set_color(YELLOW) pl_decimal.replace(prob_label[-2][2:]) prob_label[-2][2:].set_opacity(0) decimals = VGroup(pl_decimal, formula[5], formula[9]) decimals.s_tracker = s_tracker histogram.s_tracker = s_tracker histogram.n = 10 histogram.rhs_value = value def update_decimals(decs): for dec in decs: dec.set_value(decs.s_tracker.get_value()) def update_histogram(hist): new_dist = scipy.stats.binom(hist.n, hist.s_tracker.get_value()) new_data = np.array([ new_dist.pmf(x) for x in range(0, 11) ]) new_bars = hist.get_bars(new_data) new_bars.match_style(hist.bars) hist.bars.become(new_bars) hist.rhs_value.set_value(new_dist.pmf(10)) self.add(histogram) self.add(decimals, rects) self.play( FadeIn(low_axes), ) self.play( ShowCreation(v_line), FadeIn(dot), ) self.add(graph, v_line, dot) self.play(ShowCreation(graph)) self.wait() always(arrow.next_to, histogram.bars[10], UP, SMALL_BUFF) for s in [0.8, 1]: self.play( s_tracker.set_value, s, UpdateFromFunc(decimals, update_decimals), UpdateFromFunc(histogram, update_histogram), UpdateFromFunc(value, lambda m: m), run_time=5, ) self.wait() class StateNeedForBayesRule(TeacherStudentsScene): def construct(self): axes = get_beta_dist_axes(y_max=1, y_unit=0.25, label_y=False) axes.y_axis.set_height( 2, about_point=axes.c2p(0, 0), stretch=True, ) axes.set_width(5) graph = axes.get_graph(lambda x: x**10) graph.set_stroke(BLUE, 3) alt_graph = graph.copy() alt_graph.add_line_to(axes.c2p(1, 0)) alt_graph.add_line_to(axes.c2p(0, 0)) alt_graph.set_stroke(width=0) alt_graph.set_fill(BLUE_E, 1) plot = VGroup(axes, alt_graph, graph) student0, student1, student2 = self.students plot.next_to(student2.get_corner(UL), UP, MED_LARGE_BUFF) plot.shift(LEFT) v_lines = VGroup( DashedLine(axes.c2p(0.8, 0), axes.c2p(0.8, 1)), DashedLine(axes.c2p(1, 0), axes.c2p(1, 1)), ) v_lines.set_stroke(YELLOW, 2) self.play( LaggedStart( ApplyMethod(student0.change, "pondering", plot), ApplyMethod(student1.change, "pondering", plot), ApplyMethod(student2.change, "raise_left_hand", plot), ), FadeIn(plot, DOWN), run_time=1.5 ) self.play(*map(ShowCreation, v_lines)) self.play( self.teacher.change, "tease", *[ ApplyMethod( v_line.move_to, axes.c2p(0.9, 0), DOWN, ) for v_line in v_lines ] ) self.play_student_changes( "thinking", "thinking", "pondering", look_at=v_lines, ) self.wait(2) self.teacher_says( "But first...", added_anims=[ FadeOut(plot, LEFT), FadeOut(v_lines, LEFT), self.change_students( "erm", "erm", "erm", look_at=self.teacher.eyes, ) ] ) self.wait(5) class Part1EndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "1stViewMaths", "Adam Dřínek", "Aidan Shenkman", "Alan Stein", "Alex Mijalis", "Alexis Olson", "Ali Yahya", "Andrew Busey", "Andrew Cary", "Andrew R. Whalley", "Aravind C V", "Arjun Chakroborty", "Arthur Zey", "Ashwin Siddarth", "Austin Goodman", "Avi Finkel", "Awoo", "Axel Ericsson", "Ayan Doss", "AZsorcerer", "Barry Fam", "Bernd Sing", "Boris Veselinovich", "Bradley Pirtle", "Brandon Huang", "Brian Staroselsky", "Britt Selvitelle", "Britton Finley", "Burt Humburg", "Calvin Lin", "Charles Southerland", "Charlie N", "Chenna Kautilya", "Chris Connett", "Christian Kaiser", "cinterloper", "Clark Gaebel", "Colwyn Fritze-Moor", "Cooper Jones", "Corey Ogburn", "D. Sivakumar", "Dan Herbatschek", "Daniel Herrera C", "Dave B", "Dave Kester", "dave nicponski", "David B. Hill", "David Clark", "David Gow", "Delton Ding", "Dominik Wagner", "Douglas Cantrell", "emptymachine", "Eric Younge", "Eryq Ouithaqueue", "Farzaneh Sarafraz", "Federico Lebron", "Frank R. Brown, Jr.", "Giovanni Filippi", "Hal Hildebrand", "Hitoshi Yamauchi", "Ivan Sorokin", "Jacob Baxter", "Jacob Harmon", "Jacob Hartmann", "Jacob Magnuson", "Jake Vartuli - Schonberg", "Jalex Stark", "Jameel Syed", "Jason Hise", "Jayne Gabriele", "Jean-Manuel Izaret", "Jeff Linse", "Jeff Straathof", "Jimmy Yang", "John C. Vesey", "John Haley", "John Le", "John V Wertheim", "Jonathan Heckerman", "Jonathan Wilson", "Joseph John Cox", "Joseph Kelly", "Josh Kinnear", "Joshua Claeys", "Juan Benet", "Kai-Siang Ang", "Kanan Gill", "Karl Niu", "Kartik Cating-Subramanian", "Kaustuv DeBiswas", "Killian McGuinness", "Kros Dai", "L0j1k", "LAI Oscar", "Lambda GPU Workstations", "Lee Redden", "Linh Tran", "Luc Ritchie", "Ludwig Schubert", "Lukas Biewald", "Magister Mugit", "Magnus Dahlström", "Manoj Rewatkar - RITEK SOLUTIONS", "Mark B Bahu", "Mark Heising", "Mark Mann", "Martin Price", "Mathias Jansson", "Matt Godbolt", "Matt Langford", "Matt Roveto", "Matt Russell", "Matteo Delabre", "Matthew Bouchard", "Matthew Cocke", "Mia Parent", "Michael Hardel", "Michael W White", "Mirik Gogri", "Mustafa Mahdi", "Márton Vaitkus", "Nicholas Cahill", "Nikita Lesnikov", "Oleg Leonov", "Oliver Steele", "Omar Zrien", "Owen Campbell-Moore", "Patrick Lucas", "Pavel Dubov", "Peter Ehrnstrom", "Peter Mcinerney", "Pierre Lancien", "Quantopian", "Randy C. Will", "rehmi post", "Rex Godby", "Ripta Pasay", "Rish Kundalia", "Roman Sergeychik", "Roobie", "Ryan Atallah", "Samuel Judge", "SansWord Huang", "Scott Gray", "Scott Walter, Ph.D.", "soekul", "Solara570", "Steve Huynh", "Steve Sperandeo", "Steven Braun", "Steven Siddals", "Stevie Metke", "supershabam", "Suteerth Vishnu", "Suthen Thomas", "Tal Einav", "Taras Bobrovytsky", "Tauba Auerbach", "Ted Suzman", "Thomas J Sargent", "Thomas Tarler", "Tianyu Ge", "Tihan Seale", "Tyler VanValkenburg", "Vassili Philippov", "Veritasium", "Vignesh Ganapathi Subramanian", "Vinicius Reis", "Xuanji Li", "Yana Chernobilsky", "Yavor Ivanov", "YinYangBalance.Asia", "Yu Jun", "Yurii Monastyrshyn", ], }
from manim_imports_ext import * from _2020.beta.helpers import * from _2020.beta.beta1 import * from _2019.hyperdarts import Dartboard import scipy.stats OUTPUT_DIRECTORY = "bayes/beta2" class WeightedCoin(Scene): def construct(self): # Coin grid bools = 50 * [True] + 50 * [False] random.shuffle(bools) grid = get_coin_grid(bools) sorted_grid = VGroup(*grid) sorted_grid.submobjects.sort(key=lambda m: m.symbol) # Prob label p_label = get_prob_coin_label() p_label.set_height(0.7) p_label.to_edge(UP) rhs = p_label[-1] rhs_box = SurroundingRectangle(rhs, color=RED) rhs_label = OldTexText("Not necessarily") rhs_label.next_to(rhs_box, DOWN, LARGE_BUFF) rhs_label.to_edge(RIGHT) rhs_label.match_color(rhs_box) rhs_arrow = Arrow( rhs_label.get_top(), rhs_box.get_right(), buff=SMALL_BUFF, path_arc=60 * DEGREES, color=rhs_box.get_color() ) # Introduce coin self.play(FadeIn( grid, run_time=2, rate_func=linear, lag_ratio=3 / len(grid), )) self.wait() self.play( grid.set_height, 5, grid.to_edge, DOWN, FadeInFromDown(p_label) ) for coin in grid: coin.generate_target() sorted_coins = list(grid) sorted_coins.sort(key=lambda m: m.symbol) for c1, c2 in zip(sorted_coins, grid): c1.target.move_to(c2) self.play( FadeIn(rhs_label, lag_ratio=0.1), ShowCreation(rhs_arrow), ShowCreation(rhs_box), LaggedStartMap( MoveToTarget, grid, path_arc=30 * DEGREES, lag_ratio=0.01, ), ) # Alternate weightings old_grid = VGroup(*sorted_coins) rhs_junk_on_screen = True for value in [0.2, 0.9, 0.0, 0.31]: n = int(100 * value) new_grid = get_coin_grid([True] * n + [False] * (100 - n)) new_grid.replace(grid) anims = [] if rhs_junk_on_screen: anims += [ FadeOut(rhs_box), FadeOut(rhs_label), FadeOut(rhs_arrow), ] rhs_junk_on_screen = False self.wait() self.play( FadeOut( old_grid, 0.1 * DOWN, lag_ratio=0.01, run_time=1.5 ), FadeIn(new_grid, lag_ratio=0.01, run_time=1.5), ChangeDecimalToValue(rhs, value), *anims, ) old_grid = new_grid long_rhs = DecimalNumber( 0.31415926, num_decimal_places=8, show_ellipsis=True, ) long_rhs.match_height(rhs) long_rhs.move_to(rhs, DL) self.play(ShowIncreasingSubsets(long_rhs, rate_func=linear)) self.wait() # You just don't know box = get_q_box(rhs) self.remove(rhs) self.play( FadeOut(old_grid, lag_ratio=0.1), FadeOut(long_rhs, 0.1 * RIGHT, lag_ratio=0.1), Write(box), ) p_label.add(box) self.wait() # 7/10 heads bools = [True] * 7 + [False] * 3 random.shuffle(bools) coins = VGroup(*[ get_coin("H" if heads else "T") for heads in bools ]) coins.arrange(RIGHT) coins.set_height(0.7) coins.next_to(p_label, DOWN, buff=LARGE_BUFF) heads_arrows = VGroup(*[ Vector( 0.5 * UP, max_stroke_width_to_length_ratio=15, max_tip_length_to_length_ratio=0.4, ).next_to(coin, DOWN) for coin in coins if coin.symbol == "H" ]) numbers = VGroup(*[ Integer(i + 1).next_to(arrow, DOWN, SMALL_BUFF) for i, arrow in enumerate(heads_arrows) ]) for coin in coins: coin.save_state() coin.stretch(0, 0) coin.set_opacity(0) self.play(LaggedStartMap(Restore, coins), run_time=1) self.play( ShowIncreasingSubsets(heads_arrows), ShowIncreasingSubsets(numbers), rate_func=linear, ) self.wait() # Plot axes = scaled_pdf_axes() axes.to_edge(DOWN, buff=MED_SMALL_BUFF) axes.y_axis.numbers.set_opacity(0) axes.y_axis_label.set_opacity(0) x_axis_label = p_label[:4].copy() x_axis_label.set_height(0.4) x_axis_label.next_to(axes.c2p(1, 0), UR, buff=SMALL_BUFF) axes.x_axis.add(x_axis_label) n_heads = 7 n_tails = 3 graph = get_beta_graph(axes, n_heads, n_tails) dist = scipy.stats.beta(n_heads + 1, n_tails + 1) true_graph = axes.get_graph(dist.pdf) v_line = Line( axes.c2p(0.7, 0), axes.input_to_graph_point(0.7, true_graph), ) v_line.set_stroke(YELLOW, 4) region = get_region_under_curve(axes, true_graph, 0.6, 0.8) region.set_fill(GREY, 0.85) region.set_stroke(YELLOW, 1) eq_label = VGroup( p_label[:4].copy(), OldTex("= 0.7"), ) for mob in eq_label: mob.set_height(0.4) eq_label.arrange(RIGHT, buff=SMALL_BUFF) pp_label = VGroup( OldTex("P("), eq_label, OldTex(")"), ) for mob in pp_label[::2]: mob.set_height(0.7) mob.set_color(YELLOW) pp_label.arrange(RIGHT, buff=SMALL_BUFF) pp_label.move_to(axes.c2p(0.3, 3)) self.play( FadeOut(heads_arrows), FadeOut(numbers), Write(axes), DrawBorderThenFill(graph), ) self.play( FadeIn(pp_label[::2]), ShowCreation(v_line), ) self.wait() self.play(TransformFromCopy(p_label[:4], eq_label[0])) self.play( GrowFromPoint(eq_label[1], v_line.get_center()) ) self.wait() # Look confused randy = Randolph() randy.set_height(1.5) randy.next_to(axes.c2p(0, 0), UR, MED_LARGE_BUFF) self.play(FadeIn(randy)) self.play(randy.change, "confused", pp_label.get_top()) self.play(Blink(randy)) self.wait() self.play(FadeOut(randy)) # Remind what the title is title = OldTexText( "Probabilities", "of", "Probabilities" ) title.arrange(DOWN, aligned_edge=LEFT) title.next_to(axes.c2p(0, 0), UR, buff=MED_LARGE_BUFF) title.align_to(pp_label, LEFT) self.play(ShowIncreasingSubsets(title, rate_func=linear)) self.wait() self.play(FadeOut(title)) # Continuous values v_line.tracker = ValueTracker(0.7) v_line.axes = axes v_line.graph = true_graph v_line.add_updater( lambda m: m.put_start_and_end_on( m.axes.c2p(m.tracker.get_value(), 0), m.axes.input_to_graph_point(m.tracker.get_value(), m.graph), ) ) for value in [0.4, 0.9, 0.7]: self.play( v_line.tracker.set_value, value, run_time=3, ) # Label h brace = Brace(rhs_box, DOWN, buff=SMALL_BUFF) h_label = OldTex("h", buff=SMALL_BUFF) h_label.set_color(YELLOW) h_label.next_to(brace, DOWN) self.play( LaggedStartMap(FadeOutAndShift, coins, lambda m: (m, DOWN)), GrowFromCenter(brace), Write(h_label), ) self.wait() # End self.embed() class Eq70(Scene): def construct(self): label = OldTex("=", "70", "\\%", "?") fix_percent(label.get_part_by_tex("\\%")[0]) self.play(FadeIn(label)) self.wait() class ShowInfiniteContinuum(Scene): def construct(self): # Axes axes = scaled_pdf_axes() axes.to_edge(DOWN, buff=MED_SMALL_BUFF) axes.y_axis.numbers.set_opacity(0) axes.y_axis_label.set_opacity(0) self.add(axes) # Label p_label = get_prob_coin_label() p_label.set_height(0.7) p_label.to_edge(UP) box = get_q_box(p_label[-1]) p_label.add(box) brace = Brace(box, DOWN, buff=SMALL_BUFF) h_label = OldTex("h") h_label.next_to(brace, DOWN) h_label.set_color(YELLOW) eq = OldTex("=") eq.next_to(h_label, RIGHT) value = DecimalNumber(0, num_decimal_places=4) value.match_height(h_label) value.next_to(eq, RIGHT) value.set_color(YELLOW) self.add(p_label) self.add(brace) self.add(h_label) # Moving h h_part = h_label.copy() x_line = Line(axes.c2p(0, 0), axes.c2p(1, 0)) x_line.set_stroke(YELLOW, 3) self.play( h_part.next_to, x_line.get_start(), UR, SMALL_BUFF, Write(eq), FadeInFromPoint(value, h_part.get_center()), ) # Scan continuum h_part.tracked = x_line value.tracked = x_line value.x_axis = axes.x_axis self.play( ShowCreation(x_line), UpdateFromFunc( h_part, lambda m: m.next_to(m.tracked.get_end(), UR, SMALL_BUFF) ), UpdateFromFunc( value, lambda m: m.set_value( m.x_axis.p2n(m.tracked.get_end()) ) ), run_time=3, ) self.wait() self.play( FadeOut(eq), FadeOut(value), ) # Arrows arrows = VGroup() arrow_template = Vector(DOWN) def get_arrow(s, denom, arrow_template=arrow_template, axes=axes): arrow = arrow_template.copy() arrow.set_height(4 / denom) arrow.move_to(axes.c2p(s, 0), DOWN) arrow.set_color(interpolate_color( GREY_A, GREY_C, random.random() )) return arrow for k in range(2, 50): for n in range(1, k): if np.gcd(n, k) != 1: continue s = n / k arrows.add(get_arrow(s, k)) for k in range(50, 1000): arrows.add(get_arrow(1 / k, k)) arrows.add(get_arrow(1 - 1 / k, k)) kw = { "lag_ratio": 0.05, "run_time": 5, "rate_func": lambda t: t**5, } arrows.save_state() for arrow in arrows: arrow.stretch(0, 0) arrow.set_stroke(width=0) arrow.set_opacity(0) self.play(Restore(arrows, **kw)) self.play(LaggedStartMap( ApplyMethod, arrows, lambda m: (m.scale, 0, {"about_edge": DOWN}), lag_ratio=10 / len(arrows), rate_func=smooth, run_time=3, )) self.remove(arrows) self.wait() class TitleCard(Scene): def construct(self): text = OldTexText("A beginner's guide to\\\\probability density") text.scale(2) text.to_edge(UP, buff=1.5) subtext = OldTexText("Probabilities of probabilities, ", "part 2") subtext.set_width(FRAME_WIDTH - 3) subtext[0].set_color(BLUE) subtext.next_to(text, DOWN, LARGE_BUFF) self.add(text) self.play(FadeIn(subtext, lag_ratio=0.1, run_time=2)) self.wait(2) class NamePdfs(Scene): def construct(self): label = OldTexText("Probability density\\\\function") self.play(Write(label)) self.wait() class LabelH(Scene): def construct(self): p_label = get_prob_coin_label() p_label.scale(1.5) brace = Brace(p_label, DOWN) h = OldTex("h") h.scale(2) h.next_to(brace, DOWN) self.add(p_label) self.play(ShowCreationThenFadeAround(p_label)) self.play( GrowFromCenter(brace), FadeIn(h, UP), ) self.wait() class DrawUnderline(Scene): def construct(self): line = Line(2 * LEFT, 2 * RIGHT) line.set_stroke(PINK, 5) self.play(ShowCreation(line)) self.wait() line.reverse_points() self.play(Uncreate(line)) class TryAssigningProbabilitiesToSpecificValues(Scene): def construct(self): # To get "P(s = .7000001) = ???" type labels def get_p_label(value): result = OldTex( # "P(", "{s}", "=", value, "\\%", ")", "P(", "{h}", "=", value, ")", ) # fix_percent(result.get_part_by_tex("\\%")[0]) result.set_color_by_tex("{h}", YELLOW) return result labels = VGroup( get_p_label("0.70000000"), get_p_label("0.70000001"), get_p_label("0.70314159"), get_p_label("0.70271828"), get_p_label("0.70466920"), get_p_label("0.70161803"), ) labels.arrange(DOWN, buff=0.35, aligned_edge=LEFT) labels.set_height(4.5) labels.to_edge(DOWN, buff=LARGE_BUFF) q_marks = VGroup() gt_zero = VGroup() eq_zero = VGroup() for label in labels: qm = OldTex("=", "\\,???") qm.next_to(label, RIGHT) qm[1].set_color(TEAL) q_marks.add(qm) gt = OldTex("> 0") gt.next_to(label, RIGHT) gt_zero.add(gt) eqz = OldTex("= 0") eqz.next_to(label, RIGHT) eq_zero.add(eqz) v_dots = OldTex("\\vdots") v_dots.next_to(q_marks[-1][0], DOWN, MED_LARGE_BUFF) # Animations self.play(FadeInFromDown(labels[0])) self.play(FadeIn(q_marks[0], LEFT)) self.wait() self.play(*[ TransformFromCopy(m1, m2) for m1, m2 in [ (q_marks[0], q_marks[1]), (labels[0][:3], labels[1][:3]), (labels[0][-1], labels[1][-1]), ] ]) self.play(ShowIncreasingSubsets( labels[1][3], run_time=3, int_func=np.ceil, rate_func=linear, )) self.add(labels[1]) self.wait() self.play( LaggedStartMap( FadeInFrom, labels[2:], lambda m: (m, UP), ), LaggedStartMap( FadeInFrom, q_marks[2:], lambda m: (m, UP), ), Write(v_dots, rate_func=squish_rate_func(smooth, 0.5, 1)) ) self.add(labels, q_marks) self.wait() self.play( ReplacementTransform(q_marks, gt_zero, lag_ratio=0.05), run_time=2, ) self.wait() # Show sum group = VGroup(labels, gt_zero, v_dots) sum_label = OldTex( "\\sum_{0 \\le {h} \\le 1}", "P(", "{h}", ")", "=", tex_to_color_map={"{h}": YELLOW}, ) # sum_label.set_color_by_tex("{s}", YELLOW) sum_label[0].set_color(WHITE) sum_label.scale(1.75) sum_label.next_to(ORIGIN, RIGHT, buff=1) sum_label.shift(LEFT) morty = Mortimer() morty.set_height(2) morty.to_corner(DR) self.play(group.to_corner, DL) self.play( Write(sum_label), VFadeIn(morty), morty.change, "confused", sum_label, ) infty = OldTex("\\infty") zero = OldTex("0") for mob in [infty, zero]: mob.scale(2) mob.next_to(sum_label[-1], RIGHT) zero.set_color(RED) zero.shift(SMALL_BUFF * RIGHT) self.play( Write(infty), morty.change, "horrified", infty, ) self.play(Blink(morty)) self.wait() # If equal to zero eq_zero.move_to(gt_zero) eq_zero.set_color(RED) self.play( ReplacementTransform( gt_zero, eq_zero, lag_ratio=0.05, run_time=2, path_arc=30 * DEGREES, ), morty.change, "pondering", eq_zero, ) self.wait() self.play( FadeIn(zero, DOWN), FadeOut(infty, UP), morty.change, "sad", zero ) self.play(Blink(morty)) self.wait() class WanderingArrow(Scene): def construct(self): arrow = Vector(0.8 * DOWN) arrow.move_to(4 * LEFT, DOWN) for u in [1, -1, 1, -1, 1]: self.play( arrow.shift, u * 8 * RIGHT, run_time=3 ) class ProbabilityToContinuousValuesSupplement(Scene): def construct(self): nl = UnitInterval() nl.set_width(10) nl.add_numbers( *np.arange(0, 1.1, 0.1), buff=0.3, ) nl.to_edge(LEFT) self.add(nl) def f(x): return -100 * (x - 0.6) * (x - 0.8) values = np.linspace(0.65, 0.75, 100) lines = VGroup() for x, color in zip(values, it.cycle([BLUE_E, BLUE_C])): line = Line(ORIGIN, UP) line.set_height(f(x)) line.set_stroke(color, 1) line.move_to(nl.n2p(x), DOWN) lines.add(line) self.play(ShowCreation(lines, lag_ratio=0.9, run_time=5)) lines_row = lines.copy() lines_row.generate_target() for lt in lines_row.target: lt.rotate(90 * DEGREES) lines_row.target.arrange(RIGHT, buff=0) lines_row.target.set_stroke(width=4) lines_row.target.next_to(nl, UP, LARGE_BUFF) lines_row.target.align_to(nl.n2p(0), LEFT) self.play( MoveToTarget( lines_row, lag_ratio=0.1, rate_func=rush_into, run_time=4, ) ) self.wait() self.play( lines.set_height, 0.01, {"about_edge": DOWN, "stretch": True}, ApplyMethod( lines_row.set_width, 0.01, {"about_edge": LEFT}, rate_func=rush_into, ), run_time=6, ) self.wait() class CarFactoryNumbers(Scene): def construct(self): # Test words denom_words = OldTexText( "in a test of 100 cars", tex_to_color_map={"100": BLUE}, ) denom_words.to_corner(UR) numer_words = OldTexText( "2 defects found", tex_to_color_map={"2": RED} ) numer_words.move_to(denom_words, LEFT) self.play(Write(denom_words, run_time=1)) self.wait() self.play( denom_words.next_to, numer_words, DOWN, {"aligned_edge": LEFT}, FadeIn(numer_words), ) self.wait() # Question words question = VGroup( OldTexText("What can you say"), OldTex( "\\text{about } P(\\text{defect})?", tex_to_color_map={"\\text{defect}": RED} ) ) question.arrange(DOWN, aligned_edge=LEFT) question.next_to(denom_words, DOWN, buff=1.5, aligned_edge=LEFT) self.play(FadeIn(question)) self.wait() class TeacherHoldingValue(TeacherStudentsScene): def construct(self): self.play(self.teacher.change, "raise_right_hand", self.screen) self.play_all_student_changes( "pondering", look_at=self.screen, ) self.wait(8) class ShowLimitToPdf(Scene): def construct(self): # Init axes = self.get_axes() alpha = 4 beta = 2 dist = scipy.stats.beta(alpha, beta) bars = self.get_bars(axes, dist, 0.05) axis_prob_label = OldTexText("Probability") axis_prob_label.next_to(axes.y_axis, UP) axis_prob_label.to_edge(LEFT) self.add(axes) self.add(axis_prob_label) # From individual to ranges kw = {"tex_to_color_map": {"h": YELLOW}} eq_label = OldTex("P(h = 0.8)", **kw) ineq_label = OldTex("P(0.8 < h < 0.85)", **kw) arrows = VGroup(Vector(DOWN), Vector(DOWN)) for arrow, x in zip(arrows, [0.8, 0.85]): arrow.move_to(axes.c2p(x, 0), DOWN) brace = Brace( Line(arrows[0].get_start(), arrows[1].get_start()), UP, buff=SMALL_BUFF ) eq_label.next_to(arrows[0], UP) ineq_label.next_to(brace, UP) self.play( FadeIn(eq_label, 0.2 * DOWN), GrowArrow(arrows[0]), ) self.wait() vect = eq_label.get_center() - ineq_label.get_center() self.play( FadeOut(eq_label, -vect), FadeIn(ineq_label, vect), TransformFromCopy(*arrows), GrowFromPoint(brace, brace.get_left()), ) self.wait() # Bars arrow = arrows[0] arrow.generate_target() arrow.target.next_to(bars[16], UP, SMALL_BUFF) highlighted_bar_color = RED_E bars[16].set_color(highlighted_bar_color) for bar in bars: bar.save_state() bar.stretch(0, 1, about_edge=DOWN) kw = { "run_time": 2, "rate_func": squish_rate_func(smooth, 0.3, 0.9), } self.play( MoveToTarget(arrow, **kw), ApplyMethod(ineq_label.next_to, arrows[0].target, UP, **kw), FadeOut(arrows[1]), FadeOut(brace), LaggedStartMap(Restore, bars, run_time=2, lag_ratio=0.025), ) self.wait() # Focus on area, not height lines = VGroup() new_bars = VGroup() for bar in bars: line = Line( bar.get_corner(DL), bar.get_corner(DR), ) line.set_stroke(YELLOW, 0) line.generate_target() line.target.set_stroke(YELLOW, 3) line.target.move_to(bar.get_top()) lines.add(line) new_bar = bar.copy() new_bar.match_style(line) new_bar.set_fill(YELLOW, 0.5) new_bar.generate_target() new_bar.stretch(0, 1, about_edge=UP) new_bars.add(new_bar) prob_label = OldTexText( "Height", "$\\rightarrow$", "Probability", ) prob_label.space_out_submobjects(1.1) prob_label.next_to(bars[10], UL, LARGE_BUFF) height_word = prob_label[0] height_cross = Cross(height_word) area_word = OldTexText("Area") area_word.move_to(height_word, UR) area_word.set_color(YELLOW) self.play( LaggedStartMap( MoveToTarget, lines, lag_ratio=0.01, ), FadeInFromDown(prob_label), ) self.add(height_word) self.play( ShowCreation(height_cross), FadeOut(axis_prob_label, LEFT) ) self.wait() self.play( FadeOut(height_word, UP), FadeOut(height_cross, UP), FadeInFromDown(area_word), ) self.play( FadeOut(lines), LaggedStartMap( MoveToTarget, new_bars, lag_ratio=0.01, ) ) self.play( FadeOut(new_bars), area_word.set_color, BLUE, ) prob_label = VGroup(area_word, *prob_label[1:]) self.add(prob_label) # Ask about where values come from randy = Randolph(height=1) randy.next_to(prob_label, UP, aligned_edge=LEFT) bubble = SpeechBubble( height=2, width=4, ) bubble.move_to(randy.get_corner(UR), DL) bubble.write("Where do these\\\\probabilities come from?") self.play( FadeIn(randy), ShowCreation(bubble), ) self.play( randy.change, "confused", FadeIn(bubble.content, lag_ratio=0.1) ) self.play(Blink(randy)) bars.generate_target() bars.save_state() bars.target.arrange(RIGHT, buff=SMALL_BUFF, aligned_edge=DOWN) bars.target.next_to(bars.get_bottom(), UP) self.play(MoveToTarget(bars)) self.play(LaggedStartMap(Indicate, bars, scale_factor=1.05), run_time=1) self.play(Restore(bars)) self.play(Blink(randy)) self.play( FadeOut(randy), FadeOut(bubble), FadeOut(bubble.content), ) # Refine last_ineq_label = ineq_label last_bars = bars all_ineq_labels = VGroup(ineq_label) for step_size in [0.025, 0.01, 0.005, 0.001]: new_bars = self.get_bars(axes, dist, step_size) new_ineq_label = OldTex( "P(0.8 < h < {:.3})".format(0.8 + step_size), tex_to_color_map={"h": YELLOW}, ) if step_size <= 0.005: new_bars.set_stroke(width=0) arrow.generate_target() bar = new_bars[int(0.8 * len(new_bars))] bar.set_color(highlighted_bar_color) arrow.target.next_to(bar, UP, SMALL_BUFF) new_ineq_label.next_to(arrow.target, UP) vect = new_ineq_label.get_center() - last_ineq_label.get_center() self.wait() self.play( ReplacementTransform( last_bars, new_bars, lag_ratio=step_size, ), MoveToTarget(arrow), FadeOut(last_ineq_label, vect), FadeIn(new_ineq_label, -vect), run_time=2, ) last_ineq_label = new_ineq_label last_bars = new_bars all_ineq_labels.add(new_ineq_label) # Show continuous graph graph = get_beta_graph(axes, alpha - 1, beta - 1) graph_curve = axes.get_graph(dist.pdf) graph_curve.set_stroke([YELLOW, GREEN]) limit_words = OldTexText("In the limit...") limit_words.next_to( axes.input_to_graph_point(0.75, graph_curve), UP, MED_LARGE_BUFF, ) self.play( FadeIn(graph), FadeOut(last_ineq_label), FadeOut(arrow), FadeOut(last_bars), ) self.play( ShowCreation(graph_curve), Write(limit_words, run_time=1) ) self.play(FadeOut(graph_curve)) self.wait() # Show individual probabilities goes to zero all_ineq_labels.arrange(DOWN, aligned_edge=LEFT) all_ineq_labels.move_to(prob_label, LEFT) all_ineq_labels.to_edge(UP) prob_label.generate_target() prob_label.target.next_to( all_ineq_labels, DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT ) rhss = VGroup() step_sizes = [0.05, 0.025, 0.01, 0.005, 0.001] for label, step in zip(all_ineq_labels, step_sizes): eq = OldTex("=") decimal = DecimalNumber( dist.cdf(0.8 + step) - dist.cdf(0.8), num_decimal_places=3, ) eq.next_to(label, RIGHT) decimal.next_to(eq, RIGHT) decimal.set_stroke(BLACK, 3, background=True) rhss.add(VGroup(eq, decimal)) for rhs in rhss: rhs.align_to(rhss[1], LEFT) VGroup(all_ineq_labels, rhss).set_height(3, about_edge=UL) arrow = Arrow(rhss.get_top(), rhss.get_bottom(), buff=0) arrow.next_to(rhss, RIGHT) arrow.set_color(YELLOW) to_zero_words = OldTexText("Individual probabilites\\\\", "go to zero") to_zero_words[1].align_to(to_zero_words[0], LEFT) to_zero_words.next_to(arrow, RIGHT, aligned_edge=UP) self.play( LaggedStartMap( FadeInFrom, all_ineq_labels, lambda m: (m, UP), ), LaggedStartMap( FadeInFrom, rhss, lambda m: (m, UP), ), MoveToTarget(prob_label) ) self.play( GrowArrow(arrow), FadeIn(to_zero_words), ) self.play( LaggedStartMap( Indicate, rhss, scale_factor=1.05, ) ) self.wait(2) # What if it was heights bars.restore() height_word.move_to(area_word, RIGHT) height_word.set_color(PINK) step = 0.05 new_y_numbers = VGroup(*[ DecimalNumber(x) for x in np.arange(step, 5 * step, step) ]) for n1, n2 in zip(axes.y_axis.numbers, new_y_numbers): n2.match_height(n1) n2.add_background_rectangle( opacity=1, buff=SMALL_BUFF, ) n2.move_to(n1, RIGHT) self.play( FadeOut(limit_words), FadeOut(graph), FadeIn(bars), FadeOut(area_word, UP), FadeIn(height_word, DOWN), FadeIn(new_y_numbers, 0.5 * RIGHT), ) # Height refine rect = SurroundingRectangle(rhss[0][1]) rect.set_stroke(RED, 3) self.play(FadeIn(rect)) last_bars = bars for step_size, rhs in zip(step_sizes[1:], rhss[1:]): new_bars = self.get_bars(axes, dist, step_size) bar = new_bars[int(0.8 * len(new_bars))] bar.set_color(highlighted_bar_color) new_bars.stretch( step_size / 0.05, 1, about_edge=DOWN, ) if step_size <= 0.05: new_bars.set_stroke(width=0) self.remove(last_bars) self.play( TransformFromCopy(last_bars, new_bars, lag_ratio=step_size), rect.move_to, rhs[1], ) last_bars = new_bars self.play( FadeOut(last_bars), FadeOutAndShiftDown(rect), ) self.wait() # Back to area self.play( FadeIn(graph), FadeIn(area_word, 0.5 * DOWN), FadeOut(height_word, 0.5 * UP), FadeOut(new_y_numbers, lag_ratio=0.2), ) self.play( arrow.scale, 0, {"about_edge": DOWN}, FadeOut(to_zero_words, DOWN), LaggedStartMap(FadeOutAndShiftDown, all_ineq_labels), LaggedStartMap(FadeOutAndShiftDown, rhss), ) self.wait() # Ask about y_axis units arrow = Arrow( axes.y_axis.get_top() + 3 * RIGHT, axes.y_axis.get_top(), path_arc=90 * DEGREES, ) question = OldTexText("What are the\\\\units here?") question.next_to(arrow.get_start(), DOWN) self.play( FadeIn(question, lag_ratio=0.1), ShowCreation(arrow), ) self.wait() # Bring back bars bars = self.get_bars(axes, dist, 0.05) self.play( FadeOut(graph), FadeIn(bars), ) bars.generate_target() bars.save_state() bars.target.set_opacity(0.2) bar_index = int(0.8 * len(bars)) bars.target[bar_index].set_opacity(0.8) bar = bars[bar_index] prob_word = OldTexText("Probability") prob_word.rotate(90 * DEGREES) prob_word.set_height(0.8 * bar.get_height()) prob_word.move_to(bar) self.play( MoveToTarget(bars), Write(prob_word, run_time=1), ) self.wait() # Show dimensions of bar top_brace = Brace(bar, UP) side_brace = Brace(bar, LEFT) top_label = top_brace.get_tex("\\Delta x") side_label = side_brace.get_tex( "{\\text{Prob.} \\over \\Delta x}" ) self.play( GrowFromCenter(top_brace), FadeIn(top_label), ) self.play(GrowFromCenter(side_brace)) self.wait() self.play(Write(side_label)) self.wait() y_label = OldTexText("Probability density") y_label.next_to(axes.y_axis, UP, aligned_edge=LEFT) self.play( Uncreate(arrow), FadeOutAndShiftDown(question), Write(y_label), ) self.wait(2) self.play( Restore(bars), FadeOut(top_brace), FadeOut(side_brace), FadeOut(top_label), FadeOut(side_label), FadeOut(prob_word), ) # Point out total area is 1 total_label = OldTexText("Total area = 1") total_label.set_height(0.5) total_label.next_to(bars, UP, LARGE_BUFF) self.play(FadeIn(total_label, DOWN)) bars.save_state() self.play( bars.arrange, RIGHT, {"aligned_edge": DOWN, "buff": SMALL_BUFF}, bars.move_to, bars.get_bottom() + 0.5 * UP, DOWN, ) self.play(LaggedStartMap(Indicate, bars, scale_factor=1.05)) self.play(Restore(bars)) # Refine again for step_size in step_sizes[1:]: new_bars = self.get_bars(axes, dist, step_size) if step_size <= 0.05: new_bars.set_stroke(width=0) self.play( ReplacementTransform( bars, new_bars, lag_ratio=step_size ), run_time=3, ) self.wait() bars = new_bars self.add(graph, total_label) self.play( FadeIn(graph), FadeOut(bars), total_label.move_to, axes.c2p(0.7, 0.8) ) self.wait() # Name pdf func_name = OldTexText("Probability ", "Density ", "Function") initials = OldTexText("P", "D", "F") for mob in func_name, initials: mob.set_color(YELLOW) mob.next_to(axes.input_to_graph_point(0.75, graph_curve), UP) self.play( ShowCreation(graph_curve), Write(func_name, run_time=1), ) self.wait() func_name_copy = func_name.copy() self.play( func_name.next_to, initials, UP, *[ ReplacementTransform(np[0], ip[0]) for np, ip in zip(func_name_copy, initials) ], *[ FadeOut(np[1:]) for np in func_name_copy ] ) self.add(initials) self.wait() self.play( FadeOut(func_name), FadeOut(total_label), FadeOut(graph_curve), initials.next_to, axes.input_to_graph_point(0.95, graph_curve), UR, ) # Look at bounded area min_x = 0.6 max_x = 0.8 region = get_region_under_curve(axes, graph_curve, min_x, max_x) area_label = DecimalNumber( dist.cdf(max_x) - dist.cdf(min_x), num_decimal_places=3, ) area_label.move_to(region) v_lines = VGroup() for x in [min_x, max_x]: v_lines.add( DashedLine( axes.c2p(x, 0), axes.c2p(x, 2.5), ) ) v_lines.set_stroke(YELLOW, 2) p_label = VGroup( OldTex("P("), DecimalNumber(min_x), OldTex("\\le"), OldTex("h", color=YELLOW), OldTex("\\le"), DecimalNumber(max_x), OldTex(")") ) p_label.arrange(RIGHT, buff=0.25) VGroup(p_label[0], p_label[-1]).space_out_submobjects(0.92) p_label.next_to(v_lines, UP) rhs = VGroup( OldTex("="), area_label.copy() ) rhs.arrange(RIGHT) rhs.next_to(p_label, RIGHT) self.play( FadeIn(p_label, 2 * DOWN), *map(ShowCreation, v_lines), ) self.wait() region.func = get_region_under_curve self.play( UpdateFromAlphaFunc( region, lambda m, a: m.become( m.func( m.axes, m.graph, m.min_x, interpolate(m.min_x, m.max_x, a) ) ) ), CountInFrom(area_label), UpdateFromAlphaFunc( area_label, lambda m, a: m.set_opacity(a), ), ) self.wait() self.play( TransformFromCopy(area_label, rhs[1]), Write(rhs[0]), ) self.wait() # Change range new_x = np.mean([min_x, max_x]) area_label.original_width = area_label.get_width() region.new_x = new_x # Squish to area 1 self.play( ChangeDecimalToValue(p_label[1], new_x), ChangeDecimalToValue(p_label[5], new_x), ChangeDecimalToValue(area_label, 0), UpdateFromAlphaFunc( area_label, lambda m, a: m.set_width( interpolate(m.original_width, 1e-6, a) ) ), ChangeDecimalToValue(rhs[1], 0), v_lines[0].move_to, axes.c2p(new_x, 0), DOWN, v_lines[1].move_to, axes.c2p(new_x, 0), DOWN, UpdateFromAlphaFunc( region, lambda m, a: m.become(m.func( m.axes, m.graph, interpolate(m.min_x, m.new_x, a), interpolate(m.max_x, m.new_x, a), )) ), run_time=2, ) self.wait() # Stretch to area 1 self.play( ChangeDecimalToValue(p_label[1], 0), ChangeDecimalToValue(p_label[5], 1), ChangeDecimalToValue(area_label, 1), UpdateFromAlphaFunc( area_label, lambda m, a: m.set_width( interpolate(1e-6, m.original_width, clip(5 * a, 0, 1)) ) ), ChangeDecimalToValue(rhs[1], 1), v_lines[0].move_to, axes.c2p(0, 0), DOWN, v_lines[1].move_to, axes.c2p(1, 0), DOWN, UpdateFromAlphaFunc( region, lambda m, a: m.become(m.func( m.axes, m.graph, interpolate(m.new_x, 0, a), interpolate(m.new_x, 1, a), )) ), run_time=5, ) self.wait() def get_axes(self): axes = Axes( x_min=0, x_max=1, x_axis_config={ "tick_frequency": 0.05, "unit_size": 12, "include_tip": False, }, y_min=0, y_max=4, y_axis_config={ "tick_frequency": 1, "unit_size": 1.25, "include_tip": False, } ) axes.center() h_label = OldTex("h") h_label.set_color(YELLOW) h_label.next_to(axes.x_axis.n2p(1), UR, buff=0.2) axes.x_axis.add(h_label) axes.x_axis.label = h_label axes.x_axis.add_numbers( *np.arange(0.2, 1.2, 0.2), num_decimal_places=1 ) axes.y_axis.add_numbers(*range(1, 5)) return axes def get_bars(self, axes, dist, step_size): bars = VGroup() for x in np.arange(0, 1, step_size): bar = Rectangle() bar.set_stroke(BLUE, 2) bar.set_fill(BLUE, 0.5) h_line = Line( axes.c2p(x, 0), axes.c2p(x + step_size, 0), ) v_line = Line( axes.c2p(0, 0), axes.c2p(0, dist.pdf(x)), ) bar.match_width(h_line, stretch=True) bar.match_height(v_line, stretch=True) bar.move_to(h_line, DOWN) bars.add(bar) return bars class FiniteVsContinuum(Scene): def construct(self): # Title f_title = OldTexText("Discrete context") f_title.set_height(0.5) f_title.to_edge(UP) f_underline = Underline(f_title) f_underline.scale(1.3) f_title.add(f_underline) self.add(f_title) # Equations dice = get_die_faces()[::2] cards = [PlayingCard(letter + "H") for letter in "A35"] eqs = VGroup( self.get_union_equation(dice), self.get_union_equation(cards), ) for eq in eqs: eq.set_width(FRAME_WIDTH - 1) eqs.arrange(DOWN, buff=LARGE_BUFF) eqs.next_to(f_underline, DOWN, LARGE_BUFF) anims = [] for eq in eqs: movers = eq.mob_copies1.copy() for m1, m2 in zip(movers, eq.mob_copies2): m1.generate_target() m1.target.replace(m2) eq.mob_copies2.set_opacity(0) eq.add(movers) self.play(FadeIn(eq[0])) anims.append(FadeIn(eq[1:])) anims.append(LaggedStartMap( MoveToTarget, movers, path_arc=30 * DEGREES, lag_ratio=0.1, )) self.wait() for anim in anims: self.play(anim) # Continuum label c_title = OldTexText("Continuous context") c_title.match_height(f_title) c_underline = Underline(c_title) c_underline.scale(1.25) self.play( Write(c_title, run_time=1), ShowCreation(c_underline), eqs[0].shift, 0.5 * UP, eqs[1].shift, UP, ) # Range sum c_eq = OldTex( "P\\big(", "x \\in [0.65, 0.75]", "\\big)", "=", "\\sum_{x \\in [0.65, 0.75]}", "P(", "x", ")", ) c_eq.set_color_by_tex("P", YELLOW) c_eq.set_color_by_tex(")", YELLOW) c_eq.next_to(c_underline, DOWN, LARGE_BUFF) c_eq.to_edge(LEFT) equals = c_eq.get_part_by_tex("=") equals.shift(SMALL_BUFF * RIGHT) e_cross = Line(DL, UR) e_cross.replace(equals, dim_to_match=0) e_cross.set_stroke(RED, 5) self.play(FadeIn(c_eq)) self.wait(2) self.play(ShowCreation(e_cross)) self.wait() def get_union_equation(self, mobs): mob_copies1 = VGroup() mob_copies2 = VGroup() p_color = YELLOW # Create mob_set brackets = OldTex("\\big\\{\\big\\}")[0] mob_set = VGroup(brackets[0]) commas = VGroup() for mob in mobs: mc = mob.copy() mc.match_height(mob_set[0]) mob_copies1.add(mc) comma = OldTex(",") commas.add(comma) mob_set.add(mc) mob_set.add(comma) mob_set.remove(commas[-1]) commas.remove(commas[-1]) mob_set.add(brackets[1]) mob_set.arrange(RIGHT, buff=0.15) commas.set_y(mob_set[1].get_bottom()[1]) mob_set.scale(0.8) # Create individual probabilities probs = VGroup() for mob in mobs: prob = OldTex("P(", "x = ", "00", ")") index = prob.index_of_part_by_tex("00") mc = mob.copy() mc.replace(prob[index]) mc.scale(0.8, about_edge=LEFT) mc.match_y(prob[-1]) mob_copies2.add(mc) prob.replace_submobject(index, mc) prob[0].set_color(p_color) prob[1].match_y(mc) prob[-1].set_color(p_color) probs.add(prob) # Result lhs = VGroup( OldTex("P\\big(", color=p_color), OldTex("x \\in"), mob_set, OldTex("\\big)", color=p_color), ) lhs.arrange(RIGHT, buff=SMALL_BUFF) group = VGroup(lhs, OldTex("=")) for prob in probs: group.add(prob) group.add(OldTex("+")) group.remove(group[-1]) group.arrange(RIGHT, buff=0.2) group.mob_copies1 = mob_copies1 group.mob_copies2 = mob_copies2 return group class ComplainAboutRuleChange(TeacherStudentsScene): def construct(self): self.student_says( "Wait, the rules\\\\changed?", target_mode="sassy", added_anims=[self.teacher.change, "tease"] ) self.play_student_changes("erm", "confused") self.wait(4) self.teacher_says("You may enjoy\\\\``Measure theory''") self.play_all_student_changes( "pondering", look_at=self.teacher.bubble ) self.wait(8) class HalfFiniteHalfContinuous(Scene): def construct(self): # Basic symbols box = Rectangle(width=3, height=1.2) box.set_stroke(WHITE, 2) box.set_fill(GREY_E, 1) box.move_to(2.5 * LEFT, RIGHT) arrows = VGroup() arrow_labels = VGroup() for vect in [UP, DOWN]: arrow = Arrow( box.get_corner(vect + RIGHT), box.get_corner(vect + RIGHT) + 3 * RIGHT + 1.5 * vect, buff=MED_SMALL_BUFF, ) label = OldTex("50\\%") fix_percent(label[0][-1]) label.set_color(YELLOW) label.next_to( arrow.get_center(), vect + LEFT, buff=SMALL_BUFF, ) arrow_labels.add(label) arrows.add(arrow) zero = Integer(0) zero.set_height(0.5) zero.next_to(arrows[0].get_end(), RIGHT) # Half Gaussian axes = Axes( x_min=0, x_max=6.5, y_min=0, y_max=0.25, y_axis_config={ "tick_frequency": 1 / 16, "unit_size": 10, "include_tip": False, } ) axes.next_to(arrows[1].get_end(), RIGHT) dist = scipy.stats.norm(0, 2) graph = axes.get_graph(dist.pdf) graph_fill = graph.copy() close_off_graph(axes, graph_fill) graph.set_stroke(BLUE, 3) graph_fill.set_fill(BLUE_E, 1) graph_fill.set_stroke(BLUE_E, 0) half_gauss = Group( graph, graph_fill, axes, ) # Random Decimal number = DecimalNumber(num_decimal_places=4) number.set_height(0.6) number.move_to(box) number.time = 0 number.last_change = 0 number.change_freq = 0.2 def update_number(number, dt, dist=dist): number.time += dt if (number.time - number.last_change) < number.change_freq: return number.last_change = number.time rand_val = random.random() if rand_val < 0.5: number.set_value(0) else: number.set_value(dist.ppf(rand_val)) number.add_updater(update_number) v_line = SurroundingRectangle(zero) v_line.save_state() v_line.set_stroke(YELLOW, 3) def update_v_line(v_line, number=number, axes=axes, graph=graph): x = number.get_value() if x < 0.5: v_line.restore() else: v_line.set_width(1e-6) p1 = axes.c2p(x, 0) p2 = axes.input_to_graph_point(x, graph) v_line.set_height(get_norm(p2 - p1), stretch=True) v_line.move_to(p1, DOWN) v_line.add_updater(update_v_line) # Add everything self.add(box) self.add(number) self.wait(4) self.play( GrowArrow(arrows[0]), FadeIn(arrow_labels[0]), GrowFromPoint(zero, box.get_corner(UR)) ) self.wait(2) self.play( GrowArrow(arrows[1]), FadeIn(arrow_labels[1]), FadeIn(half_gauss), ) self.add(v_line) self.wait(30) class SumToIntegral(Scene): def construct(self): # Titles titles = VGroup( OldTexText("Discrete context"), OldTexText("Continuous context"), ) titles.set_height(0.5) for title, vect in zip(titles, [LEFT, RIGHT]): title.move_to(vect * FRAME_WIDTH / 4) title.to_edge(UP, buff=MED_SMALL_BUFF) v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) h_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) h_line.next_to(titles, DOWN) h_line.set_x(0) v_line.center() self.play( ShowCreation(VGroup(h_line, v_line)), LaggedStartMap( FadeInFrom, titles, lambda m: (m, -0.2 * m.get_center()[0] * RIGHT), run_time=1, lag_ratio=0.1, ), ) self.wait() # Sum and int kw = {"tex_to_color_map": {"S": BLUE}} s_sym = OldTex("\\sum", "_{x \\in S} P(x)", **kw) i_sym = OldTex("\\int_{S} p(x)", "\\text{d}x", **kw) syms = VGroup(s_sym, i_sym) syms.scale(2) for sym, title in zip(syms, titles): sym.shift(-sym[-1].get_center()) sym.match_x(title) arrow = Arrow( s_sym[0].get_corner(UP), i_sym[0].get_corner(UP), path_arc=-90 * DEGREES, ) arrow.set_color(YELLOW) self.play(Write(s_sym, run_time=1)) anims = [ShowCreation(arrow)] for i, j in [(0, 0), (2, 1), (3, 2)]: source = s_sym[i].deepcopy() target = i_sym[j] target.save_state() source.generate_target() target.replace(source, stretch=True) source.target.replace(target, stretch=True) target.set_opacity(0) source.target.set_opacity(0) anims += [ Restore(target, path_arc=-60 * DEGREES), MoveToTarget(source, path_arc=-60 * DEGREES), ] self.play(LaggedStart(*anims)) self.play(FadeInFromDown(i_sym[3])) self.add(i_sym) self.wait() self.play( FadeOut(arrow, UP), syms.next_to, h_line, DOWN, {"buff": MED_LARGE_BUFF}, syms.match_x, syms, ) # Add curve area in editing # Add bar chart axes = Axes( x_min=0, x_max=10, y_min=0, y_max=7, y_axis_config={ "unit_size": 0.75, } ) axes.set_width(0.5 * FRAME_WIDTH - 1) axes.next_to(s_sym, DOWN) axes.y_axis.add_numbers(2, 4, 6) bars = VGroup() for x, y in [(1, 1), (4, 3), (7, 2)]: bar = Rectangle() bar.set_stroke(WHITE, 1) bar.set_fill(BLUE_D, 1) line = Line(axes.c2p(x, 0), axes.c2p(x + 2, y)) bar.replace(line, stretch=True) bars.add(bar) addition_formula = OldTex(*"1+3+2") addition_formula.space_out_submobjects(2.1) addition_formula.next_to(bars, UP) for bar in bars: bar.save_state() bar.stretch(0, 1, about_edge=DOWN) self.play( Write(axes), LaggedStartMap(Restore, bars), LaggedStartMap(FadeInFromDown, addition_formula), ) self.wait() # Confusion morty = Mortimer() morty.to_corner(DR) morty.look_at(i_sym) self.play( *map(FadeOut, [axes, bars, addition_formula]), FadeIn(morty) ) self.play(morty.change, "maybe") self.play(Blink(morty)) self.play(morty.change, "confused", i_sym.get_right()) self.play(Blink(morty)) self.wait() # Focus on integral self.play( Uncreate(VGroup(v_line, h_line)), FadeOut(titles, UP), FadeOut(morty, RIGHT), FadeOut(s_sym, LEFT), i_sym.center, i_sym.to_edge, LEFT ) arrows = VGroup() for vect in [UP, DOWN]: corner = i_sym[-1].get_corner(RIGHT + vect) arrows.add(Arrow( corner, corner + 2 * RIGHT + 2 * vect, path_arc=-np.sign(vect[1]) * 60 * DEGREES, )) self.play(*map(ShowCreation, arrows)) # Types of integration dist = scipy.stats.beta(7 + 1, 3 + 1) axes_pair = VGroup() graph_pair = VGroup() for arrow in arrows: axes = get_beta_dist_axes(y_max=5, y_unit=1) axes.set_width(4) axes.next_to(arrow.get_end(), RIGHT) graph = axes.get_graph(dist.pdf) graph.set_stroke(BLUE, 2) graph.set_fill(BLUE_E, 0) graph.make_smooth() axes_pair.add(axes) graph_pair.add(graph) r_axes, l_axes = axes_pair r_graph, l_graph = graph_pair r_name = OldTexText("Riemann\\\\Integration") r_name.next_to(r_axes, RIGHT) l_name = OldTexText("Lebesgue\\\\Integration$^*$") l_name.next_to(l_axes, RIGHT) footnote = OldTexText("*a bit more complicated than\\\\these bars make it look") footnote.match_width(l_name) footnote.next_to(l_name, DOWN) self.play(LaggedStart( FadeIn(r_axes), FadeIn(r_graph), FadeIn(r_name), FadeIn(l_axes), FadeIn(l_graph), FadeIn(l_name), run_time=1, )) # Approximation bars def get_riemann_rects(dx, axes=r_axes, func=dist.pdf): bars = VGroup() for x in np.arange(0, 1, dx): bar = Rectangle() line = Line( axes.c2p(x, 0), axes.c2p(x + dx, func(x)), ) bar.replace(line, stretch=True) bar.set_stroke(BLUE_E, width=10 * dx, opacity=1) bar.set_fill(BLUE, 0.5) bars.add(bar) return bars def get_lebesgue_bars(dy, axes=l_axes, func=dist.pdf, mx=0.7, y_max=dist.pdf(0.7)): bars = VGroup() for y in np.arange(dy, y_max + dy, dy): x0 = binary_search(func, y, 0, mx) or mx x1 = binary_search(func, y, mx, 1) or mx line = Line(axes.c2p(x0, y - dy), axes.c2p(x1, y)) bar = Rectangle() bar.set_stroke(RED_E, 0) bar.set_fill(RED_E, 0.5) bar.replace(line, stretch=True) bars.add(bar) return bars r_bar_groups = [] l_bar_groups = [] Ns = [10, 20, 40, 80, 160] Ms = [2, 4, 8, 16, 32] for N, M in zip(Ns, Ms): r_bar_groups.append(get_riemann_rects(dx=1 / N)) l_bar_groups.append(get_lebesgue_bars(dy=1 / M)) self.play( FadeIn(r_bar_groups[0], lag_ratio=0.1), FadeIn(l_bar_groups[0], lag_ratio=0.1), FadeIn(footnote), ) self.wait() for rbg0, rbg1, lbg0, lbg1 in zip(r_bar_groups, r_bar_groups[1:], l_bar_groups, l_bar_groups[1:]): self.play( ReplacementTransform( rbg0, rbg1, lag_ratio=1 / len(rbg0), run_time=2, ), ReplacementTransform( lbg0, lbg1, lag_ratio=1 / len(lbg0), run_time=2, ), ) self.wait() self.play( FadeOut(r_bar_groups[-1]), FadeOut(l_bar_groups[-1]), r_graph.set_fill, BLUE_E, 1, l_graph.set_fill, RED_E, 1, ) class MeasureTheoryLeadsTo(Scene): def construct(self): words = OldTexText("Measure Theory") words.set_color(RED) arrow = Vector(DOWN) arrow.next_to(words, DOWN, buff=SMALL_BUFF) arrow.set_stroke(width=7) arrow.rotate(45 * DEGREES, about_point=arrow.get_start()) self.play( FadeIn(words, DOWN), GrowArrow(arrow), UpdateFromAlphaFunc(arrow, lambda m, a: m.set_opacity(a)), ) self.wait() class WhenIWasFirstLearning(TeacherStudentsScene): def construct(self): self.teacher.change_mode("raise_right_hand") self.play( self.change_students("pondering", "thinking", "tease"), self.teacher.change, "thinking", ) younger = BabyPiCreature(color=GREY_BROWN) younger.set_height(2) younger.move_to(self.students, DL) self.look_at(self.screen) self.wait() self.play( ReplacementTransform(self.teacher, younger), LaggedStartMap( FadeOutAndShift, self.students, lambda m: (m, DOWN), ) ) # Bubble bubble = ThoughtBubble() bubble[-1].set_fill(GREEN_SCREEN, 1) bubble.move_to(younger.get_corner(UR), DL) self.play( Write(bubble), younger.change, "maybe", bubble.get_bubble_center(), ) self.play(Blink(younger)) for mode in ["confused", "angry", "pondering", "maybe"]: self.play(younger.change, mode) for x in range(2): self.wait() if random.random() < 0.5: self.play(Blink(younger)) class PossibleYetProbabilityZero(Scene): def construct(self): poss = OldTexText("Possible") prob = OldTexText("Probability = 0") total = OldTexText("P(dart hits somewhere) = 1") # total[1].next_to(total[0][0], RIGHT) words = VGroup(poss, prob, total) words.scale(1.5) words.arrange(DOWN, aligned_edge=LEFT, buff=MED_LARGE_BUFF) self.play(Write(poss, run_time=0.5)) self.wait() self.play(FadeIn(prob, UP)) self.wait() self.play(FadeIn(total, UP)) self.wait() class TiePossibleToDensity(Scene): def construct(self): poss = OldTexText("Possibility") prob = OldTexText("Probability", " $>$ 0") dens = OldTexText("Probability \\emph{density}", " $>$ 0") dens[0].set_color(BLUE) implies = OldTex("\\Rightarrow") implies2 = implies.copy() poss.next_to(implies, LEFT) prob.next_to(implies, RIGHT) dens.next_to(implies, RIGHT) cross = Cross(implies) self.camera.frame.scale(0.7, about_point=dens.get_center()) self.add(poss) self.play( FadeIn(prob, LEFT), Write(implies, run_time=1) ) self.wait() self.play(ShowCreation(cross)) self.wait() self.play( VGroup(implies, cross, prob).shift, UP, FadeIn(implies2), FadeIn(dens), ) self.wait() self.embed() class DrawBigRect(Scene): def construct(self): rect = Rectangle(width=7, height=2.5) rect.set_stroke(RED, 5) rect.to_edge(RIGHT) words = OldTexText("Not how to\\\\think about it") words.set_color(RED) words.align_to(rect, LEFT) words.to_edge(UP) arrow = Arrow( words.get_bottom(), rect.get_top(), buff=0.25, color=RED, ) self.play(ShowCreation(rect)) self.play( FadeInFromDown(words), GrowArrow(arrow), ) self.wait() class Thumbnail(Scene): def construct(self): dartboard = Dartboard() axes = NumberPlane( x_min=-1.25, x_max=1.25, y_min=-1.25, y_max=1.25, axis_config={ "unit_size": 0.5 * dartboard.get_width(), "tick_frequency": 0.25, }, x_line_frequency=1.0, y_line_frequency=1.0, ) group = VGroup(dartboard, axes) group.to_edge(LEFT, buff=0) # Arrow arrow = Vector(DR, max_stroke_width_to_length_ratio=np.inf) arrow.move_to(axes.c2p(PI / 10, np.exp(1) / 10), DR) arrow.scale(1.5, about_edge=DR) arrow.set_stroke(WHITE, 10) black_arrow = arrow.copy() black_arrow.set_color(BLACK) black_arrow.set_stroke(width=20) arrow.get_points()[0] += 0.025 * DR # Coords coords = OldTex("(x, y) = (0.31415\\dots, 0.27182\\dots)") coords.set_width(5.5) coords.set_stroke(BLACK, 10, background=True) coords.next_to(axes.get_bottom(), UP, buff=0) # Words words = VGroup( OldTexText("Probability = 0"), OldTexText("$\\dots$but still possible"), ) for word in words: word.set_width(6) words.arrange(DOWN, buff=MED_LARGE_BUFF) words.next_to(axes, RIGHT) words.to_edge(UP, buff=LARGE_BUFF) # Pi morty = Mortimer() morty.to_corner(DR) morty.change("confused", words) self.add(group) self.add(black_arrow) self.add(arrow) self.add(coords) self.add(words) self.add(morty) self.embed() class Part2EndScreen(PatreonEndScreen): CONFIG = { "scroll_time": 30, "specific_patrons": [ "1stViewMaths", "Adam Dřínek", "Aidan Shenkman", "Alan Stein", "Albin Egasse", "Alex Mijalis", "Alexander Mai", "Alexis Olson", "Ali Yahya", "Andrew Busey", "Andrew Cary", "Andrew R. Whalley", "Anthony Losego", "Aravind C V", "Arjun Chakroborty", "Arthur Zey", "Ashwin Siddarth", "Augustine Lim", "Austin Goodman", "Avi Finkel", "Awoo", "Axel Ericsson", "Ayan Doss", "AZsorcerer", "Barry Fam", "Ben Delo", "Bernd Sing", "Bill Gatliff", "Bob Sanderson", "Boris Veselinovich", "Bradley Pirtle", "Brandon Huang", "Brian Staroselsky", "Britt Selvitelle", "Britton Finley", "Burt Humburg", "Calvin Lin", "Charles Southerland", "Charlie N", "Chenna Kautilya", "Chris Connett", "Chris Druta", "Christian Kaiser", "cinterloper", "Clark Gaebel", "Colwyn Fritze-Moor", "Cooper Jones", "Corey Ogburn", "D. Sivakumar", "Dan Herbatschek", "Daniel Brown", "Daniel Herrera C", "Darrell Thomas", "Dave B", "Dave Kester", "dave nicponski", "David B. Hill", "David Clark", "David Gow", "Delton Ding", "Dominik Wagner", "Eddie Landesberg", "Eduardo Rodriguez", "emptymachine", "Eric Younge", "Eryq Ouithaqueue", "Federico Lebron", "Fernando Via Canel", "Frank R. Brown, Jr.", "Gavin", "Giovanni Filippi", "Goodwine", "Hal Hildebrand", "Hitoshi Yamauchi", "Ivan Sorokin", "Jacob Baxter", "Jacob Harmon", "Jacob Hartmann", "Jacob Magnuson", "Jalex Stark", "Jameel Syed", "James Beall", "Jason Hise", "Jayne Gabriele", "Jean-Manuel Izaret", "Jeff Dodds", "Jeff Linse", "Jeff Straathof", "Jimmy Yang", "John C. Vesey", "John Camp", "John Haley", "John Le", "John Luttig", "John Rizzo", "John V Wertheim", "Jonathan Heckerman", "Jonathan Wilson", "Joseph John Cox", "Joseph Kelly", "Josh Kinnear", "Joshua Claeys", "Joshua Ouellette", "Juan Benet", "Kai-Siang Ang", "Kanan Gill", "Karl Niu", "Kartik Cating-Subramanian", "Kaustuv DeBiswas", "Killian McGuinness", "Klaas Moerman", "Kros Dai", "L0j1k", "Lael S Costa", "LAI Oscar", "Lambda GPU Workstations", "Laura Gast", "Lee Redden", "Linh Tran", "Luc Ritchie", "Ludwig Schubert", "Lukas Biewald", "Lukas Zenick", "Magister Mugit", "Magnus Dahlström", "Magnus Hiie", "Manoj Rewatkar - RITEK SOLUTIONS", "Mark B Bahu", "Mark Heising", "Mark Mann", "Martin Price", "Mathias Jansson", "Matt Godbolt", "Matt Langford", "Matt Roveto", "Matt Russell", "Matteo Delabre", "Matthew Bouchard", "Matthew Cocke", "Maxim Nitsche", "Michael Bos", "Michael Day", "Michael Hardel", "Michael W White", "Mihran Vardanyan", "Mirik Gogri", "Molly Mackinlay", "Mustafa Mahdi", "Márton Vaitkus", "Nate Heckmann", "Nicholas Cahill", "Nikita Lesnikov", "Oleg Leonov", "Omar Zrien", "Owen Campbell-Moore", "Patrick Lucas", "Pavel Dubov", "Pesho Ivanov", "Petar Veličković", "Peter Ehrnstrom", "Peter Francis", "Peter Mcinerney", "Pierre Lancien", "Pradeep Gollakota", "Rafael Bove Barrios", "Randy C. Will", "rehmi post", "Rex Godby", "Ripta Pasay", "Rish Kundalia", "Roman Sergeychik", "Roobie", "Ryan Atallah", "Ryan Prayogo", "Samuel Judge", "SansWord Huang", "Scott Gray", "Scott Walter, Ph.D.", "soekul", "Solara570", "Steve Huynh", "Steve Muench", "Steve Sperandeo", "Steven Siddals", "Stevie Metke", "Sunil Nagaraj", "supershabam", "Susanne Fenja Mehr-Koks", "Suteerth Vishnu", "Suthen Thomas", "Tal Einav", "Taras Bobrovytsky", "Tauba Auerbach", "Ted Suzman", "THIS IS THE point OF NO RE tUUurRrhghgGHhhnnn", "Thomas J Sargent", "Thomas Tarler", "Tianyu Ge", "Tihan Seale", "Tyler Herrmann", "Tyler McAtee", "Tyler VanValkenburg", "Tyler Veness", "Vassili Philippov", "Vasu Dubey", "Veritasium", "Vignesh Ganapathi Subramanian", "Vinicius Reis", "Vladimir Solomatin", "Wooyong Ee", "Xuanji Li", "Yana Chernobilsky", "YinYangBalance.Asia", "Yorick Lesecque", "Yu Jun", "Yurii Monastyrshyn", ], }
from manim_imports_ext import * from _2020.beta.helpers import * from _2020.beta.beta1 import * from _2020.beta.beta2 import ShowLimitToPdf import scipy.stats OUTPUT_DIRECTORY = "bayes/beta3" class RemindOfWeightedCoin(Scene): def construct(self): # Largely copied from beta2 # Prob label p_label = get_prob_coin_label() p_label.set_height(0.7) p_label.to_edge(UP) rhs = p_label[-1] q_box = get_q_box(rhs) p_label.add(q_box) self.add(p_label) # Coin grid def get_random_coin_grid(p): bools = np.random.random(100) < p grid = get_coin_grid(bools) return grid grid = get_random_coin_grid(0.5) grid.next_to(p_label, DOWN, MED_LARGE_BUFF) self.play(LaggedStartMap( FadeIn, grid, lag_ratio=2 / len(grid), run_time=3, )) self.wait() # Label as h brace = Brace(q_box, DOWN, buff=SMALL_BUFF) h_label = OldTex("h") h_label.next_to(brace, DOWN) eq = OldTex("=") eq.next_to(h_label, RIGHT) h_decimal = DecimalNumber(0.5) h_decimal.next_to(eq, RIGHT) self.play( GrowFromCenter(brace), FadeIn(h_label, UP), grid.scale, 0.8, {"about_edge": DOWN}, ) self.wait() # Alternate weightings tail_grid = get_random_coin_grid(0) head_grid = get_random_coin_grid(1) grid70 = get_random_coin_grid(0.7) alt_grids = [tail_grid, head_grid, grid70] for ag in alt_grids: ag.replace(grid) for coins in [grid, *alt_grids]: for coin in coins: coin.generate_target() coin.target.rotate(90 * DEGREES, axis=UP) coin.target.set_opacity(0) def get_grid_swap_anims(g1, g2): return [ LaggedStartMap(MoveToTarget, g1, lag_ratio=0.02, run_time=1.5, remover=True), LaggedStartMap(MoveToTarget, g2, lag_ratio=0.02, run_time=1.5, rate_func=reverse_smooth), ] self.play( FadeIn(eq), UpdateFromAlphaFunc(h_decimal, lambda m, a: m.set_opacity(a)), ChangeDecimalToValue(h_decimal, 0, run_time=2), *get_grid_swap_anims(grid, tail_grid) ) self.wait() self.play( ChangeDecimalToValue(h_decimal, 1, run_time=1.5), *get_grid_swap_anims(tail_grid, head_grid) ) self.wait() self.play( ChangeDecimalToValue(h_decimal, 0.7, run_time=1.5), *get_grid_swap_anims(head_grid, grid70) ) self.wait() # Graph axes = scaled_pdf_axes() axes.to_edge(DOWN, buff=MED_SMALL_BUFF) axes.y_axis.numbers.set_opacity(0) axes.y_axis_label.set_opacity(0) h_lines = VGroup() for y in range(15): h_line = Line(axes.c2p(0, y), axes.c2p(1, y)) h_lines.add(h_line) h_lines.set_stroke(WHITE, 0.5, opacity=0.5) axes.add(h_lines) x_axis_label = p_label[:4].copy() x_axis_label.set_height(0.4) x_axis_label.next_to(axes.c2p(1, 0), UR, buff=SMALL_BUFF) axes.x_axis.add(x_axis_label) n_heads_tracker = ValueTracker(3) n_tails_tracker = ValueTracker(3) def get_graph(axes=axes, nht=n_heads_tracker, ntt=n_tails_tracker): dist = scipy.stats.beta(nht.get_value() + 1, ntt.get_value() + 1) graph = axes.get_graph(dist.pdf, step_size=0.05) graph.set_stroke(BLUE, 3) graph.set_fill(BLUE_E, 1) return graph graph = always_redraw(get_graph) area_label = OldTexText("Area = 1") area_label.set_height(0.5) area_label.move_to(axes.c2p(0.5, 1)) # pdf label pdf_label = OldTexText("probability ", "density ", "function") pdf_label.next_to(axes.input_to_graph_point(0.5, graph), UP) pdf_target_template = OldTexText("p", "d", "f") pdf_target_template.next_to(axes.input_to_graph_point(0.7, graph), UR) pdf_label.generate_target() for part, letter2 in zip(pdf_label.target, pdf_target_template): for letter1 in part: letter1.move_to(letter2) part[1:].set_opacity(0) # Add plot self.add(axes, *self.mobjects) self.play( FadeOut(eq), FadeOut(h_decimal), LaggedStartMap(MoveToTarget, grid70, run_time=1, remover=True), FadeIn(axes), ) self.play( DrawBorderThenFill(graph), FadeIn(area_label, rate_func=squish_rate_func(smooth, 0.5, 1), run_time=2), Write(pdf_label, run_time=1), ) self.wait() # Region lh_tracker = ValueTracker(0.7) rh_tracker = ValueTracker(0.7) def get_region(axes=axes, graph=graph, lh_tracker=lh_tracker, rh_tracker=rh_tracker): lh = lh_tracker.get_value() rh = rh_tracker.get_value() region = get_region_under_curve(axes, graph, lh, rh) region.set_fill(GREY, 0.85) region.set_stroke(YELLOW, 1) return region region = always_redraw(get_region) region_area_label = DecimalNumber(num_decimal_places=3) region_area_label.next_to(axes.c2p(0.7, 0), UP, MED_LARGE_BUFF) def update_ra_label(label, nht=n_heads_tracker, ntt=n_tails_tracker, lht=lh_tracker, rht=rh_tracker): dist = scipy.stats.beta(nht.get_value() + 1, ntt.get_value() + 1) area = dist.cdf(rht.get_value()) - dist.cdf(lht.get_value()) label.set_value(area) region_area_label.add_updater(update_ra_label) range_label = VGroup( OldTex("0.6 \\le"), p_label[:4].copy(), OldTex("\\le 0.8"), ) for mob in range_label: mob.set_height(0.4) range_label.arrange(RIGHT, buff=SMALL_BUFF) pp_label = VGroup( OldTex("P("), range_label, OldTex(")"), ) for mob in pp_label[::2]: mob.set_height(0.7) mob.set_color(YELLOW) pp_label.arrange(RIGHT, buff=SMALL_BUFF) pp_label.move_to(axes.c2p(0.3, 3)) self.play( FadeIn(pp_label[::2]), MoveToTarget(pdf_label), FadeOut(area_label), ) self.wait() self.play(TransformFromCopy(p_label[:4], range_label[1])) self.wait() self.play(TransformFromCopy(axes.x_axis.numbers[2], range_label[0])) self.play(TransformFromCopy(axes.x_axis.numbers[3], range_label[2])) self.wait() self.add(region) self.play( lh_tracker.set_value, 0.6, rh_tracker.set_value, 0.8, UpdateFromAlphaFunc( region_area_label, lambda m, a: m.set_opacity(a), rate_func=squish_rate_func(smooth, 0.25, 1) ), run_time=3, ) self.wait() # 7/10 heads bools = [True] * 7 + [False] * 3 random.shuffle(bools) coins = VGroup(*[ get_coin("H" if heads else "T") for heads in bools ]) coins.arrange(RIGHT) coins.set_height(0.7) coins.next_to(h_label, DOWN, buff=MED_LARGE_BUFF) heads = [c for c in coins if c.symbol == "H"] numbers = VGroup(*[ Integer(i + 1).set_height(0.2).next_to(coin, DOWN, SMALL_BUFF) for i, coin in enumerate(heads) ]) for coin in coins: coin.save_state() coin.rotate(90 * DEGREES, UP) coin.set_opacity(0) pp_label.generate_target() pp_label.target.set_height(0.5) pp_label.target.next_to(axes.c2p(0, 2), RIGHT, MED_LARGE_BUFF) self.play( LaggedStartMap(Restore, coins), MoveToTarget(pp_label), run_time=1, ) self.play(ShowIncreasingSubsets(numbers)) self.wait() # Move plot self.play( n_heads_tracker.set_value, 7, n_tails_tracker.set_value, 3, FadeOut(pdf_label, rate_func=squish_rate_func(smooth, 0, 0.5)), run_time=2 ) self.wait() # How does the answer change with more data new_bools = [True] * 63 + [False] * 27 random.shuffle(new_bools) bools = [c.symbol == "H" for c in coins] + new_bools grid = get_coin_grid(bools) grid.set_height(3.5) grid.next_to(axes.c2p(0, 3), RIGHT, MED_LARGE_BUFF) self.play( FadeOut(numbers), ReplacementTransform(coins, grid[:10]), ) self.play( FadeIn(grid[10:], lag_ratio=0.1, rate_func=linear), pp_label.next_to, grid, DOWN, ) self.wait() self.add(graph, region, region_area_label, p_label, q_box, brace, h_label) self.play( n_heads_tracker.set_value, 70, n_tails_tracker.set_value, 30, ) self.wait() origin = axes.c2p(0, 0) self.play( axes.y_axis.stretch, 0.5, 1, {"about_point": origin}, h_lines.stretch, 0.5, 1, {"about_point": origin}, ) self.wait() # Shift the shape around pairs = [ (70 * 3, 30 * 3), (35, 15), (35 + 20, 15 + 20), (7, 3), (70, 30), ] for nh, nt in pairs: self.play( n_heads_tracker.set_value, nh, n_tails_tracker.set_value, nt, run_time=2, ) self.wait() # End self.embed() class LastTimeWrapper(Scene): def construct(self): fs_rect = FullScreenFadeRectangle(fill_opacity=1, fill_color=GREY_E) self.add(fs_rect) title = OldTexText("Last Time") title.scale(1.5) title.to_edge(UP) rect = ScreenRectangle() rect.set_height(6) rect.set_fill(BLACK, 1) rect.next_to(title, DOWN) self.play( DrawBorderThenFill(rect), FadeInFromDown(title), ) self.wait() class ComplainAboutSimplisticModel(ExternallyAnimatedScene): pass class BayesianFrequentistDivide(Scene): def construct(self): # Setup Bayesian vs. Frequentist divide b_label = OldTexText("Bayesian") f_label = OldTexText("Frequentist") labels = VGroup(b_label, f_label) for label, vect in zip(labels, [LEFT, RIGHT]): label.set_height(0.7) label.move_to(vect * FRAME_WIDTH / 4) label.to_edge(UP, buff=0.35) h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH) h_line.next_to(labels, DOWN) v_line = Line(UP, DOWN) v_line.set_height(FRAME_HEIGHT) v_line.center() for label in labels: label.save_state() label.set_y(0) self.play( FadeIn(label, -normalize(label.get_center())), ) self.wait() self.play( ShowCreation(VGroup(v_line, h_line)), *map(Restore, labels), ) self.wait() # Overlay ShowBayesianUpdating in editing # Frequentist list (ignore?) kw = { "tex_to_color_map": { "$p$-value": YELLOW, "$H_0$": PINK, "$\\alpha$": BLUE, }, "alignment": "", } freq_list = VGroup( OldTexText("1. State a null hypothesis $H_0$", **kw), OldTexText("2. Choose a test statistic,\\\\", "$\\qquad$ compute its value", **kw), OldTexText("3. Calculate a $p$-value", **kw), OldTexText("4. Choose a significance value $\\alpha$", **kw), OldTexText("5. Reject $H_0$ if $p$-value\\\\", "$\\qquad$ is less than $\\alpha$", **kw), ) freq_list.set_width(0.5 * FRAME_WIDTH - 1) freq_list.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) freq_list.move_to(FRAME_WIDTH * RIGHT / 4) freq_list.to_edge(DOWN, buff=LARGE_BUFF) # Frequentist icon axes = get_beta_dist_axes(y_max=5, y_unit=1) axes.set_width(0.5 * FRAME_WIDTH - 1) axes.move_to(FRAME_WIDTH * RIGHT / 4 + DOWN) dist = scipy.stats.norm(0.5, 0.1) graph = axes.get_graph(dist.pdf) graphs = VGroup() for x_min, x_max in [(0, 0.3), (0.3, 0.7), (0.7, 1.0)]: graph = axes.get_graph(dist.pdf, x_min=x_min, x_max=x_max) graph.add_line_to(axes.c2p(x_max, 0)) graph.add_line_to(axes.c2p(x_min, 0)) graph.add_line_to(graph.get_start()) graphs.add(graph) graphs.set_stroke(width=0) graphs.set_fill(RED, 1) graphs[1].set_fill(GREY_D, 1) H_words = VGroup(*[TexText("Reject\\\\$H_0$") for x in range(2)]) for H_word, graph, vect in zip(H_words, graphs[::2], [RIGHT, LEFT]): H_word.next_to(graph, UP, MED_LARGE_BUFF) arrow = Arrow( H_word.get_bottom(), graph.get_center() + 0.75 * vect, buff=SMALL_BUFF ) H_word.add(arrow) H_words.set_color(RED) self.add(H_words) self.add(axes) self.add(graphs) self.embed() # Transition to 2x2 # Go back to prior # Label uniform prior # Talk about real coin prior # Update ad infinitum class ArgumentBetweenBayesianAndFrequentist(Scene): def construct(self): pass # From version 1 class ShowBayesianUpdating(Scene): CONFIG = { "true_p": 0.72, "random_seed": 4, "initial_axis_scale_factor": 3.5 } def construct(self): # Axes axes = scaled_pdf_axes(self.initial_axis_scale_factor) self.add(axes) # Graph n_heads = 0 n_tails = 0 graph = get_beta_graph(axes, n_heads, n_tails) self.add(graph) # Get coins true_p = self.true_p bool_values = np.random.random(100) < true_p bool_values[1] = True coins = self.get_coins(bool_values) coins.next_to(axes.y_axis, RIGHT, MED_LARGE_BUFF) coins.to_edge(UP, LARGE_BUFF) # Probability label p_label, prob, prob_box = self.get_probability_label() self.add(p_label) self.add(prob_box) # Slow animations def head_likelihood(x): return x def tail_likelihood(x): return 1 - x n_previews = 10 n_slow_previews = 5 for x in range(n_previews): coin = coins[x] is_heads = bool_values[x] new_data_label = OldTexText("New data") new_data_label.set_height(0.3) arrow = Vector(0.5 * UP) arrow.next_to(coin, DOWN, SMALL_BUFF) new_data_label.next_to(arrow, DOWN, SMALL_BUFF) new_data_label.shift(MED_SMALL_BUFF * RIGHT) if is_heads: line = axes.get_graph(lambda x: x) label = OldTex("\\text{Scale by } x") likelihood = head_likelihood n_heads += 1 else: line = axes.get_graph(lambda x: 1 - x) label = OldTex("\\text{Scale by } (1 - x)") likelihood = tail_likelihood n_tails += 1 label.next_to(graph, UP) label.set_stroke(BLACK, 3, background=True) line.set_stroke(YELLOW, 3) graph_copy = graph.copy() scaled_graph = graph.copy() scaled_graph.apply_function( lambda p: axes.c2p( axes.x_axis.p2n(p), axes.y_axis.p2n(p) * likelihood(axes.x_axis.p2n(p)) ) ) scaled_graph.set_color(GREEN) renorm_label = OldTexText("Renormalize") renorm_label.move_to(label) new_graph = get_beta_graph(axes, n_heads, n_tails) renormalized_graph = scaled_graph.copy() renormalized_graph.match_style(graph) renormalized_graph.match_height(new_graph, stretch=True, about_edge=DOWN) if x < n_slow_previews: self.play( FadeInFromDown(coin), FadeIn(new_data_label), GrowArrow(arrow), ) self.play( FadeOut(new_data_label), FadeOut(arrow), ShowCreation(line), FadeIn(label), ) self.add(graph_copy, line, label) self.play(Transform(graph_copy, scaled_graph)) self.play( FadeOut(line), FadeOut(label), FadeIn(renorm_label), ) self.play( Transform(graph_copy, renormalized_graph), FadeOut(graph), ) self.play(FadeOut(renorm_label)) else: self.add(coin) graph_copy.become(scaled_graph) self.add(graph_copy) self.play( Transform(graph_copy, renormalized_graph), FadeOut(graph), ) graph = new_graph self.remove(graph_copy) self.add(new_graph) # Rescale y axis axes.save_state() sf = self.initial_axis_scale_factor axes.y_axis.stretch(1 / sf, 1, about_point=axes.c2p(0, 0)) for number in axes.y_axis.numbers: number.stretch(sf, 1) axes.y_axis.numbers[:4].set_opacity(0) self.play( Restore(axes, rate_func=lambda t: smooth(1 - t)), graph.stretch, 1 / sf, 1, {"about_edge": DOWN}, run_time=2, ) # Fast animations for x in range(n_previews, len(coins)): coin = coins[x] is_heads = bool_values[x] if is_heads: n_heads += 1 else: n_tails += 1 new_graph = get_beta_graph(axes, n_heads, n_tails) self.add(coins[:x + 1]) self.add(new_graph) self.remove(graph) self.wait(0.25) # self.play( # FadeIn(new_graph), # run_time=0.25, # ) # self.play( # FadeOut(graph), # run_time=0.25, # ) graph = new_graph # Show confidence interval dist = scipy.stats.beta(n_heads + 1, n_tails + 1) v_lines = VGroup() labels = VGroup() x_bounds = dist.interval(0.95) for x in x_bounds: line = DashedLine( axes.c2p(x, 0), axes.c2p(x, 12), ) line.set_color(YELLOW) v_lines.add(line) label = DecimalNumber(x) label.set_height(0.25) label.next_to(line, UP) label.match_color(line) labels.add(label) true_graph = axes.get_graph(dist.pdf) region = get_region_under_curve(axes, true_graph, *x_bounds) region.set_fill(GREY_BROWN, 0.85) region.set_stroke(YELLOW, 1) label95 = OldTex("95\\%") fix_percent(label95.family_members_with_points()[-1]) label95.move_to(region, DOWN) label95.shift(0.5 * UP) self.play(*map(ShowCreation, v_lines)) self.play( FadeIn(region), Write(label95) ) self.wait() for label in labels: self.play(FadeInFromDown(label)) self.wait() # Show true value self.wait() self.play(FadeOut(prob_box)) self.play(ShowCreationThenFadeAround(prob)) self.wait() # Much more data many_bools = np.hstack([ bool_values, (np.random.random(1000) < true_p) ]) N_tracker = ValueTracker(100) graph.N_tracker = N_tracker graph.bools = many_bools graph.axes = axes graph.v_lines = v_lines graph.labels = labels graph.region = region graph.label95 = label95 label95.width_ratio = label95.get_width() / region.get_width() def update_graph(graph): N = int(graph.N_tracker.get_value()) nh = sum(graph.bools[:N]) nt = len(graph.bools[:N]) - nh new_graph = get_beta_graph(graph.axes, nh, nt, step_size=0.05) graph.become(new_graph) dist = scipy.stats.beta(nh + 1, nt + 1) x_bounds = dist.interval(0.95) for x, line, label in zip(x_bounds, graph.v_lines, graph.labels): line.set_x(graph.axes.c2p(x, 0)[0]) label.set_x(graph.axes.c2p(x, 0)[0]) label.set_value(x) graph.labels[0].shift(MED_SMALL_BUFF * LEFT) graph.labels[1].shift(MED_SMALL_BUFF * RIGHT) new_simple_graph = graph.axes.get_graph(dist.pdf) new_region = get_region_under_curve(graph.axes, new_simple_graph, *x_bounds) new_region.match_style(graph.region) graph.region.become(new_region) graph.label95.set_width(graph.label95.width_ratio * graph.region.get_width()) graph.label95.match_x(graph.region) self.add(graph, region, label95, p_label) self.play( N_tracker.set_value, 1000, UpdateFromFunc(graph, update_graph), Animation(v_lines), Animation(labels), Animation(graph.region), Animation(graph.label95), run_time=5, ) self.wait() # def get_coins(self, bool_values): coins = VGroup(*[ get_coin("H" if heads else "T") for heads in bool_values ]) coins.arrange_in_grid(n_rows=10, buff=MED_LARGE_BUFF) coins.set_height(5) return coins def get_probability_label(self): head = get_coin("H") p_label = OldTex( "P(00) = ", tex_to_color_map={"00": WHITE} ) template = p_label.get_part_by_tex("00") head.replace(template) p_label.replace_submobject( p_label.index_of_part(template), head, ) prob = DecimalNumber(self.true_p) prob.next_to(p_label, RIGHT) p_label.add(prob) p_label.set_height(0.75) p_label.to_corner(UR) prob_box = SurroundingRectangle(prob, buff=SMALL_BUFF) prob_box.set_fill(GREY_D, 1) prob_box.set_stroke(WHITE, 2) q_marks = OldTex("???") q_marks.move_to(prob_box) prob_box.add(q_marks) return p_label, prob, prob_box class HighlightReviewPartsReversed(HighlightReviewParts): CONFIG = { "reverse_order": True, } class Grey(Scene): def construct(self): self.add(FullScreenFadeRectangle(fill_color=GREY_D, fill_opacity=1)) class ShowBayesRule(Scene): def construct(self): hyp = "\\text{Hypothesis}" data = "\\text{Data}" bayes = OldTex( f"P({hyp} \\,|\\, {data})", "=", "{", f"P({data} \\,|\\, {hyp})", f"P({hyp})", "\\over", f"P({data})", tex_to_color_map={ hyp: YELLOW, data: GREEN, } ) title = OldTexText("Bayes' rule") title.scale(2) title.to_edge(UP) self.add(title) self.add(*bayes[:5]) self.wait() self.play( *[ TransformFromCopy(bayes[i], bayes[j], path_arc=30 * DEGREES) for i, j in [ (0, 7), (1, 10), (2, 9), (3, 8), (4, 11), ] ], FadeIn(bayes[5]), run_time=1.5 ) self.wait() self.play( *[ TransformFromCopy(bayes[i], bayes[j], path_arc=30 * DEGREES) for i, j in [ (0, 12), (1, 13), (4, 14), (0, 16), (3, 17), (4, 18), ] ], FadeIn(bayes[15]), run_time=1.5 ) self.add(bayes) self.wait() hyp_word = bayes.get_part_by_tex(hyp) example_hyp = OldTexText( "For example,\\\\", "$0.9 < s < 0.99$", ) example_hyp[1].set_color(YELLOW) example_hyp.next_to(hyp_word, DOWN, buff=1.5) data_word = bayes.get_part_by_tex(data) example_data = OldTex( "48\\,", CMARK_TEX, "\\,2\\,", XMARK_TEX, ) example_data.set_color_by_tex(CMARK_TEX, GREEN) example_data.set_color_by_tex(XMARK_TEX, RED) example_data.scale(1.5) example_data.next_to(example_hyp, RIGHT, buff=1.5) hyp_arrow = Arrow( hyp_word.get_bottom(), example_hyp.get_top(), ) data_arrow = Arrow( data_word.get_bottom(), example_data.get_top(), ) self.play( GrowArrow(hyp_arrow), FadeInFromPoint(example_hyp, hyp_word.get_center()), ) self.wait() self.play( GrowArrow(data_arrow), FadeInFromPoint(example_data, data_word.get_center()), ) self.wait() class VisualizeBayesRule(Scene): def construct(self): self.show_continuum() self.show_arrows() self.show_discrete_probabilities() self.show_bayes_formula() self.parallel_universes() self.update_from_data() def show_continuum(self): axes = get_beta_dist_axes(y_max=1, y_unit=0.1) axes.y_axis.add_numbers( *np.arange(0.2, 1.2, 0.2), num_decimal_places=1, ) p_label = OldTex( "P(s \\,|\\, \\text{data})", tex_to_color_map={ "s": YELLOW, "\\text{data}": GREEN, } ) p_label.scale(1.5) p_label.to_edge(UP, LARGE_BUFF) s_part = p_label.get_part_by_tex("s").copy() x_line = Line(axes.c2p(0, 0), axes.c2p(1, 0)) x_line.set_stroke(YELLOW, 3) arrow = Vector(DOWN) arrow.next_to(s_part, DOWN, SMALL_BUFF) value = DecimalNumber(0, num_decimal_places=4) value.set_color(YELLOW) value.next_to(arrow, DOWN) self.add(axes) self.add(p_label) self.play( s_part.next_to, x_line.get_start(), UR, SMALL_BUFF, GrowArrow(arrow), FadeInFromPoint(value, s_part.get_center()), ) s_part.tracked = x_line value.tracked = x_line value.x_axis = axes.x_axis self.play( ShowCreation(x_line), UpdateFromFunc( s_part, lambda m: m.next_to(m.tracked.get_end(), UR, SMALL_BUFF) ), UpdateFromFunc( value, lambda m: m.set_value( m.x_axis.p2n(m.tracked.get_end()) ) ), run_time=3, ) self.wait() self.play( FadeOut(arrow), FadeOut(value), ) self.p_label = p_label self.s_part = s_part self.value = value self.x_line = x_line self.axes = axes def show_arrows(self): axes = self.axes arrows = VGroup() arrow_template = Vector(DOWN) def get_arrow(s, denom): arrow = arrow_template.copy() arrow.set_height(4 / denom) arrow.move_to(axes.c2p(s, 0), DOWN) arrow.set_color(interpolate_color( GREY_A, GREY_C, random.random() )) return arrow for k in range(2, 50): for n in range(1, k): if np.gcd(n, k) != 1: continue s = n / k arrows.add(get_arrow(s, k)) for k in range(50, 1000): arrows.add(get_arrow(1 / k, k)) arrows.add(get_arrow(1 - 1 / k, k)) kw = { "lag_ratio": 0.5, "run_time": 5, "rate_func": lambda t: t**4, } arrows.save_state() for arrow in arrows: arrow.stretch(0, 0) arrow.set_stroke(width=0) arrow.set_opacity(0) self.play(Restore(arrows, **kw)) self.play(LaggedStartMap( ApplyMethod, arrows, lambda m: (m.scale, 0, {"about_edge": DOWN}), **kw )) self.remove(arrows) self.wait() def show_discrete_probabilities(self): axes = self.axes x_lines = VGroup() dx = 0.01 for x in np.arange(0, 1, dx): line = Line( axes.c2p(x, 0), axes.c2p(x + dx, 0), ) line.set_stroke(BLUE, 3) line.generate_target() line.target.rotate( 90 * DEGREES, about_point=line.get_start() ) x_lines.add(line) self.add(x_lines) self.play( FadeOut(self.x_line), LaggedStartMap( MoveToTarget, x_lines, ) ) label = Integer(0) label.set_height(0.5) label.next_to(self.p_label[1], DOWN, LARGE_BUFF) unit = OldTex("\\%") unit.match_height(label) fix_percent(unit.family_members_with_points()[0]) always(unit.next_to, label, RIGHT, SMALL_BUFF) arrow = Arrow() arrow.max_stroke_width_to_length_ratio = 1 arrow.axes = axes arrow.label = label arrow.add_updater(lambda m: m.put_start_and_end_on( m.label.get_bottom() + MED_SMALL_BUFF * DOWN, m.axes.c2p(0.01 * m.label.get_value(), 0.03), )) self.add(label, unit, arrow) self.play( ChangeDecimalToValue(label, 99), run_time=5, ) self.wait() self.play(*map(FadeOut, [label, unit, arrow])) # Show prior label p_label = self.p_label given_data = p_label[2:4] prior_label = OldTex("P(s)", tex_to_color_map={"s": YELLOW}) prior_label.match_height(p_label) prior_label.move_to(p_label, DOWN, LARGE_BUFF) p_label.save_state() self.play( given_data.scale, 0.5, given_data.set_opacity, 0.5, given_data.to_corner, UR, Transform(p_label[:2], prior_label[:2]), Transform(p_label[-1], prior_label[-1]), ) self.wait() # Zoom in on the y-values new_ticks = VGroup() new_labels = VGroup() dy = 0.01 for y in np.arange(dy, 5 * dy, dy): height = get_norm(axes.c2p(0, dy) - axes.c2p(0, 0)) tick = axes.y_axis.get_tick(y, SMALL_BUFF) label = DecimalNumber(y) label.match_height(axes.y_axis.numbers[0]) always(label.next_to, tick, LEFT, SMALL_BUFF) new_ticks.add(tick) new_labels.add(label) for num in axes.y_axis.numbers: height = num.get_height() always(num.set_height, height, stretch=True) bars = VGroup() dx = 0.01 origin = axes.c2p(0, 0) for x in np.arange(0, 1, dx): rect = Rectangle( width=get_norm(axes.c2p(dx, 0) - origin), height=get_norm(axes.c2p(0, dy) - origin), ) rect.x = x rect.set_stroke(BLUE, 1) rect.set_fill(BLUE, 0.5) rect.move_to(axes.c2p(x, 0), DL) bars.add(rect) stretch_group = VGroup( axes.y_axis, bars, new_ticks, x_lines, ) x_lines.set_height( bars.get_height(), about_edge=DOWN, stretch=True, ) self.play( stretch_group.stretch, 25, 1, {"about_point": axes.c2p(0, 0)}, VFadeIn(bars), VFadeIn(new_ticks), VFadeIn(new_labels), VFadeOut(x_lines), run_time=4, ) highlighted_bars = bars.copy() highlighted_bars.set_color(YELLOW) self.play( LaggedStartMap( FadeIn, highlighted_bars, lag_ratio=0.5, rate_func=there_and_back, ), ShowCreationThenFadeAround(new_labels[0]), run_time=3, ) self.remove(highlighted_bars) # Nmae as prior prior_name = OldTexText("Prior", " distribution") prior_name.set_height(0.6) prior_name.next_to(prior_label, DOWN, LARGE_BUFF) self.play(FadeInFromDown(prior_name)) self.wait() # Show alternate distribution bars.save_state() for a, b in [(5, 2), (1, 6)]: dist = scipy.stats.beta(a, b) for bar, saved in zip(bars, bars.saved_state): bar.target = saved.copy() height = get_norm(axes.c2p(0.1 * dist.pdf(bar.x)) - axes.c2p(0, 0)) bar.target.set_height(height, about_edge=DOWN, stretch=True) self.play(LaggedStartMap(MoveToTarget, bars, lag_ratio=0.00)) self.wait() self.play(Restore(bars)) self.wait() uniform_name = OldTexText("Uniform") uniform_name.match_height(prior_name) uniform_name.move_to(prior_name, DL) uniform_name.shift(RIGHT) uniform_name.set_y(bars.get_top()[1] + MED_SMALL_BUFF, DOWN) self.play( prior_name[0].next_to, uniform_name, RIGHT, MED_SMALL_BUFF, DOWN, FadeOut(prior_name[1], RIGHT), FadeIn(uniform_name, LEFT) ) self.wait() self.bars = bars self.uniform_label = VGroup(uniform_name, prior_name[0]) def show_bayes_formula(self): uniform_label = self.uniform_label p_label = self.p_label bars = self.bars prior_label = VGroup( p_label[0].deepcopy(), p_label[1].deepcopy(), p_label[4].deepcopy(), ) eq = OldTex("=") likelihood_label = OldTex( "P(", "\\text{data}", "|", "s", ")", ) likelihood_label.set_color_by_tex("data", GREEN) likelihood_label.set_color_by_tex("s", YELLOW) over = Line(LEFT, RIGHT) p_data_label = OldTexText("P(", "\\text{data}", ")") p_data_label.set_color_by_tex("data", GREEN) for mob in [eq, likelihood_label, over, p_data_label]: mob.scale(1.5) mob.set_opacity(0.1) eq.move_to(prior_label, LEFT) over.set_width( prior_label.get_width() + likelihood_label.get_width() + MED_SMALL_BUFF ) over.next_to(eq, RIGHT, MED_SMALL_BUFF) p_data_label.next_to(over, DOWN, MED_SMALL_BUFF) likelihood_label.next_to(over, UP, MED_SMALL_BUFF, RIGHT) self.play( p_label.restore, p_label.next_to, eq, LEFT, MED_SMALL_BUFF, prior_label.next_to, over, UP, MED_SMALL_BUFF, LEFT, FadeIn(eq), FadeIn(likelihood_label), FadeIn(over), FadeIn(p_data_label), FadeOut(uniform_label), ) # Show new distribution post_bars = bars.copy() total_prob = 0 for bar, p in zip(post_bars, np.arange(0, 1, 0.01)): prob = scipy.stats.binom(50, p).pmf(48) bar.stretch(prob, 1, about_edge=DOWN) total_prob += 0.01 * prob post_bars.stretch(1 / total_prob, 1, about_edge=DOWN) post_bars.stretch(0.25, 1, about_edge=DOWN) # Lie to fit on screen... post_bars.set_color(MAROON_D) post_bars.set_fill(opacity=0.8) brace = Brace(p_label, DOWN) post_word = brace.get_text("Posterior") post_word.scale(1.25, about_edge=UP) post_word.set_color(MAROON_D) self.play( ReplacementTransform( bars.copy().set_opacity(0), post_bars, ), GrowFromCenter(brace), FadeIn(post_word, 0.25 * UP) ) self.wait() self.play( eq.set_opacity, 1, likelihood_label.set_opacity, 1, ) self.wait() data = get_check_count_label(48, 2) data.scale(1.5) data.next_to(likelihood_label, DOWN, buff=2, aligned_edge=LEFT) data_arrow = Arrow( likelihood_label[1].get_bottom(), data.get_top() ) data_arrow.set_color(GREEN) self.play( GrowArrow(data_arrow), GrowFromPoint(data, data_arrow.get_start()), ) self.wait() self.play(FadeOut(data_arrow)) self.play( over.set_opacity, 1, p_data_label.set_opacity, 1, ) self.wait() self.play( FadeOut(brace), FadeOut(post_word), FadeOut(post_bars), FadeOut(data), p_label.set_opacity, 0.1, eq.set_opacity, 0.1, likelihood_label.set_opacity, 0.1, over.set_opacity, 0.1, p_data_label.set_opacity, 0.1, ) self.bayes = VGroup( p_label, eq, prior_label, likelihood_label, over, p_data_label ) self.data = data def parallel_universes(self): bars = self.bars cols = VGroup() squares = VGroup() sample_colors = color_gradient( [GREEN_C, GREEN_D, GREEN_E], 100 ) for bar in bars: n_rows = 12 col = VGroup() for x in range(n_rows): square = Rectangle( width=bar.get_width(), height=bar.get_height() / n_rows, ) square.set_stroke(width=0) square.set_fill(opacity=1) square.set_color(random.choice(sample_colors)) col.add(square) squares.add(square) col.arrange(DOWN, buff=0) col.move_to(bar) cols.add(col) squares.shuffle() self.play( LaggedStartMap( VFadeInThenOut, squares, lag_ratio=0.005, run_time=3 ) ) self.remove(squares) squares.set_opacity(1) self.wait() example_col = cols[95] self.play( bars.set_opacity, 0.25, FadeIn(example_col, lag_ratio=0.1), ) self.wait() dist = scipy.stats.binom(50, 0.95) for x in range(12): square = random.choice(example_col).copy() square.set_fill(opacity=0) square.set_stroke(YELLOW, 2) self.add(square) nc = dist.ppf(random.random()) data = get_check_count_label(nc, 50 - nc) data.next_to(example_col, UP) self.add(square, data) self.wait(0.5) self.remove(square, data) self.wait() self.data.set_opacity(1) self.play( FadeIn(self.data), FadeOut(example_col), self.bayes[3].set_opacity, 1, ) self.wait() def update_from_data(self): bars = self.bars data = self.data bayes = self.bayes new_bars = bars.copy() new_bars.set_stroke(opacity=1) new_bars.set_fill(opacity=0.8) for bar, p in zip(new_bars, np.arange(0, 1, 0.01)): dist = scipy.stats.binom(50, p) scalar = dist.pmf(48) bar.stretch(scalar, 1, about_edge=DOWN) self.play( ReplacementTransform( bars.copy().set_opacity(0), new_bars ), bars.set_fill, {"opacity": 0.1}, bars.set_stroke, {"opacity": 0.1}, run_time=2, ) # Show example bar bar95 = VGroup( bars[95].copy(), new_bars[95].copy() ) bar95.save_state() bar95.generate_target() bar95.target.scale(2) bar95.target.next_to(bar95, UP, LARGE_BUFF) bar95.target.set_stroke(BLUE, 3) ex_label = OldTex("s", "=", "0.95") ex_label.set_color(YELLOW) ex_label.next_to(bar95.target, DOWN, submobject_to_align=ex_label[-1]) highlight = SurroundingRectangle(bar95, buff=0) highlight.set_stroke(YELLOW, 2) self.play(FadeIn(highlight)) self.play( MoveToTarget(bar95), FadeInFromDown(ex_label), data.shift, LEFT, ) self.wait() side_brace = Brace(bar95[1], RIGHT, buff=SMALL_BUFF) side_label = side_brace.get_text("0.26", buff=SMALL_BUFF) self.play( GrowFromCenter(side_brace), FadeIn(side_label) ) self.wait() self.play( FadeOut(side_brace), FadeOut(side_label), FadeOut(ex_label), ) self.play( bar95.restore, bar95.set_opacity, 0, ) for bar in bars[94:80:-1]: highlight.move_to(bar) self.wait(0.5) self.play(FadeOut(highlight)) self.wait() # Emphasize formula terms tops = VGroup() for bar, new_bar in zip(bars, new_bars): top = Line(bar.get_corner(UL), bar.get_corner(UR)) top.set_stroke(YELLOW, 2) top.generate_target() top.target.move_to(new_bar, UP) tops.add(top) rect = SurroundingRectangle(bayes[2]) rect.set_stroke(YELLOW, 1) rect.target = SurroundingRectangle(bayes[3]) rect.target.match_style(rect) self.play( ShowCreation(rect), ShowCreation(tops), ) self.wait() self.play( LaggedStartMap( MoveToTarget, tops, run_time=2, lag_ratio=0.02, ), MoveToTarget(rect), ) self.play(FadeOut(tops)) self.wait() # Show alternate priors axes = self.axes bar_groups = VGroup() for bar, new_bar in zip(bars, new_bars): bar_groups.add(VGroup(bar, new_bar)) bar_groups.save_state() for a, b in [(5, 2), (7, 1)]: dist = scipy.stats.beta(a, b) for bar, saved in zip(bar_groups, bar_groups.saved_state): bar.target = saved.copy() height = get_norm(axes.c2p(0.1 * dist.pdf(bar[0].x)) - axes.c2p(0, 0)) height = max(height, 1e-6) bar.target.set_height(height, about_edge=DOWN, stretch=True) self.play(LaggedStartMap(MoveToTarget, bar_groups, lag_ratio=0)) self.wait() self.play(Restore(bar_groups)) self.wait() # Rescale ex_p_label = OldTex( "P(s = 0.95 | 00000000) = ", tex_to_color_map={ "s = 0.95": YELLOW, "00000000": WHITE, } ) ex_p_label.scale(1.5) ex_p_label.next_to(bars, UP, LARGE_BUFF) ex_p_label.align_to(bayes, LEFT) template = ex_p_label.get_part_by_tex("00000000") template.set_opacity(0) highlight = SurroundingRectangle(new_bars[95], buff=0) highlight.set_stroke(YELLOW, 1) self.remove(data) self.play( FadeIn(ex_p_label), VFadeOut(data[0]), data[1:].move_to, template, FadeIn(highlight) ) self.wait() numer = new_bars[95].copy() numer.set_stroke(YELLOW, 1) denom = new_bars[80:].copy() h_line = Line(LEFT, RIGHT) h_line.set_width(3) h_line.set_stroke(width=2) h_line.next_to(ex_p_label, RIGHT) self.play( numer.next_to, h_line, UP, denom.next_to, h_line, DOWN, ShowCreation(h_line), ) self.wait() self.play( denom.space_out_submobjects, rate_func=there_and_back ) self.play( bayes[4].set_opacity, 1, bayes[5].set_opacity, 1, FadeOut(rect), ) self.wait() # Rescale self.play( FadeOut(highlight), FadeOut(ex_p_label), FadeOut(data), FadeOut(h_line), FadeOut(numer), FadeOut(denom), bayes.set_opacity, 1, ) new_bars.unlock_shader_data() self.remove(new_bars, *new_bars) self.play( new_bars.set_height, 5, {"about_edge": DOWN, "stretch": True}, new_bars.set_color, MAROON_D, ) self.wait() class UniverseOf95Percent(WhatsTheModel): CONFIG = {"s": 0.95} def construct(self): self.introduce_buyer_and_seller() for m, v in [(self.seller, RIGHT), (self.buyer, LEFT)]: m.shift(v) m.label.shift(v) pis = VGroup(self.seller, self.buyer) label = get_prob_positive_experience_label(True, True) label[-1].set_value(self.s) label.set_height(1) label.next_to(pis, UP, LARGE_BUFF) self.add(label) for x in range(4): self.play(*self.experience_animations( self.seller, self.buyer, arc=30 * DEGREES, p=self.s )) self.embed() class UniverseOf50Percent(UniverseOf95Percent): CONFIG = {"s": 0.5} class OpenAndCloseAsideOnPdfs(Scene): def construct(self): labels = VGroup( OldTexText("$\\langle$", "Aside on", " pdfs", "$\\rangle$"), OldTexText("$\\langle$/", "Aside on", " pdfs", "$\\rangle$"), ) labels.set_width(FRAME_WIDTH / 2) for label in labels: label.set_color_by_tex("pdfs", YELLOW) self.play(FadeInFromDown(labels[0])) self.wait() self.play(Transform(*labels)) self.wait() class BayesRuleWithPdf(ShowLimitToPdf): def construct(self): # Axes axes = self.get_axes() sf = 1.5 axes.y_axis.stretch(sf, 1, about_point=axes.c2p(0, 0)) for number in axes.y_axis.numbers: number.stretch(1 / sf, 1) self.add(axes) # Formula bayes = self.get_formula() post = bayes[:5] eq = bayes[5] prior = bayes[6:9] likelihood = bayes[9:14] over = bayes[14] p_data = bayes[15:] self.play(FadeInFromDown(bayes)) self.wait() # Prior prior_graph = get_beta_graph(axes, 0, 0) prior_graph_top = Line( prior_graph.get_corner(UL), prior_graph.get_corner(UR), ) prior_graph_top.set_stroke(YELLOW, 3) bayes.save_state() bayes.set_opacity(0.2) prior.set_opacity(1) self.play( Restore(bayes, rate_func=reverse_smooth), FadeIn(prior_graph), ShowCreation(prior_graph_top), ) self.play(FadeOut(prior_graph_top)) self.wait() # Scale Down nh = 1 nt = 2 scaled_graph = axes.get_graph( lambda x: scipy.stats.binom(3, x).pmf(1) + 1e-6 ) scaled_graph.set_stroke(GREEN) scaled_region = get_region_under_curve(axes, scaled_graph, 0, 1) def to_uniform(p, axes=axes): return axes.c2p( axes.x_axis.p2n(p), int(axes.y_axis.p2n(p) != 0), ) scaled_region.set_fill(opacity=0.75) scaled_region.save_state() scaled_region.apply_function(to_uniform) self.play( Restore(scaled_region), UpdateFromAlphaFunc( scaled_region, lambda m, a: m.set_opacity(a * 0.75), ), likelihood.set_opacity, 1, ) self.wait() # Rescale new_graph = get_beta_graph(axes, nh, nt) self.play( ApplyMethod( scaled_region.set_height, new_graph.get_height(), {"about_edge": DOWN, "stretch": True}, run_time=2, ), over.set_opacity, 1, p_data.set_opacity, 1, ) self.wait() self.play( post.set_opacity, 1, eq.set_opacity, 1, ) self.wait() # Use lower case new_bayes = self.get_formula(lowercase=True) new_bayes.replace(bayes, dim_to_match=0) rects = VGroup( SurroundingRectangle(new_bayes[0][0]), SurroundingRectangle(new_bayes[6][0]), ) rects.set_stroke(YELLOW, 3) self.remove(bayes) bayes = self.get_formula() self.add(bayes) self.play(Transform(bayes, new_bayes)) self.play(ShowCreationThenFadeOut(rects)) def get_formula(self, lowercase=False): p_sym = "p" if lowercase else "P" bayes = OldTex( p_sym + "({s} \\,|\\, \\text{data})", "=", "{" + p_sym + "({s})", "P(\\text{data} \\,|\\, {s})", "\\over", "P(\\text{data})", tex_to_color_map={ "{s}": YELLOW, "\\text{data}": GREEN, } ) bayes.set_height(1.5) bayes.to_edge(UP) return bayes class TalkThroughCoinExample(ShowBayesianUpdating): def construct(self): # Setup axes = self.get_axes() x_label = OldTex("x") x_label.next_to(axes.x_axis.get_end(), UR, MED_SMALL_BUFF) axes.add(x_label) p_label, prob, prob_box = self.get_probability_label() prob_box_x = x_label.copy().move_to(prob_box) self.add(axes) self.add(p_label) self.add(prob_box) self.wait() q_marks = prob_box[1] prob_box.remove(q_marks) self.play( FadeOut(q_marks), TransformFromCopy(x_label, prob_box_x) ) prob_box.add(prob_box_x) # Setup coins bool_values = (np.random.random(100) < self.true_p) bool_values[:5] = [True, False, True, True, False] coins = self.get_coins(bool_values) coins.next_to(axes.y_axis, RIGHT, MED_LARGE_BUFF) coins.to_edge(UP) # Random coin rows = VGroup() for x in range(5): row = self.get_coins(np.random.random(10) < self.true_p) row.arrange(RIGHT, buff=MED_LARGE_BUFF) row.set_width(6) row.move_to(UP) rows.add(row) last_row = VMobject() for row in rows: self.play( FadeOut(last_row, DOWN), FadeIn(row, lag_ratio=0.1) ) last_row = row self.play(FadeOut(last_row, DOWN)) # Uniform pdf region = get_beta_graph(axes, 0, 0) graph = Line( region.get_corner(UL), region.get_corner(UR), ) func_label = OldTex("f(x) =", "1") func_label.next_to(graph, UP) self.play( FadeIn(func_label, lag_ratio=0.1), ShowCreation(graph), ) self.add(region, graph) self.play(FadeIn(region)) self.wait() # First flip coin = coins[0] arrow = Vector(0.5 * UP) arrow.next_to(coin, DOWN, SMALL_BUFF) data_label = OldTexText("New data") data_label.set_height(0.25) data_label.next_to(arrow, DOWN) data_label.shift(0.5 * RIGHT) self.play( FadeIn(coin, DOWN), GrowArrow(arrow), Write(data_label, run_time=1) ) self.wait() # Show Bayes rule bayes = OldTex( "p({x} | \\text{data})", "=", "p({x})", "{P(\\text{data} | {x})", "\\over", "P(\\text{data})", tex_to_color_map={ "{x}": WHITE, "\\text{data}": GREEN, } ) bayes.next_to(func_label, UP, LARGE_BUFF, LEFT) likelihood = bayes[9:14] p_data = bayes[15:] likelihood_rect = SurroundingRectangle(likelihood, buff=0.05) likelihood_rect.save_state() p_data_rect = SurroundingRectangle(p_data, buff=0.05) likelihood_x_label = OldTex("x") likelihood_x_label.next_to(likelihood_rect, UP) self.play(FadeInFromDown(bayes)) self.wait() self.play(ShowCreation(likelihood_rect)) self.wait() self.play(TransformFromCopy(likelihood[-2], likelihood_x_label)) self.wait() # Scale by x times_x = OldTex("\\cdot \\, x") times_x.next_to(func_label, RIGHT, buff=0.2) new_graph = axes.get_graph(lambda x: x) sub_region = get_region_under_curve(axes, new_graph, 0, 1) self.play( Write(times_x), Transform(graph, new_graph), ) self.play( region.set_opacity, 0.5, FadeIn(sub_region), ) self.wait() # Show example scalings low_x = 0.1 high_x = 0.9 lines = VGroup() for x in [low_x, high_x]: lines.add(Line(axes.c2p(x, 0), axes.c2p(x, 1))) lines.set_stroke(YELLOW, 3) for x, line in zip([low_x, high_x], lines): self.play(FadeIn(line)) self.play(line.scale, x, {"about_edge": DOWN}) self.wait() self.play(FadeOut(lines)) # Renormalize self.play( FadeOut(likelihood_x_label), ReplacementTransform(likelihood_rect, p_data_rect), ) self.wait() one = func_label[1] two = OldTex("2") two.move_to(one, LEFT) self.play( FadeOut(region), sub_region.stretch, 2, 1, {"about_edge": DOWN}, sub_region.set_color, BLUE, graph.stretch, 2, 1, {"about_edge": DOWN}, FadeInFromDown(two), FadeOut(one, UP), ) region = sub_region func_label = VGroup(func_label[0], two, times_x) self.add(func_label) self.play(func_label.shift, 0.5 * UP) self.wait() const = OldTex("C") const.scale(0.9) const.move_to(two, DR) const.shift(0.07 * RIGHT) self.play( FadeOut(two, UP), FadeIn(const, DOWN) ) self.remove(func_label) func_label = VGroup(func_label[0], const, times_x) self.add(func_label) self.play(FadeOut(p_data_rect)) self.wait() # Show tails coin = coins[1] self.play( arrow.next_to, coin, DOWN, SMALL_BUFF, MaintainPositionRelativeTo(data_label, arrow), FadeInFromDown(coin), ) self.wait() to_prior_arrow = Arrow( func_label[0][3], bayes[6], max_tip_length_to_length_ratio=0.15, stroke_width=3, ) to_prior_arrow.set_color(RED) self.play(Indicate(func_label, scale_factor=1.2, color=RED)) self.play(ShowCreation(to_prior_arrow)) self.wait() self.play(FadeOut(to_prior_arrow)) # Scale by (1 - x) eq_1mx = OldTex("(1 - x)") dot = OldTex("\\cdot") rhs_part = VGroup(dot, eq_1mx) rhs_part.arrange(RIGHT, buff=0.2) rhs_part.move_to(func_label, RIGHT) l_1mx = eq_1mx.copy() likelihood_rect.restore() l_1mx.next_to(likelihood_rect, UP, SMALL_BUFF) self.play( ShowCreation(likelihood_rect), FadeIn(l_1mx, 0.5 * DOWN), ) self.wait() self.play(ShowCreationThenFadeOut(Underline(p_label))) self.play(Indicate(coins[1])) self.wait() self.play( TransformFromCopy(l_1mx, eq_1mx), FadeIn(dot, RIGHT), func_label.next_to, dot, LEFT, 0.2, ) scaled_graph = axes.get_graph(lambda x: 2 * x * (1 - x)) scaled_region = get_region_under_curve(axes, scaled_graph, 0, 1) self.play(Transform(graph, scaled_graph)) self.play(FadeIn(scaled_region)) self.wait() # Renormalize self.remove(likelihood_rect) self.play( TransformFromCopy(likelihood_rect, p_data_rect), FadeOut(l_1mx) ) new_graph = get_beta_graph(axes, 1, 1) group = VGroup(graph, scaled_region) self.play( group.set_height, new_graph.get_height(), {"about_edge": DOWN, "stretch": True}, group.set_color, BLUE, FadeOut(region), ) region = scaled_region self.play(FadeOut(p_data_rect)) self.wait() self.play(ShowCreationThenFadeAround(const)) # Repeat exp1 = Integer(1) exp1.set_height(0.2) exp1.move_to(func_label[2].get_corner(UR), DL) exp1.shift(0.02 * DOWN + 0.07 * RIGHT) exp2 = exp1.copy() exp2.move_to(eq_1mx.get_corner(UR), DL) exp2.shift(0.1 * RIGHT) exp2.align_to(exp1, DOWN) shift_vect = UP + 0.5 * LEFT VGroup(exp1, exp2).shift(shift_vect) self.play( FadeIn(exp1, DOWN), FadeIn(exp2, DOWN), VGroup(func_label, dot, eq_1mx).shift, shift_vect, bayes.scale, 0.5, bayes.next_to, p_label, DOWN, LARGE_BUFF, {"aligned_edge": RIGHT}, ) nh = 1 nt = 1 for coin, is_heads in zip(coins[2:10], bool_values[2:10]): self.play( arrow.next_to, coin, DOWN, SMALL_BUFF, MaintainPositionRelativeTo(data_label, arrow), FadeIn(coin, DOWN), ) if is_heads: nh += 1 old_exp = exp1 else: nt += 1 old_exp = exp2 new_exp = old_exp.copy() new_exp.increment_value(1) dist = scipy.stats.beta(nh + 1, nt + 1) new_graph = axes.get_graph(dist.pdf) new_region = get_region_under_curve(axes, new_graph, 0, 1) new_region.match_style(region) self.play( FadeOut(graph), FadeOut(region), FadeIn(new_graph), FadeIn(new_region), FadeOut(old_exp, MED_SMALL_BUFF * UP), FadeIn(new_exp, MED_SMALL_BUFF * DOWN), ) graph = new_graph region = new_region self.remove(new_exp) self.add(old_exp) old_exp.increment_value() self.wait() if coin is coins[4]: area_label = OldTexText("Area = 1") area_label.move_to(axes.c2p(0.6, 0.8)) self.play(GrowFromPoint( area_label, const.get_center() )) class PDefectEqualsQmark(Scene): def construct(self): label = OldTex( "P(\\text{Defect}) = ???", tex_to_color_map={ "\\text{Defect}": RED, } ) self.play(FadeIn(label, DOWN)) self.wait() class UpdateOnceWithBinomial(TalkThroughCoinExample): def construct(self): # Fair bit of copy-pasting from above. If there's # time, refactor this properly # Setup axes = self.get_axes() x_label = OldTex("x") x_label.next_to(axes.x_axis.get_end(), UR, MED_SMALL_BUFF) axes.add(x_label) p_label, prob, prob_box = self.get_probability_label() prob_box_x = x_label.copy().move_to(prob_box) q_marks = prob_box[1] prob_box.remove(q_marks) prob_box.add(prob_box_x) self.add(axes) self.add(p_label) self.add(prob_box) # Coins bool_values = (np.random.random(100) < self.true_p) bool_values[:5] = [True, False, True, True, False] coins = self.get_coins(bool_values) coins.next_to(axes.y_axis, RIGHT, MED_LARGE_BUFF) coins.to_edge(UP) self.add(coins[:10]) # Uniform pdf region = get_beta_graph(axes, 0, 0) graph = axes.get_graph( lambda x: 1, min_samples=30, ) self.add(region, graph) # Show Bayes rule bayes = OldTex( "p({x} | \\text{data})", "=", "p({x})", "{P(\\text{data} | {x})", "\\over", "P(\\text{data})", tex_to_color_map={ "{x}": WHITE, "\\text{data}": GREEN, } ) bayes.move_to(axes.c2p(0, 2.5)) bayes.align_to(coins, LEFT) likelihood = bayes[9:14] # likelihood_rect = SurroundingRectangle(likelihood, buff=0.05) self.add(bayes) # All data at once brace = Brace(coins[:10], DOWN) all_data_label = brace.get_text("One update from all data") self.wait() self.play( GrowFromCenter(brace), FadeIn(all_data_label, 0.2 * UP), ) self.wait() # Binomial formula nh = sum(bool_values[:10]) nt = sum(~bool_values[:10]) likelihood_brace = Brace(likelihood, UP) t2c = { str(nh): BLUE, str(nt): RED, } binom_formula = OldTex( "{10 \\choose ", str(nh), "}", "x^{", str(nh), "}", "(1-x)^{" + str(nt) + "}", tex_to_color_map=t2c, ) binom_formula[0][-1].set_color(BLUE) binom_formula[1].set_color(WHITE) binom_formula.set_width(likelihood_brace.get_width() + 0.5) binom_formula.next_to(likelihood_brace, UP) self.play( TransformFromCopy(brace, likelihood_brace), FadeOut(all_data_label), FadeIn(binom_formula) ) self.wait() # New plot rhs = OldTex( "C \\cdot", "x^{", str(nh), "}", "(1-x)^{", str(nt), "}", tex_to_color_map=t2c ) rhs.next_to(bayes[:5], DOWN, LARGE_BUFF, aligned_edge=LEFT) eq = OldTex("=") eq.rotate(90 * DEGREES) eq.next_to(bayes[:5], DOWN, buff=0.35) dist = scipy.stats.beta(nh + 1, nt + 1) new_graph = axes.get_graph(dist.pdf) new_graph.shift(1e-6 * UP) new_graph.set_stroke(WHITE, 1, opacity=0.5) new_region = get_region_under_curve(axes, new_graph, 0, 1) new_region.match_style(region) new_region.set_opacity(0.75) self.add(new_region, new_graph, bayes) self.play( FadeOut(graph), FadeOut(region), FadeIn(new_graph), FadeIn(new_region), run_time=1, ) self.play( Write(eq), FadeIn(rhs, UP) ) self.wait()
from manim_imports_ext import * def get_value_grid(n_rows=6, n_cols=6): random.seed(1) boxes = VGroup(*[Square() for x in range(n_rows * n_cols)]) array = np.array(list(boxes)).reshape((n_rows, n_cols)) boxes.array = array boxes.arrange_in_grid(n_rows, n_cols, buff=0) boxes.set_height(5) boxes.to_edge(DOWN) boxes.shift(UP) boxes.set_stroke(BLUE_D, 2) for box in boxes: value = DecimalNumber( np.round(random.random(), 1), num_decimal_places=1 ) box.set_fill(WHITE, opacity=0.8 * value.get_value()) box.value = value value.match_height(box) value.scale(0.3) value.move_to(box) box.add(value) boxes.array[5, 1].value.set_value(0.4) # Tweaking for examples return boxes def highlight_box(box, opacity=0.5, color=PINK): box.set_stroke(color, opacity) box[1].set_stroke(BLACK, 2, background=True) return box def get_box_highlight(box, color=PINK, stroke_width=8, opacity=0.25): highlight = SurroundingRectangle(box, buff=0) highlight.set_fill(color, opacity) highlight.set_stroke(color, stroke_width) return highlight class GreedyAlgorithm(Scene): def construct(self): n_rows, n_cols = 6, 6 boxes = get_value_grid(n_rows, n_cols) self.add(boxes) last_sum_term = boxes[0].value.copy() last_sum_term.to_edge(UP) last_sum_term.set_x(-5) sum_terms = VGroup() to_fade = VGroup() (i, j) = (0, 3) while i < n_rows: box = boxes.array[i, j] value = box.value box_highlight = get_box_highlight(box) sum_term = VGroup( OldTex("+"), value.copy() ) if i == 0: sum_term[0].set_opacity(0) sum_term.arrange(RIGHT, buff=0.2) sum_term.next_to(last_sum_term, RIGHT, buff=0.2) sum_terms.add(sum_term) last_sum_term = sum_term self.play( FadeIn(box_highlight), FadeIn(sum_term), *map(FadeOut, to_fade) ) i += 1 # Find new j if i < n_rows: next_boxes = VGroup() for nj in range(j - 1, j + 2): next_boxes.add(boxes.array[i, clip(nj, 0, n_cols - 1)]) next_highlights = VGroup() for nb in next_boxes: next_highlights.add(get_box_highlight(nb, stroke_width=4)) self.play(FadeIn(next_highlights)) min_box_index = np.argmin([b.value.get_value() for b in next_boxes]) j = j - 1 + min_box_index j = clip(j, 0, n_cols - 1) # Am I doing this right? to_fade = next_highlights final_sum = VGroup( OldTex("="), DecimalNumber( sum([np.round(st[1].get_value(), 1) for st in sum_terms]), height=sum_terms.get_height(), num_decimal_places=1, ).set_color(YELLOW) ) final_sum.arrange(RIGHT, buff=0.2) final_sum.next_to(sum_terms, RIGHT, buff=0.2) self.play(Write(final_sum)) self.wait() class RecrusiveExhaustiveSearch(Scene): def construct(self): n_rows = 6 n_cols = 6 boxes = get_value_grid(n_rows, n_cols) self.add(boxes) seam = [ (i, 3) for i in range(n_rows) ] def get_seam_sum(seam): terms = VGroup(*[boxes.array[i, j].value.copy() for (i, j) in seam]) row = VGroup() for term in terms[:-1]: row.add(term) row.add(OldTex("+")) row.add(terms[-1]) row.add(OldTex("=")) sum_term = DecimalNumber(sum([t.get_value() for t in terms]), num_decimal_places=1) sum_term.match_height(terms[0]) sum_term.set_color(YELLOW) row.add(sum_term) row.arrange(RIGHT, buff=0.15) row.to_edge(UP) return row def get_highlighted_seam(seam): return VGroup(*[ get_box_highlight(boxes.array[i, j]) for (i, j) in seam ]) def get_all_seams(seam_starts, n_rows=n_rows, n_cols=n_cols): if seam_starts[0][-1][0] == n_rows - 1: return seam_starts new_seams = [] for seam in seam_starts: i, j = seam[-1] # Adjacent j values below (i, j) js = [] if j > 0: js.append(j - 1) js.append(j) if j < n_cols - 1: js.append(j + 1) for j_prime in js: new_seams.append([*seam, (i + 1, j_prime)]) return get_all_seams(new_seams, n_rows, n_cols) all_seams = get_all_seams([[(0, 3)]]) curr_min_energy = np.inf curr_best_seam = VGroup() for seam in all_seams: ss = get_seam_sum(seam) hs = get_highlighted_seam(seam) energy = ss[-1].get_value() if energy < curr_min_energy: curr_min_energy = energy curr_best_seam = VGroup(ss, hs) self.add(ss, hs) self.wait(0.05) self.remove(ss, hs) self.add(curr_best_seam) self.wait() class DynamicProgrammingApproachSearch(Scene): def construct(self): n_rows = 6 n_cols = 6 boxes = get_value_grid(n_rows, n_cols) boxes.to_corner(DL) boxes.shift(UP) self.add(boxes) new_boxes = get_value_grid(n_rows, n_cols) new_boxes.to_corner(DR) new_boxes.shift(UP) for box in new_boxes: box.set_fill(opacity=0) box.value.set_fill(opacity=0) self.add(new_boxes) left_title = OldTexText("Energy") right_title = OldTexText("Minimal energy to bottom") left_title.next_to(boxes, UP) right_title.next_to(new_boxes, UP) self.add(left_title, right_title) op_factor = 0.5 movers = VGroup() for j in range(n_cols): box = boxes.array[n_rows - 1, j] new_box = new_boxes.array[n_rows - 1, j] new_box.generate_target() new_box.target.match_style(box) new_box.target.set_fill(TEAL, opacity=op_factor * new_box.value.get_value()) new_box.target[1].set_fill(WHITE, 1) movers.add(new_box) self.play(LaggedStartMap(MoveToTarget, movers)) self.wait() for i in range(n_rows - 2, -1, -1): for j in range(n_cols): box = boxes.array[i, j] new_box = new_boxes.array[i, j] box_highlight = get_box_highlight(box) new_box_highlight = get_box_highlight(new_box) boxes_below = [ new_boxes.array[i + 1, j] for j in range(j - 1, j + 2) if 0 <= j < n_cols ] index = np.argmin([bb.value.get_value() for bb in boxes_below]) low_box = boxes_below[index] low_box_highlight = get_box_highlight(low_box, stroke_width=3) low_box_highlight.fade(0.5) new_box.value.set_value(new_box.value.get_value() + low_box.value.get_value()) new_box.generate_target() new_box.target.set_fill(TEAL, opacity=op_factor * new_box.value.get_value()) new_box.target[1].set_fill(WHITE, 1) self.play( FadeIn(box_highlight), FadeIn(new_box_highlight), FadeIn(low_box_highlight), MoveToTarget(new_box), ) self.play( FadeOut(box_highlight), FadeOut(new_box_highlight), FadeOut(low_box_highlight), )
from manim_imports_ext import * def get_value_grid(n_rows=10, n_cols=10): boxes = VGroup(*[Square() for x in range(n_rows * n_cols)]) boxes.arrange_in_grid(n_rows, n_cols, buff=0) boxes.set_height(6) boxes.set_style(GREY_B, 2) for box in boxes: value = DecimalNumber(random.random(), num_decimal_places=1) box.value = value value.set_height(0.7 * box.get_height()) value.move_to(box) box.add(value) return boxes class GreedyAlgorithm(Scene): def construct(self): value_grid = get_value_grid() self.add(value_grid) class RecrusiveExhaustiveSearch(Scene): def construct(self): pass class DynamicProgrammingApproachSearch(Scene): def construct(self): pass
from manim_imports_ext import * class IntroduceDFT(Scene): def construct(self): # Create signal N = 8 np.random.seed(2) signal = 3 * np.random.random(N) signal[signal < 0.5] = 0.5 axes = Axes( (0, 8), (0, 2, 0.5), width=12, height=4, ) axes.x_axis.add_numbers() axes.y_axis.add_numbers(excluding=[0], num_decimal_places=1) vectors = VGroup(*( Arrow(axes.c2p(x, 0), axes.c2p(x, signal[x]), buff=0) for x in range(N) )) vectors.set_submobject_colors_by_gradient(BLUE, YELLOW) vectors.set_stroke(BLACK, 2, background=True) self.add(axes) self.play(LaggedStartMap(GrowArrow, vectors, lag_ratio=0.3)) self.wait() # Label signal s_title = OldTexText("List of value: ", "$s$", font_size=72) s_title.to_edge(UP) self.play(FadeIn(s_title, UP)) self.wait() s_labels = VGroup(*( OldTex("s", f"[{x}]") for x in range(N) )) for label, vector in zip(s_labels, vectors): label.next_to(vector, UP, SMALL_BUFF) label.match_color(vector) label.add_background_rectangle() s_labels[0].shift(MED_SMALL_BUFF * RIGHT) self.play( LaggedStartMap(FadeIn, s_labels), LaggedStart(*( Transform(s_title[1].copy(), label[1].copy(), remover=True) for label in s_labels )), lag_ratio=0.3, run_time=2, ) self.wait() # Show zeroth DFT element s_labels.generate_target() plusses = VGroup() rhs = VGroup() for label in s_labels.target: plus = OldTex("+") label.next_to(plusses, RIGHT, buff=0.3) plus.next_to(label, buff=0.3) plusses.add(plus) rhs.add(label, plus) plusses[-1].scale(0) lhs = OldTex("\\hat s", "[0]", "=") lhs.to_corner(UL) rhs.next_to(lhs, RIGHT) self.play( FadeOut(s_title, UP), Write(lhs), Write(plusses), MoveToTarget(s_labels) ) self.wait() vectors.generate_target() vectors.target.rotate(-90 * DEGREES) vectors.target.arrange(RIGHT, buff=0) vectors.target.set_width(FRAME_WIDTH - 3) vectors.target.move_to(DOWN) self.play( FadeOut(axes), MoveToTarget(vectors), ) self.wait() # Add plane plane = ComplexPlane(x_range=(-2, 2), y_range=(-2, 2)) plane.set_height(5) plane.to_edge(DOWN) plane.add_coordinate_labels() plane.coordinate_labels[1].scale(0) sf = signal[0] * get_norm(plane.n2p(1) - plane.n2p(0)) / vectors[0].get_length() vectors.generate_target() for n, vector in enumerate(vectors.target): vector.scale(sf) vector.set_angle(-n * TAU / N) vector.shift(plane.n2p(0) - vector.get_start()) self.add(plane, vectors) self.play( Write(plane), MoveToTarget(vectors), ) # Write first DFT term lhs1 = OldTex("\\hat s", "[1]", "=") lhs1.next_to(lhs, DOWN, MED_LARGE_BUFF) rhs1 = VGroup() for n, s_term, plus in zip(it.count(), rhs[0::2], rhs[1::2]): new_s = s_term.copy() new_plus = plus.copy() top_clump = VGroup(s_term, plus) zeta = OldTex(f"\\zeta^{{{n}}}") zeta.add_background_rectangle() clump = VGroup(new_s, zeta, new_plus) clump.arrange(RIGHT, buff=0.15) clump.match_width(top_clump) clump.scale(1.1) clump.next_to(top_clump, DOWN, MED_LARGE_BUFF, LEFT) rhs1.add(*clump) for term in clump: term.save_state() new_s.replace(s_term) new_plus.replace(plus) zeta.replace(plus) zeta.set_opacity(0) self.play( TransformFromCopy(lhs, lhs1), *map(Restore, rhs1), ) self.wait() # Define zeta zeta = np.exp(complex(0, TAU / N)) zeta_power_vectors = VGroup(*( Arrow(plane.n2p(0), plane.n2p(zeta**(-n)), buff=0) for n in range(N) )) zeta_power_vectors.set_fill(GREY_B) unit_circle = Circle( radius=get_norm(plane.n2p(1) - plane.n2p(0)), ) unit_circle.move_to(plane) unit_circle.set_stroke(YELLOW, 2) zeta_label = OldTex( "\\zeta = e^{-2\\pi i / N}" ) zeta_label.to_edge(RIGHT, buff=LARGE_BUFF) self.play( vectors.set_opacity, 0.1, FadeIn(unit_circle), FadeIn(zeta_power_vectors[1]), Write(zeta_label), ) self.wait() zeta_powers = rhs1[1::3].copy() for z_power, vect in zip(zeta_powers, zeta_power_vectors): z_power.generate_target() z_power.target.next_to( vect, np.round(vect.get_vector(), 2), buff=SMALL_BUFF ) kw = { "lag_ratio": 0.5, "run_time": 3, } self.play( LaggedStartMap(MoveToTarget, zeta_powers, **kw), LaggedStartMap(FadeIn, zeta_power_vectors, **kw), Animation(zeta_power_vectors[1].copy(), remover=True), plane.coordinate_labels.set_opacity, 0, ) self.wait() self.play( FadeOut(zeta_powers), FadeOut(zeta_power_vectors), vectors.set_opacity, 1, plane.coordinate_labels.set_opacity, 1, ) self.wait() # Show cosine example cos_signal = np.cos(np.arange(0, TAU, TAU / N)) + 1.5 sin_signal = np.sin(np.arange(0, TAU, TAU / N)) + 1.5 neg_cos_signal = -np.sin(np.arange(0, TAU, TAU / N)) + 1.5 side_axes = Axes( (0, 8), (0, 3), width=3, height=2, axis_config={"include_tip": False} ) side_axes.to_edge(LEFT) side_axes.x_axis.add_numbers(height=0.2) side_vectors = VGroup(*( Arrow( side_axes.c2p(x, 0), side_axes.c2p(x, cos_signal[x]), buff=0, thickness=0.05 ) for x in range(N) )) side_vectors.match_style(vectors) side_vectors.set_stroke(background=True) vectors.generate_target() for x, vect in enumerate(vectors.target): vect.put_start_and_end_on( plane.n2p(0), plane.n2p(cos_signal[x] * zeta**(-x)), ) self.play( MoveToTarget(vectors), FadeIn(side_axes), FadeIn(side_vectors), ) self.wait() def change_signal(new_signal, omega=1): side_vectors.generate_target() vectors.generate_target() for x, sv, v in zip(it.count(), side_vectors.target, vectors.target): sv.put_start_and_end_on( side_axes.c2p(x, 0), side_axes.c2p(x, new_signal[x]), ) v.put_start_and_end_on( plane.n2p(0), plane.n2p(new_signal[x] * zeta**(-omega * x)), ) self.play( MoveToTarget(vectors), MoveToTarget(side_vectors), ) change_signal(sin_signal) self.wait() change_signal(neg_cos_signal) self.wait() change_signal(signal) self.wait() # Write second DFT term lhs2 = OldTex("\\hat s", "[2]", "=") lhs2.next_to(lhs1, DOWN, MED_LARGE_BUFF) rhs2 = rhs1.copy() rhs2.next_to(lhs2, RIGHT) for n, z_term in enumerate(rhs2[1::3]): new_exp = Integer(2 * n) new_exp.match_height(z_term[1][1]) new_exp.move_to(z_term[1][1], DL) z_term[1].replace_submobject(1, new_exp) plane_group = VGroup( plane, vectors, unit_circle, ) self.add(plane_group) self.play( TransformFromCopy(lhs1, lhs2), TransformFromCopy(rhs1, rhs2), plane_group.scale, 0.8, {"about_edge": DOWN}, zeta_label.shift, DOWN, FadeOut(side_axes), FadeOut(side_vectors), ) self.add(vectors) anims = [] for n, vect in enumerate(vectors): anims.append(Rotate( vect, -n * TAU / N, about_point=plane.n2p(0), )) self.play(*anims) self.wait() for n in range(N): rhs2.generate_target() rhs2.target.set_opacity(0.25) rhs2.target[3 * n:3 * (n + 1)].set_opacity(1) vectors.generate_target() vectors.target.set_opacity(0.1) vectors.target[n].set_opacity(1) self.play( MoveToTarget(rhs2), MoveToTarget(vectors), ) self.wait() self.play( vectors.set_opacity, 1, rhs2.set_opacity, 1, ) self.wait() # Show cos(2x) example cos2x_signal = np.cos(2 * np.arange(0, TAU, TAU / N)) + 1.5 sin2x_signal = np.sin(2 * np.arange(0, TAU, TAU / N)) + 1.5 VGroup(side_axes, side_vectors).shift(DOWN) self.play( FadeIn(side_axes), FadeIn(side_vectors), ) self.wait() change_signal(cos2x_signal, omega=2) self.wait() change_signal(sin2x_signal, omega=2) self.wait() change_signal(signal, omega=2) self.play(*map(FadeOut, (side_axes, side_vectors))) self.wait() # Show general formula dots = OldTex("\\vdots") dots.next_to(lhs2[:-1], DOWN, MED_LARGE_BUFF) formula = OldTex( "\\hat s[f] = " "\\sum_{n=0}^{N - 1} s[n] \\zeta^{f \\cdot n}" ) formula.next_to(dots, DOWN) formula.align_to(lhs2, LEFT) self.play( Write(dots), FadeIn(formula, DOWN), ) self.wait() # Cycle through omega_label = VGroup( OldTex("f = ", font_size=72), Integer(2), ) omega_label.arrange(RIGHT) omega_label.next_to(plane, LEFT, MED_LARGE_BUFF, aligned_edge=DOWN) self.play(FadeIn(omega_label)) for omega in range(3, 8): anims = [] for n, vect in enumerate(vectors): anims.append(Rotate( vect, -n * TAU / N, about_point=plane.n2p(0), )) new_count = omega_label[1].copy() new_count.set_value(omega) self.play( *anims, FadeIn(new_count, 0.5 * UP), FadeOut(omega_label[1], 0.5 * UP) ) omega_label.replace_submobject(1, new_count) self.wait()
from manim_imports_ext import * def box_blur(n): return np.ones((n, n)) / (n**2) class ConvolutionIntroduction(InteractiveScene): def construct(self): frame = self.camera.frame # Setup the pixel grids image = Image.open(get_full_raster_image_path("Mario")) arr = np.array(image) skip = 40 arr = arr[skip::skip, 0::skip, :3] height, width = arr.shape[:2] pixel_array = VGroup(*[ Square(fill_color=rgb_to_hex(arr[i, j] / 255), fill_opacity=1) for i in range(height) for j in range(width) ]) pixel_array.arrange_in_grid(height, width, buff=0) pixel_array.set_height(6) pixel_array.set_stroke(WHITE, 1) pixel_array.to_edge(LEFT, buff=LARGE_BUFF) new_array = pixel_array.copy() new_array.next_to(pixel_array, RIGHT, buff=2) new_array.set_fill(BLACK, 0) self.add(pixel_array) self.add(new_array) # Setup kernel def get_kernel_array(kernel, pixel_array=pixel_array, tex=None): kernel_array = VGroup() for row in kernel: for x in row: square = pixel_array[0].copy() square.set_fill(BLACK, 0) square.set_stroke(BLUE, 2) if tex: value = OldTex(tex) else: value = DecimalNumber(x, num_decimal_places=3) value.set_width(square.get_width() * 0.7) value.set_backstroke(BLACK, 3) value.move_to(square) square.add(value) kernel_array.add(square) kernel_array.arrange_in_grid(*kernel.shape, buff=0) kernel_array.move_to(pixel_array[0]) return kernel_array kernel = box_blur(3) kernel_array = get_kernel_array(kernel, tex="1 / 9") self.add(kernel_array) # Define step right_rect = new_array[0].copy() right_rect.set_stroke(BLUE, 2) self.add(right_rect) def step(pos=0): i = pos // width j = pos % width h, w = kernel.shape pixels = np.array([ square.data["fill_rgba"][0] for square in pixel_array ]).reshape((height, width, 4)) rgba = sum([ kernel[k, l] * pixels[i - k, j - l] for k in range(-(w // 2), w // 2 + 1) for l in range(-(h // 2), h // 2 + 1) if (0 <= i - k < pixels.shape[0]) and (0 <= j - l < pixels.shape[1]) ]) kernel_array.move_to(pixel_array[pos]) right_rect.move_to(new_array[pos]) new_array[pos].data["fill_rgba"][0] = rgba def walk(start, stop, time=5, surface=None): for n in range(start, stop): step(n) if surface is not None: surface.move_to(kernel_array, IN) self.wait(time / (stop - start), ignore_presenter_mode=True) # Setup zooming def zoom_to_kernel(): self.play( frame.animate.set_height(1.5 * kernel_array.get_height()).move_to(kernel_array), run_time=2 ) def zoom_to_new_pixel(): self.play( frame.animate.set_height(1.5 * kernel_array.get_height()).move_to(right_rect), run_time=2 ) def reset_frame(): self.play(frame.animate.to_default_state()) # Example walking last_i = 0 next_i = 151 walk(last_i, next_i, 5) self.wait() zoom_to_kernel() self.wait() reset_frame() zoom_to_new_pixel() self.wait() reset_frame() last_i = next_i next_i = 390 walk(151, next_i, 2) self.wait(0.5) zoom_to_kernel() self.wait() # reset_frame() zoom_to_new_pixel() self.wait() reset_frame() last_i = next_i next_i = len(pixel_array) walk(last_i, next_i, 10) self.wait() # Gauss kernel gauss_kernel = 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], ]) # Oh good, hard coded, I hope you feel happy with yourself. gauss_array = get_kernel_array(gauss_kernel) kernel_array.set_submobjects(gauss_array) kernel = gauss_kernel new_array.set_fill(BLACK, 0) walk(0, 206, time=5) # walk(0, 200, time=10) self.wait() zoom_to_kernel() self.wait() # Gauss surface 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) def update_surface(surface, kernel_array=kernel_array): surface.move_to(kernel_array, IN) update_surface(gaussian) self.play( FadeIn(gaussian), frame.animate.reorient(10, 70), run_time=3 ) self.wait() self.play( frame.animate.set_height(8).reorient(0, 60).set_x(-1), run_time=3, ) # More walking walk(200, len(pixel_array), time=10, surface=gaussian) self.wait() self.play(frame.animate.to_default_state(), run_time=2) self.wait()
from manim_imports_ext import * class Diffusion1D(Scene): CONFIG = { "n_dots": 100, "y_range": (0, 100, 10), "x_range": (-20, 20), "show_y_axis": False, "dot_radius": 0.07, "dot_opacity": 0.5, "dither_dots": True, "total_steps": 100, "clip_at_bounds": True, } def construct(self): y_range = self.y_range x_range = self.x_range # Set up axes axes = Axes( x_range=x_range, y_range=y_range, axis_config={ "stroke_width": 2, "include_tip": False, }, width=FRAME_WIDTH, height=FRAME_HEIGHT - 1, ) axes.x_axis.add_numbers( range(*x_range, 5) ) if self.show_y_axis: axes.y_axis.add_numbers( np.arange(*y_range) + y_range[2], height=0.2, ) else: axes.y_axis.scale(0, about_point=axes.c2p(0, 0)) axes.center() x_unit = axes.c2p(1, 0)[0] - axes.c2p(0, 0)[0] y_unit = axes.c2p(0, 1)[1] - axes.c2p(0, 0)[1] self.add(axes) # Set up time label time_label = self.get_time_label() self.add(time_label) # Set up dots (make generalizable) dots = self.get_dots() dots.move_to(axes.c2p(0, 0)) self.adjust_initial_dot_positions(dots, x_unit) self.add(dots) # Set up bars bars = VGroup() epsilon = 1e-6 for x in range(x_range[0], x_range[1] + 1): bar = Rectangle() bar.x = x bar.set_width(0.5 * x_unit) bar.set_height(epsilon, stretch=True) bar.move_to(axes.c2p(x, 0), DOWN) bars.add(bar) bars.set_fill(GREY, 0.8) bars.set_stroke(GREY_B, 0.2) def update_bars(bars, dots=dots, y_unit=y_unit, epsilon=epsilon): for bar in bars: count = 0 for dot in dots: if dot.x == bar.x: count += 1 bar.set_height( count * y_unit + epsilon, about_edge=bar.get_bottom(), stretch=True ) update_bars(bars, dots) self.add(bars, dots) # Include rule for updating def step(dots=dots, bars=bars, x_unit=x_unit, x_range=x_range, time_label=time_label): time_label[1].increment_value() for dot in dots: u = random.choice([-1, 1]) if self.clip_at_bounds: # Boundary condition if dot.x == x_range[0]: u = max(0, u) elif dot.x == x_range[1]: u = min(0, u) dot.shift(u * x_unit * RIGHT) dot.x += u update_bars(bars) # Let it play out. for t in range(self.total_steps): if t < 6: self.wait() else: self.wait(0.1) step() def get_time_label(self): time_label = VGroup( OldTexText("Time: "), Integer(0), ) time_label.arrange(RIGHT, aligned_edge=DOWN) time_label.to_corner(UR) time_label.shift(0.5 * LEFT) return time_label def get_dots(self): dots = VGroup(*[Dot() for x in range(self.n_dots)]) dots.set_height(2 * self.dot_radius) dots.set_fill(opacity=self.dot_opacity) for dot in dots: dot.x = 0 if self.dither_dots: dot.shift( self.dot_radius * random.random() * RIGHT, self.dot_radius * random.random() * UP ) dot.set_color(interpolate_color( BLUE_B, BLUE_D, random.random() )) return dots def adjust_initial_dot_positions(self, dots, x_unit): pass class Diffusion1DWith1Dot(Diffusion1D): CONFIG = { "n_dots": 1, "dot_radius": 0.1, "dot_opacity": 1, "dither_dots": False, } class Diffusion1DStepFunction(Diffusion1D): CONFIG = { "n_dots": 15000, "initial_range": (-20, 0), "y_range": (0, 1000, 100), "total_steps": 100, } def adjust_initial_dot_positions(self, dots, x_unit): initial_positions = list(range(*self.initial_range)) for n, dot in enumerate(dots): x = initial_positions[n % len(initial_positions)] dot.x = x dot.shift(x * x_unit * RIGHT) class Diffusion1DStepFunctionGraphed(Diffusion1DStepFunction): CONFIG = { "show_y_axis": True, "total_steps": 500, } class DiffusionDeltaGraphed(Diffusion1D): CONFIG = { "n_dots": 1000, "show_y_axis": True, "y_range": (0, 1000, 100), "total_steps": 200, } class DiffusionDeltaGraphedTripleStart(DiffusionDeltaGraphed): CONFIG = { "n_dots": 2000, } def adjust_initial_dot_positions(self, dots, x_unit): for n, dot in enumerate(dots): x = int(n % 4 - 1.5) dot.x = x dot.shift(x * x_unit * RIGHT) class DiffusionDeltaGraphedShowingMean(DiffusionDeltaGraphed): CONFIG = { "n_dots": 10000, "y_range": (0, 10000, 1000), "clip_at_bounds": False, "total_steps": 100, } def adjust_initial_dot_positions(self, dots, x_unit): # Hack, just using this to add something new and updated label = VGroup( OldTex("\\overline{x^2} = "), DecimalNumber(0), ) label.arrange(RIGHT) label.to_corner(UL) label.add_updater(lambda m: m[1].set_value(np.mean([ dot.x**2 for dot in dots ]))) self.add(label) class Diffusion2D(Diffusion1D): CONFIG = { "n_dots": 100, "dot_opacity": 0.5, "dither_dots": True, "grid_dimensions": (19, 35), } def construct(self): grid_dimensions = self.grid_dimensions # Setup grid grid = VGroup(*[ Square() for x in range(grid_dimensions[0]) for y in range(grid_dimensions[1]) ]) grid.arrange_in_grid(*grid_dimensions, buff=0) grid.set_height(FRAME_HEIGHT) grid.set_stroke(GREY_B, 1) self.add(grid) step_size = get_norm(grid[1].get_center() - grid[0].get_center()) # Add time label time_label = self.get_time_label() br = BackgroundRectangle(time_label) br.stretch(1.5, 0, about_edge=LEFT) time_label.add_to_back(br) self.add(time_label) # Initialize dots dots = self.get_dots() self.add(dots) # Rule for updating def step(dots=dots, step_size=step_size, time_label=time_label): for dot in dots: vect = random.choice([ UP, DOWN, LEFT, RIGHT, ORIGIN ]) dot.shift(step_size * vect) time_label[-1].increment_value() # Let it play out for t in range(self.total_steps): if t < 6: self.wait() else: self.wait(0.1) step() class Diffusion2D1Dot(Diffusion2D): CONFIG = { "n_dots": 1, "dither_dots": False, "dot_opacity": 1, "total_steps": 50, } class Diffusion2D10KDots(Diffusion2D): CONFIG = { "n_dots": 10000, "dot_opacity": 0.2, "total_steps": 200, }
from __future__ import annotations from manimlib.constants import * from manimlib.mobject.coordinate_systems import NumberPlane from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.frame import FullScreenFadeRectangle from manimlib.scene.scene import Scene from custom.characters.pi_creature import Mortimer from custom.characters.pi_creature import Randolph from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import Vect3 class Banner(Scene): camera_config = dict(pixel_height=1440, pixel_width=2560) pi_height = 1.25 pi_bottom = 0.25 * DOWN use_date = False message = None date = "Sunday, February 3rd" message_height = 0.4 add_supporter_note = False pre_date_text = "Next video on " def construct(self): # Background self.add(FullScreenFadeRectangle().set_fill(BLACK, 1)) plane = NumberPlane( (-7, 7), (-5, 5), height=10 * 1.5, width=14 * 1.5, axis_config={"stroke_color": BLUE_A}, faded_line_ratio=4, ) for line in plane.family_members_with_points(): line.set_stroke(width=line.get_stroke_width() / 2) self.add( plane, # FullScreenFadeRectangle().set_fill(BLACK, 0.25), ) # Pis pis = self.get_pis() pis.set_height(self.pi_height) pis.arrange(RIGHT, aligned_edge=DOWN) pis.move_to(self.pi_bottom, DOWN) self.pis = pis self.add(pis) plane.move_to(pis.get_bottom() + SMALL_BUFF * DOWN) # Message message = self.get_message() message.set_height(self.message_height) message.next_to(pis, DOWN) message.set_stroke(BLACK, 10, background=True) self.add(message) # Suppoerter note if self.add_supporter_note: note = self.get_supporter_note() note.scale(0.5) message.shift((MED_SMALL_BUFF - SMALL_BUFF) * UP) note.next_to(message, DOWN, SMALL_BUFF) self.add(note) yellow_parts = [sm for sm in message if sm.get_color() == YELLOW] for pi in pis: if yellow_parts: pi.look_at(yellow_parts[-1]) else: pi.look_at(message) def get_pis(self): return VGroup( Randolph(color=BLUE_E, mode="pondering"), Randolph(color=BLUE_D, mode="hooray"), Randolph(color=BLUE_C, mode="tease"), Mortimer(color=GREY_BROWN, mode="thinking") ) def get_message(self): if self.message: return Text(self.message) if self.use_date: return self.get_date_message() else: return self.get_probabalistic_message() def get_probabalistic_message(self): return Text( "New video every day " + \ "(with probability 0.05)", t2c={"Sunday": YELLOW}, ) def get_date_message(self): return Text( self.pre_date_text, self.date, t2c={self.date: YELLOW}, ) def get_supporter_note(self): return OldTexText( "(Available to supporters for review now)", color="#F96854", ) class CurrBanner(Banner): camera_config: dict = { "pixel_height": 1440, "pixel_width": 2560, } pi_height: float = 1.25 pi_bottom: Vect3 = 0.25 * DOWN use_date: bool = False date: str = "Wednesday, March 15th" message_scale_val: float = 0.9 add_supporter_note: bool = False pre_date_text: str = "Next video on " def construct(self): super().construct() for pi in self.pis: pi.set_gloss(0.1)
from manimlib.scene.scene import Scene class ExternallyAnimatedScene(Scene): def construct(self): raise Exception("Don't actually run this class.")
# This file contains functions and classes which have been used in old # videos, but which have since been supplanted in manim. For example, # there were previously various specifically named classes for version # of fading which are now covered by arguments passed into FadeIn and # FadeOut from manimlib.animation.fading import FadeIn, FadeOut class FadeInFromDown(FadeIn): def __init__(self, mobject, **kwargs): super().__init__(mobject, UP, **kwargs) class FadeOutAndShiftDown(FadeOut): def __init__(self, mobject, **kwargs): super().__init__(mobject, DOWN, **kwargs) class FadeInFromLarge(FadeIn): def __init__(self, mobject, scale_factor=2, **kwargs): super().__init__(mobject, scale=(1 / scale_factor), **kwargs)
from __future__ import annotations import numpy as np import itertools as it import random from manimlib.constants import * from manimlib.scene.scene import Scene from manimlib.mobject.geometry import AnnularSector from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Polygon from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import interpolate from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.rate_functions import squish_rate_func from manimlib.utils.rate_functions import smooth from manimlib.animation.animation import Animation from manimlib.animation.transform import Restore from manimlib.animation.transform import Transform from manimlib.animation.composition import AnimationGroup from manimlib.animation.composition import LaggedStartMap from manimlib.animation.creation import Write class Logo(VMobject): pupil_radius: float = 1.0 outer_radius: float = 2.0 iris_background_blue: ManimColor = "#74C0E3" iris_background_brown: ManimColor = "#8C6239" blue_spike_colors: list[ManimColor] = [ "#528EA3", "#3E6576", "#224C5B", BLACK, ] brown_spike_colors: list[ManimColor] = [ "#754C24", "#603813", "#42210b", BLACK, ] n_spike_layers: int = 4 n_spikes: int = 28 spike_angle: float = TAU / 28 def __init__(self, **kwargs): super().__init__(**kwargs) self.add_iris_back() self.add_spikes() self.add_pupil() def add_iris_back(self): blue_iris_back = AnnularSector( inner_radius=self.pupil_radius, outer_radius=self.outer_radius, angle=270 * DEGREES, start_angle=180 * DEGREES, fill_color=self.iris_background_blue, fill_opacity=1, stroke_width=0, ) brown_iris_back = AnnularSector( inner_radius=self.pupil_radius, outer_radius=self.outer_radius, angle=90 * DEGREES, start_angle=90 * DEGREES, fill_color=self.iris_background_brown, fill_opacity=1, stroke_width=0, ) self.iris_background = VGroup( blue_iris_back, brown_iris_back, ) self.add(self.iris_background) def add_spikes(self): layers = VGroup() radii = np.linspace( self.outer_radius, self.pupil_radius, self.n_spike_layers, endpoint=False, ) radii[:2] = radii[1::-1] # Swap first two if self.n_spike_layers > 2: radii[-1] = interpolate(radii[-1], self.pupil_radius, 0.25) for radius in radii: tip_angle = self.spike_angle half_base = radius * np.tan(tip_angle) triangle, right_half_triangle = [ Polygon( radius * UP, half_base * RIGHT, vertex3, fill_opacity=1, stroke_width=0, ) for vertex3 in (half_base * LEFT, ORIGIN,) ] left_half_triangle = right_half_triangle.copy() left_half_triangle.flip(UP, about_point=ORIGIN) n_spikes = self.n_spikes full_spikes = [ triangle.copy().rotate( -angle, about_point=ORIGIN ) for angle in np.linspace( 0, TAU, n_spikes, endpoint=False ) ] index = (3 * n_spikes) // 4 if radius == radii[0]: layer = VGroup(*full_spikes) layer.rotate( -TAU / n_spikes / 2, about_point=ORIGIN ) layer.brown_index = index else: half_spikes = [ right_half_triangle.copy(), left_half_triangle.copy().rotate( 90 * DEGREES, about_point=ORIGIN, ), right_half_triangle.copy().rotate( 90 * DEGREES, about_point=ORIGIN, ), left_half_triangle.copy() ] layer = VGroup(*it.chain( half_spikes[:1], full_spikes[1:index], half_spikes[1:3], full_spikes[index + 1:], half_spikes[3:], )) layer.brown_index = index + 1 layers.add(layer) # Color spikes blues = self.blue_spike_colors browns = self.brown_spike_colors for layer, blue, brown in zip(layers, blues, browns): index = layer.brown_index layer[:index].set_color(blue) layer[index:].set_color(brown) self.spike_layers = layers self.add(layers) def add_pupil(self): self.pupil = Circle( radius=self.pupil_radius, fill_color=BLACK, fill_opacity=1, stroke_width=0, stroke_color=BLACK, sheen=0.0, ) self.pupil.rotate(90 * DEGREES) self.add(self.pupil) def cut_pupil(self): pupil = self.pupil center = pupil.get_center() new_pupil = VGroup(*[ pupil.copy().pointwise_become_partial(pupil, a, b) for (a, b) in [(0.25, 1), (0, 0.25)] ]) for sector in new_pupil: sector.add_cubic_bezier_curve_to([ sector.get_points()[-1], *[center] * 3, *[sector.get_points()[0]] * 2 ]) self.remove(pupil) self.add(new_pupil) self.pupil = new_pupil def get_blue_part_and_brown_part(self): if len(self.pupil) == 1: self.cut_pupil() blue_part = VGroup( self.iris_background[0], *[ layer[:layer.brown_index] for layer in self.spike_layers ], self.pupil[0], ) brown_part = VGroup( self.iris_background[1], *[ layer[layer.brown_index:] for layer in self.spike_layers ], self.pupil[1], ) return blue_part, brown_part class LogoGenerationTemplate(Scene): def setup(self): super().setup() frame = self.camera.frame frame.shift(DOWN) self.logo = Logo() name = Text("3Blue1Brown") name.scale(2.5) name.next_to(self.logo, DOWN, buff=MED_LARGE_BUFF) name.set_gloss(0.2) self.channel_name = name def construct(self): logo = self.logo name = self.channel_name self.play( Write(name, run_time=3), *self.get_logo_animations(logo) ) self.wait() def get_logo_animations(self, logo): return [] # For subclasses class LogoGeneration(LogoGenerationTemplate): def construct(self): logo = self.logo name = self.channel_name layers = logo.spike_layers logo.save_state() for layer in layers: for spike in layer: spike.save_state() point = np.array(spike.get_points()[0]) angle = angle_of_vector(point) spike.rotate(-angle + 90 * DEGREES) spike.stretch_to_fit_width(0.2) spike.stretch_to_fit_height(0.5) spike.point = point for spike in layer[::2]: spike.rotate(180 * DEGREES) layer.arrange(LEFT, buff=0.1) layers.arrange(UP) layers.to_edge(DOWN) wrong_spike = layers[1][-5] wrong_spike.real_saved_state = wrong_spike.saved_state.copy() wrong_spike.saved_state.scale(0.25, about_point=wrong_spike.point) wrong_spike.saved_state.rotate(90 * DEGREES) self.wrong_spike = wrong_spike def get_spike_animation(spike, **kwargs): return Restore(spike, **kwargs) logo.iris_background.save_state() logo.iris_background.set_fill(opacity=0.0) logo.iris_background.scale(0.8) alt_name = name.copy() alt_name.set_stroke(BLACK, 5) self.play( Restore( logo.iris_background, rate_func=squish_rate_func(smooth, 1.0 / 3, 1), run_time=2, ), AnimationGroup(*( LaggedStartMap( get_spike_animation, layer, run_time=2, # rate_func=squish_rate_func(smooth, a / 3.0, (a + 0.9) / 3.0), lag_ratio=2 / len(layer), path_arc=-90 * DEGREES ) for layer, a in zip(layers, [0, 2, 1, 0]) )), Animation(logo.pupil), Write(alt_name), Write(name), run_time=3 ) self.wait(0.25) self.play( Transform( wrong_spike, wrong_spike.real_saved_state, ), Animation(self.logo), run_time=0.75 ) class SortingLogoGeneration(LogoGenerationTemplate): def get_logo_animations(self, logo): layers = logo.spike_layers for j, layer in enumerate(layers): for i, spike in enumerate(layer): spike.angle = (13 * (i + 1) * (j + 1) * TAU / 28) % TAU if spike.angle > PI: spike.angle -= TAU spike.save_state() spike.rotate( spike.angle, about_point=ORIGIN ) # spike.get_points()[1] = rotate_vector( # spike.get_points()[1], TAU/28, # ) # spike.get_points()[-1] = rotate_vector( # spike.get_points()[-1], -TAU/28, # ) def get_spike_animation(spike, **kwargs): return Restore( spike, path_arc=-spike.angle, **kwargs ) logo.iris_background.save_state() # logo.iris_background.scale(0.49) logo.iris_background.set_fill(GREY_D, 0.5) return [ Restore( logo.iris_background, rate_func=squish_rate_func(smooth, 2.0 / 3, 1), run_time=3, ), AnimationGroup(*[ LaggedStartMap( get_spike_animation, layer, run_time=2, # rate_func=squish_rate_func(smooth, a / 3.0, (a + 0.9) / 3.0), lag_ratio=0.2, ) for layer, a in zip(layers, [0, 2, 1, 0]) ]), Animation(logo.pupil), ] class LogoTest(Scene): def construct(self): n_range = list(range(4, 40, 4)) for n, denom in zip(n_range, np.linspace(14, 28, len(n_range))): logo = Logo(**{ "iris_background_blue": "#78C0E3", "iris_background_brown": "#8C6239", "blue_spike_colors": [ "#528EA3", "#3E6576", "#224C5B", BLACK, ], "brown_spike_colors": [ "#754C24", "#603813", "#42210b", BLACK, ], "n_spike_layers": 4, "n_spikes": n, "spike_angle": TAU / denom, }) self.add(logo) self.wait() self.clear() self.add(logo) class LogoGenerationFlurry(LogoGenerationTemplate): random_seed: int = 2 def get_logo_animations(self, logo): layers = logo.spike_layers for i, layer in enumerate(layers): random.shuffle(layer.submobjects) for spike in layer: spike.save_state() spike.scale(0.5) spike.apply_complex_function(np.log) spike.rotate(-90 * DEGREES, about_point=ORIGIN) spike.set_fill(opacity=0) layer.rotate(i * PI / 5) logo.iris_background.save_state() logo.iris_background.scale(0.25) logo.iris_background.fade(1) return [ Restore( logo.iris_background, run_time=3, ), AnimationGroup(*[ LaggedStartMap( Restore, layer, run_time=3, path_arc=180 * DEGREES, # rate_func=squish_rate_func(smooth, a / 3.0, (a + 1.9) / 3.0), lag_ratio=0.8, ) for layer, a in zip(layers, [0, 0.2, 0.1, 0]) ]), Animation(logo.pupil), ] class WrittenLogo(LogoGenerationTemplate): def get_logo_animations(self, logo): return [Write(logo, stroke_color=None, stroke_width=2, run_time=3, lag_ratio=5e-3)] class LogoGenerationFivefold(LogoGenerationTemplate): def construct(self): logo = self.logo iris, spike_layers, pupil = logo name = OldTexText("3Blue1Brown") name.scale(2.5) name.next_to(logo, DOWN, buff=MED_LARGE_BUFF) name.set_gloss(0.2) self.add(iris) anims = [] for layer in spike_layers: for n, spike in enumerate(layer): angle = (5 * (n + 1) * TAU / len(layer)) % TAU spike.rotate(angle, about_point=ORIGIN) anims.append(Rotate( spike, -angle, about_point=ORIGIN, run_time=5, # rate_func=rush_into, )) self.add(spike) self.add(pupil) def update(alpha): spike_layers.set_opacity(alpha) mid_alpha = 4.0 * (1.0 - alpha) * alpha spike_layers.set_stroke(WHITE, 1, opacity=mid_alpha) pupil.set_stroke(WHITE, 1, opacity=mid_alpha) iris.set_stroke(WHITE, 1, opacity=mid_alpha) name.flip().flip() self.play( *anims, VFadeIn(iris, run_time=3), UpdateFromAlphaFunc( Mobject(), lambda m, a: update(a), run_time=3, ), # FadeIn(name, run_time=3, lag_ratio=0.5, rate_func=linear), Write(name, run_time=3) ) self.wait(2) class Vertical3B1B(Scene): def construct(self): words = OldTexText( "3", "Blue", "1", "Brown", ) words.scale(2) words[::2].scale(1.2) buff = 0.2 words.arrange( DOWN, buff=buff, aligned_edge=LEFT, ) words[0].match_x(words[1][0]) words[2].match_x(words[3][0]) self.add(words) logo = Logo() logo.next_to(words, LEFT) self.add(logo) VGroup(logo, words).center()
from manimlib.constants import WHITE from manimlib.constants import BLACK from manimlib.constants import DOWN from manimlib.constants import UP from manimlib.constants import BLUE from manimlib.scene.scene import Scene from manimlib.mobject.frame import FullScreenRectangle from manimlib.mobject.frame import ScreenRectangle from manimlib.mobject.changing import AnimatedBoundary from manimlib.mobject.svg.tex_mobject import TexText from manimlib.animation.creation import Write class Spotlight(Scene): title = "" title_font_size = 60 def construct(self): title = TexText(self.title, font_size=self.title_font_size) title.to_edge(UP) self.add(title) self.add(FullScreenRectangle()) screen = ScreenRectangle() screen.set_height(6.0) screen.set_stroke(WHITE, 2) screen.set_fill(BLACK, 1) screen.to_edge(DOWN) animated_screen = AnimatedBoundary(screen) self.add(screen, animated_screen) self.wait(16) class VideoWrapper(Scene): animate_boundary = True animated_boundary_config = {"cycle_rate": 0.25} title = "" title_config = dict( font_size=60 ) wait_time = 32 screen_height = 6.25 def construct(self): self.add(FullScreenRectangle()) screen = ScreenRectangle() screen.set_fill(BLACK, 1) screen.set_stroke(BLUE, 0) screen.set_height(self.screen_height) screen.to_edge(DOWN) if self.animate_boundary: boundary = self.boundary = AnimatedBoundary(screen, **self.animated_boundary_config) self.add(boundary) wait_time = self.wait_time else: wait_time = 1 self.add(screen) if self.title: title_text = self.title_text = TexText( self.title, **self.title_config, ) title_text.set_max_width(screen.get_width()) title_text.next_to(screen, UP) self.play(Write(title_text)) self.wait(wait_time)
from manimlib import * # Related to pi creatures class Car(SVGMobject): file_name = "Car" height = 1 color = GREY_B light_colors = [BLACK, BLACK] def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) path = self.submobjects[0] subpaths = path.get_subpaths() path.clear_points() for indices in [(0, 1), (2, 3), (4, 6, 7), (5,), (8,)]: part = VMobject() for index in indices: part.append_points(subpaths[index]) path.add(part) self.set_height(self.height) self.set_stroke(color=WHITE, width=0) self.set_fill(self.color, opacity=1) from videos.characters.pi_creature import Randolph randy = Randolph(mode="happy") randy.set_height(0.6 * self.get_height()) randy.stretch(0.8, 0) randy.look(RIGHT) randy.move_to(self) randy.shift(0.07 * self.height * (RIGHT + UP)) self.randy = self.pi_creature = randy self.add_to_back(randy) orientation_line = Line(self.get_left(), self.get_right()) orientation_line.set_stroke(width=0) self.add(orientation_line) self.orientation_line = orientation_line for light, color in zip(self.get_lights(), self.light_colors): light.set_fill(color, 1) light.is_subpath = False self.add_treds_to_tires() def move_to(self, point_or_mobject): vect = rotate_vector( UP + LEFT, self.orientation_line.get_angle() ) self.next_to(point_or_mobject, vect, buff=0) return self def get_front_line(self): return DashedLine( self.get_corner(UP + RIGHT), self.get_corner(DOWN + RIGHT), color=DISTANCE_COLOR, dash_length=0.05, ) def add_treds_to_tires(self): for tire in self.get_tires(): radius = tire.get_width() / 2 center = tire.get_center() tred = Line( 0.7 * radius * RIGHT, 1.1 * radius * RIGHT, stroke_width=2, color=BLACK ) tred.rotate(PI / 5, about_point=tred.get_end()) for theta in np.arange(0, 2 * np.pi, np.pi / 4): new_tred = tred.copy() new_tred.rotate(theta, about_point=ORIGIN) new_tred.shift(center) tire.add(new_tred) return self def get_tires(self): return VGroup(self[1][0], self[1][1]) def get_lights(self): return VGroup(self.get_front_light(), self.get_rear_light()) def get_front_light(self): return self[1][3] def get_rear_light(self): return self[1][4] class MoveCar(ApplyMethod): def __init__(self, car, target_point, run_time=5, moving_forward=True, **kwargs): self.moving_forward = moving_forward self.check_if_input_is_car(car) self.target_point = target_point super().__init__( car.move_to, target_point, run_time=run_time, **kwargs ) def check_if_input_is_car(self, car): if not isinstance(car, Car): raise Exception("MoveCar must take in Car object") def begin(self): super().begin() car = self.mobject distance = get_norm(op.sub( self.target_mobject.get_right(), self.starting_mobject.get_right(), )) if not self.moving_forward: distance *= -1 tire_radius = car.get_tires()[0].get_width() / 2 self.total_tire_radians = -distance / tire_radius def interpolate_mobject(self, alpha): ApplyMethod.interpolate_mobject(self, alpha) if alpha == 0: return radians = alpha * self.total_tire_radians for tire in self.mobject.get_tires(): tire.rotate(radians) class PartyHat(SVGMobject): file_name = "party_hat" height = 1.5 pi_creature = None stroke_width = 0 fill_opacity = 1 frills_colors = [MAROON_B, PURPLE] cone_color = GREEN dots_colors = [YELLOW] NUM_FRILLS = 7 NUM_DOTS = 6 def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) self.set_height(self.height) if self.pi_creature is not None: self.next_to(self.pi_creature.eyes, UP, buff=0) self.frills = VGroup(*self[:self.NUM_FRILLS]) self.cone = self[self.NUM_FRILLS] self.dots = VGroup(*self[self.NUM_FRILLS + 1:]) self.frills.set_color_by_gradient(*self.frills_colors) self.cone.set_color(self.cone_color) self.dots.set_color_by_gradient(*self.dots_colors) class SunGlasses(SVGMobject): file_name = "sunglasses" glasses_width_to_eyes_width = 1.1 def __init__(self, pi_creature, **kwargs): super().__init__(**kwargs) self.set_stroke(WHITE, width=0) self.set_fill(GREY, 1) self.set_width( self.glasses_width_to_eyes_width * pi_creature.eyes.get_width() ) self.move_to(pi_creature.eyes, UP) class Headphones(SVGMobject): file_name = "headphones" height = 2 y_stretch_factor = 0.5 color = GREY def __init__(self, pi_creature=None, **kwargs): super().__init__(file_name=self.file_name, **kwargs) self.stretch(self.y_stretch_factor, 1) self.set_height(self.height) self.set_stroke(width=0) self.set_fill(color=self.color) if pi_creature is not None: eyes = pi_creature.eyes self.set_height(3 * eyes.get_height()) self.move_to(eyes, DOWN) self.shift(DOWN * eyes.get_height() / 4) class Guitar(SVGMobject): file_name = "guitar" def __init__( self, height=2.5, fill_color=GREY_D, fill_opacity=1, stroke_color=WHITE, stroke_width=0.5, ): super().__init__( height=height, fill_color=fill_color, fill_opacity=fill_opacity, stroke_color=stroke_color, stroke_width=stroke_width, ) # Cards class DeckOfCards(VGroup): def __init__(self, **kwargs): possible_values = list(map(str, list(range(1, 11)))) + ["J", "Q", "K"] possible_suits = ["hearts", "diamonds", "spades", "clubs"] super().__init__(*( PlayingCard(value=value, suit=suit, **kwargs) for value in possible_values for suit in possible_suits )) class PlayingCard(VGroup): def __init__( self, key=None, # String like "8H" or "KS" value=None, suit=None, height=2, height_to_width=3.5 / 2.5, card_height_to_symbol_height=7, card_width_to_corner_num_width=10, card_height_to_corner_num_height=10, color=GREY_A, turned_over=False, possible_suits=["hearts", "diamonds", "spades", "clubs"], possible_values=list(map(str, list(range(2, 11)))) + ["J", "Q", "K", "A"], **kwargs, ): self.key = key self.value = value self.suit = suit self.height = height self.height_to_width = height_to_width self.card_height_to_symbol_height = card_height_to_symbol_height self.card_width_to_corner_num_width = card_width_to_corner_num_width self.card_height_to_corner_num_height = card_height_to_corner_num_height self.color = color self.turned_over = turned_over self.possible_suits = possible_suits self.possible_values = possible_values super().__init__(**kwargs) self.key = key self.add(Rectangle( height=self.height, width=self.height / self.height_to_width, stroke_color=WHITE, stroke_width=2, fill_color=self.color, fill_opacity=1, )) if self.turned_over: self.set_fill(GREY_D) self.set_stroke(GREY_B) contents = VectorizedPoint(self.get_center()) else: value = self.get_value() symbol = self.get_symbol() design = self.get_design(value, symbol) corner_numbers = self.get_corner_numbers(value, symbol) contents = VGroup(design, corner_numbers) self.design = design self.corner_numbers = corner_numbers self.add(contents) def get_value(self): value = self.value if value is None: if self.key is not None: value = self.key[:-1] else: value = random.choice(self.possible_values) value = str(value).upper() if value == "1": value = "A" if value not in self.possible_values: raise Exception("Invalid card value") face_card_to_value = { "J": 11, "Q": 12, "K": 13, "A": 14, } try: self.numerical_value = int(value) except Exception: self.numerical_value = face_card_to_value[value] return value def get_symbol(self): suit = self.suit if suit is None: if self.key is not None: suit = dict([ (s[0].upper(), s) for s in self.possible_suits ])[self.key[-1].upper()] else: suit = random.choice(self.possible_suits) if suit not in self.possible_suits: raise Exception("Invalud suit value") self.suit = suit symbol_height = float(self.height) / self.card_height_to_symbol_height symbol = SuitSymbol(suit, height=symbol_height) return symbol def get_design(self, value, symbol): if value == "A": return self.get_ace_design(symbol) if value in list(map(str, list(range(2, 11)))): return self.get_number_design(value, symbol) else: return self.get_face_card_design(value, symbol) def get_ace_design(self, symbol): design = symbol.copy().scale(1.5) design.move_to(self) return design def get_number_design(self, value, symbol): num = int(value) n_rows = { 2: 2, 3: 3, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, 9: 4, 10: 4, }[num] n_cols = 1 if num in [2, 3] else 2 insertion_indices = { 5: [0], 7: [0], 8: [0, 1], 9: [1], 10: [0, 2], }.get(num, []) top = self.get_top() + symbol.get_height() * DOWN bottom = self.get_bottom() + symbol.get_height() * UP column_points = [ interpolate(top, bottom, alpha) for alpha in np.linspace(0, 1, n_rows) ] design = VGroup(*[ symbol.copy().move_to(point) for point in column_points ]) if n_cols == 2: space = 0.2 * self.get_width() column_copy = design.copy().shift(space * RIGHT) design.shift(space * LEFT) design.add(*column_copy) design.add(*[ symbol.copy().move_to( center_of_mass(column_points[i:i + 2]) ) for i in insertion_indices ]) for symbol in design: if symbol.get_center()[1] < self.get_center()[1]: symbol.rotate(np.pi) return design def get_face_card_design(self, value, symbol): from videos.characters.pi_creature import PiCreature sub_rect = Rectangle( stroke_color=BLACK, fill_opacity=0, height=0.9 * self.get_height(), width=0.6 * self.get_width(), ) sub_rect.move_to(self) # pi_color = average_color(symbol.get_color(), GREY) pi_color = symbol.get_color() if Color(pi_color) == Color(BLACK): pi_color = GREY_D pi_mode = { "J": "plain", "Q": "thinking", "K": "hooray" }[value] pi_creature = PiCreature( mode=pi_mode, color=pi_color, ) pi_creature.set_width(0.8 * sub_rect.get_width()) if value in ["Q", "K"]: prefix = "king" if value == "K" else "queen" crown = SVGMobject(file_name=prefix + "_crown") crown.set_stroke(width=0) crown.set_fill(YELLOW, 1) crown.stretch_to_fit_width(0.5 * sub_rect.get_width()) crown.stretch_to_fit_height(0.17 * sub_rect.get_height()) crown.move_to(pi_creature.eyes.get_center(), DOWN) pi_creature.add_to_back(crown) to_top_buff = 0 else: to_top_buff = SMALL_BUFF * sub_rect.get_height() pi_creature.next_to(sub_rect.get_top(), DOWN, to_top_buff) # pi_creature.shift(0.05*sub_rect.get_width()*RIGHT) pi_copy = pi_creature.copy() pi_copy.rotate(np.pi, about_point=sub_rect.get_center()) return VGroup(sub_rect, pi_creature, pi_copy) def get_corner_numbers(self, value, symbol): value_mob = OldTexText(value) width = self.get_width() / self.card_width_to_corner_num_width height = self.get_height() / self.card_height_to_corner_num_height value_mob.set_width(width) value_mob.stretch_to_fit_height(height) value_mob.next_to( self.get_corner(UP + LEFT), DOWN + RIGHT, buff=MED_LARGE_BUFF * width ) value_mob.set_color(symbol.get_color()) corner_symbol = symbol.copy() corner_symbol.set_width(width) corner_symbol.next_to( value_mob, DOWN, buff=MED_SMALL_BUFF * width ) corner_group = VGroup(value_mob, corner_symbol) opposite_corner_group = corner_group.copy() opposite_corner_group.rotate( np.pi, about_point=self.get_center() ) return VGroup(corner_group, opposite_corner_group) class SuitSymbol(SVGMobject): def __init__(self, suit_name, **kwargs): suits = {"hearts", "diamonds", "spades", "clubs"} if suit_name not in suits: raise Exception("Invalid suit name") super().__init__(file_name=suit_name, **kwargs) # Logos class AoPSLogo(SVGMobject): file_name = "aops_logo" height = 1.5 def __init__(self, **kwargs): super().__init__(**kwargs) self.set_stroke(WHITE, width=0) colors = [BLUE_E, "#008445", GREEN_B] index_lists = [ (10, 11, 12, 13, 14, 21, 22, 23, 24, 27, 28, 29, 30), (0, 1, 2, 3, 4, 15, 16, 17, 26), (5, 6, 7, 8, 9, 18, 19, 20, 25) ] for color, index_list in zip(colors, index_lists): for i in index_list: self.submobjects[i].set_fill(color, opacity=1) self.set_height(self.height) self.center() class BitcoinLogo(SVGMobject): file_name = "Bitcoin_logo" height = 1
from manimlib.animation.creation import Write from manimlib.animation.fading import FadeIn from manimlib.constants import * from manimlib.mobject.svg.tex_mobject import TexText from manimlib.scene.scene import Scene from manimlib.utils.rate_functions import linear class OpeningQuote(Scene): quote = [] quote_arg_separator = " " highlighted_quote_terms = {} author = "" fade_in_kwargs = { "lag_ratio": 0.5, "rate_func": linear, "run_time": 5, } text_size = R"\Large" use_quotation_marks = True top_buff = 1.0 author_buff = 1.0 def construct(self): self.quote = self.get_quote() self.author = self.get_author(self.quote) self.play(FadeIn(self.quote, **self.fade_in_kwargs)) self.wait(2) self.play(Write(self.author, run_time=3)) self.wait() def get_quote(self, max_width=FRAME_WIDTH - 1): text_mobject_kwargs = { "alignment": "", "arg_separator": self.quote_arg_separator, } if isinstance(self.quote, str): if self.use_quotation_marks: quote = OldTexText("``%s''" % self.quote.strip(), **text_mobject_kwargs) else: quote = OldTexText("%s" % self.quote.strip(), **text_mobject_kwargs) else: if self.use_quotation_marks: words = [self.text_size + " ``"] + list(self.quote) + ["''"] else: words = [self.text_size] + list(self.quote) quote = OldTexText(*words, **text_mobject_kwargs) # TODO, make less hacky if self.quote_arg_separator == " ": quote[0].shift(0.2 * RIGHT) quote[-1].shift(0.2 * LEFT) for term, color in self.highlighted_quote_terms: quote.set_color_by_tex(term, color) quote.to_edge(UP, buff=self.top_buff) if quote.get_width() > max_width: quote.set_width(max_width) return quote def get_author(self, quote): author = OldTexText(self.text_size + " --" + self.author) author.next_to(quote, DOWN, buff=self.author_buff) author.set_color(YELLOW) return author
import random import os import json from tqdm import tqdm as ProgressDisplay from manimlib.animation.animation import Animation from manimlib.animation.composition import Succession from manimlib.animation.transform import ApplyMethod from manimlib.constants import * from manimlib.mobject.mobject import Mobject from manimlib.mobject.geometry import DashedLine from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import Square from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.scene import Scene from manimlib.utils.directories import get_directories from manimlib.utils.rate_functions import linear from custom.characters.pi_creature import Mortimer from custom.characters.pi_creature import Randolph from custom.characters.pi_creature_animations import Blink class PatreonEndScreen(Scene): title_text = "Clicky Stuffs" show_pis = True max_patron_group_size = 20 patron_scale_val = 0.8 n_patron_columns = 4 max_patron_width = 5 randomize_order = False capitalize = True name_y_spacing = 0.6 thanks_words = """ Instead of sponsor messages, these lessons are supported directly by viewers, such as those below | 3b1b.co/support """ scroll_time = 20 def construct(self): # Add title title = self.title = Text(self.title_text) title.scale(1.5) title.to_edge(UP, buff=MED_SMALL_BUFF) self.add(title) pi_creatures = VGroup(Randolph(), Mortimer()) for pi, vect in zip(pi_creatures, [LEFT, RIGHT]): pi.set_height(title.get_height()) pi.change_mode("thinking") pi.look(DOWN) pi.next_to(title, vect, buff=MED_LARGE_BUFF) self.add(pi_creatures) if not self.show_pis: pi_creatures.set_opacity(0) # Set the top of the screen logo_box = Square(side_length=2.5) logo_box.to_corner(DOWN + LEFT, buff=MED_LARGE_BUFF) black_rect = Rectangle( fill_color=BLACK, fill_opacity=1, stroke_width=3, stroke_color=BLACK, width=FRAME_WIDTH, height=FRAME_HEIGHT, ) black_rect.to_edge(UP, buff=0) line = DashedLine(FRAME_X_RADIUS * LEFT, FRAME_X_RADIUS * RIGHT) line.move_to(ORIGIN) # Add thanks thanks = Text(self.thanks_words) thanks.scale(0.8) thanks.next_to(line, DOWN, buff=MED_SMALL_BUFF) thanks.set_color(YELLOW) underline = Line(LEFT, RIGHT) underline.match_width(thanks) underline.scale(1.1) underline.next_to(thanks, DOWN, SMALL_BUFF) thanks.add(underline) black_rect.match_y(underline, DOWN) # Build name list names = self.get_names() name_labels = VGroup(*map( Text, ProgressDisplay(names, leave=False, desc="Writing names") )) name_labels.scale(self.patron_scale_val) for label in name_labels: label.set_max_width(self.max_patron_width) columns = VGroup(*[ VGroup(*name_labels[i::self.n_patron_columns]) for i in range(self.n_patron_columns) ]) column_x_spacing = 0.5 + max([c.get_width() for c in columns]) for i, column in enumerate(columns): for n, name in enumerate(column): name.shift(n * self.name_y_spacing * DOWN) name.align_to(ORIGIN, LEFT) column.move_to(i * column_x_spacing * RIGHT, UL) columns.center() max_width = FRAME_WIDTH - 1 if columns.get_width() > max_width: columns.set_width(max_width) underline.match_width(columns) columns.next_to(underline, DOWN, buff=3) # Set movement columns.generate_target() distance = columns.get_height() + 2 wait_time = self.scroll_time frame = self.camera.frame frame_shift = ApplyMethod( frame.shift, distance * DOWN, run_time=wait_time, rate_func=linear, ) blink_anims = [] blank_mob = Mobject() for x in range(wait_time): if random.random() < 0.25: blink_anims.append(Blink(random.choice(pi_creatures))) else: blink_anims.append(Animation(blank_mob)) blinks = Succession(*blink_anims) static_group = VGroup(black_rect, line, thanks, pi_creatures, title) static_group.fix_in_frame() self.add(columns, static_group) self.play(frame_shift, blinks) def get_names(self): patron_file = "patrons.txt" hardcoded_patron_file = "hardcoded_patrons.txt" names = [] for file in patron_file, hardcoded_patron_file: full_path = os.path.join(get_directories()["data"], file) with open(full_path, "r") as fp: names.extend([ self.modify_patron_name(name.strip()) for name in fp.readlines() ]) # Remove duplicates names = list(set(names)) # Make sure these aren't missed if self.randomize_order: random.shuffle(names) else: names.sort() return names def modify_patron_name(self, name): path = os.path.join( get_directories()['data'], "patron_name_replacements.json" ) with open(path) as fp: modification_map = json.load(fp) for n1, n2 in modification_map.items(): # name = name.replace("ā", "\\={a}") if name.lower() == n1.lower(): name = n2 if self.capitalize: name = " ".join(map( lambda s: s.capitalize(), name.split(" ") )) return name
from __future__ import annotations from manimlib.animation.composition import AnimationGroup from manimlib.animation.fading import FadeOut from manimlib.animation.creation import DrawBorderThenFill from manimlib.animation.creation import Write from manimlib.animation.transform import ApplyMethod from manimlib.animation.transform import MoveToTarget from manimlib.constants import * from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Mobject from manimlib.mobject.svg.drawings import SpeechBubble from manimlib.utils.rate_functions import squish_rate_func from manimlib.utils.rate_functions import there_and_back from custom.characters.pi_creature import PiCreature from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import Vect3 class Blink(ApplyMethod): def __init__( self, pi_creature: PiCreature, rate_func: Callable = squish_rate_func(there_and_back), **kwargs ): super().__init__(pi_creature.blink, rate_func=rate_func, **kwargs) class PiCreatureBubbleIntroduction(AnimationGroup): def __init__( self, pi_creature: PiCreature, content: str, target_mode: str = "speaking", look_at: Mobject | Vect3 | None = None, bubble_type: type = SpeechBubble, max_bubble_height: float | None = None, max_bubble_width: float | None = None, bubble_direction: Vect3 | None = None, bubble_config=dict(), bubble_creation_class: type = DrawBorderThenFill, bubble_creation_kwargs: dict = dict(), content_introduction_class: type = Write, content_introduction_kwargs: dict = dict(), **kwargs, ): bubble_config = dict(bubble_config) bubble_config["max_height"] = max_bubble_height bubble_config["max_width"] = max_bubble_width if bubble_direction is not None: bubble_config["direction"] = bubble_direction bubble = pi_creature.get_bubble( content, bubble_type=bubble_type, **bubble_config ) Group(bubble, bubble.content).shift_onto_screen() super().__init__( pi_creature.change(target_mode, look_at), bubble_creation_class(bubble, **bubble_creation_kwargs), content_introduction_class(bubble.content, **content_introduction_kwargs), **kwargs ) class PiCreatureSays(PiCreatureBubbleIntroduction): def __init__( self, pi_creature: PiCreature, content: str, target_mode: str = "speaking", bubble_type: type = SpeechBubble, **kwargs, ): super().__init__( pi_creature, content, target_mode=target_mode, bubble_type=bubble_type, **kwargs ) class RemovePiCreatureBubble(AnimationGroup): def __init__( self, pi_creature: PiCreature, target_mode: str = "plain", look_at: Mobject | Vect3 | None = None, remover: bool = True, **kwargs ): assert hasattr(pi_creature, "bubble") self.pi_creature = pi_creature pi_creature.generate_target() pi_creature.target.change_mode(target_mode) if look_at is not None: pi_creature.target.look_at(look_at) super().__init__( MoveToTarget(pi_creature), FadeOut(pi_creature.bubble), FadeOut(pi_creature.bubble.content), ) def clean_up_from_scene(self, scene=None): AnimationGroup.clean_up_from_scene(self, scene) self.pi_creature.bubble = None if scene is not None: scene.add(self.pi_creature)
from __future__ import annotations import os import logging import numpy as np from manimlib.animation.animation import Animation from manimlib.animation.composition import AnimationGroup from manimlib.animation.fading import FadeTransform from manimlib.animation.transform import ReplacementTransform from manimlib.constants import * from manimlib.mobject.mobject import _AnimationBuilder from manimlib.mobject.mobject import Mobject from manimlib.mobject.geometry import Circle from manimlib.mobject.svg.drawings import ThoughtBubble from manimlib.mobject.svg.drawings import SpeechBubble from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.directories import get_directories from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import normalize from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor, Vect3 PI_CREATURE_SCALE_FACTOR: float = 0.5 LEFT_EYE_INDEX: int = 0 RIGHT_EYE_INDEX: int = 1 LEFT_PUPIL_INDEX: int = 2 RIGHT_PUPIL_INDEX: int = 3 BODY_INDEX: int = 4 MOUTH_INDEX: int = 5 class PiCreature(SVGMobject): # Range of proportions along body where arms are right_arm_range: tuple[float, float] = (0.55, 0.7) left_arm_range: tuple[float, float] = (0.34, 0.462) pupil_to_eye_width_ratio: float = 0.4 pupil_dot_to_pupil_width_ratio: float = 0.3 def __init__( self, mode: str = "plain", color: ManimColor = BLUE_E, stroke_width: float = 0.0, stroke_color: ManimColor = BLACK, fill_opacity: float = 1.0, height: float = 3, flip_at_start: bool = False, start_corner: Vect3 | None = None, **kwargs ): self.mode = mode self.bubble = None self.body = VMobject() # Just to keep self.get_color happy super().__init__( file_name=self.get_svg_file_path(mode), color=None, stroke_width=stroke_width, stroke_color=stroke_color, fill_opacity=fill_opacity, height=height, **kwargs ) self.init_structure() self.set_color(color) if flip_at_start: self.flip() if start_corner is not None: self.to_corner(start_corner) self.refresh_triangulation() def get_svg_file_path(self, mode): folder = get_directories()["pi_creature_images"] path = os.path.join(folder, f"{mode}.svg") if os.path.exists(path): return path else: logging.log( logging.WARNING, f"No design with mode {mode}", ) folder = get_directories()["pi_creature_images"] return os.path.join(folder, "plain.svg") def init_structure(self): # Figma exports with superfluous parts, so this # hardcodes how to extract what we want. parts = self.submobjects self.eyes: VGroup = self.draw_eyes( original_irises=VGroup(parts[2], parts[6]), original_pupils=VGroup(parts[8], parts[9]) ) self.body: VMobject = parts[10] self.mouth: VMobject = parts[11] self.mouth.insert_n_curves(10) self.set_submobjects([self.eyes, self.body, self.mouth]) def draw_eyes(self, original_irises, original_pupils): # Instead of what is drawn, make new circles. # This is mostly because the paths associated # with the eyes in all the drawings got slightly # messed up. eyes = VGroup() for iris, ref_pupil in zip(original_irises, original_pupils): pupil_r = iris.get_width() / 2 pupil_r *= self.pupil_to_eye_width_ratio dot_r = pupil_r dot_r *= self.pupil_dot_to_pupil_width_ratio black = Circle(radius=pupil_r, color=BLACK) dot = Circle(radius=dot_r, color=WHITE) dot.shift(black.pfp(3 / 8) - dot.pfp(3 / 8)) pupil = VGroup(black, dot) pupil.set_style(fill_opacity=1, stroke_width=0) pupil.move_to(ref_pupil) eye = VGroup(iris, pupil) eye.pupil = pupil eye.iris = iris eyes.add(eye) return eyes def align_data_and_family(self, mobject): # This ensures that after a transform into a different mode, # the pi creatures mode will be updated appropriately SVGMobject.align_data_and_family(self, mobject) if isinstance(mobject, PiCreature): self.mode = mobject.get_mode() def set_color(self, color, recurse=True): self.body.set_fill(color, recurse=recurse) return self def get_color(self): return self.body.get_color() def change_mode(self, mode): new_self = self.__class__(mode=mode) new_self.match_style(self) new_self.match_height(self) if self.is_flipped() != new_self.is_flipped(): new_self.flip() new_self.shift(self.eyes.get_center() - new_self.eyes.get_center()) if hasattr(self, "purposeful_looking_direction"): new_self.look(self.purposeful_looking_direction) self.become(new_self) self.mode = mode return self def get_mode(self): return self.mode def look(self, direction): direction = normalize(direction) self.purposeful_looking_direction = direction for eye in self.eyes: iris, pupil = eye iris_center = iris.get_center() right = iris.get_right() - iris_center up = iris.get_top() - iris_center vect = direction[0] * right + direction[1] * up v_norm = get_norm(vect) pupil_radius = 0.5 * pupil.get_width() vect *= (v_norm - 0.75 * pupil_radius) / v_norm pupil.move_to(iris_center + vect) self.eyes[1].pupil.align_to(self.eyes[0].pupil, DOWN) return self def look_at(self, point_or_mobject): if isinstance(point_or_mobject, Mobject): point = point_or_mobject.get_center() else: point = point_or_mobject self.look(point - self.eyes.get_center()) return self def get_looking_direction(self): vect = self.eyes[0].pupil.get_center() - self.eyes[0].get_center() return normalize(vect) def get_look_at_spot(self): return self.eyes.get_center() + self.get_looking_direction() def is_flipped(self): return self.eyes.submobjects[0].get_center()[0] > \ self.eyes.submobjects[1].get_center()[0] def blink(self): eyes = self.eyes eye_bottom_y = eyes.get_y(DOWN) for eye_part in eyes.family_members_with_points(): new_points = eye_part.get_points() new_points[:, 1] = eye_bottom_y eye_part.set_points(new_points) return self def get_bubble(self, content, bubble_type=ThoughtBubble, **bubble_config): bubble = bubble_type(**bubble_config) if len(content) > 0: if isinstance(content[0], str): content_mob = Text(content) else: content_mob = content bubble.add_content(content_mob) bubble.resize_to_content() bubble.pin_to(self, auto_flip=("direction" not in bubble_config)) self.bubble = bubble return bubble def make_eye_contact(self, pi_creature): self.look_at(pi_creature.eyes) pi_creature.look_at(self.eyes) return self def shrug(self): self.change_mode("shruggie") points = self.mouth.get_points() top_mouth_point, bottom_mouth_point = [ points[np.argmax(points[:, 1])], points[np.argmin(points[:, 1])] ] self.look(top_mouth_point - bottom_mouth_point) return self def get_arm_copies(self): body = self.body return VGroup(*[ body.copy().pointwise_become_partial(body, *alpha_range) for alpha_range in (self.right_arm_range, self.left_arm_range) ]) # Overrides def become(self, mobject): super().become(mobject) if isinstance(mobject, PiCreature): self.bubble = mobject.bubble return self # Animations def change(self, new_mode, look_at=None) -> _AnimationBuilder: animation = self.animate.change_mode(new_mode) if look_at is not None: animation = animation.look_at(look_at) return animation def says(self, content, mode="speaking", look_at=None, **kwargs) -> Animation: from custom.characters.pi_creature_animations import PiCreatureBubbleIntroduction return PiCreatureBubbleIntroduction( self, content, target_mode=mode, look_at=look_at, bubble_type=SpeechBubble, **kwargs, ) def thinks(self, content, mode="thinking", look_at=None, **kwargs) -> Animation: from custom.characters.pi_creature_animations import PiCreatureBubbleIntroduction return PiCreatureBubbleIntroduction( self, content, target_mode=mode, look_at=look_at, bubble_type=ThoughtBubble, **kwargs, ) def replace_bubble(self, content, mode="pondering", look_at=None, **kwargs) -> Animation | _AnimationBuilder: if self.bubble is None: return self.change(mode, look_at) old_bubble = self.bubble new_bubble = self.get_bubble(content, bubble_type=old_bubble.__class__, **kwargs) self.bubble = new_bubble return AnimationGroup( ReplacementTransform(old_bubble, new_bubble), FadeTransform(old_bubble.content, new_bubble.content), self.change(mode, look_at) ) def debubble(self, mode="plain", look_at=None, **kwargs): if self.bubble is None: logging.log( logging.WARNING, f"Calling debubble on PiCreature with no bubble", ) return self.change(mode, look_at) from custom.characters.pi_creature_animations import RemovePiCreatureBubble result = RemovePiCreatureBubble( self, target_mode=mode, look_at=look_at, **kwargs ) self.bubble = None return result class Randolph(PiCreature): pass # Nothing more than an alternative name class Mortimer(PiCreature): def __init__( self, mode: str = "plain", color: ManimColor=GREY_BROWN, flip_at_start: bool = True, **kwargs, ): super().__init__(mode, color, flip_at_start=flip_at_start, **kwargs) class Mathematician(PiCreature): def __init__(self, mode: str = "plain", color: ManimColor = GREY, **kwargs): super().__init__(mode, color, **kwargs) class BabyPiCreature(PiCreature): def __init__( self, mode: str = "plain", height: float = 1.5, eye_scale_factor: float = 1.2, pupil_scale_factor: float = 1.3, **kwargs ): super().__init__(mode, height=height, **kwargs) eyes = self.eyes eyes_bottom = eyes.get_bottom() eyes.scale(eye_scale_factor) eyes.move_to(eyes_bottom, aligned_edge=DOWN) looking_direction = self.get_looking_direction() for eye in eyes: eye.pupil.scale(pupil_scale_factor) self.look(looking_direction) class TauCreature(PiCreature): # TODO, this currently does nothing file_name_prefix: str = "TauCreatures" class ThreeLeggedPiCreature(PiCreature): # TODO, this currently does nothing file_name_prefix: str = "ThreeLeggedPiCreatures" # TODO, it'd be better to rewrite this so that # the pi creature eyes from above are an instance # of this, rather than the logic going the other way # around class Eyes(VGroup): def __init__( self, body: VMobject, height: float = 0.3, mode: str = "plain", **kwargs ): super().__init__(**kwargs) self.create_eyes(mode, height, body.get_top()) def create_eyes( self, mode: str, height: float, bottom: Vect3, look_at: Vect3 | Mobject | None = None ): self.mode = mode pi = PiCreature(mode=mode) pi.eyes.set_height(height) pi.eyes.move_to(bottom, DOWN) if look_at is not None: pi.look_at(look_at) self.set_submobjects(list(pi.eyes)) def change_mode(self, mode, look_at=None): self.create_eyes(mode, self.get_height(), self.get_bottom(), look_at) return self def look_at(self, target): self.create_eyes(self.mode, self.get_height(), self.get_bottom(), target) def blink(self, **kwargs): # TODO, change Blink bottom_y = self.get_bottom()[1] for submob in self: submob.apply_function( lambda p: np.array([p[0], bottom_y, p[2]]) ) return self
from __future__ import annotations from collections.abc import Iterable import random from manimlib.animation.transform import ReplacementTransform from manimlib.animation.transform import Transform from manimlib.animation.transform import ApplyMethod from manimlib.animation.composition import LaggedStart from manimlib.animation.fading import FadeIn from manimlib.animation.fading import FadeTransform from manimlib.constants import * from manimlib.mobject.mobject import Group from manimlib.mobject.frame import ScreenRectangle from manimlib.mobject.frame import FullScreenFadeRectangle from manimlib.mobject.svg.drawings import SpeechBubble from manimlib.mobject.svg.drawings import ThoughtBubble from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.interactive_scene import InteractiveScene from manimlib.scene.scene import Scene from manimlib.utils.rate_functions import squish_rate_func from manimlib.utils.rate_functions import there_and_back from manimlib.utils.space_ops import get_norm from custom.characters.pi_creature import Mortimer from custom.characters.pi_creature import PiCreature from custom.characters.pi_creature import Randolph from custom.characters.pi_creature_animations import Blink from custom.characters.pi_creature_animations import PiCreatureBubbleIntroduction from custom.characters.pi_creature_animations import RemovePiCreatureBubble from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor, Vect3 class PiCreatureScene(InteractiveScene): total_wait_time: float = 0 seconds_to_blink: float = 3 pi_creatures_start_on_screen: bool = True default_pi_creature_kwargs: dict = dict( color=BLUE, flip_at_start=False, ) default_pi_creature_start_corner: Vect3 = DL def setup(self): super().setup() self.pi_creatures = VGroup(*self.create_pi_creatures()) self.pi_creature = self.get_primary_pi_creature() if self.pi_creatures_start_on_screen: self.add(*self.pi_creatures) def create_pi_creatures(self) -> VGroup | Iterable[PiCreature]: """ Likely updated for subclasses """ return [self.create_pi_creature()] def create_pi_creature(self) -> PiCreature: pi_creature = PiCreature(**self.default_pi_creature_kwargs) pi_creature.to_corner(self.default_pi_creature_start_corner) return pi_creature def get_pi_creatures(self) -> VGroup: return self.pi_creatures def get_primary_pi_creature(self) -> PiCreature: return self.pi_creatures[0] def any_pi_creatures_on_screen(self): return len(self.get_on_screen_pi_creatures()) > 0 def get_on_screen_pi_creatures(self): mobjects = self.get_mobject_family_members() return VGroup(*( pi for pi in self.get_pi_creatures() if pi in mobjects )) def pi_changes(self, *modes, look_at=None, lag_ratio=0.5, run_time=1): return LaggedStart( *( pi.change(mode, look_at) for pi, mode in zip(self.pi_creatures, modes) if mode is not None ), lag_ratio=lag_ratio, run_time=1, ) def introduce_bubble( self, pi_creature, content, bubble_type=SpeechBubble, target_mode=None, look_at=None, bubble_config=dict(), bubble_removal_kwargs=dict(), added_anims=[], **kwargs ): if target_mode is None: target_mode = "thinking" if bubble_type is ThoughtBubble else "speaking" anims = [] on_screen_mobjects = self.get_mobject_family_members() pi_creatures_with_bubbles = [ pi for pi in self.get_pi_creatures() if pi.bubble in on_screen_mobjects ] if pi_creature in pi_creatures_with_bubbles: pi_creatures_with_bubbles.remove(pi_creature) old_bubble = pi_creature.bubble bubble = pi_creature.get_bubble( content, bubble_type=bubble_type, **bubble_config ) anims += [ ReplacementTransform(old_bubble, bubble), FadeTransform(old_bubble.content, bubble.content), pi_creature.change(target_mode, look_at) ] else: anims.append(PiCreatureBubbleIntroduction( pi_creature, content, target_mode=target_mode, bubble_type=bubble_type, bubble_config=bubble_config, **kwargs )) anims += [ RemovePiCreatureBubble(pi, **bubble_removal_kwargs) for pi in pi_creatures_with_bubbles ] anims += added_anims self.play(*anims, **kwargs) def pi_creature_says(self, pi_creature, content, **kwargs): self.introduce_bubble(pi_creature, content, bubble_type=SpeechBubble, **kwargs) def pi_creature_thinks(self, pi_creature, content, **kwargs): self.introduce_bubble(pi_creature, content, bubble_type=ThoughtBubble, **kwargs) def say(self, content, **kwargs): self.pi_creature_says(self.get_primary_pi_creature(), content, **kwargs) def think(self, content, **kwargs): self.pi_creature_thinks(self.get_primary_pi_creature(), content, **kwargs) def anims_from_play_args(self, *args, **kwargs): """ Add animations so that all pi creatures look at the first mobject being animated with each .play call """ animations = super().anims_from_play_args(*args, **kwargs) anim_mobjects = Group(*[a.mobject for a in animations]) all_movers = anim_mobjects.get_family() if not self.any_pi_creatures_on_screen(): return animations pi_creatures = self.get_on_screen_pi_creatures() non_pi_creature_anims = [ anim for anim in animations if len(set(anim.mobject.get_family()).intersection(pi_creatures)) == 0 ] if len(non_pi_creature_anims) == 0: return animations # Get pi creatures to look at whatever # is being animated first_anim = non_pi_creature_anims[0] if hasattr(first_anim, "target_mobject") and first_anim.target_mobject is not None: main_mobject = first_anim.target_mobject else: main_mobject = first_anim.mobject for pi_creature in pi_creatures: if pi_creature not in all_movers: animations.append(ApplyMethod(pi_creature.look_at, main_mobject)) return animations def blink(self): self.play(Blink(random.choice(self.get_on_screen_pi_creatures()))) def joint_blink(self, pi_creatures=None, shuffle=True, **kwargs): if pi_creatures is None: pi_creatures = self.get_on_screen_pi_creatures() creatures_list = list(pi_creatures) if shuffle: random.shuffle(creatures_list) def get_rate_func(pi): index = creatures_list.index(pi) proportion = float(index) / len(creatures_list) start_time = 0.8 * proportion return squish_rate_func( there_and_back, start_time, start_time + 0.2 ) self.play(*[ Blink(pi, rate_func=get_rate_func(pi), **kwargs) for pi in creatures_list ]) return self def wait(self, time=1, blink=True, **kwargs): if "stop_condition" in kwargs: self.non_blink_wait(time, **kwargs) return while time >= 1: time_to_blink = self.total_wait_time % self.seconds_to_blink == 0 if blink and self.any_pi_creatures_on_screen() and time_to_blink: self.blink() else: self.non_blink_wait(**kwargs) time -= 1 self.total_wait_time += 1 if time > 0: self.non_blink_wait(time, **kwargs) return self def non_blink_wait(self, time=1, **kwargs): Scene.wait(self, time, **kwargs) return self def change_mode(self, mode): self.play(self.get_primary_pi_creature().change_mode, mode) def look_at(self, thing_to_look_at, pi_creatures=None, added_anims=None, **kwargs): if pi_creatures is None: pi_creatures = self.get_pi_creatures() anims = [ pi.animate.look_at(thing_to_look_at) for pi in pi_creatures ] if added_anims is not None: anims.extend(added_anims) self.play(*anims, **kwargs) class MortyPiCreatureScene(PiCreatureScene): default_pi_creature_kwargs: dict = dict( color=GREY_BROWN, flip_at_start=True, ) default_pi_creature_start_corner: Vect3 = DR class TeacherStudentsScene(PiCreatureScene): student_colors: list[ManimColor] = [BLUE_D, BLUE_E, BLUE_C] teacher_color: ManimColor = GREY_BROWN background_color: ManimColor = GREY_E student_scale_factor: float = 0.8 seconds_to_blink: float = 2 screen_height: float = 4 def setup(self): super().setup() self.add_background(self.background_color) self.screen = ScreenRectangle( height=self.screen_height, fill_color=BLACK, fill_opacity=1.0, ) self.screen.to_corner(UP + LEFT) self.hold_up_spot = self.teacher.get_corner(UP + LEFT) + MED_LARGE_BUFF * UP def add_background(self, color: ManimColor): self.background = FullScreenFadeRectangle( fill_color=color, fill_opacity=1, ) self.disable_interaction(self.background) self.add(self.background) self.bring_to_back(self.background) def create_pi_creatures(self): self.teacher = Mortimer(color=self.teacher_color) self.teacher.to_corner(DOWN + RIGHT) self.teacher.look(DOWN + LEFT) self.students = VGroup(*[ Randolph(color=c) for c in self.student_colors ]) self.students.arrange(RIGHT) self.students.scale(self.student_scale_factor) self.students.to_corner(DOWN + LEFT) self.teacher.look_at(self.students[-1].eyes) for student in self.students: student.look_at(self.teacher.eyes) return [*self.students, self.teacher] def get_teacher(self): return self.teacher def get_students(self): return self.students def teacher_says(self, content, **kwargs): return self.pi_creature_says(self.get_teacher(), content, **kwargs) def student_says( self, content, target_mode=None, bubble_direction=LEFT, index=2, **kwargs ): if target_mode is None: target_mode = random.choice([ "raise_right_hand", "raise_left_hand", ]) return self.pi_creature_says( self.get_students()[index], content, target_mode=target_mode, bubble_direction=bubble_direction, **kwargs ) def teacher_thinks(self, content, **kwargs): return self.pi_creature_thinks(self.get_teacher(), content, **kwargs) def student_thinks(self, content, target_mode=None, index=2, **kwargs): return self.pi_creature_thinks( self.get_students()[index], content, target_mode=target_mode, **kwargs ) def play_all_student_changes(self, mode, **kwargs): self.play_student_changes(*[mode] * len(self.students), **kwargs) def play_student_changes(self, *modes, **kwargs): added_anims = kwargs.pop("added_anims", []) self.play( self.change_students(*modes, **kwargs), *added_anims ) def change_students(self, *modes, look_at=None, lag_ratio=0.5, run_time=1): return LaggedStart( *( student.change(mode, look_at) for student, mode in zip(self.get_students(), modes) if mode is not None ), lag_ratio=lag_ratio, run_time=1, ) def zoom_in_on_thought_bubble(self, bubble=None, radius=FRAME_Y_RADIUS + FRAME_X_RADIUS): if bubble is None: for pi in self.get_pi_creatures(): if isinstance(pi.bubble, ThoughtBubble): bubble = pi.bubble break if bubble is None: raise Exception("No pi creatures have a thought bubble") vect = -bubble.get_bubble_center() def func(point): centered = point + vect return radius * centered / get_norm(centered) self.play(*[ ApplyPointwiseFunction(func, mob) for mob in self.get_mobjects() ]) def teacher_holds_up(self, mobject, target_mode="raise_right_hand", added_anims=None, **kwargs): mobject.move_to(self.hold_up_spot, DOWN) mobject.shift_onto_screen() added_anims = added_anims or [] self.play( FadeIn(mobject, shift=UP), self.teacher.change(target_mode, mobject), *added_anims )
from manim_imports_ext import * import csv import time from datetime import datetime class SEDTest(MovingCameraScene): def construct(self): file_name1 = "/Users/grant/Desktop/SED_launch_data.csv" file_name2 = "/Users/grant/Desktop/SED_scrub_data.csv" times = [] heart_rates = [] with open(file_name1, newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in reader: try: values = row[0].split(",") timestamp = str(values[8]) heart_rate = int(values[10]) dt = datetime.fromisoformat(timestamp) curr_time = time.mktime(dt.timetuple()) times.append(curr_time) heart_rates.append(heart_rate) except ValueError: continue times = np.array(times) times -= times[0] heart_rates = np.array(heart_rates) average_over = 100 hr_averages = np.array([ np.mean(heart_rates[i:i + average_over]) for i in range(len(heart_rates) - average_over) ]) prop = 10 shown_times = times[::prop] # shown_heart_rates = heart_rates[::prop] shown_heart_rates = hr_averages[::prop] min_time = np.min(times) max_time = np.max(times) min_HR = np.min(heart_rates) max_HR = np.max(heart_rates) axes = Axes( x_min=-1, x_max=12, y_min=0, y_max=130, y_axis_config={ "unit_size": 1.0 / 25, "tick_frequency": 10, } ) axes.to_corner(UL) axes.set_stroke(width=2) def c2p(t, h): t_coord = t / 20 # 20 minute intervals return axes.coords_to_point(t_coord, h) # x_axis_labels = VGroup() # for t in range(0, 190, 60): # point = c2p(t, 0) # label = Integer(t) # label.next_to(point, DOWN, MED_SMALL_BUFF) # x_axis_labels.add(label) # axes.x_axis.add(x_axis_labels) # x_label = OldTexText("Time (minutes)") # x_label.next_to(axes.x_axis, UP, SMALL_BUFF) # x_label.to_edge(RIGHT) # axes.x_axis.add(x_label) y_axis_labels = VGroup() for y in range(50, 150, 50): point = axes.coords_to_point(0, y) label = Integer(y) label.next_to(point, LEFT) y_axis_labels.add(label) axes.y_axis.add(y_axis_labels) y_label = OldTexText("Heart rates") y_label.next_to(axes.y_axis, RIGHT, aligned_edge=UP) axes.y_axis.add(y_label) def point_to_color(point): hr = axes.y_axis.point_to_number(point) ratio = (hr - 50) / (120 - 50) if ratio < 0.5: return interpolate_color(BLUE_D, GREEN, 2 * ratio) else: return interpolate_color(GREEN, RED, 2 * ratio - 1) def get_v_line(t, label=None, **kwargs): line = DashedLine(c2p(t, 0), c2p(t, 120), **kwargs) line.set_stroke(width=2) if label is not None: label_mob = OldTexText(label) label_mob.next_to(line, UP) label_mob.set_color(WHITE) line.label = label_mob return line points = [] for t, hr in zip(shown_times, shown_heart_rates): points.append(c2p(t / 60, hr)) lines = VGroup() for p1, p2, p3, p4 in zip(points, points[1:], points[2:], points[3:]): line = Line(p1, p2) line.set_points_smoothly([p1, p2, p3, p4]) line.set_color(( point_to_color(p1), point_to_color(p2), )) line.set_sheen_direction(line.get_vector()) lines.add(line) lines.set_stroke(width=2) def get_lines_after_value(lines, t): result = VGroup() for line in lines: line_t = axes.x_axis.point_to_number(line.get_center()) line_t *= 20 if t - 7 < line_t < t + 7: result.add(line) # if t < line_t: # alpha = 1 - smooth(abs(line_t - t) / 20) # elif line_t > t - 5: # alpha = 1 - (t - line_t) / 5 # line.set_stroke( # width=interpolate(2, 10, alpha), # opacity=interpolate(0.5, 1, alpha), # ) return result # base_line = Line( # c2p(0, 55), c2p(180, 55), # ) # base_line_label = OldTexText( # "(Felipe's resting HR)" # ) # base_line_label.next_to(base_line, DOWN) # base_line_label.to_edge(RIGHT) # 22:22, yt launch time # 18:32, T-minus 4 # 28:22, separation launch_time = 116 for mark in axes.x_axis.tick_marks: mark.shift(c2p(0, 0) - c2p(4, 0)) if mark.get_center()[0] < c2p(0, 0)[0]: mark.fade(1) times_and_words = [ (launch_time - 60, "T-minus\\\\1 hour"), (launch_time, "Launch!"), (launch_time + 60, "1 hour \\\\ into flight"), ] time_labels = VGroup() for t, words in times_and_words: point = c2p(t, 0) tick = Line(DOWN, UP) tick.set_height(0.5) tick.move_to(point) label = OldTexText(words) label.next_to(tick, DOWN) time_labels.add(VGroup(tick, label)) tm4_time = launch_time - 4 tm4_line = get_v_line(tm4_time, "T-minus 4 (aka Game on!)") tm4_line.label.shift(2 * RIGHT) # self.add(tm4_line) sep1_time = launch_time + 5 + (35 / 60) sep1_line = get_v_line(sep1_time, "First stage separation") sep2_time = launch_time + 37 # Second stage separation sep2_line = get_v_line(sep2_time, "Second stage separation") sep3_time = launch_time + 43 sep3_line = get_v_line(sep3_time, "Third stage (probe) separation") frame = self.camera.frame from _2017.eoc.uncertainty import FalconHeavy rocket = FalconHeavy() rocket.logo.set_fill(WHITE, opacity=0).scale(0) rocket.set_height(1) rocket.move_to(c2p(launch_time, 0)) time_line_pairs = [ (tm4_time, tm4_line), (sep1_time, sep1_line), (sep2_time, sep2_line), (sep3_time, sep3_line), ] # Introduce self.play(Write(axes), run_time=1) self.play( LaggedStartMap(FadeInFromLarge, lines, run_time=5, lag_ratio=0.1) ) self.play(LaggedStartMap(FadeInFromDown, time_labels)) self.wait() # Point indications curr_line = get_v_line(launch_time) last_label = VectorizedPoint() self.play( ShowCreation(curr_line), rocket.to_edge, UP, UpdateFromAlphaFunc( rocket, lambda r, a: r.set_fill( opacity=min(2 - 2 * a, 1), ), remover=True ), run_time=2 ) for t, line in time_line_pairs: post_t_lines = get_lines_after_value(lines, t).copy() flicker = LaggedStartMap( UpdateFromAlphaFunc, post_t_lines, lambda mob: ( mob, lambda l, a: l.set_stroke( width=interpolate(2, 10, a), opacity=interpolate(0.5, 1, a), ) ), rate_func=there_and_back, run_time=1.5 ) self.play( flicker, lines.set_stroke, {"opacity": 0.5}, # ApplyFunction( # lambda m: emphasize_lines_near_value(m, t), # lines, # run_time=1, # lag_ratio=0.5, # ), Transform(curr_line, line), FadeInFromDown(line.label), FadeOut(last_label, DOWN), ) for x in range(3): self.play(flicker) last_label = line.label # self.show_frame() # T -4 spike # Separation of arrays # Deployment of arrays # Indication of power positive
import numpy as np from manimlib.animation.animation import Animation from manimlib.mobject.mobject import Mobject from manimlib.constants import * from manimlib.mobject.svg.tex_mobject import Tex from manimlib.scene.scene import Scene from manimlib.utils.paths import path_along_arc class RearrangeEquation(Scene): def construct( self, start_terms, end_terms, index_map, path_arc=np.pi, start_transform=None, end_transform=None, leave_start_terms=False, transform_kwargs={}, ): transform_kwargs["path_func"] = path_along_arc(path_arc) start_mobs, end_mobs = self.get_mobs_from_terms( start_terms, end_terms ) if start_transform: start_mobs = start_transform(Mobject(*start_mobs)).split() if end_transform: end_mobs = end_transform(Mobject(*end_mobs)).split() unmatched_start_indices = set(range(len(start_mobs))) unmatched_end_indices = set(range(len(end_mobs))) unmatched_start_indices.difference_update( [n % len(start_mobs) for n in index_map] ) unmatched_end_indices.difference_update( [n % len(end_mobs) for n in list(index_map.values())] ) mobject_pairs = [ (start_mobs[a], end_mobs[b]) for a, b in index_map.items() ] + [ (Point(end_mobs[b].get_center()), end_mobs[b]) for b in unmatched_end_indices ] if not leave_start_terms: mobject_pairs += [ (start_mobs[a], Point(start_mobs[a].get_center())) for a in unmatched_start_indices ] self.add(*start_mobs) if leave_start_terms: self.add(Mobject(*start_mobs)) self.wait() self.play(*[ Transform(*pair, **transform_kwargs) for pair in mobject_pairs ]) self.wait() def get_mobs_from_terms(self, start_terms, end_terms): """ Need to ensure that all image mobjects for a tex expression stemming from the same string are point-for-point copies of one and other. This makes transitions much smoother, and not look like point-clouds. """ num_start_terms = len(start_terms) all_mobs = np.array( OldTex(start_terms).split() + OldTex(end_terms).split()) all_terms = np.array(start_terms + end_terms) for term in set(all_terms): matches = all_terms == term if sum(matches) > 1: base_mob = all_mobs[list(all_terms).index(term)] all_mobs[matches] = [ base_mob.copy().replace(target_mob) for target_mob in all_mobs[matches] ] return all_mobs[:num_start_terms], all_mobs[num_start_terms:] class FlipThroughSymbols(Animation): def __init__( self, tex_list, start_center=ORIGIN, end_center=ORIGIN, **kwargs ): self.tex_list = tex_list self.start_center = start_center self.end_center = end_center mobject = OldTex(self.curr_tex).shift(start_center) Animation.__init__(self, mobject, **kwargs) def interpolate_mobject(self, alpha): new_tex = self.tex_list[np.ceil(alpha * len(self.tex_list)) - 1] if new_tex != self.curr_tex: self.curr_tex = new_tex self.mobject = OldTex(new_tex).shift(self.start_center) if not all(self.start_center == self.end_center): self.mobject.center().shift( (1 - alpha) * self.start_center + alpha * self.end_center )
import numpy as np from manimlib.animation.creation import ShowCreation from manimlib.animation.fading import FadeOut from manimlib.animation.transform import ApplyMethod from manimlib.animation.transform import Transform from manimlib.constants import * from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Line from manimlib.mobject.matrix import Matrix from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.scene import Scene class NumericalMatrixMultiplication(Scene): left_matrix = [[1, 2], [3, 4]] right_matrix = [[5, 6], [7, 8]] use_parens = True def construct(self): left_string_matrix, right_string_matrix = [ np.array(matrix).astype("string") for matrix in (self.left_matrix, self.right_matrix) ] if right_string_matrix.shape[0] != left_string_matrix.shape[1]: raise Exception("Incompatible shapes for matrix multiplication") left = Matrix(left_string_matrix) right = Matrix(right_string_matrix) result = self.get_result_matrix( left_string_matrix, right_string_matrix ) self.organize_matrices(left, right, result) self.animate_product(left, right, result) def get_result_matrix(self, left, right): (m, k), n = left.shape, right.shape[1] mob_matrix = np.array([VGroup()]).repeat(m * n).reshape((m, n)) for a in range(m): for b in range(n): template = "(%s)(%s)" if self.use_parens else "%s%s" parts = [ prefix + template % (left[a][c], right[c][b]) for c in range(k) for prefix in ["" if c == 0 else "+"] ] mob_matrix[a][b] = OldTex(parts, next_to_buff=0.1) return Matrix(mob_matrix) def add_lines(self, left, right): line_kwargs = { "color": BLUE, "stroke_width": 2, } left_rows = [ VGroup(*row) for row in left.get_mob_matrix() ] h_lines = VGroup() for row in left_rows[:-1]: h_line = Line(row.get_left(), row.get_right(), **line_kwargs) h_line.next_to(row, DOWN, buff=left.v_buff / 2.) h_lines.add(h_line) right_cols = [ VGroup(*col) for col in np.transpose(right.get_mob_matrix()) ] v_lines = VGroup() for col in right_cols[:-1]: v_line = Line(col.get_top(), col.get_bottom(), **line_kwargs) v_line.next_to(col, RIGHT, buff=right.h_buff / 2.) v_lines.add(v_line) self.play(ShowCreation(h_lines)) self.play(ShowCreation(v_lines)) self.wait() self.show_frame() def organize_matrices(self, left, right, result): equals = OldTex("=") everything = VGroup(left, right, equals, result) everything.arrange() everything.set_width(FRAME_WIDTH - 1) self.add(everything) def animate_product(self, left, right, result): l_matrix = left.get_mob_matrix() r_matrix = right.get_mob_matrix() result_matrix = result.get_mob_matrix() circle = Circle( radius=l_matrix[0][0].get_height(), color=GREEN ) circles = VGroup(*[ entry.get_point_mobject() for entry in (l_matrix[0][0], r_matrix[0][0]) ]) (m, k), n = l_matrix.shape, r_matrix.shape[1] for mob in result_matrix.flatten(): mob.set_color(BLACK) lagging_anims = [] for a in range(m): for b in range(n): for c in range(k): l_matrix[a][c].set_color(YELLOW) r_matrix[c][b].set_color(YELLOW) for c in range(k): start_parts = VGroup( l_matrix[a][c].copy(), r_matrix[c][b].copy() ) result_entry = result_matrix[a][b].split()[c] new_circles = VGroup(*[ circle.copy().shift(part.get_center()) for part in start_parts.split() ]) self.play(Transform(circles, new_circles)) self.play( Transform( start_parts, result_entry.copy().set_color(YELLOW), path_arc=-np.pi / 2, lag_ratio=0, ), *lagging_anims ) result_entry.set_color(YELLOW) self.remove(start_parts) lagging_anims = [ ApplyMethod(result_entry.set_color, WHITE) ] for c in range(k): l_matrix[a][c].set_color(WHITE) r_matrix[c][b].set_color(WHITE) self.play(FadeOut(circles), *lagging_anims) self.wait()
from manimlib.animation.transform import Transform from manimlib.constants import * from manimlib.mobject.mobject import Mobject from manimlib.scene.scene import Scene class ReconfigurableScene(Scene): """ Note, this seems to no longer work as intented. """ CONFIG = { "allow_recursion": True, } def setup(self): self.states = [] self.num_recursions = 0 def transition_to_alt_config( self, return_to_original_configuration=True, transformation_kwargs=None, **new_config ): if transformation_kwargs is None: transformation_kwargs = {} original_state = self.get_state() state_copy = original_state.copy() self.states.append(state_copy) if not self.allow_recursion: return alt_scene = self.__class__( skip_animations=True, allow_recursion=False, **new_config ) alt_state = alt_scene.states[len(self.states) - 1] if return_to_original_configuration: self.clear() self.transition_between_states( state_copy, alt_state, **transformation_kwargs ) self.transition_between_states( state_copy, original_state, **transformation_kwargs ) self.clear() self.add(*original_state) else: self.transition_between_states( original_state, alt_state, **transformation_kwargs ) self.__dict__.update(new_config) def get_state(self): # Want to return a mobject that maintains the most # structure. The way to do that is to extract only # those that aren't inside another. return Mobject(*self.get_top_level_mobjects()) def transition_between_states(self, start_state, target_state, **kwargs): self.play(Transform(start_state, target_state, **kwargs)) self.wait()
from functools import reduce import random from manimlib.constants import * # from manimlib.for_3b1b_videos.pi_creature import PiCreature # from manimlib.for_3b1b_videos.pi_creature import Randolph # from manimlib.for_3b1b_videos.pi_creature import get_all_pi_creature_modes from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Polygon from manimlib.mobject.geometry import RegularPolygon from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import interpolate from manimlib.utils.color import color_gradient from manimlib.utils.dict_ops import digest_config from manimlib.utils.space_ops import center_of_mass from manimlib.utils.space_ops import compass_directions from manimlib.utils.space_ops import rotate_vector from manimlib.utils.space_ops import rotation_matrix def rotate(points, angle=np.pi, axis=OUT): if axis is None: return points matrix = rotation_matrix(angle, axis) points = np.dot(points, np.transpose(matrix)) return points def fractalify(vmobject, order=3, *args, **kwargs): for x in range(order): fractalification_iteration(vmobject) return vmobject def fractalification_iteration(vmobject, dimension=1.05, num_inserted_anchors_range=list(range(1, 4))): num_points = vmobject.get_num_points() if num_points > 0: # original_anchors = vmobject.get_anchors() original_anchors = [ vmobject.point_from_proportion(x) for x in np.linspace(0, 1 - 1. / num_points, num_points) ] new_anchors = [] for p1, p2, in zip(original_anchors, original_anchors[1:]): num_inserts = random.choice(num_inserted_anchors_range) inserted_points = [ interpolate(p1, p2, alpha) for alpha in np.linspace(0, 1, num_inserts + 2)[1:-1] ] mass_scaling_factor = 1. / (num_inserts + 1) length_scaling_factor = mass_scaling_factor**(1. / dimension) target_length = get_norm(p1 - p2) * length_scaling_factor curr_length = get_norm(p1 - p2) * mass_scaling_factor # offset^2 + curr_length^2 = target_length^2 offset_len = np.sqrt(target_length**2 - curr_length**2) unit_vect = (p1 - p2) / get_norm(p1 - p2) offset_unit_vect = rotate_vector(unit_vect, np.pi / 2) inserted_points = [ point + u * offset_len * offset_unit_vect for u, point in zip(it.cycle([-1, 1]), inserted_points) ] new_anchors += [p1] + inserted_points new_anchors.append(original_anchors[-1]) vmobject.set_points_as_corners(new_anchors) vmobject.set_submobjects([ fractalification_iteration( submob, dimension, num_inserted_anchors_range) for submob in vmobject.submobjects ]) return vmobject class SelfSimilarFractal(VMobject): order = 5 num_subparts = 3 height = 4 colors = [RED, WHITE] stroke_width = 1 # Not the right way to assign stroke width fill_opacity = 1 # Not the right way to assign fill opacity def init_colors(self): VMobject.init_colors(self) self.set_color_by_gradient(*self.colors) def init_points(self): order_n_self = self.get_order_n_self(self.order) if self.order == 0: self.set_submobjects([order_n_self]) else: self.set_submobjects(order_n_self.submobjects) return self def get_order_n_self(self, order): if order == 0: result = self.get_seed_shape() else: lower_order = self.get_order_n_self(order - 1) subparts = [ lower_order.copy() for x in range(self.num_subparts) ] self.arrange_subparts(*subparts) result = VGroup(*subparts) result.set_height(self.height) result.center() return result def get_seed_shape(self): raise Exception("Not implemented") def arrange_subparts(self, *subparts): raise Exception("Not implemented") class Sierpinski(SelfSimilarFractal): def get_seed_shape(self): return Polygon( RIGHT, np.sqrt(3) * UP, LEFT, ) def arrange_subparts(self, *subparts): tri1, tri2, tri3 = subparts tri1.move_to(tri2.get_corner(DOWN + LEFT), UP) tri3.move_to(tri2.get_corner(DOWN + RIGHT), UP) class DiamondFractal(SelfSimilarFractal): num_subparts = 4 height = 4 colors = [GREEN_E, YELLOW] def get_seed_shape(self): return RegularPolygon(n=4) def arrange_subparts(self, *subparts): # VGroup(*subparts).rotate(np.pi/4) for part, vect in zip(subparts, compass_directions(start_vect=UP + RIGHT)): part.next_to(ORIGIN, vect, buff=0) VGroup(*subparts).rotate(np.pi / 4, about_point=ORIGIN) class PentagonalFractal(SelfSimilarFractal): num_subparts = 5 colors = [MAROON_B, YELLOW, RED] height = 6 def get_seed_shape(self): return RegularPolygon(n=5, start_angle=np.pi / 2) def arrange_subparts(self, *subparts): for x, part in enumerate(subparts): part.shift(0.95 * part.get_height() * UP) part.rotate(2 * np.pi * x / 5, about_point=ORIGIN) class PentagonalPiCreatureFractal(PentagonalFractal): def init_colors(self): SelfSimilarFractal.init_colors(self) internal_pis = [ pi for pi in self.get_family() if isinstance(pi, PiCreature) ] colors = color_gradient(self.colors, len(internal_pis)) for pi, color in zip(internal_pis, colors): pi.init_colors() pi.body.set_stroke(color, width=0.5) pi.set_color(color) def get_seed_shape(self): return Randolph(mode="shruggie") def arrange_subparts(self, *subparts): for part in subparts: part.rotate(2 * np.pi / 5, about_point=ORIGIN) PentagonalFractal.arrange_subparts(self, *subparts) class PiCreatureFractal(VMobject): order = 7 scale_val = 2.5 start_mode = "hooray" height = 6 colors = [ BLUE_D, BLUE_B, MAROON_B, MAROON_D, GREY, YELLOW, RED, GREY_BROWN, RED, RED_E, ] random_seed = 0 stroke_width = 0 def init_colors(self): VMobject.init_colors(self) internal_pis = [ pi for pi in self.get_family() if isinstance(pi, PiCreature) ] random.seed(self.random_seed) for pi in reversed(internal_pis): color = random.choice(self.colors) pi.set_color(color) pi.set_stroke(color, width=0) def init_points(self): random.seed(self.random_seed) modes = get_all_pi_creature_modes() seed = PiCreature(mode=self.start_mode) seed.set_height(self.height) seed.to_edge(DOWN) creatures = [seed] self.add(VGroup(seed)) for x in range(self.order): new_creatures = [] for creature in creatures: for eye, vect in zip(creature.eyes, [LEFT, RIGHT]): new_creature = PiCreature( mode=random.choice(modes) ) new_creature.set_height( self.scale_val * eye.get_height() ) new_creature.next_to( eye, vect, buff=0, aligned_edge=DOWN ) new_creatures.append(new_creature) creature.look_at(random.choice(new_creatures)) self.add_to_back(VGroup(*new_creatures)) creatures = new_creatures # def init_colors(self): # VMobject.init_colors(self) # self.set_color_by_gradient(*self.colors) class WonkyHexagonFractal(SelfSimilarFractal): num_subparts = 7 def get_seed_shape(self): return RegularPolygon(n=6) def arrange_subparts(self, *subparts): for i, piece in enumerate(subparts): piece.rotate(i * np.pi / 12, about_point=ORIGIN) p1, p2, p3, p4, p5, p6, p7 = subparts center_row = VGroup(p1, p4, p7) center_row.arrange(RIGHT, buff=0) for p in p2, p3, p5, p6: p.set_width(p1.get_width()) p2.move_to(p1.get_top(), DOWN + LEFT) p3.move_to(p1.get_bottom(), UP + LEFT) p5.move_to(p4.get_top(), DOWN + LEFT) p6.move_to(p4.get_bottom(), UP + LEFT) class CircularFractal(SelfSimilarFractal): num_subparts = 3 colors = [GREEN, BLUE, GREY] def get_seed_shape(self): return Circle() def arrange_subparts(self, *subparts): if not hasattr(self, "been_here"): self.num_subparts = 3 + self.order self.been_here = True for i, part in enumerate(subparts): theta = np.pi / self.num_subparts part.next_to( ORIGIN, UP, buff=self.height / (2 * np.tan(theta)) ) part.rotate(i * 2 * np.pi / self.num_subparts, about_point=ORIGIN) self.num_subparts -= 1 ######## Space filling curves ############ class JaggedCurvePiece(VMobject): def insert_n_curves(self, n): if self.get_num_curves() == 0: self.set_points(np.zeros((1, 3))) anchors = self.get_anchors() indices = np.linspace( 0, len(anchors) - 1, n + len(anchors) ).astype('int') self.set_points_as_corners(anchors[indices]) class FractalCurve(VMobject): radius = 3 order = 5 colors = [RED, GREEN] num_submobjects = 20 monochromatic = False order_to_stroke_width_map = { 3: 3, 4: 2, 5: 1, } def init_points(self): points = self.get_anchor_points() self.set_points_as_corners(points) if not self.monochromatic: alphas = np.linspace(0, 1, self.num_submobjects) for alpha_pair in zip(alphas, alphas[1:]): submobject = JaggedCurvePiece() submobject.pointwise_become_partial( self, *alpha_pair ) self.add(submobject) self.set_points(np.zeros((0, 3))) def init_colors(self): VMobject.init_colors(self) self.set_color_by_gradient(*self.colors) for order in sorted(self.order_to_stroke_width_map.keys()): if self.order >= order: self.set_stroke(width=self.order_to_stroke_width_map[order]) def get_anchor_points(self): raise Exception("Not implemented") class LindenmayerCurve(FractalCurve): axiom = "A" rule = {} scale_factor = 2 radius = 3 start_step = RIGHT angle = np.pi / 2 def expand_command_string(self, command): result = "" for letter in command: if letter in self.rule: result += self.rule[letter] else: result += letter return result def get_command_string(self): result = self.axiom for x in range(self.order): result = self.expand_command_string(result) return result def get_anchor_points(self): step = float(self.radius) * self.start_step step /= (self.scale_factor**self.order) curr = np.zeros(3) result = [curr] for letter in self.get_command_string(): if letter == "+": step = rotate(step, self.angle) elif letter == "-": step = rotate(step, -self.angle) else: curr = curr + step result.append(curr) return np.array(result) - center_of_mass(result) class SelfSimilarSpaceFillingCurve(FractalCurve): offsets = [] # keys must awkwardly be in string form... offset_to_rotation_axis = {} scale_factor = 2 radius_scale_factor = 0.5 def transform(self, points, offset): """ How to transform the copy of points shifted by offset. Generally meant to be extended in subclasses """ copy = np.array(points) if str(offset) in self.offset_to_rotation_axis: copy = rotate( copy, axis=self.offset_to_rotation_axis[str(offset)] ) copy /= self.scale_factor, copy += offset * self.radius * self.radius_scale_factor return copy def refine_into_subparts(self, points): transformed_copies = [ self.transform(points, offset) for offset in self.offsets ] return reduce( lambda a, b: np.append(a, b, axis=0), transformed_copies ) def get_anchor_points(self): points = np.zeros((1, 3)) for count in range(self.order): points = self.refine_into_subparts(points) return points def generate_grid(self): raise Exception("Not implemented") class HilbertCurve(SelfSimilarSpaceFillingCurve): offsets = [ LEFT + DOWN, LEFT + UP, RIGHT + UP, RIGHT + DOWN, ] offset_to_rotation_axis = { str(LEFT + DOWN): RIGHT + UP, str(RIGHT + DOWN): RIGHT + DOWN, } class HilbertCurve3D(SelfSimilarSpaceFillingCurve): offsets = [ RIGHT + DOWN + IN, LEFT + DOWN + IN, LEFT + DOWN + OUT, RIGHT + DOWN + OUT, RIGHT + UP + OUT, LEFT + UP + OUT, LEFT + UP + IN, RIGHT + UP + IN, ] offset_to_rotation_axis_and_angle = { str(RIGHT + DOWN + IN): (LEFT + UP + OUT, 2 * np.pi / 3), str(LEFT + DOWN + IN): (RIGHT + DOWN + IN, 2 * np.pi / 3), str(LEFT + DOWN + OUT): (RIGHT + DOWN + IN, 2 * np.pi / 3), str(RIGHT + DOWN + OUT): (UP, np.pi), str(RIGHT + UP + OUT): (UP, np.pi), str(LEFT + UP + OUT): (LEFT + DOWN + OUT, 2 * np.pi / 3), str(LEFT + UP + IN): (LEFT + DOWN + OUT, 2 * np.pi / 3), str(RIGHT + UP + IN): (RIGHT + UP + IN, 2 * np.pi / 3), } # Rewrote transform method to include the rotation angle def transform(self, points, offset): copy = np.array(points) copy = rotate( copy, axis=self.offset_to_rotation_axis_and_angle[str(offset)][0], angle=self.offset_to_rotation_axis_and_angle[str(offset)][1], ) copy /= self.scale_factor, copy += offset * self.radius * self.radius_scale_factor return copy class PeanoCurve(SelfSimilarSpaceFillingCurve): colors = [PURPLE, TEAL] offsets = [ LEFT + DOWN, LEFT, LEFT + UP, UP, ORIGIN, DOWN, RIGHT + DOWN, RIGHT, RIGHT + UP, ] offset_to_rotation_axis = { str(LEFT): UP, str(UP): RIGHT, str(ORIGIN): LEFT + UP, str(DOWN): RIGHT, str(RIGHT): UP, } scale_factor = 3 radius_scale_factor = 2.0 / 3 class TriangleFillingCurve(SelfSimilarSpaceFillingCurve): colors = [MAROON, YELLOW] offsets = [ LEFT / 4. + DOWN / 6., ORIGIN, RIGHT / 4. + DOWN / 6., UP / 3., ] offset_to_rotation_axis = { str(ORIGIN): RIGHT, str(UP / 3.): UP, } scale_factor = 2 radius_scale_factor = 1.5 class HexagonFillingCurve(SelfSimilarSpaceFillingCurve): start_color = WHITE end_color = BLUE_D axis_offset_pairs = [ (None, 1.5*DOWN + 0.5*np.sqrt(3)*LEFT), (UP+np.sqrt(3)*RIGHT, 1.5*DOWN + 0.5*np.sqrt(3)*RIGHT), (np.sqrt(3)*UP+RIGHT, ORIGIN), ((UP, RIGHT), np.sqrt(3)*LEFT), (None, 1.5*UP + 0.5*np.sqrt(3)*LEFT), (None, 1.5*UP + 0.5*np.sqrt(3)*RIGHT), (RIGHT, np.sqrt(3)*RIGHT), ] scale_factor = 3 radius_scale_factor = 2/(3*np.sqrt(3)) def refine_into_subparts(self, points): return SelfSimilarSpaceFillingCurve.refine_into_subparts( self, rotate(points, np.pi/6, IN) ) class UtahFillingCurve(SelfSimilarSpaceFillingCurve): colors = [WHITE, BLUE_D] axis_offset_pairs = [] scale_factor = 3 radius_scale_factor = 2 / (3 * np.sqrt(3)) class FlowSnake(LindenmayerCurve): colors = [YELLOW, GREEN] axiom = "A" rule = { "A": "A-B--B+A++AA+B-", "B": "+A-BB--B-A++A+B", } radius = 6 # TODO, this is innaccurate scale_factor = np.sqrt(7) start_step = RIGHT angle = -np.pi / 3 def __init__(self, **kwargs): LindenmayerCurve.__init__(self, **kwargs) self.rotate(-self.order * np.pi / 9, about_point=ORIGIN) class SierpinskiCurve(LindenmayerCurve): colors = [RED, WHITE] axiom = "B" rule = { "A": "+B-A-B+", "B": "-A+B+A-", } radius = 6 # TODO, this is innaccurate scale_factor = 2 start_step = RIGHT angle = -np.pi / 3 class KochSnowFlake(LindenmayerCurve): colors = [BLUE_D, WHITE, BLUE_D] axiom = "A--A--A--" rule = { "A": "A+A--A+A" } radius = 4 scale_factor = 3 start_step = RIGHT angle = np.pi / 3 order_to_stroke_width_map = { 3: 3, 5: 2, 6: 1, } def __init__(self, **kwargs): digest_config(self, kwargs) self.scale_factor = 2 * (1 + np.cos(self.angle)) LindenmayerCurve.__init__(self, **kwargs) class KochCurve(KochSnowFlake): axiom = "A--" class QuadraticKoch(LindenmayerCurve): colors = [YELLOW, WHITE, MAROON_B] axiom = "A" rule = {"A": "A+A-A-AA+A+A-A"} radius = 4 scale_factor = 4 start_step = RIGHT angle = np.pi / 2 class QuadraticKochIsland(QuadraticKoch): axiom = "A+A+A+A" class StellarCurve(LindenmayerCurve): start_color = RED end_color = BLUE_E rule = { "A": "+B-A-B+A-B+", "B": "-A+B+A-B+A-", } scale_factor = 3 angle = 2 * np.pi / 5 class SnakeCurve(FractalCurve): start_color = BLUE end_color = YELLOW def get_anchor_points(self): result = [] resolution = 2**self.order step = 2.0 * self.radius / resolution lower_left = ORIGIN + \ LEFT * (self.radius - step / 2) + \ DOWN * (self.radius - step / 2) for y in range(resolution): x_range = list(range(resolution)) if y % 2 == 0: x_range.reverse() for x in x_range: result.append( lower_left + x * step * RIGHT + y * step * UP ) return result
from traceback import * from scipy.spatial import ConvexHull from manimlib.animation.composition import LaggedStartMap from manimlib.animation.fading import FadeIn from manimlib.animation.fading import FadeOut from manimlib.animation.transform import Transform from manimlib.constants import * from manimlib.mobject.geometry import AnnularSector from manimlib.mobject.geometry import Annulus from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.types.vectorized_mobject import VectorizedPoint from manimlib.utils.space_ops import angle_between_vectors from manimlib.utils.space_ops import project_along_vector from manimlib.utils.space_ops import rotate_vector from manimlib.utils.space_ops import z_to_vector LIGHT_COLOR = YELLOW SHADOW_COLOR = BLACK SWITCH_ON_RUN_TIME = 1.5 FAST_SWITCH_ON_RUN_TIME = 0.1 NUM_LEVELS = 30 NUM_CONES = 7 # in first lighthouse scene NUM_VISIBLE_CONES = 5 # ibidem ARC_TIP_LENGTH = 0.2 AMBIENT_FULL = 0.8 AMBIENT_DIMMED = 0.5 SPOTLIGHT_FULL = 0.8 SPOTLIGHT_DIMMED = 0.5 LIGHTHOUSE_HEIGHT = 0.8 DEGREES = TAU / 360 def inverse_power_law(maxint, scale, cutoff, exponent): return (lambda r: maxint * (cutoff / (r / scale + cutoff))**exponent) def inverse_quadratic(maxint, scale, cutoff): return inverse_power_law(maxint, scale, cutoff, 2) class SwitchOn(LaggedStartMap): CONFIG = { "lag_ratio": 0.2, "run_time": SWITCH_ON_RUN_TIME } def __init__(self, light, **kwargs): if (not isinstance(light, AmbientLight) and not isinstance(light, Spotlight)): raise Exception( "Only AmbientLights and Spotlights can be switched on") LaggedStartMap.__init__( self, FadeIn, light, **kwargs ) class SwitchOff(LaggedStartMap): CONFIG = { "lag_ratio": 0.2, "run_time": SWITCH_ON_RUN_TIME } def __init__(self, light, **kwargs): if (not isinstance(light, AmbientLight) and not isinstance(light, Spotlight)): raise Exception( "Only AmbientLights and Spotlights can be switched off") light.set_submobjects(light.submobjects[::-1]) LaggedStartMap.__init__(self, FadeOut, light, **kwargs) light.set_submobjects(light.submobjects[::-1]) class Lighthouse(SVGMobject): CONFIG = { "height": LIGHTHOUSE_HEIGHT, "fill_color": WHITE, "fill_opacity": 1.0, } def __init__(self, **kwargs): super().__init__("lighthouse", **kwargs) def move_to(self, point): self.next_to(point, DOWN, buff=0) class AmbientLight(VMobject): # Parameters are: # * a source point # * an opacity function # * a light color # * a max opacity # * a radius (larger than the opacity's dropoff length) # * the number of subdivisions (levels, annuli) CONFIG = { "source_point": VectorizedPoint(location=ORIGIN, stroke_width=0, fill_opacity=0), "opacity_function": lambda r: 1.0 / (r + 1.0)**2, "color": LIGHT_COLOR, "max_opacity": 1.0, "num_levels": NUM_LEVELS, "radius": 5.0 } def init_points(self): # in theory, this method is only called once, right? # so removing submobs shd not be necessary # # Note: Usually, yes, it is only called within Mobject.__init__, # but there is no strong guarantee of that, and you may want certain # update functions to regenerate points here and there. for submob in self.submobjects: self.remove(submob) self.add(self.source_point) # create annuli self.radius = float(self.radius) dr = self.radius / self.num_levels for r in np.arange(0, self.radius, dr): alpha = self.max_opacity * self.opacity_function(r) annulus = Annulus( inner_radius=r, outer_radius=r + dr, color=self.color, fill_opacity=alpha ) annulus.move_to(self.get_source_point()) self.add(annulus) def move_source_to(self, point): # old_source_point = self.get_source_point() # self.shift(point - old_source_point) self.move_to(point) return self def get_source_point(self): return self.source_point.get_location() def dimming(self, new_alpha): old_alpha = self.max_opacity self.max_opacity = new_alpha for submob in self.submobjects: old_submob_alpha = submob.fill_opacity new_submob_alpha = old_submob_alpha * new_alpha / old_alpha submob.set_fill(opacity=new_submob_alpha) class Spotlight(VMobject): CONFIG = { "source_point": VectorizedPoint(location=ORIGIN, stroke_width=0, fill_opacity=0), "opacity_function": lambda r: 1.0 / (r / 2 + 1.0)**2, "color": GREEN, # LIGHT_COLOR, "max_opacity": 1.0, "num_levels": 10, "radius": 10.0, "screen": None, "camera_mob": None } def projection_direction(self): # Note: This seems reasonable, though for it to work you'd # need to be sure that any 3d scene including a spotlight # somewhere assigns that spotlights "camera" attribute # to be the camera associated with that scene. if self.camera_mob is None: return OUT else: [phi, theta, r] = self.camera_mob.get_center() v = np.array([np.sin(phi) * np.cos(theta), np.sin(phi) * np.sin(theta), np.cos(phi)]) return v # /get_norm(v) def project(self, point): v = self.projection_direction() w = project_along_vector(point, v) return w def get_source_point(self): return self.source_point.get_location() def init_points(self): self.set_submobjects([]) self.add(self.source_point) if self.screen is not None: # look for the screen and create annular sectors lower_angle, upper_angle = self.viewing_angles(self.screen) self.radius = float(self.radius) dr = self.radius / self.num_levels lower_ray, upper_ray = self.viewing_rays(self.screen) for r in np.arange(0, self.radius, dr): new_sector = self.new_sector(r, dr, lower_angle, upper_angle) self.add(new_sector) def new_sector(self, r, dr, lower_angle, upper_angle): alpha = self.max_opacity * self.opacity_function(r) annular_sector = AnnularSector( inner_radius=r, outer_radius=r + dr, color=self.color, fill_opacity=alpha, start_angle=lower_angle, angle=upper_angle - lower_angle ) # rotate (not project) it into the viewing plane rotation_matrix = z_to_vector(self.projection_direction()) annular_sector.apply_matrix(rotation_matrix) # now rotate it inside that plane rotated_RIGHT = np.dot(RIGHT, rotation_matrix.T) projected_RIGHT = self.project(RIGHT) omega = angle_between_vectors(rotated_RIGHT, projected_RIGHT) annular_sector.rotate(omega, axis=self.projection_direction()) annular_sector.move_arc_center_to(self.get_source_point()) return annular_sector def viewing_angle_of_point(self, point): # as measured from the positive x-axis v1 = self.project(RIGHT) v2 = self.project(np.array(point) - self.get_source_point()) absolute_angle = angle_between_vectors(v1, v2) # determine the angle's sign depending on their plane's # choice of orientation. That choice is set by the camera # position, i. e. projection direction if np.dot(self.projection_direction(), np.cross(v1, v2)) > 0: return absolute_angle else: return -absolute_angle def viewing_angles(self, screen): screen_points = screen.get_anchors() projected_screen_points = list(map(self.project, screen_points)) viewing_angles = np.array(list(map(self.viewing_angle_of_point, projected_screen_points))) lower_angle = upper_angle = 0 if len(viewing_angles) != 0: lower_angle = np.min(viewing_angles) upper_angle = np.max(viewing_angles) if upper_angle - lower_angle > TAU / 2: lower_angle, upper_angle = upper_angle, lower_angle + TAU return lower_angle, upper_angle def viewing_rays(self, screen): lower_angle, upper_angle = self.viewing_angles(screen) projected_RIGHT = self.project( RIGHT) / get_norm(self.project(RIGHT)) lower_ray = rotate_vector( projected_RIGHT, lower_angle, axis=self.projection_direction()) upper_ray = rotate_vector( projected_RIGHT, upper_angle, axis=self.projection_direction()) return lower_ray, upper_ray def opening_angle(self): l, u = self.viewing_angles(self.screen) return u - l def start_angle(self): l, u = self.viewing_angles(self.screen) return l def stop_angle(self): l, u = self.viewing_angles(self.screen) return u def move_source_to(self, point): self.source_point.set_location(np.array(point)) # self.source_point.move_to(np.array(point)) # self.move_to(point) self.update_sectors() return self def update_sectors(self): if self.screen is None: return for submob in self.submobjects: if type(submob) == AnnularSector: lower_angle, upper_angle = self.viewing_angles(self.screen) # dr = submob.outer_radius - submob.inner_radius dr = self.radius / self.num_levels new_submob = self.new_sector( submob.inner_radius, dr, lower_angle, upper_angle ) # submob.points = new_submob.points # submob.set_fill(opacity = 10 * self.opacity_function(submob.outer_radius)) Transform(submob, new_submob).update(1) def dimming(self, new_alpha): old_alpha = self.max_opacity self.max_opacity = new_alpha for submob in self.submobjects: # Note: Maybe it'd be best to have a Shadow class so that the # type can be checked directly? if type(submob) != AnnularSector: # it's the shadow, don't dim it continue old_submob_alpha = submob.fill_opacity new_submob_alpha = old_submob_alpha * new_alpha / old_alpha submob.set_fill(opacity=new_submob_alpha) def change_opacity_function(self, new_f): self.opacity_function = new_f dr = self.radius / self.num_levels sectors = [] for submob in self.submobjects: if type(submob) == AnnularSector: sectors.append(submob) for (r, submob) in zip(np.arange(0, self.radius, dr), sectors): if type(submob) != AnnularSector: # it's the shadow, don't dim it continue alpha = self.opacity_function(r) submob.set_fill(opacity=alpha) # Warning: This class is likely quite buggy. class LightSource(VMobject): # combines: # a lighthouse # an ambient light # a spotlight # and a shadow CONFIG = { "source_point": VectorizedPoint(location=ORIGIN, stroke_width=0, fill_opacity=0), "color": LIGHT_COLOR, "num_levels": 10, "radius": 10.0, "screen": None, "opacity_function": inverse_quadratic(1, 2, 1), "max_opacity_ambient": AMBIENT_FULL, "max_opacity_spotlight": SPOTLIGHT_FULL, "camera_mob": None } def init_points(self): self.add(self.source_point) self.lighthouse = Lighthouse() self.ambient_light = AmbientLight( source_point=VectorizedPoint(location=self.get_source_point()), color=self.color, num_levels=self.num_levels, radius=self.radius, opacity_function=self.opacity_function, max_opacity=self.max_opacity_ambient ) if self.has_screen(): self.spotlight = Spotlight( source_point=VectorizedPoint(location=self.get_source_point()), color=self.color, num_levels=self.num_levels, radius=self.radius, screen=self.screen, opacity_function=self.opacity_function, max_opacity=self.max_opacity_spotlight, camera_mob=self.camera_mob ) else: self.spotlight = Spotlight() self.shadow = VMobject(fill_color=SHADOW_COLOR, fill_opacity=1.0, stroke_color=BLACK) self.lighthouse.next_to(self.get_source_point(), DOWN, buff=0) self.ambient_light.move_source_to(self.get_source_point()) if self.has_screen(): self.spotlight.move_source_to(self.get_source_point()) self.update_shadow() self.add(self.ambient_light, self.spotlight, self.lighthouse, self.shadow) def has_screen(self): if self.screen is None: return False elif self.screen.get_num_points() == 0: return False else: return True def dim_ambient(self): self.set_max_opacity_ambient(AMBIENT_DIMMED) def set_max_opacity_ambient(self, new_opacity): self.max_opacity_ambient = new_opacity self.ambient_light.dimming(new_opacity) def dim_spotlight(self): self.set_max_opacity_spotlight(SPOTLIGHT_DIMMED) def set_max_opacity_spotlight(self, new_opacity): self.max_opacity_spotlight = new_opacity self.spotlight.dimming(new_opacity) def set_camera_mob(self, new_cam_mob): self.camera_mob = new_cam_mob self.spotlight.camera_mob = new_cam_mob def set_screen(self, new_screen): if self.has_screen(): self.spotlight.screen = new_screen else: # Note: See below index = self.submobjects.index(self.spotlight) # camera_mob = self.spotlight.camera_mob self.remove(self.spotlight) self.spotlight = Spotlight( source_point=VectorizedPoint(location=self.get_source_point()), color=self.color, num_levels=self.num_levels, radius=self.radius, screen=new_screen, camera_mob=self.camera_mob, opacity_function=self.opacity_function, max_opacity=self.max_opacity_spotlight, ) self.spotlight.move_source_to(self.get_source_point()) # Note: This line will make spotlight show up at the end # of the submojects list, which can make it show up on # top of the shadow. To make it show up in the # same spot, you could try the following line, # where "index" is what I defined above: self.submobjects.insert(index, self.spotlight) # self.add(self.spotlight) # in any case self.screen = new_screen def move_source_to(self, point): apoint = np.array(point) v = apoint - self.get_source_point() # Note: As discussed, things stand to behave better if source # point is a submobject, so that it automatically interpolates # during an animation, and other updates can be defined wrt # that source point's location self.source_point.set_location(apoint) # self.lighthouse.next_to(apoint,DOWN,buff = 0) # self.ambient_light.move_source_to(apoint) self.lighthouse.shift(v) # self.ambient_light.shift(v) self.ambient_light.move_source_to(apoint) if self.has_screen(): self.spotlight.move_source_to(apoint) self.update() return self def change_spotlight_opacity_function(self, new_of): self.spotlight.change_opacity_function(new_of) def set_radius(self, new_radius): self.radius = new_radius self.ambient_light.radius = new_radius self.spotlight.radius = new_radius def update(self): self.update_lighthouse() self.update_ambient() self.spotlight.update_sectors() self.update_shadow() def update_lighthouse(self): self.lighthouse.move_to(self.get_source_point()) # new_lh = Lighthouse() # new_lh.move_to(ORIGIN) # new_lh.apply_matrix(self.rotation_matrix()) # new_lh.shift(self.get_source_point()) # self.lighthouse.submobjects = new_lh.submobjects def update_ambient(self): new_ambient_light = AmbientLight( source_point=VectorizedPoint(location=ORIGIN), color=self.color, num_levels=self.num_levels, radius=self.radius, opacity_function=self.opacity_function, max_opacity=self.max_opacity_ambient ) new_ambient_light.apply_matrix(self.rotation_matrix()) new_ambient_light.move_source_to(self.get_source_point()) self.ambient_light.set_submobjects(new_ambient_light.submobjects) def get_source_point(self): return self.source_point.get_location() def rotation_matrix(self): if self.camera_mob is None: return np.eye(3) phi = self.camera_mob.get_center()[0] theta = self.camera_mob.get_center()[1] R1 = np.array([ [1, 0, 0], [0, np.cos(phi), -np.sin(phi)], [0, np.sin(phi), np.cos(phi)] ]) R2 = np.array([ [np.cos(theta + TAU / 4), -np.sin(theta + TAU / 4), 0], [np.sin(theta + TAU / 4), np.cos(theta + TAU / 4), 0], [0, 0, 1] ]) R = np.dot(R2, R1) return R def update_shadow(self): point = self.get_source_point() projected_screen_points = [] if not self.has_screen(): return for point in self.screen.get_anchors(): projected_screen_points.append(self.spotlight.project(point)) projected_source = project_along_vector( self.get_source_point(), self.spotlight.projection_direction()) projected_point_cloud_3d = np.append( projected_screen_points, np.reshape(projected_source, (1, 3)), axis=0 ) # z_to_vector(self.spotlight.projection_direction()) rotation_matrix = self.rotation_matrix() back_rotation_matrix = rotation_matrix.T # i. e. its inverse rotated_point_cloud_3d = np.dot( projected_point_cloud_3d, back_rotation_matrix.T) # these points now should all have z = 0 point_cloud_2d = rotated_point_cloud_3d[:, :2] # now we can compute the convex hull hull_2d = ConvexHull(point_cloud_2d) # guaranteed to run ccw hull = [] # we also need the projected source point source_point_2d = np.dot(self.spotlight.project( self.get_source_point()), back_rotation_matrix.T)[:2] index = 0 for point in point_cloud_2d[hull_2d.vertices]: if np.all(np.abs(point - source_point_2d) < 1.0e-6): source_index = index index += 1 continue point_3d = np.array([point[0], point[1], 0]) hull.append(point_3d) index += 1 hull_mobject = VMobject() hull_mobject.set_points_as_corners(hull) hull_mobject.apply_matrix(rotation_matrix) anchors = hull_mobject.get_anchors() # add two control points for the outer cone if np.size(anchors) == 0: self.shadow.resize_points(0) return ray1 = anchors[source_index - 1] - projected_source ray1 = ray1 / get_norm(ray1) * 100 ray2 = anchors[source_index] - projected_source ray2 = ray2 / get_norm(ray2) * 100 outpoint1 = anchors[source_index - 1] + ray1 outpoint2 = anchors[source_index] + ray2 new_anchors = anchors[:source_index] new_anchors = np.append(new_anchors, np.array( [outpoint1, outpoint2]), axis=0) new_anchors = np.append(new_anchors, anchors[source_index:], axis=0) self.shadow.set_points_as_corners(new_anchors) # shift it closer to the camera so it is in front of the spotlight self.shadow.mark_paths_closed = True # Redefining what was once a ContinualAnimation class # as a function def ScreenTracker(light_source): light_source.add_updater(lambda m: m.update()) return light_source
import numpy as np from manimlib.animation.animation import Animation from manimlib.animation.creation import ShowCreation from manimlib.animation.creation import Write from manimlib.animation.fading import FadeOut from manimlib.animation.growing import GrowArrow from manimlib.animation.transform import ApplyFunction from manimlib.animation.transform import ApplyPointwiseFunction from manimlib.animation.transform import Transform from manimlib.constants import BLACK, BLUE_D, GREEN_C, RED_C, GREY, WHITE, YELLOW from manimlib.constants import DL, DOWN, ORIGIN, RIGHT, UP from manimlib.constants import FRAME_WIDTH, FRAME_X_RADIUS, FRAME_Y_RADIUS from manimlib.constants import SMALL_BUFF from manimlib.mobject.coordinate_systems import Axes from manimlib.mobject.coordinate_systems import NumberPlane from manimlib.mobject.geometry import Arrow from manimlib.mobject.geometry import Dot from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import Vector from manimlib.mobject.matrix import Matrix from manimlib.mobject.matrix import VECTOR_LABEL_SCALE_FACTOR from manimlib.mobject.matrix import vector_coordinate_label from manimlib.mobject.mobject import Mobject from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.scene.scene import Scene from manimlib.utils.rate_functions import rush_from from manimlib.utils.rate_functions import rush_into from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import get_norm from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor from typing import List X_COLOR = GREEN_C Y_COLOR = RED_C Z_COLOR = BLUE_D # TODO: Much of this scene type seems dependent on the coordinate system chosen. # That is, being centered at the origin with grid units corresponding to the # arbitrary space units. Change it! # # Also, methods I would have thought of as getters, like coords_to_vector, are # actually doing a lot of animating. class VectorScene(Scene): basis_vector_stroke_width: int = 6 def add_plane(self, animate=False, **kwargs): plane = NumberPlane(**kwargs) if animate: self.play(ShowCreation(plane, lag_ratio=0.5)) self.add(plane) return plane def add_axes(self, animate=False, color=WHITE, **kwargs): axes = Axes(color=color, tick_frequency=1) if animate: self.play(ShowCreation(axes)) self.add(axes) return axes def lock_in_faded_grid(self, dimness=0.7, axes_dimness=0.5): plane = self.add_plane() axes = plane.get_axes() plane.fade(dimness) axes.set_color(WHITE) axes.fade(axes_dimness) self.add(axes) self.freeze_background() def get_vector(self, numerical_vector, **kwargs): return Arrow( self.plane.coords_to_point(0, 0), self.plane.coords_to_point(*numerical_vector[:2]), buff=0, **kwargs ) def add_vector(self, vector, color=YELLOW, animate=True, **kwargs): if not isinstance(vector, Arrow): vector = Vector(vector, color=color, **kwargs) if animate: self.play(GrowArrow(vector)) self.add(vector) return vector def write_vector_coordinates(self, vector, **kwargs): coords = vector_coordinate_label(vector, **kwargs) self.play(Write(coords)) return coords def get_basis_vectors(self, i_hat_color=X_COLOR, j_hat_color=Y_COLOR): return VGroup(*[ Vector( vect, color=color, stroke_width=self.basis_vector_stroke_width ) for vect, color in [ ([1, 0], i_hat_color), ([0, 1], j_hat_color) ] ]) def get_basis_vector_labels(self, **kwargs): i_hat, j_hat = self.get_basis_vectors() return VGroup(*[ self.get_vector_label( vect, label, color=color, label_scale_factor=1, **kwargs ) for vect, label, color in [ (i_hat, "\\hat{\\imath}", X_COLOR), (j_hat, "\\hat{\\jmath}", Y_COLOR), ] ]) def get_vector_label(self, vector, label, at_tip=False, direction="left", rotate=False, color=None, label_scale_factor=VECTOR_LABEL_SCALE_FACTOR): if not isinstance(label, Tex): if len(label) == 1: label = "\\vec{\\textbf{%s}}" % label label = OldTex(label) if color is None: color = vector.get_color() label.set_color(color) label.scale(label_scale_factor) label.add_background_rectangle() if at_tip: vect = vector.get_vector() vect /= get_norm(vect) label.next_to(vector.get_end(), vect, buff=SMALL_BUFF) else: angle = vector.get_angle() if not rotate: label.rotate(-angle, about_point=ORIGIN) if direction == "left": label.shift(-label.get_bottom() + 0.1 * UP) else: label.shift(-label.get_top() + 0.1 * DOWN) label.rotate(angle, about_point=ORIGIN) label.shift((vector.get_end() - vector.get_start()) / 2) return label def label_vector(self, vector, label, animate=True, **kwargs): label = self.get_vector_label(vector, label, **kwargs) if animate: self.play(Write(label, run_time=1)) self.add(label) return label def position_x_coordinate(self, x_coord, x_line, vector): x_coord.next_to(x_line, -np.sign(vector[1]) * UP) x_coord.set_color(X_COLOR) return x_coord def position_y_coordinate(self, y_coord, y_line, vector): y_coord.next_to(y_line, np.sign(vector[0]) * RIGHT) y_coord.set_color(Y_COLOR) return y_coord def coords_to_vector(self, vector, coords_start=2 * RIGHT + 2 * UP, clean_up=True): starting_mobjects = list(self.mobjects) array = Matrix(vector) array.shift(coords_start) arrow = Vector(vector) x_line = Line(ORIGIN, vector[0] * RIGHT) y_line = Line(x_line.get_end(), arrow.get_end()) x_line.set_color(X_COLOR) y_line.set_color(Y_COLOR) x_coord, y_coord = array.get_mob_matrix().flatten() self.play(Write(array, run_time=1)) self.wait() self.play(ApplyFunction( lambda x: self.position_x_coordinate(x, x_line, vector), x_coord )) self.play(ShowCreation(x_line)) self.play( ApplyFunction( lambda y: self.position_y_coordinate(y, y_line, vector), y_coord ), FadeOut(array.get_brackets()) ) y_coord, brackets = self.get_mobjects_from_last_animation() self.play(ShowCreation(y_line)) self.play(ShowCreation(arrow)) self.wait() if clean_up: self.clear() self.add(*starting_mobjects) def vector_to_coords(self, vector, integer_labels=True, clean_up=True): starting_mobjects = list(self.mobjects) show_creation = False if isinstance(vector, Arrow): arrow = vector vector = arrow.get_end()[:2] else: arrow = Vector(vector) show_creation = True array = vector_coordinate_label(arrow, integer_labels=integer_labels) x_line = Line(ORIGIN, vector[0] * RIGHT) y_line = Line(x_line.get_end(), arrow.get_end()) x_line.set_color(X_COLOR) y_line.set_color(Y_COLOR) x_coord, y_coord = array.get_mob_matrix().flatten() x_coord_start = self.position_x_coordinate( x_coord.copy(), x_line, vector ) y_coord_start = self.position_y_coordinate( y_coord.copy(), y_line, vector ) brackets = array.get_brackets() if show_creation: self.play(ShowCreation(arrow)) self.play( ShowCreation(x_line), Write(x_coord_start), run_time=1 ) self.play( ShowCreation(y_line), Write(y_coord_start), run_time=1 ) self.wait() self.play( Transform(x_coord_start, x_coord, lag_ratio=0), Transform(y_coord_start, y_coord, lag_ratio=0), Write(brackets, run_time=1), ) self.wait() self.remove(x_coord_start, y_coord_start, brackets) self.add(array) if clean_up: self.clear() self.add(*starting_mobjects) return array, x_line, y_line def show_ghost_movement(self, vector): if isinstance(vector, Arrow): vector = vector.get_end() - vector.get_start() elif len(vector) == 2: vector = np.append(np.array(vector), 0.0) x_max = int(FRAME_X_RADIUS + abs(vector[0])) y_max = int(FRAME_Y_RADIUS + abs(vector[1])) dots = VMobject(*[ Dot(x * RIGHT + y * UP) for x in range(-x_max, x_max) for y in range(-y_max, y_max) ]) dots.set_fill(BLACK, opacity=0) dots_halfway = dots.copy().shift(vector / 2).set_fill(WHITE, 1) dots_end = dots.copy().shift(vector) self.play(Transform( dots, dots_halfway, rate_func=rush_into )) self.play(Transform( dots, dots_end, rate_func=rush_from )) self.remove(dots) class LinearTransformationScene(VectorScene): include_background_plane: bool = True include_foreground_plane: bool = True foreground_plane_kwargs: dict = dict( x_max=FRAME_WIDTH / 2, x_min=-FRAME_WIDTH / 2, y_max=FRAME_WIDTH / 2, y_min=-FRAME_WIDTH / 2, faded_line_ratio=0 ) background_plane_kwargs: dict = dict( color=GREY, axis_config=dict(color=GREY), background_line_style=dict( stroke_color=GREY, stroke_width=1, ), ) show_coordinates: bool = True show_basis_vectors: bool = True basis_vector_stroke_width: float = 6.0 i_hat_color: ManimColor = X_COLOR j_hat_color: ManimColor = Y_COLOR leave_ghost_vectors: bool = False t_matrix: List[List[float]] = [[3, 0], [1, 2]] def setup(self): # The has_already_setup attr is to not break all the old Scenes if hasattr(self, "has_already_setup"): return self.has_already_setup = True self.background_mobjects = [] self.foreground_mobjects = [] self.transformable_mobjects = [] self.moving_vectors = [] self.transformable_labels = [] self.moving_mobjects = [] self.t_matrix = np.array(self.t_matrix) self.background_plane = NumberPlane( **self.background_plane_kwargs ) if self.show_coordinates: self.background_plane.add_coordinates() if self.include_background_plane: self.add_background_mobject(self.background_plane) if self.include_foreground_plane: self.plane = NumberPlane(**self.foreground_plane_kwargs) self.add_transformable_mobject(self.plane) if self.show_basis_vectors: self.basis_vectors = self.get_basis_vectors( i_hat_color=self.i_hat_color, j_hat_color=self.j_hat_color, ) self.moving_vectors += list(self.basis_vectors) self.i_hat, self.j_hat = self.basis_vectors self.add(self.basis_vectors) def add_special_mobjects(self, mob_list, *mobs_to_add): for mobject in mobs_to_add: if mobject not in mob_list: mob_list.append(mobject) self.add(mobject) def add_background_mobject(self, *mobjects): self.add_special_mobjects(self.background_mobjects, *mobjects) # TODO, this conflicts with Scene.add_fore def add_foreground_mobject(self, *mobjects): self.add_special_mobjects(self.foreground_mobjects, *mobjects) def add_transformable_mobject(self, *mobjects): self.add_special_mobjects(self.transformable_mobjects, *mobjects) def add_moving_mobject(self, mobject, target_mobject=None): mobject.target = target_mobject self.add_special_mobjects(self.moving_mobjects, mobject) def get_unit_square(self, color=YELLOW, opacity=0.3, stroke_width=3): square = self.square = Rectangle( color=color, width=self.plane.get_x_unit_size(), height=self.plane.get_y_unit_size(), stroke_color=color, stroke_width=stroke_width, fill_color=color, fill_opacity=opacity ) square.move_to(self.plane.coords_to_point(0, 0), DL) return square def add_unit_square(self, animate=False, **kwargs): square = self.get_unit_square(**kwargs) if animate: self.play( DrawBorderThenFill(square), Animation(Group(*self.moving_vectors)) ) self.add_transformable_mobject(square) self.bring_to_front(*self.moving_vectors) self.square = square return self def add_vector(self, vector, color=YELLOW, **kwargs): vector = VectorScene.add_vector( self, vector, color=color, **kwargs ) self.moving_vectors.append(vector) return vector def write_vector_coordinates(self, vector, **kwargs): coords = VectorScene.write_vector_coordinates(self, vector, **kwargs) self.add_foreground_mobject(coords) return coords def add_transformable_label( self, vector, label, transformation_name="L", new_label=None, **kwargs): label_mob = self.label_vector(vector, label, **kwargs) if new_label: label_mob.target_text = new_label else: label_mob.target_text = "%s(%s)" % ( transformation_name, label_mob.get_tex() ) label_mob.vector = vector label_mob.kwargs = kwargs if "animate" in label_mob.kwargs: label_mob.kwargs.pop("animate") self.transformable_labels.append(label_mob) return label_mob def add_title(self, title, scale_factor=1.5, animate=False): if not isinstance(title, Mobject): title = OldTexText(title).scale(scale_factor) title.to_edge(UP) title.add_background_rectangle() if animate: self.play(Write(title)) self.add_foreground_mobject(title) self.title = title return self def get_matrix_transformation(self, matrix): return self.get_transposed_matrix_transformation(np.array(matrix).T) def get_transposed_matrix_transformation(self, transposed_matrix): transposed_matrix = np.array(transposed_matrix) if transposed_matrix.shape == (2, 2): new_matrix = np.identity(3) new_matrix[:2, :2] = transposed_matrix transposed_matrix = new_matrix elif transposed_matrix.shape != (3, 3): raise Exception("Matrix has bad dimensions") return lambda point: np.dot(point, transposed_matrix) def get_piece_movement(self, pieces): start = VGroup(*pieces) target = VGroup(*[mob.target for mob in pieces]) if self.leave_ghost_vectors: self.add(start.copy().fade(0.7)) return Transform(start, target, lag_ratio=0) def get_moving_mobject_movement(self, func): for m in self.moving_mobjects: if m.target is None: m.target = m.copy() target_point = func(m.get_center()) m.target.move_to(target_point) return self.get_piece_movement(self.moving_mobjects) def get_vector_movement(self, func): for v in self.moving_vectors: v.target = Vector(func(v.get_end()), color=v.get_color()) norm = get_norm(v.target.get_end()) if norm < 0.1: v.target.get_tip().scale(norm) return self.get_piece_movement(self.moving_vectors) def get_transformable_label_movement(self): for l in self.transformable_labels: l.target = self.get_vector_label( l.vector.target, l.target_text, **l.kwargs ) return self.get_piece_movement(self.transformable_labels) def apply_matrix(self, matrix, **kwargs): self.apply_transposed_matrix(np.array(matrix).T, **kwargs) def apply_inverse(self, matrix, **kwargs): self.apply_matrix(np.linalg.inv(matrix), **kwargs) def apply_transposed_matrix(self, transposed_matrix, **kwargs): func = self.get_transposed_matrix_transformation(transposed_matrix) if "path_arc" not in kwargs: net_rotation = np.mean([ angle_of_vector(func(RIGHT)), angle_of_vector(func(UP)) - np.pi / 2 ]) kwargs["path_arc"] = net_rotation self.apply_function(func, **kwargs) def apply_inverse_transpose(self, t_matrix, **kwargs): t_inv = np.linalg.inv(np.array(t_matrix).T).T self.apply_transposed_matrix(t_inv, **kwargs) def apply_nonlinear_transformation(self, function, **kwargs): self.plane.prepare_for_nonlinear_transform() self.apply_function(function, **kwargs) def apply_function(self, function, added_anims=[], **kwargs): if "run_time" not in kwargs: kwargs["run_time"] = 3 anims = [ ApplyPointwiseFunction(function, t_mob) for t_mob in self.transformable_mobjects ] + [ self.get_vector_movement(function), self.get_transformable_label_movement(), self.get_moving_mobject_movement(function), ] + [ Animation(f_mob) for f_mob in self.foreground_mobjects ] + added_anims self.play(*anims, **kwargs)
from manim_imports_ext import * class Cycloidify(Scene): def construct(self): def cart_to_polar(xxx_todo_changeme): (x, y, z) = xxx_todo_changeme return x*RIGHT+x*y*UP def polar_to_cycloid(point): epsilon = 0.00001 t = get_norm(point) R = point[1]/(point[0]+epsilon)+epsilon return R*(t/R-np.sin(t/R))*RIGHT+R*(1-np.cos(t/R))*UP polar = Mobject(*[ Line(ORIGIN, T*(np.cos(theta)*RIGHT+np.sin(theta)*UP)) for R in np.arange(0.25, 4, 0.25) for theta in [np.arctan(R)] for T in [R*2*np.pi] ]) polar.set_color(BLUE) cycloids = polar.copy().apply_function(polar_to_cycloid) cycloids.set_color(YELLOW) for mob in polar, cycloids: mob.rotate(np.pi, RIGHT) mob.to_corner(UP+LEFT) lines = polar.copy() self.add(lines) self.wait() self.play(Transform( lines, cycloids, run_time = 3, path_func = path_along_arc(np.pi/2) )) self.wait() self.play(Transform( lines, polar, run_time = 3, path_func = path_along_arc(-np.pi/2) )) self.wait() class PythagoreanTransformation(Scene): def construct(self): triangle = Mobject( Line(ORIGIN, 4*UP, color = "#FF69B4"), Line(4*UP, 2*RIGHT, color = YELLOW_C), Line(2*RIGHT, ORIGIN, color = BLUE_D) ) arrangment1 = Mobject(*[ triangle.copy().rotate(theta).shift(3*vect) for theta, vect in zip( np.arange(0, 2*np.pi, np.pi/2), compass_directions(4, DOWN+LEFT) ) ]) arrangment2 = Mobject( triangle.copy().rotate(np.pi, UP).rotate(-np.pi/2).shift(3*DOWN+3*LEFT), triangle.copy().rotate(np.pi, UP).rotate(np.pi/2).shift(DOWN+RIGHT), triangle.copy().shift(DOWN+RIGHT), triangle.copy().rotate(np.pi).shift(3*UP+3*RIGHT) ) growth = 1.2 a_region, b_region, c_region = regions = [ MobjectFromRegion( region_from_polygon_vertices( *compass_directions(4, growth*start) ), color ).scale(1/growth).shift(shift_val) for start, color, shift_val in [ (DOWN+RIGHT, BLUE_D, 2*(DOWN+RIGHT)), (2*(DOWN+RIGHT), MAROON_B, UP+LEFT), (3*RIGHT+DOWN, YELLOW_E, ORIGIN), ] ] for mob, char in zip(regions, "abc"): mob.add( OldTex("%s^2"%char).shift(mob.get_center()) ) square = Square(side_length = 6, color = WHITE) mover = arrangment1.copy() self.add(square, mover) self.play(FadeIn(c_region)) self.wait(2) self.remove(c_region) self.play(Transform( mover, arrangment2, run_time = 3, path_func = path_along_arc(np.pi/2) )) self.remove(c_region) self.play(*[ FadeIn(region) for region in (a_region, b_region) ]) self.wait(2) self.clear() self.add(mover, square) self.play(Transform( mover, arrangment1, run_time = 3, path_func = path_along_arc(-np.pi/2) )) self.wait() class PullCurveStraight(Scene): def construct(self): start = -1.5 end = 1.5 parabola = ParametricCurve( lambda t : (t**3-t)*RIGHT + (2*np.exp(-t**2))*UP, start = start, end = end, color = BLUE_D, density = 2*DEFAULT_POINT_DENSITY_1D ) from scipy import integrate integral = integrate.quad( lambda x : np.sqrt(1 + 4*x**2), start, end ) length = integral[0] line = Line( 0.5*length*LEFT, 0.5*length*RIGHT, color = BLUE_D ) brace = Brace(line, UP) label = OldTexText("What is this length?") label.next_to(brace, UP) self.play(ShowCreation(parabola)) self.wait() self.play(Transform( parabola, line, path_func = path_along_arc(np.pi/2), run_time = 2 )) self.play( GrowFromCenter(brace), ShimmerIn(label) ) self.wait(3) class StraghtenCircle(Scene): def construct(self): radius = 1.5 radius_line = Line(ORIGIN, radius*RIGHT, color = RED_D) radius_brace = Brace(radius_line, UP) r = OldTex("r").next_to(radius_brace, UP) circle = Circle(radius = radius, color = BLUE_D) line = Line( np.pi*radius*LEFT, np.pi*radius*RIGHT, color = circle.get_color() ) line_brace = Brace(line, UP) two_pi_r = OldTex("2\\pi r").next_to(line_brace, UP) self.play(ShowCreation(radius_line)) self.play(ShimmerIn(r), GrowFromCenter(radius_brace)) self.wait() self.remove(r, radius_brace) self.play( ShowCreation(circle), Rotating( radius_line, axis = OUT, rate_func = smooth, in_place = False ), run_time = 2 ) self.wait() self.remove(radius_line) self.play(Transform( circle, line, run_time = 2 )) self.play( ShimmerIn(two_pi_r), GrowFromCenter(line_brace) ) self.wait(3) class SingleVariableFunc(Scene): def construct(self): start = OldTex("3").set_color(GREEN) start.scale(2).shift(5*LEFT+2*UP) end = OldTex("9").set_color(RED) end.scale(2).shift(5*RIGHT+2*DOWN) point = Point() func = OldTex("f(x) = x^2") circle = Circle(color = WHITE, radius = func.get_width()/1.5) self.add(start, circle, func) self.wait() self.play(Transform( start, point, path_func = path_along_arc(np.pi/2) )) self.play(Transform( start, end, path_func = path_along_arc(-np.pi/2) )) self.wait() class MultivariableFunc(Scene): def construct(self): start = OldTex("(1, 2)").set_color(GREEN) start.scale(1.5).shift(5*LEFT, 2*UP) end = OldTex("(5, -3)").set_color(RED) end.scale(1.5).shift(5*RIGHT, 2*DOWN) point = Point() func = OldTex("f(x, y) = (x^2+y^2, x^2-y^2)") circle = Circle(color = WHITE) circle.stretch_to_fit_width(func.get_width()+1) self.add(start, circle, func) self.wait() self.play(Transform( start, point, path_func = path_along_arc(np.pi/2) )) self.play(Transform( start, end, path_func = path_along_arc(-np.pi/2) )) self.wait() def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors class ShowSumOfSquaresPattern(Scene): def construct(self): dots = VGroup(*[ VGroup(*[ Dot() for x in range(2*n + 1) ]).arrange(DOWN, buff = SMALL_BUFF) for n in range(30) ]).arrange(RIGHT, buff = MED_LARGE_BUFF, aligned_edge = UP) dots = VGroup(*it.chain(*dots)) dots.to_edge(UP) numbers = VGroup() for n, dot in enumerate(dots): factors = prime_factors(n) color = True factors_to_counts = dict() for factor in factors: if factor not in factors_to_counts: factors_to_counts[factor] = 0 factors_to_counts[factor] += 1 for factor, count in list(factors_to_counts.items()): if factor%4 == 3 and count%2 == 1: color = False n_mob = Integer(n) n_mob.replace(dot, dim_to_match = 1) if color: n_mob.set_color(RED) numbers.add(n_mob) self.add(numbers)
from manimlib.animation.animation import Animation from manimlib.animation.transform import MoveToTarget from manimlib.animation.transform import Transform from manimlib.animation.update import UpdateFromFunc from manimlib.constants import DOWN, RIGHT from manimlib.constants import MED_LARGE_BUFF, SMALL_BUFF from manimlib.mobject.probability import SampleSpace from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.scene import Scene class SampleSpaceScene(Scene): def get_sample_space(self, **config): self.sample_space = SampleSpace(**config) return self.sample_space def add_sample_space(self, **config): self.add(self.get_sample_space(**config)) def get_division_change_animations( self, sample_space, parts, p_list, dimension=1, new_label_kwargs=None, **kwargs ): if new_label_kwargs is None: new_label_kwargs = {} anims = [] p_list = sample_space.complete_p_list(p_list) space_copy = sample_space.copy() vect = DOWN if dimension == 1 else RIGHT parts.generate_target() for part, p in zip(parts.target, p_list): part.replace(space_copy, stretch=True) part.stretch(p, dimension) parts.target.arrange(vect, buff=0) parts.target.move_to(space_copy) anims.append(MoveToTarget(parts)) if hasattr(parts, "labels") and parts.labels is not None: label_kwargs = parts.label_kwargs label_kwargs.update(new_label_kwargs) new_braces, new_labels = sample_space.get_subdivision_braces_and_labels( parts.target, **label_kwargs ) anims += [ Transform(parts.braces, new_braces), Transform(parts.labels, new_labels), ] return anims def get_horizontal_division_change_animations(self, p_list, **kwargs): assert(hasattr(self.sample_space, "horizontal_parts")) return self.get_division_change_animations( self.sample_space, self.sample_space.horizontal_parts, p_list, dimension=1, **kwargs ) def get_vertical_division_change_animations(self, p_list, **kwargs): assert(hasattr(self.sample_space, "vertical_parts")) return self.get_division_change_animations( self.sample_space, self.sample_space.vertical_parts, p_list, dimension=0, **kwargs ) def get_conditional_change_anims( self, sub_sample_space_index, value, post_rects=None, **kwargs ): parts = self.sample_space.horizontal_parts sub_sample_space = parts[sub_sample_space_index] anims = self.get_division_change_animations( sub_sample_space, sub_sample_space.vertical_parts, value, dimension=0, **kwargs ) if post_rects is not None: anims += self.get_posterior_rectangle_change_anims(post_rects) return anims def get_top_conditional_change_anims(self, *args, **kwargs): return self.get_conditional_change_anims(0, *args, **kwargs) def get_bottom_conditional_change_anims(self, *args, **kwargs): return self.get_conditional_change_anims(1, *args, **kwargs) def get_prior_rectangles(self): return VGroup(*[ self.sample_space.horizontal_parts[i].vertical_parts[0] for i in range(2) ]) def get_posterior_rectangles(self, buff=MED_LARGE_BUFF): prior_rects = self.get_prior_rectangles() areas = [ rect.get_width() * rect.get_height() for rect in prior_rects ] total_area = sum(areas) total_height = prior_rects.get_height() post_rects = prior_rects.copy() for rect, area in zip(post_rects, areas): rect.stretch_to_fit_height(total_height * area / total_area) rect.stretch_to_fit_width( area / rect.get_height() ) post_rects.arrange(DOWN, buff=0) post_rects.next_to( self.sample_space, RIGHT, buff ) return post_rects def get_posterior_rectangle_braces_and_labels( self, post_rects, labels, direction=RIGHT, **kwargs ): return self.sample_space.get_subdivision_braces_and_labels( post_rects, labels, direction, **kwargs ) def update_posterior_braces(self, post_rects): braces = post_rects.braces labels = post_rects.labels for rect, brace, label in zip(post_rects, braces, labels): brace.stretch_to_fit_height(rect.get_height()) brace.next_to(rect, RIGHT, SMALL_BUFF) label.next_to(brace, RIGHT, SMALL_BUFF) def get_posterior_rectangle_change_anims(self, post_rects): def update_rects(rects): new_rects = self.get_posterior_rectangles() Transform(rects, new_rects).update(1) if hasattr(rects, "braces"): self.update_posterior_braces(rects) return rects anims = [UpdateFromFunc(post_rects, update_rects)] if hasattr(post_rects, "braces"): anims += list(map(Animation, [ post_rects.labels, post_rects.braces ])) return anims
import inspect from manimlib.utils.dict_ops import merge_dicts_recursively def filtered_locals(caller_locals): result = caller_locals.copy() ignored_local_args = ["self", "kwargs"] for arg in ignored_local_args: result.pop(arg, caller_locals) return result def digest_config(obj, kwargs, caller_locals={}): """ (Deprecated) Sets init args and CONFIG values as local variables The purpose of this function is to ensure that all configuration of any object is inheritable, able to be easily passed into instantiation, and is attached as an attribute of the object. """ # Assemble list of CONFIGs from all super classes classes_in_hierarchy = [obj.__class__] static_configs = [] while len(classes_in_hierarchy) > 0: Class = classes_in_hierarchy.pop() classes_in_hierarchy += Class.__bases__ if hasattr(Class, "CONFIG"): static_configs.append(Class.CONFIG) # Order matters a lot here, first dicts have higher priority caller_locals = filtered_locals(caller_locals) all_dicts = [kwargs, caller_locals, obj.__dict__] all_dicts += static_configs obj.__dict__ = merge_dicts_recursively(*reversed(all_dicts)) def digest_locals(obj, keys=None): caller_locals = filtered_locals( inspect.currentframe().f_back.f_locals ) if keys is None: keys = list(caller_locals.keys()) for key in keys: setattr(obj, key, caller_locals[key]) # Occasionally convenient in order to write dict.x instead of more laborious # (and less in keeping with all other attr accesses) dict["x"] class DictAsObject(object): def __init__(self, dict): self.__dict__ = dict def get_all_descendent_classes(Class): awaiting_review = [Class] result = [] while awaiting_review: Child = awaiting_review.pop() awaiting_review += Child.__subclasses__() result.append(Child) return result
from functools import reduce import itertools as it import operator as op import numpy as np from manimlib.constants import * from manimlib.scene.scene import Scene from manimlib.utils.rate_functions import there_and_back from manimlib.utils.space_ops import center_of_mass class Graph(): def __init__(self): # List of points in R^3 # vertices = [] # List of pairs of indices of vertices # edges = [] # List of tuples of indices of vertices. The last should # be a cycle whose interior is the entire graph, and when # regions are computed its complement will be taken. # region_cycles = [] self.construct() def construct(self): pass def __str__(self): return self.__class__.__name__ class CubeGraph(Graph): """ 5 7 12 03 4 6 """ def construct(self): self.vertices = [ (x, y, 0) for r in (1, 2) for x, y in it.product([-r, r], [-r, r]) ] self.edges = [ (0, 1), (0, 2), (3, 1), (3, 2), (4, 5), (4, 6), (7, 5), (7, 6), (0, 4), (1, 5), (2, 6), (3, 7), ] self.region_cycles = [ [0, 2, 3, 1], [4, 0, 1, 5], [4, 6, 2, 0], [6, 7, 3, 2], [7, 5, 1, 3], [4, 6, 7, 5], # By convention, last region will be "outside" ] class SampleGraph(Graph): """ 4 2 3 8 0 1 7 5 6 """ def construct(self): self.vertices = [ (0, 0, 0), (2, 0, 0), (1, 2, 0), (3, 2, 0), (-1, 2, 0), (-2, -2, 0), (2, -2, 0), (4, -1, 0), (6, 2, 0), ] self.edges = [ (0, 1), (1, 2), (1, 3), (3, 2), (2, 4), (4, 0), (2, 0), (4, 5), (0, 5), (1, 5), (5, 6), (6, 7), (7, 1), (7, 8), (8, 3), ] self.region_cycles = [ (0, 1, 2), (1, 3, 2), (2, 4, 0), (4, 5, 0), (0, 5, 1), (1, 5, 6, 7), (1, 7, 8, 3), (4, 5, 6, 7, 8, 3, 2), ] class OctohedronGraph(Graph): """ 3 1 0 2 4 5 """ def construct(self): self.vertices = [ (r * np.cos(angle), r * np.sin(angle) - 1, 0) for r, s in [(1, 0), (3, 3)] for angle in (np.pi / 6) * np.array([s, 4 + s, 8 + s]) ] self.edges = [ (0, 1), (1, 2), (2, 0), (5, 0), (0, 3), (3, 5), (3, 1), (3, 4), (1, 4), (4, 2), (4, 5), (5, 2), ] self.region_cycles = [ (0, 1, 2), (0, 5, 3), (3, 1, 0), (3, 4, 1), (1, 4, 2), (2, 4, 5), (5, 0, 2), (3, 4, 5), ] class CompleteGraph(Graph): def __init__(self, num_vertices, radius=3): self.num_vertices = num_vertices self.radius = radius Graph.__init__(self) def construct(self): self.vertices = [ (self.radius * np.cos(theta), self.radius * np.sin(theta), 0) for x in range(self.num_vertices) for theta in [2 * np.pi * x / self.num_vertices] ] self.edges = it.combinations(list(range(self.num_vertices)), 2) def __str__(self): return Graph.__str__(self) + str(self.num_vertices) class DiscreteGraphScene(Scene): args_list = [ (CubeGraph(),), (SampleGraph(),), (OctohedronGraph(),), ] @staticmethod def args_to_string(*args): return str(args[0]) def __init__(self, graph, *args, **kwargs): # See CubeGraph() above for format of graph self.graph = graph Scene.__init__(self, *args, **kwargs) def construct(self): self._points = list(map(np.array, self.graph.vertices)) self.vertices = self.dots = [Dot(p) for p in self._points] self.edges = self.lines = [ Line(self._points[i], self._points[j]) for i, j in self.graph.edges ] self.add(*self.dots + self.edges) def generate_regions(self): regions = [ self.region_from_cycle(cycle) for cycle in self.graph.region_cycles ] regions[-1].complement() # Outer region painted outwardly... self.regions = regions def region_from_cycle(self, cycle): point_pairs = [ [ self._points[cycle[i]], self._points[cycle[(i + 1) % len(cycle)]] ] for i in range(len(cycle)) ] return region_from_line_boundary( *point_pairs, shape=self.shape ) def draw_vertices(self, **kwargs): self.clear() self.play(ShowCreation(Mobject(*self.vertices), **kwargs)) def draw_edges(self): self.play(*[ ShowCreation(edge, run_time=1.0) for edge in self.edges ]) def accent_vertices(self, **kwargs): self.remove(*self.vertices) start = Mobject(*self.vertices) end = Mobject(*[ Dot(point, radius=3 * Dot.DEFAULT_RADIUS, color="lightgreen") for point in self._points ]) self.play(Transform( start, end, rate_func=there_and_back, **kwargs )) self.remove(start) self.add(*self.vertices) def replace_vertices_with(self, mobject): mobject.center() diameter = max(mobject.get_height(), mobject.get_width()) self.play(*[ CounterclockwiseTransform( vertex, mobject.copy().shift(vertex.get_center()) ) for vertex in self.vertices ] + [ ApplyMethod( edge.scale, (edge.get_length() - diameter) / edge.get_length() ) for edge in self.edges ]) def annotate_edges(self, mobject, fade_in=True, **kwargs): angles = list(map(np.arctan, list(map(Line.get_slope, self.edges)))) self.edge_annotations = [ mobject.copy().rotate(angle).move_to(edge.get_center()) for angle, edge in zip(angles, self.edges) ] if fade_in: self.play(*[ FadeIn(ann, **kwargs) for ann in self.edge_annotations ]) def trace_cycle(self, cycle=None, color="yellow", run_time=2.0): if cycle is None: cycle = self.graph.region_cycles[0] next_in_cycle = it.cycle(cycle) next(next_in_cycle) # jump one ahead self.traced_cycle = Mobject(*[ Line(self._points[i], self._points[j]).set_color(color) for i, j in zip(cycle, next_in_cycle) ]) self.play( ShowCreation(self.traced_cycle), run_time=run_time ) def generate_spanning_tree(self, root=0, color="yellow"): self.spanning_tree_root = 0 pairs = deepcopy(self.graph.edges) pairs += [tuple(reversed(pair)) for pair in pairs] self.spanning_tree_index_pairs = [] curr = root spanned_vertices = set([curr]) to_check = set([curr]) while len(to_check) > 0: curr = to_check.pop() for pair in pairs: if pair[0] == curr and pair[1] not in spanned_vertices: self.spanning_tree_index_pairs.append(pair) spanned_vertices.add(pair[1]) to_check.add(pair[1]) self.spanning_tree = Mobject(*[ Line( self._points[pair[0]], self._points[pair[1]] ).set_color(color) for pair in self.spanning_tree_index_pairs ]) def generate_treeified_spanning_tree(self): bottom = -FRAME_Y_RADIUS + 1 x_sep = 1 y_sep = 2 if not hasattr(self, "spanning_tree"): self.generate_spanning_tree() root = self.spanning_tree_root color = self.spanning_tree.get_color() indices = list(range(len(self._points))) # Build dicts parent_of = dict([ tuple(reversed(pair)) for pair in self.spanning_tree_index_pairs ]) children_of = dict([(index, []) for index in indices]) for child in parent_of: children_of[parent_of[child]].append(child) x_coord_of = {root: 0} y_coord_of = {root: bottom} # width to allocate to a given node, computed as # the maximum number of decendents in a single generation, # minus 1, multiplied by x_sep width_of = {} for index in indices: next_generation = children_of[index] curr_max = max(1, len(next_generation)) while next_generation != []: next_generation = reduce(op.add, [ children_of[node] for node in next_generation ]) curr_max = max(curr_max, len(next_generation)) width_of[index] = x_sep * (curr_max - 1) to_process = [root] while to_process != []: index = to_process.pop() if index not in y_coord_of: y_coord_of[index] = y_sep + y_coord_of[parent_of[index]] children = children_of[index] left_hand = x_coord_of[index] - width_of[index] / 2.0 for child in children: x_coord_of[child] = left_hand + width_of[child] / 2.0 left_hand += width_of[child] + x_sep to_process += children new_points = [ np.array([ x_coord_of[index], y_coord_of[index], 0 ]) for index in indices ] self.treeified_spanning_tree = Mobject(*[ Line(new_points[i], new_points[j]).set_color(color) for i, j in self.spanning_tree_index_pairs ]) def generate_dual_graph(self): point_at_infinity = np.array([np.inf] * 3) cycles = self.graph.region_cycles self.dual_points = [ center_of_mass([ self._points[index] for index in cycle ]) for cycle in cycles ] self.dual_vertices = [ Dot(point).set_color("green") for point in self.dual_points ] self.dual_vertices[-1] = Circle().scale(FRAME_X_RADIUS + FRAME_Y_RADIUS) self.dual_points[-1] = point_at_infinity self.dual_edges = [] for pair in self.graph.edges: dual_point_pair = [] for cycle in cycles: if not (pair[0] in cycle and pair[1] in cycle): continue index1, index2 = cycle.index(pair[0]), cycle.index(pair[1]) if abs(index1 - index2) in [1, len(cycle) - 1]: dual_point_pair.append( self.dual_points[cycles.index(cycle)] ) assert(len(dual_point_pair) == 2) for i in 0, 1: if all(dual_point_pair[i] == point_at_infinity): new_point = np.array(dual_point_pair[1 - i]) vect = center_of_mass([ self._points[pair[0]], self._points[pair[1]] ]) - new_point new_point += FRAME_X_RADIUS * vect / get_norm(vect) dual_point_pair[i] = new_point self.dual_edges.append( Line(*dual_point_pair).set_color() )
from manimlib.animation.creation import ShowCreation from manimlib.animation.fading import FadeIn from manimlib.animation.transform import MoveToTarget from manimlib.animation.transform import Transform from manimlib.constants import * from manimlib.mobject.geometry import Arrow from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Dot from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.scene import Scene import itertools as it class CountingScene(Scene): CONFIG = { "digit_place_colors": [YELLOW, MAROON_B, RED, GREEN, BLUE, PURPLE_D], "counting_dot_starting_position": (FRAME_X_RADIUS - 1) * RIGHT + (FRAME_Y_RADIUS - 1) * UP, "count_dot_starting_radius": 0.5, "dot_configuration_height": 2, "ones_configuration_location": UP + 2 * RIGHT, "num_scale_factor": 2, "num_start_location": 2 * DOWN, } def setup(self): self.dots = VGroup() self.number = 0 self.max_place = 0 self.number_mob = VGroup(OldTex(str(self.number))) self.number_mob.scale(self.num_scale_factor) self.number_mob.shift(self.num_start_location) self.dot_templates = [] self.dot_template_iterators = [] self.curr_configurations = [] self.arrows = VGroup() self.add(self.number_mob) def get_template_configuration(self, place): # This should probably be replaced for non-base-10 counting scenes down_right = (0.5) * RIGHT + (np.sqrt(3) / 2) * DOWN result = [] for down_right_steps in range(5): for left_steps in range(down_right_steps): result.append( down_right_steps * down_right + left_steps * LEFT ) return reversed(result[:self.get_place_max(place)]) def get_dot_template(self, place): # This should be replaced for non-base-10 counting scenes dots = VGroup(*[ Dot( point, radius=0.25, fill_opacity=0, stroke_width=2, stroke_color=WHITE, ) for point in self.get_template_configuration(place) ]) dots.set_height(self.dot_configuration_height) return dots def add_configuration(self): new_template = self.get_dot_template(len(self.dot_templates)) new_template.move_to(self.ones_configuration_location) left_vect = (new_template.get_width() + LARGE_BUFF) * LEFT new_template.shift( left_vect * len(self.dot_templates) ) self.dot_templates.append(new_template) self.dot_template_iterators.append( it.cycle(new_template) ) self.curr_configurations.append(VGroup()) def count(self, max_val, run_time_per_anim=1): for x in range(max_val): self.increment(run_time_per_anim) def increment(self, run_time_per_anim=1): moving_dot = Dot( self.counting_dot_starting_position, radius=self.count_dot_starting_radius, color=self.digit_place_colors[0], ) moving_dot.generate_target() moving_dot.set_fill(opacity=0) kwargs = { "run_time": run_time_per_anim } continue_rolling_over = True first_move = True place = 0 while continue_rolling_over: added_anims = [] if first_move: added_anims += self.get_digit_increment_animations() first_move = False moving_dot.target.replace( next(self.dot_template_iterators[place]) ) self.play(MoveToTarget(moving_dot), *added_anims, **kwargs) self.curr_configurations[place].add(moving_dot) if len(self.curr_configurations[place].split()) == self.get_place_max(place): full_configuration = self.curr_configurations[place] self.curr_configurations[place] = VGroup() place += 1 center = full_configuration.get_center_of_mass() radius = 0.6 * max( full_configuration.get_width(), full_configuration.get_height(), ) circle = Circle( radius=radius, stroke_width=0, fill_color=self.digit_place_colors[place], fill_opacity=0.5, ) circle.move_to(center) moving_dot = VGroup(circle, full_configuration) moving_dot.generate_target() moving_dot[0].set_fill(opacity=0) else: continue_rolling_over = False def get_digit_increment_animations(self): result = [] self.number += 1 is_next_digit = self.is_next_digit() if is_next_digit: self.max_place += 1 new_number_mob = self.get_number_mob(self.number) new_number_mob.move_to(self.number_mob, RIGHT) if is_next_digit: self.add_configuration() place = len(new_number_mob.split()) - 1 result.append(FadeIn(self.dot_templates[place])) arrow = Arrow( new_number_mob[place].get_top(), self.dot_templates[place].get_bottom(), color=self.digit_place_colors[place] ) self.arrows.add(arrow) result.append(ShowCreation(arrow)) result.append(Transform( self.number_mob, new_number_mob, lag_ratio=0.5 )) return result def get_number_mob(self, num): result = VGroup() place = 0 max_place = self.max_place while place < max_place: digit = OldTex(str(self.get_place_num(num, place))) if place >= len(self.digit_place_colors): self.digit_place_colors += self.digit_place_colors digit.set_color(self.digit_place_colors[place]) digit.scale(self.num_scale_factor) digit.next_to(result, LEFT, buff=SMALL_BUFF, aligned_edge=DOWN) result.add(digit) place += 1 return result def is_next_digit(self): return False def get_place_num(self, num, place): return 0 def get_place_max(self, place): return 0 class PowerCounter(CountingScene): def is_next_digit(self): number = self.number while number > 1: if number % self.base != 0: return False number /= self.base return True def get_place_max(self, place): return self.base def get_place_num(self, num, place): return (num / (self.base ** place)) % self.base class CountInDecimal(PowerCounter): CONFIG = { "base": 10, } def construct(self): for x in range(11): self.increment() for x in range(85): self.increment(0.25) for x in range(20): self.increment() class CountInTernary(PowerCounter): CONFIG = { "base": 3, "dot_configuration_height": 1, "ones_configuration_location": UP + 4 * RIGHT } def construct(self): self.count(27) # def get_template_configuration(self, place): # return [ORIGIN, UP] class CountInBinaryTo256(PowerCounter): CONFIG = { "base": 2, "dot_configuration_height": 1, "ones_configuration_location": UP + 5 * RIGHT } def construct(self): self.count(128, 0.3) def get_template_configuration(self, place): return [ORIGIN, UP] class FactorialBase(CountingScene): CONFIG = { "dot_configuration_height": 1, "ones_configuration_location": UP + 4 * RIGHT } def construct(self): self.count(30, 0.4) def is_next_digit(self): return self.number == self.factorial(self.max_place + 1) def get_place_max(self, place): return place + 2 def get_place_num(self, num, place): return (num / self.factorial(place + 1)) % self.get_place_max(place) def factorial(self, n): if (n == 1): return 1 else: return n * self.factorial(n - 1)
from copy import deepcopy import itertools as it from manimlib.constants import * from manimlib.mobject.mobject import Mobject from manimlib.utils.iterables import adjacent_pairs # Warning: This is all now pretty deprecated, and should not be expected to work class Region(Mobject): CONFIG = { "display_mode": "region" } def __init__(self, condition=(lambda x, y: True), **kwargs): """ Condition must be a function which takes in two real arrays (representing x and y values of space respectively) and return a boolean array. This can essentially look like a function from R^2 to {True, False}, but & and | must be used in place of "and" and "or" """ Mobject.__init__(self, **kwargs) self.condition = condition def _combine(self, region, op): self.condition = lambda x, y: op( self.condition(x, y), region.condition(x, y) ) def union(self, region): self._combine(region, lambda bg1, bg2: bg1 | bg2) return self def intersect(self, region): self._combine(region, lambda bg1, bg2: bg1 & bg2) return self def complement(self): self.bool_grid = ~self.bool_grid return self class HalfPlane(Region): def __init__(self, point_pair, upper_left=True, *args, **kwargs): """ point_pair of the form [(x_0, y_0,...), (x_1, y_1,...)] Pf upper_left is True, the side of the region will be everything on the upper left side of the line through the point pair """ if not upper_left: point_pair = list(point_pair) point_pair.reverse() (x0, y0), (x1, y1) = point_pair[0][:2], point_pair[1][:2] def condition(x, y): return (x1 - x0) * (y - y0) > (y1 - y0) * (x - x0) Region.__init__(self, condition, *args, **kwargs) def region_from_line_boundary(*lines, **kwargs): reg = Region(**kwargs) for line in lines: reg.intersect(HalfPlane(line, **kwargs)) return reg def region_from_polygon_vertices(*vertices, **kwargs): return region_from_line_boundary(*adjacent_pairs(vertices), **kwargs) def plane_partition(*lines, **kwargs): """ A 'line' is a pair of points [(x0, y0,...), (x1, y1,...)] Returns the list of regions of the plane cut out by these lines """ result = [] half_planes = [HalfPlane(line, **kwargs) for line in lines] complements = [deepcopy(hp).complement() for hp in half_planes] num_lines = len(lines) for bool_list in it.product(*[[True, False]] * num_lines): reg = Region(**kwargs) for i in range(num_lines): if bool_list[i]: reg.intersect(half_planes[i]) else: reg.intersect(complements[i]) if reg.bool_grid.any(): result.append(reg) return result def plane_partition_from_points(*points, **kwargs): """ Returns list of regions cut out by the complete graph with points from the argument as vertices. Each point comes in the form (x, y) """ lines = [[p1, p2] for (p1, p2) in it.combinations(points, 2)] return plane_partition(*lines, **kwargs)
from manim_imports_ext import * class RotatingButterflyCurve(Animation): """ Pretty hacky, but should only be redone in the context of a broader 4d mobject class """ CONFIG = { "space_epsilon": 0.002, "grid_line_sep": 0.2, "radius": 2, "radians": 2 * np.pi, "run_time": 15, "rate_func": linear, } def __init__(self, **kwargs): digest_config(self, kwargs) fine_range = np.arange(-self.radius, self.radius, self.space_epsilon) corse_range = np.arange(-self.radius, self.radius, self.grid_line_sep) self.points = np.array([ [x, y, x * x, y * y] for a in fine_range for b in corse_range for x, y in [(a, b), (b, a)] ]) graph_rgb = Color(TEAL).get_rgb() self.rgbas = np.array([graph_rgb] * len(self.points)) colors = iter([YELLOW_A, YELLOW_B, YELLOW_C, YELLOW_D]) for i in range(4): vect = np.zeros(4) vect[i] = 1 line_range = np.arange(-FRAME_Y_RADIUS, FRAME_Y_RADIUS, self.space_epsilon) self.points = np.append(self.points, [ x * vect for x in line_range ], axis=0) axis_rgb = Color(next(colors)).get_rgb() self.rgbas = np.append( self.rgbas, [axis_rgb] * len(line_range), axis=0) self.quads = [(0, 1, 2, 3), (0, 1, 0, 1), (3, 2, 1, 0)] self.multipliers = [0.9, 1, 1.1] Animation.__init__(self, Mobject(), **kwargs) def interpolate_mobject(self, alpha): angle = alpha * self.radians rot_matrix = np.identity(4) for quad, mult in zip(self.quads, self.multipliers): base = np.identity(4) theta = mult * angle base[quad[:2], quad[2]] = [np.cos(theta), np.sin(theta)] base[quad[:2], quad[3]] = [-np.sin(theta), np.cos(theta)] rot_matrix = np.dot(rot_matrix, base) points = np.dot(self.points, np.transpose(rot_matrix)) self.mobject.points = points[:, :3] self.mobject.rgbas = self.rgbas class RotatingFourDButterflyCurve(Scene): def construct(self): self.play(RotatingButterflyCurve())
from manimlib.animation.animation import Animation from manimlib.animation.movement import ComplexHomotopy from manimlib.animation.transform import MoveToTarget from manimlib.constants import * from manimlib.mobject.coordinate_systems import ComplexPlane from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.scene import Scene # TODO, refactor this full scene class ComplexTransformationScene(Scene): CONFIG = { "plane_config": {}, "background_fade_factor": 0.5, "use_multicolored_plane": False, "vert_start_color": BLUE, # TODO "vert_end_color": BLUE, "horiz_start_color": BLUE, "horiz_end_color": BLUE, "num_anchors_to_add_per_line": 50, "post_transformation_stroke_width": None, "default_apply_complex_function_kwargs": { "run_time": 5, }, "background_label_scale_val": 0.5, "include_coordinate_labels": True, } def setup(self): self.foreground_mobjects = [] self.transformable_mobjects = [] self.add_background_plane() if self.include_coordinate_labels: self.add_coordinate_labels() def add_foreground_mobject(self, mobject): self.add_foreground_mobjects(mobject) def add_transformable_mobjects(self, *mobjects): self.transformable_mobjects += list(mobjects) self.add(*mobjects) def add_foreground_mobjects(self, *mobjects): self.foreground_mobjects += list(mobjects) Scene.add(self, *mobjects) def add(self, *mobjects): Scene.add(self, *list(mobjects) + self.foreground_mobjects) def play(self, *animations, **kwargs): Scene.play( self, *list(animations) + list(map(Animation, self.foreground_mobjects)), **kwargs ) def add_background_plane(self): background = ComplexPlane(**self.plane_config) background.fade(self.background_fade_factor) self.add(background) self.background = background def add_coordinate_labels(self): self.background.add_coordinates() self.add(self.background) def add_transformable_plane(self, **kwargs): self.plane = self.get_transformable_plane() self.add(self.plane) def get_transformable_plane(self, x_range=None, y_range=None): """ x_range and y_range would be tuples (min, max) """ plane_config = dict(self.plane_config) shift_val = ORIGIN if x_range is not None: x_min, x_max = x_range plane_config["x_radius"] = x_max - x_min shift_val += (x_max + x_min) * RIGHT / 2. if y_range is not None: y_min, y_max = y_range plane_config["y_radius"] = y_max - y_min shift_val += (y_max + y_min) * UP / 2. plane = ComplexPlane(**plane_config) plane.shift(shift_val) if self.use_multicolored_plane: self.paint_plane(plane) return plane def prepare_for_transformation(self, mob): if hasattr(mob, "prepare_for_nonlinear_transform"): mob.prepare_for_nonlinear_transform( self.num_anchors_to_add_per_line ) # TODO... def paint_plane(self, plane): for lines in planes, plane.secondary_lines: lines.set_color_by_gradient( self.vert_start_color, self.vert_end_color, self.horiz_start_color, self.horiz_end_color, ) # plane.axes.set_color_by_gradient( # self.horiz_start_color, # self.vert_start_color # ) def z_to_point(self, z): return self.background.number_to_point(z) def get_transformer(self, **kwargs): transform_kwargs = dict(self.default_apply_complex_function_kwargs) transform_kwargs.update(kwargs) transformer = VGroup() if hasattr(self, "plane"): self.prepare_for_transformation(self.plane) transformer.add(self.plane) transformer.add(*self.transformable_mobjects) return transformer, transform_kwargs def apply_complex_function(self, func, added_anims=[], **kwargs): transformer, transform_kwargs = self.get_transformer(**kwargs) transformer.generate_target() # Rescale, apply function, scale back transformer.target.shift(-self.background.get_center_point()) transformer.target.scale(1. / self.background.unit_size) transformer.target.apply_complex_function(func) transformer.target.scale(self.background.unit_size) transformer.target.shift(self.background.get_center_point()) # for mob in transformer.target[0].family_members_with_points(): mob.make_smooth() if self.post_transformation_stroke_width is not None: transformer.target.set_stroke( width=self.post_transformation_stroke_width) self.play( MoveToTarget(transformer, **transform_kwargs), *added_anims ) def apply_complex_homotopy(self, complex_homotopy, added_anims=[], **kwargs): transformer, transform_kwargs = self.get_transformer(**kwargs) # def homotopy(x, y, z, t): # output = complex_homotopy(complex(x, y), t) # rescaled_output = self.z_to_point(output) # return (rescaled_output.real, rescaled_output.imag, z) self.play( ComplexHomotopy(complex_homotopy, transformer, **transform_kwargs), *added_anims )
import itertools as it from manimlib.animation.creation import Write, DrawBorderThenFill, ShowCreation from manimlib.animation.transform import Transform from manimlib.animation.update import UpdateFromAlphaFunc from manimlib.constants import * from manimlib.mobject.functions import ParametricCurve from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import RegularPolygon from manimlib.mobject.number_line import NumberLine from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VectorizedPoint from manimlib.scene.scene import Scene from manimlib.utils.bezier import interpolate from manimlib.utils.color import color_gradient from manimlib.utils.color import invert_color from manimlib.utils.space_ops import angle_of_vector # TODO, this class should be deprecated, with all its # functionality moved to Axes and handled at the mobject # level rather than the scene level class GraphScene(Scene): x_min = -1 x_max = 10 x_axis_width = 9 x_tick_frequency = 1 x_leftmost_tick = None # Change if different from x_min x_labeled_nums = None x_axis_label = "$x$" y_min = -1 y_max = 10 y_axis_height = 6 y_tick_frequency = 1 y_bottom_tick = None # Change if different from y_min y_labeled_nums = None y_axis_label = "$y$" axes_color = GREY graph_origin = 2.5 * DOWN + 4 * LEFT exclude_zero_label = True default_graph_colors = [BLUE, GREEN, YELLOW] default_derivative_color = GREEN default_input_color = YELLOW default_riemann_start_color = BLUE default_riemann_end_color = GREEN area_opacity = 0.8 num_rects = 50 def setup(self): self.default_graph_colors_cycle = it.cycle(self.default_graph_colors) self.left_T_label = VGroup() self.left_v_line = VGroup() self.right_T_label = VGroup() self.right_v_line = VGroup() def setup_axes(self, animate=False): # TODO, once eoc is done, refactor this to be less redundant. x_num_range = float(self.x_max - self.x_min) self.space_unit_to_x = self.x_axis_width / x_num_range if self.x_labeled_nums is None: self.x_labeled_nums = [] if self.x_leftmost_tick is None: self.x_leftmost_tick = self.x_min x_axis = NumberLine( x_min=self.x_min, x_max=self.x_max, unit_size=self.space_unit_to_x, tick_frequency=self.x_tick_frequency, leftmost_tick=self.x_leftmost_tick, numbers_with_elongated_ticks=self.x_labeled_nums, color=self.axes_color ) x_axis.shift(self.graph_origin - x_axis.number_to_point(0)) if len(self.x_labeled_nums) > 0: if self.exclude_zero_label: self.x_labeled_nums = [x for x in self.x_labeled_nums if x != 0] x_axis.add_numbers(self.x_labeled_nums) if self.x_axis_label: x_label = OldTexText(self.x_axis_label) x_label.next_to( x_axis.get_tick_marks(), UP + RIGHT, buff=SMALL_BUFF ) x_label.shift_onto_screen() x_axis.add(x_label) self.x_axis_label_mob = x_label y_num_range = float(self.y_max - self.y_min) self.space_unit_to_y = self.y_axis_height / y_num_range if self.y_labeled_nums is None: self.y_labeled_nums = [] if self.y_bottom_tick is None: self.y_bottom_tick = self.y_min y_axis = NumberLine( x_min=self.y_min, x_max=self.y_max, unit_size=self.space_unit_to_y, tick_frequency=self.y_tick_frequency, leftmost_tick=self.y_bottom_tick, numbers_with_elongated_ticks=self.y_labeled_nums, color=self.axes_color, line_to_number_vect=LEFT, label_direction=LEFT, ) y_axis.shift(self.graph_origin - y_axis.number_to_point(0)) y_axis.rotate(np.pi / 2, about_point=y_axis.number_to_point(0)) if len(self.y_labeled_nums) > 0: if self.exclude_zero_label: self.y_labeled_nums = [y for y in self.y_labeled_nums if y != 0] y_axis.add_numbers(self.y_labeled_nums) if self.y_axis_label: y_label = OldTexText(self.y_axis_label) y_label.next_to( y_axis.get_corner(UP + RIGHT), UP + RIGHT, buff=SMALL_BUFF ) y_label.shift_onto_screen() y_axis.add(y_label) self.y_axis_label_mob = y_label if animate: self.play(Write(VGroup(x_axis, y_axis))) else: self.add(x_axis, y_axis) self.x_axis, self.y_axis = self.axes = VGroup(x_axis, y_axis) self.default_graph_colors = it.cycle(self.default_graph_colors) def coords_to_point(self, x, y): assert(hasattr(self, "x_axis") and hasattr(self, "y_axis")) result = self.x_axis.number_to_point(x)[0] * RIGHT result += self.y_axis.number_to_point(y)[1] * UP return result def point_to_coords(self, point): return (self.x_axis.point_to_number(point), self.y_axis.point_to_number(point)) def get_graph( self, func, color=None, x_min=None, x_max=None, **kwargs ): if color is None: color = next(self.default_graph_colors_cycle) if x_min is None: x_min = self.x_min if x_max is None: x_max = self.x_max def parameterized_function(alpha): x = interpolate(x_min, x_max, alpha) y = func(x) if not np.isfinite(y): y = self.y_max return self.coords_to_point(x, y) graph = ParametricCurve( parameterized_function, color=color, **kwargs ) graph.underlying_function = func return graph def input_to_graph_point(self, x, graph): return self.coords_to_point(x, graph.underlying_function(x)) def angle_of_tangent(self, x, graph, dx=0.01): vect = self.input_to_graph_point( x + dx, graph) - self.input_to_graph_point(x, graph) return angle_of_vector(vect) def slope_of_tangent(self, *args, **kwargs): return np.tan(self.angle_of_tangent(*args, **kwargs)) def get_derivative_graph(self, graph, dx=0.01, **kwargs): if "color" not in kwargs: kwargs["color"] = self.default_derivative_color def deriv(x): return self.slope_of_tangent(x, graph, dx) / self.space_unit_to_y return self.get_graph(deriv, **kwargs) def get_graph_label( self, graph, label="f(x)", x_val=None, direction=RIGHT, buff=MED_SMALL_BUFF, color=None, ): label = OldTex(label) color = color or graph.get_color() label.set_color(color) if x_val is None: # Search from right to left for x in np.linspace(self.x_max, self.x_min, 100): point = self.input_to_graph_point(x, graph) if point[1] < FRAME_Y_RADIUS: break x_val = x label.next_to( self.input_to_graph_point(x_val, graph), direction, buff=buff ) label.shift_onto_screen() return label def get_riemann_rectangles( self, graph, x_min=None, x_max=None, dx=0.1, input_sample_type="left", stroke_width=1, stroke_color=BLACK, fill_opacity=1, start_color=None, end_color=None, show_signed_area=True, width_scale_factor=1.001 ): x_min = x_min if x_min is not None else self.x_min x_max = x_max if x_max is not None else self.x_max if start_color is None: start_color = self.default_riemann_start_color if end_color is None: end_color = self.default_riemann_end_color rectangles = VGroup() x_range = np.arange(x_min, x_max, dx) colors = color_gradient([start_color, end_color], len(x_range)) for x, color in zip(x_range, colors): if input_sample_type == "left": sample_input = x elif input_sample_type == "right": sample_input = x + dx elif input_sample_type == "center": sample_input = x + 0.5 * dx else: raise Exception("Invalid input sample type") graph_point = self.input_to_graph_point(sample_input, graph) points = VGroup(*list(map(VectorizedPoint, [ self.coords_to_point(x, 0), self.coords_to_point(x + width_scale_factor * dx, 0), graph_point ]))) rect = Rectangle() rect.replace(points, stretch=True) if graph_point[1] < self.graph_origin[1] and show_signed_area: fill_color = invert_color(color) else: fill_color = color rect.set_fill(fill_color, opacity=fill_opacity) rect.set_stroke(stroke_color, width=stroke_width) rectangles.add(rect) return rectangles def get_riemann_rectangles_list( self, graph, n_iterations, max_dx=0.5, power_base=2, stroke_width=1, **kwargs ): return [ self.get_riemann_rectangles( graph=graph, dx=float(max_dx) / (power_base**n), stroke_width=float(stroke_width) / (power_base**n), **kwargs ) for n in range(n_iterations) ] def get_area(self, graph, t_min, t_max): numerator = max(t_max - t_min, 0.0001) dx = float(numerator) / self.num_rects return self.get_riemann_rectangles( graph, x_min=t_min, x_max=t_max, dx=dx, stroke_width=0, ).set_fill(opacity=self.area_opacity) def transform_between_riemann_rects(self, curr_rects, new_rects, **kwargs): transform_kwargs = { "run_time": 2, "lag_ratio": 0.5 } added_anims = kwargs.get("added_anims", []) transform_kwargs.update(kwargs) curr_rects.align_family(new_rects) x_coords = set() # Keep track of new repetitions for rect in curr_rects: x = rect.get_center()[0] if x in x_coords: rect.set_fill(opacity=0) else: x_coords.add(x) self.play( Transform(curr_rects, new_rects, **transform_kwargs), *added_anims ) def get_vertical_line_to_graph( self, x, graph, line_class=Line, **line_kwargs ): if "color" not in line_kwargs: line_kwargs["color"] = graph.get_color() return line_class( self.coords_to_point(x, 0), self.input_to_graph_point(x, graph), **line_kwargs ) def get_vertical_lines_to_graph( self, graph, x_min=None, x_max=None, num_lines=20, **kwargs ): x_min = x_min or self.x_min x_max = x_max or self.x_max return VGroup(*[ self.get_vertical_line_to_graph(x, graph, **kwargs) for x in np.linspace(x_min, x_max, num_lines) ]) def get_secant_slope_group( self, x, graph, dx=None, dx_line_color=None, df_line_color=None, dx_label=None, df_label=None, include_secant_line=True, secant_line_color=None, secant_line_length=10, ): """ Resulting group is of the form VGroup( dx_line, df_line, dx_label, (if applicable) df_label, (if applicable) secant_line, (if applicable) ) with attributes of those names. """ kwargs = locals() kwargs.pop("self") group = VGroup() group.kwargs = kwargs dx = dx or float(self.x_max - self.x_min) / 10 dx_line_color = dx_line_color or self.default_input_color df_line_color = df_line_color or graph.get_color() p1 = self.input_to_graph_point(x, graph) p2 = self.input_to_graph_point(x + dx, graph) interim_point = p2[0] * RIGHT + p1[1] * UP group.dx_line = Line( p1, interim_point, color=dx_line_color ) group.df_line = Line( interim_point, p2, color=df_line_color ) group.add(group.dx_line, group.df_line) labels = VGroup() if dx_label is not None: group.dx_label = OldTex(dx_label) labels.add(group.dx_label) group.add(group.dx_label) if df_label is not None: group.df_label = OldTex(df_label) labels.add(group.df_label) group.add(group.df_label) if len(labels) > 0: max_width = 0.8 * group.dx_line.get_width() max_height = 0.8 * group.df_line.get_height() if labels.get_width() > max_width: labels.set_width(max_width) if labels.get_height() > max_height: labels.set_height(max_height) if dx_label is not None: group.dx_label.next_to( group.dx_line, np.sign(dx) * DOWN, buff=group.dx_label.get_height() / 2 ) group.dx_label.set_color(group.dx_line.get_color()) if df_label is not None: group.df_label.next_to( group.df_line, np.sign(dx) * RIGHT, buff=group.df_label.get_height() / 2 ) group.df_label.set_color(group.df_line.get_color()) if include_secant_line: secant_line_color = secant_line_color or self.default_derivative_color group.secant_line = Line(p1, p2, color=secant_line_color) group.secant_line.scale( secant_line_length / group.secant_line.get_length() ) group.add(group.secant_line) return group def add_T_label(self, x_val, side=RIGHT, label=None, color=WHITE, animated=False, **kwargs): triangle = RegularPolygon(n=3, start_angle=np.pi / 2) triangle.set_height(MED_SMALL_BUFF) triangle.move_to(self.coords_to_point(x_val, 0), UP) triangle.set_fill(color, 1) triangle.set_stroke(width=0) if label is None: T_label = OldTex(self.variable_point_label, fill_color=color) else: T_label = OldTex(label, fill_color=color) T_label.next_to(triangle, DOWN) v_line = self.get_vertical_line_to_graph( x_val, self.v_graph, color=YELLOW ) if animated: self.play( DrawBorderThenFill(triangle), ShowCreation(v_line), Write(T_label, run_time=1), **kwargs ) if np.all(side == LEFT): self.left_T_label_group = VGroup(T_label, triangle) self.left_v_line = v_line self.add(self.left_T_label_group, self.left_v_line) elif np.all(side == RIGHT): self.right_T_label_group = VGroup(T_label, triangle) self.right_v_line = v_line self.add(self.right_T_label_group, self.right_v_line) def get_animation_integral_bounds_change( self, graph, new_t_min, new_t_max, fade_close_to_origin=True, run_time=1.0 ): curr_t_min = self.x_axis.point_to_number(self.area.get_left()) curr_t_max = self.x_axis.point_to_number(self.area.get_right()) if new_t_min is None: new_t_min = curr_t_min if new_t_max is None: new_t_max = curr_t_max group = VGroup(self.area) group.add(self.left_v_line) group.add(self.left_T_label_group) group.add(self.right_v_line) group.add(self.right_T_label_group) def update_group(group, alpha): area, left_v_line, left_T_label, right_v_line, right_T_label = group t_min = interpolate(curr_t_min, new_t_min, alpha) t_max = interpolate(curr_t_max, new_t_max, alpha) new_area = self.get_area(graph, t_min, t_max) new_left_v_line = self.get_vertical_line_to_graph( t_min, graph ) new_left_v_line.set_color(left_v_line.get_color()) left_T_label.move_to(new_left_v_line.get_bottom(), UP) new_right_v_line = self.get_vertical_line_to_graph( t_max, graph ) new_right_v_line.set_color(right_v_line.get_color()) right_T_label.move_to(new_right_v_line.get_bottom(), UP) # Fade close to 0 if fade_close_to_origin: if len(left_T_label) > 0: left_T_label[0].set_fill(opacity=min(1, np.abs(t_min))) if len(right_T_label) > 0: right_T_label[0].set_fill(opacity=min(1, np.abs(t_max))) Transform(area, new_area).update(1) Transform(left_v_line, new_left_v_line).update(1) Transform(right_v_line, new_right_v_line).update(1) return group return UpdateFromAlphaFunc(group, update_group, run_time=run_time) def animate_secant_slope_group_change( self, secant_slope_group, target_dx=None, target_x=None, run_time=3, added_anims=None, **anim_kwargs ): if target_dx is None and target_x is None: raise Exception( "At least one of target_x and target_dx must not be None") if added_anims is None: added_anims = [] start_dx = secant_slope_group.kwargs["dx"] start_x = secant_slope_group.kwargs["x"] if target_dx is None: target_dx = start_dx if target_x is None: target_x = start_x def update_func(group, alpha): dx = interpolate(start_dx, target_dx, alpha) x = interpolate(start_x, target_x, alpha) kwargs = dict(secant_slope_group.kwargs) kwargs["dx"] = dx kwargs["x"] = x new_group = self.get_secant_slope_group(**kwargs) group.become(new_group) return group self.play( UpdateFromAlphaFunc( secant_slope_group, update_func, run_time=run_time, **anim_kwargs ), *added_anims ) secant_slope_group.kwargs["x"] = target_x secant_slope_group.kwargs["dx"] = target_dx
from manimlib.constants import * from manimlib.mobject.numbers import Integer from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.types.vectorized_mobject import VMobject, VGroup from manimlib.scene.scene import Scene from manimlib.utils.simple_functions import choose DEFAULT_COUNT_NUM_OFFSET = (FRAME_X_RADIUS - 1, FRAME_Y_RADIUS - 1, 0) DEFAULT_COUNT_RUN_TIME = 5.0 class CountingScene(Scene): def count(self, items, item_type="mobject", *args, **kwargs): if item_type == "mobject": self.count_mobjects(items, *args, **kwargs) elif item_type == "region": self.count_regions(items, *args, **kwargs) else: raise Exception("Unknown item_type, should be mobject or region") return self def count_mobjects( self, mobjects, mode="highlight", color="red", display_numbers=True, num_offset=DEFAULT_COUNT_NUM_OFFSET, run_time=DEFAULT_COUNT_RUN_TIME, ): """ Note, leaves final number mobject as "number" attribute mode can be "highlight", "show_creation" or "show", otherwise a warning is given and nothing is animating during the count """ if len(mobjects) > 50: # TODO raise Exception("I don't know if you should be counting \ too many mobjects...") if len(mobjects) == 0: raise Exception("Counting mobject list of length 0") if mode not in ["highlight", "show_creation", "show"]: raise Warning("Unknown mode") frame_time = run_time / len(mobjects) if mode == "highlight": self.add(*mobjects) for mob, num in zip(mobjects, it.count(1)): if display_numbers: num_mob = OldTex(str(num)) num_mob.center().shift(num_offset) self.add(num_mob) if mode == "highlight": original_color = mob.color mob.set_color(color) self.wait(frame_time) mob.set_color(original_color) if mode == "show_creation": self.play(ShowCreation(mob, run_time=frame_time)) if mode == "show": self.add(mob) self.wait(frame_time) if display_numbers: self.remove(num_mob) if display_numbers: self.add(num_mob) self.number = num_mob return self def count_regions(self, regions, mode="one_at_a_time", num_offset=DEFAULT_COUNT_NUM_OFFSET, run_time=DEFAULT_COUNT_RUN_TIME, **unused_kwargsn): if mode not in ["one_at_a_time", "show_all"]: raise Warning("Unknown mode") frame_time = run_time / (len(regions)) for region, count in zip(regions, it.count(1)): num_mob = OldTex(str(count)) num_mob.center().shift(num_offset) self.add(num_mob) self.set_color_region(region) self.wait(frame_time) if mode == "one_at_a_time": self.reset_background() self.remove(num_mob) self.add(num_mob) self.number = num_mob return self def combinationMobject(n, k): return Integer(choose(n, k)) class GeneralizedPascalsTriangle(VMobject): nrows = 7 height = FRAME_HEIGHT - 1 width = 1.5 * FRAME_X_RADIUS portion_to_fill = 0.7 submob_class = combinationMobject def init_points(self): self.cell_height = float(self.height) / self.nrows self.cell_width = float(self.width) / self.nrows self.bottom_left = (self.cell_width * self.nrows / 2.0) * LEFT + \ (self.cell_height * self.nrows / 2.0) * DOWN self.coords_to_mobs = {} self.coords = [ (n, k) for n in range(self.nrows) for k in range(n + 1) ] for n, k in self.coords: center = self.coords_to_center(n, k) num_mob = self.submob_class(n, k) # OldTex(str(num)) scale_factor = min( 1, self.portion_to_fill * self.cell_height / num_mob.get_height(), self.portion_to_fill * self.cell_width / num_mob.get_width(), ) num_mob.center().scale(scale_factor).shift(center) if n not in self.coords_to_mobs: self.coords_to_mobs[n] = {} self.coords_to_mobs[n][k] = num_mob self.add(*[ self.coords_to_mobs[n][k] for n, k in self.coords ]) return self def coords_to_center(self, n, k): x_offset = self.cell_width * (k + self.nrows / 2.0 - n / 2.0) y_offset = self.cell_height * (self.nrows - n) return self.bottom_left + x_offset * RIGHT + y_offset * UP def generate_n_choose_k_mobs(self): self.coords_to_n_choose_k = {} for n, k in self.coords: nck_mob = OldTex(r"{%d \choose %d}" % (n, k)) scale_factor = min( 1, self.portion_to_fill * self.cell_height / nck_mob.get_height(), self.portion_to_fill * self.cell_width / nck_mob.get_width(), ) center = self.coords_to_mobs[n][k].get_center() nck_mob.center().scale(scale_factor).shift(center) if n not in self.coords_to_n_choose_k: self.coords_to_n_choose_k[n] = {} self.coords_to_n_choose_k[n][k] = nck_mob return self def fill_with_n_choose_k(self): if not hasattr(self, "coords_to_n_choose_k"): self.generate_n_choose_k_mobs() self.set_submobjects([]) self.add(*[ self.coords_to_n_choose_k[n][k] for n, k in self.coords ]) return self def generate_sea_of_zeros(self): zero = OldTex("0") self.sea_of_zeros = [] for n in range(self.nrows): for a in range((self.nrows - n) / 2 + 1): for k in (n + a + 1, -a - 1): self.coords.append((n, k)) mob = zero.copy() mob.shift(self.coords_to_center(n, k)) self.coords_to_mobs[n][k] = mob self.add(mob) return self def get_lowest_row(self): n = self.nrows - 1 lowest_row = VGroup(*[ self.coords_to_mobs[n][k] for k in range(n + 1) ]) return lowest_row class PascalsTriangle(GeneralizedPascalsTriangle): submob_class = combinationMobject
from manim_imports_ext import * from _2023.barber_pole.objects import * class SlicedWave(Group): default_wave_config = dict( z_amplitude=0, y_amplitude=1, wave_len=2.0, color=BLUE, ) default_layer_style = dict( stroke_width=2.0, stroke_color=WHITE, ) default_vect_wave_style = dict( stroke_opacity=0.5 ) def __init__( self, axes, layer_xs, phase_kick_back=0, layer_height=4.0, damping_per_layer=1.0, wave_config = dict(), vect_wave_style=dict(), layer_style=dict(), ): self.layer_xs = layer_xs self.axes = axes wave_kw = merge_dicts_recursively(self.default_wave_config, wave_config) vwave_kw = merge_dicts_recursively(self.default_vect_wave_style, vect_wave_style) line_kw = merge_dicts_recursively(self.default_layer_style, layer_style) self.wave = OscillatingWave(axes, **wave_kw) self.vect_wave = OscillatingFieldWave(axes, self.wave, **vwave_kw) self.phase_kick_trackers = [ ValueTracker(phase_kick_back) for x in layer_xs ] self.absorbtion_trackers = [ ValueTracker(damping_per_layer) for x in layer_xs ] self.layers = VGroup() for x in layer_xs: line = Line(DOWN, UP, **line_kw) line.set_height(layer_height) line.move_to(axes.c2p(x, 0)) self.layers.add(line) self.wave.xt_to_yz = self.xt_to_yz super().__init__( self.wave, self.vect_wave, self.layers, *self.phase_kick_trackers ) def set_layer_xs(self, xs): self.layer_xs = xs def xt_to_yz(self, x, t): phase = np.ones_like(x) phase *= TAU * t * self.wave.speed / self.wave.wave_len amplitudes = self.wave.y_amplitude * np.ones_like(x) for layer_x, pkt, at in zip(self.layer_xs, self.phase_kick_trackers, self.absorbtion_trackers): phase[x > layer_x] += pkt.get_value() amplitudes[x > layer_x] *= at.get_value() y = amplitudes * np.sin(TAU * x / self.wave.wave_len - phase) return y, np.zeros_like(x) # Scenes class SpeedInMediumFastPart(InteractiveScene): z_amplitude = 0 y_amplitude = 1.0 color = YELLOW wave_len = 3.0 speed = 1.5 medium_color = BLUE medium_opacity = 0.35 add_label = True run_time = 30 material_label = "Glass" def construct(self): # Basic wave axes = ThreeDAxes((-12, 12), (-4, 4)) axes.z_axis.set_stroke(opacity=0) axes.y_axis.set_stroke(opacity=0) wave = OscillatingWave( axes, z_amplitude=self.z_amplitude, y_amplitude=self.y_amplitude, color=self.color, wave_len=self.wave_len, speed=self.speed, ) vect_wave = OscillatingFieldWave(axes, wave) vect_wave.set_stroke(opacity=0.5) self.add(axes, wave, vect_wave) # Water label rect = FullScreenRectangle() rect.stretch(0.5, 0, about_edge=RIGHT) rect.set_stroke(width=0) rect.set_fill(self.medium_color, self.medium_opacity) self.add(rect) if self.add_label: label = Text(self.material_label, font_size=60) label.next_to(rect.get_top(), DOWN) self.add(label) # Propagate self.wait(self.run_time) class SpeedInMediumSlower(SpeedInMediumFastPart): wave_len = 2.0 speed = 1.0 class VectorOverMedia(InteractiveScene): def construct(self): vect = Vector(DOWN) vect.next_to(UP, UP) vect.to_edge(LEFT, buff=0) def update_vect(v, dt): # speed = 1.5 if v.get_x() < 0 else 1.0 speed = 1.33 if v.get_x() < 0 else 1.33 / 1.5 v.shift(dt * RIGHT * speed) vect.add_updater(update_vect) word = Text("Phase velocity") word.add_updater(lambda m: m.next_to(vect, UP)) self.add(vect) self.add(word) self.wait(13) class VioletWaveFast(SpeedInMediumFastPart): color = get_spectral_color(0.95) wave_len = 1.2 y_amplitude = 0.5 speed = 1.5 medium_opacity = 0.25 add_label = False run_time = 15 class VioletWaveSlow(VioletWaveFast): wave_len = 1.2 * 0.5 speed = 1.5 * 0.5 class GreenWaveFast(VioletWaveFast): color = get_spectral_color(0.65) wave_len = 1.5 class GreenWaveSlow(GreenWaveFast): wave_len = 1.5 * 0.6 speed = 1.5 * 0.6 class OrangeWaveFast(VioletWaveFast): color = get_spectral_color(0.3) wave_len = 2.0 class OrangeWaveSlow(OrangeWaveFast): wave_len = 2.0 * 0.7 speed = 1.5 * 0.7 class RedWaveFast(VioletWaveFast): color = get_spectral_color(0.05) wave_len = 2.5 class RedWaveSlow(RedWaveFast): wave_len = 2.5 * 0.8 speed = 1.5 * 0.8 class PhaseKickBacks(SpeedInMediumFastPart): layer_xs = np.arange(0, 8, 1) kick_back_value = 0 axes_config = dict( x_range=(-8, 8), y_range=(-4, 4), ) line_style = dict() wave_config = dict() vect_wave_style = dict() layer_add_on_run_time = 5 damping_per_layer = 1.0 def get_axes(self): axes = ThreeDAxes(**self.axes_config) axes.z_axis.set_stroke(opacity=0) return axes def get_layer_xs(self): return self.layer_xs def get_sliced_wave(self): return SlicedWave( self.get_axes(), self.get_layer_xs(), wave_config=self.wave_config, vect_wave_style=self.vect_wave_style, layer_style=self.line_style, phase_kick_back=self.kick_back_value, damping_per_layer=self.damping_per_layer, ) def setup(self): super().setup() self.sliced_wave = self.get_sliced_wave() self.add(self.sliced_wave) class RevertToOneLayerAtATime(PhaseKickBacks): layer_xs = np.arange(0, FRAME_WIDTH / 2, FRAME_WIDTH / 2**(11)) kick_back_value = -0.025 n_layers_skipped = 64 exagerated_phase_kick = -0.8 line_style = dict( stroke_width=1, stroke_opacity=0.25, stroke_color=BLUE_B ) axes_config = dict( x_range=(-12, 12), y_range=(-4, 4), ) wave_config = dict( color=YELLOW, sample_resolution=0.001 ) vect_wave_style = dict(tip_width_ratio=3, stroke_opacity=0.5) def construct(self): # Objects sliced_wave = self.sliced_wave wave = sliced_wave.wave layers = sliced_wave.layers pkts = sliced_wave.phase_kick_trackers # Add label block_label = Text("Material (e.g. glass)") block_label.next_to(layers, UP, aligned_edge=LEFT) for pkt in pkts: pkt.set_value(-0.015) self.wait(5) self.play(Write(block_label["Material"], run_time=1)) self.play(FadeIn(block_label["(e.g. glass)"], 0.25 * UP)) self.add(block_label) self.wait(2) # Show layers layers.save_state() rect = BackgroundRectangle(sliced_wave) rect.set_fill(BLACK, 0.9) self.add(sliced_wave, rect, layers) self.play( layers.animate.arrange(RIGHT, buff=0.3).move_to(ORIGIN, LEFT).set_stroke(width=2, opacity=1), FadeIn(rect), *(pkt.animate.set_value(0) for pkt in pkts), run_time=2, ) self.wait(3) # Revert to one single layer left_layers = VGroup() for layer in layers: if layer.get_x() < FRAME_WIDTH / 2: left_layers.add(layer) self.remove(layers) self.add(left_layers) layer_label = Text("Thin layer of material") layer_label.next_to(layers[0], UP, buff=0.75) kw = dict(run_time=5, lag_ratio=0.1) self.play( LaggedStart(*( layer.animate().set_stroke(opacity=0).shift(DOWN) for layer in left_layers[:0:-1] ), **kw), layers[0].animate.set_stroke(width=2, opacity=1).set_height(5).set_anim_args(time_span=(4, 5)), FadeTransform( block_label, layer_label, time_span=(4, 5) ), FadeOut(rect, time_span=(3, 5)), ) self.wait(4) # Pause, shift the phase a bit arrow = Vector(1.0 * LEFT, stroke_width=6) arrow.next_to(wave, UP, buff=0.75) arrow.set_x(0, LEFT).shift(0.1 * RIGHT) phase_kick = self.exagerated_phase_kick kick_words = Text("Kick back\nthe phase", font_size=36) kick_words.next_to(arrow, RIGHT) kick_label = VGroup(arrow, kick_words) kick_label.set_color(RED) self.wait(1 - (wave.time % 1)) wave.stop_clock() self.wait() self.play( pkts[0].animate.set_value(phase_kick), FadeIn(kick_label, LEFT), ) self.wait() # Show the phase kick form1 = Tex(R"A\sin(kx)") form2 = Tex(R"A\sin(kx + 1.00)") pk_decimal: DecimalNumber = form2.make_number_changable("1.00") pk_decimal.set_value(-phase_kick) pk_decimal.set_color(RED) VGroup(form1, form2).next_to(wave, DOWN) form1.set_x(-FRAME_WIDTH / 4) form2.set_x(+FRAME_WIDTH / 4) self.play(FadeIn(form1, 0.5 * DOWN)) self.wait() self.play(TransformMatchingStrings(form1.copy(), form2, path_arc=20 * DEGREES)) self.wait() for value in [-0.01, phase_kick]: self.play( pkts[0].animate.set_value(value), ChangeDecimalToValue(pk_decimal, -value), run_time=2, ) self.wait() # Add phase kick label pk_label = Text("Phase kick = ", font_size=36, fill_color=GREY_B) pk_label.next_to(wave, UP, LARGE_BUFF) pk_label.to_edge(LEFT) form2.remove(pk_decimal) form2.add(pk_decimal.copy()) self.add(form2) self.play( pk_decimal.animate.match_height(pk_label).next_to(pk_label, RIGHT, 0.2, DOWN), ReplacementTransform(kick_words["Kick"].copy(), pk_label["kick"]), ReplacementTransform(kick_words["phase"].copy(), pk_label["Phase"]), FadeIn(pk_label["="]), run_time=2 ) pk_label.add(pk_decimal) self.add(pk_label) self.play( FadeOut(form1), FadeOut(form2), ) # Show following layers for layer in layers[1:]: layer.match_height(layers[0]) layer.match_style(layers[0]) layer.set_stroke(opacity=0) nls = self.n_layers_skipped shown_layers = VGroup(layers[0]) layer_arrows = VGroup(VectorizedPoint(layer_label.get_center())) for layer, pkt in zip(layers[nls::nls], pkts[nls::nls]): layer.set_stroke(opacity=1) shown_layers.add(layer) layer_label.target = layer_label.generate_target() layer_label.target.set_height(0.35) layer_label.target.match_x(shown_layers) layer_label.target.to_edge(UP, buff=0.25) layer_arrows.target = VGroup(*( Arrow( layer_label.target.get_bottom(), sl.get_top(), buff=0.1, stroke_width=2, stroke_opacity=0.5, ) for sl in shown_layers )) self.play( FadeOut(kick_label), GrowFromCenter(layer), MoveToTarget(layer_label), MoveToTarget(layer_arrows), ) kick_label.align_to(layer, LEFT).shift(0.1 * RIGHT) self.play( FadeIn(kick_label, 0.5 * LEFT), pkt.animate.set_value(phase_kick) ) self.play(FadeOut(kick_label)) # Restart clock wave.start_clock() self.play(FadeOut(layer_label), FadeOut(layer_arrows)) self.wait(6) # Change phase kick self.play(FlashAround(pk_label)) for value in [-0.01, self.exagerated_phase_kick]: phase_kick = value globals().update(locals()) self.play( ChangeDecimalToValue(pk_decimal, -phase_kick), *( pkt.animate.set_value(phase_kick) for pkt in pkts[::nls] ), run_time=4 ) self.wait(2) self.wait(2) # Number of layers label n_shown_layers = len(layers[::nls]) n_layers_label = TexText(f"Num. layers = {n_shown_layers}", font_size=36) n_layers_label.set_color(GREY_B) n_layers_label.next_to(pk_label, UP, MED_LARGE_BUFF, LEFT) nl_decimal = n_layers_label.make_number_changable(n_shown_layers) nl_decimal.set_color(BLUE) self.play(FadeIn(n_layers_label, UP)) self.wait(8) # Fill in opacity = 1.0 stroke_width = 2.0 kw = dict(lag_ratio=0.1, run_time=3) while nls > 1: # Update parameters nls //= 2 opacity = 0.25 + 0.5 * (opacity - 0.25) stroke_width = 1.0 + 0.5 * (stroke_width - 1.0) phase_kick /= 2 new_layers = layers[nls::2 * nls] old_layers = layers[0::2 * nls] new_nl_decimal = Integer(len(layers[::nls])) new_nl_decimal.match_height(nl_decimal) new_nl_decimal.match_style(nl_decimal) new_nl_decimal.move_to(nl_decimal, LEFT) new_pk_decimal = DecimalNumber( -phase_kick, num_decimal_places=(2 if -phase_kick > 0.05 else 3) ) new_pk_decimal.match_height(pk_decimal) new_pk_decimal.match_style(pk_decimal) new_pk_decimal.move_to(pk_decimal, LEFT) new_layers.set_stroke(width=stroke_width, opacity=opacity) globals().update(locals()) # Only necessary for embedded runs self.play( LaggedStart(*( GrowFromCenter(layer) for layer in new_layers ), **kw), old_layers.animate.set_stroke(width=stroke_width, opacity=opacity), LaggedStart(*( pkt.animate.set_value(phase_kick) for pkt in pkts[::nls] ), **kw), LaggedStart( FadeOut(nl_decimal, 0.2 * UP), FadeIn(new_nl_decimal, 0.2 * UP), FadeOut(pk_decimal, 0.2 * UP), FadeIn(new_pk_decimal, 0.2 * UP), lag_ratio=0.1, run_time=1 ) ) nl_decimal = new_nl_decimal pk_decimal = new_pk_decimal globals().update(locals()) # Only necessary for embedded runs self.play(*( pkt.animate.set_value(phase_kick) for pkt in pkts[::nls] )) self.wait(3 if nls >= 32 else 1) # Wait self.wait(10) class SimplerRevertToOneLayerAtATime(RevertToOneLayerAtATime): layer_xs = np.arange(-0, 7.5, 0.11) kick_back_value = -0.25 n_layers_skipped = 8 class SlowedAndAbsorbed(RevertToOneLayerAtATime): layer_xs = np.arange(-FRAME_WIDTH / 3, FRAME_WIDTH / 3, FRAME_WIDTH / 2**(8)) kick_back_value = -0.2 damping_per_layer = 1 - 2e-2 wave_config = dict( color=YELLOW, sample_resolution=0.001, ) line_style = dict( stroke_color=BLUE_B, stroke_width=1.5, stroke_opacity=0.5, ) def construct(self): # Objects sliced_wave = self.sliced_wave wave = sliced_wave.wave layers = sliced_wave.layers pkts = sliced_wave.phase_kick_trackers ats = sliced_wave.absorbtion_trackers # Show labels label = Text("Wave gets slowed and absorbed") label.next_to(layers, UP) abs_words = label["and absorbed"] mu_label = Tex(R"\mu").set_color(PINK) mu_line = NumberLine((0, 1, 0.2), width=1.0, tick_size=0.05) mu_line.rotate(PI / 2) mu_line.to_corner(UR) mu_indicator = Triangle(start_angle=0) mu_indicator.set_width(0.15) mu_indicator.set_fill(PINK, 1) mu_indicator.set_stroke(width=0) mu_tracker = ValueTracker(1) mu_indicator.add_updater(lambda m: m.move_to(mu_line.n2p(mu_tracker.get_value()), RIGHT)) mu_label.add_updater(lambda m: m.next_to(mu_indicator, LEFT, buff=0.1)) for pkt in pkts: pkt.set_value(0) for at in ats: at.set_value(1) self.play( FadeIn(label, time_span=(0, 2)), FlashAround(abs_words, color=PINK, time_span=(2, 4)), abs_words.animate.set_color(PINK).set_anim_args(time_span=(2, 4)), FadeIn(mu_line), FadeIn(mu_indicator), FadeIn(mu_label), LaggedStart(*( pkt.animate.set_value(self.kick_back_value) for pkt in pkts )), LaggedStart(*( at.animate.set_value(self.damping_per_layer) for at in ats )), LaggedStart(*( FadeIn(layer, scale=0.8) for layer in layers )), run_time=5, ) # Play with mu for mu in [0.1, 1.0]: self.play( mu_tracker.animate.set_value(mu), *(at.animate.set_value(1 - mu * 2e-2) for at in ats), run_time=3, ) self.wait(17) class PlayWithIndex(RevertToOneLayerAtATime): layer_xs = np.arange(-FRAME_WIDTH / 4, FRAME_WIDTH / 4, FRAME_WIDTH / 2**(10)) def construct(self): # Objects sliced_wave = self.sliced_wave wave = sliced_wave.wave layers = sliced_wave.layers layers.set_stroke(BLUE, 1, 0.5) pkts = sliced_wave.phase_kick_trackers global_pk = ValueTracker(self.kick_back_value) for pkt in pkts: pkt.add_updater(lambda m: m.set_value(global_pk.get_value())) def get_index(): return 1 - 20 * global_pk.get_value() # equation label equation = Tex( R""" \text{Index of refraction } = {\small \text{Speed in a vacuum} \over \text{Speed in medium}} = 1.00 """, t2c={ R"\text{Speed in a vacuum}": YELLOW, R"\text{Speed in medium}": BLUE, } ) equation.next_to(layers, UP) rhs = equation.make_number_changable("1.00") rhs.add_updater(lambda m: m.set_value(get_index())) arrow = Arrow(rhs.get_bottom(), layers.get_corner(UR) + 1.0 * DL) self.add(equation) self.add(arrow) # Speed label speed_label = Tex(R"\text{Speed} = c / 1.00") speed_factor = speed_label.make_number_changable("1.00") speed_factor.add_updater(lambda m: m.set_value(get_index())) speed_label.next_to(layers.get_bottom(), UP) self.add(speed_label) # Change value self.wait(3) for value in [0, 0.02]: self.play(global_pk.animate.set_value(value), run_time=2) self.wait(3) self.wait(10) class RedLight(RevertToOneLayerAtATime): wave_config = dict( color=RED, stroke_width=6, sample_resolution=0.001, wave_len=4.0, ) kick_back_value = -0.005 def construct(self): # Test sliced_wave = self.sliced_wave wave = sliced_wave.wave layers = sliced_wave.layers pkts = sliced_wave.phase_kick_trackers sliced_wave.update() sliced_wave.clear_updaters() sliced_wave.vect_wave.set_stroke(opacity=1) sliced_wave.wave.make_jagged() new_wave = VMobject() new_wave.set_points_smoothly(sliced_wave.wave.get_anchors()[0::5]) new_wave.match_style(sliced_wave.wave) self.add(self.sliced_wave) self.add(new_wave) self.remove(sliced_wave.layers) class XRay(RedLight): wave_config = dict( color=YELLOW, stroke_width=6, sample_resolution=0.001, wave_len=1.0, ) kick_back_value = 0.02 class DissolveLayers(PhaseKickBacks): def construct(self): # Test sliced_wave = self.sliced_wave layers = sliced_wave.layers pkts = sliced_wave.phase_kick_trackers # Zoom in on layers frame = self.frame layers_copy = layers.copy() layers_copy.set_stroke(width=1) fade_rect = FullScreenRectangle().set_fill(BLACK, 1) self.wait(4) self.add(fade_rect, layers_copy) self.play( frame.animate.scale(0.2).move_to(layers).set_anim_args(run_time=4), FadeIn(fade_rect, time_span=(1, 3)), FadeIn(layers_copy, time_span=(1, 3)), ) self.wait() self.play( frame.animate.to_default_state().set_anim_args(run_time=2), FadeOut(fade_rect), FadeOut(layers_copy), ) self.wait(2) # Dissolve kw = dict(run_time=8, lag_ratio=0.1) self.play( LaggedStart(*( layer.animate().set_stroke(WHITE, 2, 0).set_height(5) for layer in layers[:0:-1] ), **kw), LaggedStart(*( pkt.animate.set_value(0) for pkt in pkts[:0:-1] ), **kw), layers[0].animate.set_stroke(WHITE, 2).set_height(5).set_anim_args(time_span=(7, 8)) ) self.wait(3) class IntroducePhaseKickBack(PhaseKickBacks): layer_xs = np.arange(0, 8, PI / 4) vect_wave_style = dict(stroke_width=0) def construct(self): # Set up sine wave sliced_wave = self.sliced_wave axes = sliced_wave.axes layers = sliced_wave.layers pkts = sliced_wave.phase_kick_trackers wave = sliced_wave.wave self.remove(sliced_wave) wave.stop_clock() self.add(wave) self.add(*pkts) # # Pair of braces # brace1 = Brace(Line(LEFT_SIDE, ORIGIN, buff=0.25), UP) # brace2 = brace1.copy().set_x(FRAME_WIDTH / 4) # braces = VGroup(brace1, brace2) # braces.set_y(2) # self.add(braces) # b1_tex = brace1.get_tex(R"\sin(\omega t - kx)") # b2_tex = brace2.get_tex(R"\sin(\omega t - kx - \Delta \phi)") # self.add(b1_tex) # self.add(b2_tex) # Add one layer of material self.play(GrowFromCenter(layers[0])) # TODO: Some kind of labels here? # Show small kick back arrow = Vector(2 * LEFT, stroke_width=8) arrow.next_to(wave, UP, buff=0.75) arrow.set_x(0, LEFT).shift(0.5 * RIGHT) phase_kick = -0.5 self.play( pkts[0].animate.set_value(phase_kick), FadeIn(arrow, LEFT), ) self.play(FadeOut(arrow)) # Add more layers of material for layer, pkt in zip(layers[1:], pkts[1:]): arrow.align_to(layer, LEFT).shift(0.25 * RIGHT) self.play( GrowFromCenter(layer), FadeIn(arrow, LEFT), pkt.animate.set_value(phase_kick), ) self.play(FadeOut(arrow), run_time=0.5) # Make it all more dense pass class PhaseKickBackAddInLayers(PhaseKickBacks): n_layers = 10 kick_back_value = 0 target_kick_back = -0.5 def get_layer_xs(self): return np.linspace(0, 8, self.n_layers) def construct(self): sliced_wave = self.sliced_wave lag_kw = dict(run_time=self.layer_add_on_run_time, lag_ratio=0.5) self.play( LaggedStart(*( FadeIn(line, 0.5 * DOWN) for line in sliced_wave.layers ), **lag_kw), LaggedStart(*( pkt.animate.set_value(self.target_kick_back) for pkt in sliced_wave.phase_kick_trackers ), **lag_kw), ) self.wait(8) class DensePhaseKickBacks25(PhaseKickBackAddInLayers): n_layers = 25 target_kick_back = -0.4 line_style = dict( stroke_width=1.0, stroke_color=BLUE_B, ) class DensePhaseKickBacks50(PhaseKickBackAddInLayers): n_layers = 50 target_kick_back = -0.2 line_style = dict( stroke_width=1.0, stroke_color=BLUE_B, ) class DensePhaseKickBacks100(PhaseKickBackAddInLayers): n_layers = 100 target_kick_back = -0.15 line_style = dict( stroke_width=1.5, stroke_color=BLUE_C, stroke_opacity=0.7, ) layer_add_on_run_time = 10 class FastWave(PhaseKickBacks): layer_xs = np.arange(-3, 3, 0.01) kick_back_value = 0.01 line_style = dict( stroke_width=1, stroke_opacity=0.35, stroke_color=BLUE_D ) wave_config = dict( color=YELLOW, sample_resolution=0.001 ) def construct(self): # Test self.wait(20) class KickForward(PhaseKickBacks): layer_xs = np.arange(0, 8, 0.25) kick_back_value = 0.25 line_style = dict( stroke_color=BLUE, stroke_width=2, stroke_opacity=0.75, ) wave_config = dict( color=YELLOW, sample_resolution=0.001 ) time_per_layer = 0.25 def construct(self): # Objects sliced_wave = self.sliced_wave wave = sliced_wave.wave layers = sliced_wave.layers layers.stretch(1.2, 1) pkts = sliced_wave.phase_kick_trackers # Just show one layer layer_label = Text("Thin layer of material") layer_label.next_to(layers[0], UP, buff=0.75) for pkt in pkts: pkt.set_value(0) self.wait(1 - (wave.time % 1)) wave.stop_clock() self.remove(layers) self.play( ShowCreation(layers[0]), FadeIn(layer_label, lag_ratio=0.1), ) self.wait() # Kick back then forth kick_back = VGroup( Vector(LEFT, stroke_width=6), Text("Kick back\nthe phase", font_size=36), ) kick_back.set_color(RED) kick_forward = VGroup( Vector(RIGHT, stroke_width=6), Text( "Kick forward\nthe phase", font_size=36, t2s={"forward": ITALIC} ), ) kick_forward.set_color(GREEN) for label in [kick_back, kick_forward]: label.arrange(RIGHT) label.next_to(wave, UP) label.align_to(layers[0], LEFT).shift(MED_SMALL_BUFF * RIGHT) self.play( pkts[0].animate.set_value(-0.75), FadeIn(kick_back, LEFT), ) self.wait() self.play(FadeOut(kick_back)) self.play( pkts[0].animate.set_value(self.kick_back_value), FadeIn(kick_forward, RIGHT), ) self.wait() self.play(FadeOut(layer_label)) # Add other layers wave.start_clock() remaining_layers = layers[1:] self.play( ShowIncreasingSubsets(remaining_layers, rate_func=linear), UpdateFromFunc( kick_forward, lambda m: m.align_to(remaining_layers.get_right(), LEFT).shift(MED_SMALL_BUFF * RIGHT), ), LaggedStart(*( pkt.animate.set_value(self.kick_back_value) for pkt in pkts[1:] ), lag_ratio=1), run_time = len(remaining_layers) * self.time_per_layer ) # Wait self.wait(20) class DenserKickForward(KickForward): # Run at 9 layer_xs = np.arange(0, 8, 0.1) kick_back_value = 0.1 line_style = dict( stroke_color=BLUE, stroke_width=1.5, stroke_opacity=0.75, ) time_per_layer = 0.1 class DensestKickForward(DenserKickForward): layer_xs = np.arange(0, 8, 0.025) kick_back_value = 0.025 time_per_layer = 0.025 line_style = dict( stroke_color=BLUE, stroke_width=1.0, stroke_opacity=0.65, )
from manim_imports_ext import * from _2023.barber_pole.objects import * class AnnotateDemo(InteractiveScene): def construct(self): image = ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/barber_pole/images/DemoStill.jpg") image.set_height(FRAME_HEIGHT) plane = NumberPlane().fade(0.25) # self.add(image) # self.add(plane) # Label sugar sugar_label = Text("Sugar solution\n(0.75g sucrose/mL water)") sugar_label.move_to(2.5 * UP) sugar_label.set_backstroke(BLACK, 3) arrow_kw = dict(stroke_color=RED, stroke_width=10) sugar_arrow = Arrow(sugar_label, plane.c2p(0, 0.5), **arrow_kw) self.play( Write(sugar_label, lag_ratio=0.01, run_time=2), ShowCreation(sugar_arrow), ) self.wait() # Label light light_label = Text("White light\n(unpolarized)") light_label.match_y(sugar_label) light_label.match_style(sugar_label) light_label.to_edge(RIGHT) light_arrow = Arrow(light_label, plane.c2p(4.75, 0.85), buff=0.1, **arrow_kw) self.play( FadeTransform(sugar_label, light_label), ReplacementTransform(sugar_arrow, light_arrow), ) self.wait() # Label polarizer filter_label = Text("Linearly polarizing filter\n(variable angle)") filter_label.set_x(3.5).to_edge(UP) filter_label.match_style(sugar_label) filter_arrow = Arrow(filter_label, plane.c2p(3.4, 1.25), buff=0.1, **arrow_kw) self.play( FadeTransform(light_label, filter_label), ReplacementTransform(light_arrow, filter_arrow), ) self.wait() self.play( filter_label.animate.set_x(-2.2).to_edge(UP, buff=0.5), filter_arrow.animate.set_x(-3.3), ) self.wait() class HoldUp(TeacherStudentsScene): def construct(self): arrow = Vector(LEFT, stroke_color=YELLOW) arrow.to_edge(UP, buff=1.0) # self.add(arrow) self.play( self.teacher.change("raise_right_hand", look_at=3 * UR), self.change_students("pondering", "erm", "sassy", look_at=self.screen) ) self.wait(3) self.play( self.change_students("maybe", "pondering", "hesitant", look_at=3 * UR) ) self.wait(3) class SteveVideoWrapper(VideoWrapper): title = "Steve Mould: Why Sugar Always Twists Light" class DidntSteveCover(TeacherStudentsScene): def construct(self): stds = self.students morty = self.teacher image = ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/barber_pole/chat with Steve/MouldThumbnail.jpg") image.set_height(3) thumbnail = Group( SurroundingRectangle(image, buff=0).set_stroke(WHITE, 3), image ) thumbnail.next_to(stds[2].get_corner(UR), UP, buff=1.0) thumbnail.shift(RIGHT) # Test self.play( stds[2].says("Didn't Steve Mould\ncover this?", mode="raise_right_hand"), morty.change("tease"), self.change_students("pondering", "pondering", look_at=thumbnail), FadeIn(thumbnail, UP) ) self.wait(4) class FocusOnWall(InteractiveScene): def construct(self): # Test words = Text("Notice what color comes out", font_size=72) words.set_backstroke(BLACK, 5) words.to_edge(UP) arrow = Arrow( words["Notice what"].get_bottom(), 6.5 * LEFT + 0.5 * UP, buff=0.5, stroke_color=RED, stroke_width=14, ) self.play( FadeIn(words, 0.25 * UP), GrowArrow(arrow), ) self.wait() class WhatWeNeedToUnderstand(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students # React self.play( self.change_students("pondering", "maybe", "confused", look_at=self.screen), morty.change("tease") ) self.wait(3) self.play( self.change_students("erm", "sassy", "maybe", look_at=self.screen) ) self.wait(3) # Core concepts concepts = VGroup( Text("Polarization"), Text("Scattering"), Text("The index of refraction"), ) concepts.arrange(DOWN, aligned_edge=LEFT) concepts.next_to(self.hold_up_spot, UP) for i in range(3): concepts[i].align_to(concepts, DOWN) self.play( FadeIn(concepts[i], 0.5 * UP), concepts[:i].animate.shift(UP), morty.change("raise_right_hand", concepts), *(pi.animate.look_at(concepts) for pi in stds), ) self.wait() self.wait() # Start with an overview self.play( morty.says("To begin:\nAn overview"), FadeOut(concepts, UP), self.change_students("tease", "happy", "well", look_at=morty.eyes) ) self.look_at(self.screen) self.wait(3) class ThisIsStillWhiteLight(InteractiveScene): def construct(self): # Test words = Text("This is still white light", font_size=60) words.to_edge(UP) arrow = Arrow( words["This"].get_bottom(), LEFT + 0.5 * UP, stroke_color=WHITE, stroke_width=8, ) self.play( Write(words, run_time=1), FadeIn(arrow, RIGHT, run_time=4.0, rate_func=rush_into), ) self.wait() class Questions(InteractiveScene): def construct(self): # Title title = Text("Lingering questions", font_size=72) title.add(Underline(title)) title.to_edge(UP, buff=0.25) self.add(title) # Questions questions = self.get_questions() last_questions = questions[1:] last_questions.save_state() last_questions.set_height(6, about_edge=DL) for question in last_questions: self.play(FadeIn(question, 0.25 * UP)) self.wait() self.wait() self.play( FadeIn(questions[0], shift=0.25 * DOWN), Restore(last_questions) ) self.wait() # Check marks marks = VGroup(*( Checkmark(font_size=60).next_to(question[0], RIGHT).shift(0.15 * UP) for question in questions )) for mark in marks: mark.align_to(marks, RIGHT) # Crossing off cross_lines = VGroup() for question in questions: full_question = question[1] phrases = full_question.get_text().split("\n") cross_lines.add(VGroup(*( Line(LEFT, RIGHT).set_stroke(YELLOW, 3).replace(full_question[phrase], dim_to_match=0) for phrase in phrases ))) # Mark off Q0 self.play( Write(marks[0], stroke_color=GREEN), ShowCreation(cross_lines[0]), ) self.wait() # Highlight question 3 rect = SurroundingRectangle(questions[3]) rect.set_stroke(YELLOW, 2) arrow = Vector(LEFT, stroke_color=YELLOW) arrow.next_to(rect, RIGHT) self.play( questions[:3].animate.set_opacity(0.5), ShowCreation(rect), FadeInFromPoint(arrow, ORIGIN), ) self.wait() self.play( FadeOut(rect), FadeOut(arrow), ShowCreation(cross_lines[3]), Write(marks[3], stroke_color=GREEN), questions[:3].animate.set_opacity(1), ) self.wait() # Question 1 rect.set_stroke(opacity=0) arrow.set_stroke(opacity=0) self.play( rect.animate.surround(questions[1]).set_stroke(opacity=1), arrow.animate.next_to(questions[1], RIGHT).set_stroke(opacity=1), ) self.wait() marks[1].set_fill(opacity=0) marks[1].set_stroke(GREEN, 2) self.play( FadeOut(rect), Write(marks[1]), ) self.wait() # Question 2 self.play( arrow.animate.next_to(questions[2], RIGHT) ) self.wait() def get_questions(self): kw = dict(alignment="LEFT") question_texts = [ "What exactly is wiggling?", "Why does sugar make light twist?", "Why does the twisting rate\ndepend on frequency?", "Why do we see colors\nin diagonal stripes?", ] questions = VGroup(*( VGroup( Text(f"Question #{n}:", **kw).set_fill(GREY_A), Text(text, **kw), ).arrange(DOWN, buff=0.25, aligned_edge=LEFT) for n, text in enumerate(question_texts) )) questions.arrange(DOWN, buff=1.0, aligned_edge=LEFT) questions.set_height(6) questions.to_corner(DL) return questions class TwoLines(InteractiveScene): def construct(self): h_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) v_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) lines = VGroup(h_line, v_line) lines.set_stroke(WHITE, 3) self.add(lines) class CyclingQuestions(Questions): def construct(self): # Test questions = self.get_questions()[1:] for question in questions: question.scale(1.1) question.to_corner(UL, buff=0.5) self.add(questions[0]) self.wait() for q1, q2 in zip(questions, questions[1:]): self.play(FadeOut(q1, UP), FadeIn(q2, UP)) self.wait() class FromOnHigh(InteractiveScene): def construct(self): rects = ScreenRectangle().replicate(3) rects.set_height(0.3 * FRAME_HEIGHT) rects.arrange(RIGHT) # self.add(rects) top_words = Text("Authoritative explainer") top_words.to_edge(UP) low_words = Text("Fundamental understanding") low_words.to_edge(DOWN) cross = Cross(top_words) top_arrows = VGroup(*(Arrow(top_words.get_bottom(), rect.get_top()) for rect in rects)) low_arrows = VGroup(*(Arrow(low_words.get_top(), rect.get_bottom()) for rect in rects)) # Test self.add(top_words) self.play(LaggedStartMap(GrowArrow, top_arrows)) self.play(ShowCreation(cross)) self.wait() self.play( Transform(top_arrows, low_arrows), FadeTransform(VGroup(top_words, cross), low_words), ) self.wait() class ThreeParts(InteractiveScene): def construct(self): # Setup self.add(FullScreenRectangle()) parts = ScreenRectangle().replicate(3) parts.set_height(0.3 * FRAME_HEIGHT) parts.arrange(RIGHT) parts.arrange_to_fit_width(FRAME_WIDTH - 0.5) parts.set_fill(BLACK, 1) parts.set_stroke(width=0) self.add(parts) self.clear() rect = SurroundingRectangle(parts[0], buff=0) rect.set_stroke(WHITE, 4) self.add(rect) # Test self.wait() for part in parts[1:]: self.play(rect.animate.surround(part, buff=0)) self.wait() class UnitRVector(InteractiveScene): def construct(self): text = TexText(R"Unit vector in \\ the direction of $\vec{r}$") text.set_fill(YELLOW) text.set_backstroke(BLACK, 10) self.add(text) class RSquaredVsR(InteractiveScene): def construct(self): # Axes axes = Axes((0, 10), (0, 1, 0.25), height=5, width=12) axes.x_axis.add_numbers() axes.y_axis.add_numbers(num_decimal_places=2) self.add(axes) # Add graphs graph1 = axes.get_graph(lambda x: 1 / x**2, x_range=(0.1, 10)).set_stroke(YELLOW, 5) graph2 = axes.get_graph(lambda x: 1 / x, x_range=(0.1, 10)).set_stroke(BLUE, 5) graphs = VGroup(graph1, graph2) labels = VGroup( Tex(R"f(r) = \frac{1}{r^2}").set_color(YELLOW), Tex(R"f(r) = \frac{1}{r}").set_color(BLUE), ) labels.arrange(DOWN, buff=1.0, aligned_edge=LEFT) labels.move_to(axes, UR) for graph, label in zip(graphs, labels): self.play( ShowCreation(graph, run_time=3), FadeIn(label, 0.5 * UP), ) self.wait(3) class SimpleRect(InteractiveScene): def construct(self): rad = Text("rad") rect = SurroundingRectangle(rad) rect.set_stroke(YELLOW, 3) arrow = Vector(UP) arrow.set_stroke(YELLOW) arrow.next_to(rect, DOWN) self.play(ShowCreation(arrow), ShowCreation(rect)) self.wait() class ThisIsLight(InteractiveScene): def construct(self): morty = Mortimer(height=1.5) morty.to_corner(DR) self.play(morty.says("This is light!", mode="surprised")) self.play(Blink(morty)) self.wait() class MentionMaxwell(TeacherStudentsScene): def construct(self): # Introduce stds = self.students morty = self.teacher kw = dict( tex_to_color_map={ R"\mathbf{E}": BLUE, R"\mathbf{B}": YELLOW, }, font_size=30, ) maxwells_equations = VGroup( Tex(R"\nabla \cdot \mathbf{E}=\frac{\rho}{\varepsilon_0}", **kw), Tex(R"\nabla \cdot \mathbf{B}=0", **kw), Tex(R"\nabla \times \mathbf{E}=-\frac{\partial \mathbf{B}}{\partial t}", **kw), Tex(R"\nabla \times \mathbf{B}=\mu_0\left(\mathbf{J}+\varepsilon_0 \frac{\partial \mathbf{E}}{\partial t}\right)", **kw), ) maxwells_equations.arrange(DOWN, aligned_edge=LEFT) equations_rect = SurroundingRectangle(maxwells_equations, buff=0.25) equations_rect.set_stroke(WHITE, 1) equations_rect.set_fill(BLACK, 1) maxwells_equations.add_to_back(equations_rect) maxwells_equations.next_to(stds[2].get_corner(UR), UP) maxwells_equations.shift(MED_SMALL_BUFF * UP) equations_title = Text("Maxwell's Equations") equations_title.next_to(maxwells_equations, UP, buff=0.25) self.play( stds[2].says(TexText(R"What about \\ Maxwell's equations?")), morty.change("tease"), self.change_students("confused", "pondering") ) self.play( stds[2].change("raise_right_hand"), FadeIn(maxwells_equations, UP), ) self.play( FadeTransform(stds[2].bubble.content["Maxwell's equations"].copy(), equations_title), stds[2].debubble(), *(pi.animate.look_at(equations_title) for pi in [morty, *stds[:2]]), ) self.wait() self.play(self.change_students("maybe", "erm", look_at=maxwells_equations)) self.wait(4) maxwells_equations.add(equations_title) # Lorentz law maxwells_equations.generate_target() maxwells_equations.target.scale(0.7).to_edge(LEFT) equation = Tex(R""" \vec{E}_{\text{rad}}(\vec{r}, t) = {-q \over 4\pi \epsilon_0 c^2} {1 \over ||\vec{r}||} \vec{a}_\perp(t - ||\vec{r}|| / c) """, font_size=42) lhs = equation[R"\vec{E}_{\text{rad}}(\vec{r}, t)"] lhs.set_color(BLUE) equation[R"\vec{a}_\perp("].set_color(PINK) equation[R")"][1].set_color(PINK) equation.next_to(morty.get_corner(UL), UP) equation.shift_onto_screen() equation.match_y(maxwells_equations) eq_rect = SurroundingRectangle(equation) eq_rect.set_stroke(BLUE, 2) eq_rect.set_fill(BLUE, 0.1) implies_arrow = Arrow(eq_rect, maxwells_equations.target) implies_word = Text("Derived from these", font_size=30) implies_word.next_to(implies_arrow, UP) question = Text("How far will this take us?") question.next_to(equation, UP, buff=2.0) question.shift_onto_screen() arrow = Arrow(equation, question) self.play( morty.change("raise_right_hand"), FadeIn(equation, 0.5 * UP), MoveToTarget(maxwells_equations), GrowArrow(implies_arrow), FadeIn(implies_word, lag_ratio=0.1), self.change_students("well", "happy") ) self.wait() self.add(eq_rect, equation) self.play( FadeIn(eq_rect), ShowCreation(arrow), FadeIn(question, lag_ratio=0.1), morty.change("tease", look_at=question), self.change_students("tease", "well", "happy", look_at=equation) ) self.wait(4) # Remove self.remove(equation) everything = Group(*self.mobjects) self.play( LaggedStartMap(FadeOut, everything), equation.copy().animate.scale(36.0 / 42).to_corner(UR), run_time=1, ) self.wait() class BasicallyZ(InteractiveScene): def construct(self): rect = Rectangle(6.0, 2.0) rect.set_stroke(YELLOW, 2) rect.set_fill(YELLOW, 0.2) rect.to_edge(RIGHT, buff=0.25) words = Text("Essentially parallel\nto the z-axis") words.next_to(rect, UP) self.play( FadeIn(words, 0.25 * UP), FadeIn(rect) ) self.wait() class StrengthInDifferentDirectionsWithDecimal(InteractiveScene): def construct(self): line = Line(ORIGIN, 7 * RIGHT) line.set_stroke(TEAL, 4) arc = always_redraw(lambda: Arc(angle=line.get_angle(), radius=0.5)) angle_label = Integer(0, unit=R"^\circ") angle_label.add_updater(lambda m: m.set_value(line.get_angle() / DEGREES)) angle_label.add_updater(lambda m: m.set_height(clip(arc.get_height(), 0.01, 0.4))) angle_label.add_updater(lambda m: m.next_to(arc.pfp(0.3), normalize(arc.pfp(0.3)), SMALL_BUFF, aligned_edge=DOWN)) strong_words = Text("Strongest in this direction") strong_words.next_to(line, UP) cos_temp_text = "cos(00*)=0.00" weak_words = Text(f"Weaker by a factor of {cos_temp_text}", font_size=36) cos_template = weak_words[cos_temp_text][0] cos_template.set_opacity(0) weak_words.next_to(line, UP) strong_words.set_backstroke(BLACK, 10) weak_words.set_backstroke(BLACK, 10) def get_cos_tex(): cos_tex = Tex(R"\cos(10^\circ) = 0.00", font_size=36) cos_tex.make_number_changable("10", edge_to_fix=RIGHT).set_value(line.get_angle() / DEGREES) cos_tex.make_number_changable("0.00").set_value(math.cos(line.get_angle())) cos_tex.rotate(line.get_angle()) cos_tex.move_to(weak_words[-len(cos_temp_text) + 1:]) cos_tex.set_backstroke(BLACK, 10) return cos_tex cos_tex = always_redraw(get_cos_tex) # Test self.play(ShowCreation(line), Write(strong_words, run_time=1)) self.wait(2) self.add(arc, angle_label, weak_words, cos_tex) self.remove(strong_words) rot_group = VGroup(line, weak_words) self.play( Rotate(rot_group, 30 * DEGREES, about_point=ORIGIN), run_time=3 ) self.wait(2) self.play( self.frame.animate.set_height(12), Rotate(rot_group, 30 * DEGREES, about_point=ORIGIN), run_time=3 ) self.wait(2) self.play( self.frame.animate.set_height(15), Rotate(rot_group, 30 * DEGREES, about_point=ORIGIN), run_time=3 ) self.wait(2) class ERadEquation(InteractiveScene): def construct(self): equation = Tex(R""" \vec{E}_{\text{rad}}(\vec{r}, t) = {-q \over 4\pi \epsilon_0 c^2} {1 \over ||\vec{r}||} \vec{a}_\perp(t - ||\vec{r}|| / c) """, font_size=36) lhs = equation[R"\vec{E}_{\text{rad}}(\vec{r}, t)"] lhs.set_color(BLUE) equation[R"\vec{a}_\perp("].set_color(PINK) equation[R")"][1].set_color(PINK) self.add(equation) class XZLabel(InteractiveScene): def construct(self): xz_label = Tex("xz") x, z = xz_label x.next_to(ORIGIN, UP, SMALL_BUFF).to_edge(RIGHT, buff=0.2) z.next_to(ORIGIN, RIGHT, SMALL_BUFF).to_edge(UP, buff=0.2) self.add(xz_label) class TransitionBeforePolarization(TeacherStudentsScene): def construct(self): self.play( self.change_students("pondering", "thinking", "happy", look_at=self.screen), ) self.wait(3) self.play( self.teacher.change("raise_left_hand", look_at=3 * UR), self.change_students("well", "tease", "happy", look_at=3 * UR), ) self.wait(4) class AskAboutQuantum(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students # Question self.play( stds[0].says("What about, like,\nphotons and quantum stuff?"), morty.change("well"), self.change_students(None, "sassy", "hesitant", look_at=stds[0].eyes), ) self.wait(3) # Create T chart titles = VGroup( Text("Classical"), Text("Quantum"), ) v_lines = Line(UP, DOWN).replicate(2).set_height(4.5) v_lines.arrange(RIGHT, buff=titles[0].get_width() + 0.75) v_lines.to_edge(UP, buff=0) v_lines.shift(1.5 * RIGHT) h_line = Line(LEFT, RIGHT) h_line.set_width(13.25) h_line.to_edge(UP, buff=titles.get_height() + 0.5) h_line.set_x(0) lines = VGroup(h_line, *v_lines) lines.set_stroke(WHITE, 2) titles[0].move_to(v_lines).to_edge(UP, buff=0.25) titles[1].next_to(v_lines, RIGHT, buff=0.5).match_y(titles[0]) # Points points = VGroup( Text("Waves radiate away from changing charges"), Text("These waves have polarization"), Text("Energy scales continuously"), ) points.scale(0.7) points.arrange(DOWN, buff=0.5, aligned_edge=LEFT) points.next_to(h_line, DOWN, buff=0.5, aligned_edge=LEFT) soft_h_lines = h_line.replicate(len(points)) soft_h_lines.set_stroke(WHITE, 1, opacity=0.5) for point, soft_line in zip(points, soft_h_lines): soft_line.next_to(point, DOWN, buff=0.25) soft_line.align_to(h_line, LEFT) checks = VGroup(*( Checkmark().match_x(title).match_y(point) for point in points for title in titles )) cross = Exmark().move_to(checks[-1]) last_q_point = Text( """ Energy comes in discrete chunks (that is, in quanta) """, alignment="LEFT" ) last_q_point.scale(0.7) last_q_point.next_to(cross, DOWN, buff=0.5) last_q_point.align_to(titles[1], LEFT) last_q_point.set_color(YELLOW) # Animate in the charge self.play( morty.change("raise_right_hand"), FadeTransform(stds[0].bubble.content["quantum"].copy(), titles[1]), FadeIn(titles[0], shift=0.25 * UP), ShowCreation(h_line), ShowCreation(v_lines), Write(soft_h_lines), stds[0].debubble(mode="pondering"), self.change_students(None, "pondering", "pondering", look_at=UP), run_time=2, ) self.wait() # Points self.play( FadeIn(points[0], lag_ratio=0.1), Write(checks[:2], lag_ratio=0.7, stroke_color=GREEN), *(pi.animate.look_at(titles) for pi in self.pi_creatures) ) self.wait() self.play( FadeIn(points[1], lag_ratio=0.1), Write(checks[2:4], lag_ratio=0.7, stroke_color=GREEN) ) self.wait() self.play( FadeIn(points[2], lag_ratio=0.1), Write(checks[4], stroke_color=GREEN), FadeIn(cross, scale=0.5), morty.change("sassy", look_at=cross) ) self.wait() self.play( FadeOut(self.pi_creatures, DOWN), FadeOut(soft_h_lines[-1]), # FadeIn(last_q_point, lag_ratio=0.1), v_lines.animate.set_height(7, about_edge=UP, stretch=True), ) self.wait() class ContinuousWave(InteractiveScene): def construct(self): wave = self.get_wave() points = wave.get_points().copy() wave.add_updater(lambda m: m.set_points(points).stretch( (1 - math.sin(self.time)), 1, )) self.add(wave) self.wait(20) def get_wave(self): axes = Axes((0, 2 * TAU), (0, 1)) wave = axes.get_graph(np.sin) wave.set_stroke(BLUE, 4) wave.set_width(2.0) return wave class DiscreteWave(ContinuousWave): def construct(self): # Test waves = self.get_wave().replicate(3) waves.scale(2) waves.arrange(DOWN, buff=1.0) labels = VGroup() for n, wave in zip(it.count(1), waves): wave.stretch(0.5 * n, 1) label = TexText(f"{n} $hf$" + ("" if n > 1 else "")) label.scale(0.5) label.next_to(wave, UP, buff=0.2) labels.add(label) self.play( FadeIn(wave), FadeIn(label), ) dots = Tex(R"\vdots", font_size=60) dots.next_to(waves, DOWN) self.play(Write(dots)) self.wait() class ContinuousGraph(InteractiveScene): def construct(self): axes = Axes((0, 5), (0, 5), width=4, height=4) graph = axes.get_graph(lambda x: (x**2) / 5) graph.set_stroke(YELLOW, 3) self.add(axes) self.play(ShowCreation(graph)) self.wait() class DiscreteGraph(InteractiveScene): def construct(self): # Test axes = Axes((0, 5), (0, 5), width=4, height=4) graph = axes.get_graph( lambda x: np.floor(x) + 0.5, discontinuities=np.arange(0, 8), x_range=(0, 4.99), ) graph.set_stroke(RED, 5) self.add(axes) self.play(ShowCreation(graph)) self.wait() class LightQuantumWrapper(VideoWrapper): title = "Some light quantum mechanics" class RedFilter(InteractiveScene): def construct(self): image = ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/barber_pole/images/RedFilter.jpg") image.set_height(FRAME_HEIGHT) # self.add(image) plane = NumberPlane() plane.fade(0.75) # Pixel indicator indicator = self.get_pixel_indicator(image) indicator.move_to(plane.c2p(5.25, -0.25), DOWN) self.add(indicator) # Move around self.wait() self.play( indicator.animate.move_to(plane.c2p(1.5, -0.125), DOWN), run_time=6, ) self.wait() self.play( indicator.animate.move_to(plane.c2p(-3.5, 0), DOWN), run_time=6, ) self.wait() def get_pixel_indicator(self, image, vect_len=2.0, direction=DOWN, square_size=1.0): vect = Vector(vect_len * direction, stroke_color=WHITE) square = Square(side_length=square_size) square.set_stroke(WHITE, 1) square.next_to(vect, -direction) def get_color(): points = vect.get_end() + 0.05 * compass_directions(12) rgbs = np.array([image.point_to_rgb(point) for point in points]) return rgb_to_color(rgbs.mean(0)) square.add_updater(lambda s: s.set_fill(get_color(), 1)) return VGroup(square, vect) class LengthsOnDifferentColors(InteractiveScene): def construct(self): # Setup image = ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/barber_pole/images/RainbowTubes.jpg") image.set_height(FRAME_HEIGHT) # self.add(image) plane = NumberPlane() plane.fade(0.75) # self.add(plane) # Rectangles rects = Rectangle().replicate(4) rects.set_stroke(width=0) rects.set_fill(BLACK, opacity=0) rects.set_height(2) rects.set_width(FRAME_WIDTH, stretch=True) rects.arrange(DOWN, buff=0) # Braces lines = VGroup( Line(plane.c2p(3.2, 2.8), plane.c2p(-0.5, 2.8)), Line(plane.c2p(3.2, 0.9), plane.c2p(0.6, 0.9)), Line(plane.c2p(3.2, -1.0), plane.c2p(1.0, -1.0)), Line(plane.c2p(3.2, -3.0), plane.c2p(1.3, -3.0)), ) braces = VGroup(*( Brace(line, DOWN, buff=SMALL_BUFF) for line in lines )) braces.set_backstroke(BLACK, 3) numbers = VGroup(*( DecimalNumber(line.get_length() / 7, font_size=36, unit=R" \text{m}") for line in lines )) for number, brace in zip(numbers, braces): number.next_to(brace, DOWN, buff=SMALL_BUFF) # Show braces for brace, rect, number in zip(braces, rects, numbers): globals().update(locals()) other_rects = VGroup(*(r for r in rects if r is not rect)) self.play( GrowFromPoint(brace, brace.get_right()), CountInFrom(number, 0), UpdateFromFunc(VGroup(), lambda m: number.next_to(brace, DOWN, SMALL_BUFF)), rect.animate.set_opacity(0), other_rects.animate.set_opacity(0.8), ) self.wait(2) self.play(FadeOut(rects)) # Ribbons axes_3d = ThreeDAxes((0, 6)) ribbons = Group() twist_rates = [1.0 / PI / line.get_length() for line in lines] twist_rates = [0.09, 0.11, 0.115, 0.12] for line, twist_rate in zip(lines, twist_rates): ribbon = TwistedRibbon( axes_3d, amplitude=0.25, twist_rate=twist_rate, color=rgb_to_color(image.point_to_rgb(line.get_start())), ) ribbon.rotate(PI / 2, RIGHT) ribbon.set_opacity(0.75) ribbon.flip(UP) ribbon.next_to(line, UP, MED_LARGE_BUFF, aligned_edge=RIGHT) ribbons.add(ribbon) for ribbon in ribbons: self.play(ShowCreation(ribbon, run_time=2)) self.wait() class AskAboutDiagonal(InteractiveScene): def construct(self): randy = Randolph(height=2) self.play(randy.says("Why diagonal?", mode="maybe", look_at=DOWN)) self.play(Blink(randy)) self.wait() class AskNoteVerticalVariation(RedFilter): def construct(self): image = ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/barber_pole/images/GreenFilter.jpg") image.set_height(FRAME_HEIGHT) # self.add(image) plane = NumberPlane() plane.fade(0.75) # self.add(plane) indicator = self.get_pixel_indicator(image) # Scan horizontally, then vertically indicator.move_to(plane.c2p(-0.5, -0.5), DOWN) lr_arrows = VGroup(Vector(LEFT), Vector(RIGHT)) lr_arrows.arrange(RIGHT, buff=1.0) lr_arrows.move_to(plane.c2p(0.5, -1.5)) ud_arrows = VGroup(Vector(UP), Vector(DOWN)) ud_arrows.arrange(DOWN, buff=1.0) ud_arrows.move_to(plane.c2p(0, -0.6)) self.add(indicator) self.play( FadeIn(lr_arrows, time_span=(0, 1)), indicator.animate.move_to(plane.c2p(3, -0.5), DOWN), run_time=3 ) self.play(indicator.animate.move_to(plane.c2p(1.5, -0.5), DOWN), run_time=3) self.wait() self.play( FadeIn(ud_arrows, time_span=(0, 1)), FadeOut(lr_arrows, time_span=(0, 1)), indicator.animate.move_to(plane.c2p(1.5, -0.2), DOWN), run_time=3 ) self.play(indicator.animate.move_to(plane.c2p(1.5, -0.9), DOWN), run_time=3) self.play(indicator.animate.move_to(plane.c2p(1.5, -0.5), DOWN), run_time=3) self.wait() class CombineColors(InteractiveScene): def construct(self): # Get images folder = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/barber_pole/images/" images = Group(*( ImageMobject(os.path.join(folder, ext + "Still.jpg")) for ext in ["Red", "Orange", "Green", "Blue", "Rainbow"] )) colors = images[:4] rainbow = images[4] colors.set_height(FRAME_HEIGHT / 2) colors.arrange_in_grid(buff=0) rainbow.set_height(FRAME_HEIGHT) self.add(*colors) class SteveMouldMention(InteractiveScene): def construct(self): morty = Mortimer(height=2) morty.to_edge(DOWN) self.play( morty.says(""" This is the part that Steve Mould explains quite well, by the way """, mode="tease") ) self.play(Blink(morty)) self.wait() class IndexOfRefraction(InteractiveScene): def construct(self): # Test equation = Tex(R"{\text{Speed in a vacuum} \over \text{Speed in water}} \approx 1.33") equation.shift(UP) rhs = equation[R"\approx 1.33"] equation.scale(0.75) rhs.scale(1 / 0.75, about_edge=LEFT) arrow = Vector(DOWN) arrow.next_to(rhs, DOWN, SMALL_BUFF) words = TexText("``Index of refraction''") words.next_to(arrow, DOWN, SMALL_BUFF) words.set_color(BLUE) self.play(FadeIn(equation, 0.5 * UP)) self.wait() self.play( GrowArrow(arrow), Write(words) ) self.wait() class LayerKickBackLabel(InteractiveScene): def construct(self): layer_label = Text("Each layer kicks back the phase") layer_label.to_edge(UP) self.play(Write(layer_label)) self.wait() class SugarIsChiral(InteractiveScene): default_frame_orientation = (-33, 85) title = R"Sucrose $\text{C}_{12}\text{H}_{22}\text{O}_{11}$ " subtitle = "(D-Glucose + D-Fructose)" molecule_height = 3 def construct(self): axes = ThreeDAxes() axes.set_stroke(opacity=0.5) # self.add(axes) # Set up frame = self.frame title = VGroup( TexText(self.title), TexText(self.subtitle), ) title[1].scale(0.7).set_color(GREY_A) title.arrange(DOWN) title.fix_in_frame() title.to_edge(UP, buff=0.25) sucrose = Sucrose() sucrose.set_height(self.molecule_height) # Introduce frame.reorient(24, 74, 0) self.add(title) self.play( FadeIn(sucrose, scale=5), ) self.play( self.frame.animate.reorient(-16, 75, 0).set_anim_args(run_time=6) ) self.add(sucrose) self.wait() # Show mirror image mirror = Square(side_length=6) mirror.set_fill(BLUE, 0.35) mirror.set_stroke(width=0) mirror.rotate(PI / 2, UP) mirror.set_shading(0, 1, 0) mirror.stretch(3, 1) sucrose.target = sucrose.generate_target() sucrose.target.next_to(mirror, LEFT, buff=1.0) self.add(mirror, sucrose) self.play( frame.animate.move_to(0.75 * OUT), MoveToTarget(sucrose), FadeIn(mirror), title.animate.scale(0.75).match_x(sucrose.target).set_y(1.75), run_time=1.5, ) mirror_image = sucrose.copy() mirror_image.target = mirror_image.generate_target() mirror_image.target.stretch(-1, 0, about_point=mirror.get_center()) mirror_words = Text("(mirror image)", font_size=36, color=GREY_A) mirror_words.fix_in_frame() mirror_words.match_x(mirror_image.target) mirror_words.match_y(title) self.add(mirror_image, mirror, sucrose) self.play( MoveToTarget(mirror_image), FadeIn(mirror_words), ) # Chiral definition definition = TexText(R"Chiral $\rightarrow$ Cannot be superimposed onto its mirror image") definition.fix_in_frame() definition.to_edge(UP) sucrose.add_updater(lambda m, dt: m.rotate(10 * DEGREES * dt, axis=OUT)) mirror_image.add_updater(lambda m, dt: m.rotate(-10 * DEGREES * dt, axis=OUT)) self.play(Write(definition)) self.play( self.frame.animate.reorient(-8, 76, 0), run_time=15, ) self.wait(15) class SimplerChiralShape(InteractiveScene): default_frame_orientation = (0, 70) def construct(self): # Ribbon frame = self.frame frame.set_field_of_view(1 * DEGREES) axes = ThreeDAxes((-3, 3)) ribbon = TwistedRibbon(axes, amplitude=1, twist_rate=-0.35) ribbon.rotate(PI / 2, DOWN) ribbon.set_color(RED) ribbon.set_opacity(0.9) ribbon.set_shading(0.5, 0.5, 0.5) always(ribbon.sort_faces_back_to_front, UP) ribbon.set_x(-4) mirror_image = ribbon.copy() mirror_image.stretch(-1, 0) mirror_image.set_x(-ribbon.get_x()) mirror_image.set_color(YELLOW_C) mirror_image.set_opacity(0.9) # Title spiral_name = Text("Spiral") mirror_name = Text("Mirror image") for name, mob in [(spiral_name, ribbon), (mirror_name, mirror_image)]: name.fix_in_frame() name.to_edge(UP) name.match_x(mob) self.play( FadeIn(spiral_name, 0.5 * UP), ShowCreation(ribbon, run_time=3), ) self.wait() self.play( ReplacementTransform(ribbon.copy().shift(0.1 * DOWN), mirror_image), FadeTransformPieces(spiral_name.copy(), mirror_name), ) self.wait() # Reorient r_copy = ribbon.copy() self.play(r_copy.animate.next_to(mirror_image, LEFT)) self.play(Rotate(r_copy, PI, RIGHT, run_time=2)) self.play(Rotate(r_copy, PI, OUT, run_time=2)) self.play(Rotate(r_copy, PI, UP, run_time=2)) self.wait() class SucroseAction(InteractiveScene): just_sucrose = False def construct(self): # Sucrose sucrose = Sucrose(height=1.5) sucrose.balls.scale_radii(0.5) sucrose.rotate(PI / 2, RIGHT) sucrose.to_edge(LEFT) sucrose.add_updater(lambda m, dt: m.rotate(10 * DEGREES * dt, UP)) if self.just_sucrose: self.add(sucrose) self.wait(36) return # Arrows arrows = VGroup() words = VGroup( Text("The amount that sugar\nslows this light..."), Text("...is different from how\nit slows this light"), ) words.scale(0.75) for sign, word in zip([+1, -1], words): arrow = Line(ORIGIN, 5 * RIGHT + 1.5 * sign * UP, path_arc=-sign * 60 * DEGREES) arrow.insert_n_curves(100) arrow.add_tip(length=0.2, width=0.2) arrow.shift(sucrose.get_right() + 0.5 * LEFT + sign * 1.25 * UP) arrows.add(arrow) word.next_to(arrow, sign * UP, buff=0.1) self.play( ShowCreation(arrow), FadeIn(word, 0.25 * sign * UP) ) self.wait(2) class SucroseActionSucrosePart(SucroseAction): just_sucrose = True class ThatSeemsIrrelevant(TeacherStudentsScene): def construct(self): stds = self.students morty = self.teacher self.play( stds[0].says("That seems irrelevant", mode="sassy"), self.change_students(None, "erm", "hesitant", look_at=stds[0].eyes), morty.change("guilty"), ) self.wait(2) self.play( stds[0].debubble(mode="raise_left_hand", look_at=self.screen), self.change_students(None, "pondering", "pondering", look_at=self.screen), ) self.wait(5) class BigPlus(InteractiveScene): def construct(self): brace = Brace(Line(2 * DOWN, 2 * UP), RIGHT) brace.set_height(7) brace.move_to(2 * LEFT) plus = Tex("+", font_size=90) plus.next_to(brace, LEFT, buff=2.5) equals = Tex("=", font_size=90) equals.next_to(brace, RIGHT, buff=1.0) self.add(plus, brace, equals) class CurvyCurvyArrow(InteractiveScene): def construct(self): # Test kw = dict(path_arc=-PI, buff=0.2, stroke_width=30, tip_width_ratio=4) arrows = VGroup( Arrow(DOWN, UP, **kw), Arrow(UP, DOWN, **kw), ) arrows.set_color(WHITE) arrows.set_height(5) self.frame.reorient(-9, 75, 90) self.frame.set_field_of_view(1 * DEGREES) self.add(arrows) class GlowDot(InteractiveScene): def construct(self): self.add(GlowDot(radius=3, color=WHITE)) mid_point = 0.85 * LEFT mask = VMobject().set_points_as_corners([ UR, mid_point, DR, DL, UL, ]) mask.set_fill(BLACK, 1) mask.set_stroke(width=0) mask.set_height(20, about_point=mid_point) self.add(mask) class Randy(InteractiveScene): def construct(self): self.add(Randolph(mode="confused")) class EndScreen(PatreonEndScreen): scroll_time = 25 show_pis = False title_text = ""
from _2023.barber_pole.objects import TimeVaryingVectorField from _2023.barber_pole.objects import Calcite from _2023.barber_pole.objects import Sucrose from manim_imports_ext import * class HarmonicOscillator(TrueDot): def __init__( self, center=np.zeros(3), initial_velocity=np.zeros(3), k=20.0, damping=0.1, mass=1.0, radius=0.5, color=BLUE, three_d=True, **kwargs ): self.k = k self.mass = mass self.damping = damping self.velocity = initial_velocity self.center_of_attraction = center self.external_forces = [] super().__init__( radius=radius, color=color, **kwargs ) if three_d: self.make_3d() self.move_to(center) self.add_updater(lambda m, dt: self.update_position(dt)) def update_position(self, dt): time_step = 1 / 300 n_divisions = max(int(dt / time_step), 1) true_step = dt / n_divisions for _ in range(n_divisions): self.velocity += self.get_acceleration() * true_step self.shift(self.velocity * true_step) def get_displacement(self): return self.get_center() - self.center_of_attraction def get_acceleration(self): disp = self.get_displacement() result = -self.k * disp / self.mass - self.damping * self.velocity for force in self.external_forces: result += force() / self.mass return result def reset_velocity(self): self.velocity = 0 def set_damping(self, damping): self.damping = damping def set_k(self, k): self.k = k return self def suspend_updating(self): super().suspend_updating() self.reset_velocity() def set_external_forces(self, funcs): self.external_forces = list(funcs) return self def add_external_force(self, func): self.external_forces.append(func) return self class Spring(VMobject): def __init__( self, mobject, base_point, edge=ORIGIN, stroke_color=GREY, stroke_width=2, twist_rate=8.0, n_twists=8, radius=0.1, lead_length=0.25, **kwargs ): super().__init__(**kwargs) helix = ParametricCurve( lambda t: [ radius * math.cos(TAU * t), radius * math.sin(TAU * t), t / twist_rate ], t_range=(0, n_twists, 0.01) ) helix.rotate(PI / 2, UP) # helix.make_jagged() self.start_new_path(helix.get_start() + lead_length * LEFT) self.add_line_to(helix.get_start()) self.append_vectorized_mobject(helix) self.add_line_to(helix.get_end() + lead_length * RIGHT) self.set_stroke(color=stroke_color, width=stroke_width) self.set_flat_stroke(False) reference_points = self.get_points().copy() width = self.get_width() self.add_updater(lambda m: m.set_points(reference_points)) self.add_updater(lambda m: m.stretch( get_norm(base_point - mobject.get_edge_center(edge)) / width, 0 )) self.add_updater(lambda m: m.put_start_and_end_on( base_point, mobject.get_edge_center(edge) )) def get_length(self): return get_norm(self.get_end() - self.get_start()) class DynamicPlot(VMobject): def __init__( self, axes, func, stroke_color=RED, stroke_width=3, ): self.axes = axes self.func = func self.time = 0 super().__init__( stroke_color=stroke_color, stroke_width=stroke_width, ) self.reset() self.add_updater(lambda m, dt: m.add_point(dt)) def add_point(self, dt): self.time += dt if self.time < self.axes.x_axis.x_max: self.add_line_to(self.axes.c2p(self.time, self.func())) return self def reset(self): self.clear_points() self.time = 0 self.start_new_path(self.axes.c2p(0, self.func())) return self class DrivenHarmonicOscillator(InteractiveScene): def construct(self): # Zoom in on a plane of charges frame = self.frame frame.reorient(-90, 80, 90) zoom_out_radius = 0.035 radius = 0.2 charges = DotCloud(color=BLUE_D, radius=zoom_out_radius) charges.to_grid(31, 31) charges.set_height(3) charges.set_radius(zoom_out_radius) charges.make_3d() self.add(charges) in_shift = 0.01 * IN charges_target_height = 59 self.play( frame.animate.reorient(-90, 0, 90).center().set_focal_distance(100).set_anim_args(time_span=(0, 4)), charges.animate.center().set_height(charges_target_height).set_radius(radius).shift(in_shift), run_time=6, ) frame.reorient(0, 0, 0) # Add springs sho = HarmonicOscillator( center=charges.get_center() - in_shift, radius=radius, color=charges.get_color(), ) cover = BackgroundRectangle(sho, buff=0.1) cover.set_fill(BLACK, 1) spacing = get_norm(charges.get_points()[1] - charges.get_points()[0]) globals().update(locals()) small_radius = 0.35 * radius springs = VGroup(*( Spring(sho, sho.get_center() + (spacing - small_radius) * vect) for vect in compass_directions(4) )) sho.add_updater(lambda m: springs.update()) self.add(cover, springs, sho) self.play( charges.animate.set_opacity(0.5).set_radius(small_radius), FadeIn(springs), ) self.wait() # Show example oscillating self.play(sho.animate.shift(0.5 * UL)) sho.suspend_updating() self.wait() sho.resume_updating() sho.set_damping(0.25) self.wait(8) sho.move_to(sho.center_of_attraction) sho.reset_velocity() # Add coordiante plane axes = Axes(axis_config=dict(tick_size=0.05)) axes.set_stroke(width=1, opacity=1) axes.set_flat_stroke(False) axes.scale(spacing) self.add(axes, springs, sho) self.play(FadeIn(axes)) sho.suspend_updating() self.play(sho.animate.move_to(0.75 * UP + 0.5 * LEFT)) # Set up Hooke's law t2c = { R"\vec{\textbf{x}}(t)": RED, R"\vec{\textbf{v}}(t)": PINK, R"\vec{\textbf{F}}(t)": YELLOW, R"\vec{\textbf{a}}(t)": YELLOW, R"\frac{d^2 \vec{\textbf{x}}}{dt^2}(t) ": YELLOW, R"\omega_r": PINK, R"\omega_l": TEAL, } x_vect = always_redraw(lambda: Arrow( axes.c2p(0, 0), sho.get_center(), stroke_width=5, stroke_color=RED, buff=0 )) equation = Tex(R"\vec{\textbf{F}}(t) = -k \vec{\textbf{x}}(t)", t2c=t2c) equation.move_to(axes.c2p(0.5, 0.5), LEFT) x_label = equation[R"\vec{\textbf{x}}(t)"] x_label.set_backstroke(BLACK, 5) x_label.save_state() x_label.next_to(x_vect, RIGHT, 0.05, DOWN) self.play( GrowArrow(x_vect), springs.animate.set_stroke(opacity=0.35) ) self.play(Write(x_label)) self.wait() self.play(sho.animate.move_to(DR), rate_func=there_and_back, run_time=3) self.wait() self.play( Write(equation[R"\vec{\textbf{F}}(t) = -k "]), Restore(x_label), ) self.add(equation) # Show force vector sho.set_damping(0.005) F_vect = Vector(stroke_color=YELLOW) def update_F_vect(F_vect, vect_scale=0.04): center = sho.get_center() acc = sho.get_acceleration() F_vect.put_start_and_end_on(center, center + vect_scale * acc) F_vect.add_updater(update_F_vect) initial_position = 0.75 * UL self.play( FlashAround(equation[R"\vec{\textbf{F}}"]), ReplacementTransform(x_vect, F_vect, path_arc=PI), ) self.wait() self.play(sho.animate.move_to(0.25 * UL)) self.wait() self.play(sho.animate.move_to(initial_position)) self.wait() sho.resume_updating() self.wait(6) # Show graphical solution up_shift = 1.5 * UP plot_rect, plot_axes, plot = self.get_plot_group( lambda: np.sign(sho.get_center()[1]) * get_norm(sho.get_center()), ) plot_group1 = VGroup(plot_rect, plot_axes, plot) plot_group1.to_corner(UR, buff=0.1) plot_group1.shift(up_shift) sho.move_to(initial_position) sho.reset_velocity() plot.reset() self.add(*plot_group1) self.play( frame.animate.shift(up_shift), equation.animate.to_corner(UL).match_y(plot_rect), FadeIn(plot_rect), FadeIn(plot_axes), FadeOut(charges), run_time=2 ) self.wait(15) plot.suspend_updating() sho.suspend_updating() self.play(sho.animate.center(), run_time=2) # Show the equation for the solution tex_kw = dict(t2c=t2c) equations = VGroup(equation) equations.add( Tex(R"m \vec{\textbf{a}}(t) = -k \vec{\textbf{x}}(t)", **tex_kw), Tex(R"\frac{d^2 \vec{\textbf{x}}}{dt^2}(t) = -{k \over m} \vec{\textbf{x}}(t)", **tex_kw), Tex(R"\vec{\textbf{x}}(t) = \vec{\textbf{x}}_0 \cos( \sqrt{k \over m} \cdot t)", **tex_kw), Tex(R"\vec{\textbf{x}}(t) = \vec{\textbf{x}}_0 \cos(\omega_r t)", **tex_kw), ) eq1, eq2, eq3, eq4, eq5 = equations eq2.next_to(eq1, DOWN, LARGE_BUFF) eq3.next_to(eq2, DOWN, LARGE_BUFF, aligned_edge=LEFT) eq4.next_to(eq2, DOWN, buff=0.75, aligned_edge=LEFT) eq5.move_to(eq4, LEFT) implies = Tex(R"\Downarrow").replicate(2) implies[0].move_to(VGroup(eq1, eq2)) implies[1].move_to(VGroup(eq2, eq3)) implies[1].match_x(implies[0]) eq1_copy = eq1.copy() self.play( TransformMatchingTex( eq1_copy, eq2, matched_pairs=[ (eq1_copy[R"\vec{\textbf{F}}(t)"], eq2[R"\vec{\textbf{a}}(t)"]), (eq1_copy[R"= -k \vec{\textbf{x}}(t)"], eq2[R"= -k \vec{\textbf{x}}(t)"]), ], run_time=1 ), FadeIn(implies[0], 0.5 * DOWN) ) self.wait() eq2_copy = eq2.copy() self.play( TransformMatchingTex( eq2_copy, eq3, matched_pairs=[ (eq2_copy[R"\vec{\textbf{a}}(t)"], eq3[R"\frac{d^2 \vec{\textbf{x}}}{dt^2}(t)"]), (eq2_copy[R"k"], eq3["k"]), ], path_arc=PI / 4, ), FadeIn(implies[1]) ) self.wait() self.play( eq3.animate.move_to(eq2).align_to(eq1, LEFT), FadeOut(eq2), FadeOut(implies[1]), ) # Show solution for a given initial condition initial_position = 0.5 * UR x0 = eq4[R"\vec{\textbf{x}}_0"] cos_part = eq4[R"\cos( \sqrt{k \over m} \cdot t)"] x0_copy = x0.copy() x0_copy.next_to(0.5 * initial_position, UL, buff=0.05) x0_copy.set_color(RED) x0_copy.set_backstroke(BLACK, 4) ic_label = Text("Initial condition") ic_label.next_to(initial_position, UR, MED_LARGE_BUFF) x0_rect = SurroundingRectangle(x0, buff=0.05) x0_rect.set_stroke(TEAL, 2) self.remove(F_vect) self.add(x_vect) self.play( FadeIn(ic_label), sho.animate.move_to(initial_position) ) self.play(FadeIn(x0_copy, DOWN)) self.wait() self.play( TransformFromCopy(x0_copy, x0), Write(implies[1]), *( TransformFromCopy(eq3[tex], eq4[tex]) for tex in ["=", R"\vec{\textbf{x}}(t)"] ) ) self.play( FadeIn(cos_part, lag_ratio=0.1), ) self.play( FlashAround(cos_part, color=RED, run_time=3, time_width=1.5), ) self.wait() self.play( FadeTransform(ic_label, x0_rect) ) self.play( plot.animate.stretch(0.5, 1), sho.animate.move_to(0.5 * initial_position), x0_copy.animate.next_to(0.25 * initial_position, UL, SMALL_BUFF), rate_func=there_and_back_with_pause, run_time=6, ) # Reset self.play( FadeOut(plot), FadeOut(x0_copy), FadeOut(x_vect), run_time=2 ) self.wait() sho.resume_updating() plot.reset() plot.resume_updating() self.add(plot) # Describe frequency terms sqrt_km = eq4[R"\sqrt{k \over m}"] sqrt_km_rect = SurroundingRectangle(sqrt_km, buff=0.05) k_rect = SurroundingRectangle(eq4["k"]) m_rect = SurroundingRectangle(eq4["m"]) VGroup(sqrt_km_rect, k_rect, m_rect).set_stroke(TEAL, 2) for rect in k_rect, m_rect: rect.arrow = Vector(0.5 * UP) rect.arrow.match_color(rect) rect.arrow.next_to(rect, RIGHT, buff=SMALL_BUFF) self.play(ReplacementTransform(x0_rect, sqrt_km_rect)) self.wait(10) plot.reset() original_k = sho.k sho.set_k(4 * original_k) sho.move_to(initial_position) sho.reset_velocity() self.play( ReplacementTransform(sqrt_km_rect, k_rect), GrowArrow(k_rect.arrow) ) initial_position = sho.get_center() self.wait(5) globals().update(locals()) self.wait_until(lambda: get_norm(sho.get_center() - initial_position) < 0.05) sho.set_k(0.5 * original_k) sho.move_to(initial_position) sho.reset_velocity() self.play( ReplacementTransform(k_rect, m_rect), FadeOut(k_rect.arrow), GrowArrow(m_rect.arrow), ) self.wait(8) sho.set_k(original_k) # Define omega_0 omega0_eq = Tex(R"\omega_r = \sqrt{k / m}") omega0_eq[R"\omega_r"].set_color(PINK) omega0_eq.next_to(eq5, DOWN, buff=1.25) omega0_name = TexText("``Resonant frequency''", font_size=36) omega0_name.next_to(omega0_eq, DOWN) plot.reset() self.play( FadeOut(m_rect), FadeOut(m_rect.arrow), ) self.play( TransformFromCopy(sqrt_km, omega0_eq[R"\sqrt{k / m}"]), Write(omega0_eq[R"\omega_r = "]), TransformMatchingTex(eq4, eq5), ) self.wait(2) self.play(FadeIn(omega0_name)) self.wait(12) # Clean up solution corner_box = Rectangle(width=3, height=plot_rect.get_height()) corner_box.set_fill(interpolate_color(BLUE_E, BLACK, 0.75), 1.0) corner_box.set_stroke(WHITE, 1) corner_box.match_y(plot_rect) corner_box.to_edge(LEFT, buff=SMALL_BUFF) free_solution = VGroup(eq1, implies[0], eq5, omega0_eq) free_solution.target = free_solution.generate_target() free_solution.target.arrange(DOWN) free_solution.target.set_height(0.8 * corner_box.get_height()) free_solution.target.move_to(corner_box) sho.suspend_updating() self.play( FadeIn(corner_box), MoveToTarget(free_solution), *map(FadeOut, [eq3, implies[1], omega0_name]), sho.animate.center(), ) corner_box.push_self_into_submobjects() corner_box.add(free_solution) self.wait() self.play( FadeOut(plot_group1), frame.animate.shift(-up_shift), corner_box.animate.shift(-up_shift), run_time=2 ) corner_box.fix_in_frame() # Write new equation with driving force free_label = Text("No external\nforces", font_size=36) free_label.next_to(corner_box, DOWN) t2c[R"\vec{\textbf{E}}_0"] = BLUE_D driven_eq = Tex( R""" \vec{\textbf{F}}(t) = - k \vec{\textbf{x}}(t) + \vec{\textbf{E}}_0 q \cos(\omega_l t) """, t2c=t2c ) driven_eq.to_edge(UP) driven_eq.set_x(FRAME_WIDTH / 4) external_force = driven_eq[R"\vec{\textbf{E}}_0 q \cos(\omega_l t)"] external_force_rect = SurroundingRectangle(external_force, buff=SMALL_BUFF) external_force_rect.set_stroke(TEAL, 2) external_force_label = Text("Force from a\nlight wave", font_size=36) external_force_label.next_to(external_force_rect, DOWN) external_force_label.set_backstroke(BLACK, 7) self.play(FadeIn(free_label, lag_ratio=0.1)) self.wait() self.play(TransformMatchingTex(eq1.copy(), driven_eq)) driven_eq_group = VGroup( BackgroundRectangle(driven_eq, buff=0.5).set_fill(BLACK, 0.9), BackgroundRectangle(external_force_label, buff=0.5).set_fill(BLACK, 0.9), driven_eq, external_force_rect, external_force_label ) driven_eq_group.fix_in_frame() self.add(driven_eq_group) # Add a oscillating E field omega_tracker = ValueTracker(2.0) F_max = 0.5 wave_number = 2.0 axes.set_flat_stroke(False) def time_func(points, time): omega = omega_tracker.get_value() result = np.zeros(points.shape) result[:, 1] = F_max * np.cos(wave_number * points[:, 2] - omega * time) return result field_config = dict( stroke_color=TEAL, stroke_width=3, stroke_opacity=0.5, max_vect_len=1.0, x_density=1.0, y_density=1.0, ) planar_field = TimeVaryingVectorField( time_func, **field_config ) z_axis_field = TimeVaryingVectorField( time_func, height=0, width=0, depth=16, z_density=5, **field_config ) full_field = TimeVaryingVectorField( time_func, depth=16, z_density=5, height=5, width=5, norm_to_opacity_func=lambda n: n, **field_config, ) z_axis_field.set_stroke(opacity=1) full_field_opacity_mult = ValueTracker(0) globals().update(locals()) def udpate_full_field_opacity(ff): ff.data["stroke_rgba"][:, 3] *= full_field_opacity_mult.get_value() full_field.add_updater(udpate_full_field_opacity) sho.set_k(8) sho.set_damping(1) sho.set_external_forces([ lambda: 3 * planar_field.func(np.array([ORIGIN]))[0] ]) sho.center() sho.reset_velocity() sho.resume_updating() self.add(planar_field, corner_box, driven_eq_group) self.play( VFadeIn(planar_field), FadeOut(corner_box, time_span=(0, 1)), FadeOut(free_label, time_span=(0, 1)), ) self.wait(12) # Gather clean oscillations for B roll later self.remove(driven_eq_group) self.wait(30) self.add(driven_eq_group) self.play( frame.animate.reorient(-100, 100, 90), run_time=6 ) z_axis_field.time = full_field.time self.play( full_field_opacity_mult.animate.set_value(0), VFadeIn(z_axis_field), run_time=2 ) self.remove(full_field) self.play( frame.animate.reorient(-100, 80, 90), run_time=6 ) planar_field.set_stroke(opacity=0.5) self.play( frame.animate.reorient(-90, 0, 90).set_focal_distance(100).set_height(8), VFadeOut(z_axis_field), VFadeIn(planar_field), run_time=4 ) self.wait(4) # Change perspective a bunch full_field.time = planar_field.time frame.set_focal_distance(10) self.add(full_field) self.play( frame.animate.reorient(-100, 80, 90).set_height(10), full_field_opacity_mult.animate.set_value(1).set_anim_args(time_span=(2, 4)), VFadeOut(planar_field, time_span=(2, 4), remover=False), run_time=4, ) planar_field.set_stroke(opacity=0) self.remove(driven_eq_group) full_field_opacity_mult.set_value(0) frame.to_default_state().reorient(-90, 0, 90) self.play( full_field_opacity_mult.animate.set_value(1).set_anim_args(time_span=(1, 4)), frame.animate.reorient(-95, 60, 90).set_height(10), run_time=4, ) self.play( frame.animate.reorient(-100, 110, 90), run_time=12 ) self.play( frame.animate.reorient(-120, 80, 95), run_time=10 ) planar_field.time = full_field.time planar_field.set_stroke(opacity=1) self.play( frame.animate.reorient(-90, 0, 90).set_height(8), full_field_opacity_mult.animate.set_value(0).set_anim_args(time_span=(8, 10)), VFadeIn(planar_field, time_span=(8, 10)), run_time=12 ) self.add(driven_eq_group) self.wait(5) # Show graphical solution up_shift = UP driven_eq_group.unfix_from_frame() plot_rect, plot_axes, plot = self.get_plot_group( lambda: 2 * sho.get_y(), width=FRAME_WIDTH - 1, max_t=20 ) plot_group2 = VGroup(plot_rect, plot_axes, plot) plot_group2.to_edge(UP, buff=SMALL_BUFF).shift(up_shift) plot_box1, plot_box2 = plot_boxes = Rectangle().replicate(2) plot_boxes.match_height(plot_rect) plot_boxes.set_stroke(width=0) plot_boxes.set_fill(opacity=0.25) plot_boxes.set_submobject_colors_by_gradient(GREY_BROWN, TEAL) for box, width, x in zip(plot_boxes, (5, 15.5), (0, 5)): box.set_width(width * plot_axes.x_axis.get_unit_size(), stretch=True) box.move_to(plot_axes.c2p(x, 0), LEFT) sho.suspend_updating() self.play( frame.animate.shift(up_shift), FadeIn(plot_rect), FadeIn(plot_axes), driven_eq_group.animate.shift(1.0 * DOWN), sho.animate.center(), VFadeOut(planar_field, time_span=(0, 1)), run_time=2, ) self.wait() planar_field.time = 0 sho.resume_updating() plot.reset() self.add(planar_field, driven_eq_group, plot_rect, plot_axes, plot) self.play(VFadeIn(planar_field)) self.wait(5) self.play(FadeIn(plot_box1)) self.wait(4) self.play(FadeIn(plot_box2)) self.wait(9) plot.suspend_updating() self.wait(3) # Compare with the previous plot self.play( VFadeOut(axes), VFadeOut(planar_field), FadeOut(sho), VFadeOut(springs), ) down_shift = 2.5 * DOWN plot_group2.add(*plot_boxes) plot_group1.next_to(plot_group2, UP, aligned_edge=LEFT).shift(down_shift) top_axes = plot_group1[1] VGroup(top_axes.x_axis, plot_group1[2]).stretch( plot_axes.x_axis.get_unit_size() / top_axes.x_axis.get_unit_size(), 0, about_edge=LEFT ) top_axes[-2].match_x(top_axes.x_axis.get_right()) corner_box.unfix_from_frame() corner_box.next_to(plot_group1, RIGHT) self.remove(*driven_eq_group[:2]) self.play( FadeIn(plot_group1), FadeIn(corner_box), plot_group2.animate.shift(down_shift), driven_eq.animate.shift(down_shift), FadeOut(driven_eq_group[-2:], down_shift), run_time=3 ) self.wait() # Emphasize different frequencies omega0_eq_copy = omega0_eq.copy() omega_copy = driven_eq[R"\omega_l"].copy() self.play( omega0_eq_copy.animate.set_height(0.4).move_to(plot_group1, UR).shift(SMALL_BUFF * DL) ) self.wait() self.play( omega_copy.animate.move_to(plot_axes.c2p(14, 0.8)) ) self.wait() # Show equation for the solution driven_eq.target = driven_eq.generate_target() driven_eq.target.to_edge(LEFT, buff=MED_SMALL_BUFF) driven_eq.target.shift(0.5 * DOWN) implies = Tex(R"\Rightarrow", font_size=72) implies.next_to(driven_eq.target, RIGHT, MED_LARGE_BUFF) solution = Tex( R""" \vec{\textbf{x}}(t) = \frac{q \vec{\textbf{E}}_0}{m\left(\omega_r^2-\omega_l^2\right)} \cos(\omega_l t) """, t2c=t2c ) solution.next_to(implies, RIGHT, MED_LARGE_BUFF) implies.match_y(solution) self.play( MoveToTarget(driven_eq), FadeIn(implies, LEFT), FadeIn(solution, RIGHT), ) self.wait() # Comment on the equation full_rect = SurroundingRectangle(solution) amp_rect = SurroundingRectangle(solution[R"\frac{q \vec{\textbf{E}}_0}{m\left(\omega_r^2-\omega_l^2\right)}"]) E_rect = SurroundingRectangle(solution[R"\vec{\textbf{E}}_0"]) q_rect = SurroundingRectangle(solution[6]) freq_diff_rect = SurroundingRectangle( solution[R"\omega_r^2-\omega_l^2"], buff=0.05 ) lil_rects = VGroup(amp_rect, E_rect, q_rect, freq_diff_rect) steady_state_rect = plot_box2.copy().set_fill(opacity=0) VGroup( full_rect, amp_rect, E_rect, freq_diff_rect, steady_state_rect ).set_stroke(YELLOW, 2) self.play(ShowCreation(full_rect)) self.wait() self.play(TransformFromCopy(full_rect, steady_state_rect)) self.wait() self.play( ReplacementTransform(full_rect, amp_rect), FadeOut(steady_state_rect), ) self.wait() for r1, r2 in zip(lil_rects, lil_rects[1:]): self.play(ReplacementTransform(r1, r2)) self.wait() # Reintroduce oscillator plot_group2.add(omega_copy) plot_group2.target = plot_group2.generate_target() plot_group2.target.shift(1.75 * UP) top_rect = plot_rect.copy() top_rect.set_fill(BLACK, 1).set_stroke(width=0) top_rect.next_to(plot_group2.target, UP, buff=0) to_fade = VGroup( plot_group1, omega0_eq_copy, corner_box, driven_eq, implies, ) self.add(planar_field, springs, top_rect, plot_group2, solution, freq_diff_rect) self.add(to_fade) planar_field.set_stroke(opacity=0) planar_field.suspend_updating() sho.center() sho.suspend_updating() self.play( frame.animate.shift(UP), solution.animate.move_to(top_rect), MaintainPositionRelativeTo(freq_diff_rect, solution), MoveToTarget(plot_group2), FadeOut(to_fade, UP), FadeIn(sho), VFadeIn(springs), VFadeIn(planar_field), run_time=2, ) # Show strong resonance close_freq_words = Tex(R"\text{If } \omega_l \approx \omega_r", t2c=t2c) close_freq_words.next_to(plot_rect, DOWN, aligned_edge=LEFT) self.add(*plot_group2) self.play(LaggedStart( FadeOut(plot_boxes), FadeOut(plot), FadeOut(omega_copy), FadeIn(close_freq_words), Transform( freq_diff_rect, SurroundingRectangle(close_freq_words).set_stroke(width=0), remover=True ), *( TransformFromCopy(solution[tex][0], close_freq_words[tex][0]) for tex in [R"\omega_r", R"\omega_l"] ) )) self.wait() self.play( plot_axes.y_axis.animate.stretch(0.75, 1), plot_axes[-1].animate.shift(0.1 * DOWN + 0.4 * LEFT) ) sho.set_k(16) sho.set_damping(0.25) sho.center() sho.reset_velocity() omega_tracker.set_value(4) planar_field.set_stroke(opacity=1) plot.reset() plot.resume_updating() sho.resume_updating() planar_field.resume_updating() self.add(plot) self.play(VFadeIn(planar_field)) self.wait(30) # Out of sync frequencies half = Tex(R"0.5") omega_r = close_freq_words[R"\omega_r"][0] half.move_to(omega_r, LEFT) half.align_to(omega_r[0], DOWN) sho.suspend_updating() plot.suspend_updating() self.play( sho.animate.center(), planar_field.animate.set_opacity(0), FadeOut(plot), ) self.play( Write(half), omega_r.animate.shift((half.get_width() + 0.05) * RIGHT) ) close_freq_words.add(half) self.add(BackgroundRectangle(close_freq_words).set_fill(BLACK, 1), close_freq_words) self.play(FlashAround(VGroup(close_freq_words, half))) self.wait() plot.reset() plot.resume_updating() omega_tracker.set_value(2) sho.set_damping(0.25) sho.resume_updating() planar_field.set_stroke(opacity=1) self.add(plot) self.play(VFadeIn(planar_field)) self.wait(19) plot.reset() self.wait(20) def scrap(self): ## Line 281, used for thumbnail ## self.remove(axes) self.remove(equation) self.add(sho) springs.set_stroke(GREY_B, 4, 1) sho.shift(0.5 * LEFT) F_vect.set_stroke(width=10) self.frame.set_height(5) ############ # For clean driven_eq self.clear() self.add(driven_eq) self.play( ShowCreation(external_force_rect), FadeIn(external_force_label, lag_ratio=0.1), ) ### # Show damping (Right after show force vector) damp_term = Tex(R"- \mu \vec{\textbf{v}}(t)", t2c=t2c) damp_term.next_to(equation, RIGHT, SMALL_BUFF) damp_rect = SurroundingRectangle(damp_term) damp_rect.set_stroke(PINK, 2) damp_arrow = Vector(DOWN).next_to(damp_rect, UP) damp_arrow.match_color(damp_rect) up_shift = 1.5 * UP plot_rect, plot_axes, plot = self.get_plot_group( lambda: np.sign(sho.get_center()[1]) * get_norm(sho.get_center()), width=14, max_t=20, ) plot_group1 = VGroup(plot_rect, plot_axes, plot) plot_group1.to_corner(UR, buff=0.1) plot_group1.shift(up_shift) sho.move_to(initial_position) sho.reset_velocity() plot.reset() self.add(*plot_group1) frame.shift(up_shift) self.add( plot_rect, plot_axes, plot ) self.wait(3) sho.set_damping(0.5) self.play(Write(damp_term)) self.play(ShowCreation(damp_rect), GrowArrow(damp_arrow)) self.wait(17) ### def get_plot_group( self, func, width=10.0, height=2.0, max_t=12.0, ): plot_rect = Rectangle(width, height) plot_rect.set_fill(GREY_E, 1) plot_rect.set_stroke(WHITE, 1) plot_axes = Axes((0, max_t), (-1, 1), width=width - 1, height=height - 0.25) plot_axes.move_to(plot_rect) y_axis_label = Tex(R"x(t)", font_size=20) y_axis_label.set_color(RED) y_axis_label.next_to(plot_axes.y_axis.get_top(), RIGHT) t_axis_label = Tex("t", font_size=24) t_axis_label.next_to(plot_axes.x_axis.get_right(), DOWN) plot_axes.add(t_axis_label, y_axis_label) plot = DynamicPlot(plot_axes, func) return plot_rect, plot_axes, plot class JigglesInCalcite(InteractiveScene): polarization_direction = 1 def construct(self): # Set up crystal calcite = Calcite(height=8) calcite.center() index = 118 calcium_center = calcite.balls.get_points()[index] radii = calcite.balls.get_radii() radii[index] = 0 calcite.balls.set_radii(radii) calcium = HarmonicOscillator(center=calcium_center) calcium.set_radius(np.max(radii)) calcium.set_color(GREEN) calcium.set_glow_factor(calcite.balls.get_glow_factor()) calcium.move_to(calcium_center) self.add(calcite, calcium) # Initial panning frame = self.frame frame.reorient(12, 64, 0).move_to([0.21, -0.18, -0.77]).set_height(9) self.play( frame.animate.reorient(1, 84, 0).move_to([-0.08, -0.16, -0.53]).set_height(9), run_time=3 ) self.wait() # Add springs spring_length = 2.5 springs = VGroup( *( Spring( calcium, calcium.get_center() + spring_length * (v_vect + 0.2 * h_vect), edge=v_vect ) for v_vect in [UP, DOWN] for h_vect in [LEFT, ORIGIN, RIGHT] ), *( Spring( calcium, calcium.get_center() + spring_length * h_vect, edge=h_vect ) for h_vect in [LEFT, RIGHT] ) ) springs.set_stroke(opacity=0.7) self.play( VFadeIn(springs), calcium.animate.shift(RIGHT), calcite.balls.animate.set_opacity(0.1), frame.animate.reorient(-2, 25, 0).move_to(calcium).set_height(6), run_time=2, ) # Show two resonant frequencies def wait_until_centered(): disp = calcium.get_displacement() self.wait_until(lambda: np.dot(calcium.get_displacement(), disp) <= 0) calcium.move_to(calcium_center) calcium.reset_velocity() for vect, k in [(RIGHT, 5), (UP, 30)]: self.play(calcium.animate.move_to(calcium_center + vect), run_time=0.5) calcium.reset_velocity() calcium.set_k(k) self.wait(6) wait_until_centered() # Shine in light omega = -4.0 F_max = 1.0 wave_number = 2.0 def time_func(points, time): result = np.zeros(points.shape) result[:, self.polarization_direction] = F_max * np.cos(wave_number * points[:, 2] - omega * time) return result field_config = dict( stroke_color=TEAL, stroke_width=3, stroke_opacity=0.5, max_vect_len=1.0, x_density=1.0, y_density=1.0, center=calcium_center, ) z_axis_field = TimeVaryingVectorField( time_func, height=0, width=0, depth=16, z_density=5, **field_config ) z_axis_field.set_stroke(opacity=0.5) calcium.set_k([5, 30][self.polarization_direction]) calcium.set_damping(1) calcium.set_external_forces([ lambda: 3 * z_axis_field.func(np.array([calcium_center]))[0] ]) self.play( VFadeIn(z_axis_field), frame.animate.reorient(108, 46, -102).move_to(calcium).set_height(12), run_time=3 ) self.wait(25) class JigglesInCalciteY(JigglesInCalcite): polarization_direction = 0 class SpiralPaths(InteractiveScene): default_frame_orientation = (-30, 70) color = RED sign = 1 def construct(self): # Sucrose sucrose = Sucrose() sucrose.rotate(PI / 2) sucrose.set_height(7) sucrose.set_opacity(0.2) self.add(sucrose) # Frame motion frame = self.frame frame.add_updater(lambda t: t.reorient(-30 * math.sin(0.1 * self.time))) # Spiral helix = ParametricCurve( lambda t: [ math.cos(self.sign * t), math.sin(self.sign * t), 0.25 * t ], t_range=(-TAU, TAU, 0.01) ) line = Line(helix.get_end(), helix.get_start()) spiral = VGroup(helix, line) spiral.rotate(PI / 2, LEFT, about_point=ORIGIN) spiral.set_height(5, stretch=True) spiral.center() spiral.set_stroke(self.color, 1) spiral.set_flat_stroke(False) self.add(spiral) charge = Group( GlowDot(color=self.color), TrueDot(color=self.color, radius=0.15), ) self.add(charge) for _ in range(5): self.play(MoveAlongPath(charge, helix, run_time=3)) self.play(MoveAlongPath(charge, line, run_time=2)) class SpiralPathsLeftHanded(SpiralPaths): sign = -1 color = YELLOW
from manim_imports_ext import * class WaveMachine(Group): def __init__( self, n_arms=100, width=20, delta_angle=2 * TAU / 50, shaft_radius=0.1, arm_radius=0.025, arm_length=1.5, arm_cap_radius=0.035, shaft_color=GREY_D, arm_color=GREY_BROWN, cap_color=GREY_BROWN, ): shaft = Cylinder( height=width, radius=shaft_radius, color=shaft_color, ) for point in [shaft.get_zenith(), shaft.get_nadir()]: disk = Circle(radius=shaft_radius) disk.set_stroke(width=0) disk.set_fill(shaft_color, 1) disk.move_to(point) shaft.add(disk) angle = 0 arms = Group() z_range = np.linspace( shaft.get_z(IN) + arm_radius + 1e-2, shaft.get_z(OUT) - arm_radius - 1e-2, n_arms ) for z in z_range: arm = Cylinder( height=arm_length, radius=arm_radius, color=arm_color, ) arm.rotate(PI / 2, UP) arm.next_to(ORIGIN, RIGHT, buff=0) cap = Sphere(radius=arm_cap_radius, color=cap_color) cap.move_to(arm.get_right()) # full_arm = Group(arm, cap) full_arm = arm full_arm.rotate(angle, about_point=ORIGIN) full_arm.shift(z * OUT) full_arm.angle = angle arms.add(full_arm) angle += delta_angle super().__init__(shaft, arms) self.shaft = shaft self.arms = arms self.rotate(PI / 2, UP) class WaveMachineDemo(InteractiveScene, ThreeDScene): def construct(self): # Add axes (or don't!) frame = self.frame axes = ThreeDAxes(width=14) axes.set_stroke(width=1) plane = NumberPlane( background_line_style=dict(stroke_color=BLUE_D, stroke_width=1), faded_line_style=dict(stroke_color=BLUE_D, stroke_width=0.5, stroke_opacity=0.25), ) plane.axes.set_stroke(BLUE_D, 1) plane.set_width(14) # Add machine machine = WaveMachine(width=14, delta_angle=2 * TAU / 25) self.add(machine) frame.set_field_of_view(0.2) frame.reorient(-68, 79, 0).move_to([-2.41, 1.04, -0.68]) self.play( frame.animate.reorient(0, 78, 0).move_to([-0.0, 0.01, 0.02]).set_height(9.5), LaggedStartMap(ShowCreation, machine.arms, lag_ratio=0.1), run_time=9, ) self.play( Rotating(machine, 5 * TAU, RIGHT, ORIGIN, run_time=20), ) # Reposition machine2 = WaveMachine(width=14, delta_angle=2 * TAU / 100) self.play( frame.animate.reorient(-80, 88, 0).move_to([0.21, -0.56, 0.39]).set_height(11.11), run_time=2 ) self.play(*( Transform(arm1, arm2, path_arc=arm2.angle - arm1.angle, path_arc_axis=RIGHT, run_time=3) for arm1, arm2 in zip(machine.arms, machine2.arms) )) self.play( frame.animate.reorient(0, 78, 0).move_to([-0.0, 0.01, 0.02]).set_height(9.5), run_time=2 ) self.play( Rotating(machine, 5 * TAU, RIGHT, ORIGIN, run_time=20), ) # Yet another machine3 = WaveMachine(width=14, delta_angle=2 * TAU / 200) self.play(*( Transform(arm1, arm3, path_arc=arm3.angle - arm2.angle, path_arc_axis=RIGHT) for arm1, arm2, arm3 in zip(machine.arms, machine2.arms, machine3.arms) )) self.play( Rotating(machine, 5 * TAU, RIGHT, ORIGIN, run_time=20), ) def get_rotation_arrow_animations(self, x_value=6): rot_arrows = VGroup( Arrow(RIGHT, LEFT, path_arc=PI, stroke_width=8), Arrow(LEFT, RIGHT, path_arc=PI, stroke_width=8), ) rot_arrows.set_height(3) rot_arrows.rotate(PI / 2, RIGHT) rot_arrows.rotate(PI / 2, OUT) rot_arrows.set_flat_stroke(True) rot_arrows.set_x(-x_value) rot_arrows.add(*rot_arrows.copy().set_x(x_value)) return ( Succession( ShowCreation(arrow), Animation(arrow), arrow.animate.set_stroke(BLACK, opacity=0), run_time=3, remover=True ) for arrow in rot_arrows )
from manim_imports_ext import * from _2023.barber_pole.objects import * class SlicedWave(Group): default_wave_config = dict( z_amplitude=0, y_amplitude=1, wave_len=2.0, color=BLUE, ) default_layer_style = dict( stroke_width=2.0, stroke_color=WHITE, ) default_vect_wave_style = dict( stroke_opacity=0.5 ) def __init__( self, axes, layer_xs, phase_kick_back=0, layer_height=4.0, damping_per_layer=1.0, wave_config = dict(), vect_wave_style=dict(), layer_style=dict(), ): self.layer_xs = layer_xs self.axes = axes wave_kw = merge_dicts_recursively(self.default_wave_config, wave_config) vwave_kw = merge_dicts_recursively(self.default_vect_wave_style, vect_wave_style) line_kw = merge_dicts_recursively(self.default_layer_style, layer_style) self.wave = OscillatingWave(axes, **wave_kw) self.vect_wave = OscillatingFieldWave(axes, self.wave, **vwave_kw) self.phase_kick_trackers = [ ValueTracker(phase_kick_back) for x in layer_xs ] self.absorbtion_trackers = [ ValueTracker(damping_per_layer) for x in layer_xs ] self.layers = VGroup() for x in layer_xs: line = Line(DOWN, UP, **line_kw) line.set_height(layer_height) line.move_to(axes.c2p(x, 0)) self.layers.add(line) self.wave.xt_to_yz = self.xt_to_yz super().__init__( self.wave, self.vect_wave, self.layers, *self.phase_kick_trackers ) def set_layer_xs(self, xs): self.layer_xs = xs def xt_to_yz(self, x, t): phase = np.ones_like(x) phase *= TAU * t * self.wave.speed / self.wave.wave_len amplitudes = self.wave.y_amplitude * np.ones_like(x) for layer_x, pkt, at in zip(self.layer_xs, self.phase_kick_trackers, self.absorbtion_trackers): phase[x > layer_x] += pkt.get_value() amplitudes[x > layer_x] *= at.get_value() y = amplitudes * np.sin(TAU * x / self.wave.wave_len - phase) return y, np.zeros_like(x) # Scenes class SpeedInMediumFastPart(InteractiveScene): z_amplitude = 0 y_amplitude = 1.0 color = YELLOW wave_len = 3.0 speed = 1.5 medium_color = BLUE medium_opacity = 0.35 add_label = True run_time = 30 material_label = "Glass" def construct(self): # Basic wave axes = ThreeDAxes((-12, 12), (-4, 4)) axes.z_axis.set_stroke(opacity=0) axes.y_axis.set_stroke(opacity=0) wave = OscillatingWave( axes, z_amplitude=self.z_amplitude, y_amplitude=self.y_amplitude, color=self.color, wave_len=self.wave_len, speed=self.speed, ) vect_wave = OscillatingFieldWave(axes, wave) vect_wave.set_stroke(opacity=0.5) self.add(axes, wave, vect_wave) # Water label rect = FullScreenRectangle() rect.stretch(0.5, 0, about_edge=RIGHT) rect.set_stroke(width=0) rect.set_fill(self.medium_color, self.medium_opacity) self.add(rect) if self.add_label: label = Text(self.material_label, font_size=60) label.next_to(rect.get_top(), DOWN) self.add(label) # Propagate self.wait(self.run_time) class SpeedInMediumSlower(SpeedInMediumFastPart): wave_len = 2.0 speed = 1.0 class VectorOverMedia(InteractiveScene): def construct(self): vect = Vector(DOWN) vect.next_to(UP, UP) vect.to_edge(LEFT, buff=0) def update_vect(v, dt): # speed = 1.5 if v.get_x() < 0 else 1.0 speed = 1.33 if v.get_x() < 0 else 1.33 / 1.5 v.shift(dt * RIGHT * speed) vect.add_updater(update_vect) word = Text("Phase velocity") word.add_updater(lambda m: m.next_to(vect, UP)) self.add(vect) self.add(word) self.wait(13) class VioletWaveFast(SpeedInMediumFastPart): color = get_spectral_color(0.95) wave_len = 1.2 y_amplitude = 0.5 speed = 1.5 medium_opacity = 0.25 add_label = False run_time = 15 class VioletWaveSlow(VioletWaveFast): wave_len = 1.2 * 0.5 speed = 1.5 * 0.5 class GreenWaveFast(VioletWaveFast): color = get_spectral_color(0.65) wave_len = 1.5 class GreenWaveSlow(GreenWaveFast): wave_len = 1.5 * 0.6 speed = 1.5 * 0.6 class OrangeWaveFast(VioletWaveFast): color = get_spectral_color(0.3) wave_len = 2.0 class OrangeWaveSlow(OrangeWaveFast): wave_len = 2.0 * 0.7 speed = 1.5 * 0.7 class RedWaveFast(VioletWaveFast): color = get_spectral_color(0.05) wave_len = 2.5 class RedWaveSlow(RedWaveFast): wave_len = 2.5 * 0.8 speed = 1.5 * 0.8 class PhaseKickBacks(SpeedInMediumFastPart): layer_xs = np.arange(0, 8, 1) kick_back_value = 0 axes_config = dict( x_range=(-8, 8), y_range=(-4, 4), ) line_style = dict() wave_config = dict() vect_wave_style = dict() layer_add_on_run_time = 5 damping_per_layer = 1.0 def get_axes(self): axes = ThreeDAxes(**self.axes_config) axes.z_axis.set_stroke(opacity=0) return axes def get_layer_xs(self): return self.layer_xs def get_sliced_wave(self): return SlicedWave( self.get_axes(), self.get_layer_xs(), wave_config=self.wave_config, vect_wave_style=self.vect_wave_style, layer_style=self.line_style, phase_kick_back=self.kick_back_value, damping_per_layer=self.damping_per_layer, ) def setup(self): super().setup() self.sliced_wave = self.get_sliced_wave() self.add(self.sliced_wave) class RevertToOneLayerAtATime(PhaseKickBacks): layer_xs = np.arange(0, FRAME_WIDTH / 2, FRAME_WIDTH / 2**(11)) kick_back_value = -0.025 n_layers_skipped = 64 exagerated_phase_kick = -0.8 line_style = dict( stroke_width=1, stroke_opacity=0.25, stroke_color=BLUE_B ) axes_config = dict( x_range=(-12, 12), y_range=(-4, 4), ) wave_config = dict( color=YELLOW, sample_resolution=0.001 ) vect_wave_style = dict(tip_width_ratio=3, stroke_opacity=0.5) def construct(self): # Objects sliced_wave = self.sliced_wave wave = sliced_wave.wave layers = sliced_wave.layers pkts = sliced_wave.phase_kick_trackers # Add label block_label = Text("Material (e.g. glass)") block_label.next_to(layers, UP, aligned_edge=LEFT) for pkt in pkts: pkt.set_value(-0.015) self.wait(5) self.play(Write(block_label["Material"], run_time=1)) self.play(FadeIn(block_label["(e.g. glass)"], 0.25 * UP)) self.add(block_label) self.wait(2) # Show layers layers.save_state() rect = BackgroundRectangle(sliced_wave) rect.set_fill(BLACK, 0.9) self.add(sliced_wave, rect, layers) self.play( layers.animate.arrange(RIGHT, buff=0.3).move_to(ORIGIN, LEFT).set_stroke(width=2, opacity=1), FadeIn(rect), *(pkt.animate.set_value(0) for pkt in pkts), run_time=2, ) self.wait(3) # Revert to one single layer left_layers = VGroup() for layer in layers: if layer.get_x() < FRAME_WIDTH / 2: left_layers.add(layer) self.remove(layers) self.add(left_layers) layer_label = Text("Thin layer of material") layer_label.next_to(layers[0], UP, buff=0.75) kw = dict(run_time=5, lag_ratio=0.1) self.play( LaggedStart(*( layer.animate().set_stroke(opacity=0).shift(DOWN) for layer in left_layers[:0:-1] ), **kw), layers[0].animate.set_stroke(width=2, opacity=1).set_height(5).set_anim_args(time_span=(4, 5)), FadeTransform( block_label, layer_label, time_span=(4, 5) ), FadeOut(rect, time_span=(3, 5)), ) self.wait(4) # Pause, shift the phase a bit arrow = Vector(1.0 * LEFT, stroke_width=6) arrow.next_to(wave, UP, buff=0.75) arrow.set_x(0, LEFT).shift(0.1 * RIGHT) phase_kick = self.exagerated_phase_kick kick_words = Text("Kick back\nthe phase", font_size=36) kick_words.next_to(arrow, RIGHT) kick_label = VGroup(arrow, kick_words) kick_label.set_color(RED) self.wait(1 - (wave.time % 1)) wave.stop_clock() self.wait() self.play( pkts[0].animate.set_value(phase_kick), FadeIn(kick_label, LEFT), ) self.wait() # Show the phase kick form1 = Tex(R"A\sin(kx)") form2 = Tex(R"A\sin(kx + 1.00)") pk_decimal: DecimalNumber = form2.make_number_changable("1.00") pk_decimal.set_value(-phase_kick) pk_decimal.set_color(RED) VGroup(form1, form2).next_to(wave, DOWN) form1.set_x(-FRAME_WIDTH / 4) form2.set_x(+FRAME_WIDTH / 4) self.play(FadeIn(form1, 0.5 * DOWN)) self.wait() self.play(TransformMatchingStrings(form1.copy(), form2, path_arc=20 * DEGREES)) self.wait() for value in [-0.01, phase_kick]: self.play( pkts[0].animate.set_value(value), ChangeDecimalToValue(pk_decimal, -value), run_time=2, ) self.wait() # Add phase kick label pk_label = Text("Phase kick = ", font_size=36, fill_color=GREY_B) pk_label.next_to(wave, UP, LARGE_BUFF) pk_label.to_edge(LEFT) form2.remove(pk_decimal) form2.add(pk_decimal.copy()) self.add(form2) self.play( pk_decimal.animate.match_height(pk_label).next_to(pk_label, RIGHT, 0.2, DOWN), ReplacementTransform(kick_words["Kick"].copy(), pk_label["kick"]), ReplacementTransform(kick_words["phase"].copy(), pk_label["Phase"]), FadeIn(pk_label["="]), run_time=2 ) pk_label.add(pk_decimal) self.add(pk_label) self.play( FadeOut(form1), FadeOut(form2), ) # Show following layers for layer in layers[1:]: layer.match_height(layers[0]) layer.match_style(layers[0]) layer.set_stroke(opacity=0) nls = self.n_layers_skipped shown_layers = VGroup(layers[0]) layer_arrows = VGroup(VectorizedPoint(layer_label.get_center())) for layer, pkt in zip(layers[nls::nls], pkts[nls::nls]): layer.set_stroke(opacity=1) shown_layers.add(layer) layer_label.target = layer_label.generate_target() layer_label.target.set_height(0.35) layer_label.target.match_x(shown_layers) layer_label.target.to_edge(UP, buff=0.25) layer_arrows.target = VGroup(*( Arrow( layer_label.target.get_bottom(), sl.get_top(), buff=0.1, stroke_width=2, stroke_opacity=0.5, ) for sl in shown_layers )) self.play( FadeOut(kick_label), GrowFromCenter(layer), MoveToTarget(layer_label), MoveToTarget(layer_arrows), ) kick_label.align_to(layer, LEFT).shift(0.1 * RIGHT) self.play( FadeIn(kick_label, 0.5 * LEFT), pkt.animate.set_value(phase_kick) ) self.play(FadeOut(kick_label)) # Restart clock wave.start_clock() self.play(FadeOut(layer_label), FadeOut(layer_arrows)) self.wait(6) # Change phase kick self.play(FlashAround(pk_label)) for value in [-0.01, self.exagerated_phase_kick]: phase_kick = value globals().update(locals()) self.play( ChangeDecimalToValue(pk_decimal, -phase_kick), *( pkt.animate.set_value(phase_kick) for pkt in pkts[::nls] ), run_time=4 ) self.wait(2) self.wait(2) # Number of layers label n_shown_layers = len(layers[::nls]) n_layers_label = TexText(f"Num. layers = {n_shown_layers}", font_size=36) n_layers_label.set_color(GREY_B) n_layers_label.next_to(pk_label, UP, MED_LARGE_BUFF, LEFT) nl_decimal = n_layers_label.make_number_changable(n_shown_layers) nl_decimal.set_color(BLUE) self.play(FadeIn(n_layers_label, UP)) self.wait(8) # Fill in opacity = 1.0 stroke_width = 2.0 kw = dict(lag_ratio=0.1, run_time=3) while nls > 1: # Update parameters nls //= 2 opacity = 0.25 + 0.5 * (opacity - 0.25) stroke_width = 1.0 + 0.5 * (stroke_width - 1.0) phase_kick /= 2 new_layers = layers[nls::2 * nls] old_layers = layers[0::2 * nls] new_nl_decimal = Integer(len(layers[::nls])) new_nl_decimal.match_height(nl_decimal) new_nl_decimal.match_style(nl_decimal) new_nl_decimal.move_to(nl_decimal, LEFT) new_pk_decimal = DecimalNumber( -phase_kick, num_decimal_places=(2 if -phase_kick > 0.05 else 3) ) new_pk_decimal.match_height(pk_decimal) new_pk_decimal.match_style(pk_decimal) new_pk_decimal.move_to(pk_decimal, LEFT) new_layers.set_stroke(width=stroke_width, opacity=opacity) globals().update(locals()) # Only necessary for embedded runs self.play( LaggedStart(*( GrowFromCenter(layer) for layer in new_layers ), **kw), old_layers.animate.set_stroke(width=stroke_width, opacity=opacity), LaggedStart(*( pkt.animate.set_value(phase_kick) for pkt in pkts[::nls] ), **kw), LaggedStart( FadeOut(nl_decimal, 0.2 * UP), FadeIn(new_nl_decimal, 0.2 * UP), FadeOut(pk_decimal, 0.2 * UP), FadeIn(new_pk_decimal, 0.2 * UP), lag_ratio=0.1, run_time=1 ) ) nl_decimal = new_nl_decimal pk_decimal = new_pk_decimal globals().update(locals()) # Only necessary for embedded runs self.play(*( pkt.animate.set_value(phase_kick) for pkt in pkts[::nls] )) self.wait(3 if nls >= 32 else 1) # Wait self.wait(10) class SimplerRevertToOneLayerAtATime(RevertToOneLayerAtATime): layer_xs = np.arange(-0, 7.5, 0.11) kick_back_value = -0.25 n_layers_skipped = 8 class SlowedAndAbsorbed(RevertToOneLayerAtATime): layer_xs = np.arange(-FRAME_WIDTH / 3, FRAME_WIDTH / 3, FRAME_WIDTH / 2**(8)) kick_back_value = -0.2 damping_per_layer = 1 - 2e-2 wave_config = dict( color=YELLOW, sample_resolution=0.001, ) line_style = dict( stroke_color=BLUE_B, stroke_width=1.5, stroke_opacity=0.5, ) def construct(self): # Objects sliced_wave = self.sliced_wave wave = sliced_wave.wave layers = sliced_wave.layers pkts = sliced_wave.phase_kick_trackers ats = sliced_wave.absorbtion_trackers # Show labels label = Text("Wave gets slowed and absorbed") label.next_to(layers, UP) abs_words = label["and absorbed"] mu_label = Tex(R"\mu").set_color(PINK) mu_line = NumberLine((0, 1, 0.2), width=1.0, tick_size=0.05) mu_line.rotate(PI / 2) mu_line.to_corner(UR) mu_indicator = Triangle(start_angle=0) mu_indicator.set_width(0.15) mu_indicator.set_fill(PINK, 1) mu_indicator.set_stroke(width=0) mu_tracker = ValueTracker(1) mu_indicator.add_updater(lambda m: m.move_to(mu_line.n2p(mu_tracker.get_value()), RIGHT)) mu_label.add_updater(lambda m: m.next_to(mu_indicator, LEFT, buff=0.1)) for pkt in pkts: pkt.set_value(0) for at in ats: at.set_value(1) self.play( FadeIn(label, time_span=(0, 2)), FlashAround(abs_words, color=PINK, time_span=(2, 4)), abs_words.animate.set_color(PINK).set_anim_args(time_span=(2, 4)), FadeIn(mu_line), FadeIn(mu_indicator), FadeIn(mu_label), LaggedStart(*( pkt.animate.set_value(self.kick_back_value) for pkt in pkts )), LaggedStart(*( at.animate.set_value(self.damping_per_layer) for at in ats )), LaggedStart(*( FadeIn(layer, scale=0.8) for layer in layers )), run_time=5, ) # Play with mu for mu in [0.1, 1.0]: self.play( mu_tracker.animate.set_value(mu), *(at.animate.set_value(1 - mu * 2e-2) for at in ats), run_time=3, ) self.wait(17) class PlayWithIndex(RevertToOneLayerAtATime): layer_xs = np.arange(-FRAME_WIDTH / 4, FRAME_WIDTH / 4, FRAME_WIDTH / 2**(10)) def construct(self): # Objects sliced_wave = self.sliced_wave wave = sliced_wave.wave layers = sliced_wave.layers layers.set_stroke(BLUE, 1, 0.5) pkts = sliced_wave.phase_kick_trackers global_pk = ValueTracker(self.kick_back_value) for pkt in pkts: pkt.add_updater(lambda m: m.set_value(global_pk.get_value())) def get_index(): return 1 - 20 * global_pk.get_value() # equation label equation = Tex( R""" \text{Index of refraction } = {\small \text{Speed in a vacuum} \over \text{Speed in medium}} = 1.00 """, t2c={ R"\text{Speed in a vacuum}": YELLOW, R"\text{Speed in medium}": BLUE, } ) equation.next_to(layers, UP) rhs = equation.make_number_changable("1.00") rhs.add_updater(lambda m: m.set_value(get_index())) arrow = Arrow(rhs.get_bottom(), layers.get_corner(UR) + 1.0 * DL) self.add(equation) self.add(arrow) # Speed label speed_label = Tex(R"\text{Speed} = c / 1.00") speed_factor = speed_label.make_number_changable("1.00") speed_factor.add_updater(lambda m: m.set_value(get_index())) speed_label.next_to(layers.get_bottom(), UP) self.add(speed_label) # Change value self.wait(3) for value in [0, 0.02]: self.play(global_pk.animate.set_value(value), run_time=2) self.wait(3) self.wait(10) class RedLight(RevertToOneLayerAtATime): wave_config = dict( color=RED, sample_resolution=0.001, wave_len=4.0, ) kick_back_value = -0.005 def construct(self): # Test sliced_wave = self.sliced_wave wave = sliced_wave.wave layers = sliced_wave.layers pkts = sliced_wave.phase_kick_trackers sliced_wave.clear_updaters() self.remove(layers) self.add(self.sliced_wave) class XRay(RedLight): wave_config = dict( self.embed() color=BLUE, sample_resolution=0.001, wave_len=1.0, ) kick_back_value = 0.005 class DissolveLayers(PhaseKickBacks): def construct(self): # Test sliced_wave = self.sliced_wave layers = sliced_wave.layers pkts = sliced_wave.phase_kick_trackers # Zoom in on layers frame = self.frame layers_copy = layers.copy() layers_copy.set_stroke(width=1) fade_rect = FullScreenRectangle().set_fill(BLACK, 1) self.wait(4) self.add(fade_rect, layers_copy) self.play( frame.animate.scale(0.2).move_to(layers).set_anim_args(run_time=4), FadeIn(fade_rect, time_span=(1, 3)), FadeIn(layers_copy, time_span=(1, 3)), ) self.wait() self.play( frame.animate.to_default_state().set_anim_args(run_time=2), FadeOut(fade_rect), FadeOut(layers_copy), ) self.wait(2) # Dissolve kw = dict(run_time=8, lag_ratio=0.1) self.play( LaggedStart(*( layer.animate().set_stroke(WHITE, 2, 0).set_height(5) for layer in layers[:0:-1] ), **kw), LaggedStart(*( pkt.animate.set_value(0) for pkt in pkts[:0:-1] ), **kw), layers[0].animate.set_stroke(WHITE, 2).set_height(5).set_anim_args(time_span=(7, 8)) ) self.wait(3) class IntroducePhaseKickBack(PhaseKickBacks): layer_xs = np.arange(0, 8, PI / 4) vect_wave_style = dict(stroke_width=0) def construct(self): # Set up sine wave sliced_wave = self.sliced_wave axes = sliced_wave.axes layers = sliced_wave.layers pkts = sliced_wave.phase_kick_trackers wave = sliced_wave.wave self.remove(sliced_wave) wave.stop_clock() self.add(wave) self.add(*pkts) # # Pair of braces # brace1 = Brace(Line(LEFT_SIDE, ORIGIN, buff=0.25), UP) # brace2 = brace1.copy().set_x(FRAME_WIDTH / 4) # braces = VGroup(brace1, brace2) # braces.set_y(2) # self.add(braces) # b1_tex = brace1.get_tex(R"\sin(\omega t - kx)") # b2_tex = brace2.get_tex(R"\sin(\omega t - kx - \Delta \phi)") # self.add(b1_tex) # self.add(b2_tex) # Add one layer of material self.play(GrowFromCenter(layers[0])) # TODO: Some kind of labels here? # Show small kick back arrow = Vector(2 * LEFT, stroke_width=8) arrow.next_to(wave, UP, buff=0.75) arrow.set_x(0, LEFT).shift(0.5 * RIGHT) phase_kick = -0.5 self.play( pkts[0].animate.set_value(phase_kick), FadeIn(arrow, LEFT), ) self.play(FadeOut(arrow)) # Add more layers of material for layer, pkt in zip(layers[1:], pkts[1:]): arrow.align_to(layer, LEFT).shift(0.25 * RIGHT) self.play( GrowFromCenter(layer), FadeIn(arrow, LEFT), pkt.animate.set_value(phase_kick), ) self.play(FadeOut(arrow), run_time=0.5) # Make it all more dense pass class PhaseKickBackAddInLayers(PhaseKickBacks): n_layers = 10 kick_back_value = 0 target_kick_back = -0.5 def get_layer_xs(self): return np.linspace(0, 8, self.n_layers) def construct(self): sliced_wave = self.sliced_wave lag_kw = dict(run_time=self.layer_add_on_run_time, lag_ratio=0.5) self.play( LaggedStart(*( FadeIn(line, 0.5 * DOWN) for line in sliced_wave.layers ), **lag_kw), LaggedStart(*( pkt.animate.set_value(self.target_kick_back) for pkt in sliced_wave.phase_kick_trackers ), **lag_kw), ) self.wait(8) class DensePhaseKickBacks25(PhaseKickBackAddInLayers): n_layers = 25 target_kick_back = -0.4 line_style = dict( stroke_width=1.0, stroke_color=BLUE_B, ) class DensePhaseKickBacks50(PhaseKickBackAddInLayers): n_layers = 50 target_kick_back = -0.2 line_style = dict( stroke_width=1.0, stroke_color=BLUE_B, ) class DensePhaseKickBacks100(PhaseKickBackAddInLayers): n_layers = 100 target_kick_back = -0.15 line_style = dict( stroke_width=1.5, stroke_color=BLUE_C, stroke_opacity=0.7, ) layer_add_on_run_time = 10 class FastWave(PhaseKickBacks): layer_xs = np.arange(-3, 3, 0.01) kick_back_value = 0.01 line_style = dict( stroke_width=1, stroke_opacity=0.35, stroke_color=BLUE_D ) wave_config = dict( color=YELLOW, sample_resolution=0.001 ) def construct(self): # Test self.wait(20) class KickForward(PhaseKickBacks): layer_xs = np.arange(0, 8, 0.25) kick_back_value = 0.25 line_style = dict( stroke_color=BLUE, stroke_width=2, stroke_opacity=0.75, ) wave_config = dict( color=YELLOW, sample_resolution=0.001 ) time_per_layer = 0.25 def construct(self): # Objects sliced_wave = self.sliced_wave wave = sliced_wave.wave layers = sliced_wave.layers layers.stretch(1.2, 1) pkts = sliced_wave.phase_kick_trackers # Just show one layer layer_label = Text("Thin layer of material") layer_label.next_to(layers[0], UP, buff=0.75) for pkt in pkts: pkt.set_value(0) self.wait(1 - (wave.time % 1)) wave.stop_clock() self.remove(layers) self.play( ShowCreation(layers[0]), FadeIn(layer_label, lag_ratio=0.1), ) self.wait() # Kick back then forth kick_back = VGroup( Vector(LEFT, stroke_width=6), Text("Kick back\nthe phase", font_size=36), ) kick_back.set_color(RED) kick_forward = VGroup( Vector(RIGHT, stroke_width=6), Text( "Kick forward\nthe phase", font_size=36, t2s={"forward": ITALIC} ), ) kick_forward.set_color(GREEN) for label in [kick_back, kick_forward]: label.arrange(RIGHT) label.next_to(wave, UP) label.align_to(layers[0], LEFT).shift(MED_SMALL_BUFF * RIGHT) self.play( pkts[0].animate.set_value(-0.75), FadeIn(kick_back, LEFT), ) self.wait() self.play(FadeOut(kick_back)) self.play( pkts[0].animate.set_value(self.kick_back_value), FadeIn(kick_forward, RIGHT), ) self.wait() self.play(FadeOut(layer_label)) # Add other layers wave.start_clock() remaining_layers = layers[1:] self.play( ShowIncreasingSubsets(remaining_layers, rate_func=linear), UpdateFromFunc( kick_forward, lambda m: m.align_to(remaining_layers.get_right(), LEFT).shift(MED_SMALL_BUFF * RIGHT), ), LaggedStart(*( pkt.animate.set_value(self.kick_back_value) for pkt in pkts[1:] ), lag_ratio=1), run_time = len(remaining_layers) * self.time_per_layer ) # Wait self.wait(20) class DenserKickForward(KickForward): # Run at 9 layer_xs = np.arange(0, 8, 0.1) kick_back_value = 0.1 line_style = dict( stroke_color=BLUE, stroke_width=1.5, stroke_opacity=0.75, ) time_per_layer = 0.1 class DensestKickForward(DenserKickForward): layer_xs = np.arange(0, 8, 0.025) kick_back_value = 0.025 time_per_layer = 0.025 line_style = dict( stroke_color=BLUE, stroke_width=1.0, stroke_opacity=0.65, )
from __future__ import annotations from manim_imports_ext import * from matplotlib import colormaps from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import Vect3 spectral_cmap = colormaps.get_cmap("Spectral") # Helper functions def get_spectral_color(alpha): return Color(rgb=spectral_cmap(alpha)[:3]) def get_spectral_colors(n_colors, lower_bound=0, upper_bound=1): return [ get_spectral_color(alpha) for alpha in np.linspace(lower_bound, upper_bound, n_colors) ] def get_axes_and_plane( x_range=(0, 24), y_range=(-1, 1), z_range=(-1, 1), x_unit=1, y_unit=2, z_unit=2, origin_point=5 * LEFT, axes_opacity=0.5, plane_line_style=dict( stroke_color=GREY_C, stroke_width=1, stroke_opacity=0.5 ), ): axes = ThreeDAxes( x_range=x_range, y_range=y_range, z_range=z_range, width=x_unit * (x_range[1] - x_range[0]), height=y_unit * (y_range[1] - y_range[0]), depth=z_unit * (z_range[1] - z_range[0]), ) axes.shift(origin_point - axes.get_origin()) axes.set_opacity(axes_opacity) axes.set_flat_stroke(False) plane = NumberPlane( axes.x_range, axes.y_range, width=axes.x_axis.get_length(), height=axes.y_axis.get_length(), background_line_style=plane_line_style, axis_config=dict(stroke_width=0), ) plane.shift(axes.get_origin() - plane.get_origin()) plane.set_flat_stroke(False) return axes, plane def get_twist(wave_length, distance): # 350 is arbitrary. Change return distance / (wave_length / 350)**2 def acceleration_from_position(pos_func, time, dt=1e-3): p0 = pos_func(time - dt) p1 = pos_func(time) p2 = pos_func(time + dt) return (p0 + p2 - 2 * p1) / dt**2 def points_to_particle_info(particle, points, radius=None, c=2.0): """ Given an origin, a set of points, and a radius, this returns: 1) The unit vectors directed from the origin to each point 2) The distances from the origin to each point 3) An adjusted version of those distances where points within a given radius of the origin are considered to be farther away, approaching infinity at the origin. The intent is that when this is used for coulomb/lorenz forces, field vectors within a radius of a particle don't blow up """ if radius is None: radius = particle.get_radius() if particle.track_position_history: approx_delays = np.linalg.norm(points - particle.get_center(), axis=1) / c centers = particle.get_past_position(approx_delays) else: centers = particle.get_center() diffs = points - centers norms = np.linalg.norm(diffs, axis=1)[:, np.newaxis] unit_diffs = np.zeros_like(diffs) np.true_divide(diffs, norms, out=unit_diffs, where=(norms > 0)) adjusted_norms = norms.copy() mask = (0 < norms) & (norms < radius) adjusted_norms[mask] = radius * radius / norms[mask] adjusted_norms[norms == 0] = np.inf return unit_diffs, norms, adjusted_norms def coulomb_force(points, particle, radius=None): unit_diffs, norms, adjusted_norms = points_to_particle_info(particle, points, radius) return particle.get_charge() * unit_diffs / adjusted_norms**2 def lorentz_force( points, particle, radius=None, c=2.0, epsilon0=0.025, ): unit_diffs, norms, adjusted_norms = points_to_particle_info(particle, points, radius, c) delays = norms[:, 0] / c acceleration = particle.get_past_acceleration(delays) dot_prods = (unit_diffs * acceleration).sum(1)[:, np.newaxis] a_perp = acceleration - dot_prods * unit_diffs denom = 4 * PI * epsilon0 * c**2 * adjusted_norms return -particle.get_charge() * a_perp / denom # For the cylinder class OscillatingWave(VMobject): def __init__( self, axes, y_amplitude=0.0, z_amplitude=0.75, z_phase=0.0, y_phase=0.0, wave_len=0.5, twist_rate=0.0, # In rotations per unit distance speed=1.0, sample_resolution=0.005, stroke_width=2, offset=ORIGIN, color=None, **kwargs, ): self.axes = axes self.y_amplitude = y_amplitude self.z_amplitude = z_amplitude self.z_phase = z_phase self.y_phase = y_phase self.wave_len = wave_len self.twist_rate = twist_rate self.speed = speed self.sample_resolution = sample_resolution self.offset = offset super().__init__(**kwargs) color = color or self.get_default_color(wave_len) self.set_stroke(color, stroke_width) self.set_flat_stroke(False) self.time = 0 self.clock_is_stopped = False self.add_updater(lambda m, dt: m.update_points(dt)) def update_points(self, dt): if not self.clock_is_stopped: self.time += dt xs = np.arange( self.axes.x_axis.x_min, self.axes.x_axis.x_max, self.sample_resolution ) self.set_points_as_corners( self.offset + self.xt_to_point(xs, self.time) ) def stop_clock(self): self.clock_is_stopped = True def start_clock(self): self.clock_is_stopped = False def xt_to_yz(self, x, t): phase = TAU * t * self.speed / self.wave_len y_outs = self.y_amplitude * np.sin(TAU * x / self.wave_len - phase - self.y_phase) z_outs = self.z_amplitude * np.sin(TAU * x / self.wave_len - phase - self.z_phase) twist_angles = x * self.twist_rate * TAU y = np.cos(twist_angles) * y_outs - np.sin(twist_angles) * z_outs z = np.sin(twist_angles) * y_outs + np.cos(twist_angles) * z_outs return y, z def xt_to_point(self, x, t): y, z = self.xt_to_yz(x, t) return self.axes.c2p(x, y, z) def get_default_color(self, wave_len): return get_spectral_color(inverse_interpolate( 1.5, 0.5, wave_len )) class MeanWave(VMobject): def __init__(self, waves, **kwargs): self.waves = waves self.offset = np.array(ORIGIN) self.time = 0 super().__init__(**kwargs) self.set_flat_stroke(False) self.add_updater(lambda m, dt: m.update_points(dt)) def update_points(self, dt): for wave in self.waves: wave.update_points(dt) self.time += dt points = sum(wave.get_points() for wave in self.waves) / len(self.waves) self.set_points(points) def xt_to_yz(self, x, t): return tuple( np.array([ wave.xt_to_yz(x, t)[i] for wave in self.waves ]).mean(0) for i in (0, 1) ) class SugarCylinder(Cylinder): def __init__( self, axes, camera, radius=0.5, color=BLUE_A, opacity=0.2, shading=(0.5, 0.5, 0.5), resolution=(51, 101), ): super().__init__( color=color, opacity=opacity, resolution=resolution, shading=shading, ) self.set_width(2 * axes.z_axis.get_unit_size() * radius) self.set_depth(axes.x_axis.get_length(), stretch=True) self.rotate(PI / 2, UP) self.move_to(axes.get_origin(), LEFT) # self.set_shading(*shading) self.always_sort_to_camera(camera) class Polarizer(VGroup): def __init__( self, axes, radius=1.0, angle=0, stroke_color=GREY_C, stroke_width=2, fill_color=GREY_C, fill_opacity=0.25, n_lines=14, line_opacity=0.2, arrow_stroke_color=WHITE, arrow_stroke_width=5, ): true_radius = radius * axes.z_axis.get_unit_size() circle = Circle( radius=true_radius, stroke_color=stroke_color, stroke_width=stroke_width, fill_color=fill_color, fill_opacity=fill_opacity, ) lines = VGroup(*( Line(circle.pfp(a), circle.pfp(1 - a)) for a in np.arccos(np.linspace(1, -1, n_lines + 2)[1:-1]) / TAU )) lines.set_stroke(WHITE, 1, opacity=line_opacity) arrow = Vector( 0.5 * true_radius * UP, stroke_color=arrow_stroke_color, stroke_width=arrow_stroke_width, ) arrow.move_to(circle.get_top(), DOWN) super().__init__( circle, lines, arrow, # So the center works correctly VectorizedPoint(circle.get_bottom() + arrow.get_height() * DOWN), ) self.set_flat_stroke(True) self.rotate(PI / 2, RIGHT) self.rotate(PI / 2, IN) self.rotate(angle, RIGHT) self.rotate(1 * DEGREES, UP) class ProbagatingRings(VGroup): def __init__( self, line, n_rings=5, start_width=3, width_decay_rate=0.1, stroke_color=WHITE, growth_rate=2.0, spacing=0.2, ): ring = Circle(radius=1e-3, n_components=101) ring.set_stroke(stroke_color, start_width) ring.apply_matrix(z_to_vector(line.get_vector())) ring.move_to(line) ring.set_flat_stroke(False) super().__init__(*ring.replicate(n_rings)) self.growth_rate = growth_rate self.spacing = spacing self.width_decay_rate = width_decay_rate self.start_width = start_width self.time = 0 self.add_updater(lambda m, dt: self.update_rings(dt)) def update_rings(self, dt): if dt == 0: return self.time += dt space = 0 for ring in self.submobjects: effective_time = max(self.time - space, 0) target_radius = max(effective_time * self.growth_rate, 1e-3) ring.scale(target_radius / ring.get_radius()) space += self.spacing ring.set_stroke(width=np.exp(-self.width_decay_rate * effective_time)) return self class TwistedRibbon(ParametricSurface): def __init__( self, axes, amplitude, twist_rate, start_point=(0, 0, 0), color=WHITE, opacity=0.4, resolution=(101, 11), ): super().__init__( lambda u, v: axes.c2p( u, v * amplitude * np.sin(TAU * twist_rate * u), v * amplitude * np.cos(TAU * twist_rate * u) ), u_range=axes.x_range[:2], v_range=(-1, 1), color=color, opacity=opacity, resolution=resolution, prefered_creation_axis=0, ) self.shift(axes.c2p(*start_point) - axes.get_origin()) # For fields class ChargedParticle(Group): def __init__( self, point=ORIGIN, charge=1.0, mass=1.0, color=RED, show_sign=True, sign="+", radius=0.2, rotation=0, sign_stroke_width=2, track_position_history=True, history_size=7200, euler_steps_per_frame=10, ): self.charge = charge self.mass = mass sphere = TrueDot(radius=radius, color=color) sphere.make_3d() sphere.move_to(point) self.sphere = sphere self.track_position_history = track_position_history self.history_size = history_size self.velocity = np.zeros(3) # Only used if force are added self.euler_steps_per_frame = euler_steps_per_frame self.init_clock(point) super().__init__(sphere) if show_sign: sign = Tex(sign) sign.set_width(radius) sign.rotate(rotation, RIGHT) sign.set_stroke(WHITE, sign_stroke_width) sign.move_to(sphere) self.add(sign) self.sign = sign # Related to updaters def update(self, dt: float = 0, recurse: bool = True): super().update(dt, recurse) # Do this instead of adding an updater, because # otherwise all animations require the # suspend_mobject_updating=false flag self.increment_clock(dt) def init_clock(self, start_point): self.time = 0 self.time_step = 1 / 30 # This will be updated self.recent_positions = np.tile(start_point, 3).reshape((3, 3)) if self.track_position_history: self.position_history = np.zeros((self.history_size, 3)) self.acceleration_history = np.zeros((self.history_size, 3)) self.history_index = -1 def increment_clock(self, dt): if dt == 0: return self self.time += dt self.time_step = dt self.recent_positions[0:2] = self.recent_positions[1:3] self.recent_positions[2] = self.get_center() if self.track_position_history: self.add_to_position_history() def add_to_position_history(self): self.history_index += 1 hist_size = self.history_size # If overflowing, copy second half of history # lists to the first half, and reset index if self.history_index >= hist_size: for arr in [self.position_history, self.acceleration_history]: arr[:hist_size // 2, :] = arr[hist_size // 2:, :] self.history_index = (hist_size // 2) + 1 self.position_history[self.history_index] = self.get_center() self.acceleration_history[self.history_index] = self.get_acceleration() return self def ignore_last_motion(self): self.recent_positions[:] = self.get_center() return self def add_force(self, force_func: Callable[[Vect3], Vect3]): espf = self.euler_steps_per_frame def update_from_force(particle, dt): if dt == 0: return for _ in range(espf): acc = force_func(particle.get_center()) / self.mass self.velocity += acc * dt / espf self.shift(self.velocity * dt / espf) self.add_updater(update_from_force) return self def add_spring_force(self, k=1.0, center=None): center = center if center is not None else self.get_center().copy() self.add_force(lambda p: k * (center - p)) return self def add_field_force(self, field): charge = self.get_charge() self.add_force(lambda p: charge * field.get_forces([p])[0]) return self def fix_x(self): x = self.get_x() self.add_updater(lambda m: m.set_x(x)) # Getters def get_charge(self): return self.charge def get_radius(self): return self.sphere.get_radius() def get_internal_time(self): return self.time def scale(self, factor, *args, **kwargs): super().scale(factor, *args, **kwargs) self.sphere.set_radius(factor * self.sphere.get_radius()) return self def get_acceleration(self): p0, p1, p2 = self.recent_positions # if (p0 == p1).all() or (p1 == p2).all(): if np.isclose(p0, p1).all() or np.isclose(p1, p2).all(): # Otherwise, starts and stops have artificially # high acceleration return np.zeros(3) return (p0 + p2 - 2 * p1) / self.time_step**2 def get_info_from_delays(self, info_arr, delays): if not hasattr(self, "acceleration_history"): raise Exception("track_position_history is not turned on") if len(info_arr) == 0: return np.zeros((len(delays), 3)) pre_indices = self.history_index - delays / self.time_step indices = np.clip(pre_indices, 0, self.history_index).astype(int) return info_arr[indices] def get_past_acceleration(self, delays): return self.get_info_from_delays(self.acceleration_history, delays) def get_past_position(self, delays): return self.get_info_from_delays(self.position_history, delays) class AccelerationVector(Vector): def __init__( self, particle, stroke_color=PINK, stroke_width=4, flat_stroke=False, norm_func=lambda n: np.tanh(n), **kwargs ): self.norm_func = norm_func super().__init__( RIGHT, stroke_color=stroke_color, stroke_width=stroke_width, flat_stroke=flat_stroke, **kwargs ) self.add_updater(lambda m: m.pin_to_particle(particle)) def pin_to_particle(self, particle): a_vect = particle.get_acceleration() norm = get_norm(a_vect) if self.norm_func is not None and norm > 0: a_vect *= self.norm_func(norm) / norm center = particle.get_center() self.put_start_and_end_on(center, center + a_vect) class VectorField(VMobject): def __init__( self, func, stroke_color=BLUE, center=ORIGIN, x_density=2.0, y_density=2.0, z_density=2.0, width=14, height=8, depth=0, stroke_width: float = 2, tip_width_ratio: float = 4, tip_len_to_width: float = 0.01, max_vect_len: float | None = None, min_drawn_norm: float = 1e-2, flat_stroke=False, norm_to_opacity_func=None, norm_to_rgb_func=None, **kwargs ): self.func = func self.stroke_width = stroke_width self.tip_width_ratio = tip_width_ratio self.tip_len_to_width = tip_len_to_width self.min_drawn_norm = min_drawn_norm self.norm_to_opacity_func = norm_to_opacity_func self.norm_to_rgb_func = norm_to_rgb_func if max_vect_len is not None: self.max_vect_len = max_vect_len else: densities = np.array([x_density, y_density, z_density]) dims = np.array([width, height, depth]) self.max_vect_len = 1.0 / densities[dims > 0].mean() self.sample_points = self.get_sample_points( center, width, height, depth, x_density, y_density, z_density ) self.init_base_stroke_width_array(len(self.sample_points)) super().__init__( stroke_color=stroke_color, flat_stroke=flat_stroke, **kwargs ) n_samples = len(self.sample_points) self.set_points(np.zeros((8 * n_samples - 1, 3))) self.set_stroke(width=stroke_width) self.update_vectors() def get_sample_points( self, center: np.ndarray, width: float, height: float, depth: float, x_density: float, y_density: float, z_density: float ) -> np.ndarray: to_corner = np.array([width / 2, height / 2, depth / 2]) spacings = 1.0 / np.array([x_density, y_density, z_density]) to_corner = spacings * (to_corner / spacings).astype(int) lower_corner = center - to_corner upper_corner = center + to_corner + spacings return cartesian_product(*( np.arange(low, high, space) for low, high, space in zip(lower_corner, upper_corner, spacings) )) def init_base_stroke_width_array(self, n_sample_points): arr = np.ones(8 * n_sample_points - 1) arr[4::8] = self.tip_width_ratio arr[5::8] = self.tip_width_ratio * 0.5 arr[6::8] = 0 arr[7::8] = 0 self.base_stroke_width_array = arr def set_stroke(self, color=None, width=None, opacity=None, background=None, recurse=True): super().set_stroke(color, None, opacity, background, recurse) if width is not None: self.set_stroke_width(float(width)) return self def set_stroke_width(self, width: float): if self.get_num_points() > 0: self.get_stroke_widths()[:] = width * self.base_stroke_width_array self.stroke_width = width return self def update_vectors(self): tip_width = self.tip_width_ratio * self.stroke_width tip_len = self.tip_len_to_width * tip_width samples = self.sample_points # Get raw outputs and lengths outputs = self.func(samples) norms = np.linalg.norm(outputs, axis=1)[:, np.newaxis] # How long should the arrows be drawn? max_len = self.max_vect_len if max_len < np.inf: drawn_norms = max_len * np.tanh(norms / max_len) else: drawn_norms = norms # What's the distance from the base of an arrow to # the base of its head? dist_to_head_base = np.clip(drawn_norms - tip_len, 0, np.inf) # Set all points unit_outputs = np.zeros_like(outputs) np.true_divide(outputs, norms, out=unit_outputs, where=(norms > self.min_drawn_norm)) points = self.get_points() points[0::8] = samples points[2::8] = samples + dist_to_head_base * unit_outputs points[4::8] = points[2::8] points[6::8] = samples + drawn_norms * unit_outputs for i in (1, 3, 5): points[i::8] = 0.5 * (points[i - 1::8] + points[i + 1::8]) points[7::8] = points[6:-1:8] # Adjust stroke widths width_arr = self.stroke_width * self.base_stroke_width_array width_scalars = np.clip(drawn_norms / tip_len, 0, 1) width_scalars = np.repeat(width_scalars, 8)[:-1] self.get_stroke_widths()[:] = width_scalars * width_arr # Potentially adjust opacity and color if self.norm_to_opacity_func is not None: self.get_stroke_opacities()[:] = self.norm_to_opacity_func( np.repeat(norms, 8)[:-1] ) if self.norm_to_rgb_func is not None: self.get_stroke_colors() self.data['stroke_rgba'][:, :3] = self.norm_to_rgb_func( np.repeat(norms, 8)[:-1] ) self.note_changed_data() return self class TimeVaryingVectorField(VectorField): def __init__( self, # Takes in an array of points and a float for time time_func, **kwargs ): self.time = 0 super().__init__(func=lambda p: time_func(p, self.time), **kwargs) self.add_updater(lambda m, dt: m.increment_time(dt)) always(self.update_vectors) def increment_time(self, dt): self.time += dt class ChargeBasedVectorField(VectorField): default_color = BLUE def __init__(self, *charges, **kwargs): self.charges = list(charges) super().__init__( self.get_forces, color=kwargs.pop("color", self.default_color), **kwargs ) self.add_updater(lambda m: m.update_vectors()) def get_forces(self, points): # To be implemented in subclasses return np.zeros_like(points) class CoulombField(ChargeBasedVectorField): default_color = YELLOW def get_forces(self, points): return sum( coulomb_force(points, charge) for charge in self.charges ) class LorentzField(ChargeBasedVectorField): def __init__( self, *charges, radius_of_suppression=None, c=2.0, **kwargs ): self.radius_of_suppression = radius_of_suppression self.c = c super().__init__(*charges, **kwargs) def get_forces(self, points): return sum( lorentz_force( points, charge, radius=self.radius_of_suppression, c=self.c ) for charge in self.charges ) class ColoumbPlusLorentzField(LorentzField): def get_forces(self, points): return sum( lorentz_force( points, charge, radius=self.radius_of_suppression, c=self.c ) + sum( coulomb_force(points, charge) for charge in self.charges ) for charge in self.charges ) class GraphAsVectorField(VectorField): def __init__( self, axes: Axes | ThreeDAxes, # Maps x to y, or x to (y, z) graph_func: Callable[[VectN], VectN] | Callable[[VectN], Tuple[VectN, VectN]], x_density=10.0, max_vect_len=np.inf, **kwargs, ): self.sample_xs = np.arange(axes.x_axis.x_min, axes.x_axis.x_max, 1.0 / x_density) self.axes = axes def vector_func(points): output = graph_func(self.sample_xs) if isinstance(axes, ThreeDAxes): graph_points = axes.c2p(self.sample_xs, *output) else: graph_points = axes.c2p(self.sample_xs, output) base_points = axes.x_axis.n2p(self.sample_xs) return graph_points - base_points super().__init__( func=vector_func, max_vect_len=max_vect_len, **kwargs ) always(self.update_vectors) def reset_sample_points(self): self.sample_points = self.get_sample_points() def get_sample_points(self, *args, **kwargs): # Override super class and ignore all length/density information return self.axes.x_axis.n2p(self.sample_xs) class OscillatingFieldWave(GraphAsVectorField): def __init__(self, axes, wave, **kwargs): self.wave = wave if "stroke_color" not in kwargs: kwargs["stroke_color"] = wave.get_color() super().__init__( axes=axes, graph_func=lambda x: wave.xt_to_yz(x, wave.time), **kwargs ) def get_sample_points(self, *args, **kwargs): # Override super class and ignore all length/density information return self.wave.offset + self.axes.x_axis.n2p(self.sample_xs) # Structure class Molecule(Group): # List of characters atoms = [] # List of 3d coordinates coordinates = np.zeros((0, 3)) # List of pairs of indices bonds = [] atom_to_color = { "H": WHITE, "O": RED, "C": GREY, } atom_to_radius = { "H": 0.1, "O": 0.2, "C": 0.19, } ball_config = dict(shading=(0.25, 0.5, 0.5), glow_factor=0.25) stick_config = dict(stroke_width=1, stroke_color=GREY_A, flat_stroke=False) def __init__(self, height=2.0, **kwargs): coords = np.array(self.coordinates) radii = np.array([self.atom_to_radius[atom] for atom in self.atoms]) rgbas = np.array([color_to_rgba(self.atom_to_color[atom]) for atom in self.atoms]) balls = DotCloud(coords, **self.ball_config) balls.set_radii(radii) balls.set_rgba_array(rgbas) sticks = VGroup() for i, j in self.bonds: c1, c2 = coords[[i, j], :] r1, r2 = radii[[i, j]] unit_vect = normalize(c2 - c1) sticks.add(Line( c1 + r1 * unit_vect, c2 - r2 * unit_vect, **self.stick_config )) super().__init__(balls, sticks, **kwargs) self.apply_depth_test() self.balls = balls self.sticks = sticks self.set_height(height) class Sucrose(Molecule): atoms = [ "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H", ] coordinates = np.array([ [-1.468 , 0.4385, -0.9184], [-0.6033, -0.8919, 0.8122], [ 0.9285, 0.4834, -0.3053], [-3.0702, -2.0054, 1.1933], [-4.62 , 0.6319, 0.7326], [ 1.2231, 0.2156, 2.5658], [ 3.6108, -1.7286, 0.6379], [ 3.15 , 1.8347, 1.1537], [-1.9582, -1.848 , -2.43 ], [-1.3845, 3.245 , -0.8933], [ 3.8369, 0.2057, -2.5044], [-1.4947, -0.8632, -0.3037], [-2.9301, -1.0229, 0.1866], [-3.229 , 0.3737, 0.6887], [-2.5505, 1.2243, -0.3791], [ 0.7534, -0.7453, 0.3971], [ 1.6462, -0.7853, 1.639 ], [ 3.1147, -0.5553, 1.2746], [ 3.2915, 0.6577, 0.3521], [ 2.2579, 0.7203, -0.7858], [-1.0903, -1.9271, -1.3122], [-2.0027, 2.5323, 0.1653], [ 2.5886, -0.1903, -1.9666], [-3.6217, -1.2732, -0.6273], [-2.8148, 0.5301, 1.6917], [-3.2289, 1.4361, -1.215 ], [ 1.0588, -1.5992, -0.2109], [ 1.5257, -1.753 , 2.1409], [ 3.6908, -0.4029, 2.1956], [ 4.31 , 0.675 , -0.0511], [ 2.2441, 1.7505, -1.1644], [-1.1311, -2.9324, -0.8803], [-0.0995, -1.7686, -1.74 ], [-1.2448, 2.3605, 0.9369], [-2.799 , 3.1543, 0.5841], [ 1.821 , -0.1132, -2.7443], [ 2.6532, -1.2446, -1.6891], [-3.98 , -1.9485, 1.5318], [-4.7364, 1.5664, 0.9746], [ 0.2787, 0.0666, 2.7433], [ 4.549 , -1.5769, 0.4327], [ 3.3427, 2.6011, 0.5871], [-1.6962, -2.5508, -3.0488], [-0.679 , 2.6806, -1.2535], [ 3.7489, 1.1234, -2.8135], ]) bonds = [ (0, 11), (0, 14), (1, 11), (1, 15), (2, 15), (2, 19), (3, 12), (3, 37), (4, 13), (4, 38), (5, 16), (5, 39), (6, 17), (6, 40), (7, 18), (7, 41), (8, 20), (8, 42), (9, 21), (9, 43), (10, 22), (10, 44), (11, 12), (11, 20), (12, 13), (12, 23), (13, 14), (13, 24), (14, 21), (14, 25), (15, 16), (15, 26), (16, 17), (16, 27), (17, 18), (17, 28), (18, 19), (18, 29), (19, 22), (19, 30), (20, 31), (20, 32), (21, 33), (21, 34), (22, 35), (22, 36), ] class Carbonate(Molecule): # List of characters atoms = ["O", "O", "O", "C", "H", "H"] # List of 3d coordinates coordinates = np.array([ [-6.9540e-01, -1.1061e+00, 0.0000e+00], [-6.9490e-01, 1.1064e+00, 0.0000e+00], [ 1.3055e+00, -3.0000e-04, 1.0000e-04], [ 8.4700e-02, 0.0000e+00, -1.0000e-04], [-1.6350e-01, -1.9304e+00, 1.0000e-04], [-1.6270e-01, 1.9305e+00, 1.0000e-04], ]) # List of pairs of indices bonds = [(0, 3), (0, 4), (1, 3), (1, 5), (2, 3)] bond_types = [1, 1, 1, 1, 2] class Calcite(Molecule): atoms = [ "C", "C", "Ca", "C", "O", "O", "C", "Ca", "C", "O", "O", "O", "Ca", "C", "O", "O", "C", "Ca", "C", "O", "C", "Ca", "C", "O", "O", "O", "Ca", "Ca", "C", "O", "O", "O", "O", "O", "O", "Ca", "C", "O", "O", "C", "Ca", "C", "O", "O", "O", "Ca", "Ca", "C", "O", "O", "O", "O", "O", "O", "Ca", "C", "O", "O", "O", "Ca", "Ca", "C", "O", "O", "O", "O", "O", "Ca", "C", "O", "O", "O", "C", "C", "Ca", "C", "O", "O", "O", "Ca", "Ca", "C", "O", "O", "O", "C", "Ca", "C", "O", "O", "O", "Ca", "Ca", "C", "O", "O", "O", "O", "O", "O", "Ca", "C", "O", "O", "O", "Ca", "C", "O", "O", "Ca", "Ca", "C", "O", "O", "O", "O", "O", "O", "Ca", "C", "O", "O", "O", "Ca", "C", "O", "O", "O", "Ca", "C", "O", "Ca", "C", "O", "O", "Ca", "Ca", "C", "O", "O", "O", "O", "O", "O", "Ca", "C", "O", "O", "Ca", "C", "O", "O", "Ca", "Ca", "C", "O", "O", "O", "O", "O", "O", "Ca", "C", "O", "O", "O", "Ca", "Ca", "C", "O", "O", "O", "O", "O", "Ca", "C", "O", "O", "O", "O", "O", "O", ] atom_to_color = { "Ca": GREEN, "O": RED, "C": GREY, } atom_to_radius = { "Ca": 0.25, "O": 0.2, "C": 0.19, } coordinates = np.array([ [-1.43769337, -2.49015797, 1.41822405], [-1.43769337, 2.49015797, 1.41822405], [-2.87538675, .00000000, 2.83644809], [-2.87538675, .00000000, 7.09112022], [-2.48577184, 1.88504958, 1.41822404], [-1.43769337, -1.27994119, 1.41822404], [-1.43769337, 7.47047390, 1.41822405], [-2.87538675, 4.98031594, 2.83644809], [-2.87538675, 4.98031594, 7.09112022], [-2.48577184, 6.86536552, 1.41822404], [-1.43769337, 3.70037474, 1.41822404], [-2.87538675, 1.21021677, 7.09112022], [-2.87538675, 9.96063187, 2.83644809], [-2.87538675, 9.96063187, 7.09112022], [-1.43769337, 8.68069068, 1.41822404], [-2.87538675, 6.19053271, 7.09112022], [ 2.87538675, .00000000, 1.41822405], [ 1.43769337, -2.49015797, 2.83644809], [ 1.43769337, -2.49015797, 7.09112022], [ 1.82730828, -.60510839, 1.41822404], [ 2.87538675, 4.98031594, 1.41822405], [ 1.43769337, 2.49015797, 2.83644809], [ 1.43769337, 2.49015797, 7.09112022], [ -.38961490, 1.88504958, 1.41822404], [ 1.82730828, 4.37520755, 1.41822404], [ 2.87538675, 1.21021677, 1.41822404], [ .00000000, .00000000, .00000000], [ .00000000, .00000000, 8.50934427], [ .00000000, .00000000, 4.25467213], [-1.04807847, .60510839, 4.25467213], [ 1.04807847, .60510839, 4.25467213], [ .00000000, -1.21021677, 4.25467213], [-1.82730828, -.60510839, 7.09112022], [ .38961490, 1.88504958, 7.09112022], [ 1.43769337, -1.27994119, 7.09112022], [-1.43769337, -2.49015797, 5.67289618], [-1.43769337, -2.49015797, 9.92756831], [-2.48577184, -1.88504958, 9.92756831], [ -.38961490, -1.88504958, 9.92756831], [ 2.87538675, 9.96063187, 1.41822405], [ 1.43769337, 7.47047390, 2.83644809], [ 1.43769337, 7.47047390, 7.09112022], [ -.38961490, 6.86536552, 1.41822404], [ 1.82730828, 9.35552349, 1.41822404], [ 2.87538675, 6.19053271, 1.41822404], [ .00000000, 4.98031594, .00000000], [ .00000000, 4.98031594, 8.50934427], [ .00000000, 4.98031594, 4.25467213], [-1.04807847, 5.58542432, 4.25467213], [ 1.04807847, 5.58542432, 4.25467213], [ .00000000, 3.77009916, 4.25467213], [-1.82730828, 4.37520755, 7.09112022], [ .38961490, 6.86536552, 7.09112022], [ 1.43769337, 3.70037474, 7.09112022], [-1.43769337, 2.49015797, 5.67289618], [-1.43769337, 2.49015797, 9.92756831], [-2.48577184, 3.09526635, 9.92756831], [ -.38961490, 3.09526635, 9.92756831], [-1.43769337, 1.27994120, 9.92756831], [ .00000000, 9.96063187, .00000000], [ .00000000, 9.96063187, 8.50934427], [ .00000000, 9.96063187, 4.25467213], [-1.04807847, 10.56574026, 4.25467213], [ 1.04807847, 10.56574026, 4.25467213], [ .00000000, 8.75041510, 4.25467213], [-1.82730828, 9.35552349, 7.09112022], [ 1.43769337, 8.68069068, 7.09112022], [-1.43769337, 7.47047390, 5.67289618], [-1.43769337, 7.47047390, 9.92756831], [-2.48577184, 8.07558229, 9.92756831], [ -.38961490, 8.07558229, 9.92756831], [-1.43769337, 6.26025713, 9.92756831], [ 7.18846687, -2.49015797, 1.41822405], [ 7.18846687, 2.49015797, 1.41822405], [ 5.75077349, .00000000, 2.83644809], [ 5.75077349, .00000000, 7.09112022], [ 3.92346522, -.60510839, 1.41822404], [ 6.14038840, 1.88504958, 1.41822404], [ 7.18846687, -1.27994119, 1.41822404], [ 4.31308012, -2.49015797, .00000000], [ 4.31308012, -2.49015797, 8.50934427], [ 4.31308012, -2.49015797, 4.25467213], [ 3.26500165, -1.88504958, 4.25467213], [ 5.36115859, -1.88504958, 4.25467213], [ 4.70269502, -.60510839, 7.09112022], [ 7.18846687, 7.47047390, 1.41822405], [ 5.75077349, 4.98031594, 2.83644809], [ 5.75077349, 4.98031594, 7.09112022], [ 3.92346522, 4.37520755, 1.41822404], [ 6.14038840, 6.86536552, 1.41822404], [ 7.18846687, 3.70037474, 1.41822404], [ 4.31308012, 2.49015797, .00000000], [ 4.31308012, 2.49015797, 8.50934427], [ 4.31308012, 2.49015797, 4.25467213], [ 3.26500165, 3.09526635, 4.25467213], [ 5.36115859, 3.09526635, 4.25467213], [ 4.31308012, 1.27994120, 4.25467213], [ 2.48577184, 1.88504958, 7.09112022], [ 4.70269502, 4.37520755, 7.09112022], [ 5.75077349, 1.21021677, 7.09112022], [ 2.87538675, .00000000, 5.67289618], [ 2.87538675, .00000000, 9.92756831], [ 1.82730828, .60510839, 9.92756831], [ 3.92346522, .60510839, 9.92756831], [ 2.87538675, -1.21021677, 9.92756831], [ 5.75077349, 9.96063187, 2.83644809], [ 5.75077349, 9.96063187, 7.09112022], [ 3.92346522, 9.35552349, 1.41822404], [ 7.18846687, 8.68069068, 1.41822404], [ 4.31308012, 7.47047390, .00000000], [ 4.31308012, 7.47047390, 8.50934427], [ 4.31308012, 7.47047390, 4.25467213], [ 3.26500165, 8.07558229, 4.25467213], [ 5.36115859, 8.07558229, 4.25467213], [ 4.31308012, 6.26025713, 4.25467213], [ 2.48577184, 6.86536552, 7.09112022], [ 4.70269502, 9.35552349, 7.09112022], [ 5.75077349, 6.19053271, 7.09112022], [ 2.87538675, 4.98031594, 5.67289618], [ 2.87538675, 4.98031594, 9.92756831], [ 1.82730828, 5.58542432, 9.92756831], [ 3.92346522, 5.58542432, 9.92756831], [ 2.87538675, 3.77009916, 9.92756831], [ 2.87538675, 9.96063187, 5.67289618], [ 2.87538675, 9.96063187, 9.92756831], [ 1.82730828, 10.56574026, 9.92756831], [ 3.92346522, 10.56574026, 9.92756831], [ 2.87538675, 8.75041510, 9.92756831], [10.06385361, -2.49015797, 2.83644809], [10.06385361, -2.49015797, 7.09112022], [10.45346852, -.60510839, 1.41822404], [10.06385361, 2.49015797, 2.83644809], [10.06385361, 2.49015797, 7.09112022], [ 8.23654533, 1.88504958, 1.41822404], [10.45346852, 4.37520755, 1.41822404], [ 8.62616024, .00000000, .00000000], [ 8.62616024, .00000000, 8.50934427], [ 8.62616024, .00000000, 4.25467213], [ 7.57808177, .60510839, 4.25467213], [ 9.67423871, .60510839, 4.25467213], [ 8.62616024, -1.21021677, 4.25467213], [ 6.79885196, -.60510839, 7.09112022], [ 9.01577514, 1.88504958, 7.09112022], [10.06385361, -1.27994119, 7.09112022], [ 7.18846687, -2.49015797, 5.67289618], [ 7.18846687, -2.49015797, 9.92756831], [ 6.14038840, -1.88504958, 9.92756831], [ 8.23654533, -1.88504958, 9.92756831], [10.06385361, 7.47047390, 2.83644809], [10.06385361, 7.47047390, 7.09112022], [ 8.23654533, 6.86536552, 1.41822404], [10.45346852, 9.35552349, 1.41822404], [ 8.62616024, 4.98031594, .00000000], [ 8.62616024, 4.98031594, 8.50934427], [ 8.62616024, 4.98031594, 4.25467213], [ 7.57808177, 5.58542432, 4.25467213], [ 9.67423871, 5.58542432, 4.25467213], [ 8.62616024, 3.77009916, 4.25467213], [ 6.79885196, 4.37520755, 7.09112022], [ 9.01577514, 6.86536552, 7.09112022], [10.06385361, 3.70037474, 7.09112022], [ 7.18846687, 2.49015797, 5.67289618], [ 7.18846687, 2.49015797, 9.92756831], [ 6.14038840, 3.09526635, 9.92756831], [ 8.23654533, 3.09526635, 9.92756831], [ 7.18846687, 1.27994120, 9.92756831], [ 8.62616024, 9.96063187, .00000000], [ 8.62616024, 9.96063187, 8.50934427], [ 8.62616024, 9.96063187, 4.25467213], [ 7.57808177, 10.56574026, 4.25467213], [ 9.67423871, 10.56574026, 4.25467213], [ 8.62616024, 8.75041510, 4.25467213], [ 6.79885196, 9.35552349, 7.09112022], [10.06385361, 8.68069068, 7.09112022], [ 7.18846687, 7.47047390, 5.67289618], [ 7.18846687, 7.47047390, 9.92756831], [ 6.14038840, 8.07558229, 9.92756831], [ 8.23654533, 8.07558229, 9.92756831], [ 7.18846687, 6.26025713, 9.92756831], [10.45346852, .60510839, 9.92756831], [10.45346852, 5.58542432, 9.92756831], [10.45346852, 10.56574026, 9.92756831], ])
from manim_imports_ext import * from _2023.barber_pole.objects import * # Scenes class SimpleLightBeam(InteractiveScene): default_frame_orientation = (-33, 85) axes_config = dict() z_amplitude = 0.5 wave_len = 2.0 speed = 1.0 color = YELLOW oscillating_field_config = dict( stroke_opacity=0.5, stroke_width=2, tip_width_ratio=1 ) def construct(self): axes, plane = get_axes_and_plane(**self.axes_config) self.add(axes, plane) # Introduce wave wave = OscillatingWave( axes, z_amplitude=self.z_amplitude, wave_len=self.wave_len, speed=self.speed, color=self.color ) vect_wave = OscillatingFieldWave(axes, wave, **self.oscillating_field_config) def update_wave(wave): st = self.time * self.speed # Suppressor threshold points = wave.get_points().copy() xs = axes.x_axis.p2n(points) suppressors = np.clip(smooth(st - xs), 0, 1) points[:, 1] *= suppressors points[:, 2] *= suppressors wave.set_points(points) return wave wave.add_updater(update_wave) vect_wave.add_updater(update_wave) self.add(wave) self.play( self.frame.animate.reorient(-98, 77, 0).move_to([-0.87, 0.9, -0.43]), run_time=8, ) self.add(vect_wave, wave) self.play( VFadeIn(vect_wave), self.frame.animate.reorient(-10, 77, 0).move_to([-0.87, 0.9, -0.43]), run_time=4 ) self.wait(3) # Label directions z_label = Tex("z") z_label.rotate(PI / 2, RIGHT) z_label.next_to(axes.z_axis, OUT) y_label = Tex("y") y_label.rotate(PI / 2, RIGHT) y_label.next_to(axes.y_axis, UP + OUT) x_label = VGroup( TexText("$x$-direction"), Vector(RIGHT, stroke_color=WHITE), ) x_label.arrange(RIGHT) x_label.set_flat_stroke(False) x_label.rotate(PI / 2, RIGHT) x_label.next_to(z_label, RIGHT, buff=2.0) x_label.match_z(axes.c2p(0, 0, 0.75)) self.play( FadeIn(z_label, 0.5 * OUT), FadeIn(y_label, 0.5 * UP), ) self.wait(3) self.play( Write(x_label[0]), GrowArrow(x_label[1]), ) self.play( self.frame.animate.reorient(-41, 77, 0).move_to([-0.87, 0.9, -0.43]), run_time=12, ) self.wait(6) class TwistingLightBeam(SimpleLightBeam): z_amplitude = 0.5 wave_len = 2.0 twist_rate = 1 / 72 speed = 1.0 color = YELLOW def construct(self): # Axes axes, plane = get_axes_and_plane(**self.axes_config) self.add(axes, plane) # Add wave wave = OscillatingWave( axes, z_amplitude=self.z_amplitude, wave_len=self.wave_len, speed=self.speed, color=self.color ) vect_wave = OscillatingFieldWave(axes, wave, **self.oscillating_field_config) twist_rate_tracker = ValueTracker(0) def update_twist_rate(wave): wave.twist_rate = twist_rate_tracker.get_value() return wave wave.add_updater(update_twist_rate) cylinder = SugarCylinder(axes, self.camera, radius=self.z_amplitude) self.add(vect_wave, wave) self.frame.reorient(-41, 77, 0).move_to([-0.87, 0.9, -0.43]) self.wait(4) cylinder.save_state() cylinder.stretch(0, 0, about_edge=RIGHT) self.play( Restore(cylinder, time_span=(0, 3)), twist_rate_tracker.animate.set_value(self.twist_rate).set_anim_args(time_span=(0, 3)), self.frame.animate.reorient(-47, 80, 0).move_to([0.06, -0.05, 0.05]).set_height(8.84), run_time=6, ) self.wait(2) self.play( self.frame.animate.reorient(-130, 77, 0).move_to([0.35, -0.36, 0.05]), run_time=10, ) self.wait() self.play( self.frame.animate.reorient(-57, 77, 0).move_to([0.35, -0.36, 0.05]), run_time=10, ) # Add rod with oscillating ball x_tracker, plane, rod, ball, x_label = self.get_slice_group(axes, wave) plane.save_state() plane.stretch(0, 2, about_edge=OUT) frame_anim = self.frame.animate.reorient(-45, 79, 0) frame_anim.move_to([0.63, 0.47, -0.25]) frame_anim.set_height(10.51) frame_anim.set_anim_args(run_time=3) self.add(rod, ball, plane, cylinder) self.play( frame_anim, FadeIn(rod), Restore(plane), FadeIn(x_label), UpdateFromAlphaFunc(wave, lambda m, a: m.set_stroke( width=interpolate(2, 1, a), opacity=interpolate(1, 0.5, a), ), run_time=3, time_span=(0, 2), ), UpdateFromAlphaFunc(ball, lambda m, a: m.set_opacity(a)), ) self.wait(9) # Show twist down the line of the cylinder x_tracker.set_value(0) x_tracker.clear_updaters() x_tracker.add_updater(lambda m, dt: m.increment_value(0.5 * dt)) self.add(x_tracker) self.wait(5) self.play( self.frame.animate.reorient(-87, 88, 0).move_to([0.63, 0.47, -0.25]).set_height(10.51), run_time=5, ) self.wait(3) self.play( self.frame.animate.reorient(-43, 78, 0).move_to([0.63, 0.47, -0.25]).set_height(10.51), run_time=5 ) self.play( self.frame.animate.reorient(-34, 80, 0).move_to([1.61, -0.05, 0.3]).set_height(10.30), run_time=15, ) self.wait(10) def get_slice_group(self, axes, wave): x_tracker = ValueTracker(0) get_x = x_tracker.get_value rod = self.get_polarization_rod(axes, wave, get_x) ball = self.get_wave_ball(wave, get_x) plane = self.get_slice_plane(axes, get_x) x_label = self.get_plane_label(axes, plane) return Group(x_tracker, plane, rod, ball, x_label) def get_polarization_rod(self, axes, wave, get_x, stroke_color=None, length_mult=2.0, stroke_width=3): rod = Line(IN, OUT) rod.set_stroke( color=stroke_color or wave.get_stroke_color(), width=stroke_width, ) rod.set_flat_stroke(False) wave_z = axes.z_axis.p2n(wave.get_center()) wave_y = axes.y_axis.p2n(wave.get_center()) def update_rod(rod): x = get_x() rod.put_start_and_end_on( axes.c2p(x, wave_y, wave_z - length_mult * wave.z_amplitude), axes.c2p(x, wave_y, wave_z + length_mult * wave.z_amplitude), ) rod.rotate(TAU * wave.twist_rate * x, RIGHT) return rod rod.add_updater(update_rod) return rod def get_wave_ball(self, wave, get_x, radius=0.075): ball = TrueDot(radius=radius) ball.make_3d() ball.set_color(wave.get_color()) def update_ball(ball): ball.move_to(wave.offset + wave.xt_to_point(get_x(), wave.time)) return ball ball.add_updater(update_ball) return ball def get_slice_plane(self, axes, get_x): plane = Square(side_length=axes.z_axis.get_length()) plane.set_fill(BLUE, 0.25) plane.set_stroke(width=0) circle = Circle( radius=axes.z_axis.get_unit_size() * self.z_amplitude, n_components=100, ) circle.set_flat_stroke(False) circle.set_stroke(BLACK, 1) plane.add(circle) plane.rotate(PI / 2, UP) plane.add_updater(lambda m: m.move_to(axes.c2p(get_x(), 0, 0))) return plane def get_plane_label(self, axes, plane, font_size=24, color=GREY_B): x_label = Tex("x = 0.00", font_size=font_size) x_label.set_fill(color) x_label.value_mob = x_label.make_number_changable("0.00") x_label.rotate(PI / 2, RIGHT) x_label.rotate(PI / 2, IN) def update_x_label(x_label): x_value = x_label.value_mob x_value.set_value(axes.x_axis.p2n(plane.get_center())) x_value.rotate(PI / 2, RIGHT) x_value.rotate(PI / 2, IN) x_value.next_to(x_label[1], DOWN, SMALL_BUFF) x_label.next_to(plane, OUT) return x_label x_label.add_updater(update_x_label) return x_label class TwistingBlueLightBeam(TwistingLightBeam): wave_len = 1.0 twist_rate = 1 / 48 color = PURPLE class TwistingRedLightBeam(TwistingLightBeam): wave_len = 3.0 twist_rate = 1 / 96 color = RED class TwistingWithinCylinder(InteractiveScene): default_frame_orientation = (-40, 80) n_lines = 11 pause_down_the_tube = True def construct(self): # Reference objects frame = self.frame axes, plane = get_axes_and_plane( x_range=(0, 8), y_range=(-2, 2), z_range=(-2, 2), y_unit=1, z_unit=1, origin_point=3 * LEFT ) cylinder = SugarCylinder(axes, self.camera, radius=0.5) self.add(plane, axes) self.add(cylinder) # Light lines lines = VGroup() colors = get_spectral_colors(self.n_lines) for color in colors: line = Line(ORIGIN, 0.95 * OUT) line.set_flat_stroke(False) line.set_stroke(color, 2) lines.add(line) lines.arrange(DOWN, buff=0.1) lines.move_to(cylinder.get_left()) # Add polarizer to the start light = GlowDot(color=WHITE, radius=3) light.move_to(axes.c2p(-3, 0, 0)) polarizer = Polarizer(axes, radius=0.6) polarizer.move_to(axes.c2p(-1, 0, 0)) polarizer_label = Text("Linear polarizer", font_size=36) polarizer_label.rotate(PI / 2, RIGHT) polarizer_label.rotate(PI / 2, IN) polarizer_label.next_to(polarizer, OUT) frame.reorient(-153, 79, 0) frame.shift(1.0 * IN) self.play(GrowFromCenter(light)) self.play( Write(polarizer_label), FadeIn(polarizer, IN), light.animate.shift(LEFT).set_anim_args(time_span=(1, 3)), self.frame.animate.reorient(-104, 77, 0).center().set_anim_args(run_time=3), ) # Many waves waves = VGroup(*( OscillatingWave( axes, z_amplitude=0.3, wave_len=wave_len, color=line.get_color(), offset=LEFT + line.get_y() * UP ) for line, wave_len in zip( lines, np.linspace(2.0, 0.5, len(lines)) ) )) waves.set_stroke(width=1) superposition = MeanWave(waves) superposition.set_stroke(WHITE, 2) superposition.add_updater(lambda m: m.stretch(4, 2, about_point=ORIGIN)) self.play( VFadeIn(superposition), FadeOut(cylinder), ) self.play( self.frame.animate.reorient(-66, 76, 0), light.animate.scale(0.25), run_time=10, ) self.remove(superposition) superposition.suspend_updating() self.play(*( TransformFromCopy(superposition, wave, run_time=2) for wave in waves )) # Go through individual waves self.add(waves) for wave1 in waves: anims = [] for wave2 in waves: wave2.current_opacity = wave2.get_stroke_opacity() if wave1 is wave2: wave2.target_opacity = 1 else: wave2.target_opacity = 0.1 anims.append(UpdateFromAlphaFunc(wave2, lambda m, a: m.set_stroke( opacity=interpolate(m.current_opacity, m.target_opacity, a) ))) self.play(*anims, run_time=0.5) self.wait() for wave in waves: wave.current_opacity = wave.get_stroke_opacity() wave.target_opacity = 1 self.play( *( UpdateFromAlphaFunc(wave, lambda m, a: m.set_stroke( opacity=interpolate(m.current_opacity, m.target_opacity, a) )) for wave in waves ), frame.animate.reorient(-55, 76, 0).move_to([-0.09, 0.13, -0.17]).set_height(7.5), run_time=3 ) # Introduce lines white_lines = lines.copy() white_lines.set_stroke(WHITE) white_lines.arrange(UP, buff=0) white_lines.move_to(axes.get_origin()) plane = Square(side_length=2 * axes.z_axis.get_unit_size()) plane.set_fill(WHITE, 0.25) plane.set_stroke(width=0) plane.add( Circle(radius=0.5 * cylinder.get_depth(), n_components=100).set_stroke(BLACK, 1) ) plane.rotate(PI / 2, UP) plane.move_to(axes.get_origin()) plane.save_state() plane.stretch(0, 2, about_edge=UP) self.play( ReplacementTransform(waves, lines, lag_ratio=0.1, run_time=3), frame.animate.reorient(-61, 83, 0).move_to([0.03, -0.16, -0.28]).set_height(7).set_anim_args(run_time=2), Restore(plane), FadeIn(cylinder), ) self.add(axes, lines) self.wait() self.play( lines.animate.arrange(UP, buff=0).move_to(axes.get_origin()), FadeIn(white_lines), FadeOut(polarizer), FadeOut(polarizer_label), FadeOut(light), ) self.wait() # Enable lines to twist through the tube line_start, line_end = white_lines[0].get_start_and_end() distance_tracker = ValueTracker(0) wave_lengths = np.linspace(700, 400, self.n_lines) # Is this right? for line, wave_length in zip(lines, wave_lengths): line.wave_length = wave_length def update_lines(lines): dist = distance_tracker.get_value() for line in lines: line.set_points_as_corners([line_start, line_end]) line.rotate(get_twist(line.wave_length, dist), RIGHT) line.move_to(axes.c2p(dist, 0, 0)) line.set_gloss(3 * np.exp(-3 * dist)) lines.add_updater(update_lines) # Add wave trails trails = VGroup(*( self.get_wave_trail(line) for line in lines )) continuous_trails = Group(*( self.get_continuous_wave_trail(axes, line) for line in lines )) for trail in continuous_trails: x_unit = axes.x_axis.get_unit_size() x0 = axes.get_origin()[0] trail.add_updater( lambda t: t.set_clip_plane(LEFT, distance_tracker.get_value() + x0) ) self.add(trails, lines, white_lines) # Move light beams down the pole self.add(distance_tracker) distance_tracker.set_value(0) plane.add_updater(lambda m: m.match_x(lines)) self.remove(white_lines) if self.pause_down_the_tube: # Test self.play( self.frame.animate.reorient(-42, 76, 0).move_to([0.03, -0.16, -0.28]).set_height(7.00), distance_tracker.animate.set_value(4), run_time=6, rate_func=linear, ) trails.suspend_updating() self.play( self.frame.animate.reorient(67, 77, 0).move_to([-0.31, 0.48, -0.33]).set_height(4.05), run_time=3, ) self.wait(2) trails.resume_updating() self.play( distance_tracker.animate.set_value(axes.x_axis.x_max), self.frame.animate.reorient(-36, 79, 0).move_to([-0.07, 0.06, 0.06]).set_height(7.42), run_time=6, rate_func=linear, ) trails.clear_updaters() self.play( self.frame.animate.reorient(-10, 77, 0).move_to([0.42, -0.16, -0.03]).set_height(5.20), trails.animate.set_stroke(width=3, opacity=0.25).set_anim_args(time_span=(0, 3)), run_time=10, ) else: self.play( self.frame.animate.reorient(-63, 84, 0).move_to([1.04, -1.86, 0.55]).set_height(1.39), distance_tracker.animate.set_value(axes.x_axis.x_max), run_time=15, rate_func=linear, ) trails.clear_updaters() lines.clear_updaters() self.play( self.frame.animate.reorient(64, 81, 0).move_to([3.15, 0.46, -0.03]).set_height(5), run_time=3, ) self.wait() # Add polarizer at the end end_polarizer = Polarizer(axes, radius=0.6) end_polarizer.next_to(lines, RIGHT, buff=0.5) self.play( FadeIn(end_polarizer, OUT), FadeOut(plane), self.frame.animate.reorient(54, 78, 0).move_to([3.15, 0.46, -0.03]).set_height(5.00).set_anim_args(run_time=4) ) end_polarizer.save_state() self.play(end_polarizer.animate.fade(0.8)) # Show a few different frequencies vertical_components = VGroup() for index in range(len(lines)): lines.generate_target() trails.generate_target() lines.target.set_opacity(0) trails.target.set_opacity(0) lines.target[index].set_opacity(1) trails.target[index].set_opacity(0.2) line = lines[index] x = float(axes.x_axis.p2n(cylinder.get_right())) vcomp = line.copy().set_opacity(1) vcomp.stretch(0, 1) vcomp.move_to(axes.c2p(x, -2 + index / len(lines), 0)) z = float(axes.z_axis.p2n(vcomp.get_zenith())) y_min, y_max = axes.y_range[:2] globals().update(locals()) dashed_lines = VGroup(*( DashedLine(axes.c2p(x, y_min, u * z), axes.c2p(x, y_max, u * z), dash_length=0.02) for u in [1, -1] )) dashed_lines.set_stroke(WHITE, 0.5) dashed_lines.set_flat_stroke(False) self.play( MoveToTarget(lines), MoveToTarget(trails), FadeIn(dashed_lines), FadeIn(vcomp), self.frame.animate.reorient(77, 87, 0).move_to([3.1, 0.4, 0]).set_height(5), ) self.play( FadeOut(dashed_lines), ) vertical_components.add(vcomp) self.play( lines.animate.set_opacity(1), trails.animate.set_opacity(0.05), ) # Final color def get_final_color(): rgbs = np.array([ line.data["stroke_rgba"][0, :3] for line in lines ]) depths = np.array([v_line.get_depth() for v_line in vertical_components]) alphas = depths / depths.sum() rgb = ((rgbs**0.5) * alphas[:, np.newaxis]).sum(0)**2.0 return rgb_to_color(rgb) new_color = get_final_color() new_lines = vertical_components.copy() for line in new_lines: line.set_depth(cylinder.get_depth()) line.set_stroke(new_color, 4) line.next_to(end_polarizer, RIGHT, buff=0.5) self.play( Restore(end_polarizer), TransformFromCopy(vertical_components, new_lines), self.frame.animate.reorient(43, 73, 0).move_to([3.3, 0.66, -0.38]).set_height(5.68), run_time=4, ) self.play( self.frame.animate.reorient(45, 72, 0).move_to([3.17, 0.4, -0.56]), run_time=8, ) # Twist the tube result_line = new_lines[0] self.remove(new_lines) self.add(result_line) result_line.add_updater(lambda l: l.set_stroke(get_final_color())) line_group = VGroup(trails, lines) p1, p2 = axes.c2p(0, 1, 0), axes.c2p(0, -1, 0) twist_arrows = VGroup( Arrow(p1, p2, path_arc=PI), Arrow(p2, p1, path_arc=PI), ) twist_arrows.rotate(PI / 2, UP, about_point=axes.get_origin()) twist_arrows.apply_depth_test() self.add(twist_arrows, cylinder, line_group, vertical_components) for v_comp, line in zip(vertical_components, lines): v_comp.line = line v_comp.add_updater(lambda m: m.match_depth(m.line)) self.play( ShowCreation(twist_arrows, lag_ratio=0), Rotate(line_group, PI, axis=RIGHT, run_time=12, rate_func=linear) ) def get_wave_trail(self, line, spacing=0.05, opacity=0.05): trail = VGroup() trail.time = 1 def update_trail(trail, dt): trail.time += dt if trail.time > spacing: trail.time = 0 trail.add(line.copy().set_opacity(opacity).set_shading(0, 0, 0)) trail.add_updater(update_trail) return trail def get_continuous_wave_trail(self, axes, line, opacity=0.4): return TwistedRibbon( axes, amplitude=0.5 * line.get_length(), twist_rate=get_twist(line.wave_length, TAU), color=line.get_color(), opacity=opacity, ) class InducedWiggleInCylinder(TwistingLightBeam): random_seed = 3 cylinder_radius = 0.5 wave_config = dict( z_amplitude=0.15, wave_len=0.5, color=get_spectral_color(0.1), speed=1.0, twist_rate=-1 / 24 ) def construct(self): # Setup frame = self.frame frame.reorient(-51, 80, 0).move_to(0.5 * IN).set_height(9) axes, plane = get_axes_and_plane(**self.axes_config) cylinder = SugarCylinder(axes, self.camera, radius=self.cylinder_radius) wave = OscillatingWave(axes, **self.wave_config) x_tracker, plane, rod, ball, x_label = slice_group = self.get_slice_group(axes, wave) rod = self.get_polarization_rod(axes, wave, x_tracker.get_value, length_mult=5.0) axes_labels = Tex("yz", font_size=30) axes_labels.rotate(89 * DEGREES, RIGHT) axes_labels[0].next_to(axes.y_axis.get_top(), OUT, SMALL_BUFF) axes_labels[1].next_to(axes.z_axis.get_zenith(), OUT, SMALL_BUFF) axes.add(axes_labels) light = GlowDot(radius=4, color=RED) light.move_to(axes.c2p(-3, 0, 0)) polarizer = Polarizer(axes, radius=0.5) polarizer.move_to(axes.c2p(-1, 0, 0)) self.add(axes, cylinder, polarizer, light) # Bounces of various points randy = self.get_observer(axes.c2p(8, -3, -0.5)) self.play( self.frame.animate.reorient(-86, 70, 0).move_to([1.01, -2.98, -0.79]).set_height(11.33), FadeIn(randy, time_span=(0, 1)), run_time=2, ) max_y = 0.5 * self.cylinder_radius line = VMobject() line.set_stroke(RED, 2) line.set_flat_stroke(False) dot = TrueDot(radius=0.05) dot.make_3d() for x in range(10): point = axes.c2p( random.uniform(axes.x_axis.x_min, axes.x_axis.x_max), random.uniform(-max_y, -max_y), random.uniform(-max_y, -max_y), ) line_points = [light.get_center(), point, randy.eyes.get_top()] self.add(dot, cylinder) if x == 0: dot.move_to(point) line.set_points_as_corners(line_points) self.play(ShowCreation(line)) else: self.play( line.animate.set_points_as_corners(line_points), dot.animate.move_to(point), ) self.wait() self.play( FadeOut(line), FadeOut(dot), ) # Show slice such that wiggling is in z direction x_tracker.set_value(0) self.add(wave, cylinder) self.play( self.frame.animate.reorient(-73, 78, 0).move_to([0.8, -2.22, -0.83]).set_height(10.64), light.animate.scale(0.5), polarizer.animate.fade(0.5), VFadeIn(wave), ) self.wait(4) self.add(wave, cylinder) self.play( FadeIn(plane), FadeIn(x_label), FadeIn(rod), ) self.play( x_tracker.animate.set_value(12), run_time=12, rate_func=linear, ) self.add(rod, ball, wave, cylinder) # Show observer line_of_sight = DashedLine(randy.eyes.get_top(), rod.get_center()) line_of_sight.set_stroke(WHITE, 2) line_of_sight.set_flat_stroke(False) self.play( self.frame.animate.reorient(-60, 79, 0).move_to([0.73, -0.59, -0.39]).set_height(9.63), Write(line_of_sight, time_span=(3, 4), lag_ratio=0), run_time=5, ) self.wait(2) # Show propagating rings self.show_propagation(rod) # Move to a less favorable spot new_line_of_sight = DashedLine(randy.eyes.get_top(), axes.c2p(6, 0, 0)) new_line_of_sight.match_style(line_of_sight) new_line_of_sight.set_flat_stroke(False) self.remove(ball) self.play( x_tracker.animate.set_value(6), FadeOut(line_of_sight, time_span=(0, 0.5)), run_time=4, ) self.add(ball, wave, cylinder, plane) self.play(ShowCreation(new_line_of_sight)) self.wait(4) # New propagations self.show_propagation(rod) # Show ribbon ribbon = TwistedRibbon( axes, amplitude=wave.z_amplitude, twist_rate=wave.twist_rate, color=wave.get_color(), ) self.add(ribbon, cylinder) self.play(ShowCreation(ribbon, run_time=5)) self.wait() self.play( self.frame.animate.reorient(8, 77, 0).move_to([2.01, -0.91, -0.58]).set_height(5.55), FadeOut(randy), run_time=2, ) self.wait(4) self.play( self.frame.animate.reorient(-25, 76, 0).move_to([4.22, -1.19, -0.5]), x_tracker.animate.set_value(12), FadeOut(new_line_of_sight, time_span=(0, 0.5)), run_time=3, ) self.wait(4) self.play( self.frame.animate.reorient(-61, 78, 0).move_to([0.7, 0.05, -0.69]).set_height(9.68), FadeIn(randy), run_time=3, ) self.play( LaggedStartMap(FadeOut, Group( line_of_sight, plane, rod, ball, x_label )) ) # Show multiple waves n_waves = 11 amp = 0.03 zs = np.linspace(0.5 - amp, -0.5 + amp, n_waves) small_wave_config = dict(self.wave_config) small_wave_config["z_amplitude"] = amp waves = VGroup(*( OscillatingWave( axes, offset=axes.c2p(0, 0, z)[2] * OUT, **small_wave_config ) for z in zs )) self.remove(ribbon) self.play( FadeOut(wave), VFadeIn(waves), ) self.wait(4) # Focus on various x_slices x_tracker.set_value(0) rods = VGroup(*( self.get_polarization_rod( axes, lil_wave, x_tracker.get_value, length_mult=1, stroke_width=2, ) for lil_wave in waves )) balls = Group(*( self.get_wave_ball(lil_wave, x_tracker.get_value, radius=0.025) for lil_wave in waves )) sf = 1.2 * axes.z_axis.get_unit_size() / plane.get_height() plane.scale(sf) plane[0].scale(1.0 / sf) plane.update() x_label.update() self.add(plane, rods, balls, cylinder, x_label) self.play( self.frame.animate.reorient(-90, 83, 0).move_to([0.17, -0.37, -0.63]).set_height(7.35).set_anim_args(run_time=3), FadeOut(light), FadeOut(polarizer), FadeIn(plane), FadeIn(rods), FadeIn(x_label), waves.animate.set_stroke(width=0.5, opacity=0.5).set_anim_args(time_span=(1, 2), suspend_mobject_updating=False), cylinder.animate.set_opacity(0.05).set_anim_args(time_span=(1, 2)) ) self.wait(4) self.play( self.frame.animate.reorient(-91, 90, 0).move_to([-0.01, -1.39, 0.21]).set_height(3.70), x_tracker.animate.set_value(5).set_anim_args(rate_func=linear), run_time=12, ) self.wait(4) # Show lines of sight lines_of_sight = VGroup(*( self.get_line_of_sign(rod, randy, stroke_width=0.5) for rod in rods )) self.play(ShowCreation(lines_of_sight[0])) self.show_propagation(rods[0]) for line1, line2 in zip(lines_of_sight, lines_of_sight[1:]): self.play(FadeOut(line1), FadeIn(line2), run_time=0.25) self.wait(0.25) self.wait(4) self.play(FadeIn(lines_of_sight[:-1])) self.add(lines_of_sight) # Move closer and farther self.play( randy.animate.shift(3.5 * UP + 0.5 * IN), run_time=2, ) self.wait(8) self.play( self.frame.animate.reorient(-91, 89, 0).move_to([-0.05, -3.75, 0.07]).set_height(8.92), randy.animate.shift(10 * DOWN), run_time=2, ) self.wait(8) def show_propagation(self, rod, run_time=10): rings = ProbagatingRings(rod, start_width=5) self.add(rings) self.wait(run_time) self.play(VFadeOut(rings)) def get_observer(self, location=ORIGIN): randy = Randolph(mode="pondering") randy.look(RIGHT) randy.rotate(PI / 2, RIGHT) randy.rotate(PI / 2, OUT) randy.move_to(location) return randy def get_line_of_sign(self, rod, observer, stroke_color=WHITE, stroke_width=1): line = Line(ORIGIN, 5 * RIGHT) line.set_stroke(stroke_color, stroke_width) line.add_updater(lambda l: l.put_start_and_end_on( observer.eyes.get_top(), rod.get_center() )) line.set_flat_stroke(False) return line class VectorFieldWigglingNew(InteractiveScene): default_frame_orientation = (-33, 85) def construct(self): # Waves axes, plane = get_axes_and_plane() self.add(axes, plane) wave = OscillatingWave( axes, wave_len=3.0, speed=1.5, color=BLUE, z_amplitude=0.5, ) vector_wave = OscillatingFieldWave(axes, wave) wave_opacity_tracker = ValueTracker(0) vector_opacity_tracker = ValueTracker(1) wave.add_updater(lambda m: m.set_stroke(opacity=wave_opacity_tracker.get_value())) vector_wave.add_updater(lambda m: m.set_stroke(opacity=vector_opacity_tracker.get_value())) self.add(wave, vector_wave) # Charges charges = DotCloud(color=RED) charges.to_grid(50, 50) charges.set_radius(0.04) charges.set_height(2 * axes.z_axis.get_length()) charges.rotate(PI / 2, RIGHT).rotate(PI / 2, IN) charges.move_to(axes.c2p(-10, 0, 0)) charges.make_3d() charge_opacity_tracker = ValueTracker(1) charges.add_updater(lambda m: m.set_opacity(charge_opacity_tracker.get_value())) charges.add_updater(lambda m: m.set_z(0.3 * wave.xt_to_point(0, self.time)[2])) self.add(charges, wave, vector_wave) # Pan camera self.frame.reorient(47, 69, 0).move_to([-8.68, -7.06, 2.29]).set_height(5.44) self.play( self.frame.animate.reorient(-33, 83, 0).move_to([-0.75, -1.84, 0.38]).set_height(8.00), run_time=10, ) self.play( self.frame.animate.reorient(-27, 80, 0).move_to([-0.09, -0.42, -0.1]).set_height(9.03), wave_opacity_tracker.animate.set_value(1).set_anim_args(time_span=(1, 2)), vector_opacity_tracker.animate.set_value(0.5).set_anim_args(time_span=(1, 2)), run_time=4, ) # Highlight x_axis x_line = Line(*axes.x_axis.get_start_and_end()) x_line.set_stroke(BLUE, 10) self.play( wave_opacity_tracker.animate.set_value(0.25), vector_opacity_tracker.animate.set_value(0.25), charge_opacity_tracker.animate.set_value(0.25), ) self.play( ShowCreation(x_line, run_time=2), ) self.wait(5) # Show 3d wave wave_3d = VGroup() origin = axes.get_origin() for y in np.linspace(-1, 1, 5): for z in np.linspace(-1, 1, 5): vects = OscillatingFieldWave( axes, wave, max_vect_len=0.5, norm_to_opacity_func=lambda n: 0.75 * np.arctan(n), ) vects.y = y vects.z = z vects.add_updater(lambda m: m.shift(axes.c2p(0, m.y, m.z) - origin)) wave_3d.add(vects) self.wait(2) wave_opacity_tracker.set_value(0) self.remove(vector_wave) self.remove(x_line) self.add(wave_3d) self.wait(2) self.play( self.frame.animate.reorient(22, 69, 0).move_to([0.41, -0.67, -0.1]).set_height(10.31), run_time=8 ) self.play( self.frame.animate.reorient(-48, 68, 0).move_to([0.41, -0.67, -0.1]), run_time=10 ) class ClockwiseCircularLight(InteractiveScene): clockwise = True default_frame_orientation = (-20, 70) color = YELLOW x_range = (0, 24) amplitude = 0.5 def setup(self): super().setup() # Axes axes, plane = get_axes_and_plane(x_range=self.x_range) self.add(axes, plane) # Wave wave = OscillatingWave( axes, wave_len=3, speed=0.5, z_amplitude=self.amplitude, y_amplitude=self.amplitude, y_phase=-PI / 2 if self.clockwise else PI / 2, color=self.color, ) vect_wave = OscillatingFieldWave(axes, wave) vect_wave.set_stroke(opacity=0.7) self.add(wave, vect_wave) def construct(self): self.play( self.frame.animate.reorient(73, 82, 0), run_time=5 ) for pair in [(100, 70), (59, 72), (110, 65), (60, 80)]: self.play( self.frame.animate.reorient(*pair), run_time=12, ) class CounterclockwiseCircularLight(ClockwiseCircularLight): clockwise = False color = RED class AltClockwiseCircularLight(ClockwiseCircularLight): x_range = (0, 8) amplitude = 0.4 def construct(self): self.frame.reorient(69, 81, 0) self.wait(12) class AltCounterclockwiseCircularLight(CounterclockwiseCircularLight): x_range = (0, 8) amplitude = 0.4 def construct(self): self.frame.reorient(69, 81, 0) self.wait(12) class TransitionTo2D(InteractiveScene): default_frame_orientation = (-20, 70) wave_config = dict( color=BLUE, wave_len=3, ) def construct(self): # Axes axes, plane = get_axes_and_plane(x_range=(0, 8.01)) self.add(axes, plane) # Waves wave = OscillatingWave(axes, **self.wave_config) vect_wave = OscillatingFieldWave(axes, wave) wave_opacity_tracker = ValueTracker(1) wave.add_updater(lambda m: m.set_stroke(opacity=wave_opacity_tracker.get_value())) vect_wave.add_updater(lambda m: m.set_stroke(opacity=wave_opacity_tracker.get_value())) single_vect = Vector(OUT, stroke_color=wave.get_color(), stroke_width=4) single_vect.set_flat_stroke(False) def update_vect(vect): x_max = axes.x_axis.x_max base = axes.c2p(x_max, 0, 0) vect.put_start_and_end_on(base, base + wave.xt_to_point(x_max, wave.time) * [0, 1, 1]) single_vect.add_updater(update_vect) self.add(wave, vect_wave) # Shift perspective self.frame.reorient(69, 81, 0) wave_opacity_tracker.set_value(0.8) self.wait(6) self.play( self.frame.animate.reorient(73, 84, 0), VFadeIn(single_vect, time_span=(2, 3)), wave_opacity_tracker.animate.set_value(0.35).set_anim_args(time_span=(2, 3)), run_time=5, ) self.wait() self.play( self.frame.animate.reorient(90, 90, 0), wave_opacity_tracker.animate.set_value(0), run_time=4, ) self.wait(4) class TransitionTo2DRightHanded(TransitionTo2D): wave_config = dict( wave_len=3, y_amplitude=0.5, z_amplitude=0.5, y_phase=PI / 2, color=RED, ) class TransitionTo2DLeftHanded(TransitionTo2D): wave_config = dict( wave_len=3, y_amplitude=0.5, z_amplitude=0.5, y_phase=-PI / 2, color=YELLOW, ) class LinearAsASuperpositionOfCircular(InteractiveScene): rotation_rate = 0.25 amplitude = 2.0 def construct(self): # Set up planes plane_config = dict( background_line_style=dict(stroke_color=GREY, stroke_width=1), faded_line_style=dict(stroke_color=GREY, stroke_width=0.5, stroke_opacity=0.5), ) planes = VGroup( ComplexPlane((-1, 1), (-1, 1), **plane_config), ComplexPlane((-1, 1), (-1, 1), **plane_config), ComplexPlane((-2, 2), (-2, 2), **plane_config), ) planes[:2].arrange(DOWN, buff=2.0).set_height(FRAME_HEIGHT - 1.5).next_to(ORIGIN, LEFT, 1.0) planes[2].set_height(6).next_to(ORIGIN, RIGHT, 1.0) # planes.arrange(RIGHT, buff=1.5) self.add(planes) # Set up trackers phase_trackers = ValueTracker(0).replicate(2) phase1_tracker, phase2_tracker = phase_trackers def update_phase(m, dt): m.increment_value(TAU * self.rotation_rate * dt) def slow_changer(m, dt): m.increment_value(-0.5 * TAU * self.rotation_rate * dt) for tracker in phase_trackers: tracker.add_updater(update_phase) self.add(*phase_trackers) def get_z1(): return 0.5 * self.amplitude * np.exp((PI / 2 + phase1_tracker.get_value()) * 1j) def get_z2(): return 0.5 * self.amplitude * np.exp((PI / 2 - phase2_tracker.get_value()) * 1j) def get_sum(): return get_z1() + get_z2() # Vectors vects = VGroup( self.get_vector(planes[0], get_z1, color=RED), self.get_vector(planes[1], get_z2, color=YELLOW), self.get_vector(planes[2], get_sum, color=BLUE), self.get_vector(planes[2], get_z1, color=RED), self.get_vector(planes[2], get_sum, get_base=get_z1, color=YELLOW), ) self.add(*vects) # Polarization line pol_line = Line(UP, DOWN) pol_line.set_stroke(YELLOW, 1) pol_line.match_height(planes[2]) pol_line.move_to(planes[2]) def update_pol_line(line): if abs(vects[2].get_length()) > 1e-3: line.set_angle(vects[2].get_angle()) line.move_to(planes[2].n2p(0)) return line pol_line.add_updater(update_pol_line) self.add(pol_line, *planes, *vects) # Write it as an equation plus = Tex("+", font_size=72) equals = Tex("=", font_size=72) plus.move_to(planes[0:2]) # equals.move_to(planes[1:3]) equals.move_to(ORIGIN) self.add(plus, equals) # Slow down annotation arcs = VGroup( Arrow(LEFT, RIGHT, path_arc=-PI, stroke_width=2), Arrow(RIGHT, LEFT, path_arc=-PI, stroke_width=2), ) arcs.move_to(planes[0]) slow_word = Text("Slow down!") slow_word.next_to(planes[0], DOWN) sucrose = Sucrose(height=1) sucrose.balls.scale_radii(0.25) sucrose.fade(0.5) sucrose.move_to(planes[0]) slow_group = Group(slow_word, arcs, sucrose) def slow_down(): self.play(FadeIn(slow_group, run_time=0.25)) phase1_tracker.add_updater(slow_changer) self.wait(0.75) phase1_tracker.remove_updater(slow_changer) self.play(FadeOut(slow_group)) # Highlight constituent parts back_rects = VGroup(*(BackgroundRectangle(plane) for plane in planes)) back_rects.set_fill(opacity=0.5) self.wait(8) self.add(back_rects[1]) VGroup(vects[1], vects[2], vects[4]).set_stroke(opacity=0.25) self.wait(8) self.remove(back_rects[1]) self.add(back_rects[0]) vects.set_stroke(opacity=1) VGroup(vects[0], vects[2]).set_stroke(opacity=0.25) self.wait(8) vects.set_stroke(opacity=1) self.remove(back_rects) self.wait(4) # Rotation labels for tracker in phase_trackers: tracker.set_value(0) rot_labels = VGroup(*( TexText("Total rotation: 0.00") for _ in range(2) )) for rot_label, plane, tracker in zip(rot_labels, planes, phase_trackers): rot_label.set_height(0.2) rot_label.set_color(GREY_B) rot_label.next_to(plane, UP) dec = rot_label.make_number_changable("0.00", edge_to_fix=LEFT) dec.phase_tracker = tracker dec.add_updater(lambda m: m.set_value(m.phase_tracker.get_value() / TAU)) self.add(rot_labels) # Let it play, occasionally kink self.wait(9) for _ in range(20): slow_down() self.wait(3 * random.random()) def get_vector(self, plane, get_z, get_base=lambda: 0, color=BLUE): vect = Vector(UP, stroke_color=color) vect.add_updater(lambda m: m.put_start_and_end_on( plane.n2p(get_base()), plane.n2p(get_z()) )) return vect
from manim_imports_ext import * from _2023.barber_pole.objects import * class WaveIntoMedium(TimeVaryingVectorField): def __init__( self, interface_origin=ORIGIN, interface_normal=DR, prop_direction=RIGHT, index=1.5, c=2.0, frequency=0.25, amplitude=1.0, x_density=5.0, y_density=5.0, width=15.0, height=15.0, norm_to_opacity_func=lambda n: np.tanh(n), **kwargs ): def time_func(points, time): k = frequency / c phase = TAU * (k * np.dot(points, prop_direction.T) - frequency * time) kickback = np.dot(points - interface_origin, interface_normal.T) kickback[kickback < 0] = 0 phase += kickback * index * c return amplitude * np.outer(np.cos(phase), OUT) super().__init__( time_func, x_density=x_density, y_density=y_density, width=width, height=height, norm_to_opacity_func=norm_to_opacity_func, **kwargs ) class ScalarFieldByOpacity(DotCloud): def __init__( self, # Takes (n, 3) array of points to n-array of values between 0 and 1 opacity_func, width=15, height=8, density=10, color=WHITE, ): step = 1.0 / density radius = step / 2.0 points = np.array([ [x, y, 0] for x in np.arange(-width / 2, width / 2 + step, step) for y in np.arange(-height / 2, height / 2 + step, step) ]) super().__init__(points, color=color, radius=radius) self.opacity_func = opacity_func def update_opacity(dots): dots.set_opacity(opacity_func(dots.get_points())) self.add_updater(update_opacity) class WavesByOpacity(ScalarFieldByOpacity): def __init__( self, wave: VectorField, vects_to_opacities=lambda v: np.tanh(v[:, 2]), **kwargs ): super().__init__( opacity_func=lambda p: vects_to_opacities(wave.func(p)), **kwargs ) # Scenes class SnellsLaw(InteractiveScene): # index = 1.5 index = 1.0 def construct(self): # Setup key objects medium = FullScreenRectangle() medium.set_fill(BLUE, 0.3).set_stroke(width=0) medium.stretch(0.5, 1, about_edge=DOWN) hit_point = medium.get_top() angle_tracker = ValueTracker(40 * DEGREES) beam = self.get_beam(angle_tracker, hit_point) glow = GlowDot(color=YELLOW) self.add(medium) # Shine in anim_kw = dict(run_time=3, rate_func=linear) self.play( ShowCreation(beam, **anim_kw), UpdateFromFunc(glow, lambda m: m.move_to(beam.get_end())) ) self.wait() # Add angle labels normal_line = Line(2 * UP, 2 * DOWN) normal_line.move_to(hit_point) normal_line.set_stroke(WHITE, 1) def get_theta1(): return angle_tracker.get_value() def get_theta2(): return np.arcsin(np.sin(get_theta1()) / self.index) arc_kw = dict(radius=0.8, stroke_width=1) arc1 = always_redraw(lambda: Arc(90 * DEGREES, get_theta1(), **arc_kw)) arc2 = always_redraw(lambda: Arc(-90 * DEGREES, get_theta2(), **arc_kw)) theta1_label = Tex(R"\theta_1") theta1_label.arc = arc1 theta2_label = Tex(R"\theta_2") theta2_label.arc = arc2 def update_theta_label(label): point = label.arc.pfp(0.2) vect = normalize(point - hit_point) label.set_height(min(0.4, max(1.0 * label.arc.get_width(), 1e-2))) label.next_to(point, vect, buff=SMALL_BUFF) theta1_label.add_updater(update_theta_label) theta2_label.add_updater(update_theta_label) ineq = Tex(R"\theta_1 > \theta_2") ineq.move_to(FRAME_WIDTH * RIGHT / 4 + 3 * UP) self.play( LaggedStart( ShowCreation(normal_line), ShowCreation(arc1), ShowCreation(arc2), Write(theta1_label), Write(theta2_label), lag_ratio=0.1, run_time=1 ), FadeIn(ineq, UP) ) self.wait() angle_labels = VGroup(normal_line, arc1, arc2, theta1_label, theta2_label) # Vary the angle for a bit self.remove(arc2, theta2_label, ineq) beam.set_stroke(opacity=1, width=2) for width in np.linspace(2, 10.0, 40): beam_copy = beam.copy() beam_copy.set_stroke(width=width, opacity=0.2 / (width)**1.4) self.add(beam_copy) for angle in [70 * DEGREES, -50 * DEGREES, 40 * DEGREES]: self.play(angle_tracker.animate.set_value(angle), run_time=5) # Tank analogy tank = SVGMobject("tank") tank.set_fill(WHITE) tank.rotate(-16 * DEGREES) tank.set_height(1) tank.move_to(beam.pfp(0.25)) self.play(FadeOut(angle_labels)) self.frame.set_height(4) self.play( tank.animate.move_to(beam.pfp(0.49)).set_anim_args(rate_func=linear, run_time=6), VFadeIn(tank), self.frame.animate.set_height(4).set_anim_args(time_span=(4, 6)) ) self.play( tank.animate.rotate(get_theta2() - get_theta1()).move_to(hit_point + 0.3 * UP + 0.1 * LEFT), rate_func=linear, run_time=1.5, ) self.play( tank.animate.move_to(beam.pfp(0.65)).set_anim_args(rate_func=linear, run_time=8), VFadeOut(tank, time_span=(7, 8)), self.frame.animate.set_height(8).set_anim_args(time_span=(6, 8)) ) self.wait() # Write Snell's law law = Tex(R"{\sin(\theta_1) \over v_1} = {\sin(\theta_2) \over v_2}", font_size=52) title = TexText("Snell's Law", font_size=60) group = VGroup(title, law) group.arrange(DOWN, buff=0.75) group.to_corner(UR) self.play(FadeIn(angle_labels)) self.play( Write(title), FlashUnder(title, run_time=2), FadeOut(ineq[">"]), Transform(ineq[R"\theta_1"], law[R"\theta_1"]), Transform(ineq[R"\theta_2"], law[R"\theta_2"]), ) self.play(FadeIn(law)) self.wait() tl1_copy = theta1_label.copy() tl2_copy = theta2_label.copy() self.play(LaggedStart( Transform(tl1_copy, law[R"\theta_1"]), Transform(tl2_copy, law[R"\theta_2"]), lag_ratio=0.5 )) self.play(FadeIn(law, lag_ratio=0.1, run_time=2)) self.remove(tl1_copy, tl2_copy) self.wait() # Vary the angle again for angle in [70 * DEGREES, 20 * DEGREES, 40 * DEGREES]: self.play(angle_tracker.animate.set_value(angle), run_time=3) # Show speeds in_beam = Line(beam.get_start(), hit_point) out_beam = Line(hit_point, beam.get_end()) in_beam.set_length(8, about_point=hit_point) def get_dot_anim(): dot = GlowDot() return Succession( MoveAlongPath(dot, in_beam, rate_func=linear, run_time=3), MoveAlongPath(dot, out_beam, rate_func=linear, run_time=3), remover=True, ) self.play(LaggedStart( *( get_dot_anim() for x in range(50) ), lag_ratio=0.02, run_time=20, )) def get_beam(self, angle_tracker, hit_point, stroke_color=YELLOW, stroke_width=3): result = Line() result.set_stroke(stroke_color, stroke_width) def update_beam(beam): theta1 = angle_tracker.get_value() theta2 = np.arcsin(np.sin(theta1) / self.index) beam.set_points_as_corners([ hit_point + 0.6 * FRAME_HEIGHT * rotate_vector(UP, theta1) / math.cos(theta1), hit_point, hit_point + 0.6 * FRAME_HEIGHT * rotate_vector(DOWN, theta2) / math.cos(theta2), ]) result.add_updater(update_beam) return result class WavesIntoAngledMedium(InteractiveScene): default_frame_orientation = (0, 0) interface_origin = ORIGIN interface_normal = DR prop_direction = RIGHT frequency = 0.5 c = 1.0 index = 2.0 amplitude = 0.5 def get_medium( self, width=10, height=30, depth=5, color=BLUE, opacity=0.2, ): medium = VCube(side_length=1.0) medium.set_shape(width, height, depth) medium.set_fill(color, opacity) medium.move_to(self.interface_origin, LEFT) medium.rotate( angle_of_vector(self.interface_normal), about_point=self.interface_origin ) return medium def get_wave(self, **kwargs): config = dict( interface_origin=self.interface_origin, interface_normal=self.interface_normal, prop_direction=self.prop_direction, frequency=self.frequency, c=self.c, index=self.index, max_vect_len=np.inf, amplitude=self.amplitude, norm_to_opacity_func=lambda n: sigmoid(n), ) config.update(kwargs) return WaveIntoMedium(**config) def get_wave_dots(self, wave, density=20, offset=0.2, color=WHITE, max_opacity=1.0, **kwargs): return WavesByOpacity( wave, density=density, vects_to_opacities=lambda v: max_opacity * np.tanh(v[:, 2] - offset * self.amplitude), color=color, **kwargs ) class TransitionToOverheadView(WavesIntoAngledMedium): interface_normal = RIGHT index = 2.0 amplitude = 0.5 def construct(self): # 1D case frame = self.frame medium = self.get_medium(opacity=0.3, height=8.0, depth=2.0) medium.remove(medium[-1]) medium.sort(lambda p: -p[1] - p[2]) medium.set_stroke(WHITE, 0.5, 0.5) medium.set_flat_stroke(False) wave_1d = self.get_wave(x_density=10, height=0.0) wave_1d.set_stroke(YELLOW) plane = NumberPlane( background_line_style=dict( stroke_color=BLUE_D, stroke_width=1, stroke_opacity=1, ), ) plane.axes.set_stroke(width=1) plane.fade(0.5) self.add(plane, medium, wave_1d) frame.reorient(-37, 61, 0) self.play( frame.animate.reorient(0, 90).set_height(6), run_time=5, ) self.wait(10) # Highlight wave length past_time = wave_1d.time wave_1d.suspend_updating() wave_len = 1.0 mult = 2.0 brace1 = Brace(Line(ORIGIN, mult * wave_len * RIGHT), UP) brace1.add(brace1.get_tex(Rf"\lambda = {wave_len}")) brace2 = Brace(Line(ORIGIN, 0.6 * mult * wave_len * RIGHT), UP) brace2.add(brace2.get_tex(Rf"\lambda = {0.6 * wave_len}")) for brace in [brace1, brace2]: brace.rotate(90 * DEGREES, RIGHT) brace.set_fill(border_width=0) brace1.next_to(3 * LEFT + 0.35 * OUT, OUT) brace2.next_to(1.85 * RIGHT + 0.35 * OUT, OUT) self.play(FadeIn(brace1, lag_ratio=0.1)) self.wait() self.play(FadeTransform(brace1.copy(), brace2)) self.wait() wave_1d.time = past_time wave_1d.resume_updating() self.play( FadeOut(brace1, RIGHT), FadeOut(brace2, 0.6 * RIGHT), ) self.wait(3) # Transition to 2d wave_2d = self.get_wave( width=20.0, height=8.0, norm_to_opacity_func=lambda n: 0.5 * sigmoid(2 * n), ) wave_2d.set_stroke(YELLOW) invisible_wave_2d = self.get_wave( width=20.0, height=12.0, norm_to_opacity_func=None, stroke_opacity=0, ) wave_dots = self.get_wave_dots( invisible_wave_2d, ) self.remove(wave_1d) wave_2d.time = wave_1d.time self.add(wave_2d) self.play( frame.animate.reorient(-10, 45).set_height(8).set_anim_args( run_time=7, time_span=(1, 7), ), ) self.wait(2) self.wait(8) self.remove(wave_2d) invisible_wave_2d.time = wave_2d.time self.add(invisible_wave_2d, wave_dots) self.wait(2) self.play( frame.animate.reorient(0, 0), plane.animate.fade(0.5), medium.animate.set_opacity(0.2), run_time=4, ) self.wait(8) # Show wave lengths again invisible_wave_2d.suspend_updating() VGroup(brace1, brace2).rotate(90 * DEGREES, LEFT) VGroup(brace1, brace2).set_backstroke(BLACK, 3) brace1.next_to(4 * LEFT, UP) brace2.next_to(2.45 * RIGHT, UP) braces = VGroup(brace1, brace2) self.play( FadeIn(braces), ) self.wait() # Pan back down to 1d wave wave_1d.time = invisible_wave_2d.time wave_1d.update() wave_1d.clear_updaters() self.play( # FadeOut(wave_dots), FadeIn(wave_1d), frame.animate.reorient(0, 70), braces.animate.rotate(90 * DEGREES, RIGHT, about_point=ORIGIN).shift(0.3 * OUT), run_time=5, ) self.wait() class AngledMedium(WavesIntoAngledMedium): amplitude = 1.2 frequency = 2.0 / 3.0 def construct(self): # Add setup plane = NumberPlane() plane.fade(0.75) medium = self.get_medium() self.add(plane) self.add(medium) # Wave wave = self.get_wave() wave.set_opacity(0) wave_dots = self.get_wave_dots(wave, offset=0.5) self.add(wave, wave_dots) self.wait(30) class AngledMediumSingleFront(AngledMedium): def get_wave_dots(self, wave, density=20, offset=0.2, color=RED, max_opacity=1.0, **kwargs): return super().get_wave_dots(wave, density, offset, color, max_opacity, **kwargs) class AngledMediumAnnotations(InteractiveScene): def construct(self): # Set up the lane h_lines = Line(LEFT, RIGHT).replicate(3) h_lines.set_width(0.7 * FRAME_WIDTH) h_lines.arrange(DOWN, buff=0.5) h_lines.move_to(ORIGIN, RIGHT) index = WavesIntoAngledMedium.index angle = math.asin(math.sin(45 * DEGREES) / index) diag_lines = h_lines.copy() for line1, line2 in zip(h_lines, diag_lines): line2.move_to(line1.get_end(), LEFT) line2.rotate(-angle, about_point=line1.get_end()) lane_points = [ h_lines[0].get_left(), h_lines[0].get_right(), diag_lines[0].get_end(), diag_lines[2].get_end(), h_lines[2].get_right(), h_lines[2].get_left(), ] fade_rect = FullScreenFadeRectangle() fade_rect.scale(1.5) fade_rect.start_new_path(lane_points[-1]) for point in lane_points: fade_rect.add_line_to(point) fade_rect.set_fill(BLACK, 0.8) beam = h_lines[1].copy() beam.add_line_to(diag_lines[1].get_end()) beam.set_stroke(YELLOW, 1.5) beam.insert_n_curves(100) self.play( FadeIn(fade_rect), ) self.play( ShowCreation(beam, run_time=3), VShowPassingFlash(beam.copy().set_stroke(width=5), run_time=3) ) self.wait() class LineGame(InteractiveScene): def construct(self): # Add line and medium interface = Line(6 * DL, 6 * UR) medium = Square().set_fill(BLUE, 0.2).set_stroke(width=0) medium.move_to(ORIGIN, LEFT) medium.rotate(-45 * DEGREES, about_point=ORIGIN) medium.scale(20, about_point=ORIGIN) self.add(medium, interface) # Prepare lines, with control large_spacing = 1.5 small_spacing = 0.6 * large_spacing circ = Circle(radius=0.5) circ.set_fill(interpolate_color(BLUE_E, BLACK, 0.5), 1) circ.set_stroke(WHITE, 2) circ.next_to(ORIGIN, RIGHT, buff=1.0) dial = Vector(0.8 * RIGHT) dial.move_to(circ) top_lines = self.get_line_group(interface, UP, large_spacing) low_lines = always_redraw(lambda: self.get_line_group( interface, rotate_vector(dial.get_vector(), -PI / 2), small_spacing, line_color=GREEN, dot_color=YELLOW )) top_spacing_label = self.get_spacing_label(top_lines[1], R"\lambda_1") low_spacing_label = self.get_spacing_label(low_lines[1], R"\lambda_2") low_spacing_label.shift(UP) # Add top lines, then lower lines self.play(FadeIn(top_lines, lag_ratio=0.1)) self.play(Write(top_spacing_label)) self.wait() self.highlight_intersection_points(top_lines, PINK, LEFT) self.wait() # Reposition lower lines key_angle = -19.9 * DEGREES dial.rotate(key_angle) low_lines.update() low_spacing_label.rotate(key_angle, about_point=ORIGIN) top_lines.save_state() self.play( top_lines.animate.fade(0.8), FadeIn(low_lines, lag_ratio=0.1), ) self.play(Write(low_spacing_label)) self.wait() dial.set_stroke(opacity=0) self.play( Rotate(dial, -key_angle, run_time=2, remover=True), Rotate(low_spacing_label, -key_angle, run_time=2, about_point=ORIGIN), ) dial.set_stroke(opacity=1) self.wait() self.highlight_intersection_points(low_lines, YELLOW, RIGHT) self.play(Restore(top_lines)) # Rotate lower lines self.add(low_lines) self.play( FadeIn(circ), FadeIn(dial) ) low_lines.resume_updating() for angle in [-15, -15, 10.1]: self.play( Rotate(dial, angle * DEGREES), Rotate(low_spacing_label, angle * DEGREES, about_point=ORIGIN), run_time=3 ) self.wait() low_lines.suspend_updating() self.highlight_intersection_points(low_lines, YELLOW) # Ask about angles theta1 = top_lines[1][0].get_angle() - interface.get_angle() theta2 = low_lines[1][0].get_angle() + TAU - (interface.get_angle() + PI) radius = 0.75 arc1 = Arc(interface.get_angle(), theta1, radius=radius) arc2 = Arc(interface.get_angle() + PI, theta2, radius=radius) theta1_label = Tex(R"\theta_1", font_size=36) theta2_label = Tex(R"\theta_2", font_size=36) theta1_label.next_to(arc1.pfp(0.5), UP, SMALL_BUFF) theta2_label.next_to(arc2.pfp(0.75), DL, SMALL_BUFF) self.play( ShowCreation(arc1), Write(theta1_label), self.frame.animate.set_height(6.5).set_anim_args(run_time=2), FadeOut(circ), FadeOut(dial), ) self.wait() self.play( ShowCreation(arc2), Write(theta2_label) ) self.wait() def get_line_group( self, interface, line_direction=UP, spacing=1.0, n_lines=17, length=30, line_color=WHITE, line_stroke_width=2, dot_radius=0.05, dot_color=RED, dot_opacity=1, ): # Calculate dot spacing interface_vect = normalize(interface.get_vector()) line_vect = normalize(line_direction) interface_center = interface.get_center() angle = angle_between_vectors(interface_vect, line_vect) dot_spacing = spacing / math.sin(angle) points = [ interface_center + i * dot_spacing * interface_vect for i in range(-n_lines // 2, n_lines // 2 + 1) ] dots = VGroup(*( Dot(point, radius=dot_radius).set_fill(dot_color, dot_opacity) for point in points )) lines = VGroup(*( Line( point, point + length * line_vect, stroke_color=line_color, stroke_width=line_stroke_width, ) for point in points )) result = VGroup(dots, lines) result.set_stroke(background=True) return result def get_spacing_label(self, lines, label_tex): n = len(lines) line1, line2 = lines[n // 2: (n // 2) + 2] x1 = line1.get_x() x2 = line2.get_x() dist = x2 - x1 arrows = VGroup( Arrow(dist * LEFT / 4, dist * RIGHT / 2, buff=SMALL_BUFF), Arrow(dist * RIGHT / 4, dist * LEFT / 2, buff=SMALL_BUFF), ) label = Tex(label_tex) label.set_max_width(0.9 * arrows.get_width()) label.next_to(arrows, UP, MED_SMALL_BUFF) result = VGroup(arrows, label) result.move_to(VGroup(line1, line2)) result.shift_onto_screen(buff=LARGE_BUFF) label.set_fill(border_width=0.5) return result def highlight_intersection_points(self, line_group, color, arrow_direction=LEFT): points = VGroup(*(p for p in line_group[0] if -4 < p.get_y() < 4)) arrows = VGroup(*( Vector(arrow_direction).next_to(point, -arrow_direction, SMALL_BUFF) for point in points )) arrows.set_color(color) self.play(LaggedStartMap(GrowArrow, arrows, lag_ratio=0.25)) self.play( LaggedStartMap(Indicate, line_group[0], scale_factor=2, color=color, lag_ratio=0.2), LaggedStartMap(FlashAround, line_group[0], buff=0.2, color=color, lag_ratio=0.2), run_time=4, ) self.play(FadeOut(arrows)) class Prism(InteractiveScene): def construct(self): # Add flat flat_prism = Triangle() flat_prism.set_height(4) flat_prism.set_stroke(WHITE, 1) flat_prism.set_fill(BLUE, 0.2) prism = Prismify(flat_prism, depth=5) prism.set_fill(BLUE_D, 0.25, border_width=0) prism.set_stroke(WHITE, 0) prism.sort(lambda p: -p[2]) prism.apply_depth_test() prism.deactivate_depth_test() prism.set_shading(0.5, 0.5, 0) verts = flat_prism.get_vertices() in_edge = Line(verts[0], verts[1]) out_edge = Line(verts[0], verts[2]) self.add(flat_prism) # Beams of light frame = self.frame self.camera.light_source.move_to((-10, -10, 10)) left_side = 10 * LEFT in_beam = Line(left_side, in_edge.get_center()) in_beam.set_stroke(WHITE, 3) def get_beams(light_in): return self.get_beams( min_index=1.3, # max_index=1.4, max_index=1.45, n_beams=200, in_beam=light_in, in_edge=in_edge, out_edge=out_edge, ) beams = always_redraw(lambda: get_beams(in_beam)) self.play( ShowCreation(beams, time_span=(0.5, 1.5), lag_ratio=0), ShowCreation(in_beam, time_span=(0, 1.0)), rate_func=linear ) # Show x-ray x_ray = self.get_beams(0.8, 0.8, 1, in_beam, in_edge, out_edge) x_ray.set_stroke("#FF00D5", 8) self.add(x_ray, in_beam) self.play(ShowCreation(x_ray, run_time=2)) self.wait() self.remove(x_ray) # Transition to 3d self.play( FadeOut(flat_prism), FadeIn(prism), frame.animate.reorient(-90, 35, 90).set_height(15).move_to(RIGHT + 4 * DOWN), run_time=4, ) turn_animation_into_updater( ApplyMethod(frame.reorient, -90, 10, 90, run_time=15) ) # for vect, alpha in zip([DOWN, 2 * UP, ORIGIN], [0.3, 0.3, 0.5]): for vect, alpha in zip([5 * DOWN, 3 * DOWN, 4 * DOWN], [0.3, 0.3, 0.5]): self.play( in_beam.animate.put_start_and_end_on(left_side + vect, in_edge.pfp(alpha)), # run_time=5 ) # Back to 2d frame.clear_updaters() self.play( frame.animate.reorient(0, 0, 0).set_height(8), in_beam.animate.put_start_and_end_on(left_side + 2 * DOWN, in_edge.get_center()), FadeOut(prism, time_span=(1, 2)), FadeIn(flat_prism, time_span=(1, 2)), run_time=2, ) self.wait() def get_beams(self, min_index, max_index, n_beams, in_beam, in_edge: Line, out_edge: Line): alphas = np.linspace(0, 1, n_beams)**1.5 indices = interpolate(min_index, max_index, alphas) normal1 = rotate_vector(normalize(in_edge.get_vector()), PI / 2) normal2 = rotate_vector(normalize(out_edge.get_vector()), PI / 2) in_point = in_beam.get_end() vect1 = normalize(in_beam.get_vector()) theta1 = angle_between_vectors(normal1, vect1) theta2s = np.arcsin(np.sin(theta1) / indices) vect2s = np.array([ rotate_vector(normal1, theta2) for theta2 in theta2s ]) out_points = np.array([ find_intersection(in_point, vect2, out_edge.get_start(), out_edge.get_vector()) for vect2 in vect2s ]) theta3s = np.array([ angle_between_vectors(normal2, vect2) for vect2 in vect2s ]) theta4s = np.arcsin(np.sin(theta3s) * indices) vect3s = np.array([ rotate_vector(normal2, -theta4) for theta4 in theta4s ]) beams = VGroup(*( VMobject().set_points_as_corners([ in_point - 1.0 * FRAME_WIDTH * vect1, in_point, out_point, out_point + 3.0 * FRAME_WIDTH * vect3 ]) for out_point, vect3 in zip(out_points, vect3s) )) for alpha, beam in zip(np.linspace(0, 1, n_beams), beams): beam.set_stroke(get_spectral_color(alpha), 1, opacity=0.8) return beams
from manim_imports_ext import * from _2023.barber_pole.objects import * def get_influence_ring(center_point, color=WHITE, speed=2.0, max_width=3.0, width_decay_exp=0.5): ring = Circle() ring.set_stroke(color) ring.move_to(center_point) ring.time = 0 def update_ring(ring, dt): ring.time += dt radius = ring.time * speed ring.set_width(max(2 * radius, 1e-3)) ring.set_stroke(width=max_width / (1 + radius)**width_decay_exp) return ring ring.add_updater(update_ring) return ring # Scenes class TestFields(InteractiveScene): def construct(self): # Test coulomb field particles = ChargedParticle(rotation=0).replicate(1) particles.arrange(DOWN) particles.move_to(6 * LEFT) field = CoulombField(*particles) self.add(field, particles) self.play(particles.animate.move_to(0.2 * UP), run_time=3) self.clear() # Test Lorenz field def pos_func(time): return 0.1 * np.sin(5 * time) * OUT particle = ChargedParticle( rotation=0, radius=0.1, track_position_history=True ) particles = particle.get_grid(20, 1, buff=0.25) particles.add_updater(lambda m: m.move_to(pos_func(self.time))) field = LorentzField( *particles, radius_of_suppression=1.0, x_density=4, y_density=4, max_vect_len=1, height=10, ) field.set_stroke(opacity=0.7) self.frame.reorient(-20, 70) self.add(field, particles) self.wait(10) class IntroduceEField(InteractiveScene): def construct(self): # Show two neighboring particles frame = self.frame frame.set_field_of_view(1 * DEGREES) charges = ChargedParticle(rotation=0).replicate(2) charges.arrange(RIGHT, buff=4) question = VGroup( Text(""" How does the position and motion of this... """), Text("influence this?"), ) for q, charge, vect in zip(question, charges, [LEFT, RIGHT]): q.next_to(charge, UP + vect, buff=1.0).shift(-2 * vect) question[1].align_to(question[0], DOWN) q0_bottom = question[0].get_bottom() arrow0 = always_redraw(lambda: Arrow(q0_bottom, charges[0])) arrow1 = Arrow(question[1].get_bottom(), charges[1]) arrows = VGroup(arrow0, arrow1) self.play(LaggedStartMap(FadeIn, charges, shift=UP, lag_ratio=0.5)) self.add(arrow0) self.play( Write(question[0]), charges[0].animate.shift(UR).set_anim_args( rate_func=wiggle, time_span=(1, 3), ) ) self.play( Write(question[1]), ShowCreation(arrow1), ) self.wait() # Show force arrows def show_coulomb_force(arrow, charge1, charge2): root = charge2.get_center() vect = 4 * coulomb_force( charge2.get_center()[np.newaxis, :], charge1 )[0] arrow.put_start_and_end_on(root, root + vect) coulomb_vects = Vector(RIGHT, stroke_width=5, stroke_color=YELLOW).replicate(2) coulomb_vects[0].add_updater(lambda a: show_coulomb_force(a, *charges)) coulomb_vects[1].add_updater(lambda a: show_coulomb_force(a, *charges[::-1])) self.add(*coulomb_vects, *charges) self.play( FadeOut(question, time_span=(0, 1)), FadeOut(arrows, time_span=(0, 1)), charges.animate.arrange(RIGHT, buff=1.25), run_time=2 ) # Show force word force_words = Text("Force", font_size=48).replicate(2) force_words.set_fill(border_width=1) fw_width = force_words.get_width() def place_force_word_on_arrow(word, arrow): word.set_width(min(0.5 * arrow.get_width(), fw_width)) word.next_to(arrow, UP, buff=0.2) force_words[0].add_updater(lambda w: place_force_word_on_arrow(w, coulomb_vects[0])) force_words[1].add_updater(lambda w: place_force_word_on_arrow(w, coulomb_vects[1])) self.play(LaggedStartMap(FadeIn, force_words, run_time=1, lag_ratio=0.5)) self.add(force_words, charges) self.wait() # Add distance label d_line = always_redraw(lambda: DashedLine( charges[0].get_right(), charges[1].get_left(), dash_length=0.025 )) d_label = Tex("r = 0.00", font_size=36) d_label.next_to(d_line, DOWN, buff=0.35) d_label.add_updater(lambda m: m.match_x(d_line)) dist_decimal = d_label.make_number_changable("0.00") def get_d(): return get_norm(charges[0].get_center() - charges[1].get_center()) dist_decimal.add_updater(lambda m: m.set_value(get_d())) # Show graph axes = Axes((0, 10), (0, 1, 0.25), width=10, height=5) axes.shift(charges[0].get_center() + 1 * UP - axes.get_origin()) axes.add( Text("Distance", font_size=36).next_to(axes.c2p(10, 0), UP), Text("Force", font_size=36).next_to(axes.c2p(0, 0.8), LEFT), ) graph = axes.get_graph(lambda x: 0.5 / x**2, x_range=(0.01, 10, 0.05)) graph.make_jagged() graph.set_stroke(YELLOW, 2) graph_dot = GlowDot(color=WHITE) graph_dot.add_updater(lambda d: d.move_to(axes.i2gp(get_d(), graph))) d_label.update() self.play( frame.animate.move_to([3.5, 2.5, 0.0]), LaggedStart( FadeIn(axes), ShowCreation(graph), FadeIn(graph_dot), ShowCreation(d_line), FadeIn(d_label, 0.25 * UP), ), run_time=2, ) self.wait() for buff in (0.4, 8, 1.25): self.play( charges[1].animate.next_to(charges[0], RIGHT, buff=buff), run_time=4 ) self.wait() # Write Coulomb's law coulombs_law = Tex(R""" F = {q_1 q_2 \over 4 \pi \epsilon_0} \cdot \frac{1}{r^2} """) coulombs_law_title = TexText("Coulomb's law") coulombs_law_title.move_to(axes, UP) coulombs_law.next_to(coulombs_law_title, DOWN, buff=0.75) rect = SurroundingRectangle(coulombs_law["q_1 q_2"]) rect.set_stroke(YELLOW, 2) rect.set_fill(YELLOW, 0.25) self.play( FadeIn(coulombs_law_title), FadeIn(coulombs_law, UP), ) self.wait() self.add(rect, coulombs_law) self.play(FadeIn(rect)) self.wait() self.play(rect.animate.surround(coulombs_law[R"4 \pi \epsilon_0"])) self.wait() self.play(rect.animate.surround(coulombs_law[R"\frac{1}{r^2}"])) self.wait() self.play(charges[1].animate.next_to(charges[0], RIGHT, buff=3.0), run_time=3) self.play(FadeOut(rect)) self.wait() # Remove graph d_line.clear_updaters() self.play( frame.animate.center(), VGroup(coulombs_law, coulombs_law_title).animate.to_corner(UL), LaggedStartMap(FadeOut, Group( axes, graph, graph_dot, d_line, d_label, force_words, coulomb_vects )), charges[0].animate.center(), FadeOut(charges[1]), run_time=2, ) self.wait() # Show Coulomb's law vector field coulombs_law.add_background_rectangle() coulombs_law_title.add_background_rectangle() field = CoulombField(charges[0], x_density=3.0, y_density=3.0) dots = DotCloud(field.sample_points, radius=0.025, color=RED) dots.make_3d() self.add(dots, coulombs_law_title, coulombs_law) self.play(ShowCreation(dots)) self.wait() self.add(field, coulombs_law_title, coulombs_law) self.play(FadeIn(field)) for vect in [2 * RIGHT, 4 * LEFT, 2 * RIGHT]: self.play(charges[0].animate.shift(vect).set_anim_args(path_arc=PI, run_time=3)) self.wait() # Electric field e_coulombs_law = Tex(R""" \vec{E}(\vec{r}) = {q \over 4 \pi \epsilon_0} \cdot \frac{1}{||\vec{r}||^2} \cdot \frac{\vec{r}}{||\vec{r}||} """) e_coulombs_law.move_to(coulombs_law, LEFT) ebr = BackgroundRectangle(e_coulombs_law) r_vect = Vector(2 * RIGHT + UP) r_vect.set_stroke(GREEN) r_label = e_coulombs_law[R"\vec{r}"][0].copy() r_label.next_to(r_vect.get_center(), UP, buff=0.1) r_label.set_backstroke(BLACK, 20) e_words = VGroup( Text("Electric Field:"), Text( """ What force would be applied to a unit charge at a given point """, t2s={"would": ITALIC}, t2c={"unit charge": RED}, alignment="LEFT", font_size=36 ), ) e_words.set_backstroke(BLACK, 20) e_words.arrange(DOWN, buff=0.5, aligned_edge=LEFT) e_words.next_to(e_coulombs_law, DOWN, buff=0.5) e_words.to_edge(LEFT, buff=MED_SMALL_BUFF) rect.surround(e_coulombs_law[R"\vec{E}"]) rect.scale(0.9, about_edge=DR) self.play( FadeOut(coulombs_law, UP), FadeIn(ebr, UP), FadeIn(e_coulombs_law, UP), ) self.wait() self.add(ebr, rect, e_coulombs_law) self.play(FadeIn(rect)) self.play(Write(e_words, stroke_color=BLACK)) self.wait() self.play( FadeOut(e_words), rect.animate.surround(e_coulombs_law[R"(\vec{r})"][0], buff=0) ) self.add(r_vect, charges[0]) self.play( field.animate.set_stroke(opacity=0.4), FadeTransform(e_coulombs_law[R"\vec{r}"][0].copy(), r_label), ShowCreation(r_vect), ) self.wait() self.play( rect.animate.surround(e_coulombs_law[R"\frac{\vec{r}}{||\vec{r}||}"]) ) self.wait() # Example E vect e_vect = r_vect.copy() e_vect.scale(0.25) e_vect.set_stroke(BLUE) e_vect.shift(r_vect.get_end() - e_vect.get_start()) e_vect_label = Tex(R"\vec{E}", font_size=36) e_vect_label.set_backstroke(BLACK, 5) e_vect_label.next_to(e_vect.get_center(), UL, buff=0.1).shift(0.05 * UR) self.play( TransformFromCopy(r_vect, e_vect, path_arc=PI / 2), FadeTransform(e_coulombs_law[:2].copy(), e_vect_label), run_time=2 ) self.wait() # Not the full story! words = Text("Not the full story!", font_size=60) arrow = Vector(LEFT) arrow.next_to(coulombs_law_title, RIGHT) arrow.set_color(RED) words.set_color(RED) words.set_backstroke(BLACK, 20) words.next_to(arrow, RIGHT) charges[1].move_to(20 * RIGHT) self.remove(field) field = CoulombField(*charges, x_density=3.0, y_density=3.0) field.set_stroke(opacity=float(field.get_stroke_opacity())) self.add(field) self.play( FadeIn(words, lag_ratio=0.1), ShowCreation(arrow), FadeOut(rect), FadeOut(r_vect), FadeOut(r_label), FadeOut(e_vect), FadeOut(e_vect_label), ) self.wait() self.play( LaggedStartMap(FadeOut, Group( dots, coulombs_law_title, e_coulombs_law, words, arrow, )), FadeOut(ebr), charges[0].animate.to_edge(LEFT, buff=1.0), charges[1].animate.to_edge(RIGHT, buff=1.0), run_time=3, ) # Wiggle here -> wiggle there tmp_charges = Group(*(ChargedParticle(track_position_history=True, charge=0.3) for x in range(2))) tmp_charges[0].add_updater(lambda m: m.move_to(charges[0])) tmp_charges[1].add_updater(lambda m: m.move_to(charges[1])) for charge in tmp_charges: charge.ignore_last_motion() lorentz_field = ColoumbPlusLorentzField( *tmp_charges, x_density=6.0, y_density=6.0, norm_to_opacity_func=lambda n: np.clip(0.5 * n, 0, 0.75) ) self.remove(field) self.add(lorentz_field, *tmp_charges) influence_ring0 = self.get_influence_ring(charges[0].get_center()).set_stroke(opacity=0) influence_ring1 = self.get_influence_ring(charges[1].get_center()).set_stroke(opacity=0) dist = get_norm(charges[1].get_center() - charges[0].get_center()) wiggle_kwargs = dict( rate_func=lambda t: wiggle(t, 3), run_time=1.5, suspend_mobject_updating=False, ) self.add(influence_ring0, charges) self.play(charges[0].animate.shift(UP).set_anim_args(**wiggle_kwargs)) self.wait_until(lambda: influence_ring0.get_radius() > dist, max_time=dist / 2.0) self.add(influence_ring1) self.play(charges[1].animate.shift(0.5 * DOWN).set_anim_args(**wiggle_kwargs)) self.wait_until(lambda: influence_ring1.get_radius() > dist, max_time=dist / 2.0) self.play(charges[0].animate.shift(0.25 * UP).set_anim_args(**wiggle_kwargs)) self.wait(6) self.play( FadeOut(influence_ring0), FadeOut(influence_ring1), FadeOut(lorentz_field) ) self.remove(tmp_charges) # Show this the force ring = self.get_influence_ring(charges[0].get_center()) ghost_charge = charges[0].copy().set_opacity(0.25) ghost_charge.shift(0.1 * IN) a_vect = Vector(UP).shift(charges[0].get_center()) a_vect.set_stroke(PINK) a_label = Tex(R"\vec{a}(t_0)", font_size=48) a_label.set_color(PINK) a_label.next_to(a_vect, RIGHT, SMALL_BUFF) f_vect = Vector(1.0 * DOWN).shift(charges[1].get_center()) f_vect.set_stroke(BLUE) f_label = Tex(R"\vec{F}(t)") f_label.set_color(BLUE) f_label.next_to(f_vect, LEFT, buff=0.15) time_label = Tex("t = 0.00") time_label.to_corner(UL) time_decimal = time_label.make_number_changable("0.00") time_decimal.add_updater(lambda m: m.set_value(ring.time)) start_point = charges[0].get_center().copy() speed = 2.0 def field_func(points): time = ring.time diffs = (points - start_point) norms = np.linalg.norm(diffs, axis=1) past_times = time - (norms / speed) mags = np.exp(-3 * past_times) mags[past_times < 0] = 0 return mags[:, np.newaxis] * DOWN field = VectorField( field_func, height=0, x_density=4.0, max_vect_len=1.0, ) field.add_updater(lambda f: f.update_vectors()) self.add(time_label, a_vect, a_label, charges) self.wait() self.add(ring, ghost_charge, field, charges) target = charges[0].get_center() + 2 * UP charges[0].add_updater(lambda m, dt: m.shift(3 * dt * (target - m.get_center()))) self.wait_until(lambda: ring.get_radius() > dist) self.add(f_vect, f_label, charges) ring.suspend_updating() charges[0].suspend_updating() self.add(f_vect, charges[1]) self.play( FadeIn(f_vect), FadeIn(f_label), FadeOut(field), ) # Write the Lorentz force lorentz_law = Tex(R""" \vec{F}(t) = {-q_1 q_2 \over 4\pi \epsilon_0 c^2} {1 \over r} \vec{a}_\perp(t - r / c) """) lorentz_law.to_edge(UP) lorentz_law[R"\vec{F}(t)"][0].match_style(f_label) a_hat_perp = lorentz_law[R"\vec{a}_\perp"][0] a_hat_perp.match_style(a_label) a_hat_perp.save_state() a_hat_perp[2].set_opacity(0) a_hat_perp[:2].move_to(a_hat_perp, RIGHT) a_hat_perp[:2].scale(1.25, about_edge=DR) lorentz_law["("][1].match_style(a_label) lorentz_law[")"][1].match_style(a_label) self.play( Transform( f_label.copy(), lorentz_law[R"\vec{F}(t)"][0].copy(), remover=True, run_time=1.5, ), FadeIn(lorentz_law, time_span=(1, 2)) ) self.wait() # Go through parts of the equation rect = SurroundingRectangle(lorentz_law["-q_1 q_2"]) rect.set_stroke(YELLOW, 2) rect.set_fill(YELLOW, 0.2) r_line = DashedLine(ghost_charge.get_right(), charges[1].get_left()) r_label = Tex("r").next_to(r_line, UP) self.add(rect, lorentz_law) self.play(FadeIn(rect)) self.wait() self.play(rect.animate.surround(lorentz_law[R"4\pi \epsilon_0 c^2"])) self.wait() self.play( rect.animate.surround(lorentz_law[R"{1 \over r}"]), ShowCreation(r_line), ) self.play(TransformFromCopy(lorentz_law[R"r"][1], r_label)) self.wait() self.play(rect.animate.surround(lorentz_law[R"\vec{a}_\perp(t - r / c)"])) self.wait() self.play(rect.animate.surround(lorentz_law[R"t - r / c"], buff=0.05)) self.wait() # Indicate back in time new_a_label = Tex(R"\vec{a}(t - r / c)") new_a_label.match_style(a_label) new_a_label.move_to(a_label, LEFT) ring.clear_updaters() time_decimal.clear_updaters() charges[0].clear_updaters() self.add(charges[0]) self.play( ring.animate.scale(1e-3), UpdateFromFunc(time_decimal, lambda m: m.set_value( ring.get_radius() / 2 )), charges[0].animate.shift(2 * DOWN).set_anim_args( time_span=(1, 4), rate_func=lambda t: smooth(t)**0.5, ), run_time=4, ) time_decimal.set_value(0) self.play( TransformMatchingStrings(a_label, new_a_label), FadeOut(rect), ) self.remove(rect) self.remove(ring) # Do another wiggle ring = self.get_influence_ring(charges[0].get_center()) time_decimal.add_updater(lambda m: m.set_value(ring.time)) self.add(ring) self.play(charges[0].animate.shift(UP).set_anim_args(**wiggle_kwargs)) self.wait_until(lambda: ring.get_radius() > dist) self.play(charges[1].animate.shift(0.5 * DOWN).set_anim_args(**wiggle_kwargs)) self.remove(ring) self.play(FadeOut(time_label)) # Add back perpenducular part charges.target = charges.generate_target() charges.target.arrange(UR, buff=3).center() r_line.target = r_line.generate_target() r_line.target.become(DashedLine( charges.target[0].get_center(), charges.target[1].get_center(), )) f_vect.target = f_vect.generate_target() f_vect.target.rotate(45 * DEGREES) f_vect.target.shift(charges.target[1].get_center() - f_vect.target.get_start()) rect = SurroundingRectangle(a_hat_perp.saved_state, buff=0.1) rect.set_stroke(YELLOW, 2) rect.set_fill(YELLOW, 0.25) self.add(rect, lorentz_law) self.play(FadeIn(rect, scale=0.5)) self.play(Restore(a_hat_perp)) self.wait() self.remove(ghost_charge) self.play( MoveToTarget(charges), MoveToTarget(r_line), MoveToTarget(f_vect), r_label.animate.next_to(r_line.target.get_center(), UL, SMALL_BUFF), f_label.animate.next_to(f_vect.target.get_center(), UR, buff=0), new_a_label.animate.next_to(charges.target[0], UL, buff=0), MaintainPositionRelativeTo(a_vect, charges[0]), run_time=2 ) self.wait() r_unit = normalize(charges[1].get_center() - charges[0].get_center()) a_perp_vect = Vector( a_vect.get_vector() - np.dot(a_vect.get_vector(), r_unit) * r_unit, ) a_perp_vect.match_style(a_vect) a_perp_vect.set_stroke(interpolate_color(PINK, WHITE, 0.5)) a_perp_vect.shift(a_vect.get_end() - a_perp_vect.get_end()) a_hat_perp2 = a_hat_perp.copy() a_hat_perp2.scale(0.9) a_hat_perp2.next_to(a_perp_vect.get_center(), UR, buff=0.1) a_hat_perp2.match_color(a_perp_vect) self.play(TransformFromCopy(a_vect, a_perp_vect)) self.play(TransformFromCopy(a_hat_perp, a_hat_perp2)) self.wait() rings = VGroup() for x in range(2): wiggle_kwargs = dict( run_time=2, rate_func=lambda t: wiggle(t, 5) ) ring = self.get_influence_ring(charges[0].get_center()) rings.add(ring) dist = get_norm(charges[0].get_center() - charges[1].get_center()) self.add(ring) self.play(charges[0].animate.shift(0.5 * UP).set_anim_args(**wiggle_kwargs)) self.wait_until(lambda: ring.get_radius() > dist) self.play(charges[1].animate.shift(0.25 * DR).set_anim_args(**wiggle_kwargs)) self.play(FadeOut(rings)) # Clear the canvas plane = NumberPlane( background_line_style=dict(stroke_color=GREY_D, stroke_opacity=0.75, stroke_width=1), axis_config=dict(stroke_opacity=(0.25)) ) new_lorentz = Tex(R""" \vec{E}_{\text{rad}}(\vec{r}, t) = {-q \over 4\pi \epsilon_0 c^2} {1 \over ||\vec{r}||} \vec{a}_\perp(t - ||\vec{r}|| / c) """, font_size=36) new_lorentz.to_corner(UL) lhs = new_lorentz[R"\vec{E}_{\text{rad}}(\vec{r}, t)"] lhs.set_color(BLUE) new_lorentz[R"\vec{a}_\perp("].set_color(PINK) new_lorentz[R")"][1].set_color(PINK) lhs_rect = SurroundingRectangle(lhs) arrow = Vector(UP).next_to(lhs_rect, DOWN) self.add(plane, lorentz_law, *charges) self.remove(rect) self.play( LaggedStartMap(FadeOut, Group( r_line, r_label, a_hat_perp2, a_perp_vect, a_vect, new_a_label, new_a_label, f_vect, f_label, charges[1], )), FadeIn(plane, time_span=(1, 2)), charges[0].animate.center().set_anim_args(time_span=(1, 2)), FadeTransform(lorentz_law, new_lorentz), ) self.play( ShowCreation(lhs_rect), GrowArrow(arrow), ) self.wait() self.play(FadeOut(lhs_rect), FadeOut(arrow)) # Show vector field charge = ChargedParticle( track_position_history=True ) field = LorentzField( charge, stroke_width=3, x_density=4.0, y_density=4.0, max_vect_len=0.25, norm_to_opacity_func=lambda n: np.clip(1.5 * n, 0, 1), ) a_vect = AccelerationVector(charge) small_charges = DotCloud(field.sample_points, radius=0.02) small_charges.match_color(charges[1][0]) small_charges.make_3d() new_lorentz.set_backstroke(BLACK, 20) self.add(small_charges, new_lorentz) self.play(ShowCreation(small_charges)) self.wait() self.remove(charges[0]) self.add(field, a_vect, charge, new_lorentz) charge.ignore_last_motion() # Have some fun with the charge wiggle_kwargs = dict( rate_func=lambda t: wiggle(t, 3), run_time=3.0, suspend_mobject_updating=False, ) lemniscate = ParametricCurve( lambda t: np.sin(t)**2 * (np.cos(t) * RIGHT + np.sin(t) * UP), t_range=(0, TAU, TAU / 200) ) self.play( charge.animate.shift(0.4 * UP).set_anim_args(**wiggle_kwargs), ) self.wait(3) self.play( MoveAlongPath(charge, lemniscate, run_time=6) ) self.wait(3) for point in [2 * RIGHT, ORIGIN]: self.play(charge.animate.move_to(point).set_anim_args(path_arc=PI, run_time=5, suspend_mobject_updating=False)) self.wait(5) # Set it oscillating charge.init_clock() charge.ignore_last_motion() charge.add_updater(lambda m: m.move_to( 0.25 * np.sin(0.5 * TAU * m.get_internal_time()) * UP )) self.wait(30) def get_influence_ring(self, center_point, color=WHITE, speed=2.0, max_width=3.0, width_decay_exp=0.5): return get_influence_ring(center_point, color, speed, max_width, width_decay_exp) class AltEFieldIntroduction(IntroduceEField): def construct(self): # Title title1 = TexText(R"Light $\rightarrow$ Wave in the Electromagnetic field") title2 = TexText(R"Electric field") title2.scale(1.5) VGroup(title1, title2).to_edge(UP) self.add(title1) self.wait() self.play( TransformMatchingStrings(title1, title2) ) title2.add_to_back(BackgroundRectangle(title2)) # Add field density = 4.0 charges = Group( ChargedParticle(ORIGIN, 1), ChargedParticle(3 * UL, -1, color=BLUE, sign="-"), ChargedParticle([3, -2, 0], 2), ChargedParticle([5, 1, 0], -2, color=BLUE, sign="-"), ) field_config = dict( x_density=density, y_density=density, width=2 * FRAME_WIDTH, ) c_field = CoulombField(*charges, **field_config) c_field_opacity_tracker = ValueTracker(0) c_field.add_updater(lambda m: m.set_stroke(opacity=c_field_opacity_tracker.get_value())) points = DotCloud(c_field.sample_points, radius=0.02) points.make_3d() points.set_color(BLUE) points.move_to(0.01 * IN) self.add(points, charges, title2) self.play( ShowCreation(points), FadeIn(charges), ) self.add(points, c_field, charges, title2) self.play( charges[0].animate.shift(0.0001 * UP).set_anim_args(rate_func=there_and_back), c_field_opacity_tracker.animate.set_value(1), ) self.wait() # Show example charge for charge in charges: charge.save_state() charge.target = charge.generate_target() charge.target.fade(0.5) charge.target.scale(1e-3) hyp_charge = ChargedParticle(sign="+1") hyp_charge.move_to(UR) vect = Vector(stroke_color=YELLOW) vect.charge = hyp_charge vect.field = c_field glow = GlowDot(hyp_charge.get_center(), color=RED, radius=0.5) hyp_charge.add_to_back(glow) hyp_words = Text("Hypothetical\nunit charge", font_size=24) hyp_words.set_backstroke(BLACK, 5) hyp_words.charge = hyp_charge hyp_words.add_updater(lambda m: m.next_to(m.charge, buff=-SMALL_BUFF)) def update_vect(vect): p = vect.charge.get_center() vect.put_start_and_end_on(p, p + vect.field.func([p])[0]) return vect vect.add_updater(update_vect) self.play( *map(MoveToTarget, charges), c_field_opacity_tracker.animate.set_value(0.5), VFadeIn(vect), FadeIn(hyp_charge), FadeIn(hyp_words), ) for point in [UL, (-3, 2, 0), (2, -3, 0)]: self.play(hyp_charge.animate.move_to(point + 0.05 * OUT), run_time=5) # Emphasize coulombenss c1 = charges[0] c2 = ChargedParticle((FRAME_WIDTH - 2) * RIGHT) c1.charge = c2.charge = 0.5 l_field = ColoumbPlusLorentzField( c1, c2, norm_to_opacity_func=lambda n: np.arctan(n), **field_config ) self.play( FadeOut(points), ReplacementTransform(c_field, l_field), Restore(c1), FadeOut(hyp_charge), FadeOut(hyp_words), FadeOut(vect), *( c.animate.move_to(10 * c.get_center()) for c in charges[1:] ), ) self.add(l_field, charges[0], title2) self.wait() hyp_charge.next_to(charges[0], RIGHT, buff=0.5) vect.field = l_field self.play( VFadeIn(vect), FadeIn(hyp_charge), ) self.play( hyp_charge.animate.next_to(charges[0], LEFT, buff=0.5).set_anim_args(path_arc=PI), run_time=8, ) self.play( FadeOut(hyp_charge), FadeOut(vect), FadeOut(title2), ) # Shake the charge def wiggle_charge(charge, direction, run_time=2): return charge.animate.shift(direction).set_anim_args( rate_func=lambda t: wiggle(t, 3), run_time=run_time, suspend_mobject_updating=False, ) self.play(wiggle_charge(c1, 0.5 * UP)) self.wait(5) # Indicate speed ring = self.get_influence_ring(c1.get_center()) speed_words = Text("Speed = c", font_size=36) speed_words.set_backstroke(BLACK, 5) speed_words.ring = ring speed_words.add_updater(lambda m: m.next_to(m.ring.get_right(), LEFT, SMALL_BUFF)) self.add(ring, speed_words) self.play( wiggle_charge(c1, 0.5 * UP), VFadeIn(speed_words) ) self.wait(5) # Show second charge self.add(c2) self.play( self.frame.animate.move_to(Group(c1, c2)), run_time=3 ) amp = 0.5 for sign in [1, -1, 1, -1]: q1, q2 = (c1, c2) if sign > 0 else (c2, c1) ring = self.get_influence_ring(q1.get_center()) ring.set_stroke(opacity=0) dist = get_norm(q1.get_center() - q2.get_center()) self.add(ring) self.play(wiggle_charge(q1, sign * amp * UP)) globals().update(locals()) self.wait_until(lambda: ring.get_radius() > dist) amp *= 0.4 self.wait(4) class TestForMithuna(InteractiveScene): def construct(self): # Setup n_rows = 10 n_cols = 16 n_charges = n_rows * n_cols charges = Group(*( ChargedParticle( track_position_history=True, charge=10 / n_charges, radius=0.1, show_sign=False, ) for _ in range(n_charges) )) charges.arrange_in_grid(n_rows, n_cols, buff=0.5) charges.center() self.add(charges) columns = Group(*(charges[i::n_cols] for i in range(n_cols))) field = LorentzField( *charges, stroke_width=3, x_density=4.0, y_density=4.0, radius_of_suppression=0.1, # max_vect_len=np.inf, max_vect_len=None, norm_to_opacity_func=lambda n: np.clip(1.5 * n, 0, 0.7), ) self.add(field) c_dot = GlowDot().get_grid(1, 100, buff=0.5) c_dot.move_to(charges) c_dot.add_updater(lambda m, dt: m.shift(field.c * dt * RIGHT)) self.wait(0.1) # self.add(c_dot) self.play(LaggedStart( *( col.animate.shift(0.5 * UP).set_anim_args( rate_func=lambda t: wiggle(t, 6), suspend_mobject_updating=False, run_time=8, ) for col in columns ), lag_ratio=1 / n_cols )) self.wait(5) # # Rotate # self.play( # Rotate( # charges, # TAU, # # rate_func=wiggle, # suspend_mobject_updating=False, # run_time=5, # ) # ) class ShowTheEffectsOfOscillatingCharge(InteractiveScene): amplitude = 0.25 frequency = 0.5 direction = UP show_acceleration_vector = True origin = None axes_config = dict( axis_config=dict(stroke_opacity=0.7), x_range=(-10, 10), y_range=(-5, 5), z_range=(-3, 3), ) particle_config = dict( track_position_history=True, radius=0.15, ) acceleration_vector_config = dict() field_config = dict( max_vect_len=0.35, stroke_opacity=0.75, radius_of_suppression=1.0, height=10, x_density=4.0, y_density=4.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(2 * n, 0, 0.8) ) field_class = LorentzField def setup(self): super().setup() self.add_axes() self.add_axis_labels(self.axes) self.add_particles(self.axes) self.add_field(self.particles) if self.show_acceleration_vector: self.add_acceleration_vectors(self.particles) def add_axes(self): self.axes = ThreeDAxes(**self.axes_config) if self.origin is not None: self.axes.shift(self.origin - self.axes.get_origin()) self.add(self.axes) def add_axis_labels(self, axes): axis_labels = label = Tex("xyz") if axes.z_axis.get_stroke_opacity() > 0: axis_labels.rotate(PI / 2, RIGHT) axis_labels[0].next_to(axes.x_axis.get_right(), OUT) axis_labels[1].next_to(axes.y_axis.get_top(), OUT) axis_labels[2].next_to(axes.z_axis.get_zenith(), RIGHT) else: axis_labels[1].clear_points() axis_labels[0].next_to(axes.x_axis.get_right(), UP) axis_labels[2].next_to(axes.y_axis.get_top(), RIGHT) self.axis_labels = axis_labels self.add(self.axis_labels) def add_particles(self, axes): self.particles = self.get_particles() self.particles.add_updater(lambda m: m.move_to( axes.c2p(*self.oscillation_function(self.time)) )) for particle in self.particles: particle.ignore_last_motion() self.add(self.particles) def get_particles(self): return Group(ChargedParticle(**self.particle_config)) def add_field(self, particles): self.field = self.field_class(*particles, **self.field_config) self.add(self.field, particles) def add_acceleration_vectors(self, particles): self.acceleration_vectors = VGroup(*( AccelerationVector(particle) for particle in particles )) self.add(self.acceleration_vectors, self.particles) def oscillation_function(self, time): return self.amplitude * np.sin(TAU * self.frequency * time) * self.direction def construct(self): # Test self.wait(20) class SendingLittlePulses(ShowTheEffectsOfOscillatingCharge): axes_config = dict( axis_config=dict(stroke_opacity=0.7), x_range=(0, 10), y_range=(-3, 3), z_range=(-1, 1), ) field_config = dict( max_vect_len=0.25, stroke_opacity=0.75, radius_of_suppression=1.0, height=10, x_density=4.0, y_density=4.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(1.5 * n, 0, 0.8) ) def add_axis_labels(self, axes): pass def construct(self): # Setup self.axes.z_axis.set_stroke(opacity=0) self.axes.y_axis[-1] particle = self.particles[0] particle.clear_updaters() # Test for _ in range(10): shake_size = 0.5 + random.random() self.play( particle.animate.shift(0.06 * shake_size * UP), rate_func=lambda t: wiggle(t, 2), run_time=(shake_size), ) self.wait(random.choice([1, 2])) self.wait(4) class OscillateOnYOneDField(ShowTheEffectsOfOscillatingCharge): origin = 5 * LEFT axes_config = dict( axis_config=dict(stroke_opacity=0.7), z_axis_config=dict(stroke_opacity=0), x_range=(-3, 12), y_range=(-3, 3) ) field_config = dict( max_vect_len=1, stroke_opacity=1.0, radius_of_suppression=0.25, height=0, x_density=4.0, c=2.0, norm_to_opacity_func=None ) def construct(self): # Start wiggling axes = self.axes field = self.field particles = self.particles points = DotCloud(field.sample_points, color=BLUE) points.make_3d() points.set_radius(0.03) field.suspend_updating() particles.suspend_updating() self.add(points, particles) self.play(ShowCreation(points)) self.wait() self.time = 0 particles.resume_updating() for particle in particles: particle.ignore_last_motion() field.resume_updating() self.wait(24.5) paused_time = float(self.time) # Zoom in field.suspend_updating() particles.suspend_updating() self.remove(particles) self.remove(field) field_copy = field.copy() field_copy.clear_updaters() particle = particles[0].copy() particle.clear_updaters() self.add(field_copy, particle) frame = self.frame particle.save_state() particle.target = particle.generate_target() particle.target[0].set_radius(0.075) particle.target[1].scale(0.5) particle.target[1].set_stroke(width=1) self.play( frame.animate.set_height(3, about_point=axes.get_origin()), MoveToTarget(particle), self.acceleration_vectors.animate.set_stroke(opacity=0.2), run_time=2 ) # Go through points last_line = VMobject() last_ghost = Group() step = get_norm(field.sample_points[0] - field.sample_points[1]) for x in np.arange(1, 9): ghost = particle.copy() ghost.fade(0.5) dist = get_norm(axes.c2p(x * step, 0) - particle.get_center()) ghost.move_to(particle.get_past_position(dist / field.c)) line = Line( ghost.get_center(), axes.c2p(x * step, 0) ) line.set_stroke(WHITE, 1) elbow = Elbow(width=0.1) angle = line.get_angle() + 90 * DEGREES if x > 3: angle += 90 * DEGREES elbow.rotate(angle, about_point=ORIGIN) elbow.shift(line.get_end()) elbow.set_stroke(WHITE, 1) self.play( ShowCreation(line), FadeOut(last_line), FadeOut(last_ghost, scale=0), GrowFromCenter(ghost), FadeIn(elbow, time_span=(0.5, 1)), ) self.wait(0.5) last_line = Group(line, elbow) last_ghost = ghost self.play(FadeOut(last_line)) self.time = paused_time self.play( Restore(particle), frame.animate.to_default_state().set_anim_args(run_time=3) ) self.remove(field_copy, particle) self.add(particles, field) self.wait(5) class OscillateOnYTwoDField(ShowTheEffectsOfOscillatingCharge): particle_config = dict( track_position_history=True, radius=0.15, ) field_config = dict( max_vect_len=0.25, stroke_opacity=0.75, radius_of_suppression=0.25, height=10, x_density=4.0, y_density=4.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(1.5 * n, 0, 1.0) ) def construct(self): # Start wiggling axes = self.axes field = self.field particles = self.particles self.wait(60) class DiscussDecay(OscillateOnYOneDField): def construct(self): # Start wiggling axes = self.axes particles = self.particles self.wait(8) # Show graph axes_config = dict(self.axes_config) axes_config.pop("z_axis_config") axes2d = Axes(**axes_config) axes2d.shift(axes.get_origin() - axes2d.get_origin()) graph = axes2d.get_graph(lambda x: 2 / x, x_range=(0.5, 12)) graph.set_stroke(TEAL, 2) words = TexText(R"Decays proportionally to $\frac{1}{r}$") words[R"$\frac{1}{r}$"].scale(1.5, about_edge=LEFT).set_color(TEAL) words.move_to(2 * UP) particles[0].ignore_last_motion() self.play( ShowCreation(graph), Write(words), ) self.wait(20) class ChargeOnZAxis(ShowTheEffectsOfOscillatingCharge): default_frame_orientation = (-20, 70) direction = OUT origin = ORIGIN axes_config = dict( axis_config=dict(stroke_opacity=0.7), x_range=(-8, 8), y_range=(-6, 6), z_range=(-3, 3), ) particle_config = dict( show_sign=False, rotation=PI / 2, track_position_history=True, radius=0.2, ) field_config = dict( max_vect_len=0.5, stroke_opacity=0.7, radius_of_suppression=1.0, width=40, height=40, depth=0, x_density=4.0, y_density=4.0, z_density=1.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(n, 0, 0.8) ) def construct(self): # Test self.play(self.frame.animate.reorient(16, 71, 0), run_time=12) self.play(self.frame.animate.reorient(-15, 84, 0), run_time=6) self.play(self.frame.animate.reorient(-38, 64, 0), run_time=10) self.play(self.frame.animate.reorient(24, 66, 0), run_time=10) class ThreeCharges(ChargeOnZAxis): def get_particles(self): return Group(*( ChargedParticle(**self.particle_config) for n in range(3) )).arrange(UP, buff=2) class Introduce3dMovements(ChargeOnZAxis): axes_config = dict( axis_config=dict(stroke_opacity=0.7), x_range=(-5, 5), y_range=(-5, 5), z_range=(-3, 3), ) def construct(self): charge = self.particles[0] self.remove(self.particles) self.add(charge) # Test kw = dict(suspend_mobject_updating=False) frame = self.frame frame.reorient(-13, 71, 0).move_to([-0.24, 0.12, 0.04]).set_height(4.88) self.play( Rotate(charge, TAU, axis=UP, about_point=RIGHT, **kw), self.frame.animate.reorient(-17, 71, 0).move_to([-0.12, 0.17, 0.27]).set_height(7.16), run_time=6, ) self.play( self.frame.animate.reorient(-20, 69, 0).set_height(8).center(), Rotate(charge, TAU, axis=OUT, about_point=RIGHT, **kw), run_time=6, ) # self.wait(4) self.play( charge.animate.shift(0.8 * (UP + OUT)).set_anim_args(rate_func=lambda t: wiggle(t, 6), **kw), self.frame.animate.reorient(20, 71, 0).move_to([0.31, 0.54, -0.3]).set_height(8.22), run_time=8, ) self.play( charge.animate.shift(4 * DOWN).set_anim_args(rate_func=there_and_back, **kw), self.frame.animate.reorient(-21, 64, 0).move_to([0.31, 0.54, -0.3]).set_height(8.22), run_time=9, ) self.wait(4) class Introduce3dMovements3DVects(Introduce3dMovements): field_config = dict( max_vect_len=0.25, stroke_opacity=0.7, radius_of_suppression=1.0, width=20, height=20, depth=8, x_density=4.0, y_density=4.0, z_density=1.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(n, 0, 0.6) ) class CoulombLorentzExample(Introduce3dMovements): field_class = ColoumbPlusLorentzField field_config = dict( max_vect_len=0.3, stroke_opacity=0.7, radius_of_suppression=1.0, width=40, height=40, depth=0, x_density=4.0, y_density=4.0, z_density=1.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(n, 0, 0.8) ) class CoulombLorentzExample3D(Introduce3dMovements3DVects): field_class = ColoumbPlusLorentzField field_config = dict( max_vect_len=0.35, stroke_opacity=0.7, radius_of_suppression=1.0, width=10, height=10, depth=8, x_density=2.0, y_density=2.0, z_density=2.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(n, 0, 0.75) ) class RowOfCharges(ChargeOnZAxis): n_charges = 17 particle_buff = 0.25 particle_config = dict( rotation=PI / 2, track_position_history=True, radius=0.1, show_sign=False, charge=0.15 ) field_config = dict( max_vect_len=0.5, stroke_opacity=0.7, radius_of_suppression=1.0, width=30, height=30, depth=0, x_density=4.0, y_density=4.0, z_density=1.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(1.5 * n, 0, 0.8) ) show_acceleration_vector = False def construct(self): # Test self.play(self.frame.animate.reorient(-7, 62, 0).set_height(16), run_time=12) self.play(self.frame.animate.reorient(26, 70, 0), run_time=12) self.play(self.frame.animate.reorient(-26, 70, 0), run_time=12) def get_particles(self): return Group(*( ChargedParticle(**self.particle_config) for n in range(self.n_charges) )).arrange(UP, buff=self.particle_buff) class PlaneOfCharges(RowOfCharges): n_rows = 20 n_cols = 20 particle_buff = 0.1 grid_height = 6 particle_config = dict( rotation=PI / 2, track_position_history=True, radius=0.05, show_sign=False, charge=2.0 / 400.0, ) def get_particles(self): result = Group(*( ChargedParticle(**self.particle_config) for _ in range(self.n_rows * self.n_cols) )) result.arrange_in_grid( self.n_rows, self.n_cols, buff=self.particle_buff ) result.set_width(self.grid_height) result.rotate(PI / 2, UP) return result class RowOfChargesMoreCharges(RowOfCharges): n_charges = 100 particle_buff = 0.01 particle_config = dict( rotation=PI / 2, track_position_history=True, radius=0.05, show_sign=False, charge=0.0, ) field_config = dict( max_vect_len=0.5, stroke_opacity=0.7, radius_of_suppression=1.0, width=30, height=30, depth=0, x_density=4.0, y_density=4.0, z_density=1.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(1.5 * n, 0, 0.8) ) class AltRowOfCharges(RowOfCharges): def construct(self): # Test self.play(self.frame.animate.reorient(-4, 82, 0).move_to([3.12, -0.06, 1.0]).set_height(5.23), run_time=12) self.play(self.frame.animate.reorient(-20, 69, 0).set_height(8.00), run_time=12) self.play(self.frame.animate.reorient(-13, 78, 0).move_to([4.32, -0.91, 0.42]).set_height(5.27), run_time=12) class RowOfChargesXAxis(RowOfCharges): field_config = dict( max_vect_len=1.0, stroke_opacity=0.7, radius_of_suppression=0.25, width=40, height=0, depth=0, x_density=8.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(1.5 * n, 0, 0.8) ) axes_config = dict( axis_config=dict(stroke_opacity=0.7), x_range=(-20, 20), y_range=(-6, 6), z_range=(-3, 3), ) def setup(self): super().setup() self.frame.reorient(-26, 70, 0).set_height(16) self.axis_labels[0].set_x(8) def construct(self): # Form the field self.wait(20) # Zoom in self.play( self.frame.animate.reorient(-15, 84, 0).move_to([4.36, -1.83, 0.37]).set_height(5.59), run_time=3 ) # Show graph axes_kw = dict(self.axes_config) axes_kw.pop("z_range") axes = Axes(**axes_kw) graph1 = axes.get_graph(lambda r: 2.0 / r, x_range=(0.01, 20, 0.1)) graph2 = axes.get_graph(lambda r: 1.0 / r**0.3, x_range=(0.01, 20, 0.1)) graphs = VGroup(graph1, graph2) graphs.rotate(PI / 2, RIGHT, about_point=axes.get_origin()) graphs.set_flat_stroke(False) graphs.set_stroke(TEAL, 2) words = VGroup( TexText(R"Instead of decaying like $\frac{1}{r}$"), TexText(R"It decays much more gently"), ) words.fix_in_frame() words.to_edge(UP, buff=1.5) self.play( ShowCreation(graph1, run_time=2), FadeIn(words[0], 0.5 * UP) ) self.wait() self.play( FadeOut(words[0], 0.5 * UP), FadeIn(words[1], 0.5 * UP), Transform(*graphs) ) self.wait(6) class RowOfChargesXAxisMoreCharges(RowOfChargesXAxis): n_charges = 100 particle_buff = 0.1 particle_config = dict( rotation=PI / 2, track_position_history=True, radius=0.05, show_sign=False, charge=3.0 / 50, ) def construct(self): # Test self.wait(12) # Let the field form class RowOfChargesWiggleOnY(RowOfCharges): direction = UP class WavesIn3D(ChargeOnZAxis): field_config = dict( max_vect_len=0.5, stroke_opacity=0.25, radius_of_suppression=1.0, height=10, depth=10, x_density=4.0, y_density=4.0, z_density=1.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(0.5 * n, 0, 0.8) ) class WiggleHereWiggleThere(IntroduceEField): def construct(self): # Setup charges = Group(*( ChargedParticle(track_position_history=True) for _ in range(2) )) charges[0].to_edge(LEFT, buff=2.0) charges[1].to_edge(RIGHT, buff=2.0) dist = get_norm(charges[0].get_center() - charges[1].get_center()) for charge in charges: charge.ignore_last_motion() field = LorentzField( *charges, x_density=6.0, y_density=6.0, norm_to_opacity_func=lambda n: np.clip(0.5 * n, 0, 0.75) ) self.add(field) self.add(*charges) # Wiggles wiggle_kwargs = dict( rate_func=lambda t: wiggle(t, 3), run_time=1.5, suspend_mobject_updating=False, ) def wiggle_charge(charge, vect): ring = self.get_influence_ring(charge.get_center()) ring.set_stroke(opacity=2 * get_norm(vect)) self.add(ring) self.play(charge.animate.shift(vect).set_anim_args(**wiggle_kwargs)) self.wait_until(lambda: ring.get_radius() > dist, max_time=dist / 2.0) for n, charge in zip(range(6), it.cycle((charges))): wiggle_charge(charge, UP * (-1)**n / 2**n) class ScatteringOfPolarizedBeam(InteractiveScene): def construct(self): pass class CircularPolarization1D(ShowTheEffectsOfOscillatingCharge): default_frame_orientation = (-20, 70) amplitude = 0.2 field_config = dict( max_vect_len=1.0, stroke_opacity=0.85, radius_of_suppression=0.4, height=0, width=30, x_density=5.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(2 * n, 0, 0.8) ) particle_config = dict( track_position_history=True, radius=0.15, show_sign=False, ) def construct(self): # Setup frame = Square() frame.set_stroke(WHITE, 2) frame.set_fill(WHITE, 0.25) frame.rotate(PI / 2, UP) frame.move_to(self.axes.c2p(3, 0, 0)) frame.set_flat_stroke(False) field = self.field field_opacity_tracker = ValueTracker(1) field.add_updater(lambda m: m.set_stroke(opacity=field_opacity_tracker.get_value())) lone_vect_config = dict(self.field_config) lone_vect_config["width"] = 0 lone_vect_config["stroke_width"] = 3 lone_vect = LorentzField(self.particles[0], **lone_vect_config) lone_vect.sample_points = np.array([frame.get_center()]) # Pan self.play( self.frame.animate.reorient(81, 86, 0), run_time=12, ) self.add(lone_vect) self.play( FadeIn(frame), field_opacity_tracker.animate.set_value(0.25), self.frame.animate.reorient(41, 76, 0), run_time=5, ) self.play( self.frame.animate.reorient(79, 70, 0), run_time=12, ) self.play( field_opacity_tracker.animate.set_value(0.15), self.frame.animate.reorient(97, 84, 0), run_time=12 ) self.play( field_opacity_tracker.animate.set_value(0.35), self.frame.animate.reorient(59, 73, 0), run_time=12, ) def oscillation_function(self, time): angle = TAU * self.frequency * time return self.amplitude * np.array([-0, np.sin(angle), np.cos(angle)]) class PIPHelper(InteractiveScene): def construct(self): frame = Square(side_length=3) frame.set_stroke(WHITE, 4) frame.set_fill(WHITE, 0.25) frame.to_corner(UR) vect = Vector(RIGHT, stroke_color=BLUE) vect.shift(frame.get_center()) self.add(frame) self.play( Rotating(vect, -15 * TAU, about_point=frame.get_center()), run_time=30, rate_func=linear, ) class CircularPolarization2D(CircularPolarization1D): field_config = dict( max_vect_len=0.35, stroke_opacity=0.85, radius_of_suppression=0.5, height=30, width=30, x_density=4.0, y_density=4.0, c=2.0, norm_to_opacity_func=lambda n: np.clip(2 * n, 0, 0.8) ) def construct(self): # Test self.play( self.frame.animate.reorient(79, 78, 0), run_time=12, ) self.play( self.frame.animate.reorient(-83, 80, 0), run_time=24, ) self.play( self.frame.animate.reorient(17, 62, 0), run_time=18 ) class RandomRicochet(InteractiveScene): default_frame_orientation = (-36, 70) def construct(self): # Setup frame = self.frame plane, axes = self.get_plane_and_axes() self.add(plane, axes) # Light and Ball ball = TrueDot(radius=0.1) ball.make_3d() ball.set_color(RED) light = GlowDot(radius=2) light.move_to(5 * DOWN) self.add(light, ball) # Beams n_beams = 15 beams = VGroup() for _ in range(n_beams): point = 5 * normalize(np.random.uniform(-5, 5, 3)) beam = VMobject().set_points_as_corners([ light.get_center(), ball.get_center(), point ]) beam.set_stroke(YELLOW, 5) beam.set_flat_stroke(False) beam.insert_n_curves(100) beams.add(beam) frame.reorient(-36, 70, 0) frame.clear_updaters() frame.add_updater(lambda m, dt: m.increment_theta(dt * 3 * DEGREES)) for beam in beams: self.play( VShowPassingFlash( beam, time_width=0.3, run_time=1.5 ) ) def get_plane_and_axes(self): axes = ThreeDAxes(axis_config=dict(tick_size=0)) axes.set_stroke(opacity=0.5) plane = NumberPlane( x_range=axes.x_range, y_range=axes.y_range, background_line_style=dict( stroke_color=GREY_B, stroke_width=1.0, stroke_opacity=0.5, ) ) plane.axes.set_opacity(0) return plane, axes class PolarizedScattering(RandomRicochet): field_config = dict( width=20, height=20, x_density=5.0, y_density=5.0, stroke_color=BLUE, norm_to_opacity_func=lambda n: np.clip(n, 0, 0.75) ) def construct(self): # Setup frame = self.frame plane, axes = self.get_plane_and_axes() self.add(plane, axes) # Wave wave = OscillatingWave( axes, wave_len=2.0, color=YELLOW ) vects = OscillatingFieldWave(axes, wave) wave.set_stroke(opacity=0) vects_opacity_tracker = ValueTracker(0.75) vects.add_updater(lambda m: m.set_stroke(opacity=vects_opacity_tracker.get_value())) self.add(wave, vects) # Charge charge = ChargedParticle(show_sign=False, radius=0.1, track_position_history=True) charge.add_updater(lambda m: m.move_to( -0.5 * wave.xt_to_point(0, self.time) )) a_vect = AccelerationVector( charge, norm_func=lambda n: 0.5 * np.tanh(n) ) self.add(a_vect, charge) self.wait(6) # Result field charge.charge = 1.0 field = LorentzField(charge, **self.field_config) field_opacity_multiple = ValueTracker(1) def update_field(f): mult = field_opacity_multiple.get_value() f.set_stroke(opacity=mult * f.get_stroke_opacities()) return f field.add_updater(update_field) charge.ignore_last_motion() self.add(field, vects) self.play( self.frame.animate.reorient(15, 70, 0), run_time=12 ) # Show propagation rings = ProbagatingRings(axes.z_axis, n_rings=5, spacing=0.4) direction_vectors = VGroup(*( Arrow(v, 3 * v) for v in compass_directions(8) )) self.add(rings) self.play( LaggedStartMap(GrowArrow, direction_vectors, lag_ratio=0.1), field_opacity_multiple.animate.set_value(0.5), vects_opacity_tracker.animate.set_value(0.25), ) self.play( self.frame.animate.reorient(-32, 73, 0), run_time=8, ) self.play(VFadeOut(rings)) # More vertical direction direction_vectors.generate_target() for dv in direction_vectors.target: dv.scale(0.5) dv.shift(-0.5 * dv.get_start()) dv.rotate( 70 * DEGREES, axis=cross(dv.get_vector(), OUT), about_point=ORIGIN ) self.play(MoveToTarget(direction_vectors, run_time=2)) self.play(FadeOut(direction_vectors)) self.wait(6) class PolarizedScatteringYZ(PolarizedScattering): field_config = dict( width=0, height=20, depth=20, x_density=5.0, y_density=5.0, stroke_color=BLUE, norm_to_opacity_func=lambda n: np.clip(n, 0, 1.0) ) class OneOfManyCharges(InteractiveScene): speed = 1.5 wave_len = 3 default_frame_orientation=(0, 70, 0) dot_amplitude_factor = 0.2 plane_wave_field_config = dict( x_density=4.0, y_density=0.5, z_density=1.0, width=28, height=0, depth=12, tip_width_ratio=3, stroke_color=TEAL, stroke_width=3, stroke_opacity=0.5, norm_to_opacity_func=(lambda n: 2 * n), max_vect_len=1.0 ) plane_wave_amlpitude = 0.5 charge_field_config = dict( x_density=4.0, y_density=4.0, z_density=4.0, width=28, height=0, depth=16, tip_width_ratio=3, stroke_color=BLUE, stroke_width=3, norm_to_opacity_func=(lambda n: np.tanh(n)), ) charge_index = 3155 dots_dims = (11, 20, 20) dots_shape = (6, 4, 4) def setup(self): super().setup() # Axes self.axes = ThreeDAxes() self.add(self.axes) # Add incoming wave omega = TAU * self.speed / self.wave_len k = TAU / self.wave_len amplitude = 0.5 def plane_wave_func(points, t): return self.plane_wave_amlpitude * np.outer( np.cos(k * np.dot(points, RIGHT) - omega * t), OUT ) plane_wave = TimeVaryingVectorField( plane_wave_func, **self.plane_wave_field_config ) plane_wave.opacity_multiplier = ValueTracker(1) plane_wave.add_updater(lambda m: m.set_stroke(opacity=m.opacity_multiplier.get_value() * m.get_stroke_opacities())) self.plane_wave_func = plane_wave_func self.plane_wave = plane_wave self.add(plane_wave) # Add 3d grid of charges dots = DotCloud(color=BLUE) dots.to_grid(*self.dots_dims, height=None) dots.set_radius(0) dots.set_shape(*self.dots_shape) dots.set_radius(0.05) dots.make_3d(0.1) self.dot_center_refs = dots.copy() self.dot_center_refs.set_opacity(0) self.dot_center_refs.set_radius(0) def update_dots(dots): centers = self.dot_center_refs.get_points() offsets = plane_wave.func(centers) offsets *= self.dot_amplitude_factor dots.set_points(centers + offsets) dots.add_updater(update_dots) dots.opacity_multiplier = ValueTracker(0.75) dots.add_updater(lambda m: m.set_opacity(m.opacity_multiplier.get_value())) self.dots = dots self.add(dots) def construct(self): # Pan a little to start frame = self.frame self.play( frame.animate.reorient(25, 72, 0), run_time=4 ) # Create field based on the charges if self.charge_index > 0: charge = ChargedParticle( charge=-5, color=BLUE, show_sign=False, radius=0.1 ) charge.add_updater(lambda m: m.move_to(self.dots.get_points()[self.charge_index])) charge.update() charge.ignore_last_motion() charge_field = LorentzField( charge, center=charge.get_y() * UP, radius_of_suppression=0.2, **self.charge_field_config ) # acc_vect = AccelerationVector(charge) acc_vect = VectorizedPoint() self.add(charge_field, acc_vect, charge, self.dots) self.play( self.plane_wave.opacity_multiplier.animate.set_value(0), self.dots.opacity_multiplier.animate.set_value(0.1), FadeIn(charge, suspend_mobject_updating=False), VFadeIn(acc_vect), run_time=2, ) else: self.play( self.dots.opacity_multiplier.animate.set_value(0.2), run_time=2 ) self.play( frame.animate.reorient(25, 72, 0), run_time=8 ) self.play( frame.animate.reorient(-25, 72, 0), run_time=8 ) class AlternateCompositeChargesInPlane(OneOfManyCharges): dots_dims = (11, 10, 10) dots_shape = (6, 4, 4) random_seed = 2 def construct(self): # Objects frame = self.frame plane_wave = self.plane_wave dots = self.dots dots.set_radius(0.075) dots.opacity_multiplier.set_value(1) # Some panning frame.reorient(-17, 76, 0) self.play( frame.animate.reorient(16, 77, 0), run_time=12 ) # Reorient self.play( dots.animate.set_height(0, stretch=True), self.dot_center_refs.animate.set_height(0, stretch=True), frame.animate.reorient(0, 90).set_height(6), self.axes.y_axis.animate.set_stroke(opacity=0), plane_wave.opacity_multiplier.animate.set_value(0.5), run_time=2, ) self.wait(2) self.play( dots.opacity_multiplier.animate.set_value(0.25), plane_wave.opacity_multiplier.animate.set_value(0.0), ) self.wait() # Add charges w, h, d = self.dots_dims indices = np.arange(0, w * h * d, w) charge = ChargedParticle( color=BLUE, radius=dots.get_radius(), show_sign=False, ) charges = charge.replicate(len(indices)) charges.apply_depth_test(False) for charge, index in zip(charges, indices): charge.index = index charge.add_updater(lambda m: m.move_to(dots.get_points()[m.index] + 0.01 * DOWN)) charges.shuffle() charges[0].update() charges[0].ignore_last_motion() charge_field = LorentzField( charges[0], radius_of_suppression=0.2, **self.charge_field_config ) self.add(charges[0]) self.add(charge_field) self.wait(3) start_time = float(self.time) for n, charge in enumerate(charges[1:]): charge.update() charge.ignore_last_motion() if n < 2: time = 3 if n < 5: time = 2 elif n < 15: time = 1 else: time = 0.2 charge_field.charges.append(charge) n_charges = len(charge_field.charges) alpha = inverse_interpolate(start_time, start_time + 30, self.time) q_per_particle = interpolate(1, 0.5, alpha) for c2 in charge_field.charges: c2.charge = q_per_particle self.add(charge) self.wait(time) self.wait(30) class FullCompositeEffect(OneOfManyCharges): default_frame_orientation = (-25, 72, 0) dot_amplitude_factor = 0.1 index = 1.75 def construct(self): frame = self.frame dots = self.dots plane_wave = self.plane_wave min_x = dots.get_x(LEFT) max_x = dots.get_x(RIGHT) def new_pw_func(points, time): adj_points = points.copy() to_left = np.clip(adj_points[:, 0] - min_x, 0, np.inf) to_right = np.clip(adj_points[:, 0] - max_x, 0, np.inf) adj_points[:, 0] += (self.index - 1) * to_left - (self.index - 1) * to_right return self.plane_wave_func(adj_points, time) new_wave = TimeVaryingVectorField( new_pw_func, stroke_color=YELLOW, x_density=10, z_density=1, width=14, height=0, depth=0, max_vect_len=np.inf, norm_to_opacity_func=lambda n: 2 * n, ) new_wave.opacity_multiplier = ValueTracker(0) new_wave.add_updater(lambda m: m.set_stroke(opacity=m.get_stroke_opacities() * m.opacity_multiplier.get_value())) # Test self.add(new_wave) self.play( frame.animate.reorient(0, 90, 0).set_height(8).set_focal_distance(100), dots.opacity_multiplier.animate.set_value(0.75), plane_wave.opacity_multiplier.animate.set_value(0), new_wave.opacity_multiplier.animate.set_value(1), VFadeIn(new_wave), run_time=5 ) self.wait(15) class FullCompositeEffectIndexLessThanOne(FullCompositeEffect): index = 0.7 class ManyParallelPropagations(OneOfManyCharges): dots_dims = (11, 20, 20) dots_shape = (6, 0, 4) def construct(self): # Test dots = self.dots plane_wave = self.plane_wave self.axes.y_axis.set_opacity(0) frame = self.frame frame.reorient(0, 90, 0) frame.set_focal_distance(10) dots.set_radius(0.05) dots.opacity_multiplier.set_value(1) plane_wave.opacity_multiplier.set_value(0) rings = [] for _ in range(10): min_x, min_y, min_z = self.dot_centers[0] max_x, max_y, max_z = self.dot_centers[-1] for x in np.linspace(min_x, max_x, 6): for z in np.linspace(min_z, max_z, 10): ring = get_influence_ring([x, 0, z], speed=self.speed, max_width=1, width_decay_exp=2) ring.rotate(PI / 2, RIGHT) rings.append(ring) self.add(ring) self.wait() for ring in rings: if ring.get_stroke_width() < 0.01: self.remove(ring) self.wait(5) class ResponsiveCharge(InteractiveScene): def construct(self): # Driving chrage charge1 = ChargedParticle(charge=0.25) charge1.add_spring_force(k=10) charge1.move_to(0.3 * DOWN) # Responsive charge k = 20 charge2 = ChargedParticle(charge=1.0, radius=0.1, show_sign=False) charge2.move_to(2.5 * RIGHT) # charge2.add_field_force(field) charge2.add_spring_force(k=k) charge2.add_force(lambda p: wave.xt_to_point(p[0], wave.time) * [0, 1, 1]) # charge2.fix_x() self.add(charge2) # E field # field_type = ColoumbPlusLorentzField field_type = LorentzField field = field_type( charge1, charge2, x_density=4.0, y_density=4.0, norm_to_opacity_func=lambda n: np.clip(0.5 * n, 0, 1), c=1.0, ) self.add(field) # Pure wave axes = ThreeDAxes() wave = OscillatingWave(axes, y_amplitude=1.0, z_amplitude=0.0, wave_len=2.0) field_wave = OscillatingFieldWave(axes, wave) wave.set_stroke(opacity=0.5) self.add(axes, wave, field_wave) # omega = (wave.speed / wave.wave_len) * TAU # omega_0 = math.sqrt(k / charge2.mass) # v0 = omega / (omega_0**2 - omega**2) # charge2.velocity = v0 * UP self.wait(20) # Plane plane = NumberPlane() plane.fade(0.5) self.add(plane) # Test wiggle self.play( charge1.animate.shift(UP).set_anim_args( rate_func=wiggle, run_time=3, ) ) self.wait(4)
from manim_imports_ext import * from _2023.barber_pole.objects import * class WhiteLightAsASum(InteractiveScene): def construct(self): # Initial orientation frame = self.frame frame.reorient(0, 90) # Create axes n_colors = 15 axes_width = 9.0 x_max = 8 spectral_axes = VGroup(*( ThreeDAxes((0, x_max), (-1, 1), (-1, 1)) for _ in range(n_colors) )) spectral_axes.set_width(axes_width) spectral_axes.arrange(UP, buff=0.05) white_axes = ThreeDAxes((0, x_max), (-1, 1), (-1, 1)) white_axes.set_width(axes_width) white_axes.shift(2 * DOWN) spectral_axes.next_to(white_axes, UP) all_axes = [white_axes, *spectral_axes] for axes in all_axes: axes.y_axis.set_opacity(0) for axes in spectral_axes: axes.z_axis.stretch(0.5, 2) white_axes.z_axis.stretch(1.5, 2) # Create individual waves white_parts = VGroup() spectral_waves = VGroup() alphas = np.linspace(0.0, 1.0, n_colors) for alpha, s_axes in zip(alphas, spectral_axes): wave_len = interpolate(1.0, 2.0, alpha) for axes, group in [(s_axes, spectral_waves), (white_axes, white_parts)]: wave = OscillatingWave( axes, y_amplitude=0, z_amplitude=1, wave_len=wave_len, color=get_spectral_color(1 - alpha) ) group.add(wave) # Show white wave white_wave = MeanWave(white_parts) white_wave.set_stroke(width=1) white_vects = OscillatingFieldWave(white_axes, white_wave, tip_width_ratio=3) self.add(white_axes, white_wave, white_vects) self.wait(5) # Show spectral parts symbols = Tex("=" + "+" * (n_colors - 1)) symbols.scale(2) symbols.rotate(90 * DEGREES) for symbol, a1, a2 in zip(symbols, all_axes, all_axes[1:]): symbol.move_to(VGroup(a1, a2)) spectral_vect_waves = VGroup() for sa, sw in zip(spectral_axes, spectral_waves): vwave = OscillatingFieldWave(sa, sw, tip_width_ratio=3) sw.set_stroke(width=1) spectral_vect_waves.add(vwave) self.play( frame.animate.reorient(50, 65, 0).move_to([0.6, 2.9, -0.16]).set_height(11).set_anim_args(run_time=3), LaggedStartMap(FadeIn, spectral_axes), LaggedStartMap(VFadeIn, spectral_waves), LaggedStartMap(VFadeIn, spectral_vect_waves), LaggedStartMap(FadeIn, symbols), ) self.play( self.frame.animate.reorient(19, 65, 0).move_to([0.6, 2.9, -0.16]).set_height(11.00), run_time=8 ) return # Scrap arrows = VGroup(*( Arrow( sa.get_left(), interpolate(white_axes.get_corner(UR), white_axes.get_corner(DR), alpha), buff=0.3, stroke_color=wave.get_color() ) for sa, wave, alpha in zip( spectral_axes, spectral_waves, np.linspace(0, 1, n_colors), ) )) pass class AddTwoSineWaves(InteractiveScene): def construct(self): # Setup axes axes1, axes2, axes3 = all_axes = [self.get_axes() for _ in range(3)] for axes, y in zip(all_axes, [2.5, 0, -3.0]): axes.set_y(y) axes.to_edge(RIGHT) # First two waves wave1 = self.get_variable_wave(axes1, color=BLUE, func_name="f(t)", index="1") wave2 = self.get_variable_wave(axes2, color=YELLOW, func_name="g(t)", index="2", omega=PI) self.play( FadeIn(axes1), ShowCreation(wave1[0]), ) self.play(LaggedStartMap(FadeIn, wave1[2]),) self.change_all_parameters(wave1, 0.5, PI, PI / 4) self.wait() self.play( FadeIn(axes2), ShowCreation(wave2[0]), ) self.play(LaggedStartMap(FadeIn, wave2[2]),) self.change_all_parameters(wave2, 0.75, 2 * PI, PI / 2) self.wait() self.add(axes2) self.add(wave2) # Sum wave wave3 = axes3.get_graph( lambda x: wave1.func(x) + wave2.func(x), color=GREEN, bind=True ) wave3_label = Tex("f(t) + g(t)", font_size=36) wave3_label.move_to(axes3.c2p(0.5, 1.5), DL) self.play(LaggedStart( TransformFromCopy(axes1, axes3), TransformFromCopy(axes2, axes3), TransformFromCopy(wave1.labels[3]["f(t)"], wave3_label["f(t)"]), TransformFromCopy(wave2.labels[3]["g(t)"], wave3_label["+ g(t)"]), lag_ratio=0.05 )) self.play( TransformFromCopy(wave1[0], wave3), TransformFromCopy(wave2[0], wave3), ) self.wait() # Some example changes self.change_wave_parameter(wave1, "phi", TAU) self.change_wave_parameter(wave2, "A", 0.5) self.change_wave_parameter(wave1, "omega", 4.5) self.change_wave_parameter(wave1, "phi", 3 * PI / 4) self.change_wave_parameter(wave2, "omega", 3 * PI) self.change_wave_parameter(wave2, "phi", 5) self.wait() # Lock both frequencies frame = self.frame t2c = {R"\omega": GOLD} top_words = TexText( R"If both have matching \\ frequencies, $\omega$...", font_size=36, t2c=t2c ) top_words.next_to(VGroup(wave1.labels, wave2.labels), LEFT, buff=2.0) omega_locks = VGroup() for wave in [wave1, wave2]: lock = SVGMobject("lock") lock.match_height(wave.labels[1]) lock.next_to(wave.labels[1], LEFT, SMALL_BUFF) omega_locks.add(lock) omega_locks.set_color(GOLD) top_arrows = VGroup(*( Arrow(top_words.get_right(), lock.get_left()) for lock in omega_locks )) self.play( frame.animate.set_x(-5), FadeIn(top_words, 0.5 * LEFT), LaggedStartMap(ShowCreation, top_arrows), run_time=2, ) self.play( LaggedStartMap(FadeIn, omega_locks), *self.get_wave_change_animations(wave1, "omega", PI), *self.get_wave_change_animations(wave2, "omega", PI), run_time=2 ) self.wait() # Graph is also sine low_words = TexText( R"Then this is also a sine \\ wave with frequency $\omega$", font_size=36, t2c=t2c, ) low_words.align_to(top_words, LEFT) low_words.match_y(axes3).shift(UP) low_arrow = Arrow(low_words.get_right(), axes3.get_left()) self.play( FadeTransform(top_words.copy(), low_words), FadeIn(low_arrow, 2 * DOWN), ) self.wait() # Show lower function label sum_sine = Tex(R"= 1.00\sin(\omega t +2.00)", t2c={R"\omega": GOLD}, font_size=36) sum_sine.next_to(wave3_label, RIGHT, SMALL_BUFF) sum_A = sum_sine.make_number_changable("1.00") sum_phi = sum_sine.make_number_changable("+2.00", include_sign=True) sum_A.set_color(RED) sum_phi.set_color(PINK) sum_parameters = VGroup(sum_A, sum_phi) def update_sum_parameters(params): A1 = wave1.trackers[0].get_value() A2 = wave2.trackers[0].get_value() phi1 = wave1.trackers[2].get_value() phi2 = wave2.trackers[2].get_value() z3 = A1 * np.exp(phi1 * 1j) + A2 * np.exp(phi2 * 1j) params[0].set_value(abs(z3)) params[1].set_value(np.log(z3).imag) sum_parameters.add_updater(update_sum_parameters) self.play(Write(sum_sine)) self.add(sum_parameters) # Ask about sum parameters param_arrows = VGroup() param_qmarks = VGroup() for param in sum_parameters: arrow = Vector(0.5 * DOWN) arrow.next_to(param, UP, buff=SMALL_BUFF) arrow.match_color(param) q_mark = Text("?") q_mark.match_color(param) q_mark.next_to(arrow, UP, SMALL_BUFF) param_arrows.add(arrow) param_qmarks.add(q_mark) self.play(ShowCreation(arrow), FadeIn(q_mark)) self.wait() # Change the other parameters a bunch self.change_wave_parameter(wave1, "phi", 0) self.change_wave_parameter(wave1, "A", 1.0) self.change_wave_parameter(wave2, "phi", -0.8, run_time=4) self.change_wave_parameter(wave2, "A", 0.75) self.change_wave_parameter(wave1, "phi", PI / 3) # Clear the board low_fade_rect = FullScreenFadeRectangle() low_fade_rect.set_height(5.25, about_edge=DOWN, stretch=True) low_fade_rect.set_fill(BLACK, 0.85) self.play(LaggedStart( FadeOut(top_words), FadeOut(top_arrows), FadeOut(low_words), FadeOut(low_arrow), FadeOut(param_arrows), FadeOut(param_qmarks), FadeIn(low_fade_rect), )) # Show first and second phasors phasor1 = self.get_phasor(axes1, wave1) phasor2 = self.get_phasor(axes2, wave2) for wave, phasor in [(wave1, phasor1), (wave2, phasor2)]: # Setup and add phasor A_label = wave.labels[0][:2] phi_label = wave.labels[2][:2] phasor.A_label = A_label.copy() phasor.A_label.scale(0.75) max_A_height = phasor.A_label.get_height() phasor.A_label.vector = phasor.vector phasor.A_label.add_updater(lambda m: m.set_height(min(max_A_height, m.vector.get_length()))) phasor.A_label.add_updater(lambda m: m.next_to( m.vector.pfp(0.5), normalize(rotate_vector( m.vector.get_vector(), (1 if m.vector.get_angle() > 0 else -1) * 90 * DEGREES )), buff=0.05, )) phasor.phi_label = phi_label.copy() phasor.phi_label.scale(0.65) max_phi_height = phasor.phi_label.get_height() phasor.phi_label.plane = phasor.plane phasor.phi_label.arc = phasor.arc phasor.phi_label.add_updater(lambda m: m.set_height(min(max_phi_height, m.arc.get_height()))) phasor.phi_label.add_updater(lambda m: m.move_to(m.plane.n2p( 1.5 * m.plane.p2n(m.arc.pfp(0.5)) ))) self.play( FadeIn(phasor.plane, LEFT), FadeIn(phasor.rot_vect, LEFT), ) self.wait() # Show y coordinate wave.output_indicator = self.get_output_indicator( wave.axes, wave.wave, phasor.t_tracker ) self.play( FadeIn(phasor.y_line), FadeIn(phasor.y_dot), FadeIn(wave.output_indicator), ) self.play( phasor.t_tracker.animate.set_value(4), run_time=8, rate_func=linear, ) self.wait() self.play( FadeOut(wave.output_indicator), FadeOut(phasor.y_line), FadeOut(phasor.y_dot), ) self.add( phasor.vector, phasor.rot_vect, ) # Show amplitude and phase self.play(TransformFromCopy(A_label, phasor.A_label)) self.play( wave.trackers[0].animate.set_value(1.5 * wave.trackers[0].get_value()), run_time=2, rate_func=there_and_back, ) self.wait() self.play( TransformFromCopy(phi_label, phasor.phi_label), FadeIn(phasor.arc), ) self.play( wave.trackers[2].animate.set_value(wave.trackers[2].get_value() + PI / 2), run_time=4, rate_func=there_and_back, ) # Shrink rect self.play( low_fade_rect.animate.set_height(3, about_edge=DOWN, stretch=True) ) # Show the sum sum_plane = ComplexPlane( (-1, 1), (-1, 1), background_line_style=dict(stroke_color=GREY_B, stroke_width=1), faded_line_style=dict(stroke_color=GREY_B, stroke_width=0.5, stroke_opacity=0.25), faded_line_ratio=4, ) sum_plane.set_height(2.0) sum_plane.match_x(phasor1) sum_plane.match_y(axes3) sum_plane.to_edge(DOWN, buff=MED_SMALL_BUFF) low_vects = VGroup(*( Vector( stroke_width=3, stroke_color=wave.wave.get_color(), ) for wave in [wave1, wave2] )) def update_low_vects(vects): z1 = phasor1.get_z() z2 = phasor2.get_z() vects[0].put_start_and_end_on( sum_plane.n2p(0), sum_plane.n2p(z1), ) vects[1].put_start_and_end_on( sum_plane.n2p(z1), sum_plane.n2p(z1 + z2), ) low_vects.add_updater(update_low_vects) self.play( FadeIn(sum_plane), FadeOut(low_fade_rect), ) self.wait() self.play( TransformFromCopy(phasor1.rot_vect, low_vects[0]), TransformFromCopy(phasor2.rot_vect, low_vects[1]), ) self.add(low_vects) self.wait() # Show the sum of the two vectors sum_vect = Vector(stroke_color=wave3.get_color(), stroke_width=3) sum_vect.add_updater(lambda m: m.put_start_and_end_on( sum_plane.n2p(0), sum_plane.n2p(phasor1.get_z() + phasor2.get_z()), )) sum_output_indicator = self.get_output_indicator(axes3, wave3, phasor1.t_tracker) def show_rotation(max_t=4): for phasor in [phasor1, phasor2]: phasor.t_tracker.set_value(0) self.add( wave1.output_indicator, wave2.output_indicator, sum_output_indicator, ) self.play( phasor1.t_tracker.animate.set_value(max_t), phasor2.t_tracker.animate.set_value(max_t), run_time=4 * max_t, rate_func=linear, ) self.play(*map(FadeOut, ( wave1.output_indicator, wave2.output_indicator, sum_output_indicator, ))) self.play(ShowCreation(sum_vect)) show_rotation() self.wait() # Emphasize amplitude and phase of the new wave param_rects = VGroup(*( SurroundingRectangle(param).match_color(param) for param in sum_parameters )) param_rects.set_stroke(width=2) sum_arc = Arc(angle=sum_parameters[1].get_value(), radius=0.5, arc_center=sum_plane.n2p(0)) sum_arc.set_stroke(WHITE, 2) sum_A_copy, sum_phi_copy = sum_parameters.copy() sum_A_copy.scale(0.5) sum_A_copy.rotate(sum_vect.get_angle()) sum_A_copy.next_to(sum_vect.get_center(), UP, buff=0.05) sum_phi_copy.scale(0.25) sum_phi_copy.next_to(sum_arc, RIGHT, buff=0.05) self.play( ShowCreation(param_arrows[0]), FadeIn(param_qmarks[0]), ShowCreation(param_rects[0]), ) self.wait() self.play( TransformFromCopy(sum_parameters[0], sum_A_copy), ) self.wait() self.play( ReplacementTransform(*param_arrows), ReplacementTransform(*param_qmarks), ReplacementTransform(*param_rects), ) self.wait() self.play( TransformFromCopy(sum_parameters[1], sum_phi_copy), ShowCreation(sum_arc) ) self.wait() self.play(*map(FadeOut, ( sum_A_copy, sum_phi_copy, sum_arc, param_arrows[1], param_qmarks[1], param_rects[1] ))) self.wait() # Play around with some alternate values, again phi0 = PI / 6 self.play( *self.get_wave_change_animations(wave1, "phi", phi0), *self.get_wave_change_animations(wave2, "phi", phi0), run_time=3 ) self.wait() self.play( *self.get_wave_change_animations(wave2, "phi", phi0 - PI), run_time=3 ) self.wait() self.change_wave_parameter(wave2, "phi", phi0 - PI / 2, run_time=3) self.change_wave_parameter(wave2, "A", 0.2) self.wait() # Highlight sum offset self.play(FlashAround(low_vects, run_time=2)) self.wait() show_rotation(4) # Bigger and smaller shift for value in [0.1, 0.3]: self.change_wave_parameter(wave2, "A", value) self.wait() def get_axes( self, x_range=(0, 8), y_range=(-1, 1), width=11, height=1.25 ): result = Axes( x_range, y_range, width=width, height=height ) result.add_coordinate_labels(font_size=16, buff=0.15) return result def get_variable_wave( self, axes, color=YELLOW, func_name="f(t)", A=1.0, omega=TAU, phi=0.0, index="", label_font_size=36, parameter_font_size=24, A_color=RED, k_color=GOLD, phi_color=PINK, func_name_coords=(0.5, 1.25) ): A_tracker = ValueTracker(A) k_tracker = ValueTracker(omega) phi_tracker = ValueTracker(phi) trackers = Group(A_tracker, k_tracker, phi_tracker) A_tex = f"A_{{{index}}}" omega_tex = Rf"\omega_{{{index}}}" phi_tex = Rf"\phi_{{{index}}}" t2c = { A_tex: A_color, omega_tex: k_color, phi_tex: phi_color, } get_A = A_tracker.get_value get_k = k_tracker.get_value get_phi = phi_tracker.get_value def func(x): return get_A() * np.sin(get_k() * x + get_phi()) wave = axes.get_graph( func, stroke_color=color, bind=True ) labels = VGroup(*( Tex(tex, font_size=parameter_font_size, t2c=t2c) for tex in [ f"{A_tex} = 1.00", f"{omega_tex} = 1.00", f"{phi_tex} = 1.00", ] )) labels.arrange(DOWN, aligned_edge=RIGHT) labels.next_to(axes, LEFT, MED_LARGE_BUFF) for label, tracker in zip(labels, trackers): label.tracker = tracker label.value = label.make_number_changable("1.00") label.add_updater(lambda m: m.value.set_value(m.tracker.get_value())) name_label = Tex( fR"{func_name} = {A_tex} \sin({omega_tex} t + {phi_tex})", tex_to_color_map=t2c, font_size=label_font_size, ) name_label.move_to(axes.c2p(*func_name_coords), DL) labels.add(name_label) result = Group(wave, trackers, labels) result.axes = axes result.func = func result.wave = wave result.trackers = trackers result.labels = labels return result def get_phasor(self, axes, wave_group, plane_height=2.0): # Plane plane = ComplexPlane( (-1, 1), (-1, 1), background_line_style=dict(stroke_color=GREY_B, stroke_width=1), faded_line_style=dict(stroke_color=GREY_B, stroke_width=0.5, stroke_opacity=0.5), faded_line_ratio=4, ) plane.set_height(plane_height) plane.next_to(axes, LEFT, buff=4.0) # Initial arrow graph, trackers, labels = wave_group get_A, get_omega, get_phi = (t.get_value for t in trackers) def get_z0(): return get_A() * np.exp(get_phi() * 1j) vector = Arrow( plane.n2p(0), plane.n2p(1), buff=0, stroke_color=GREY_B, stroke_width=3, stroke_opacity=0.5 ) vector.add_updater(lambda m: m.put_start_and_end_on( plane.n2p(0), plane.n2p(get_z0()) )) # Arc arc = always_redraw(lambda: Arc( angle=get_phi(), radius=min(plane_height / 6, 0.5 * vector.get_length()), arc_center=plane.n2p(0) ).set_stroke(WHITE, 1)) # t tracker t_tracker = ValueTracker(0) get_t = t_tracker.get_value rot_vect = vector.copy() rot_vect.set_stroke(graph.get_color(), opacity=1) def get_z(): return np.exp(get_omega() * get_t() * 1j) * get_z0() rot_vect.add_updater(lambda m: m.put_start_and_end_on( plane.n2p(0), plane.n2p(get_z()) )) # Y glow dot y_dot = GlowDot(color=graph.get_color()) y_dot.add_updater(lambda m: m.match_x(plane).match_y(rot_vect.get_end())) y_line = Line() y_line.set_stroke(WHITE, 1, 0.5) globals().update(locals()) y_line.add_updater(lambda m: m.put_start_and_end_on( rot_vect.get_end(), y_dot.get_center() )) # Result result = Group(plane, vector, arc, t_tracker, rot_vect, y_dot, y_line) result.plane = plane result.vector = vector result.arc = arc result.t_tracker = t_tracker result.rot_vect = rot_vect result.y_dot = y_dot result.y_line = y_line result.get_z = get_z return result def get_output_indicator(self, axes, graph, t_tracker): # Triangle func = graph.underlying_function get_t = t_tracker.get_value triangle = ArrowTip(angle=PI / 2) triangle.set_height(0.1) triangle.set_fill(GREY_C) triangle.add_updater(lambda m: m.move_to(axes.x_axis.n2p(get_t()), UP)) # Glow dot dot = GlowDot(color=graph.get_color()) dot.add_updater(lambda m: m.move_to(axes.c2p(get_t(), func(get_t())))) # Vertical line v_line = Line() v_line.set_stroke(WHITE, 1, 0.5) v_line.add_updater(lambda m: m.put_start_and_end_on( axes.x_axis.n2p(get_t()), dot.get_center() )) result = Group(dot, v_line) return result def get_wave_change_animations(self, wave_group, parameter, value): index = ["A", "omega", "phi"].index(parameter) if len(parameter) > 1: parameter = Rf"\{parameter}" wave, trackers, labels = wave_group rect1 = SurroundingRectangle(labels[index]) rect2 = SurroundingRectangle(labels[3][parameter]) rect1.stretch(1.1, 0, about_edge=LEFT) rect2.stretch(1.25, 0, about_edge=LEFT) rects = VGroup(rect1, rect2) rects.match_color(labels[index][0]) return [ VFadeInThenOut(rects, rate_func=lambda t: there_and_back(t)**0.5), trackers[index].animate.set_value(value), ] def change_wave_parameter(self, wave_group, parameter, value, run_time=2): self.play( *self.get_wave_change_animations(wave_group, parameter, value, ), run_time=run_time ) def change_all_parameters(self, wave_group, *values, **kwargs): parameters = ["A", "omega", "phi"] for parameter, value in zip(parameters, values): if value is not None: self.change_wave_parameter(wave_group, parameter, value) class AddTwoRotatingVectors(InteractiveScene): def construct(self): pass class WavePlusLayerInfluence(InteractiveScene): default_frame_orientation = (-90, 0, 90) def construct(self): # Initialize axes frame = self.frame boxes = FullScreenRectangle().replicate(3) boxes.set_height(FRAME_HEIGHT / 3, stretch=True) boxes.arrange(DOWN, buff=0) x_range = (-12, 12) y_range = (-1, 1) z_range = (-1, 1) top_axes, mid_axes, low_axes = ( ThreeDAxes(x_range, y_range, z_range), Axes(x_range, y_range), Axes(x_range, y_range), ) all_axes = VGroup(top_axes, mid_axes, low_axes) all_axes.move_to(boxes[1]) low_axes.move_to(boxes[2]) for axes in all_axes: axes.set_stroke(opacity=0) axes.x_axis.set_stroke(opacity=0.5) # Initialize labels text_kw = dict(font_size=36) labels = VGroup( Text("Incoming light", **text_kw), Text("Wave from layer oscillations", **text_kw), Text("Net effect", **text_kw), ) for label, box in zip(labels, boxes): label.next_to(box.get_corner(UL), DR, buff=MED_SMALL_BUFF) labels[2].shift(0.25 * UP) # Initialize waves wave1 = OscillatingWave( top_axes, y_amplitude=0.75, z_amplitude=0.0, wave_len=4.0, speed=1.5, ) wave2_scale_tracker = ValueTracker(0.2) def wave2_func(x): offset_x = np.abs(x) + wave1.wave_len / 4 y, z = wave1.xt_to_yz(offset_x, wave1.time) return wave2_scale_tracker.get_value() * y def sum_func(x): return wave1.xt_to_yz(x, wave1.time)[0] + wave2_func(x) wave2 = mid_axes.get_graph(wave2_func, bind=True) wave2.set_stroke(BLUE, 2) wave3 = low_axes.get_graph(sum_func, bind=True) wave3.set_stroke(TEAL, 2) # Vect waves field_kw = dict(stroke_width=2, stroke_opacity=0.5, tip_width_ratio=3) vect_wave1 = OscillatingFieldWave(top_axes, wave1, **field_kw) vect_wave2 = GraphAsVectorField( mid_axes, wave2_func, stroke_color=wave2.get_color(), **field_kw ) vect_wave3 = GraphAsVectorField( low_axes, sum_func, stroke_color=wave3.get_color(), **field_kw ) for vect_wave in [vect_wave1, vect_wave2, vect_wave3]: vect_wave.add_updater(lambda m: m.reset_sample_points(), index=0) wave1_group = VGroup(wave1, vect_wave1) wave2_group = VGroup(wave2, vect_wave2) wave3_group = VGroup(wave3, vect_wave3) # Layers of charges layer_xs = np.arange(0, 6, 0.25) layers = Group() for x in layer_xs: charges = DotCloud(color=BLUE) charges.to_grid(31, 15) charges.make_3d() charges.set_shape(3, 3) charges.set_radius(0.035) charges.set_opacity(0.5) charges.rotate(90 * DEGREES, UP) charges.sort_points(lambda p: np.dot(p, OUT + UP)) charges.x = x charges.amplitude_tracker = ValueTracker(0) charges.add_updater(lambda m: m.move_to(mid_axes.c2p( m.x, m.amplitude_tracker.get_value() * wave1.xt_to_yz(m.x, wave1.time)[0], 0, ))) layers.add(charges) # Glass glass = VCube() glass.set_fill(opacity=0.25) glass.deactivate_depth_test() glass.set_shading(0.5, 0.5, 0) buff = 0.1 glass.set_shape(*( dim + buff for dim in layers.get_shape() )) glass.move_to(layers, LEFT) glass.sort(lambda p: -p[0]) glass.set_stroke(WHITE, 0.5, 0.5) # Show initial wave, then add layers frame = self.frame frame.reorient(-135, 20, 135) self.add(top_axes) self.add(wave1, vect_wave1) self.wait(2) self.play( Write(glass, time_span=(0, 2)), frame.animate.reorient(-110, 10, 110).set_anim_args(run_time=4), ) self.play( LaggedStart(*( layer.amplitude_tracker.animate.set_value(0.1) for layer in layers ), lag_ratio=0, time_span=(0, 2)), LaggedStart(*( FadeIn(layer, suspend_mobject_updating=False) for layer in layers ), lag_ratio=0, time_span=(0, 2)), ) self.play( self.frame.animate.reorient(-90, -40, 90), FadeOut(glass), run_time=9 ) self.wait(3) # Go back to just one layer self.play( LaggedStart(*( FadeOut(charges, suspend_mobject_updating=False) for charges in layers[1:] ), run_time=5, lag_ratio=0.25), layers[0].amplitude_tracker.animate.set_value(0.2), self.frame.animate.reorient(-90, -20, 90), run_time=5 ) self.wait(3) # Add the second order wave, then separate self.play( VFadeIn(wave2_group), FadeIn(mid_axes), run_time=1 ) self.wait(5) self.play( top_axes.animate.move_to(boxes[0], DOWN), frame.animate.reorient(-90, 0, 90).set_focal_distance(100), LaggedStartMap(FadeIn, labels[:2], shift=UP), run_time=2 ) self.wait(6) # Show sum (todo, add + and =) plus, eq = plus_eq = Tex("+=", font_size=72) eq.rotate(90 * DEGREES) plus.move_to(all_axes[0:2]) eq.move_to(all_axes[1:3]) plus_eq.set_x(FRAME_WIDTH / 4) self.play( LaggedStartMap(FadeIn, plus_eq), ShowCreation(low_axes), ) self.play( VFadeIn(wave3_group), Write(labels[2]), ) self.wait(12) # Comment on reflected light reflection_label = VGroup( Vector(2 * LEFT), Text("Reflected light", font_size=36), ) reflection_label.arrange(RIGHT) reflection_label.next_to(mid_axes.get_origin(), LEFT, buff=0.75) reflection_label.shift(0.5 * DOWN) reflection_label.set_color(YELLOW) self.play( GrowArrow(reflection_label[0]), Write(reflection_label[1]), ) self.wait(8) # Cover left half cover = FullScreenFadeRectangle() cover.set_fill(BLACK, 0.9) cover.stretch(0.5, 0, about_edge=LEFT) self.add(cover, charges, labels) self.play( FadeOut(reflection_label), FadeIn(cover), plus_eq.animate.set_x(1.5), frame.animate.set_x(0.5 * FRAME_WIDTH - 2), *( label.animate.set_x(FRAME_WIDTH - 2.5, RIGHT) for label in labels ), run_time=2 ) self.wait(9) # Compare wave1.stop_clock() wave1_copy = wave1.copy() wave1_copy.clear_updaters() wave1_copy.set_stroke(width=3) self.wait() self.add(wave1_copy, cover, charges) self.play( wave1_copy.animate.match_y(wave3), run_time=2 ) self.wait() # Indicate tiny change def find_peak(wave, threshold=1e-2): points = wave.get_points() sub_points = points[int(0.6 * len(points)):int(0.8 * len(points))] top_y = wave.get_top()[1] index = np.argmax(sub_points[:, 1]) return sub_points[index] line = Line(find_peak(wave3), find_peak(wave1_copy)) shift_arrow = Vector( line.get_length() * LEFT * 2, stroke_width=3, max_tip_length_to_length_ratio=10, ) shift_arrow.next_to(line, UP, buff=0.2) shift_label = Text("shift", font_size=24) always(shift_label.next_to, shift_arrow, UP) self.play( ShowCreation(shift_arrow), Write(shift_label), ) self.wait() # Play with different strengths net_stretch = 1.0 for stretch_factor in [3.0, 0.5, 2.0, 0.5, 1.0]: stretch = stretch_factor / net_stretch net_stretch = stretch_factor scale_arrows = VGroup(Vector(0.5 * UP), Vector(0.5 * DOWN)) scale_arrows.arrange(DOWN if stretch > 1 else UP, buff=1.0) scale_arrows.move_to(mid_axes.c2p(2, 0)) scale_arrows.set_stroke(opacity=1) scale_arrows.save_state() scale_arrows.stretch(0.5 if stretch > 1 else 1.5, 1) scale_arrows.set_stroke(opacity=0) globals().update(locals()) self.play( Restore(scale_arrows), wave2_scale_tracker.animate.set_value(stretch * wave2_scale_tracker.get_value()), shift_arrow.animate.stretch(stretch, 0, about_edge=RIGHT), ) self.play(FadeOut(scale_arrows)) self.wait() self.play( wave2_scale_tracker.animate.set_value(0.2), FadeOut(wave1_copy), FadeOut(shift_arrow), FadeOut(shift_label), ) # Restart wave1.start_clock() self.wait(8) class Pulse(InteractiveScene): def construct(self): # Setup axes n_parts = 10 x_max = 4 left_axes_group = VGroup(*( Axes( (0, x_max), (-1, 1), width=0.5 * FRAME_WIDTH - 2, height=1, num_sampled_graph_points_per_tick=20, ) for _ in range(n_parts) )) left_axes_group.arrange(DOWN, buff=0.75) left_axes_group.set_height(FRAME_HEIGHT - 1) left_axes_group.to_edge(LEFT) right_axes = Axes((0, x_max), (-1, 1), width=0.5 * FRAME_WIDTH - 1, height=3) right_axes.to_edge(RIGHT) brace = Brace(left_axes_group, RIGHT, buff=0.5) arrow = Arrow(brace, right_axes) sigma = Tex(R"\Sigma", font_size=72).next_to(arrow, UP) self.add(left_axes_group) self.add(right_axes) self.add(brace, arrow, sigma) # Graphs f0 = 6 sigma = 2 frequencies = np.linspace(0, 2 * f0, n_parts + 1)[1:] weights = 0.25 * np.exp(-0.5 * ((frequencies - f0) / sigma) ** 2) speeds = np.linspace(8, 10, n_parts) time_tracker = ValueTracker(0) colors = color_gradient([BLUE, YELLOW], n_parts) left_graphs = VGroup(*( self.create_graph(axes, freq, speed, color, time_tracker) for axes, freq, speed, color in zip( left_axes_group, frequencies, speeds, colors, ) )) def sum_func(x): time = time_tracker.get_value() return sum( weight * self.wave_func(x, freq, speed, time) for weight, freq, speed in zip(weights, frequencies, speeds) ) sum_graph = right_axes.get_graph(sum_func, bind=True) sum_graph.set_stroke(TEAL, 3) self.add(left_graphs) self.add(sum_graph) final_time = 20.0 time_tracker.set_value(0) self.play( time_tracker.animate.increment_value(final_time), rate_func=linear, run_time=final_time, ) def wave_func(self, x, freq, speed, time): return np.cos(freq * x - speed * time) def create_graph(self, axes, freq, speed, color, time_tracker): return axes.get_graph( lambda x: self.wave_func(x, freq, speed, time_tracker.get_value()), stroke_color=color, stroke_width=2, bind=True )
from manim_imports_ext import * EQUATION_T2C = { R"\vec{\textbf{x}}(t)": RED, R"\vec{\textbf{F}}(t)": YELLOW, R"\vec{\textbf{a}}(t)": YELLOW, R"\frac{d^2 \vec{\textbf{x}}}{dt^2}(t) ": YELLOW, R"\vec{\textbf{E}}_0": BLUE, R"\omega_r": PINK, R"\omega_l": TEAL, } def get_bordered_thumbnail(path, height=3, stroke_width=3): image = ImageMobject(path) thumbnail = Group( SurroundingRectangle(image, buff=0).set_stroke(WHITE, stroke_width), image, ) thumbnail.set_height(height) return thumbnail class HoldUpAlbumCover(TeacherStudentsScene): background_color = interpolate_color(GREY_E, BLACK, 0.5) def construct(self): # Album album = ImageMobject("Dark-side-of-the-moon") album.set_height(3.5) album.move_to(self.hold_up_spot, DOWN) self.play( self.teacher.change("raise_right_hand", album), self.change_students("hooray", "coin_flip_2", "tease", look_at=album) ) self.play( FadeIn(album), ) self.wait(2) # Enlarge album full_rect = FullScreenRectangle() full_rect.set_fill(BLACK, 1) prism_image = ImageMobject("True-prism") true_prism = Group( SurroundingRectangle(prism_image, buff=0).set_stroke(WHITE, 10), prism_image ) album.save_state() album.target = album.generate_target() album.target.set_height(5.5) album.target.next_to(ORIGIN, RIGHT, buff=0.5) true_prism.match_height(album.target).scale(0.98) true_prism.next_to(ORIGIN, LEFT, buff=0.5) titles = VGroup( Text("Genuine simulation"), Text("Pink Floyd"), ) for title, mob in zip(titles, [true_prism, album.target]): title.move_to(mob) title.to_edge(UP, buff=0.5) self.add(full_rect, album, true_prism) self.play( FadeIn(full_rect), MoveToTarget(album), FadeInFromPoint(true_prism, album.get_center()), run_time=2, ) self.remove(self.pi_creatures) self.play(FadeIn(titles)) self.wait() # Why is this white white_point = np.array([3.25, 0.62, 0]) red_arrow = Arrow(white_point + UL, white_point, buff=0.1, stroke_width=7) red_arrow.set_color(RED) why_white = Text("Why is this white?!") why_white.next_to(red_arrow, UP, SMALL_BUFF) why_white.match_x(album) why_white.set_color(RED) self.play( FadeIn(why_white, lag_ratio=0.1), GrowArrow(red_arrow), ) self.wait() # Discrete roygbiv = Text("ROYGBV") roygbiv.rotate(-10 * DEGREES) roygbiv.move_to(white_point).shift(1.5 * RIGHT + 0.25 * UP) rainbow = VGroup(*( Arc(PI, -PI, radius=radius, stroke_width=10) for radius in np.linspace(1.5, 2.0, 6) )) rainbow.reverse_submobjects() rainbow.move_to(album, DOWN).shift(0.05 * UP) for mob in roygbiv, rainbow: mob.set_submobject_colors_by_gradient( RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE ) self.play( FadeIn(roygbiv, lag_ratio=0.5), ShowCreation(rainbow, lag_ratio=0.5), run_time=4 ) self.wait() # Return self.play(LaggedStartMap( FadeOut, Group( why_white, red_arrow, roygbiv, rainbow, true_prism, *titles, ), shift=DOWN, scale=0.5, lag_ratio=0.1 )) self.add(self.pi_creatures, full_rect, album) self.play( Restore(album), FadeOut(full_rect), ) self.wait() # Ask question question = Text("Why exactly does\nthis work?") question.move_to(album, UP) arrow = Arrow(question.get_bottom(), 2 * RIGHT + UP) arrow.set_stroke(opacity=0) self.play( FadeOut(album, UP), FadeIn(question, UP), self.teacher.change("confused", arrow.get_end()), self.change_students("erm", "hesitant", "sassy", look_at=arrow.get_end()) ) self.play(GrowArrow(arrow)) self.wait(5) # Standard explanation title = Text("Standard explanation:", font_size=60) title.to_edge(UP, buff=MED_SMALL_BUFF) self.play( FadeTransform(question, title), FadeOut(arrow, LEFT), self.teacher.change("raise_right_hand", look_at=3 * UP), self.change_students("pondering", "pondering", "pondering", look_at=3 * UP), ) self.wait(5) class DefineIndexOfRefraction(InteractiveScene): def construct(self): # Speeds ior = "1.52" speed1 = Tex(R"\text{Speed} = c \approx 3\times 10^8 \, {\text{m} / \text{s}}") speed2 = Tex(R"\text{Speed} \approx c / " + ior) speed2[ior].set_color(PINK) for speed, x in zip([speed1, speed2], [-1, 1]): speed.set_x(x * FRAME_WIDTH / 4) speed.set_y(-2) self.play(FadeIn(speed, lag_ratio=0.1)) self.wait() # Index of refraction num_words = R"\text{Speed in a vacuum}" den_words = R"\text{Speed in a glass}" equation = Tex( fR"{{{num_words} \over {den_words}}} \approx {ior}", font_size=36 ) equation[den_words].set_color(BLUE) equation[ior].set_color(PINK).scale(1.5, about_edge=LEFT) equation.to_corner(UL) name = TexText("``Index of refraction''") name.next_to(equation, DOWN, buff=LARGE_BUFF) arrow = Arrow(name, equation[ior], buff=0.2) self.play( TransformMatchingShapes(speed1["Speed"].copy(), equation[num_words]), TransformMatchingShapes(speed2["Speed"].copy(), equation[den_words]), Write(equation[R"\over"]), Write(equation[R"\approx"]), TransformFromCopy(speed2[ior], equation[ior]), ) self.wait() self.play(Write(name), GrowArrow(arrow)) self.wait() class LightDoesntHaveTreads(TeacherStudentsScene): def construct(self): # Test stds = self.students self.play( stds[0].change("confused", self.screen), stds[1].change("erm", self.screen), stds[2].says("But, light doesn't\nhave treads...", mode="sassy", bubble_direction=LEFT), self.teacher.change("guilty"), ) self.wait(4) class LookAtScrolling(InteractiveScene): random_seed = 1 def construct(self): morty = Mortimer() morty.set_height(3) morty.to_edge(RIGHT) self.play(morty.change("pondering", 3 * DOWN)) for _ in range(4): self.play(morty.change( random.choice(["tease", "pondering"]), 3 * UP )) if random.random() < 0.3: self.play(Blink(morty)) else: self.wait() self.play(morty.animate.look_at(3 * DOWN)) if random.random() < 0.3: self.play(Blink(morty)) else: self.wait() class WhySlowAtAll(TeacherStudentsScene): def construct(self): # Test stds = self.students self.play( stds[0].change("pondering", self.screen), stds[1].says("Why would light\nslow down at all?", mode="confused", bubble_direction=LEFT, look_at=self.screen), stds[2].change("erm", self.screen), self.teacher.change("tease"), ) self.wait(2) self.play(self.change_students("hesitant", "maybe", "pondering", look_at=self.screen)) self.wait(3) class TankAnnotations(InteractiveScene): def construct(self): # self.add(ImageMobject("TankStill").set_height(FRAME_HEIGHT)) point = LEFT words = Text("First contact!", font_size=24) words.next_to(point, DOWN) self.play( Flash(point), FadeIn(words, run_time=0.5) ) self.wait() class ReactToStandardExplanation(InteractiveScene): samples = 4 def construct(self): # Phrases phrases = VGroup( Text("Light slows down in glass\ndifferent amounts for different colors", alignment="LEFT"), TexText(R"Slowing down $\Rightarrow$ bending"), TexText(R"Therefore colors refract at different angles"), ) phrases.set_fill(border_width=0) for phrase, y in zip(phrases, [1, 0, -1]): phrase.set_y(y * FRAME_HEIGHT / 3) phrase.set_x(-2.0, LEFT) self.add(phrases) self.wait() # Ask question p1 = phrases[0]["Light slows down in glass"] p2 = phrases[0]["different amounts for different colors"] slows_down = phrases[0]["slows down"] rect = SurroundingRectangle(p1, buff=0.05) rect.set_stroke(YELLOW, 2) why = Text("Why?!") why.set_color(YELLOW) why.next_to(rect, RIGHT) how = Text("How?") how.match_style(why) how.next_to(slows_down, UP) discovered = Text("This should feel discovered") discovered.match_style(why) discovered.next_to(phrases[0], DOWN, buff=0.5) morty = Mortimer(height=2) morty.to_edge(RIGHT) self.play( ShowCreation(rect), Write(why), p2.animate.set_opacity(0.25), phrases[1:].animate.set_opacity(0.25), VFadeIn(morty), morty.change("maybe", rect), ) self.play(Blink(morty)) self.wait() self.play( FadeTransform(why, how), rect.animate.surround(slows_down), morty.change("angry", rect), ) self.play(Blink(morty)) self.wait() why.next_to(p2, DOWN) self.play( rect.animate.surround(p2), p2.animate.set_opacity(1), p1.animate.set_opacity(0.25), FadeTransform(how, why), morty.change("confused", rect), ) self.play(Blink(morty)) self.wait() self.remove(why) self.play( rect.animate.surround(phrases[0], buff=0.25), phrases[0].animate.set_opacity(1), FadeTransformPieces(why.copy(), discovered, remover=True), morty.change("tease", rect), ) self.add(discovered) self.play(Blink(morty)) self.wait() # Ask for better explanation of bending new_why = Text("Better explanation?") new_why.match_style(why) new_why.next_to(phrases[1], UP) self.play( phrases[0].animate.set_opacity(0.25), phrases[1].animate.set_opacity(1), rect.animate.surround(phrases[1]), FadeTransform(discovered, new_why), morty.change("pondering", phrases[1]), ) self.play(Blink(morty)) self.wait() # Back to central question why.next_to(p1, UP) self.play( rect.animate.surround(p1), p1.animate.set_opacity(1), phrases[1].animate.set_opacity(0.25), FadeTransform(new_why, why), morty.change("raise_right_hand") ) self.play(Blink(morty)) self.wait() class SnellPuzzle(InteractiveScene): def construct(self): # Test title = Text("Puzzle", font_size=60).set_color(YELLOW) underline = Underline(title, stretch_factor=2, stroke_color=YELLOW) puzzle = TexText(R""" Can you find an equation \\ relating $\lambda_1$, $\lambda_2$, $\theta_1$ and $\theta_2$? """) puzzle.next_to(underline, DOWN, buff=0.5) group = VGroup(title, underline, puzzle) rect = SurroundingRectangle(group, buff=0.25) rect.set_fill(BLACK, 1) rect.set_stroke(WHITE, 0) group.add_to_back(rect) group.to_corner(UL) self.add(group) class SnellComparrisonBackdrop(InteractiveScene): def construct(self): self.add(FullScreenRectangle().set_fill(GREY_E, 1)) rects = Rectangle(6, 7).replicate(2) rects.set_fill(BLACK, 1) rects.set_stroke(WHITE, 1) rects[0].set_x(-FRAME_WIDTH / 4) rects[1].set_x(FRAME_WIDTH / 4) self.add(rects) class KeyPoints(InteractiveScene): def construct(self): key_points = VGroup( Text("Key point #1: Phase kicks"), Text("Key point #2: Layer oscillations"), Text("Key point #3: Resonance"), ) key_points.set_submobject_colors_by_gradient(BLUE, TEAL, YELLOW) key_points.scale(1.25) key_points.to_edge(UP, buff=0.25) key_points.set_backstroke(BLACK, 4) key_points.to_edge(UP) self.add(key_points[0]) self.wait() for kp1, kp2 in zip(key_points, key_points[1:]): self.play( FadeOut(kp1, 0.5 * UP), FadeIn(kp2, 0.5 * UP), ) self.wait() class AsideOnWaveTerminology(TeacherStudentsScene): def construct(self): # Test title = Text("Wave terminology", font_size=60) title.to_corner(UR) title.to_edge(UP, buff=0.25) title.add(Underline(title)) title.set_color(YELLOW) terms = VGroup( Text("Phase"), Text("Frequency"), Text("Wave number"), Text("Amplitude"), ) terms.arrange(DOWN, buff=0.5, aligned_edge=LEFT) terms.next_to(title, DOWN) terms.shift(0.5 * LEFT) self.add(title, terms) self.play( self.teacher.change("raise_right_hand", terms), self.change_students("pondering", "tease", "hesitant", look_at=terms), LaggedStartMap(FadeIn, terms, shift=0.25 * DOWN, lag_ratio=0.5), ) self.wait(3) class NewQuestion(InteractiveScene): def construct(self): # Questions text_kw = dict(font_size=48) questions = VGroup( Text("Why does light\nslow down in glass?", **text_kw), Text("Why does light's interaction\nwith a layer of glass\nkick back its phase?", **text_kw), Text("How much does\nlight slow down?", **text_kw), Text("How strong is\nthe phase kick?", **text_kw), ) q1, q2, q3, q4 = questions for question, x in zip(questions, [-1, 1, -1, 1]): question.set_x(x * FRAME_WIDTH / 4) question.set_y(2.75) q3.shift(0.5 * RIGHT) q4.shift(0.5 * LEFT) bad_ap = q2["'"][0] good_ap = TexText("'") good_ap.replace(bad_ap, dim_to_match=1) bad_ap.become(good_ap) arrow1 = Arrow(q1, q2) arrow2 = Arrow(q3, q4) for question in [q1, q3]: question.set_opacity(0.5) question.save_state() question.set_x(0) question.set_opacity(1) # First pair self.play(FadeIn(q1)) self.wait() self.play( ShowCreation(arrow1), Restore(q1), TransformMatchingStrings(q1.copy(), q2, run_time=1), ) self.wait() self.play( FlashUnder(q2["layer of glass"], color=BLUE), q2["layer of glass"].animate.set_color(BLUE) ) self.wait() self.play( FlashUnder(q2["phase"]), q2["phase"].animate.set_color(YELLOW) ) self.wait() # Second pair self.play( FadeOut(q1, UP), FadeIn(q3, UP), FadeOut(arrow1), FadeOut(q2), ) self.wait() self.play( ShowCreation(arrow2), Restore(q3), TransformMatchingStrings(q3.copy(), q4, run_time=1), ) self.wait() class HoldUpLastVideo(TeacherStudentsScene): def construct(self): self.remove(self.background) image = ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/barber_pole/Thumbnails/Part2Thumbnail4.png") tn = Group( SurroundingRectangle(image, buff=0).set_stroke(WHITE, 3), image, ) tn.set_height(3) tn.move_to(self.hold_up_spot, DOWN) tn.shift(0.25 * DOWN) label = Text("Last video") arrow = Vector(RIGHT) arrow.next_to(tn, LEFT) label.next_to(arrow, LEFT) self.play( self.teacher.change("raise_right_hand", tn), FadeIn(tn, UP), self.change_students("pondering", "erm", "tease", look_at=tn) ) self.play( FadeIn(label, lag_ratio=0.1), GrowArrow(arrow) ) self.wait(4) class WhyDoesAddingCauseAShift(TeacherStudentsScene): def construct(self): # Test morty = self.teacher stds = self.students self.play( stds[2].says("But, why?", look_at=morty.eyes, mode="raise_left_hand", bubble_direction=LEFT), self.change_students("pondering", "pondering", look_at=self.screen), morty.change("guilty", self.screen), ) self.wait() self.play(stds[2].change("confused", self.screen)) self.wait(2) self.play(morty.change("tease", stds[2].eyes)) self.wait() self.play( morty.change("raise_right_hand", 3 * UR), stds[2].debubble(look_at=3 * UR), self.change_students("erm", "hesitant", look_at=3 * UR) ) self.wait(3) class AnnoateWaveSumPhaseShift(InteractiveScene): def construct(self): image = ImageMobject("WaveSumPhaseShift") image.set_height(FRAME_HEIGHT).center() # self.add(image) # Test wave_len = 4.0 point1 = (-1.31, 2.33, 0) point2 = (-2.3, 0, 0) line = DashedLine(UP, DOWN) lines1 = line.get_grid(1, 6, h_buff=wave_len / 2) lines1.set_height(1.0, stretch=True) lines1.set_stroke(YELLOW, 3) lines1.move_to(point1 + wave_len * LEFT / 2, LEFT) lines2 = lines1.copy() lines2.move_to(point2 + wave_len * LEFT / 2, LEFT) arrow = Arrow( lines2[1].get_top(), lines1[1].get_bottom(), buff=0.2 ) label = TexText(R"$90^\circ$ behind") label.next_to(arrow.get_center(), RIGHT) self.play(LaggedStartMap(ShowCreation, lines2, lag_ratio=0, run_time=0.5)) self.wait() self.play( TransformFromCopy(lines2, lines1), GrowArrow(arrow), FadeIn(label, lag_ratio=0.1), ) self.wait() class PreviewQuarterBehindReason(InteractiveScene): def construct(self): # Plane plane = ComplexPlane( (-3, 3), (-3, 3), background_line_style=dict(stroke_width=2, stroke_color=BLUE), faded_line_style=dict(stroke_width=1, stroke_opacity=0.3, stroke_color=BLUE), ) plane.set_height(7) self.add(plane) # Add little vectors z1 = 1 + complex(-4e-3, -0.05) amp = 0.08 zs = np.array([amp * z1**n for n in range(1000)]) vects = VGroup(*( Vector(plane.n2p(z), stroke_width=2) for z in zs )) vects.set_submobject_colors_by_gradient(YELLOW, RED) for v1, v2 in zip(vects, vects[1:]): v2.shift(v1.get_end() - v2.get_start()) big_vect = Vector(stroke_width=5) big_vect.add_updater(lambda m: m.put_start_and_end_on( plane.n2p(0), vects[-1].get_end() if len(vects) > 0 else plane.n2p(amp) )) self.add(big_vect) self.play( ShowIncreasingSubsets(vects, rate_func=linear, run_time=8) ) self.wait() class ElectronLabel(InteractiveScene): def construct(self): # Test label = Text("An electron, say") label.set_backstroke(BLACK, 5) label.next_to(ORIGIN, UR, buff=LARGE_BUFF) arrow = Arrow(label, ORIGIN) self.play( FadeIn(label, lag_ratio=0.1), GrowArrow(arrow) ) self.wait() class IsThatTrue(TeacherStudentsScene): def construct(self): # Ask stds = self.students morty = self.teacher law = Tex(R"\vec{\textbf{F}}(t) = -k \vec{\textbf{x}}(t)", t2c=EQUATION_T2C) law.move_to(self.hold_up_spot, DOWN) morty.change_mode("raise_right_hand") self.add(law) self.play( stds[0].change("pondering", self.screen), stds[1].says("Is that accurate?", mode="sassy", look_at=self.screen), stds[2].change("erm", self.screen), ) self.wait(2) # Answer self.play( morty.says(TexText( R"For small $\vec{\textbf{x}}$, \\ accurate enough", t2c={R"$\vec{\textbf{x}}$": RED} )), self.change_students("thinking", "erm", "happy", look_at=morty.eyes), law.animate.to_edge(UP), ) self.wait() # Name restoring force label = TexText("``Linear restoring force''") label.next_to(law, DOWN) self.play( FadeInFromPoint(label, morty.get_corner(UL)), self.change_students(look_at=label), morty.debubble("raise_right_hand", look_at=label), stds[1].debubble("pondering", look_at=label), ) self.wait(2) # True law group = VGroup(law, label) true_law = Tex( R""" \text{True force: } F = -k x + c_2 x^2 + c_3 x^3 + c_4 x^4 + \cdots """, t2c={"F": YELLOW, "x": RED}, font_size=60 ) true_law.move_to(UP) rect = SurroundingRectangle(true_law["F = -k x"], buff=0.25) rect.set_stroke(BLUE, 1) self.play( group.animate.set_height(1).to_corner(UR), FadeIn(true_law, lag_ratio=0.1, run_time=2), morty.change("hesitant"), self.change_students("pondering", "pondering", "pondering", look_at=true_law) ) self.wait(2) self.play( ShowCreation(rect), true_law[R" + c_2 x^2 + c_3 x^3 + c_4 x^4 + \cdots"].animate.set_opacity(0.2), morty.change("tease"), ) self.wait(2) class VelocityZero(InteractiveScene): def construct(self): label = Tex(R"(\text{Velocity} = 0)") label.set_color(PINK) self.play(FadeIn(label, 0.5 * UP)) self.wait() class FrequencyVsAngularFrequency(TeacherStudentsScene): def construct(self): # Correction morty = self.teacher stds = self.students rf_words = Text("Resonant frequency") raf_words = Text("Resonant angular frequency") omega = Tex(R"\omega_r", font_size=72) omega.set_color(PINK) omega.move_to(self.hold_up_spot, DOWN) for words in rf_words, raf_words: words.next_to(omega, UP) cross = Cross(rf_words) self.add(rf_words, omega) morty.change_mode("raise_right_hand") self.play( ShowCreation(cross), self.change_students("sassy", "hesitant", "angry") ) rf_words.add(cross) rf_words.target = rf_words.generate_target() rf_words.target.next_to(raf_words, UP, LARGE_BUFF) rf_words.target.set_fill(opacity=0.5) rf_words.target[-1].set_opacity(0) self.wait() self.play( MoveToTarget(rf_words), TransformMatchingStrings( rf_words.copy(), raf_words, run_time=1, ), self.change_students("pondering", "hesitant", "hesitant") ) # Show cycles plane = ComplexPlane( (-1, 1), (-1, 1), background_line_style=dict(stroke_width=1, stroke_color=BLUE), faded_line_style=dict(stroke_width=0.5, stroke_opacity=0.5, stroke_color=BLUE), ) plane.set_height(4) plane.to_edge(DOWN) circle = Circle(radius=plane.x_axis.get_unit_size()) circle.set_stroke(TEAL, 2) circle.move_to(plane.get_origin()) f_words = Text("Frequency", font_size=60) af_words = Text("Angular Frequency", font_size=60) for words, x in [(f_words, -1), (af_words, 1)]: words.set_x(x * FRAME_WIDTH / 4) words.to_edge(UP, buff=MED_SMALL_BUFF) t2c = {R"\omega": PINK, "f": TEAL} f_eq = Tex(R"f = {\text{Cycles} \over \text{Seconds}}", t2c=t2c) f_eq.next_to(f_words, DOWN, MED_LARGE_BUFF) f_eq["f"].set_color(YELLOW) af_eq = Tex(R"\omega = {\text{Radians} \over \text{Seconds}}", t2c=t2c) af_eq.next_to(af_words, DOWN, MED_LARGE_BUFF) af_eq[R"\omega"].set_color(PINK) angle_tracker = ValueTracker() angle_tracker.add_updater(lambda m, dt: m.increment_value(0.25 * dt * TAU)) vect = Vector(RIGHT).set_color(YELLOW) vect.add_updater(lambda m: m.put_start_and_end_on( plane.n2p(0), plane.n2p(np.exp(complex(0, angle_tracker.get_value()))) )) self.add(angle_tracker) self.play( FadeOut(self.background), LaggedStartMap(FadeOut, self.pi_creatures, shift=DOWN), ShowCreation(plane, lag_ratio=0.1), FadeIn(circle), TransformMatchingStrings(rf_words, f_words), TransformMatchingStrings(raf_words, af_words), FadeTransform(omega, af_eq[R"\omega"]), FadeIn(af_eq[1:]), FadeIn(f_eq), VFadeIn(vect) ) self.wait(4) # Show specific value f_value_eq = Tex("f = 0.25", t2c=t2c) af_value_eq = Tex(R"\omega = 2\pi f = 1.57", t2c=t2c) values = VGroup(f_value_eq, af_value_eq) values.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) values.next_to(plane, LEFT, MED_LARGE_BUFF) self.play(FadeIn(f_value_eq)) self.wait(8) self.play(FadeIn(af_value_eq)) # Show angle label arc_angle_tracker = ValueTracker() get_arc_angle = arc_angle_tracker.get_value arc = always_redraw(lambda: Arc( 0, get_arc_angle(), arc_center=plane.n2p(0), radius=0.5, )) arc_angle_label = DecimalNumber(0, unit=R"\text{ Radians}") arc_angle_label.add_updater(lambda m: m.set_value(get_arc_angle())) arc_angle_label.add_updater(lambda m: m.next_to(arc.get_center(), UR)) arc_angle_label.add_updater(lambda m: m[4:].shift(SMALL_BUFF * RIGHT)) self.add(arc) self.play( arc_angle_tracker.animate.set_value(TAU / 4), VFadeIn(arc_angle_label), ) arc.clear_updaters() self.wait(10) self.play( VFadeOut(arc), VFadeOut(arc_angle_label), FadeOut(values), ) # Show cosine plane.add(circle) plane.generate_target() plane.target.to_edge(LEFT) axes = Axes((0, 16), (-1, 1), width=9, height=0.75 * plane.get_height()) axes.next_to(plane.target, RIGHT) graph = axes.get_graph(lambda x: np.cos(TAU * 0.25 * x)) graph.set_stroke(YELLOW, 2) cos_eq = Tex(R"\cos(\omega t) = \cos(2\pi f t)", t2c=t2c) cos_eq.next_to(graph, UP) omega_arrow = Vector(0.5 * DOWN).set_color(PINK) omega_arrow.next_to(cos_eq[R"\omega"], UP, SMALL_BUFF) dot = GlowDot() dot.add_updater(lambda m: m.move_to(plane.n2p(math.cos(angle_tracker.get_value())))) line = Line(UP, DOWN) line.set_stroke(YELLOW, 1) line.add_updater(lambda m: m.put_start_and_end_on( vect.get_end(), dot.get_center() )) self.play( MoveToTarget(plane), FadeIn(axes, 2 * LEFT) ) self.wait(4 * (1 - (angle_tracker.get_value() / TAU) % 1)) self.add(dot, line) self.play( ShowCreation(graph, rate_func=linear), FadeIn(cos_eq, time_span=(0, 1)), ShowCreation(omega_arrow, time_span=(4, 5)), run_time=16 ) class UnequalFrequencies(InteractiveScene): def construct(self): # Test # self.add(ImageMobject("WaveEqStill").set_height(FRAME_HEIGHT)) word_eq = TexText(R"Freq. of light $\ne$ Resonant freq.") eq = Tex(R"\omega_l \ne \omega_r") word_lhs = word_eq["Freq. of light"] word_rhs = word_eq["Resonant freq."] word_lhs.set_color(TEAL) word_rhs.set_color(PINK) eq[R"\omega_l"].set_color(TEAL) eq[R"\omega_r"].set_color(PINK) equations = VGroup(word_eq, eq) equations.arrange(DOWN) equations.to_corner(UR) oml_point = np.array([-1.2, 2.7, 0]) arrow = Arrow(word_eq.get_left(), oml_point, path_arc=90 * DEGREES) arrow.set_color(TEAL) oml = eq[R"\omega_l"] oml_copy = oml.copy().move_to(oml_point) self.play( FadeIn(word_eq), ShowCreation(arrow), ) self.wait() self.play(ReplacementTransform(oml_copy, oml)) self.play(Write(eq[R"\ne \omega_r"])) self.wait() class DisectDrivenEq(InteractiveScene): def construct(self): # Setup driven_eq = Tex( R""" \vec{\textbf{F}}(t) = - k \vec{\textbf{x}}(t) + \vec{\textbf{E}}_0 q \cos(\omega_l t) """, t2c=EQUATION_T2C ) driven_eq.to_corner(UR, buff=0.6) lhs = driven_eq[R"\vec{\textbf{F}}(t) = - k \vec{\textbf{x}}(t)"] parts = VGroup(*( driven_eq[tex] for tex in [ R"\vec{\textbf{E}}_0 q \cos(\omega_l t)", R"\omega_l", R"\vec{\textbf{E}}_0", R"q", ] )) light_part, omega_l, E0, q = parts words = VGroup( Text("Force from a\nlight wave"), Text("Angular frequency\nof the light (color)"), Text("Strength of\nthe wave"), Text("Charge of the\nelectron"), ) words[0].scale(0.75) words[1:].scale(0.75) for part, word in zip(parts, words): word.next_to(part, DOWN, buff=0.35) word.shift_onto_screen() word.match_color(part[0][0]) words[0].set_color(WHITE) rect = SurroundingRectangle(light_part) rect.set_stroke(TEAL, 2) # for expr in driven_eq, words[0]: # bg = BackgroundRectangle(expr, buff=MED_SMALL_BUFF) # bg.set_fill(BLACK, 1) # self.add(bg) words[0].set_backstroke(BLACK, 8) # Animations self.play(FadeIn(lhs, UP)) self.wait() self.play( Write(driven_eq["+"]), FadeIn(light_part, lag_ratio=0.1), ) self.play( ShowCreation(rect), Write(words[0]), ) self.wait() self.play( rect.animate.surround(omega_l), FadeTransform(*words[0:2]), ) self.wait() self.play( rect.animate.surround(E0), FadeTransform(*words[1:3]), ) self.wait() self.play( rect.animate.surround(q), FadeTransform(*words[2:4]), ) self.wait() self.play( rect.animate.surround(light_part), FadeTransform(words[3], words[0]), ) self.wait() class AskAboutAmplitude(InteractiveScene): def construct(self): # Test lines = DashedLine(3 * LEFT, 3 * RIGHT).replicate(2) lines.arrange(DOWN, buff=0.8) brace = Brace(lines, LEFT) text = brace.get_text("What is this\nAmplitude?") text.set_backstroke(BLACK, 8) self.play(*map(ShowCreation, lines)) self.play( GrowFromCenter(brace), Write(text), ) self.wait() class PiCreaturesReactingToEquation(TeacherStudentsScene): def construct(self): # Test morty = self.teacher stds = self.students self.remove(self.background) point = morty.get_corner(UL) + 2 * UP + LEFT self.play( morty.change("raise_left_hand", point), self.change_students("pondering", "thinking", "erm", look_at=point) ) self.wait(3) self.play(self.change_students("thinking", "pondering", "pondering", look_at=point)) self.wait(3) self.play( morty.says("Oh hey, it depends\non the frequency!", mode="hooray"), self.change_students("happy", "tease", "thinking", look_at=point) ) self.wait(4) class HighlightExpression(InteractiveScene): def construct(self): # Test expr = Tex( R""" \vec{\textbf{x}}(t) = \frac{q ||\vec{\textbf{E}}_0||}{m\left(\omega_r^2-\omega_l^2\right)} \cos(\omega_l t) """, t2c=EQUATION_T2C ) expr.to_edge(UP) rect1 = SurroundingRectangle(expr[R"\omega_r^2-\omega_l^2"]) rect2 = SurroundingRectangle(expr[R"\frac{q ||\vec{\textbf{E}}_0||}{m\left(\omega_r^2-\omega_l^2\right)}"]) self.add(expr) self.play(ShowCreation(rect1)) self.wait() self.play(Transform(rect1, rect2)) self.wait() self.play(FadeOut(rect2)) class Amplitude(InteractiveScene): def construct(self): # Show equation with annotations equation = Tex(R""" \text{Layer wiggle amplitude} = \frac{q ||\vec{\textbf{E}}_0||}{m\left(\omega_r^2-\omega_l^2\right)} """, t2c=EQUATION_T2C) equation.to_corner(UL) lf_rect = SurroundingRectangle(equation[R"\omega_l"]) rf_rect = SurroundingRectangle(equation[R"\omega_r"]) lf_words = Text("Light frequency", font_size=36) rf_words = Text("Resonant frequency", font_size=36) lf_words.next_to(lf_rect, DOWN) rf_words.next_to(rf_rect, DOWN) VGroup(lf_rect, rf_rect).set_stroke(width=2) VGroup(lf_rect, lf_words).set_color(EQUATION_T2C[R"\omega_l"]) VGroup(rf_rect, rf_words).set_color(EQUATION_T2C[R"\omega_r"]) self.add(equation) self.wait() self.play( ShowCreation(lf_rect), FadeIn(lf_words, 0.5 * DOWN), ) self.wait() self.play( ReplacementTransform(lf_rect, rf_rect), FadeTransform(lf_words, rf_words), ) self.wait() self.play(FadeOut(rf_rect), FadeOut(rf_words)) self.wait() class GuessSteadyState(InteractiveScene): def construct(self): # Show prompt prompt = VGroup( Text("Guess that: "), Tex(R""" \vec{\textbf{x}}(t) = A \cos(\omega_l t) """, t2c=EQUATION_T2C) ) prompt.arrange(RIGHT, buff=0.5) prompt.to_edge(UP) A_part = prompt[1]["A"] A_part.set_color(GREY_B) freq = prompt[1][R"\omega_l"] A_arrow = Vector(0.3 * UP, stroke_width=2).next_to(A_part, DOWN, buff=0.1) freq_arrow = Vector(0.3 * UP, stroke_width=2).next_to(freq, DOWN, buff=0.1) freq_arrow.set_color(TEAL) A_word = Text("Solve for\nthis", font_size=24) A_word.next_to(A_arrow, DOWN, buff=0.1) freq_word = Text("Light frequency", font_size=24) freq_word.next_to(freq_arrow, DOWN, buff=0.1) freq_word.shift(0.5 * RIGHT) freq_word.set_color(TEAL) A_word.align_to(freq_word, UP) rect = FullScreenRectangle() rect.set_fill(BLACK, 1) rect.set_height(2, about_edge=UP, stretch=True) self.add(rect) self.add(prompt) self.play( GrowArrow(A_arrow), FadeIn(A_word), ) self.play( GrowArrow(freq_arrow), FadeIn(freq_word), ) self.wait() # Answer amp_tex = R"\frac{q \vec{\textbf{E}}_0}{m\left(\omega_r^2-\omega_l^2\right)}" solution = Tex( fR"\vec{{\textbf{{x}}}}(t) = {amp_tex} \cos(\omega_l t)", t2c=EQUATION_T2C ) solution.move_to(np.array([3.85, 0.65, 0.0])) self.play( rect.animate.set_height(FRAME_HEIGHT, about_edge=UP, stretch=True).set_anim_args(run_time=2), FadeOut(VGroup( prompt[0], A_arrow, A_word, freq_arrow, freq_word )), TransformMatchingTex( prompt[1], solution, matched_pairs=[ (prompt[1][R"\vec{\textbf{x}}(t)"], solution[R"\vec{\textbf{x}}(t)"]), (A_part, solution[amp_tex]) ] ), ) self.wait() class StrongerResonanceStrongerPhaseShift(InteractiveScene): def construct(self): words = TexText(R"Stronger resonance $\rightarrow$ Bigger phase kick", font_size=60) words.to_edge(UP) self.add(words) class WhyIsThisTrue(TeacherStudentsScene): def construct(self): # Test stds = self.students morty = self.teacher self.screen.to_corner(UR) self.play( stds[2].says("Why is it\na phase shift?", look_at=self.screen), stds[1].change("confused", self.screen), stds[0].change("pondering", self.screen), morty.change("guilty", stds[0].eyes) ) self.wait(2) self.play( self.change_students("pondering", "pleading", "maybe", look_at=self.screen), morty.change("hesitant", self.screen) ) self.wait(3) class QuestionsFromPatrons(InteractiveScene): def construct(self): # Questions title = Text("Viewer questions about the index of refraction", font_size=60) title.to_edge(UP) title.add(Underline(title)) title.set_color(BLUE) questions = BulletedList( "Why does slowing imply bending?", "What causes birefringence?", "What's the end of the barber pole explanation?", "How can the index of refraction be lower than 1?", buff=0.75 ) questions.next_to(title, DOWN, buff=1.0) self.play( FadeIn(title, lag_ratio=0.1), LaggedStartMap(FadeIn, questions, shift=0.5 * DOWN, lag_ratio=0.25) ) self.wait() # Higlight last three last_three = questions[1:] highlight_rect = SurroundingRectangle(last_three, buff=0.25) highlight_rect.set_stroke(YELLOW, 2) grey_rect = highlight_rect.copy().set_stroke(width=0).set_fill(GREY_E, 1) back_rect = FullScreenRectangle().set_fill(BLACK, 0.9) self.add(back_rect, grey_rect, highlight_rect, last_three) self.play( FadeIn(back_rect), FadeIn(grey_rect), DrawBorderThenFill(highlight_rect) ) self.wait() self.play(FadeOut(back_rect), FadeOut(grey_rect), FadeOut(highlight_rect)) # Each question background = FullScreenRectangle() background.set_fill(interpolate_color(GREY_E, BLACK, 0.5), 1) for question in questions: question.save_state() question.target = question.generate_target() question.target[0].scale(0, about_point=question[1].get_left()).set_opacity(0) question.target.center().to_edge(UP) self.add(background, question) self.play( FadeIn(background), MoveToTarget(question), ) self.wait() self.play( Restore(question), FadeOut(background), ) class HoldUpMainVideo(TeacherStudentsScene): def construct(self): # Show previous video thumbnail = get_bordered_thumbnail("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/barber_pole/Thumbnails/PrismThumbnail2.png") thumbnail.move_to(self.hold_up_spot, DOWN) morty = self.teacher self.play( morty.change("raise_left_hand"), FadeIn(thumbnail, UP), self.change_students("happy", "guilty", "erm", look_at=thumbnail), ) self.wait(2) # Key points key_points = VGroup( Text("Key point #1: Phase kicks"), Text("Key point #2: Layer oscillations"), Text("Key point #3: Resonance"), ) key_points.scale(1.25) key_points.set_backstroke(BLACK, 4) key_points.to_edge(UP) key_points[0].set_fill(BLUE) key_points[0].save_state() key_points.set_fill(WHITE) key_points.scale(0.7) key_points.arrange(DOWN, buff=0.5, aligned_edge=LEFT) key_points.set_y(2).to_edge(RIGHT) thumbnail.generate_target() thumbnail.target.next_to(key_points, LEFT, buff=0.75) self.play( MoveToTarget(thumbnail), morty.change("raise_right_hand", key_points), self.change_students("pondering", "hesitant", "pondering", look_at=thumbnail.target), LaggedStartMap(FadeIn, key_points, shift=0.5 * LEFT, lag_ratio=0.5) ) self.wait(2) self.play( Restore(key_points[0]), LaggedStartMap(FadeOut, key_points[1:], shift=DOWN), LaggedStartMap(FadeOut, self.pi_creatures, shift=DOWN), FadeOut(thumbnail, scale=0.5, shift=DOWN), ) self.wait() class HoldUpBarberPoleVideos(HoldUpMainVideo): def construct(self): # Show thumbnails folder = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/barber_pole/Thumbnails/" thumbnails = Group(*( get_bordered_thumbnail(os.path.join(folder, name), stroke_width=2) for name in ["CleanThumbnail", "Part2Thumbnail6"] )) thumbnails.arrange(RIGHT, buff=1.0) thumbnails.set_height(2.5) thumbnails.move_to(self.hold_up_spot, DR) morty = self.teacher self.play( morty.change("raise_right_hand", thumbnails), LaggedStartMap(FadeIn, thumbnails, shift=0.5 * UP, lag_ratio=0.5), self.change_students("maybe", "erm", "happy", look_at=thumbnails), ) self.wait() self.play( self.change_students("confused", "maybe"), morty.animate.look_at(self.students) ) self.wait() self.play( self.students[2].change("tease", thumbnails) ) self.wait(2) class MissingDetails(InteractiveScene): def construct(self): # Test title = Text("Details I skipped:", font_size=72) title.to_edge(UP) title.add(Underline(title)) title.set_color(BLUE) details = BulletedList( "There will be many resonant frequencies", "Our force law should include a damping term", "Why the wave produced by a plane of charges is a \\\\" + \ "quarter-cycle out of phase with the incoming light", "Everything related to the magnetic field", "Whether accounting for quantum effects makes a difference", ) details.next_to(title, DOWN, buff=0.5) details.set_fill(border_width=0) self.add(title) self.play(LaggedStartMap(FadeIn, details, shift=0.5 * DOWN, lag_ratio=0.35, run_time=3)) self.wait() self.play(details.animate.fade_all_but(1)) self.wait() class ArrowOverInldexHalf(InteractiveScene): speed = 1.0 index = 0.68 bounds = (-3, 3) def construct(self): arrow = Vector(0.5 * DOWN) arrow.next_to(UP, UP) arrow.to_edge(LEFT, buff=0) x_min, x_max = self.bounds def update_arrow(arr, dt): step = dt * self.speed if x_min < arr.get_x() < x_max: step /= self.index arr.shift(step * RIGHT) arrow.add_updater(update_arrow) self.add(arrow) self.wait_until(lambda: arrow.get_x() > FRAME_WIDTH / 2 + 2 * arrow.get_width()) class SteadyStateSolutionCircledAmplitude(InteractiveScene): def construct(self): equation = Tex( R""" \vec{\textbf{x}}(t) = \cos(\omega_l t) \cdot \frac{q ||\vec{\textbf{E}}_0||}{m\left(\omega_r^2-\omega_l^2\right)} """, t2c=EQUATION_T2C ) equation.set_backstroke(BLACK, 5) rect = SurroundingRectangle(equation[R"\frac{q ||\vec{\textbf{E}}_0||}{m\left(\omega_r^2-\omega_l^2\right)}"]) rect.set_stroke(TEAL) self.add(equation) self.play(ShowCreation(rect)) self.wait() class LimitToContinuity(InteractiveScene): def construct(self): arrow = Arrow(3 * UP, 3 * DOWN, buff=0, stroke_width=10, stroke_color=YELLOW) words = Text("Continuous in\nthe limit", font_size=60) words.next_to(arrow, RIGHT, buff=0.5) self.play( GrowArrow(arrow), FadeIn(words), ) self.wait() class KickForwardOrBackCondition(InteractiveScene): def construct(self): # First statement words = VGroup( TexText("If this $< 0$"), TexText("Refractive Index $< 1$", font_size=48), ) rect = Rectangle(2, 1) rect.next_to(LEFT, LEFT, buff=MED_LARGE_BUFF).set_y(1.9) words[0].next_to(rect, UP, MED_SMALL_BUFF) words[1].set_y(1.5) words[1].set_x(FRAME_WIDTH / 4) arrow = Arrow(words[0].get_right(), words[1].get_left()) arrow.set_stroke(YELLOW, 6) self.play(Write(words[0])) self.play( GrowArrow(arrow), FadeIn(words[1], RIGHT) ) self.wait() # Freq reference freq_ineq = Tex(R"\text{If } \omega_l > \omega_r", t2c=EQUATION_T2C) freq_ineq.move_to(words[0]) lf_rect = SurroundingRectangle(freq_ineq[R"\omega_l"]) rf_rect = SurroundingRectangle(freq_ineq[R"\omega_r"]) lf_words = Text("Light frequency", font_size=36) rf_words = Text("Resonant frequency", font_size=36) lf_words.next_to(lf_rect, UP) rf_words.next_to(rf_rect, UP) VGroup(lf_rect, rf_rect).set_stroke(width=2) VGroup(lf_rect, lf_words).set_color(EQUATION_T2C[R"\omega_l"]) VGroup(rf_rect, rf_words).set_color(EQUATION_T2C[R"\omega_r"]) words[0].generate_target() words[0].target.next_to(rect, RIGHT, SMALL_BUFF) self.play( # MoveToTarget(words[0]), # arrow.animate.put_start_and_end_on( # words[0].target.get_right() + SMALL_BUFF * RIGHT, # arrow.get_end(), # ), FadeOut(words[0], 0.5 * UP), FadeIn(freq_ineq, 0.5 * UP), ) self.wait() self.play( FadeIn(lf_rect), FadeIn(lf_words, shift=0.25 * UP), ) self.wait() self.play( ReplacementTransform(lf_rect, rf_rect), FadeTransform(lf_words, rf_words), ) self.wait() self.play(FadeOut(rf_words), FadeOut(rf_rect)) self.wait() class ThisReallyDoesHappen(TeacherStudentsScene): def construct(self): # Test self.play( self.teacher.says("This really\ndoes happen!", mode="surprised"), ) self.play(self.change_students("sassy", "confused", "pleading", look_at=self.screen)) self.wait(4) class LookAround(InteractiveScene): def construct(self): # Test circle = Circle(radius=2) circle.stretch(1.5, 0) arrows = VGroup(*( Arrow(v, 2 * v, buff=0, stroke_width=8, stroke_color=GREY_B) for alpha in np.arange(0, 1, 1 / 12) for v in [circle.pfp(alpha)] )) words1 = Text("Look\naround", font_size=90) words2 = Text("Most things\nare opaque", font_size=72) self.add(words1) self.play(LaggedStartMap(GrowArrow, arrows, lag_ratio=0.2)) self.wait() self.play(FadeTransform(words1, words2)) self.wait() class CausalInfluence(InteractiveScene): def construct(self): words = TexText(R"No causal influence can \\ propagate faster than $c$", font_size=72) c = words["$c$"] c.set_color(YELLOW) rect = SurroundingRectangle(c) arrow = Vector(UP) arrow.set_color(YELLOW) arrow.next_to(rect, DOWN) self.add(words) self.wait() self.play( GrowArrow(arrow), ShowCreation(rect), FlashAround(c), ) self.wait() class RightLeftArrow(InteractiveScene): def construct(self): vect = Vector(DOWN) vect.to_edge(RIGHT) self.play(vect.animate.to_edge(LEFT), run_time=24, rate_func=linear) class SameRotationRate(InteractiveScene): def construct(self): # Test words = Text("Same rate\nof rotation", font_size=60) words.to_edge(RIGHT) arrows = VGroup(*( Arrow(words.get_corner(corner), y * UP + 1.25 * RIGHT, buff=0.2) for y, corner in zip([2.75, 0, -2.75], [UL, LEFT, DL]) )) self.play( Write(words), LaggedStartMap(GrowArrow, arrows) ) self.wait() class IOREndScreen(PatreonEndScreen): pass
from manim_imports_ext import * from PIL import ImageFilter class PitchShifterWrapper(VideoWrapper): animate_boundary = False title = "Making a Pitch Shifter by JentGent" class ThumbnailProgression(InteractiveScene): def construct(self): # Make grid thumbnail_dir = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/SoME3/EntryThumbnails" names = [ "Pixel Art Anti Aliasing", "The Math of Saving The Enola Gay", "Making a Pitch Shifter", "Cayley Graphs and Pretty Things", "The Longest Increasing Subsequence", "The Matrix Arcade: A Visual Explorable of Matrix Transformations", "Watching Neural Networks Learn", "Functions are Vectors", "The Art of Linear Programming", "The Mosaic Problem - How and Why to do Math for Fun", "Affording a Planet With Geometry", "When CAN'T Math Be Generalized?", "Rotation + Translation = Rotation. Animated proof", "Rethinking the real line", "How did the Ancient Egyptians find this volume without Algebra?", "A Subtle Aspect of Circular Motion", "Minimal Surfaces & the Calculus of Variations", "How does a computer-calculator compute logarithms?", "What Happens If We Add Fractions Incorrectly?", "Can you guess this shape from its shadows?", "Chasing Fixed Points: Greedy Gremlin's Trade-Off", "How Computers Use Numbers", "Mathematical Magic Mirrorball", "The Mathematics of String Art", "How Infinity Works", ] thumbnails = Group(*( ImageMobject(os.path.join(thumbnail_dir, name)) for name in names )) framed_thumbnails = Group(*( Group( SurroundingRectangle(tn, buff=0).set_stroke(WHITE, 3), tn ) for tn in thumbnails )) framed_thumbnails.set_height(2) framed_thumbnails.arrange_in_grid(h_buff=0.5, v_buff=0.25) framed_thumbnails.set_height(FRAME_HEIGHT - 1) # Covers covers = Group() cover_labels = VGroup() for thumbnail in thumbnails: folder, name = os.path.split(thumbnail.image_path) new_folder = guarantee_existence(os.path.join(folder, "blurred")) blur_path = os.path.join(new_folder, name) pil_img = thumbnail.image blurry_pil_img = pil_img.filter(ImageFilter.GaussianBlur(radius=75)) with open(blur_path, 'w') as fp: blurry_pil_img.save(fp) blurry_image = ImageMobject(blur_path) blurry_image.replace(thumbnail) cover = Group( SurroundingRectangle(blurry_image, buff=0).set_stroke(WHITE, 3), blurry_image ) label = Tex("?").move_to(cover) cover.add(label) covers.add(cover) cover_labels.add(label) # Shuffle them up and add labels indices = list(range(1, 25)) # random.shuffle(indices) indices = [0, *indices] for n, cover in enumerate(covers): cover.save_state() cover.move_to(thumbnails[indices[n]]) label = Integer(indices[n] + 1, font_size=60) label.set_height(0.6 * cover.get_height()) label.move_to(cover) label.set_fill(WHITE) label.set_backstroke(BLACK, 7) cover[-1].become(label) cover_labels.set_stroke(background=True) # Show entries self.play(LaggedStart(*( FadeIn(covers[indices.index(n)]) for n in range(len(indices)) ), run_time=4, lag_ratio=0.1)) self.wait() cover_labels.set_backstroke(BLACK, 12) # Highlight one fave = Text("(My personal\nFavorite)") fave.replace(framed_thumbnails[23], dim_to_match=0) fave.scale(0.8) fave.set_backstroke(BLACK, 3) self.play(FadeOut(cover_labels), FadeIn(fave)) self.wait() self.play(FadeOut(fave), FadeIn(cover_labels)) # Reveal first self.reveal(framed_thumbnails[0], names[0], covers[0]) self.wait() # Shuffle remaining for cover in covers: cover.saved_state[-1].set_opacity(0) self.play(LaggedStart(*( Restore(cover, path_arc=30 * DEGREES) for cover in covers[1:] )), lag_ratio=0.01, run_time=2) # Reveal one by one for image, name, cover in list(zip(framed_thumbnails, names, covers))[1:]: self.reveal(image, name, cover) # Reveal winners winners = [ "The Mathematics of String Art", "Minimal Surfaces & the Calculus of Variations", "Rethinking the real line", "Pixel Art Anti Aliasing", "How Computers Use Numbers", ] winner_ftns = Group(*( framed_thumbnails[names.index(winner)] for winner in winners )) to_fade = Group(*( ftn for ftn in framed_thumbnails if ftn not in winner_ftns )) winner_ftns.target = winner_ftns.generate_target() winner_ftns.target.scale(2) winner_ftns.target.arrange_in_grid(2, 3, h_buff=0.5, v_buff=1.5) winner_ftns.target[3:].match_x(winner_ftns.target[:3]) winner_ftns.target.set_width(FRAME_WIDTH - 1) winner_ftns.target.to_edge(DOWN) for ftn in winner_ftns.target: ftn.scale(0.5) self.play(FadeOut(to_fade, lag_ratio=0.1, run_time=2)) self.play(MoveToTarget(winner_ftns, run_time=2)) self.wait() # Add winner names winner_names = VGroup(*( Text(name, font_size=36) for name in [ "The Mathematics\nof String Art", "Minimal Surfaces & \n Calculus of Variations", "Rethinking the\nReal Line", "Pixel Art\nAnti-aliasing", "How Computers\nUse Numbers", ] )) for name, ftn in zip(winner_names, winner_ftns): ftn.target = ftn.generate_target() ftn.target.scale(2) name.next_to(ftn.target, UP) self.play( FadeIn(name, lag_ratio=0.1), MoveToTarget(ftn), ) self.wait() def reveal(self, image, name, cover): fade_rect = FullScreenRectangle() fade_rect.set_fill(BLACK, opacity=0) image.save_state() title = Text(name, font_size=60) title.set_max_width(FRAME_WIDTH - 1) title.to_edge(UP) self.add(fade_rect, image, cover) self.play(FadeOut(cover)) self.remove(cover) self.play( fade_rect.animate.set_fill(opacity=1.0), image.animate.set_height(6).next_to(title, DOWN), FadeInFromPoint(title, image.get_top()), ) self.wait() self.play( FadeOut(fade_rect), Restore(image), FadeOutToPoint(title, image.saved_state.get_top()), ) class MetaThumbnail(InteractiveScene): def construct(self): thumbnail_dir = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/SoME3/EntryThumbnails" names = [ "The Mathematics of String Art", "Rethinking the real line", "The Longest Increasing Subsequence", "Chasing Fixed Points: Greedy Gremlin's Trade-Off", "How Infinity Works", "Pixel Art Anti Aliasing", "The Math of Saving The Enola Gay", "Making a Pitch Shifter", "Functions are Vectors", "Cayley Graphs and Pretty Things", "The Matrix Arcade: A Visual Explorable of Matrix Transformations", "Watching Neural Networks Learn", "The Art of Linear Programming", "The Mosaic Problem - How and Why to do Math for Fun", "Affording a Planet With Geometry", "When CAN'T Math Be Generalized?", "Rotation + Translation = Rotation. Animated proof", "How did the Ancient Egyptians find this volume without Algebra?", "A Subtle Aspect of Circular Motion", "Minimal Surfaces & the Calculus of Variations", "How does a computer-calculator compute logarithms?", "What Happens If We Add Fractions Incorrectly?", "Can you guess this shape from its shadows?", "How Computers Use Numbers", "Signed Distance Functions", "A Study In Greyscale", "Conservative matrix fields", "Are Elo Systems Overrated?", "The essence of multivariable calculus", "The Principle of Least Action", ] thumbnails = Group(*( ImageMobject(os.path.join(thumbnail_dir, name)) for name in names )) ftns = Group(*( Group( SurroundingRectangle(tn, buff=0).set_stroke(GREY_A, 2), tn ) for tn in thumbnails )) # Rows groups = Group( ftns[:2], ftns[2:6], ftns[6:14], ftns[14:30], ) last = self.frame.get_top() for n, group in enumerate(groups): group.scale(2**-n) group.arrange(RIGHT, buff=0.1) group.set_width(FRAME_WIDTH - 0.5) group.next_to(last, DOWN, buff=0.2) last = group.get_bottom() self.add(ftns) return # Fractal last_rect = FullScreenRectangle().set_height(7.25) for trip in zip(ftns[0::3], ftns[1::3], ftns[2::3]): triad = self.create_triad(*trip, last_rect) last_rect = triad[-1] self.add(ftns) def create_triad(self, im1, im2, im3, to_replace): group = Group(im1, im2, im3) for im in group: im.set_height(4) group.add(ScreenRectangle(height=4).set_opacity(0)) group.arrange_in_grid(buff=0.25) group.replace(to_replace) return group class GenerallyGreat(InteractiveScene): def construct(self): # Set up audience types audience_names = [ "a child", "a middle school student", "a high school student", "an undergraduate in math", "an undergraduate in engineering", "a college student who doesn't like math", "a math Ph.D. student", "a professional in a technical field", "a person who hasn't thought about math for a decade", ] audiences = VGroup(*( Text(f"for {name}") for name in audience_names )) audiences.scale(0.9) audiences.arrange(DOWN, buff=0.3, aligned_edge=LEFT) audiences.to_corner(UR) dots = Tex(R"\vdots") dots.next_to(audiences, DOWN) dots.shift(3 * LEFT + 0.25 * DOWN) self.add(audiences, dots) # Quality GREEN_YELLOW = interpolate_color(GREEN, YELLOW, 0.25) qualities1 = VGroup(*map(Text, ["Good"] * len(audiences))).set_color(GREEN) qualities2 = VGroup(*map(Text, ["Pretty good"] * len(audiences))).set_color(YELLOW) qualities3 = VGroup( Text("Terrible").set_color(RED), Text("Bad").set_color(RED), Text("Okay").set_color(YELLOW), Text("Good").set_color(GREEN_YELLOW), Text("Great").set_color(GREEN), Text("Bad").set_color(RED), Text("Okay").set_color(YELLOW), Text("Good").set_color(GREEN_YELLOW), Text("Bad").set_color(RED), ) for group in [qualities1, qualities2, qualities3]: group.scale(0.9) for quality, audience in zip(group, audiences): quality.next_to(audience, LEFT, buff=0.25) annotations = VGroup( Text("Not\nPossible", font_size=90, fill_color=RED, alignment="LEFT"), Text("Rare, but\nPossible", font_size=90, fill_color=YELLOW, alignment="LEFT"), Text("", font_size=90, fill_color=GREEN, alignment="LEFT"), ) for annotation in annotations: annotation.to_corner(UR) rect = SurroundingRectangle(VGroup(qualities3[4], audiences[4])) rect.set_stroke(GREEN, 2) self.play( LaggedStartMap(FadeIn, qualities1), FadeIn(annotations[0]) ) self.wait() self.play( LaggedStartMap(FadeOut, qualities1, shift=LEFT), LaggedStartMap(FadeIn, qualities2, shift=LEFT), FadeOut(annotations[0], LEFT), FadeIn(annotations[1], LEFT), ) self.wait() self.play( LaggedStartMap(FadeOut, qualities2, shift=LEFT), LaggedStartMap(FadeIn, qualities3, shift=LEFT), FadeIn(rect), FadeOut(annotations[1], LEFT), FadeIn(annotations[2], LEFT), ) self.wait() class OtherGreatOnes(InteractiveScene): def construct(self): self.add(FullScreenRectangle()) names = [ "Signed Distance Functions", "A Study In Greyscale", "Conservative matrix fields", "Are Elo Systems Overrated?", "The essence of multivariable calculus", "The Principle of Least Action", ] thumbnail_dir = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/SoME3/EntryThumbnails" pieces = Group(*( Group( Text(name), ImageMobject( os.path.join(thumbnail_dir, name), height=4 ) ).arrange(UP) for name in names )) pieces.arrange_in_grid(2, 3, buff=0.5) # pieces[3:].match_x(pieces[:3]) pieces.set_width(FRAME_WIDTH - 1) pieces.to_edge(DOWN) title = Text("Some others I personally enjoyed a lot", font_size=60) title.to_edge(UP) self.add(title) self.play(LaggedStartMap(FadeIn, pieces, lag_ratio=0.5, run_time=4)) self.wait() class ManyThanks(InteractiveScene): def construct(self): morty = Mortimer() words = Text("Many thanks are in order") words.next_to(morty, DOWN) self.add(morty, words) self.play(morty.change("gracious")) self.play(Blink(morty)) self.wait() class Credits(InteractiveScene): def construct(self): # Credits credit_words = [ ("Community management and logistics", "James Schloss"), ("Web development", "Frédéric Crozatier"), ("Guest judging, advising, and funding", "Jane Street"), ] credits = VGroup(*( VGroup( Text(role, font_size=36, fill_color=GREY_B), Text(name, font_size=48), ).arrange(DOWN) for role, name in credit_words )) credits.arrange(DOWN, buff=1.0) credits.to_edge(UP) logo = SVGMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/SoME3/main/images/janestreet_logo/LOGO_stacked_w_registration_white.svg") logo.set_height(1.75) logo.move_to(credits[2][1], UP) logo.shift(0.5 * DOWN) credits[2].replace_submobject(1, logo) for credit in credits: for part in credit.family_members_with_points(): part.set_stroke(color=part.get_fill_color(), width=0.5, background=True) self.play(FadeIn(credit[0]), Write(credit[1])) self.wait() # Test class EndScreen(PatreonEndScreen): thanks_words = """ And, of course, many thanks to channel patrons """
from manim_imports_ext import * from _2023.clt.main import * # class MysteryConstant(InteractiveScene): # def construct(self): # eq_C = Tex("= C", t2c={"C": RED}, font_size=24) # eq_C.to_edge(UP).shift(3 * LEFT) # words = Text("Mystery Constant", font_size=56) # words.set_color(RED) # words.next_to(ORIGIN, RIGHT) # words.to_edge(UP) # arrow = Arrow(words, eq_C, stroke_color=RED) # self.play( # Write(words), # FadeIn(eq_C, LEFT), # GrowArrow(arrow) # ) # self.wait() class WignerZoom(InteractiveScene): def construct(self): im1 = ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/clt/artwork/wigner-speech/wigner-speech-transition-3.jpg") im1.set_height(FRAME_HEIGHT) self.add(im1) # Test self.play( self.frame.animate.scale(0.4419, about_edge=UL), run_time=4, ) self.wait() class WignerReverseZoom(InteractiveScene): def construct(self): # Test im1 = ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/clt/artwork/wigner-speech/wigner-speech-transition-4.jpg") im1.set_height(FRAME_HEIGHT) self.add(im1) frame = self.frame frame.save_state() frame.scale(0.4419, about_edge=UL) words = TexText(R"Now you're pushing \\ the joke too far...", font_size=20) words.set_backstroke(BLACK, 6) words.next_to(frame.get_corner(UR), DL, buff=0.2) words.shift(0.7 * LEFT) self.play(FadeIn(words, lag_ratio=0.1, run_time=2)) self.play( Restore(frame), words.animate.set_stroke(width=3), run_time=7, ) self.wait() class PaperTitle(InteractiveScene): def construct(self): # Test title = Text(R""" The Unreasonable Effectiveness of Mathematics in the Natural Sciences """, alignment="LEFT", font_size=60) title.to_corner(UL) self.play(Write(title, run_time=3, lag_ratio=0.1)) self.wait() part = title["Unreasonable Effectiveness"] self.play( part.animate.set_color(BLUE), FlashUnder(part, time_width=1.5, run_time=2, color=BLUE) ) self.wait() class StoryWords(InteractiveScene): quote = R""" ``There is a story about \\ two friends who were \\ classmates in high school... """ def construct(self): # Test quote = TexText(self.quote, font_size=75, alignment=R"") quote.to_corner(DL) quote.set_backstroke(BLACK, 8) self.play(FadeIn(quote, lag_ratio=0.1, run_time=2)) self.wait() class ClosingStoryWords(StoryWords): quote = R""" ...surely the population has \\ nothing to do with the \\ circumference of the circle!'' """ class ClassicProofFrame(VideoWrapper): title = "A classic proof, due to Poisson" wait_time = 4 class OtherVideos(InteractiveScene): def construct(self): # Test folder = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/clt/why_pi_supplements/images/" images = Group(*( ImageMobject(os.path.join(folder, name)) for name in ["VCubingxThumbnail", "BrimathThumbnail", "DrAlters", "KeithConrad"] )) images.set_height(0.35 * FRAME_HEIGHT) images.arrange_in_grid(h_buff=2.0, v_buff=1.0) images.to_edge(DOWN) names = VGroup( Text("vcubingx"), Text("BriTheMathGuy"), Text("idan-alter.github.io"), Text("kconrad.math.uconn.edu"), ) rects = VGroup() groups = Group() for name, image in zip(names, images): name.scale(0.75) name.move_to(image.get_top()) name.shift(0.25 * UP) rect = SurroundingRectangle(image, buff=0) rects.add(rect) groups.add(Group(rect, image, name)) rects.set_stroke(WHITE, 4) self.play(LaggedStartMap(FadeIn, groups, lag_ratio=0.5)) self.wait() class CirclesToPopulation(InteractiveScene): def construct(self): # Show arrow circle = Circle(radius=1.5) circle.set_stroke(RED, 3) circle.set_fill(RED, 0.25) circle.to_corner(UL) screen = ScreenRectangle(height=5) screen.to_corner(DR) title = Text("Population statistics") title.next_to(screen, UP, SMALL_BUFF) arrow = Arrow(circle.get_right() + UP, title, path_arc=-0.5 * PI) q_marks = Text("???") q_marks.move_to(arrow) self.add(circle) self.play( ShowCreation(arrow), FadeIn(title, DR) ) self.wait() self.play(Write(q_marks)) self.wait() class LastVideoFrame(InteractiveScene): def construct(self): self.add(FullScreenRectangle().set_fill(GREY_E, 1)) screen = ScreenRectangle(height=6.5) screen.to_edge(DOWN, buff=MED_SMALL_BUFF) screen.set_fill(BLACK, 1) screen.set_stroke(BLACK, 0) screen_outline = screen.copy().set_stroke(BLUE_D, 2) self.add(screen) # Test titles = VGroup( Text("Central Limit Theorem"), Text("Normal Distribution"), Text("Normal Distribution (aka a Gaussian)"), ) for title in titles: title.scale(56 / 48) title.move_to(midpoint(screen.get_top(), TOP)) self.add(titles[0]) self.play(ShowCreation(screen_outline, run_time=3)) self.wait(2) self.play( FadeOut(titles[0], UP), FadeIn(titles[1], UP), ) self.wait() self.play( ReplacementTransform(titles[1], titles[2]["Normal Distribution"][0]), Write(titles[2]["(aka a Gaussian)"]) ) self.wait(3) class SatisfyThisDisbelief(InteractiveScene): def construct(self): # Words words = Text(""" What explanation would satisfy their disbelief? """, alignment="LEFT") words.set_backstroke(width=3) words.to_corner(UR) arrow = Arrow(words.get_left(), 2 * LEFT + 2 * UP) pis = VGroup( Mortimer(), Randolph(color=BLUE_D).flip(), Randolph(color=BLUE_E).flip(), Randolph(color=BLUE_C).flip(), ) pis.arrange_in_grid() pis.set_height(4) pis.to_corner(DR) self.add(pis) pis[0].change_mode("happy") self.play(LaggedStart( pis[0].change("raise_right_hand"), pis[1].change("pondering", look_at=arrow.get_end()), pis[2].change("pondering", look_at=arrow.get_end()), pis[3].change("pondering", look_at=arrow.get_end()), lag_ratio=0.5 )) for x in range(2): self.play(Blink(random.choice(pis))) self.wait() self.play( FadeIn(words, lag_ratio=0.1), GrowArrow(arrow), pis[0].change("raise_left_hand", look_at=words), *(pi.animate.look_at(words) for pi in pis[1:]) ) for x in range(3): self.play(Blink(random.choice(pis))) self.wait() self.wait() class ThreeStepPlan(InteractiveScene): def construct(self): # Steps step_titles = VGroup(*( Text(f"Step {n}", font_size=48) for n in [1, 2, 3] )) kw = dict(t2c={"e^{-{x}^2}": BLUE, R"\sqrt{\pi}": TEAL}, color=GREY_A, font_size=36, alignment="") step_contents = VGroup( TexText(R"Explain why the area under \\$e^{-{x}^2}$ is $\sqrt{\pi}$", **kw), TexText(R"Explain where $e^{-{x}^2}$ comes from \\ in the first place", **kw), TexText(R"Connect it all to the \\ Central Limit Theorem", **kw), ) steps = VGroup() for title, content in zip(step_titles, step_contents): content.next_to(title, DOWN, aligned_edge=LEFT) steps.add(VGroup(title, content)) steps.arrange(DOWN, buff=0.75, aligned_edge=LEFT) steps.to_corner(UL) step_rects = VGroup(*( SurroundingRectangle(content) for content in step_contents )) step_rects.set_fill(GREY_E, 1) step_rects.set_stroke(RED, 1, 0.5) self.add(steps) self.add(step_rects) self.remove(step_contents) self.wait() for rect, content in zip(step_rects, step_contents): self.add(content, rect) self.play(rect.animate.stretch(0, 0, about_edge=RIGHT).set_stroke(opacity=0)) self.remove(rect) self.wait() # Step by step for step in steps: step.save_state() for step in steps: anims = [Restore(step)] for other_step in steps: if other_step is not step: anims.append(other_step.animate.restore().scale(0.75, about_edge=LEFT).set_opacity(0.5)) self.play(*anims) self.wait() class ManyBulgingFunctions(InteractiveScene): def construct(self): # Test axes = Axes((-3, 3), (0, 1), width=3, height=1, axis_config=dict(tick_size=0.05)) all_axes = axes.get_grid(3, 2, h_buff=LARGE_BUFF, v_buff=1.5) all_axes.to_edge(RIGHT) ie = math.exp(-1) eem1 = math.exp(-math.exp(-1)) functions = [ lambda x: (1 / (1 + x**2)), lambda x: (1 / (1 + x**4)), lambda x: np.exp(-x**2), lambda x: np.exp(-x**4), lambda x: eem1 * (np.abs(x) + ie)**(-np.abs(x) - ie), lambda x: np.sinc(x)**2, ] func_labels = VGroup( Tex(R"\frac{1}{1 + x^2}"), Tex(R"\frac{1}{1 + x^4}"), Tex(R"e^{-x^2}", font_size=60), Tex(R"e^{-x^4}", font_size=60), Tex(R"e^{-1/e} \left(\left|x\right|+\frac{1}{e}\right)^{-\left(\left|x\right|+\frac{1}{e}\right)}", font_size=36), Tex(R"\left(\frac{\sin(\pi x)}{\pi x} \right)^2"), ) colors = [TEAL_C, TEAL_D, BLUE_C, BLUE_D, RED_C, RED_D] plots = VGroup() for axes, func, label, color in zip(all_axes, functions, func_labels, colors): label.scale(0.5) label.move_to(axes.get_corner(UR)) label.shift_onto_screen() graph = axes.get_graph(func) graph.set_stroke(color, 3) graph.move_to(axes.get_top(), UP) plots.add(VGroup(axes, graph, label)) key_plot = plots[2] plots.remove(key_plot) self.play( FadeIn(key_plot[0]), ShowCreation(key_plot[1]), Write(key_plot[2]), ) self.wait() self.play(LaggedStartMap(FadeIn, plots, lag_ratio=0.5)) self.wait() self.play(plots.animate.fade(0.5)) self.wait() class WarningCalculus(InteractiveScene): def construct(self): # Add warning sign warning_sign = Triangle().set_height(2) warning_sign.set_stroke(RED, 5) warning_sign.set_fill(RED, 0.25) warning_sign.round_corners(radius=0.1) bang = Text("!") bang.set_height(warning_sign.get_height() * 0.7) bang.next_to(warning_sign.get_bottom(), UP, SMALL_BUFF) bang.match_color(warning_sign) warning_sign.add(bang) signs = warning_sign.replicate(2) signs.arrange(RIGHT) warning = VGroup( Text("Warning", font_size=120), Text("Calculus ahead", font_size=90) ) warning.arrange(DOWN, MED_LARGE_BUFF) warning.set_color(RED) signs.match_height(warning) signs[0].next_to(warning, LEFT) signs[1].next_to(warning, RIGHT) warning.add(*signs) warning.to_edge(UP) self.add(warning) # Explanation text = Text(""" I mean, it's not that bad, but what follows does assume some familiarity with integrals. If you haven't yet learned calculus, feel free to give it a go and watch anyway, the visuals hopefully help to make the main idea clear, but know that in that case you shouldn't feel bad at all if it doesn't make sense! If that is you, perhaps I could interest you in watching the series about calculus on this channel? I mean, you do you, learn calculus from wherever you want. I'm just saying, it's right there if you want it. """, alignment="LEFT", font_size=36) text.next_to(warning, DOWN, LARGE_BUFF) self.play(FadeIn(text, lag_ratio=1 / len(text))) class IntegralTitleCard(InteractiveScene): def construct(self): # Test curve = FunctionGraph(lambda x: np.exp(-x**2), x_range=(-2.5, 2.5, 0.1)) curve.set_width(8) curve.set_height(3, stretch=True) curve.move_to(DOWN) curve.set_stroke(BLUE, 3) curve.set_fill(BLUE, 0.5) # Make it into an equation curve.set_height(2) parens = Tex("()") parens.match_height(curve) parens[0].next_to(curve, LEFT, buff=0.2) parens[1].next_to(curve, RIGHT, buff=0.2) lhs = VGroup(curve, parens) two = Integer(2).move_to(lhs.get_corner(UR)) lhs.add(two) equals = Tex("=", font_size=90) equals.next_to(lhs, RIGHT, MED_LARGE_BUFF) circle = Circle() circle.match_style(curve) circle.set_height(3) circle.next_to(equals, RIGHT, MED_LARGE_BUFF) radius = Line(circle.get_center(), circle.get_right()) radius.set_stroke(WHITE, 2) r_label = Integer(1).next_to(radius, UP, SMALL_BUFF) rhs = VGroup(circle, radius, r_label) equation = VGroup(lhs, equals, rhs) equation.move_to(DOWN) # Animate self.add(curve) circle.set_fill(opacity=0) self.play(LaggedStart( Write(VGroup(parens, two, equals), run_time=1), TransformFromCopy(curve.copy().set_fill(opacity=0), circle), FadeIn(VGroup(radius, r_label)), FadeIn(circle.copy().set_fill(opacity=0.5)), lag_ratio=0.5, run_time=3 )) # circle.set_fill(opacity=0.5) self.add(rhs) # self.play(circle.animate.set_fill(opacity=0.5)) self.wait(2) return # Alternatively... func_label = Tex("e^{-x^2}", font_size=60) func_label.next_to(curve.pfp(0.6), UR) area_label = Tex(R"\sqrt{\pi}", font_size=120) area_label.move_to(curve, DOWN).shift(0.5 * UP) self.play(ShowCreation(curve), FadeIn(func_label, lag_ratio=0.1)) self.play(curve.animate.set_fill(BLUE, 0.5), Write(area_label)) self.wait() class Usually(TeacherStudentsScene): def construct(self): self.remove(self.background) self.play(self.change_students("pondering", "pondering", "pondering", look_at=self.screen)) self.play(self.teacher.says("At least, usually")) self.play(self.change_students("erm", "confused", "sassy")) self.wait(3) class SorryWhat(TeacherStudentsScene): def construct(self): stds = self.students morty = self.teacher self.remove(self.background) self.play(LaggedStart( stds[1].says("Sorry, what?!", mode="angry"), stds[0].change("sassy", look_at=morty), stds[2].change("hesitant", look_at=morty), morty.change("tease"), lag_ratio=0.2, )) self.wait(3) class WhoOrderedMoreDimensions(TeacherStudentsScene): def construct(self): # Ask stds = self.students morty = self.teacher self.remove(self.background) self.play(LaggedStart( stds[0].says("Why", mode="raise_left_hand"), stds[2].change("hesitant", look_at=morty), morty.change("tease"), stds[1].says( "Who ordered \n another dimension?", mode="confused", bubble_direction=LEFT, ), lag_ratio=0.2, )) self.wait(3) self.play(LaggedStart( morty.says("Well, watch\nwhat happens", mode="shruggie"), stds[0].debubble(mode="hesitant"), stds[1].debubble(mode="maybe"), stds[2].change("sassy"), )) self.wait(3) self.play( FadeOut(VGroup(morty.bubble, morty.bubble.content)), morty.says("It never hurts to\ntry similar problems"), self.change_students("pondering", "erm", "pondering", look_at=self.screen) ) self.wait(3) class MysteryConstant(InteractiveScene): def construct(self): eq_C = Tex("= C", t2c={"C": RED}, font_size=24) eq_C.to_edge(UP).shift(3 * LEFT) words = Text("Mystery Constant", font_size=56) words.set_color(RED) words.next_to(ORIGIN, RIGHT) words.to_edge(UP) arrow = Arrow(words, eq_C, stroke_color=RED) self.play( Write(words), FadeIn(eq_C, LEFT), GrowArrow(arrow) ) self.wait() class YLineFlash(InteractiveScene): def construct(self): line = Line(7 * RIGHT, 7 * LEFT) line.insert_n_curves(50) line.set_stroke(YELLOW, 5) self.play(VShowPassingFlash(line, run_time=3, time_width=0.7)) class VolumeEqualsPi(InteractiveScene): def construct(self): text = TexText(R"Volume = $\pi$") text[R"\pi"].scale(2, about_edge=LEFT) self.add(text) class OurKind(TeacherStudentsScene): def construct(self): self.remove(self.background) self.play(self.change_students("pondering", "thinking", "pondering", look_at=self.screen)) self.play( self.teacher.says("Where there is\ncircular symmetry,\nour kind thrives", mode="hooray") ) self.play(self.change_students("happy", "thinking", "tease")) self.play(self.teacher.change("tease")) self.look_at(self.screen) self.wait(6) class DirectlyUseful(InteractiveScene): def construct(self): self.add(FullScreenRectangle().set_fill(GREY_E, 1)) rects = ScreenRectangle().replicate(2) rects.set_stroke(WHITE, 2) rects.set_fill(BLACK, 1) rects.arrange(RIGHT, buff=LARGE_BUFF) rects.set_width(FRAME_WIDTH - 1) rects.to_edge(DOWN, buff=1.5) self.add(rects) arrow = Arrow(rects[1].get_top(), rects[0].get_top(), path_arc=0.5 * PI) words = Text("Directly useful") words.next_to(arrow, UP) self.play( ShowCreation(arrow), FadeIn(words, lag_ratio=0.1), ) self.wait() class CompareThreeIntegrals(InteractiveScene): def construct(self): # Frames self.add(FullScreenRectangle().set_fill(GREY_E, 0.5)) buff = MED_LARGE_BUFF rects = Rectangle(height=5.0, width=(FRAME_WIDTH - 4 * buff) / 3).replicate(3) rects.arrange(RIGHT, buff=buff) rects.to_edge(DOWN, buff=1.0) rects.set_fill(BLACK, 1) rects.set_stroke(TEAL, 1) # Titles kw = dict( font_size=48, t2c={"C": PINK, "{x}": BLUE, "{y}": YELLOW, "{r}": RED} ) titles = VGroup( TexText("Area = $C$", **kw), TexText("Volume = $C^2$", **kw), TexText(R"Volume = $\pi$", **kw), ) titles[2][R"\pi"].scale(1.5, about_edge=DL) integrals = VGroup( Tex(R"\int_{-\infty}^\infty e^{-{x}^2}\,d{x} = C", **kw), Tex(R"\int_{-\infty}^\infty \int_{-\infty}^\infty e^{-{y}^2} e^{-{x}^2}\,d{x}\,d{y} = C^2", **kw), Tex(R"\int_0^\infty 2\pi r \cdot e^{-{r}^2} \,d{r} = \pi", **kw), ) integrals.scale(0.5) for title, integral, rect in zip(titles, integrals, rects): title.next_to(rect, UP, buff=MED_LARGE_BUFF) integral.next_to(rect.get_top(), DOWN) # Show first two self.add(*rects[:2]) self.wait() for title, integral in zip(titles[:2], integrals[:2]): self.play( FadeIn(title, 0.5 * UP), FadeIn(integral, 0.5 * DOWN) ) self.wait(2) # Show third self.play( FadeIn(rects[2]), FadeIn(titles[2], 0.5 * UP), FadeIn(integrals[2], 0.5 * DOWN) ) self.wait() # Equations eq_pi = titles[2][R"= $\pi$"][0].copy() eq_pi.generate_target() eq_sqrt_pi = Tex(R"= \sqrt{\pi}", **kw) for title, rhs in zip(titles[:2], (eq_sqrt_pi, eq_pi.target)): title.generate_target() rhs.next_to(title, RIGHT) rhs.shift((title["="].get_y() - rhs[0].get_y()) * UP) VGroup(title.target, rhs).match_x(title) self.play(LaggedStart( MoveToTarget(eq_pi), MoveToTarget(titles[1]), lag_ratio=0.35, )) self.play(LaggedStart( TransformMatchingShapes(eq_pi.copy(), eq_sqrt_pi, run_time=1), MoveToTarget(titles[0]), lag_ratio=0.35, )) self.wait() self.play(FlashAround(eq_sqrt_pi[1:], run_time=2, time_width=1)) self.wait() class FeelsLikeATrick(InteractiveScene): def construct(self): # Test words = VGroup( Text("This feels \n like a trick"), Text("How could you have \n discovered this?"), ) words.to_corner(UL) screen = ScreenRectangle(height=5) screen.to_corner(DR) arrows = VGroup(*( Arrow(word.get_right(), screen.get_top(), path_arc=-0.3 * PI) for word in words )) self.play(Write(words[0], run_time=1), ShowCreation(arrows[0])) self.wait(2) self.play( FadeOut(words[0], UP), FadeIn(words[1], UP), Transform(*arrows), ) self.wait(2) class HerschelMaxwellTitle(InteractiveScene): def construct(self): title = Text(""" The Herschel-Maxwell derivation for a Gaussian """, font_size=72) title.to_edge(UP, buff=MED_SMALL_BUFF) title.set_backstroke(width=5) self.play(Write(title)) self.wait(3) # Transition to Herschel name name = Text("John Herschel", font_size=60) years = Text("1792 - 1871") bio = VGroup(name, years) bio.arrange(DOWN) bio.to_corner(UL) bio.shift(1.0 * RIGHT) pre_name = title["Herschel"] title.remove(*pre_name) self.play( FadeOut(title, lag_ratio=0.1), ReplacementTransform(pre_name, name["Herschel"]), FadeInFromPoint(name["John"], pre_name.get_left()), ) self.play(Write(years)) self.wait() class HerschelDescription(InteractiveScene): def construct(self): # Positions positions = VGroup( Text("Mathematician"), Text("Scientist"), Text("Inventor"), ) positions.scale(1.5) positions.to_edge(RIGHT, buff=1.5) last = VGroup() for position in positions: self.play( FadeIn(position, 0.5 * UP), FadeOut(last, 0.5 * UP), ) self.wait(0.5) last = position self.wait() self.play(FadeOut(positions[-1])) # Contributions contributions = VGroup( Text("Chemistry"), Text("Astronomy"), Text("Photography"), Text("Botany"), ) contributions.scale(1.25) contributions.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) contributions.move_to(3 * RIGHT) self.play(ShowIncreasingSubsets(contributions, rate_func=linear, run_time=3)) self.play(LaggedStartMap(FadeOut, contributions, lag_ratio=0.5, run_time=3)) self.wait() # Moons desc = TexText(R"He named many of \\ Saturn's moons") desc.move_to(3.5 * RIGHT).to_edge(UP) moon_names = VGroup( Text("Mimas"), Text("Enceladus"), Text("Tethys"), Text("Dione"), Text("Rhea"), Text("Titan"), Text("Iapetus"), ) moon_names.set_color(GREY_B) moon_names.scale(0.75) moon_names.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) moons = Group() for name in moon_names: image = ImageMobject(name.get_string()) image.set_height(1.25 * name.get_height()) image.next_to(name, LEFT, buff=0.2) moons.add(Group(image, name)) moons.next_to(desc, DOWN, MED_LARGE_BUFF) self.play( FadeIn(desc), LaggedStartMap(FadeIn, moons, shift=0.5 * DOWN, lag_ratio=0.5, run_time=3) ) self.wait() class GaussianQuestion(InteractiveScene): def construct(self): # Test curve = FunctionGraph(lambda x: math.exp(-x**2), x_range=(-3, 3, 0.1)) curve.set_width(6) curve.set_height(2, stretch=True) curve.to_edge(RIGHT).shift(UP) curve.set_stroke(BLUE, 3) func = Tex(R"{1 \over \sqrt{2 \pi} } e^{-x^2 / 2}", font_size=40) func.move_to(curve.get_bottom()) question = Text("Where does this\ncome from?") question.next_to(func, DOWN, MED_LARGE_BUFF) year = Text("(1850)", font_size=40) year.next_to(question, DOWN, MED_LARGE_BUFF) year.set_fill(GREY_B) self.play( ShowCreation(curve), FadeIn(func), Write(question) ) self.play(FadeIn(year, DOWN)) self.wait(2) class WhatWouldBeNice(TeacherStudentsScene): def construct(self): self.play( self.teacher.says("You know what\nwould be nice?"), self.change_students("pondering", "happy", "tease", look_at=self.screen) ) self.wait(4) class HowDoYouApproachThat(TeacherStudentsScene): def construct(self): stds = self.students self.remove(self.background) self.play( stds[0].says("How do you \n approach that?", mode="raise_left_hand"), stds[1].change("maybe", look_at=3 * UP), stds[2].change("erm", look_at=3 * UP), self.teacher.change("tease") ) self.wait() self.play( self.teacher.change("raise_right_hand"), self.change_students("confused", "confused", "pondering", look_at=3 * UP) ) self.wait(3) class ImplicationPIP(InteractiveScene): def construct(self): self.add(FullScreenRectangle().set_fill(GREY_E, 1)) screens = ScreenRectangle().replicate(2) screens.set_height(0.45 * FRAME_HEIGHT) screens.arrange(RIGHT, buff=0.75) screens.set_stroke(WHITE, 2) screens.set_fill(BLACK, 1) screens.move_to(0.5 * DOWN) arrow = Arrow(screens[0].get_top(), screens[1].get_top(), path_arc=-0.4 * PI) words = Text("These necessarily imply") words.next_to(arrow, UP) self.add(screens) self.wait() self.play( ShowCreation(arrow), FadeIn(words, lag_ratio=0.1) ) self.wait() class MaxwellsEquations(InteractiveScene): def construct(self): kw = dict( t2c={R"\mathbf{E}": RED, R"\mathbf{B}": TEAL} ) equations = VGroup( Tex(R"\nabla \cdot \mathbf{E}=4 \pi \rho", **kw), Tex(R"\nabla \cdot \mathbf{B}=0", **kw), Tex(R"\nabla \times \mathbf{E}=-\frac{1}{c} \frac{\partial \mathbf{B}}{\partial t}", **kw), Tex(R"\nabla \times \mathbf{B}=\frac{1}{c}\left(4 \pi \mathbf{J}+\frac{\partial \mathbf{E}}{\partial t}\right)", **kw), ) equations.arrange(DOWN, buff=0.5, aligned_edge=LEFT) equations.set_height(6.5) equations.to_edge(LEFT) equations.set_backstroke(BLACK, 3) self.play(LaggedStartMap(FadeIn, equations, shift=0.5 * DOWN, lag_ratio=0.5)) self.wait() class StatisticalMechanicsIn3d(InteractiveScene): def construct(self): # Test n_balls = 200 self.camera.light_source.move_to([0, -5, 5]) frame = self.frame frame.reorient(20, 70) frame.set_height(2) frame.move_to([0.5, 0.5, 0.5]) balls = DotCloud(np.random.random((n_balls, 3))) balls.set_radius(0.015) balls.make_3d() balls.set_shading(0.25, 0.5, 1) cube = VCube(side_length=1.0) cube.move_to(ORIGIN, [-1, -1, -1]) cube.set_stroke(BLUE, 2) cube.set_fill(opacity=0) self.add(cube) velocities = np.random.normal(0, 3, (n_balls, 3)) def update(balls, dt): points = balls.get_points() new_points = np.clip(points + 0.1 * velocities * dt, 0, 1) velocities[new_points <= 0] *= -1 velocities[new_points >= 1] *= -1 balls.set_points(new_points) return balls balls.add_updater(update) self.add(balls) self.play(frame.animate.reorient(-20), run_time=20) class ThreeDExpression(InteractiveScene): def construct(self): expr = Tex( R"{1 \over \sigma^3 (2\pi)^{3/2}} e^{-(x^2 + y^2 + z^2) / 2 \sigma^2}", t2c={R"\sigma": RED}, font_size=48 ) expr[R"1 \over \sigma^3 (2\pi)^{3/2}}"].scale(0.7, about_edge=RIGHT) expr.to_corner(UL) self.add(expr) class DefiningProperty(InteractiveScene): def construct(self): # Setup prop = VGroup( Text("1. Radial symmetry", font_size=36), Text("2. Independence of\neach coordinate", font_size=36), ) prop.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) implies = Tex(R"\Downarrow", font_size=72) form = Tex(R"e^{-c r^2}", t2c={"c": RED}, font_size=72) derivation = VGroup(prop, implies, form) derivation.arrange(DOWN, buff=MED_LARGE_BUFF) form.shift(0.25 * UP) derivation.to_edge(LEFT, buff=1.0).shift(0.5 * DOWN) derivation_box = SurroundingRectangle(derivation, buff=0.5) derivation_box.set_stroke(YELLOW, 2) derivation_box.set_fill(YELLOW, 0.05) title = Text("Herschel-Maxwell\nDerivation") title.next_to(derivation_box, UP, MED_LARGE_BUFF) self.add(derivation_box) self.add(derivation) self.add(title) self.wait() # If we view this words = Text( "Suppose we take this\nto define a Gaussian...", t2s={"define": ITALIC}, t2c={"define": TEAL}, alignment="LEFT" ) words.match_width(derivation_box) words.next_to(derivation_box, UP) self.play(LaggedStart( FadeIn(words, 0.5 * UP), FadeOut(title, UP), lag_ratio=0.2, )) self.wait() self.play( FlashAround(prop[0], color=TEAL, time_width=1, run_time=2) ) self.wait() class ReactToDefiningProperty(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.remove(self.background) self.play( morty.change("raise_right_hand"), self.change_students("sassy", "hesitant", "erm", look_at=self.screen), ) self.play( self.change_students("erm", "sassy", "hesitant", look_at=self.screen), ) self.wait(2) # Ask self.play(LaggedStart( stds[1].says("But that assumes \n we're in 2D", mode="angry"), stds[0].change("sassy"), stds[2].animate.look_at(morty), morty.change("guilty"), lag_ratio=0.2 )) self.wait(3) self.play(LaggedStart( stds[1].debubble(mode="sassy"), stds[2].says("What about\nthe Central Limit Theorem?"), stds[0].change("hesitant"), morty.change("hesitant"), )) self.wait(3) self.play(morty.change("tease", self.screen)) self.wait() self.play( stds[0].change("pondering", self.screen), stds[1].change("pondering", self.screen), ) self.wait(3) class NextVideo(InteractiveScene): def construct(self): self.add(FullScreenRectangle().set_fill(GREY_E, 0.75)) # Thumbnails images = Group( ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2022/convolutions/discrete/images/EquationThumbnail.png"), ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/clt/main/images/Thumbnail.png"), ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/clt/integral/images/ProofSummary.jpg"), ) images.set_height(3) titles = VGroup( Text("Convolutions"), Text("Central Limit Theorem"), TexText(R"Why $\sqrt{\pi}$?"), ) thumbnails = Group() for image, title in zip(images, titles): rect = SurroundingRectangle(image, buff=0).set_stroke(WHITE, 3) title.next_to(image, UP) title.set_max_width(image.get_width()) thumbnails.add(Group(rect, image, title)) thumbnails.arrange(DOWN, buff=LARGE_BUFF) thumbnails.set_height(7) thumbnails.to_corner(UL) thumbnails.to_edge(LEFT, buff=1.0) # Video 1 morty = Mortimer(height=1).flip() morty.change_mode("tease") morty.next_to(images[0], RIGHT, MED_LARGE_BUFF, aligned_edge=DOWN) bubble = SpeechBubble(width=3, height=1) bubble.set_stroke(width=1) bubble.move_to(morty.get_corner(UR), DL).shift(SMALL_BUFF * LEFT) bubble.add_content(Text("In the next video...")) self.add(thumbnails[0]) self.play( VFadeIn(morty), morty.change("speaking"), FadeIn(bubble), Write(bubble.content, run_time=1) ) self.play( morty.animate.look_at(thumbnails[1]), FadeIn(thumbnails[1], DOWN) ) # Video 2 morty.generate_target() morty.target.align_to(thumbnails[1], DOWN) morty.target.change_mode("maybe").look_at(thumbnails[2]) words = bubble.content words2 = Text("Or rather, the next one...", t2s={"next": ITALIC}) bubble2 = morty.target.get_bubble(words2, bubble_type=SpeechBubble, width=4, height=1) bubble2.set_stroke(WHITE, 1) ghost1 = VGroup(morty, bubble, words).copy() to_fade = VGroup(ghost1) self.play( MoveToTarget(morty), Transform(bubble, bubble2), Transform(words, words2), ghost1.animate.set_opacity(0.25), ) words.become(words2) self.play(Blink(morty), FadeIn(thumbnails[2], DOWN)) # Video 3 morty.generate_target() morty.target.align_to(thumbnails[2], DOWN) morty.target.change_mode("guilty") words3 = Text("But for real this time") bubble3 = morty.target.get_bubble(words3, bubble_type=SpeechBubble, width=4, height=1) bubble3.set_stroke(WHITE, 1) ghost2 = VGroup(morty, bubble, words).copy() to_fade.add(ghost2) self.play( MoveToTarget(morty), Transform(bubble, bubble3), Transform(words, words3), ghost2.animate.set_opacity(0.25) ) words.become(words3) self.play(Blink(morty)) self.wait(2) # Right screen screen = ScreenRectangle() screen.set_height(4) screen.set_stroke(WHITE, 2) screen.set_fill(BLACK, 1) screen.to_edge(RIGHT) arrows = VGroup(*( Arrow(thumbnail.get_right(), screen.get_left() + vect, buff=0.3) for thumbnail, vect in zip(thumbnails, [UP, ORIGIN, DOWN]) )) self.play( LaggedStartMap(GrowArrow, arrows), FadeIn(screen), LaggedStartMap(FadeOut, VGroup(*to_fade, morty, bubble, words)) ) self.wait() class NDimensionalBallGrid(InteractiveScene): def construct(self): # Setup grid N_terms = 7 grid = Square().get_grid(3, N_terms + 1, buff=0, group_by_rows=True) grid.set_stroke(WHITE, 1) for row in grid: row[0].stretch(1.5, 0, about_edge=RIGHT) grid.set_width(FRAME_WIDTH - 1) grid.center().to_edge(DOWN, buff=1.0) self.add(grid) # Content kw = dict(t2c={"r": BLUE}) numbers = VGroup( *(Integer(n) for n in range(1, 6)), Tex(R"\cdots"), Text(R"N"), ) interiors = VGroup( Tex(R"2r", **kw), Tex(R"\pi r^2", **kw), Tex(R"\frac{4}{3} \pi r^3", **kw), Tex(R"\frac{1}{2} \pi^2 r^4", **kw), Tex(R"\frac{8}{15} \pi^2 r^5", **kw), Tex(R"\cdots"), Tex(R"\frac{\pi^{n / 2}}{(n / 2)!} r^n", **kw), ) exteriors = VGroup( Tex(R"2", **kw), Tex(R"2 \pi r", **kw), Tex(R"4 \pi r^2", **kw), Tex(R"2 \pi^2 r^3", **kw), Tex(R"\frac{8}{3} \pi^2 r^4", **kw), Tex(R"\cdots"), Tex(R"n \frac{\pi^{n / 2}}{(n / 2)!} r^{n - 1}", **kw), ) for group, row in zip([numbers, interiors, exteriors], grid): for elem, square in zip(group, row[1:]): elem.set_max_width(0.8 * square.get_width()) elem.move_to(square) row_titles = VGroup( Text("Dimension"), TexText(R"Volume of \\ $n$-ball", font_size=30), TexText(R"Volume of \\ $n$-ball boundary", font_size=30), ) for title, row in zip(row_titles, grid): title.set_max_width(0.8 * row[0].get_width()) title.move_to(row[0]) self.add(row_titles, numbers) # Shapes line = Line() line.set_stroke(BLUE_A, 3) one_ball = VGroup( line, Dot(line.get_start()), Dot(line.get_end()) ) one_ball[1:].set_color(BLUE) circle = Circle() circle.set_stroke(BLUE, 2) circle.set_fill(BLUE, 0.5) sphere = Sphere(color=BLUE) mesh = SurfaceMesh(sphere) mesh.set_stroke(WHITE, 0.5, 0.5) ball = Group(sphere, mesh) ball.rotate(70 * DEGREES, LEFT) shapes = Group( one_ball, circle, ball, Randolph("shruggie"), Tex(R"\dots"), *VectorizedPoint().replicate(2), ) for shape, square in zip(shapes, grid[0][1:]): shape.set_max_width(0.7 * square.get_width()) shape.move_to(square.get_top()) shape.shift(0.6 * shape.get_width() * UP) shapes[4].match_y(shapes[0]) # Animate in for shape, interior, exterior in zip(shapes, interiors, exteriors): self.play(FadeIn(shape), FadeIn(interior)) self.play(TransformMatchingTex(interior.copy(), exterior, run_time=1)) self.wait() class FinalExercise(InteractiveScene): def construct(self): # Test kw = dict( t2c={ "I_n": YELLOW, "I_1": YELLOW, "I_2": YELLOW, "I_{n - 2}": YELLOW, "C_2": TEAL, "C_3": TEAL, "C_4": TEAL, "C_5": TEAL, "C_6": TEAL, "C_n": TEAL, "C_{n - 2}": TEAL, "{r}": BLUE, }, font_size=30, alignment="" ) parts = VGroup( TexText(R""" \textbf{Part 1} \\ Define $I_n$ to be the integral below. For example, we showed in this \\ video that $I_1 = \sqrt{\pi}$ and $I_2 = \pi$. $$ I_n = \underbrace{\int_{-\infty}^\infty \cdots \int_{-\infty}^\infty}_{n \text{ times}} e^{-(x_1^2 + \cdots + x_n^2)} dx_1 \cdots dx_n $$ Explain why $I_n = \pi^{n / 2}$. Specifically, factor the expression then integrate \\ along each of the $n$ coordinate axes. """, **kw), TexText(R""" \textbf{Part 2} \\ We all learn that the circumference of a circle is $2\pi {r}$, and the surface area \\ of a sphere is $4\pi {r}^2$. In general, the boundary of an $n$-dimensional ball has \\ an $(n-1)$-dimensional volume of $C_n {r}^{n - 1}$ for some constant $C_n$. For\\ example, $C_2 = 2\pi$ and $C_3 = 4 \pi$. Our goal is to figure out this value $C_n$ \\ for each dimension $n$.\\ Explain why the integral from the previous problem can also be \\ interpreted as $$ I_n = \int_0^\infty C_n {r}^{n - 1} e^{-{r}^2} dr $$ """, **kw), TexText(R""" \textbf{Part 3} \\ Using integration by parts, show that \begin{align*} I_n = \int_0^\infty C_n {r}^{n - 1} e^{-{r}^2} dr &=\frac{n - 2}{2} C_n \int_0^\infty {r}^{n - 3} e^{-{r}^2} dr \\ &= \frac{n - 2}{2} C_n \cdot { I_{n - 2} \over C_{n - 2}} \end{align*} \quad \\ (Hint, let $u = {r}^{n - 2}$ and $dv = {r} e^{-{r}^2} dr$) """, **kw), TexText(R""" \textbf{Part 4} \\ Combine parts 1 and 3 to deduce $C_n = \frac{2\pi}{n - 2} C_{n - 2}$ for $n > 2$. Use this \\ to write the values of $C_3$, $C_4$, $C_5$, and as many more as you'd like. \\ Considering the recurrence relation above, together with the assumption \\ that $(-1/2)! = \sqrt{\pi}$ (a story for another day), can you explain why \\ the formula below for the $(n-1)$-dimensional boundary of a $n$-dimensional \\ ball makes sense? \\ $$ n {\pi^{n/2} \over (n/2)!} {r}^{n - 1}$$ """, **kw), ) rects = ScreenRectangle().get_grid(2, 2, buff=0) rects.set_height(7) rects.set_width(FRAME_WIDTH, stretch=True) rects.to_edge(DOWN, buff=0) rects.set_stroke(WHITE, 2) self.add(rects) title = Text("Challenge for the ambitious viewer", font_size=60) title.set_color(RED) title.to_edge(UP, MED_SMALL_BUFF) self.add(title) parts.scale(0.7) for part, rect in zip(parts, rects): part.move_to(rect, UL).shift(DR * SMALL_BUFF) self.add(parts) self.play(LaggedStartMap(FadeIn, parts, lag_ratio=0.7)) self.wait() class EndScreen(PatreonEndScreen): scroll_time = 30 class Thanks(InteractiveScene): def construct(self): message = Text("Thank you \n patrons!", font_size=72) morty = Mortimer().flip() morty.next_to(ORIGIN, LEFT) message.next_to(morty, RIGHT) self.play( morty.change("gracious"), Write(message) ) self.play(Blink(morty)) self.wait() self.play(Blink(morty)) self.wait(2)
from manim_imports_ext import * from _2023.convolutions2.continuous import * from _2023.clt.main import * class LastTime(VideoWrapper): wait_time = 8 title = "Normal Distribution" class AltBuildUpGaussian(BuildUpGaussian): pass class BellCurveArea(InteractiveScene): def construct(self): # Setup axes = NumberPlane( (-4, 4), (0, 1.5, 0.5), width=14, height=5, background_line_style=dict( stroke_color=GREY_C, stroke_width=2, stroke_opacity=0.5 ) ) axes.x_axis.add_numbers(font_size=24) axes.y_axis.add_numbers(num_decimal_places=1, excluding=[0]) axes.to_edge(DOWN) graph = axes.get_graph(lambda x: np.exp(-x**2)) graph.set_stroke(BLUE, 3) t2c = {"x": BLUE} graph_label = Tex("e^{-x^2}", font_size=72, t2c=t2c) graph_label.next_to(graph.pfp(0.6), UR) self.add(axes) self.play(ShowCreation(graph)) self.play(Write(graph_label)) self.wait() # Show integral integral = Tex(R"\int_{-\infty}^\infty e^{-x^2} dx", t2c=t2c) integral.to_edge(UP) self.play(graph.animate.set_fill(BLUE, 0.5)) self.wait() self.play( Write(integral[R"\int_{-\infty}^\infty"]), FadeTransform(graph_label.copy(), integral["e^{-x^2}"]) ) self.play(TransformFromCopy(integral["x"][0], integral["dx"])) self.wait() # Show rectangles colors = (BLUE_E, BLUE_D, TEAL_D, TEAL_E) rects = axes.get_riemann_rectangles(graph, dx=0.2, colors=colors) rects.set_stroke(WHITE, 1) rects.set_fill(opacity=0.75) rect = rects[len(rects) // 2 - 2].copy() rect.set_opacity(1) graph_label.set_backstroke(width=5) brace = Brace(rect, UP, SMALL_BUFF) brace.set_backstroke(width=3) dx_label = brace.get_tex("dx", buff=SMALL_BUFF) dx_label["x"].set_color(BLUE) axes.generate_target() axes.target.y_axis.numbers.set_opacity(0) self.play( FadeIn(rects, lag_ratio=0.1, run_time=3), graph.animate.set_fill(opacity=0).set_anim_args(time_span=(1, 2)), graph_label.animate.shift(SMALL_BUFF * UR).set_anim_args(time_span=(1, 2)), ) self.wait() self.play( rects.animate.set_opacity(0.1), MoveToTarget(axes), FadeIn(rect), ) self.wait() self.play(graph_label.animate.set_height(0.5).next_to(rect, LEFT, SMALL_BUFF)) self.play(FlashAround(integral["e^{-x^2}"], time_width=1, run_time=1.5)) self.wait() self.play( GrowFromCenter(brace), FadeIn(dx_label, 0.5 * UP), ) self.play(FlashAround(integral["dx"], time_width=1, run_time=1.5)) self.wait() # Show addition rects.set_fill(opacity=0.8) rects.set_stroke(WHITE, 1) self.play( graph_label.animate.set_height(0.7).next_to(graph.pfp(0.4), UL), rects.animate.set_opacity(0.75), FadeOut(rect) ) self.wait() self.play( LaggedStart(*( r.animate.shift(0.25 * UP).set_color(YELLOW).set_anim_args(rate_func=there_and_back) for r in rects ), run_time=5, lag_ratio=0.1), LaggedStart( FlashAround(integral[2:4], time_width=1), FlashAround(integral[1], time_width=1), lag_ratio=0.25, run_time=5, ) ) self.wait() # Thinner rectangles for dx in [0.1, 0.075, 0.05, 0.03, 0.02, 0.01, 0.005]: new_rects = axes.get_riemann_rectangles(graph, dx=dx, colors=colors) new_rects.set_stroke(WHITE, 1) new_rects.set_fill(opacity=0.7) self.play( Transform(rects, new_rects), brace.animate.set_width(dx * axes.x_axis.get_unit_size(), about_edge=LEFT), MaintainPositionRelativeTo(dx_label, brace), ) self.add(graph) self.play( FadeOut(brace), FadeOut(dx_label), ShowCreation(graph), ) # Indefinite integral frame = self.frame equals = Tex("=") equals.move_to(integral) equals.shift(0.5 * UP) answer_box = SurroundingRectangle(integral["e^{-x^2} dx"]) answer_box.next_to(equals, RIGHT) answer_box.set_stroke(TEAL, 2) answer_box.set_fill(GREY_E, 1) q_marks = Tex("???") q_marks.set_height(0.6 * answer_box.get_height()) q_marks.move_to(answer_box) answer_box.add(q_marks) self.play( frame.animate.set_height(9, about_edge=DOWN), integral.animate.next_to(equals, LEFT), FadeIn(equals), Write(answer_box), ) integral.save_state() integral.generate_target() integral.target[1:4].stretch(0, 0, about_edge=RIGHT).set_opacity(0) integral.target[0].move_to(integral[:4], RIGHT) self.play(MoveToTarget(integral)) # Arrows int_box = SurroundingRectangle(integral["e^{-x^2} dx"]) int_box.set_stroke(BLUE, 2) arc = -0.5 * PI low_arrow = Arrow(answer_box.get_bottom(), int_box.get_bottom(), path_arc=arc) top_arrow = Arrow(int_box.get_top(), answer_box.get_top(), path_arc=arc) low_words = Text("Derivative", font_size=30) low_words.next_to(low_arrow, DOWN, MED_SMALL_BUFF) top_words = Text("Antiderivative", font_size=30) top_words.next_to(top_arrow, UP, MED_SMALL_BUFF) self.play( ShowCreation(low_arrow), FadeIn(low_words, 0.5 * LEFT), FadeTransform(answer_box.copy(), int_box, path_arc=arc) ) self.wait() self.play( ShowCreation(top_arrow), FadeIn(top_words, 0.5 * RIGHT), ) self.wait() # Impossible impossible = Text("Impossible!", font_size=72, color=RED) impossible.next_to(answer_box, RIGHT) functions = VGroup( Tex(R"a_n x^n + \cdots a_1 x + a_0", t2c=t2c), Tex(R"\sin(x), \cos(x), \tan(x)", t2c=t2c), Tex(R"b^x", t2c=t2c), Tex(R"\vdots") ) functions.arrange(DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) functions.set_height(2.5) functions.next_to(impossible, RIGHT, buff=LARGE_BUFF) self.play(FadeIn(impossible, scale=0.5, rate_func=rush_into)) self.wait() self.play( LaggedStartMap(FadeIn, functions, shift=DOWN, lag_ratio=0.5), frame.animate.shift(4 * RIGHT), run_time=3 ) self.wait() class AntiDerivative(InteractiveScene): def construct(self): # Add both planes x_min, x_max = (-3, 3) planes = VGroup(*( NumberPlane( (x_min, x_max), (0, 2), width=5.5, height=2.75, background_line_style=dict(stroke_color=GREY, stroke_width=1, stroke_opacity=1.0), faded_line_ratio=3, ) for x in range(2) )) planes.arrange(DOWN, buff=LARGE_BUFF) planes.to_corner(UL) self.add(planes) # Titles titles = VGroup( Tex("f(x) = e^{-x^2}", font_size=66), Tex(R"F(x) = \int_0^x e^{-t^2} dt"), ) for title, plane in zip(titles, planes): title.next_to(plane, RIGHT) ad_word = Text("Antiderivative") ad_word.next_to(titles[1], UP, MED_LARGE_BUFF) VGroup(ad_word, titles[1]).match_y(planes[1]) self.add(titles) self.add(ad_word) # High graph x_tracker = ValueTracker(0) get_x = x_tracker.get_value high_graph = planes[0].get_graph(lambda x: np.exp(-x**2)) high_graph.set_stroke(BLUE, 3) high_area = high_graph.copy() def update_area(area: VMobject): x = get_x() area.become(high_graph) area.set_stroke(width=0) area.set_fill(BLUE, 0.5) area.pointwise_become_partial( high_graph, 0, inverse_interpolate(x_min, x_max, x) ) area.add_line_to(planes[0].c2p(x, 0)) area.add_line_to(planes[0].c2p(x_min, 0)) return area high_area.add_updater(update_area) self.add(high_graph, high_area) # Low graph dist = scipy.stats.norm(0, 1) low_graph = planes[1].get_graph(lambda x: math.sqrt(PI) * dist.cdf(x)) low_graph.set_stroke(YELLOW, 2) low_dot = GlowDot() low_dot.add_updater(lambda m: m.move_to(planes[1].i2gp(get_x(), low_graph))) low_line = always_redraw(lambda: DashedLine( planes[1].c2p(get_x(), 0), planes[1].i2gp(get_x(), low_graph), ).set_stroke(WHITE, 2)) self.add(low_graph, low_dot, low_line) # Animations for value in [1.5, -2, -1, 1, -0.5, 0.5, 3.0, -1.5]: self.play(x_tracker.animate.set_value(value), run_time=3) self.wait() class UsualFunctionTypes(InteractiveScene): def construct(self): t2c = {"x": YELLOW} functions = VGroup( Tex(R"a_n x^n + \cdots a_1 x + a_0", t2c=t2c), Tex(R"\sin(x), \cos(x), \arctan(x)", t2c=t2c), Tex(R"b^x, \log(x), \cosh(x)", t2c=t2c), Tex(R"\vdots") ) functions.arrange(DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) functions.set_height(2.5) functions.to_edge(RIGHT, buff=0.6) box = SurroundingRectangle(functions, buff=MED_LARGE_BUFF) box.set_stroke(RED, 2) words = Text("Cannot be expressed \n in terms of these:") words.next_to(box, UP) words.set_fill(RED) self.play( FadeIn(words, lag_ratio=0.1), FadeIn(box), LaggedStartMap(FadeIn, functions, shift=DOWN, lag_ratio=0.5, run_time=3), ) self.wait() class GaussianIntegral(ThreeDScene, InteractiveScene): def func(self, x, y): return np.exp(-x**2 - y**2) def get_axes( self, x_range=(-3, 3), y_range=(-3, 3), z_range=(0, 1.5, 0.5), width=8, height=8, depth=3, center=0.5 * IN, include_plane=False ): axes = ThreeDAxes( x_range, y_range, z_range, width=width, height=height, depth=depth ) axes.set_stroke(GREY_C) if include_plane: plane = NumberPlane( x_range, y_range, width=width, height=height, background_line_style=dict( stroke_color=GREY_C, stroke_width=1, ), ) plane.faded_lines.set_stroke(opacity=0.5) plane.shift(0.01 * IN) axes.plane = plane axes.add(plane) x, y, z = axis_labels = VGroup(*map(Tex, "xyz")) axis_labels.use_winding_fill(False) x.next_to(axes.x_axis, RIGHT) y.next_to(axes.y_axis, UP) z.rotate(90 * DEGREES, RIGHT) z.next_to(axes.z_axis, OUT) axes.labels = axis_labels axes.add(axis_labels) axes.shift(center - axes.c2p(0, 0, 0)) axes.set_flat_stroke(False) return axes def get_gaussian_graph( self, axes, color=interpolate_color(BLUE_E, BLACK, 0.6), opacity=1.0, shading=(0.2, 0.2, 0.4), ): graph = axes.get_graph(self.func) graph.set_color(color) graph.set_opacity(opacity) graph.set_shading(*shading) return graph def get_dynamic_cylinder(self, axes, r_init=1): cylinder = self.get_cylinder(axes, r_init) r_tracker = ValueTracker(r_init) cylinder.add_updater(lambda m: self.set_cylinder_r( m, axes, r_tracker.get_value() )) return cylinder, r_tracker def get_cylinder( self, axes, r, color=BLUE_E, opacity=1 ): cylinder = Cylinder(color=color, opacity=opacity) self.set_cylinder_r(cylinder, axes, r) return cylinder def set_cylinder_r(self, cylinder, axes, r): r = max(r, 1e-5) cylinder.set_width(2 * r * axes.x_axis.get_unit_size()) cylinder.set_depth( self.func(r, 0) * axes.z_axis.get_unit_size(), stretch=True ) cylinder.move_to(axes.c2p(0, 0, 0), IN) return cylinder def get_thick_cylinder(self, cylinder, delta_r): radius = 0.5 * cylinder.get_width() outer_cylinder = cylinder.copy() factor = (radius + delta_r) / radius outer_cylinder.stretch(factor, 0) outer_cylinder.stretch(factor, 1) annulus = ParametricSurface( lambda u, v: (radius + u * delta_r) * np.array([math.cos(v), math.sin(v), 0]), u_range=(0, 1), v_range=(0, TAU), ) annulus.match_color(cylinder) annulus.move_to(cylinder, OUT) result = Group(cylinder.copy(), annulus, outer_cylinder) result.clear_updaters() return result def get_x_slice(self, axes, y, x_range=(-3, 3.1, 0.1)): xs = np.arange(*x_range) ys = np.ones(len(xs)) * y points = axes.c2p(xs, ys, self.func(xs, y)) graph = VMobject().set_points_smoothly(points) graph.use_winding_fill(False) return graph def get_dynamic_slice( self, axes, stroke_color=BLUE, stroke_width=2, fill_color=BLUE_E, fill_opacity=0.5, ): y_tracker = ValueTracker(0) get_y = y_tracker.get_value z_unit = axes.z_axis.get_unit_size() x_slice = self.get_x_slice(axes, 0) x_slice.set_stroke(stroke_color, stroke_width) x_slice.set_fill(fill_color, fill_opacity) x_slice.add_updater( lambda m: m.set_depth(self.func(0, get_y()) * z_unit, stretch=True) ) x_slice.add_updater(lambda m: m.move_to(axes.c2p(0, get_y(), 0), IN)) return x_slice, y_tracker class CylinderSlices(GaussianIntegral): def construct(self): # Setup frame = self.frame axes = self.get_axes() graph = self.get_gaussian_graph(axes) graph.set_opacity(0.8) graph.always_sort_to_camera(self.camera) graph_mesh = SurfaceMesh(graph, resolution=(21, 21)) graph_mesh.set_stroke(WHITE, 0.5, opacity=0.25) graph_mesh.set_flat_stroke(False) self.add(axes) # Animate in by rotating e^{-x^2} bell_halves = Group(*( axes.get_parametric_surface( lambda r, theta: np.array( [r * np.cos(theta), r * np.sin(theta), np.exp(-r**2) ]), u_range=(0, 3), v_range=v_range, ) for v_range in [(0, PI), (PI, TAU)] )) for half in bell_halves: half.match_style(graph) half.set_opacity(0.5) bell2d = self.get_x_slice(axes, 0) bell2d.set_stroke(TEAL, 3) kw = dict(t2c={"x": BLUE, "y": YELLOW}) label2d, label3d = func_labels = VGroup( Tex("f_1(x) = e^{-x^2}", **kw), Tex("f_2(x, y) = e^{-(x^2 + y^2)}", **kw), ) for label in func_labels: label.fix_in_frame() label.move_to(4 * LEFT + 2 * UP) axes.save_state() frame.reorient(0, 90) frame.move_to(OUT + 2 * UP) axes.y_axis.set_opacity(0) axes.labels.set_opacity(0) self.play( ShowCreation(bell2d), Write(label2d) ) self.wait() self.play( ShowCreation(bell_halves[0]), ShowCreation(bell_halves[1]), Rotate(bell2d, PI, axis=OUT, about_point=axes.c2p(0, 0, 0)), frame.animate.move_to(ORIGIN).reorient(-20, 70), Restore(axes), TransformMatchingTex(label2d.copy(), label3d, time_span=(0, 2)), label2d.animate.next_to(label3d, UP, MED_LARGE_BUFF, LEFT), run_time=6 ) self.wait() self.play( FadeOut(bell_halves, 0.01 * IN), FadeOut(bell2d, 0.1 * IN), FadeIn(graph, 0.01 * IN), ) self.play(Write(graph_mesh, stroke_width=1, lag_ratio=0.01)) self.wait() # Rotate the frame self.play( frame.animate.set_theta(20 * DEGREES), rate_func=there_and_back, run_time=30, ) # Reposition to 2d view frame.save_state() graph_mesh.save_state() func_labels.use_winding_fill(False) self.play( frame.animate.reorient(0, 0).set_height(10).move_to(1.5 * LEFT).set_field_of_view(1 * DEGREES), graph.animate.set_opacity(0.25), func_labels.animate.scale(0.75).to_corner(UL), graph_mesh.animate.set_stroke(width=1), run_time=3, ) # Explain meaning of r x, y = (1.5, 0.75) dot = Dot(axes.c2p(x, y), fill_color=RED) dot.set_stroke(WHITE, 0.5) coords = Tex("(x, y)", font_size=36) coords.next_to(dot, UR, SMALL_BUFF) x_line = Line(axes.get_origin(), axes.c2p(x, 0, 0)) y_line = Line(axes.c2p(x, 0, 0), axes.c2p(x, y, 0)) r_line = Line(axes.c2p(x, y, 0), axes.get_origin()) x_line.set_stroke(BLUE, 3) y_line.set_stroke(YELLOW, 3) r_line.set_stroke(RED, 3) lines = VGroup(x_line, y_line, r_line) labels = VGroup(*map(Tex, "xyr")) for label, line in zip(labels, lines): label.match_color(line) label.scale(0.85) label.next_to(line.get_center(), rotate_vector(line.get_vector(), -90 * DEGREES), SMALL_BUFF) self.add(dot, coords, set_depth_test=False) self.play( FadeIn(dot, scale=0.5), FadeIn(coords), ) for line, label in zip(lines, labels): self.add(line, label, dot, set_depth_test=False) self.play( ShowCreation(line), Write(label), ) # Plug in r r_label_rect = SurroundingRectangle(labels[2], buff=SMALL_BUFF) r_label_rect.set_stroke(RED, 2) arrow = Arrow(r_label_rect, axes.c2p(-3, 3, 0) + 3.2 * LEFT + 0.25 * UP, path_arc=45 * DEGREES) arrow.set_stroke(RED) self.always_depth_test = False self.play(ShowCreation(r_label_rect)) self.play(ShowCreation(arrow)) self.wait() # Show Pythagorean equations r_func = Tex("= e^{-r^2}", t2c={"r": RED}) r_func.match_height(label2d["= e^{-x^2}"]) r_func.next_to(label3d, RIGHT, MED_SMALL_BUFF, UP) r_func.fix_in_frame() r_rect = SurroundingRectangle(r_func["r^2"], buff=0.025) xy_rect = SurroundingRectangle(label3d["x^2 + y^2"], buff=0.025) VGroup(r_rect, xy_rect).set_stroke(TEAL, 1) VGroup(r_rect, xy_rect).fix_in_frame() pythag = Tex("x^2 + y^2 = r^2", t2c={"x": BLUE, "y": YELLOW, "r": RED}) pythag.next_to(label3d, DOWN, buff=2.0, aligned_edge=LEFT) pythag.fix_in_frame() self.play( FadeTransform(label2d["= e^{-x^2}"].copy(), r_func), FadeOut(arrow, scale=0.8, shift=DR + RIGHT), FadeOut(r_label_rect) ) self.wait() line_copies = lines.copy() self.add(*line_copies, set_depth_test=False) self.play( *( VShowPassingFlash(line.insert_n_curves(20).set_stroke(width=8), time_width=1.5) for line in line_copies ), *map(ShowCreation, lines) ) self.play( FadeTransform(r_func["r^2"][0].copy(), pythag["r^2"]), FadeTransform(label3d["x^2 + y^2"][0].copy(), pythag["x^2 + y^2"]), Write(pythag["="]), ) self.wait() self.wait() self.play(ShowCreation(xy_rect)) self.wait() self.play(Transform(xy_rect, r_rect)) self.play(FadeOut(xy_rect)) functions = VGroup(label2d, label3d, r_func) functions.fix_in_frame() # Emphasize rotational symmetry self.always_depth_test = True x_label, y_label, r_label = labels self.play( *map(FadeOut, [x_line, y_line, x_label, y_label, pythag]) ) def get_circle(point, z_shift=0.02): origin = axes.c2p(0, 0, 0) point[2] = origin[2] radius = get_norm(point - origin) circle = Circle(radius=radius, n_components=96) x = axes.x_axis.p2n(point) y = axes.y_axis.p2n(point) circle.move_to(axes.c2p(0, 0, self.func(x, y) + z_shift)) circle.set_stroke(RED, 2) circle.rotate(np.arctan2(y, x)) circle.set_flat_stroke(False) return circle r_label.add_updater(lambda m: m.next_to(r_line.get_center(), UL, SMALL_BUFF)) dot.add_updater(lambda m: m.move_to(r_line.get_start())) coords.add_updater(lambda m: m.next_to(dot, UR, SMALL_BUFF)) circle = get_circle(r_line.get_start()) self.play( Rotate(r_line, TAU, about_point=axes.get_origin()), ShowCreation(circle), frame.animate.reorient(30, 60).move_to(ORIGIN).set_height(8).set_field_of_view(45 * DEGREES), Restore(graph_mesh), run_time=7, ) self.wait() self.play( r_line.animate.scale(0.1, about_point=axes.get_origin()), UpdateFromFunc(circle, lambda c: c.replace(get_circle(r_line.get_start()))), rate_func=there_and_back, run_time=8, ) self.wait() self.play(*map(FadeOut, [r_line, dot, r_label, coords, circle])) # Dynamic cylinder cylinder, r_tracker = self.get_dynamic_cylinder(axes) delta_r = 0.1 cylinders = Group(*( self.get_cylinder(axes, r, opacity=0.5) for r in np.arange(0, 3, delta_r) )) r_tracker.set_value(0) self.add(cylinder, cylinders, graph, graph_mesh) self.play( graph.animate.set_opacity(0.1).set_anim_args(time_span=(0, 2)), FadeIn(cylinders, lag_ratio=0.9), r_tracker.animate.set_value(3).set_anim_args( rate_func=linear, time_span=(0.5, 10), ), frame.animate.reorient(-15, 75).set_height(5.5), run_time=10, ) self.wait() # Isolate one particular cylinder self.play( r_tracker.animate.set_value(0.7), cylinders.animate.set_opacity(0.1), frame.animate.reorient(-27, 71), run_time=3, ) # Unwrap cylinder axes.labels[2].set_opacity(0) R = cylinder.get_width() / 2 rect = Square3D(resolution=cylinder.resolution) rect.set_width(TAU * R) rect.set_height(cylinder.get_depth(), stretch=True) rect.match_color(cylinder) rect_top = Line(rect.get_corner(UL), rect.get_corner(UR)) rect_top.set_stroke(RED, 3) rect_side = Line(rect.get_corner(DL), rect.get_corner(UL)) rect_side.set_stroke(PINK, 3) VGroup(rect_top, rect_side).set_flat_stroke(False) rect_group = Group(rect, rect_top, rect_side) rect_group.apply_matrix(frame.get_orientation().as_matrix()) rect_group.next_to(cylinder, [1, 0, 1], LARGE_BUFF) eq_kw = dict( font_size=35, t2c={"{r}": RED}, ) area_eq1 = TexText("Area = (Circumference)(Height)", **eq_kw) area_eq2 = TexText(R"Area = $2 \pi {r} \cdot e^{-{r}^2}$", **eq_kw) for eq in area_eq1, area_eq2: eq.fix_in_frame() eq.to_corner(UL) area_eq1.shift(area_eq2[0].get_center() - area_eq1[0].get_center()) self.add(functions) functions.fix_in_frame() functions.deactivate_depth_test() functions.use_winding_fill(False) self.play( FadeIn(area_eq1, DOWN), functions.animate.shift(1.5 * DOWN).scale(0.7, about_edge=DL).set_fill(opacity=0.75) ) self.wait() pre_rect = cylinder.copy() pre_rect.clear_updaters() self.add(pre_rect, graph) self.play( pre_rect.animate.scale(0.95).next_to(cylinder, OUT, buff=1.0), frame.animate.set_height(7).move_to([1.0, 0.15, 1.0]), run_time=2, ) self.play(ReplacementTransform(pre_rect, rect), run_time=2) self.wait() # Show cylinder area circle = get_circle(cylinder.get_points()[0], z_shift=0) height_line = Line(cylinder.get_corner(IN + DOWN), cylinder.get_corner(OUT + DOWN)) height_line.set_stroke(PINK, 3) height_line.set_flat_stroke(False) circ_brace = Brace(area_eq2[R"2 \pi {r}"], DOWN, SMALL_BUFF) height_brace = Brace(area_eq2[R"e^{-{r}^2}"], DOWN, SMALL_BUFF) VGroup(circ_brace, height_brace).fix_in_frame() circ_word = area_eq1["(Circumference)"] height_word = area_eq1["(Height)"] self.add(circle, set_depth_test=False) self.play( ShowCreation(circle), ShowCreation(rect_top), ) self.play( FadeIn(circ_brace), circ_word.animate.scale(0.75).next_to(circ_brace, DOWN, SMALL_BUFF), Write(area_eq2[R"2 \pi {r}"]), height_word.animate.next_to(area_eq2[R"2 \pi {r}"], RIGHT) ) self.wait() self.add(height_line, set_depth_test=False) self.play( FadeOut(circle), FadeOut(rect_top), ShowCreation(rect_side), ShowCreation(height_line), ) self.play( FadeIn(height_brace), height_word.animate.scale(0.75).next_to(height_brace, DOWN, SMALL_BUFF, aligned_edge=LEFT), circ_word.animate.align_to(circ_brace, RIGHT), FadeInFromPoint(area_eq2[R"\cdot e^{-{r}^2}"], r_func[1:].get_center()), ) self.remove(area_eq1) self.add(area_eq2, circ_word, height_word) self.wait() self.play( frame.animate.center().reorient(-15, 66).set_height(4).set_anim_args(run_time=15), *map(FadeOut, [rect, rect_side, height_line]), ) # Show thickness volume_word = Text("Volume", **eq_kw) volume_word.fix_in_frame() volume_word.move_to(area_eq2, DL) area_part = area_eq2[R"= $2 \pi {r} \cdot e^{-{r}^2}$"] annotations = VGroup(circ_brace, height_brace, circ_word, height_word) dr_tex = Tex("d{r}", **eq_kw) dr_tex.fix_in_frame() thick_cylinder = self.get_thick_cylinder(cylinder, delta_r * axes.x_axis.get_unit_size()) thin_cylinder = self.get_thick_cylinder(cylinder, 0.1 * delta_r * axes.x_axis.get_unit_size()) _, annulus, outer_cylinder = thick_cylinder dr_brace = Brace( Line(axes.get_origin(), axes.c2p(delta_r, 0, 0)), UP ) dr_brace.stretch(0.5, 1) brace_label = dr_brace.get_tex("d{r}", buff=SMALL_BUFF) brace_label["r"].set_color(RED) brace_label.scale(0.35, about_edge=DOWN) dr_brace.add(brace_label) dr_brace.rotate(90 * DEGREES, RIGHT) dr_brace.move_to(thick_cylinder.get_corner(OUT + LEFT), IN + LEFT) self.remove(cylinder) self.add(thin_cylinder, cylinders, graph, graph_mesh) self.play(Transform(thin_cylinder, thick_cylinder)) self.add(dr_brace, set_depth_test=False) self.play(Write(dr_brace)) self.wait() self.play( LaggedStartMap(FadeOut, annotations, shift=DOWN, run_time=1), FadeOut(area_eq2["Area"], DOWN), FadeIn(volume_word, DOWN), area_part.animate.next_to(volume_word, RIGHT, SMALL_BUFF, DOWN), ) dr_tex.next_to(area_part, RIGHT, SMALL_BUFF, DOWN) self.play(FadeIn(dr_tex)) self.wait() # Show all cylinders integrand = VGroup(*area_part[0][1:], *dr_tex) integrand.fix_in_frame() integral = Tex(R"\int_0^\infty", **eq_kw) integral.fix_in_frame() integral.move_to(volume_word, LEFT) thick_cylinders = Group(*( self.get_thick_cylinder(cyl, delta_r * axes.x_axis.get_unit_size()) for cyl in cylinders )) thick_cylinders.set_opacity(0.8) thick_cylinders.set_shading(0.25, 0.25, 0.25) small_dr = 0.02 thin_cylinders = Group(*( self.get_thick_cylinder(self.get_cylinder(axes, r), small_dr) for r in np.arange(0, 5, small_dr) )) thin_cylinders.set_opacity(0.5) self.play( FadeOut(volume_word, LEFT), FadeOut(area_part[0][0], LEFT), FadeIn(integral, LEFT), integrand.animate.next_to(integral, RIGHT, buff=0), ) self.add(thick_cylinders, cylinders, graph, graph_mesh) self.play(ShowIncreasingSubsets(thick_cylinders, run_time=8)) self.play(FadeOut(thick_cylinders, 0.1 * IN)) self.wait() self.add(dr_brace[:-1], dr_brace[-1], set_depth_test=False) self.play( Transform(thin_cylinder, thin_cylinders[int(np.round(r_tracker.get_value() / small_dr))]), dr_brace[:-1].animate.stretch(small_dr / delta_r, 0, about_edge=RIGHT), UpdateFromFunc(dr_brace[-1], lambda m: m.next_to(dr_brace[:-1], OUT, SMALL_BUFF)), run_time=3, ) self.add(thin_cylinders, cylinders, graph, graph_mesh) self.add(dr_brace) dr_brace.deactivate_depth_test() self.play( ShowIncreasingSubsets(thin_cylinders), frame.animate.reorient(20, 70).set_height(8).move_to(OUT), FadeOut(dr_brace, time_span=(0, 2)), FadeOut(thin_cylinder, 2 * IN, time_span=(0, 2)), FadeOut(functions, time_span=(0, 2)), FadeOut(integral, time_span=(0, 2)), FadeOut(integrand, time_span=(0, 2)), run_time=20, ) self.wait() # Ambient rotation t0 = self.time frame.add_updater(lambda m: m.reorient(20 * math.cos(0.1 * (self.time - t0)))) self.wait(30) class CylinderIntegral(InteractiveScene): def construct(self): # Set up equations kw = dict( font_size=48, t2c={ "{r}": RED, "{0}": RED, R"{\infty}": RED, } ) exprs = VGroup( Tex(R"\int_0^\infty 2\pi {r} \cdot e^{-{r}^2} \, d{r}", **kw), Tex(R"\pi \int_0^\infty 2 {r} \cdot e^{-{r}^2}\, d{r}", **kw), Tex(R"= \pi \left[ -e^{-{\infty}^2} - \left(-e^{-{0}^2} \right) \right]", **kw), Tex(R"= \pi", **kw), ) exprs[1:].arrange(RIGHT, buff=SMALL_BUFF) exprs[1:].to_corner(UL) exprs[0].move_to(exprs[1], LEFT) # Factor out self.add(exprs[0]) self.wait() self.play(TransformMatchingTex(*exprs[:2], run_time=1, path_arc=30 * DEGREES)) self.wait() # Show antiderivative integrand = exprs[1][R"2 {r} \cdot e^{-{r}^2}"] integrand_rect = SurroundingRectangle(integrand, buff=SMALL_BUFF) integrand_rect.set_stroke(YELLOW, 2) anti_derivative = Tex(R"-e^{-{r}^2}", **kw) anti_derivative.next_to(integrand_rect, DOWN, buff=1.5) arrow = Arrow(anti_derivative, integrand_rect) arrow.set_color(YELLOW) arrow_label = Tex(R"d \over d{r}", **kw) arrow_label.scale(0.75) arrow_label.next_to(arrow, RIGHT, MED_SMALL_BUFF) self.play( ShowCreation(integrand_rect), GrowArrow(arrow), FadeIn(arrow_label, UP), ) self.wait() self.play(TransformMatchingShapes(integrand.copy(), anti_derivative)) self.wait() # Evaluate self.play( Write(exprs[2]["="]), TransformFromCopy(exprs[1][R"\pi"], exprs[2][R"\pi"]), TransformFromCopy(exprs[1][R"\int"], exprs[2][R"["]), TransformFromCopy(exprs[1][R"\int"], exprs[2][R"]"]), ) self.wait() self.play(LaggedStart( FadeTransform(anti_derivative.copy(), exprs[2][R"-e^{-{\infty}^2}"]), FadeIn(VGroup(*exprs[2][R"- \left("], exprs[2][R"\right)"])), FadeTransform(anti_derivative.copy(), exprs[2][R"-e^{-{0}^2}"]), lag_ratio=0.7 )) self.play( TransformMatchingShapes( VGroup( *exprs[1][R"\pi \int_0^\infty"], *anti_derivative ).copy(), exprs[2] ) ) self.wait() self.play(TransformMatchingTex(exprs[2].copy(), exprs[3])) self.wait() # Simplify rects = VGroup( SurroundingRectangle(exprs[2][R"-e^{-{\infty}^2}"]), SurroundingRectangle(exprs[2][R"-e^{-{0}^2}"]), ) rects.set_stroke(TEAL, 1) values = VGroup(*map(Integer, [0, -1])) for value, rect in zip(values, rects): value.next_to(rect, DOWN) value.match_color(rect) zero, one = values self.play( TransformFromCopy(integrand_rect, rects[0]), integrand_rect.animate.set_stroke(YELLOW, 1, 0.5) ) self.play(FadeIn(zero, 0.5 * DOWN)) self.wait() self.play(TransformFromCopy(*rects)) self.play(FadeIn(one, 0.5 * DOWN)) self.wait() self.play(Write(exprs[3])) self.wait() # Highlight answer answer = exprs[3][R"\pi"] self.play( LaggedStartMap(FadeOut, VGroup( integrand_rect, arrow, arrow_label, anti_derivative, *rects, *values )), answer.animate.scale(2, about_edge=LEFT) ) self.play(FlashAround(answer, run_time=2, time_width=1.5, color=TEAL)) self.wait() class CartesianSlices(GaussianIntegral): def construct(self): # Setup frame = self.frame axes = self.get_axes() graph = self.get_gaussian_graph(axes) graph_mesh = SurfaceMesh(graph, resolution=(21, 21)) graph_mesh.set_stroke(WHITE, 0.5, opacity=0.25) graph_mesh.set_flat_stroke(False) self.add(axes, graph, graph_mesh) # Dynamic slice x_slice, y_tracker = self.get_dynamic_slice(axes) y_unit = axes.y_axis.get_unit_size() graph.add_updater(lambda m: m.set_clip_plane(UP, -y_tracker.get_value() * y_unit)) x_max = axes.x_range[1] y_tracker.set_value(x_max) self.add(x_slice) self.play( y_tracker.animate.set_value(-x_max), run_time=5, rate_func=linear, ) self.wait() # Show many slices def get_x_slices(dx=0.25): original_y_value = y_tracker.get_value() x_slices = VGroup() x_min, x_max = axes.x_range[:2] for y in np.arange(x_max, x_min, -dx): y_tracker.set_value(y) x_slice.update() x_slices.add(x_slice.copy().clear_updaters()) x_slices.use_winding_fill(False) x_slices.deactivate_depth_test() x_slices.set_stroke(BLUE, 2, 0.5) x_slices.set_flat_stroke(False) y_tracker.set_value(original_y_value) return x_slices x_slices = get_x_slices(dx=0.25) self.add(x_slice, x_slices, graph, graph_mesh) self.play( FadeOut(graph, time_span=(0, 1)), FadeOut(x_slice, time_span=(0, 1)), FadeIn(x_slices, 0.1 * OUT, lag_ratio=0.1), axes.labels[2].animate.set_opacity(0), frame.animate.reorient(-80), run_time=4 ) self.play( frame.animate.reorient(-100), run_time=3, ) self.wait() y_tracker.set_value(-x_max) self.add(x_slice, x_slices, graph, graph_mesh) self.play( FadeOut(x_slices, 0.1 * IN, time_span=(0, 2.5)), FadeIn(graph, time_span=(0, 2.5)), VFadeIn(x_slice), frame.animate.reorient(-15).set_height(6), y_tracker.animate.set_value(0), run_time=5, ) # Discuss area of each slice tex_kw = dict( font_size=42, t2c={"x": BLUE, "y": YELLOW} ) get_y = y_tracker.get_value x_slice_label = Tex("0.00 e^{-x^2}", **tex_kw) coef = x_slice_label.make_number_changable("0.00") coef.set_color(YELLOW) coef.add_updater(lambda m: m.set_value(math.exp(-get_y()**2)).rotate(90 * DEGREES, RIGHT)) x_term = x_slice_label[1:] brace = Brace(coef, UP, MED_SMALL_BUFF) y_term = Tex("e^{-y^2}", **tex_kw) y_term.next_to(brace, UP, SMALL_BUFF) y0_label = Tex("y = 0", **tex_kw) y0_label.rotate(90 * DEGREES, RIGHT) y0_label.next_to(x_slice.pfp(0.35), OUT + LEFT) x_slice_label.add(brace, y_term) x_slice_label.rotate(90 * DEGREES, RIGHT) x_slice_label.add_updater(lambda m: m.next_to(x_slice.pfp(0.6), OUT + RIGHT)) x_slice_label.save_state() y_term.next_to(x_term, LEFT, SMALL_BUFF, aligned_edge=DOWN) brace.scale(0, about_edge=IN) coef.scale(0, about_edge=IN) swap = Swap(x_term, y_term) swap.begin() swap.update(1) func_label = Tex(R"e^{-(x^2 + y^2)}", **tex_kw) func_label.rotate(90 * DEGREES, RIGHT) func_label.next_to(x_slice_label, OUT, MED_LARGE_BUFF) fx0 = Tex(R"e^{-(x^2 + 0^2)} = e^{-x^2}", **tex_kw) fx0.rotate(90 * DEGREES, RIGHT) fx0.next_to(func_label, IN, MED_LARGE_BUFF, aligned_edge=LEFT) fx0["0"].set_color(YELLOW) self.always_depth_test = False self.play( *( VShowPassingFlash(mob, time_width=1.5, run_time=3) for mob in [ x_slice.copy().set_stroke(YELLOW, 8).set_fill(opacity=0).shift(0.02 * OUT), Line(*axes.x_axis.get_start_and_end()).set_stroke(YELLOW, 8).insert_n_curves(40), ] ), Write(y0_label) ) self.wait() self.play(FadeIn(func_label)) self.wait() self.play(TransformMatchingTex(func_label.copy(), fx0, lag_ratio=0.025)) self.wait() self.play(FadeOut(fx0, RIGHT, rate_func=running_start)) self.play(TransformMatchingShapes(func_label.copy(), x_slice_label)) self.wait() self.play(Swap(x_term, y_term, path_arc=0.5 * PI)) self.play( Restore(x_slice_label), FadeOut(func_label, OUT), ) self.wait() # Note the area def get_area_label(): area_label = TexText(R"Area = $0.00 \cdot C$", font_size=30) area_label["C"].set_color(RED) num = area_label.make_number_changable("0.00") num.set_value(coef.get_value()) area_label.rotate(90 * DEGREES, RIGHT) area_label.move_to(interpolate(x_slice.get_zenith(), x_slice.get_nadir(), 0.66)) area_label.shift(0.1 * DOWN) return area_label self.play(FadeIn(get_area_label(), run_time=3, rate_func=there_and_back_with_pause)) # Move the slice y0_slice_copy = x_slice.copy() y0_slice_copy.clear_updaters() y0_slice_copy.set_fill(opacity=0) self.play(FadeOut(y0_label)) for value in [-0.5, -0.75, -1]: self.play(y_tracker.animate.set_value(value), run_time=3) slice_copy = y0_slice_copy.copy().set_opacity(0) area_label = get_area_label() self.play(FadeIn(area_label)) self.play(slice_copy.animate.match_y(x_slice).set_stroke(YELLOW, 3, 1)) self.wait(0.25) self.play(slice_copy.animate.match_depth(x_slice, stretch=True, about_edge=IN).set_opacity(0)) self.wait() self.play(FadeOut(area_label)) # Go back to finer slices x_slices = get_x_slices(dx=0.1) y_tracker.set_value(-1) self.add(x_slices, graph, graph_mesh) self.play( FadeIn(x_slices, 0.1 * OUT, lag_ratio=0.1, run_time=4), FadeOut(graph), FadeOut(x_slice, time_span=(3, 4)), FadeOut(x_slice_label, time_span=(3, 4)), frame.animate.reorient(-83, 72, 0).set_height(8).center().set_anim_args(run_time=5) ) # Ambient rotation t0 = self.time theta0 = frame.get_theta() frame.clear_updaters() frame.add_updater(lambda m: m.set_theta( theta0 + -0.2 * math.sin(0.1 * (self.time - t0)) )) self.wait(10) # Show slice width mid_index = len(x_slices) // 2 - 3 line = Line(x_slices[mid_index].get_zenith(), x_slices[mid_index + 1].get_zenith()) brace = Brace(Line().set_width(line.get_length()), UP) brace.stretch(0.5, 1) brace.add(brace.get_tex("dy", buff=SMALL_BUFF).scale(0.75, about_edge=DOWN)) brace.rotate(90 * DEGREES, RIGHT) brace.rotate(90 * DEGREES, IN) brace.next_to(line, OUT, buff=0) brace.use_winding_fill(False) self.play(FadeIn(brace)) self.wait(60) class CartesianSliceOverlay(InteractiveScene): def construct(self): # Show integral kw = dict( t2c={"{x}": BLUE, "{y}": YELLOW, "C": RED}, font_size=48, ) integral1 = Tex(R"\int_{-\infty}^\infty C \cdot e^{-{y}^2} d{y}", **kw) integral2 = Tex(R"= C \int_{-\infty}^\infty e^{-{y}^2}d{y}", **kw) rhs = Tex(R"= C^2", **kw) top_eq = VGroup(integral1, integral2, rhs) top_eq.arrange(RIGHT, buff=MED_SMALL_BUFF) top_eq.to_corner(UL) for part in top_eq: part.shift((integral1[0].get_y() - part[0].get_y()) * UP) self.play(FadeIn(integral1)) self.wait() # Spell out meanings of each part area_part = integral1[R"C \cdot e^{-{y}^2}"] volume_part = integral1[R"C \cdot e^{-{y}^2} d{y}"] area_rect = SurroundingRectangle(area_part, buff=0.05) volume_rect = SurroundingRectangle(volume_part, buff=0.05) rects = VGroup(area_rect, volume_rect) rects.set_stroke(TEAL, 1) rects.set_fill(TEAL, 0.25) area_word = Text("Area of a slice") volume_word = Text("Volume of a slice") words = VGroup(area_word, volume_word) arrows = VGroup() for word, rect in zip(words, rects): word.next_to(rect, DOWN, LARGE_BUFF, LEFT) arrows.add(Arrow(rect, word)) self.add(area_rect, integral1) self.play( FadeIn(area_rect), GrowArrow(arrows[0]), FadeIn(area_word) ) self.wait() self.play( Transform(*rects), Transform(*arrows), TransformMatchingStrings(area_word, volume_word, run_time=1), ) self.wait() self.play(*map(FadeOut, [area_rect, arrows[0], volume_word])) self.wait() # Show meaning of C sub_int = Tex(R"C = \int_{-\infty}^\infty e^{-{x}^2} d{x}", **kw) sub_int.next_to(top_eq, DOWN, LARGE_BUFF, aligned_edge=LEFT) box = SurroundingRectangle(sub_int) box.set_stroke(RED, 2) arrow = Arrow(integral1["C"], box, stroke_color=RED) for mob in box, sub_int: mob.save_state() mob.replace(integral1["C"], stretch=True) mob.set_opacity(0) self.play( ShowCreation(arrow), Restore(box), Restore(sub_int), ) self.wait() self.play(TransformMatchingTex(integral1.copy(), integral2, path_arc=30 * DEGREES)) self.wait() # Expand box2 = SurroundingRectangle(integral2[2:], buff=SMALL_BUFF) box2.set_stroke(RED, 1) self.play(TransformFromCopy(box, box2)) self.wait() self.play( FadeOut(box2), Write(rhs) ) self.wait() # Emphasize C^2 C2 = rhs["C^2"] everything = VGroup(integral1, integral2, sub_int) self.play(C2.animate.scale(2, about_point=C2.get_left() + 0.1 * LEFT)) self.play( FlashAround(C2, time_width=1.5, run_time=3), everything.animate.set_opacity(0.7), ) self.wait()
from manim_imports_ext import * from _2023.clt.main import * class TwoDGaussianAsADistribution(InteractiveScene): n_points = 2000 n_dots_per_moment = 10 def construct(self): # Setup frame = self.frame plane = self.get_plane() plane.set_flat_stroke(False) self.add(plane) dartboard = self.get_dartboard(plane) dartboard.save_state() dartboard.set_opacity(0) self.add(dartboard) self.add_random_points_anim(plane) self.wait(10) self.play(Restore(dartboard)) self.wait(10) # Graph def func(u, v, sigma=1): return np.exp(-(u**2 + v**2) / sigma**2) / sigma graphs = [] for sigma in [0.8, 1.0, 0.6]: graph = ParametricSurface(lambda u, v: [u, v, func(u, v, sigma)], u_range=(-2, 2), v_range=(-2, 2)) graph.match_width(plane.axes) graph.set_color(BLUE_E, 0.5) graph.move_to(plane.axes, IN) graph.always_sort_to_camera(self.camera) mesh = VGroup(*plane.background_lines.copy(), plane.faded_lines.copy()) mesh.insert_n_curves(50) mesh.start = mesh.copy().set_opacity(0) mesh.save_state() mesh.saved_state.set_opacity(0) unit_size = plane.x_axis.get_unit_size() for submob in mesh.family_members_with_points(): submob.set_points([ p + unit_size * func(*plane.p2c(p), sigma) * OUT for p in submob.get_points() ]) submob.set_stroke( WHITE, width=0.5 * submob.get_stroke_width(), opacity=0.5 * submob.get_stroke_opacity() ) mesh.shift(0.01 * OUT) graphs.append(Group(graph, mesh)) graph1, graph2, graph3 = graphs # Test self.add(graph1) graph1[0].set_opacity(0) self.play( frame.animate.reorient(20, 70), graph1[0].animate.set_opacity(0.5), TransformFromCopy(graph1[1].start, graph1[1]), run_time=3 ) self.play( frame.animate.reorient(-20), run_time=7, ) graph1.save_state() self.play(Transform(graph1, graph2), run_time=2) self.play(Transform(graph1, graph3), run_time=2) self.play(Restore(graph1), run_time=2) self.wait(2) self.play( FadeOut(graph1[0]), Restore(graph1[1]), frame.animate.reorient(0, 0), run_time=3, ) # Radial symmetry blob = Circle(radius=0.2) blob.set_stroke(TEAL, 2) blob.set_fill(TEAL, 0.5) blob.move_to(plane.c2p(0.5, 0.5)) arrow = FillArrow(ORIGIN, DL) arrow.next_to(blob, UR, buff=0) arrow.set_fill(RED, 1) arrow.set_backstroke(width=2) radial_line = DashedLine(plane.c2p(0, 0), blob.get_center(), dash_length=0.025) radial_line.set_stroke(TEAL, 2) self.play( dartboard.animate.set_opacity(0.2), DrawBorderThenFill(blob), GrowArrow(arrow) ) self.wait() self.play(ShowCreation(radial_line)) self.play( Rotate(blob, TAU, about_point=plane.get_origin(), run_time=6), Rotate(radial_line, TAU, about_point=plane.get_origin(), run_time=6), MaintainPositionRelativeTo(arrow, blob), ) self.wait() self.play( LaggedStartMap(FadeOut, VGroup(blob, arrow, radial_line)), dartboard.animate.set_opacity(0.75) ) self.play( self.frame.animate.set_gamma(-0.75 * PI), rate_func=there_and_back, run_time=6, ) self.wait() # Ambient randomness self.wait(0.1 * self.n_points) def get_plane(self): plane = NumberPlane( (-2, 2), (-2, 2), background_line_style=dict(stroke_color=GREY, stroke_width=1, stroke_opacity=1) ) plane.set_height(7) plane.to_edge(DOWN, buff=0.25) plane.add(Tex("x").next_to(plane.x_axis.get_right(), RIGHT, SMALL_BUFF)) plane.add(Tex("y").next_to(plane.y_axis.get_top(), UP, SMALL_BUFF)) return plane def get_dartboard(self, plane): dartboard = Dartboard() dartboard.match_height(plane.axes) dartboard.move_to(plane.axes) dartboard.set_opacity(0.75) return dartboard def add_random_points_anim(self, plane): coords = np.random.normal(0, 0.5, (self.n_points, 2)) dots = Group(*( GlowDot(plane.c2p(x, y), glow_factor=4.0, radius=0.3) for x, y in coords )) anim = LaggedStart(*( FadeIn(dot, rate_func=there_and_back) for dot in dots ), lag_ratio=1 / self.n_dots_per_moment, run_time=self.n_points / self.n_dots_per_moment) anim_mob = turn_animation_into_updater(anim) self.add(anim_mob) class FaintDartboard(TwoDGaussianAsADistribution): n_points = 1000 n_dots_per_moment = 5 def construct(self): frame = self.frame plane = self.get_plane() plane.set_flat_stroke(False) self.add(plane) dartboard = self.get_dartboard(plane) dartboard.set_opacity(0.15) self.add(dartboard) self.add_random_points_anim(plane) self.wait(0.1 * self.n_points) class ShowXYCoordinate(TwoDGaussianAsADistribution): def construct(self): plane = self.get_plane() # self.add(plane) # Remove # Test x, y = (-1.5, 0.5) dot = Dot(plane.c2p(x, y)) dot.set_color(TEAL) r_line = Line(plane.get_origin(), dot.get_center()) r_line.set_stroke(RED, 3) x_line = Line(plane.get_origin(), plane.c2p(x, 0)) x_line.set_stroke(BLUE, 5) y_line = Line(plane.c2p(x, 0), plane.c2p(x, y)) y_line.set_stroke(YELLOW, 5) x_label = Tex("x", color=BLUE).next_to(x_line, DOWN, SMALL_BUFF) y_label = Tex("y", color=YELLOW).next_to(y_line, LEFT, SMALL_BUFF) r_label = Tex("r", color=RED).next_to(r_line.get_center(), UR, SMALL_BUFF) self.play( FadeIn(dot), ShowCreation(x_line), FadeIn(x_label, 0.5 * LEFT), ) self.add(y_line, dot) self.play( ShowCreation(y_line), FadeIn(y_label, 0.5 * UP), ) self.wait() self.add(r_line, dot) self.play( ShowCreation(r_line), FadeIn(r_label, shift=0.5 * normalize(r_line.get_vector())) ) self.wait() class IndependentCoordinates(TwoDGaussianAsADistribution): n_iterations = 20 random_seed = 1 def construct(self): frame = self.frame plane = self.get_plane() dartboard = self.get_dartboard(plane) dartboard.set_opacity(0.15) self.add(plane, dartboard) x_tip = ArrowTip(angle=90 * DEGREES).scale(0.5).set_color(BLUE) y_tip = ArrowTip(angle=0).scale(0.5).set_color(YELLOW) x_tip.move_to(plane.get_origin(), UP) y_tip.move_to(plane.get_origin(), RIGHT) for tip in x_tip, y_tip: tip.set_opacity(0) tip.save_state() for n in range(self.n_iterations): # Test x_tip.restore() y_tip.restore() # xs = np.random.normal(0, 1, 10) # ys = np.random.normal(0, 1, 10) # x = xs[-2] # y = ys[-2] x = np.random.normal(0, 0.5) y = np.random.normal(0, 0.5) if y < 0: x_tip.flip(RIGHT, about_point=plane.get_origin()) if x < 0: y_tip.flip(UP, about_point=plane.get_origin()) lines = VGroup( DashedLine(plane.c2p(x, 0), plane.c2p(x, y), dash_length=0.05), DashedLine(plane.c2p(0, y), plane.c2p(x, y), dash_length=0.05), ) lines.set_stroke(WHITE, 2) dot = GlowDot().move_to(plane.c2p(x, y)) self.play(LaggedStart( x_tip.animate.match_x(dot).set_opacity(1), y_tip.animate.match_y(dot).set_opacity(1), lag_ratio=0.5, )) self.play( *map(ShowCreation, lines), FadeIn(dot), run_time=0.5 ) self.wait(0.5) # self.play(UpdateFromAlphaFunc(x_tip, lambda m, a: m.match_x( # plane.c2p(xs[integer_interpolate(0, len(xs) - 1, a)[0]], 0) # ))) # self.play(UpdateFromAlphaFunc(y_tip, lambda m, a: m.match_y( # plane.c2p(0, ys[integer_interpolate(0, len(ys) - 1, a)[0]]) # ))) # self.add(lines, dot) # self.wait() self.play(LaggedStartMap(FadeOut, Group( x_tip, y_tip, lines, dot )), run_time=1) class ShowPointR0(TwoDGaussianAsADistribution): def construct(self): plane = self.get_plane() plane.axes.set_stroke(width=1) dartboard = self.get_dartboard(plane) dartboard.set_opacity(0.15) self.add(plane, dartboard) # Show point x, y = (0.7, 0.5) r = get_norm([x, y]) dot = Dot(plane.c2p(x, y), radius=0.05) r_line = Line(plane.get_origin(), dot.get_center()) r_line.set_stroke(RED, 3) coord_label = Tex("(x, y)", t2c={"x": BLUE, "y": YELLOW}) coord_label.next_to(dot, UR, buff=SMALL_BUFF) coord_label.set_backstroke() new_coord_label = Tex("(r, 0)", t2c={"r": RED, "0": YELLOW}) new_coord_label.next_to(plane.c2p(r, 0), UR, SMALL_BUFF) angle = math.atan2(y, x) self.add(r_line, dot, coord_label) self.wait() self.play( Rotate(r_line, -angle, about_point=plane.get_origin()), Rotate(dot, -angle, about_point=plane.get_origin()), ReplacementTransform(coord_label, new_coord_label, path_arc=-angle, time_span=(1, 2)), run_time=3 ) self.wait() class RescaleG(InteractiveScene): def construct(self): def g(x): return 0.5 * math.exp(-x**4 + x**2) # Setup axes = Axes((-2, 2), (0, 1, 0.25), width=6, height=3) axes.x_axis.add_numbers() axes.y_axis.add_numbers(num_decimal_places=2, excluding=[0], font_size=16) self.add(axes) curve = axes.get_graph(g) curve.make_smooth() curve.set_stroke(BLUE, 3) curve.save_state() curve.generate_target() curve.target.stretch(1 / g(0), 1, about_edge=DOWN) label1 = TexText(R"$g(0) \ne 1$", font_size=36) label2 = TexText(R"$g(0) = 1$", font_size=36) label3 = TexText(R"Later we \\ re-scale anyway", font_size=36) labels = [label1, label2, label3] curves = [curve, curve.target, curve] for label, crv in zip(labels, curves): label.next_to(crv.get_top(), UR) self.play( ShowCreation(curve), FadeIn(label1, lag_ratio=0.1), ) self.wait() self.play( MoveToTarget(curve), FadeTransform(label1, label2), ) self.wait(2) self.play( Restore(curve), FadeTransform(label2, label3), ) self.play(curve.animate.set_fill(BLUE, 0.5)) self.wait() class ManyDifferentFs(InteractiveScene): def construct(self): axes = Axes((0, 4), (0, 1, 0.25), width=6, height=3) axes.x_axis.add_numbers() axes.y_axis.add_numbers(num_decimal_places=2, excluding=[0], font_size=16) self.add(axes) # Many curves curves = VGroup( axes.get_graph(lambda x: math.exp(-x**2)), axes.get_graph(lambda x: 1 / (1 + x**2)), axes.get_graph(lambda x: math.exp(-x)), axes.get_graph(lambda x: 0.5 * math.exp(-x**4 + x**2)), axes.get_graph(lambda x: math.cos(x)**2 / (x + 1)), axes.get_graph(lambda x: (1 / 2) * (x**2) * np.exp(-x)), ) curves.set_stroke(RED, 3) func_names = VGroup( Tex("e^{-x^2}"), Tex(R"1 \over (1 + x^2)"), Tex("e^{-x}"), Tex(R"\frac{1}{2} e^{-x^4 + x^2}"), Tex(R"\cos^2(x) \over (x + 1)"), Tex(R"\frac{1}{2} x^2 e^{-x}"), ) func_names.move_to(axes.get_top()) curve = curves[0] name = func_names[0] self.play( ShowCreation(curve), FadeIn(name, 0.5 * UP) ) self.wait() for new_curve, new_name in zip(curves[1:], func_names[1:]): self.play( Transform(curve, new_curve), TransformMatchingTex(name, new_name, run_time=1) ) name = new_name self.wait() class VariableInputs(InteractiveScene): def construct(self): equation = Tex(R"f(\sqrt{(1.00)^2 + (0.00)^2}) = f(1.00)f(0.00)") xs = equation.make_number_changable("1.00", replace_all=True) ys = equation.make_number_changable("0.00", replace_all=True) xs.set_color(BLUE) ys.set_color(YELLOW) x_tracker = ValueTracker(1.0) y_tracker = ValueTracker(1.0) for mob in xs: mob.add_updater(lambda m: m.set_value(x_tracker.get_value())) for mob in ys: mob.add_updater(lambda m: m.set_value(y_tracker.get_value())) self.add(equation) for n in range(30): self.play(x_tracker.animate.set_value(random.random() * 10)) self.play(y_tracker.animate.set_value(random.random() * 10)) self.wait(0.5) class RationalNumbers(InteractiveScene): def construct(self): # Interval interval = UnitInterval((0, 1, 1)) interval.center() interval.add_numbers(font_size=36, num_decimal_places=0) self.add(interval) # Add rational points pairs = [] max_n = 100 for n in range(2, max_n): for k in range(1, n): if math.gcd(n, k) == 1: pairs.append((k, n)) lines = VGroup() line_groups = VGroup(*(VGroup() for n in range(max_n - 2))) labels = VGroup() frac_template = Tex(R"1 \over 2") frac_template.make_number_changable("1") frac_template.make_number_changable("2") for pair in pairs: k, n = pair line = Line(DOWN, UP) line.set_height(2.0 / n) line.set_stroke(TEAL, width=4.0 / math.sqrt(n)) line.move_to(interval.n2p(k / n)) lines.add(line) line_groups[n - 2].add(line) if n < 15: frac = frac_template.copy() frac[0].set_value(k) frac[2].set_value(n) frac[1].match_width(frac[2]) frac.set_height(1.5 / n) frac.next_to(line, UP, SMALL_BUFF) labels.add(frac) line_groups.set_submobject_colors_by_gradient(BLUE, TEAL) for i, j in [(0, 9), (9, 27), (27, len(labels))]: self.play( LaggedStartMap(FadeIn, lines[i:j], lag_ratio=0.75), LaggedStartMap(FadeIn, labels[i:j], lag_ratio=0.75), rate_func=linear, run_time=3, ) self.play( LaggedStartMap(FadeIn, lines[27:], lag_ratio=0.75), run_time=10, rate_func=rush_into, ) self.wait() # Transition to real real_line = Line(interval.n2p(0), interval.n2p(1)) real_line.insert_n_curves(50) real_line.set_stroke([TEAL, BLUE, TEAL], width=[0, 3, 3, 0]) self.play( LaggedStart(*(Rotate(line, -90 * DEGREES) for line in lines), lag_ratio=1 / len(lines), run_time=3), FadeOut(labels, lag_ratio=0.1, run_time=1), ShowCreation(real_line, time_span=(2, 3)), ) self.wait() class TwoProperties(InteractiveScene): def construct(self): # Name properties properties = VGroup( VGroup( Text("Property 1"), TexText(R""" The probability (density) depends \\ only on the distance from the origin """, alignment="", font_size=36, color=GREY_A), ), VGroup( Text("Property 2"), TexText(R""" The $x$ and $y$ coordinates are \\ independent from each other. """, alignment="", font_size=36, color=GREY_A), ), ) for prop in properties: prop.arrange(DOWN, aligned_edge=LEFT) properties.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) properties.to_corner(UL) prop_boxes = VGroup(*( SurroundingRectangle(prop[1]).set_fill(GREY_E, 1).set_stroke(RED, 1, 0.5) for prop in properties )) for prop, box in zip(properties, prop_boxes): self.play(FadeIn(prop[0], lag_ratio=0.1), FadeIn(box)) # Formula implies = Tex(R"\Downarrow", font_size=72) implies.next_to(properties, DOWN, MED_LARGE_BUFF) kw = dict( t2c={"x": BLUE, "y": YELLOW, R"\sigma": RED, "{r}": RED} ) form1, form2, form3 = forms = VGroup( Tex(R"f_2(x, y) = e^{-(x^2 + y^2)}", **kw), Tex(R"f_2(x, y) = e^{-(x^2 + y^2) / 2 \sigma^2}", **kw), Tex(R"f_2(x, y) = {1 \over 4 \sigma^2 \pi} e^{-(x^2 + y^2) / 2 \sigma^2}", **kw), ) forms.next_to(implies, DOWN, MED_SMALL_BUFF) form1.save_state() self.play( Write(implies), FadeIn(form1, DOWN) ) self.wait() self.play(TransformMatchingTex(form1, form2, run_time=1, lag_ratio=0.05)) self.wait(2) self.play(TransformMatchingTex(form2, form3, run_time=1, lag_ratio=0.05)) self.wait(2) form1.restore() self.play(TransformMatchingTex(form3, form1, run_time=2, lag_ratio=0.05)) self.wait(2) # Property 1 lhs = form1["f_2(x, y)"][0] self.add(properties[0][1], prop_boxes[0]) self.play( prop_boxes[0].animate.stretch(0, 0, about_edge=RIGHT).set_opacity(0), FadeOut(implies), FadeOut(form1["= e^{-(x^2 + y^2)}"]), ) self.remove(prop_boxes[0]) self.add(lhs) self.wait() phrase = properties[0][1]["only on the distance"] self.play( FlashUnder(phrase, color=TEAL, buff=0), phrase.animate.set_color(TEAL), ) self.wait(2) # Function of radius lhs.generate_target() lhs.target.to_edge(LEFT) radial_rhs = Tex(R"= f({r})", **kw) full_radial_rhs = Tex(R"= f(\sqrt{x^2 + y^2})", **kw) radial_rhs.next_to(lhs.target, RIGHT, SMALL_BUFF) full_radial_rhs.next_to(radial_rhs, RIGHT, MED_SMALL_BUFF) full_radial_rhs.shift((radial_rhs["="].get_y() - full_radial_rhs["="].get_y()) * UP) lhs_rect = SurroundingRectangle(lhs) f_rect = SurroundingRectangle(radial_rhs["f"], buff=0.05) f_rect.set_stroke(BLUE, 2) f_words = Text("Some single-variable function", font_size=36) f_words.next_to(f_rect, UP, SMALL_BUFF, aligned_edge=LEFT) f_words.match_color(f_rect) self.play(ShowCreation(lhs_rect)) self.wait() self.play(lhs_rect.animate.replace(lhs[1], stretch=True).set_stroke(width=1).scale(1.1)) self.play(FadeOut(lhs_rect)) self.wait() self.play( MoveToTarget(lhs), Write(radial_rhs), ) self.play( ShowCreation(f_rect), FadeIn(f_words, lag_ratio=0.1) ) self.wait(2) self.play(FadeOut(f_words), FadeOut(f_rect)) self.play(TransformMatchingTex(radial_rhs.copy(), full_radial_rhs)) self.wait(2) # Property 2 self.add(properties[1][1], prop_boxes[1]) self.play( prop_boxes[1].animate.stretch(0, 0, about_edge=RIGHT).set_opacity(0), ) self.remove(prop_boxes[0]) self.wait() phrase = properties[1][1]["independent"] self.play( FlashUnder(phrase, color=TEAL, buff=0), phrase.animate.set_color(TEAL) ) self.wait() # Factored expression lhs.generate_target() lhs.target.next_to(properties, DOWN, buff=0.7, aligned_edge=LEFT) radial_rhss = VGroup(radial_rhs, full_radial_rhs) factored_rhs = Tex(R"= g(x) h(y)", **kw) simpler_rhs = Tex(R"= g(x) g(y)", **kw) for rhs in factored_rhs, simpler_rhs: rhs.next_to(lhs.target, RIGHT) g_box = SurroundingRectangle(factored_rhs["g(x)"], buff=0.05).set_stroke(BLUE, 2) h_box = SurroundingRectangle(factored_rhs["h(y)"], buff=0.05).set_stroke(YELLOW, 2) g_words = TexText("Distribution of $x$", font_size=30).next_to(g_box, DOWN, 0.2) h_words = TexText("Distribution of $y$", font_size=30).next_to(h_box, DOWN, 0.2) self.play( MoveToTarget(lhs), radial_rhss.animate.to_edge(LEFT).shift(0.5 * DOWN).set_opacity(0.35), ) self.play( TransformMatchingShapes(lhs.copy(), factored_rhs) ) self.wait() self.play( ShowCreation(g_box), FadeIn(g_words) ) self.wait() self.play( ReplacementTransform(g_box, h_box), ReplacementTransform(g_words, h_words), ) self.wait() self.play(FadeOut(h_box), FadeOut(h_words)) self.wait() self.play( FadeOut(factored_rhs["h(y)"], 0.5 * UP), FadeIn(simpler_rhs["g(y)"], 0.5 * UP), ) self.wait() self.remove(factored_rhs) self.add(simpler_rhs) # Show proportionality arrow = Arrow(simpler_rhs, radial_rhs) self.play( GrowArrow(arrow), radial_rhs.animate.set_opacity(1), FadeOut(full_radial_rhs), ) self.wait() radial_rhs.generate_target() radial_rhs.target.next_to(lhs, RIGHT), self.play( MoveToTarget(radial_rhs), simpler_rhs.animate.next_to(radial_rhs.target, RIGHT), Uncreate(arrow), ) self.wait() xs = VGroup(lhs[3], simpler_rhs["x"][0][0]) ys = VGroup(lhs[5], simpler_rhs["y"][0][0]) rs = Tex("{r}", **kw).replicate(2) zeros = Tex("0", **kw).replicate(2) zeros.set_color(YELLOW) for x, r in zip(xs, rs): r.move_to(x, DOWN) for x, y, zero in zip(xs, ys, zeros): zero.move_to(y) zero.align_to(x, DOWN) const_rect = SurroundingRectangle(simpler_rhs["g(y)"], buff=0.05) const_rect.set_stroke(YELLOW, 1) const_words = Text("Some constant", font_size=36) const_words.match_color(const_rect) const_words.next_to(const_rect, DOWN) self.play( LaggedStartMap(FadeOut, VGroup(*xs, *ys), shift=0.5 * UP), LaggedStartMap(FadeIn, VGroup(*rs, *zeros), shift=0.5 * UP), ) self.wait() self.play( ShowCreation(const_rect), FadeIn(const_words) ) self.wait() # Assume this constant is 1 assumption = TexText("Assume this is 1", font_size=36) assumption.move_to(const_words) assumption.match_color(const_words) f_eq_g = Tex("f = g", **kw) f_eq_g.next_to(radial_rhs, DOWN, LARGE_BUFF) f_rhs = Tex(R"= f(x)f(y)", **kw) f_rhs.move_to(simpler_rhs, LEFT) gs = simpler_rhs["g"] fs = f_rhs["f"] self.play( FadeIn(assumption, 0.5 * DOWN), FadeOut(const_words, 0.5 * DOWN), ) self.wait() self.play( TransformFromCopy( VGroup(radial_rhs[1], *simpler_rhs[:2]), f_eq_g ) ) self.wait() self.play( LaggedStartMap(FadeIn, VGroup(*xs, *ys), shift=0.5 * DOWN), LaggedStartMap(FadeOut, VGroup(*rs, *zeros), shift=0.5 * DOWN), FadeOut(const_rect), FadeOut(assumption), ) self.wait() self.play( TransformMatchingShapes(f_eq_g[0].copy(), fs), ReplacementTransform(simpler_rhs, f_rhs), ) self.wait() # Highlight key equation key_equation = VGroup(*radial_rhs[1:], *f_rhs) self.play( key_equation.animate.set_x(0.25 * FRAME_WIDTH).to_edge(UP), FadeOut(f_eq_g), FadeOut(lhs), FadeOut(radial_rhs[0]), ) self.play(FlashAround(key_equation, time_width=1, run_time=2)) full_radial_rhs.set_opacity(1) full_radial_rhs.move_to(key_equation).shift(LEFT) self.play( GrowFromCenter(full_radial_rhs, lag_ratio=0.02), radial_rhs[1:].animate.next_to(full_radial_rhs, LEFT, aligned_edge=DOWN), key_equation[4:].animate.next_to(full_radial_rhs, RIGHT), ) self.wait() # Name as a functional equation func_eq_name = Text("Functional\nequation") func_eq_name.to_corner(UL) func_eq_name.match_y(key_equation) arrow = Arrow(func_eq_name, radial_rhs[1].get_left(), buff=0.25) func_eq_name.to_edge(UP) self.play(LaggedStartMap(FadeOut, properties, shift=LEFT, lag_ratio=0.2)) self.play( Write(func_eq_name), GrowArrow(arrow) ) self.wait() # Example example_box = Rectangle(4, 3) example_box.set_stroke(TEAL, 2) example_box.set_fill(TEAL, 0.35) example_box.to_corner(DL, buff=0) example_word = Text("For example", font_size=30) example_word.next_to(example_box.get_top(), DOWN, SMALL_BUFF) example_f = Tex(R"f({r}) = e^{-{r}^2}", **kw) example_f.scale(0.75) example_f.next_to(example_word, DOWN, MED_LARGE_BUFF) self.play( FadeIn(example_box), FadeIn(example_word, 0.5 * DOWN) ) self.play( TransformFromCopy(key_equation[:4], example_f[:4]), GrowFromPoint(example_f[4:], key_equation.get_left()), ) self.wait() # Define h let = Text("Let") h_def = Tex(R"h({x}) = f(\sqrt{{x}})", **kw) h_def.next_to(key_equation, DOWN, LARGE_BUFF) let.next_to(h_def, LEFT, MED_LARGE_BUFF) h_def2 = Tex(R"h({x}^2) = f({x})", **kw) h_def2.next_to(h_def["h"], DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) h_eq = Tex(R"h(x^2 + y^2) = h(x^2) h(y^2)", **kw) h_eq.to_corner(UR) h_eq.to_edge(RIGHT, buff=1.25) example_h = Tex(R"h({r}) = e^{-{r}}", **kw) example_h.scale(0.75) example_h.next_to(example_f, DOWN, MED_LARGE_BUFF) self.play(FadeIn(h_def, DOWN), Write(let)) self.wait() self.play(TransformMatchingTex( h_def.copy(), h_def2, key_map={R"\sqrt": "^2"}, run_time=1 )) self.wait() self.play( TransformFromCopy(h_def, example_h) ) self.wait(2) self.play( VGroup(key_equation, full_radial_rhs).animate.scale(0.8).to_edge(LEFT), VGroup(let, h_def, h_def2).animate.scale(0.8).to_edge(LEFT), FadeOut(func_eq_name, LEFT), Uncreate(arrow), ) self.play( TransformMatchingShapes( VGroup(*full_radial_rhs[1:], *f_rhs).copy(), h_eq ) ) self.wait() # Exponential property sum_box = SurroundingRectangle(h_eq["x^2 + y^2"]) prod_box = SurroundingRectangle(h_eq["h(x^2) h(y^2)"]) sum_words = Text("Adding inputs", font_size=30) sum_words.next_to(sum_box, DOWN) prod_words = Text("Multiplying outputs", font_size=30) prod_words.next_to(prod_box, DOWN) VGroup(sum_box, prod_box).set_stroke(TEAL, 2) VGroup(sum_words, prod_words).set_color(TEAL) self.play( ShowCreation(sum_box), FadeIn(sum_words, lag_ratio=0.1), ) self.wait() self.play( ReplacementTransform(sum_box, prod_box), FadeTransform(sum_words, prod_words), ) self.wait() self.play(FadeOut(prod_box), FadeOut(prod_words)) self.wait() # Multi-input property implies = Tex(R"\Downarrow", font_size=72) implies.next_to(h_eq, DOWN) full_h_eq = Tex(R"h(x_1 + x_2 + \cdots + x_n) = h(x_1)h(x_2) \cdots h(x_n)") for s, color in zip(["1", "2", "n"], color_gradient([BLUE, YELLOW], 3)): full_h_eq[f"x_{s}"].set_color(color) full_h_eq.scale(0.75) full_h_eq.next_to(implies, DOWN) self.play( Write(implies), FadeIn(full_h_eq, DOWN), ) self.wait() # Whole numbers implies2 = implies.copy() implies2.next_to(full_h_eq, DOWN, buff=MED_LARGE_BUFF) five_eq = Tex(R"h(5) &= h(1 + 1 + 1 + 1 + 1) \\ &= h(1)h(1)h(1)h(1)h(1) = h(1)^5") five_eq.next_to(implies2, DOWN) five_eq.to_edge(RIGHT) n_eq = Tex(R"h(n) = h(1 + \cdots + 1) = h(1) \cdots h(1) = h(1)^n") n_eq.scale(0.75) n_eq.next_to(implies2, DOWN, MED_LARGE_BUFF) sum_brace = Brace(n_eq[R"1 + \cdots + 1"], UP, SMALL_BUFF) sum_tex = sum_brace.get_tex(R"n \text{ times}", buff=SMALL_BUFF).scale(0.5, about_edge=DOWN) prod_brace = Brace(n_eq[R"h(1) \cdots h(1)"], UP, SMALL_BUFF) prod_tex = prod_brace.get_tex(R"n \text{ times}", buff=SMALL_BUFF).scale(0.5, about_edge=DOWN) for tex in n_eq, sum_tex, prod_tex: tex["n"].set_color(BLUE) self.play(Write(five_eq["h(5)"])) self.wait() self.play( TransformFromCopy(five_eq["h("][0], five_eq["h("][1]), TransformFromCopy(five_eq[")"][0], five_eq[")"][1]), Write(five_eq["="][0]), ) self.play(ShowIncreasingSubsets(five_eq["1 + 1 + 1 + 1 + 1"][0])) self.wait() self.play( FadeTransform( five_eq["= h(1 + 1 + 1 + 1 + 1)"].copy(), five_eq["= h(1)h(1)h(1)h(1)h(1)"], ) ) self.wait() self.play(Write(five_eq["= h(1)^5"])) self.wait() self.play(FadeOut(five_eq), FadeIn(n_eq), FadeIn(implies2)) self.play(LaggedStart( GrowFromCenter(sum_brace), FadeIn(sum_tex, 0.25 * DOWN), GrowFromCenter(prod_brace), FadeIn(prod_tex, 0.25 * DOWN), )) self.wait() # Exponential equation exp_eq1 = Tex(R"h(n) = h(1)^n") exp_eq2 = Tex(R"h(n) = b^n") for eq in exp_eq1, exp_eq2: eq["n"].set_color(BLUE) exp_eq1.next_to(n_eq, DOWN, MED_LARGE_BUFF) exp_eq2.move_to(exp_eq1, LEFT) h1_rect = SurroundingRectangle(exp_eq1["h(1)"], buff=0.05) h1_rect.set_stroke(YELLOW, 1) h1_words = Text("Some number", font_size=30) h1_words.match_color(h1_rect) h1_words.next_to(h1_rect, DOWN, SMALL_BUFF) self.play( TransformFromCopy(n_eq["h(n)"], exp_eq1["h(n)"]), TransformFromCopy(n_eq["= h(1)^n"], exp_eq1["= h(1)^n"]), ) self.wait() self.play(ShowCreation(h1_rect), FadeIn(h1_words)) self.wait() self.play( TransformMatchingTex(exp_eq1, exp_eq2), FadeOut(h1_rect, scale=0.5), FadeOut(h1_words, scale=0.5), ) self.wait() # Show exercises self.play( exp_eq2.animate.next_to(implies2, DOWN), FadeOut(VGroup(n_eq, sum_brace, sum_tex, prod_brace, prod_tex), UP), ) rational_eq = Tex(R"h(p / q) = b^{\,p / q}") rational_eq["p / q"].set_color(RED) rational_eq.move_to(exp_eq2) exercise = TexText(R"Exercise: Show this is also true for rational inputs, $p / q$") exercise["p / q"].set_color(RED) hint = TexText(R"Hint, think about $h\left(\frac{p}{q} + \cdots + \frac{p}{q} \right)$") exercise.next_to(rational_eq, DOWN, LARGE_BUFF) exercise.to_edge(RIGHT) hint.scale(0.7) hint.set_fill(GREY_A) hint.next_to(exercise, DOWN) self.play( Write(exercise), FadeOut(VGroup(example_box, example_word, example_f, example_h), shift=DL), ) self.wait() pq_target = rational_eq["p / q"].copy() self.play( TransformMatchingTex(exp_eq2, rational_eq), TransformMatchingShapes(exercise["p / q"].copy(), pq_target), ) self.remove(pq_target) self.wait() self.play(FadeIn(hint, DOWN)) self.wait(2) self.play(LaggedStart( FadeOut(exercise, 0.5 * DOWN), FadeOut(hint, 0.5 * DOWN), lag_ratio=0.25, )) # Continuity assumption = TexText(R"Assuming $f$ (and hence also $h$) \\ is continuous...", font_size=36) assumption.next_to(rational_eq, LEFT, buff=2.0, aligned_edge=UP) assumption.shift(0.5 * DOWN) hx_eq = Tex("h(x) = b^x", **kw) hx_eq.move_to(rational_eq) range1 = TexText(R"For all $x \in \mathds{R}$", **kw) range2 = TexText(R"For all $x \in \mathds{R}^+$", **kw) for ran in range1, range2: ran.scale(0.75) ran.next_to(hx_eq, DOWN, MED_LARGE_BUFF) arrow = Arrow(assumption, hx_eq) self.play(FadeIn(assumption, lag_ratio=0.1)) self.wait() self.play( GrowArrow(arrow), TransformMatchingTex(rational_eq, hx_eq) ) self.play(FadeIn(range1, DOWN)) self.wait() self.play(FadeTransform(range1, range2)) self.wait() # Swap out for e hx_eq2 = Tex(R"h(x) = e^{{c} x}", **kw) hx_eq2.move_to(hx_eq) hx_eq2["c"].set_color(RED) b_rect = SurroundingRectangle(hx_eq["b"], buff=0.05) b_rect.set_stroke(PINK, 2) b_words = Text("Some constant", font_size=30) b_words.next_to(b_rect, DOWN, SMALL_BUFF, LEFT) b_words.match_color(b_rect) self.play( FadeOut(assumption, LEFT), Uncreate(arrow), FadeOut(range2, LEFT), ShowCreation(b_rect), Write(b_words, run_time=1) ) self.wait() c = hx_eq2["{c}"][0][0] c_copy = c.copy() c.set_opacity(0) self.play( ReplacementTransform(b_rect, c_copy), TransformMatchingTex(hx_eq, hx_eq2, key_map={"b": "e"}), FadeOut(b_words, 0.2 * DOWN), ) self.remove(c_copy) c.set_opacity(1) self.add(hx_eq2) self.wait() # Write final form for f implies3 = implies2.copy() implies3.rotate(-90 * DEGREES) implies3.next_to(hx_eq2, LEFT) f_form = Tex(R"f(x) = e^{cx^2}", **kw) f_form["c"].set_color(RED) f_form.next_to(implies3, LEFT) f_form.align_to(hx_eq2, DOWN) self.play( Write(implies3), TransformMatchingTex(hx_eq2.copy(), f_form, run_time=1) ) self.wait() f_form.generate_target() f_form.target.scale(1.5, about_edge=RIGHT) rect = SurroundingRectangle(f_form.target) rect.set_stroke(YELLOW, 2) self.play( MoveToTarget(f_form), FlashAround(f_form.target, time_width=1, run_time=2, stroke_width=5), ShowCreation(rect, run_time=2), ) self.wait() class VariableC(InteractiveScene): c_values = [1.0, 0.5, -1.0, -0.7, -0.5, 0.25, -0.2, -0.4, -0.9, -0.1, 0.5, 0.3, 0.1] def construct(self): axes = self.get_axes() self.add(axes) curve = axes.get_graph(lambda x: self.func(x, 1)) curve.set_stroke(RED, 3) self.add(curve) label = self.get_label(axes) self.add(label) c_tracker, c_interval, c_tip, c_label = self.get_c_group() get_c = c_tracker.get_value c_interval.move_to(axes, UR) c_interval.shift(0.5 * DOWN) self.add(c_interval, c_tip, c_label) axes.bind_graph_to_func(curve, lambda x: self.func(x, get_c())) # Animate for c in self.c_values: self.play(c_tracker.animate.set_value(c), run_time=2) self.wait() def get_c_group(self): c_tracker = ValueTracker(1) get_c = c_tracker.get_value c_interval = NumberLine( (-1, 1, 0.25), width=3, tick_size=0.05, numbers_with_elongated_ticks=[-1, 0, 1], ) c_interval.set_stroke(WHITE, 1) c_interval.add_numbers([-1, 0, 1], num_decimal_places=1, font_size=16) c_tip = ArrowTip(angle=-90 * DEGREES) c_tip.scale(0.5) c_tip.set_fill(RED) c_tip.add_updater(lambda m: m.move_to(c_interval.n2p(get_c()), DOWN)) c_label = Tex("c = 1.00", t2c={"c": RED}, font_size=36) c_label.make_number_changable("1.00") c_label[-1].scale(0.8, about_edge=LEFT) c_label.add_updater(lambda m: m[-1].set_value(get_c())) c_label.add_updater(lambda m: m.next_to(c_tip, UP, aligned_edge=LEFT)) return [c_tracker, c_interval, c_tip, c_label] def get_axes(self): axes = Axes( (-1, 5), (0, 4), width=6, height=4, ) return axes def func(self, x, c): return np.exp(c * x) def get_label(self, axes): label = Tex("e^{cx}", t2c={"c": RED}) label.next_to(axes.c2p(0, 2.7), RIGHT) return label class VariableCWithF(VariableC): def get_axes(self): axes = Axes( (-4, 4), (0, 2), width=8, height=3, ) axes.add(VectorizedPoint(axes.c2p(0, 3))) axes.center() return axes def func(self, x, c): return np.exp(c * x * x) def get_label(self, axes): label = Tex("e^{cx^2}", t2c={"c": RED}) label.next_to(axes.c2p(0, 2), LEFT) return label class TalkAboutSignOfConstant3D(VariableCWithF): def construct(self): # Setup frame = self.frame frame.add_updater(lambda m: m.reorient(20 * math.cos(0.1 * self.time), 75)) axes = ThreeDAxes((-4, 4), (-4, 4), (0, 1), depth=2) axes.set_width(10) axes.set_depth(2, stretch=True) axes.center() self.add(axes) label = Tex("f(r) = e^{cr^2}", t2c={"c": RED}, font_size=72) label.next_to(ORIGIN, LEFT) label.to_edge(UP) label.fix_in_frame() c_tracker, c_interval, c_tip, c_label = self.get_c_group() get_c = c_tracker.get_value c_interval.next_to(label, RIGHT, LARGE_BUFF) c_interval.shift(0.5 * DOWN) c_tracker.set_value(-1) c_group = VGroup(c_interval, c_tip, c_label) c_group.fix_in_frame() # Graph def get_graph(c): surface = axes.get_graph(lambda x, y: np.exp(c * (x**2 + y**2))) surface.always_sort_to_camera(self.camera) surface.set_color(BLUE_E, 0.5) mesh = SurfaceMesh(surface, (31, 31)) mesh.set_stroke(WHITE, 0.5, 0.5) mesh.shift(0.001 * OUT) x_slice = ParametricCurve( lambda t: axes.c2p(t, 0, np.exp(c * t**2)), t_range=(-4, 4, 0.1) ) x_slice.set_stroke(RED, 2) x_slice.set_flat_stroke(False) return Group(mesh, surface, x_slice) graph = get_graph(-1) self.add(graph) self.add(c_group) self.add(label) # Animations for value in [-0.5, -0.8, -0.3, -1.0, -0.3, 0.05, 0.1, -0.3, -1.0, -0.7, -1.0]: new_graph = get_graph(value) self.play( c_tracker.animate.set_value(value), Transform(graph, new_graph), run_time=5 ) self.wait() class OldTalkAboutSignOfConstantScraps(InteractiveScene): def construct(self): plane.bind_graph_to_func(graph, lambda x: self.func(x, get_c())) # Area area = VMobject() area.set_fill(RED, 0.5) area.set_stroke(width=0) def update_area(area): area.set_points_as_corners([ plane.c2p(-4, 0), *graph.get_anchors(), plane.c2p(4, 0) ]) area.add_updater(update_area) class OldTwoKeyProperties(InteractiveScene): def construct(self): # Setup equations kw = dict( t2c={"x": BLUE, "y": YELLOW, "{r}": RED, "{c}": PINK} ) one_var = Tex("f_1(x) = e^{-x^2}", **kw) two_var = Tex("f_2(x, y) = e^{-(x^2 + y^2)}", **kw) factored = Tex("= f_1(x)f_1(y)", **kw) factored_exp = Tex("= e^{-x^2} e^{-y^2}", **kw) radial_exp = Tex(R"= e^{-{r}^2}", **kw) radial = Tex(R"= f_1({r})", **kw) radial_full = Tex(R"= f_1(\sqrt{x^2 + y^2})", **kw) expressions = VGroup( one_var, two_var, factored_exp, factored, radial_exp, radial, radial_full, ) expressions.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) expressions.to_corner(UL) expressions.set_backstroke() rhs1 = VGroup(factored_exp, factored) rhs2 = VGroup(radial_exp, radial, radial_full) for rhs in [rhs1, rhs2]: rhs.arrange(RIGHT) rhs.next_to(two_var, RIGHT) for mob in expressions[2:]: mob.shift((two_var["="].get_y() - mob["="].get_y()) * UP) # From one to two self.add(one_var, two_var) self.wait() rects = VGroup(SurroundingRectangle(one_var), SurroundingRectangle(two_var)) rects.set_stroke(TEAL, 2) rect_words = VGroup(Text("1 variable"), Text("2 variable")) for rect, words in zip(rects, rect_words): words.next_to(rect, RIGHT) arrow = Arrow( one_var.get_right(), two_var.get_corner(UR) + 0.5 * LEFT, path_arc=-PI, ) words = Text("Two interpretations") words.next_to(arrow, RIGHT) self.play( FadeIn(rects[0]), FadeIn(rect_words[0]), ) self.wait() self.play( ReplacementTransform(*rects), FadeTransform(*rect_words), ) self.wait() two_var_copy = two_var.copy() self.play( FadeOut(rects[1]), FadeOut(rect_words[1]), ShowCreation(arrow), TransformMatchingTex(one_var.copy(), two_var_copy, run_time=1), Write(words, run_time=1) ) self.remove(two_var_copy) self.wait() # Factored self.play(LaggedStart( Write(factored_exp["="]), TransformFromCopy(one_var["e^{-x^2}"], factored_exp["e^{-x^2}"]), TransformFromCopy(one_var["e^{-x^2}"], factored_exp["e^{-y^2}"]), run_time=2, lag_ratio=0.4, )) self.wait() self.play(LaggedStart( Write(factored["="]), TransformFromCopy(one_var["f_1(x)"], factored["f_1(x)"], path_arc=PI / 4), TransformFromCopy(one_var["f_1(x)"], factored["f_1(y)"], path_arc=PI / 4), run_time=3, lag_ratio=0.5, )) self.wait() # Rearrange rhs1.generate_target() rhs1.target.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) rhs1.target.next_to(two_var["="], DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) rhs1.target.set_fill(opacity=0.5) self.play(MoveToTarget(rhs1, path_arc=-PI / 2)) # Radial self.play( Write(radial_exp["="]), TransformFromCopy(one_var["e^{-x^2}"], radial_exp["e^{-{r}^2}"]), ) self.wait() self.play( Write(radial["="]), TransformFromCopy(one_var["f_1(x)"], radial["f_1({r})"]), ) self.wait() self.play(FadeIn(radial_full, lag_ratio=0.1)) self.wait() # Consolidate prop = VGroup(factored, radial) prop.generate_target() prop.target.arrange(RIGHT) prop.target.center().move_to(UP) prop.target.set_opacity(1) prop.target.scale(1.5) prop.target[0]["="].set_opacity(0).scale(0, about_edge=RIGHT) prop.target.shift(0.5 * LEFT) f2_eq = VGroup(two_var, radial_exp, factored_exp) f2_eq.generate_target() f2_eq.target.set_fill(opacity=0.5) f2_eq.target[-1].next_to(f2_eq.target[-2], RIGHT) f2_eq.target.to_corner(UR) one_var.generate_target() one_var.target.scale(1.5, about_edge=UL) self.play(LaggedStart( FadeOut(arrow), FadeOut(words), MoveToTarget(prop), MoveToTarget(f2_eq), FadeOut(radial_full), lag_ratio=0.15, run_time=3, )) self.wait() self.play( FlashAround(one_var.target, time_width=1.0, run_time=2), MoveToTarget(one_var), ) self.wait() self.play(FlashUnder(factored[1:])) self.wait() self.play(FlashUnder(radial)) self.wait() radial_full.set_opacity(1) radial_full.scale(1.5) radial_full.move_to(radial, LEFT) radial_full.shift(0.1 * UP) left_shift = 2.0 * LEFT radial_full.shift(left_shift) self.play( FadeIn(radial_full), radial.animate.next_to(radial_full, RIGHT), factored.animate.shift(left_shift) ) self.wait() # Flip the question prop = VGroup(factored, radial_full, radial) prop.generate_target() prop.target.scale(1 / 1.5).to_edge(UP).shift(1.5 * RIGHT) question = Text("What are all the functions \n with this property?") question.next_to(prop.target, DOWN, buff=1.5) question.to_edge(LEFT) arrow = Arrow(question, prop.target[0], buff=0.5) self.play( one_var.animate.scale(1 / 1.5).to_corner(DL).set_opacity(0.5), FadeOut(f2_eq, UP), MoveToTarget(prop), ) self.play( FadeIn(question, lag_ratio=0.1), GrowArrow(arrow), ) self.wait() # Substitute h h_eq = Tex(R"h(x^2) h(y^2) = h(x^2 + y^2)", **kw) h_eq.next_to(prop, DOWN, buff=MED_LARGE_BUFF) h_eq.shift((prop[1]["="].get_x() - h_eq["="].get_x()) * RIGHT) h_def = Tex(R"h(x) = f_1(\sqrt{x})", **kw) h_def.to_edge(LEFT).match_y(h_eq) h_def2 = Tex(R"h(x^2) = f_1(x)", **kw) h_def2.next_to(h_def, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) example_box = Rectangle(4, 4) example_box.set_stroke(TEAL, 2) example_box.set_fill(TEAL, 0.2) example_box.to_corner(DL, buff=0) example_word = Text("For example", font_size=30) example_word.next_to(example_box.get_top(), DOWN, SMALL_BUFF) one_var.generate_target() one_var.target.set_opacity(1) one_var.target.next_to(example_word, DOWN, MED_LARGE_BUFF) one_var.target.to_edge(LEFT) h_example = Tex(R"h(x) = e^{-x}", **kw) h_example.next_to(one_var.target, DOWN, MED_LARGE_BUFF) h_example.to_edge(LEFT) self.play( FadeOut(question, DOWN), FadeOut(arrow, DOWN), Write(h_def) ) self.wait() self.play(TransformMatchingTex(h_def.copy(), h_def2)) self.wait() self.add(example_box, one_var) self.play( FadeIn(example_box), FadeIn(example_word), MoveToTarget(one_var), ) self.wait() self.play(FadeIn(h_example, DOWN)) self.wait() self.play(FlashAround(prop[:2], time_width=1, run_time=2)) self.play( TransformFromCopy(factored, h_eq["h(x^2) h(y^2)"][0]), TransformFromCopy(radial_full, h_eq["= h(x^2 + y^2)"][0]), ) self.wait() # Exponential property h_box = SurroundingRectangle(h_eq) exp_words = Text("Exponential property!") exp_words.next_to(h_box, DOWN) sum_box = SurroundingRectangle(h_eq["x^2 + y^2"]) prod_box = SurroundingRectangle(h_eq["h(x^2) h(y^2)"]) sum_words = Text("Adding inputs", font_size=30) sum_words.next_to(sum_box, DOWN) prod_words = Text("Multiplying outputs", font_size=30) prod_words.next_to(prod_box, DOWN) VGroup(h_box, sum_box, prod_box).set_stroke(TEAL, 2) VGroup(exp_words, sum_words, prod_words).set_color(TEAL) self.play( ShowCreation(sum_box), FadeIn(sum_words, lag_ratio=0.1), ) self.wait() self.play( ReplacementTransform(sum_box, prod_box), FadeTransform(sum_words, prod_words), ) self.wait() self.play( ReplacementTransform(prod_box, h_box), FadeTransform(prod_words, exp_words), ) self.wait() # Exponent implies = Tex(R"\Downarrow", font_size=72) implies.next_to(h_eq, DOWN) implies.rotate(PI) h_exp = Tex(R"h(x) = a \cdot b^x", **kw) h_exp.next_to(implies, DOWN) h_exp2 = Tex(R"h(x) = a \cdot e^{{c}x}", **kw) h_exp2.move_to(h_exp) h_exp0 = Tex(R"h(x) = b^x", **kw) h_exp0.move_to(h_exp) assumption = TexText("Assuming $h$ is continuous", font_size=24) assumption.next_to(implies, RIGHT) b_rect = SurroundingRectangle(h_exp["b"], buff=SMALL_BUFF) b_rect.set_stroke(PINK, 2) b_words = Text("Some constant", font_size=30) b_words.next_to(b_rect, DOWN, SMALL_BUFF, LEFT) b_words.match_color(b_rect) self.play( FadeTransform(h_box, implies), FadeTransform(exp_words, h_exp0), ) self.wait() self.play(TransformMatchingTex(h_exp0, h_exp, run_time=1)) self.wait() self.play( Rotate(implies, PI), FadeIn(assumption, lag_ratio=0.1) ) self.wait() self.play( ShowCreation(b_rect), Write(b_words, run_time=1) ) self.wait() c = h_exp2["{c}"][0][0] c_copy = c.copy() c.set_opacity(0) self.play( ReplacementTransform(b_rect, c_copy), TransformMatchingTex(h_exp, h_exp2), FadeOut(b_words, 0.2 * DOWN), ) self.remove(c_copy) c.set_opacity(1) self.add(h_exp2) self.wait() # Final form implies2 = implies.copy() implies2.next_to(h_exp2, DOWN, MED_LARGE_BUFF) f_eq = Tex(R"f_1(x) = a \cdot e^{{c}x^2}", **kw) f_eq.next_to(implies2, DOWN) rect = SurroundingRectangle(f_eq) rect.set_stroke(YELLOW, 1) self.play( TransformMatchingTex(h_exp2.copy(), f_eq), Write(implies2, run_time=1) ) self.wait() self.play( ShowCreation(rect, run_time=2), FlashAround(f_eq, time_width=1, run_time=2, stroke_width=5), ) self.wait()
from manim_imports_ext import * import pandas as pd def year_to_file_name(year): year_str = str(year)[-2:] year_p1_str = str(year + 1)[-2:] return f"/Users/grant/Downloads/allShots/nbaShots{year_str}_{year_p1_str}.csv" def load_data(year): frame = pd.read_csv( year_to_file_name(year), usecols=[ 'LOC_X', 'LOC_Y', 'SHOT_MADE_FLAG', ] ) coords = np.array(frame[["LOC_X", "LOC_Y"]]) zero_free_coords = coords[~(coords == [0, 0]).all(1)] return zero_free_coords def get_dots(axes, coords): dots = DotCloud(axes.c2p(*coords.T)) dots.set_color(YELLOW) dots.set_glow_factor(0) dots.set_radius(0.01) dots.shift(0.01 * OUT) dots.set_opacity(0.5) return dots def get_bars(axes, coords, resolution=(50, 94)): # Test # resolution = (10, 20) # resolution = (25, 47) x_min, x_max = axes.x_range y_min, y_max = axes.y_range int_coords = (((coords - [x_min, y_min]) / [x_max - x_min, y_max - y_min]) * resolution).astype(int) int_coords = int_coords[::50] xs = np.linspace(x_min, x_max, resolution[0]) ys = np.linspace(y_min, y_max, resolution[1]) factor = 200 / len(int_coords) boxes = VGroup() for i, j in it.product(range(len(xs) - 1), range(len(ys) - 1)): n_in_range = (int_coords == (i, j)).all(1).sum() x1, x2 = xs[i:i + 2] y1, y2 = ys[j:j + 2] line = Line(axes.c2p(x1, y1), axes.c2p(x2, y2)) box = VCube() box.remove(box[-1]) box.set_fill(RED, 1) box.set_stroke(BLACK, 0.5, 0.5) box.set_width(0.35 * line.get_width(), stretch=True) box.set_height(0.35 * line.get_height(), stretch=True) box.set_depth(factor * n_in_range, stretch=True) box.move_to(line, IN) if n_in_range < 1: box.set_opacity(0) boxes.add(box) boxes.set_fill(BLUE_E) boxes.set_stroke(WHITE, 1) return boxes class ShotHistory(InteractiveScene, ThreeDScene): def construct(self): self.always_depth_test = False frame = self.frame frame.reorient(-65, 70) # Court court_rect = Rectangle(50, 94) court_rect.set_height(10) court_rect.set_fill(GREY, 1) court_rect.set_stroke(width=0) court_rect.move_to(IN) court = ImageMobject("basketball-court") court.rotate(90 * DEGREES) court.replace(court_rect, stretch=True) axes = Axes((-250, 250), (-50, 900)) axes.replace(court, stretch=True) self.add(court) # Year label year_label = TexText("Year: 2000", font_size=72) year_mob = year_label.make_number_changable("2000", group_with_commas=False) year_label.fix_in_frame() year_label.to_edge(UP) self.add(year_label) year_mob.add_updater(lambda m: m.fix_in_frame()) # Create plots all_dots = Group() all_bars = Group() year_range = (1997, 2022) low_point = court_rect.get_bottom() + 0.6 * UP for year in ProgressDisplay(range(*year_range)): try: coords = load_data(year) except FileNotFoundError: continue all_dots.add(get_dots(axes, coords)) all_bars.add(get_bars(axes, coords)) for bar in all_bars[-1]: dist = get_norm(bar.get_nadir() - low_point) if dist < 0.5: bar.set_opacity(0) for bars in all_bars: bars.sort(lambda p: np.dot(p, frame.get_implied_camera_location())) all_dots.save_state() all_bars.save_state() # Show all data self.remove(all_dots, all_bars) all_dots.restore() all_bars.restore() self.play( frame.animate.reorient(-100), ShowSubmobjectsOneByOne(all_dots, rate_func=linear, int_func=np.floor), ShowSubmobjectsOneByOne(all_bars, rate_func=linear, int_func=np.floor), UpdateFromAlphaFunc(year_mob, lambda m, a: m.set_value( integer_interpolate(year_range[0], year_range[1] - 1, a)[0] ), rate_func=linear), run_time=20, ) self.play( frame.animate.reorient(-65), run_time=10 ) # Reset states all_bars.restore() all_dots.restore() curr_bars = all_bars[-1].copy() curr_dots = all_dots[-1].copy() self.remove(*all_bars, *all_dots) self.add(curr_dots, curr_bars) # Roll back to 2000 def update_dots(dots): dots.set_submobjects( all_dots[int(year_mob.get_value() - year_range[0])] ) def update_bars(bars): bars.set_submobjects( all_bars[int(year_mob.get_value() - year_range[0])] ) self.play( UpdateFromFunc(curr_dots, update_dots), UpdateFromFunc(curr_bars, update_bars), ChangeDecimalToValue(year_mob, 2000), self.frame.animate.reorient(-117, 69, 0).move_to([-0.54, -2.5, 0.31]).set_height(5.50), run_time=3, ) self.wait(2) self.play( self.frame.animate.reorient(42, 98, 0).move_to([-0.54, -2.5, 0.31]).set_height(5.50), run_time=3, ) self.wait() self.play( self.frame.animate.reorient(-29, 95, 0).move_to([-0.57, -2.46, 0.52]).set_height(6.10), run_time=3, ) # Up to 2010 self.play( UpdateFromFunc(curr_dots, update_dots), UpdateFromFunc(curr_bars, update_bars), ChangeDecimalToValue(year_mob, 2010), self.frame.animate.reorient(-159, 84, 0).move_to([-0.41, -2.56, 0.76]).set_height(6.73), run_time=4, ) self.play( self.frame.animate.reorient(-232, 84, 0).move_to([-0.41, -2.56, 0.76]).set_height(6.73), run_time=15, ) self.frame.reorient(128) self.wait() # Up to 2020 self.play( UpdateFromFunc(curr_dots, update_dots), UpdateFromFunc(curr_bars, update_bars), ChangeDecimalToValue(year_mob, 2020), self.frame.animate.reorient(0, 31, 0).move_to([-0.37, -2.11, 0.71]).set_height(7.26), run_time=4, ) self.wait() self.play( self.frame.animate.reorient(-34, 80, 0).move_to([-0.37, -2.11, 0.71]).set_height(7.26), run_time=5, ) self.play( self.frame.animate.reorient(29, 70, 0).move_to([0.43, -1.87, 0.95]).set_height(7.49), run_time=25, ) self.wait()
from manim_imports_ext import * class PoolTableReflections(InteractiveScene): def construct(self): # Add table table = ImageMobject("pool_table") table.set_height(4.0) buff = 0.475 ball = TrueDot(radius=0.1) ball.set_color(GREY_A) ball.set_shading(1, 1, 1) ball.move_to(table) self.add(table, ball) # Show inner table frame = self.frame frame.set_height(6) irt = Rectangle( # Inner rect template width=table.get_width() - 2 * buff, height=table.get_height() - 2 * buff, ) irt.move_to(table) inner_rect = VMobject() inner_rect.start_new_path(irt.get_right()) for corner in [UR, UL, DL, DR]: inner_rect.add_line_to(irt.get_corner(corner)) inner_rect.add_line_to(irt.get_right()) inner_rect.set_stroke(RED, 3) inner_rect.insert_n_curves(20) self.play(ball.animate.move_to(inner_rect.get_start())) self.play( ShowCreation(inner_rect, run_time=4), UpdateFromFunc(ball, lambda m: m.move_to(inner_rect.get_end())) ) self.wait() # Show reflections table_group1 = Group(table, inner_rect, ball) new_origin = inner_rect.get_corner(UR) self.play( frame.animate.set_height(8).move_to(new_origin), table.animate.set_opacity(0.5), ball.animate.shift(DL) ) table_group2 = table_group1.copy() table_group2[2].set_opacity(0.5) table_group2[0].set_opacity(0.1) self.play( Rotate(table_group2, axis=UP, about_point=inner_rect.get_right()), run_time=2 ) self.wait() table_group3 = table_group2.copy() self.play( Rotate(table_group3, axis=LEFT, about_point=table_group2[1].get_top()), run_time=2 ) self.wait() def get_reflection(point, dims=[0]): vect = point - new_origin for dim in dims: vect[dim] *= -1 return new_origin + vect table_group2[2].add_updater(lambda m: m.move_to(get_reflection(ball.get_center()))) table_group3[2].add_updater(lambda m: m.move_to(get_reflection(ball.get_center(), dims=[0, 1]))) # Move ball around kw = dict(rate_func=there_and_back, run_time=4) self.play(ball.animate.shift(2 * UP), **kw) self.play(ball.animate.shift(2 * LEFT), **kw) self.wait() # Show a trajectory def line_to_trajectory(line, n_reflections=2): p0 = find_intersection( line.get_start(), line.get_vector(), new_origin, DOWN, ) p1 = find_intersection( line.get_start(), line.get_vector(), new_origin, RIGHT, ) trajectory = VMobject() if n_reflections == 1: trajectory.set_points_as_corners([ line.get_start(), p1, get_reflection(line.get_end(), [1]) ]) else: trajectory.set_points_as_corners([ line.get_start(), p0, get_reflection(p1), get_reflection(line.get_end(), [0, 1]) ]) trajectory.match_style(line) trajectory.insert_n_curves(100) return trajectory ur_corner = table_group3[1].get_corner(UR) straight_line = Line(ball.get_center(), ur_corner) straight_line.set_stroke(YELLOW, 2) traj_one_ref = line_to_trajectory(straight_line, 1) trajectory = line_to_trajectory(straight_line) self.play( ShowCreation(trajectory), UpdateFromFunc(ball, lambda m: m.move_to(trajectory.get_end())), run_time=4, ) self.wait() self.play( TransformFromCopy(trajectory, traj_one_ref), trajectory.animate.set_stroke(opacity=0.5), ) self.wait() self.play( MoveAlongPath(ball, trajectory), run_time=4, ) self.wait() self.play( TransformFromCopy(traj_one_ref, straight_line), traj_one_ref.animate.set_stroke(opacity=0.5), ) self.wait() self.play( MoveAlongPath(ball, trajectory), run_time=4, ) self.wait() self.play( FadeOut(traj_one_ref), trajectory.animate.set_stroke(opacity=1) ) # Alternate line alt_line = Line(straight_line.get_start(), straight_line.get_end() + 2 * DOWN) alt_line.match_style(straight_line) self.play( Transform(straight_line, alt_line), UpdateFromFunc(trajectory, lambda m: m.become( line_to_trajectory(straight_line) )), UpdateFromFunc(trajectory, lambda m: m.become( line_to_trajectory(straight_line) )), UpdateFromFunc(ball, lambda m: m.move_to(trajectory.get_end())), run_time=4, rate_func=there_and_back ) self.wait() self.play(*map(FadeOut, [straight_line, trajectory])) # Diamond points vect1 = np.array([0.1, 0.315, 0.]) vect2 = np.array([0.309, 0.1, 0.]) low_diamond_points = np.linspace( inner_rect.get_corner(DL) + vect1 * [-1, -1, 0], inner_rect.get_corner(DR) + vect1 * [1, -1, 0], 9, ) side_diamond_points = np.linspace( inner_rect.get_corner(DR) + vect2 * [1, -1, 0], inner_rect.get_corner(UR) + vect2, 5, ) low_dots = GlowDots(low_diamond_points, radius=0.1) side_dots = GlowDots(side_diamond_points, radius=0.1) low_labels = VGroup(*( Integer(value, font_size=24).next_to(point, DOWN) for value, point in zip( range(80, -10, -10), low_diamond_points, ) )) side_labels = VGroup(*( Integer(value, font_size=24).next_to(point, RIGHT) for value, point in zip( range(90, 0, -20), side_diamond_points, ) )) low_nl = NumberLine((0, 80)) low_nl.put_start_and_end_on(low_diamond_points[-1], low_diamond_points[0]) side_nl = NumberLine((10, 90)) side_nl.put_start_and_end_on(side_diamond_points[-1], side_diamond_points[0]) self.play( FadeIn(low_dots, lag_ratio=0.5), FadeIn(low_labels, lag_ratio=0.5), frame.animate.set_height(10), *( tg[1].animate.set_stroke(width=1) for tg in [table_group1, table_group2, table_group3] ), run_time=2, ) self.play( FadeIn(side_dots, lag_ratio=0.5), FadeIn(side_labels, lag_ratio=0.5), ) self.wait() # Show the trick lines def get_diamond_line(x, y, length=25): line = Line(low_nl.n2p(x), side_nl.n2p(y)) line.scale(length / line.get_length(), about_point=line.get_start()) line.set_stroke(YELLOW, 2) return line def n_to_lines(n): return VGroup(*( get_diamond_line(x, n - x) for x in range(70, 0, -10) )).set_stroke(YELLOW) lines = n_to_lines(80) trajs = VGroup() for line in lines: traj = line_to_trajectory(line) traj.line = line traj.add_updater(lambda t: t.become(line_to_trajectory( t.line )).set_color(BLUE)) trajs.add(traj) self.play(LaggedStartMap(FadeIn, lines, lag_ratio=0.75, run_time=4)) self.wait() self.play( frame.animate.set_height(14, about_edge=DL), run_time=2, ) self.wait() trajs.suspend_updating() for n in range(len(lines)): self.play( lines[:n].animate.set_stroke(opacity=0.2), lines[n].animate.set_stroke(opacity=1), lines[n + 1:].animate.set_stroke(opacity=0.2), FadeIn(trajs[n]), trajs[:n].animate.set_stroke(opacity=0.2), run_time=0.5, ) self.play( lines.animate.set_stroke(opacity=1), trajs.animate.set_stroke(opacity=1), ) trajs.resume_updating() self.wait() # Show just one line line = lines[-1] traj = trajs[-1] self.play( lines[:-1].animate.set_stroke(opacity=0.15), trajs[:-1].animate.set_stroke(opacity=0.15), frame.animate.set_height(12, about_edge=DL).move_to(new_origin), ) self.play( UpdateFromAlphaFunc( line, lambda m, a: m.set_points(get_diamond_line( interpolate(10, 70, there_and_back(a)), interpolate(70, 10, there_and_back(a)), ).get_points()), ), run_time=8, ) self.wait() self.play( lines.animate.set_stroke(opacity=1), trajs.animate.set_stroke(opacity=1), ) # Transition between different n for n in [70, 60, 90, 100, 80]: self.play( Transform(lines, n_to_lines(n)), run_time=3 ) self.wait() # Show outward rays from the corner def get_clean_lines(point): result = VGroup(*( Line(p, point) for p in low_diamond_points[1:-1] )) result.set_stroke(YELLOW, 2) return result lines.save_state() for point in [ur_corner, ur_corner + DOWN, ur_corner, ur_corner + 2 * LEFT, ur_corner]: self.play( Transform(lines, get_clean_lines(point)), run_time=2 ) self.wait() self.play(Restore(lines)) self.wait()
from manim_imports_ext import * def moser(n): return choose(n, 4) + choose(n, 2) + 1 class Introduction(InteractiveScene): def construct(self): # Title tale = SVGMobject("cautionary_tale.svg") tale.set_fill(GREY_A, 1) tale.set_stroke(GREY_A, 2) tale.set_width(7) tale.center() tale.use_winding_fill(False) paths = VGroup(*( VMobject().set_points(path) for path in tale[0].get_subpaths() )) paths.set_fill(opacity=0) paths.set_stroke(width=0) paths.sort(lambda p: np.dot(p, RIGHT)) rect = FullScreenRectangle() rect.set_fill(BLACK, 1) rect.set_stroke(WHITE, 0) rect.move_to(tale, LEFT) self.add(tale) self.play( rect.animate.next_to(tale, RIGHT, buff=LARGE_BUFF).set_anim_args(rate_func=linear), Write(paths, stroke_width=5), run_time=3, ) self.remove(rect, paths) self.wait() # Name name = TexText( R"Moser's Circle Problem", font_size=72, ) name.to_edge(UP) self.play( FadeOut(tale), FadeIn(name, UP) ) self.wait(2) class ShowPattern(InteractiveScene): def construct(self): # Show expression N = 11 values = [moser(n) for n in range(1, N + 1)] expression = Tex( R",".join(map(str, values)) + R"\dots" ) expression.set_width(FRAME_WIDTH - 3) expression.to_edge(UP) n = 0 parts = VGroup() for value in values: new_n = n + len(str(value)) parts.add(expression[n:new_n]) self.play(FadeIn(expression[max(n - 1, 0):new_n], 0.25 * UP, run_time=0.5)) self.wait(0.5) n = new_n + 1 self.play(Write(expression[-3:])) self.wait() # Ask about expression brace1 = Brace(expression, DOWN) brace2 = Brace(expression["1,2,4,8,16"], DOWN) brace3 = Brace(expression["256"], DOWN) question = brace1.get_text("What is this pattern?") coincidence = brace2.get_text("Coincidence?") what = brace3.get_text("And what's with this?") VGroup(question, coincidence, what).set_color(BLUE) self.play( GrowFromCenter(brace1), FadeIn(question, 0.5 * DOWN), ) self.wait() self.play( ReplacementTransform(brace1, brace2), FadeTransform(question, coincidence), ) self.wait() self.play( ReplacementTransform(brace2, brace3), FadeTransform(coincidence, what), ) self.wait() self.play(FadeOut(brace3), FadeOut(what)) # Ask about the function fn = Tex(R"f(n) = \, ???", font_size=60) fn.next_to(expression, DOWN, buff=1.5) self.play(Write(fn)) last_rect = VGroup() last_term = VGroup() for n, part in zip(it.count(1), parts): rect = SurroundingRectangle(part, buff=SMALL_BUFF) rect.set_stroke(YELLOW, 2) term = Tex(fR"f({n})", font_size=48) term.set_color(YELLOW) term.next_to(rect, DOWN) self.play( FadeIn(term), FadeIn(rect), FadeOut(last_term), FadeOut(last_rect), run_time=0.5 ) self.wait(0.5) last_term = term last_rect = rect class AskAboutPosition(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.remove(self.background) self.play(LaggedStart( stds[1].says("Doesn't it depend on\nwhere the points are?", mode="sassy"), stds[0].change('confused', self.screen), stds[2].change('pondering', self.screen), morty.change("guilty", stds[1].eyes) )) self.wait(5) class ExplainNChoose2(InteractiveScene): n = 7 fudge_factor = 0.1 def construct(self): # Setup circle circle, chords, dots, numbers = diagram = self.get_circle_diagram() self.add(*diagram) # Ask question question = Text("How many pairs of points?") question.to_edge(RIGHT, MED_LARGE_BUFF) question.to_edge(UP, MED_SMALL_BUFF) question.add(Underline(question)) self.add(question) # Show all pairs indices = list(range(self.n)) pair_labels = VGroup() pair_label_template = Tex("(0, 0)") last_label = VectorizedPoint() last_label.next_to(question, DOWN) last_label.shift(1.5 * LEFT) for i, j in it.combinations(indices, 2): label = pair_label_template.copy() values = label.make_number_changable("0", replace_all=True) values[0].set_value(i + 1) values[1].set_value(j + 1) label.next_to(last_label, DOWN) if label.get_y() < -3: label.next_to(pair_labels, RIGHT, MED_LARGE_BUFF) label.align_to(pair_labels, UP) pair_labels.add(label) chords.set_opacity(0.25) dots.set_opacity(0.25) numbers.set_opacity(0.25) temp_line = Line(dots[i].get_center(), dots[j].get_center()) temp_line.set_stroke(BLUE_B, 3) for mob in [dots[i], dots[j], numbers[i], numbers[j]]: mob.set_opacity(1) self.add(pair_labels) self.add(temp_line) self.wait(0.25) self.remove(temp_line) last_label = label self.play( chords.animate.set_opacity(1), numbers.animate.set_opacity(1), dots.animate.set_opacity(1), ) self.wait() # Show n choose 2 nc2 = Tex(R"{n \choose 2}") nc2.set_color(YELLOW) nc2_label = TexText("``n choose 2''") group = VGroup(nc2, nc2_label) group.arrange(RIGHT, buff=MED_LARGE_BUFF) group.next_to(question, DOWN) self.play( FadeIn(nc2, DOWN), pair_labels.animate.set_height(4).to_edge(DOWN) ) self.play(Write(nc2_label)) self.wait() # Show counts n_value = Integer(1) n_value.move_to(nc2[1]) n_value.set_color(YELLOW) number_rects = VGroup(*(SurroundingRectangle(number) for number in numbers)) pair_rects = VGroup(*( SurroundingRectangle(pair, buff=SMALL_BUFF).set_stroke(YELLOW, 1) for pair in pair_labels )) rhs = Tex("= 0") rhs_num = rhs.make_number_changable("0") rhs.next_to(nc2, RIGHT) nc2[1].set_opacity(0) self.play( Write(number_rects, lag_ratio=0.5), ChangeDecimalToValue(n_value, self.n), ) self.play(FadeOut(number_rects, lag_ratio=0.1)) self.wait() self.play( VFadeIn(rhs), nc2_label.animate.next_to(nc2, DOWN), ChangeDecimalToValue(rhs_num, choose(self.n, 2), run_time=3), ShowIncreasingSubsets(pair_rects, run_time=3), ) self.wait() self.play(FadeOut(pair_rects, lag_ratio=0.04)) # Show how to calculate it new_rhs = Tex(R"= {7 \cdot (7 - 1) \over 2}") new_rhs.next_to(nc2, RIGHT) self.play( rhs.animate.next_to(new_rhs, RIGHT), Write(new_rhs[:2]), Write(new_rhs[R"\over"]), ) self.wait() self.play(Write(new_rhs[R"\cdot (7 - 1)"])) self.wait() self.play(Write(new_rhs[R"2"])) self.wait() def get_circle_diagram(self): circle = Circle() circle.set_stroke(Color("red"), width=2) circle.set_height(6) circle.to_edge(LEFT) points = [ circle.pfp(a + self.fudge_factor * np.random.uniform(-0., 0.5)) for a in np.arange(0, 1, 1 / self.n) ] dots = VGroup(*( Dot(point, radius=0.04).set_fill(WHITE) for point in points )) chords = VGroup(*( Line(p1, p2).set_stroke(BLUE_B, 1) for p1, p2 in it.combinations(points, 2) )) numbers = VGroup() for n, point in zip(it.count(1), points): number = Integer(n, font_size=36) vect = normalize(point - circle.get_center()) number.next_to(point, vect, buff=MED_SMALL_BUFF) numbers.add(number) return VGroup(circle, chords, dots, numbers) class SimpleCircle(InteractiveScene): def construct(self): # Test circle = Circle() circle.set_height(7.75) circle.set_stroke(RED, width=3) circle.move_to(2.6 * RIGHT) radians = np.arange(1, 7) dots = VGroup(*( Dot(circle.pfp(radians[i] / TAU)) for i in [0, 2, 4, 1, 3, 5] )) self.add(circle) for dot in dots: self.wait() self.add(dot) self.wait() class LeftDiagram(ExplainNChoose2): n = 6 fudge_factor = 0.5 def construct(self): # Initialize circle = Circle() circle.set_height(7.75) circle.set_stroke(RED, width=3) circle.move_to(2.6 * RIGHT) radians = np.arange(1, 7) dots = VGroup(*( Dot(circle.pfp(radians[i] / TAU)) for i in [0, 2, 4, 1, 3, 5] )) # First four diagrams diagrams = VGroup() for n in range(2, 6): diagram = VGroup( circle.copy(), self.get_chords(dots[:n]), dots[:n].copy(), ) diagram.set_stroke(background=True) diagram.preimage = diagram.copy() diagrams.add(diagram) diagrams.arrange(DOWN, buff=2.5) diagrams.set_height(FRAME_HEIGHT - 1) diagrams.to_edge(LEFT) numbers = VGroup(*( Integer(2**n, font_size=60).next_to(diagram, RIGHT) for n, diagram in zip(it.count(1), diagrams) )) for diagram, number in zip(diagrams, numbers): for dot in diagram[2]: dot.scale(2) self.play( TransformFromCopy(diagram.preimage, diagram), FadeInFromPoint(number, circle.get_center()), ) self.wait() def get_chords(self, dots): return VGroup(*( Line( d1.get_center(), d2.get_center(), stroke_width=2, stroke_color=BLUE_B, ) for d1, d2 in it.combinations(dots, 2) )) def get_samples(self, circle, n=1000, color=YELLOW): radius = circle.get_radius() center = circle.get_center() samples = DotCloud() samples.to_grid(n, n) samples.replace(circle) samples.set_radius(8 / n) samples.filter_out(lambda p: np.linalg.norm(p - center) > radius) samples.set_color(color) return samples def get_regions(self, samples, chords): regions = Group() for signs in it.product(*len(chords) * [[-1, 1]]): sub_samples = samples.copy() for chord, sign in zip(chords, signs): vect = sign * rotate_vector(chord.get_vector(), 90 * DEGREES) sub_samples.filter_out(lambda p: np.dot(p, vect) > 0) if sub_samples.get_num_points() > 0: regions.add(sub_samples) return regions class ProblemSolvingRule1(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students # Title title = Text( "Problem-solving rule #1", font_size=72 ) title.to_edge(UP) title.set_backstroke() underline = Underline(title, buff=-0.05) self.play( morty.change("raise_right_hand"), self.change_students("pondering", "thinking", "pondering", look_at=title), GrowFromPoint(title, morty.get_corner(UL)) ) self.add(title) self.add(underline, title) self.play(ShowCreation(underline)) self.wait() # Words words = Text(""" Try answering easier questions related to the problem at hand """, font_size=48) words.next_to(underline, DOWN, LARGE_BUFF) words.set_fill(YELLOW) self.play( FadeIn(words, lag_ratio=0.1, run_time=2), self.change_students("tease", "thinking", "well", look_at=words), morty.change("tease"), ) self.wait(6) class PairOfChords(TeacherStudentsScene): def construct(self): self.remove(self.background) self.play( self.students[0].change("confused", self.screen), self.students[1].says("Pairs of chords?", "raise_left_hand"), self.students[2].change("confused", self.screen), self.teacher.change("well") ) self.wait(5) class PauseAndPonder(TeacherStudentsScene): def construct(self): self.remove(self.background) self.play(LaggedStart( self.students[0].change("pondering", self.screen), self.students[1].change("thinking", self.screen), self.students[2].change("erm", self.screen), self.teacher.says("Pause and\nponder", mode="hooray") )) self.wait(5) class CountIntersections(ExplainNChoose2): tuple_font_size = 28 def construct(self): # Setup circle diagram = self.get_circle_diagram() self.add(*diagram) # Quad words quad_words = Text("Quadruplets of points") quad_words.to_edge(RIGHT, MED_LARGE_BUFF) quad_words.to_edge(UP, MED_SMALL_BUFF) quad_words.add(Underline(quad_words)) self.add(quad_words) # Show all quadruplets int_dots, quad_labels = self.show_quadruplets( diagram, quad_words ) # Show n choose 4 nc4 = Tex(R"n \choose 4") nc4.next_to(quad_words, DOWN, MED_LARGE_BUFF) nc4.shift(2.0 * LEFT) nc4.set_color(YELLOW) nc4_label = TexText("``n choose 4''") nc4_label.next_to(nc4, DOWN) self.play( FadeIn(nc4, 0.5 * DOWN), Write(nc4_label), quad_labels.animate.set_height(4).to_edge(DOWN), ) self.wait() # Show the count rhs = Tex("= 0") rhs_num = rhs.make_number_changable("0") rhs.next_to(nc4, RIGHT) quad_rects = VGroup(*( SurroundingRectangle(label, buff=SMALL_BUFF).set_stroke(YELLOW, 1) for label in quad_labels )) self.play( VFadeIn(rhs, time_span=(0, 1)), ShowIncreasingSubsets(quad_rects), ChangeDecimalToValue(rhs_num, choose(self.n, 4)), run_time=3 ) self.wait() self.play( FadeOut(quad_rects, lag_ratio=0.02), rhs.animate.set_opacity(0), ) self.wait() # Bigger rhs full_rhs = Tex( R"= {n(n-1)(n-2)(n-3) \over 1 \cdot 2 \cdot 3 \cdot 4}", ) nc4.generate_target() nc4.target.shift(1.25 * LEFT) full_rhs.next_to(nc4.target, RIGHT, SMALL_BUFF) self.play( FadeOut(diagram), FadeOut(int_dots), Write(full_rhs), MoveToTarget(nc4), FadeOut(rhs, 2 * RIGHT), MaintainPositionRelativeTo(nc4_label, nc4), ) self.wait() def show_quadruplets(self, diagram, quad_words): circle, chords, dots, numbers = diagram indices = list(range(self.n)) quad_labels = VGroup() quad_label_template = Tex( "(0, 0, 0, 0)", font_size=self.tuple_font_size ) last_label = VectorizedPoint() last_label.next_to(quad_words, DOWN) last_label.shift(1.75 * LEFT) int_dots = VGroup() for sub_indices in it.combinations(indices, 4): label = quad_label_template.copy() values = label.make_number_changable("0", replace_all=True) for value, i in zip(values, sub_indices): value.set_value(i + 1) label.next_to(last_label, DOWN) if label.get_y() < -3.5: label.next_to(quad_labels, RIGHT, MED_LARGE_BUFF) label.align_to(quad_labels, UP) quad_labels.add(label) chords.set_opacity(0.25) dots.set_opacity(0.25) numbers.set_opacity(0.25) i, j, k, l = sub_indices temp_lines = VGroup( Line(dots[i].get_center(), dots[k].get_center()), Line(dots[j].get_center(), dots[l].get_center()), ) int_dot = Dot(find_intersection( temp_lines[0].get_start(), temp_lines[0].get_vector(), temp_lines[1].get_start(), temp_lines[1].get_vector(), ), radius=0.04) int_dot.set_fill(YELLOW) temp_lines.set_stroke(BLUE_B, 2) for group in dots, numbers: for i in sub_indices: group[i].set_opacity(1) self.add(quad_labels) self.add(temp_lines) self.play(LaggedStart(*( TransformFromCopy(dots[i], int_dot) for i in sub_indices )), lag_ratio=0.1) self.add(int_dot) self.wait(0.5) self.remove(temp_lines) int_dots.add(int_dot) int_dots.set_opacity(0.25) self.add(int_dots) last_label = label self.play( chords.animate.set_opacity(1), numbers.animate.set_opacity(1), dots.animate.set_opacity(1), int_dots.animate.set_opacity(1), ) self.wait() return int_dots, quad_labels class SimpleRect(InteractiveScene): def construct(self): self.play(FlashAround( Tex("1.2.3.4").scale(2), time_width=1.5, run_time=3, stroke_width=8, )) class Clean4choose4(InteractiveScene): def construct(self): self.add(Tex(R""" {4 \choose 4} =\frac{4(4-1)(4-2)(4-3)}{1 \cdot 2 \cdot 3 \cdot 4} =1 \text { quadruplet } """).to_edge(UP)) class Clean6choose4(InteractiveScene): def construct(self): self.add(Tex(R""" {6 \choose 4} =\frac{6(6-1)(6-2)(6-3)}{1 \cdot 2 \cdot 3 \cdot 4} =15 \text { quadruplets } """).to_edge(UP)) class Clean100choose4(InteractiveScene): def construct(self): self.add(Tex(R""" {100 \choose 4} =\frac{100(100-1)(100-2)(100-3)}{1 \cdot 2 \cdot 3 \cdot 4} =3{,}921{,}225 \text { quadruplets } """).to_edge(UP)) class FillIn100PointDiagram(ExplainNChoose2): n = 100 def construct(self): # Show all points circle, chords, dots, numbers = diagram = self.get_circle_diagram() diagram.center() chords.set_stroke(width=1, opacity=0.1) for dot in dots: dot.scale(0.75) self.add(circle, chords, dots) self.play( ShowCreation(chords), run_time=9, ) class PlanarNonPlanar(InteractiveScene): def construct(self): v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) v_line.set_stroke(GREY_C, 2) self.add(v_line) titles = VGroup( Text("Planar graph"), Text("Non-planar graph"), ) for vect, title in zip([LEFT, RIGHT], titles): title.shift(vect * FRAME_WIDTH / 4) titles.to_edge(UP) self.add(titles) class NonPlanarGraph(InteractiveScene): def construct(self): # Test circle = Circle(radius=3) dots = Dot().get_grid(2, 3, h_buff=1.5, v_buff=3.0) lines = VGroup(*( Line(d1.get_center(), d2.get_center()) for d1, d2 in it.product(dots[:3], dots[3:]) )) lines.set_stroke(BLUE_B, 2) self.add(lines, dots) self.play(ShowCreation(lines, lag_ratio=0.1, run_time=2)) self.wait() class SimpleR(InteractiveScene): def construct(self): self.add(Tex("R").scale(2)) class SimpleVLine(InteractiveScene): def construct(self): v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) v_line.set_stroke(GREY_C, 2) self.add(v_line) class Polyhedra(InteractiveScene): def construct(self): # Test frame = self.frame frame.reorient(30, 70) cube = VCube() cube.set_stroke(WHITE, 2, 0.5) cube.set_flat_stroke(False) cube.set_fill(BLUE_D, 0.8) cube.set_shading(1, 0.5, 0) cube.apply_depth_test() cube.move_to(2.0 * OUT) dodec = Dodecahedron() dodec.match_style(cube) dodec.move_to(2.0 * IN) dodec.set_fill(TEAL_E) camera_point = frame.get_implied_camera_location() cube.add_updater(lambda m: m.sort(lambda p: -get_norm(p - camera_point))) dodec.add_updater(lambda m: m.sort(lambda p: -get_norm(p - camera_point))) self.add(cube, dodec) self.play(LaggedStart( Rotating( cube, axis=np.array([1, 1, 1]), angle=PI, rate_func=smooth, about_point=cube.get_center() ), Rotating( dodec, axis=np.array([1, -1, 0]), angle=PI, rate_func=smooth, about_point=dodec.get_center() ), run_time=16, lag_ratio=0.2 )) class BalancedEquation(InteractiveScene): def construct(self): # Equation full_rect = FullScreenRectangle() equation = Tex("V - E + F = 2", font_size=60) equation.to_edge(UP) variables = VGroup(*( equation[char][0] for char in "VEF" )) numbers = VGroup(*map(Integer, [1, 0, 1])) for number, variable in zip(numbers, variables): number.scale(1.25) number.next_to(variable, DOWN, MED_SMALL_BUFF) self.add(full_rect) self.add(equation) # Initialize Graph original_points = [ORIGIN, RIGHT, UL, DL, UR, 2 * LEFT] edges = [ (0, 1), (0, 2), (0, 3), (1, 4), (2, 5), (2, 4), (5, 0), (3, 5), (1, 3), ] faces = [ (0, 1, 4, 2), (0, 2, 5), (0, 3, 5), (0, 1, 3), ] dots = VGroup(*(Dot(point) for point in original_points)) dots.space_out_submobjects(1.5) dots.move_to(DOWN) points = [dot.get_center() for dot in dots] edges = VGroup(*( Line(points[i], points[j]) for i, j in edges )) edges.set_stroke(BLUE_B, 2) colors = [BLUE_E, BLUE_C, TEAL_C, GREY_BROWN] faces = VGroup(*( Polygon(*[points[i] for i in face]).set_fill(color, 1) for face, color in zip(faces, colors) )) faces.set_stroke(width=0) # Trivial graph arrow = Vector(DL) arrow.next_to(dots[0], UR, SMALL_BUFF) word = Text("Trivial graph") word.next_to(arrow.get_start(), UP) self.add(dots[0]) self.play( Write(word, run_time=1), GrowArrow(arrow), ) self.wait() self.play( FlashAround(equation["V"]), FlashAround(dots[0]), FadeIn(numbers[0], 0.5 * DOWN), ) self.wait(0.5) self.play( FlashAround(equation["F"]), full_rect.animate.set_fill(BLUE_E, 0.5).set_anim_args(rate_func=there_and_back), FadeIn(numbers[2], 0.5 * DOWN) ) self.wait() self.play( FlashAround(equation["E"]), FadeIn(numbers[1], 0.5 * DOWN) ) self.wait() self.play(FadeOut(word), FadeOut(arrow)) # Edges with new vertices number_y = numbers.get_y() increments = VGroup( Integer(1, include_sign=True), Integer(-1, include_sign=True), Integer(1, include_sign=True), ) for number, incr in zip(numbers, increments): incr.next_to(number, DOWN) incr.set_color(YELLOW) def incr_anim(*ns): return LaggedStart(*( AnimationGroup( UpdateFromAlphaFunc( increments[n], lambda m, a: m.set_y(number_y - 0.75 * a).set_opacity(there_and_back(a)) ), ChangeDecimalToValue( numbers[n], numbers[n].get_value() + 1, run_time=0.25 ) ) for n in ns ), lag_ratio=0.1) new_vert_word = TexText(R"New edge $\rightarrow$ New vertex") new_vert_word["New vertex"].set_color(YELLOW) new_vert_word.next_to(dots[1], UP) new_vert_word.set_backstroke(width=2) self.play( ShowCreation(edges[0]), FadeIn(new_vert_word[R"New edge $\rightarrow$"][0]) ) self.wait() self.play( FadeIn(dots[1], scale=0.5), FadeIn(new_vert_word["New vertex"][0], lag_ratio=0.1) ) self.play(incr_anim(0, 1)) for i in [2, 3, 5, 4]: self.add(edges[i - 1], new_vert_word) self.play( ShowCreation(edges[i - 1]), new_vert_word.animate.next_to(dots[i], UP), FadeIn(dots[i]) ) self.play(incr_anim(0, 1)) # Edges with new faces new_face_word = TexText(R"New edge $\rightarrow$ New face") new_face_word["New face"].set_color(BLUE) new_face_word.next_to(faces[0], UP) self.play( FadeTransform(new_vert_word, new_face_word), ShowCreation(edges[5]), ) self.play(Write(faces[0])) self.play(incr_anim(1, 2)) self.wait() for i, vect in zip([1, 2, 3], [UP, DOWN, DOWN]): self.add(edges[i + 5], dots) self.play( ShowCreation(edges[i + 5]), new_face_word.animate.next_to(faces[i], vect), ) self.add(faces[i], edges[:i + 5], dots, new_face_word) self.play(Write(faces[i])) self.play(incr_anim(1, 2)) self.add(*faces, *edges, *dots) self.play( FadeOut(new_face_word), FadeOut(numbers), ) # Name formula rect = SurroundingRectangle(equation) rect.set_stroke(YELLOW, 2) name = TexText("Euler's Characteristic Formula", font_size=60) name.next_to(rect, DOWN, buff=MED_LARGE_BUFF) self.play( ShowCreation(rect), FlashAround(equation), Write(name, run_time=2), ) self.wait() self.play(FadeOut(rect), FadeOut(name)) # Rearrange new_equation = Tex("F = E - V + 2") new_equation.match_height(equation) new_equation.move_to(equation) face_labels = index_labels(faces, label_height=0.2) face_labels.set_backstroke(BLACK, 3) face_labels[3].shift(0.3 * UP) outer_label = Integer(len(faces) + 1) outer_label.match_height(face_labels[0]) outer_label.match_style(face_labels[0]) outer_label.next_to(faces, RIGHT, MED_LARGE_BUFF) self.remove(faces) self.play( ShowIncreasingSubsets(faces), ShowIncreasingSubsets(face_labels), run_time=2, ) self.add(edges, *dots) self.wait(0.2) self.add(outer_label) full_rect.set_fill(BLUE_E, 0.5) self.wait(0.5) full_rect.set_fill(GREY_E, 1) self.wait() self.play(TransformMatchingTex( equation, new_equation, path_arc=90 * DEGREES )) self.wait() class OnDumbJoke(TeacherStudentsScene): def construct(self): self.remove(self.background) morty = self.teacher stds = self.students self.play( morty.change("raise_left_hand", 3 * UR), self.change_students("hesitant", "happy", "tease", look_at=3 * UR) ) self.wait(3) self.play( stds[0].says("Um, no, Euler was\na person...", mode="sassy"), stds[1].change("hesitant", stds[0].eyes), stds[2].change("jamming", stds[0].eyes), morty.change("well", stds[0].eyes) ) self.wait(4) class SimpleFEq(InteractiveScene): def construct(self): F_eq = Tex("F = E - V + 2") F_eq.to_edge(UP) one = Tex("1") one.move_to(F_eq["2"], DOWN) self.add(F_eq) self.wait() self.play( FadeOut(F_eq["2"][0], 0.5 * UP), FadeIn(one, 0.5 * UP), ) self.wait() class NonPlanarComplaint(TeacherStudentsScene): def construct(self): stds = self.students morty = self.teacher self.remove(self.background) self.play( stds[2].says("But our graph\nis not planar!", mode="angry"), stds[1].change("sassy", 3 * UR), stds[0].change("hesitant", 3 * UR), morty.change("tease"), ) self.wait(3) self.play( morty.change("raise_left_hand"), self.change_students("angry", "sassy", "hesitant") ) self.wait(4) class VEquation(InteractiveScene): def construct(self): eq = Tex(R"V = n + {n \choose 4}") eq.to_corner(UL) self.play(Write(eq)) self.wait() class EdgeAdditionFactor(InteractiveScene): def construct(self): eq = Tex(R""" E = (\#\text{Original lines}) + 2(\#\text{Intersection points}) """) eq["Original lines"].set_color(BLUE_B) eq["Intersection points"].set_color(YELLOW) eq.to_edge(UP) self.add(eq) class EEquation(InteractiveScene): def construct(self): eq = Tex(R"E = {n \choose 2} + 2 {n \choose 4} + n", font_size=72) eq.to_corner(UR) self.play(FadeIn(eq[:6], UP)) self.wait() self.play(Write(eq[6:-2])) self.wait() self.play(Write(eq[-2:])) self.wait() class AddArcComment(InteractiveScene): def construct(self): comment = TexText("$+n$ circular arcs") comment.to_corner(UL) comment.set_color(YELLOW) self.add(comment) class FinalRearrangment(InteractiveScene): def construct(self): # Add equations top_eq = Tex("F = E - V + 1") top_eq.to_edge(UP, buff=LARGE_BUFF) V_rhs = R"n + {n \choose 4}" E_rhs = R"{n \choose 2} + 2{n \choose 4} + n" V_eq = Tex(Rf"V = {V_rhs}") E_eq = Tex(Rf"E = {E_rhs}") V_eq.next_to(top_eq, DOWN, buff=1.5) E_eq.next_to(top_eq, DOWN, buff=1.5) V_eq.set_color(TEAL) E_eq.set_color(BLUE_B) t2c = { Rf"\left({V_rhs}\right)": TEAL, Rf"\left({E_rhs}\right)": BLUE_B, } self.play(FadeIn(top_eq, UP)) self.wait() # Substitute V top_eq2 = Tex(Rf"F = E - \left({V_rhs}\right) + 1", t2c=t2c) top_eq2.move_to(top_eq) self.play( top_eq["V"][0].animate.set_color(TEAL), FadeTransform(top_eq["V"][0].copy(), V_eq[0]), Write(V_eq[1:], run_time=1) ) self.wait() self.play( FadeTransform(V_eq[2:].copy(), top_eq2[Rf"\left({V_rhs}\right)"]), FadeOut(top_eq["V"][0], UP), ReplacementTransform( top_eq["F = E - "], top_eq2["F = E - "], ), ReplacementTransform( top_eq[-2:], top_eq2[-2:], ), ) self.wait() # Substitute E E_eq.set_color(BLUE_B) top_eq3 = Tex( Rf"F = \left({E_rhs}\right) - \left({V_rhs}\right) + 1", t2c=t2c ) top_eq3.move_to(top_eq) self.play( top_eq2[2].animate.set_color(BLUE_B), # top_eq2[3:].animate.set_color(WHITE), FadeTransform(top_eq2[2].copy(), E_eq[0]), Write(E_eq[1:], run_time=1), V_eq.animate.shift(2.0 * DOWN), ) self.wait() self.play( FadeTransform(E_eq[2:].copy(), top_eq3[Rf"\left({E_rhs}\right)"]), FadeOut(top_eq2[2], UP), ReplacementTransform(top_eq2[:2], top_eq3[:2]), ReplacementTransform(top_eq2[-11:], top_eq3[-11:]), ) # Show cancellation final_eq = Tex(R"F = 1 + {n \choose 2} + {n \choose 4}") final_eq.move_to(top_eq) self.play(LaggedStart( FadeOut(E_eq, DOWN), FadeOut(V_eq, DOWN), )) self.play( # Ns FlashAround(top_eq3[14], color=RED), FlashAround(top_eq3[18], color=RED), ) self.play( FadeOut(top_eq3[13:15], DOWN), FadeOut(top_eq3[18:20], DOWN), ) self.play( # Ns FlashAround(top_eq3[9:13], color=RED), FlashAround(top_eq3[20:24], color=RED), ) self.play( # N choose 4s FadeOut(top_eq3[8], DOWN), FadeOut(top_eq3[20:24], DOWN), ) kw = dict(path_arc=90 * DEGREES) self.play(LaggedStart( Transform(top_eq3[:2], final_eq[:2], **kw), Transform(top_eq3[26], final_eq[2], **kw), Transform(top_eq3[25], final_eq[3], **kw), Transform(top_eq3[3:7], final_eq[4:8], **kw), Transform(top_eq3[7], final_eq[8], **kw), Transform(top_eq3[9:13], final_eq[9:13], **kw), *(FadeOut(top_eq3[i], DOWN) for i in [2, 15, 16, 17, 24]), run_time=2, )) self.wait() class ExamplesOfFormula(InteractiveScene): def construct(self): # Test examples = VGroup(*( self.get_example(n) for n in range(1, 7) )) examples.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) examples.set_height(7) examples.to_edge(RIGHT) self.add(*(ex[0] for ex in examples)) for ex in examples: self.play(FadeTransform(ex[0].copy(), ex[1])) self.wait(0.5) self.wait() def get_example(self, n): result = VGroup( Tex(fR"1 + {{{n} \choose 2 }} + {{{n} \choose 4 }}"), Tex(fR"= 1 + {choose(n, 2)} + {choose(n, 4)} = {1 + choose(n, 2) + choose(n, 4)}") ) result.arrange(RIGHT) return result class WhyThePowersOfTwo(TeacherStudentsScene): def construct(self): stds = self.students morty = self.teacher self.remove(self.background) self.play(LaggedStart( stds[0].change("confused", self.screen), stds[1].says("Why the powers \n of 2?"), stds[2].change("pondering", self.screen), morty.change("tease") )) self.wait(6) class IllustrateNChooseK(InteractiveScene): n = 7 k = 3 show_count = False def construct(self): # Test2 n = 7 k = 3 dots = Dot(radius=0.1).replicate(self.n) dots.arrange(RIGHT, buff=0.5) self.add(dots) rects = SurroundingRectangle(dots[0], buff=SMALL_BUFF).replicate(self.k) rects.set_stroke(BLUE) self.add(rects) if self.show_count: count = Integer(0, font_size=60) count.next_to(dots, DOWN, buff=MED_LARGE_BUFF) self.add(count) for subdots in it.combinations(dots, self.k): dots.set_color(WHITE) for dot, rect in zip(subdots, rects): rect.move_to(dot) dot.set_fill(BLUE) if self.show_count: count.set_value(count.get_value() + 1) self.wait(0.2) class Illustrate5Choose3(InteractiveScene): n = 5 k = 3 def construct(self): # Test row = Dot().replicate(self.n) row.arrange(RIGHT) rows = row.replicate(choose(self.n, self.k)) rows.arrange(DOWN) indices = list(range(self.n)) for tup, row in zip(it.combinations(indices, self.k), rows): for i in tup: row[i].set_color(BLUE) rect = SurroundingRectangle(row[i], buff=SMALL_BUFF) rect.set_stroke(BLUE, 2) row[i].add(rect) brace = Brace(rows, RIGHT, buff=SMALL_BUFF) count = Integer(1, font_size=60) count.next_to(brace, RIGHT, SMALL_BUFF) count.add_updater(lambda m: m.set_value(len(rows))) self.add(count) self.play( ShowIncreasingSubsets(rows), run_time=2, ) self.wait() class OnScreenExplanationOfNChooseK(InteractiveScene): def construct(self): # Test kw = dict( tex_to_color_map={"{n}": BLUE, "{k}": TEAL}, alignment="" ) explanation = VGroup( TexText(R""" The claim is that if you look at the ${k}^\text{th}$ element of the ${n}^\text{th}$ row in Pascal's triangle, it equals ${n} \choose {k}$. To show this, it's enough to show that $$ {{n} \choose {k}} = {{n} - 1 \choose {k} - 1} + {{n} - 1 \choose {k}} $$ Can you see why? """, **kw), TexText(R""" There's a nice counting argument which proves this equation. Imagine you have ${n}$ items, and you want to choose ${k}$ of them. On the one hand, by definition, there are ${n} \choose {k}$ ways to do this. But on the other hand, imagine marking one of the items as special. How many ways can you select ${k}$ unmarked items? How may ways can you select ${k}$ items where one of them is the marked one? What does this tell you? """, **kw) ) explanation.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) explanation.set_width(FRAME_WIDTH - 1) self.add(explanation) class ChallengeProblem(InteractiveScene): def construct(self): numbers = VGroup(*( Integer(1 + choose(n, 2) + choose(n, 4)) for n in range(100) )) numbers.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=RIGHT) numbers.to_corner(UL) numbers.shift(DR) numbers.add_updater(lambda m, dt: m.shift(2 * dt * UP)) question = VGroup( Text("Challenge question", font_size=72).set_fill(YELLOW), Text("Will there ever be another power of 2?") ) question.arrange(DOWN, buff=MED_LARGE_BUFF) question.next_to(numbers, RIGHT, LARGE_BUFF) question.set_y(0) # Test self.add(numbers) self.play(Write(question)) self.wait(20) class AskAboutSome(InteractiveScene): def construct(self): randy = Randolph() morty = Mortimer() randy.next_to(ORIGIN, LEFT, LARGE_BUFF).to_edge(DOWN) morty.next_to(ORIGIN, RIGHT, LARGE_BUFF).to_edge(DOWN) morty.to_corner(DR) randy.next_to(morty, LEFT, LARGE_BUFF) self.add(morty) # SoME words = Text("The 3rd Summer of\nMath Exposition", font_size=72) words.next_to(randy, UP) words.to_edge(RIGHT) small_words = Text("SoME3", font_size=72) small_words.move_to(words, UP) small_words_copy = small_words.copy() small_words_copy.next_to(morty.get_corner(UL), UP) three_some = Text("3SoME", font_size=72) three_some.next_to(randy.get_corner(UR), UP) self.play( morty.change("raise_left_hand", words), FadeIn(words, 0.25 * UP, lag_ratio=0.01) ) self.play(Blink(morty)) self.wait(3) self.play( TransformMatchingStrings(words, small_words, path_arc=45 * DEGREES), morty.change("raise_right_hand") ) self.play(Blink(morty)) self.wait(2) self.play( VFadeIn(randy), randy.change("shruggie", three_some), morty.change("sassy", randy.eyes), TransformMatchingStrings(small_words, three_some, path_arc=45 * DEGREES) ) self.play(morty.change("angry", randy.eyes)) self.play(Blink(morty)) self.play( TransformMatchingStrings(three_some, small_words_copy, run_time=1), morty.change("raise_right_hand"), randy.change("sassy") ) self.play(Blink(morty)) self.play(Blink(randy)) self.wait(2) class EndScreen(PatreonEndScreen): pass
from manim_imports_ext import * import sympy class PrimeRace(InteractiveScene): race_length = 26863 def construct(self): ONE_COLOR = BLUE THREE_COLOR = RED colors = [ONE_COLOR, THREE_COLOR] # Labels labels = VGroup( Tex(R"p \equiv 1 \mod 4", t2c={"1": ONE_COLOR}), Tex(R"p \equiv 3 \mod 4", t2c={"3": THREE_COLOR}), ) labels.arrange(DOWN, buff=0.75) labels.to_edge(LEFT) h_line = Line(LEFT, RIGHT) h_line.set_width(100) h_line.to_edge(LEFT) v_line = Line(UP, DOWN) v_line.set_height(1.5 * labels.get_height()) v_line.next_to(labels, RIGHT) v_line.set_y(0) VGroup(h_line, v_line).set_stroke(width=2) self.add(h_line, v_line) self.add(labels) # Start the race primes: list[int] = list(sympy.primerange(3, self.race_length)) team1 = VGroup() team3 = VGroup() teams = [team1, team3] blocks = [] for prime in primes: index = int((prime % 4) == 3) square = Square(side_length=1) square.set_fill(colors[index], 0.5) square.set_stroke(colors[index], 1.0) p_mob = Integer(prime) p_mob.set_max_width(0.8 * square.get_width()) block = VGroup(square, p_mob) teams[index].add(block) blocks.append(block) for team, label in zip(teams, labels): team.arrange(RIGHT, buff=0) team.next_to(v_line, RIGHT, buff=SMALL_BUFF) team.match_y(label) h_line.set_width(teams[1].get_width() + 10, about_edge=LEFT) for block in blocks[:10]: self.play(FadeIn(block[0]), Write(block[1])) # Next sets frame = self.frame frame.target = frame.generate_target() frame.target.scale(1.75, about_edge=LEFT) self.play( LaggedStartMap( FadeIn, VGroup(*blocks[10:30]), lag_ratio=0.9, ), MoveToTarget(frame, rate_func=rush_into), run_time=12, ) # Last set curr = 30 tups = [ (200, 10, linear, 1.25), (len(blocks) - 100, 60, linear, 1.25), (len(blocks) - 1, 5, smooth, 0.8) ] for index, rt, func, sf in tups: frame.target = frame.generate_target() frame.target.scale(sf) frame.target.set_x(blocks[index].get_right()[0] + 1) self.play( ShowIncreasingSubsets(VGroup(*blocks[curr:index])), MoveToTarget(frame), run_time=rt, rate_func=func, ) curr = index blocks = VGroup(*blocks) self.add(blocks) self.play(frame.animate.set_height(8, about_point=blocks.get_right() + 2 * LEFT), run_time=3) self.wait() class RaceGraph(InteractiveScene): race_length = 26863 y_range = (-4, 30, 2) def construct(self): # Compute differences primes: list[int] = list(sympy.primerange(3, self.race_length)) diffs = [0] colors = [WHITE] y_max = self.y_range[1] for p in primes: diff = diffs[-1] + (p % 4 - 2) diffs.append(diff) if diff < 0: colors.append(BLUE) elif diff < y_max / 2: colors.append(interpolate_color(WHITE, RED, clip(2 * diff / y_max, 0, 1))) else: colors.append(interpolate_color(RED, RED_E, clip(2 * (diff - y_max / 2) / y_max, 0, 1))) # Axes and graph x_unit = 10 axes = Axes( x_range=(0, len(primes) + 10, x_unit), y_range=self.y_range, width=len(primes) / x_unit / 1.6, height=7, axis_config=dict(tick_size=0.05), ) axes.to_edge(LEFT, buff=0.8) y_label = TexText(R"\#Team3 $-$ \#Team1") y_label["Team3"].set_color(RED) y_label["Team1"].set_color(BLUE) y_label.next_to(axes.y_axis.get_top(), RIGHT) y_label.fix_in_frame() axes.y_axis.add_numbers(font_size=14, buff=0.15) graph = VMobject() graph.set_points_as_corners([ axes.c2p(i, diff) for i, diff in enumerate(diffs) ]) graph.set_stroke(colors, width=3) self.add(axes) self.add(y_label) self.add(graph) # Set blocking rectangle rect = FullScreenRectangle() rect.set_fill(BLACK, 1) rect.set_stroke(BLACK, 0) rect.match_x(axes.c2p(0, 0), LEFT) def set_x_shift(x, anims=[], **kwargs): self.play( rect.animate.match_x(axes.c2p(x, 0), LEFT), *anims, **kwargs ) self.clear() self.add(graph, rect, axes.x_axis, axes.y_axis, y_label) # First blocks, total runtime should be 12 frame = self.frame frame.save_state() zoom_point = axes.c2p(0, 0) frame.set_height(3, about_point=zoom_point) for x in range(10): set_x_shift(x + 1) for x in range(10, 30): set_x_shift(x + 1, run_time = 6 / 20) self.wait(6 / 20) # Next block set_x_shift( 200, anims=[Restore(frame)], run_time=10, rate_func=linear ) # Squish the graph full_width = get_norm(axes.c2p(200, 0) - axes.c2p(0, 0)) origin = axes.c2p(0, 0) prime_label = Integer(primes[200]) prime_label.next_to(rect, LEFT, buff=0.7) prime_label.to_edge(DOWN, buff=0.3) prime_label.fix_in_frame() self.add(prime_label) def set_x_squish(x1, x2, **kwargs): group = VGroup(axes.x_axis, graph) self.add(group, rect) self.play( UpdateFromAlphaFunc( group, lambda m, a: m.stretch( full_width / get_norm(axes.c2p(interpolate(x1, x2, a), 0) - origin), 0, about_point=origin, ), ), UpdateFromAlphaFunc( prime_label, lambda m, a: m.set_value( primes[min(int(interpolate(x1, x2, a)), len(primes) - 1)] ) ), **kwargs ) set_x_squish(200, len(primes) - 100, rate_func=linear, run_time=60) set_x_squish(len(primes) - 100, len(primes), rate_func=smooth, run_time=5) # Reset frame self.play( VGroup(axes, graph).animate.set_width( len(primes) / 10, about_point=axes.c2p(len(primes), 0), stretch=True ), FadeOut(rect), run_time=6, ) self.wait() class LongRaceGraph(RaceGraph): race_length = 650000 y_range = (-10, 100, 5)
from manim_imports_ext import * import scipy.integrate as integrate class SplitScreen(InteractiveScene): def construct(self): h_lines = Line(DOWN, UP).set_height(FRAME_HEIGHT).replicate(2) h_lines.arrange(RIGHT, buff=FRAME_WIDTH / 3) h_lines.center() h_lines.set_stroke(GREY_B, 2) self.add(h_lines) class ImagineProving(InteractiveScene): def construct(self): self.add(FullScreenRectangle()) screen = ScreenRectangle() screen.set_height(0.70 * FRAME_HEIGHT) screen.to_edge(DOWN) screen.set_stroke(GREY_A, 1) self.add(screen) # Randy randy = Randolph(height=1.5) randy.next_to(screen, UP, aligned_edge=LEFT) words = Text(""" Imagine yourself proving the central limit theorem """) yourself = words["Imagine yourself"][0] words["central limit theorem"].set_color(YELLOW) words.next_to(randy, RIGHT, buff=1.5) arrow = Arrow(words, randy) yourself.save_state() yourself.match_y(words) self.play( Write(yourself), ShowCreation(arrow), randy.change("pondering", screen) ) self.play(Blink(randy)) self.wait() self.play( Restore(yourself), Write(words[len(yourself):]), randy.change("thinking"), ) for x in range(2): self.play(Blink(randy)) self.wait(2) class WhyGaussian(InteractiveScene): def construct(self): self.add(TexText("Why $e^{-x^2}$?", font_size=72)) class AskAboutTheProof(TeacherStudentsScene): def construct(self): self.remove(self.background) self.pi_creatures.scale(0.5, about_edge=DOWN) self.pi_creatures.space_out_submobjects(1.5) # Ask morty = self.teacher stds = self.students self.play( stds[0].change("pondering", 5 * DOWN), stds[1].says("Proof?"), stds[2].change("sassy"), morty.change("tease"), ) self.wait(6) words = VGroup( Text("Moment generating functions"), Text("Culumants"), Text("Characteristic functions"), ) words.move_to(morty.get_corner(UL), DOWN) words.shift(0.2 * UP) words.scale(0.65) self.play( morty.change("raise_right_hand"), FadeIn(words[0], UP), stds[1].debubble(mode="well"), stds[0].change("confused", morty.eyes), stds[2].change("pondering", morty.eyes), ) self.wait() for i in [1, 2]: self.play( words[:i].animate.next_to(words[i], LEFT, buff=0.5), FadeIn(words[i], LEFT) ) self.wait() self.wait(3) class RefinedHypothesis(InteractiveScene): def construct(self): # Setup tex_kw = dict( t2c={"X": BLUE_B} ) # Given X, sum depends only on mu and sigma # ... # Rescale the sum, ask about the limit # Specify the sense of the limit # Ask about the moments # Rephrase by asking for the MGF of the scaled sum # Rephrase by asking for the CGF of the scaled sum # Show explicity CGF # Turn into explicit MGF pass class LookingBeyondExpectationAndVariance(InteractiveScene): def construct(self): # Only E[X] and Var(X) matter kw = dict(t2c={ R"\mu": PINK, R"\sigma": RED, R"\mathds{E}[X]": PINK, R"\text{Var}(X)": RED, }) top_words1 = TexText(R"Only $\mu$ and $\sigma$ matter", **kw) top_words2 = TexText(R"Only $\mathds{E}[X]$ and $\text{Var}(X)$ matter", **kw) for words in [top_words1, top_words2]: words.to_edge(UP) words.set_backstroke(width=2) self.play(Write(top_words1, run_time=1)) self.wait() self.remove(top_words1) self.play(LaggedStart(*( ReplacementTransform( top_words1[t1][0], top_words2[t2][0], ) for t1, t2 in [ ("Only", "Only"), (R"$\mu$", R"$\mathds{E}[X]$"), ("and", "and"), (R"$\sigma$", R"$\text{Var}(X)$"), ("matter", "matter"), ] ))) self.wait() # Add distribution axes = Axes((-4, 4), (0, 0.75, 0.25), width=10, height=3) axes.to_edge(DOWN) def func(x): return (np.exp(-(x - 1)**2) + 0.5 * np.exp(-(x + 1)**2)) / 2.66 graph = axes.get_graph(func) graph.set_stroke(TEAL, 3) mu = integrate.quad(lambda x: x * func(x), -4, 4)[0] mu_line = Line(axes.c2p(mu, 0), axes.c2p(mu, 0.5)) mu_line.set_stroke(PINK, 2) exp_label = Tex(R"\mathds{E}[X]", font_size=30) exp_label.next_to(mu_line, UP, SMALL_BUFF) exp_label.set_color(PINK) sigma_arrows = VGroup(Vector(LEFT), Vector(RIGHT)) sigma_arrows.arrange(RIGHT) sigma_arrows.move_to(mu_line.pfp(0.2)) sigma_arrows.set_color(RED) plot = VGroup(axes, graph, mu_line, exp_label, sigma_arrows) self.play(LaggedStartMap(Write, plot)) self.wait() # What else is there moment_list = Tex(R""" \mathds{E}\left[X\right],\quad \mathds{E}\left[X^2\right],\quad \mathds{E}\left[X^3\right],\quad \mathds{E}\left[X^4\right],\quad \mathds{E}\left[X^5\right],\quad \dots """) moment_list.next_to(top_words2, DOWN, LARGE_BUFF) moments = moment_list[re.compile(r"\\mathds{E}\\left\[X.*\\right\]")] commas = moment_list[","] commas.shift(SMALL_BUFF * RIGHT) moments[1:].shift(SMALL_BUFF * LEFT) for moment in moments: y = moment[0].get_y() moment[0].next_to(moment[1], LEFT, SMALL_BUFF) moment[0].set_y(y) moment_boxes = VGroup(*( SurroundingRectangle(moment, buff=0.05) for moment in moments )) moment_boxes.set_stroke(TEAL, 2) moment_boxes.set_fill(GREY_E, 1) var_sub = Tex(R"\text{Var}(X)") var_sub.move_to(commas[:2]).align_to(moments[0], DOWN) question = Text("What else is there?") question.next_to(moment_boxes[2:], DOWN) self.play(LaggedStart( TransformFromCopy(top_words2[R"\mathds{E}[X]"][0], moments[0]), Write(commas[0]), TransformFromCopy(top_words2[R"\text{Var}(X)"][0], var_sub), Write(commas[1]), lag_ratio=0.5, )) self.play( LaggedStartMap(FadeIn, moment_boxes[2:]), LaggedStartMap(FadeIn, commas[2:]), Write(question) ) self.play(Write(moment_list[R"\dots"][0])) self.wait() # Expand variance var_equation = Tex(R"\text{Var}(X) = \mathds{E}[X^2] - \mathds{E}[X]^2") full_var_equation = Tex(R""" \text{Var}(X) &= \mathds{E}[(X - \mu)^2] \\ &= \mathds{E}[X^2 - 2\mu X + \mu^2] \\ &= \mathds{E}[X^2] - 2 \mu \mathds{E}[X] + \mu^2] \\ &= \mathds{E}[X^2] - \mathds{E}[X]^2 \\ """, font_size=32, t2c={R"\mu": PINK}) var_equation.to_edge(UP) full_var_equation.to_corner(DL) full_var_equation.shift(UP) full_var_equation.set_fill(GREY_A) second_moment = var_equation[R"\mathds{E}[X^2]"][0] second_moment_rect = SurroundingRectangle(second_moment) self.play( TransformFromCopy(var_sub, var_equation[:len(var_sub)]), FadeIn(var_equation[len(var_sub):], UP), FadeOut(top_words2, UP), ) self.wait() self.play(FadeIn(full_var_equation)) self.wait() self.play( ShowCreation(second_moment_rect), FlashAround(second_moment, run_time=1.5) ) self.play( TransformFromCopy(second_moment, moments[1]), FadeOut(var_sub, DOWN), ) self.wait() self.play( FadeOut(second_moment_rect), var_equation.animate.scale(0.7).to_corner(UL), FadeOut(full_var_equation, DOWN) ) # Show the moments self.add(moment_list, moment_boxes[2:]) for box in moment_boxes[2:]: self.play( FadeOut(box, UP), question.animate.set_opacity(0), ) self.remove(question) self.wait() # Name the moments moment_name = TexText("Moments of $X$") moment_name.to_edge(UP, buff=MED_SMALL_BUFF) moment_name.match_x(moments) moment_name.set_color(BLUE) points = np.linspace(moment_name.get_corner(DL), moment_name.get_corner(DR), len(moments)) arrows = VGroup(*( Arrow(point, moment.get_top() + 0.1 * UP) for point, moment in zip(points, moments) )) arrows.set_color(BLUE) self.play( FadeIn(moment_name, UP), FadeOut(var_equation, UL), ) self.play(LaggedStartMap(GrowArrow, arrows)) self.wait() # Hypothesis rect = SurroundingRectangle(VGroup(moments[2], moment_list[R"\dots"])) rect.set_stroke(RED, 3) hyp = TexText(R""" Hypothesis: These have no \\ influence on $X_1 + \cdots + X_n$ """, font_size=42) hyp["Hypothesis"].set_color(RED) hyp.next_to(rect, DOWN).shift(LEFT) correction = Text("diminishing", font_size=42) correction.set_color(YELLOW) correction.next_to(hyp["no"], RIGHT) cross = Cross(hyp["no"]) cross.scale(1.5) self.play( ShowCreation(rect), Write(hyp), ) self.wait() self.play(ShowCreation(cross)) self.play(Write(correction)) self.wait() class DefineMGF(InteractiveScene): def construct(self): # Equations mgf_name = Text("Moment Generating Function") mgf_name.to_corner(UL) kw = dict(t2c={ "t": YELLOW, R"\frac{t^2}{2}": YELLOW, R"\frac{t^k}{k!}": YELLOW, }) top_eq = Tex(R"M_X(t) = \mathds{E}[e^{tX}]", **kw) top_eq.next_to(mgf_name, DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) kw["font_size"] = 42 lines = VGroup( Tex(R"\mathds{E}\left[1 + tX + \frac{t^2}{2} X^2 + \cdots + \frac{t^k}{k!} X^k + \cdots\right]", **kw), Tex(R"1 + \mathds{E}[X]t + \mathds{E}[X^2] \frac{t^2}{2} + \cdots + \mathds{E}[X^k] \frac{t^k}{k!} + \cdots", **kw), ) stack_kw = dict(buff=1.75, aligned_edge=LEFT) lines.arrange(DOWN, **stack_kw) lines.next_to(top_eq, DOWN, **stack_kw) # Introduce the expression x_rect = SurroundingRectangle(top_eq["X"][0], buff=0.05) x_rect.set_stroke(BLUE, 2) indic_arrow = Vector(0.5 * UP) indic_arrow.next_to(x_rect, DOWN, SMALL_BUFF) indic_arrow.target = indic_arrow.generate_target() indic_arrow.target.next_to(top_eq["t"][0], DOWN, SMALL_BUFF) x_words, t_words = [ Text(text, font_size=36) for text in ["Random variable", "Some real number"] ] x_words.next_to(indic_arrow, DOWN, SMALL_BUFF) x_words.shift_onto_screen() t_words.next_to(indic_arrow.target, DOWN, SMALL_BUFF) t_words.shift_onto_screen() self.play(Write(mgf_name, run_time=1)) self.wait() self.play( FadeTransform(mgf_name[0].copy(), top_eq[0]), FadeIn(top_eq[1:5], lag_ratio=0.1) ) self.play( GrowArrow(indic_arrow), FadeIn(x_words, 0.5 * DOWN), ShowCreation(x_rect), ) self.wait() self.play( MoveToTarget(indic_arrow), FadeTransform(x_words, t_words), FadeOut(x_rect), ) self.wait() self.play( TransformFromCopy(*top_eq["X"]), TransformFromCopy(*top_eq["t"]), Write(top_eq[R"= \mathds{E}[e"][0]), Write(top_eq[R"]"][0]), ) self.play(FadeOut(indic_arrow), FadeOut(t_words)) self.wait() # Expand series exp_term = top_eq[R"e^{tX}"] exp_series = lines[0][re.compile(r"1 +.*\\cdots")][0] exp_rects = VGroup(*( SurroundingRectangle(m, buff=0.05) for m in [exp_term, exp_series] )) exp_rects.set_stroke(BLUE, 2) arrow1 = Arrow(exp_term.get_bottom(), exp_series, stroke_color=BLUE, buff=0.3) arrow1_label = Text("Taylor series", font_size=32) arrow1_label.next_to(arrow1.get_center(), LEFT) gf_words = mgf_name["Generating Function"] gf_rect = SurroundingRectangle(gf_words, buff=0.05) gf_rect.set_stroke(TEAL, 2) gf_expl = Text("Focus on coefficients\nin a series expansion", font_size=36) gf_expl.next_to(gf_rect, DOWN) gf_expl.align_to(mgf_name["Function"], LEFT) self.play( ShowCreation(gf_rect), gf_words.animate.set_color(TEAL), ) self.play( FadeIn(gf_expl, lag_ratio=0.1) ) self.wait() self.play(ShowCreation(exp_rects[0])) self.play( ReplacementTransform(*exp_rects), TransformMatchingShapes(exp_term.copy(), exp_series, run_time=1), TransformFromCopy(top_eq[R"\mathds{E}["], lines[0][R"\mathds{E}\left["]), TransformFromCopy(top_eq[R"]"], lines[0][R"]"]), GrowArrow(arrow1), FadeIn(arrow1_label), ) self.play(FadeOut(exp_rects[1])) self.wait() # Linearity of expectations frame = self.frame arrow2 = Arrow(*lines) arrow2.match_style(arrow1) arrow2.rotate(arrow1.get_angle() - arrow2.get_angle()) arrow2_label = Text("Linearity of Expectation", font_size=32) arrow2_label.next_to(arrow2.get_center(), LEFT) self.play( frame.animate.align_to(top_eq, UP).shift(0.5 * UP), mgf_name.animate.next_to(top_eq, RIGHT, buff=1.0).set_color(WHITE), FadeOut(gf_expl, DOWN), FadeOut(gf_rect), ) self.play( TransformMatchingTex(lines[0].copy(), lines[1]), GrowArrow(arrow2), FadeIn(arrow2_label), ) self.wait() # Highlight term by term terms = VGroup(lines[1]["1"][0]) terms.add(*lines[1][re.compile(r'(?<=\+)(.*?)(?=\+)')]) terms.remove(terms[-2]) rects = VGroup(*(SurroundingRectangle(term) for term in terms)) rects.set_stroke(PINK, 2) last_rect = VMobject() for rect in rects: self.play(ShowCreation(rect), FadeOut(last_rect)) self.wait() last_rect = rect self.play(FadeOut(last_rect)) class DirectMGFInterpretation(InteractiveScene): random_seed = 4 n_samples = 30 def construct(self): # Graph t_tracker = ValueTracker(1) get_t = t_tracker.get_value axes = Axes((-2, 2), (0, 15), width=8, height=7) axes.x_axis.add(Tex("x").next_to( axes.x_axis.get_right(), UR, SMALL_BUFF) ) def get_exp_graph(): t = get_t() graph = axes.get_graph(lambda x: np.exp(t * x)) graph.set_stroke(BLUE, 2) return graph exp_graph = get_exp_graph() kw = dict(t2c={"t": YELLOW}) graph_label = VGroup( Tex("e^{tX}", **kw).scale(1.3), Tex("t = 1.00", **kw), ) graph_label.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) graph_label.to_corner(UR).shift(3 * LEFT) value = graph_label[1].make_number_changable("1.00") value.add_updater(lambda m: m.set_value(get_t())) self.add(axes) self.add(exp_graph) self.add(graph_label) # Prepare samples samples = np.random.uniform(-2, 2, self.n_samples) def get_sample_group(samples): ys = np.exp(get_t() * samples) y_points = axes.y_axis.n2p(ys) x_points = axes.x_axis.n2p(samples) graph_points = axes.c2p(samples, ys) v_lines = VGroup(*( Line(xp, gp) for xp, gp in zip(x_points, graph_points) )) h_lines = VGroup(*( Line(gp, yp) for gp, yp in zip(graph_points, y_points) )) lines = VGroup(v_lines, h_lines) lines.set_stroke(WHITE, 1, 0.7) kw = dict(radius=0.075, glow_factor=1) x_dots = Group(*(GlowDot(point, color=YELLOW, **kw) for point in x_points)) y_dots = Group(*(GlowDot(point, color=RED, **kw) for point in y_points)) sample_group = Group(x_dots, v_lines, h_lines, y_dots) return sample_group def get_Ey(): return np.exp(get_t() * samples).mean() x_dots, v_lines, h_lines, y_dots = s_group = get_sample_group(samples) # Show samples sample_arrows = VGroup(*( Vector(0.5 * DOWN).next_to(dot, UP, buff=0) for dot in x_dots )) sample_arrows.set_color(YELLOW) sample_words = Text("Samples of X") sample_words.next_to(sample_arrows, UP, aligned_edge=LEFT) self.play( # FadeIn(sample_words, time_span=(0, 1)), LaggedStartMap(VFadeInThenOut, sample_arrows, lag_ratio=0.1), LaggedStartMap(FadeIn, x_dots, lag_ratio=0.1), run_time=1, ) # self.play(FadeOut(sample_words)) # Show outputs Ey_tip = ArrowTip() Ey_tip.scale(0.5) Ey_tip.add_updater(lambda m: m.move_to(axes.y_axis.n2p(get_Ey()), RIGHT)) Ey_label = Tex(R"\mathds{E}[e^{tX}]", **kw) Ey_label.add_updater(lambda m: m.next_to(Ey_tip, LEFT)) y_dots.save_state() y_dots.set_points([l.get_end() for l in v_lines]) for dot in y_dots: dot.set_radius(0) self.play(ShowCreation(v_lines, lag_ratio=0.3, run_time=2)) self.wait() self.play( Restore(y_dots, lag_ratio=0), ShowCreation(h_lines, lag_ratio=0), run_time=2, ) yd_mover = y_dots.copy() yd_mover.generate_target() points = yd_mover.get_points().copy() points[:] = Ey_tip.get_start() yd_mover.target.set_points(points) yd_mover.target.set_opacity(0) self.play( MoveToTarget(yd_mover), FadeIn(Ey_tip), FadeIn(Ey_label, scale=0.5), ) self.wait() # Move around # self.frame.set_height(10) s_group.add_updater(lambda m: m.become(get_sample_group(samples))) exp_graph.add_updater(lambda g: g.become(get_exp_graph())) self.remove(*s_group) self.add(s_group) t_tracker.add_updater(lambda m: m.set_value(1.5 * math.sin(self.time / 6))) self.add(t_tracker) self.wait(48) for _ in range(15): target_t = random.uniform(0, 2.5) self.play( t_tracker.animate.set_value(target_t), run_time=7 ) for target_t in [1.5, 0.5, 1.2, 0.2, 2.0, 1.0]: self.play( t_tracker.animate.set_value(target_t), run_time=5 ) class AddingVariablesWithMGF(InteractiveScene): def construct(self): # What we want is M_{X1+...+Xn}(t) # Addition rule pass class ScalingProperty(InteractiveScene): def construct(self): # Test kw = dict(t2c={"c": YELLOW, "t": PINK, "X": WHITE, "Y": WHITE}) equation = VGroup( Tex(R"M_{cX}(t) = ", **kw), Tex(R"\mathds{E}[e^{tcX}] = ", **kw), Tex(R"M_X(ct)", **kw), ) equation.arrange(RIGHT) self.add(equation[0]) self.wait() for i in [0, 1]: self.play(TransformMatchingTex( equation[i].copy(), equation[i + 1], path_arc=-45 * DEGREES )) self.wait() # Equation 2 equation.generate_target() equation.target[1].scale(0).set_opacity(0) equation.target.arrange(RIGHT, buff=0.05) equation2 = Tex(R"M_{X+Y}(t) = M_X(t)M_Y(t)", **kw) equation2.next_to(equation.target, UP, buff=LARGE_BUFF) VGroup(equation.target, equation2).center() self.play( MoveToTarget(equation), FadeIn(equation2, UP), ) self.wait() self.play( FadeOut(equation), equation2.animate.to_edge(UP), ) self.wait() class DefineCGF(InteractiveScene): def construct(self): # Take logs kw = dict(t2c={"t": PINK, R"\log": RED_B}) mgf_eq = Tex(R"M_{X+Y}(t) = M_X(t)M_Y(t)", **kw) mgf_eq.to_edge(UP) log_eq = Tex(R""" \log\left( M_{X + Y}(t) \right) = \log\left( M_{X}(t) \right) + \log\left( M_{Y}(t) \right) """, font_size=36, **kw) log_eq.next_to(mgf_eq, DOWN, LARGE_BUFF) self.add(mgf_eq) self.wait() self.play( TransformMatchingTex(mgf_eq.copy(), log_eq) ) self.wait() # Name CGF parts = log_eq[re.compile(r"\\log\\left(.* \\right)")] braces = VGroup() for part in parts: braces.add(Brace(part, DOWN, buff=SMALL_BUFF)) cgf_funcs = VGroup( Tex("K_{X + Y}(t)", font_size=36, **kw), Tex("K_{X}(t)", font_size=36, **kw), Tex("K_{Y}(t)", font_size=36, **kw), ) for name, brace in zip(cgf_funcs, braces): name.next_to(brace, DOWN, SMALL_BUFF) cgf_name = TexText("``Cumulant Generating Function''") cgf_name.next_to(cgf_funcs, DOWN, buff=1.5) arrows = VGroup(*(Arrow(cgf_name, func) for func in cgf_funcs)) self.play( LaggedStartMap(GrowFromCenter, braces, lag_ratio=0.2), LaggedStartMap(FadeIn, cgf_funcs, shift=0.5 * DOWN, lag_ratio=0.2), ) self.wait() self.play( Write(cgf_name), LaggedStartMap(GrowArrow, arrows), ) self.wait() # Highlight generating function gen_func = cgf_name["Generating Function"] rect = SurroundingRectangle(gen_func, buff=0.1) rect.set_stroke(YELLOW, 1) series = Tex( R"K_X(t) = k_0 + k_1 t + k_2 \frac{t^2}{2} + k_3 \frac{t^3}{6} + \cdots", font_size=42, t2c={ R"t": PINK, R"\frac{t^2}{2}": PINK, R"\frac{t^3}{6}": PINK, }, ) series.next_to(cgf_name, DOWN, LARGE_BUFF) self.play( ShowCreation(rect), gen_func.animate.set_color(YELLOW) ) self.wait() self.play(FadeIn(series, lag_ratio=0.1, run_time=2)) self.wait() class ExpandCGF(InteractiveScene): def construct(self): # Taylor series for log t2c = { "x": YELLOW, "{t}": MAROON_B, R"\frac{t^2}{2}": MAROON_B, R"\frac{t^3}{3!}": MAROON_B, R"\frac{t^m}{m!}": MAROON_B, } kw = dict(t2c=t2c) log_eq = VGroup( Tex(R"\log(1 + x)", **kw), Tex(R"= x -\frac{1}{2}x^{2} +\frac{1}{3}x^{3} -\frac{1}{4}x^{4} +\cdots", **kw) ) log_eq.arrange(RIGHT, buff=0.15) log_eq.to_edge(UP) equals = log_eq[1][0] approx = Tex(R"\approx") approx.move_to(equals) taylor_label = Text("Taylor Series expansion") taylor_label.next_to(log_eq, DOWN, buff=MED_LARGE_BUFF) self.add(log_eq) self.add(taylor_label) # Graph of log bls = dict( stroke_color=GREY_B, stroke_width=1, stroke_opacity=0.5, ) axes = NumberPlane( (-1, 10), (-3, 3), background_line_style=bls, faded_line_ratio=0, num_sampled_graph_points_per_tick=10, ) axes.set_height(5) axes.to_edge(DOWN, buff=0.25) graph = axes.get_graph(lambda x: np.log(1.01 + x)) graph.make_smooth() graph.set_stroke(BLUE, 3) self.add(axes, graph) # Approximations rects = VGroup(*( SurroundingRectangle(log_eq[1][s][0]) for s in [ R"x", R"x -\frac{1}{2}x^{2}", R"x -\frac{1}{2}x^{2} +\frac{1}{3}x^{3}", R"x -\frac{1}{2}x^{2} +\frac{1}{3}x^{3} -\frac{1}{4}x^{4}", R"x -\frac{1}{2}x^{2} +\frac{1}{3}x^{3} -\frac{1}{4}x^{4} +\cdots", ] )) rects.set_stroke(TEAL, 2) coefs = [0, *[(-1)**(n + 1) / n for n in range(1, 14)]] def poly(x, coefs): return sum(c * x**n for n, c in enumerate(coefs)) approxs = VGroup(*( axes.get_graph(lambda x: poly(x, coefs[:N])) for N in range(2, len(coefs)) )) approxs.set_stroke(YELLOW, 3, opacity=0.75) top_rect = FullScreenRectangle().set_fill(BLACK, 1) top_rect.set_height( FRAME_HEIGHT / 2 - axes.get_top()[1] - SMALL_BUFF, about_edge=UP, stretch=True ) rect = rects[0].copy() rect.scale(1e-6).move_to(rects[0].get_corner(DL)) approx = VectorizedPoint(axes.c2p(0, 0)) self.add(approx, top_rect, log_eq, taylor_label) for target_rect, target_approx in zip(rects, approxs): self.play( Transform(rect, target_rect), FadeOut(approx), FadeIn(target_approx), ) approx = target_approx self.wait() for target_approx in approxs[len(rects):]: self.play( FadeOut(approx), FadeIn(target_approx), rect.animate.stretch(1.02, 0, about_edge=LEFT), ) approx = target_approx self.wait() self.remove(top_rect) self.play(LaggedStartMap( FadeOut, VGroup(axes, graph, approx, rect, taylor_label) )) # Set up expansion mgf_term = R"\mathds{E}[X]{t} + \mathds{E}[X^2]\frac{t^2}{2} + \mathds{E}[X^3]\frac{t^3}{3!} + \cdots" log_mgf = Tex(R"\log(M_X({t}))", **kw) log_mgf.next_to(log_eq[0], DOWN, buff=1.75, aligned_edge=RIGHT) kt = Tex("K_X({t}) = ", **kw) full_rhs = Tex(Rf""" &=\left({mgf_term}\right)\\ &-\frac{{1}}{{2}} \left({mgf_term}\right)^{{2}}\\ &+\frac{{1}}{{3}} \left({mgf_term}\right)^{{3}}\\ &-\frac{{1}}{{4}} \left({mgf_term}\right)^{{4}}\\ &+\cdots """, font_size=36, **kw) full_rhs.next_to(log_mgf, RIGHT, aligned_edge=UP) log_mgf.next_to(full_rhs["="], LEFT) kt.next_to(log_mgf, LEFT, buff=0.2) # Setup log anim self.play( TransformMatchingTex(log_eq[0].copy(), log_mgf), FadeIn(kt, DOWN), run_time=1 ) self.wait() self.play(LaggedStart( *( TransformFromCopy(log_eq[1][tex][0], full_rhs[tex][0]) for tex in [ "=", R"-\frac{1}{2}", R"+\frac{1}{3}", R"-\frac{1}{4}", R"+\cdots", "^{2}", "^{3}", "^{4}", ] ), *( AnimationGroup( TransformFromCopy(x, lp), TransformFromCopy(x, rp), ) for x, lp, rp in zip( log_eq[1]["x"], full_rhs[R"\left("], full_rhs[R"\right)"], ) ), lag_ratio=0.1, run_time=4 )) self.wait() # Interim equation frame = self.frame log_eq.generate_target() log_eq.target.shift(UP) mid_eq = Tex(f"x = M_X({{t}}) - 1 = {mgf_term}", font_size=42, **kw) mid_eq.set_y(midpoint(log_eq.target.get_y(DOWN), full_rhs.get_y(UP))) self.play(LaggedStart( frame.animate.set_height(10), MoveToTarget(log_eq), TransformFromCopy(log_eq[0]["x"][0], mid_eq["x"][0]), TransformFromCopy(log_mgf["M_X({t})"][0], mid_eq["M_X({t})"][0]), Write(mid_eq["="]), Write(mid_eq["- 1"]), )) self.wait() self.play(FadeIn(mid_eq[mgf_term][0], lag_ratio=0.1, run_time=2)) self.wait() # Fill in parens self.play(LaggedStart( *( TransformFromCopy(mid_eq[mgf_term][0], term, path_arc=-60 * DEGREES) for term in full_rhs[f"{mgf_term}"] ), lag_ratio=0.2, run_time=4 )) self.wait() # Reposition k_eq = VGroup(kt, log_mgf, full_rhs) self.play( k_eq.animate.align_to(mid_eq, UP), FadeOut(mid_eq, UP) ) self.wait() # Expand out first order term term11, term21, term31 = full_rhs[R"\mathds{E}[X]{t}"][:3].copy() term12, term22 = full_rhs[R"\mathds{E}[X^2]\frac{t^2}{2}"][:2].copy() term13 = full_rhs[R"\mathds{E}[X^3]\frac{t^3}{3!}"][0].copy() parens2 = VGroup( full_rhs[R"-\frac{1}{2} \left("][0], full_rhs[R"\right)^{2}"][0], ).copy() parens3 = VGroup( full_rhs[R"+\frac{1}{3} \left("][0], full_rhs[R"\right)^{3}"][0], ).copy() expansion = Tex(R""" K_X({t}) = \mathds{E}[X]{t} + \text{Var}(X)\frac{t^2}{2} + K_3[X]\frac{t^3}{3!} + \cdots + K_m[X]\frac{t^m}{m!} + \cdots """, **kw) expansion[R"\text{Var}"].set_color(BLUE) expansion.next_to(k_eq, DOWN, buff=0.75, aligned_edge=LEFT) self.add(term11) self.play(full_rhs.animate.set_opacity(0.3)) self.wait() self.play( TransformFromCopy(kt, expansion[R"K_X({t}) ="][0]), TransformFromCopy(term11, expansion[R"\mathds{E}[X]{t}"][0]), ) self.wait() # Second order term full_second = Tex( R"\left(\mathds{E}[X^2] - \mathds{E}[X]^2 \right) \frac{t^2}{2}", **kw ) plus = expansion["+"][0] full_second.next_to(plus, RIGHT, index_of_submobject_to_align=0) self.play( FadeOut(term11), FadeIn(term12), FadeIn(parens2), FadeIn(term21), ) self.wait() self.play(FlashAround(term12, run_time=1.5)) self.play( LaggedStart(*( TransformFromCopy(m1, full_second[tex][0]) for m1, tex in [ (term12[:4], R"\mathds{E}[X^2]"), (term12[4:], R"\frac{t^2}{2}"), ] )), Write(plus), Write(full_second[R"\left("][0]), Write(full_second[R"\right)"][0]), ) self.wait() self.play( TransformFromCopy(term21, full_second[R"- \mathds{E}[X]^2"][0]) ) self.wait() # Highlight variance expanded_var = full_second[R"\left(\mathds{E}[X^2] - \mathds{E}[X]^2 \right)"] var_term = expansion[R"\text{Var}(X)"] rect = SurroundingRectangle(expanded_var, buff=0.05) rect.set_stroke(BLUE, 2) arrow = Vector(DR) arrow.next_to(var_term, UL, SMALL_BUFF) arrow.set_color(BLUE) self.play( VGroup(expanded_var, rect).animate.next_to(arrow.get_start(), UL, SMALL_BUFF), FadeIn(var_term), GrowArrow(arrow), ReplacementTransform( full_second[R"\frac{t^2}{2}"][0], expansion[R"\frac{t^2}{2}"][0], ), ) self.wait() self.play( FadeOut(expanded_var), FadeOut(rect), FadeOut(arrow), ) # Third term preview self.play(LaggedStart( FadeOut(term12), FadeIn(term13), FadeIn(term22), FadeIn(term31), )) self.play(Write(expansion[R"+ K_3[X]\frac{t^3}{3!}"])) self.wait() self.play( full_rhs.animate.set_opacity(1), Write(expansion[R"+ \cdots + K_m[X]\frac{t^m}{m!} + \cdots"]) ) self.wait() class FirstFewTermsOfCGF(InteractiveScene): def construct(self): # Test kw = dict(t2c={ "t": PINK, R"\frac{t^2}{2}": PINK, R"\frac{t^3}{3!}": PINK, R"\frac{t^4}{4!}": PINK, }) rhs = Tex(R""" = \mathds{E}[X]t + \text{Var}(X)\frac{t^2}{2} + K_3[X]\frac{t^3}{3!} + K_4[X]\frac{t^4}{4!} + \cdots """, **kw ) self.add(rhs) class ConfusionAboutCGF(TeacherStudentsScene): def construct(self): # Setup morty = self.teacher stds = self.students kw = dict(t2c={ "t": PINK, R"\frac{t^2}{2}": PINK, R"\frac{t^3}{6}": PINK, R"\frac{t^m}{m!}": PINK, R"\log": BLUE_B }) equation = Tex( R""" K_X(t) = \log\left(\mathds{E}[e^{tX}]\right) = \sum_{m=1}^\infty K_m[X] \frac{t^m}{m!} """, **kw ) equation.next_to(morty.get_corner(UL), UP) equation.shift_onto_screen() # React self.play( morty.change("raise_right_hand"), FadeIn(equation, UP), self.change_students("confused", "maybe", "confused", look_at=equation), ) self.wait(3) # Another way... equation.generate_target() equation.target.scale(0.7) equation.target.to_corner(UR) eq_rect = SurroundingRectangle(equation.target) words = Text("Another language to\ndescribe distributions") words.move_to(self.hold_up_spot, DOWN) arrow = Arrow(words, eq_rect, stroke_color=YELLOW) self.play( morty.change("tease"), MoveToTarget(equation), self.change_students("hesitant", "sassy", "erm", look_at=words) ) self.play( Write(words), ShowCreation(arrow), ) self.wait(3) # Back and forth words.generate_target() words.target.scale(0.7) words.target.next_to(equation, LEFT, buff=1.5) words.target.shift_onto_screen() arrow.target = Arrow(words.target, equation, stroke_color=YELLOW) self.play( morty.says("I'm thinking of\na distribution", run_time=1), MoveToTarget(words), MoveToTarget(arrow), ) self.wait() self.play( stds[0].says("Oh cool, what\nis it?", mode="coin_flip_2", run_time=1), stds[1].change("happy"), stds[1].change("tease"), ) self.wait() # Show pdf axes = Axes((0, 10), (0, 0.3), width=4, height=1.25) axes.move_to(self.hold_up_spot, DOWN) graph = axes.get_graph(lambda x: np.exp(-x) * x**3 / 6) graph.set_stroke(YELLOW, 2) label = Tex(R"p_X(x) = e^{-x} x^3 / 6", font_size=36) label.move_to(axes, UL) label.shift(0.5 * UP) plot = VGroup(axes, graph, label) self.play( morty.debubble(mode="raise_right_hand"), FadeIn(plot, UP), ) self.wait() # Show CGF cgf = Tex(R""" K_{X}(t) = 4t + 4 \frac{t^2}{2} + 8 \frac{t^3}{6} + \cdots """, **kw ) cgf.move_to(self.hold_up_spot, DOWN) self.play( morty.change("tease"), stds[0].change("sassy"), stds[1].change("hesitant"), plot.animate.set_width(2).to_corner(UL), FadeIn(cgf, UP), ) self.wait(2) # Term by term words = VGroup(Text("Expected value"), Text("Variance")) coefs = cgf["4"] arrows = VGroup(*(Vector(0.5 * DOWN).next_to(coef, UP) for coef in coefs)) arrows.set_color(YELLOW) words.set_color(YELLOW) for word, arrow in zip(words, arrows): word.next_to(arrow, UP, SMALL_BUFF) self.play( FadeIn(words[0]), FadeIn(arrows[0]), ) self.wait(2) self.play( ReplacementTransform(*words), ReplacementTransform(*arrows), ) self.wait(5) class TermByTermSum(InteractiveScene): def construct(self): # One line equation top_eq = Tex("K_{X+Y}(t) = K_X(t) + K_Y(t)", t2c={"t": MAROON_B}) top_eq.to_edge(UP) self.add(top_eq) self.wait() # Set up equations sum_eq, x_eq, y_eq = all_eqs = VGroup(*( VGroup( Tex(Rf"K_{{{sym}}}({{t}})"), Tex("="), Tex(Rf"\mathds{{E}}[{sym}] {{t}}"), Tex("+"), Tex(Rf"\text{{Var}}({sym}) \frac{{t^2}}{{2}}"), Tex("+"), Tex(Rf"K_3[{sym}] \frac{{t^3}}{{3!}}"), Tex(R"+ \cdots") ) for sym in ["X + Y", "X", "Y"] )) for eq in all_eqs: eq.arrange(RIGHT, buff=SMALL_BUFF) all_eqs.arrange(DOWN, buff=LARGE_BUFF) for p1, p2, p3 in zip(x_eq, y_eq, sum_eq): for part in p1, p2, p3: part["{t}"].set_color(MAROON_B) part[R"\frac{t^2}{2}"].set_color(MAROON_B) part[R"\frac{t^3}{3!}"].set_color(MAROON_B) p1.match_x(p3) p2.match_x(p3) plus = Tex("+").scale(1.25) equals = Tex("=").scale(1.25).rotate(90 * DEGREES) plus.move_to(VGroup(x_eq[0], y_eq[0])) equals.move_to(VGroup(x_eq[0], sum_eq[0])) sum_eq[4].shift(0.05 * UP) anim_kw = dict(path_arc=-45 * DEGREES) self.play(LaggedStart( ReplacementTransform(top_eq["K_{X+Y}(t)"][0], sum_eq[0], **anim_kw), ReplacementTransform(top_eq["+"][1], plus, **anim_kw), ReplacementTransform(top_eq["K_X(t)"][0], x_eq[0], **anim_kw), ReplacementTransform(top_eq["="][0], equals, **anim_kw), ReplacementTransform(top_eq["K_Y(t)"][0], y_eq[0], **anim_kw), run_time=3, )) self.play(LaggedStartMap(FadeIn, sum_eq[1:])) self.play(FadeIn(x_eq[1:], DOWN)) self.play(FadeIn(y_eq[1:], DOWN)) self.wait() # Highlight variance pe_copy = VGroup(plus, equals).copy() rects = VGroup(*( SurroundingRectangle(VGroup(*(eq[i] for eq in all_eqs))) for i in [2, 4, 6] )) rects.set_stroke(YELLOW, 2) self.play( ShowCreation(rects[0]), pe_copy.animate.match_x(rects[0]), ) self.wait() for r1, r2 in zip(rects, rects[1:]): self.play( ReplacementTransform(r1, r2), pe_copy.animate.match_x(r2), ) self.wait() self.play( rects[2].animate.become(SurroundingRectangle(all_eqs).set_stroke(width=0)), FadeOut(pe_copy), ) self.wait() class CumulantsOfScaledSum(InteractiveScene): def construct(self): # Setup kw = dict( t2c={ "{t}": MAROON_B, R"\frac{t^2}{2}": MAROON_B, R"\frac{t^3}{6}": MAROON_B, R"\frac{t^m}{m!}": MAROON_B, } ) clt_var_tex = R"{X_1 + \cdots + X_n \over \sigma \sqrt{n}}" clt_var_flat = R"(X_1 + \cdots + X_n) / \sigma \sqrt{n}" cgf_def = Tex(R""" K_X({t}) = \log\left(\mathds{E}\left[e^{{t}X}\right]\right) = \sum_{m=1}^\infty K_m[X] \frac{t^m}{m!} """, **kw) cgf_of_clt_var = Tex( Rf""" \mathds{{E}}\left[{clt_var_tex}\right] {{t}} + \text{{Var}}\left({clt_var_tex}\right) \frac{{t^2}}{{2}} + K_3\left[{clt_var_tex}\right] \frac{{t^3}}{{6}} + \cdots """, ) cgf_of_clt_var.set_max_width(FRAME_WIDTH - 1) cgf_of_clt_var.to_edge(UP) clt_var = Tex(clt_var_tex, **kw) # Highlight scaled sum clt_var.set_height(1.5) clt_var.move_to(ORIGIN, DOWN) rect = SurroundingRectangle(clt_var) rect.set_stroke(YELLOW, 2) limit_words = TexText(R"What happens to \\ this as $n \to \infty$?") limit_words.next_to(rect, DOWN) limit_words.next_to(rect, DOWN) self.add(clt_var) self.play( FlashAround(clt_var, run_time=1.5), ShowCreation(rect), FadeIn(limit_words, lag_ratio=0.1), ) self.wait() # Bring in CGF cgf_def.to_edge(UP) cgf_of_clt_sum = Tex(Rf""" K_{{{clt_var_flat}}}({{t}}) = \sum_{{m=1}}^\infty K_m\left[{clt_var_tex}\right] \frac{{t^m}}{{m!}} """, **kw) cumulant_of_clt_var = cgf_of_clt_sum[Rf"K_m\left[{clt_var_tex}\right]"][0] cgf_of_clt_sum.save_state() cgf_of_clt_sum.set_opacity(0) cumulant_of_clt_var.set_opacity(1) cumulant_of_clt_var.center() cumulant_of_clt_var.set_height(1.5) self.play( clt_var.animate.center(), FadeIn(cgf_def, lag_ratio=0.1), FadeOut(limit_words), FadeOut(rect), ) self.wait() self.play( ReplacementTransform( clt_var, cgf_of_clt_sum[clt_var_tex][0], path_arc=45 * DEGREES, ), Write(cumulant_of_clt_var[:3]), Write(cumulant_of_clt_var[-1:]), ) self.wait() self.play(Restore(cgf_of_clt_sum)) self.wait() # Discuss scaling sigma_sqrt_n = cgf_of_clt_sum[R"\sigma \sqrt{n}"][0] sigma_sqrt_n_rect = SurroundingRectangle(sigma_sqrt_n, buff=0.05) sigma_sqrt_n_rect.set_stroke(YELLOW, 2) scaling_equation = Tex( R""" K_{cX}(t) = \log\left(\mathds{E}\left[e^{tcX} \right]\right) = \sum_{m=1}^\infty K_m[X] c^m \frac{t^m}{m!} """, t2c={ "t": MAROON_B, R"\frac{t^m}{m!}": MAROON_B, "c": YELLOW, } ) part1 = scaling_equation["K_{cX}(t)"][0] part2 = scaling_equation[re.compile(r"=.*\\right\)")][0] part3 = scaling_equation[re.compile(r"= \\sum.*m\!\}")][0] arrow = Vector(LEFT).next_to(part1, RIGHT) question = Text("How does this expand?") question.next_to(arrow) cX_rect = SurroundingRectangle(scaling_equation["cX"][1], buff=0.05) tc_rect = SurroundingRectangle(scaling_equation["tc"][0], buff=0.05) new_K_rect = SurroundingRectangle(scaling_equation["K_m[X] c^m"], buff=0.1) VGroup(cX_rect, tc_rect).set_stroke(BLUE, 2) new_K_rect.set_stroke(YELLOW, 2) self.play(ShowCreation(sigma_sqrt_n_rect)) self.wait() self.play( TransformFromCopy( cgf_of_clt_sum[f"K_{{{clt_var_flat}}}({{t}})"][0], part1, ), Write(question), GrowArrow(arrow), cgf_of_clt_sum.animate.scale(0.75).to_edge(DOWN, buff=LARGE_BUFF), FadeOut(sigma_sqrt_n_rect, 2 * DOWN + 0.2 * RIGHT), ) self.wait() self.play( FadeOut(question, lag_ratio=0.1), arrow.animate.next_to(part2, RIGHT), FadeIn(part2, lag_ratio=0.1) ) self.wait() self.play(ShowCreation(cX_rect)) self.wait() self.play(ReplacementTransform(cX_rect, tc_rect)) self.wait() self.play( FadeOut(tc_rect), arrow.animate.next_to(part3, RIGHT), FadeIn(part3, lag_ratio=0.1) ) self.wait() self.play(ShowCreation(new_K_rect)) self.wait() self.play( FadeOut(cgf_def, UP), FadeOut(arrow, UP), scaling_equation.animate.to_edge(UP), MaintainPositionRelativeTo(new_K_rect, scaling_equation), ) # Scaling rule for cumulant scaling_rule = Tex(R"K_m[cX] = c^m K_m[X]", t2c={"c": YELLOW}) var_example = TexText(R""" For example, $\text{Var}(cX) = c^2 \text{Var}(X)$ """, t2c={"c": YELLOW}) var_example.move_to(scaling_rule.get_bottom()) self.play(Write(scaling_rule["K_m[cX] = "][0])) self.wait() globals().update(locals()) self.play( new_K_rect.animate.move_to(scaling_rule["c^m K_m[X]"]), LaggedStart(*( TransformFromCopy( scaling_equation[tex][0], scaling_rule[tex][0], path_arc=45 * DEGREES, ) for tex in ["K_m[X]", "c^m"] )) ) self.play(FadeOut(new_K_rect)) self.wait() self.play( scaling_rule.animate.next_to(var_example, UP, buff=0.5), FadeIn(var_example, 0.5 * DOWN) ) self.wait() # Apply to the cummulant of the clt variable lhs = cumulant_of_clt_var.copy() scaling_rule.generate_target() scaling_rule.target.center().to_edge(UP) implies = Tex(R"\Downarrow", font_size=72) implies.next_to(scaling_rule.target, DOWN, buff=0.5) rhs = Tex(R""" = \left({1 \over \sigma \sqrt{n}} \right)^m K_m[X_1 + \cdots + X_n] """, font_size=42) rhs[R"\left({1 \over \sigma \sqrt{n}} \right)"].set_color(YELLOW) lhs.next_to(implies, DOWN, buff=0.5) self.play( FadeOut(var_example, UP), FadeOut(scaling_equation, UP), MoveToTarget(scaling_rule), ) self.play( Write(implies), TransformFromCopy(cumulant_of_clt_var, lhs), ) denom = lhs[-5:-1] self.play( FlashAround(denom), denom.animate.set_color(YELLOW) ) self.wait() center_point = lhs.get_center() + LEFT rhs.next_to(center_point, RIGHT, buff=0.1) self.play( lhs.animate.next_to(center_point, LEFT, 0.1), TransformMatchingShapes(lhs.copy(), rhs), ) self.wait() # Expand sum K_of_sum = rhs[R"K_m[X_1 + \cdots + X_n]"] K_of_sum_rect = SurroundingRectangle(K_of_sum, buff=0.1) K_of_sum_rect.set_stroke(BLUE, 2) sum_of_K = Tex(R"K_m[X_1] + \cdots + K_m[X_n]", font_size=42) nK = Tex(R"n \cdot K_m[X]", font_size=42) equals = Tex("=").rotate(90 * DEGREES).replicate(2) stack = VGroup(equals[0], sum_of_K, equals[1], nK) stack.arrange(DOWN) stack.next_to(K_of_sum_rect, DOWN) self.play(ShowCreation(K_of_sum_rect)) self.wait() self.play( Write(equals[0]), TransformMatchingShapes(K_of_sum.copy(), sum_of_K, run_time=1.5) ) self.wait() self.play( Write(equals[1]), TransformMatchingTex(sum_of_K.copy(), nK, run_time=1.5), cgf_of_clt_sum.animate.set_height(0.75).shift(3 * LEFT) ) self.wait() nK.target = nK.generate_target() nK.target.move_to(K_of_sum, LEFT) self.play( MoveToTarget(nK), FadeOut(equals, UP), FadeOut(sum_of_K, UP), FadeOut(K_of_sum, UP), K_of_sum_rect.animate.match_points(SurroundingRectangle(nK.target)) ) self.play( FadeOut(K_of_sum_rect), ) self.wait() # Emphasize expression cumulant_of_clt_var_equation = VGroup( lhs, rhs[re.compile(r"=.*\^m")], nK ) full_rect = SurroundingRectangle(cumulant_of_clt_var_equation, buff=0.5) full_rect.set_stroke(TEAL, 3) words = TexText(f"Excellent! This is a complete(?) description of ${clt_var_tex}$") words.next_to(full_rect, UP, buff=MED_LARGE_BUFF) self.play( ShowCreation(full_rect), FadeOut(scaling_rule, UP), FadeOut(implies, 2 * UP), ) self.play(Write(words)) self.wait() # Clean up clean_rhs = Tex(R""" \frac{1}{\sigma^m} \frac{n}{n^{m / 2}} K_m[X] """) self.play( FadeOut(words, UP), FadeOut(full_rect, 2 * UP), FadeOut(cgf_of_clt_sum), cumulant_of_clt_var_equation.animate.to_edge(UP), ) self.wait() class ConnectingArrow(InteractiveScene): def construct(self): # Test arrow = CubicBezier( np.array([-0.5, -3.33, 0]), np.array([3, -3.33, 0]), np.array([-1, 1.0, 0]), np.array([0.7, 1.85, 0]), ) arrow.set_stroke(RED_E, 8) line = Line(*arrow.get_points()[-2:]) line.add_tip() tip = line.tip tip.shift(0.25 * line.get_vector()) tip.set_fill(RED_E, 1) label = TexText(R"$m^{\text{th}}$ cumulant of $\frac{X_1 + \cdots + X_n}{\sigma \sqrt{n}}$") label.set_fill(RED_E) label.set_stroke(BLACK, 2, background=True) label.next_to(arrow.pfp(0.5), RIGHT, SMALL_BUFF) self.play( ShowCreation(arrow), FadeIn(tip, time_span=(0.8, 1.0)) ) self.play(Write(label, stroke_color=BLACK, lag_ratio=0.2)) self.wait() class PictureCharacteristicFunction(InteractiveScene): def construct(self): pass
from manim_imports_ext import * from _2023.clt.main import * # Galton board class GaltonBoard(InteractiveScene): random_seed = 1 pegs_per_row = 15 n_rows = 5 spacing = 1.0 top_buff = 1.0 peg_radius = 0.1 ball_radius = 0.1 bucket_floor_buff = 1.0 bucket_style = dict( fill_color=GREY_D, fill_opacity=1.0, ) stack_ratio = 1.0 fall_factor = 0.6 # clink_sound = "click.wav" clink_sound = "plate.wav" def setup(self): super().setup() self.ball_template = Sphere( radius=self.ball_radius, color=YELLOW, resolution=(51, 26), ) self.ball_template.rotate(90 * DEGREES, RIGHT) self.ball_template.set_shading(0.25, 0.5, 0.5) # ball = TrueDot(radius=self.ball_radius, color=color) # ball.make_3d() def construct(self): # Setup pegs = self.get_pegs() buckets = self.get_buckets(pegs) self.play( LaggedStartMap(Write, buckets), LaggedStartMap(Write, pegs), ) self.wait() # Initial flurry balls = self.drop_n_balls(25, pegs, buckets, sound=True) self.wait() balls.reverse_submobjects() self.play(FadeOut(balls, lag_ratio=0.05)) for bucket in buckets: bucket.balls.clear() bucket.bottom.match_y(bucket[0].get_bottom()) # Single ball bouncing, step-by-step ball = self.get_ball() bits = np.random.randint(0, 2, self.n_rows) full_trajectory, pieces = self.random_trajectory(ball, pegs, buckets, bits) all_arrows = VGroup() for piece, bit in zip(pieces, bits): ball.move_to(piece.get_end()) pm_arrows = self.get_pm_arrows(ball) self.play(self.falling_anim(ball, piece)) self.add_single_clink_sound() self.play(FadeIn(pm_arrows, lag_ratio=0.1)) all_arrows.add(pm_arrows) self.wait() self.play(pm_arrows[1 - bit].animate.set_opacity(0.25)) for piece in pieces[-2:]: self.play(self.falling_anim(ball, piece)) self.wait() # Add up arrows corner_sum_anim, corner_sum_fade = self.show_corner_sum(all_arrows, bits) self.play(corner_sum_anim) self.wait() # Show buckets as sums sums = range(-self.pegs_per_row + 2, self.pegs_per_row, 2) sum_labels = VGroup(*( Integer(s, font_size=24, include_sign=True) for s in sums )) for bucket, label in zip(buckets, sum_labels): label.next_to(bucket, DOWN, SMALL_BUFF) sum_labels.set_stroke(WHITE, 1) self.play(Write(sum_labels)) self.wait() for bucket, label in zip(buckets, sum_labels): bucket.add(label) self.play( FadeOut(all_arrows, lag_ratio=0.025), corner_sum_fade ) # Show a few more trajectories with cumulative sum for x in range(3): ball = self.get_ball() bits = np.random.randint(0, 2, self.n_rows) full_trajectory, pieces = self.random_trajectory(ball, pegs, buckets, bits) all_arrows = VGroup() self.add(all_arrows) for piece, bit in zip(pieces, bits): ball.move_to(piece.get_end()) arrows = self.get_pm_arrows(ball) all_arrows.add(arrows) self.play(self.falling_anim(ball, piece)) self.add_single_clink_sound() arrows[1 - bit].set_opacity(0.25) corner_sum_anim, corner_sum_fade = self.show_corner_sum(all_arrows, bits) self.play(self.falling_anim(ball, pieces[-2])) self.add_single_clink_sound() self.play( self.falling_anim(ball, pieces[-1]), corner_sum_anim, ) self.wait() self.play( FadeOut(all_arrows, lag_ratio=0.025), corner_sum_fade ) # Show a flurry self.drop_n_balls(25, pegs, buckets) # Fade out irrelevant parts n = self.pegs_per_row // 2 to_fade = VGroup() peg_triangle = VGroup() for row in range(self.n_rows): r2 = row // 2 low = n - r2 high = n + 1 + r2 + (row % 2) to_fade.add(pegs[row][:low]) to_fade.add(pegs[row][high:]) peg_triangle.add(pegs[row][low:high]) to_fade.add(buckets[:n - 3]) to_fade.add(buckets[n + 3:]) self.play(to_fade.animate.set_opacity(0.25), lag_ratio=0.01) # Show relevant probabilities point = peg_triangle[0][0].get_top() + MED_SMALL_BUFF * UP v1 = peg_triangle[1][0].get_center() - peg_triangle[0][0].get_center() v2 = peg_triangle[1][1].get_center() - peg_triangle[1][0].get_center() def get_peg_label(n, k, split=False): kw = dict(font_size=16) if n == 0: label = Tex("1", font_size=24) elif split and 0 < k < n: label = VGroup( Tex(f"{choose(n - 1, k - 1)} \\over {2**n}", **kw), Tex(f" + {{{choose(n - 1, k)} \\over {2**n}}}", **kw), ) label.arrange(RIGHT, buff=0.75 * label[0].get_width()) else: label = VGroup(Tex(f"{choose(n, k)} \\over {2**n}", **kw)) label.move_to(point + n * v1 + k * v2) return label last_labels = VGroup(get_peg_label(0, 0)) self.play(FadeIn(last_labels)) for n in range(1, self.n_rows + 1): globals().update(locals()) split_labels = VGroup(*(get_peg_label(n, k, split=True) for k in range(n + 1))) unsplit_labels = VGroup(*(get_peg_label(n, k, split=False) for k in range(n + 1))) anims = [ TransformFromCopy(last_labels[0], split_labels[0]), TransformFromCopy(last_labels[-1], split_labels[-1]) ] for k in range(1, n): anims.append(TransformFromCopy(last_labels[k - 1], split_labels[k][0])) anims.append(TransformFromCopy(last_labels[k], split_labels[k][1])) self.play(*anims) self.play(*( FadeTransformPieces(sl1, sl2) for sl1, sl2 in zip(split_labels, unsplit_labels) )) last_labels = unsplit_labels # Larger flurry all_balls = Group() for bucket in buckets: bucket.bottom.match_y(bucket[0].get_bottom()) all_balls.add(*bucket.balls) bucket.balls.clear() self.play(LaggedStartMap(FadeOut, all_balls, run_time=1)) self.stack_ratio = 0.125 np.random.seed(0) self.drop_n_balls(250, pegs, buckets, lr_factor=2) self.wait(2) def get_pegs(self): row = VGroup(*( Dot(radius=self.peg_radius).shift(x * self.spacing * RIGHT) for x in range(self.pegs_per_row) )) rows = VGroup(*( row.copy().shift(y * self.spacing * DOWN * math.sqrt(3) / 2) for y in range(self.n_rows) )) rows[1::2].shift(0.5 * self.spacing * LEFT) rows.set_fill(GREY_C, 1) rows.set_shading(0.5, 0.5) rows.center() rows.to_edge(UP, buff=self.top_buff) return rows def get_buckets(self, pegs): # Buckets points = [dot.get_center() for dot in pegs[-1]] height = 0.5 * FRAME_HEIGHT + pegs[-1].get_y() - self.bucket_floor_buff buckets = VGroup() for point in points: # Fully construct bucket here width = 0.5 * self.spacing - self.ball_radius buff = 0.7 p0 = point + 0.5 * self.spacing * DOWN + buff * width * RIGHT p1 = p0 + height * DOWN p2 = p1 + (1 - buff) * width * RIGHT y = point[1] - 0.5 * self.spacing * math.sqrt(3) + self.ball_radius p3 = p2[0] * RIGHT + y * UP side1 = VMobject().set_points_as_corners([p0, p1, p2, p3, p0]) side1.set_stroke(WHITE, 0) side1.set_style(**self.bucket_style) side2 = side1.copy() side2.flip(about_point=point) side2.reverse_points() side2.shift(self.spacing * RIGHT) floor = Line(side1.get_corner(DR), side2.get_corner(DL)) floor.set_stroke(GREY_D, 1) bucket = VGroup(side1, side2, floor) bucket.set_shading(0.25, 0.25) # Add bottom reference bucket.bottom = VectorizedPoint(floor.get_center()) bucket.add(bucket.bottom) # Keep track of balls bucket.balls = Group() buckets.add(bucket) self.add(buckets) return buckets def get_ball_arrows(self, ball, labels, sub_labels=[], colors=[RED, BLUE]): arrows = VGroup() for vect, color, label in zip([LEFT, RIGHT], colors, labels): arrow = Vector( 0.5 * self.spacing * vect, tip_width_ratio=3, stroke_color=color ) arrow.next_to(ball, vect, buff=0.1) arrows.add(arrow) text = TexText(label, font_size=28) text.next_to(arrow, UP, SMALL_BUFF) arrow.add(text) # Possibly add smaller labels for arrow, label in zip(arrows, sub_labels): text = Text(label, font_size=16) text.next_to(arrow, DOWN, SMALL_BUFF) arrow.add(text) return arrows def get_fifty_fifty_arrows(self, ball): return self.get_ball_arrows(ball, ["50%", "50%"]) def get_pm_arrows(self, ball, show_prob=True): return self.get_ball_arrows( ball, ["$-1$", "$+1$"], sub_labels=(["50%", "50%"] if show_prob else []) ) def show_corner_sum(self, pm_arrows, bits, font_size=48): # Test parts = VGroup(*( arrow[bit][0].copy() for arrow, bit in zip(pm_arrows, bits) )) parts.target = parts.generate_target() parts.target.arrange(RIGHT, buff=0.1) parts.target.scale(font_size / 28) parts.target.to_edge(UP, buff=MED_SMALL_BUFF) parts.target.to_edge(LEFT) anim1 = MoveToTarget(parts, lag_ratio=0.01) sum_term = Tex(f"= {2 * sum(bits) - len(bits)}", font_size=font_size) sum_term.next_to(parts.target, RIGHT, buff=0.1, aligned_edge=UP) anim2 = LaggedStart(*( ReplacementTransform( part.copy().set_opacity(0), sum_term, path_arc=-30 * DEGREES ) for part in parts.target )) return Succession(anim1, anim2), FadeOut(VGroup(parts, sum_term)) def get_ball(self, color=YELLOW_E): ball = TrueDot(radius=self.ball_radius, color=color) ball.make_3d() ball.set_shading(0.5, 0.5, 0.2) return ball def single_bounce_trajectory(self, ball, peg, direction): sgn = np.sign(direction[0]) trajectory = FunctionGraph( lambda x: -x * (x - 1), x_range=(0, 2, 0.2), ) p1 = peg.get_top() p2 = p1 + self.spacing * np.array([sgn * 0.5, -0.5 * math.sqrt(3), 0]) vect = trajectory.get_end() - trajectory.get_start() for i in (0, 1): trajectory.stretch((p2 - p1)[i] / vect[i], i) trajectory.shift(p1 - trajectory.get_start() + 0.5 * ball.get_height() * UP) return trajectory def random_trajectory(self, ball, pegs, buckets, bits=None): index = len(pegs[0]) // 2 radius = ball.get_height() / 2 peg = pegs[0][index] top_line = ParametricCurve(lambda t: t**2 * DOWN) top_line.move_to(peg.get_top() + radius * UP, DOWN) bounces = [] if bits is None: bits = np.random.randint(0, 2, self.n_rows) for row, bit in enumerate(bits): peg = pegs[row][index] bounces.append(self.single_bounce_trajectory(ball, peg, [LEFT, RIGHT][bit])) index += bit if row % 2 == 1: index -= 1 bucket = buckets[index + (0 if self.n_rows % 2 == 0 else -1)] final_line = Line( bounces[-1].get_end(), bucket.bottom.get_center() + self.ball_radius * UP ) final_line.insert_n_curves(int(8 * final_line.get_length())) bucket.bottom.shift(2 * self.ball_radius * self.stack_ratio * UP) bucket.balls.add(ball) result = VMobject() pieces = VGroup(top_line, *bounces, final_line) for vmob in pieces: if result.get_num_points() > 0: vmob.shift(result.get_end() - vmob.get_start()) result.append_vectorized_mobject(vmob) return result, pieces def falling_anim(self, ball, trajectory): return MoveAlongPath( ball, trajectory, rate_func=linear, run_time=self.fall_factor * trajectory.get_arc_length() ) def add_single_clink_sound(self, time_offset=0, gain=-20): self.add_sound( sound_file=self.clink_sound.replace("click", "click" + str(random.randint(1, 12))), time_offset=time_offset, gain=gain, ) def add_falling_clink_sounds(self, trajectory_pieces, time_offset=0, gain=-20): total_len = trajectory_pieces[0].get_arc_length() for piece in trajectory_pieces[1:-1]: self.add_single_clink_sound(time_offset + self.fall_factor * total_len, gain) total_len += piece.get_arc_length() def drop_n_balls(self, n, pegs, buckets, lr_factor=1, sound=False): # Test balls = Group(*(self.get_ball() for x in range(n))) trajs = [ self.random_trajectory(ball, pegs, buckets) for ball in balls ] anims = ( self.falling_anim(ball, traj[0]) for ball, traj in zip(balls, trajs) ) full_anim = LaggedStart(*anims, lag_ratio=lr_factor / n) # Add sounds if sound: start_times = [tup[1] for tup in full_anim.anims_with_timings] for time, traj in zip(start_times, trajs): self.add_falling_clink_sounds(traj[1], time + 0.00 * random.random(), gain=-30) self.play(full_anim) return balls class EmphasizeMultipleSums(GaltonBoard): def construct(self): pegs = self.get_pegs() buckets = self.get_buckets(pegs) self.add(pegs, buckets) # Show a trajectories with cumulative sum for x in range(20): ball = self.get_ball() bits = np.random.randint(0, 2, self.n_rows) full_trajectory, pieces = self.random_trajectory(ball, pegs, buckets, bits) all_arrows = VGroup() self.add(all_arrows) for piece, bit in zip(pieces, bits): ball.move_to(piece.get_end()) arrows = self.get_pm_arrows(ball) all_arrows.add(arrows) self.play(self.falling_anim(ball, piece)) self.add_single_clink_sound() arrows[1 - bit].set_opacity(0.25) self.play(self.falling_anim(ball, pieces[-2])) self.add_single_clink_sound() self.play( self.falling_anim(ball, pieces[-1]), FadeOut(all_arrows) ) class GaltonTrickle(GaltonBoard): def construct(self): frame = self.frame pegs = self.get_pegs() buckets = self.get_buckets(pegs) self.add(pegs, buckets) ball = self.get_ball() peg = pegs[0][len(pegs[0]) // 2] ball.move_to(peg.get_top(), DOWN) arrows = self.get_pm_arrows(ball) frame.set_height(3, about_edge=UP) # Drops n = 25 balls = Group(*(self.get_ball() for x in range(n))) all_bits = [np.random.randint(0, 2, self.n_rows) for x in range(n)] trajs = [ self.random_trajectory(ball, pegs, buckets, bits) for ball, bits in zip(balls, all_bits) ] falling_anims = ( self.falling_anim(ball, traj[0]) for ball, traj in zip(balls, trajs) ) arrow_copies = VGroup() for bits in all_bits: ac = arrows.copy() ac[1 - bits[0]].set_opacity(0.2) arrow_copies.add(ac) rt = 60 arrows.set_opacity(1) self.add(arrows) self.play( LaggedStart(*falling_anims, lag_ratio=0.4, run_time=rt), # ShowSubmobjectsOneByOne(arrow_copies, run_time=1.0 * rt), ) self.wait() class BiggerGaltonBoard(GaltonBoard): random_seed = 0 pegs_per_row = 30 n_rows = 13 spacing = 0.5 top_buff = 0.5 peg_radius = 0.025 ball_radius = 0.05 bucket_floor_buff = 0.5 stack_ratio = 0.1 n_balls = 800 def construct(self): # Setup pegs = self.get_pegs() buckets = self.get_buckets(pegs) self.add(pegs, buckets) # Drop! self.drop_n_balls(self.n_balls, pegs, buckets, lr_factor=2) self.wait() # Show low bell cuve full_rect = FullScreenFadeRectangle() full_rect.set_fill(BLACK, 0.5) balls = self.mobjects[-1] curve = FunctionGraph(lambda x: gauss_func(x, 0, 1)) curve.set_stroke(YELLOW) curve.move_to(balls, DOWN) curve.match_height(balls, stretch=True, about_edge=DOWN) formula = Tex(R"{1 \over \sqrt{2\pi}} e^{-x^2 / 2}", font_size=60) formula.move_to(balls, LEFT) formula.shift(1.25 * LEFT) formula.set_backstroke(width=8) self.add(full_rect, balls) self.play( FadeIn(full_rect), ShowCreation(curve, run_time=2), Write(formula) ) self.wait() class SingleDropBigGaltonBoard(BiggerGaltonBoard): spacing = 0.55 ball_radius = 0.075 def construct(self): # Setup pegs = self.get_pegs() buckets = self.get_buckets(pegs) self.add(pegs, buckets) # Single ball bouncing, step-by-step ball = self.get_ball() full_trajectory, pieces = self.random_trajectory(ball, pegs, buckets) self.add_falling_clink_sounds(pieces) self.play(self.falling_anim(ball, full_trajectory)) self.wait() class NotIdenticallyDistributed(GaltonBoard): def construct(self): # Setup pegs = self.get_pegs() buckets = self.get_buckets(pegs) self.add(pegs, buckets) # Arrows to show distributions max_arrow_len = 0.5 def get_peg_arrow(peg, angle, length, color=RED_E): vect = np.array([-math.sin(angle), math.cos(angle), 0]) arrow = FillArrow( ORIGIN, length * vect, buff=0, fill_color=color, tip_width_ratio=3, thickness=0.025, ) arrow.shift(peg.get_center() + vect * peg.get_radius()) arrow.set_fill(opacity=0.8 * length / max_arrow_len) return arrow def get_bounce_distribution(peg, sigma=30 * DEGREES): ds = sigma / 2 angles = np.arange(-2 * sigma, 2 * sigma + ds, ds) denom = math.sqrt(2 * PI) * sigma arrows = VGroup(*( get_peg_arrow(peg, angle, denom * gauss_func(angle, 0, sigma) * max_arrow_len) for angle in angles )) return arrows # Show many distributions all_dists = VGroup(*( get_bounce_distribution(peg) for row in pegs for peg in row )) all_dists.set_fill(RED_E, 0.8) self.play(LaggedStart(*( LaggedStartMap(GrowArrow, dist) for dist in all_dists ))) self.wait() # Zoom in to top one ball = self.get_ball() peg1 = pegs[0][len(pegs[0]) // 2] peg2 = pegs[1][len(pegs[1]) // 2] frame = self.frame peg1_dist = get_bounce_distribution(peg1) peg2_dist = get_bounce_distribution(peg2) peg1_dist.rotate(30 * DEGREES, about_point=peg1.get_center()) peg2_dist.rotate(-30 * DEGREES, about_point=peg2.get_center()) full_trajectory, pieces = self.random_trajectory(ball, pegs, buckets, [0, 1, 0, 0, 0]) pieces[0].move_to(peg1.pfp(3 / 8) + ball.get_radius() * UP, DOWN) pieces[1].stretch(0.7, 0) pieces[1].shift(pieces[0].get_end() - pieces[1].get_start()) pieces[2].stretch(0.9, 0) pieces[2].stretch(0.97, 1) pieces[2].shift(pieces[1].get_end() - pieces[2].get_start()) self.play( frame.animate.set_height(3, about_edge=UP), FadeOut(all_dists, lag_ratio=0.01), self.falling_anim(ball, pieces[0]), run_time=2, ) self.add(peg1_dist, ball) self.play(LaggedStartMap(FadeIn, peg1_dist)) self.wait() self.play(self.falling_anim(ball, pieces[1]), run_time=1) self.play(LaggedStartMap(FadeIn, peg2_dist)) self.wait() self.play(self.falling_anim(ball, pieces[2]), run_time=1) self.wait(2)
from manim_imports_ext import * from _2023.clt.main import * # Dice Simulations class DiceSimulation(InteractiveScene): n_dice = 10 n_samples = 3000 distribution = [1 / 6] * 6 die_distribution_config = dict( axes_config=dict(width=3.5, height=1.5), y_range=(0, 0.5, 0.25), ) brick_height = 0.2 initial_brick_color = YELLOW full_dist_color = GREEN_D spread = 22 dice_width = 5 def setup(self): super().setup() self.add_die_distribution() self.add_sum_axes() self.add_sample_label() self.buckets = dict() self.all_bricks = VGroup() def construct(self): # Slow samples for _ in range(3): self.run_one_sum() # Speedier samples for _ in range(10): self.run_one_sum(run_time=0.5, transition_time=0.5) # First few instant samples for _ in range(200): self.run_one_sum(transition_time=1 / 30, still_frame=True) # Thousands of samples self.scale_brick_height(0.1) for _ in range(self.n_samples - int(self.sample_label.count.get_value())): self.run_one_sum(transition_time=1 / 30, still_frame=True) self.play(self.all_bricks.animate.set_fill(color=self.full_dist_color)) def add_die_distribution(self, animate=False): die_dist = get_die_distribution_chart( self.distribution, **self.die_distribution_config, ) die_dist.to_corner(UL) die_dist.shift(0.25 * DOWN) axes, bars, dice = die_dist if animate: self.play( Write(axes), LaggedStartMap(GrowFromEdge, bars, edge=DOWN), Write(dice), ) self.add(die_dist) self.die_dist = die_dist def add_sum_axes(self): # (Value, probability) pairs vps = list(zip(it.count(1), self.distribution)) mu = sum(v * p for v, p in vps) var = sum(p * (v - mu)**2 for v, p in vps) n = self.n_dice x_mid = int(n * mu) spread = self.spread or int(2.5 * math.sqrt(var * n)) x_range = (x_mid - spread, x_mid + spread, 1) axes = Axes( x_range, (0, int(math.sqrt(self.n_samples))), width=FRAME_WIDTH - 1, height=4, ) # dots = Tex(R"\dots", font_size=24) # dots.next_to(axes.x_axis, LEFT, SMALL_BUFF) # axes.y_axis.set_x(dots.get_left()[0] - SMALL_BUFF) # axes.add(dots) x_axis = axes.x_axis x_axis.add_numbers(font_size=16) x_axis.numbers.remove(x_axis.numbers[-1]) x_axis.numbers.shift( 0.5 * x_axis.get_unit_size() * RIGHT + \ 0.1 * UP ) # axes.center() # axes.to_edge(DOWN) x_axis.center() x_axis.to_edge(DOWN) self.add(x_axis) self.sum_axes = axes self.sum_axis = x_axis def add_sample_label(self): label = TexText(R"\# Sums = 0", font_size=36) label.set_fill(GREY_B) label.to_edge(LEFT) label.count = label.make_number_changable("0") label.count.edge_to_fix = LEFT self.add(label) self.sample_label = label def run_one_sum(self, run_time=3.0, transition_time=1.0, still_frame=False): # Setup sample values = list(range(1, 7)) bars = self.die_dist.bars samples = np.random.choice(values, size=self.n_dice, p=self.distribution) dice = VGroup(*(DieFace(sample) for sample in samples)) dice.arrange_in_grid(n_cols=5) dice.set_width(self.dice_width) dice.to_corner(UR) bar_highlights = VGroup(*( bars[sample - 1].copy() for sample in samples )) bar_highlights.set_fill(YELLOW, 1) face_counts = [0] * len(self.distribution) for sample in samples: face_counts[sample - 1] += 1 # Tips tips = get_sample_markers(bars, samples) def get_sum(): return sum(d.value for d in dice) # Sum label sum_label = TexText(f"Sum = 0") sum_label.count = sum_label.make_number_changable(0) sum_label.next_to(dice, DOWN, buff=MED_LARGE_BUFF) sum_label.count.set_value(get_sum()) # Mark the sample brick = self.get_brick() s = get_sum() if s not in self.buckets: self.buckets[s] = VGroup(VectorizedPoint( self.sum_axis.n2p(s + 0.5) )) bucket = self.buckets[s] brick.next_to(bucket, UP, buff=0) count_copy = sum_label.count.copy() count_copy.target = bucket[0] for number in self.sum_axis.numbers: if number.get_value() == sum_label.count.get_value(): sum_label.count.target = number break # Animate! if still_frame: self.all_bricks.set_fill(color=self.full_dist_color) self.sample_label.count.increment_value() self.add(dice, brick, sum_label, tips) self.wait(transition_time) self.remove(dice, sum_label, tips) else: self.play( ShowIncreasingSubsets(dice, int_func=np.ceil), ShowIncreasingSubsets(tips, int_func=np.ceil), ShowSubmobjectsOneByOne(bar_highlights, remover=True), UpdateFromFunc(sum_label, lambda m: m.count.set_value(get_sum())), self.all_bricks.animate.set_fill(color=self.full_dist_color), run_time=run_time, ) self.wait(transition_time) self.play( FadeInFromPoint(brick, count_copy.get_center()), MoveToTarget(count_copy), FadeOut(sum_label, lag_ratio=0.1), FadeOut(dice, lag_ratio=0.1), FadeOut(tips, lag_ratio=0.1), run_time=transition_time ) self.sample_label.count.increment_value() self.wait(transition_time) self.buckets[s].add(brick) self.all_bricks.add(brick) self.add(self.all_bricks) def scale_brick_height(self, scale_factor): self.brick_height *= scale_factor bricks = self.all_bricks bricks.target = bricks.generate_target() bricks.target.stretch(scale_factor, 1, about_edge=DOWN) bricks.target.set_stroke(width=scale_factor * bricks[0].get_stroke_width()) self.play(MoveToTarget(bricks), run_time=3) self.wait() def get_brick(self): return Rectangle( stroke_width=self.brick_height * 5, stroke_color=BLACK, fill_color=self.initial_brick_color, fill_opacity=1, height=self.brick_height, width=0.8 * self.sum_axis.get_unit_size() ) class DiceSimulationAlt1(DiceSimulation): random_seed = 1 class DiceSimulationAlt2(DiceSimulation): random_seed = 2 class DiceSimulationAlt3(DiceSimulation): random_seed = 3 class DiceSimulationAlt4(DiceSimulation): random_seed = 4 class DiceSimulationAlt5(DiceSimulation): random_seed = 5 class LargerDiceSimulation(DiceSimulation): n_samples = 3000 brick_height = 0.02 random_seed = 1 def construct(self): # Larger sample for _ in range(self.n_samples): self.run_one_sum(transition_time=1 / 30, still_frame=True) class SimulationWithUShapedDistribution(DiceSimulation): random_seed = 1 distribution = U_SHAPED_DISTRIBUTION brick_height = 0.2 n_samples = 3000 def construct(self): # Transition tmp_dist = self.distribution tmp_die_dist = self.die_dist self.remove(tmp_die_dist) self.distribution = self.__class__.__base__.distribution self.add_die_distribution() self.play(Transform(self.die_dist, tmp_die_dist, run_time=3)) self.distribution = tmp_dist # First few samples for _ in range(2): self.run_one_sum() for _ in range(6): self.run_one_sum(run_time=0.5, transition_time=0.5) for _ in range(300): self.run_one_sum(transition_time=1 / 30, still_frame=True) # Thousands of samples self.scale_brick_height(0.1) for _ in range(self.n_samples - int(self.sample_label.count.get_value())): self.run_one_sum(transition_time=1 / 30, still_frame=True) self.play(self.all_bricks.animate.set_fill(color=self.full_dist_color)) class LargerUSimulation(SimulationWithUShapedDistribution): n_samples = 10000 brick_height = 0.01 def construct(self): # Thousands of samples for _ in range(self.n_samples): self.run_one_sum(transition_time=1 / 30, still_frame=True) def get_brick(self): return super().get_brick().set_stroke(width=0) class SteeperUDistributionSimulation(SimulationWithUShapedDistribution): distribution = STEEP_U_SHAPED_DISTRIBUTION class SimulationWithSteepUShapedDistribution(LargerUSimulation): distribution = [0.4, 0.075, 0.025, 0.025, 0.075, 0.4] n_samples = 3000 brick_height = 0.02 class SimulationWithExpDistribution(SimulationWithUShapedDistribution): random_seed = 1 distribution = EXP_DISTRIBUTION class SimulationWithExpDistribution2(SimulationWithExpDistribution): random_seed = 2 class SimulationWithExpDistribution2Dice(SimulationWithExpDistribution): n_dice = 2 brick_height = 0.13 dice_width = 2 def get_brick(self): return super().get_brick().set_stroke(width=0) class SimulationWithRandomDistribution(SimulationWithUShapedDistribution): random_seed = 1 n_dice = 15 distribution = [0.05, 0.17, 0.28, 0.05, 0.18, 0.27] class SimulationWithExpDistribution5Dice(SimulationWithExpDistribution): n_dice = 5 brick_height = 0.15 class SimulationWithExpDistribution15Dice(SimulationWithExpDistribution): n_dice = 15
from __future__ import annotations from manim_imports_ext import * from _2023.convolutions2.continuous import * from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence from manimlib.typing import ManimColor EXP_DISTRIBUTION = [0.41, 0.25, 0.15, 0.10, 0.06, 0.03] U_SHAPED_DISTRIBUTION = [0.3, 0.15, 0.05, 0.05, 0.15, 0.3] STEEP_U_SHAPED_DISTRIBUTION = [0.4, 0.075, 0.025, 0.025, 0.075, 0.4] class ChartBars(VGroup): def __init__( self, axes, values: Sequence[float | int], xs: Sequence[float] | None = None, width_ratio: float = 1.0, offset: float = 0.5, fill_color: ManimColor = BLUE, fill_opacity: float = 0.5, stroke_color: ManimColor = WHITE, stroke_width: float = 1.0 ): xs = xs if xs is not None else np.arange(*axes.x_range) self.x_to_index = dict(zip(xs, it.count())) x_step = xs[1] - xs[0] x_unit = axes.x_axis.get_unit_size() y_unit = axes.y_axis.get_unit_size() width = width_ratio * x_unit * x_step # Create a list of rectangles arranged side by side, # one for each x value rects = [] epsilon = 1e-8 for x, y in zip(xs, values): rect = Rectangle( width=width, height=max(y * y_unit, epsilon), fill_color=fill_color, fill_opacity=fill_opacity, stroke_color=stroke_color, stroke_width=stroke_width, ) rect.move_to(axes.c2p(x + offset * x_step, 0), DOWN) rects.append(rect) super().__init__(*rects) self.axes = axes self.xs = xs self.set_values(values) def set_values(self, values: Iterable[float | int]): y_unit = self.axes.y_axis.get_unit_size() for rect, value in zip(self, values): rect.set_height( y_unit * value, stretch=True, about_edge=DOWN, ) def get_die_distribution_chart( dist: list[float], die_config=dict(), axes_config=dict( width=4, height=3, ), font_size=25, y_range=(0, 1, 0.2), max_value: int = 6, bar_colors=(BLUE, TEAL) ): axes = Axes((0, max_value), y_range, **axes_config) ndp = len(str(y_range[2])) - 2 axes.y_axis.add_numbers(font_size=font_size, num_decimal_places=ndp) bars = ChartBars(axes, dist) bars.set_submobject_colors_by_gradient(*bar_colors) dice = VGroup() for n in range(1, max_value + 1): die = DieFace(n, **die_config) die.set_width(0.5 * axes.x_axis.get_unit_size()) die.next_to(axes.c2p(n - 0.5, 0), DOWN, SMALL_BUFF) dice.add(die) result = VGroup(axes, bars, dice) result.axes = axes result.bars = bars result.dice = dice return result def get_sample_markers(bars, samples): width = 0.25 * bars[0].get_width() tips = ArrowTip(angle=-90 * DEGREES).replicate(len(samples)) tips.set_width(width) tips.set_height(0.5 * width, stretch=True) tips.set_fill(YELLOW, 1) tip_map = [VGroup() for b in bars] for sample, tip in zip(samples, tips): tip_map[sample - 1].add(tip) for value, group in enumerate(tip_map): group.arrange(UP, buff=0.5 * width) group.next_to(bars[value], UP, SMALL_BUFF) return tips def get_dist(bars): result = np.array([bar.get_height() for bar in bars]) return result / result.sum() def get_mean_and_sd(dist, x_min=1): mean = sum(p * (n + x_min) for n, p in enumerate(dist)) sd = math.sqrt(sum(p * (n + x_min - mean)**2 for n, p in enumerate(dist))) return mean, sd def gauss_func(x, mu, sigma): pre_factor = 1 / (sigma * math.sqrt(2 * PI)) return pre_factor * np.exp(-0.5 * ((x - mu) / sigma)**2) # Composite distributions class RandomDieRolls(InteractiveScene): def construct(self): n_runs = 30 n_movements_per_run = 30 faces = VGroup(*( DieFace(n, fill_color=BLUE_E, dot_color=WHITE) for n in range(1, 7) )) for x in range(n_runs): random_faces = VGroup(*( random.choice(faces).copy() for x in range(n_movements_per_run) )) for face in random_faces: face.shift(np.random.uniform(-0.1, 0.1, 3)) self.play(ShowSubmobjectsOneByOne(random_faces, run_time=1)) self.wait() self.remove(random_faces) class DiceSumDistributions(InteractiveScene): distribution = [1 / 6] * 6 max_plot_width = 10 n_examples = 7 values = list(range(1, 7)) def construct(self): # Setup all plots plots = VGroup(*( self.get_sum_distribution_plot( n, y_max=(0.2 if n > 1 else 0.5) ) for n in range(1, self.n_examples + 1) )) plots.scale(0.9) plots.arrange(DOWN, buff=1.0, aligned_edge=LEFT) plots.to_corner(UL) labels = VGroup(*( self.get_plot_label(plot, n, die_face=True) for plot, n in zip(plots, it.count(1)) )) # n = 1 distribution plot1 = plots[0] plot1.save_state() plot1.set_height(4) plot1.center() dice = self.get_dice_axis_labels(plot1) axes, bars = plot1 prob_labels = Tex(r"1 / 6").replicate(6) for label, bar in zip(prob_labels, bars): label.set_width(0.5 * bar.get_width()) label.next_to(bar, UP) self.add(plot1, dice) self.play(Write(prob_labels)) self.wait() axes.add(dice, prob_labels) plot1.generate_target() plot1.target.replace(plot1.saved_state) # Grid of dice to bar chart grid = Square().get_grid(6, 6, buff=0) grid.set_stroke(GREY, 2) grid.set_height(5.5) grid.to_corner(UR) plot2 = plots[1] axes, bars = plot2 plot2.save_state() plot2.set_width(10) plot2.center().to_edge(DOWN) axes.y_axis.numbers.set_opacity(0) die_groups = [VGroup() for n in range(6)] columns = VGroup(*(VGroup() for n in range(11))) for n, square in enumerate(grid): i = n % 6 j = n // 6 die1 = dice[i].copy() die2 = dice[j].copy() die2.set_fill(RED_E) die2.dots.set_fill(WHITE) pair = VGroup(die1, die2) pair.arrange(RIGHT, buff=SMALL_BUFF) pair.move_to(square) square.dice = pair columns[i + j].add(square) die_groups[i].add(die1) die_groups[j].add(die2) self.play( MoveToTarget(plot1), LaggedStart(*( TransformFromCopy(VGroup(dice[n]), die_groups[n]) for n in range(6) ), lag_ratio=0.1), Write(grid), run_time=3 ) self.wait() for square in grid: square.add(square.dice) column_targets = VGroup() for column in columns: column.target = column.generate_target() for square in column.target: square.stretch(0.5, 1) square.dice.stretch(2, 1) column.target.arrange(DOWN, buff=0) column_targets.add(column.target) column_targets.arrange(RIGHT, buff=0, aligned_edge=DOWN) column_targets.match_width(bars[1:]) column_targets.move_to(bars[1:], DOWN) bars.match_height(column_targets, stretch=True, about_edge=DOWN) bars.set_opacity(0.25) axes = plot2[0] axes.save_state() axes.set_opacity(0) self.add(axes) for column in columns: ct = column.target self.play(column.animate.set_stroke(YELLOW, 2)) self.play( Transform(column, ct, run_time=1, lag_ratio=0.001), Restore(axes), ) self.add(plot2[1], columns) self.play(FadeIn(plot2[1])) self.add(plot2, columns) self.wait() # n = 2 prob labels prob_labels = VGroup() for column in columns: label = Tex("1 / 36") numer = label.make_number_changable("1") numer.edge_to_fix = RIGHT numer.set_value(len(column)) label.next_to(column, UP, SMALL_BUFF) label.set_width(0.6 * column.get_width()) prob_labels.add(label) self.play(Write(prob_labels)) self.wait() labelled_bars = VGroup(bars, columns, prob_labels) labelled_bars.save_state() highlights = [ VGroup(columns[n - 2], prob_labels[n - 2]).copy() for n in [6, 10] ] last = VMobject() for highlight in highlights: self.play( FadeOut(last), FadeIn(highlight), labelled_bars.animate.set_opacity(0.075) ) last = highlight self.wait() self.play( FadeOut(last), Restore(labelled_bars), ) # Restore columns.generate_target() pre_bars = plot2.saved_state[1][1:] columns.target.replace(pre_bars, stretch=True) columns.target.set_opacity(0) prob_labels.target = prob_labels.generate_target() for bar, label in zip(pre_bars, prob_labels.target): label.set_width(0.6 * bar.get_width()) label.next_to(bar, UP, 0.5 * SMALL_BUFF) self.play( Restore(plot2), MoveToTarget(columns, remover=True), MoveToTarget(prob_labels), FadeIn(labels[:2], lag_ratio=0.2), ) axes.add(prob_labels) self.wait() # Pan through the rest frame = self.frame frame.target = frame.generate_target() for n in range(1, len(plots) - 1): frame.target.match_y(plots[n]) min_width = VGroup(plots[n + 1], labels[n + 1]).get_width() + 1 frame.target.set_width( max(FRAME_WIDTH, min_width), about_edge=LEFT ) self.play(LaggedStart( MoveToTarget(frame, run_time=2), FadeTransform( plots[n].copy().set_opacity(0), plots[n + 1], run_time=2 ), TransformMatchingShapes(labels[n].copy(), labels[n + 1]), lag_ratio=0.2 )) self.wait() frame.target.set_height(FRAME_HEIGHT) frame.target.center() frame.target.set_height(plots.get_height() + 1, about_edge=UL) self.play(MoveToTarget(frame, run_time=2)) # Flash through plot_groups = VGroup(*( VGroup(plot, label) for plot, label in zip(plots, labels) )) for pg in plot_groups: pg.save_state() for pg1 in plot_groups: anims = [] for pg2 in plot_groups: if pg2 is pg1: anims.append(Restore(pg2)) else: anims.append(pg2.animate.restore().fade(0.85)) self.play(*anims) self.play(LaggedStartMap(Restore, plot_groups)) # Comment on center of mass straying to the right? mean_labels = self.get_mean_labels(plots) self.play(frame.animate.set_height(4).move_to(plots[0], DOWN).shift(DOWN)) self.play(Write(mean_labels[0], run_time=1)) self.wait() prob_labels.set_opacity(0) for n in range(6): frame.target = frame.generate_target() frame.target.set_height(plots[:n + 2].get_height() + 2) frame.target.move_to(plots[n + 1], DL).shift(0.75 * DL) self.play(LaggedStart( MoveToTarget(frame), TransformFromCopy(*mean_labels[n:n + 2]), lag_ratio=0.5 )) self.wait() # Comment on distributions becoming more spread out? sd_labels = self.get_sd_labels(plots) for label in sd_labels: label.save_state() label.stretch(0, 0) label.set_opacity(0) self.play( LaggedStartMap(Restore, sd_labels), LaggedStart(*( FadeOut(label[1]) for label in mean_labels )), run_time=3 ) self.wait() self.play(*( FadeOut(label[2]) for label in sd_labels )) self.wait() mean_lines = VGroup(*(ml[0] for ml in mean_labels)) sd_lines = VGroup(*(sl[:2] for sl in sd_labels)) self.add(mean_lines, sd_lines) # Realign all_axes = VGroup(*(plot[0] for plot in plots)) all_bars = VGroup(*(plot[1] for plot in plots)) self.play(FadeOut(all_axes)) self.realign_distributions(all_bars, labels, mean_lines, sd_lines) self.wait() # Rescale self.rescale_distributions(all_bars, mean_lines, sd_lines) # Draw up against normal curve axes = Axes( (-3, 3), (0, 1, 0.25), width=0.45 * frame.get_width(), height=0.18 * frame.get_height(), ) axes.next_to(frame.get_left(), RIGHT, buff=1) axes.x_axis.add_numbers() axes.y_axis.add_numbers(np.arange(0.25, 1.25, 0.25), num_decimal_places=2) graph = axes.get_graph(lambda x: np.exp(-x**2)) graph.set_stroke(YELLOW, 3) graph_label = Tex(R"e^{-x^2}") graph_label.set_height(0.5 * graph.get_height()) graph_label.move_to(graph, UL) self.play( labels.animate.shift(1.5 * RIGHT), all_bars.animate.shift(4.5 * RIGHT), FadeOut(mean_lines, 4.5 * RIGHT), FadeOut(sd_lines, 4.5 * RIGHT), FadeIn(axes), ShowCreation(graph, run_time=2), Write(graph_label) ) self.wait() # Rescale normal curve alt_graph_label = Tex(R"{1 \over \sigma \sqrt{2 \pi}} e^{-x^2 / 2\sigma^2}") alt_graph_label[R"{1 \over \sigma \sqrt{2 \pi}}"].scale(0.75, about_edge=RIGHT) alt_graph_label.set_height(1.25 * graph_label.get_height()) alt_graph_label.move_to(graph_label, DL) mu, sigma = self.get_mean_and_standard_deviation(self.distribution) alt_graph = axes.get_graph( lambda x: (1 / sigma / math.sqrt(2 * PI)) * math.exp(-x**2 / 2 * sigma**2) ) alt_graph.match_style(graph) self.play( Transform(graph, alt_graph), TransformMatchingTex(graph_label, alt_graph_label), run_time=2 ) axes.generate_target() sf = 3.5 axes.target.y_axis.stretch(sf, 1, about_edge=DOWN) for number in axes.target.y_axis.numbers: number.stretch(1 / sf, 1) self.play( MoveToTarget(axes), graph.animate.stretch(sf, 1, about_edge=DOWN), ) self.wait() # Map bell curve over bars graph_copies = VGroup(*( graph.copy().replace( bars[n:], dim_to_match=1 ).set_stroke(width=1.5) for n, bars in zip(it.count(1), all_bars[1:]) )) self.play( LaggedStart(*( TransformFromCopy(graph, graph_copy) for graph_copy in graph_copies )), run_time=3 ) self.wait() def get_plot_label(self, plot, n, die_face=False, height=0.35): # Test if die_face: die = DieFace(1).set_width(height) die.set_fill(BLUE_E) die.remove(*die.dots) terms = die.replicate(min(n, 5)) else: term = Tex("X_0") term.make_number_changable("0") terms = term.replicate(min(n, 5)) for i, term in enumerate(terms): term[1].set_value(i + 1) if n > 5: terms.replace_submobject(2, Tex(R"\cdots")) if not die_face: terms[-2][1].set_value(n - 1) terms[-1][1].set_value(n) label = VGroup() for term in terms[:-1]: label.add(term) label.add(Tex("+")) label.add(terms[-1]) label.arrange(RIGHT, buff=SMALL_BUFF) if n > 5 and die_face: brace = Brace(label, DOWN, SMALL_BUFF) count = brace.get_text(str(n), buff=SMALL_BUFF) label.add(brace, count) label.move_to(plot.get_corner(UR), UL) return label def get_sum_distribution_plot(self, n, **kwargs): return self.get_distribution_plot( self.get_sum_distribution(n), **kwargs ) def get_distribution_plot( self, distribution, x_unit=0.5, height=1.5, bar_colors=(BLUE, TEAL), y_max=None, ): n = len(distribution) if y_max is not None: y_step = 0.1 elif n == len(self.distribution): y_max = 0.5 y_step = 0.1 else: y_max = 0.05 * int(20 * max(distribution) + 2) y_step = 0.1 if y_max > 0.2 else 0.05 axes = Axes( (0, n), (0, y_max, y_step), width=n * x_unit, height=height ) axes.set_stroke(width=1) axes.center() axes.y_axis.add_numbers( num_decimal_places=len(str(y_step)) - 2, font_size=16 ) axes.x_axis.add_numbers( range(1, n + 1), num_decimal_places=0, font_size=int(axes.x_axis.get_unit_size() * 40), buff=0.1 ) axes.x_axis.numbers.shift(0.5 * axes.x_axis.get_unit_size() * LEFT) bars = ChartBars(axes, distribution) bars.set_submobject_colors_by_gradient(*bar_colors) bars.set_stroke(WHITE, 1) plot = VGroup(axes, bars) return plot def get_sum_distribution(self, n): dist0 = [0, *self.distribution] dist = np.array(dist0) for _ in range(n - 1): dist = np.convolve(dist, dist0) return dist[1:] def get_dice_axis_labels(self, plot): axes, bars = plot numbers = axes.x_axis.numbers die_faces = VGroup(*( DieFace( n + 1, fill_color=BLUE_E, dot_color=WHITE, ).replace(number, dim_to_match=1) for n, number in enumerate(numbers) )) for die in die_faces: die.dots.set_stroke(WHITE, 1) die_faces.set_stroke(width=1) return die_faces def get_mean_and_standard_deviation(self, distribution): prob_value_pairs = list(zip(distribution, it.count(1))) mu = sum(p * x for p, x in prob_value_pairs) sigma = math.sqrt(sum(p * (x - mu)**2 for p, x in prob_value_pairs)) return mu, sigma def get_mean_labels(self, plots, color=PINK, num_decimal_places=1): mu = self.get_mean_and_standard_deviation(self.distribution)[0] mean_labels = VGroup() for n, plot in zip(it.count(1), plots): axes = plot[0] label = Tex(fR"{n}\mu = {np.round(n * mu, num_decimal_places)}") if n == 1: label[0].scale(0, about_edge=RIGHT) v_line = Line(*axes.y_axis.get_start_and_end()) v_line.move_to(axes.c2p(n * mu - 0.5, 0), DOWN) label.shift( v_line.get_top() + MED_SMALL_BUFF * UP - label[:2].get_bottom() ) mean_labels.add(VGroup(v_line, label)) mean_labels.set_color(color) return mean_labels def get_sd_labels(self, plots, color=RED): mu, sigma = self.get_mean_and_standard_deviation(self.distribution) sd_labels = VGroup() for n, plot in zip(it.count(1), plots): axes = plot[0] v_lines = Line(*axes.y_axis.get_start_and_end()).replicate(2) v_lines[0].move_to(axes.c2p(n * mu - math.sqrt(n) * sigma - 0.5, 0), DOWN) v_lines[1].move_to(axes.c2p(n * mu + math.sqrt(n) * sigma - 0.5, 0), DOWN) arrows = VGroup( FillArrow(v_lines.get_center(), v_lines[0].get_center()), FillArrow(v_lines.get_center(), v_lines[1].get_center()), ) for arrow in arrows: arrow.scale(0.75) arrows.move_to(v_lines) if n == 1: sigma_label = Tex(fR"\sigma") else: sigma_label = Tex(fR"\sqrt{n} \cdot \sigma") sigma_label.scale(0.8) sigma_label.next_to(arrows[1], UP, SMALL_BUFF) sd_labels.add(VGroup( v_lines, arrows, sigma_label, )) sd_labels.set_color(color) return sd_labels def realign_distributions(self, all_bars, labels, mean_lines, sd_lines): frame = self.frame bar_groups = VGroup() for bars, mean_line, sd_line in zip(all_bars, mean_lines, sd_lines): bar_group = VGroup(bars, mean_line, sd_line) bar_group.target = bar_group.generate_target() bar_group.target.shift( (frame.get_center()[0] - mean_line.get_x()) * RIGHT ) bar_groups.add(bar_group) labels.target = labels.generate_target() for label, bars in zip(labels.target, all_bars): label.match_y(bars) label.set_x(0) labels.target.set_x(frame.get_right()[0] - 1, RIGHT) self.play( MoveToTarget(labels), LaggedStartMap(MoveToTarget, bar_groups, lag_ratio=0.01), run_time=2 ) def rescale_distributions(self, all_bars, mean_lines, sd_lines): arrows = VGroup(*( self.get_rescaling_arrows(bars, n) for n, bars in zip(it.count(2), all_bars[1:]) )) self.play(Write(arrows, lag_ratio=0.01)) def get_factor(n): return math.sqrt(n) self.play( LaggedStart(*( bars.animate.stretch( 1 / get_factor(n), 0, about_point=lines.get_center() ).stretch(get_factor(n), 1, about_edge=DOWN) for n, bars, lines in zip(it.count(2), all_bars[1:], sd_lines) )), LaggedStart(*( lines.animate.stretch( 1 / get_factor(n), 0, ) for n, lines in zip(it.count(2), sd_lines[1:]) )), Animation(mean_lines), LaggedStart(*( arrow.animate.shift(arrow.get_vector()) for arrow_pair in arrows for arrow in arrow_pair )), run_time=3 ) self.wait() self.play(FadeOut(arrows)) def get_center_of_mass_base(self, bars): dist = np.array([bar.get_height() for bar in bars]) dist /= dist.sum() mu = sum(p * x for p, x in zip(dist, it.count())) return bars.get_corner(DL) + mu * bars[0].get_width() * RIGHT def get_rescaling_arrows(self, bars, n): dist = np.array([bar.get_height() for bar in bars]) dist /= dist.sum() mu = sum(p * x for p, x in zip(dist, it.count())) sigma = math.sqrt(sum(p * (x - mu)**2 for p, x in zip(dist, it.count()))) bar_width = bars[0].get_width() length = sigma * bar_width center = bars.get_corner(DL) + mu * bar_width * RIGHT center += bars.get_height() * UP / 2.0 kw = dict(fill_color=RED) arrows = VGroup(*( FillArrow(ORIGIN, length * vect, **kw).move_to( center - 3.0 * sigma * bar_width * vect, -vect ) for vect in [LEFT, RIGHT] )) labels = Tex(Rf"\sigma \sqrt{{{n}}}").replicate(2) for arrow, label in zip(arrows, labels): label.next_to(arrow, UP, buff=0) label.set_max_width(arrow.get_width()) label[R"\sigma"].set_color(RED) arrow.add(label) return arrows def show_sample_sum(self, plot, distribution, n, low_plot=None): axes, bars = plot samples = np.random.choice(self.values, size=n, p=distribution) bar_highlights = VGroup(*( bars[sample - 1].copy() for sample in samples )) bar_highlights.set_fill(YELLOW, 1) if low_plot: low_bar_highlight = low_plot[1][sum(samples) - 1].copy() low_bar_highlight.set_fill(YELLOW, 1) else: low_bar_highlight = VMobject() tips = get_sample_markers(bars, samples) sum_expr = VGroup() for sample in samples: sum_expr.add(Integer(sample)) sum_expr.add(Tex("+")) sum_expr.remove(sum_expr[-1]) sum_expr.add(Tex("=")) sum_expr.add(Integer(sum(samples), color=YELLOW)) sum_expr.arrange(RIGHT, buff=0.15) sum_expr.scale(1.25) sum_expr.next_to(plot, RIGHT, buff=2.5) kw = dict(int_func=np.ceil) self.play( ShowIncreasingSubsets(tips, **kw), ShowSubmobjectsOneByOne(bar_highlights, remover=True, **kw), ShowIncreasingSubsets(sum_expr[0:-1:2], **kw), ShowIncreasingSubsets(sum_expr[1::2], **kw), run_time=0.5 ) self.wait(0.1) self.add(sum_expr) self.add(low_bar_highlight) self.wait() self.play(LaggedStartMap(FadeOut, VGroup(tips, sum_expr, low_bar_highlight)), run_time=0.5) class DiceSumDistributionsExp(DiceSumDistributions): distribution = EXP_DISTRIBUTION class TransitionToSkewDistribution(DiceSumDistributions): def construct(self): # Setup all plots self.distribution = [1 / 6] * 6 plot1 = self.get_sum_distribution_plot(1, y_max=0.5) self.distribution = EXP_DISTRIBUTION plot2 = self.get_sum_distribution_plot(1, y_max=0.5) for plot in plot1, plot2: plot.set_height(4) plot.center() plot[0].x_axis.numbers.set_opacity(0) axes, bars = plot1 dice = self.get_dice_axis_labels(plot1) for die in dice: die.set_width(0.6, about_edge=UP) prob_labels = Tex(r"1 / 6").replicate(6) exp_prob_labels = VGroup(*(DecimalNumber(p) for p in self.distribution)) for bars, labels in [(plot1[1], prob_labels), (plot2[1], exp_prob_labels)]: for bar, label in zip(bars, labels): label.set_width(0.5 * bar.get_width()) label.next_to(bar, UP) self.add(plot1, dice) for bar in plot1[1]: bar.save_state() bar.stretch(0, 1, about_edge=DOWN) self.play( LaggedStartMap(FadeIn, prob_labels, shift=UP), LaggedStartMap(Restore, plot1[1]), ) self.wait() self.play( ReplacementTransform(plot1, plot2, run_time=2), LaggedStart(*( FadeTransform(*labels) for labels in zip(prob_labels, exp_prob_labels) ), lag_ratio=0.05, run_time=2) ) self.wait() self.play( VGroup(plot2, exp_prob_labels, dice).animate.set_height(2).to_corner(UL) ) self.wait() axes.add(dice, prob_labels) class ExpDistSumDistributions(DiceSumDistributions): n_examples = 7 distribution = EXP_DISTRIBUTION def construct(self): # Setup all plots distributions = [ [1 / 6] * 6, list(self.distribution), ] plots_list = VGroup() for dist in distributions: self.distribution = dist plots = VGroup(*( self.get_sum_distribution_plot( n, y_max=(0.2 if n > 1 else 0.4) ) for n in range(1, self.n_examples + 1) )) plots.scale(0.9) plots.arrange(DOWN, buff=1.0, aligned_edge=LEFT) plots.to_corner(UL) plots_list.add(plots) plots = plots_list[0] labels, die_labels = [ VGroup(*( self.get_plot_label(plot, n, die_face) for plot, n in zip(plots, it.count(1)) )) for die_face in [False, True] ] self.add(plots) self.add(die_labels) # Show new distribution self.play( Transform(plots, plots_list[1], run_time=3, lag_ratio=0.001), die_labels[0].animate.shift(0.25 * RIGHT), ) self.wait() # Show pairs of samples self.play( FadeOut(plots[2:]), FadeOut(die_labels[2:]), ) for _ in range(10): self.show_sample_sum(plots[0], distributions[1], 2, plots[1]) self.play(ShowCreationThenFadeAround(VGroup(plots[1], die_labels[1]))) self.wait() # Show triplet of samples plots[1].save_state() die_labels[1].save_state() self.play( FadeIn(plots[2], DOWN), FadeIn(die_labels[2], DOWN), plots[1].animate.set_opacity(0.2), die_labels[1].animate.set_opacity(0.2), ) for _ in range(10): self.show_sample_sum(plots[0], distributions[1], 3, plots[2]) self.play(Restore(plots[1]), Restore(die_labels[1])) # Replace labels labels[0].move_to(die_labels[0], LEFT) self.play( LaggedStartMap(FadeOut, die_labels, shift=UP, lag_ratio=0.25), LaggedStartMap(FadeIn, labels, shift=UP, lag_ratio=0.25), ) self.wait() # Show more plots frame = self.frame self.add(plots) self.play( frame.animate.set_height(plots.get_height() + 2).move_to(plots, LEFT).shift(LEFT), run_time=4 ) self.wait() # Show means and standard deviation lines mu, sigma = self.get_mean_and_standard_deviation(self.distribution) mean_labels = self.get_mean_labels(plots, num_decimal_places=2) mean_lines = VGroup(*(ml[0] for ml in mean_labels)) mu_labels = VGroup(*(ml[1] for ml in mean_labels)) sd_labels = self.get_sd_labels(plots) sd_lines = VGroup(*(sdl[0] for sdl in sd_labels)) sd_arrows = VGroup(*(sdl[1] for sdl in sd_labels)) sigma_labels = VGroup(*(sdl[2] for sdl in sd_labels)) all_axes = VGroup(*(plot[0] for plot in plots)) arrows = VGroup(*( FillArrow(axes.c2p(0, 0), axes.c2p(n * mu, 0)).move_to( axes.y_axis.pfp(0.75), LEFT ).scale(0.7) for n, axes in zip(it.count(1), all_axes[1:]) )) arrows.set_color(PINK) self.play( LaggedStartMap(GrowArrow, arrows, lag_ratio=0.2), LaggedStartMap(FadeIn, mean_lines, shift=RIGHT, lag_ratio=0.2), ) self.wait() for line in sd_lines: line.save_state() line.stretch(0, 0) line.set_opacity(0) self.play( FadeOut(arrows), LaggedStartMap(Restore, sd_lines), LaggedStartMap(FadeIn, sd_arrows) ) self.wait() # Quantify means frame.target = frame.generate_target() frame.target.set_height(5) frame.target.move_to(plots[0], DOWN) frame.target.shift(DOWN) frame_around_plot0 = frame.target.copy() self.play( MoveToTarget(frame), FadeOut(sd_lines, lag_ratio=0.1), FadeOut(sd_arrows, lag_ratio=0.1), run_time=5 ) self.play(Write(mu_labels[0])) self.wait() for n in range(6): frame.target = frame.generate_target() frame.target.set_height(plots[:n + 2].get_height() + 2) frame.target.move_to(plots[n + 1], DL).shift(0.75 * DL) self.play(LaggedStart( MoveToTarget(frame), TransformFromCopy(*mu_labels[n:n + 2]), lag_ratio=0.5 )) self.wait() # Quantify standard deviation # sigma = 1.38, if you're curious VGroup(sd_arrows, sigma_labels).shift(0.25 * UP) for label, arrows in zip(sigma_labels, sd_arrows): label.set_max_width(arrows[1].get_width()) self.play( LaggedStartMap(FadeIn, sd_lines, scale=2), LaggedStartMap(FadeIn, sd_arrows, scale=2), FadeOut(mu_labels, lag_ratio=0.01), ) self.play( frame.animate.become(frame_around_plot0).set_anim_args(run_time=5), Write(sigma_labels[0]), ) self.wait() for n in range(6): frame.target = frame.generate_target() frame.target.set_height(plots[:n + 2].get_height() + 2) frame.target.move_to(plots[n + 1], DL).shift(0.75 * DL) self.play(LaggedStart( MoveToTarget(frame), TransformFromCopy(*sigma_labels[n:n + 2]), lag_ratio=0.5 )) self.wait() self.play( FadeOut(sigma_labels, lag_ratio=0.1), FadeOut(sd_arrows, lag_ratio=0.1), ) self.add(mean_lines, sd_lines) # Realign and rescale all_axes = VGroup(*(plot[0] for plot in plots)) all_bars = VGroup(*(plot[1] for plot in plots)) all_bars[1].stretch(0.8, 1, about_edge=DOWN) self.play(FadeOut(all_axes)) self.realign_distributions(all_bars, labels, mean_lines, sd_lines) big_mean_line = Line(mean_lines.get_top(), mean_lines.get_bottom()) big_mean_line.set_stroke(PINK, 5) big_mean_line.insert_n_curves(20) self.play(VShowPassingFlash(big_mean_line, run_time=2, time_width=2.0)) self.wait() self.rescale_distributions(all_bars, mean_lines, sd_lines) big_sd_lines = Line(UP, DOWN).replicate(2) big_sd_lines.arrange(RIGHT) big_sd_lines.replace(sd_lines, stretch=True) big_sd_lines.set_stroke(RED, 5) big_sd_lines.insert_n_curves(20) self.play(*( VShowPassingFlash(line, run_time=2, time_width=2.0) for line in big_sd_lines )) self.wait() self.play( FadeOut(mean_lines), FadeOut(sd_lines), lag_ratio=0.1 ) # Show bell curves axes = Axes( (-5, 5), (0, 1, 0.25), width=0.45 * frame.get_width(), height=0.5 * frame.get_height(), ) axes.next_to(frame.get_left(), RIGHT, buff=1) axes.x_axis.add_numbers(font_size=36) axes.y_axis.add_numbers(np.arange(0.25, 1.25, 0.25), font_size=36, num_decimal_places=2) graph = axes.get_graph(lambda x: np.exp(-0.5 * x**2) / math.sqrt(2 * PI)) graph.set_stroke(YELLOW, 3) graph_label = Tex(R"{1 \over \sqrt{2\pi}} e^{-{1 \over 2}x^2}") graph_label.set_height(0.8 * graph.get_height()) graph_label.move_to(graph.get_corner(UL), DL) box = SurroundingRectangle(graph_label) box.set_stroke(YELLOW, 1) words = Text("We'll unpack this\n in a moment") words.match_width(box) words.next_to(box, UP, buff=LARGE_BUFF) bar_shift = 5 * RIGHT self.play(LaggedStart( FadeIn(axes), all_bars.animate.shift(bar_shift), ShowCreation(graph), Write(graph_label), lag_ratio=0.25 )) self.wait() self.play( Write(words), ShowCreation(box) ) self.wait() self.play(FadeOut(words), FadeOut(box)) mean_lines.shift(bar_shift) sd_lines.shift(bar_shift) # Map bell curve over plots target_curves = VGroup() for bars, mean_line in zip(all_bars, mean_lines): curve = graph.copy() curve.replace(bars, dim_to_match=1) curve.set_width(sd_lines[0].get_width() * 4, stretch=True) curve.match_x(mean_line) target_curves.add(curve) self.play(LaggedStart(*( TransformFromCopy(graph, curve) for curve in target_curves ))) self.wait() class UDistSumDistributions(ExpDistSumDistributions): distribution = U_SHAPED_DISTRIBUTION # Mean and standard deviation class MeanAndStandardDeviation(InteractiveScene): def construct(self): # Setup axes dist = np.array([3, 2, 1, 0.5, 1, 0.75]) dist /= dist.sum() original_dist = dist die_config = dict( fill_color=BLUE_E, dot_color=WHITE, ) chart = get_die_distribution_chart( dist, y_range=(0, 0.5, 0.1), die_config=die_config ) chart.to_edge(LEFT) self.add(*chart) axes, bars, die_labels = chart assert(isinstance(axes, Axes)) # Functions def set_dist(dist, **kwargs): new_bars = ChartBars(axes, dist) new_bars.match_style(bars) self.play(Transform(bars, new_bars, **kwargs)) def get_dist(): result = np.array([bar.get_height() for bar in bars]) return result / result.sum() def get_mu(): dist = get_dist() return sum(p * (n + 1) for n, p in enumerate(dist)) def get_sigma(): dist = get_dist() mu = get_mu() return math.sqrt(sum(p * (n + 1 - mu)**2 for n, p in enumerate(dist))) # Mean line tex_kw = dict( t2c={R"\mu": PINK, R"\sigma": RED}, font_size=48 ) mean_line = Line(axes.c2p(0, 0), axes.c2p(0, 0.5)) mean_line.set_stroke(PINK, 3) mean_line.add_updater(lambda m: m.move_to(axes.c2p(get_mu() - 0.5, 0), DOWN)) mu_label = Tex(R"\mu = 1.00", **tex_kw) mu_number = mu_label.make_number_changable("1.00") mu_number.add_updater(lambda m: m.set_value(get_mu())) mu_number.scale(0.75, about_edge=LEFT) mu_label.add_updater(lambda m: m.next_to(mean_line, UP)) mean_name = Text("Mean") mean_name.next_to(mu_label, UL, buff=1.0) mean_name.shift_onto_screen() mean_arrow = Arrow(mean_name, mu_label) mean_arrow.add_updater(lambda m: m.put_start_and_end_on( mean_name.get_bottom(), mu_label.get_corner(UL) ).scale(0.7)) self.play( ShowCreation(mean_line), VFadeIn(mu_label), ) self.wait() self.play( ShowCreation(mean_arrow), FadeIn(mean_name, 0.5 * UL) ) # Show a few means dists = [ EXP_DISTRIBUTION[::-1], EXP_DISTRIBUTION, U_SHAPED_DISTRIBUTION, original_dist ] for dist in dists: set_dist(dist, run_time=2) self.wait() # Mean equation mean_eq = Tex(R"\mu = E[X] = \sum_{x} P(X = x) \cdot x =", **tex_kw) mean_eq[R"\mu"].scale(1.2, about_edge=RIGHT) rhs = VGroup() for n in range(1, 7): term = Tex(Rf"P(\square) \cdot {n} \, + ", **tex_kw) die = DieFace(n, **die_config) die.replace(term[R"\square"]) term.replace_submobject(2, die) term.add(die) rhs.add(term) rhs.arrange(DOWN, buff=0.35) rhs[-1][-1].set_opacity(0) rhs.scale(0.75) mean_eq.next_to(rhs[0], LEFT, submobject_to_align=mean_eq[-1]) VGroup(mean_eq, rhs).to_corner(UR) mean_eq[-1].set_opacity(0) self.play(Write(mean_eq)) self.wait() # Highlight terms highlights = chart.bars.copy() highlights.set_stroke(YELLOW, 3) highlights.set_fill(opacity=0) for highlight, die, part in zip(highlights, chart.dice, rhs): self.play( ShowCreation(highlight), mean_eq[-1].animate.set_opacity(1), ) self.play( TransformMatchingShapes(die.copy(), part), FadeOut(highlight), run_time=1 ) # Show a few other distributions again for dist in dists: set_dist(dist, run_time=2) self.wait() # Reorganize mean labels mu_label.target = mu_label.generate_target() mu_label.target[1:].scale(0, about_point=mu_label[0].get_right()) mu_label.target.match_x(mean_line) mu_number.clear_updaters() self.play( MoveToTarget(mu_label), LaggedStart( FadeOut(mean_name), FadeOut(mean_arrow), FadeOut(rhs), FadeOut(mean_eq[-1]), ) ) mu_label.remove(*mu_label[1:]) # Standard deviation sd_lines = mean_line.copy().replicate(2) sd_lines.set_stroke(RED, 3) sd_lines.clear_updaters() sd_lines[0].add_updater(lambda m: m.move_to( axes.c2p(get_mu() - get_sigma() - 0.5, 0), DOWN) ) sd_lines[1].add_updater(lambda m: m.move_to( axes.c2p(get_mu() + get_sigma() - 0.5, 0), DOWN) ) sd_arrows = VGroup(Vector(LEFT), Vector(RIGHT)) sd_arrows.set_color(RED) sd_arrows.arrange(RIGHT, buff=0.35) sd_arrows.add_updater(lambda m: m.set_width(0.8 * sd_lines.get_width())) sd_arrows.add_updater(lambda m: m.move_to(sd_lines).shift(UP)) sd_lines.save_state() sd_lines.stretch(0.5, 0).set_opacity(0) self.play( Restore(sd_lines), ShowCreation(sd_arrows, lag_ratio=0), ) self.wait() # Contrast low and high variance var_dists = [ np.array([1, 3, 12, 4, 2, 1], dtype='float'), np.array([10, 2, 1, 1, 2, 10], dtype='float'), ] for dist in var_dists: dist /= dist.sum() set_dist(dist, run_time=3) self.wait() # Variance equation var_eq = VGroup( Tex(R"\text{Var}(X) &= E[(X - \mu)^2]", **tex_kw), Tex(R"= \sum_x P(X = x) \cdot (x - \mu)^2", **tex_kw), ) var_eq[1].next_to(var_eq[0]["="], DOWN, LARGE_BUFF, aligned_edge=LEFT) var_eq.next_to(mean_eq["E[X]"], DOWN, buff=1.5, aligned_edge=LEFT) variance_name = Text("Variance") variance_name.next_to(var_eq[0]["Var"], DOWN, buff=1.25).shift(0.5 * LEFT) variance_name.set_color(YELLOW) variance_arrow = Arrow(variance_name, var_eq[0]["Var"]) variance_arrow.match_color(variance_name) self.play( FadeIn(var_eq[0], DOWN), mean_eq.animate.set_opacity(0.5), ) self.play( Write(variance_name), ShowCreation(variance_arrow) ) self.wait() self.play(Write(var_eq[1])) self.wait() partial_square_opacity_tracker = ValueTracker(0) # Show squares partial_square_opacity_tracker.set_value(0.5) new_dist = np.array([10, 2, 1, 3, 4, 13], dtype='float') new_dist /= new_dist.sum() sd_group = VGroup(sd_lines, sd_arrows) def get_squares(bars): result = VGroup() for bar in bars: prob = axes.y_axis.p2n(bars[0].get_top()) line = Line(bar.get_bottom(), mean_line.get_bottom()) square = Square(line.get_width()) square.move_to(line, DOWN) square.match_y(bar.get_top(), DOWN) square.set_stroke(RED, 1) square.set_fill(RED, 0.2) p_square = square.copy() p_square.stretch(prob, 1, about_edge=DOWN) p_square.set_opacity(partial_square_opacity_tracker.get_value()) result.add(VGroup(square, p_square)) return result squares = get_squares(bars) globals().update(locals()) labels = VGroup(*(Tex(Rf"P({n}) \cdot ({n} - \mu)^2", **tex_kw) for n in range(1, 7))) labels.scale(0.5) for label, square in zip(labels, squares): label.square = square label.add_updater(lambda m: m.set_width(0.7 * m.square.get_width()).next_to(m.square.get_bottom(), UP, SMALL_BUFF)) label = labels[0] square = squares[0] square[1].set_fill(opacity=0) part1 = label[R"P(1) \cdot"] part2 = label[R"(1 - \mu)^2"] part2.save_state() part2.match_x(squares[0]) self.play( FadeOut(sd_group), FadeIn(square, lag_ratio=0.8), FadeIn(part2), ) self.wait() self.play( square[1].animate.set_fill(opacity=0.5), FadeIn(part1), Restore(part2), ) self.add(label) # Show other squares last_group = VGroup(square, label) for new_label, new_square in zip(labels[1:], squares[1:]): new_group = VGroup(new_square, new_label) self.play(FadeOut(last_group), FadeIn(new_group)) last_group = new_group self.play( FadeOut(last_group), FadeIn(square), FadeIn(label), ) self.wait() squares = always_redraw(lambda: get_squares(bars[:1])) self.remove(square) self.add(squares, label) # Again, toggle between low and high variance for dist in [var_dists[0], EXP_DISTRIBUTION, var_dists[1]]: set_dist(dist, run_time=3) self.wait(2) sd_group.update() self.play(FadeOut(squares), FadeOut(label), FadeIn(sd_group)) self.wait() # Standard deviation sd_equation = Tex(R"\sigma = \sqrt{\text{Var}(X)}", **tex_kw) sd_equation.next_to(var_eq, DOWN, LARGE_BUFF, aligned_edge=LEFT) sd_name = Text("Standard deviation") sd_name.set_color(RED) sd_name.next_to(sd_equation, DOWN, LARGE_BUFF).shift_onto_screen() sd_name.shift(2 * LEFT) sd_arrow = Arrow(sd_name, sd_equation[R"\sigma"], buff=0.1) sd_arrow.match_color(sd_name) sigma_labels = Tex(R"\sigma", **tex_kw).replicate(2) for label, arrow in zip(sigma_labels, sd_arrows): label.arrow = arrow label.add_updater(lambda m: m.next_to(m.arrow, UP)) self.play( FadeTransformPieces(variance_name, sd_name), ReplacementTransform(variance_arrow, sd_arrow), Write(sd_equation[:-len("Var(X)")]), TransformFromCopy( var_eq[0][R"\text{Var}(X)"], sd_equation[R"\text{Var}(X)"], ), ) self.wait() self.play(*( TransformFromCopy(sd_equation[R"\sigma"][0], label) for label in sigma_labels )) self.wait() # Show a few distributions for dist in [*dists, *var_dists]: set_dist(dist, run_time=2) self.wait() # Build up Gaussian class BuildUpGaussian(InteractiveScene): def construct(self): # Axes and graph axes = self.get_axes() bell_graph = axes.get_graph(lambda x: gauss_func(x, 0, 0.5)) bell_graph.set_stroke(YELLOW, 3) def get_graph(func, **kwargs): return axes.get_graph(func, **kwargs).match_style(bell_graph) self.add(axes) self.add(bell_graph) # Peel off from full Gaussian kw = dict( tex_to_color_map={ R"\mu": PINK, R"\sigma": RED, }, font_size=72 ) formulas = VGroup(*( Tex(tex, **kw) for tex in [ "e^x", "e^{-x}", "e^{-x^2}", R"e^{-{1 \over 2} x^2}", R"{1 \over \sqrt{2\pi}} e^{-{1 \over 2} x^2}", R"{1 \over \sigma \sqrt{2\pi}} e^{-{1 \over 2} \left({x \over \sigma}\right)^2}", R"{1 \over \sigma \sqrt{2\pi}} e^{-{1 \over 2} \left({x - \mu \over \sigma}\right)^2}", ] )) saved_formulas = formulas.copy() morty = Mortimer() morty.to_edge(DOWN).shift(3 * RIGHT) formulas[-1].set_max_height(1.25) formulas[-1].to_edge(UP) self.add(formulas[-1]) self.play(FlashAround(formulas[-1], run_time=2, time_width=1.5)) self.wait() self.play( FadeOut(axes, 2 * DOWN), FadeOut(bell_graph, DOWN), VFadeIn(morty), morty.change("raise_right_hand"), formulas[-1].animate.next_to(morty.get_corner(UL), UP) ) for form1, form2 in zip(formulas[::-1], formulas[-2::-1]): form2.next_to(morty.get_corner(UL), UP) self.play(TransformMatchingTex(form1, form2), run_time=1) self.play( formulas[0].animate.center().to_edge(UP), FadeIn(axes, 3 * UP), FadeOut(morty, DOWN) ) self.wait() # Show decay self.remove(formulas[0]) formulas = saved_formulas for form in formulas: form.center().to_edge(UP) self.add(formulas[0]) def decay_anim(graph): dot = GlowDot(color=WHITE) dot.move_to(graph.pfp(0.5)) sub_graph = VMobject() sub_graph.set_points(graph.get_points()[graph.get_num_points() // 2::]) return AnimationGroup( MoveAlongPath(dot, sub_graph), UpdateFromAlphaFunc( VectorizedPoint(), lambda m, a: dot.set_radius(0.2 * clip(10 * there_and_back(a), 0, 1)), remover=True ), run_time=1.5, remover=True ) graph = get_graph(np.exp) self.play(ShowCreation(graph)) self.wait() self.play(LaggedStart( TransformMatchingTex(formulas[0], formulas[1]), graph.animate.stretch(-1, 0).set_anim_args(run_time=2), lag_ratio=0.5 )) graph.become(get_graph(lambda x: np.exp(-x))) self.play(LaggedStart(*( decay_anim(graph) for x in range(8) ), lag_ratio=0.15, run_time=4)) # Decay in both directions abs_formula = Tex("e^{-|x|}", **kw) abs_formula.to_edge(UP) abs_graph = get_graph( lambda x: np.exp(-np.abs(x)), ) abs_graph.make_jagged() smooth_graph = get_graph(lambda x: np.exp(-x**2)) self.play( TransformMatchingTex(formulas[1], abs_formula), Transform(graph, abs_graph) ) self.wait() self.play(Flash(axes.c2p(0, 1))) self.wait() self.play( TransformMatchingTex(abs_formula, formulas[2]), Transform(graph, smooth_graph) ) self.wait() # Tweak the spread form_with_const = Tex("e^{-c x^2}", **kw) form_with_const["c"].set_color(RED) form_with_const.move_to(formulas[2]) c_display, c_tracker = self.get_variable_display("c", RED, (0, 5)) base_tracker = ValueTracker(math.exp(1)) get_c = c_tracker.get_value get_base = base_tracker.get_value axes.bind_graph_to_func( graph, lambda x: np.exp(-get_c() * np.log(get_base()) * x**2) ) self.play( TransformMatchingTex(formulas[2], form_with_const), FadeIn(c_display), ) self.wait() for value in [5.0, 0.2, 1.0]: self.play(c_tracker.animate.set_value(value), run_time=2) self.wait() # Show effective base rhs = Tex(R"= \left(e^c\right)^{-x^2}", **kw) rhs["c"].set_color(RED) rhs.next_to(form_with_const) self.play( Write(rhs.shift(2 * LEFT)), form_with_const.animate.shift(2 * LEFT) ) self.wait() alt_base_form = Tex(R"=(2.718)^{-x^2}", **kw) alt_base_form.next_to(rhs, RIGHT) base = alt_base_form.make_number_changable("2.718") base_width = base.get_width() base.set_color(TEAL) base.edge_to_fix = ORIGIN base.add_updater(lambda m: m.set_value( np.exp(get_c() * np.log(get_base())) )) base.add_updater(lambda m: m.set_width(base_width)) self.play( FadeIn(alt_base_form, RIGHT), ) self.wait() for value in [2.2, 0.1, 1.0]: self.play(c_tracker.animate.set_value(value), run_time=2) self.wait() # Writing this family with "e" is a choice that we're making es = VGroup(form_with_const[0], rhs[2]) pis, twos, threes = [ VGroup(*( Tex(tex, **kw).move_to(e, DR) for e in es )) for tex in [R"\pi", "2", "3"] ] note = TexText("$e$ is not special here") note.next_to(es[0], DOWN, buff=1.5, aligned_edge=RIGHT) note.set_backstroke(width=5) arrow = Arrow(note, es[0]) self.play( FlashAround(es[0], run_time=2), FadeIn(note), GrowArrow(arrow), ) self.wait() last_mobs = es for mobs, value in [(pis, PI), (twos, 2), (threes, 3), (es, math.exp(1))]: base.suspend_updating() self.play( FadeOut(last_mobs, 0.25 * UP, lag_ratio=0.2), FadeIn(mobs, 0.25 * UP, lag_ratio=0.2), c_tracker.animate.set_value(1 / math.log(value)), base_tracker.animate.set_value(value), ) base.resume_updating() self.wait() for c in [3, 0.5, 1]: self.play(c_tracker.animate.set_value(c), run_time=2) self.wait() last_mobs = mobs # Introduce sigma self.play( form_with_const.animate.set_x(0), FadeOut(rhs, RIGHT), FadeOut(alt_base_form, RIGHT), FadeOut(note, RIGHT), FadeOut(arrow, RIGHT), ) self.play(FlashAround(form_with_const["c"], color=RED)) form_with_sigma = Tex( R"e^{-{1 \over 2} \left({x / \sigma}\right)^2}", **kw ) form_with_sigma.to_edge(UP) sigma_display, sigma_tracker = self.get_variable_display(R"\sigma", RED, (0, 3)) sigma_tracker.set_value(math.sqrt(0.5)) get_sigma = sigma_tracker.get_value sigma_display.update() graph.clear_updaters() axes.bind_graph_to_func(graph, lambda x: np.exp( -0.5 * (x / get_sigma())**2 )) graph.update() self.play( TransformMatchingTex(form_with_const, form_with_sigma), FadeOut(c_display, UP), FadeIn(sigma_display, UP), run_time=1 ) self.wait() # Show standard deviation v_lines = Line(axes.c2p(0, 0), axes.c2p(0, 0.75 * axes.y_axis.x_max)).replicate(2) v_lines.set_stroke(RED, 2) v_lines[0].add_updater(lambda m: m.move_to(axes.c2p(-get_sigma(), 0), DOWN)) v_lines[1].add_updater(lambda m: m.move_to(axes.c2p(get_sigma(), 0), DOWN)) arrows = VGroup(Vector(LEFT), Vector(RIGHT)) arrows.arrange(RIGHT, buff=0.25) arrows.match_color(v_lines) arrows.add_updater(lambda m: m.set_width(max(0.9 * v_lines.get_width(), 1e-5))) arrows.add_updater(lambda m: m.move_to(axes.c2p(0, 0.575 * axes.y_axis.x_max))) sigma_labels = Tex(R"\sigma").replicate(2) sigma_labels.set_color(RED) sigma_labels[0].add_updater(lambda m: m.next_to(arrows[0], UP, 0.15)) sigma_labels[1].add_updater(lambda m: m.next_to(arrows[1], UP, 0.15)) v_lines.suspend_updating() v_lines.save_state() v_lines.stretch(0.1, 0) v_lines.set_opacity(0) self.play( Restore(v_lines), ShowCreation(arrows, lag_ratio=0), FadeIn(sigma_labels) ) v_lines.resume_updating() sd_group = VGroup(v_lines, arrows, sigma_labels) self.wait() for value in [2, math.sqrt(0.5)]: self.play(sigma_tracker.animate.set_value(value), run_time=3) self.wait() # Back to simple e^(-x^2) simple_form = Tex("e^{-x^2}", **kw) simple_form.to_edge(UP) self.remove(form_with_sigma) sd_group.save_state() self.play( FadeOut(sd_group), FadeOut(sigma_display), TransformMatchingTex(form_with_sigma.copy(), simple_form) ) # We want the area to be 1 ab_tracker = ValueTracker(np.array([-4, 4])) area = graph.copy() area.set_stroke(width=0) area.set_fill(YELLOW, 0.5) area.set_shading(0.5, 0.5) def update_area(area): a, b = ab_tracker.get_value() x_min, x_max = axes.x_range[:2] area.pointwise_become_partial( graph, (a - x_min) / (x_max - x_min), (b - x_min) / (x_max - x_min), ) area.add_line_to(axes.c2p(b, 0)) area.add_line_to(axes.c2p(a, 0)) area.add_line_to(area.get_start()) area.add_updater(update_area) note = Text("We want this area\nto be 1") note.next_to(axes.get_top(), DOWN) note.match_x(axes.c2p(2, 0)) note.set_backstroke(width=5) note_arrow = Arrow(note.get_bottom() + LEFT, area.get_center()) prob_label = Tex("p(a < x < b)") prob_label.move_to(axes.c2p(-2, 1.5)) prob_arrow = Arrow(LEFT, RIGHT) prob_arrow.add_updater(lambda m: m.put_start_and_end_on( prob_label.get_bottom() + SMALL_BUFF * DOWN, area.get_center(), )) self.add(area, graph) self.play( FadeIn(area), Write(note, run_time=1), ShowCreation(note_arrow), ) self.wait() self.play( Write(prob_label), ShowCreation(prob_arrow), ab_tracker.animate.set_value([-1, 0]), FadeOut(note), FadeOut(note_arrow), ) self.wait() for value in [(-0.5, 0.5), (-1.5, -0.5), (0, 1), (-2, 1), (-4, 4)]: self.play(ab_tracker.animate.set_value(value), run_time=3) self.wait() self.play( FadeOut(prob_label), FadeOut(prob_arrow), FadeIn(note), FadeIn(note_arrow), ) self.wait() self.remove(area) graph.set_fill(area.get_fill_color(), area.get_fill_opacity()) # Normalize area_label = TexText(R"Area = $\sqrt{\pi}$", **kw) area_label.next_to(note_arrow.get_start(), UR, SMALL_BUFF) area_label.set_backstroke(width=5) graph.clear_updaters() normalized_form = Tex(R"{1 \over \sqrt{\pi}} e^{-x^2}", **kw) normalized_form[R"{1 \over \sqrt{\pi}}"].scale(0.8, about_edge=RIGHT) normalized_form.to_edge(UP, buff=MED_SMALL_BUFF) one = Tex("1", **kw) one.move_to(area_label[R"\sqrt{\pi}"], LEFT) one.align_to(area_label[0], DOWN) self.play( FadeOut(note, 0.5 * UP), FadeIn(area_label, 0.5 * UP), ) self.wait() self.play( TransformMatchingTex(simple_form, normalized_form, run_time=1), FadeTransform(area_label[R"\sqrt{\pi}"], normalized_form[R"\sqrt{\pi}"]), graph.animate.stretch(1 / math.sqrt(PI), 1, about_edge=DOWN), note_arrow.animate.put_start_and_end_on( note_arrow.get_start(), note_arrow.get_end() + 0.5 * DOWN, ) ) self.play(Write(one)) self.play(FlashAround(one)) self.wait() # Show normalized form with sigma sigma_forms = [ Tex(R"{1 \over \sqrt{\pi}} e^{-{1 \over 2}(x / \sigma)^2}", **kw), Tex(R"{1 \over \sigma \sqrt{2}} {1 \over \sqrt{\pi}} e^{-{1 \over 2}(x / \sigma)^2}", **kw), Tex(R"{1 \over \sigma \sqrt{2\pi}} e^{-{1 \over 2}(x / \sigma)^2}", **kw), ] for form in sigma_forms: e = form["e^"][0][0] form[:form.submobjects.index(e)].scale(0.7, about_edge=RIGHT) form.to_edge(UP, buff=MED_SMALL_BUFF) sqrt2_sigma = Tex(R"\sigma \sqrt{2}", **kw) sqrt2_sigma.move_to(one, LEFT) sigma_display.update() sd_group.restore().update() self.play( TransformMatchingTex(normalized_form, sigma_forms[0]), FadeIn(sigma_display), FadeIn(sd_group), ) self.play( FadeOut(one, UP), FadeIn(sqrt2_sigma, UP), sigma_tracker.animate.set_value(1), graph.animate.stretch(math.sqrt(2), 0), ) self.wait() self.play( TransformMatchingTex(*sigma_forms[:2], run_time=1), FadeTransform(sqrt2_sigma, sigma_forms[1][R"\sigma \sqrt{2}"][0]), graph.animate.stretch(1 / math.sqrt(2) / get_sigma(), 1, about_edge=DOWN), FadeIn(one), ) self.wait() self.play(TransformMatchingTex(*sigma_forms[1:3])) self.play(FlashAround(sigma_forms[2][R"{1 \over \sigma \sqrt{2\pi}}"], run_time=3)) self.wait() self.play(FlashAround(sigma_forms[2], run_time=3, time_width=1.0)) axes.bind_graph_to_func( graph, lambda x: gauss_func(x, 0, get_sigma()) ) for value in [0.2, 0.5, math.sqrt(0.5)]: self.play(sigma_tracker.animate.set_value(value), run_time=3) self.wait() area_label[R"\sqrt{\pi}"].set_opacity(0) self.play(LaggedStartMap(FadeOut, VGroup(area_label, one, note_arrow))) self.wait() # Show standard form curr_form = sigma_forms[2].copy() self.remove(*sigma_forms) self.add(curr_form) standard_form = Tex(R"{1 \over \sqrt{2\pi}} e^{-{1 \over 2} x^2}", **kw) standard_form[R"{1 \over \sqrt{2\pi}}"].scale(0.7, about_edge=RIGHT) standard_form.move_to(curr_form) rect = SurroundingRectangle(standard_form) rect.set_stroke(BLUE, 2) std_words = Text("Standard\nnormal\ndistribution", alignment="LEFT") std_words.match_height(rect) std_words.scale(0.9) std_words.next_to(rect, RIGHT, buff=MED_LARGE_BUFF) std_words.set_color(BLUE) self.play(sigma_tracker.animate.set_value(1)) self.play(TransformMatchingTex(curr_form, standard_form, run_time=1)) one_labels = Integer(1).replicate(2) for ol, sl in zip(one_labels, sigma_labels): ol.match_style(sl) ol.move_to(sl) ol.shift(SMALL_BUFF * UP) self.play( FadeOut(sigma_labels, 0.1 * UP, lag_ratio=0.1), FadeIn(one_labels, 0.1 * UP, lag_ratio=0.1), ) self.wait() self.play( ShowCreation(rect), Write(std_words) ) self.wait() self.play( FadeOut(rect), FadeOut(std_words), FadeOut(one_labels, 0.2 * DOWN), FadeIn(sigma_labels, 0.2 * DOWN), TransformMatchingTex(standard_form, sigma_forms[2]) ) # Add the mean final_form = formulas[-1].copy() final_form[:final_form.submobjects.index(final_form["e^"][0][0])].scale(0.75, about_edge=RIGHT) final_form.to_edge(UP, buff=MED_SMALL_BUFF) mu_display, mu_tracker = self.get_variable_display(R"\mu", PINK, (-2, 2)) mu_tracker.set_value(0) mu_display.update() get_mu = mu_tracker.get_value mu_display.to_corner(UR, buff=MED_SMALL_BUFF) mu_line = v_lines[0].copy() mu_line.clear_updaters() mu_line.set_stroke(PINK, 3) mu_line.add_updater(lambda m: m.move_to(axes.c2p(get_mu(), 0), DOWN)) mu_label = Tex(R"\mu") mu_label.match_color(mu_line) mu_label.set_backstroke(width=10) mu_label.add_updater(lambda m: m.next_to(mu_line, UP)) sd_group.add_updater(lambda m: m.match_x(mu_line)) self.add(sd_group) axes.bind_graph_to_func(graph, lambda x: gauss_func(x, get_mu(), get_sigma())) self.add(mu_label) self.play( TransformMatchingTex( sigma_forms[2], final_form, matched_pairs=[ (sigma_forms[2][R"/ \sigma"], final_form[R"\over \sigma"][1]), ], match_animation=FadeTransform, mismatch_animation=FadeTransform, ), ShowCreation(mu_line), FadeIn(mu_display), ) self.wait() for value in [2, -2, 1]: self.play(mu_tracker.animate.set_value(value), run_time=3) self.wait() for value in [0.5, 1.5, 0.8]: self.play(sigma_tracker.animate.set_value(value), run_time=2) self.wait() # Added animations for an opening scene mu_tracker.set_value(0) sigma_tracker.set_value(0.5) ms_mobs = VGroup( mu_display, sigma_display, mu_line, mu_label, sd_group ) self.remove(ms_mobs) self.wait() self.play(LaggedStartMap(FadeIn, ms_mobs, lag_ratio=0.2)) pairs = [(1, 1.5), (1, 1.0), (1.5, 1.0), (1, 0.7), (0, 1)] for mu, sigma in pairs: self.play( mu_tracker.animate.set_value(mu), sigma_tracker.animate.set_value(sigma), run_time=3 ) self.wait() def get_variable_display(self, name, color, value_range): eq = Tex(f"{name} = 1.00", t2c={name: color}) number = eq.make_number_changable("1.00") tracker = ValueTracker(1) get_value = tracker.get_value number.add_updater(lambda c: c.set_value(get_value())) number_line = NumberLine( value_range, width=1.25, tick_size=0.05 ) number_line.rotate(90 * DEGREES) number_line.next_to(eq, RIGHT, MED_LARGE_BUFF) number_line.add_numbers(font_size=14, direction=LEFT, buff=0.15) slider = ArrowTip(angle=PI).set_width(0.15) slider.set_color(color) slider.add_updater(lambda m: m.move_to(number_line.n2p(get_value()), LEFT)) display = VGroup(eq, number_line, slider) display.to_corner(UL, buff=MED_SMALL_BUFF) return display, tracker def get_axes( self, x_range=(-4, 4), y_range=(-1.0, 2.0, 1.0), ): axes = NumberPlane( x_range, y_range, width=FRAME_WIDTH, height=6, background_line_style=dict( stroke_color=GREY_A, stroke_width=2, stroke_opacity=0.5 ) ) axes.shift(BOTTOM - axes.c2p(0, y_range[0])) axes.x_axis.add_numbers() axes.y_axis.add_numbers(num_decimal_places=1) return axes # Show limiting distributions class LimitingDistributions(InteractiveScene): distribution = EXP_DISTRIBUTION x_min = 1 bar_colors = (BLUE, TEAL) bar_opacity = 0.75 y_range = (0, 0.5, 0.1) max_n = 50 normal_y_range = (0, 0.5, 0.25) normal_axes_height = 2 def construct(self): # Dividing line h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH) h_line.set_stroke(GREY, 2) self.add(h_line) # Starting distribution dist = np.array(self.distribution) dist /= dist.sum() top_plot = self.get_top_distribution_plot(dist) top_label = TexText(R"Random variable \\ $X$", font_size=36) top_label[-1].scale(1.2, about_edge=UP).shift(0.25 * DOWN) top_label.move_to(top_plot).to_edge(LEFT, buff=0.25).shift(0.35 * UP) self.add(top_plot) self.add(top_label) # Lower plot N_tracker = ValueTracker(2) get_N = lambda: int(N_tracker.get_value()) s_plot = self.get_sum_plot(dist, get_N(), top_plot) # TODO self.add(s_plot) # Mean and s.d. labels bars = top_plot.bars mean, sd = get_mean_and_sd(get_dist(bars)) top_mean_sd_labels = self.get_mean_sd_labels( R"\mu", R"\sigma", mean, sd ) sum_mean_sd_labels = self.get_mean_sd_labels( R"\mu \cdot N", R"\sigma \cdot \sqrt{N}", mean * 10, sd * math.sqrt(10), ) scaled_sum_mean_sd_labels = self.get_mean_sd_labels(R"", R"", 0, 1) sum_mean_sd_labels.next_to(h_line, DOWN) sum_mean_sd_labels.to_edge(RIGHT) scaled_sum_mean_sd_labels.next_to(h_line, DOWN) scaled_sum_mean_sd_labels.align_to(sum_mean_sd_labels, LEFT) top_mean_sd_labels.next_to(TOP, DOWN) top_mean_sd_labels.align_to(sum_mean_sd_labels, LEFT) mu_label, sigma_label = self.get_mu_sigma_annotations(top_plot) # Lower distribution labels sum_label = self.get_sum_label(get_N()) self.add(sum_label) # Increase N for n in range(3, 11): new_s_plot = self.get_sum_plot(dist, n, top_plot) new_sum_label = self.get_sum_label(n, dots=False) N_tracker.set_value(n) self.play( ReplacementTransform(s_plot.bars, new_s_plot.bars[:len(s_plot.bars)]), GrowFromEdge(new_s_plot.bars[len(s_plot.bars):], DOWN), ReplacementTransform(s_plot.axes, new_s_plot.axes), FadeTransform(sum_label, new_sum_label), run_time=0.5, ) s_plot = new_s_plot sum_label = new_sum_label self.wait(0.5) self.wait() # Show mean and standard deviation self.play(Write(mu_label, stroke_color=PINK), run_time=1) self.play(TransformMatchingTex(mu_label[1].copy(), top_mean_sd_labels[0]), run_time=1) self.wait() sigma_label.save_state() sigma_label.stretch(0, 0).set_opacity(0) self.play(Restore(sigma_label)) self.play(TransformMatchingTex(sigma_label[2].copy(), top_mean_sd_labels[1]), run_time=1) self.wait() low_mu_label, low_sigma_label = self.get_mu_sigma_annotations(s_plot) low_lines = VGroup(low_mu_label[0], low_sigma_label[0]) low_lines.shift((get_N() - 1.5)* s_plot.axes.x_axis.get_unit_size() * RIGHT) low_lines.stretch(0.5, 1, about_edge=DOWN) new_sum_label = self.get_sum_label(get_N()) sum_mean_sd_labels.update() self.play( TransformMatchingTex(top_mean_sd_labels[0].copy(), sum_mean_sd_labels[0]), TransformMatchingTex(sum_label, new_sum_label), TransformFromCopy(mu_label[:1], low_mu_label[:1]), run_time=1.5 ) sum_label = new_sum_label self.wait() self.play( TransformMatchingTex(top_mean_sd_labels[1].copy(), sum_mean_sd_labels[1]), TransformFromCopy(sigma_label[:1], low_sigma_label[:1]), run_time=1.5 ) self.wait() # Write formula formula = Tex( R"{1 \over \sigma \sqrt{2\pi N}} e^{-{1 \over 2} \left({x - \mu N \over \sigma \sqrt{N}} \right)^2}", t2c={ R"\mu": PINK, R"\sigma": RED, R"N": YELLOW, }, font_size=36 ) N = get_N() mu, sigma = get_mean_and_sd(get_dist(s_plot.bars), x_min=N) graph = s_plot.axes.get_graph(lambda x: gauss_func(x, mu - 1, sigma)) graph.set_stroke(WHITE, 3) formula.next_to(graph, UP).align_to(graph, LEFT).shift(0.5 * RIGHT) self.play( ShowCreation(graph), FadeIn(formula, UP), ) self.wait() self.play(LaggedStartMap( FadeOut, VGroup(graph, *low_lines, formula), lag_ratio=0.5 )) # Transition to rescaled version scaled_sum_label = self.get_sum_label(get_N(), scaled=True) ss_plot = self.get_scaled_sum_plot(dist, get_N()) x_shift = 2 * RIGHT self.play(FlashAround(sum_label, time_width=1.5, run_time=2)) self.play(LaggedStart( Transform( sum_label, scaled_sum_label[sum_label.get_string()][0].copy(), remover=True, ), Write(scaled_sum_label), s_plot.animate.shift(x_shift), lag_ratio=0.5 )) self.wait() sub_part = scaled_sum_label[R"- \decimalmob \cdot \mu"] rect = SurroundingRectangle(sum_mean_sd_labels[0], color=RED) target_x = ss_plot.axes.c2p(0, 0)[0] self.play(ShowCreation(rect)) self.play( FadeTransform(sum_mean_sd_labels[0].copy(), sub_part), rect.animate.set_points(SurroundingRectangle(sub_part).get_points()), s_plot.bars.animate.shift((target_x - low_lines[0].get_x() - x_shift) * RIGHT), s_plot.axes.animate.shift((target_x - s_plot.axes.c2p(0, 0)[0]) * RIGHT), ) self.play( FadeOut(rect), FadeOut(sum_mean_sd_labels[0], RIGHT), FadeIn(scaled_sum_mean_sd_labels[0], RIGHT) ) self.wait() div_part = scaled_sum_label[R"\sigma \cdot \sqrt{\decimalmob}"] rect = SurroundingRectangle(sum_mean_sd_labels[1], color=RED) self.play(ShowCreation(rect)) self.play( FadeTransform(sum_mean_sd_labels[1].copy(), div_part), rect.animate.set_points(SurroundingRectangle(div_part).get_points()), ) self.play(FadeOut(rect)) self.wait() # Swap to new axes stretch_group = VGroup(ss_plot.axes.y_axis, ss_plot.bars) stretch_factor = s_plot.bars.get_height() / ss_plot.bars.get_height() stretch_group.stretch(stretch_factor, dim=1, about_edge=DOWN) self.play( FadeOut(s_plot.axes), FadeIn(ss_plot.axes), ReplacementTransform(s_plot.bars, ss_plot.bars), FadeOut(sum_label) ) self.play(stretch_group.animate.stretch(1 / stretch_factor, dim=1, about_edge=DOWN)) self.wait() # Show sd of 1 sd_lines = Line(DOWN, UP).replicate(2) sd_lines[0].move_to(ss_plot.axes.c2p(1, 0), DOWN) sd_lines[1].move_to(ss_plot.axes.c2p(-1, 0), DOWN) sd_lines.set_stroke(RED, 3) sd_lines.save_state() sd_lines.stretch(0, 0).set_opacity(0) self.play( Restore(sd_lines), FadeOut(sum_mean_sd_labels[1], RIGHT), FadeIn(scaled_sum_mean_sd_labels[1], RIGHT) ) self.wait() self.play(FadeOut(sd_lines)) # Readable meaning full_screen_rect = FullScreenFadeRectangle() full_screen_rect.set_opacity(0.7) top_rect = full_screen_rect.copy().stretch(0.5, 1, about_edge=UP) top_rect.set_fill(BLACK, 0.7) words = Text("Highly readable meaning:") words.next_to(scaled_sum_label, UP, LARGE_BUFF, aligned_edge=LEFT) meaning = TexText( R"How many std devs away from the mean is $X_1 + \cdots + X_{10}$", t2c={"std devs": RED, "mean": PINK, }, font_size=40 ) meaning.move_to(words, LEFT) self.add(full_screen_rect, scaled_sum_label) self.play(FadeIn(full_screen_rect)) self.wait() self.play( FadeIn(top_rect), FadeIn(words) ) self.wait() self.play( words.animate.shift(UP), Write(meaning) ) self.wait() # Example bar bar = ss_plot.bars[9].copy() ss_plot.bars.save_state() sum_tex = Tex(R"0 = 19") die = DieFace(1, fill_color=BLUE_E) die.dots.set_opacity(0) dice = die.get_grid(2, 5) dice.set_height(0.75) dice.set_stroke(width=1) dice.move_to(sum_tex[0], RIGHT) sum_tex.replace_submobject(0, dice) sum_tex.move_to(bar).to_edge(LEFT) arrow = Arrow(sum_tex, bar, buff=0.1) ss_plot.bars.set_opacity(0.2) self.play( FadeOut(full_screen_rect), top_rect.animate.set_opacity(1), FadeIn(bar) ) self.wait() self.play( FadeIn(sum_tex, lag_ratio=0.2, run_time=2), GrowArrow(arrow), ) self.wait() self.play( arrow.animate.become(Vector(0.5 * UP).next_to(bar, DOWN, SMALL_BUFF)) ) self.wait() self.play(LaggedStart( FadeOut(top_rect), Restore(ss_plot.bars), FadeOut(bar), FadeOut(words), FadeOut(meaning), FadeOut(sum_tex), FadeOut(arrow), )) # Comment on meaning of bars words = Text("Probability = Area", font_size=36) words.next_to(bar, LEFT, buff=1.5, aligned_edge=UP) arrow = Arrow(words.get_right(), bar.get_center()) y_axis_label = Text("Probability\ndensity", font_size=24) y_axis_label.set_color(GREY_B) y_axis_label.next_to(ss_plot.axes.c2p(0, 0.5), RIGHT, SMALL_BUFF) bar_range = ss_plot.bars[8:16].copy() self.play( ss_plot.bars.animate.set_opacity(0.2), FadeIn(bar) ) self.play(FlashAround(scaled_sum_label)) self.wait() self.play(Write(words), ShowCreation(arrow)) self.wait() self.play(FadeIn(y_axis_label, 0.2 * UP)) self.wait() self.play( FadeIn(bar_range, lag_ratio=0.2), FadeOut(bar) ) self.wait() self.play( Restore(ss_plot.bars), FadeOut(bar_range) ) self.wait() self.play(FadeOut(words), FadeOut(arrow), FadeOut(y_axis_label)) # Roll back to 3 for n in range(9, 2, -1): new_scaled_sum_label = self.get_sum_label(n, scaled=True) new_ss_plot = self.get_scaled_sum_plot(dist, n) N_tracker.set_value(n) self.remove(ss_plot.axes) self.add(new_ss_plot.axes) self.play( FadeTransform(scaled_sum_label, new_scaled_sum_label), FadeTransform(ss_plot.bars, new_ss_plot.bars), run_time=0.1 ) self.wait(0.4) scaled_sum_label = new_scaled_sum_label ss_plot = new_ss_plot # Mess around with the distribution alt_dists = [ np.array(U_SHAPED_DISTRIBUTION), np.random.random(6), np.random.random(6), np.array(STEEP_U_SHAPED_DISTRIBUTION), np.random.random(6), ] for dist in alt_dists: dist /= dist.sum() words = Text("Change this\ndistribution") words.set_color(YELLOW) words.move_to(top_plot, UR) self.play( FadeOut(mu_label), FadeOut(sigma_label), Write(words), ) self.change_distribution( alt_dists, top_plot, ss_plot, top_mean_sd_labels, get_N() ) self.play(FadeOut(words)) # Show limit for n in range(4, self.max_n + 1): N_tracker.set_value(n) new_ss_plot = self.get_scaled_sum_plot(self.distribution, n) new_scaled_sum_label = self.get_sum_label(n, scaled=True) if n < 5: rt = 0.5 wt = 0.25 elif n < 15: rt = 0.1 wt = 0.1 else: rt = 0 wt = 0.1 if rt > 0: self.play( FadeOut(ss_plot.bars), FadeIn(new_ss_plot.bars), ReplacementTransform(ss_plot.axes, new_ss_plot.axes), FadeTransform(scaled_sum_label, new_scaled_sum_label), run_time=rt ) else: self.remove(ss_plot, scaled_sum_label) self.add(new_ss_plot, new_scaled_sum_label) self.wait(wt) ss_plot = new_ss_plot scaled_sum_label = new_scaled_sum_label if n in [10, self.max_n]: # More switching self.wait() self.change_distribution( [EXP_DISTRIBUTION, *alt_dists], top_plot, ss_plot, top_mean_sd_labels, get_N(), ) self.wait() # Show standard normal graph graph = ss_plot.axes.get_graph( lambda x: gauss_func(x, 0, 1), x_range=(-8, 8) ) graph.set_stroke(YELLOW, 3) label = Tex(R"{1 \over \sqrt{2\pi}} e^{-x^2 / 2}") label[R"{1 \over \sqrt{2\pi}}"].scale(0.8, about_edge=RIGHT) label.next_to(graph.pfp(0.55), UR) self.play( ShowCreation(graph), Write(label), scaled_sum_mean_sd_labels.animate.to_edge(RIGHT) ) self.play(FlashAround(label, run_time=2)) self.wait() random_dists = [normalize(np.random.random(6))**2 for x in range(8)] self.change_distribution( [*random_dists, alt_dists[-1]], top_plot, ss_plot, top_mean_sd_labels, get_N(), run_time=1.5 ) self.wait() # Formal statement gen_scaled_sum_label = self.get_sum_label("N", scaled=True) gen_scaled_sum_label.replace(new_scaled_sum_label) rect = SurroundingRectangle(gen_scaled_sum_label) rect.set_stroke(BLUE, 2) statement = Tex( R"\lim_{N \to \infty} P(a < \text{This value} < b) = \int_a^b " + label.get_string() + "dx", font_size=36 ) statement["N"].set_color(YELLOW) statement.next_to(rect, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) arrow = Arrow(statement["This value"], rect, buff=0.1) arrow.set_color(BLUE) bars = ss_plot.bars mid_i = np.argmax([bar.get_height() for bar in bars]) to_fade = VGroup(*bars[:mid_i - 5], *bars[mid_i + 10:]) shift_group = VGroup(ss_plot, graph) self.play(ShowCreation(rect)) self.play(ReplacementTransform(new_scaled_sum_label, gen_scaled_sum_label)) self.wait() self.play( FadeIn(statement[R"P(a < \text{This value} < b)"], 0.5 * DOWN) ) self.play( statement["This value"].animate.set_color(BLUE), ShowCreation(arrow) ) self.play( to_fade.animate.set_fill(opacity=0.1).set_stroke(width=0), graph.animate.set_stroke(width=1.5), ) self.wait() self.play(Write(statement[R"\lim_{N \to \infty}"])) self.wait() self.play(LaggedStart( shift_group.animate.shift(3 * RIGHT), FadeTransform(label, statement[label.get_string()]), Write(statement[R" = \int_a^b "]), Write(statement[R"dx"]), lag_ratio=0.4, run_time=3, )) self.wait() self.play(LaggedStart(*( Indicate(bar, color=BLUE) for bar in bars[mid_i - 5:mid_i + 10] ))) self.wait() def get_top_distribution_plot( self, dist, width=5, height=2.5, y_range=(0, 0.5, 0.1) ): # Axes and bars x_min = self.x_min axes = Axes( (x_min - 1, x_min + len(dist) - 1), y_range, width=width, height=height, ) axes.x_axis.add_numbers(font_size=24, excluding=[0]) axes.x_axis.numbers.shift(0.5 * axes.x_axis.get_unit_size() * LEFT) axes.y_axis.add_numbers(num_decimal_places=1, font_size=24, excluding=[0]) bars = ChartBars(axes, dist) bars.set_submobject_colors_by_gradient(*self.bar_colors) bars.set_opacity(self.bar_opacity) plot = VGroup(axes, bars) plot.move_to(LEFT).to_edge(UP) plot.axes = axes plot.bars = bars return plot def get_mu_sigma_annotations(self, plot, mu_tex=R"\mu", sigma_tex=R"\sigma", min_height=2.0, x_min=1): bars = plot.bars axes = plot.axes dist = get_dist(bars) mu, sigma = get_mean_and_sd(dist, x_min) mean_line = Line(DOWN, UP) mean_line.set_height(max(bars.get_height() + 0.25, min_height)) mean_line.set_stroke(PINK, 2) mean_line.move_to(axes.c2p(mu - 0.5, 0), DOWN) sd_lines = Line(DOWN, UP).replicate(2) sd_lines.arrange(RIGHT) sd_lines.set_stroke(RED, 2) sd_lines.match_height(mean_line) sd_lines[0].move_to(axes.c2p(mu - sigma - 0.5, 0), DOWN) sd_lines[1].move_to(axes.c2p(mu + sigma - 0.5, 0), DOWN) sd_arrows = VGroup(Vector(LEFT, stroke_width=3), Vector(RIGHT, stroke_width=3)) sd_arrows.arrange(RIGHT, buff=0.25) sd_arrows.set_width(0.85 * sd_lines.get_width()) sd_arrows.move_to(mean_line.pfp(0.75)) sd_arrows.set_color(RED) mu_label = Tex(mu_tex, color=PINK, font_size=30) mu_label.next_to(mean_line, UP, SMALL_BUFF) sigma_label = Tex(sigma_tex, color=RED, font_size=30) sigma_label.set_max_width(sd_arrows[1].get_width() * 0.8) sigma_label.next_to(sd_arrows[1], UP, SMALL_BUFF) return ( VGroup(mean_line, mu_label), VGroup(sd_lines, sd_arrows, sigma_label), ) def get_sum_label(self, n: str | int, dots=True, scaled: bool = False): if isinstance(n, int) and n not in [2, 3]: if len(str(n)) == 1: n_str = "0" else: n_str = "1" + "0" * (len(str(n)) - 1) else: n_str = str(n) if n_str == "2": sum_tex = R"X_1 + X_2" elif n_str == "3": sum_tex = R"X_1 + X_2 + X_3" elif dots: sum_tex = Rf"X_1 + \cdots + X_{{{n_str}}}" else: sum_tex = " + ".join(f"X_{{{k}}}" for k in range(1, int(n) + 1)) if scaled: sum_tex = "(" + sum_tex + ")" + Rf" - {n_str} \cdot \mu \over \sigma \cdot \sqrt{{{n_str}}}" sum_label = Tex( sum_tex, t2c={ R"\mu": PINK, R"\sigma": RED, n_str: YELLOW, }, font_size=40 ) if scaled: sum_label.scale(0.8) if isinstance(n, int) and n_str in sum_label.get_string(): n_parts = sum_label.make_number_changable(n_str, replace_all=True) for part in n_parts: part.set_value(n) sum_label.next_to(ORIGIN, DOWN) sum_label.to_edge(LEFT) return sum_label def get_scaled_sum_plot(self, dist, n): sum_dist = np.array(dist) for _ in range(n - 1): sum_dist = np.convolve(sum_dist, dist) axes = self.get_normal_plot_axes() mu, sigma = get_mean_and_sd(dist) x_min = n * self.x_min unscaled_xs = np.arange(x_min, x_min + len(sum_dist)) xs = (unscaled_xs - n * mu) / (sigma * math.sqrt(n)) bars = ChartBars(axes, sum_dist, xs=xs) bars.shift(0.5 * bars[0].get_width() * LEFT) bars.set_submobject_colors_by_gradient(*self.bar_colors) bars.set_opacity(self.bar_opacity) unit_area = axes.x_axis.get_unit_size() * axes.y_axis.get_unit_size() bar_area = sum(bar.get_width() * bar.get_height() for bar in bars) bars.stretch(unit_area / bar_area, 1, about_edge=DOWN) plot = VGroup(axes, bars) plot.set_stroke(background=True) plot.bars = bars plot.axes = axes return plot def get_normal_plot_axes(self): sum_axes = Axes( (-6, 6), self.normal_y_range, width=12, height=self.normal_axes_height ) sum_axes.center().move_to(FRAME_HEIGHT * DOWN / 4) sum_axes.x_axis.add_numbers(font_size=16) sum_axes.y_axis.add_numbers(num_decimal_places=1, font_size=16, excluding=[0]) return sum_axes def get_sum_plot( self, dist, n, top_plot, x_range=(0, 40), y_range=(0, 0.2, 0.1), x_num_range=(5, 40, 5), max_width=10, ): sum_dist = np.array(dist) for _ in range(n - 1): sum_dist = np.convolve(sum_dist, dist) x_min = n * self.x_min x_max = x_range[1] axes = Axes( x_range, y_range, width=top_plot.axes.x_axis.get_unit_size() * x_max, height=self.normal_axes_height, axis_config=dict(tick_size=0.05), ) axes.x_axis.set_max_width(max_width, stretch=True, about_point=axes.c2p(0, 0)) axes.shift(top_plot.axes.c2p(0, 0) - axes.c2p(0, 0)) axes.to_edge(DOWN) axes.x_axis.add_numbers(np.arange(*x_num_range), font_size=16, excluding=[0]) axes.x_axis.numbers.shift(0.5 * axes.x_axis.get_unit_size() * LEFT) axes.y_axis.add_numbers( num_decimal_places=len(str(y_range[2])) - 2, font_size=24, excluding=[0] ) bars = ChartBars(axes, sum_dist, xs=range(x_min - 1, x_min + len(sum_dist) - 1)) bars.set_submobject_colors_by_gradient(*self.bar_colors) bars.set_opacity(self.bar_opacity) plot = VGroup(axes, bars) plot.axes = axes plot.bars = bars return plot def get_mean_sd_labels(self, mu_tex, sigma_tex, mean, sd): label_kw = dict( t2c={ R"\mu": PINK, R"\sigma": RED, R"N": YELLOW, }, font_size=36 ) if len(mu_tex) > 0: mu_tex = "= " + mu_tex if len(sigma_tex) > 0: sigma_tex = "= " + sigma_tex labels = VGroup( Tex(Rf"\text{{mean}} {mu_tex} = 0.00", **label_kw), Tex(Rf"\text{{std dev}} {sigma_tex} = 0.00", **label_kw), ) labels.arrange(DOWN, aligned_edge=LEFT) values = [mean, sd] colors = [PINK, RED] for label, value, color in zip(labels, values, colors): num = label.make_number_changable("0.00") num.set_value(value) num.set_color(color) return labels def change_distribution( self, alt_dists, top_plot, ss_plot, top_mean_sd_labels, n, run_time=1, ): for dist in alt_dists: new_top_plot = self.get_top_distribution_plot(dist) new_top_plot.bars.align_to(top_plot.bars, DOWN) new_ss_plot = self.get_scaled_sum_plot(dist, n) mean, sd = get_mean_and_sd(dist) self.play( Transform(top_plot.bars, new_top_plot.bars), UpdateFromFunc( ss_plot.bars, lambda m: m.set_submobjects(self.get_scaled_sum_plot( get_dist(top_plot.bars), n ).bars) ), ChangeDecimalToValue(top_mean_sd_labels[0][-1], mean), ChangeDecimalToValue(top_mean_sd_labels[1][-1], sd), ) self.wait() self.distribution = dist class HowVarianceAdds(LimitingDistributions): def construct(self): # Define two distributions dist1 = EXP_DISTRIBUTION dist2 = np.convolve(dist1, U_SHAPED_DISTRIBUTION) plot1 = self.get_top_distribution_plot(dist1) plot2 = self.get_top_distribution_plot(dist2, y_range=(0, 0.301, 0.1)) plot1.to_corner(UL) plot2.to_corner(UR) plot2.bars.set_submobject_colors_by_gradient(TEAL_E, GREEN_D) top_plots = VGroup(plot1, plot2) label_kw = dict( font_size=60, t2c={"X": BLUE, "Y": GREEN} ) top_labels = VGroup( Tex("X", **label_kw), Tex("Y", **label_kw), ) for plot, label in zip(top_plots, top_labels): label.move_to(plot, UR).shift(LEFT) h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH) h_line.set_stroke(GREY_A, 1) # Define the sum sum_dist = np.convolve(dist1, dist2) sum_plot = self.get_top_distribution_plot( sum_dist, y_range=(0, 0.301, 0.1), width=10 ) sum_plot.to_corner(DL) sum_plot.bars.set_color_by_gradient(GREEN, YELLOW_E) sum_label = Tex("X + Y", **label_kw) sum_label.move_to(sum_plot, UL) sum_label.shift(RIGHT) # Define annotations top_annotations1 = VGroup(*(self.get_mu_sigma_annotations(plot1, "", ""))) top_annotations2 = VGroup(*(self.get_mu_sigma_annotations(plot2, "", ""))) sum_annotations = VGroup(*(self.get_mu_sigma_annotations(sum_plot, "", ""))) for annotations in [top_annotations1, top_annotations2, sum_annotations]: annotations[0].set_color(GREY_C) annotations[1].set_color(GREY_A) top_annotations = VGroup(top_annotations1, top_annotations2) # Define variance formula var_form = Tex( R"\text{Var}(X + Y) = \text{Var}(X) + \text{Var}(Y)", **label_kw ) var_form.scale(0.75) var_form.next_to(h_line, DOWN) var_form.to_edge(RIGHT, buff=1.0) note = TexText("(Assuming $X$ and $Y$ are independent!)", font_size=36) for key, color in label_kw["t2c"].items(): note[key].set_color(color) note.next_to(var_form, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) # Add them all! self.add(h_line) self.play( LaggedStartMap(FadeIn, top_plots, lag_ratio=0.7, run_time=2), LaggedStartMap(FadeIn, top_labels, lag_ratio=0.7, run_time=2), LaggedStartMap(FadeIn, top_annotations, lag_ratio=0.7, run_time=2), ) self.play( TransformFromCopy(plot1, sum_plot), TransformFromCopy(plot2, sum_plot.copy().fade(1)), TransformFromCopy(top_labels[0], sum_label[:1]), TransformFromCopy(top_labels[1], sum_label[1:]), TransformFromCopy(top_annotations1, sum_annotations), TransformFromCopy(top_annotations2, sum_annotations), ) # Show variance formulas self.play(LaggedStart( TransformMatchingShapes( sum_label.copy(), var_form[R"\text{Var}(X + Y) = "] ), TransformMatchingShapes( top_labels[0].copy(), var_form[R"\text{Var}(X)"] ), TransformMatchingShapes( top_labels[1].copy(), var_form[R"+ \text{Var}(Y)"] ), FadeIn(note, 0.25 * DOWN), lag_ratio=0.25 )) self.wait() # Sigma equation sigma_form = Tex( R"\sigma_{X + Y}^2 = \sigma_X^2 + \sigma_Y^2", **label_kw ) sigma_form.scale(0.75) sigma_form.move_to(var_form, LEFT) self.play(LaggedStart( FadeIn(sigma_form, 0.5 * DOWN), var_form.animate.shift(DOWN), note.animate.shift(DOWN).set_opacity(0.7), lag_ratio=0.2, run_time=2 )) self.wait() # Add many X_n plot1_group = VGroup(plot1, top_labels[0], top_annotations1) new_top_groups = plot1_group.replicate(4) for n, group in zip([1, 2, 3, "N"], new_top_groups): label = group[1] substr = Tex(str(n)) substr.match_color(label) substr.set_height(label.get_height() * 0.5) substr.next_to(label.get_corner(DR), RIGHT, buff=0.05) label.add(substr) new_top_groups.scale(0.5) dots = Tex(R"\dots", font_size=90) arranger = VGroup(*new_top_groups[:3], dots, *new_top_groups[3:]) arranger.arrange(RIGHT, buff=LARGE_BUFF) arranger.set_width(FRAME_WIDTH - 1) arranger.set_y(2.5) sum_dist = dist1 for _ in range(6): sum_dist = np.convolve(dist1, sum_dist) new_sum_plot = self.get_top_distribution_plot( sum_dist, y_range=(0, 0.2, 0.1), width=10 ) new_sum_plot.axes.x_axis.remove(new_sum_plot.axes.x_axis.numbers) new_sum_plot.to_corner(DL) new_sum_label = Tex( R"X_1 + \cdots + X_n", t2c={"X_1": BLUE, "X_n": BLUE} ) new_sum_label.next_to(new_sum_plot.axes.c2p(0, 0.2), UR) rules = VGroup(sigma_form, var_form, note) self.play( FadeOut(plot2, RIGHT), FadeOut(top_labels[1], RIGHT), FadeOut(top_annotations2, RIGHT), ) self.remove(plot1_group) self.play( FadeTransformPieces( plot1_group.replicate(4), new_top_groups, ), Write(dots), h_line.animate.shift(UP), FadeOut(sum_plot), FadeOut(sum_annotations), FadeOut(sum_label), rules.animate.scale(0.5).next_to(new_sum_plot.axes.c2p(0, 0), UP).to_edge(RIGHT), FadeIn(new_sum_plot), FadeIn(new_sum_label), ) self.wait() # New variance formula t2c = {"X_1": BLUE, "X_n": BLUE} new_var_form = Tex( # R"Var(X_1 + \cdots + X_n) = Var(X_1) + \cdots + Var(X_n) = n \cdot Var(X_1)", # R"\sigma_{X_1 + \cdots + X_n}^2 = \sigma_{X_1}^2 + \cdots + \sigma_{X_n}^2 = n \cdot \sigma_{X_1}^2", R"\sigma_{X_1 + \cdots + X_n}^2 = n \cdot \sigma_{X_1}^2", t2c=t2c ) new_sigma_form = Tex( R"\sigma_{X_1 + \cdots + X_n} = \sqrt{n} \cdot \sigma_{X_1}", t2c=t2c ) new_var_form.next_to(h_line, DOWN) new_var_form.to_edge(RIGHT, buff=2.5) new_sigma_form.next_to(new_var_form, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) rects = VGroup( SurroundingRectangle(new_var_form[R"\sigma_{X_1 + \cdots + X_n}^2"]), SurroundingRectangle(new_var_form[R"\sigma_{X_1}^2"]), ) var_labels = VGroup( Tex(R"\text{Var}(X_1 + \cdots + X_n)", t2c=t2c), Tex(R"\text{Var}(X_1)", t2c=t2c), ) for label, rect in zip(var_labels, rects): label.set_max_width(rect.get_width()) label.next_to(rect, DOWN) rect.add(label) self.play(FadeTransform(new_sum_label.copy(), new_var_form)) self.wait() # Test self.play(FadeIn(rects[0])) self.wait() self.play(FadeOut(rects[0]), FadeIn(rects[1])) self.wait() self.play(FadeOut(rects[1])) self.wait() self.play(TransformMatchingTex(new_var_form.copy(), new_sigma_form)) self.play(FlashAround(new_sigma_form[R"\sqrt{n}"], time_width=1.5, run_time=2)) self.wait() class InfiniteVariance(LimitingDistributions): def construct(self): # Test max_n = 300 full_dist = np.array([(1 / n**1.5) for n in range(3, max_n)]) old_plot = VGroup() var_label = Tex(R"\text{Var}(X) = 0.00", font_size=60) var_label.make_number_changable("0.00") var_label.move_to(2 * UP) var_label["X"].set_color(BLUE) self.add(var_label) for n in range(6, len(full_dist)): dist = full_dist[:n] / full_dist[:n].sum() plot = self.get_top_distribution_plot( dist, width=min(n * (5 / 6), 12), height=4, y_range=(0, 0.301, 0.1) ) plot.axes.x_axis.remove(plot.axes.x_axis.numbers) plot.axes.x_axis.add_numbers(range(0, n, 10), font_size=16) plot.axes.x_axis.ticks.stretch(0.2, 1) plot.bars.set_height(4, about_edge=DOWN, stretch=True) plot.shift(3 * DOWN + 6 * LEFT - plot.axes.c2p(0, 0)) annotations = VGroup(*(self.get_mu_sigma_annotations(plot, "", ""))) annotations.stretch(0.75, 1, about_edge=DOWN) annotations.set_opacity((max_n - n) / max_n) plot.add(annotations) mu, sigma = get_mean_and_sd(dist) var = sigma**2 if n < 12: self.play( FadeOut(old_plot), FadeIn(plot), ChangeDecimalToValue(var_label[-1], var), run_time=0.5 ) self.wait(0.5) else: self.remove(old_plot) self.add(plot) var_label[-1].set_value(var) self.wait(1 / 30) old_plot = plot inf = Tex(R"\infty", font_size=60) inf.move_to(var_label[-1], LEFT) self.remove(var_label[-1]) self.add(inf) self.wait() class RuleOfThumb(BuildUpGaussian): def construct(self): # Title colors = color_gradient([YELLOW, RED], 3) t2c = { "68": colors[0], "95": colors[1], "99.7": colors[2], } title = Text( "The 68–95–99.7 rule", font_size=60, t2c=t2c ) title.to_edge(UP, buff=MED_SMALL_BUFF) underline = Underline(title) underline.set_stroke(GREY, [0, 3, 3, 3, 0]).scale(1.2) self.add(title, underline) # Axes and graph axes = NumberPlane( (-4, 4), (0, 1.0, 0.1), width=0.5 * FRAME_WIDTH, height=5.5, background_line_style=dict( stroke_color=GREY_A, stroke_width=2, stroke_opacity=0.5 ) ) axes.to_edge(LEFT, buff=0) axes.to_edge(DOWN) axes.x_axis.add_numbers() axes.y_axis.add_numbers( np.arange(0.2, 1.2, 0.2), num_decimal_places=1, direction=DL, font_size=16, ) graph = axes.get_graph(lambda x: gauss_func(x, 0, 1)) graph.set_stroke(YELLOW, 3) self.add(axes, graph) # Function for changeable area area = VMobject() area.set_stroke(width=0) area.set_fill(YELLOW, 0.5) ab_tracker = ValueTracker(np.array([0, 0])) def update_area(area, dx=0.01): a, b = ab_tracker.get_value() if a == b: area.clear_points() return xs = np.arange(a, b, dx) ys = gauss_func(xs, 0, 1) samples = axes.c2p(xs, ys) area.set_points_as_corners([ *samples, axes.c2p(b, 0), axes.c2p(a, 0), samples[0], ]) area.add_updater(update_area) self.add(area) # Area decimal area_label = TexText("Area = 0.000", font_size=40) area_label.set_backstroke(width=8) num = area_label.make_number_changable("0.000") from scipy.stats import norm def get_area(): a, b = ab_tracker.get_value() return norm.cdf(b) - norm.cdf(a) num.add_updater(lambda m: m.set_value(get_area())) area_label.next_to(graph.get_top(), UR, buff=0.5) area_arrow = Arrow(area_label.get_bottom(), axes.c2p(0, 0.2)) # Normal label func_label = VGroup( Text("Standard normal\ndistribution", font_size=30), Tex(R"\frac{1}{\sqrt{2\pi}} e^{-x^2 / 2}").set_color(YELLOW) ) func_label[1][R"\frac{1}{\sqrt{2\pi}}"].scale(0.75, about_edge=RIGHT) func_label.arrange(DOWN) func_label.next_to(graph, UP).shift(DOWN) func_label.to_edge(LEFT) func_label.set_backstroke(width=8) self.play( FadeIn(func_label[0]), Write(func_label[1]), ) self.wait() # Rule of thumb labels labels = VGroup() for n, num, color in zip(it.count(1), [68, 95, 99.7], colors): label = Text(f""" {num}% of values fall within {n} standard deviations of the mean """, font_size=40) label[f"{n}"].set_color(color) label[f"{num}%"].set_color(color) labels.add(label) labels.arrange(DOWN, aligned_edge=LEFT, buff=LARGE_BUFF) labels.move_to(midpoint(axes.get_right(), RIGHT_SIDE)) # Show successive regions for n in range(3): anims = [ FadeIn(labels[n], DOWN), ab_tracker.animate.set_value([-n - 1, n + 1]), ] if n == 0: anims.extend([VFadeIn(area_label), FadeIn(area_arrow)]) self.play(*anims) self.wait() class AnalyzeHundreDiceQuestion(LimitingDistributions): distribution = [1 / 6] * 6 def construct(self): # Setup h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH) h_line.set_stroke(GREY, 2) self.add(h_line) N = 100 dist = self.distribution top_plot = self.get_top_distribution_plot(dist) top_plot.to_edge(LEFT) sum_plot_config = dict( x_range=(0, 500, 10), y_range=(0, 0.05, 0.01), x_num_range=(0, 600, 100), max_width=14, ) sum_plot = self.get_sum_plot(dist, N, top_plot, **sum_plot_config) sum_label = self.get_sum_label(N) self.add(top_plot) self.add(sum_plot) self.add(sum_label) # Add fair die labels sixths = Tex("1 / 6").replicate(6) sixths.set_width(0.4 * top_plot.bars[0].get_width()) for sixth, bar in zip(sixths, top_plot.bars): sixth.next_to(bar, UP, SMALL_BUFF) fair_label = Text("Fair die") fair_label.move_to(top_plot, UP) dot_config = dict(fill_color=BLUE_E, dot_color=WHITE, stroke_width=1) dice = VGroup(*( DieFace(value, **dot_config) for value in range(1, 7) )) for die, number in zip(dice, top_plot.axes.x_axis.numbers): die.match_height(number).scale(1.5) die.move_to(number) self.add(fair_label) self.add(sixths) self.add(dice) # Animate in plot for n in range(5, 101): sum_label.become(self.get_sum_label(n)) sum_plot.become(self.get_sum_plot(dist, n, top_plot, **sum_plot_config)) self.wait(1 / 30) n = 100 # Compute mean and standard deviation kw = dict( t2c={ "100": YELLOW, R"\mu": PINK, R"\mu_s": PINK, R"\mu_a": PINK, R"\sigma": RED, R"\sigma_s": RED, R"\sigma_a": RED, "3.5": PINK, "1.71": RED, }, font_size=36, ) top_mean = Tex( R"\mu = \frac{1}{6}\big(1 + 2 + 3 + 4 + 5 + 6\big) = 3.5", **kw ) top_var = Tex( R"\text{Var}(X) = \frac{1}{6}\Big((1 - 3.5)^2 + \cdots + (6 - 3.5)^2 \Big) = 2.92", **kw ) top_var.scale(0.8) top_var[R"\text{Var}(X) = "].scale(1 / 0.8, about_edge=RIGHT) top_var["= 2.92"].scale(1 / 0.8, about_edge=LEFT) top_var.refresh_bounding_box() top_sd = Tex(R"\sigma = \sqrt{\text{Var}(X)} = 1.71", **kw) top_eqs = VGroup(top_mean, top_var, top_sd) top_eqs.arrange(DOWN, buff=0.5, aligned_edge=LEFT) top_eqs.to_corner(UR, buff=0.25) top_mean_simple = Tex(R"\mu = 3.5", **kw).scale(1.25) top_sd_simple = Tex(R"\sigma = 1.71", **kw).scale(1.25) simp_eqs = VGroup(top_mean_simple, top_sd_simple) simp_eqs.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) simp_eqs.next_to(top_plot.bars, RIGHT, MED_LARGE_BUFF, aligned_edge=DOWN) self.play(Write(top_mean)) self.wait() self.play(Write(top_var)) self.wait() self.play( Write(top_sd), Transform(top_var[R"\text{Var}(X)"].copy(), top_sd[R"\text{Var}(X)"].copy(), remover=True) ) self.wait() self.play( TransformMatchingTex(top_mean.copy(), top_mean_simple), TransformMatchingTex(top_sd.copy(), top_sd_simple), top_eqs.animate.scale(0.75, about_edge=UR).set_opacity(0.5), ) self.wait() # Sum mean and sd low_mean = Tex(R"\mu_s = 100 \cdot \mu = 350", **kw) low_sd = Tex(R"\sigma_s = \sqrt{100} \cdot \sigma = 17.1", **kw) low_eqs = VGroup(low_mean, low_sd) low_eqs.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) low_eqs.next_to(h_line, DOWN) low_eqs.align_to(top_mean_simple, LEFT) mean_label, sd_label = self.get_mu_sigma_annotations( sum_plot, "350", "17.1", min_height=1.0, x_min=n ) self.play(TransformMatchingTex(top_mean_simple.copy(), low_mean)) self.play(Write(mean_label)) self.wait() self.play(TransformMatchingTex(top_sd_simple.copy(), low_sd, key_map={"1.71": "17.1"})) sd_label.save_state() sd_label.stretch(0, 0).set_opacity(0) self.play(Restore(sd_label)) self.wait() # Show range sd_lines, sd_arrows, sd_num = sd_label sd_line_ghosts = sd_lines.copy().set_opacity(0.5) sd_line_ghosts.stretch(0.75, 1, about_edge=DOWN) two_times = Tex(R"2 \, \cdot") two_times.match_height(sd_num) new_sd_num = VGroup(two_times, sd_num.copy()) new_sd_num.arrange(RIGHT, buff=SMALL_BUFF) new_sd_num.set_color(RED) new_sd_num.next_to(sd_arrows.get_right(), UP, SMALL_BUFF) new_sd_num.scale(1.25, about_edge=DOWN) bound_equations = VGroup( Tex(R"\mu_s - 2 \sigma_s = 350 - 2 \cdot 17.1 \approx 316", **kw), Tex(R"\mu_s + 2 \sigma_s = 350 + 2 \cdot 17.1 \approx 384", **kw), ) bound_equations.arrange(DOWN, aligned_edge=LEFT) bound_equations.move_to(sum_plot.axes.c2p(0, 0.035), UL) bound_equations.shift(RIGHT) self.add(sd_line_ghosts) self.play( sd_lines.animate.stretch(2, 0), sd_arrows.animate.stretch(2, 0), TransformMatchingShapes(sd_num, new_sd_num, run_time=1) ) new_sd_num.set_backstroke(BLACK, width=5) self.add(new_sd_num) self.wait() self.play(LaggedStartMap(FadeIn, bound_equations, shift=0.5 * UP, lag_ratio=0.75)) self.wait() rhss = VGroup(bound_equations[0]["316"], bound_equations[1]["384"]) rhs_rect = SurroundingRectangle(rhss) rhs_rect.set_stroke(YELLOW, 2) self.play(ShowCreation(rhs_rect)) self.wait() # Add range values to diagram new_rhss = rhss.copy() new_rhss.set_color(RED) new_rhss.scale(mean_label[1].get_height() / rhss[0].get_height()) for rhs, line in zip(new_rhss, sd_lines): rhs.next_to(line, UP, SMALL_BUFF) rhs.align_to(mean_label[1], DOWN) for rhs, new_rhs in zip(rhss, new_rhss): self.play(TransformFromCopy(rhs, new_rhs)) self.wait() self.play(LaggedStartMap( FadeOut, VGroup(*bound_equations, rhs_rect), shift=DOWN )) # Transition to sample mean case sample_mean_expr = Tex(R"X_1 + \cdots + X_{100} \over 100", **kw) sample_mean_expr.move_to(sum_label, UP) number_swaps = [] x_numbers = VGroup() new_x_labels = VGroup(*(Integer(k, font_size=36) for k in range(1, 6))) for old_label, new_label in zip(sum_plot.axes.x_axis.numbers, new_x_labels): faded_old_label = old_label old_label = old_label.copy() faded_old_label.set_opacity(0) self.add(old_label) new_label.move_to(old_label) number_swaps.append(FadeIn(new_label, 0.5 * UP)) number_swaps.append(FadeOut(old_label, 0.5 * UP)) x_numbers.add(old_label) diagram_labels = VGroup(new_rhss[0], mean_label[1], new_rhss[1], new_sd_num) new_diagram_labels = VGroup( DecimalNumber(3.16), DecimalNumber(3.50), DecimalNumber(3.84), Tex(R"2 \cdot 0.171") ) for old_label, new_label in zip(diagram_labels, new_diagram_labels): new_label.match_style(old_label.family_members_with_points()[0]) new_label.replace(old_label, dim_to_match=0) number_swaps.append(FadeOut(old_label, 0.5 * UP)) number_swaps.append(FadeIn(new_label, 0.5 * UP)) x_numbers.add(old_label) self.play(WiggleOutThenIn(sum_label)) length = len(sum_label) + 2 self.play( FadeTransform(sum_label, sample_mean_expr[:length]), Write(sample_mean_expr[length:]), ) self.wait() self.play(LaggedStartMap(FlashAround, x_numbers, lag_ratio=0.1, time_width=1.5)) self.play( LaggedStart(*number_swaps), low_eqs.animate.set_opacity(0.4), ) # Show dice rect = SurroundingRectangle(sample_mean_expr) rect.set_stroke(BLUE, 2) avg_words = Text("Average of\n100 rolls") avg_words.next_to(rect, RIGHT) dice = VGroup(*( DieFace(random.randint(1, 6), **dot_config) for x in range(100) )) dice.arrange_in_grid(10, 10) dice.set_height(2) dice.next_to(sum_plot.axes.c2p(0, 0), UR, SMALL_BUFF) dice.match_x(avg_words) self.play( ShowCreation(rect), Write(avg_words), FadeIn(dice, lag_ratio=0.1), ) self.wait() # Mean mean and sd label avg_mean = Tex(R"\mu_a = 3.5", **kw) avg_sd = Tex(R"\sigma_a = \sigma / \sqrt{100} = 0.171", **kw) avg_eqs = VGroup(avg_mean, avg_sd) avg_eqs.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) avg_eqs.move_to(low_eqs, UL) avg_eqs.shift(0.2 * LEFT) self.play( FadeIn(avg_mean, RIGHT), low_mean.animate.to_edge(RIGHT), ) self.wait() self.play( FadeIn(avg_sd, RIGHT), low_sd.animate.to_edge(RIGHT) ) self.wait() self.play( FlashAround(low_sd), low_sd.animate.set_opacity(1), ) self.wait() self.play(low_sd.animate.set_opacity(0.5)) self.wait() class Thumbnail(LimitingDistributions): def construct(self): # Tests dist = [1 / 6] * 6 ss_plot = self.get_scaled_sum_plot(dist, 50) for axis in ss_plot.axes: axis.remove(axis.numbers) for tick in axis.ticks: tick.scale(0.5) ss_plot.axes.y_axis.set_opacity(0) ss_plot.scale(2) ss_plot.bars.set_submobject_colors_by_gradient( *3 * [BLUE], *3 * [YELLOW] ) ss_plot.shift(2 * DOWN - ss_plot.axes.c2p(0, 0)) ss_plot.to_edge(DOWN) self.add(ss_plot) # Top plots top_plots = VGroup() np.random.seed(3) dists = [ EXP_DISTRIBUTION, normalize(np.random.random(6))**2, normalize(np.random.random(6))**2, U_SHAPED_DISTRIBUTION, ] for dist in dists: top_plot = self.get_top_distribution_plot(dist, width=3, height=2, y_range=(0, 0.401, 0.1)) for axis in top_plot.axes: axis.remove(axis.numbers) top_plots.add(top_plot) top_plot.bars.set_submobject_colors_by_gradient(BLUE_D, TEAL) top_plot.bars.set_stroke(WHITE, 1) top_plots.arrange(RIGHT, buff=2.0, aligned_edge=DOWN) top_plots.set_width(FRAME_WIDTH - 1) top_plots.to_edge(UP) arrows = VGroup(*( Arrow( tp.get_bottom(), ss_plot.bars.get_top() + vect, buff=0.3, stroke_width=10, stroke_color=YELLOW ) for tp, vect in zip(top_plots, np.linspace(2 * LEFT, 2 * RIGHT, len(top_plots))) )) self.add(top_plots) self.add(arrows) # Words words = Text("Bizarrely\nUniversal", font_size=90) words.move_to(ss_plot.axes.c2p(0, 0.03), DOWN).to_edge(LEFT) words.set_x(0) words.set_backstroke() # self.add(words) # Formula form = Tex(R"{1 \over \sqrt{2\pi}} e^{-x^2 / 2}", font_size=90) form.move_to(words, DOWN).to_edge(RIGHT)
from manim_imports_ext import * from _2023.clt.main import * import sympy class GaltonBoardName(InteractiveScene): def construct(self): # Test name = Text("Galton \nBoard", font_size=120) name.next_to(ORIGIN, RIGHT).shift(2 * UP) point = name.get_bottom() + 1 * DOWN arrow = Arrow( point, point + FRAME_WIDTH * LEFT * 0.25, stroke_width=10 ) self.add(name) self.play(GrowArrow(arrow)) self.wait() class NormalName(InteractiveScene): def construct(self): # Names names = VGroup( Text("Normal distribution"), Text("Bell curve"), Text("Gaussian distribution"), ) point = 2 * LEFT + 1.5 * UP names.next_to(point, UP) names.set_color(GREY_A) shift = 0.75 * UP names[0].scale(2, about_edge=DOWN) self.play(Write(names[0]), run_time=1) self.wait() self.play( names[0].animate.scale(0.5, about_edge=DOWN).shift(shift), FadeIn(names[1], shift=0.5 * shift), ) self.wait() self.play( names[:2].animate.shift(shift), FadeIn(names[2], shift=0.5 * shift) ) self.wait() # In a moment words = TexText("We'll unpack this in a bit", font_size=36) words.set_fill(GREY_A) words.next_to(point, UP) words.shift(0.5 * UL) arrow = Arrow( words.get_bottom() + LEFT, words.get_bottom() + DOWN, stroke_width=3, stroke_color=GREY_A, ) self.play(LaggedStart( FadeOut(names[1:]), FadeIn(words, lag_ratio=0.1), ShowCreation(arrow), lag_ratio=0.25 )) self.wait() class ErdosKac(InteractiveScene): def construct(self): # Title h_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) VGroup(h_line, v_line).set_stroke(GREY_A, 1) h_line.to_edge(UP, buff=1.0) titles = VGroup( Tex("N"), TexText(R"\# of distinct prime factors of $N$"), ) titles.next_to(h_line, UP) titles[0].set_x(-FRAME_WIDTH * 0.25) titles[1].set_width(6) titles[1].to_edge(RIGHT) v_line.set_x(titles[1].get_x(LEFT) - 0.25) self.add(titles) self.add(h_line) # Number line number_line = NumberLine((0, 10), width=10) number_line.add_numbers(excluding=[0]) number_line.numbers.shift(number_line.get_unit_size() * LEFT / 2) number_line.to_edge(DOWN, buff=LARGE_BUFF) self.add(number_line) stacks = VGroup(*( VGroup(VectorizedPoint(number_line.n2p(x - 0.5))) for x in range(1, 20) )) self.add(stacks) rect_template = Rectangle(width=number_line.get_unit_size(), height=0.1) rect_template.set_stroke(BLUE_E, 0.5) rect_template.set_fill(TEAL_E, 0.5) # Add normal curve mean = math.log(math.log(1e18)) sd = math.sqrt(mean) curve = FunctionGraph(lambda x: 10 * gauss_func(x, mean, sd), x_range=(0, 10, 0.25)) curve.set_stroke(RED, 2) curve.match_width(number_line) curve.move_to(number_line.n2p(0), DL) self.add(curve) # Show many numbers num = int(1e18) group = VGroup() for x in range(0, 100): rect = rect_template.copy() nf = len(sympy.factorint(num + x)) stack = stacks[nf - 1] rect.next_to(stack, UP, buff=0) rect.set_fill(YELLOW) self.remove(group) group = self.get_factor_group(num + x, h_line) self.add(group, rect) if x < 20: self.wait(0.5) else: self.wait(0.1) rect.set_fill(TEAL_E) stack.add(rect) self.add(stacks) def get_factor_group(self, num, h_line, font_size=36): # Test num_mob = Integer(num, font_size=font_size) num_mob.next_to(h_line, DOWN, MED_LARGE_BUFF).to_edge(LEFT, buff=0.25) rhs = self.get_rhs(num_mob) omega_n = len(sympy.factorint(num)) omega_n_mob = Integer(omega_n, color=YELLOW) omega_n_mob.match_y(num_mob) omega_n_mob.to_edge(RIGHT, buff=1) arrow = Arrow(rhs, omega_n_mob, buff=0.5) group = VGroup(num_mob, rhs, arrow, omega_n_mob) return group def get_rhs(self, num_mob): if not isinstance(num_mob, Integer): return VGroup() kw = dict(font_size=num_mob.get_font_size()) parts = [Tex("=", **kw)] for factor, exp in sympy.factorint(num_mob.get_value()).items(): base = Integer(factor, **kw) underline = Underline(base, stretch_factor=1) underline.set_stroke(YELLOW, 2) underline.set_y(base[0].get_y(DOWN) - 0.05) base.add(underline) if exp == 1: parts.append(base) else: exp_mob = Integer(exp, **kw) exp_mob.scale(0.75) exp_mob.next_to(base.get_corner(UR), RIGHT, buff=0.05) parts.append(VGroup(*base, *exp_mob)) parts.append(Tex(R"\times", **kw)) result = VGroup(*parts[:-1]) result.arrange(RIGHT, buff=SMALL_BUFF) result.next_to(num_mob, buff=SMALL_BUFF) target_y = num_mob[0].get_y() for part in result: part.shift((target_y - part[0].get_y()) * UP) self.add(result) return result class PopulationHeights(InteractiveScene): random_seed = 2 def construct(self): # Test func = lambda x: gauss_func(x, 1, 0.175) stacks = VGroup() all_pis = VGroup() for height in np.arange(0.6, 1.5, 0.1): n = int(10 * func(height)) randys = VGroup(*(self.get_pi(height) for _ in range(n))) randys.arrange(RIGHT, buff=SMALL_BUFF) stacks.add(randys) all_pis.add(*randys) stacks.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) for stack, color in zip(stacks, color_gradient([BLUE_C, BLUE_E], len(stacks))): for pi in stack: pi.body.set_color(color) stacks.set_height(FRAME_HEIGHT - 1) stacks.to_edge(LEFT) for pi in all_pis: pi.save_state() all_pis.shuffle() all_pis.arrange_in_grid(n_cols=15) all_pis.shuffle() self.play(FadeIn(all_pis, lag_ratio=0.01, run_time=4)) self.wait() self.play(LaggedStartMap(Restore, all_pis, lag_ratio=0.01, run_time=5)) self.wait() def get_pi(self, height=1): pi = Randolph( mode=random.choice(["happy", "hooray", "pondering", "tease"]), 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 pi.body.set_points(new_points) return pi class VideoPlan(InteractiveScene): def construct(self): # Rectangles full_rect = FullScreenRectangle() screen_rect = ScreenRectangle() screen_rect.set_height(5.5) screen_rect.to_edge(DOWN) screen_rect.set_fill(BLACK, 1) screen_rect.set_stroke(width=2) rects = VGroup(full_rect, screen_rect) self.add(*rects) # CLT title big_name = Text("The Central\nLimit Theorem", font_size=120) name = Text("The Central Limit Theorem", font_size=60) name.to_edge(UP) subtitle = Text("from the basics") subtitle.set_color(GREY_A) subtitle.next_to(name, DOWN) rects.set_opacity(0) self.play(FadeIn(big_name, lag_ratio=0.1)) self.wait() self.play( TransformMatchingStrings(big_name, name, run_time=1), full_rect.animate.set_opacity(1) ) self.play(FadeIn(subtitle, 0.5 * DOWN)) self.wait(2) # Next part group1 = VGroup(name, subtitle, screen_rect) group1.target = group1.generate_target() group1.target.set_width(FRAME_WIDTH * 0.5 - 1) group1.target.move_to(FRAME_WIDTH * LEFT * 0.25) screen2 = group1.target[2].copy() screen2.set_opacity(1) name2 = Text("Diving deeper") name2.scale(group1.target[0][0].get_height() / name2[0].get_height()) name2.move_to(group1.target[0]) group2 = VGroup(name2, screen2) group2.move_to(FRAME_WIDTH * RIGHT * 0.25) self.play(MoveToTarget(group1)) self.play( FadeTransform(screen_rect.copy(), screen2), FadeTransform(name.copy(), name2), ) self.wait() # Also follow-on to convolutions group1.target = group1.generate_target() group1.target[2].scale(0.75, about_edge=UP) group1.target[1].scale(0) group1.target.arrange(DOWN, buff=SMALL_BUFF) group1.target.to_corner(UL) conv_rect = group1.target[2].copy() conv_rect.set_stroke(WHITE, 3, 1) conv_image = ImageMobject("ConvolutionThumbnail") conv_image.replace(conv_rect) conv_name = Text("Convolutions") conv_name.replace(group1.target[0], dim_to_match=1) conv_group = Group(conv_name, conv_rect, conv_image) conv_group.to_corner(DL) arrows = VGroup( Arrow(group1.target[2].get_right(), screen2.get_left() + UP), Arrow(conv_rect.get_right(), screen2.get_left() + DOWN), ) arrows.set_color(BLUE) self.play(LaggedStart( MoveToTarget(group1), FadeIn(conv_group, DOWN), name2.animate.next_to(screen2, UP), lag_ratio=0.25 )) self.play(*map(GrowArrow, arrows)) self.wait() class NextVideoInlay(InteractiveScene): def construct(self): # Graph plane = NumberPlane( (-5, 5), (-0.25, 1.0, 0.25), width=2.5, height=1.25, background_line_style=dict( stroke_color=GREY_B, stroke_width=1, ), faded_line_style=dict( stroke_color=GREY_B, stroke_width=1, stroke_opacity=0.25, ), faded_line_ratio=4 ) plane.set_height(FRAME_HEIGHT) graph = plane.get_graph(lambda x: gauss_func(x, 0, 1)) graph.set_stroke(YELLOW, 3) self.add(plane) self.play( VShowPassingFlash(graph.copy().set_stroke(TEAL, 10), time_width=1.5), ShowCreation(graph), run_time=2 ) # Function name expr = Tex( R"{1 \over \sqrt{2\pi}} e^{-x^2 / 2}", ) expr.set_height(3) expr.next_to(plane.c2p(0, 0.25), UP) expr.to_edge(LEFT) expr.set_backstroke(width=20) self.play(Write(expr, lag_ratio=0.1)) self.wait() # Questions rects = VGroup( SurroundingRectangle(expr["e^{-x^2 / 2}"]).set_stroke(TEAL, 5), SurroundingRectangle(expr[R"\pi"]).set_stroke(RED, 5), ) questions = [ Text("Why this function?"), Text("Where's\nthe circle?", alignment="LEFT"), ] for question, rect, vect in zip(questions, rects, [UP, DOWN]): question.scale(2) question.next_to(rect, vect, MED_LARGE_BUFF, aligned_edge=LEFT) question.match_color(rect) question.set_backstroke(width=20) self.play( FadeIn(questions[0]), ShowCreation(rects[0]), ) self.wait() self.play( FadeIn(questions[1]), ShowCreation(rects[1]), ) self.wait() class SumsOfSizeFive(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.play( morty.change("raise_right_hand", self.screen), self.change_students("pondering", "happy", "tease", look_at=self.screen) ) self.wait() # Show sums def get_sum(): values = [ Integer(random.choice([-1, 1]), include_sign=True) for x in range(5) ] lhs = Tex(R"\text{Sum} = ") rhs = Integer(sum(v.get_value() for v in values)) result = VGroup(lhs, *values, Tex(R" = "), rhs) result.arrange(RIGHT, buff=0.15) result.next_to(self.screen, RIGHT, buff=-0.5) return result curr_sum = get_sum() brace = Brace(curr_sum[1:-2], UP) brace_text = brace.get_text("5 values") brace_text.set_color(YELLOW) self.add(curr_sum) self.play(GrowFromCenter(brace), FadeIn(brace_text)) for x in range(7): new_sum = get_sum() self.play( FadeOut(curr_sum[1:], lag_ratio=0.1, shift=0.2 * UP), FadeIn(new_sum[1:], lag_ratio=0.1, shift=0.2 * UP), *(pi.animate.look_at(new_sum) for pi in self.pi_creatures) ) self.wait() curr_sum = new_sum self.wait() class HighLevelCLTDescription(InteractiveScene): def construct(self): # Title title = Text("General idea of the Central Limit Theorem", font_size=60) title.to_edge(UP, buff=MED_SMALL_BUFF) title["Central Limit Theorem"].set_color(YELLOW) underline = Underline(title) underline.scale(1.2) underline.set_stroke(WHITE, [0, 3, 3, 0]) self.add(title) self.play(ShowCreation(underline)) self.wait() # Random variables kw = dict(font_size=42) words = TexText("Start with a random variable: $X$", **kw) words["random variable: $X$"].set_color(BLUE) sub_words = Text(""" (a random process, where each outcome is associated with some number) """, font_size=32) sub_words.next_to(words, DOWN) sub_words.set_color(GREY_A) point1 = VGroup(words, sub_words) point1.next_to(underline, DOWN, buff=0.7) point1.to_edge(LEFT, buff=MED_SMALL_BUFF) example_boxes = Square().replicate(2) example_boxes.set_height(1.75) example_boxes.set_width(2.25, stretch=True) example_boxes.arrange(RIGHT, buff=1) example_boxes.set_stroke(WHITE, 1) example_boxes.match_y(point1) example_boxes.to_edge(RIGHT) self.play( Write(words, run_time=1, stroke_width=1), LaggedStartMap(FadeIn, example_boxes, lag_ratio=0.5), ) self.wait() self.play(FadeIn(sub_words, 0.25 * DOWN)) self.wait() # Sample many point2 = TexText(R""" Add $N$ samples of this variable \\ $X_1 + X_2 + \cdots + X_N$ """, **kw) point2["$N$ samples"].set_color(RED) point2[R"$X_1 + X_2 + \cdots + X_N$"].set_color(BLUE).shift(0.25 * DOWN) point2.next_to(point1, DOWN, buff=1.1, aligned_edge=LEFT) example_boxes2 = example_boxes.copy() example_boxes2.match_y(point2) self.play( FadeIn(point2, DOWN), FadeIn(example_boxes2, DOWN), ) self.wait() # Distribution point3 = TexText(R""" The distribution of this sum looks \\ more like a bell curve as $N \to \infty$ """, **kw) point3["this sum"].set_color(BLUE) point3["bell curve"].set_color(YELLOW) point3[R"$N \to \infty$"].set_color(RED) point3.next_to(point2, DOWN, buff=1.25, aligned_edge=LEFT) example_boxes3 = example_boxes.copy() example_boxes3.match_y(point3) self.play( FadeIn(point3, DOWN), FadeIn(example_boxes3, DOWN), ) self.wait() class GoalsThisLesson(TeacherStudentsScene): def construct(self): self.add(self.screen) self.screen.set_stroke(width=2) morty = self.teacher stds = self.students self.play( morty.change("tease"), self.change_students("confused", "thinking", "hesitant", look_at=self.screen) ) self.wait(2) # Goals title = Text("Goals of this lesson", font_size=60) title.to_corner(UR) underline = Underline(title) underline.scale(1.2) underline.set_color(GREY_B) goals = BulletedList( "Make this quantitative", "Put formulas to it", "Use it to predict", buff=0.35, font_size=48 ) goals.next_to(underline, DOWN, MED_LARGE_BUFF) goals.align_to(title, LEFT) self.play( FadeIn(title), ShowCreation(underline), morty.change("raise_right_hand", title), self.change_students("erm", "thinking", "tease", look_at=title) ) self.wait() for goal in goals: self.play(FadeIn(goal, UP)) self.wait() # Three assumptions new_title = VGroup( Text("3 assumptions underlie the"), Text("Central Limit Theorem"), ) for line in new_title: line.match_width(title) new_title.arrange(DOWN) new_title.move_to(title, UP) new_title.set_color(RED) numbers = VGroup(Tex("1."), Tex("2."), Tex("3.")) numbers.arrange(DOWN, buff=0.5, aligned_edge=LEFT) numbers.next_to(new_title, DOWN, buff=0.75, aligned_edge=LEFT) numbers.set_color(RED) boxes = VGroup(*( Rectangle(height=1.2 * num.get_height(), width=4).next_to(num) for num in numbers )) boxes.set_stroke(width=0) boxes.set_fill(interpolate_color(RED_E, BLACK, 0.8), 1) for box in boxes: box.save_state() box.stretch(0, 0, about_edge=LEFT) self.play( FadeOut(title, 0.5 * DOWN), FadeIn(new_title, 0.5 * DOWN), underline.animate.next_to(new_title, DOWN, SMALL_BUFF).set_color(RED_E), LaggedStartMap(FadeOut, goals, shift=DOWN), morty.change("tease", new_title), self.change_students("hesitant", "pondering", "skeptical", new_title), ) self.play( FadeIn(numbers, lag_ratio=0.25), morty.change("raise_left_hand") ) self.wait(2) self.play( LaggedStartMap(Restore, boxes), LaggedStart( morty.change("tease"), stds[0].change("angry"), stds[1].change("hesitant"), stds[2].change("erm"), lag_ratio=0.2 ) ) self.wait(4) # # Reference again and look down # self.remove(self.screen) # self.remove(self.background) # self.play( # morty.change("raise_left_hand", boxes), # self.change_students(look_at=boxes) # ) # self.wait(2) # self.play( # self.change_students("pondering", "pondering", "pondering", look_at=BOTTOM + 3 * LEFT), # morty.change("tease", stds) # ) # self.wait(3) class CommentOnSpikeyBellCurve(TeacherStudentsScene): def construct(self): self.remove(self.background) morty = self.teacher stds = self.students # Test self.play( morty.says("Kind of a\nbell curve", mode="shruggie"), self.change_students("erm", "hesitant", "hesitant", look_at=self.screen) ) self.wait(3) self.play( stds[1].says("Is it...supposed to\nlook like that?"), morty.debubble(), ) self.look_at(self.screen) self.wait(2) self.play( stds[2].says("How many samples\nuntil we're sure?"), stds[1].debubble(), ) self.wait(5) class ConvolutionsWrapper(VideoWrapper): title = "Convolutions" wait_time = 8 class WhatElseDoYouNotice(TeacherStudentsScene): def construct(self): morty = self.teacher self.remove(self.background) self.play( morty.says("What else do\nyou notice?"), self.change_students("pondering", "erm", "pondering", look_at=self.screen) ) self.wait(2) self.play(self.change_students("erm", "pondering", "tease", look_at=self.screen)) self.wait(2) class ReferenceMeanAndSD(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.remove(self.background) self.play( morty.says("We must put\nnumbers to those!", mode="surprised"), self.change_students("hesitant", "concerned_musician", "tease") ) self.look_at(self.screen) self.wait(3) # Mean and sd kw = dict(t2c={R"\mu": PINK, R"\sigma": RED}, font_size=42) terms = VGroup( Tex(R"\text{Mean: } \mu = E[X]", **kw), Tex(R"\text{Std dev: } \sigma = \sqrt{E[(X - \mu)^2]}", **kw), ) terms.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) terms.next_to(morty, UP, LARGE_BUFF) terms.to_edge(RIGHT) self.play( morty.debubble(mode="raise_right_hand", look_at=terms), self.change_students("pondering", "hesitant", "happy", look_at=terms), LaggedStartMap(FadeIn, terms, shift=UP, lag_ratio=0.5) ) self.wait(3) self.play( stds[2].says("Great!", mode="hooray"), morty.change("happy") ) self.play( stds[0].says("Wait, can you\nremind me?", mode="guilty"), morty.change("tease") ) self.wait(5) class AskWhy(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.play( stds[1].says("Why?", mode="raise_left_hand") ) self.play( morty.change("tease"), self.change_students("pondering", "raise_left_hand", "confused", look_at=morty.get_top() + 3 * UP) ) self.wait(8) class PDFWrapper(VideoWrapper): title = "Probability Density Functions" wait_time = 8 class AskAboutPi(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.remove(self.background) self.play(LaggedStart( morty.change("happy"), stds[1].says("Wait, what?!", mode="surprised"), stds[0].change("confused", self.screen), stds[2].change("hesitant", self.screen), )) self.wait() self.play( stds[2].says("Where's the\ncircle?", mode="raise_left_hand") ) self.wait(3) self.play( stds[1].debubble(), stds[2].debubble(), morty.says(TexText(R"We'll cover \\ that later")) ) self.wait(2) class WhyPiQuestion(InteractiveScene): def construct(self): # Axes axes = Axes((-3, 3), (0, 2, 0.5), width=10, height=5) axes.x_axis.add_numbers(font_size=16) axes.y_axis.add_numbers(num_decimal_places=1, font_size=16) graph = axes.get_graph(lambda x: math.exp(-x**2)) graph.set_stroke(BLUE, 2) graph.set_fill(TEAL, 0.5) self.add(axes, graph) # Labels graph_label = Tex("e^{-x^2}", font_size=72) graph_label.next_to(graph.pfp(0.4), UL) self.add(graph_label) area_label = Tex(R"\text{Area} = \sqrt{\pi}") area_label.move_to(graph, UR) area_label.shift(UL) arrow = Arrow(area_label.get_bottom(), graph.get_center() + 0.5 * RIGHT) self.add(area_label, arrow) question = Text("But where's the circle?", font_size=30) question.set_color(YELLOW) question.next_to(area_label, DOWN) question.to_edge(RIGHT) self.add(question) class WeCanBeMoreElegant(TeacherStudentsScene): def construct(self): self.play( self.teacher.says("We can be\nmore elegant"), self.change_students("pondering", "confused", "sassy", look_at=self.screen) ) self.wait() self.play(self.students[2].change("tease", look_at=self.teacher.eyes)) self.wait(3) class OneMoreNuance(InteractiveScene): def construct(self): morty = Mortimer() morty.to_edge(DOWN) self.play(morty.says("One more\nquick nuance", mode="speaking")) self.play(Blink(morty)) self.play(morty.change("tease", look_at=BOTTOM)) self.wait() for x in range(2): self.play(Blink(morty)) self.wait() class LetsHaveFun(InteractiveScene): def construct(self): morty = Mortimer() morty.to_edge(DOWN) self.play(morty.says("Let's have\nsome fun", mode="hooray", look_at=BOTTOM)) for x in range(2): self.play(Blink(morty)) self.wait() class AskAboutFormalStatement(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students question = Text( "But what is the\ncentral limit\ntheorem", t2s={"theorem": ITALIC}, t2c={"theorem": YELLOW}, ) self.play( stds[2].says(question, mode="sassy", bubble_direction=LEFT) ) self.play(morty.change("guilty")) self.play( stds[0].change("pondering"), stds[1].change("erm"), ) self.wait(8) class TrueTheoremWords(InteractiveScene): def construct(self): words = "Actual rigorous\nno-jokes-this-time\nCentral Limit Theorem" text = Text(words) text.set_height(0.3 * FRAME_HEIGHT) text.to_edge(UP) for word in ["Actual", "rigorous", "no-","jokes-", "this-", "time", "Central", "Limit", "Theorem"]: self.add(text[word]) self.wait(0.1 * len(word)) self.wait() class ExampleQuestion(TeacherStudentsScene): def construct(self): # Setup question = Text(""" Consider rolling a fair die 100 times, and adding the results. Find a range of values such that you're 95% sure the sum will fall within this range. """, alignment="LEFT") question.to_corner(UL) die_values = np.random.randint(1, 7, 100) dice = VGroup(*( DieFace( value, fill_color=BLUE_E, stroke_width=1, dot_color=WHITE ) for value in die_values )) dice.arrange_in_grid() dice.set_height(3.0) dice.next_to(question, RIGHT, buff=1) dice.to_edge(UP, buff=1.0) sum_label = TexText("Sum = 100") sum_label.next_to(dice, UP) num = sum_label.make_number_changable("100") n_tracker = ValueTracker(0) num.add_updater(lambda m: m.set_value(sum(die_values[:int(n_tracker.get_value())]))) # Ask for an example morty = self.teacher stds = self.students self.play( stds[2].says("Can we see a\nconcrete example?"), morty.change("happy") ) self.wait() # Add up dice die_highlights = dice.copy() die_highlights.set_stroke(YELLOW, 1) part1 = re.findall(r"Consider .*\n.* results.", question.get_string())[0] self.play( morty.change("raise_right_hand", question), self.change_students("pondering", "pondering", "tease", look_at=question), FadeIn(question[part1], lag_ratio=0.1, run_time=1.5), FadeOut(stds[2].bubble), FadeOut(stds[2].bubble.content), ) self.play( FlashUnder(question["fair die"]), question["fair die"].animate.set_color(YELLOW), FadeIn(dice, lag_ratio=0.03, run_time=2), ) self.play( *(pi.animate.look_at(dice) for pi in [morty, *stds]) ) n_tracker.set_value(0) self.play( VFadeIn(sum_label), n_tracker.animate.set_value(100).set_anim_args(run_time=2), ShowIncreasingSubsets(die_highlights, run_time=2) ) self.play(FadeOut(die_highlights)) self.wait() # Find a range part2 = re.findall(r"Find .*\n.*\n.* range.", question.get_string())[0] self.play( morty.change("tease", question), self.change_students("erm", "hesitant", "pondering", look_at=question), FadeIn(question[part2], lag_ratio=0.1, run_time=1.5), ) self.wait() self.play( FlashUnder(question[r"95% sure"], color=TEAL), question[r"95% sure"].animate.set_color(TEAL) ) self.wait(2) self.play(self.change_students("confused", "erm", "tease", look_at=question)) self.wait(3) class ExampleQuestionNoPiCreatures(InteractiveScene): def construct(self): # Setup question = [ Text(""" Consider rolling a die 100 times, and adding the results. """, alignment="LEFT"), Text(""" Find a range of values such that you're 95% sure the sum will fall within this range. """, alignment="LEFT") ] question[0].to_corner(UL) question[1].to_corner(UR) # Dice def get_dice(): die_values = np.random.randint(1, 7, 100) dice = VGroup(*( DieFace( value, fill_color=BLUE_E, stroke_width=1, dot_color=WHITE ) for value in die_values )) dice.arrange_in_grid() dice.set_height(4.5) dice.next_to(question[0], DOWN, buff=1) return dice dice = get_dice() sum_label = TexText("Sum = 100", font_size=60) sum_label.next_to(dice, RIGHT, buff=LARGE_BUFF) num = sum_label.make_number_changable("100") num.add_updater(lambda m: m.set_value(sum( die.value for die in dice ))) # Add up dice self.play(FadeIn(question[0], lag_ratio=0.1, run_time=1.5)) self.play( VFadeIn(sum_label), ShowIncreasingSubsets(dice, run_time=2) ) self.wait() # Find a range self.play( FadeIn(question[1], lag_ratio=0.1, run_time=1.5), ) self.wait() self.play( FlashUnder(question[1][r"95% sure"], color=TEAL), question[1][r"95% sure"].animate.set_color(TEAL) ) # More sums for x in range(5): old_dice = dice.copy() dice.set_submobjects(list(get_dice())) self.play(ShowIncreasingSubsets(dice, run_time=2), FadeOut(old_dice, run_time=0.5)) self.wait() class AverageDiceValues(InteractiveScene): def construct(self): # Test avg_label = TexText("Average value = 0.00") avg_label.make_number_changable("0.00") avg_label.next_to(ORIGIN, RIGHT) avg_label.set_y(FRAME_HEIGHT / 4) self.add(avg_label) self.old_dice = VGroup() for _ in range(20): self.show_sample(avg_label, 100) self.wait(2) def show_sample(self, avg_label, n_dice, added_anims=[]): dice = VGroup(*( DieFace(random.randint(1, 6), fill_color=BLUE_E, dot_color=WHITE, stroke_width=1) for x in range(n_dice) )) dice.arrange_in_grid() dice.set_height(3.5) dice.next_to(avg_label, LEFT, buff=LARGE_BUFF) dice.to_edge(UP, buff=MED_SMALL_BUFF) self.play(LaggedStart( FadeOut(self.old_dice, run_time=0.5), ShowIncreasingSubsets(dice, run_time=1, int_func=np.ceil), UpdateFromFunc(avg_label[-1], lambda m: m.set_value( np.mean([die.value for die in dice]) )), *added_anims )) avg_label[-1].set_color(YELLOW) self.old_dice = dice class DoesThisMakeSense(InteractiveScene): def construct(self): rect = SurroundingRectangle(Tex(R"\sigma_a = \sigma / \sqrt{100} = 0.171")) words = Text("Does this make sense?") words.next_to(rect, DOWN) words.align_to(rect.get_center(), RIGHT) rect.set_stroke(RED, 2) words.set_color(RED) self.play( ShowCreation(rect), Write(words) ) self.wait() class OneMoreSideNote(TeacherStudentsScene): def construct(self): # Test self.play( self.change_students("pondering", "pondering", "erm", look_at=self.screen) ) self.wait() self.play( self.teacher.says( "Will you tolerate\none more\nside note?", mode="speaking", ), ) self.play( self.change_students("tired", "pondering", "hesitant") ) self.wait(4) class ThreeAssumptions(InteractiveScene): def construct(self): # Title title = Text("Three assumptions", font_size=60) title.to_edge(UP, buff=MED_SMALL_BUFF) title.set_color(RED) underline = Underline(title, stretch_factor=1.5) underline.match_color(title) underline.shift(0.15 * UP) # Points points = [ TexText(R"1. All $X_i$'s are independent \\ from each other."), TexText(R"2. Each $X_i$ is drawn from \\ the same distribution."), TexText(R"3. $0 < \text{Var}(X_i) < \infty$"), ] points[0]["from each other."].align_to(points[0]["All"], LEFT) points[1]["the same distribution."].align_to(points[1]["Each"], LEFT) VGroup(*points).arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT).to_edge(LEFT) for point in points: point["X_i"].set_color(BLUE) rects = VGroup(*(SurroundingRectangle(point[2:]) for point in points)) rects.set_stroke(width=0) rects.set_fill(interpolate_color(RED_E, BLACK, 0.9), 1.0) # Add title and numbers self.add(title) self.play(ShowCreation(underline, run_time=2)) self.play( LaggedStart(*( Write(point[:2]) for point in points ), lag_ratio=0.7), LaggedStartMap(FadeIn, rects, lag_ratio=0.7) ) self.add(*points, rects) self.wait() # Add first two points self.play(rects[0].animate.stretch(0, 0, about_edge=RIGHT)) self.remove(rects[0]) self.wait() word = points[0]["independent"] self.play( FlashUnder(word, color=TEAL), word.animate.set_color(TEAL), ) self.wait() self.play(rects[1].animate.stretch(0, 0, about_edge=RIGHT)) self.remove(rects[1]) self.wait() word = points[1]["same distribution"] self.play( FlashUnder(word, color=YELLOW), word.animate.set_color(YELLOW), ) self.wait() # Mention iid box = SurroundingRectangle(VGroup(*points[:2])) box.set_stroke(GREY_C, 2) iid_words = TexText(R"i.i.d. $\rightarrow$ independent and identically distributed") iid_words.next_to(box, UP, MED_LARGE_BUFF, aligned_edge=LEFT) title.add(underline) self.play( FadeOut(title), ShowCreation(box), ) self.play(Write(iid_words)) self.wait(2) self.play( FadeOut(box), FadeOut(iid_words), FadeIn(title) ) self.wait() # Mention generalizations gen_words = TexText(R"These can be relaxed (see Lindeberg CLT, $\alpha$-mixing, etc.)") gen_words.scale(0.7) gen_words.set_color(GREY_A, 1) gen_words.next_to(box, UP, aligned_edge=LEFT) self.play( FadeOut(title), FadeIn(gen_words), FadeIn(box) ) self.wait(2) self.play( FadeOut(box), FadeOut(gen_words), FadeIn(title), ) self.wait() # Add last point self.play(rects[2].animate.stretch(0, 0, about_edge=RIGHT)) self.remove(rects[2]) self.wait(2) class VariableSum(InteractiveScene): def construct(self): expr = Tex(R"X_1 + X_2 + \cdots + X_n") for c in "12n": expr["X_" + c].set_color(BLUE) self.add(expr) class AssumingNormality(InteractiveScene): def construct(self): # Setup randy = Randolph().to_corner(DL) morty = Mortimer().to_corner(DR) randy.shift(2 * RIGHT) thought = ThoughtBubble(height=2, width=3, direction=RIGHT) thought.pin_to(randy) curve = FunctionGraph(lambda x: 5 * gauss_func(x, 0, 1), x_range=(-3, 3, 0.1)) curve.set_stroke(YELLOW, 3) curve.scale(0.35) curve.move_to(thought.get_bubble_center() + 0.15 * UL) self.add(FullScreenRectangle().set_fill(GREY_E, 0.5)) self.add(randy, morty) self.add(thought, curve) # Words self.play( randy.says( TexText( R""" It's a $3\sigma$ event, \\ so $p < 0.003$ """, t2c={R"\sigma": RED} ), look_at=morty.eyes, mode="tease" ), morty.change("hesitant", randy.eyes) ) self.play(Blink(morty)) self.wait() self.play(Blink(randy)) self.wait() self.play( morty.says("Is it though?", look_at=randy.eyes, mode="sassy"), randy.change("guilty", morty.eyes) ) self.wait() self.play(Blink(randy)) self.wait() class FiniteExpectations(InteractiveScene): def construct(self): tex = TexText(R"And finite $E[X]$ for that matter", t2c={"X": BLUE}) self.add(tex) class EndScreen(PatreonEndScreen): scroll_time = 30
from manim_imports_ext import * from _2023.convolutions2.continuous import * class IntroWords(InteractiveScene): def construct(self): # Test title1 = Text("Last video", font_size=72) title1.to_edge(UP) title2 = Text("Today: An important example", font_size=72) title2.move_to(title1) VGroup(title1, title2).set_backstroke(width=3) self.play(Write(title1, run_time=1)) self.wait() self.play( FadeOut(title1, 0.5 * UP), FadeIn(title2, 0.5 * UP), ) self.wait() class NewIntroWords(InteractiveScene): def construct(self): kw = dict(font_size=66) words = VGroup( Text("Last chapter", **kw), Text("Convolution between two Gaussians", **kw), Text("Central Limit Theorem", **kw), Text("Today: A satisfying visual argument", **kw), ) words.to_edge(UP, buff=MED_SMALL_BUFF) last_word = VMobject() for word in words: self.play( FadeOut(last_word, 0.5 * UP), FadeIn(word, 0.5 * UP), ) self.wait() last_word = word class MultipleBellishCurves(InteractiveScene): def construct(self): # Axes line_style = dict(stroke_color=GREY_B, stroke_width=1) faded_line_style = dict(stroke_opacity=0.25, **line_style) all_axes = VGroup(*( NumberPlane( (-3, 3), (0, 1, 0.5), height=1.5, width=4, background_line_style=line_style, faded_line_style=faded_line_style, ) for _ in range(3) )) all_axes.arrange(DOWN, buff=LARGE_BUFF) all_axes.to_edge(LEFT) # Graphs def pseudo_bell(x): A = np.abs(x) + np.exp(-1) return np.exp(-np.exp(-1)) * A**(-A) graphs = VGroup( all_axes[0].get_graph(lambda x: np.exp(-x**2)), all_axes[1].get_graph(lambda x: 1 / (1 + x**2)), all_axes[2].get_graph(pseudo_bell), ) labels = VGroup( Tex("e^{-x^2}"), Tex(R"\frac{1}{1 + x^2}"), Tex( R"e^{-1 / e}\left(|x|+\frac{1}{e}\right)^{-\left(|x|+\frac{1}{e}\right)}", font_size=40 ), ) plots = VGroup() colors = color_gradient([YELLOW, RED], 3) for axes, label, graph, color in zip(all_axes, labels, graphs, colors): label.next_to(axes, RIGHT) graph.set_stroke(color, 3) plots.add(VGroup(axes, graph)) # Show initial graph plot = plots[0] plot.save_state() plot.center() plot.set_height(4) label = labels[0] label.save_state() label.set_height(1.25) label.next_to(plot.get_corner(UR), DL) words = Text("Normal Distribution (aka Gaussian)", font_size=60) words.next_to(plot, UP, MED_LARGE_BUFF) words.save_state() normal = words["Normal Distribution"] gaussian = words["(aka Gaussian)"] gaussian.set_opacity(0) normal.set_x(0) gaussian.set_x(0) self.add(plot) self.add(words) graph_copy = plot[1].copy() self.play(UpdateFromAlphaFunc( plot[1], lambda m, a: m.pointwise_become_partial( graph_copy, 0.5 - 0.5 * a, 0.5 + 0.5 * a ), run_time=2, )) self.play(words.animate.restore()) self.wait() self.play( Write(label), VShowPassingFlash( graph_copy.set_stroke(YELLOW, width=10), time_width=2, run_time=3, ), ) self.wait() # Ask why question = Text("Why this function?", font_size=60) arrow = Vector(LEFT) arrow.next_to(label.saved_state, RIGHT) question.next_to(arrow, RIGHT) self.play( plot.animate.restore(), label.animate.restore(), words.animate.match_width(plot.saved_state).next_to(plot.saved_state, UP, SMALL_BUFF), GrowArrow(arrow), FadeIn(question, lag_ratio=0.1, shift=0.2 * LEFT), ) self.wait() last_plot = plot last_label = label for plot, label in zip(plots[1:], labels[1:]): self.play( TransformFromCopy(last_plot, plot), TransformMatchingTex(last_label.copy(), label, run_time=1), ) self.wait() last_plot = plot last_label = label self.wait() # Highlight first function l0 = labels[0] l0.generate_target() l0.target.set_height(1.0, about_edge=DL) l0.target.shift(0.1 * RIGHT) self.play(LaggedStart( MoveToTarget(l0), VGroup(arrow, question).animate.next_to(l0.target, RIGHT, aligned_edge=DOWN), labels[1:].animate.fade(0.5), plots[1:].animate.fade(0.5), FlashAround(l0.target, time_width=1.5), )) self.wait() class LastFewVideos(InteractiveScene): def construct(self): self.add(FullScreenRectangle()) # Images root = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/" images = Group(*( ImageMobject(os.path.join(root, ext)) for ext in [ "2022/convolutions/discrete/images/EquationThumbnail.png", "2023/clt/main/images/Thumbnail.png", "2023/clt/Thumbnail.jpg", "2023/convolutions2/Thumbnail/Thumbnail2.png", ] )) titles = VGroup(*( Text("Convolutions (discrete)"), Text("Central limit theorem"), TexText(R"Why $\pi$ is in a Gaussian"), Text("Convolutions (continuous)"), )) titles.scale(1.4) thumbnails = Group() for image, title in zip(images, titles): rect = SurroundingRectangle(image, buff=0) rect.set_stroke(WHITE, 3) title.next_to(image, UP, buff=MED_LARGE_BUFF) thumbnails.add(Group(rect, image, title)) thumbnails.arrange_in_grid(buff=thumbnails[0].get_width() * 0.2) thumbnails.set_height(FRAME_HEIGHT - 1) self.play(LaggedStartMap(FadeIn, thumbnails, shift=UP, lag_ratio=0.7, run_time=4)) self.wait() class AddingCopiesOfAVariable(InteractiveScene): def construct(self): # Test expr = Tex(R"X_1 + X_2 + \cdots + X_N \text{ is approximately Gaussian}") expr.set_fill(GREY_A) expr_lhs = expr[R"X_1 + X_2 + \cdots + X_N"][0] expr.to_edge(UP) expr_lhs.save_state() expr_lhs.set_x(0) self.play(FadeIn(expr_lhs, lag_ratio=0.5, run_time=2)) self.wait() self.play( Restore(expr_lhs), Write(expr[len(expr_lhs):], run_time=1) ) self.wait(3) # Limit expr2 = Tex(R"X_1 + X_2 + \cdots + X_N \longrightarrow \text{Gaussian}") expr2.match_style(expr) expr2.move_to(expr) lim = Tex(R"N \to \infty", font_size=24) lim.next_to(expr2[R"\longrightarrow"], UP, buff=0.1) lim.set_color(YELLOW) self.play( TransformMatchingTex(expr, expr2), FadeIn(lim, 0.25 * UP, time_span=(1, 2)) ) self.wait() class WhyGaussian(InteractiveScene): def construct(self): question = TexText("What makes $e^{-x^2}$ special?", font_size=60) question.to_edge(UP, buff=LARGE_BUFF) self.play(Write(question)) self.wait() class AskAboutConvolution(InteractiveScene): def construct(self): text = TexText( "Convolution between $e^{-x^2}$ and $e^{-y^2}$", t2c={"x": BLUE, "y": YELLOW}, font_size=60 ) text.to_edge(UP, buff=MED_LARGE_BUFF) text.set_backstroke(width=2) self.add(text) class PreviewExplicitCalculation(InteractiveScene): def construct(self): # Title goal = Text("Goal: Compute a convolution between two Gaussian functions") goal.set_width(FRAME_WIDTH - 1) goal.to_edge(UP) conv_word = goal["convolution"] gauss_word = goal["Gaussian"] self.add(goal) # Convolution conv_color = BLUE tex_kw = dict( t2c={"{f}": BLUE, "{g}": TEAL, R"\sigma_1": RED, R"\sigma_2": RED_B}, font_size=42, ) conv_eq = Tex(R"[{f} * {g}](s) = \int_{-\infty}^\infty {f}(x){g}(s - x)dx", **tex_kw) conv_eq.next_to(goal, DOWN, buff=1.5) conv_eq.to_edge(LEFT) conv_arrow = Arrow(conv_word.get_bottom(), conv_eq.get_top() + SMALL_BUFF * UP) conv_arrow.set_color(conv_color) self.play(LaggedStart( FlashAround(conv_word, time_width=1.5, run_time=2.0, color=conv_color), conv_word.animate.set_color(conv_color), GrowArrow(conv_arrow), FadeTransform(conv_word.copy(), conv_eq), lag_ratio=0.2, )) self.wait() # Gaussian gauss_color = RED gaussian1 = Tex( R"f(x) = {1 \over \sigma_1 \sqrt{2 \pi}} e^{-x^2 / 2 \sigma_1^2}", **tex_kw ) gaussian2 = Tex( R"g(y) = {1 \over \sigma_2 \sqrt{2 \pi}} e^{-y^2 / 2 \sigma_2^2}", **tex_kw ) gaussian1.match_y(conv_eq) gaussian1.to_edge(RIGHT) gaussian2.next_to(gaussian1, DOWN, LARGE_BUFF) gauss_arrow = Arrow(gauss_word.get_bottom(), gaussian1.get_top() + SMALL_BUFF * UP) gauss_arrow.set_color(gauss_color) f_rect = SurroundingRectangle(conv_eq["{f}(x)"], buff=0.05) g_rect = SurroundingRectangle(conv_eq["{g}(s - x)"], buff=0.05) f_rect.set_stroke(RED, 5) g_rect.set_stroke(RED, 5) self.play( ShowCreation(f_rect), FadeTransform(gauss_word.copy(), gaussian1), GrowArrow(gauss_arrow), gauss_word.animate.set_color(gauss_color), ) self.wait() self.play( ReplacementTransform(f_rect, g_rect), FadeIn(gaussian2, DOWN), ) self.wait() self.play(FadeOut(g_rect)) self.wait() # Combine full_expr = Tex(R""" \int_{-\infty}^\infty \frac{1}{2\pi \sigma_1 \sigma_2} e^{-x^2 / 2\sigma_1^2} e^{-(s-x)^2 / 2\sigma_2^2} \,dx """, **tex_kw) full_expr.next_to(conv_eq, DOWN, buff=2.0, aligned_edge=LEFT) full_expr_rect = SurroundingRectangle(full_expr) full_expr_rect.set_stroke(RED_E, 2) arrow_kw = dict(stroke_width=2, stroke_color=RED_E) arrows = VGroup(*( Arrow(conv_eq, full_expr_rect, **arrow_kw), Arrow(gaussian1.get_left(), full_expr_rect, **arrow_kw), Arrow(gaussian2.get_left(), full_expr_rect.get_right(), **arrow_kw), )) self.play( LaggedStart(*( TransformMatchingShapes(conv_eq[9:13].copy(), full_expr[R"\int_{-\infty}^\infty"][0]), TransformMatchingShapes( VGroup(*gaussian1[5:13], gaussian2[5:13]).copy(), full_expr[R"\frac{1}{2\pi \sigma_1 \sigma_2}"][0] ), TransformMatchingShapes(gaussian1[13:].copy(), full_expr[R"e^{-x^2 / 2\sigma_1^2}"][0]), TransformMatchingShapes(gaussian2[13:].copy(), full_expr[R"e^{-(s-x)^2 / 2\sigma_2^2}"][0]), TransformMatchingShapes(conv_eq[-2:].copy(), full_expr[R"dx"]), ), run_time=3, lag_ratio=0.1), LaggedStartMap(GrowArrow, arrows), ) self.play(ShowCreation(full_expr_rect)) self.add(full_expr) self.wait(3) class NothingWrongWithThat(TeacherStudentsScene): def construct(self): morty = self.teacher self.remove(self.background) self.play( morty.says("There's nothing\nwrong with that!", mode="hooray"), self.change_students("awe", "horrified", "confused", look_at=self.screen), ) self.wait(3) self.play( morty.debubble(mode="tease"), self.change_students("pondering", "plain", "well") ) self.wait() self.play( morty.change("raise_right_hand", look_at=3 * UP), self.change_students("well", "pondering", "tease", look_at=3 * UR) ) self.wait(10) class SimpleBellRHS(InteractiveScene): def construct(self): self.add(Tex("= e^{-x^2}")) class SimpleBellRHS2(InteractiveScene): def construct(self): self.add(Tex("= e^{-(s - x)^2}")) class ConvolutionMeaning(InteractiveScene): def construct(self): # x + y = s kw = dict(t2c={"{s}": YELLOW}) words = VGroup( Tex(R"[f * g]({s})", font_size=60, **kw), Tex(R"\longrightarrow", **kw), Tex(R"\text{How likely is it that } x + y = {s} \, ?", **kw), ) words.arrange(RIGHT, buff=0.5) words.to_edge(UP) words[0].save_state() words[0].set_x(0) self.play(FadeIn(words[0], 0.5 * UP)) self.wait() self.play( Restore(words[0]), Write(words[1]), FadeIn(words[2], RIGHT), ) self.wait() # Mention sqrt(2) new_rhs = Tex(R"(\text{This area}) / \sqrt{2}", font_size=60) new_rhs[R"\text{This area}"].set_color(TEAL) new_rhs.next_to(words[1], RIGHT) new_rhs.set_opacity(0) self.play( VGroup(*words[:2], new_rhs).animate.set_x(0).set_opacity(1), FadeOut(words[2], RIGHT), ) self.wait() class RotationalSymmetryAnnotations(InteractiveScene): def construct(self): # Add equation kw = dict(t2c={"x": BLUE, "y": YELLOW, "r": RED}) top_eq = Tex("f(x)g(y) = e^{-x^2} e^{-y^2}", **kw) top_eq_lhs = top_eq["f(x)g(y)"][0] top_eq_rhs = top_eq["= e^{-x^2} e^{-y^2}"][0] top_eq.to_corner(UL) self.add(top_eq) # Expand equation rhs2 = Tex("= e^{-(x^2 + y^2)}", **kw) rhs3 = Tex("= e^{-r^2}", **kw) rhs2.next_to(top_eq_rhs, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) rhs3.next_to(rhs2, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) xy_rect = SurroundingRectangle(rhs2["x^2 + y^2"], buff=0.05) r_rect = SurroundingRectangle(rhs3["r^2"], buff=0.05) rects = VGroup(xy_rect, r_rect) rects.set_stroke(RED, 1) self.play( TransformMatchingShapes( top_eq_rhs.copy(), rhs2, path_arc=30 * DEGREES, ) ) self.wait() self.play(ShowCreation(xy_rect)) self.play( TransformMatchingTex( rhs2.copy(), rhs3, key_map={"x^2 + y^2": "r^2"}, run_time=1 ), TransformFromCopy(xy_rect, r_rect), ) self.play(FadeOut(rects)) self.wait() class UniqueCharacterization(InteractiveScene): def construct(self): # Test kw = dict(t2c={"{x}": BLUE, "{y}": YELLOW}) group = VGroup( TexText("Rotational symmetry of $f({x})f({y})$", font_size=36, **kw), Tex(R"\Downarrow"), Tex(R"f({x}) = Ae^{-c {x}^2}", **kw), ) group.arrange(DOWN) group.to_corner(UR) self.add(group[0]) self.wait() self.play( Write(group[1]), FadeInFromPoint(group[2], group[0]["f({x})"].get_center()), run_time=1 ) self.wait() class SliceLineAnnotations(InteractiveScene): def construct(self): # Line equation kw = dict(t2c={"s": RED}) line_eq = Tex("x + y = s", **kw) line_eq.to_edge(UP) s_term = line_eq["s"][0] decimal_rhs = DecimalNumber(-6, edge_to_fix=LEFT) decimal_rhs.move_to(s_term, LEFT) decimal_rhs.shift(0.025 * UP) s_eq = Tex("=").rotate(90 * DEGREES) s_eq.next_to(s_term, DOWN, SMALL_BUFF) self.add(line_eq, decimal_rhs) self.remove(s_term) self.play(ChangeDecimalToValue(decimal_rhs, 1), run_time=5 / 1.5) self.wait() self.play( decimal_rhs.animate.next_to(s_eq, DOWN, SMALL_BUFF), Write(s_eq), FadeIn(s_term, 0.5 * DOWN), ) self.wait() # What we want words = Text("What we want:") words.to_corner(UR) conv = Tex("[f * g](s)", **kw) conv.next_to(words, DOWN, MED_LARGE_BUFF) conv_eq = Tex("=").rotate(90 * DEGREES) conv_eq.next_to(conv, DOWN) area = Tex(R"(\text{This area}) / \sqrt{2}") area[R"\text{This area}"].set_color(TEAL) area.next_to(conv_eq, DOWN) self.play( FadeIn(words, 0.5 * UP), FadeIn(conv, 0.5 * DOWN), ) self.play(FlashAround(conv, run_time=2, time_width=1.5)) self.wait() self.play( Write(conv_eq), FadeIn(area, 0.5 * DOWN), ) for s in [1.5, 0.5, 1.0]: self.play(ChangeDecimalToValue(decimal_rhs, s)) self.wait() self.play( LaggedStartMap(FadeOut, VGroup( words, conv, conv_eq, area, s_eq, decimal_rhs )), line_eq.animate.to_corner(UR), ) self.wait() class YIntegralAnnotations(InteractiveScene): def construct(self): # Setup kw = dict( t2c={ "{s}": RED, "{y}": YELLOW, "{x}": BLUE, R"\text{Area}": TEAL } ) integrals = VGroup( Tex(R"\text{Area} = \int_{\text{-}\infty}^\infty e^{-{x}^2} \cdot e^{-{y}^2} \, d{y}", **kw), Tex(R"\text{Area} = \int_{\text{-}\infty}^\infty e^{-({s} / \sqrt{2})^2} \cdot e^{-{y}^2} \, d{y}", **kw), Tex(R"\text{Area} = e^{-({s} / \sqrt{2})^2} \int_{\text{-}\infty}^\infty e^{-{y}^2} \, d{y}", **kw), Tex(R"\text{Area} = e^{-({s} / \sqrt{2})^2} \sqrt{\pi}", **kw), ) for integral in integrals: integral.to_edge(UP) x_rect = SurroundingRectangle(integrals[0]["e^{-{x}^2}"], buff=0.05) s_rect1 = SurroundingRectangle(integrals[1][R"e^{-({s} / \sqrt{2})^2}"], buff=0.05) s_rect2 = SurroundingRectangle(integrals[2][R"e^{-({s} / \sqrt{2})^2}"], buff=0.05) y_int = integrals[2][R"\int_{\text{-}\infty}^\infty e^{-{y}^2} \, d{y}"] y_int_rect = SurroundingRectangle(y_int, buff=0.05) x_rect.set_stroke(BLUE, 2) s_rect1.set_stroke(RED, 2) s_rect2.set_stroke(RED, 2) y_int_rect.set_stroke(YELLOW, 2) const_word = Text("Constant!", font_size=36) const_word.next_to(x_rect, DOWN, buff=MED_SMALL_BUFF, aligned_edge=LEFT) const_word.shift(SMALL_BUFF * RIGHT) # Replace x self.play(Write(integrals[0])) self.wait() self.play( ShowCreation(x_rect), FadeIn(const_word, scale=0.7), ) self.wait() self.play( TransformMatchingTex(*integrals[:2]), ReplacementTransform(x_rect, s_rect1), const_word.animate.match_x(s_rect1).set_anim_args(run_time=2), ) self.wait() # Factor out self.play( FadeOut(const_word, 0.5 * DOWN), VShowPassingFlash( s_rect1.copy().insert_n_curves(100).set_stroke(width=5), run_time=2, ), ShowCreation(s_rect1, run_time=2) ) self.wait() s_rect2.set_stroke(opacity=0) self.play( TransformMatchingTex(*integrals[1:3], path_arc=45 * DEGREES), ReplacementTransform(s_rect1, s_rect2, path_arc=45 * DEGREES), run_time=2 ) self.wait() # Emphasize separation s_rect2.set_stroke(RED, 2, 1) self.play(ShowCreation(s_rect2)) self.wait() self.play(ReplacementTransform(s_rect2, y_int_rect)) self.wait() y_int_group = VGroup(y_int_rect, y_int.copy()) y_int.set_opacity(0) int_eq = Tex("=").rotate(90 * DEGREES) pi_term = integrals[3][R"\sqrt{\pi}"] int_eq.next_to(pi_term, DOWN, SMALL_BUFF) self.play( TransformMatchingTex(*integrals[2:4]), y_int_group.animate.scale(0.5).next_to(int_eq, DOWN, SMALL_BUFF), Write(int_eq), ) self.wait() self.play(LaggedStartMap(FadeOut, VGroup(int_eq, *y_int_group))) self.wait() # Area expression area_eq = Tex(R"\text{Area} = e^{-{s}^2 / 2} \sqrt{\pi}", **kw) area_eq.to_edge(UP) area_eq.save_state() twos = area_eq["2"] twos_copies = twos.copy() twos[0].become(twos_copies[1]) twos[1].become(twos_copies[0]) self.play( TransformMatchingTex(integrals[3], area_eq) ) area_eq.restore() self.wait() # From area to convolution conv_eqs = VGroup( Tex(R"[f * g]({s}) = \text{Area} / \sqrt{2}", **kw), Tex(R"[f * g]({s}) = \text{Area} / \sqrt{2} = e^{-{s}^2 / 2} \sqrt{\pi} / \sqrt{2}", **kw), Tex(R"[f * g]({s}) = \text{Area} / \sqrt{2} = e^{-{s}^2 / 2} \sqrt{\pi \over 2}", **kw), ) conv_eqs[0].next_to(ORIGIN, LEFT, LARGE_BUFF).to_edge(UP) conv_eqs[1].move_to(area_eq) conv_eqs[2].move_to(area_eq) self.play( Write(conv_eqs[0]), Transform(area_eq["Area"].copy(), conv_eqs[0]["Area"].copy(), remover=True), area_eq.animate.next_to(ORIGIN, RIGHT, LARGE_BUFF).to_edge(UP), ) self.wait() self.play( LaggedStart(*( FadeTransform(src[tex][-1], conv_eqs[1][tex][-1]) for src, tex in [ (conv_eqs[0], conv_eqs[0].get_tex()), (area_eq, R"e^{-{s}^2 / 2} \sqrt{\pi}"), (conv_eqs[0], R"/ \sqrt{2}"), ] )), Write(conv_eqs[1]["="][1]), FadeOut(area_eq[R"\text{Area} ="][0]), ) self.clear() self.add(conv_eqs[1]) self.wait() self.play(TransformMatchingTex( *conv_eqs[1:3], key_map={R"\sqrt{\pi} / \sqrt{2}": R"\sqrt{\pi \over 2}"}, run_time=1.5, )) self.wait() class OscillatingGraphValue(InteractiveScene): def construct(self): # Add graph axes = Axes((-3, 3), (0, 2), width=8, height=1.5) axes.move_to(1.5 * UP) graph = axes.get_graph(lambda x: np.exp(-x**2 / 2) * math.sqrt(PI)) graph.set_stroke(TEAL, 2) axes.add(Tex("s").set_color(RED).next_to(axes.x_axis.get_end(), UR, SMALL_BUFF)) self.add(axes, graph) # Add s tracker s_tracker = ValueTracker(-3) get_s = s_tracker.get_value globals().update(locals()) v_line = always_redraw(lambda: axes.get_v_line_to_graph(get_s(), graph, line_func=Line).set_stroke(WHITE, 1)) dot = GlowDot(radius=0.2, color=WHITE) dot.add_updater(lambda m: m.move_to(axes.i2gp(get_s(), graph))) tri = Triangle(start_angle=PI / 2) tri.set_height(0.05) tri.set_fill(TEAL, 1) tri.set_stroke(width=0) tri.add_updater(lambda m: m.move_to(axes.c2p(get_s(), 0), UP)) globals().update(locals()) label = DecimalNumber(0, font_size=24) label.add_updater(lambda m: m.set_value(get_s())) label.add_updater(lambda m: m.next_to(tri, DOWN, SMALL_BUFF)) self.add(v_line, dot, label, tri) for _ in range(2): self.play( s_tracker.animate.set_value(3), rate_func=there_and_back, run_time=24 ) class ShowGaussianConvolutionsAsEquations(InteractiveScene): def construct(self): # Add axes axes = VGroup(*( NumberPlane( (-3, 3), (0, 2), width=3, height=1, background_line_style=dict(stroke_width=1, stroke_color=GREY_D), faded_line_style=dict(stroke_width=1, stroke_opacity=0.2, stroke_color=GREY_D) ) for x in range(6) )) axes.set_height(1.25) axes.arrange_in_grid(2, 3, h_buff=0.75, v_buff=3.0) for ax in axes[2::3]: ax.shift(0.75 * RIGHT) axes.center() stars = Tex("*", font_size=72).replicate(2) eqs = Tex("=", font_size=72).replicate(2) stars[0].move_to(axes[0:2]) eqs[0].move_to(axes[1:3]) stars[1].move_to(axes[3:5]) eqs[1].move_to(axes[4:6]) self.add(axes) self.add(stars, eqs) # Equations kw = dict( font_size=30, t2c={"x": BLUE, "y": YELLOW, "{s}": TEAL, R"\sigma": RED} ) equations = VGroup( Tex(R"e^{-x^2}", **kw), Tex(R"e^{-y^2}", **kw), Tex(R"\sqrt{\frac{\pi}{2}} e^{-{s}^2 / 2}", **kw), Tex(R"\frac{1}{\sigma \sqrt{2\pi}} e^{-\frac{1}{2} x^2 / \sigma^2}", **kw), Tex(R"\frac{1}{\sigma \sqrt{2\pi}} e^{-\frac{1}{2} y^2 / \sigma^2}", **kw), Tex(R"\frac{1}{\sqrt{2}\sigma \sqrt{2\pi}} e^{-\frac{1}{2} {s}^2 / 2 \sigma^2}", **kw), ) normal_annotations = VGroup( Tex(R"\mathcal{N}\left(0, \sigma^2\right)", **kw), Tex(R"\mathcal{N}\left(0, \sigma^2\right)", **kw), Tex(R"\mathcal{N}\left(0, 2\sigma^2\right)", **kw), ) normal_annotations.scale(1.25) for eq, ax in zip(equations, axes): eq.next_to(ax, UP, MED_SMALL_BUFF) for ann, eq in zip(normal_annotations, equations[3:]): ann.next_to(eq, UP, MED_LARGE_BUFF) # Graphs sigma = 0.35 graphs = VGroup( axes[0].get_graph(lambda x: np.exp(-x**2)), axes[1].get_graph(lambda y: np.exp(-y**2)), axes[2].get_graph(lambda s: np.exp(-s**2 / 2) * math.sqrt(PI / 2)), axes[3].get_graph(lambda x: gauss_func(x, 0, sigma)), axes[4].get_graph(lambda y: gauss_func(y, 0, sigma)), axes[5].get_graph(lambda s: gauss_func(s, 0, math.sqrt(2) * sigma)), ) colors = [BLUE, YELLOW, TEAL] for graph, color in zip(graphs, it.cycle(colors)): graph.set_stroke(color, 2) # Animations self.add(equations[:3]) self.add(graphs[:3]) self.wait() self.play( LaggedStart(*( FadeTransform(eq1.copy(), eq2) for eq1, eq2 in zip(equations[:3], equations[3:]) ), lag_ratio=0.15), LaggedStart(*( TransformFromCopy(graph1, graph2) for graph1, graph2 in zip(graphs[:3], graphs[3:]) ), lag_ratio=0.15), LaggedStartMap( FadeIn, normal_annotations[:2], shift=0.5 * DOWN, lag_ratio=0.25, run_time=1 ) ) self.wait() self.play( FadeTransform(normal_annotations[0].copy(), normal_annotations[2]), FadeTransform(normal_annotations[1].copy(), normal_annotations[2]), run_time=1 ) self.wait() class Exercise(InteractiveScene): def construct(self): # Tex key word args tex_kw = dict( t2c={ R"\sigma_1": RED, R"\sigma_2": RED_B, } ) # Set up axes planes = VGroup(*( NumberPlane( (-1, 3), (-1, 3), background_line_style=dict(stroke_color=GREY_A, stroke_width=1, stroke_opacity=0.5), faded_line_style=dict(stroke_color=GREY_A, stroke_width=1, stroke_opacity=0.25), width=5, height=5 ) for x in range(2) )) labels = VGroup(*map(Tex, ["x", "y", "x'", "y'"])) labels.scale(0.75) label_iter = iter(labels) for plane in planes: for axis, vect in zip(plane.axes, [RIGHT, UP]): label = next(label_iter) label.next_to(axis.get_end(), vect, SMALL_BUFF) plane.add(label) planes.arrange(RIGHT, buff=4.0) planes.set_width(10) planes.to_edge(LEFT) planes.set_y(-1.5) arrow = Arrow(*planes, stroke_width=6, stroke_color=RED, buff=0.5) self.add(planes) self.add(arrow) # Show lines and intersections lines = VGroup( Line(planes[0].c2p(-1, 3), planes[0].c2p(3, -1)), Line(planes[1].c2p(-0.25, 3), planes[1].c2p(2.25, -1)), ) lines.set_stroke(YELLOW, 2) intersection_labels = VGroup(*( Tex(tex, **tex_kw) for tex in [ "(s, 0)", "(0, s)", R"(s / \sigma_1)", R"(s / \sigma_2)", ] )) intersection_labels.scale(0.5) intersection_labels_iter = iter(intersection_labels) dots = Group() for plane, line in zip(planes, lines): for axis in plane.axes: point = find_intersection( line.get_start(), line.get_vector(), axis.get_start(), axis.get_vector(), ) dot = GlowDot(point, color=WHITE) dots.add(dot) label = next(intersection_labels_iter) label.set_backstroke(width=2) label.next_to(point, DL, buff=SMALL_BUFF) l2_perp = lines[1].copy().rotate(90 * DEGREES) l2_perp.shift(planes[1].get_origin() - l2_perp.get_start()) mid_point = find_intersection( l2_perp.get_start(), l2_perp.get_vector(), lines[1].get_start(), lines[1].get_vector() ) d_line = Line(planes[1].get_origin(), mid_point) d_line.set_stroke(GREEN, 2) d_label = Tex("d", font_size=36) d_label.next_to(d_line.get_center(), UL, buff=0.05) elbow = Elbow() elbow.rotate(l2_perp.get_angle() + 90 * DEGREES, about_point=ORIGIN) elbow.set_stroke(width=1) elbow.shift(mid_point) self.add(lines) self.add(dots) self.add(intersection_labels) self.add(d_line) self.add(d_label) self.add(elbow) # Equations d_eq = Tex(R"d = \frac{s}{\sqrt{\sigma_1^2 + \sigma_2^2}}", **tex_kw) d_eq.scale(0.85) d_eq.next_to(planes[1], RIGHT, buff=0.35) xy_eq = Tex("x + y = s") xy_eq.scale(0.7) xy_eq.set_backstroke(width=3) xy_eq.next_to(lines[0].get_center(), UR, SMALL_BUFF) change_of_coord_eqs = VGroup( Tex(R"x' = x / \sigma_1", **tex_kw), Tex(R"y' = y / \sigma_2", **tex_kw), ) change_of_coord_eqs.arrange(DOWN) change_of_coord_eqs.scale(0.7) change_of_coord_eqs.next_to(arrow, UP) self.add(d_eq) self.add(xy_eq) self.add(change_of_coord_eqs) # Words tex_kw["alignment"] = "" words = VGroup( TexText(R""" Consider the diagonal slice method for two Gaussians with\\ different standard deviations, $\sigma_1$ and $\sigma_2$:\\ $$ f(x) = \frac{1}{\sigma_1 \sqrt{2\pi}} e^{-\frac{1}{2}(x / \sigma_1)^2} \quad \text{ and } \quad g(y) = \frac{1}{\sigma_2 \sqrt{2\pi}} e^{-\frac{1}{2}(y / \sigma_2)^2} \qquad\qquad\qquad\qquad\qquad\qquad $$ The graph of $f(x)g(y)$ is no longer rotationally symmetric.\\ However, it will be if you pass to a new set of coordinates\\ $(x', y')$ as illustrated below. Why? """, **tex_kw), TexText(R""" The transformatoin of the line $x + y = s$ is illustrated below.\\ After the transformation, the area of a the slice of the graph\\ over this line is changed by some factor which depends on\\ $\sigma_1$ and $\sigma_2$, but importantly, not on $s$. \\ \\ Explain how to find the distance $d$ in the digram below, and\\ how this shows that the area of a slice of $f(x)g(y)$ over the line\\ $x + y = s$ is proportional to $e^{-\frac{1}{2} s^2 / (\sigma_1^2 + \sigma_2^2)}$. """, **tex_kw), ) words.arrange(RIGHT, buff=LARGE_BUFF, aligned_edge=UP) words.set_width(FRAME_WIDTH - 1) words.to_edge(UP) v_line = Line(words.get_top(), words.get_bottom()) v_line.set_stroke(GREY_A, 1) v_line.move_to(midpoint(words[0].get_right(), words[1].get_left())) words.add(v_line) self.add(words) class WhatsTheBigdeal(TeacherStudentsScene): def construct(self): # What's the big deal morty = self.teacher stds = self.students self.remove(self.background) self.play( stds[0].change("pondering", look_at=self.screen), stds[1].change("maybe", look_at=self.screen), stds[2].says("What's the\nbig deal?", mode="dance_3"), morty.change("guilty"), ) self.wait(2) self.play( self.change_students("pondering", "sassy", "hesitant", look_at=self.screen), morty.change("plain"), run_time=2 ) self.wait(6) # Aren't they common self.play( stds[2].debubble(mode="heistant"), stds[1].says("What else\nwould it be?", mode="maybe", run_time=1), stds[0].change("well"), ) self.play( stds[2].says("Normal distributions\nare very common\nright?", mode="speaking", look_at=morty.eyes), run_time=2, ) self.add(stds[2].bubble, stds[2].bubble.content) self.wait(3) # But are they? common_words = stds[2].bubble.content["Normal distributions\nare very common"][0].copy() are_they = Text("But are they?") are_they.set_color(RED) are_they.move_to(self.hold_up_spot, DOWN) self.play( stds[0].change("pondering", look_at=self.screen), stds[1].debubble(), stds[2].debubble(), morty.change("sassy"), FadeIn(are_they, UP), common_words.animate.next_to(are_they, UP) ) self.wait() self.play(morty.change("hesitant", are_they)) self.wait(2) # Central limit theorem clt = Text("Central Limit Theorem") clt.set_color(YELLOW) clt.move_to(common_words).to_edge(UP, buff=LARGE_BUFF) implies = Tex(R"\Downarrow") implies.next_to(clt, DOWN) n = len("Normaldistributions") self.play( morty.change("raise_right_hand"), self.change_students("pondering", "erm", "pondering", look_at=clt), common_words[:n].animate.next_to(implies, DOWN), FadeOut(common_words[n:], DOWN), FadeOut(are_they, DOWN), Write(clt), Write(implies) ) self.wait(5) class AddedBubble(InteractiveScene): def construct(self): randy = Randolph() randy.to_corner(DL) self.play(randy.says("It follows from \n the CLT")) self.remove(randy) class StepsToProof(InteractiveScene): def construct(self): # Title title = Text("Steps to proving the CLT", font_size=60) title.to_edge(UP, buff=MED_SMALL_BUFF) underline = Underline(title, buff=-0.05, stretch_factor=1.5) self.add(title, underline) # Steps steps = VGroup( Text(""" Step 1: Show that for all (finite variance) distribution, there exists some universal shape that this process will approach. """, t2s={"some": ITALIC}, alignment="LEFT"), Text(""" Step 2: Show that the convolution of two Gaussians is another Gaussian. """, alignment="LEFT") ) steps.set_width(0.9 * FRAME_WIDTH) steps.set_fill(WHITE) steps.arrange(DOWN, buff=1.0, aligned_edge=LEFT) steps.next_to(underline, DOWN, buff=0.75) steps[0]["(finite variance)"].set_opacity(0.7) # Two steps self.play(LaggedStartMap( FadeIn, VGroup(steps[0]["Step 1:"], steps[1]["Step 2:"]), shift=0.5 * UP, lag_ratio=0.5 )) self.wait() # Step 1 self.play( FadeIn(steps[0][len("Step1:"):], lag_ratio=0.01, run_time=3), FadeOut(steps[1]["Step 2:"]), ) self.play( steps[0]["some universal shape"].animate.set_color(TEAL), lag_ratio=0.1, ) self.wait() # Step 2 self.play( FadeIn(steps[1], lag_ratio=0.01, run_time=2), self.frame.animate.move_to(steps, UP).shift(0.25 * UP) ) texts = ["two Gaussians", "another Gaussian"] for text, color in zip(texts, [YELLOW, TEAL]): self.play( steps[1][text].animate.set_color(color), lag_ratio=0.1, ) self.wait(0.5) self.wait() class HerschelMaxwellWords(InteractiveScene): def construct(self): # Test ideas = VGroup( VGroup( Text("Herschel-Maxwell derivation", font_size=60), TexText( R"Rotational symmetry of $f({x})f({y}) \Rightarrow f({x}) = Ae^{-cx^2}$", t2c={"{x}": BLUE, "{y}": YELLOW}, font_size=36, ), ).arrange(DOWN), TexText( R"Why $\pi$ is in this formula", font_size=60, t2c={R"\pi": YELLOW} ) ) for idea in ideas: idea.move_to(3.15 * UP) self.play(FadeIn(ideas[0], 0.5 * UP)) self.wait() self.play( FadeIn(ideas[1], 0.5 * UP), FadeOut(ideas[0], 0.5 * UP), ) self.wait() class LinksInDescription(TeacherStudentsScene): def construct(self): # Test self.play( self.teacher.says(""" Links for the theoretically curious in the description """), self.change_students( "pondering", "hooray", "well", look_at=self.teacher.eyes ) ) self.play(self.change_students( "pondering", "well", "tease", look_at=4 * DOWN, )) self.wait(5) class DrawQRCode(InteractiveScene): def construct(self): # Test # self.add(FullScreenRectangle(fill_color=GREY_A)) code = SVGMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/convolutions2/gauss_example_supplements/images/SubstackQR2.svg") code.remove(*code[:2]) code.set_fill(BLACK, 1) code.set_height(7) back_rect = SurroundingRectangle(code) back_rect.set_fill(GREY_A, 1) back_rect.set_stroke(WHITE, 1) code.shuffle() self.play( FadeIn(back_rect, time_span=(3, 5)), Write(code, stroke_color=RED_E, stroke_width=2, lag_ratio=0.005, run_time=5), ) self.wait() class Thumbnail1(InteractiveScene): def construct(self): # Test line_style = dict(stroke_color=GREY_B, stroke_width=1) faded_line_style = dict(stroke_opacity=0.25, **line_style) plane = NumberPlane( (-3, 3), (0, 1, 0.5), height=1.5, width=4, background_line_style=line_style, faded_line_style=faded_line_style, ) plane.set_width(FRAME_WIDTH) plane.to_edge(DOWN) graph = plane.get_graph(lambda x: np.exp(-x**2)) graph.set_stroke(TEAL, 5) expr = Tex("e^{-x^2}", font_size=120) expr.next_to(plane.c2p(1.5, 1), DOWN) question = Text("Why this function?", font_size=90) question.to_edge(UP) arrow = Arrow( question["this"], expr["e"], stroke_width=10, stroke_color=YELLOW ) self.add(plane) self.add(graph) self.add(question) self.add(arrow) self.add(expr) class EndScreen(PatreonEndScreen): pass
from manim_imports_ext import * from _2023.convolutions2.continuous import * class QuizTime(TeacherStudentsScene): def construct(self): # Test self.play(self.teacher.says("Quiz time!", mode="hooray")) self.play( self.change_students("happy", "tease", "hooray") ) self.wait(2) class IfYouReallyUnderstand(TeacherStudentsScene): def construct(self): # Initial comments morty = self.teacher self.play( morty.says(TexText(R"If you \emph{really} \\ understand"), run_time=1.5), self.change_students("pondering", "confused", "erm", look_at=self.screen) ) self.wait() old_bubble = morty.bubble old_words = morty.bubble.content new_bubble = morty.get_bubble( TexText(R"You'll understand \\ why normal distributions \\ are special"), bubble_type=SpeechBubble, width=5, height=4, ) new_bubble.content.scale(1.2) VGroup(new_bubble, new_bubble.content).shift(0.5 * RIGHT) self.play( Transform(old_bubble, new_bubble), Transform(old_words, new_bubble.content, run_time=1), morty.change("tease"), ) self.remove(old_bubble, old_words) self.add(new_bubble, new_bubble.content) morty.bubble = new_bubble # Stare at it self.wait() self.play(self.change_students(None, "tease", "maybe", look_at=self.screen)) self.wait(3) self.play(self.change_students("happy", "erm", "hesitant", look_at=self.screen, lag_ratio=0.2)) self.wait(3) # The real lesson title = TexText("Today's lesson:", font_size=60) subtitle = Text("How to add random\nvariables, in general", font_size=48) title.set_x(FRAME_WIDTH / 4).to_edge(UP, buff=MED_SMALL_BUFF) subtitle.next_to(title, DOWN, buff=LARGE_BUFF) self.play( morty.debubble("raise_right_hand"), FadeIn(title, UP), self.change_students("pondering", "pondering", "hesitant", look_at=title), ) self.play(FadeIn(subtitle, lag_ratio=0.1)) self.wait(2) self.play(self.change_students("maybe", "hesitant", "well", look_at=self.screen)) self.wait(4) class WhatDistributionDescribesThis(InteractiveScene): def construct(self): words = Text("What distribution\ndescribes this?") arrow = Arrow(words.get_bottom(), words.get_bottom() + DL) VGroup(words, arrow).set_color(TEAL) self.play(Write(words), ShowCreation(arrow)) self.wait() class GuessTheAnswer(TeacherStudentsScene): def construct(self): pass class AlreadyCoveredConvolutions(TeacherStudentsScene): def construct(self): # Ask morty = self.teacher stds = self.students self.screen.to_edge(UR) self.play( stds[2].says( "Wait, didn't you already\ncover convolutions?", mode="dance_1" ), morty.change("guilty"), ) self.play( self.change_students("hesitant", "awe", None, look_at=self.screen) ) self.wait(2) # Show video words = VGroup( Text("Only discrete examples", font_size=48), Text( """ Probability Moving averages Image processing Polynomial multiplication Relationship with FFTs """, alignment="LEFT", font_size=36 ), ) words.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) words[1].shift(0.25 * RIGHT) words.to_corner(UL) words.to_edge(UP) self.play(LaggedStart( morty.change("raise_right_hand", look_at=self.screen), stds[2].debubble(mode="sassy", look_at=self.screen), stds[1].change("pondering", look_at=self.screen), )) self.wait(2) self.play( Write(words[0], run_time=1), self.change_students("pondering", "tease", "plain", look_at=words) ) self.wait(3) self.play(FadeIn(words[1], run_time=1, lag_ratio=0.1)) self.wait(3) # Awkward spot no_prereq = Text("Not a \n prerequisite", font_size=60) no_prereq.move_to(words).to_edge(LEFT, buff=1.0) no_prereq.set_color(RED) redundancy_words = Text("But some overlap\nwith this video") redundancy_words.move_to(no_prereq, LEFT) redundancy_words.match_color(no_prereq) arrow = Vector(2.5 * RIGHT) arrow.next_to(no_prereq, RIGHT) arrow.match_color(no_prereq) self.play( morty.change("guilty"), self.change_students("hesitant", "pondering", "hesitant", look_at=morty.eyes) ) self.wait() self.look_at(no_prereq, added_anims=[ FadeOut(words, LEFT), FadeIn(no_prereq, LEFT), ]) self.play( GrowArrow(arrow), morty.change("raise_left_hand", self.screen) ) self.wait(2) self.play(morty.change("maybe")) self.look_at(no_prereq, added_anims=[ FadeOut(no_prereq, UP), FadeIn(redundancy_words, UP), arrow.animate.stretch(0.8, 0, about_edge=RIGHT), ]) self.wait(3) self.play( morty.change("tease"), self.change_students("happy", "thinking", "happy", look_at=morty.eyes), ) self.wait(4) class PauseAndPonder(TeacherStudentsScene): def construct(self): self.play(self.teacher.says("Pause and\nponder!", mode="hooray", run_time=1)) self.play(self.change_students("thinking", "pondering", "pondering", look_at=self.screen)) self.wait(5) # State goal self.play( self.teacher.debubble(mode="raise_right_hand", look_at=3 * UP), self.change_students("tease", "thinking", "awe", look_at=3 * UP) ) self.wait(8) class CountOutcomes(InteractiveScene): def construct(self): equation = Tex(R"6 \times 6 = 36 \text{ outcomes}") self.play(FadeIn(equation, lag_ratio=0.1)) self.wait() class AssumingIndependence(TeacherStudentsScene): def construct(self): # Assuming... morty = self.teacher stds = self.students self.remove(self.background) self.play( morty.says("Assuming\nindependence!", mode="surprised", run_time=1), self.change_students("hesitant", "guilty", "plain") ) self.wait(3) self.play( morty.debubble("tease"), stds[1].says(TexText(R"Isn't that a \\ little pedantic?"), mode="sassy"), stds[2].change("angry") ) self.wait(3) class IsntThatOvercomplicated(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.remove(self.background) # Show self.play( stds[0].change("erm", self.screen), stds[2].change("confused", self.screen), stds[1].says( "Isn't that...a little\nover-complicated?", mode="angry", bubble_config=dict(width=7, height=4), ), morty.change("shruggie") ) self.wait(2) self.play(morty.change("guilty")) self.wait() self.play( morty.says("It's fun!", mode="hooray", bubble_config=dict(width=2, height=1.5)), stds[1].debubble() ) self.play(self.change_students("hesitant", "tease", "pondering", look_at=self.screen)) self.wait(3) self.play( morty.debubble(mode="raise_right_hand"), self.change_students("pondering", "erm", "pondering", look_at=self.screen) ) self.wait(5) class QuestionTheFormula(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.remove(self.background) self.play(morty.change("raise_right_hand", 3 * UR)) self.play( stds[0].change("erm", 3 * UR), stds[1].says("Hang on...", mode="hesitant"), stds[2].change("confused", 3 * UR), ) self.wait(3) class RuleOfThumb(InteractiveScene): def construct(self): # Test title = Text("General rule of thumb", font_size=72) title.to_edge(UP) sigma, arrow, integral = group = VGroup( Tex(R"\sum \dots").set_height(1.5), Vector(2 * RIGHT, stroke_width=10), Tex(R"\int\dots dx").set_height(2.5), ) group.arrange(RIGHT, buff=LARGE_BUFF) integral.shift(0.5 * LEFT) group.center() sigma.set_fill(RED) integral.set_fill(TEAL) VGroup(sigma, integral).set_stroke(WHITE, 1) sigma.save_state() sigma.center() self.add(title) self.play(Write(sigma, run_time=1)) self.wait() self.play( TransformFromCopy(sigma, integral), sigma.animate.restore(), GrowFromCenter(arrow) ) self.wait() class CanWeSeeAnExample(TeacherStudentsScene): def construct(self): # Test morty = self.teacher stds = self.students self.remove(self.background) self.play( stds[1].says("Can we see\nan example?", mode="raise_left_hand"), ) self.play( stds[0].change("confused", self.screen), stds[2].change("maybe", self.screen), morty.change("happy"), ) self.wait(2) self.play( morty.change("raise_right_hand", 3 * UP), self.change_students("pondering", None, "pondering", look_at=3 * UP), stds[1].debubble() ) self.look_at(3 * UP) self.wait(5) class AskAboutAddingThreeUniforms(InteractiveScene): def construct(self): # Set up equations h_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) h_line.set_stroke(GREY_A, 1) two_sum = Tex("X_1 + X_2", font_size=96) three_sum = Tex("X_1 + X_2 + X_3", font_size=96) two_sum.to_edge(UP) three_sum.next_to(h_line, DOWN, MED_SMALL_BUFF) VGroup(two_sum, three_sum).shift(LEFT) # Braces exprs = [two_sum, three_sum] term_braces = VGroup(*( Brace(xi, DOWN, SMALL_BUFF) for expr in exprs for xi in expr[re.compile("X_.")] )) expr_braces = VGroup(*( Brace(expr, DOWN) for expr in [*exprs] )) x12_brace = Brace(three_sum["X_1 + X_2"], DOWN) # Plots # (Christ this is confusingly written) all_braces = [*term_braces, *expr_braces, x12_brace] funcs = [*[uniform] * 5, *[wedge_func] * 3] colors = [*[BLUE] * 5, TEAL, YELLOW, TEAL] for brace, func, color in zip(all_braces, funcs, colors): x_range = (-1, 1) if brace in term_braces else (-2, 2) axes = Axes( x_range, (0, 1.5, 0.5), width=2.0, height=1.0, axis_config=dict(tick_size=0.025) ) axes.next_to(brace, np.round(brace.get_direction(), 1)) if brace is expr_braces[1]: graph = get_conv_graph(axes, uniform, wedge_func) else: graph = axes.get_graph( func, x_range=(*x_range, 0.025), use_smoothing=False ) graph.set_stroke(color, 3) brace.plot = VGroup(axes, graph) term_plots = VGroup(*(brace.plot for brace in term_braces)) expr_plots = VGroup(*(brace.plot for brace in expr_braces)) x12_plot = x12_brace.plot # Convolution equations symbols = VGroup() x_shift = (term_plots[1].get_center() - term_plots[0].get_center()) / 2 for ch, plot in zip("*=**=", term_plots): symbol = Tex(ch, font_size=72) symbol.move_to(plot) symbol.shift(x_shift * RIGHT) if ch == "=": symbol.shift(0.25 * x_shift * RIGHT) symbols.add(symbol) expr_plots[0].move_to(term_plots[1], DOWN).shift(2.5 * x_shift * RIGHT) expr_plots[1].move_to(term_plots[4], DOWN).shift(2.5 * x_shift * RIGHT) q_marks = Tex("???", font_size=96) q_marks.move_to(expr_plots[1]) # Show the first two self.add(two_sum) self.play( LaggedStartMap(GrowFromCenter, term_braces[:2], lag_ratio=0), LaggedStartMap(FadeIn, term_plots[:2], shift=DOWN), FadeIn(symbols[:2], lag_ratio=0.2), run_time=1, ) self.play( TransformFromCopy(term_plots[0], expr_plots[0]), TransformFromCopy(term_plots[1], expr_plots[0]), ) self.wait() # Transition from two_sum to three_sum self.play(LaggedStart( ShowCreation(h_line), TransformFromCopy(two_sum, three_sum["X_1 + X_2"][0]), TransformFromCopy(term_braces[:2], term_braces[2:4]), TransformFromCopy(term_plots[:2], term_plots[2:4]), TransformFromCopy(two_sum["+ X_2"][0], three_sum["+ X_3"][0]), TransformFromCopy(term_braces[1], term_braces[4]), TransformFromCopy(term_plots[1], term_plots[4]), TransformFromCopy(symbols[0].replicate(2), symbols[2:4]), TransformFromCopy(symbols[1], symbols[4]), lag_ratio=0.02, )) self.wait() self.play(Write(q_marks)) self.wait() # Threat first two of three as a wedge self.play( TransformFromCopy(expr_plots[0], x12_plot), ReplacementTransform(term_braces[2], x12_brace), ReplacementTransform(term_braces[3], x12_brace), FadeOut(term_plots[2:4], DOWN), FadeOut(symbols[2], DOWN), symbols[3].animate.shift(0.5 * LEFT) ) self.wait() self.play( TransformFromCopy(x12_plot, expr_plots[1]), TransformFromCopy(term_plots[4], expr_plots[1]), FadeOut(q_marks, RIGHT) ) self.wait() class ConfusedAtThree(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.play( morty.change("raise_right_hand"), self.change_students("maybe", "confused", "sassy", look_at=self.screen) ) self.wait(2) self.look_at(morty.get_corner(UL)) self.play(self.change_students("hesitant", "maybe", "pondering", look_at=self.screen)) self.wait(5) class LikeAMovingAverage(InteractiveScene): def construct(self): words = Text("Kind of like\na moving average") top_words = words["Kind of like"] cross = Cross(top_words) self.play(FadeIn(words, lag_ratio=0.1)) self.wait() self.play(ShowCreation(cross)) self.wait() class KeepGoing(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.play( stds[0].says("More\niterations!", mode="hooray", bubble_config=dict(width=4, height=2)), stds[1].change("tease", stds[0].eyes), stds[2].change("coin_flip_1", stds[0].eyes), morty.change("happy"), run_time=1 ) self.wait(5) class SumOfThree(InteractiveScene): def construct(self): self.add(Tex("X_1 + X_2 + X_3")) class SumOfFour(InteractiveScene): def construct(self): self.add(Tex("X_1 + X_2 + X_3 + X_4")) class WhyNormals(InteractiveScene): def construct(self): # Add graph plane = NumberPlane( (-4, 4), (0, 0.75, 0.125), width=7, height=5, axis_config=dict(stroke_width=1), background_line_style=dict(stroke_color=GREY_B, stroke_width=1, stroke_opacity=0.5) ) plane.to_edge(RIGHT) graph = plane.get_graph(lambda x: np.exp(-x**2 / 2) / math.sqrt(TAU)) graph.set_stroke(BLUE, 3) formula = Tex(R"\frac{1}{\sqrt{2\pi}} e^{-x^2 / 2}") formula.next_to(graph.pfp(0.45), UL, buff=-0.25) formula.set_backstroke() name = Text("Standard normal distribution", font_size=48) name.next_to(plane.get_top(), DOWN, buff=0.2) name.set_backstroke() self.add(plane) self.add(graph) self.add(formula) self.add(name) # Ask question randy = Randolph(height=2) randy.move_to(interpolate(plane.get_left(), LEFT_SIDE, 0.75)) randy.align_to(plane, DOWN) morty = Mortimer(height=2) morty.next_to(randy, RIGHT, buff=1.0) self.add(randy) self.play(LaggedStart( randy.thinks( Text("Why this\nfunction?", font_size=32), mode="pondering", look_at=formula, run_time=1 ), FlashAround(formula, run_time=3, time_width=1.5) )) self.play(Blink(randy)) self.wait() self.play( randy.debubble(mode="tease", look_at=morty.eyes), VFadeIn(morty), morty.says( Text("There's a very\nfun answer", font_size=32), look_at=randy.eyes, run_time=1 ), ) self.wait(4) class AskIfItsTheArea(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.remove(self.background) # Test self.play( stds[0].says( TexText("Is $[f*g](s)$ the\narea of this slice?"), mode="raise_left_hand", look_at=self.screen, ), stds[1].change("pondering", self.screen), stds[2].change("pondering", self.screen), morty.change("tease", stds[0].eyes), ) self.wait(3) self.play(morty.says("Almost!", mode="coin_flip_2")) self.play( self.change_students("confused", "erm", "hesitant", look_at=morty.eyes) ) self.wait(5) class TwoRects(InteractiveScene): height = 5.5 width = 6.11 buff = 1.0 bottom_buff = MED_LARGE_BUFF def construct(self): rects = Rectangle(self.width, self.height).replicate(2) rects.set_stroke(WHITE, 2) rects.arrange(RIGHT, buff=self.buff) rects.to_edge(DOWN, buff=self.bottom_buff) self.add(rects) class ShorterRects(TwoRects): height = 4.0 width = 6.5 buff = 0.25 bottom_buff = 1.5 class IndicatingRectangle(InteractiveScene): def construct(self): self.play(FlashAround(Rectangle(9, 3), run_time=2, time_width=1.5, stroke_width=8)) class Sqrt2Correction(InteractiveScene): def construct(self): # Test words = TexText(R"Technically, this shape is $\sqrt{2}$ times wider than this shape") shape_words = words["this shape"] words.to_edge(UP, buff=0.5) points = [ [-3.75, 0.25, 0], [2.5, -2.5, 0], ] colors = [YELLOW, TEAL] arrows = VGroup() for word, point, color in zip(shape_words, points, colors): word.set_color(color) arrow = FillArrow(word[:4].get_bottom(), point) arrow.scale(0.9) arrow.set_fill(color, 1) arrow.set_backstroke() arrows.add(arrow) self.play(FadeIn(words, lag_ratio=0.1)) self.play(LaggedStartMap(GrowArrow, arrows, lag_ratio=0.5)) self.wait() class Sqrt2Explanation(InteractiveScene): def construct(self): # Test tex_kw = dict(font_size=30, alignment="") explanation = VGroup( TexText(R""" Think about what a Riemann sum approximating the area of \\ the slice below would look like, where the slice is taken over \\ the line $x + y = s$. If you have some samples of $x$, spaced \\ apart by $\Delta x$, the sum of the areas of the rectangles \\ below looks like\\ $$ \displaystyle \sum_{x \in \text{samples}} \overbrace{f(x) g(s - x)}^{\text{Rect. height}} \underbrace{\sqrt{2} \cdot \Delta x}_{\text{Rect. width}} $$\\ """, **tex_kw), TexText(R""" This is \emph{almost} a Riemann approximation of the\\ integral we care about \\ $$\displaystyle [f * g](s) = \int_{-\infty}^\infty f(x)g(s - x)dx.$$\\ The only difference is that factor of $\sqrt{2}$. That factor \\ persists in the limit as $\Delta x \to 0$, so the area of the \\ slice below is exactly $\sqrt{2} \cdot [f * g](s)$.\\ """, **tex_kw), ) explanation[0][196:].scale(1.25, about_edge=UP).match_x(explanation[0][:196]) explanation[1][57:83].scale(1.25, about_edge=UP).match_x(explanation[1][:57]) explanation.arrange(RIGHT, buff=LARGE_BUFF, aligned_edge=UP) explanation.set_width(FRAME_WIDTH - 1) h_line = Line(UP, DOWN).match_height(explanation) h_line.move_to(explanation) h_line.shift(0.5 * RIGHT) h_line.set_stroke(GREY_B, 1) explanation.add(h_line) explanation.to_edge(UP) self.add(explanation) class SimpleQuestion(InteractiveScene): def construct(self): # Rectangles rects = ScreenRectangle().replicate(2) rects.set_height(0.45 * FRAME_HEIGHT) rects.arrange(RIGHT, buff=0.75).shift(0.5 * DOWN) # Equations equations = VGroup( Tex("X + Y", font_size=60), Tex(R"\int_{-\infty}^\infty f(x)g(s - x)dx"), ) for equation, rect in zip(equations, rects): equation.next_to(rect, UP) # Words words = VGroup( Text("Such a \n simple question!"), Text( "Such a seemingly \n simple question.", t2s={"seemingly": ITALIC}, t2c={"seemingly": YELLOW}, ) ) for word in words: word.match_x(rects[0]) word.to_edge(UP, buff=MED_SMALL_BUFF) self.play( Write(words[0], run_time=1), FadeIn(equations[0]) ) self.wait() self.play(TransformMatchingStrings( words[0], words[1], key_map={"!": "."}, run_time=1, )) self.wait() # self.play(Write(equations[1])) self.play(TransformFromCopy(equations[0], equations[1]), run_time=2, lag_ratio=0.02) self.wait(2) class ComplainAboutCalculation(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.remove(self.background) # Complain self.play( stds[2].says("But do these help\nwith actual computations?", mode="sassy"), morty.change("guilty") ) self.play(self.change_students("erm", "frustrated", look_at=self.screen)) self.wait(3) # Opening quiz self.play( stds[1].says("Like, the opening quiz?", mode="raise_right_hand"), stds[2].debubble(mode="hesitant", look_at=self.screen), stds[0].change("pondering"), ) self.play(morty.change("well")) self.look_at(self.screen) self.wait(3) # React to ordinary approach self.play( morty.change("raise_left_hand", 4 * UR), stds[0].animate.look_at(3 * UR), stds[1].debubble(mode="pondering", look_at=3 * UR), stds[2].change("pondering", 3 * UR), self.frame.animate.set_height(12, about_edge=DOWN) ) self.wait(4) self.play( morty.change("raise_right_hand", look_at=self.screen), self.change_students("hesitant", "pondering", "guilty", look_at=self.screen), ) self.wait(2) self.play( self.change_students("horrified", "pleading", "concentrating", look_at=2 * UR) ) self.play(morty.change("tease")) self.wait(4) self.play( morty.change("coin_flip_2"), self.change_students("guilty", "guilty", "sick", look_at=2 * UR) ) self.wait() self.play( morty.change("hooray"), self.change_students("well", "tease", "happy", look_at=morty.eyes) ) self.wait(4) class OrdinaryApproach(InteractiveScene): def construct(self): # Title self.add(FullScreenRectangle().scale(2)) title = Text("Ordinary (messy) approach") title.set_x(0.25 * FRAME_WIDTH) title.to_edge(UP, buff=MED_SMALL_BUFF) title.set_backstroke() underline = Underline(title, buff=-0.05) self.play( ShowCreation(underline), FadeIn(title, lag_ratio=0.1), ) self.wait() # Equations tex1 = R"f(x) = \frac{1}{\sigma_1 \sqrt{2\pi}} e^{-x^2 / 2\sigma_1^2}" tex2 = R"g(y) = \frac{1}{\sigma_2 \sqrt{2\pi}} e^{-y^2 / 2\sigma_2^2}" tex_kw = dict( font_size=30, t2c={"x": BLUE, "y": YELLOW} ) equations = VGroup( Tex(tex1, **tex_kw), Tex(tex2, **tex_kw), ) equations.arrange(DOWN, buff=0.75, aligned_edge=LEFT) equations.next_to(title, DOWN, buff=0.75, aligned_edge=LEFT) brace = Brace(equations[0], RIGHT, tex_string=R"\underbrace{\qquad\qquad\qquad}") brace.stretch(1.5, 1) brace_text = brace.get_text( "Formula\nfor a normal\ndistribution", font_size=30, alignment="LEFT", buff=MED_SMALL_BUFF, ) self.play(LaggedStartMap(FadeIn, equations, lag_ratio=0.5, run_time=1)) self.play( GrowFromCenter(brace), FadeIn(brace_text, lag_ratio=0.1) ) self.wait() # Convolution conv_equation = Tex( R""" [f * g](s) = \int_{-\infty}^\infty f(x)g(s - x) dx = \int_{-\infty}^\infty \frac{1}{\sigma_1 \sigma_2 2 \pi} e^{-x^2 / 2\sigma_1^2} e^{-(s - x)^2 / 2\sigma_2^2} \; dx """, t2c={"x": BLUE, "s": GREEN}, font_size=36, ) conv_equation.move_to(1.0 * DOWN) rhss = conv_equation[re.compile(r"=.*dx")] lhs = conv_equation["[f * g](s)"] self.play(FadeIn(lhs), FadeIn(rhss[0])) self.wait() self.play( LaggedStart( FadeTransform(equations[0].copy(), rhss[1]), FadeTransform(equations[1].copy(), rhss[1]), FadeTransform(rhss[0].copy(), rhss[1]), lag_ratio=0.05, ), self.frame.animate.move_to(DOWN), run_time=2 ) self.wait() # Low brace low_brace = Brace(rhss[1][1:], DOWN, buff=SMALL_BUFF) calc_text = low_brace.get_text( "Not prohibitively difficult,\nbut a bit clunky", font_size=30 ) self.play( GrowFromCenter(low_brace), FadeIn(calc_text, lag_ratio=0.1) ) self.wait() # Toss out formula to_toss = VGroup(conv_equation, low_brace, calc_text) self.play( FadeOut(to_toss, 6 * RIGHT, path_arc=-30 * DEGREES, rate_func=running_start, run_time=1) ) self.wait() class GaussianFunctionAnnotations(InteractiveScene): def construct(self): # Test tex_kw = dict(font_size=36, t2c={"x": BLUE, "y": YELLOW}) functions = VGroup( Tex(R"f(x) = \frac{1}{\sigma \sqrt{2\pi}} e^{-x^2 / 2\sigma^2}", **tex_kw), Tex(R"g(y) = \frac{1}{\sigma \sqrt{2\pi}} e^{-y^2 / 2\sigma^2}", **tex_kw), ) functions.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) functions.to_corner(UL) self.add(functions) class PredictTheProof(InteractiveScene): def construct(self): morty = Mortimer(height=2) morty.to_corner(DR) self.play(morty.says("Try predicting\nthe proof!")) for x in range(3): self.play(Blink(morty)) self.wait(4 * random.random()) class PiScene(InteractiveScene): def construct(self): morty = Mortimer(height=1.5) randy = Randolph(height=1.5) morty.set_x(3).to_edge(UP) randy.set_x(-3).to_edge(UP) self.play( morty.change("pondering", ORIGIN), randy.change("thinking", ORIGIN), ) self.wait() class ThumbnailMaterial(InteractiveScene): def construct(self): # Graphs axes = Axes((-2, 2), (0, 1, 0.25), width=7, height=3) exp_graph = axes.get_graph(lambda x: np.exp(-2 - x)) exp_graph.set_stroke(BLUE, 5) exp_label = Tex("p_X(x)", font_size=72) exp_label.next_to(exp_graph.pfp(0.2), UR, SMALL_BUFF) wedge_graph = axes.get_graph(wedge_func, use_smoothing=False) wedge_graph.set_stroke(YELLOW, 5) wedge_label = Tex("p_Y(y)", font_size=72) wedge_label.next_to(wedge_graph.pfp(0.4), UL, SMALL_BUFF) # conv_label = Tex("[f * g](-1.5)", font_size=72) # self.add(conv_label) # return self.add(axes) self.add(exp_graph) self.add(exp_label) # self.add(wedge_graph) # self.add(wedge_label) class EndScreen(PatreonEndScreen): pass
from manim_imports_ext import * from _2022.convolutions.discrete import * from _2023.clt.main import * SKEW_DISTRIBUTION = [0.12, 0.23, 0.31, 0.18, 0.12, 0.04] # Helpers def get_bar_group( dist, bar_colors=(BLUE_D, TEAL_D), value_labels=None, width_ratio=0.7, height=2.0, number_config=dict(), label_buff=SMALL_BUFF, ): bars = dist_to_bars(dist, bar_colors=bar_colors, height=height) p_labels = VGroup(*(DecimalNumber(x, **number_config) for x in dist)) p_labels.set_max_width(width_ratio * bars[0].get_width()) for p_label, bar in zip(p_labels, bars): p_label.next_to(bar, UP, SMALL_BUFF) if value_labels is None: value_labels = VectorizedPoint().replicate(len(dist)) for value_label, bar in zip(value_labels, bars): value_label.set_width(width_ratio * bars[0].get_width()) value_label.next_to(bar, DOWN, buff=label_buff) labeled_bars = VGroup(*( VGroup(bar, value_label, p_label) for bar, value_label, p_label in zip(bars, value_labels, p_labels) )) for group in labeled_bars: group.bar, group.die, group.value_label = group return labeled_bars def die_sum_labels(color1=BLUE_E, color2=RED_E, height=1.0): die1, die2 = dice = [ DieFace(1, fill_color=color) for color in [color1, color2] ] for die in dice: die.remove(die[1]) die.set_height(height / 3) result = VGroup() for n in range(2, 13): sum_sym = VGroup( die1.copy(), Tex("+", font_size=24), die2.copy(), Tex("=", font_size=24).rotate(90 * DEGREES), Tex(str(n), font_size=30), ) sum_sym.arrange(DOWN, buff=SMALL_BUFF) sum_sym[:2].shift(0.05 * DOWN) sum_sym[:1].shift(0.05 * DOWN) sum_sym.set_height(height) result.add(sum_sym) result.arrange(RIGHT) return result def rotate_sum_label(sum_label): sum_label.arrange(RIGHT, buff=SMALL_BUFF) sum_label[-2].rotate(90 * DEGREES) sum_label[-2:].set_height(sum_label.get_height(), about_edge=LEFT) sum_label[-2:].shift(SMALL_BUFF * RIGHT) sum_label[-1].shift(SMALL_BUFF * RIGHT) def p_mob(mob, scale_factor=1.0): used_mob = mob.copy() aspect_ratio = mob.get_width() / mob.get_height() Os = "O" * int(np.round(aspect_ratio)) tex = Tex(f"P({Os})") used_mob.replace(tex[Os], dim_to_match=0) used_mob.scale(scale_factor) result = VGroup(*tex[:2], used_mob, tex[-1]) result.arg = used_mob return result # Scenes class SumAlongDiagonal(InteractiveScene): samples = 4 dist1 = EXP_DISTRIBUTION dist2 = SKEW_DISTRIBUTION dist1_colors = (BLUE_D, TEAL_D) dist2_colors = (RED_D, GOLD_E) sum_colors = (GREEN_E, YELLOW_E) def construct(self): # Setup distributions dist1 = self.dist1 dist2 = self.dist2 blue_dice = get_die_faces(fill_color=BLUE_E, dot_color=WHITE) red_dice = get_die_faces(fill_color=RED_E, dot_color=WHITE) bar_groups = VGroup( get_bar_group(dist1, self.dist1_colors, blue_dice), get_bar_group(dist2, self.dist2_colors, red_dice), ) bar_groups.arrange(DOWN, buff=LARGE_BUFF) bar_groups.to_edge(LEFT) self.add(bar_groups) # Setup the sum distribution conv_dist = np.convolve(dist1, dist2) sum_labels = die_sum_labels() sum_bar_group = get_bar_group( conv_dist, self.sum_colors, sum_labels, number_config=dict(num_decimal_places=3, font_size=30), label_buff=MED_SMALL_BUFF, ) sum_bar_group.to_edge(RIGHT, buff=LARGE_BUFF) sum_bar_group.set_y(0) buckets = VGroup() for bar in sum_bar_group: base = Line(LEFT, RIGHT) base.match_width(bar) base.move_to(bar[0], DOWN) v_lines = Line(DOWN, UP).replicate(2) v_lines.set_height(6) v_lines[0].move_to(base.get_left(), DOWN) v_lines[1].move_to(base.get_right(), DOWN) bucket = VGroup(base, *v_lines) bucket.set_stroke(GREY_C, 2) buckets.add(bucket) self.add(sum_labels) self.add(buckets) # Repeatedly sample from these two (for a while) self.show_repeated_samples( dist1, dist2, *bar_groups, buckets, sum_labels, n_animated_runs=1, n_total_runs=2, ) # Ask about sum values rects = VGroup(*( SurroundingRectangle(sum_label) for sum_label in sum_labels )) words1 = Text("What's the probability\nof this?", font_size=36) words2 = Text("Or this?", font_size=36) words1.next_to(rects[0], DOWN, MED_SMALL_BUFF) words2.next_to(rects[1], DOWN, MED_SMALL_BUFF) self.play(ShowCreation(rects[0]), FadeIn(words1)) self.wait() self.play( TransformMatchingStrings(words1, words2, run_time=1), FadeOut(rects[0]), FadeIn(rects[1]), ) self.wait() for i in range(1, len(rects) - 1): self.play( FadeOut(rects[i]), FadeIn(rects[i + 1]), words2.animate.match_x(rects[i + 1]), run_time=0.5 ) self.wait() self.play(FadeOut(words2), FadeOut(rects[-1])) self.play(FadeOut(sum_labels), FadeOut(buckets)) # Draw grid of dice values grid = Square().get_grid(6, 6, buff=0, fill_rows_first=False, ) grid.flip(RIGHT) grid.set_stroke(WHITE, 1) grid.set_height(5.5) grid.to_edge(RIGHT, buff=LARGE_BUFF) grid.to_edge(UP) blue_row = blue_dice.copy() red_col = red_dice.copy() for square, die in zip(grid[::6], blue_row): die.set_width(0.5 * square.get_width()) die.next_to(square, DOWN) for square, die in zip(grid, red_col): die.set_width(0.5 * square.get_width()) die.next_to(square, LEFT) self.play( ShowCreation(grid, lag_ratio=0.5), TransformFromCopy(blue_dice, blue_row), TransformFromCopy(red_dice, red_col), ) dice_pairs = VGroup() anims = [] for n, square in enumerate(grid): templates = VGroup( blue_row[n // 6], red_col[n % 6], ) pair = templates.copy() pair.arrange(RIGHT, buff=SMALL_BUFF) pair.set_width(square.get_width() * 0.7) pair.move_to(square) dice_pairs.add(pair) anims.extend([ TransformFromCopy(templates, pair), ]) self.play(LaggedStart(*anims, lag_ratio=0.1)) self.add(dice_pairs) self.wait() full_table = VGroup(blue_row, red_col, grid, dice_pairs) # Highlight (4, 2) pair pairs = [ (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 5), (2, 4), (2, 3), (3, 3), (3, 2), (4, 2), ] for pair in pairs: self.isolate_pairs(bar_groups, full_table, pair) self.wait(0.5) self.wait() # Show the probability of (4, 2) def get_p_label(dice): p_label = VGroup( p_mob(dice), Tex("="), p_mob(dice[0]), p_mob(dice[1]), ) p_label.arrange(RIGHT, buff=SMALL_BUFF) return p_label i0, j0 = pairs[-1] p_label = get_p_label(dice_pairs[(i0 - 1) * 6 + (j0 - 1)]) p_label.to_edge(UP) p_label.shift(2.5 * LEFT) movers = VGroup( dice_pairs[(i0 - 1) * 6 + j0 - 1], blue_row[(i0 - 1)], red_col[(j0 - 1)], ).copy() self.play( bar_groups.animate.set_width(2.5, about_edge=DL), full_table.animate.set_width(5.5, about_edge=DR), LaggedStart( movers[0].animate.replace(p_label[0][2]), movers[1].animate.replace(p_label[2][2]), movers[2].animate.replace(p_label[3][2]), lag_ratio=0.25, ), ) self.play(FadeIn(p_label)) self.remove(movers) self.wait() # Show numerical product prod_rhs = Tex("= (0.00)(0.00)") num_rhs = Tex("= 0.000") value1, value2 = prod_rhs.make_number_changable("0.00", replace_all=True) value1.set_value(dist1[i0 - 1]).set_color(BLUE) value2.set_value(dist2[j0 - 1]).set_color(RED) prod_rhs.next_to(p_label[1], DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) pair_prob = num_rhs.make_number_changable("0.000") pair_prob.set_value(dist1[i0 - 1] * dist2[j0 - 1]) num_rhs.next_to(prod_rhs, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) self.play(LaggedStart( Transform(bar_groups[0][i0 - 1][2].copy(), value1.copy(), remover=True), Transform(bar_groups[1][j0 - 1][2].copy(), value2.copy(), remover=True), Write(prod_rhs, lag_ratio=0.1), lag_ratio=0.5 )) self.wait() self.play(FadeIn(num_rhs, DOWN)) self.wait() example = VGroup(p_label, prod_rhs, num_rhs) # Assumption morty = Mortimer(height=2.0).flip() morty.next_to(example, DOWN, buff=2.0) morty.shift(0.5 * LEFT) self.play( morty.says( "Assuming rolls\nare independent!", mode="surprised", max_bubble_width=3.5 ), VFadeIn(morty), ) self.play(Blink(morty)) self.wait() self.play(LaggedStartMap(FadeOut, VGroup(morty, morty.bubble, morty.bubble.content))) # Set up the multiplication table full_table.generate_target() full_table.target.set_width(6.5) full_table.target.set_opacity(1) full_table.target[2].set_fill(opacity=0) full_table.target.to_edge(RIGHT, buff=1.5) full_table.target.set_y(0) self.play( MoveToTarget(full_table), example.animate.scale(0.75, about_edge=UL).shift(0.5 * LEFT) ) marginal_labels = VGroup(*( VGroup(*(bar[2] for bar in group)).copy() for group in bar_groups )) margin_dice = VGroup(*full_table[:2], full_table[3]) for margins, dice in zip(marginal_labels, margin_dice): margins.generate_target() dice.generate_target() for die, prob in zip(dice.target, margins.target): center = die.get_center() die.scale(0.7) die.set_opacity(0.85) prob.next_to(die, DOWN, buff=0.125) prob.scale(1.5) VGroup(prob, die).move_to(center) marginal_labels[0].target.set_fill(BLUE, 1) marginal_labels[1].target.set_fill(RED, 1) margin_dice[2].generate_target() for dice in margin_dice[2].target: dice.scale(0.75, about_edge=UP) dice.set_opacity(0.85) dice.set_stroke(width=1) dice.shift(0.1 * UP) for groups in zip(marginal_labels, margin_dice): self.play(*map(MoveToTarget, groups), lag_ratio=0.001) self.play(MoveToTarget(margin_dice[2], lag_ratio=0.001)) self.wait() full_table.add(marginal_labels) # Fill in multiplication table grid_probs = VGroup() self.add(grid_probs) for n, square in enumerate(grid): i, j = n // 6, n % 6 dice = margin_dice[2][n] margin1 = marginal_labels[0][i] margin2 = marginal_labels[1][j] prob = DecimalNumber( margin1.get_value() * margin2.get_value(), num_decimal_places=3 ) prob.set_height(margin1.get_height()) prob.next_to(dice, DOWN, SMALL_BUFF) rects = VGroup(*( SurroundingRectangle(mob, buff=SMALL_BUFF) for mob in [margin1, margin2, prob] )) rects.set_stroke(YELLOW, 1) grid_probs.add(prob) value1.set_value(dist1[i]) value2.set_value(dist2[j]) pair_prob.set_value(dist1[i] * dist2[j]) new_p_label = get_p_label(dice.copy().set_opacity(1)) new_p_label.replace(p_label, dim_to_match=1) p_label.become(new_p_label) bar_groups.set_opacity(0.35) bar_groups[0][i].set_opacity(1) bar_groups[1][j].set_opacity(1) self.add(rects) self.wait(0.25) self.remove(rects) self.wait() full_table.add(grid_probs) # Fade out example self.play( FadeOut(example), bar_groups.animate.set_opacity(1), ) self.wait() # Show it as a 3d plot bar_groups.fix_in_frame() sum_bar_group.fix_in_frame() bars_3d = VGroup() scale_factor = 30 for square, prob in zip(grid, grid_probs): prism = VCube() prism.set_fill(GREY_D, 0.85) prism.set_stroke(WHITE, 1, 0.5) prism.match_width(square) prism.set_depth(scale_factor * prob.get_value(), stretch=True) prism.move_to(square, IN) prism.save_state() prism.stretch(0.001, 2, about_edge=IN) prism.set_opacity(0) bars_3d.add(prism) self.play( LaggedStartMap(Restore, bars_3d), self.frame.animate.reorient(12, 65, 0).move_to([-0.48, 0.37, 0.77]).set_height(9.43), run_time=3, ) self.add(full_table, *bars_3d) self.play( self.frame.animate.reorient(43, 66, 0).move_to([-0.06, 0.21, -0.29]).set_height(10.59), run_time=7, ) self.wait() # Show sum distribution self.play( LaggedStartMap(FadeOut, bar_groups, shift=2 * LEFT), FadeIn(sum_bar_group), full_table.animate.to_edge(LEFT), self.frame.animate.reorient(4, 65, 0).move_to([0.64, 0.8, 0.69]).set_height(10.59), *( MaintainPositionRelativeTo(bar, full_table) for bar in bars_3d ), run_time=2, ) self.wait() # Reposition self.play( self.frame.animate.to_default_state(), FadeOut(bars_3d), run_time=2, ) self.wait() # Add up along all diagonals low_group = VGroup(blue_row, marginal_labels[0]) left_group = VGroup(red_col, marginal_labels[1]) diagonals = VGroup(*( VGroup(*( VGroup(dice_pairs[n], grid_probs[n]) for n in range(36) if (n // 6) + (n % 6) == s )) for s in range(11) )) diagonals.save_state() rects = VGroup() diagonals.rotate(45 * DEGREES) for diagonal in diagonals: rect = SurroundingRectangle(diagonal) rect.stretch(0.9, 1) rect.round_corners() rects.add(rect) VGroup(rects, diagonals).rotate(-45 * DEGREES, about_point=diagonals.get_center()) rects.set_fill(YELLOW, 0.25) rects.set_stroke(YELLOW, 2) last_rect = VGroup(low_group, left_group) for n, rect in zip(it.count(), rects): self.add(rect, diagonals) diagonals.generate_target() diagonals.target.set_opacity(0.5) diagonals.target[n].set_opacity(1) sum_bar_group.generate_target() sum_bar_group.target.set_opacity(0.4) sum_bar_group.target[n].set_opacity(1) self.play( FadeOut(last_rect), FadeIn(rect), MoveToTarget(diagonals), MoveToTarget(sum_bar_group), ) last_rect = rect self.wait() self.play( diagonals.animate.set_opacity(1), sum_bar_group.animate.set_opacity(1), FadeOut(last_rect), FadeIn(low_group), FadeIn(left_group), ) # Show 3d grid again self.play( self.frame.animate.reorient(27, 66, 0).move_to([-0.16, 1.41, 0.77]).set_height(9.36), FadeIn(bars_3d), sum_bar_group.animate.to_edge(RIGHT), run_time=2, ) self.wait() # Go through diagonals of the plot sorted_bars = VGroup(*bars_3d) camera_pos = self.frame.get_implied_camera_location() sorted_bars.sort(lambda p: -get_norm(p - camera_pos)) self.add(*sorted_bars) diagonal_bar_groups = VGroup().replicate(11) for s in range(11): sum_bar_group.generate_target() sum_bar_group.target.set_opacity(0.2) sum_bar_group.target[s].set_opacity(1) for n, bar in enumerate(bars_3d): bar.generate_target() bar.target.set_opacity(0.1) bar.target.set_stroke(width=0) if (n // 6) + (n % 6) == s: bar.target.set_opacity(1) diagonal_bar_groups[s].add(bar) self.play( MoveToTarget(sum_bar_group), *map(MoveToTarget, bars_3d), ) self.wait() self.play( bars_3d.animate.set_opacity(0.8).set_stroke(width=0.5), sum_bar_group.animate.set_opacity(1), ) self.wait() # Highlight bars bars_3d.save_state() bar_highlights = bars_3d.copy() bar_highlights.set_fill(opacity=0) bar_highlights.set_stroke(TEAL, 3) self.play(ShowCreationThenFadeOut(bar_highlights, lag_ratio=0.001, run_time=2)) # Collapase diagonals bars_3d.generate_target() for bar in bars_3d.target: bar.stretch(0.5, 0) bar.stretch(0.5, 1) bars_3d.target.set_fill(opacity=1) bars_3d.target.set_submobject_colors_by_gradient(GREEN_D, YELLOW_D) bars_3d.target.set_stroke(WHITE, 1) self.play( self.frame.animate.reorient(36, 46, 0).move_to([-0.56, 0.55, 1.22]).set_height(7.71), MoveToTarget(bars_3d), # FadeOut(full_table, IN), sum_bar_group.animate.set_width(4.0).to_edge(RIGHT), run_time=2, ) self.wait() diagonal_bar_groups.apply_depth_test() new_diagonals = diagonal_bar_groups.copy() for group in new_diagonals: group.arrange(IN, buff=0) new_diagonals.arrange(UR, buff=MED_SMALL_BUFF, aligned_edge=IN) new_diagonals.move_to(bars_3d.get_corner(DR)) new_diagonals.shift(DR) self.play( self.frame.animate.reorient(40, 61, 0).move_to([1.69, 0.33, -0.73]).set_height(12.96), ReplacementTransform( diagonal_bar_groups, new_diagonals, lag_ratio=0.001, ), run_time=5, ) self.add(full_table, new_diagonals) self.play( self.frame.animate.reorient(40, 85, 0).move_to([3.05, 1.93, 0.77]).set_height(14.93), sum_bar_group.animate.set_width(5.5, about_edge=RIGHT), FadeOut(full_table), run_time=3 ) self.wait() def show_repeated_samples( self, dist1, dist2, bar_group1, bar_group2, buckets, sum_labels, n_animated_runs=20, n_total_runs=150, marker_height=0.1, marker_color=YELLOW_D, ): marker_template = Rectangle( height=marker_height, width=buckets[0].get_width() * 0.8, fill_color=marker_color, fill_opacity=1, stroke_color=WHITE, stroke_width=1, ) markers = VGroup(*( VGroup(VectorizedPoint(bucket.get_bottom())) for bucket in buckets )) var1 = scipy.stats.rv_discrete(values=(range(6), dist1)) var2 = scipy.stats.rv_discrete(values=(range(6), dist2)) for n in range(n_total_runs): x = var1.rvs() y = var2.rvs() animate = n < n_animated_runs # Show dice dice = VGroup() for group, value in [(bar_group1, x), (bar_group2, y)]: die = group[value][1].copy() die.set_opacity(1) die.scale(2) die.next_to(group, RIGHT, LARGE_BUFF) dice.add(die) group.set_opacity(0.5) group[value].set_opacity(1) self.add(die) self.wait(0.25 if animate else 0.0) # Highlight sum sum_labels.set_opacity(0.25) sum_labels[x + y].set_opacity(1) # Drop marker in the appropriate sum bucket marker = marker_template.copy() marker.move_to(markers[x + y].get_top(), DOWN) if animate: self.play(FadeIn(marker, DOWN, rate_func=rush_into, run_time=0.5)) self.wait(0.5) markers[x + y].add(marker) self.add(markers) if animate: self.play(LaggedStart( FadeOut(dice[0]), bar_group1.animate.set_opacity(0.5), FadeOut(dice[1]), bar_group2.animate.set_opacity(0.5), sum_labels.animate.set_opacity(0.25), run_time=0.5 )) else: self.wait(0.1) self.remove(dice) VGroup(bar_group1, bar_group2).set_opacity(0.5) sum_labels.set_opacity(0.25) self.wait() self.play( FadeOut(markers, lag_ratio=0.01), bar_group1.animate.set_opacity(1), bar_group2.animate.set_opacity(1), sum_labels.animate.set_opacity(1), ) def isolate_pairs(self, bar_groups, full_table, *ij_tuples): full_table.set_opacity(0.25) full_table[2].set_fill(opacity=0) bar_groups.set_opacity(0.35) for i, j in ij_tuples: im1 = i - 1 jm1 = j - 1 n = im1 * 6 + jm1 bar_groups[0][im1].set_opacity(1) bar_groups[1][jm1].set_opacity(1) full_table[0][im1].set_opacity(1) full_table[1][jm1].set_opacity(1) full_table[2][n].set_stroke(opacity=1) full_table[3][n].set_opacity(1) class ConvolveDiscreteDistributions(SumAlongDiagonal): long_form = True def construct(self): # Set up two distributions dist1 = self.dist1 dist2 = self.dist2 blue_dice = get_die_faces(fill_color=BLUE_E, dot_color=WHITE) red_dice = get_die_faces(fill_color=RED_E, dot_color=WHITE) top_bars, low_bars = bar_groups = VGroup( get_bar_group(dist1, self.dist1_colors, blue_dice), get_bar_group(dist2, self.dist2_colors, red_dice), ) bar_groups.arrange(DOWN, buff=LARGE_BUFF) bar_groups.to_edge(LEFT) self.add(bar_groups) # Setup the sum distribution conv_dist = np.convolve(dist1, dist2) sum_labels = die_sum_labels() sum_bar_group = get_bar_group(conv_dist, self.sum_colors, sum_labels) sum_bar_group.to_edge(RIGHT, buff=LARGE_BUFF) sum_bar_group.set_y(0) self.add(sum_bar_group) # V lines v_lines = get_bar_dividing_lines(top_bars) for bar in top_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(top_bars.get_right()[0])) # Flip low_bars.target = low_bars.generate_target() low_bars.target.arrange(LEFT, aligned_edge=DOWN, buff=0).move_to(low_bars) low_bars.target.move_to(low_bars) rect = SurroundingRectangle(low_bars) label = Text("Flip this") label.next_to(rect, RIGHT) low_arrow = Arrow(low_bars.get_right(), low_bars.get_left()) low_arrow.set_stroke(color=YELLOW) low_arrow.next_to(low_bars, DOWN) self.play( ShowCreation(rect), FadeIn(label) ) self.wait() self.play( MoveToTarget(low_bars, path_arc=PI / 3, lag_ratio=0.005) ) self.play(ShowCreation(low_arrow), FadeOut(rect)) self.wait() self.play( FadeOut(label), FadeOut(low_arrow), ShowCreation(v_lines, lag_ratio=0.1), ) self.wait() # Show corresponding pairs rows = VGroup(blue_dice, VGroup(*reversed(red_dice))).copy() pairs = VGroup(*(VGroup(*pair) for pair in zip(*rows))) self.play(rows.animate.arrange(UP, SMALL_BUFF).next_to(bar_groups, RIGHT)) rows.generate_target() rows.target.rotate(-90 * DEGREES) for row in rows.target: for die in row: die.rotate(90 * DEGREES) rows.target.arrange(RIGHT, buff=MED_SMALL_BUFF) rows.target.set_height(5) rows.target.next_to(bar_groups, RIGHT, buff=1) sum_bar_group.generate_target() sum_bar_group.target.set_opacity(0.25) sum_bar_group.target[7 - 2].set_opacity(1) self.play( MoveToTarget(rows, run_time=2), MoveToTarget(sum_bar_group), ) self.wait() # Go through all pairs last_rect = VMobject() for n in [*range(6), *range(4, -1, -1)]: pair = pairs[n] rect = SurroundingRectangle(pair) rect.round_corners() bar_groups.generate_target() bar_groups.target.set_opacity(0.35) bar_groups.target[0][n].set_opacity(1) bar_groups.target[1][5 - n].set_opacity(1) self.play( FadeIn(rect), FadeOut(last_rect), MoveToTarget(bar_groups), run_time=0.5 ) self.wait(0.5) last_rect = rect self.play(FadeOut(last_rect), bar_groups.animate.set_opacity(1)) self.wait() self.play(FadeOut(pairs), sum_bar_group.animate.set_opacity(1)) # March! for bars in bar_groups: for i, bar in zip(it.count(1), bars): bar.index = i for n in [7, 5, *range(2, 13)]: sum_bar_group.generate_target() sum_bar_group.target.set_opacity(0.25) sum_bar_group.target[n - 2].set_opacity(1.0) self.play( get_row_shift(top_bars, low_bars, n), MoveToTarget(sum_bar_group), ) pairs = get_aligned_pairs(top_bars, low_bars, n) label_pairs = VGroup(*(VGroup(m1.value_label, m2.value_label) for m1, m2 in pairs)) die_pairs = VGroup(*(VGroup(m1.die, m2.die) for m1, m2 in pairs)) pair_rects = VGroup(*( SurroundingRectangle(pair, buff=0.05).set_stroke(YELLOW, 2).round_corners() for pair in pairs )) pair_rects.set_stroke(YELLOW, 2) for rect in pair_rects: rect.set_width(label_pairs[0].get_width() + 0.125, stretch=True) fade_anims = [] # Spell out the full dot product products = VGroup() die_pair_targets = VGroup() for die_pair in die_pairs: product = VGroup( p_mob(die_pair[0]), p_mob(die_pair[1]), ) product.arrange(RIGHT, buff=SMALL_BUFF) die_pair_targets.add(VGroup( product[0].arg, product[1].arg, )) products.add(product) products.arrange(DOWN, buff=0.75) products.move_to(midpoint(sum_bar_group.get_left(), bar_groups.get_right())) products.shift(2 * UP).shift_onto_screen() plusses = Tex("+", font_size=48).replicate(len(pairs)) plusses[-1].scale(0).set_opacity(0) for plus, lp1, lp2 in zip(plusses, products, products[1:]): plus.move_to(VGroup(lp1, lp2)) self.play( ShowIncreasingSubsets(products), ShowIncreasingSubsets(plusses), ShowIncreasingSubsets(pair_rects), run_time=0.35 * len(products) ) self.wait(0.5) prod_group = VGroup(*products, *plusses) mover = prod_group.copy() mover.sort(lambda p: -p[1]) mover.generate_target() mover.target.set_opacity(0) for mob in mover.target: mob.replace(sum_bar_group[n - 2].value_label, stretch=True) self.play(MoveToTarget(mover, remover=True, lag_ratio=0.002)) self.wait(0.5) self.play( FadeOut(prod_group), FadeOut(pair_rects), ) self.play( get_row_shift(top_bars, low_bars, 7), sum_bar_group.animate.set_opacity(1.0), run_time=0.5 ) # Distribution labels plabel_kw = dict(tex_to_color_map={"X": BLUE, "Y": RED}) PX = Tex("P_X", **plabel_kw) PY = Tex("P_Y", **plabel_kw) PXY = Tex("P_{X + Y}", **plabel_kw) PX.next_to(top_bars.get_corner(UR), DR) PY.next_to(low_bars.get_corner(UR), DR) PXY.next_to(sum_bar_group, UP, MED_LARGE_BUFF) # Function label func_label = Text("Function", font_size=36) func_label.next_to(PX, UP, LARGE_BUFF, aligned_edge=LEFT) func_label.shift_onto_screen(buff=SMALL_BUFF) arrow = Arrow(func_label, PX.get_top(), buff=0.2) VGroup(func_label, arrow).set_color(YELLOW) x_args = VGroup(*( Tex( f"({x}) = {np.round(dist1[x - 1], 2)}" ).next_to(PX, RIGHT, SMALL_BUFF) for x in range(1, 7) )) # Die rectangles die_rects = VGroup() value_rects = VGroup() for index, x_arg in enumerate(x_args): x_die = top_bars[index].die value_label = top_bars[index].value_label die_rect = SurroundingRectangle(x_die, buff=SMALL_BUFF) value_rect = SurroundingRectangle(value_label, buff=SMALL_BUFF) for rect in die_rect, value_rect: rect.set_stroke(YELLOW, 2).round_corners() die_rects.add(die_rect) value_rects.add(value_rect) index = 2 x_arg = x_args[index] die_rect = die_rects[index] value_rect = value_rects[index] x_die = top_bars[index].die value_label = top_bars[index].value_label # Describe the distribution as a function top_rect = SurroundingRectangle(top_bars) top_rect.set_stroke(BLUE, 3) top_rect.round_corners(radius=0.25) self.play(ShowCreation(top_rect)) self.play( Write(PX), Write(func_label), ShowCreation(arrow), ) self.wait() self.play(ShowCreation(die_rect), FadeOut(top_rect)) self.play(FadeTransform(x_die.copy(), x_arg[:3])) self.play(TransformFromCopy(die_rect, value_rect)) self.play(FadeTransform(value_label.copy(), x_arg[3:])) self.wait() for i in range(6): self.remove(*die_rects, *value_rects, *x_args) self.add(die_rects[i], value_rects[i], x_args[i]) self.wait(0.5) # Label other distribution functions func_group = VGroup(func_label, arrow) func_group_Y = func_group.copy().shift(PY.get_center() - PX.get_center()) func_group_XY = func_group.copy().shift(PXY.get_center() - PX.get_center()) self.play( TransformFromCopy(func_group, func_group_Y), Write(PY), FadeOut(die_rects[-1]), FadeOut(value_rects[-1]) ) self.play( TransformFromCopy(func_group, func_group_XY), Write(PXY), ) self.wait() self.play(LaggedStartMap(FadeOut, VGroup( func_group, func_group_Y, func_group_XY, x_args[-1] ))) # Label convolution sum_bar_group.generate_target() sum_bar_group.target.shift(DOWN) conv_def = Tex( R"\big[P_X * P_Y\big](s) = \sum_{x = 1}^6 P_X(x) \cdot P_Y(s - x)", font_size=36, isolate=["x = 1", "6"], **plabel_kw, ) conv_def.next_to(sum_bar_group.target, UP, buff=MED_LARGE_BUFF) PXY_arg = Tex("(s)", font_size=36) PXY.generate_target() lhs = conv_def[:10] PXY.target.next_to(lhs, UP, LARGE_BUFF).shift_onto_screen(buff=SMALL_BUFF) PXY_arg.next_to(PXY.target, RIGHT, buff=SMALL_BUFF) eq = Tex("=").rotate(90 * DEGREES) eq.move_to(midpoint(PXY.target.get_bottom(), lhs.get_top())) conv_rect = SurroundingRectangle(conv_def["P_X * P_Y"], buff=0.05) conv_rect.set_stroke(YELLOW, 2) conv_word = Text("Convolution") conv_word.match_color(conv_rect) conv_word.next_to(conv_rect, DOWN, buff=SMALL_BUFF) self.play(LaggedStart( MoveToTarget(sum_bar_group), MoveToTarget(PXY), FadeIn(PXY_arg, UP), Write(eq), TransformFromCopy(PX, lhs[1:3]), TransformFromCopy(PY, lhs[4:6]), Write(VGroup(lhs[0], lhs[3], *lhs[6:])), )) self.wait() self.play( Write(conv_word), ShowCreation(conv_rect), ) self.wait() self.play( conv_rect.animate.become(SurroundingRectangle(conv_def["*"], buff=0.05, stroke_width=1)) ) self.wait() self.play(FadeOut(conv_word), FadeOut(conv_rect)) self.add(conv_def) conv_def[10:].set_opacity(0) # Question right hand side question_rhs = Text("= (What formula goes here?)", font_size=30) question_rhs.next_to(conv_def[:10], RIGHT) self.play(Write(question_rhs)) self.wait() # Show example input of 4 ex_rhs = Tex(R"(4) = P_{-}(1)P_{-}(3) + P_{-}(2)P_{-}(2) + P_{-}(3)P_{-}(1)") ex_rhs.scale(0.9) ex_rhs.next_to(PXY, RIGHT, buff=0.1) for n, dot in enumerate(ex_rhs["-"]): even = n % 2 == 0 substr = Tex("X" if even else "Y", font_size=24) substr.set_color(BLUE if even else RED) substr.move_to(dot) dot[0].become(substr) ex_rhs[ex_rhs.submobjects.index(dot[0]) + 2].match_color(substr) PXY_copy = PXY.copy() PXY_copy.generate_target() VGroup(PXY_copy.target, ex_rhs).to_edge(RIGHT, buff=-0.5) eq.generate_target() eq.target.rotate(-90 * DEGREES) eq.target.next_to(conv_def, LEFT) PXY.generate_target() PXY.target.next_to(eq.target, LEFT) VGroup(PXY.target, eq.target).align_to(PXY_copy.target, LEFT) example_box = SurroundingRectangle(VGroup(PXY_copy.target, ex_rhs)) example_box.set_stroke(TEAL, 1) example_words = Text("For example") example_words.match_color(example_box) example_words.next_to(example_box, UP) self.play(LaggedStart( MoveToTarget(PXY_copy), MoveToTarget(eq), MoveToTarget(PXY), Transform(PXY_arg, ex_rhs["(4)"], remover=True), conv_def.animate.next_to(eq.target, RIGHT), MaintainPositionRelativeTo(question_rhs, conv_def), FadeIn(ex_rhs, LEFT), PX.animate.next_to(bar_groups[0], LEFT), PY.animate.next_to(bar_groups[1], LEFT), self.frame.animate.set_height(9).move_to(0.5 * UP), sum_bar_group.animate.shift(0.5 * DOWN), ShowCreation(example_box), FadeIn(example_words, UP), run_time=2 )) self.wait() example = VGroup(PXY_copy, ex_rhs) self.add(example) # Cycle through cases example_box.save_state() for part in ex_rhs[re.compile(R"P[^+]*P[^+]*\)")]: self.play( example_box.animate.replace(part, stretch=True).scale(1.1).set_stroke(width=2), run_time=0.5 ) self.wait() self.play(FadeOut(example_box)) self.wait() # Show full definition general_words = Text("In general") general_words.next_to(conv_def, UP) general_words.match_x(example_words) general_words.set_color(TEAL) example_words.generate_target() example_words.target.scale(0.75) example_words.target.set_y(4.5) example_words.target.set_color(GREY_B) conv_def.set_opacity(1) self.play( Write(conv_def[10:]), FadeOut(question_rhs, DOWN), FadeIn(general_words, DOWN), MoveToTarget(example_words), example.animate.scale(0.75).next_to(example_words.target, DOWN), ) self.wait() # Talk through formula s_arrow = Vector(0.5 * DOWN, stroke_color=YELLOW) s_arrow.next_to(conv_def["s"][0], UP, SMALL_BUFF) x_arrow, y_arrow = s_arrow.replicate(2) x_arrow.next_to(conv_def["x"][1], UP, SMALL_BUFF) y_arrow.next_to(conv_def["s - x"], UP, SMALL_BUFF) self.play(GrowArrow(s_arrow)) self.wait() self.play(LaggedStart( TransformFromCopy(s_arrow, x_arrow), TransformFromCopy(s_arrow, y_arrow), )) self.wait() xeq1 = conv_def["x = 1"] y_arrow.save_state() self.play( s_arrow.animate.scale(0.75).rotate(90 * DEGREES).next_to(xeq1, LEFT, SMALL_BUFF), y_arrow.animate.scale(0.75).rotate(-90 * DEGREES).next_to(xeq1, RIGHT, SMALL_BUFF), ) self.wait() self.play( s_arrow.animate.next_to(conv_def["6"], LEFT, SMALL_BUFF), y_arrow.animate.next_to(conv_def["6"], RIGHT, SMALL_BUFF), ) self.wait() self.play( Restore(y_arrow), FadeOut(s_arrow), ) self.wait() self.play(LaggedStart(FadeOut(x_arrow), FadeOut(y_arrow))) # Show zero'd example bar_groups.generate_target() bar_groups.target.scale(2 / 3, about_point=top_bars.get_top() + UP) example_words = TexText("Plugging in $s = 4$") example_words.next_to(conv_def, DOWN, buff=1.0) example = Tex( R""" [P_X * P_Y](4) = &P_X(1) \cdot P_Y(3) \; + \\ &P_X(2) \cdot P_Y(2) \; + \\ &P_X(3) \cdot P_Y(1) \; + \\ &P_X(4) \cdot P_Y(0) \; + \\ &P_X(5) \cdot P_Y(-1) \; + \\ &P_X(6) \cdot P_Y(-2) """, t2c={ "X": BLUE, "Y": RED, }, font_size=36 ) example.next_to(example_words, DOWN, buff=0.5) summands = VGroup(*( example[Rf"P_X({x}) \cdot P_Y({4 - x})"] for x in range(1, 7) )) plusses = example["+"] plusses.shift(SMALL_BUFF * RIGHT) plusses.add(VectorizedPoint(summands[-1].get_center())) self.play( FadeIn(example[R"[P_X * P_Y](4) ="]), FadeOut(v_lines), MoveToTarget(bar_groups), MaintainPositionRelativeTo(PX, bar_groups[0]), Write(example_words), PY.animate.next_to(bar_groups.target[1], RIGHT).match_x(PX), sum_bar_group.animate.scale(0.5).next_to(bar_groups.target, DOWN, buff=0.75, aligned_edge=LEFT), ) last_rect = VectorizedPoint(summands[0].get_center()) for x, summand, plus in zip(it.count(1), summands, plusses): rect = SurroundingRectangle(VGroup(summand, plus)) rect.set_stroke(BLUE, 2) rect.round_corners() rect.add(Tex(Rf"x = {x}").next_to(rect, DOWN, SMALL_BUFF)) self.play( FadeTransform( conv_def[R"P_X(x) \cdot P_Y(s - x)"].copy(), summand, ), FadeTransform(last_rect, rect), FadeIn(plus), run_time=0.5 ) self.wait() last_rect = rect self.play(FadeOut(last_rect)) # Highlight zeros zeroed_terms = VGroup(*( example[Rf"P_Y({n})"] for n in range(0, -4, -1) )) zeroed_rect = SurroundingRectangle(zeroed_terms) zeroed_rect.set_stroke(RED, 3) zeroed_rect.stretch(1.3, 0, about_edge=LEFT) zeroed_rect.round_corners() eq_zero = Tex("= 0") eq_zero.next_to(zeroed_rect, RIGHT) eq_zero.set_color(RED) self.play(ShowCreation(zeroed_rect)) self.wait() self.play(Write(eq_zero)) self.play( summands[3:].animate.set_opacity(0.35), plusses[3:].animate.set_opacity(0.35), ) self.wait() def show_bars_creation(self, bars, lag_ratio=0.05, run_time=3): anims = [] for bar in bars: rect, num, face = bar num.rect = rect rect.save_state() rect.stretch(0, 1, about_edge=DOWN) rect.set_opacity(0) anims.extend([ FadeIn(face), rect.animate.restore(), CountInFrom(num, 0), UpdateFromAlphaFunc(num, lambda m, a: m.next_to(m.rect, UP, SMALL_BUFF).set_opacity(a)), ]) return LaggedStart(*anims, lag_ratio=lag_ratio, run_time=run_time) class ShowConvolutionOfLists(SumAlongDiagonal): def construct(self): # Set up two distributions dist1 = self.dist1 dist2 = self.dist2 conv_dist = np.convolve(dist1, dist2) kw = dict(height=1.5) blue_bars, red_bars, sum_bars = bar_groups = VGroup( get_bar_group(dist1, self.dist1_colors, **kw), get_bar_group(dist2, self.dist2_colors, **kw), get_bar_group(conv_dist, self.sum_colors, **kw), ) # Create equation parens = Tex("()()") parens.stretch(2, 1) parens.match_height(bar_groups) asterisk = Tex("*", font_size=96) equation = VGroup( parens[0], blue_bars, parens[1], asterisk, parens[2], red_bars, parens[3], Tex("=", font_size=96), sum_bars, ) equation.arrange(RIGHT) equation.set_width(FRAME_WIDTH - 1) equation.to_edge(UP, buff=1.0) self.add(equation) self.remove(sum_bars) self.play( TransformFromCopy(blue_bars, sum_bars, lag_ratio=0.003), TransformFromCopy(red_bars, sum_bars, lag_ratio=0.003), run_time=1.5 ) self.wait() # Name operation arrow = Vector(0.5 * DOWN) arrow.next_to(asterisk, UP) name = Text("Convolution", font_size=60) name.next_to(arrow, UP) VGroup(arrow, name).set_color(YELLOW) self.play( Write(name), GrowArrow(arrow) ) self.play(FlashAround(asterisk)) self.wait() # Lists of numbers vs functions list_words = Text("List of numbers", font_size=36).replicate(3) func_words = Text("Function", font_size=36).replicate(3) crosses = VGroup() for list_word, func_word, bar_group in zip(list_words, func_words, bar_groups): list_word.next_to(bar_group, DOWN) func_word.next_to(bar_group, DOWN) crosses.add(Cross(list_word)) for list_word, bar_group in zip(list_words, bar_groups): self.play( FadeIn(list_word, DOWN), LaggedStart(*( FlashAround(bar[2], time_width=1.5, buff=0.05) for bar in bar_group ), lag_ratio=0.03, run_time=2) ) self.wait() self.play(LaggedStartMap(ShowCreation, crosses, lag_ratio=0.1, run_time=1)) self.play( LaggedStartMap(FadeIn, func_words, shift=0.5 * DOWN, scale=0.5, lag_ratio=0.5), list_words.animate.shift(0.5 * DOWN), crosses.animate.shift(0.5 * DOWN),n ) self.wait() # Cycle through appropriate pairs for s in range(len(sum_bars)): bar_groups.set_opacity(0.75) sum_bars[s].set_opacity(1) for x in range(len(blue_bars)): bar_groups[:2].set_opacity(0.75) y = s - x if 0 <= y < len(red_bars): blue_bars[x].set_opacity(1) red_bars[y].set_opacity(1) self.wait(0.25) self.wait(0.5) self.play(bar_groups.animate.set_opacity(1)) self.wait() class ConvolveMatchingDiscreteDistributions(ConvolveDiscreteDistributions): dist1 = EXP_DISTRIBUTION dist2 = EXP_DISTRIBUTION class RepeatedDiscreteConvolutions(InteractiveScene): distribution = EXP_DISTRIBUTION def construct(self): # Divide up space h_lines = Line(LEFT, RIGHT).set_width(FRAME_WIDTH).replicate(4) h_lines.arrange(DOWN, buff=FRAME_HEIGHT / 3).center() h_lines.set_stroke(WHITE, 1) self.add(h_lines[1:3]) # Initial distributions dist = self.distribution top_bars = self.get_bar_group(dist, colors=(BLUE, TEAL)) top_bars.next_to(h_lines[1], UP, SMALL_BUFF) low_bars = top_bars.copy() low_bars.set_y(-top_bars.get_y()) low_bars.next_to(h_lines[2], UP, SMALL_BUFF) VGroup(top_bars, low_bars).shift(2 * LEFT) self.add(top_bars) self.add(low_bars) # Add labels # Repeated convolution self.flip_bar_group(low_bars) low_bars.save_state() for n in range(5): new_bars = self.show_convolution(top_bars, low_bars) self.wait() self.play( new_bars.animate.move_to(top_bars, DL).set_anim_args(path_arc=-120 * DEGREES), FadeOut(top_bars, UP), Restore(low_bars), ) # TODO, things with labels top_bars = new_bars def get_bar_group( self, dist, colors=(BLUE, TEAL), y_unit=4, bar_width=0.35, num_decimal_places=2, min_value=1, ): bars = self.get_bars(dist, colors, y_unit, bar_width) result = VGroup( bars, self.get_bar_value_labels(bars, min_value), self.get_bar_prob_labels(bars, dist, num_decimal_places), ) result.dist = dist return result def get_bars(self, dist, colors=(BLUE, TEAL), y_unit=4, bar_width=0.35): axes = Axes( (0, len(dist)), (0, 1), height=y_unit, width=bar_width * len(dist) ) bars = ChartBars(axes, dist, fill_opacity=0.75) bars.set_submobject_colors_by_gradient(*colors) return bars def get_bar_value_labels(self, bars, min_value=1): values = VGroup(*( Integer(x + min_value, font_size=16) for x in range(len(bars)) )) for bar, value in zip(bars, values): value.next_to(bar, DOWN, SMALL_BUFF) return values def get_bar_prob_labels(self, bars, dist, num_decimal_places=2): probs = VGroup(*( DecimalNumber(p, font_size=16, num_decimal_places=num_decimal_places) for p in dist )) for bar, prob in zip(bars, probs): prob.set_max_width(0.75 * bar.get_width()) prob.next_to(bar, UP, SMALL_BUFF) return probs def get_dist_label(self, indices): index_strs = [f"X_{{{i}}}" for i in indices] if len(indices) > 3: index_strs = [index_strs[0], R"\cdots", index_strs[-1]] sub_tex = "+".join(index_strs) return Tex(f"P_{{{sub_tex}}}") def flip_bar_group(self, bar_group): bars = bar_group[0] bars.target = bars.generate_target() bars.target.arrange(LEFT, buff=0, aligned_edge=DOWN) bars.target.align_to(bars[0], DR) self.play( MoveToTarget(bars, lag_ratio=0.05, path_arc=0.5), *( MaintainPositionRelativeTo( VGroup(value, prob), bar ) for bar, value, prob in zip(*bar_group) ), ) self.add(bar_group) def show_convolution(self, top_bars, low_bars): # New bars new_dist = np.convolve(top_bars.dist, low_bars.dist) new_bars = self.get_bar_group( new_dist, y_unit=8, num_decimal_places=3, min_value=top_bars[1][0].get_value() + low_bars[1][0].get_value(), ) new_bars.next_to(BOTTOM, UP) new_bars.align_to(top_bars, LEFT) # March! for n in range(len(new_bars[0])): x_diff = top_bars[0][0].get_x() - low_bars[0][0].get_x() x_diff += low_bars[0][0].get_width() * n self.play( low_bars.animate.shift(x_diff * RIGHT), run_time=0.5 ) index_pairs = [ (k, n - k) for k in range(n + 1) if 0 <= n - k < len(low_bars[0]) if 0 <= k < len(top_bars[0]) ] highlights = VGroup(*( VGroup(top_bars[0][i].copy(), low_bars[0][j].copy()) for i, j in index_pairs )) highlights.set_color(YELLOW) conv_rect, value_label, prob_label = (group[n] for group in new_bars) partial_rects = VGroup() partial_labels = VGroup() products = [top_bars.dist[i] * low_bars.dist[j] for i, j in index_pairs] for partial_value in np.cumsum(products): rect = conv_rect.copy() rect.stretch( partial_value / new_bars.dist[n], dim=1, about_edge=DOWN, ) label = prob_label.copy() label.set_value(partial_value) label.next_to(rect, UP, SMALL_BUFF) partial_rects.add(rect) partial_labels.add(label) self.add(value_label) self.play( ShowSubmobjectsOneByOne(highlights, remover=True), ShowSubmobjectsOneByOne(partial_rects, remover=True), ShowSubmobjectsOneByOne(partial_labels, remover=True), run_time=0.15 * len(products) ) self.add(*(group[:n + 1] for group in new_bars)) self.wait(0.5) return new_bars
from manim_imports_ext import * from _2023.convolutions2.continuous import * class Introduce3DGraph(InteractiveScene): plane_config = dict( x_range=(-2, 2), y_range=(-2, 2), width=6.0, height=6.0, ) plane_width = 6.0 z_axis_height = 2.0 plane_line_style = dict( stroke_color=GREY_C, stroke_width=1, stroke_opacity=1, ) graph_resolution = (101, 101) def construct(self): # Initial axes and graphs f_axes, g_axes = all_axes = VGroup(*( Axes((-2, 2), (0, 1, 0.5), width=5, height=2) for n in range(2) )) all_axes.arrange(DOWN, buff=1.5) all_axes.to_edge(LEFT) self.frame.move_to(all_axes) for char, axes in zip("xy", all_axes): axis_label = Tex(char, font_size=24) axis_label.next_to(axes.x_axis.get_right(), UP) axes.add(axis_label) f_graph = f_axes.get_graph(self.f, use_smoothing=False) f_graph.set_stroke(BLUE, 3) g_graph = g_axes.get_graph(self.g) g_graph.set_stroke(YELLOW, 3) f_label, g_label = func_labels = VGroup( Tex("f(x)", font_size=36), Tex("g(y)", font_size=36) ) for label, axes in zip(func_labels, all_axes): label.move_to(axes, UL) self.add(f_axes, f_graph, f_label) self.add(g_axes, g_graph, g_label) # Hook up trackers x_tracker = ValueTracker() y_tracker = ValueTracker() get_x = x_tracker.get_value get_y = y_tracker.get_value x_indicator, y_indicator = indicators = ArrowTip(90 * DEGREES).replicate(2) indicators.scale(0.5) indicators.set_fill(GREY_B) x_indicator.add_updater(lambda m: m.move_to(f_axes.c2p(get_x(), 0), UP)) y_indicator.add_updater(lambda m: m.move_to(g_axes.c2p(get_y(), 0), UP)) x_label, y_label = DecimalNumber(font_size=24).replicate(2) x_label.add_updater(lambda m: m.set_value(get_x()).next_to(x_indicator, DOWN, SMALL_BUFF).fix_in_frame()) y_label.add_updater(lambda m: m.set_value(get_y()).next_to(y_indicator, DOWN, SMALL_BUFF).fix_in_frame()) Axes.get_v_line_to_graph x_line = Line().set_stroke(WHITE, 1) y_line = Line().set_stroke(WHITE, 1) x_line.add_updater(lambda m: m.put_start_and_end_on( f_axes.c2p(get_x(), 0), f_axes.i2gp(get_x(), f_graph) )) y_line.add_updater(lambda m: m.put_start_and_end_on( g_axes.c2p(get_y(), 0), g_axes.i2gp(get_y(), g_graph) )) x_dot = GlowDot(color=BLUE) y_dot = GlowDot(color=YELLOW) x_dot.add_updater(lambda m: m.move_to(f_axes.i2gp(get_x(), f_graph))) y_dot.add_updater(lambda m: m.move_to(g_axes.i2gp(get_y(), g_graph))) # Ask about analog question = Text("What is analgous to this?") question.move_to(FRAME_WIDTH * RIGHT / 4) question.to_edge(UP) arrow = Vector(DOWN).next_to(question, DOWN) self.play( Write(question), GrowArrow(arrow), self.frame.animate.center().set_anim_args(run_time=2) ) self.wait() # Scan over inputs x_tracker.set_value(-2) y_tracker.set_value(-2) self.add(x_indicator, x_label, x_line, x_dot) self.add(y_indicator, y_label, y_line, y_dot) self.play(LaggedStart( x_tracker.animate.set_value(0.31), y_tracker.animate.set_value(0.41), run_time=5, lag_ratio=0.2, )) self.wait() # Show the xy-plane plane = self.get_plane() plane.to_edge(RIGHT) x_indicator2 = x_indicator.copy().clear_updaters() y_indicator2 = y_indicator.copy().clear_updaters() y_indicator2.rotate(-90 * DEGREES) VGroup(x_indicator2, y_indicator2).scale(0.8) x_indicator2.add_updater(lambda m: m.move_to(plane.c2p(get_x()), UP)) y_indicator2.add_updater(lambda m: m.move_to(plane.c2p(0, get_y()), RIGHT)) self.play( FadeOut(question, UP), Uncreate(arrow), TransformFromCopy(f_axes.x_axis, plane.x_axis), TransformFromCopy(g_axes.x_axis, plane.y_axis), TransformFromCopy(x_indicator, x_indicator2), TransformFromCopy(y_indicator, y_indicator2), TransformFromCopy(f_axes[-1], plane.axis_labels[0]), TransformFromCopy(g_axes[-1], plane.axis_labels[1]), ) self.play( Write(plane.background_lines, stroke_width=0.5, lag_ratio=0.01), Write(plane.faded_lines, stroke_width=0.5, lag_ratio=0.01), ) self.add(plane, x_indicator2, y_indicator2) # Add plane lines h_line = Line().set_stroke(BLUE, 1) v_line = Line().set_stroke(YELLOW, 1) h_line.add_updater(lambda l: l.put_start_and_end_on( plane.c2p(0, get_y()), plane.c2p(get_x(), get_y()) )) v_line.add_updater(lambda l: l.put_start_and_end_on( plane.c2p(get_x(), 0), plane.c2p(get_x(), get_y()) )) dot = GlowDot(color=GREEN) dot.add_updater(lambda m: m.move_to(plane.c2p(get_x(), get_y()))) xy_label = Tex("(x, y)", font_size=30) xy_label.add_updater(lambda m: m.next_to(dot, UR, buff=-SMALL_BUFF)) self.play(LaggedStart( VFadeIn(h_line), VFadeIn(v_line), FadeIn(dot), VFadeIn(xy_label), )) self.wait() self.play(x_tracker.animate.set_value(1), run_time=2) self.play(y_tracker.animate.set_value(0.9), run_time=2) self.play(x_tracker.animate.set_value(0.2), run_time=2) self.wait() # Note probability density at a single point rect = SurroundingRectangle(xy_label, buff=0.05) rect.set_stroke(TEAL, 1) label = TexText("Probability density = $f(x)g(y)$", font_size=36) label.next_to(rect, UP) label.set_backstroke() prob_word = label["Probability"] equals = label["="] prob_word.save_state() prob_word.next_to(equals, LEFT) self.play( FadeIn(rect), FadeIn(prob_word, lag_ratio=0.1), FadeIn(equals), ) self.wait() self.play( prob_word.animate.restore(), FadeIn(label["density"]) ) self.wait() self.play(LaggedStart( FadeTransform(f_label.copy(), label["f(x)"][0]), FadeTransform(g_label.copy(), label["g(y)"][0]), lag_ratio=0.3, run_time=2 )) self.add(label) self.play(FadeOut(rect)) self.wait() # Draw 3d graph to_fix = [ f_axes, f_graph, f_label, x_indicator, x_label, x_line, x_dot, g_axes, g_graph, g_label, y_indicator, y_label, y_line, y_dot, label, ] for mobject in to_fix: mobject.fix_in_frame() plane.set_flat_stroke(False) three_d_axes = self.get_three_d_axes(plane) surface = three_d_axes.get_graph( lambda x, y: self.f(x) * self.g(y), resolution=self.graph_resolution, ) self.play( FadeIn(surface), label.animate.set_x(FRAME_WIDTH / 4).to_edge(UP), self.frame.animate.reorient(-27, 78, 0).move_to([0.36, -0.62, 0.71]).set_height(5.66).set_anim_args(run_time=4), ) surface.always_sort_to_camera(self.camera) self.play( self.frame.animate.reorient(68, 77, 0).move_to([-0.13, -1.12, -0.27]).set_height(9.37), run_time=5, ) # Show two perspectives self.play( self.frame.animate.reorient(3, 83, 0).move_to([1.09, -0.82, -0.54]).set_height(6.91), run_time=4, ) self.wait() self.play( self.frame.animate.reorient(89, 95, 0).move_to([0.63, -2.19, 2.56]).set_height(9.41), run_time=4, ) self.wait() self.play( self.frame.animate.reorient(69, 75, 0).move_to([1.07, -1.37, -0.19]).set_height(7.64), run_time=5, ) def get_plane(self): plane = NumberPlane( **self.plane_config, background_line_style=self.plane_line_style, ) axis_labels = VGroup( Tex("x", font_size=24).next_to(plane.x_axis, RIGHT, SMALL_BUFF), Tex("y", font_size=24).next_to(plane.y_axis, UP, SMALL_BUFF), ) axis_labels.insert_n_curves(100) axis_labels.make_jagged() plane.axis_labels = axis_labels plane.add(*axis_labels) return plane def get_three_d_axes(self, plane): axes = ThreeDAxes( plane.x_range, plane.y_range, (0, 1), width=plane.x_axis.get_width(), height=plane.y_axis.get_height(), depth=self.z_axis_height ) axes.shift(plane.c2p(0, 0) - axes.c2p(0, 0, 0)) axes.z_axis.apply_depth_test() return axes def f(self, x): return wedge_func(x) def g(self, y): return double_lump(y) class DiagonalSlices(Introduce3DGraph): mesh_resolution = (21, 21) shadow_opacity = 0.25 add_shadow = True shadow_bump = 0.01 clip_plane_unit_coord = 0.45 def setup(self): super().setup() plane, axes = self.add_plane_and_axes() self.s_tracker = ValueTracker(-2 * plane.x_range[1]) get_s = self.s_tracker.get_value self.add_surface_group(axes, get_s) self.add_slice_graph(get_s) self.init_func_name() self.init_line_labels(get_s) self.add(self.func_name) def construct(self): # Get some nice local variables frame = self.camera.frame plane = self.plane axes = self.axes s_tracker = self.s_tracker slice_graph = self.slice_graph # Insert self.remove(self.equation) axes.z_axis.set_opacity(1) axes.z_axis.set_flat_stroke(True) frame.reorient(80, 70).move_to(ORIGIN), s_tracker.set_value(-5) self.play( frame.animate.reorient(40, 70).move_to(ORIGIN), run_time=20, ) # Initial orientation self.frame.reorient(88, 90, 0).move_to([-0.31, -2.14, 2.16]) self.play(frame.animate.reorient(40, 70).move_to(ORIGIN), run_time=10) self.play( s_tracker.animate.set_value(0.5), frame.animate.reorient(0, 0), VFadeIn(self.equation), FadeOut(axes.z_axis), run_time=6, ) self.wait() # Show x + y = s slice self.play( FadeIn(self.ses_label, 0.5 * DOWN), MoveAlongPath(GlowDot(), slice_graph, run_time=5, remover=True) ) self.wait() self.play( self.frame.animate.reorient(-22, 74, 0).move_to([-0.12, -0.16, 0.04]).set_height(5.45), run_time=3 ) self.wait() # Change s self.play( s_tracker.animate.set_value(1.5), self.frame.animate.reorient(-45, 75, 0).move_to([0.18, -0.14, 0.49]).set_height(3.0), run_time=6, ) self.play( s_tracker.animate.set_value(-2.0), self.frame.animate.reorient(-5, 66, 0).move_to([-0.03, -0.18, 0.14]).set_height(6.35), run_time=20, ) self.play( s_tracker.animate.set_value(2.0), self.frame.animate.reorient(16, 73, 0).move_to([-0.03, -0.18, 0.14]).set_height(6.35), run_time=15, ) def add_plane_and_axes(self): frame = self.camera.frame frame.reorient(20, 70) plane = self.plane = self.get_plane() plane.axes.set_stroke(GREY_B) plane.set_flat_stroke(False) plane.remove(plane.faded_lines) axes = self.axes = self.get_three_d_axes(plane) self.add(axes, axes.z_axis) self.add(plane) self.plane = plane self.axes = axes return plane, axes def add_surface_group(self, axes, get_s): # Surface surface = axes.get_graph( lambda x, y: self.f(x) * self.g(y), resolution=self.graph_resolution ) vect = axes.c2p(*2 * [self.clip_plane_unit_coord], 0) # Why? surface.add_updater(lambda m: m.set_clip_plane(vect, -get_s())) surface.always_sort_to_camera(self.camera) surface_mesh = SurfaceMesh(surface, resolution=self.mesh_resolution) surface_mesh.set_stroke(WHITE, width=1, opacity=0.1) surface_group = Group(surface, surface_mesh) # Add shadow if self.add_shadow: surface_shadow = surface.copy() surface_shadow.set_opacity(self.shadow_opacity) surface_shadow.shift(self.shadow_bump * IN) self.add(surface_shadow) surface_group.add(surface_shadow) self.surface_group = surface_group self.add(surface_group) return surface_group def add_slice_graph( self, get_s, stroke_color=WHITE, stroke_width=2, fill_color=TEAL_D, fill_opacity=0.5, dx=0.01 ): axes = self.axes def get_points(s): x_min, x_max = axes.x_range[:2] y_min, y_max = axes.y_range[:2] if s > 0: xs = np.arange(s - y_max, x_max, dx) else: xs = np.arange(x_min, s - y_min, dx) return axes.c2p(xs, s - xs, self.f(xs) * self.g(s - xs)) graph = VMobject() graph.set_flat_stroke(False) graph.set_stroke(stroke_color, stroke_width) graph.set_fill(fill_color, fill_opacity) graph.add_updater(lambda m: m.set_points_as_corners(get_points(get_s()))) self.add(graph) self.slice_graph = graph def init_func_name(self): self.func_name = Tex( R"f(x) \cdot g(y)", font_size=42, ) self.func_name.to_corner(UL, buff=0.25) self.func_name.fix_in_frame() return self.func_name def init_line_labels(self, get_s): equation = Tex("x + y = 0.00") s_label = equation.make_number_changable("0.00") s_label.add_updater(lambda m: m.set_value(get_s())) equation.to_corner(UR) equation.fix_in_frame() ses_label = Tex(R"\{(x, s - x): x \in \mathds{R}\}", tex_to_color_map={"s": YELLOW}, font_size=30) ses_label.next_to(equation, DOWN, MED_LARGE_BUFF, aligned_edge=RIGHT) ses_label.fix_in_frame() self.equation = equation self.ses_label = ses_label return equation, ses_label class SyncedSlices(DiagonalSlices): initial_s = 2 add_shadow = False def setup(self): super().setup() self.func_name.set_x(-3) self.func_name.align_to(self.equation, UP) self.s_tracker.set_value(self.initial_s) self.equation.set_x(2) self.add(self.equation) def construct(self): s_tracker = self.s_tracker self.play( s_tracker.animate.set_value(-1.5), self.frame.animate.reorient(-28, 77, 0).move_to([0.17, -0.28, 0.25]).set_height(5.29), run_time=20, ) self.play( s_tracker.animate.set_value(1.5), self.frame.animate.reorient(-10, 73, 0).move_to([0.15, -0.28, 0.22]).set_height(5.04), run_time=20, ) self.play( s_tracker.animate.set_value(-0.5), self.frame.animate.reorient(-39, 79, 0).move_to([0.15, -0.28, 0.21]).set_height(5.04), run_time=20, ) class SyncedSlicesExpAndRect(SyncedSlices): initial_s = -3.0 graph_resolution = (201, 201) add_shadow = True def construct(self): # Test s_tracker = self.s_tracker self.frame.reorient(-31, 68, 0).move_to([-1.51, 0.77, 0.22]).set_height(6.35) self.play( s_tracker.animate.set_value(1.0), self.frame.animate.reorient(-38, 72, 0).move_to([0.53, -0.5, 0.34]).set_height(6.75), run_time=15, ) self.play( s_tracker.animate.set_value(-1.5), self.frame.animate.reorient(-45, 80, 0).move_to([-1.75, 0.32, 0.2]).set_height(5.04), run_time=10, ) self.play( s_tracker.animate.set_value(-3.0), self.frame.animate.reorient(-28, 73, 0).move_to([-1.75, 0.32, 0.2]).set_height(5.04), run_time=10, ) self.play( s_tracker.animate.set_value(1.0), self.frame.animate.reorient(-39, 65, 0).move_to([0.35, -0.53, 0.06]).set_height(6.38), run_time=20, ) def f(self, x): return (x > -2) * np.exp(-2 - x) def g(self, x): return wedge_func(x) class CleanExpAndRect(SyncedSlicesExpAndRect): def construct(self): self.remove(self.equation, self.func_name) s_tracker = self.s_tracker s_tracker.set_value(-1.5) surface, mesh, surface_shadow = self.surface_group mesh.make_jagged() surface_shadow.set_opacity(0.5) self.remove(self.surface_group) self.add(surface, surface_shadow, mesh, self.slice_graph) class SyncedSlicesUniformAndWedge(SyncedSlices): initial_s = -2.0 graph_resolution = (201, 201) add_shadow = True def f(self, x): return uniform(x) def g(self, x): return wedge_func(x) class SyncedSlicesGaussian(SyncedSlices): add_shadow = True def construct(self): # Test self.func_name.set_x(0) self.equation.to_edge(RIGHT) s_tracker = self.s_tracker s_tracker.set_value(0) self.frame.reorient(0, 53, 0).move_to([0.05, 0.28, -0.23]).set_height(6.70) self.play( s_tracker.animate.set_value(-2.0), self.frame.animate.reorient(-38, 72, 0).move_to([0.53, -0.5, 0.34]).set_height(6.75), run_time=8, ) self.play( s_tracker.animate.set_value(1.5), self.frame.animate.reorient(-7, 61, 0).move_to([0.5, -0.06, 0.4]).set_height(3.85), run_time=10, ) self.play( s_tracker.animate.set_value(-1.5), self.frame.animate.reorient(-28, 73, 0).move_to([-0.06, -0.56, 0.26]).set_height(5.04), run_time=20, ) def f(self, x): return gauss_func(x, 0, 0.5) def g(self, x): return gauss_func(x, 0, 0.5) class AnalyzeStepAlongDiagonalLine(DiagonalSlices): initial_s = 0.5 dx = 1 / 8 def construct(self): # Setup s_tracker = self.s_tracker frame = self.frame surface, mesh, shadow = self.surface_group s_tracker.set_value(self.initial_s) frame.reorient(-27, 73, 0) self.slice_graph.update() self.slice_graph.clear_updaters() # Focus on line line = self.plane.get_graph(lambda x: self.initial_s - x) line.set_stroke(WHITE, 3) self.play( frame.animate.reorient(0, 0, 0).center().set_height(7), run_time=2 ) self.play( FadeOut(surface), FadeOut(mesh), FadeOut(shadow), FadeOut(self.slice_graph), FadeIn(line), ) self.wait() # Show small step segment = line.copy() segment.pointwise_become_partial(line, 12 * self.dx / 4, 13 * self.dx / 4) segment.set_stroke(YELLOW, 3) segment.rotate(45 * DEGREES).scale(3) brace = Brace(segment, DOWN, buff=SMALL_BUFF) center = segment.get_center() VGroup(brace, segment).scale(1 / 3, about_point=center).rotate(-45 * DEGREES, about_point=center) tex_kw = dict(font_size=12) step_word = Text("Step", **tex_kw) step_word.next_to(brace.get_center(), DL, SMALL_BUFF) step_word.shift(0.05 * UP) step_word.set_backstroke() dx_line = DashedLine(segment.get_corner(UL), segment.get_corner(UR), dash_length=0.01) dy_line = DashedLine(segment.get_corner(UR), segment.get_corner(DR), dash_length=0.01) dx_line.set_stroke(RED) dy_line.set_stroke(GREEN) dx_label = Tex(R"\Delta x", **tex_kw) dx_label.match_color(dx_line) dx_label.next_to(dx_line, UP, buff=0.05) dy_label = Tex(R"\Delta y", **tex_kw) dy_label.next_to(dy_line, RIGHT, buff=0.05) dy_label.match_color(dy_line) self.play( ShowCreation(segment), line.animate.set_stroke(width=1), GrowFromCenter(brace), Write(step_word), frame.animate.scale(0.3, about_point=1.5 * UL).set_anim_args(run_time=2), ) self.wait() self.play( ShowCreation(dx_line), ShowCreation(dy_line), FadeIn(dx_label), FadeIn(dy_label), ) self.wait() # Show equation rhs = Tex(R"= \sqrt{2} \cdot \Delta x", **tex_kw) rhs.move_to(step_word, RIGHT) rhs.set_backstroke() self.play( FadeTransform(dx_label.copy(), rhs[R"\Delta x"][0]), Write(rhs[R"= \sqrt{2} \cdot "]), step_word.animate.next_to(rhs, LEFT, buff=0.05).shift(0.025 * DOWN) ) self.wait() # Show graph again segment.set_flat_stroke(False) line.set_flat_stroke(False) self.add(surface, mesh) self.play( FadeIn(surface), FadeIn(mesh), FadeIn(self.slice_graph), FadeOut(self.equation), FadeOut(self.ses_label), FadeOut(self.func_name), self.frame.animate.reorient(-42, 79, 0).move_to([-0.15, 0.73, 1.18]).set_height(3.50), run_time=2, ) # Show riemann rectangles rects = VGroup() x_unit = self.plane.x_axis.get_unit_size() z_unit = self.axes.z_axis.get_unit_size() dx = self.dx for x in np.arange(-2, 2, dx): y = self.initial_s - x if not (-2 <= y <= 2): continue rect = Rectangle( width=math.sqrt(2) * x_unit * dx, height=self.f(x) * self.g(y) * z_unit ) rect.rotate(90 * DEGREES, RIGHT) rect.rotate(-45 * DEGREES, OUT) rect.shift(self.plane.c2p(x, y) - rect.get_corner([-1, 1, -1])) rects.add(rect) rects.set_fill(TEAL, 0.5) rects.set_stroke(WHITE, 1) rects.set_flat_stroke(False) self.play( Write(rects), self.slice_graph.animate.set_fill(opacity=0.1) ) self.add(rects) self.wait() class RotationalSymmetryOfGaussian(DiagonalSlices): plane_config = dict( x_range=(-3, 3), y_range=(-3, 3), width=8.0, height=8.0, ) mesh_resolution = (25, 25) clip_plane_unit_coord = 0.565 def construct(self): # Variables frame = self.frame axes = self.axes s_tracker = self.s_tracker surface_group = self.surface_group slice_graph = self.slice_graph # Add functions self.add_function_labels() # Show slices s_tracker.set_value(1) frame.reorient(-20, 69, 0).move_to(0.5 * OUT) self.play( frame.animate.reorient(20, 69, 0), s_tracker.animate.set_value(-6), run_time=8 ) # Emphasize rotational symmetry curve = VMobject() curve.set_stroke(TEAL, 3) dx = 0.05 xs = np.arange(*axes.x_range, dx) curve.set_points_smoothly(axes.c2p(xs, np.zeros(xs.size), self.f(xs))) curve.set_flat_stroke(False) curve.make_jagged() curve.apply_depth_test() curve.shift(0.025 * OUT) curves = VGroup(*( curve.copy().rotate(a, about_point=axes.c2p(0, 0, 0)) for a in np.linspace(0, PI, 25) )) curves.set_stroke(width=1, opacity=0.5) self.play(ShowCreation(curve)) self.play( Rotate(curve, PI, about_point=ORIGIN), ShowIncreasingSubsets(curves, rate_func=smooth), self.frame.animate.reorient(-20, 69, 0).center(), Rotate(surface_group, PI), run_time=7 ) self.play( FadeOut(curve, time_span=(0, 2)), FadeOut(curves, time_span=(0, 2)), ) self.wait() # Show r surface, mesh, ghost_surface = surface_group surface_group.generate_target() surface_group.target[0].set_opacity(0.25) self.play( MoveToTarget(surface_group), frame.animate.reorient(0, 0).set_height(10).move_to(1.5 * LEFT).set_field_of_view(1 * DEGREES), FadeOut(self.func_names), run_time=4, ) self.wait() # Explain meaning of r x, y = (1.5, 0.75) dot = Dot(axes.c2p(x, y), fill_color=RED) dot.set_stroke(WHITE, 0.5) coords = Tex("(x, y)", font_size=36) coords.set_backstroke(width=5) coords.next_to(dot, UR, SMALL_BUFF) coords.shift(0.1 * DOWN) x_line = Line(axes.get_origin(), axes.c2p(x, 0, 0)) y_line = Line(axes.c2p(x, 0, 0), axes.c2p(x, y, 0)) r_line = Line(axes.c2p(x, y, 0), axes.get_origin()) x_line.set_stroke(BLUE, 3) y_line.set_stroke(YELLOW, 3) r_line.set_stroke(RED, 3) lines = VGroup(x_line, y_line, r_line) labels = VGroup(*map(Tex, "xyr")) for label, line in zip(labels, lines): label.match_color(line) label.scale(0.85) label.next_to(line.get_center(), rotate_vector(line.get_vector(), -90 * DEGREES), SMALL_BUFF) self.add(dot, coords) self.play( FadeIn(dot, scale=0.5), FadeIn(coords), ) for line, label in zip(lines, labels): self.add(line, label, dot) self.play( ShowCreation(line), Write(label), ) def add_function_labels(self): kw = dict(t2c={"x": BLUE, "y": YELLOW}) func_names = VGroup( Tex("f(x) = e^{-x^2}", **kw), Tex("g(y) = e^{-y^2}", **kw), ) func_names.scale(0.75) func_names.arrange(DOWN, buff=MED_LARGE_BUFF) func_names.to_corner(UL) func_names.fix_in_frame() self.func_names = func_names self.remove(self.func_name) self.add(func_names) def f(self, x): return np.exp(-x**2) def g(self, x): return np.exp(-x**2) class RotateGaussianSlice(RotationalSymmetryOfGaussian): def construct(self): # Variables frame = self.frame axes = self.axes s_tracker = self.s_tracker surface_group = self.surface_group slice_graph = self.slice_graph self.add_function_labels() self.add(s_tracker) # Focus on one slice self.play( frame.animate.reorient(-20, 69, 0), run_time=5 ) self.play( s_tracker.animate.set_value(1), frame.animate.reorient(0, 55, 0), axes.z_axis.animate.set_opacity(0), run_time=6, ) self.remove(axes.z_axis) self.wait() for s in [1.5, 0.5, 1.0]: self.play(s_tracker.animate.set_value(s), run_time=2) self.wait() # Label two points s_tracker.set_value(1) s_color = RED s: float = s_tracker.get_value() dots = Group( GlowDot(axes.c2p(s, 0, 0), color=s_color), GlowDot(axes.c2p(0, s, 0), color=s_color), ) labels = VGroup() lines = VGroup() for dot, tex in zip(dots, ["(s, 0)", "(0, s)"]): label = Tex(tex, font_size=24) label.next_to(dot, DL, buff=-0.1) label.set_backstroke() labels.add(label) line = Line(axes.get_origin(), dot.get_center()) line.set_stroke(s_color, 2) lines.add(line) self.play(frame.animate.reorient(0, 25, 0).set_height(6).move_to(UP)) for dot, label, line in zip(dots, labels, lines): self.play( FadeInFromPoint(dot, line.get_start()), Write(label), ShowCreation(line), ) self.wait() # Straight line distance s_tracker.set_value(1) dist_line = Line(axes.get_origin(), axes.c2p(s / 2, s / 2, 0)) dist_line.set_stroke(s_color, 2) dist_label = Tex(R"s / \sqrt{2}", font_size=20) dist_label.next_to(dist_line.get_center(), RIGHT, buff=0.05) self.play( frame.animate.set_height(5).set_anim_args(run_time=4), LaggedStart( ShowCreation(dist_line), Write(dist_label), ), FadeOut(self.func_names, time_span=(2, 3)), ) self.wait() self.play(LaggedStartMap(FadeOut, Group(*dots, *lines, *labels))) self.wait() # Rotate surface, mesh, shadow = surface_group shadow.set_opacity(0) surface.clear_updaters() slice_graph.clear_updaters() clip_vect = VectorizedPoint(surface.uniforms["clip_plane"][:3]) globals().update(locals()) surface.add_updater(lambda m: m.set_clip_plane( clip_vect.get_center(), -s_tracker.get_value() )) self.play( Rotate(clip_vect, -45 * DEGREES, about_point=ORIGIN), Rotate(slice_graph, -45 * DEGREES, about_point=ORIGIN), Rotate(dist_line, -45 * DEGREES, about_point=ORIGIN), dist_label.animate.next_to( axes.c2p(s / 2 / math.sqrt(2), 0, 0), DOWN, SMALL_BUFF, ), run_time=3 ) # Ambient rotation self.play( frame.animate.reorient(-35, 59, 0).move_to([-0.0, 0.22, 0.4]).set_height(5.94), run_time=8, ) self.play( frame.animate.reorient(-8, 62, 0), run_time=15, ) self.play( self.frame.animate.reorient(-31, 54, 0), run_time=15, ) self.wait() class OscillatingGaussianSlice(RotationalSymmetryOfGaussian): def construct(self): # Variables frame = self.frame axes = self.axes s_tracker = self.s_tracker surface_group = self.surface_group slice_graph = self.slice_graph self.add(s_tracker) self.remove(self.func_name) self.add(self.equation) # Change value s_tracker.set_value(-3) frame.reorient(-20, 55, 0) frame.set_height(6) self.play( s_tracker.animate.set_value(3).set_anim_args(rate_func=there_and_back), frame.animate.reorient(20, 60, 0), run_time=24, ) self.play( s_tracker.animate.set_value(3).set_anim_args(rate_func=there_and_back), frame.animate.reorient(-20, 55, 0), run_time=24, ) class Thumbnail(RotationalSymmetryOfGaussian): def construct(self): # Variables frame = self.frame axes = self.axes s_tracker = self.s_tracker surface_group = self.surface_group slice_graph = self.slice_graph self.add(s_tracker) self.remove(self.func_name) self.remove(self.equation) s_tracker.set_value(0) frame.reorient(0, 47, 0) # Better surface surface, mesh, shadow = surface_group shadow.clear_updaters() shadow.set_clip_plane(ORIGIN, 00) shadow.set_opacity(0.5) self.add(shadow, surface, mesh, slice_graph) # Title title = TexText("It's about symmetry", font_size=90) title.to_edge(UP) title.fix_in_frame() self.add(title)
from manim_imports_ext import * from _2023.clt.main import * from _2022.convolutions.discrete import * import scipy.stats def wedge_func(x): return np.clip(-np.abs(x) + 1, 0, 1) def double_lump(x): return 0.45 * np.exp(-6 * (x - 0.5)**2) + np.exp(-6 * (x + 0.5)**2) def uniform(x): return 1.0 * (-0.5 < x) * (x < 0.5) def get_conv_graph(axes, f, g, dx=0.1): dx = 0.1 x_min, x_max = axes.x_range[:2] x_samples = np.arange(x_min, x_max + dx, dx) f_samples = np.array([f(x) for x in x_samples]) g_samples = np.array([g(x) for x in x_samples]) full_conv = np.convolve(f_samples, g_samples) x0 = len(x_samples) // 2 - 1 # TODO, be smarter about this conv_samples = full_conv[x0:x0 + len(x_samples)] conv_graph = VMobject() conv_graph.set_stroke(TEAL, 2) conv_graph.set_points_smoothly(axes.c2p(x_samples, conv_samples * dx)) return conv_graph class TransitionToContinuousProbability(InteractiveScene): def construct(self): # Setup axes and initial graph axes = Axes((0, 12), (0, 1, 0.2), width=14, height=5) axes.to_edge(LEFT, LARGE_BUFF) axes.to_edge(DOWN, buff=1.25) def pd(x): return (x**4) * np.exp(-x) / 8.0 graph = axes.get_graph(pd) graph.set_stroke(WHITE, 2) bars = axes.get_riemann_rectangles(graph, dx=1, x_range=(0, 6), input_sample_type="right") bars.set_stroke(WHITE, 3) y_label = Text("Probability", font_size=48) y_label.next_to(axes.y_axis, UP, SMALL_BUFF) y_label.shift_onto_screen() self.add(axes) self.add(y_label) self.add(*bars) self.frame.move_to(0.5 * DOWN) # Label as die probabilities dice = get_die_faces(fill_color=BLUE_E, dot_color=WHITE, stroke_width=1) dice.set_height(0.5) for bar, die in zip(bars, dice): die.next_to(bar, DOWN) self.play(FadeIn(dice, 0.1 * UP, lag_ratio=0.05, rate_func=overshoot)) self.wait() self.play(FadeOut(dice, RIGHT, rate_func=running_start, run_time=1, path_arc=-PI / 5, lag_ratio=0.01)) # Make continuous all_rects = VGroup(*( axes.get_riemann_rectangles( graph, x_range=(0, min(6 + n, 12)), dx=(1 / n), input_sample_type="right", ).set_stroke(WHITE, width=(2.0 / n), opacity=(2.0 / n), background=False) for n in (*range(1, 10), *range(10, 20, 2), *range(20, 100, 5)) )) area = all_rects[-1] area.set_stroke(width=0) self.remove(bars) self.play( ShowSubmobjectsOneByOne(all_rects, rate_func=bezier([0, 0, 0, 0, 1, 1])), FadeOut(y_label), run_time=5 ) self.remove(all_rects) self.add(area, graph) self.play(ShowCreation(graph)) self.wait() # Show continuous value x_tracker = ValueTracker(0) get_x = x_tracker.get_value tip = ArrowTip(angle=PI / 2) tip.set_height(0.25) tip.add_updater(lambda m: m.move_to(axes.c2p(get_x(), 0), UP)) x_label = DecimalNumber(font_size=36) x_label.add_updater(lambda m: m.set_value(get_x())) x_label.add_updater(lambda m: m.next_to(tip, DOWN, buff=0.2)) self.play(FadeIn(tip), FadeIn(x_label)) self.play(x_tracker.animate.set_value(12), run_time=6) # Labels x_labels = VGroup(*( Text(text) for text in [ "Temperature tomorrow at noon", "Value of XYZ next year", "Time before the next bus comes", ] )) for x_label in x_labels: x_label.next_to(axes.c2p(4, 0), DOWN, buff=0.2) self.play(Write(x_labels[0], run_time=1)) for xl1, xl2 in zip(x_labels, x_labels[1:]): self.wait() self.play( FadeOut(xl1, 0.5 * UP), FadeIn(xl2, 0.5 * UP), ) self.wait() self.play( FadeOut(x_labels[-1]), x_tracker.animate.set_value(0).set_anim_args(run_time=3), ) self.play( x_tracker.animate.set_value(12), run_time=5 ) self.remove(tip, x_label) # Label density density = Text("Probability density") density.match_height(y_label) density.move_to(y_label, LEFT) cross = Cross(y_label) cross.set_stroke(RED, width=(0, 8, 8, 8, 0)) self.play(FadeIn(y_label)) self.play(ShowCreation(cross)) self.wait() self.play( VGroup(y_label, cross).animate.shift(0.75 * UP), FadeIn(density), self.frame.animate.set_y(0), ) self.wait() # Interpretation range_tracker = ValueTracker([0, 12]) sub_area_opacity_tracker = ValueTracker(0) def get_subarea(): result = axes.get_area_under_graph( graph, range_tracker.get_value() ) result.set_stroke(width=0) result.set_fill(TEAL, sub_area_opacity_tracker.get_value()) return result sub_area = always_redraw(get_subarea) v_lines = Line(DOWN, UP).replicate(2) v_lines.set_stroke(GREY_A, 1) v_lines.set_height(FRAME_HEIGHT) def update_v_lines(v_lines): values = range_tracker.get_value() for value, line in zip(values, v_lines): line.move_to(axes.c2p(value, 0), DOWN) v_lines.add_updater(update_v_lines) bound_labels = Tex("ab") bound_labels[0].add_updater(lambda m: m.move_to(v_lines[0], DOWN).shift(0.5 * DOWN)) bound_labels[1].add_updater(lambda m: m.move_to(v_lines[1], DOWN).shift(0.5 * DOWN)) bound_labels.add_updater(lambda m: m.set_opacity(sub_area_opacity_tracker.get_value())) prob_label = Tex(R"P(a < x < b) = \text{This area}") prob_label.move_to(2 * UR) rhs = prob_label[R"\text{This area}"] prob_arrow = Arrow(LEFT, RIGHT) prob_arrow.add_updater(lambda m: m.put_start_and_end_on( rhs.get_bottom() + 0.1 * DOWN, sub_area.get_center(), )) self.add(area, sub_area, graph, bound_labels) self.play( area.animate.set_opacity(0.1), range_tracker.animate.set_value([3, 4.5]), sub_area_opacity_tracker.animate.set_value(1), VFadeIn(v_lines), FadeIn(prob_label), VFadeIn(prob_arrow), run_time=2, ) self.wait() for pair in [(5, 6), (1, 3), (2.5, 3), (4, 7)]: self.play(range_tracker.animate.set_value(pair), run_time=2) self.wait() # Name the pdf long_name = Text("probability\ndensity\nfunction", alignment="LEFT") short_name = Text("pdf") long_name.move_to(axes.c2p(1, 0.75), UL) short_name.move_to(axes.c2p(2, 0.5)) self.play(FadeIn(long_name, lag_ratio=0.1)) self.wait() self.play(TransformMatchingStrings(long_name, short_name, lag_ratio=0.01, run_time=1)) self.wait() # Show integral int_rhs = Tex(R"\int_a^b p_X(x) \, dx") int_rhs.move_to(rhs, LEFT) self.play( rhs.animate.set_opacity(0).shift(0.5 * DOWN + 1.0 * LEFT), FadeIn(int_rhs, DL) ) self.wait() # Ambient range changing for pair in [(2.5, 7), (8, 10), (3.5, 9), (3, 4.5)]: self.play(range_tracker.animate.set_value(pair), run_time=3) self.wait() class CompareFormulas(InteractiveScene): def construct(self): # Setup division v_line = Line(DOWN, UP).set_height(FRAME_HEIGHT) kw = dict(font_size=60) disc_title, cont_title = titles = VGroup( Text("Discrete case", **kw), Text("Continuous case", **kw), ) for vect, title in zip([LEFT, RIGHT], titles): title.move_to(vect * FRAME_WIDTH * 0.25) title.to_edge(UP, buff=MED_SMALL_BUFF) underline = Underline(title, stretch_factor=1.5) underline.set_stroke(GREY_B) title.add(underline) self.add(v_line, titles) # Discrete diagram (pre-made image) discrete_diagram = ImageMobject("/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2023/convolutions2/dice/DiscreteDistributionSum.png") discrete_diagram.set_height(5) discrete_diagram.match_x(disc_title) discrete_diagram.to_edge(DOWN, buff=0.5) self.add(discrete_diagram) # Continuous diagrams kw = dict(y_range=(0, 1, 0.5), width=5, height=1.5) all_axes = VGroup( Axes((-2, 2), **kw), Axes((-2, 2), **kw), Axes((-3, 3), **kw), ) all_axes[:2].arrange(RIGHT, buff=1.5) all_axes[2].set_width(10) all_axes[2].next_to(all_axes[:2], UP, buff=1.5) all_axes.set_width(FRAME_WIDTH * 0.5 - 0.5) all_axes.match_x(cont_title) all_axes.to_edge(DOWN, buff=0.75) graphs = VGroup( all_axes[0].get_graph( wedge_func, use_smoothing=False ).set_stroke(BLUE), all_axes[1].get_graph(double_lump).set_stroke(RED), get_conv_graph(all_axes[2], wedge_func, double_lump).set_stroke(TEAL) ) graphs.set_stroke(width=2) tex_kw = dict() labels = VGroup( Tex("f(x)", font_size=24), Tex("g(y)", font_size=24), Tex("[f * g](s)", font_size=36), ) for label, axes in zip(labels, all_axes): label.move_to(midpoint(axes.get_corner(UR), axes.get_top()), UP) plots = VGroup(*( VGroup(*tup) for tup in zip(all_axes, graphs, labels) )) self.add(plots) # Formulae disc_formula = Tex( R"\big[P_X * P_Y\big](s) = \sum_{x = 1}^N P_X(x) \cdot P_Y(s - x)", font_size=36, t2c={"X": BLUE, "Y": RED}, ) disc_formula.next_to(disc_title, DOWN, MED_LARGE_BUFF) cont_formula = Tex( R"\big[f * g \big](s) = \int_{-\infty}^\infty f(x) g(s - x) \, dx", font_size=36, ) cont_formula.match_x(cont_title) cont_formula.match_y(disc_formula) self.play( FadeIn(disc_formula, run_time=2, lag_ratio=0.1), FlashAround(disc_formula, time_width=1.5, run_time=2), ) self.wait() rect = SurroundingRectangle(disc_formula) rect.set_stroke(YELLOW, 2, opacity=0) target_rects = VGroup(*( SurroundingRectangle(disc_formula[s][0]) for s in ["P_X", "P_Y", "P_X * P_Y", re.compile(R"\\sum.*")] )) target_rects.set_stroke(YELLOW, 2) for target_rect in target_rects: self.play(rect.animate.become(target_rect), run_time=0.5) self.wait() self.play(FadeOut(rect)) self.play( TransformMatchingTex( disc_formula.copy(), cont_formula, lag_ratio=-0.001, path_arc=-0.1 * PI ) ) self.wait() # Out of context fade_rect = FullScreenFadeRectangle() randy = Randolph() randy.next_to(cont_formula, DL, LARGE_BUFF) self.add(fade_rect, cont_formula) self.play( FadeIn(fade_rect), VFadeIn(randy), randy.change("horrified", cont_formula), ) self.play(Blink(randy)) self.wait() self.play(randy.change("pondering", cont_formula)) self.play(Blink(randy)) self.wait() # Random samples from continuous distributions class RepeatedSamplesFromContinuousDistributions(InteractiveScene): sigma1 = 1.0 sigma2 = 1.0 graph_colors = [BLUE, RED, TEAL] graph_stroke_width = 2 dot_fade_factor = 0.25 def setup(self): super().setup() self.random_variables = self.get_random_variables() self.all_dots = Group() self.add(self.all_dots) def get_plots(self): # Axes and graphs all_axes = self.get_axes() left_axes = all_axes[:2] left_axes.arrange(DOWN, buff=1.5) left_axes.to_edge(LEFT) all_axes[2].center().to_edge(RIGHT) for axes in all_axes: axes.x_axis.add_numbers(font_size=16) axes.y_axis.set_stroke(opacity=0.5) pdfs = self.get_pdfs() graphs = VGroup(*( axes.get_graph(func).set_stroke(color) for axes, func, color in zip( all_axes, self.get_pdfs(), self.graph_colors ) )) graphs.add(self.get_sum_graph(all_axes[2])) graphs.set_stroke(width=self.graph_stroke_width) # Labels labels = self.get_axes_labels(all_axes) plots = VGroup(*( VGroup(*tup) for tup in zip(all_axes, graphs, labels) )) return plots def get_axes(self): return VGroup(*( Axes( (-5, 5), (0, 0.5, 0.25), width=5.5, height=2, ) for x in range(3) )) def get_axes_labels(self, all_axes): a1, a2, a3 = all_axes return VGroup( Tex("X").move_to(midpoint(a1.get_corner(UR), a1.get_top())), Tex("Y").move_to(midpoint(a2.get_corner(UR), a2.get_top())), Tex("X + Y").next_to(a3, UP, buff=1.0) ) def repeated_samples(self, plots, n_repetitions, **kwargs): for n in range(n_repetitions): self.animate_samples(plots, **kwargs) def animate_samples( self, plots, time_between_samples=0.25, time_before_fade=1.0, animate=True, ): # Setup xy_samples = np.round(self.get_samples(), 2) sample_sum = sum(xy_samples) samples = [*xy_samples[:2], sample_sum] dots = Group() labels = VGroup() lines = VGroup() for sample, plot in zip(samples, plots): axes, graph, sym_label = plot dot = GlowDot(axes.c2p(sample, 0)) label = DecimalNumber(sample) label.next_to(sym_label, DOWN) label.scale(0.75, about_edge=DOWN) label.set_fill(GREY_A) line = axes.get_v_line_to_graph(sample, graph, line_func=Line) line.set_stroke(YELLOW, 2) dots.add(dot) labels.add(label) lines.add(line) if len(plots) > 2: sum_label = VGroup( DecimalNumber(samples[0]), Tex("+") if samples[1] > 0 else Tex("-"), DecimalNumber(abs(samples[1])), Tex("="), DecimalNumber(samples[2]), ) sum_label.arrange(RIGHT, buff=0.15) sum_label[-1].align_to(sum_label[0], DOWN) sum_label.match_height(labels[2]) sum_label.match_style(labels[2]) sum_label.move_to(labels[2], DL) labels.remove(labels[2]) labels.add(sum_label) sum_label.shift((plots[2][2]["+"].get_x() - sum_label[1].get_x()) * RIGHT) # Animate for i in range(min(2, len(plots))): self.add(dots[i], labels[i], lines[i]) if len(plots) > 2: self.add(sum_label[:2 * i + 1]) self.wait(time_between_samples) if len(plots) > 2: self.play(LaggedStart( Transform(dots[0].copy(), dots[2].copy().set_opacity(0.5), remover=True), Transform(dots[1].copy(), dots[2].copy().set_opacity(0.5), remover=True), FadeTransform(sum_label[:3].copy(), sum_label[3:]), run_time=1.0 if animate else 0, )) self.add(sum_label) self.add(dots[2]) self.wait(time_before_fade) kw = dict(run_time=0.25 if animate else 0) self.play( LaggedStart(*( dot.animate.set_radius(0.1).set_opacity(self.dot_fade_factor) for dot in dots ), **kw), LaggedStartMap(FadeOut, labels, **kw), LaggedStartMap(FadeOut, lines[:2], **kw), ) self.all_dots.add(*dots) self.add(self.all_dots) def get_random_variables(self): return [ scipy.stats.norm(0, self.sigma1), scipy.stats.norm(0, self.sigma2), ] def get_samples(self): return [ np.round(var.rvs(), 2) for var in self.random_variables ] def get_pdfs(self): return [var.pdf for var in self.random_variables] def get_sum_graph(self, axes): graph = get_conv_graph(axes, *self.get_pdfs()) graph.set_stroke(self.graph_colors[2]) return graph class SampleTwoNormals(RepeatedSamplesFromContinuousDistributions): random_seed = 1 sigma1 = 1 sigma2 = 1.5 annotations = False def construct(self): # Setup plots plots = self.get_plots() plots.to_edge(UP, buff=1.0) sum_axes, sum_graph, sum_label = plots[2] sum_axes.y_axis.set_opacity(0) sum_graph.set_opacity(0) sum_label.shift(DOWN) normal_parameters = VGroup(*( self.get_normal_parameter_labels(plot, 0, sigma) for plot, sigma in zip(plots, [self.sigma1, self.sigma2]) )) normal_words = VGroup(*( Text("Normal\ndistribution", font_size=30, alignment="LEFT").next_to( parameters, UP, MED_LARGE_BUFF, LEFT ) for parameters in normal_parameters )) if self.annotations: plots.set_opacity(0) # Repeated samples of X frame = self.frame frame.move_to(plots[0]) frame.set_height(plots[0].get_height() + 2) self.add(plots[0]) if self.annotations: # Describe X axes, graph, label = plots[0] label_rect = SurroundingRectangle(label, buff=0.05) label_rect.set_stroke(YELLOW, 2) sample_point = label.get_center() + label.get_height() * DOWN rv_words = Text("Random variable", font_size=24) rv_words.next_to(label, UR, buff=0.5) rv_arrow = Arrow(rv_words, label, buff=0.2, stroke_color=YELLOW) sample_words = Text("Samples", font_size=24) sample_words.next_to(sample_point, DOWN, LARGE_BUFF) sample_words.match_x(rv_words) sample_arrow = Arrow(sample_words, sample_point + 0.25 * DR, buff=0.2) sample_arrow.set_stroke(BLUE) self.play( FadeIn(rv_words, lag_ratio=0.1), ShowCreation(label_rect), GrowArrow(rv_arrow), ) self.wait() self.play( FadeTransform(rv_words.copy(), sample_words), TransformFromCopy(rv_arrow, sample_arrow), FadeOut(label_rect), ) self.wait() # Describe normal distribution curve_copy = graph.copy() curve_copy.set_stroke(TEAL, 7, 1) self.play( LaggedStartMap(FadeOut, VGroup( sample_words, sample_arrow, rv_arrow, rv_words, )), Write(normal_words[0], run_time=2), FadeIn(normal_parameters[0]), VShowPassingFlash(curve_copy, time_width=0.7, time_span=(0.5, 5)), ) self.wait() # Show area bound_tracker = ValueTracker([-1, -1]) area = always_redraw(lambda: axes.get_area_under_graph( graph, bound_tracker.get_value() )) self.add(area) self.play( bound_tracker.animate.set_value([-1, 2]), run_time=3 ) self.wait() self.play(FadeOut(area)) else: self.repeated_samples(plots[:1], 30, time_before_fade=0.5) # Show Y frame.generate_target() frame.target.set_height(plots[:2].get_height() + 2) frame.target.move_to(plots[:2]) self.play( MoveToTarget(frame), FadeIn(plots[1]), FadeOut(self.all_dots), ) self.all_dots.clear() if self.annotations: self.play(TransformFromCopy(*normal_words)) self.play( LaggedStartMap(FadeIn, normal_parameters[1], lag_ratio=0.25), LaggedStartMap( FlashAround, normal_parameters[1], stroke_width=1, time_width=1.0, lag_ratio=0.25, ), ) self.wait() else: self.repeated_samples(plots[:2], 10, time_before_fade=0.5) # Show sum self.play( frame.animate.to_default_state(), FadeIn(plots[2]), FadeOut(self.all_dots), ) self.all_dots.clear() if self.annotations: # Show multiple graphs axes, graph, label = plots[2] graphs = VGroup( graph.copy(), axes.get_graph(lambda x: 0.3 * np.exp(-0.1 * x**4)), axes.get_graph(lambda x: 0.3 * (1 / (1 + x**2))), ) graphs.set_stroke(TEAL, 2, 1) kw = dict(font_size=24) words = [ Text("Another\nnormal?", **kw), Text("Something\nnew?", **kw), Text("Maybe this?", **kw), ] for word in words: word.move_to(axes) word.align_to(axes.x_axis.get_start(), LEFT) curr_graph = graphs[0].copy() self.play( ShowCreation(curr_graph), FadeIn(words[0], 0.5 * UP), ) self.wait() for i in range(2): self.play( FadeOut(words[i], 0.5 * UP), FadeIn(words[i + 1], 0.5 * UP), Transform(curr_graph, graphs[i + 1]) ) self.wait() self.wait() self.play( FadeOut(words[-1]), Transform(curr_graph, graphs[0]) ) self.wait() self.play(FadeOut(curr_graph, run_time=3)) else: self.repeated_samples( plots, 10, time_between_samples=0.25, time_before_fade=1.0, ) # More! Faster! self.repeated_samples( plots[:3], 100, time_between_samples=1 / 30, time_before_fade=0.2, animate=False ) def get_normal_parameter_labels(self, plot, mean, sigma, font_size=18, color=GREY_A): kw = dict(font_size=font_size) labels = VGroup( Tex(R"\text{Mean} = 0.0", **kw), Tex(R"\text{Std. Dev.} = 0.0", **kw), ) for label, value in zip(labels, [mean, sigma]): number = label.make_number_changable("0.0") number.set_value(value) labels.arrange(DOWN, aligned_edge=LEFT) labels.move_to(plot, LEFT) labels.shift(0.1 * plot.get_height() * DOWN) labels.align_to(plot[0].x_axis.get_start(), LEFT) labels.set_color(color) return labels def get_sum_graph(self, axes): # Todo, it would be better to directly convolve the first # two graphs var = scipy.stats.norm(0, np.sqrt(self.sigma1**2 + self.sigma2**2)) return axes.get_graph(var.pdf, color=self.graph_colors[2]) class IntroAnnotations(SampleTwoNormals): annotations = True class AddTwoGammaDistributions(RepeatedSamplesFromContinuousDistributions): dot_fade_factor = 0.75 def construct(self): # Plots plots = self.get_plots() self.add(plots) # Add graph labels kw = dict(font_size=30) graph_labels = VGroup( Tex("e^{-x}", **kw), Tex(R"\frac{1}{2} x^2 \cdot e^{-x}", **kw), Tex(R"\frac{1}{6} x^3 \cdot e^{-x}", **kw), ) for plot, label, x in zip(plots, graph_labels, [1, 2, 3]): axes, graph, var_label = plot label.next_to(axes.i2gp(x, graph), UP, SMALL_BUFF) label.match_color(graph) graph_labels[0].shift(0.3 * UR) self.add(graph_labels) # Initial samples self.repeated_samples( plots, 40, animate=False, time_between_samples=0.1, time_before_fade=0.5 ) # Graph equation frame = self.frame fs_rect = FullScreenRectangle() fs_rect.set_stroke(GREY_B, 1) fs_rect.set_fill(BLACK, 1) fuller_rect = FullScreenRectangle() fuller_rect.set_fill(GREY_E, 1) fuller_rect.scale(3) self.add(fuller_rect, fs_rect, *self.mobjects) graph_groups = VGroup(*( VGroup(plot[1], label).copy() for plot, label in zip(plots, graph_labels) )) graph_groups.generate_target() for graph_group in graph_groups.target: graph_group[0].stretch(0.5, 0, about_edge=LEFT) graph_group[0].set_stroke(width=4) graph_group[1].shift(SMALL_BUFF * UP) kw = dict(font_size=96) lp, rp = parens = Tex("()", **kw) parens.stretch(1.5, 1) parens.match_height(graph_groups.target[0]) equation = VGroup( lp.copy(), graph_groups.target[0], rp.copy(), Tex("*", **kw), lp.copy(), graph_groups.target[1], rp.copy(), Tex("=", **kw), graph_groups.target[2], ) equation.arrange(RIGHT, buff=0.5) equation[:3].space_out_submobjects(0.9) equation[4:7].space_out_submobjects(0.9) equation.next_to(plots, UP, buff=1.5) symbols = VGroup(*( mob for mob in equation if mob not in graph_groups.target )) self.play( frame.animate.set_height(13, about_point = 3 * DOWN), FadeIn(fuller_rect), FadeIn(fs_rect), MoveToTarget(graph_groups, run_time=2), Write(symbols, run_time=2), ) self.wait() # Label convolution conv_label = Text("Convolution", font_size=72) arrow = Vector(DOWN) arrow.next_to(equation[3], UP) conv_label.next_to(arrow, UP) VGroup(conv_label, arrow).set_color(YELLOW) self.play(Write(conv_label), GrowArrow(arrow)) # More repeated samples self.repeated_samples( plots, 50, animate=False, time_between_samples=0.1, time_before_fade=0.5 ) def get_axes(self): kw = dict(width=5.5, height=2,) return VGroup( Axes((0, 10), (0, 1.0, 0.25), **kw), Axes((0, 10), (0, 0.5, 0.25), **kw), Axes((0, 10), (0, 0.5, 0.25), **kw), ) def get_random_variables(self): return [ scipy.stats.gamma(1), scipy.stats.gamma(3), ] def get_sum_graph(self, axes): var = scipy.stats.gamma(4) return axes.get_graph( var.pdf, color=self.graph_colors[2] ) class SampleWedgePlusDoubleLump(RepeatedSamplesFromContinuousDistributions): def construct(self): # Plots plots = self.get_plots() plots[0][1].make_jagged() self.add(plots) # Initial samples self.repeated_samples( plots, 50, animate=False, time_between_samples=0.1, time_before_fade=0.5 ) def get_axes(self): return VGroup(*( Axes( (-2, 2), (0, 1, 0.25), width=5.5, height=2.5, ) for x in range(3) )) def get_samples(self): x1 = sum(np.random.uniform(-0.5, 0.5, 2)) # Hack x2 = np.random.normal(0, 0.5) x2 += (0.5 if random.random() < 0.3 else -0.5) return [x1, x2] def get_pdfs(self): return [wedge_func, double_lump] class ContinuousSampleAnnotations(SampleWedgePlusDoubleLump): def construct(self): plots = self.get_plots() plots[0][1].make_jagged() # self.add(plots) thick_graphs = VGroup(*( plot[1].copy().set_stroke(width=10) for plot in plots )) # Labels func_labels = VGroup(Tex("f(x)"), Tex("g(y)")) func_labels.scale(0.75) for graph, label in zip(thick_graphs, func_labels): label.next_to(graph.pfp(0.4), LEFT) self.play( Write(label, time_span=(1, 2)), VShowPassingFlash(graph, time_width=1.5, run_time=3), ) # Question question = Text("What is this?") question.move_to(plots[2][0].get_corner(UL)).shift(0.5 * RIGHT) question.set_color(TEAL_A) arrow = Arrow(question.get_bottom(), plots[2][1].pfp(0.25), buff=0.2) arrow.set_color(TEAL_A) self.play(FadeIn(question), GrowArrow(arrow)) self.wait() class UniformSamples(RepeatedSamplesFromContinuousDistributions): def construct(self): # Plots plots = self.get_plots() funcs = [uniform, uniform, wedge_func] for plot, func in zip(plots, funcs): axes, graph, label = plot axes.y_axis.add_numbers( np.arange(0.5, 2.5, 0.5), font_size=12, buff=0.15, num_decimal_places=1, ) new_graph = axes.get_graph( func, x_range=(-2, 2, 0.01), use_smoothing=False ) new_graph.match_style(graph) graph.match_points(new_graph) plots[2][1].set_opacity(0) plots[2][0].y_axis.set_opacity(0) self.add(plots) # Samples self.repeated_samples( plots, 50, animate=False, time_between_samples=0.1, time_before_fade=0.5 ) def get_axes(self): return VGroup(*( Axes( (-2, 2), (0, 2, 0.5), width=5.5, height=2, ) for x in range(3) )) def get_samples(self): return np.random.uniform(-0.5, 0.5, 2) def get_pdfs(self): return [uniform, uniform] class WedgeAndExpSamples(SampleWedgePlusDoubleLump): def get_axes(self): return VGroup( Axes( (-2, 2), (0, 1, 0.25), width=5.5, height=2, ), Axes( (-2, 5), (0, 1.0, 0.25), width=5.5, height=2, ), Axes( (-3, 6), (0, 1.0, 0.25), width=5.5, height=2, ), ) def get_random_variables(self): return [ scipy.stats.gamma(1), scipy.stats.gamma(3), ] def get_samples(self): wedge_sum = np.random.uniform(-0.5, 0.5, 2).sum() exp_value = np.clip(self.random_variables[0].rvs() - 2, -2, 5) return [wedge_sum, exp_value] def get_pdfs(self): return [wedge_func, lambda x: self.random_variables[0].pdf(x + 2)] # Sliding window view of convolutions class Convolutions(InteractiveScene): axes_config = dict( x_range=(-3, 3, 1), y_range=(-1, 1, 1.0), width=6, height=2, ) f_graph_style = dict(stroke_color=BLUE, stroke_width=2) g_graph_style = dict(stroke_color=YELLOW, stroke_width=2) fg_graph_style = dict(stroke_color=GREEN, stroke_width=4) conv_graph_style = dict(stroke_color=TEAL, stroke_width=2) f_graph_x_step = 0.1 g_graph_x_step = 0.1 f_label_tex = "f(x)" g_label_tex = "g(s - x)" fg_label_tex = R"f(x) \cdot g(s - x)" conv_label_tex = R"[f * g](s) = \int_{-\infty}^\infty f(x) \cdot g(s - x) dx" label_config = dict(font_size=36) t_color = TEAL area_line_dx = 0.05 jagged_product = True jagged_convolution = True g_is_rect = False conv_y_stretch_factor = 2.0 def setup(self): super().setup() if self.g_is_rect: k1_tracker = self.k1_tracker = ValueTracker(1) k2_tracker = self.k2_tracker = ValueTracker(1) # Add axes all_axes = self.all_axes = self.get_all_axes() f_axes, g_axes, fg_axes, conv_axes = all_axes x_min, x_max = self.axes_config["x_range"][:2] self.disable_interaction(*all_axes) self.add(*all_axes) # Add f(x) f_graph = self.f_graph = f_axes.get_graph(self.f, x_range=(x_min, x_max, self.f_graph_x_step)) f_graph.set_style(**self.f_graph_style) f_label = self.f_label = self.get_label(self.f_label_tex, f_axes) if self.jagged_product: f_graph.make_jagged() self.add(f_graph) self.add(f_label) # Add g(s - x) self.toggle_selection_mode() # So triangle is highlighted s_indicator = self.s_indicator = ArrowTip().rotate(90 * DEGREES) s_indicator.set_height(0.15) s_indicator.set_fill(self.t_color, 0.8) s_indicator.move_to(g_axes.get_origin(), UP) s_indicator.add_updater(lambda m: m.align_to(g_axes.get_origin(), UP)) def get_s(): return g_axes.x_axis.p2n(s_indicator.get_center()) self.get_s = get_s g_graph = self.g_graph = g_axes.get_graph(lambda x: 0, x_range=(x_min, x_max, self.g_graph_x_step)) g_graph.set_style(**self.g_graph_style) if self.g_is_rect: x_min = g_axes.x_axis.x_min x_max = g_axes.x_axis.x_max g_graph.add_updater(lambda m: m.set_points_as_corners([ g_axes.c2p(x, y) for s in [get_s()] for k1 in [k1_tracker.get_value()] for k2 in [k2_tracker.get_value()] for x, y in [ (x_min, 0), (-0.5 / k1 + s, 0), (-0.5 / k1 + s, k2), (0.5 / k1 + s, k2), (0.5 / k1 + s, 0), (x_max, 0) ] ])) else: g_axes.bind_graph_to_func(g_graph, lambda x: self.g(get_s() - x), jagged=self.jagged_product) g_label = self.g_label = self.get_label(self.g_label_tex, g_axes) s_label = self.s_label = VGroup(*Tex("s = "), DecimalNumber()) s_label.arrange(RIGHT, buff=SMALL_BUFF) s_label.scale(0.5) s_label.set_backstroke(width=8) s_label.add_updater(lambda m: m.next_to(s_indicator, DOWN, buff=0.15)) s_label.add_updater(lambda m: m[-1].set_value(get_s())) self.add(g_graph) self.add(g_label) self.add(s_indicator) self.add(s_label) # Show integral of f(x) * g(s - x) def prod_func(x): k1 = self.k1_tracker.get_value() if self.g_is_rect else 1 k2 = self.k2_tracker.get_value() if self.g_is_rect else 1 return self.f(x) * self.g((get_s() - x) * k1) * k2 fg_graph = fg_axes.get_graph(lambda x: 0, x_range=(x_min, x_max, self.g_graph_x_step)) pos_graph = fg_graph.copy() neg_graph = fg_graph.copy() for graph in f_graph, g_graph, fg_graph, pos_graph, neg_graph: self.disable_interaction(graph) fg_graph.set_style(**self.fg_graph_style) VGroup(pos_graph, neg_graph).set_stroke(width=0) pos_graph.set_fill(BLUE, 0.5) neg_graph.set_fill(RED, 0.5) get_discontinuities = None if self.g_is_rect: def get_discontinuities(): k1 = self.k1_tracker.get_value() return [get_s() - 0.5 / k1, get_s() + 0.5 / k1] kw = dict( jagged=self.jagged_product, get_discontinuities=get_discontinuities, ) fg_axes.bind_graph_to_func(fg_graph, prod_func, **kw) fg_axes.bind_graph_to_func(pos_graph, lambda x: np.clip(prod_func(x), 0, np.inf), **kw) fg_axes.bind_graph_to_func(neg_graph, lambda x: np.clip(prod_func(x), -np.inf, 0), **kw) self.prod_graphs = VGroup(fg_graph, pos_graph, neg_graph) fg_label = self.fg_label = self.get_label(self.fg_label_tex, fg_axes) self.add(pos_graph, neg_graph, fg_axes, fg_graph) self.add(fg_label) # Show convolution conv_graph = self.conv_graph = self.get_conv_graph(conv_axes) if self.jagged_convolution: conv_graph.make_jagged() conv_graph.set_style(**self.conv_graph_style) graph_dot = self.graph_dot = GlowDot(color=WHITE) graph_dot.add_updater(lambda d: d.move_to(conv_graph.quick_point_from_proportion( inverse_interpolate(x_min, x_max, get_s()) ))) graph_line = self.graph_line = Line(stroke_color=WHITE, stroke_width=1) graph_line.add_updater(lambda l: l.put_start_and_end_on( graph_dot.get_center(), [graph_dot.get_x(), conv_axes.get_y(), 0], )) self.conv_graph_dot = graph_dot self.conv_graph_line = graph_line conv_label = self.conv_label = Tex(self.conv_label_tex, **self.label_config) conv_label.match_x(conv_axes) conv_label.set_y(np.mean([conv_axes.get_y(UP), FRAME_HEIGHT / 2])) self.add(conv_graph) self.add(graph_dot) self.add(graph_line) self.add(conv_label) def get_all_axes(self): all_axes = VGroup(*(Axes(**self.axes_config) for x in range(4))) all_axes[:3].arrange(DOWN, buff=0.75) all_axes[3].next_to(all_axes[:3], RIGHT, buff=1.5) all_axes[3].y_axis.stretch( self.conv_y_stretch_factor, 1 ) all_axes.to_edge(LEFT) all_axes.to_edge(DOWN, buff=0.1) for i, axes in enumerate(all_axes): x_label = Tex("x" if i < 3 else "s", font_size=24) x_label.next_to(axes.x_axis.get_right(), UP, MED_SMALL_BUFF) axes.x_label = x_label axes.x_axis.add(x_label) axes.y_axis.ticks.set_opacity(0) axes.x_axis.ticks.stretch(0.5, 1) return all_axes def get_label(self, tex, axes): label = Tex(tex, **self.label_config) label.move_to(midpoint(axes.get_origin(), axes.get_right())) label.match_y(axes.get_top()) return label def get_conv_graph(self, conv_axes): return get_conv_graph(conv_axes, self.f, self.g) def get_conv_s_indicator(self): g_s_indicator = VGroup(self.s_indicator, self.s_label) f_axes, g_axes, fg_axes, conv_axes = self.all_axes def get_s(): return g_axes.x_axis.p2n(self.s_indicator.get_x()) conv_s_indicator = g_s_indicator.copy() conv_s_indicator.add_updater(lambda m: m.become(g_s_indicator)) conv_s_indicator.add_updater(lambda m: m.shift( conv_axes.c2p(get_s(), 0) - g_axes.c2p(get_s(), 0) )) return conv_s_indicator def f(self, x): return 0.5 * np.exp(-0.8 * x**2) * (0.5 * x**3 - 3 * x + 1) def g(self, x): return np.exp(-x**2) * np.sin(2 * x) class ProbConvolutions(Convolutions): jagged_product = True def construct(self): # Hit most of previous setup f_axes, g_axes, fg_axes, conv_axes = self.all_axes f_graph, g_graph, prod_graphs, conv_graph = self.f_graph, self.g_graph, self.prod_graphs, self.conv_graph f_label, g_label, fg_label, conv_label = self.f_label, self.g_label, self.fg_label, self.conv_label s_indicator = self.s_indicator s_label = self.s_label self.remove(s_indicator, s_label) f_axes.x_axis.add_numbers(font_size=16, buff=0.1, excluding=[0]) self.remove(f_axes, f_graph, f_label) y_label = Tex("y").replace(g_axes.x_label) g_label.shift(0.2 * UP) gy_label = Tex("g(y)", **self.label_config).replace(g_label, dim_to_match=1) gmx_label = Tex("g(-x)", **self.label_config).replace(g_label, dim_to_match=1) g_axes.x_label.set_opacity(0) self.remove(g_axes, g_graph, g_label) alt_fg_label = Tex(R"p_X(x) \cdot g(-x)", **self.label_config) alt_fg_label.move_to(fg_label) conv_label.shift_onto_screen() sum_label = Tex("[f * g](s)", **self.label_config) sum_label.move_to(conv_label) self.remove(fg_axes, prod_graphs, fg_label) conv_cover = SurroundingRectangle(conv_axes, buff=0.25) conv_cover.set_stroke(width=0) conv_cover.set_fill(BLACK, 0.5) self.add(conv_cover) # Show f f_term = conv_label["f(x)"][0] f_rect = SurroundingRectangle(f_term) f_rect.set_stroke(YELLOW, 2) self.play(ShowCreation(f_rect)) self.play( TransformFromCopy(f_term, f_label), FadeIn(f_axes), ) self.play( ShowCreation(f_graph), VShowPassingFlash(f_graph.copy().set_stroke(width=5)), run_time=2 ) self.wait() # Show g true_g_graph = g_axes.get_graph(self.g) true_g_graph.match_style(g_graph) g_term = conv_label["g"][1] g_rect = SurroundingRectangle(g_term, buff=0.05) g_rect.match_style(f_rect) self.play(ReplacementTransform(f_rect, g_rect)) self.play( TransformFromCopy(g_term, gy_label), FadeIn(g_axes), FadeIn(y_label), ) self.play( ShowCreation(true_g_graph), VShowPassingFlash(true_g_graph.copy().set_stroke(width=5)), run_time=2 ) self.wait() # Range over pairs of values int_rect = SurroundingRectangle(conv_label[re.compile(R"\\int.*")]) x_rects = VGroup(*( SurroundingRectangle(x, buff=0.05) for x in conv_label["x"] )) VGroup(int_rect, *x_rects).match_style(g_rect) const_sum = 0.3 x_tracker = ValueTracker(-1.0) y_tracker = ValueTracker() x_term = DecimalNumber(include_sign=True, edge_to_fix=RIGHT) y_term = DecimalNumber(include_sign=True) s_term = DecimalNumber(const_sum) equation = VGroup(x_term, y_term, Tex("="), s_term) VGroup(x_term, s_term).shift(0.05 * RIGHT) equation.arrange(RIGHT, buff=SMALL_BUFF) equation.match_x(conv_label) x_brace, y_brace, s_brace = braces = VGroup(*( Brace(term, UP, SMALL_BUFF) for term in [x_term, y_term, s_term] )) x_brace.add(x_brace.get_tex("x").set_color(BLUE)) y_brace.add(y_brace.get_tex("y").set_color(YELLOW)) s_brace.add(s_brace.get_tex("s").set_color(GREY_B)) y_brace[-1].align_to(x_brace[-1], UP) alt_y_label = Tex("s - x") alt_y_label.space_out_submobjects(0.8) alt_y_label.move_to(y_brace[-1], UP) alt_y_label.set_color_by_tex_to_color_map({"s": GREY_B, "x": BLUE}) def get_x(): return x_tracker.get_value() def get_y(): return const_sum - get_x() f_always(y_tracker.set_value, get_y) f_always(x_term.set_value, get_x) f_always(y_term.set_value, get_y) Axes.get_v_line_to_graph x_line = always_redraw(lambda: f_axes.get_v_line_to_graph( get_x(), f_graph, line_func=Line, color=WHITE )) y_line = always_redraw(lambda: g_axes.get_v_line_to_graph( get_y(), true_g_graph, line_func=Line, color=WHITE )) x_dot = GlowDot(color=BLUE) y_dot = GlowDot(color=YELLOW) f_always(x_dot.move_to, x_line.get_end) f_always(y_dot.move_to, y_line.get_end) self.play(ReplacementTransform(g_rect, int_rect)) self.wait() self.play(LaggedStart( conv_cover.animate.set_opacity(1), FadeIn(equation), FadeIn(braces), VFadeIn(x_line), VFadeIn(y_line), FadeIn(x_dot), FadeIn(y_dot), )) for x in [1.0, -1.0]: self.play(x_tracker.animate.set_value(x), run_time=8) self.wait() self.remove(int_rect) self.play(*( ReplacementTransform(int_rect.copy(), x_rect) for x_rect in x_rects )) self.wait() self.play(FadeOut(x_rects, lag_ratio=0.5)) self.play( FadeTransform(conv_label["s - x"].copy(), alt_y_label), y_brace[-1].animate.set_opacity(0) ) self.remove(alt_y_label) y_brace[-1].become(alt_y_label) for x in [1.0, -1.0]: self.play(x_tracker.animate.set_value(x), run_time=8) self.play(LaggedStart(*map(FadeOut, [ x_line, x_dot, y_line, y_dot, *equation, *braces ])), lag_ratio=0.2) # Flip g gsmx_rect = SurroundingRectangle(conv_label["g(s - x)"], buff=0.05) gsmx_rect.match_style(g_rect) g_axes_copy = g_axes.copy() g_axes_copy.add(y_label) true_group = VGroup(g_axes_copy, gy_label, true_g_graph) self.play(ShowCreation(gsmx_rect)) self.wait() self.play( true_group.animate.to_edge(DOWN, buff=MED_SMALL_BUFF), ) self.add(*true_group) g_axes.generate_target() g_axes.target.x_label.set_opacity(1), self.play( TransformMatchingShapes(gy_label.copy(), gmx_label), true_g_graph.copy().animate.flip().move_to(g_graph).set_anim_args(remover=True), MoveToTarget(g_axes), ) self.add(g_graph) self.wait() self.play(FadeOut(true_group)) # Show the parameter s self.play( s_indicator.animate.match_x(g_axes.c2p(2, 0)).set_anim_args(run_time=3), VFadeIn(s_indicator), VFadeIn(s_label), TransformMatchingTex(gmx_label, g_label, run_time=1), ) self.wait() # Play with the slider self.play( s_indicator.animate.match_x(g_axes.c2p(0.3, 0)) ) # Show product fg_rect = SurroundingRectangle(conv_label[R"f(x) \cdot g(s - x)"]) fg_rect.match_style(g_rect) self.play(ReplacementTransform(gsmx_rect, fg_rect)) self.play(LaggedStart( FadeTransform(f_axes.copy(), fg_axes), FadeTransform(g_axes.copy(), fg_axes), Transform(f_graph.copy(), prod_graphs[0].copy(), remover=True), Transform(g_graph.copy(), prod_graphs[0].copy(), remover=True), TransformFromCopy( VGroup(*f_label, *g_label), fg_label ), FadeOut(fg_rect), run_time=2, )) self.add(*prod_graphs) self.play(FadeIn(prod_graphs[1])) self.add(prod_graphs) # Play with the slider self.wait() self.play( s_indicator.animate.match_x(g_axes.c2p(-0.8, 0)) ) # Show convolution def get_s(): return g_axes.x_axis.p2n(s_indicator.get_x()) conv_s_indicator = self.get_conv_s_indicator() self.play(FadeOut(conv_cover)) self.play(Transform( VGroup(indicator, s_label).copy().clear_updaters(), conv_s_indicator.copy().clear_updaters(), remover=True )) self.add(conv_s_indicator) # Play with the slider self.wait() self.play(s_indicator.animate.match_x(g_axes.c2p(-0.4, 0))) def highlight_several_regions(self, highlighted_xs=None, s=0, reference=None): # Highlight a few regions if highlighted_xs is None: highlighted_xs = np.arange(-1, 1.1, 0.1) g_axes = self.all_axes[1] highlight_rect = Rectangle(width=0.1, height=FRAME_HEIGHT / 2) highlight_rect.set_stroke(width=0) highlight_rect.set_fill(TEAL, 0.5) highlight_rect.move_to(g_axes.get_origin(), DOWN) highlight_rect.set_opacity(0.5) self.add(highlight_rect) last_label = VMobject() for x in highlighted_xs: x_tex = f"{{{np.round(x, 1)}}}" diff_tex = f"{{{np.round(s - x, 1)}}}" label = Tex( fR"p_X({x_tex}) \cdot p_Y({diff_tex})", tex_to_color_map={diff_tex: YELLOW, x_tex: BLUE}, font_size=36 ) if reference: label.next_to(reference, UP, MED_LARGE_BUFF) else: label.next_to(ORIGIN, DOWN, LARGE_BUFF) highlight_rect.set_x(g_axes.c2p(x, 0)[0]), self.add(label) self.remove(last_label) self.wait(0.25) last_label = label self.play(FadeOut(last_label), FadeOut(highlight_rect)) def f(self, x): return wedge_func(x) def g(self, x): return double_lump(x) class ConvolveTwoUniforms(Convolutions): jagged_product = True jagged_convolution = True axes_config = dict( x_range=(-2, 2, 0.5), y_range=(-1, 1, 1.0), width=6, height=2, ) f_graph_x_step = 0.025 g_graph_x_step = 0.025 conv_y_stretch_factor = 1.0 def construct(self): self.all_axes[0].x_axis.add_numbers( font_size=16, num_decimal_places=1, excluding=[0], buff=0.1, ) self.g_label.shift(MED_LARGE_BUFF * UP) self.fg_label.shift(MED_LARGE_BUFF * UP) self.add(self.get_conv_s_indicator()) # Show it all self.wait(60) def f(self, x): return uniform(x) def g(self, x): return uniform(x) class ConvolveUniformWithWedge(Convolutions): f_graph_x_step = 0.025 g_graph_x_step = 0.025 def construct(self): self.conv_graph.shift(0.025 * LEFT) # Play around with it self.wait(20) def f(self, x): return wedge_func(x) def g(self, x): return uniform(x) class ConvolveTwoNormals(Convolutions): def construct(self): # Play around with it self.wait(20) def f(self, x): return gauss_func(x, 0, 0.5) def g(self, x): return gauss_func(x, 0, 0.5) class ProbConvolutionControlled(ProbConvolutions): t_time_pairs = [(-2.5, 4), (2.5, 10), (-1, 6)] initial_t = 0 def construct(self): s_indicator = self.s_indicator g_axes = self.all_axes[1] def set_t(t): return s_indicator.animate.set_x(g_axes.c2p(t, 0)[0]) s_indicator.set_x(g_axes.c2p(self.initial_t, 0)[0]) for t, time in self.t_time_pairs: self.play(set_t(t), run_time=time) class ProbConvolutionControlledToMatchSlices(ProbConvolutionControlled): t_time_pairs = [(-1.5, 20), (1.5, 20), (-0.5, 20)] initial_t = 2 class AltSyncedConvolution(ProbConvolutionControlledToMatchSlices): t_time_pairs = [(1.0, 15), (-1.5, 10), (-3.0, 10), (1.0, 20)] initial_t = -3.0 def f(self, x): return (x > -2) * np.exp(-2 - x) def g(self, x): return wedge_func(x) class ThumbnailGraphs(AltSyncedConvolution): def construct(self): super().construct() s_indicator = self.s_indicator f_axes, g_axes = self.all_axes[:2] for axes in [f_axes, g_axes]: axes.set_stroke(width=4) axes.x_axis[1].set_stroke(width=0) for graph in [self.f_graph, self.g_graph, self.prod_graphs]: graph.set_stroke(width=8) s = -1.68 s_indicator.set_x(g_axes.c2p(s, 0)[0]) class AltConvolutions(Convolutions): jagged_product = True def construct(self): s_indicator = self.s_indicator g_axes = self.all_axes[1] # Sample values for t in [3, -3, -1.0]: self.play(s_indicator.animate.set_x(g_axes.c2p(t, 0)[0]), run_time=3) self.wait() def f(self, x): if x < -2: return -0.5 elif x < -1: return x + 1.5 elif x < 1: return -0.5 * x else: return 0.5 * x - 1 def g(self, x): return np.exp(-3 * x**2) class MovingAverageAsConvolution(Convolutions): g_graph_x_step = 0.1 jagged_product = True g_is_rect = True def construct(self): # Setup super().construct() s_indicator = self.s_indicator f_axes, g_axes, fg_axes, conv_axes = self.all_axes self.g_label.shift(0.25 * UP) self.fg_label.shift(0.25 * UP) y_axes = VGroup(*(axes.y_axis for axes in self.all_axes[1:3])) fake_ys = y_axes.copy() for fake_y in fake_ys: fake_y.stretch(1.2, 1) self.add(*fake_ys, *self.mobjects) conv_axes.y_axis.match_height(f_axes.y_axis) VGroup(conv_axes).match_y(f_axes) self.conv_graph.match_points(get_conv_graph(conv_axes, self.f, self.g)) self.conv_label.next_to(conv_axes, DOWN, MED_LARGE_BUFF) # Sample values def set_t(t): return s_indicator.animate.set_x(g_axes.c2p(t, 0)[0]) self.play(set_t(-2.5), run_time=2) self.play(set_t(2.5), run_time=8) self.wait() self.play(set_t(-1), run_time=3) self.wait() # Isolate to slice top_line, side_line = Line().replicate(2) top_line.add_updater(lambda l: l.put_start_and_end_on(*self.g_graph.get_anchors()[4:6])) side_line.add_updater(lambda l: l.put_start_and_end_on(*self.g_graph.get_anchors()[2:4])) top_line.set_stroke(width=0) self.add(top_line) left_rect, right_rect = fade_rects = FullScreenFadeRectangle().replicate(2) left_rect.add_updater(lambda m: m.set_x(top_line.get_left()[0], RIGHT)) right_rect.add_updater(lambda m: m.set_x(top_line.get_right()[0], LEFT)) self.play(FadeIn(fade_rects)) self.play(set_t(-2), run_time=3) self.play(set_t(-0.5), run_time=3) self.wait() self.play(FadeOut(fade_rects)) # Show rect dimensions get_k1 = self.k1_tracker.get_value get_k2 = self.k2_tracker.get_value top_label = DecimalNumber(1, font_size=24) top_label.add_updater(lambda m: m.set_value(1.0 / get_k1())) top_label.add_updater(lambda m: m.next_to(top_line, UP, SMALL_BUFF)) side_label = DecimalNumber(1, font_size=24) side_label.add_updater(lambda m: m.set_value(get_k2())) side_label.add_updater(lambda m: m.next_to(side_line, LEFT, SMALL_BUFF)) def change_ks(k1, k2, run_time=3): new_conv_graph = get_conv_graph( self.all_axes[3], self.f, lambda x: self.g(k1 * x) * k2, ) new_conv_graph.match_style(self.conv_graph) self.play( self.k1_tracker.animate.set_value(k1), self.k2_tracker.animate.set_value(k2), Transform(self.conv_graph, new_conv_graph), run_time=run_time ) top_line.set_stroke(WHITE, 3) side_line.set_stroke(RED, 3) self.play( ShowCreation(side_line), VFadeIn(side_label) ) self.wait() self.play( ShowCreation(top_line), VFadeIn(top_label), ) self.wait() # Change dimensions change_ks(0.5, 1) self.wait() change_ks(0.5, 0.5) self.play(set_t(-1.5), run_time=2) self.play(set_t(-0.25), run_time=2) self.wait() change_ks(2, 0.5) self.wait() change_ks(2, 2) self.wait() change_ks(4, 4) change_ks(1, 1) self.play(*map(FadeOut, [top_label, top_line, side_label, side_line])) # Show area rect = Rectangle() rect.set_fill(YELLOW, 0.5) rect.set_stroke(width=0) rect.set_gloss(1) rect.add_updater(lambda m: m.set_width(g_axes.x_axis.unit_size / get_k1(), stretch=True)) rect.add_updater(lambda m: m.set_height(g_axes.y_axis.unit_size * get_k2(), stretch=True)) rect.add_updater(lambda m: m.set_x(s_indicator.get_x())) rect.add_updater(lambda m: m.set_y(g_axes.get_origin()[1], DOWN)) area_label = Tex(R"\text{Area } = 1", font_size=36) area_label.next_to(rect, UP, MED_LARGE_BUFF) area_label.to_edge(LEFT) arrow = Arrow(area_label.get_bottom(), rect.get_center()) avg_label = TexText(R"Average value of\\$f(x)$ in the window", font_size=24) avg_label.move_to(area_label, DL) shift_value = self.all_axes[2].get_origin() - g_axes.get_origin() + 0.5 * DOWN avg_label.shift(shift_value) arrow2 = arrow.copy().shift(shift_value) self.play( Write(area_label, stroke_color=WHITE), ShowCreation(arrow), FadeIn(rect) ) self.wait() self.play( FadeIn(avg_label, lag_ratio=0.1), ShowCreation(arrow2) ) self.wait() for k in [1.4, 0.8, 1.0, 4.0, 10.0, 1.0]: change_ks(k, k) self.play(*map(FadeOut, [area_label, arrow, avg_label, arrow2])) # More ambient variation self.play(set_t(-2.5), run_time=3) self.play(set_t(2.5), run_time=8) self.play(set_t(0), run_time=4) change_ks(20, 20) self.wait() change_ks(10, 10) self.wait() change_ks(0.2, 0.2, run_time=12) self.wait() def f(self, x): return kinked_function(x) def g(self, x): return rect_func(x) class GaussianConvolution(ProbConvolutionControlled): jagged_product = True t_time_pairs = [(-3.0, 4), (3.0, 10), (-1, 10), (1, 5)] conv_y_stretch_factor = 1.0 def f(self, x): return 1.5 * np.exp(-x**2) / np.sqrt(PI) def g(self, x): return 1.5 * np.exp(-x**2) / np.sqrt(PI) class GaussConvolutions(Convolutions): conv_y_stretch_factor = 1.0 def construct(self): super().construct() def f(self, x): return np.exp(-x**2) def g(self, x): return np.exp(-x**2) class RepeatedConvolution(MovingAverageAsConvolution): resolution = 0.01 n_iterations = 12 when_to_renormalize = 5 f_label_tex = "f_1(x)" g_label_tex = "f_1(s - x)" fg_label_tex = R"f_1(x) \cdot f_1(s - x)" conv_label_tex = R"f_2(s) = [f_1 * f_1](s)" conv_y_stretch_factor = 1.0 convolution_creation_time = 5 pre_rescale_factor = 1.5 lower_graph_target_area = 1.0 def construct(self): # Clean the board dx = self.resolution axes1, axes2, axes3, conv_axes = self.all_axes g_graph = self.g_graph x_min, x_max = axes1.x_range[:2] x_samples = np.arange(x_min, x_max + dx, dx) f_samples = np.array([self.f(x) for x in x_samples]) g_samples = np.array([self.g(x) for x in x_samples]) self.remove( self.f_graph, self.prod_graphs, self.conv_graph, self.conv_graph_dot, self.conv_graph_line, ) for axes in self.all_axes[:3]: axes.x_label.set_opacity(0) # New f graph f_graph = g_graph.copy() f_graph.clear_updaters() f_graph.set_stroke(BLUE, 3) f_graph.shift(axes1.get_origin() - axes2.get_origin()) self.add(f_graph) # New prod graph def update_prod_graph(prod_graph): s = self.get_s() prod_samples = np.array([ f_sample * self.g(s - x) for f_sample, x in zip(f_samples, x_samples) ]) prod_graph.set_points_as_corners( axes3.c2p(x_samples, prod_samples) ) prod_graph = VMobject() prod_graph.set_stroke(GREEN, 2) prod_graph.set_fill(BLUE_E, 1) prod_graph.add_updater(update_prod_graph) self.fg_label.shift(0.35 * UP) self.g_label.shift(0.35 * UP) self.add(prod_graph) self.add(self.fg_label) # Move convolution axes conv_axes.match_y(axes1) self.remove(self.conv_label) conv_label = self.get_conv_label(2) self.conv_label = conv_label self.add(conv_label) # Show repeated convolutions for n in range(1, self.n_iterations + 1): conv_samples, conv_graph = self.create_convolution( x_samples, f_samples, g_samples, conv_axes, ) if n == self.when_to_renormalize: self.add_rescale_arrow() if n >= self.when_to_renormalize: self.rescale_conv(conv_axes, conv_graph, n) self.swap_graphs(f_graph, conv_graph, axes1, conv_axes, n) self.swap_labels(n, conv_graph) f_samples[:] = conv_samples def create_convolution(self, x_samples, f_samples, g_samples, conv_axes): # Prepare self.set_s(x_samples[0], animate=False) conv_samples, conv_graph = self.get_conv( x_samples, f_samples, g_samples, conv_axes ) endpoint_dot = GlowDot(color=WHITE) endpoint_dot.add_updater(lambda m: m.move_to(conv_graph.get_points()[-1])) # Sweep self.play( self.set_s(x_samples[-1]), ShowCreation(conv_graph), UpdateFromAlphaFunc( endpoint_dot, lambda m, a: m.move_to(conv_graph.get_end()).set_opacity(min(6 * a, 1)), ), run_time=self.convolution_creation_time, rate_func=bezier([0, 0, 1, 1]) ) self.play(FadeOut(endpoint_dot, run_time=0.5)) return conv_samples, conv_graph def swap_graphs(self, f_graph, conv_graph, f_axes, conv_axes, n): shift_value = f_axes.get_origin() - conv_axes.get_origin() conv_axes_copy = conv_axes.deepcopy() f_label = self.f_label new_f_label = Tex(f"f_{{{n + 1}}}(x)", **self.label_config) new_f_label.replace(self.conv_label[:len(new_f_label)]) new_f_label[-2].set_opacity(0) f_group = VGroup(f_axes, f_graph, f_label) new_f_graph = conv_graph.copy() self.add(conv_axes_copy, new_f_graph) anims = [ Transform(conv_axes_copy, f_axes, remover=True), new_f_graph.animate.shift(shift_value).match_style(f_graph), FadeOut(f_group, shift_value), new_f_label.animate.replace(f_label, dim_to_match=1).set_opacity(1), ] self.play(LaggedStart(*anims)) self.remove(new_f_label, new_f_graph) f_graph.become(new_f_graph) f_label.become(new_f_label) self.add(f_axes, f_graph, f_label) def swap_labels(self, n, conv_graph): # Test new_conv_label = self.get_conv_label(n + 2) new_conv_label.replace(self.conv_label) prod_rhs = self.fg_label[6:] new_prod_rhs = Tex(f"f_{{{n + 1}}}(s - x)") new_prod_rhs.replace(prod_rhs, dim_to_match=1) to_remove = VGroup( self.conv_label[f"f_{{{n + 1}}}"], self.conv_label[f"f_{{{n}}}"], prod_rhs, ) to_add = VGroup( new_conv_label[f"f_{{{n + 2}}}"], new_conv_label[f"f_{{{n + 1}}}"], new_prod_rhs, ) anims = [ LaggedStartMap(FadeOut, to_remove, shift=0.5 * UP), LaggedStartMap(FadeIn, to_add, shift=0.5 * UP), FadeOut(conv_graph), ] if hasattr(self, "rescaled_graphs"): anims.append(self.rescaled_graphs.animate.set_stroke(width=0.5, opacity=0.5)) self.play(*anims, run_time=1) self.remove(self.conv_label) self.remove(new_prod_rhs) self.conv_label = new_conv_label prod_rhs.become(new_prod_rhs) self.add(self.conv_label) self.add(prod_rhs) def add_rescale_arrow(self): arrow = Vector(1.5 * DOWN) label = TexText(R"Rescale so that\\std. dev. = 1", font_size=30) label.next_to(arrow) self.rescale_label = VGroup(label, arrow) self.rescale_label.next_to(self.conv_label, DOWN) self.play( GrowArrow(arrow), FadeIn(label) ) self.add(self.rescale_label) def rescale_conv(self, conv_axes, conv_graph, n): anims = [] if not hasattr(self, "rescaled_axes"): self.rescaled_axes = conv_axes.copy() self.rescaled_axes.next_to(self.rescale_label, DOWN) self.rescaled_graphs = VGroup() anims.append(TransformFromCopy(conv_axes, self.rescaled_axes)) factor = self.pre_rescale_factor / math.sqrt(n + 1) stretched_graph = conv_graph.copy() stretched_graph.stretch(factor, 0) stretched_graph.stretch(1 / factor, 1, about_edge=DOWN) new_graph = VMobject() new_graph.start_new_path(conv_axes.x_axis.get_start()) new_graph.add_line_to(stretched_graph.get_start()) new_graph.append_vectorized_mobject(stretched_graph) new_graph.add_line_to(conv_axes.x_axis.get_end()) new_graph.match_style(stretched_graph) new_graph.shift(self.rescaled_axes.x_axis.pfp(0.5) - conv_axes.c2p(0, 0)) area = get_norm(new_graph.get_area_vector()) new_graph.stretch(self.lower_graph_target_area / area, 1, about_edge=DOWN) anims.append(TransformFromCopy(conv_graph, new_graph)) self.play(*anims) self.rescaled_graphs.add(new_graph) self.add(self.rescaled_graphs) def get_conv(self, x_samples, f_samples, g_samples, axes): """ Returns array of samples and graph """ conv_samples = self.resolution * scipy.signal.fftconvolve( f_samples, g_samples, mode='same' ) conv_graph = VMobject() conv_graph.set_points_as_corners(axes.c2p(x_samples, conv_samples)) conv_graph.set_stroke(TEAL, 3) return conv_samples, conv_graph def get_s(self): return self.all_axes[1].x_axis.p2n(self.s_indicator.get_center()) def set_s(self, s, animate=True): if animate: mob = self.s_indicator.animate else: mob = self.s_indicator return mob.set_x(self.all_axes[1].c2p(s)[0]) def get_conv_label(self, n): lhs = f"f_{{{n}}}(s)" last = f"f_{{{n - 1}}}" result = Tex(lhs, "=", R"\big[", last, "*", "f_1", R"\big]", "(s)") result.set_height(0.5) result.next_to(self.all_axes[3], DOWN, MED_LARGE_BUFF) return result def f(self, x): return uniform(x) class RepeatedConvolutionDoubleLump(RepeatedConvolution): n_iterations = 12 when_to_renormalize = 1 g_is_rect = False axes_config = dict( x_range=(-5, 5, 1), y_range=(-1, 1, 1.0), width=6, height=2, ) pre_rescale_factor = 0.75 lower_graph_target_area = 0.5 def f(self, x): x *= 1.5 return 1.5 * 0.69 * (np.exp(-6 * (x - 0.8)**2) + np.exp(-6 * (x + 0.8)**2)) def g(self, x): return self.f(x) class RepeatedConvolutionExp(RepeatedConvolutionDoubleLump): pre_rescale_factor = 1.0 axes_config = dict( x_range=(-10, 10, 1), y_range=(-1, 1, 1.0), width=6, height=2, ) def f(self, x): return np.exp(-(x + 1)) * (x > -1) class RepeatedConvolutionGaussian(RepeatedConvolution): g_is_rect = False when_to_renormalize = 1 axes_config = dict( x_range=(-7, 7, 1), y_range=(-0.5, 0.5, 0.5), width=6, height=2, ) convolution_creation_time = 2 pre_rescale_factor = 0.95 def f(self, x): return gauss_func(x, 0,1) def g(self, x): return gauss_func(x, 0, 1) # Old rect material class MovingAverageOfRectFuncs(Convolutions): f_graph_x_step = 0.01 g_graph_x_step = 0.01 jagged_product = True def construct(self): super().construct() s_indicator = self.s_indicator g_axes = self.all_axes[1] self.all_axes[3].y_axis.match_height(g_axes.y_axis) self.conv_graph.set_height(0.5 * g_axes.y_axis.get_height(), about_edge=DOWN, stretch=True) for t in [3, -3, 0]: self.play(s_indicator.animate.set_x(g_axes.c2p(t, 0)[0]), run_time=5) self.wait() def f(self, x): return rect_func(x / 2) def g(self, x): return 1.5 * rect_func(1.5 * x) class RectConvolutionsNewNotation(MovingAverageOfRectFuncs): def construct(self): # Setup axes x_min, x_max = -1.0, 1.0 all_axes = axes1, axes2, axes3 = VGroup(*( Axes( (x_min, x_max, 0.5), (0, 5), width=3.75, height=4 ) for x in range(3) )) all_axes.arrange(RIGHT, buff=LARGE_BUFF, aligned_edge=DOWN) for axes in all_axes: axes.x_axis.add_numbers(font_size=12, num_decimal_places=1) axes2.y_axis.add_numbers(font_size=12, num_decimal_places=0, direction=DL, buff=0.05) all_axes.move_to(DOWN) self.add(all_axes) # Prepare convolution graphs dx = 0.01 xs = np.arange(x_min, x_max + dx, dx) k_range = list(range(3, 9, 2)) conv_graphs = self.get_all_convolution_graphs(xs, rect_func(xs), axes3, k_range) VGroup(*conv_graphs).set_stroke(TEAL, 3) rect_defs = VGroup( self.get_rect_func_def(), *(self.get_rect_k_def(k) for k in k_range) ) rect_defs.scale(0.75) rect_defs.next_to(axes2, UP) rect_defs[0][9:].scale(0.7, about_edge=LEFT) rect_defs[0].next_to(axes1, UP).shift_onto_screen() conv_labels = VGroup( Tex(R"\big[\text{rect} * \text{rect}_3\big](x)"), Tex(R"\big[\text{rect} * \text{rect}_3 * \text{rect}_5\big](x)"), Tex(R"\big[\text{rect} * \text{rect}_3 * \text{rect}_5 * \text{rect}_7 \big](x)"), ) conv_labels.scale(0.75) conv_labels.match_x(axes3).match_y(rect_defs) # Show rect_1 * rect_3 rect_graphs = VGroup(*( self.get_rect_k_graph(axes2, k) for k in [1, *k_range] )) rect_graphs[0].set_color(BLUE) rect_graphs[0].match_x(axes1) rect = Rectangle(axes2.x_axis.unit_size / 3, axes2.y_axis.unit_size * 3) rect.set_stroke(width=0) rect.set_fill(YELLOW, 0.5) rect.move_to(axes2.get_origin(), DOWN) self.add(*rect_graphs[:2]) self.add(*rect_defs[:2]) self.add(conv_graphs[0]) self.play(FadeIn(rect)) self.wait() self.play( Transform(rect_defs[0][:4].copy(), conv_labels[0][0][1:5], remover=True, path_arc=-PI / 3), Transform(rect_defs[1][:5].copy(), conv_labels[0][0][6:11], remover=True, path_arc=-PI / 3), FadeIn(conv_labels[0][0], lag_ratio=0.1, time_span=(1.5, 2.5)), FadeOut(rect), run_time=2 ) self.wait() # Show the rest for n in range(2): left_graph = rect_graphs[n] if n == 0 else conv_graphs[n - 1] lefs_label = rect_defs[n] if n == 0 else conv_labels[n - 1] k = 2 * n + 5 new_rect = Rectangle(axes2.x_axis.unit_size / k, axes2.y_axis.unit_size * k) new_rect.set_stroke(width=0) new_rect.set_fill(YELLOW, 0.5) new_rect.move_to(axes2.get_origin(), DOWN) self.play( FadeOut(left_graph, 1.5 * LEFT), FadeOut(lefs_label, 1.5 * LEFT), FadeOut(rect_defs[n + 1]), FadeOut(rect_graphs[n + 1]), conv_labels[n].animate.match_x(axes1), conv_graphs[n].animate.match_x(axes1), ) self.play( Write(rect_defs[n + 2], stroke_color=WHITE), ShowCreation(rect_graphs[n + 2]), FadeIn(new_rect), run_time=1, ) self.wait() left_conv = conv_labels[n][0][1:-4] r = len(left_conv) + 1 self.play( Transform(left_conv.copy(), conv_labels[n + 1][0][1:r], remover=True, path_arc=-PI / 3), Transform(rect_defs[2][:5].copy(), conv_labels[n + 1][0][r + 1:r + 6], remover=True, path_arc=-PI / 3), FadeIn(conv_labels[n + 1][0], lag_ratio=0.1, time_span=(0.5, 1.5)), ShowCreation(conv_graphs[n + 1]), ) self.play(FadeOut(new_rect)) self.wait() def get_rect_k_graph(self, axes, k): x_range = axes.x_axis.x_range x_range[2] = 1 / k return axes.get_graph( lambda x: k * rect_func(k * x), discontinuities=(-1 / (2 * k), 1 / (2 * k)), stroke_color=YELLOW, stroke_width=3, ) def get_rect_k_def(self, k): return Tex(Rf"\text{{rect}}_{{{k}}}(x) := {k} \cdot \text{{rect}}({k}x)")[0] class RectConvolutionFacts(InteractiveScene): def construct(self): # Equations equations = VGroup( Tex(R"\text{rect}", "(0)", "=", "1.0"), Tex( R"\big[", R"\text{rect}", "*", R"\text{rect}_3", R"\big]", "(0)", "=", "1.0" ), Tex( R"\big[", R"\text{rect}", "*", R"\text{rect}_3", "*", R"\text{rect}_5", R"\big]", "(0)", "=", "1.0" ), Tex(R"\vdots"), Tex( R"\big[", R"\text{rect}", "*", R"\text{rect}_3", "*", R"\cdots", "*", R"\text{rect}_{13}", R"\big]", "(0)", "=", "1.0" ), Tex( R"\big[", R"\text{rect}", "*", R"\text{rect}_3", "*", R"\cdots", "*", R"\text{rect}_{13}", "*", R"\text{rect}_{15}", R"\big]", "(0)", "=", SUB_ONE_FACTOR + R"\dots" ), ) for eq in equations: eq.set_color_by_tex(R"\text{rect}", BLUE) eq.set_color_by_tex("_3", TEAL) eq.set_color_by_tex("_5", GREEN) eq.set_color_by_tex("_{13}", YELLOW) eq.set_color_by_tex("_{15}", RED_B) equations.arrange(DOWN, buff=0.75, aligned_edge=RIGHT) equations[3].match_x(equations[2][-1]) equations[-1][:-1].align_to(equations[-2][-2], RIGHT) equations[-1][-1].next_to(equations[-1][:-1], RIGHT) equations.set_width(FRAME_WIDTH - 4) equations.center() # Show all (largely copy pasted...) self.add(equations[0]) for i in range(4): if i < 3: src = equations[i].copy() else: src = equations[i + 1].copy() if i < 2: target = equations[i + 1] elif i == 2: target = VGroup(*equations[i + 1], *equations[i + 2]) else: target = equations[i + 2] self.play(TransformMatchingTex(src, target)) self.wait(0.5) self.wait()
from manim_imports_ext import * import sympy from _2023.clt.main import ChartBars class TwinPrimScrolling(InteractiveScene): def construct(self): # Create list of primes n_max = 1000 primes = list(sympy.primerange(2, n_max)) prime_mobs = VGroup(*map(Integer, primes)) prime_mobs.arrange(RIGHT, buff=MED_LARGE_BUFF) prime_mobs.move_to(1 * RIGHT, LEFT) prime_mobs.shift(2.5 * DOWN) prime_mobs.set_fill(border_width=1) twin_prime_color = BLUE tp_groups = VGroup() twin_primes = set() for i in range(len(primes) - 1): if primes[i] + 2 == primes[i + 1]: twin_primes.add(primes[i]) twin_primes.add(primes[i + 1]) arc = Line( prime_mobs[i].get_top(), prime_mobs[i + 1].get_top(), path_arc=-PI, stroke_color=twin_prime_color, stroke_width=2, ) arc.scale(0.9, about_edge=UP) plus_2 = Tex("+2", font_size=24) plus_2.next_to(arc, UP, SMALL_BUFF) plus_2.set_color(twin_prime_color) tp_groups.add(VGroup( *prime_mobs[i:i + 2].copy(), arc, plus_2 )) non_twin_primes = VGroup(*( pm for pm, prime in zip(prime_mobs, primes) if prime not in twin_primes )) highlight_point = 5 def update_tp_groups(tp_groups): for tp_group in tp_groups: for mob in tp_group[2:]: mob.match_x(tp_group[:2]) x_coord = tp_group.get_x() if x_coord < -10: tp_groups.remove(tp_group) continue pre_alpha = inverse_interpolate( highlight_point + 0.25, highlight_point - 0.25, x_coord ) alpha = clip(pre_alpha, 0, 1) color = interpolate_color(WHITE, twin_prime_color, alpha) tp_group[:2].set_color(color) tp_group[2].set_stroke(width=2 * alpha) tp_group[3].set_opacity(alpha) tp_groups.add_updater(update_tp_groups) self.add(non_twin_primes) self.add(tp_groups) # Animation velocity = 1.5 run_time = non_twin_primes.get_width() def shift_updater(mobject, dt): mobject.shift(velocity * dt * LEFT) tp_groups.add_updater(shift_updater) non_twin_primes.add_updater(shift_updater) self.wait(run_time) class Timeline(InteractiveScene): def construct(self): # Timeline timeline = NumberLine( (-500, 2050, 100), width=FRAME_WIDTH - 1 ) timeline.move_to(2.5 * DOWN) timeline.add_numbers( list(range(0, 2050, 500)), direction=DOWN, group_with_commas=False, font_size=36, ) label = Tex(R"\sim 300 BC", font_size=36) v_line = Line(DOWN, UP) v_line.move_to(timeline.n2p(-300), DOWN) v_line.shift(SMALL_BUFF * DOWN) v_line.set_stroke(WHITE, 1) label.next_to(v_line, DOWN, buff=0.15) self.add(timeline) self.add(v_line) self.add(label) # Label question = TexText( R"``Are there infinitely many twin primes?''\\ \quad -Euclid", font_size=48, alignment="", ) question[-7:].shift(RIGHT + 0.1 * DOWN) question.next_to(v_line, UP) question.shift_onto_screen(buff=0.2) arrows = VGroup( Vector(3 * LEFT), Text("No one can\nanswer", font_size=60).set_color(YELLOW), Vector(3 * RIGHT) ) arrows.arrange(RIGHT) arrows.set_width(get_norm(timeline.n2p(2000) - timeline.n2p(-300))) arrows.next_to(v_line, RIGHT) arrows.shift(0.5 * UP) # self.add(question) self.add(arrows) class InfinitePrimes(InteractiveScene): def construct(self): # Test n_max = 150 primes = list(sympy.primerange(2, n_max)) prime_mobs = VGroup(*map(Integer, primes)) prime_mobs.set_height(1.5) prime_mobs.use_winding_fill(False) def update_opacity(prime): # alpha = inverse_interpolate(10, 0, prime.get_y()) alpha = inverse_interpolate(-20, 0, prime.get_z()) prime.set_fill(opacity=alpha) for n, prime in enumerate(prime_mobs): # prime.rotate(88 * DEGREES, RIGHT) prime.set_height(1.5 * 0.95**n) prime.move_to(3 * n * IN) prime.add_updater(update_opacity) rect = FullScreenRectangle() rect.set_fill(BLACK, 1) rect.fix_in_frame() self.frame.reorient(-70, -30, 70) self.frame.set_focal_distance(5) self.add(prime_mobs) self.play( prime_mobs.animate.shift(70 * OUT), FadeIn(rect, time_span=(10, 12)), run_time=12, rate_func=rush_into, ) def old_attempt(self): # Old attempt point = UL height = 2 shift = 0.75 * np.array([1, -1.2, 0]) scale = 1.0 opacity = 1.0 scale_factor = 0.65 shift_scale_factor = 0.7 opacity_scale_factor = 0.9 for n, mob in enumerate(prime_mobs): mob.set_height(height * scale_factor**n) mob.move_to(point + sum( shift * shift_scale_factor**k for k in range(n) )) mob.set_fill(opacity=opacity * opacity_scale_factor**n) prime_mobs.submobjects.reverse() self.add(prime_mobs) class ThoughtBubble(InteractiveScene): def construct(self): randy = Randolph() randy.to_edge(LEFT) bubble = randy.get_bubble("Suppose\nnot...") self.add(bubble, bubble.content) class EuclidProof(InteractiveScene): def construct(self): # Suppose finite prime_sequence = Tex(R"2, 3, 5, \dots , p_n", font_size=72) prime_sequence.move_to(UP + LEFT) last = prime_sequence["p_n"] finite_words = Text("All primes (suppose finite)", font_size=60) finite_words.next_to(last, UR).shift(0.2 * UP) sequence_rect = SurroundingRectangle(prime_sequence) sequence_rect.set_stroke(YELLOW, 2) sequence_rect.set_stroke(YELLOW, 2) finite_words.next_to(sequence_rect, UP) finite_words.shift(RIGHT * (sequence_rect.get_x() - finite_words["All primes"].get_x())) last_arrow = Arrow( finite_words["prime"].get_corner(DL), last, path_arc=-PI / 3, buff=0.1 ) VGroup(finite_words, sequence_rect).set_color(YELLOW) self.add(prime_sequence) self.add(finite_words) self.add(sequence_rect) # Multiply, add 1, factor product = Tex(R"N = 2 \cdot 3 \cdot 5 \cdots p_n", font_size=72) product.next_to(prime_sequence, DOWN, LARGE_BUFF) plus_one = Tex("+1", font_size=72) plus_one.next_to(product, RIGHT, 0.2) plus_one.shift(0.05 * UP) N_mob = VGroup(product, plus_one) N_mob.match_x(prime_sequence) psc = prime_sequence.copy() self.play( TransformMatchingTex( psc, product, matched_pairs=[ (psc[","], product[R"\cdot"]), (psc[R"\dots"], product[R"\cdots"]), ], run_time=1 ) ) self.play(Write(plus_one)) self.wait() # Factor N_rect = SurroundingRectangle( VGroup(product[2:], plus_one) ) factor_arrow = Vector(DL) factor_arrow.next_to(N_rect, DOWN) factor_word = Text("Prime factors", font_size=60) factor_word.next_to(factor_arrow, RIGHT, buff=0) VGroup(N_rect, factor_arrow, factor_word).set_color(TEAL) factor_eq = Tex(R"N = q_1 \cdots q_k", font_size=72) factor_eq[R"q_1 \cdots q_k"].set_color(RED) factor_eq.next_to(product, DOWN, buff=1.5, aligned_edge=LEFT) self.play( FadeTransformPieces(product.copy(), factor_eq), FadeIn(N_rect), GrowArrow(factor_arrow), FadeIn(factor_word, 0.5 * DOWN), ) self.wait(3) # Contradiction q_rect = SurroundingRectangle(factor_eq["q_1"], buff=0.1) q_rect.set_stroke(WHITE, 3) q_words = TexText(R"Cannot be in $\{2, 3, 5, \dots, p_n\}$", font_size=60) q_words.next_to(q_rect, UP, aligned_edge=LEFT) q_words.match_color(factor_eq[2]) rect = SurroundingRectangle(Group(*( mob for mob in self.mobjects if isinstance(mob, StringMobject) )), buff=0.5) rect.set_stroke(WHITE, 3) rect.shift(0.35 * DOWN) rect.set_fill(RED, 0.1) cont_word = Text("Contradiction!", font_size=90) cont_word.next_to(rect, UP, buff=0.5, aligned_edge=RIGHT) cont_word.set_color(WHITE) self.play( Transform(N_rect, q_rect), FadeTransformPieces(factor_word, q_words), FadeOut(factor_arrow), ) self.wait(4) self.play( FadeIn(rect), FadeIn(cont_word, 0.5 * UP), ) self.wait() def infinite(self): # Interlude to show infinite inf_sequence = Tex(R"2, 3, 5, 7, 11, \dots", font_size=72) inf_sequence.move_to(prime_sequence, LEFT) inf_arrow = Vector(RIGHT) inf_arrow.next_to(inf_sequence, RIGHT, SMALL_BUFF) inf_words = Text("Infinite", font_size=60) inf_words.next_to(inf_arrow, DOWN, aligned_edge=LEFT) self.add(inf_sequence, inf_arrow, inf_words) class PrimeDensityHistogram(InteractiveScene): def construct(self): # Axes max_x = 10000 step = 100 labeled_xs = list(range(1000, max_x + 1000, 1000)) axes = Axes( (0, max_x, step), (0, 0.5, 0.1), width=FRAME_WIDTH - 2, height=6, x_axis_config=dict( tick_size=0.03, numbers_with_elongated_ticks=labeled_xs, longer_tick_multiple=3, ) ) axes.x_axis.add_numbers( labeled_xs, font_size=16, buff=0.25, ) axes.y_axis.add_numbers( np.arange(0, 0.6, 0.1), num_decimal_places=2, ) y_label = Text(""" Proportion of primes in ranges of length 1,000 """, font_size=36) y_label.next_to(axes.y_axis.get_top(), RIGHT, buff=0.5) y_label.to_edge(UP) axes.add(y_label) self.add(axes) # Bars proportions = [] for n in range(0, max_x, step): n_primes = len(list(sympy.primerange(n, n + step))) proportions.append(n_primes / step) bars = ChartBars(axes, proportions) self.add(bars) class PrimesNearMillion(InteractiveScene): def construct(self): # Add line T = int(1e6) radius = 800 spacing = 50 labeled_numbers = list(range(T - radius, T + radius, spacing)) number_line = NumberLine( (T - radius, T + radius), width=250, tick_size=0.075, ) number_line.ticks[::spacing // 5].stretch(2, 1) # number_line.stretch(0.2, 0) number_line.add_numbers(labeled_numbers, font_size=48, buff=0.5) self.add(number_line) # Primes primes = np.array(list(sympy.primerange(T - radius, T + radius))) dots = GlowDots(number_line.n2p(primes)) dots.set_glow_factor(2) dots.set_radius(0.35) self.add(dots) # Highlight twins arcs = VGroup() for p1, p2 in zip(primes, primes[1:]): if p1 + 2 == p2: arc = Line( number_line.n2p(p1), number_line.n2p(p2), path_arc=-PI ) arc.set_stroke(YELLOW, 3) plus_2 = Tex("+2", font_size=24) plus_2.set_fill(YELLOW) plus_2.next_to(arc, UP, SMALL_BUFF) arcs.add(arc, plus_2) # Pan line_group = Group(number_line, dots, arcs) line_group.shift(1.5 * DOWN + -number_line.n2p(1e6)) line_group.add_updater(lambda m, dt: m.shift(2 * dt * LEFT)) self.add(line_group) # Words t2c = {"T": BLUE} kw = dict(font_size=90, t2c=t2c) words = TexText("How dense are primes?", **kw) lhs = TexText("Prime density near $T$", **kw) approx = Tex(R"\approx", **kw) approx.rotate(PI / 2) rhs = Tex(R"1 / \ln(T)", **kw) group = VGroup(lhs, approx, rhs) group.arrange(DOWN, buff=0.5) group.to_edge(UP) words.move_to(lhs) example = TexText("(e.g. $T = 1{,}000{,}000$)", font_size=60, t2c=t2c) example.next_to(lhs, DOWN, LARGE_BUFF) arrow = Arrow( lhs["T"].get_bottom(), example.get_right(), stroke_width=8, stroke_color=BLUE, path_arc=-PI / 2, buff=0.2, ) self.add(words) self.wait(13) self.play( FadeTransform(words, lhs, run_time=1), ShowCreation(arrow), FadeIn(example, time_span=(1, 2)), ) self.wait(5) self.play( FadeOut(arrow), FadeOut(example), Write(approx), FadeIn(rhs[:-2], DOWN), FadeIn(rhs[-1], DOWN), TransformFromCopy(lhs["T"], rhs["T"]), ) self.wait(45) def old_zooming(self): sf = 0.1 self.play( number_line.animate.scale(sf, about_point=ORIGIN), dots.animate.scale(sf, about_point=ORIGIN).set_radius(0.1), rate_func=rush_from, run_time=17 ) self.wait() # Zoom in to twin prime zoom_point = number_line.n2p(1000210) frame = self.frame self.play( frame.animate.move_to(zoom_point).set_height(0.60), dots.animate.set_radius(0.03), run_time=5 ) class PrimePanning(InteractiveScene): def construct(self): # (A bit too much copy paste from above) N_max = 500 number_line = NumberLine( (0, N_max), unit_size=0.5, tick_size=0.075, ) number_line.ticks[::10].stretch(2, 1) number_line.add_numbers(range(0, N_max), font_size=20, buff=0.2) number_line.move_to(2 * LEFT, LEFT) self.add(number_line) # Primes primes = np.array(list(sympy.primerange(0, N_max))) dots = GlowDots(number_line.n2p(primes)) dots.set_glow_factor(2) dots.set_radius(0.35) self.add(dots) # Pan frame = self.frame frame.set_height(4) frame.add_updater(lambda m, dt: m.shift(1.5 * dt * RIGHT)) self.wait(90) class DensityFormula(InteractiveScene): def construct(self): # Formula t2c = { "T": BLUE, } kw = dict(t2c=t2c, font_size=90) lhs = TexText("Prime density near $T$", **kw) approx = Tex(R"\approx", **kw) approx.rotate(PI / 2) rhs = Tex(R"1 / \ln(T)", **kw) group = VGroup(lhs, approx, rhs) group.arrange(DOWN, buff=0.5) group.to_edge(UP) example = TexText("(e.g. $T = 1{,}000{,}000$)", font_size=60, t2c=t2c) example.next_to(lhs, DOWN, LARGE_BUFF) arrow = Arrow( lhs["T"].get_bottom(), example.get_right(), stroke_width=8, stroke_color=BLUE, path_arc=-PI / 2, buff=0.2, ) self.add(lhs, example, arrow) self.wait() self.remove(example, arrow) self.add(approx, rhs) def old_mess(self): # Formula kw = dict(t2c={ "T": BLUE, "1{,}000{,}000": BLUE, }) lhs = TexText("What's the density of primes near $T$", **kw) rhs = Tex(R"\approx \frac{1}{\ln(T)}", **kw) group = VGroup(lhs, rhs) group.arrange(RIGHT) group.to_edge(UP) q_mark = Text("?") q_mark.next_to(lhs, RIGHT, buff=0.1) q_mark.align_to(lhs[0], DOWN) lhs_note = TexText( "(Some big number, e.g. $T = 1{,}000{,}000$)", font_size=36, **kw ) lhs_note.next_to(lhs, DR, buff=LARGE_BUFF) lhs_note.shift_onto_screen() arrow = Arrow(lhs_note.get_top(), lhs["T"], buff=0.1) arrow.set_color(BLUE) self.add(lhs) self.add(q_mark, lhs_note, arrow) self.wait() self.remove(q_mark, lhs_note, arrow) self.remove(lhs["What's the"]) self.add(rhs) class GapsInPrimes(InteractiveScene): def construct(self): pass class CrankEmail(InteractiveScene): def construct(self): # Background rect = FullScreenRectangle(fill_color=WHITE, fill_opacity=1) rect.scale(2) rect.stretch(10, 1, about_edge=UP) self.add(rect) frame = self.frame frame.set_height(9) frame.to_edge(UP, buff=0) # Rows of numbers numbers1 = list(range(1, 100)) numbers2 = list(filter(lambda m: m % 2 != 0, numbers1)) numbers3 = list(filter(lambda m: m % 3 != 0, numbers2)) arrays = VGroup( self.create_array(numbers1[:30], 2, BLUE_D), self.create_array(numbers2[:30], 3, GREEN_D), self.create_array(numbers3[:20], 5, RED_D), ) arrays.arrange(DOWN, buff=1.0, aligned_edge=LEFT) arrays.to_corner(UL) # Paragraphs kw = dict(alignment="LEFT", font_size=48, fill_color=BLACK, font="Roboto") paragraphs = VGroup( Text(""" Dear sir, I found a marvelous proof for that twin primes are infinite. Please, I need help having this work published. The proof procedes by analyzing the following procedure for generating primes. List all natural numbers, and start by reducing each of them modulo 2: """, **kw), arrays[0], Text(""" Remove numbers which have reduced to 0, reduce what remains modulo 3: """, **kw), arrays[1], Text(""" Again, remove numbers which have reduced to 0, reduce what remains modulo 5: """, **kw), arrays[2], ) paragraphs.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) paragraphs.shift(paragraphs[0].get_x() * LEFT) paragraphs.to_edge(UP, buff=0.2) self.add(paragraphs) for array in arrays: for grid in array: self.remove(grid[1]) # Fill in grid, slide frame self.anticipate_frame_to_y(-6, run_time=3) for grid in arrays[0]: self.animate_reduction(grid) self.cross_out_the_zeros(arrays[0]) self.wait(0.5) self.play(frame.animate.set_y(-12)) for n, grid in enumerate(arrays[1]): self.animate_reduction(grid) if n == 0: self.anticipate_frame_to_y(-15, run_time=2) self.anticipate_frame_to_y(-22, run_time=2) self.cross_out_the_zeros(arrays[1]) self.wait(2) for grid in arrays[2]: self.animate_reduction(grid) self.cross_out_the_zeros(arrays[2]) def create_array( self, numbers, modulus, color=BLUE, height=0.85, spacing=10, buff=0.75, width=10, ): result = VGroup() row1_content = numbers row2_content = [n % modulus for n in numbers] row1_title = "Numbers: " row2_title = f"Mod {modulus}:" n = 0 while n < len(row1_content): result.add(self.create_table( row1_title, row2_title, row1_content[n:n + spacing], row2_content[n:n + spacing], color=color, height=height, )) n += spacing row1_title = "" row2_title = "" result.arrange(DOWN, buff=buff, aligned_edge=RIGHT) result.set_width(width) return result def create_table( self, row1_title, row2_title, row1_content, row2_content, x_spacing=0.6, font_size=36, color=BLUE, height=0.85 ): # Numbers row1_mobs, row2_mobs = ( VGroup(*( Integer(n, font_size=font_size) for n in content )) for content in [row1_content, row2_content] ) for x, mob in enumerate(row1_mobs): mob.set_x(x_spacing * x) row1_mobs.to_edge(LEFT) row1_mobs.set_fill(BLACK) row2_mobs.set_color(color) for m1, m2 in zip(row1_mobs, row2_mobs): m2.set_max_width(0.5 * x_spacing) m2.next_to(m1, DOWN, 0.5) grid = VGroup(row1_mobs, row2_mobs) # Titles row1_label = Text(row1_title, font_size=font_size) row2_label = Text(row2_title, font_size=font_size) row1_label.set_color(BLACK) row1_label.next_to(row1_mobs, LEFT, buff=0.5) row2_label.next_to(row2_mobs, LEFT, buff=0.5) row2_label.set_color(color) grid.add(row1_label, row2_label) # Grid lines h_line = Line(ORIGIN, grid.get_width() * RIGHT) h_line.move_to(grid, LEFT) v_lines = VGroup(*( Line(grid.get_height() * UP, ORIGIN).set_x( 0.5 * (row1_mobs[i].get_right()[0] + row1_mobs[i + 1].get_left()[0]) ).align_to(grid, UP) for i in range(len(row1_mobs) - 1) )) v_lines.set_stroke(BLACK, width=1) h_line.set_stroke(BLACK, width=1) grid.add(h_line, v_lines) grid.set_height(height, about_edge=LEFT) return grid def animate_reduction(self, array, beat_time=0.17): reductions = array[1] self.remove(reductions) self.wait(0.1) for i, term in enumerate(reductions): self.add(term) self.wait(beat_time) m10 = i % 10 if m10 % 2 == 1: self.wait(beat_time) if m10 == 9: self.wait(beat_time) self.add(array) def cross_out_the_zeros(self, array): crosses = VGroup() rects = VGroup() for grid in array: for m1, m2 in zip(grid[0], grid[1]): if m2.get_value() == 0: crosses.add(Cross(m1).scale(1.5)) rect = SurroundingRectangle(VGroup(m1, m2)) rect.set_fill(RED, 0.2) rect.set_stroke(width=0) rects.add(rect) self.play( ShowCreation(crosses, lag_ratio=0), FadeIn(rects, lag_ratio=0.1) ) def anticipate_frame_to_y(self, y, run_time=3): turn_animation_into_updater( ApplyMethod(self.frame.set_y, y, run_time=run_time) ) class SieveOfEratosthenes(InteractiveScene): grid_shape = (10, 10) n_iterations = 10 rect_buff = 0.1 def construct(self): # Initialize grid grid = Square().get_grid(*self.grid_shape, buff=0) grid.set_height(FRAME_HEIGHT - 1) grid.set_stroke(width=1) number_mobs = self.get_number_mobs(grid) number_mobs[0].set_opacity(0) self.add(grid, number_mobs) # Run the sieve modulus = 2 numbers = list(range(2, len(grid) + 1)) for n in range(self.n_iterations): numbers = list(filter(lambda n: n % modulus != 0, numbers)) to_remove = VGroup(*( mob for mob in number_mobs if mob.get_value() % modulus == 0 )) rects = VGroup(*( SurroundingRectangle(tr, buff=self.rect_buff) for tr in to_remove if tr.get_fill_opacity() > 0.5 )) rects.set_stroke(RED, 1) self.play( to_remove.animate.set_color(RED), Write(rects, stroke_color=RED, stroke_width=2), lag_ratio=0.1, run_time=2 ) self.wait() self.play( to_remove[0].animate.set_color(WHITE), to_remove[1:].animate.set_opacity(0), number_mobs[0].animate.set_opacity(0), FadeOut(rects) ) modulus = numbers[0] def get_number_mobs(self, grid): return VGroup(*( Integer(i).set_height(0.3 * box.get_height()).move_to(box) for i, box in zip(it.count(1), grid) )) class GiantSieve(SieveOfEratosthenes): grid_shape = (25, 25) n_iterations = 30 rect_buff = 0.02 # def get_number_mobs(self, grid): # radius = grid[0].get_width() / 4 # return VGroup(*( # Dot(radius=radius).move_to(box) # for box in grid # ))
from manim_imports_ext import * class ThreePis(Scene): def construct(self): pis = VGroup(*(PiCreature() for x in range(3))) for pi, color in zip(pis, (BLUE_E, BLUE_C, BLUE_D)): pi.set_color(color) pis.set_height(2) pis.arrange(RIGHT, buff=2) pis.to_corner(DR) pis[2].flip() words = ["Choas", "Linear\nalgebra", "Quaternions"] modes = ["speaking", "tease", "hooray"] for pi, word, mode in zip(pis, words, modes): bubble = pi.get_bubble( word, bubble_type=SpeechBubble, height=3, width=3, direction=RIGHT ) bubble.add(bubble.content) bubble.next_to(pi, UL) bubble.shift(RIGHT) pi.change(mode, bubble.content) self.add(pi, bubble) self.wait() class PendulumAxes(Scene): def construct(self): plane = NumberPlane( (-2, 2), (-2, 2), height=8, width=8, background_line_style={ "stroke_color": WHITE, } ) theta1 = OldTex("\\theta_1").next_to(plane.c2p(2, 0), RIGHT, SMALL_BUFF) theta2 = OldTex("\\theta_2").next_to(plane.c2p(0, 2), DR, SMALL_BUFF) labels = VGroup(theta1, theta2) x_labels = VGroup(OldTex("-\\pi"), OldTex("-{\\pi \\over 2}"), OldTex("{\\pi \\over 2}"), OldTex("\\pi")) y_labels = VGroup() for label, x in zip(x_labels, (-2, -1, 1, 2)): label.scale(0.5) label.set_stroke(BLACK, 5, background=True) label.next_to(plane.c2p(x, 0), DL, SMALL_BUFF) y_label = label.copy() y_label.next_to(plane.c2p(0, x), DL, SMALL_BUFF) y_labels.add(y_label) self.add(plane) self.add(labels) self.add(x_labels, y_labels) class InterpolatingOrientations(ThreeDScene): matrix = True def construct(self): # Frame frame = self.camera.frame frame.set_height(5) self.camera.light_source.move_to((-5, -10, 5)) # 3d model color = "#539ac3" logo = Cube(color=color) logo.replace_submobject(0, TexturedSurface(logo[0], "acm_logo")) logo.set_depth(0.5, stretch=True) logo.rotate(-45 * DEGREES) logo.set_height(2) logo.set_opacity(0.8) logo_template = logo.copy() # Axes axes = ThreeDAxes( (-3, 3), (-3, 3), (-2, 2), width=6, height=6, depth=4, ) axes.set_stroke(width=1) axes.apply_depth_test() # Bases bases = DotCloud(np.identity(3)) bases.set_color((RED, GREEN, BLUE)) bases.make_3d() lines = VGroup(*(Line() for x in range(3))) lines.set_submobject_colors_by_gradient(RED, GREEN, BLUE) lines.set_stroke(width=2) lines.insert_n_curves(20) lines.apply_depth_test() def update_lines(lines): for line, point in zip(lines, bases.get_points()): line.put_start_and_end_on(ORIGIN, point) lines.add_updater(update_lines) def get_matrix(): return bases.get_points().T # Tie logo to matrix logo = always_redraw( lambda: logo_template.copy().apply_matrix(get_matrix()).sort(lambda p: -p[1]) ) # Show matrix/quaternion label if self.matrix: mat_mob = DecimalMatrix( get_matrix(), element_to_mobject_config={ "num_decimal_places": 2, "edge_to_fix": RIGHT } ) mat_mob.to_corner(UL) def update_mat_mob(mat_mob): for entry, value in zip(mat_mob.get_entries(), get_matrix().flatten()): entry.set_value(value) mat_mob.fix_in_frame() mat_mob.set_column_colors(RED, GREEN, BLUE) return mat_mob mat_mob.add_updater(update_mat_mob) self.add(mat_mob) else: quat_tracker = ValueTracker([1, 0, 0, 0]) bases.add_updater(lambda m: m.set_points( rotation_matrix_from_quaternion(quat_tracker.get_value()).T )) kw = {"num_decimal_places": 3, "include_sign": True} quat_label = VGroup( VGroup(DecimalNumber(1, **kw)), VGroup(DecimalNumber(0, **kw), OldTex("i")), VGroup(DecimalNumber(0, **kw), OldTex("j")), VGroup(DecimalNumber(0, **kw), OldTex("k")), ) for mob in quat_label: mob.arrange(RIGHT, buff=SMALL_BUFF) quat_label.arrange(DOWN, aligned_edge=LEFT, buff=MED_SMALL_BUFF) quat_label.to_corner(UL) quat_label.shift(2 * RIGHT) def update_quat_label(quat_label): colors = [WHITE, RED, GREEN, BLUE] for mob, value, color in zip(quat_label, quat_tracker.get_value(), colors): mob[0].set_value(value) mob.set_color(color) quat_label.fix_in_frame() return quat_label quat_label.add_updater(update_quat_label) self.add(quat_label) # Show 3d scene self.add(axes) self.add(bases) self.add(lines) self.add(logo) def move_to_matrix(matrix, run_time=5): self.play( bases.animate.set_points(np.transpose(matrix)), run_time=run_time ) self.wait() def move_to_quaternion(quaternion, run_time=5): self.play( quat_tracker.animate.set_value(quaternion), UpdateFromFunc( quat_tracker, lambda m: m.set_value(normalize(m.get_value())) ), run_time=run_time ) self.wait() self.play( ShowCreation(axes), frame.animate.reorient(-20, 60), run_time=3 ) self.wait() # Using the matrix to interpolate if self.matrix: move_to_matrix(z_to_vector(RIGHT)) move_to_matrix(z_to_vector(LEFT)) move_to_matrix(z_to_vector(DOWN + RIGHT)) move_to_matrix(z_to_vector(UP + LEFT + OUT)) else: move_to_quaternion(quaternion_from_angle_axis(PI / 2, UP)) move_to_quaternion(quaternion_from_angle_axis(-PI / 2, UP)) move_to_quaternion(quaternion_from_angle_axis(PI / 2, UR)) move_to_quaternion(quaternion_from_angle_axis(-0.3 * PI, UR)) class InterpolatingOrientationsWithQuaternions(InterpolatingOrientations): matrix = False class FirstStepIsToCare(Scene): def construct(self): morty = Mortimer() morty.to_corner(DR) self.play(PiCreatureSays(morty, OldTexText("The first step\\\\is to care."))) class NeverNeeded(Scene): def construct(self): formula = OldTex("\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}") formula.set_height(2) formula.to_corner(UL) self.add(formula) morty = Mortimer() morty.to_corner(DR) self.play(PiCreatureSays(morty, OldTexText("Who actually\\\\uses it!"), target_mode="angry")) class Thanks(Scene): def construct(self): morty = Mortimer() morty.to_corner(DR) self.play(PiCreatureSays(morty, OldTexText("Thanks"), target_mode="gracious")) morty.look_at(OUT)
from manim_imports_ext import * def get_matrix_exponential(matrix, height=1.5, scalar_tex="t", **matrix_config): elem = matrix[0][0] if isinstance(elem, str): mat_class = Matrix elif isinstance(elem, int) or isinstance(elem, np.int64): mat_class = IntegerMatrix else: mat_class = DecimalMatrix matrix = mat_class(matrix, **matrix_config) base = OldTex("e") base.set_height(0.4 * height) matrix.set_height(0.6 * height) matrix.move_to(base.get_corner(UR), DL) result = VGroup(base, matrix) if scalar_tex: scalar = OldTex(scalar_tex) scalar.set_height(0.7 * base.get_height()) scalar.next_to(matrix, RIGHT, buff=SMALL_BUFF, aligned_edge=DOWN) result.add(scalar) return result def get_vector_field_and_stream_lines(func, coordinate_system, magnitude_range=(0.5, 4), vector_opacity=0.75, vector_thickness=0.03, color_by_magnitude=False, line_color=GREY_A, line_width=3, line_opacity=0.75, sample_freq=5, n_samples_per_line=10, arc_len=3, time_width=0.3, ): vector_field = VectorField( func, coordinate_system, magnitude_range=magnitude_range, vector_config={ "fill_opacity": vector_opacity, "thickness": vector_thickness, } ) stream_lines = StreamLines( func, coordinate_system, step_multiple=1.0 / sample_freq, n_samples_per_line=n_samples_per_line, arc_len=arc_len, magnitude_range=magnitude_range, color_by_magnitude=color_by_magnitude, stroke_color=line_color, stroke_width=line_width, stroke_opacity=line_opacity, ) animated_lines = AnimatedStreamLines( stream_lines, line_anim_config={ "time_width": time_width, }, ) return vector_field, animated_lines def mat_exp(matrix, N=100): curr = np.identity(len(matrix)) curr_sum = curr for n in range(1, N): curr = np.dot(curr, matrix) / n curr_sum += curr return curr_sum def get_1d_equation(r="r"): return OldTex( "{d \\over d{t}} x({t}) = {" + r + "} \\cdot x({t})", tex_to_color_map={ "{t}": GREY_B, "{" + r + "}": BLUE, "=": WHITE, } ) def get_2d_equation(matrix=[["a", "b"], ["c", "d"]]): deriv = OldTex("d \\over dt", tex_to_color_map={"t": GREY_B}) vect = Matrix( [["x(t)"], ["y(t)"]], bracket_h_buff=SMALL_BUFF, bracket_v_buff=SMALL_BUFF, element_to_mobject_config={ "tex_to_color_map": {"t": GREY_B}, "isolate": ["(", ")"] } ) deriv.match_height(vect) equals = OldTex("=") matrix_mob = Matrix(matrix, h_buff=0.8) matrix_mob.set_color(TEAL) matrix_mob.match_height(vect) equation = VGroup(deriv, vect, equals, matrix_mob, vect.deepcopy()) equation.arrange(RIGHT) return equation class VideoWrapper(Scene): title = "" def construct(self): self.add(FullScreenRectangle()) screen_rect = ScreenRectangle(height=6) screen_rect.set_stroke(BLUE_D, 1) screen_rect.set_fill(BLACK, 1) screen_rect.to_edge(DOWN) self.add(screen_rect) title = OldTexText(self.title, font_size=90) if title.get_width() > screen_rect.get_width(): title.set_width(screen_rect.get_width()) title.next_to(screen_rect, UP) self.play(Write(title)) self.wait() # Video scenes class ArnoldBookClip(ExternallyAnimatedScene): pass class ZoomInOnProblem(Scene): def construct(self): # Highlight problem image = ImageMobject("mat_exp_exercise.png") image.set_height(FRAME_HEIGHT) prob_rect = Rectangle(3.25, 0.35) prob_rect.move_to([-2.5, -2.5, 0]) prob_rect.set_stroke(BLUE, 2) examples_rect = Rectangle(2.0, 0.8) examples_rect.move_to([01.8, 2.8, 0.0]) examples_rect.set_stroke(YELLOW, 3) answer_rect = Rectangle(3.0, 2.0) answer_rect.move_to(examples_rect, UR) answer_rect.shift(0.1 * RIGHT) full_rect = FullScreenRectangle() full_rect.flip() full_rect.set_fill(BLACK, opacity=0.6) full_rect.append_vectorized_mobject(prob_rect) full_rect2 = full_rect.copy() full_rect3 = full_rect.copy() full_rect.append_vectorized_mobject(examples_rect.copy().scale(1e-6)) full_rect2.append_vectorized_mobject(examples_rect) full_rect3.append_vectorized_mobject(answer_rect) self.add(image) # Write problem problem = OldTexText( "Compute the {{matrix}} {{$e^{At}$}}\\\\if the {{matrix A}} has the form..." ) problem.to_corner(UL) problem.set_stroke(BLACK, 5, background=True) prob_arrow = Arrow(prob_rect, problem) prob_arrow.set_fill(BLUE) mat_underline = Underline(problem.get_part_by_tex("matrix")) mat_underline.set_color(YELLOW) self.play( ShowCreation(prob_rect), FadeIn(full_rect), FadeTransform(prob_rect.copy(), problem), GrowArrow(prob_arrow), ) self.wait() for part in ["e^{At}", "matrix A"]: self.play(FlashAround(problem.get_part_by_tex(part), run_time=2, time_width=4)) self.wait() self.play(ShowCreation(mat_underline)) self.wait() mat_underline.rotate(PI) self.play(Uncreate(mat_underline)) self.wait() # Show inputs examples_label = OldTexText("Various matrices to\\\\plug in for $A$", font_size=40) examples_label.next_to(examples_rect) lhs = OldTex("A = ", font_size=96) lhs.set_stroke(BLACK, 5, background=True) matrices = VGroup( IntegerMatrix([[1, 0], [0, 2]]), IntegerMatrix([[0, 1], [0, 0]]), IntegerMatrix([[0, 1], [-1, 0]]), IntegerMatrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]]), ) eq = VGroup(lhs, matrices[-1]) eq.arrange(RIGHT) eq.next_to(examples_rect, DOWN, LARGE_BUFF, aligned_edge=LEFT) eq.shift_onto_screen() for matrix in matrices: matrix.move_to(matrices[-1], LEFT) matrix.set_stroke(BLACK, 5, background=True) self.play( Transform(full_rect, full_rect2) ) self.play( ShowCreation(examples_rect), FadeIn(examples_label), FadeIn(lhs), FadeIn(matrices[0]), ) self.wait() for m1, m2 in zip(matrices, matrices[1:]): self.play(FadeTransform(m1, m2)) self.wait() class LeadToPhysicsAndQM(Scene): def construct(self): de_words = OldTexText("Differential\\\\equations", font_size=60) de_words.set_x(-3).to_edge(UP) mat_exp = get_matrix_exponential([[3, 1, 4], [1, 5, 9], [2, 6, 5]]) mat_exp[1].set_color(TEAL) mat_exp.next_to(de_words, DOWN, buff=3) qm_words = OldTexText("Quantum\\\\mechanics", font_size=60) qm_words.set_x(3).to_edge(UP) physics_words = OldTexText("Physics", font_size=60) physics_words.move_to(qm_words) qm_exp = OldTex("e^{-i \\hat{H} t / \\hbar}") qm_exp.scale(2) qm_exp.refresh_bounding_box() qm_exp[0][0].set_height(mat_exp[0].get_height(), about_edge=UR) qm_exp[0][0].shift(SMALL_BUFF * DOWN) qm_exp.match_x(qm_words) qm_exp.align_to(mat_exp, DOWN) qm_exp[0][3:5].set_color(TEAL) de_arrow = Arrow(de_words, mat_exp) qm_arrow = Arrow(qm_words, qm_exp) top_arrow = Arrow(de_words, qm_words) self.add(de_words) self.play( GrowArrow(de_arrow), FadeIn(mat_exp, shift=DOWN), ) self.wait() self.play( GrowArrow(top_arrow), FadeIn(physics_words, RIGHT) ) self.wait() self.play( FadeOut(physics_words, UP), FadeIn(qm_words, UP), ) self.play( TransformFromCopy(de_arrow, qm_arrow), FadeTransform(mat_exp.copy(), qm_exp), ) self.wait() class LaterWrapper(VideoWrapper): title = "Later..." class PlanForThisVideo(TeacherStudentsScene): def construct(self): s0, s1, s2 = self.students self.play( PiCreatureSays(s0, OldTexText("But what\\\\is $e^{M}$?"), target_mode="raise_left_hand"), s1.change("erm", UL), s2.change("pondering", UL), ) self.wait() s0.bubble = None self.play( PiCreatureSays( s2, OldTexText("And who cares?"), target_mode="sassy", bubble_config={"direction": LEFT}, ), s1.change("hesitant", UL), self.teacher.change("guilty") ) self.wait(3) class IntroduceTheComputation(Scene): def construct(self): # Matrix in exponent base = OldTex("e") base.set_height(1.0) matrix = IntegerMatrix( [[3, 1, 4], [1, 5, 9], [2, 6, 5]], ) matrix.move_to(base.get_corner(UR), DL) matrix_exp = VGroup(base, matrix) matrix_exp.set_height(2) matrix_exp.to_corner(UL) matrix_exp.shift(3 * RIGHT) randy = Randolph() randy.set_height(2) randy.to_corner(DL) matrix.save_state() matrix.center() matrix.set_height(2.5) self.add(randy) self.play( randy.change("pondering", matrix), Write(matrix.get_brackets()), ShowIncreasingSubsets(matrix.get_entries()), ) self.play( matrix.animate.restore(), Write(base), randy.change("erm", base), ) self.play(Blink(randy)) # Question the repeated multiplication implication rhs = OldTex("= e \\cdot e \\dots e \\cdot e") rhs.set_height(0.75 * base.get_height()) rhs.next_to(matrix_exp, RIGHT) rhs.align_to(base, DOWN) brace = Brace(rhs[0][1:], DOWN) matrix_copy = matrix.copy() matrix_copy.scale(0.5) brace_label = VGroup( matrix.copy().scale(0.5), Text("times?") ) brace_label.arrange(RIGHT) brace_label.next_to(brace, DOWN, SMALL_BUFF) bubble = randy.get_bubble( OldTexText("I'm sorry,\\\\what?!").scale(0.75), height=2, width=3, bubble_type=SpeechBubble, ) self.play( TransformMatchingParts( base.copy(), rhs, path_arc=10 * DEGREES, lag_ratio=0.01, ), GrowFromCenter(brace), ReplacementTransform( matrix.copy(), brace_label[0], path_arc=30 * DEGREES, run_time=2, rate_func=squish_rate_func(smooth, 0.3, 1), ), Write( brace_label[1], run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1), ), randy.change("angry", rhs), ShowCreation(bubble), Write(bubble.content, run_time=1), ) self.wait() false_equation = VGroup( matrix_exp, rhs, brace, brace_label ) # This is nonsense. morty = Mortimer() morty.refresh_triangulation() morty.match_height(randy) morty.to_corner(DR) morty.set_opacity(0) false_equation.generate_target() false_equation.target.scale(0.5) false_equation.target.next_to(morty, UL) fe_rect = SurroundingRectangle(false_equation.target) fe_rect.set_color(GREY_BROWN) cross = Cross(false_equation.target[1]) cross.insert_n_curves(1) cross.set_stroke(RED, width=[1, 5, 1]) nonsense = Text("This would be nonsense") nonsense.match_width(fe_rect) nonsense.next_to(fe_rect, UP) nonsense.set_color(RED) randy.bubble = bubble self.play( MoveToTarget(false_equation), RemovePiCreatureBubble(randy, target_mode="hesitant"), morty.animate.set_opacity(1).change("raise_right_hand"), ShowCreation(fe_rect), ) self.play( ShowCreation(cross), FadeIn(nonsense), ) self.play(Blink(morty)) self.wait() false_group = VGroup(false_equation, fe_rect, cross, nonsense) # Show Taylor series real_equation = OldTex( "e^x = x^0 + x^1 + \\frac{1}{2} x^2 + \\frac{1}{6} x^3 + \\cdots + \\frac{1}{n!} x^n + \\cdots", isolate=["x"] ) xs = real_equation.get_parts_by_tex("x") xs.set_color(YELLOW) real_equation.set_width(FRAME_WIDTH - 2.0) real_equation.to_edge(UP) real_rhs = real_equation[3:] real_label = Text("Real number", color=YELLOW, font_size=24) # real_label.next_to(xs[0], DOWN, buff=0.8) # real_label.to_edge(LEFT, buff=MED_SMALL_BUFF) # real_arrow = Arrow(real_label, xs[0], buff=0.1, fill_color=GREY_B, thickness=0.025) real_label.to_corner(UL, buff=MED_SMALL_BUFF) real_arrow = Arrow(real_label, real_equation[1], buff=0.1) taylor_brace = Brace(real_rhs, DOWN) taylor_label = taylor_brace.get_text("Taylor series") self.play( TransformFromCopy(base, real_equation[0]), FadeTransform(matrix.copy(), real_equation[1]), FadeIn(real_label, UR), GrowArrow(real_arrow), randy.change("thinking", real_label), morty.animate.look_at(real_label), ) self.wait() self.play( Write(real_equation[2], lag_ratio=0.2), FadeTransformPieces(xs[:1].copy(), xs[1:], path_arc=20 * DEGREES), LaggedStart(*( FadeIn(part) for part in real_equation[4:] if part not in xs )), randy.change("pondering", real_equation), morty.change("pondering", real_equation), ) self.add(real_equation) self.play(Blink(morty)) self.play( false_group.animate.scale(0.7).to_edge(DOWN), GrowFromCenter(taylor_brace), FadeIn(taylor_label, 0.5 * DOWN) ) self.wait() # Taylor series example ex_rhs = OldTex( """ {2}^0 + {2}^1 + { {2}^2 \\over 2} + { {2}^3 \\over 6} + { {2}^4 \\over 24} + { {2}^5 \\over 120} + { {2}^6 \\over 720} + { {2}^7 \\over 5040} + \\cdots """, tex_to_color_map={"{2}": YELLOW, "+": WHITE}, ) ex_rhs.next_to(real_equation[3:], DOWN, buff=0.75) ex_parts = VGroup(*( ex_rhs[i:j] for i, j in [ (0, 2), (3, 5), (6, 8), (9, 11), (12, 14), (15, 17), (18, 20), (21, 23), (24, 25), ] )) term_brace = Brace(ex_parts[0], DOWN) frac = OldTex("1", font_size=36) frac.next_to(term_brace, DOWN, SMALL_BUFF) rects = VGroup(*( Rectangle(height=2**n / math.factorial(n), width=1) for n in range(11) )) rects.arrange(RIGHT, buff=0, aligned_edge=DOWN) rects.set_fill(opacity=1) rects.set_submobject_colors_by_gradient(BLUE, GREEN) rects.set_stroke(WHITE, 1) rects.set_width(7) rects.to_edge(DOWN) self.play( ReplacementTransform(taylor_brace, term_brace), FadeTransform(real_equation[3:].copy(), ex_rhs), FadeOut(false_group, shift=DOWN), FadeOut(taylor_label, shift=DOWN), FadeIn(frac), ) term_values = VGroup() for n in range(11): rect = rects[n] fact = math.factorial(n) ex_part = ex_parts[min(n, len(ex_parts) - 1)] value = DecimalNumber(2**n / fact) value.set_color(GREY_A) max_width = 0.6 * rect.get_width() if value.get_width() > max_width: value.set_width(max_width) value.next_to(rects[n], UP, SMALL_BUFF) new_brace = Brace(ex_part, DOWN) if fact == 1: new_frac = OldTex(f"{2**n}", font_size=36) else: new_frac = OldTex(f"{2**n} / {fact}", font_size=36) new_frac.next_to(new_brace, DOWN, SMALL_BUFF) self.play( term_brace.animate.become(new_brace), FadeTransform(frac, new_frac), ) frac = new_frac rect.save_state() rect.stretch(0, 1, about_edge=DOWN) rect.set_opacity(0) value.set_value(0) self.play( Restore(rect), ChangeDecimalToValue(value, 2**n / math.factorial(n)), UpdateFromAlphaFunc(value, lambda m, a: m.next_to(rect, UP, SMALL_BUFF).set_opacity(a)), randy.animate.look_at(rect), morty.animate.look_at(rect), ) term_values.add(value) self.play(FadeOut(frac)) new_brace = Brace(ex_rhs, DOWN) sum_value = DecimalNumber(math.exp(2), num_decimal_places=4, font_size=36) sum_value.next_to(new_brace, DOWN) self.play( term_brace.animate.become(new_brace), randy.change("thinking", sum_value), morty.change("tease", sum_value), *(FadeTransform(dec.copy().set_opacity(0), sum_value) for dec in term_values) ) self.play(Blink(randy)) lhs = OldTex("e \\cdot e =") lhs.match_height(real_equation[0]) lhs.next_to(ex_rhs, LEFT) self.play(Write(lhs)) self.play(Blink(morty)) self.play(Blink(randy)) # Increment input twos = ex_rhs.get_parts_by_tex("{2}") threes = VGroup(*( OldTex("3").set_color(YELLOW).replace(two) for two in twos )) new_lhs = OldTex("e \\cdot e \\cdot e = ") new_lhs.match_height(lhs) new_lhs[0].space_out_submobjects(0.8) new_lhs[0][-1].shift(SMALL_BUFF * RIGHT) new_lhs.move_to(lhs, RIGHT) anims = [] unit_height = 0.7 * rects[0].get_height() for n, rect, value_mob in zip(it.count(0), rects, term_values): rect.generate_target() new_value = 3**n / math.factorial(n) rect.target.set_height(unit_height * new_value, stretch=True, about_edge=DOWN) value_mob.rect = rect anims += [ MoveToTarget(rect), ChangeDecimalToValue(value_mob, new_value), UpdateFromFunc(value_mob, lambda m: m.next_to(m.rect, UP, SMALL_BUFF)) ] self.play( FadeOut(twos, 0.5 * UP), FadeIn(threes, 0.5 * UP), ) twos.set_opacity(0) self.play( ChangeDecimalToValue(sum_value, math.exp(3)), *anims, ) self.play( FadeOut(lhs, 0.5 * UP), FadeIn(new_lhs, 0.5 * UP), ) self.wait() # Isolate polynomial real_lhs = VGroup(real_equation[:3], real_label, real_arrow) self.play( LaggedStartMap(FadeOut, VGroup( *new_lhs, *threes, *ex_rhs, term_brace, sum_value, *rects, *term_values, )), real_lhs.animate.set_opacity(0.2), randy.change("erm", real_equation), morty.change("thinking", real_equation), run_time=1, ) self.play(Blink(morty)) # Alternate inputs rhs_tex = "X^0 + X^1 + \\frac{1}{2} X^2 + \\frac{1}{6} X^3 + \\cdots + \\frac{1}{n!} X^n + \\cdots" pii_rhs = OldTex( rhs_tex.replace("X", "(\\pi i)"), tex_to_color_map={"(\\pi i)": BLUE}, ) pii_rhs.match_width(real_rhs) mat_tex = "\\left[ \\begin{array}{ccc} 3 & 1 & 4 \\\\ 1 & 5 & 9 \\\\ 2 & 6 & 5 \\end{array} \\right]" mat_rhs = OldTex( rhs_tex.replace("X", mat_tex), tex_to_color_map={mat_tex: TEAL}, ) mat_rhs.scale(0.5) pii_rhs.next_to(real_rhs, DOWN, buff=0.7) mat_rhs.next_to(pii_rhs, DOWN, buff=0.7) self.play(FlashAround(real_rhs)) self.wait() self.play( morty.change("raise_right_hand", pii_rhs), FadeTransformPieces(real_rhs.copy(), pii_rhs), ) self.play(Blink(randy)) self.play( FadeTransformPieces(real_rhs.copy(), mat_rhs), ) self.play( randy.change("maybe", mat_rhs), ) self.wait() why = Text("Why?", font_size=36) why.next_to(randy, UP, aligned_edge=LEFT) self.play( randy.change("confused", mat_rhs.get_corner(UL)), Write(why), ) self.play(Blink(randy)) reassurance = VGroup( Text("I know it looks complicated.", font_size=24), Text("Don't panic.", font_size=24), ) reassurance.arrange(DOWN) reassurance.next_to(morty, LEFT, aligned_edge=UP) reassurance.set_color(GREY_A) for words in reassurance: self.play(FadeIn(words)) self.play(Blink(morty)) # Describe exp to_right_group = VGroup(real_lhs, real_rhs, mat_rhs, pii_rhs) to_right_group.generate_target() to_right_group.target.to_edge(RIGHT, buff=SMALL_BUFF) to_right_group.target[2].to_edge(RIGHT, buff=SMALL_BUFF) self.play( MoveToTarget(to_right_group), FadeOut(why), FadeOut(reassurance), randy.change("pondering", mat_rhs), morty.change("tease"), ) pii_lhs = OldTex("\\text{exp}\\left(\\pi i \\right) = ")[0] pii_lhs.next_to(pii_rhs, LEFT) mat_lhs = OldTex("\\text{exp}\\left(" + mat_tex + "\\right) = ")[0] mat_lhs.match_height(mat_rhs) mat_lhs[:3].match_height(pii_lhs[:3]) mat_lhs[:3].next_to(mat_lhs[3:5], LEFT, SMALL_BUFF) mat_lhs.next_to(mat_rhs, LEFT) pii_lhs_pi_part = pii_lhs[4:6] pii_lhs_pi_part.set_color(BLUE) mat_lhs_mat_part = mat_lhs[5:18] mat_lhs_mat_part.set_color(TEAL) self.play( FadeIn(pii_lhs), randy.change("thinking", pii_lhs), randy.change("tease", pii_lhs), ) self.play(FadeIn(mat_lhs)) self.play(Blink(randy)) self.play( LaggedStart( FlashAround(pii_lhs[:3]), FlashAround(mat_lhs[:3]), lag_ratio=0.3, run_time=2 ), randy.change("raise_left_hand", pii_lhs), ) self.wait() # Transition to e^x notation crosses = VGroup(*( Cross(lhs[:3], stroke_width=[0, 3, 3, 3, 0]).scale(1.3) for lhs in [pii_lhs, mat_lhs] )) bases = VGroup() powers = VGroup() equals = VGroup() for part, lhs in (pii_lhs_pi_part, pii_lhs), (mat_lhs_mat_part, mat_lhs): power = part.copy() part.set_opacity(0) self.add(power) base = OldTex("e", font_size=60) equal = OldTex(":=") power.generate_target() if power.target.get_height() > 0.7: power.target.set_height(0.7) power.target.next_to(base, UR, buff=0.05) group = VGroup(base, power.target, equal) equal.next_to(group[:2], RIGHT, MED_SMALL_BUFF) equal.match_y(base) if lhs is mat_lhs: equal.shift(0.1 * UP) group.shift(lhs.get_right() - equal.get_right()) bases.add(base) powers.add(power) equals.add(equal) self.play( ShowCreation(crosses), randy.change("hesitant", crosses), ) self.play(Blink(randy)) self.play(real_lhs.animate.set_opacity(1)) self.play( FadeOut(pii_lhs), FadeOut(mat_lhs), FadeOut(crosses), *(MoveToTarget(power) for power in powers), *(TransformFromCopy(real_equation[0], base) for base in bases), Write(equals), randy.change("sassy", powers), ) self.wait() # Theorem vs. definition real_part = VGroup(real_lhs, real_rhs) pii_part = VGroup(bases[0], powers[0], equals[0], pii_rhs) mat_part = VGroup(bases[1], powers[1], equals[1], mat_rhs) def_parts = VGroup(pii_part, mat_part) self.play( FadeOut(randy, DOWN), FadeOut(morty, DOWN), real_part.animate.set_x(0).shift(DOWN), def_parts.animate.set_x(0).to_edge(DOWN), ) real_rect = SurroundingRectangle(real_part) real_rect.set_stroke(YELLOW, 2) theorem_label = Text("Theorem") theorem_label.next_to(real_rect, UP) def_rect = SurroundingRectangle(def_parts) def_rect.set_stroke(BLUE, 2) def_label = Text("Definition") def_label.next_to(def_rect, UP) self.play( ShowCreation(real_rect), FadeIn(theorem_label, 0.5 * UP), ) self.wait() self.play( ShowCreation(def_rect), FadeIn(def_label, 0.5 * UP), ) self.wait() # Abuse? Or the beauty of discovery... randy2 = Randolph() randy2.set_height(1.5) randy2.next_to(def_rect, UP, SMALL_BUFF, aligned_edge=LEFT) self.play( ApplyMethod(randy2.change, "angry", mat_rhs), UpdateFromAlphaFunc(randy2, lambda m, a: m.set_opacity(a)), ) self.play(Blink(randy2)) discovery_label = Text("Discovery") discovery_label.move_to(theorem_label, DOWN) invention_label = Text("Invention") invention_label.move_to(def_label, DOWN) self.play( FadeOut(theorem_label, UP), FadeIn(discovery_label, UP), randy2.change("hesitant", theorem_label), ) self.play( FadeOut(def_label, UP), FadeIn(invention_label, UP), ) self.wait(2) # Isolate matrix right hand side to_fade = VGroup( randy2, discovery_label, invention_label, real_rect, def_rect, real_arrow, real_label, real_part, pii_part, bases, powers, equals, ) self.play( mat_rhs.animate.set_width(FRAME_WIDTH - 1).center().to_edge(UP), LaggedStartMap(FadeOut, to_fade), FadeIn(VGroup(randy, morty), run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1)) ) # Matrix powers mat = mat_rhs[4] mat_brace = Brace(VGroup(mat, mat_rhs[5][0]), DOWN, buff=SMALL_BUFF) matrix = np.array([[3, 1, 4], [1, 5, 9], [2, 6, 5]]) matrix_square = np.dot(matrix, matrix) result = IntegerMatrix(matrix_square, h_buff=1.3, v_buff=0.7) result.match_height(mat) square_eq = VGroup(mat.copy(), mat.copy(), OldTex("="), result) square_eq.arrange(RIGHT, buff=SMALL_BUFF) square_eq.next_to(mat_brace, DOWN) self.play(GrowFromCenter(mat_brace)) self.play( LaggedStart( TransformFromCopy(mat, square_eq[0], path_arc=45 * DEGREES), TransformFromCopy(mat, square_eq[1]), Write(square_eq[2]), Write(result.brackets), ), randy.change("pondering", square_eq), ) self.show_mat_mult(matrix, matrix, square_eq[0][2:11], square_eq[1][2:11], result.elements) # Show matrix cubed mat_brace.generate_target() mat_brace.target.next_to(mat_rhs[6], DOWN, SMALL_BUFF) mat_squared = result mat_cubed = IntegerMatrix( np.dot(matrix, matrix_square), h_buff=1.8, v_buff=0.7, element_alignment_corner=ORIGIN, ) mat_cubed.match_height(mat) cube_eq = VGroup( VGroup(mat.copy(), mat.copy(), mat.copy()).arrange(RIGHT, buff=SMALL_BUFF), OldTex("=").rotate(90 * DEGREES), VGroup(mat.copy(), mat_squared.deepcopy()).arrange(RIGHT, buff=SMALL_BUFF), OldTex("=").rotate(90 * DEGREES), mat_cubed ) cube_eq.arrange(DOWN) cube_eq.next_to(mat_brace.target, DOWN) self.play( MoveToTarget(mat_brace), ReplacementTransform(square_eq[0], cube_eq[0][1]), ReplacementTransform(square_eq[1], cube_eq[0][2]), ReplacementTransform(square_eq[2], cube_eq[1]), ReplacementTransform(square_eq[3], cube_eq[2][1]), randy.change("happy", cube_eq), ) self.play( LaggedStart( FadeIn(cube_eq[0][0]), FadeIn(cube_eq[2][0]), FadeIn(cube_eq[3]), FadeIn(cube_eq[4].brackets), ), randy.change("tease", cube_eq), ) self.show_mat_mult( matrix, matrix_square, cube_eq[2][0][2:11], cube_eq[2][1].get_entries(), cube_eq[4].get_entries(), 0.1, 0.1, ) self.play(Blink(morty)) # Scaling example_matrix = Matrix([ ["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ]) example_scaled_matrix = Matrix([ ["a / n!", "b / n!", "c / n!"], ["d / n!", "e / n!", "f / n!"], ["g / n!", "h / n!", "i / n!"], ]) factor = OldTex("1 \\over n!") factor.scale(1.5) factor.next_to(example_matrix, LEFT, MED_SMALL_BUFF) self.play( LaggedStartMap(FadeOut, VGroup(mat_brace, *cube_eq[:-1])), FadeIn(factor), FadeTransformPieces(cube_eq[-1], example_matrix), ) self.wait() self.play( TransformMatchingShapes( VGroup(*factor, *example_matrix), example_scaled_matrix, ), randy.change("pondering", example_scaled_matrix), ) self.wait() # Adding mat1 = np.array([[2, 7, 1], [8, 2, 8], [1, 8, 2]]) mat2 = np.array([[8, 4, 5], [9, 0, 4], [5, 2, 3]]) sum_eq = VGroup( IntegerMatrix(mat1), OldTex("+"), IntegerMatrix(mat2), OldTex("="), Matrix( np.array([ f"{m1} + {m2}" for m1, m2 in zip(mat1.flatten(), mat2.flatten()) ]).reshape((3, 3)), h_buff=1.8, ) ) sum_eq.set_height(1.5) sum_eq.arrange(RIGHT) sum_eq.center() self.play( FadeOut(example_scaled_matrix, UP), FadeIn(sum_eq[:-1], UP), FadeIn(sum_eq[-1].brackets, UP), morty.change("raise_right_hand", sum_eq), randy.change("thinking", sum_eq), ) last_rects = VGroup() for e1, e2, e3 in zip(sum_eq[0].elements, sum_eq[2].elements, sum_eq[4].elements): rects = VGroup(SurroundingRectangle(e1), SurroundingRectangle(e2)) self.add(e3, rects) self.play(FadeOut(last_rects), run_time=0.2) self.wait(0.1) last_rects = rects self.play(FadeOut(last_rects)) # Ask about infinity bubble = randy.get_bubble(OldTexText("But...going\\\\to $\\infty$?")) bubble.shift(SMALL_BUFF * RIGHT) self.play( Write(bubble), Write(bubble.content), FadeOut(sum_eq, UP), randy.change("sassy", mat_rhs), morty.change("guilty", randy.eyes), ) self.play(Blink(randy)) self.wait() self.play( FadeOut(bubble), bubble.content.animate.next_to(randy, RIGHT, aligned_edge=UP), randy.change("pondering", mat_rhs), morty.change("pondering", mat_rhs), ) # Replace matrix pi_mat_tex = "" pi_mat_tex = "\\left[ \\begin{array}{cc} 0 & -\\pi \\\\ \\pi & 0 \\end{array} \\right]" pi_mat_rhs = OldTex( rhs_tex.replace("X", pi_mat_tex), tex_to_color_map={pi_mat_tex: BLUE}, ) pi_mat_rhs.match_width(mat_rhs) pi_mat_rhs.move_to(mat_rhs) pi_mat = pi_mat_rhs.get_part_by_tex(pi_mat_tex).copy() pi_mat.scale(1.5) pi_mat.next_to(morty, UL) self.play( morty.change("raise_right_hand"), FadeIn(pi_mat, UP) ) self.play(Blink(morty)) self.play( FadeTransformPieces(mat_rhs, pi_mat_rhs), Transform( VGroup(pi_mat), pi_mat_rhs.get_parts_by_tex(pi_mat_tex), remover=True, ), morty.change("tease"), ) self.wait() # Show various partial sum values matrix = np.array([[0, -np.pi], [np.pi, 0]]) curr_matrix = np.identity(2) curr_sum = np.identity(2) curr_sum_mob = IntegerMatrix(curr_matrix) curr_sum_mob.set_height(1.5) mat_parts = pi_mat_rhs.get_parts_by_tex(pi_mat_tex) brace = Brace(mat_parts[0], DOWN) brace.stretch(1.1, 0, about_edge=LEFT) curr_sum_mob.next_to(brace, DOWN) curr_sum_mob.shift_onto_screen() self.play( GrowFromCenter(brace), FadeTransform(mat_parts[0].copy(), curr_sum_mob), randy.change("erm", curr_sum_mob), ) self.wait() last_n_label = VMobject() partial_sum_mobs = [curr_sum_mob] for n in range(1, 18): if n < 5: new_brace = Brace(mat_parts[:n + 1]) new_brace.set_width(new_brace.get_width() + 0.2, about_edge=LEFT) brace.generate_target() brace.target.become(new_brace) anims = [ MoveToTarget(brace), ] else: n_label = OldTex(f"n = {n}", font_size=24) n_label.next_to(brace.get_corner(DR), DL, SMALL_BUFF) anims = [ FadeIn(n_label), FadeOut(last_n_label), ] last_n_label = n_label curr_matrix = np.dot(curr_matrix, matrix) / n curr_sum += curr_matrix nd = min(n + 1, 4) if n < 2: h_buff = 1.3 else: sample = DecimalMatrix(curr_sum[0], num_decimal_places=nd) sample.replace(curr_sum_mob.get_entries()[0], 1) h_buff = 1.3 * sample.get_width() new_sum_mob = DecimalMatrix( curr_sum, element_alignment_corner=RIGHT, element_to_mobject_config={ "num_decimal_places": nd, "font_size": 36, }, h_buff=h_buff, ) new_sum_mob.match_height(curr_sum_mob) new_sum_mob.next_to(brace.target, DOWN) self.play( FadeOut(curr_sum_mob), FadeIn(new_sum_mob), randy.animate.look_at(new_sum_mob), *anims, run_time=(1 if n < 5 else 1 / 60) ) self.wait() curr_sum_mob = new_sum_mob partial_sum_mobs.append(new_sum_mob) self.play( FadeOut(last_n_label), randy.change("confused", curr_sum_mob), ) # Ask why why = Text("Why?") why.move_to(bubble.content, UL) epii = OldTex("e^{\\pi i} = -1") epii.next_to(morty, UL) later_text = Text("...but that comes later", font_size=24) later_text.set_color(GREY_A) later_text.next_to(epii, DOWN, aligned_edge=RIGHT) self.play( randy.change("maybe"), FadeIn(why, UP), FadeOut(bubble.content, UP), ) self.wait() self.play( morty.change("raise_right_hand"), FadeIn(epii, UP), ) self.play(Blink(morty)) self.play( Write(later_text, run_time=1), randy.change("hesitant", morty.eyes) ) # Show partial sums new_mat_rhs = OldTex( rhs_tex.replace("X", mat_tex), tex_to_color_map={mat_tex: TEAL}, isolate=["+"] ) new_mat_rhs.replace(mat_rhs) self.play( FadeOut(pi_mat_rhs), FadeIn(new_mat_rhs), FadeOut(new_sum_mob, DOWN), brace.animate.become(Brace(new_mat_rhs, DOWN)), LaggedStartMap( FadeOut, VGroup( why, epii, later_text, ), shift=DOWN, ), randy.change("pondering", new_mat_rhs), morty.change("pondering", new_mat_rhs), ) matrix = np.array([[3, 1, 4], [1, 5, 9], [2, 6, 5]]) partial_sum_mobs = VGroup() curr_matrix = np.identity(3) partial_sum = np.array(curr_matrix) for n in range(50): psm = DecimalMatrix( partial_sum, element_to_mobject_config={"num_decimal_places": 2}, element_alignment_corner=ORIGIN, h_buff=1.5 * DecimalNumber(partial_sum[0, 0]).get_width(), v_buff=1.0, ) psm.next_to(brace, DOWN, MED_LARGE_BUFF) partial_sum_mobs.add(psm) curr_matrix = np.dot(curr_matrix, matrix) / (n + 1) partial_sum += curr_matrix new_mat_rhs[2:].set_opacity(0.1) self.add(partial_sum_mobs[0]) self.wait(0.5) for n, k in zip(it.count(1), [5, 9, 13, 19, 21]): self.remove(partial_sum_mobs[n - 1]) self.add(partial_sum_mobs[n]) new_mat_rhs[:k].set_opacity(1) self.wait(0.5) brace.become(Brace(new_mat_rhs, DOWN)) n_label = VGroup(OldTex("n = "), Integer(n)) n_label[1].set_height(n_label[0].get_height() * 1.2) n_label.arrange(RIGHT, SMALL_BUFF) n_label.set_color(GREY_B) n_label.next_to(brace.get_corner(DR), DL, SMALL_BUFF) self.add(n_label) for n in range(6, 50): self.remove(partial_sum_mobs[n - 1]) self.add(partial_sum_mobs[n]) n_label[1].set_value(n) n_label[1].set_color(GREY_B) n_label[1].next_to(n_label[0], RIGHT, SMALL_BUFF) self.wait(0.1) self.play( randy.change("erm"), morty.change("tease"), # LaggedStartMap( # FadeOut, VGroup(brace, n_label, partial_sum_mobs[n]), # shift=DOWN, # ) ) self.play(Blink(morty)) self.play(Blink(randy)) self.wait() def show_mat_mult(self, m1, m2, m1_terms, m2_terms, rhs_terms, per_term=0.1, between_terms=0.35): dim = m1.shape[0] m1_color = m1_terms[0].get_fill_color() m2_color = m2_terms[0].get_fill_color() for n in range(dim * dim): i = n // dim j = n % dim row = m1_terms[dim * i:dim * i + dim] col = m2_terms[j::dim] row_rect = SurroundingRectangle(row, buff=0.05) col_rect = SurroundingRectangle(col, buff=0.05) row_rect.set_stroke(YELLOW, 2) col_rect.set_stroke(YELLOW, 2) right_elem = Integer(0, edge_to_fix=ORIGIN) right_elem.replace(rhs_terms[n], dim_to_match=1) right_elem.set_value(0) self.add(row_rect, col_rect, right_elem) for k in range(dim): self.wait(per_term) right_elem.increment_value(m1[i, k] * m2[k, j]) right_elem.scale(rhs_terms[0][0].get_height() / right_elem[-1].get_height()) row[k].set_color(YELLOW) col[k].set_color(YELLOW) self.remove(right_elem) self.add(rhs_terms[n]) self.wait(between_terms) m1_terms.set_color(m1_color) m2_terms.set_color(m2_color) self.remove(row_rect, col_rect) class ShowHigherMatrixPowers(IntroduceTheComputation): matrix = [[3, 1, 4], [1, 5, 9], [2, 6, 5]] per_term = 0.1 between_terms = 0.1 N_powers = 10 def construct(self): # Show many matrix powers def get_mat_mob(matrix): term = Integer(matrix[0, 0]) return IntegerMatrix( matrix, h_buff=max(0.8 + 0.3 * len(term), 1.0) ) N = self.N_powers matrix = np.matrix(self.matrix) matrix_powers = [np.identity(len(matrix)), matrix] for x in range(N): matrix_powers.append(np.dot(matrix, matrix_powers[-1])) mat_mobs = [get_mat_mob(mat) for mat in matrix_powers] for mob in mat_mobs: mob.set_height(1) mat_mobs[1].set_color(TEAL) equation = VGroup( mat_mobs[1].deepcopy(), Integer(2, font_size=18), OldTex("="), mat_mobs[1].deepcopy(), mat_mobs[1].deepcopy(), OldTex("="), mat_mobs[2].deepcopy() ) equation.arrange(RIGHT) equation.to_edge(LEFT) equation[1].set_y(equation[0].get_top()[1]) equation[0].set_x(equation[1].get_left()[0] - SMALL_BUFF, RIGHT) self.add(equation) exp = equation[1] m1, m2, eq, rhs = equation[-4:] self.remove(*rhs.get_entries()) for n in range(3, N): self.show_mat_mult( matrix_powers[1], matrix_powers[n - 2], m1.get_entries(), m2.get_entries(), rhs.get_entries(), between_terms=self.between_terms, per_term=self.per_term ) self.wait(0.5) rhs.generate_target() eq.generate_target() rhs.target.move_to(m2, LEFT) eq.target.next_to(rhs.target, RIGHT) new_rhs = mat_mobs[n].deepcopy() new_rhs.next_to(eq.target, RIGHT) new_exp = Integer(n) new_exp.replace(exp, dim_to_match=1) self.play( MoveToTarget(rhs, path_arc=PI / 2), MoveToTarget(eq), FadeOut(m2, DOWN), FadeIn(new_rhs.get_brackets()), FadeIn(new_exp, 0.5 * DOWN), FadeOut(exp, 0.5 * DOWN), ) m2, rhs = rhs, new_rhs exp = new_exp class Show90DegreePowers(ShowHigherMatrixPowers): matrix = [[0, -1], [1, 0]] per_term = 0.0 between_terms = 0.2 N_powers = 16 class WhyTortureMatrices(TeacherStudentsScene): def construct(self): self.play_student_changes( "maybe", "confused", "erm", look_at=self.screen, ) q_marks = VGroup() for student in self.students: marks = OldTex("???") marks.next_to(student, UP) q_marks.add(marks) self.play(FadeIn(q_marks, 0.25 * UP, lag_ratio=0.1, run_time=2)) self.wait(2) self.student_says( OldTexText("Why...would you\\\\ever want\\\\to do that?"), index=2, added_anims=[FadeOut(q_marks)], ) self.play( self.change_students("confused", "pondering", "raise_left_hand", look_at=self.screen), self.teacher.change("tease", self.screen) ) self.wait(2) self.play(self.students[0].change("erm")) self.wait(7) class DefinitionFirstVsLast(Scene): show_love_and_quantum = True def construct(self): # Setup objects top_title = Text("Textbook progression") low_title = Text("Discovery progression") top_prog = VGroup( OldTexText("Definition", color=BLUE), OldTexText("Theorem"), OldTexText("Proof"), OldTexText("Examples"), ) low_prog = VGroup( OldTexText("Specific\n\nproblem"), OldTexText("General\n\nproblems"), OldTexText("Helpful\n\nconstructs"), OldTexText("Definition", color=BLUE), ) progs = VGroup(top_prog, low_prog) for progression in progs: progression.arrange(RIGHT, buff=1.2) progs.arrange(DOWN, buff=3) progs.set_width(FRAME_WIDTH - 2) for progression in progs: arrows = VGroup() for m1, m2 in zip(progression[:-1], progression[1:]): arrows.add(Arrow(m1, m2)) progression.arrows = arrows top_dots = OldTex("\\dots", font_size=72) top_dots.next_to(top_prog.arrows[0], RIGHT) low_dots = top_dots.copy() low_dots.next_to(low_prog.arrows[-1], LEFT) top_rect = SurroundingRectangle(top_prog, buff=MED_SMALL_BUFF) top_rect.set_stroke(TEAL, 2) top_title.next_to(top_rect, UP) top_title.match_color(top_rect) low_rect = SurroundingRectangle(low_prog, buff=MED_SMALL_BUFF) low_rect.set_stroke(YELLOW, 2) low_title.next_to(low_rect, UP) low_title.match_color(low_rect) versus = Text("vs.") # Show progressions self.add(top_prog[0]) self.play( GrowArrow(top_prog.arrows[0]), FadeIn(top_dots, 0.2 * RIGHT, lag_ratio=0.1), ) self.wait() kw = {"path_arc": -90 * DEGREES} self.play( LaggedStart( TransformFromCopy(top_prog[0], low_prog[-1], **kw), TransformFromCopy(top_prog.arrows[0], low_prog.arrows[-1], **kw), TransformFromCopy(top_dots, low_dots, **kw), ), Write(versus) ) self.wait() self.play( ShowCreation(top_rect), FadeIn(top_title, 0.25 * UP) ) self.play( FadeOut(top_dots), FadeIn(top_prog[1]), ) for arrow, term in zip(top_prog.arrows[1:], top_prog[2:]): self.play( GrowArrow(arrow), FadeIn(term, shift=0.25 * RIGHT), ) self.wait() self.play( ShowCreation(low_rect), FadeIn(low_title, 0.25 * UP), versus.animate.move_to(midpoint(low_title.get_top(), top_rect.get_bottom())), ) self.wait() self.play(FadeIn(low_prog[0])) self.play( GrowArrow(low_prog.arrows[0]), FadeIn(low_prog[1], shift=0.25 * RIGHT), ) self.play( GrowArrow(low_prog.arrows[1]), FadeIn(low_prog[2], shift=0.25 * RIGHT), FadeOut(low_dots), ) self.wait() # Highlight specific example full_rect = FullScreenRectangle() full_rect.set_fill(BLACK, opacity=0.75) sp, gp, hc = low_prog[:3].copy() self.add(full_rect, sp) self.play(FadeIn(full_rect)) self.wait() # Go to general if not self.show_love_and_quantum: self.play(FadeIn(gp)) self.play(FlashAround(gp, color=BLUE, run_time=2)) self.wait() return # Love and quantum love = SVGMobject("hearts") love.set_height(1) love.set_fill(RED, 1) love.set_stroke(MAROON_B, 1) quantum = OldTex("|\\psi\\rangle") quantum.set_color(BLUE) quantum.match_height(love) group = VGroup(quantum, love) group.arrange(RIGHT, buff=MED_LARGE_BUFF) group.next_to(sp, UP, MED_LARGE_BUFF) love.save_state() love.match_x(sp) self.play(Write(love)) self.wait() self.play( Restore(love), FadeIn(quantum, 0.5 * LEFT) ) self.wait() self.play( love.animate.center().scale(1.5), FadeOut(quantum), FadeOut(sp), full_rect.animate.set_fill(opacity=1) ) self.wait() class DefinitionFirstVsLastGP(DefinitionFirstVsLast): show_love_and_quantum = False class RomeoAndJuliet(Scene): def construct(self): # Add Romeo and Juliet romeo, juliet = lovers = self.get_romeo_and_juliet() lovers.set_height(2) lovers.arrange(LEFT, buff=1) lovers.move_to(0.5 * DOWN) self.add(*lovers) self.make_romeo_and_juliet_dynamic(romeo, juliet) romeo.love_tracker.set_value(1.5) juliet.love_tracker.set_value(1.5) get_romeo_juilet_name_labels(lovers) for creature in lovers: self.play( creature.love_tracker.animate.set_value(2.5), Write(creature.name_label, run_time=1), ) self.wait() # Add their scales juliet_scale = self.get_love_scale(juliet, LEFT, "x", BLUE_B) romeo_scale = self.get_love_scale(romeo, RIGHT, "y", BLUE) scales = [juliet_scale, romeo_scale] scale_labels = VGroup( OldTexText("Juliet's love for Romeo", font_size=30), OldTexText("Romeo's love for Juliet", font_size=30), ) scale_arrows = VGroup() for scale, label in zip(scales, scale_labels): var = scale[2][0][0] label.next_to(var, UP, buff=0.7) arrow = Arrow(var, label, buff=0.1, thickness=0.025) scale_arrows.add(arrow) label.set_color(var.get_fill_color()) for lover, scale, arrow, label, final_love in zip(reversed(lovers), scales, scale_arrows, scale_labels, [1, -1]): self.add(scale) self.play(FlashAround(scale[2][0][0])) self.play( lover.love_tracker.animate.set_value(5), GrowArrow(arrow), FadeIn(label, 0.5 * UP), ) self.play(lover.love_tracker.animate.set_value(final_love), run_time=2) self.wait() # Juliet's rule frame = self.camera.frame equations = VGroup( OldTex("{dx \\over dt} {{=}} -{{y(t)}}"), OldTex("{dy \\over dt} {{=}} {{x(t)}}"), ) juliet_eq, romeo_eq = equations juliet_eq.next_to(scale_labels[0], UR) juliet_eq.shift(0.5 * UP) self.play( frame.animate.move_to(0.7 * UP), Write(equations[0]), ) self.wait() self.play(FlashAround(juliet_eq[0])) self.wait() y_rect = SurroundingRectangle(juliet_eq.get_parts_by_tex("y(t)"), buff=0.05) y_rect_copy = y_rect.copy() y_rect_copy.replace(romeo.scale_mob.dot, stretch=True) self.play(FadeIn(y_rect)) self.wait() self.play(TransformFromCopy(y_rect, y_rect_copy)) y_rect_copy.add_updater(lambda m: m.move_to(romeo.scale_mob.dot)) self.wait() self.play(romeo.love_tracker.animate.set_value(-3)) big_arrow = Arrow( juliet.scale_mob.number_line.get_bottom(), juliet.scale_mob.number_line.get_top(), ) big_arrow.set_color(GREEN) big_arrow.next_to(juliet.scale_mob.number_line, LEFT) self.play( FadeIn(big_arrow), ApplyMethod(juliet.love_tracker.set_value, 5, run_time=3, rate_func=linear), ) self.wait() self.play(romeo.love_tracker.animate.set_value(5)) self.play( big_arrow.animate.rotate(PI).set_color(RED), path_arc=PI, run_time=0.5, ) self.play(juliet.love_tracker.animate.set_value(-5), rate_func=linear, run_time=5) self.play(FadeOut(y_rect), FadeOut(y_rect_copy)) # Romeo's rule romeo_eq.next_to(scale_labels[1], UL) romeo_eq.shift(0.5 * UP) self.play( juliet_eq.animate.to_edge(LEFT), FadeOut(big_arrow), ) self.play(FadeIn(romeo_eq, UP)) self.wait() dy_rect = SurroundingRectangle(romeo_eq.get_part_by_tex("dy")) x_rect = SurroundingRectangle(romeo_eq.get_part_by_tex("x(t)"), buff=0.05) x_rect_copy = x_rect.copy() x_rect_copy.replace(juliet.scale_mob.dot, stretch=True) self.play(ShowCreation(dy_rect)) self.wait() self.play(TransformFromCopy(dy_rect, x_rect)) self.play(TransformFromCopy(x_rect, x_rect_copy)) self.wait() big_arrow.next_to(romeo.scale_mob.number_line, RIGHT) self.play(FadeIn(big_arrow), LaggedStartMap(FadeOut, VGroup(dy_rect, x_rect))) self.play(romeo.love_tracker.animate.set_value(-3), run_time=4, rate_func=linear) x_rect_copy.add_updater(lambda m: m.move_to(juliet.scale_mob.dot)) juliet.love_tracker.set_value(5) self.wait() self.play( big_arrow.animate.rotate(PI).set_color(GREEN), path_arc=PI, run_time=0.5, ) self.play(romeo.love_tracker.animate.set_value(5), rate_func=linear, run_time=5) self.play(FadeOut(x_rect_copy)) self.wait() # Show constant change left_arrow = Arrow(UP, DOWN) left_arrow.character = juliet left_arrow.get_rate = lambda: -romeo.love_tracker.get_value() right_arrow = Arrow(DOWN, UP) right_arrow.character = romeo right_arrow.get_rate = lambda: juliet.love_tracker.get_value() def update_arrow(arrow): nl = arrow.character.scale.number_line rate = arrow.get_rate() if rate == 0: rate = 1e-6 arrow.put_start_and_end_on(nl.n2p(0), nl.n2p(rate)) arrow.next_to(nl, np.sign(nl.get_center()[0]) * RIGHT) if rate > 0: arrow.set_color(GREEN) else: arrow.set_color(RED) left_arrow.add_updater(update_arrow) right_arrow.add_updater(update_arrow) self.play( VFadeIn(left_arrow), ApplyMethod(big_arrow.scale, 0, remover=True, run_time=3), ApplyMethod(juliet.love_tracker.set_value, 0, run_time=3), ) ps_point = Point(5 * UP) curr_time = self.time ps_point.add_updater(lambda m: m.move_to([ -5 * np.sin(0.5 * (self.time - curr_time)), 5 * np.cos(0.5 * (self.time - curr_time)), 0, ])) juliet.love_tracker.add_updater(lambda m: m.set_value(ps_point.get_location()[0])) romeo.love_tracker.add_updater(lambda m: m.set_value(ps_point.get_location()[1])) self.add(ps_point) self.add(right_arrow) self.play( equations.animate.arrange(RIGHT, buff=LARGE_BUFF).to_edge(UP, buff=0), run_time=2, ) # Just let this play out for a long time while other animations are played on top self.wait(5 * TAU) def get_romeo_and_juliet(self): romeo = PiCreature(color=BLUE_E, flip_at_start=True) juliet = PiCreature(color=BLUE_B) return VGroup(romeo, juliet) def make_romeo_and_juliet_dynamic(self, romeo, juliet): cutoff_values = [-5, -3, -1, 0, 1, 3, 5] modes = ["angry", "sassy", "hesitant", "plain", "happy", "hooray", "surprised"] self.make_character_dynamic(romeo, juliet, cutoff_values, modes) self.make_character_dynamic(juliet, romeo, cutoff_values, modes) def get_romeo_juilet_name_labels(self, lovers, font_size=36, spacing=1.2, buff=MED_SMALL_BUFF): name_labels = VGroup(*( Text(name, font_size=font_size) for name in ["Romeo", "Juliet"] )) for label, creature in zip(name_labels, lovers): label.next_to(creature, DOWN, buff) creature.name_label = label name_labels.space_out_submobjects(spacing) return name_labels def make_character_dynamic(self, pi_creature, lover, cutoff_values, modes): height = pi_creature.get_height() bottom = pi_creature.get_bottom() copies = [ pi_creature.deepcopy().change(mode).set_height(height).move_to(bottom, DOWN) for mode in modes ] pi_creature.love_tracker = ValueTracker() def update_func(pi): love = pi.love_tracker.get_value() if love < cutoff_values[0]: pi.become(copies[0]) elif love >= cutoff_values[-1]: pi.become(copies[-1]) else: i = 1 while cutoff_values[i] < love: i += 1 copy1 = copies[i - 1] copy2 = copies[i] alpha = inverse_interpolate(cutoff_values[i - 1], cutoff_values[i], love) s_alpha = squish_rate_func(smooth, 0.25, 0.75)(alpha) # if s_alpha > 0: copy1.align_data_and_family(copy2) pi.align_data_and_family(copy1) pi.align_data_and_family(copy2) fam = pi.family_members_with_points() f1 = copy1.family_members_with_points() f2 = copy2.family_members_with_points() for sm, sm1, sm2 in zip(fam, f1, f2): sm.interpolate(sm1, sm2, s_alpha) pi.look_at(lover.get_top()) if love < cutoff_values[1]: # Look away from the lover pi.look_at(2 * pi.eyes.get_center() - lover.eyes.get_center() + DOWN) return pi pi_creature.add_updater(update_func) def update_eyes(heart_eyes): love = pi_creature.love_tracker.get_value() l_alpha = np.clip( inverse_interpolate(cutoff_values[-1] - 0.5, cutoff_values[-1], love), 0, 1 ) pi_creature.eyes.set_opacity(1 - l_alpha) heart_eyes.set_opacity(l_alpha) # heart_eyes.move_to(pi_creature.eyes) heart_eyes.match_x(pi_creature.mouth) heart_eyes = self.get_heart_eyes(pi_creature) heart_eyes.add_updater(update_eyes) pi_creature.heart_eyes = heart_eyes self.add(heart_eyes) return pi_creature def get_heart_eyes(self, creature): hearts = VGroup() for eye in creature.eyes: heart = SVGMobject("hearts") heart.set_fill(RED) heart.match_width(eye) heart.move_to(eye) heart.scale(1.25) heart.set_stroke(BLACK, 1) hearts.add(heart) hearts.set_opacity(0) return hearts def get_love_scale(self, creature, direction, var_name, color): number_line = NumberLine((-5, 5)) number_line.rotate(90 * DEGREES) number_line.set_height(1.5 * creature.get_height()) number_line.next_to(creature, direction, buff=MED_LARGE_BUFF) number_line.add_numbers( range(-4, 6, 2), font_size=18, color=GREY_B, buff=0.1, direction=LEFT, ) dot = Dot(color=color) dot.add_updater(lambda m: m.move_to(number_line.n2p(creature.love_tracker.get_value()))) label = VGroup(OldTex(var_name, "=", font_size=36), DecimalNumber(font_size=24)) label.set_color(color) label[0].shift(label[1].get_left() + SMALL_BUFF * LEFT - label[0][1].get_right()) label.next_to(number_line, UP) label[1].add_updater(lambda m: m.set_value(creature.love_tracker.get_value()).set_color(color)) result = VGroup(number_line, dot, label) result.set_stroke(background=True) result.number_line = number_line result.dot = dot result.label = label creature.scale_mob = result return result class DiscussSystem(Scene): def construct(self): # Setup equations equations = VGroup( OldTex("{dx \\over dt} {{=}} -{{y(t)}}"), OldTex("{dy \\over dt} {{=}} {{x(t)}}"), ) equations.arrange(RIGHT, buff=LARGE_BUFF) equations.to_edge(UP, buff=1.5) eq_rect = SurroundingRectangle(equations, stroke_width=2, buff=0.25) sys_label = Text("System of differential equations") sys_label.next_to(eq_rect, UP) self.add(equations) self.play( FadeIn(sys_label, 0.5 * UP), ShowCreation(eq_rect), ) style = {"color": BLUE, "time_width": 3, "run_time": 2} self.play(LaggedStart( FlashAround(sys_label.get_part_by_text("differential"), **style), FlashAround(equations[0].get_part_by_tex("dx"), **style), FlashAround(equations[1].get_part_by_tex("dy"), **style), )) self.wait() # Ask for explicit solutions solutions = VGroup( OldTex("x(t) {{=}} (\\text{expression with } t)"), OldTex("y(t) {{=}} (\\text{expression with } t)"), ) for solution in solutions: solution.set_color_by_tex("expression", GREY_B) solutions.arrange(DOWN, buff=0.5) solutions.move_to(equations) solutions.set_x(3) self.play( sys_label.animate.match_width(eq_rect).to_edge(LEFT), VGroup(equations, eq_rect).animate.to_edge(LEFT), LaggedStartMap(FadeIn, solutions, shift=0.5 * UP, lag_ratio=0.3), ) self.wait() # Show a guess guess_rhss = VGroup( OldTex("\\cos(t)", color=GREY_B)[0], OldTex("\\sin(t)", color=GREY_B)[0], ) temp_rhss = VGroup() for rhs, solution in zip(guess_rhss, solutions): temp_rhss.add(solution[2]) rhs.move_to(solution[2], LEFT) bubble = ThoughtBubble(height=4, width=4) bubble.flip() bubble.set_fill(opacity=0) bubble[:3].rotate(30 * DEGREES, about_point=bubble[3].get_center() + 0.2 * RIGHT) bubble.shift(solutions.get_left() + 0.7 * LEFT - bubble[3].get_left()) self.remove(temp_rhss) self.play( ShowCreation(bubble), *( TransformMatchingShapes(temp_rhs.copy(), guess_rhs) for temp_rhs, guess_rhs in zip(temp_rhss, guess_rhss) ), ) self.wait() # Not enough! not_enough = Text("Not enough!", font_size=40) not_enough.next_to(bubble[3].get_corner(UR), DR) not_enough.set_color(RED) self.play(LaggedStartMap(FadeIn, not_enough, run_time=1, lag_ratio=0.1)) self.wait() self.remove(guess_rhss) self.play( LaggedStartMap(FadeOut, VGroup(*bubble, *not_enough)), *( TransformMatchingShapes(guess_rhs.copy(), temp_rhs) for temp_rhs, guess_rhs in zip(temp_rhss, guess_rhss) ), ) # Initial condition solutions.generate_target() initial_conditions = VGroup( OldTex("x(0) = x_0"), OldTex("y(0) = y_0"), ) full_requirement = VGroup(*solutions.target, *initial_conditions) full_requirement.arrange(DOWN, buff=0.25, aligned_edge=LEFT) full_requirement.scale(0.8) full_requirement.move_to(solutions) full_requirement.to_edge(UP) self.play( MoveToTarget(solutions), LaggedStartMap(FadeIn, initial_conditions, shift=0.1 * UP, lag_ratio=0.3), ) self.wait() ic_label = Text("Initial condition", font_size=30) ic_label.set_color(BLUE) ic_label.next_to(initial_conditions, RIGHT, buff=1.0) ic_arrows = VGroup(*( Arrow(ic_label.get_left(), eq.get_right(), buff=0.1, fill_color=BLUE, thickness=0.025) for eq in initial_conditions )) self.play( FadeIn(ic_label), LaggedStartMap(GrowArrow, ic_arrows, run_time=1) ) self.wait() class MoreGeneralSystem(Scene): def construct(self): kw = { "tex_to_color_map": { "x": RED, "y": GREEN, "z": BLUE, "{t}": GREY_B, } } equations = VGroup( OldTex("{dx \\over d{t} } = a\\cdot x({t}) + b\\cdot y({t}) + c\\cdot z({t})", **kw), OldTex("{dy \\over d{t} } = d\\cdot x({t}) + e\\cdot y({t}) + f\\cdot z({t})", **kw), OldTex("{dz \\over d{t} } = g\\cdot x({t}) + h\\cdot y({t}) + i\\cdot z({t})", **kw), ) equations.arrange(DOWN, buff=LARGE_BUFF) self.add(equations) self.play(LaggedStartMap(FadeIn, equations, shift=UP, lag_ratio=0.5, run_time=3)) self.wait() class HowExampleLeadsToMatrixExponents(Scene): def construct(self): # Screen self.add(FullScreenRectangle()) screen = ScreenRectangle() screen.set_height(3) screen.set_fill(BLACK, 1) screen.set_stroke(BLUE_B, 2) screen.to_edge(LEFT) self.add(screen) # Mat exp mat_exp = get_matrix_exponential( [["a", "b"], ["c", "d"]], height=2, h_buff=0.95, v_buff=0.75 ) mat_exp.set_x(FRAME_WIDTH / 4) def get_arrow(): return Arrow(screen, mat_exp[0]) arrow = get_arrow() self.play( GrowArrow(arrow), FadeIn(mat_exp, RIGHT) ) self.wait() # New screen screen2 = screen.copy() screen2.set_stroke(GREY_BROWN, 2) screen2.to_corner(DR) mat_exp.generate_target() mat_exp.target.to_edge(UP) mat_exp.target.match_x(screen2) double_arrow = VGroup( Arrow(mat_exp.target, screen2), Arrow(screen2, mat_exp.target), ) for mob in double_arrow: mob.scale(0.9, about_point=mob.get_end()) self.play( MoveToTarget(mat_exp), GrowFromCenter(double_arrow), arrow.animate.become(Arrow(screen, screen2)), FadeIn(screen2, DOWN), ) self.wait() class RomeoJulietVectorSpace(RomeoAndJuliet): def construct(self): # Set up Romeo and Juliet romeo, juliet = lovers = self.get_romeo_and_juliet() lovers.set_height(2.0) lovers.arrange(LEFT, buff=3) name_labels = self.get_romeo_juilet_name_labels(lovers, font_size=36, spacing=1.1) self.make_romeo_and_juliet_dynamic(*lovers) self.add(*lovers) self.add(*name_labels) # Scales juliet_scale = self.get_love_scale(juliet, LEFT, "x", BLUE_B) romeo_scale = self.get_love_scale(romeo, RIGHT, "y", BLUE) scales = [juliet_scale, romeo_scale] self.add(*scales) # Animate in psp_tracker = Point() def get_psp(): # Get phase space point return psp_tracker.get_location() juliet.love_tracker.add_updater(lambda m: m.set_value(get_psp()[0])) romeo.love_tracker.add_updater(lambda m: m.set_value(get_psp()[1])) self.add(romeo.love_tracker, juliet.love_tracker) psp_tracker.move_to([1, -3, 0]) self.play( Rotate(psp_tracker, 90 * DEGREES, about_point=ORIGIN, run_time=3, rate_func=linear) ) # Transition to axes axes = Axes( x_range=(-5, 5), y_range=(-5, 5), height=7, width=7, axis_config={ "include_tip": False, "numbers_to_exclude": [], } ) axes.set_x(-3) for axis in axes: axis.add_numbers(range(-4, 6, 2), color=GREY_B) axis.numbers[2].set_opacity(0) for pi in lovers: pi.clear_updaters() pi.generate_target() pi.target.set_height(0.75) pi.name_label.generate_target() pi.name_label.target.scale(0.5) group = VGroup(pi.target, pi.name_label.target) group.arrange(DOWN, buff=SMALL_BUFF) pi.target_group = group pi.scale_mob[2].clear_updaters() self.add(*pi.scale_mob) juliet.target_group.next_to(axes.x_axis.get_end(), RIGHT) romeo.target_group.next_to(axes.y_axis.get_corner(UR), RIGHT) romeo.target_group.shift_onto_screen(buff=MED_SMALL_BUFF) romeo.target.flip() juliet.target.flip() juliet.target.make_eye_contact(romeo.target) self.play(LaggedStart( juliet.scale_mob.number_line.animate.become(axes.x_axis), FadeOut(juliet.scale_mob.label), MoveToTarget(juliet), MoveToTarget(juliet.name_label), romeo.scale_mob.number_line.animate.become(axes.y_axis), FadeOut(romeo.scale_mob.label), MoveToTarget(romeo), MoveToTarget(romeo.name_label), run_time=3 )) self.add(*romeo.scale_mob[:2], *juliet.scale_mob[:2]) # Reset pi creatures self.remove(lovers) self.remove(romeo.heart_eyes) self.remove(juliet.heart_eyes) new_lovers = self.get_romeo_and_juliet() for new_pi, pi in zip(new_lovers, lovers): new_pi.flip() new_pi.replace(pi) new_pi.scale_mob = pi.scale_mob lovers = new_lovers romeo, juliet = new_lovers self.add(romeo, juliet) self.make_romeo_and_juliet_dynamic(romeo, juliet) juliet.love_tracker.add_updater(lambda m: m.set_value(get_psp()[0])) romeo.love_tracker.add_updater(lambda m: m.set_value(get_psp()[1])) self.add(romeo.love_tracker, juliet.love_tracker) # h_line and v_line ps_dot = Dot(color=BLUE) ps_dot.add_updater(lambda m: m.move_to(axes.c2p(*get_psp()[:2]))) v_line = Line().set_stroke(BLUE_D, 2) h_line = Line().set_stroke(BLUE_B, 2) v_line.add_updater(lambda m: m.put_start_and_end_on( axes.x_axis.n2p(get_psp()[0]), axes.c2p(*get_psp()[:2]), )) h_line.add_updater(lambda m: m.put_start_and_end_on( axes.y_axis.n2p(get_psp()[1]), axes.c2p(*get_psp()[:2]), )) x_dec = DecimalNumber(0, font_size=24) x_dec.next_to(h_line, UP, SMALL_BUFF) y_dec = DecimalNumber(0, font_size=24) y_dec.next_to(v_line, RIGHT, SMALL_BUFF) romeo.scale_mob.dot.clear_updaters() juliet.scale_mob.dot.clear_updaters() self.play( ShowCreation(h_line.copy().clear_updaters(), remover=True), ShowCreation(v_line.copy().clear_updaters(), remover=True), ReplacementTransform(romeo.scale_mob.dot, ps_dot), ReplacementTransform(juliet.scale_mob.dot, ps_dot), ChangeDecimalToValue(x_dec, get_psp()[0]), VFadeIn(x_dec), ChangeDecimalToValue(y_dec, get_psp()[1]), VFadeIn(y_dec), ) self.add(h_line, v_line, ps_dot) # Add coordinates equation = VGroup( Matrix([["x"], ["y"]], bracket_h_buff=SMALL_BUFF), OldTex("="), DecimalMatrix( np.reshape(get_psp()[:2], (2, 1)), element_to_mobject_config={ "num_decimal_places": 2, "font_size": 36, "include_sign": True, } ), ) equation[0].match_height(equation[2]) equation.arrange(RIGHT) equation.to_corner(UR) equation.shift(MED_SMALL_BUFF * LEFT) self.play( FadeIn(equation[:2]), FadeIn(equation[2].get_brackets()), TransformFromCopy(x_dec, equation[2].get_entries()[0]), TransformFromCopy(y_dec, equation[2].get_entries()[1]), ) equation[2].get_entries()[0].add_updater(lambda m: m.set_value(get_psp()[0])) equation[2].get_entries()[1].add_updater(lambda m: m.set_value(get_psp()[1])) self.play(FadeOut(x_dec), FadeOut(y_dec)) # Play around in state space self.play(psp_tracker.move_to, [3, -2, 0], path_arc=120 * DEGREES, run_time=3) self.wait() self.play(psp_tracker.move_to, [-5, -2, 0], path_arc=0 * DEGREES, run_time=3, rate_func=there_and_back) self.wait() self.play(psp_tracker.move_to, [3, 5, 0], path_arc=0 * DEGREES, run_time=3, rate_func=there_and_back) self.wait() self.play(psp_tracker.move_to, [5, 3, 0], path_arc=-120 * DEGREES, run_time=2) self.wait() # Arrow vs. dot arrow = Arrow(axes.get_origin(), ps_dot.get_center(), buff=0, fill_color=BLUE) arrow.set_stroke(BLACK, 2, background=True) arrow_outline = arrow.copy() arrow_outline.set_fill(opacity=0) arrow_outline.set_stroke(YELLOW, 1) self.play(LaggedStart( FadeIn(arrow), FadeOut(ps_dot), ShowPassingFlash(arrow_outline, run_time=1, time_width=0.5), lag_ratio=0.5, )) self.wait() self.play(LaggedStart( FadeIn(ps_dot), FadeOut(arrow), FlashAround(ps_dot, buff=0.05), )) self.wait() self.play(FlashAround(equation)) self.play(psp_tracker.move_to, [4, 3, 0], run_time=2) self.wait() # Function of time new_lhs = Matrix([["x(t)"], ["y(t)"]]) new_lhs.match_height(equation[0]) new_lhs.move_to(equation[0], RIGHT) self.play( FadeTransformPieces(equation[0], new_lhs), ) self.remove(equation[0]) self.add(new_lhs) equation.replace_submobject(0, new_lhs) # Initialize rotation curr_time = self.time curr_psp = get_psp() psp_tracker.add_updater(lambda m: m.move_to(np.dot( curr_psp, np.transpose(rotation_about_z(0.25 * (self.time - curr_time))), ))) self.wait(5) # Rate of change deriv_lhs = Matrix([["x'(t)"], ["y'(t)"]], bracket_h_buff=SMALL_BUFF) deriv_lhs.match_height(equation[0]) deriv_lhs.move_to(equation[0]) deriv_lhs.set_color(RED_B) deriv_label = Text("Rate of change", font_size=24) deriv_label.match_width(deriv_lhs) deriv_label.match_color(deriv_lhs) deriv_label.next_to(deriv_lhs, DOWN, SMALL_BUFF) self.play( FadeIn(deriv_lhs), Write(deriv_label, run_time=1), equation.animate.shift(2.0 * deriv_lhs.get_height() * DOWN) ) self.wait(5) deriv_vect = Arrow(fill_color=RED_B) deriv_vect.add_updater( lambda m: m.put_start_and_end_on( axes.get_origin(), axes.c2p(-0.5 * get_psp()[1], 0.5 * get_psp()[0]) ).shift( ps_dot.get_center() - axes.get_origin() ) ) pre_vect = Arrow(LEFT, RIGHT) pre_vect.replace(deriv_label, dim_to_match=0) pre_vect.set_fill(RED_B, 0) moving_vect = pre_vect.copy() deriv_vect.set_opacity(0) self.add(deriv_vect) self.play( UpdateFromAlphaFunc( moving_vect, lambda m, a: m.interpolate(pre_vect, deriv_vect, a).set_fill(opacity=a), remover=True ) ) deriv_vect.set_fill(opacity=1) self.add(deriv_vect, ps_dot) self.wait(8) # Show equation rhs = VGroup( OldTex("="), Matrix([["-y(t)"], ["x(t)"]], bracket_h_buff=SMALL_BUFF) ) rhs.match_height(deriv_lhs) rhs.arrange(RIGHT) rhs.next_to(deriv_lhs, RIGHT) self.play(FadeIn(rhs)) self.wait() for i in range(2): self.play(FlashAround( VGroup(deriv_lhs.get_entries()[i], rhs[1].get_entries()[i]), run_time=3, time_width=4, )) self.wait(2) # Write with a matrix deriv_lhs.generate_target() new_eq = VGroup( deriv_lhs.target, OldTex("="), IntegerMatrix([[0, -1], [1, 0]], bracket_v_buff=MED_LARGE_BUFF), Matrix([["x(t)"], ["y(t)"]], bracket_h_buff=SMALL_BUFF), ) new_eq[2].match_height(new_eq[0]) new_eq[3].match_height(new_eq[0]) new_eq.arrange(RIGHT) new_eq.to_corner(UR) self.play( MoveToTarget(deriv_lhs), MaintainPositionRelativeTo(deriv_label, deriv_lhs), ReplacementTransform(rhs[0], new_eq[1]), ReplacementTransform(rhs[1].get_brackets(), new_eq[3].get_brackets()), FadeIn(new_eq[2], scale=2), FadeTransform(rhs[1].get_entries()[1], new_eq[3].get_entries()[0]), FadeTransform(rhs[1].get_entries()[0], new_eq[3].get_entries()[1]), ) self.wait(3) row_rect = SurroundingRectangle(new_eq[2].get_entries()[:2], buff=SMALL_BUFF) col_rect = SurroundingRectangle(new_eq[3].get_entries(), buff=SMALL_BUFF) both_rects = VGroup(row_rect, col_rect) both_rects.set_stroke(YELLOW, 2) self.play(*map(ShowCreation, both_rects)) self.wait(3) self.play(row_rect.animate.move_to(new_eq[2].get_entries()[2:4])) self.wait(3) self.play(FadeOut(both_rects)) # Write general form general_form = OldTex( "{d \\over dt}", "\\vec{\\textbf{v} }", "(t)", "=", "\\textbf{M}", "\\vec{\\textbf{v} }", "(t)", ) general_form.set_color_by_tex("d \\over dt", RED_B) general_form.set_color_by_tex("\\textbf{v}", GREY_B) general_form.scale(1.2) general_form.next_to(new_eq, DOWN, LARGE_BUFF) general_form.shift(0.5 * RIGHT) gf_rect = SurroundingRectangle(general_form, buff=MED_SMALL_BUFF) gf_rect.set_stroke(YELLOW, 2) equation.clear_updaters() self.play( FadeIn(general_form), FadeOut(equation), ) self.wait() self.play(ShowCreation(gf_rect)) self.wait(4 * TAU) # Fade all else out self.play(FadeOut(VGroup(gf_rect, general_form, new_eq, deriv_lhs, deriv_label))) self.wait(4 * TAU) print(self.num_plays) class From2DTo1D(Scene): show_solution = False def construct(self): # (Setup vector equation) equation = get_2d_equation() equation.center() equation.to_edge(UP, buff=1.0) deriv, vect_sym, equals, matrix_mob, vect_sym2 = equation vect_sym.save_state() # (Setup plane) plane = NumberPlane( x_range=(-4, 4), y_range=(-2, 2), height=4, width=8, ) plane.to_edge(DOWN) point = Point(plane.c2p(2, 0.5)) vector = Arrow(plane.get_origin(), point.get_location(), buff=0) vector.set_color(YELLOW) # Show vector vect_sym.set_x(0) static_vect_sym = vect_sym.deepcopy() for entry in static_vect_sym.get_entries(): entry[1:].set_opacity(0) entry[:1].move_to(entry) static_vect_sym.get_brackets().space_out_submobjects(0.7) vector.save_state() vector.put_start_and_end_on( static_vect_sym.get_corner(DL), static_vect_sym.get_corner(UR), ) vector.set_opacity(0) self.add(plane, static_vect_sym) self.play(Restore(vector)) self.wait() # Changing with time matrix = np.array([[0.5, -3], [1, -0.5]]) def func(x, y): return 0.2 * np.dot([x, y], matrix.T) move_points_along_vector_field(point, func, plane) vector.add_updater(lambda m: m.put_start_and_end_on( plane.get_origin(), point.get_location(), )) deriv_vector = Vector(fill_color=RED, thickness=0.03) deriv_vector.add_updater( lambda m: m.put_start_and_end_on( plane.get_origin(), plane.c2p(*func(*plane.p2c(point.get_location()))), ).shift(vector.get_vector()) ) self.add(point) self.play(ReplacementTransform(static_vect_sym, vect_sym)) self.wait(3) # Show matrix equation deriv_underline = Underline(VGroup(deriv, vect_sym.saved_state)) deriv_underline.set_stroke(RED, 3) alt_line = deriv_underline.deepcopy() self.play( Restore(vect_sym), FadeIn(deriv), ) self.wait() self.play( ShowCreation(deriv_underline), ) self.play( VFadeIn(deriv_vector, rate_func=squish_rate_func(smooth, 0.8, 1.0)), UpdateFromAlphaFunc( alt_line, lambda m, a: m.put_start_and_end_on( interpolate(deriv_underline.get_start(), deriv_vector.get_start(), a), interpolate(deriv_underline.get_end(), deriv_vector.get_end(), a), ), remover=True, ), ) self.wait(4) self.play( LaggedStartMap(FadeIn, equation[2:4], shift=RIGHT, lag_ratio=0.3), TransformFromCopy( equation[1], equation[4], path_arc=-45 * DEGREES, run_time=2, rate_func=squish_rate_func(smooth, 0.3, 1.0) ) ) self.wait(8) # Highlight equation deriv_rect = SurroundingRectangle(equation[:2]) deriv_rect.set_stroke(RED, 2) rhs_rect = SurroundingRectangle(equation[-1]) rhs_rect.set_stroke(YELLOW, 2) self.play(ShowCreation(deriv_rect)) self.wait() self.play(ReplacementTransform(deriv_rect, rhs_rect, path_arc=-45 * DEGREES)) # Draw vector field vector_field = VectorField( func, plane, magnitude_range=(0, 1.2), opacity=0.5, vector_config={"thickness": 0.02} ) vector_field.sort(lambda p: get_norm(p - plane.get_origin())) self.add(vector_field, deriv_vector, vector) VGroup(vector, deriv_vector).set_stroke(BLACK, 5, background=True) self.play( FadeOut(rhs_rect), LaggedStartMap(GrowArrow, vector_field, lag_ratio=0) ) self.wait(14) # flow_lines = AnimatedStreamLines(StreamLines(func, plane, step_multiple=0.25)) # self.add(flow_lines) # self.wait(4) # self.play(VFadeOut(flow_lines)) # self.wait(10) # Show solution equation.add(deriv_underline) mat_exp = get_matrix_exponential( [["a", "b"], ["c", "d"]], h_buff=0.75, v_buff=0.75, ) mat_exp[1].set_color(TEAL) if self.show_solution: equation.generate_target() equation.target.to_edge(LEFT) implies = OldTex("\\Rightarrow") implies.next_to(equation.target, RIGHT) solution = VGroup( equation[1].copy(), OldTex("="), mat_exp, Matrix( [["x(0)"], ["y(0)"]], bracket_h_buff=SMALL_BUFF, bracket_v_buff=SMALL_BUFF, ) ) solution[2].match_height(solution[0]) solution[3].match_height(solution[0]) solution.arrange(RIGHT, buff=MED_SMALL_BUFF) solution.next_to(implies, RIGHT, MED_LARGE_BUFF) solution.align_to(equation[1], DOWN) solution_rect = SurroundingRectangle(solution, buff=MED_SMALL_BUFF) self.play( MoveToTarget(equation), ) self.play(LaggedStart( Write(implies), ShowCreation(solution_rect), TransformFromCopy(equation[4], solution[0], path_arc=30 * DEGREES), )) self.wait() self.play(LaggedStart( TransformFromCopy(equation[3], solution[2][1]), FadeIn(solution[2][0]), FadeIn(solution[2][2]), FadeIn(solution[1]), FadeIn(solution[3]), lag_ratio=0.1, )) self.wait(10) return else: # Show relation with matrix exp mat_exp.move_to(equation[0], DOWN) mat_exp.to_edge(RIGHT, buff=LARGE_BUFF) equation.generate_target() equation.target.to_edge(LEFT, buff=LARGE_BUFF) arrow1 = Arrow(equation.target.get_corner(UR), mat_exp.get_corner(UL), path_arc=-45 * DEGREES) arrow2 = Arrow(mat_exp.get_corner(DL), equation.target.get_corner(DR), path_arc=-45 * DEGREES) arrow1.shift(0.2 * RIGHT) self.play(MoveToTarget(equation)) self.play( FadeIn(mat_exp[0::2]), TransformFromCopy(equation[3], mat_exp[1]), Write(arrow1, run_time=1), ) self.wait(4) self.play(Write(arrow2, run_time=2)) self.wait(4) normal_exp = OldTex("e^{rt}")[0] normal_exp.set_height(1.0) normal_exp[1].set_color(BLUE) normal_exp.move_to(mat_exp) self.play( FadeTransformPieces(mat_exp, normal_exp), FadeOut(VGroup(arrow1, arrow2)) ) self.wait(2) # Transition to 1D max_x = 50 mult = 50 number_line = NumberLine((0, max_x), width=max_x) number_line.add_numbers() number_line.move_to(plane) number_line.to_edge(LEFT) nl = number_line nl2 = NumberLine((0, mult * max_x, mult), width=max_x) nl2.add_numbers() nl2.set_width(nl.get_width() * mult) nl2.shift(nl.n2p(0) - nl2.n2p(0)) nl2.set_opacity(0) nl.add(nl2) new_equation = OldTex( "{d \\over dt}", "x(t)", "=", "r \\cdot ", "x(t)", ) new_equation[0][3].set_color(GREY_B) new_equation[1][2].set_color(GREY_B) new_equation[4][2].set_color(GREY_B) new_equation[3][0].set_color(BLUE) new_equation.match_height(equation) new_equation.move_to(equation) self.remove(point) vector.clear_updaters() deriv_vector.clear_updaters() self.remove(vector_field) plane.add(vector_field) self.add(number_line, deriv_vector, vector) self.play( normal_exp.animate.scale(0.5).to_corner(UR), # Plane to number line vector.animate.put_start_and_end_on(nl.n2p(0), nl.n2p(1)), deriv_vector.animate.put_start_and_end_on(nl.n2p(1), nl.n2p(1.5)), plane.animate.shift(nl.n2p(0) - plane.get_origin()).set_opacity(0), FadeIn(number_line, rate_func=squish_rate_func(smooth, 0.5, 1)), # Equation TransformMatchingShapes(equation[0], new_equation[0]), Transform(equation[1].get_entries()[0], new_equation[1]), FadeTransform(equation[2], new_equation[2]), FadeTransform(equation[3], new_equation[3]), FadeTransform(equation[4].get_entries()[0], new_equation[4]), FadeOut(equation[1].get_brackets()), FadeOut(equation[1].get_entries()[1]), FadeOut(equation[4].get_brackets()), FadeOut(equation[4].get_entries()[1]), FadeOut(deriv_underline), run_time=2, ) vt = ValueTracker(1) vt.add_updater(lambda m, dt: m.increment_value(0.2 * dt * m.get_value())) vector.add_updater(lambda m: m.put_start_and_end_on(nl.n2p(0), nl.n2p(vt.get_value()))) deriv_vector.add_updater(lambda m: m.set_width(0.5 * vector.get_width()).move_to(vector.get_right(), LEFT)) self.add(vt) self.wait(11) self.play( number_line.animate.scale(0.3, about_point=nl.n2p(0)), ) self.wait(4) number_line.generate_target() number_line.target.scale(0.1, about_point=nl.n2p(0)), number_line.target[-1].set_opacity(1) self.play( MoveToTarget(number_line) ) self.wait(11) self.play(number_line.animate.scale(0.2, about_point=nl.n2p(0))) self.wait(10) class SchroedingersEquationIntro(Scene): def construct(self): # Show equation title = Text("Schrödinger equation", font_size=72) title.to_edge(UP) self.add(title) t2c = { "|\\psi \\rangle": BLUE, "{H}": GREY_A, "=": WHITE, "i\\hbar": WHITE, } original_equation = OldTex( "i\\hbar \\frac{\\partial}{\\partial t} |\\psi \\rangle = {H} |\\psi \\rangle", tex_to_color_map=t2c ) equation = OldTex( "\\frac{\\partial}{\\partial t} |\\psi \\rangle = \\frac{1}{i\\hbar} {H} |\\psi \\rangle", tex_to_color_map=t2c ) VGroup(original_equation, equation).scale(1.5) psis = original_equation.get_parts_by_tex("\\psi") state_label = OldTexText("State of a system \\\\ as a vector", font_size=36) state_label.next_to(psis, DOWN, buff=1.5) state_label.shift(0.5 * RIGHT) state_arrows = VGroup(*(Arrow(state_label, psi) for psi in psis)) state_label.match_color(psis[0]) state_arrows.match_color(psis[0]) psis.set_color(WHITE) randy = Randolph(height=2.0, color=BLUE_C) randy.to_corner(DL) randy.set_opacity(0) self.play(Write(original_equation, run_time=3)) self.wait() self.play( randy.animate.set_opacity(1).change("horrified", original_equation) ) self.play(Blink(randy)) self.play( randy.change("pondering", state_label), psis.animate.match_color(state_label), FadeIn(state_label, 0.25 * DOWN), *map(GrowArrow, state_arrows), ) self.wait() self.play(Blink(randy)) self.wait() self.play( ReplacementTransform(original_equation[1:4], equation[0:3]), Write(equation[3]), ReplacementTransform(original_equation[0], equation[4], path_arc=90 * DEGREES), ReplacementTransform(original_equation[4:], equation[5:]), state_arrows.animate.become( VGroup(*(Arrow(state_label, psi) for psi in equation.get_parts_by_tex("\\psi"))) ), randy.change("hesitant", equation) ) self.play(FlashAround(equation[0], time_width=2, run_time=2)) self.play(Blink(randy)) mat_rect = SurroundingRectangle(equation[3:6], buff=0.05, color=TEAL) mat_label = Text("A certain matrix", font_size=36) mat_label.next_to(mat_rect, UP) mat_label.match_color(mat_rect) self.play( ShowCreation(mat_rect), FadeIn(mat_label, 0.25 * UP), ) self.wait() self.play(randy.change("confused", equation)) self.play(Blink(randy)) self.wait() # Complicating factors psi_words = OldTexText( "Often this is a function.\\\\", "(But whatever functions are really\\\\just infinite-dimensional vectors)" ) psi_words[0].match_width(psi_words[1], about_edge=DOWN) psi_words[1].shift(0.1 * DOWN) psi_words.scale(0.75) psi_words.move_to(state_label, UP) psi_words[0].set_color(RED) psi_words[1].set_color(RED_D) mat_line = Line(LEFT, RIGHT) mat_line.set_stroke(RED, 5) mat_line.replace(mat_label.get_part_by_text("matrix"), dim_to_match=0) operator_word = Text("operator", font_size=36) operator_word.next_to(mat_label, UP, buff=SMALL_BUFF) operator_word.align_to(mat_line, LEFT) operator_word.set_color(RED) complex_valued = Text("Complex-valued", font_size=30) complex_valued.set_color(RED) complex_valued.next_to(equation, RIGHT) complex_valued.to_edge(RIGHT) cv_arrow = Arrow(complex_valued, equation, fill_color=RED) self.play(LaggedStart( FadeOut(state_label), FadeIn(psi_words), ShowCreation(mat_line), Write(operator_word, run_time=1), GrowArrow(cv_arrow), FadeIn(complex_valued), randy.change("horrified", equation), lag_ratio=0.5 )) self.play(Blink(randy)) self.wait() class SimpleDerivativeOfExp(TeacherStudentsScene): def construct(self): eq = OldTex( "{d \\over dt}", "e^{rt}", "=", "r", "e^{rt}", ) eq.set_color_by_tex("r", TEAL, substring=False) for part in eq.get_parts_by_tex("e^{rt}"): part[1].set_color(TEAL) s0, s1, s2 = self.students morty = self.teacher bubble = s2.get_bubble(eq) self.play( s2.change("pondering", eq), FadeIn(bubble, lag_ratio=0.2), ) self.play( LaggedStart( s0.change("hesitant", eq), s1.change("erm", eq), morty.change("tease"), ), Write(eq[:2]) ) self.wait() self.play( TransformFromCopy(*eq.get_parts_by_tex("e^{rt}"), path_arc=45 * DEGREES), Write(eq.get_part_by_tex("=")), *( pi.animate.look_at(eq[4]) for pi in self.pi_creatures ) ) self.play( FadeTransform(eq[4][1].copy(), eq[3][0], path_arc=90 * DEGREES) ) self.play( LaggedStart( s0.change("thinking"), s1.change("tease"), ) ) self.wait(2) rect = ScreenRectangle(height=3.5) rect.set_fill(BLACK, 1) rect.set_stroke(BLUE_B, 2) rect.to_corner(UR) self.play( morty.change("raise_right_hand", rect), self.change_students("pondering", "pondering", "pondering", look_at=rect), FadeIn(rect, UP) ) self.wait(10) class ETitleCard(Scene): def construct(self): title = OldTexText("A brief review of $e$\\\\and exponentials") title.scale(2) self.add(title) class GraphAndHistoryOfExponential(Scene): def construct(self): # Setup axes = Axes( x_range=(0, 23, 1), y_range=(0, 320, 10), height=160, width=13, axis_config={"include_tip": False} ) axes.y_axis.add(*(axes.y_axis.get_tick(x, size=0.05) for x in range(20))) axes.to_corner(DL) r = 0.25 exp_graph = axes.get_graph(lambda t: np.exp(r * t)) exp_graph.set_stroke([BLUE_E, BLUE, YELLOW]) graph_template = exp_graph.copy() graph_template.set_stroke(width=0) axes.add(graph_template) equation = self.get_equation() solution = OldTex("x({t}) = e^{r{t} }", tex_to_color_map={"{t}": GREY_B, "r": BLUE}) solution.next_to(equation, DOWN, MED_LARGE_BUFF) self.add(axes) self.add(axes.get_x_axis_label("t")) self.add(axes.get_y_axis_label("x")) self.add(equation) curr_time = self.time exp_graph.add_updater(lambda m: m.pointwise_become_partial( graph_template, 0, (self.time - curr_time) / 20, )) dot = Dot(color=BLUE_B, radius=0.04) dot.add_updater(lambda d: d.move_to(exp_graph.get_end())) vect = Arrow(DOWN, UP, fill_color=YELLOW, thickness=0.025) vect.add_updater(lambda v: v.put_start_and_end_on( axes.get_origin(), axes.y_axis.get_projection(exp_graph.get_end()), )) h_line = always_redraw(lambda: DashedLine( vect.get_end(), dot.get_left(), stroke_width=1, stroke_color=GREY_B, )) v_line = always_redraw(lambda: DashedLine( axes.x_axis.get_projection(dot.get_bottom()), dot.get_bottom(), stroke_width=1, stroke_color=GREY_B, )) def stretch_axes(factor): axes.generate_target(use_deepcopy=True) axes.target.stretch(factor, 1, about_point=axes.get_origin()), axes.target.x_axis.stretch(1 / factor, 1, about_point=axes.get_origin()), self.play(MoveToTarget(axes)) self.add(exp_graph, dot, vect, h_line, v_line) # equation.scale(2, about_edge=UP)### self.wait(2) # Highlight equation parts index = equation.index_of_part_by_tex("=") lhs = equation[:index] rhs = equation[index + 1:] for part in (rhs, lhs): self.play(FlashAround(part, time_width=3, run_time=2)) self.wait() # self.wait(4) stretch_axes(0.2) self.wait(6) stretch_axes(0.23) self.wait(4) exp_graph.clear_updaters() exp_graph.become(graph_template) exp_graph.set_stroke(width=3) self.add(exp_graph) self.play(FadeOut(vect), FadeOut(dot)) self.wait() # Write exponential growth words = Text("Exponential growth") words.next_to(axes.c2p(0, 0), UR, buff=0) original_words = words.deepcopy() original_words.set_opacity(0) def func(p): t, x = axes.p2c(p) angle = axes.angle_of_tangent(t, exp_graph) vect = rotate_vector(RIGHT, angle + PI / 2) graph_point = axes.input_to_graph_point(t, exp_graph) y = (axes.y_axis.get_projection(p) - axes.get_origin())[1] return graph_point + y * vect fill_tracker = ValueTracker(0) words.add_updater(lambda m: m.become(original_words).set_fill(opacity=fill_tracker.get_value()).apply_function(func)) self.add(words) self.play( ApplyMethod(original_words.next_to, axes.c2p(14, 0), UP, SMALL_BUFF, run_time=2), fill_tracker.animate.set_value(1), ) self.remove(original_words, fill_tracker) words.clear_updaters() self.wait() # Introduce 2.71828 solution_with_number = OldTex( "{d \\over dt}", "(2.71828...)^{", "r", "t", "}", "=", "r", "\\cdot", "(2.71828...)^{", "r", "t", "}", tex_to_color_map={ "2.71828...": TEAL, } ) solution_with_e = OldTex( "{d \\over dt}", "{e}^{", "r", "t", "}", "=", "r", "\\cdot", "{e}^{", "r", "t", "}", tex_to_color_map={ "{e}": TEAL, } ) for eq in solution_with_number, solution_with_e: eq.set_color_by_tex("r", BLUE, substring=False) eq.set_color_by_tex("t", GREY_B, substring=False) eq.next_to(equation, DOWN, buff=MED_LARGE_BUFF) lhs = solution_with_number[:6] lhs.save_state() lhs.match_x(equation) self.play(FadeIn(lhs[1:], DOWN)) self.wait() self.play(Write(lhs[0])) dot1 = Dot(radius=0.05, color=RED) dot2 = dot1.copy() for sec_dot in dot1, dot2: sec_dot.x_tracker = ValueTracker(15) sec_dot.add_updater(lambda d: d.move_to(axes.input_to_graph_point( d.x_tracker.get_value(), exp_graph ))) line = Line(LEFT, RIGHT, stroke_color=GREY_A, stroke_width=2) line.add_updater(lambda l: l.put_start_and_end_on( dot1.get_center(), dot2.get_center() ).set_length(10)) dot2.x_tracker.set_value(17) dot1.x_tracker.set_value(15) self.play( FadeOut(words), FadeIn(dot1), FadeIn(dot2), FadeIn(line), ) self.play( dot2.x_tracker.animate.set_value(15 + 1e-6), run_time=3 ) self.play( dot1.x_tracker.animate.set_value(18), dot2.x_tracker.animate.set_value(18 + 1e-6), run_time=3 ) self.play( FadeOut(dot1), FadeOut(dot2), FadeOut(line), ) self.wait() self.play(Restore(lhs)) self.play( FadeIn(solution_with_number[6]), TransformFromCopy(lhs[1:], solution_with_number[8:], path_arc=30 * DEGREES), ) self.play(TransformFromCopy( solution_with_number[12], solution_with_number[7], path_arc=-90 * DEGREES, )) self.wait() # Historical letters correspondants = Group() for name1, name2, letter, year in [("Leibniz", "Huygens", "b", "1690"), ("Euler", "Goldbach", "e", "1731")]: im1 = ImageMobject(name1, height=2.5) im2 = ImageMobject(name2, height=2.5) lines = VGroup(*(Line(LEFT, RIGHT) for x in range(11))) lines.set_width(1.6) lines.arrange(DOWN, buff=0.2) lines.set_stroke(GREY_A, 2) lines[-1].stretch(0.5, 0, about_edge=LEFT) eq = OldTex(letter, "= 2.71828\\dots") eq[0].scale(1.5, about_edge=RIGHT) eq[0].align_to(eq[1], DOWN) eq.set_color(TEAL) eq.match_width(lines) eq.move_to(lines[5]) lines.remove(*lines[4:7]) lines.add(eq) box = SurroundingRectangle(lines, buff=0.25) box.set_stroke(GREY_C, 2) note = VGroup(box, lines) note.match_height(im1) group = Group() arrow = Vector(0.5 * RIGHT, fill_color=GREY_A) group.add(im1, arrow, note, arrow.copy(), im2) group.arrange(RIGHT) note.align_to(im1, UP) group.next_to(solution_with_number, DOWN, buff=LARGE_BUFF) for im, name, index in [(im1, name1, 0), (im2, name2, 4)]: name_label = Text(name, font_size=24) name_label.set_color(GREY_A) name_label.next_to(im, DOWN) rect = SurroundingRectangle(im, buff=0, stroke_color=GREY_A, stroke_width=1) group.replace_submobject(index, Group(im, rect, name_label)) date = Text(year, font_size=24) date.next_to(box, UP) note.add(date) group.eq = eq group.eq.set_opacity(0) correspondants.add(group) b_group, e_group = correspondants self.play(LaggedStartMap(FadeIn, b_group, shift=0.5 * UP, lag_ratio=0.2, run_time=1)) b_group.eq.set_fill(opacity=1) self.play(Write(b_group.eq, run_time=1)) self.wait() self.play( LaggedStartMap(FadeOut, b_group, shift=0.5 * UP), LaggedStartMap(FadeIn, e_group, shift=0.5 * UP), ) e_group.eq.set_fill(opacity=1) self.play(Write(e_group.eq, run_time=1)) self.wait() # Euler's book e_usage = e_group.eq.copy() book = ImageMobject("Introductio_in_Analysin_infinitorum") book.match_width(e_group[0][0]) book.move_to(e_group[2][0]) date = Text("1748", font_size=24) date.next_to(book, UP, SMALL_BUFF) self.play( LaggedStartMap(FadeOut, e_group[2:], shift=0.5 * RIGHT), FadeIn(book), FadeIn(date), e_usage.animate.scale(1.4).next_to(book, RIGHT, aligned_edge=UP).shift(0.25 * DOWN) ) self.wait() pi_eq = OldTex("\\pi = 3.1415\\dots", fill_color=GREEN, font_size=36) func_eq = OldTex("f(x)", font_size=36) pi_eq.next_to(e_usage, DOWN, buff=0.5, aligned_edge=LEFT) func_eq.next_to(pi_eq, DOWN, buff=0.5, aligned_edge=LEFT) self.play(Write(pi_eq, run_time=1)) self.wait() self.play(Write(func_eq, run_time=1)) self.wait() # Final notation self.play(FadeTransformPieces(solution_with_number, solution_with_e)) self.wait() def get_equation(self, r="r"): return get_1d_equation(r).to_edge(UP) class BernoullisThoughts(Scene): def construct(self): im = ImageMobject("Jacob_Bernoulli", height=4) name = Text("Jacob Bernoulli") name.match_width(im) name.next_to(im, DOWN, SMALL_BUFF) jacob = Group(im, name) jacob.to_corner(DR) bubble = ThoughtBubble(height=3.5, width=5) bubble.pin_to(jacob) bubble.shift(0.25 * RIGHT + 0.75 * DOWN) dollars = Text("$$$") dollars.set_height(1) dollars.set_color(GREEN) dollars.move_to(bubble.get_bubble_center()) dollar = dollars[0].copy() continuous_money = VGroup(*( dollar.copy().shift(smooth(x) * RIGHT * 2.0 + np.exp(smooth(x) - 1) * UP) for x in np.linspace(0, 1, 300) )) continuous_money.set_fill(opacity=0.1) continuous_money.center() continuous_money.move_to(dollars) self.play(FadeIn(jacob, shift=RIGHT)) self.play( ShowCreation(bubble), Write(dollars) ) self.wait() self.add(continuous_money) self.play( FadeOut(dollars), Write(continuous_money, stroke_color=GREEN, stroke_width=1, run_time=3), ) self.play( FadeOut(continuous_money, lag_ratio=0.01), FadeIn(dollars) ) self.wait() limit = OldTex("\\left(1 + \\frac{r}{n}\\right)^{nt}") limit.move_to(bubble.get_bubble_center()) limit.scale(1.5) self.play( FadeOut(dollars), FadeIn(limit), ) self.wait() class CompoundInterestPopulationAndEpidemic(Scene): def construct(self): N = 16000 points = 2 * np.random.random((N, 3)) - 1 points[:, 2] = 0 points = points[[get_norm(p) < 1 for p in points]] points *= 2 * FRAME_WIDTH points = np.array(list(sorted( points, key=lambda p: get_norm(p) + 0.5 * random.random() ))) dollar = OldTex("\\$") dollar.set_fill(GREEN) person = SVGMobject("person") person.set_fill(GREY_B, 1) virus = SVGMobject("virus") virus.set_fill([RED, RED_D]) virus.remove(virus[1:]) virus[0].set_points(virus[0].get_subpaths()[0]) templates = [dollar, person, virus] mob_height = 0.25 for mob in templates: mob.set_stroke(BLACK, 1, background=True) mob.set_height(mob_height) dollars, people, viruses = groups = [ VGroup(*(mob.copy().move_to(point) for point in points)) for mob in templates ] dollars.set_submobjects(dollars[:20]) people.set_submobjects(people[:500]) start_time = self.time def get_n(): time = self.time - start_time return int(math.exp(0.75 * time)) def update_group(group): group.set_opacity(0) group[:get_n()].set_opacity(0.9) def update_height(group, alpha): for mob in group: mob.set_height(max(alpha * mob_height, 1e-4)) for group in groups: group.add_updater(update_group) frame = self.camera.frame frame.set_height(2) frame.add_updater(lambda m, dt: m.set_height(m.get_height() * (1 + 0.2 * dt))) self.add(frame) self.add(dollars) self.wait(3) self.play( UpdateFromAlphaFunc(people, update_height), UpdateFromAlphaFunc(dollars, update_height, rate_func=lambda t: smooth(1 - t), remover=True), ) self.wait(4) self.play( UpdateFromAlphaFunc(viruses, update_height), UpdateFromAlphaFunc(people, update_height, rate_func=lambda t: smooth(1 - t), remover=True), ) self.wait(4) class CovidPlot(ExternallyAnimatedScene): pass class Compare1DTo2DEquations(Scene): def construct(self): eq1d = get_1d_equation() eq2d = get_2d_equation() eq1d.match_height(eq2d) equations = VGroup(eq1d, eq2d) equations.arrange(DOWN, buff=2.0) equations.to_edge(LEFT, buff=1.0) solutions = VGroup( OldTex("e^{rt}", tex_to_color_map={"r": BLUE}), get_matrix_exponential( [["a", "b"], ["c", "d"]], h_buff=0.75, v_buff=0.5, bracket_h_buff=0.25, ) ) solutions[1][1].set_color(TEAL) solutions[0].scale(2) arrows = VGroup() for eq, sol in zip(equations, solutions): sol.next_to(eq[-1], RIGHT, index_of_submobject_to_align=0) sol.set_x(4) arrows.add(Arrow(eq, sol[0], buff=0.5)) sol0, sol1 = solutions sol0.save_state() sol0.center() self.add(sol0) self.wait() self.play( Restore(sol0), TransformFromCopy(Arrow(eq1d, sol0, fill_opacity=0), arrows[0]), FadeIn(eq1d), ) self.wait(2) self.play( TransformMatchingShapes(sol0.copy(), sol1, fade_transform_mismatches=True), ) self.wait() self.play( TransformFromCopy(*arrows), LaggedStart(*( FadeTransform(m1.copy(), m2) for m1, m2 in zip( [eq1d[:2], eq1d[2:5], eq1d[5], eq1d[6], eq1d[7:]], eq2d ) ), lag_ratio=0.05) ) self.wait() class EVideoWrapper(VideoWrapper): title = "Video on $e^x$" class ManyExponentialForms(ExternallyAnimatedScene): pass class EBaseMisconception(Scene): def construct(self): randy = Randolph() randy.flip() randy.to_corner(DR) self.add(randy) self.play( PiCreatureSays( randy, OldTexText("This function is\\\\about about $e$", tex_to_color_map={"$e$": BLUE}), target_mode="thinking", bubble_config={"height": 3, "width": 4}, ) ) self.play(Blink(randy)) self.wait(2) self.play(randy.change("tease")) self.play(Blink(randy)) cross = Cross(randy.bubble.content, stroke_width=[0, 5, 5, 5, 0]) for line in cross: line.insert_n_curves(10) cross.scale(1.25) self.play( ShowCreation(cross), randy.change("guilty") ) self.wait() class OneFinalPoint(TeacherStudentsScene): def construct(self): self.teacher_says( OldTexText("One final point\\\\about one-dimension"), bubble_config={"height": 3, "width": 4}, ) self.play_student_changes( "happy", "hesitant", "tease", added_anims=[self.teacher.animate.look_at(self.students[2])] ) self.wait(3) class ManySolutionsDependingOnInitialCondition(VideoWrapper): def construct(self): # Setup graphs and equations axes = Axes( x_range=(0, 12), y_range=(0, 10), width=12, height=6, ) axes.add(axes.get_x_axis_label("t")) axes.add(axes.get_y_axis_label("x")) axes.x_axis.add_numbers() equation = get_1d_equation("0.3").to_edge(UP) def get_graph(x0, r=0.3): return axes.get_graph(lambda t: np.exp(r * t) * x0) step = 0.05 graphs = VGroup(*( get_graph(x0) for x0 in np.arange(step, axes.y_range[1], step) )) graphs.set_submobject_colors_by_gradient(BLUE_E, BLUE, TEAL, YELLOW) graphs.set_stroke(width=1) graph = get_graph(1) graph.set_color(BLUE) solution = OldTex( "x({t}) = e^{0.3 {t} } \\cdot x_0", tex_to_color_map={"{t}": GREY_B, "0.3": BLUE, "=": WHITE}, ) solution.next_to(equation, DOWN, LARGE_BUFF) solution.shift(0.25 * RIGHT) solution[-1][1:].set_fill(MAROON_B) group = VGroup(solution, equation) group.set_stroke(BLACK, 5, background=True) group.shift(2 * LEFT) labels = VGroup( Text("Differential equation", font_size=30), Text("Solution", font_size=30), ) labels.set_stroke(BLACK, 5, background=True) arrows = VGroup() for label, eq in zip(labels, [equation, solution[:-1]]): label.next_to(eq, RIGHT, buff=1.5) label.align_to(labels[0], LEFT) arrows.add(Arrow(label, eq)) eq_label, sol_label = labels eq_arrow, sol_arrow = arrows # Show many possible representations alt_rhs = OldTex( "&= 2^{(0.4328\\dots) t }\\\\", "&= 3^{(0.2730\\dots) t }\\\\", "&= 4^{(0.2164\\dots) t }\\\\", "&= 5^{(0.1864\\dots) t }\\\\", ) alt_rhs.next_to(solution.get_part_by_tex("="), DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) alt_rhs.set_stroke(BLACK, 5, background=True) choice_words = Text("This is a choice!", color=YELLOW, font_size=24) choice_words.next_to(solution[:-1], RIGHT, MED_LARGE_BUFF) choice_words.set_stroke(BLACK, 5, background=True) self.add(axes) self.add(solution[:-1]) self.play(ShowCreation(graph, run_time=3)) self.wait() self.play(FlashAround(solution.get_part_by_tex("e"), time_width=2, buff=0.05, run_time=2)) self.wait() self.play(LaggedStartMap(FadeIn, alt_rhs, shift=0.5 * DOWN, lag_ratio=0.6, run_time=5)) self.wait() self.play( alt_rhs.animate.set_opacity(0.4), FlashAround(solution[4:-1]), Write(choice_words, run_time=1) ) self.wait() self.play( FadeTransform(solution[:3].copy(), equation[2:5]), # x(t) FadeTransform(solution[:3].copy(), equation[7:10]), # x(t) FadeTransform(solution[3].copy(), equation[5]), # = FadeIn(equation[:2]), FadeOut(choice_words), ) self.play(FadeTransform(solution[5].copy(), equation[6])) # r self.wait() self.play(alt_rhs.animate.set_opacity(1.0)) self.wait() self.play(LaggedStartMap(FadeOut, alt_rhs, shift=DOWN)) for label, arrow in zip(labels, arrows): self.play( FadeIn(label, 0.5 * RIGHT), GrowArrow(arrow), ) self.wait() # Just one solution one = Text("One", font_size=30) many = Text("out of many", font_size=30) one.move_to(sol_label.get_corner(UL), LEFT) sol_label.generate_target() group = VGroup( VGroup(one, sol_label.target).arrange(RIGHT, buff=MED_SMALL_BUFF, aligned_edge=DOWN), many ) group.arrange(DOWN, buff=0.15) group.move_to(sol_label, LEFT) dot = Dot().scale(2 / 3) dot.move_to(axes.c2p(0, 0)) self.add(graphs, graph, equation, solution[:-1], arrows, labels, one, many) self.play( MoveToTarget(sol_label, rate_func=squish_rate_func(smooth, 0, 0.5)), FadeIn(one), FadeIn(many), ShowIncreasingSubsets(graphs), dot.animate.move_to(axes.c2p(0, 10)), run_time=4, ) self.wait() sol_label = VGroup(one, sol_label, many) # Initial conditions ic_label = Text("Initial conditions") ic_label.rotate(90 * DEGREES) ic_label.next_to(axes.y_axis, LEFT) x0_tracker = ValueTracker(1) get_x0 = x0_tracker.get_value x0_label = VGroup( OldTex("x_0 = ", font_size=36), DecimalNumber(1, font_size=36), ) x0_label.set_color(MAROON_B) x0_label[1].match_height(x0_label[0]) x0_label[1].next_to(x0_label[0][0][2], RIGHT, SMALL_BUFF) x0_label.add_updater(lambda m: m[1].set_value(get_x0()).set_color(MAROON_B)) sv = x0_label.get_width() + MED_SMALL_BUFF x0_label.add_updater(lambda m: m.move_to(axes.c2p(0, get_x0()), LEFT).shift(sv * LEFT)) self.play( Write(ic_label), run_time=1, ) self.play( dot.animate.move_to(axes.c2p(0, 1)), graphs.animate.set_stroke(opacity=0.5), run_time=2, ) self.wait() graph.add_updater(lambda g: g.match_points(get_graph(get_x0()))) dot.add_updater(lambda d: d.move_to(axes.c2p(0, get_x0()))) rect = BackgroundRectangle(x0_label) rect.set_fill(BLACK, 1) self.add(x0_label, rect, ic_label) self.play( FadeOut(rect), FadeOut(ic_label), self.camera.frame.animate.shift(0.6 * LEFT) ) self.wait() self.play( x0_tracker.animate.set_value(0.1), ) self.wait() for x in [5, 9]: self.play( x0_tracker.animate.set_value(x), run_time=5 ) self.wait() self.play( x0_tracker.animate.set_value(1), run_time=3, ) self.wait() # Show general solution new_sol_label = Text("General solution", font_size=36) new_sol_label.move_to(sol_label, LEFT) self.play( TransformFromCopy(x0_label[0][0][:2], solution[-1]), sol_arrow.animate.become(Arrow(sol_label, solution)) ) self.play( FadeOut(sol_label), FadeIn(new_sol_label), ) self.wait() rhs = solution[4:].copy() rhs_rect = SurroundingRectangle(rhs, stroke_width=2) rhs.generate_target() index = equation.index_of_part(equation.get_parts_by_tex("x")[1]) rhs.target.move_to(equation[index], LEFT) rhs.target.shift(0.05 * UP) self.play(ShowCreation(rhs_rect)) self.play( MoveToTarget(rhs), MaintainPositionRelativeTo(rhs_rect, rhs), FadeOut(equation[index:]), FadeOut(eq_arrow), FadeOut(eq_label), ) self.play(FadeOut(rhs_rect)) self.wait() self.play(x0_tracker.animate.set_value(2.5), run_time=2) self.play(x0_tracker.animate.set_value(0.5), run_time=2) self.wait() self.play( FadeOut(rhs), FadeIn(equation[index:]), FadeIn(eq_arrow), FadeIn(eq_label), ) self.wait() # Emphasize solution vs action exp_rect = SurroundingRectangle(solution[4:7], buff=0.05, stroke_width=2) words1 = Text("Don't think of this\n\n as a solution", font_size=30) words2 = Text( "It's something which\n\nacts on an initial condition\n\nto give a solution", t2s={"acts": ITALIC}, t2c={"acts": YELLOW, "initial condition": MAROON_B}, font_size=30 ) for words in [words1, words2]: words.next_to(exp_rect, DOWN, MED_LARGE_BUFF) words.set_stroke(BLACK, 5, background=True) self.play( ShowCreation(exp_rect), Write(words1, run_time=1) ) self.wait(2) self.play( FadeOut(words1), FadeIn(words2), ) self.wait(2) class ExoticExponentsWithEBase(Scene): def construct(self): # Write exotic exponents exps = VGroup( OldTex("e", "^{it}"), get_matrix_exponential([[3, 1], [4, 1]]), OldTex("e", "^{((i + j + k) / \\sqrt{3})t}"), OldTex("e", "^{\\left(\\frac{\\partial}{\\partial x}\\right)t}"), ) for i in (0, 2, 3): exps[i][0].scale(1.25) exps[i][0].move_to(exps[i][1:].get_corner(DL), UR) exps[1].scale(exps[0][0].get_height() / exps[1][0].get_height()) exps.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) labels = VGroup( Text("Complex numbers", font_size=30), Text("Matrices", font_size=30), Text("Quaternions", font_size=30), Text("Operators", font_size=30), ) labels.set_submobject_colors_by_gradient(BLUE_B, BLUE_C) for label, exp in zip(labels, exps): label.move_to(exp, DL) label.align_to(labels[0], LEFT) labels.set_x(-2) exps.set_x(labels.get_right()[0] + 3) arrow = Arrow(labels.get_corner(UL), labels.get_corner(DL), buff=0) arrow.shift(0.5 * LEFT) arrow.set_color(TEAL) exotic_label = OldTexText("More\\\\exotic\\\\exponents", alignment="") exotic_label.next_to(arrow, LEFT) VGroup(arrow, exotic_label).set_opacity(0) e_mobs = VGroup() for label, exp in zip(labels, exps): e_mobs.add(exp[0]) self.play( FadeIn(label), FadeIn(exp[0]), GrowFromPoint(exp[1:], exp[0].get_center()), exotic_label.animate.set_opacity(1), arrow.animate.set_opacity(1), ) self.wait() self.play(LaggedStart(*( FlashAround(e, buff=0.05, time_width=3, run_time=2) for e in e_mobs ), lag_ratio=0.1)) self.wait() # Analytic number theory exception zeta = OldTex("\\sum_{n = 1}^\\infty \\frac{1}{n^s}") zeta.move_to(exps[0], LEFT) self.play( FadeOut(exps[0]), FadeIn(zeta), ) self.wait() self.play( FadeOut(zeta), FadeIn(exps[0]), ) self.wait() # Other bases n_mob_groups = VGroup() for n in ["2", "5", "\\pi", "1{,}729"]: n_mobs = VGroup() for e_mob in e_mobs: n_mob = OldTex(n) n_mob.match_height(e_mob) n_mob.scale(1.2) n_mob.move_to(e_mob, UR) n_mob.shift(0.025 * DL) n_mobs.add(n_mob) n_mob_groups.add(n_mobs) for color, group in zip([YELLOW, GREEN_B, RED, MAROON_B], n_mob_groups): group.set_color(color) last_group = e_mobs for group in [*n_mob_groups, e_mobs]: self.play( LaggedStartMap(FadeOut, last_group, lag_ratio=0.2), LaggedStartMap(FadeIn, group, lag_ratio=0.2), run_time=1.5, ) self.wait() last_group = group # Show which equations are solved. equations = VGroup( OldTex("\\frac{dz}{dt}(t) = i \\cdot z(t)"), get_2d_equation([["3", "1"], ["4", "1"]]), OldTex("\\frac{dq}{dt}(t) = \\frac{i + j + k}{ \\sqrt{3} } \\cdot q(t)"), OldTex("{\\partial \\over \\partial t}f(x, t) = {\\partial \\over \\partial x}f(x, t)"), ) for eq, exp in zip(equations, exps): eq.match_height(exp) eq.move_to(exp, DL) eq.align_to(equations[0], LEFT) equations.to_edge(RIGHT) self.play( FadeOut(arrow, 3 * LEFT), FadeOut(exotic_label, 3 * LEFT), VGroup(labels, exps).animate.to_edge(LEFT), LaggedStartMap(FadeIn, equations, run_time=3, lag_ratio=0.5) ) self.wait() self.play( VGroup( labels[0], labels[2:], exps[0], exps[2:], equations[0], equations[2:] ).animate.set_opacity(0.3), equations[1].animate.scale(1.5, about_edge=RIGHT), exps[1].animate.scale(1.5), labels[1].animate.scale(1.5, about_edge=LEFT), ) self.wait() class TryToDefineExp(TeacherStudentsScene): CONFIG = { "background_color": BLACK, } def construct(self): words = OldTexText( "Try to define {{$e^{M}$}} to\\\\make sure this is true!", ) words[1][1].set_color(TEAL) self.play( PiCreatureSays(self.teacher, words, target_mode="surprised"), self.change_students("pondering", "thinking", "pondering"), ) for pi in self.students: for eye in pi.eyes: eye.refresh_bounding_box() self.look_at(4 * UP + 2 * RIGHT) self.wait(6) class SolutionsToMatrixEquation(From2DTo1D): show_solution = True class SolutionToRomeoJuliet(Scene): def construct(self): mat_exp = get_matrix_exponential( [["0", "-1"], ["1", "0"]], h_buff=1.0, ) solution = VGroup( Matrix( [["x(t)"], ["y(t)"]], bracket_h_buff=SMALL_BUFF, bracket_v_buff=SMALL_BUFF, ), OldTex("="), mat_exp, Matrix( [["x(0)"], ["y(0)"]], bracket_h_buff=SMALL_BUFF, bracket_v_buff=SMALL_BUFF, ) ) solution[2].match_height(solution[0]) solution[3].match_height(solution[0]) solution.arrange(RIGHT) self.add(solution) self.wait() rect = SurroundingRectangle(mat_exp, buff=0.1) rect_copy = rect.copy() self.play(ShowCreation(rect)) self.wait() self.play(rect.animate.become(SurroundingRectangle(solution[-1], color=BLUE))) self.wait() rot_question = Text("Rotation?") rot_question.next_to(rect_copy, DOWN) rot_question.set_color(YELLOW) self.play( rect.animate.become(rect_copy), Write(rot_question) ) self.wait() class RotMatrixStill(Scene): def construct(self): mat = IntegerMatrix([[0, -1], [1, 0]]) br = BackgroundRectangle(mat, buff=SMALL_BUFF) br.set_fill(BLACK, 1) self.add(br, mat) class ExpRotMatrixComputation(Scene): def construct(self): # Plug Mt into series mat_exp = get_matrix_exponential([[0, -1], [1, 0]]) mat_exp.to_corner(UL) mat_exp[1].set_color(TEAL) equation = OldTex( "e^X", ":=", "X^0 + X^1 + \\frac{1}{2} X^2 + \\frac{1}{6} X^3 + \\cdots + \\frac{1}{n!} X^n + \\cdots", isolate=["X", "+"], ) equation.set_width(FRAME_WIDTH - 1) equation.to_edge(UP) self.add(equation) rhs_tex = "{t}^0 X^0 + {t}^1 X^1 + \\frac{1}{2} {t}^2 X^2 + \\frac{1}{6} {t}^3 X^3 + \\cdots + \\frac{1}{n!} {t}^n X^n + \\cdots" mat_tex = "\\left[ \\begin{array}{cc} 0 & -1 \\\\ 1 & 0 \\end{array} \\right]" mat_rhs = OldTex( rhs_tex.replace("X", mat_tex), tex_to_color_map={mat_tex: TEAL}, isolate=["{t}", "+"], ) mat_rhs.scale(0.5) mat_equals = OldTex("=") mat_exp.match_height(mat_rhs) mat_equation = VGroup(mat_exp, mat_equals, mat_rhs) mat_equation.arrange(RIGHT) mat_exp.align_to(mat_rhs, DOWN) mat_equation.set_width(FRAME_WIDTH - 1) mat_equation.next_to(equation, DOWN, LARGE_BUFF) self.wait() self.play(LaggedStart( FadeTransform(equation[:2].copy(), mat_equation[0]), FadeTransform(equation[2].copy(), mat_equation[1]), *( FadeTransform(equation[i].copy(), mat_equation[2][j]) for i, j in zip( # Christ... [3, 4, 3, 4, 5, 6, 7, 6, 7, 8, 9, 10, 11, 10, 11, 12, 13, 14, 15, 14, 15, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23], it.count() ) ), run_time=2, lag_ratio=0.02 )) self.wait() # Show first few powers new_eq = mat_equation.copy() new_eq.shift(1.5 * DOWN) kw = {"bracket_h_buff": 0.25} m0 = IntegerMatrix([[1, 0], [0, 1]], **kw) m1 = IntegerMatrix([[0, -1], [1, 0]], **kw) m2 = IntegerMatrix([[-1, 0], [0, -1]], **kw) m3 = IntegerMatrix([[0, 1], [-1, 0]], **kw) mat_powers = VGroup(m0, m1, m2, m3) mat_powers.set_submobject_colors_by_gradient(BLUE, GREEN, RED) indices = [2, 7, 13, 19] for mat_power, index in zip(mat_powers, indices): mat_power.replace(new_eq[2][index], dim_to_match=0) mat_power.source = mat_equation[2][index:index + 2] new_eq[2][index: index + 2].set_opacity(0) self.play(LaggedStart( TransformFromCopy(mat_equation[0], new_eq[0]), TransformFromCopy(mat_equation[1], new_eq[1]), *( TransformFromCopy(mat_equation[2][i], new_eq[2][i]) for i in range(21) if i not in indices and i - 1 not in indices ), lag_ratio=0.01 )) rect = SurroundingRectangle(mat_powers[0].source, buff=0.05) rect.set_stroke(width=0) for mat_power in mat_powers: self.play(rect.animate.become(SurroundingRectangle(mat_power.source, buff=0.05)), run_time=0.5) self.play(FadeTransform(mat_power.source.copy(), mat_power)) self.wait(0.5) self.wait() self.play(rect.animate.move_to(mat_equation[2][27:29])) # Show cycling pattern rows = VGroup() for i in range(2): row = VGroup() for j in range(4): mat_power_copy = mat_powers[j].deepcopy() power = str(4 * (i + 1) + j) coef = OldTex("+\\frac{1}{" + power + "!} t^{" + power + "}") coef.match_height(mat_equation[2][10]) coef.next_to(mat_power_copy, LEFT, SMALL_BUFF) row.add(coef, mat_power_copy) row.shift(1.1 * (i + 1) * DOWN) rows.add(row) dots = OldTex("+ \\cdots", font_size=24) dots.next_to(rows, DOWN, aligned_edge=LEFT) for row in rows: for coef, mp in zip(row[0::2], row[1::2]): new_rect = SurroundingRectangle(mp, buff=0.05) self.add(coef, mp, new_rect) self.wait(0.5) self.remove(new_rect) self.play(Write(dots)) self.wait() # Setup for new rhs lhs = mat_equation[:2] self.play( lhs.animate.scale(2).to_corner(UL).shift(DOWN), FadeOut(VGroup(mat_equation[2], rect, equation)) ) # Show massive rhs rhs = Matrix( [ [ "1 - \\frac{t^2}{2!} + \\frac{t^4}{4!} - \\frac{t^6}{6!} + \\cdots", "-t + \\frac{t^3}{3!} - \\frac{t^5}{5!} + \\frac{t^7}{7!} - \\cdots", ], [ "t - \\frac{t^3}{3!} + \\frac{t^5}{5!} - \\frac{t^7}{7!} + \\cdots", "1 - \\frac{t^2}{2!} + \\frac{t^4}{4!} - \\frac{t^6}{6!} + \\cdots", ], ], h_buff=6, v_buff=2, ) rhs.set_width(10) rhs.next_to(lhs, RIGHT) power_entry_rects = VGroup(*(VGroup() for x in range(4))) for group in [mat_powers, rows[0][1::2], rows[1][1::2]]: for mat_power in group: for i, entry in enumerate(mat_power.get_entries()): rect = SurroundingRectangle(entry, buff=0.05) rect.set_stroke(YELLOW, 2) power_entry_rects[i].add(rect) self.play(Write(rhs.get_brackets())) last_per = power_entry_rects[0].copy() last_per.set_opacity(0) last_rect = VMobject() for entry, per in zip(rhs.get_entries(), power_entry_rects): rect = VGroup(SurroundingRectangle(entry, stroke_width=1)) self.play( ReplacementTransform(last_per, per), FadeIn(entry), FadeIn(rect), FadeOut(last_rect), ) self.wait() last_per = per last_rect = rect self.play(FadeOut(last_per), FadeOut(last_rect)) self.wait() # Show collapse to trig functions low_terms = VGroup(new_eq[2][:21], mat_powers, rows, dots) new_lhs = lhs.copy() new_lhs.next_to(rhs, DOWN, LARGE_BUFF) new_lhs.align_to(lhs, LEFT) final_result = Matrix( [["\\cos(t)", "-\\sin(t)"], ["\\sin(t)", "\\cos(t)"]], h_buff=2.0 ) final_result.next_to(new_lhs, RIGHT) anims = [] colors = [BLUE_B, BLUE_D, BLUE_D, BLUE_B] for color, entry1, entry2 in zip(colors, rhs.get_entries(), final_result.get_entries()): anims.append(entry1.animate.set_color(color)) entry2.set_color(color) self.play( *anims, FadeOut(low_terms, shift=2 * DOWN), ReplacementTransform(new_eq[:2], new_lhs), TransformFromCopy(rhs.get_brackets(), final_result.get_brackets()), ) self.wait() last_rects = VGroup() for entry1, entry2 in zip(rhs.get_entries(), final_result.get_entries()): rect1 = SurroundingRectangle(entry1, stroke_width=1) rect2 = SurroundingRectangle(entry2, stroke_width=1) self.play( FadeIn(rect1), FadeIn(rect2), FadeIn(entry2), FadeOut(last_rects), ) last_rects = VGroup(rect1, rect2) self.play(FadeOut(last_rects)) self.wait() # Ask question question = OldTexText("What transformation\\\\is this?") question.next_to(final_result, RIGHT, buff=1.5) question.shift_onto_screen() arrow = Arrow(question, final_result, buff=SMALL_BUFF) self.play( FadeIn(question, shift=0.5 * RIGHT), GrowArrow(arrow) ) self.wait() # Highlight result high_eq = VGroup(lhs, rhs) low_eq = VGroup(new_lhs, final_result) self.play(LaggedStart( FadeOut(high_eq, UP), FadeOut(VGroup(question, arrow)), low_eq.animate.center().to_edge(UP), lag_ratio=0.05 )) self.wait() class ThatsHorrifying(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("You want us to\\\\do what?"), index=2, target_mode="pleading", added_anims=[LaggedStart( self.students[0].change("tired"), self.students[1].change("horrified"), self.teacher.change("guilty"), lag_ratio=0.5 )] ) for pi in self.pi_creatures: for eye in pi.eyes: # Why? eye.refresh_bounding_box() self.look_at(self.screen) self.wait(2) self.teacher_says( "Just wait", bubble_config={"height": 3, "width": 3.5}, target_mode="tease" ) self.play_student_changes( "pondering", "thinking", "hesitant", look_at=self.screen, ) self.wait(3) class LinearAlgebraWrapper(VideoWrapper): title = "Matrices as linear transformations" class HowBasisVectorMultiplicationPullsOutColumns(Scene): def construct(self): # Setup plane = NumberPlane() plane.scale(2.5) plane.shift(1.5 * DOWN) b_plane = plane.copy() b_plane.set_color(GREY_B) plane.add_coordinate_labels() self.add(b_plane, plane) matrix = Matrix( [["a", "b"], ["c", "d"]], h_buff=0.8, ) matrix.to_corner(UL) matrix.to_edge(LEFT, buff=MED_SMALL_BUFF) matrix.add_to_back(BackgroundRectangle(matrix)) self.add(matrix) basis_vectors = VGroup( Arrow(plane.get_origin(), plane.c2p(1, 0), buff=0, fill_color=GREEN), Arrow(plane.get_origin(), plane.c2p(0, 1), buff=0, fill_color=RED), ) bhb = 0.2 basis_labels = VGroup( Matrix([["1"], ["0"]], bracket_h_buff=bhb), Matrix([["0"], ["1"]], bracket_h_buff=bhb), ) for vector, label, direction in zip(basis_vectors, basis_labels, [UR, RIGHT]): label.scale(0.7) label.match_color(vector) label.add_to_back(BackgroundRectangle(label)) label.next_to(vector.get_end(), direction) # Show products basis_label_copies = basis_labels.deepcopy() rhss = VGroup( Matrix([["a"], ["c"]], bracket_h_buff=bhb), Matrix([["b"], ["d"]], bracket_h_buff=bhb), ) colors = [GREEN, RED] def show_basis_product(index, matrix): basis_label_copies[index].match_height(matrix) basis_label_copies[index].next_to(matrix, RIGHT, SMALL_BUFF), equals = OldTex("=") equals.next_to(basis_label_copies[index], RIGHT, SMALL_BUFF) rhss[index].next_to(equals, RIGHT, SMALL_BUFF) rhss[index].set_color(colors[index]) rhs_br = BackgroundRectangle(rhss[index]) self.play( FadeIn(basis_labels[index], RIGHT), GrowArrow(basis_vectors[index]), FadeIn(basis_label_copies[index]), FadeIn(equals), FadeIn(rhs_br), FadeIn(rhss[index].get_brackets()), ) rect_kw = {"stroke_width": 2, "buff": 0.1} row_rects = [ SurroundingRectangle(row, **rect_kw) for row in matrix.get_rows() ] col_rect = SurroundingRectangle(basis_label_copies[index].get_entries(), **rect_kw) col_rect.set_stroke(opacity=0) last_row_rect = VMobject() for e1, e2, row_rect in zip(matrix.get_columns()[index], rhss[index].get_entries(), row_rects): self.play( col_rect.animate.set_stroke(opacity=1), FadeIn(row_rect), FadeOut(last_row_rect), e1.animate.set_color(colors[index]), FadeIn(e2), ) last_row_rect = row_rect self.play(FadeOut(last_row_rect), FadeOut(col_rect)) rhss[index].add_to_back(rhs_br) rhss[index].add(equals) low_matrix = matrix.deepcopy() show_basis_product(0, matrix) self.wait() self.play(low_matrix.animate.shift(2.5 * DOWN)) show_basis_product(1, low_matrix) self.wait() class ColumnsToBasisVectors(ExternallyAnimatedScene): pass class ReadColumnsOfRotationMatrix(Scene): show_exponent = False def construct(self): # Setup plane = NumberPlane(faded_line_ratio=0) plane.scale(3.0) plane.shift(1.5 * DOWN) b_plane = plane.copy() b_plane.set_color(GREY_B) b_plane.set_stroke(opacity=0.5) angle = 50 * DEGREES plane2 = plane.copy().apply_matrix([ [math.cos(angle), 0], [math.sin(angle), 1], ], about_point=plane.get_origin()) plane3 = plane.copy().apply_matrix([ [math.cos(angle), -math.sin(angle)], [math.sin(angle), math.cos(angle)], ], about_point=plane.get_origin()) coords = plane.deepcopy().add_coordinate_labels((-2, -1, 1, 2), (-1, 1)) self.add(b_plane, plane, coords) equation = VGroup( get_matrix_exponential([[0, -1], [1, 0]]), OldTex("="), Matrix( [["\\cos(t)", "-\\sin(t)"], ["\\sin(t)", "\\cos(t)"]], h_buff=2.0 ) ) exp, eq, matrix = equation exp[1].set_color(TEAL) exp[1].add_background_rectangle() matrix.add_background_rectangle() equation.arrange(RIGHT) equation.set_width(6) equation.to_corner(UL) if not self.show_exponent: equation.remove(*equation[:2]) equation.set_height(1.5) equation.to_corner(UL) self.add(equation) basis_vectors = VGroup( Arrow(plane.get_origin(), plane.c2p(1, 0), buff=0, fill_color=GREEN), Arrow(plane.get_origin(), plane.c2p(0, 1), buff=0, fill_color=RED), ) basis_shadows = basis_vectors.copy() basis_shadows.set_fill(opacity=0.5) self.add(basis_shadows, basis_vectors) self.play(FlashAround(matrix.get_columns()[0], color=GREEN)) self.wait() # Show action on basis vectors rot_b0, rot_b1 = rot_basis_vectors = basis_vectors.copy() for rot_b in rot_basis_vectors: rot_b.rotate(angle, about_point=plane.get_origin()) rbl0, rbl1 = rot_basis_labels = VGroup( Matrix([["\\cos(t)"], ["\\sin(t)"]]), Matrix([["-\\sin(t)"], ["\\cos(t)"]]), ) for label, color, rot_b, direction in zip(rot_basis_labels, [GREEN, RED], rot_basis_vectors, [UR, LEFT]): label.set_color(color) label.scale(0.7) label.next_to(rot_b.get_end(), direction, SMALL_BUFF) label.add_background_rectangle() arcs = VGroup( Arc(0, angle, arc_center=plane.get_origin(), radius=0.5), Arc(PI / 2, angle, arc_center=plane.get_origin(), radius=0.5), ) arcs.set_stroke(WHITE, 2) arc_label = OldTexText("$t$", " ") arc_label.next_to(arcs[0], RIGHT, SMALL_BUFF) arc_label.shift(SMALL_BUFF * UP) h_line = DashedLine(plane.get_origin(), plane.c2p(math.cos(angle), 0)) v_line = DashedLine(plane.c2p(math.cos(angle), 0), plane.c2p(math.cos(angle), math.sin(angle))) cos_label = matrix.get_entries()[0].copy().next_to(h_line, DOWN, SMALL_BUFF) sin_label = matrix.get_entries()[2].copy().next_to(v_line, RIGHT, SMALL_BUFF) self.play( TransformFromCopy(matrix[0], rbl0[0]), # Background rectangles TransformFromCopy(matrix.get_brackets(), rbl0.get_brackets()), TransformFromCopy(matrix.get_columns()[0], rbl0.get_entries()), Transform(plane, plane2, path_arc=angle), Transform(basis_vectors[0], rot_b0, path_arc=angle), Animation(matrix.get_columns()[1]), run_time=2, ) rects = VGroup(*( SurroundingRectangle(entry, color=WHITE, stroke_width=2, buff=0.05) for entry in rbl0.get_entries() )) self.play( ShowCreation(h_line), FadeIn(rects[0]), FadeIn(cos_label), ) self.play( ShowCreation(v_line), FadeOut(rects[0]), FadeIn(rects[1]), FadeIn(sin_label), ) self.play(FadeOut(rects[1])) self.wait() self.play(FlashAround(matrix.get_columns()[1], color=RED)) self.play( TransformFromCopy(matrix[0], rbl1[0]), # Background rectangles TransformFromCopy(matrix.get_brackets(), rbl1.get_brackets()), TransformFromCopy(matrix.get_columns()[1], rbl1.get_entries()), Transform(plane, plane3, path_arc=angle), Transform(basis_vectors[1], rot_b1, path_arc=angle), Animation(matrix.get_columns()[0]), run_time=2, ) self.wait() self.play( FadeIn(arc_label), *map(ShowCreation, arcs), ) self.wait() class ReadColumnsOfRotationMatrixWithExp(ReadColumnsOfRotationMatrix): show_exponent = True class AnalyzeRomeoAndJulietSpace(RomeoJulietVectorSpace): def construct(self): # Add axes axes = self.get_romeo_juliet_axes() ps_dot = axes.ps_dot ps_dot.set_opacity(0) ps_dot.move_to(axes.c2p(4, 3)) ps_arrow = self.get_ps_arrow(axes, add_shadow=True) ps_arrow.update() self.add(ps_arrow) # Add equation matrix = [["0", "-1"], ["1", "0"]] equation = get_2d_equation(matrix) equation.to_corner(UR) implies = OldTex("\\Downarrow", font_size=72) implies.next_to(equation, DOWN, buff=0.3) initial_condition = Matrix([["x_0"], ["y_0"]], bracket_h_buff=0.1) initial_condition.match_height(equation) initial_condition.set_color(BLUE_B) ic_source = initial_condition.copy() ic_source.scale(0.5) ic_source.next_to(ps_arrow.get_end(), RIGHT, SMALL_BUFF) mat_exp = get_matrix_exponential(matrix, h_buff=0.8) solution = VGroup(equation[1].copy(), OldTex("="), mat_exp, initial_condition) solution[2][1].set_color(TEAL) solution.arrange(RIGHT) solution.scale(0.8) solution.next_to(implies, DOWN, buff=0.3) rot_matrix = Matrix( [["\\cos(t)", "-\\sin(t)"], ["\\sin(t)", "\\cos(t)"]], bracket_h_buff=0.2, h_buff=2.0 ) for entry in rot_matrix.get_entries(): entry[0][-2].set_color(GREY_B) rot_matrix.match_height(solution[0]) solution2 = solution.deepcopy() solution2.replace_submobject(2, rot_matrix) solution2.arrange(RIGHT) solution2.next_to(solution, DOWN, buff=0.7) rot_matrix_brace = Brace(rot_matrix, DOWN) rot_label = OldTexText("Rotate by angle $t$") rot_label.next_to(rot_matrix_brace, DOWN, SMALL_BUFF) self.add(equation) self.play(FlashAround(equation, run_time=2)) self.wait() self.play( Write(implies), TransformFromCopy(equation[1], solution[0], path_arc=-20 * DEGREES), TransformFromCopy(equation[2], solution[1]), ) self.play( Write(mat_exp[0]), TransformFromCopy(equation[3], mat_exp[1]), ) self.play(Write(mat_exp[2])) self.wait() self.play( FadeIn(ic_source), FlashAround(ic_source), ) self.play(TransformFromCopy(ic_source, initial_condition)) self.wait() self.play( *( TransformFromCopy(solution[i], solution2[i]) for i in [0, 1, 3] ), FadeTransform(mat_exp.copy(), rot_matrix) ) self.play( GrowFromCenter(rot_matrix_brace), FadeIn(rot_label), ) self.wait() # Rotate vector start_angle = ps_arrow.get_angle() t_tracker = ValueTracker(0) get_t = t_tracker.get_value def get_arc(): curr_time = get_t() arc = ParametricCurve( lambda s: axes.c2p(*tuple((1 + 0.2 * s) * np.array([ math.cos(start_angle + s * curr_time), math.sin(start_angle + s * curr_time), ]))), t_range=(0, 1, 0.01) ) arc.set_stroke(WHITE, 2) return arc arc = always_redraw(get_arc) t_label = VGroup(OldTex("t = ", font_size=30), DecimalNumber(font_size=24)) t_label.arrange(RIGHT, buff=SMALL_BUFF) def update_t_label(label): point = arc.pfp(0.5) label[1].set_value(get_t()) label.set_stroke(BLACK, 5, background=True) label.set_opacity(min(2 * get_t(), 1)) if get_t() < 3.65: target_point = point + 0.75 * (point - axes.get_origin()) label.shift(target_point - label[1].get_center()) t_label.add_updater(update_t_label) curr_xy = np.array(axes.p2c(ps_dot.get_center())) def update_ps_dot(dot): rot_M = np.array(rotation_matrix_transpose(get_t(), OUT))[:2, :2] new_xy = np.dot(curr_xy, rot_M) dot.move_to(axes.c2p(*new_xy)) ps_dot.add_updater(update_ps_dot) t_tracker.add_updater(lambda m, dt: m.increment_value(0.5 * dt)) self.add(arc, t_label, t_tracker, ps_dot) self.play(VFadeIn(t_label)) self.wait(16 * PI - 1) def get_romeo_juliet_axes(self, height=5): # Largely copied from RomeoJulietVectorSpace romeo, juliet = lovers = self.get_romeo_and_juliet() axes = Axes( x_range=(-5, 5), y_range=(-5, 5), height=height, width=height, axis_config={ "include_tip": False, "numbers_to_exclude": [], } ) axes.to_edge(LEFT) for axis in axes: axis.add_numbers(range(-4, 6, 2), color=GREY_A, font_size=12) axis.numbers[2].set_opacity(0) lovers.set_height(0.5) lovers.flip() juliet.next_to(axes.x_axis.get_end(), RIGHT) romeo.next_to(axes.y_axis.get_end(), UP) ps_dot = Dot(radius=0.04, fill_color=BLUE) ps_dot.move_to(axes.c2p(3, 1)) def get_xy(): # Get phase space point return axes.p2c(ps_dot.get_center()) self.make_romeo_and_juliet_dynamic(romeo, juliet) juliet.love_tracker.add_updater(lambda m: m.set_value(get_xy()[0])) romeo.love_tracker.add_updater(lambda m: m.set_value(get_xy()[1])) self.add(romeo.love_tracker, juliet.love_tracker) name_labels = self.get_romeo_juilet_name_labels(lovers, font_size=12, spacing=1.0, buff=0.05) axes.lovers = lovers axes.name_labels = name_labels axes.ps_dot = ps_dot axes.add(lovers, name_labels, ps_dot) self.add(axes) self.add(*lovers) self.add(*(pi.heart_eyes for pi in lovers)) return axes def get_ps_arrow(self, axes, color=BLUE, add_shadow=False): arrow = Arrow( LEFT, RIGHT, fill_color=color, thickness=0.04 ) arrow.add_updater(lambda m: m.put_start_and_end_on( axes.get_origin(), axes.ps_dot.get_center(), )) if add_shadow: ps_arrow_shadow = arrow.copy() ps_arrow_shadow.clear_updaters() ps_arrow_shadow.set_fill(BLUE, 0.5) self.add(ps_arrow_shadow) return arrow class GeometricReasoningForRomeoJuliet(AnalyzeRomeoAndJulietSpace): def construct(self): # Setup axes = self.get_romeo_juliet_axes() ps_dot = axes.ps_dot ps_dot.set_opacity(0) ps_dot.move_to(axes.c2p(4, 3)) ps_arrow = self.get_ps_arrow(axes) self.add(ps_arrow) matrix = [["0", "-1"], ["1", "0"]] equation = get_2d_equation(matrix) ddt, xy1, eq, mat, xy2 = equation equation.to_corner(UR) self.add(equation) # Show 90 degree rotation mat_brace = Brace(mat, DOWN, buff=SMALL_BUFF) mat_label = mat_brace.get_text("90-degree rotation matrix", font_size=30) mat_label.set_color(TEAL) self.play( GrowFromCenter(mat_brace), Write(mat_label, run_time=1) ) self.wait() # Spiral around to various points curve = VMobject() curve.set_points_smoothly( [ axes.c2p(x, y) for x, y in [(4, 3), (0, 2), (0, -1), (-3, -4), (-3, 2), (3, 1)] ], true_smooth=True ) self.play(MoveAlongPath(ps_dot, curve, run_time=5)) self.wait() # Rate of change deriv_vect = ps_arrow.copy() deriv_vect.clear_updaters() deriv_vect.set_color(RED) deriv_vect.shift(ps_arrow.get_vector()) deriv_rect = SurroundingRectangle(VGroup(ddt, xy1)) deriv_rect.set_stroke(RED, 2) d_line = DashedLine(ps_arrow.get_start(), ps_arrow.get_end()) d_line.shift(ps_arrow.get_vector()) d_line.set_stroke(WHITE, 1) arc = Arc( start_angle=ps_arrow.get_angle(), angle=90 * DEGREES, arc_center=ps_arrow.get_end(), radius=0.25 ) elbow = VMobject() elbow.set_points_as_corners([RIGHT, UR, UP]) elbow.scale(0.25, about_point=ORIGIN) elbow.rotate(ps_arrow.get_angle(), about_point=ORIGIN) elbow.shift(ps_arrow.get_end()) VGroup(elbow, arc).set_stroke(WHITE, 2) self.play( TransformFromCopy(ps_arrow, deriv_vect, path_arc=30 * DEGREES), ShowCreation(deriv_rect), ) self.add(d_line, deriv_vect) self.play( ShowCreation(arc), Rotate(deriv_vect, 90 * DEGREES, about_point=ps_arrow.get_end()), run_time=2, rate_func=rush_into, ) self.remove(arc) self.add(elbow) self.wait() # Show rotation ps_arrow.clear_updaters() ps_dot.add_updater(lambda m: m.move_to(ps_arrow.get_end())) rot_group = VGroup(ps_arrow, d_line, elbow, deriv_vect) circle = Circle(radius=ps_arrow.get_length()) circle.set_stroke(GREY, 1) circle.move_to(axes.get_origin()) self.play( Rotate( rot_group, angle=TAU - ps_arrow.get_angle(), about_point=axes.get_origin(), run_time=6, rate_func=linear, ), FadeIn(circle), ) self.wait() # Show matching length self.play( deriv_vect.animate.put_start_and_end_on(ps_arrow.get_start(), ps_arrow.get_end()).shift(0.2 * UP), run_time=3, rate_func=there_and_back_with_pause, ) self.wait() # Show one radian of arc arc = Arc( 0, 1, radius=circle.radius, arc_center=axes.get_origin(), ) arc.set_stroke(YELLOW, 3) sector = Sector( start_angle=0, angle=1, outer_radius=circle.radius, ) sector.shift(axes.get_origin()) sector.set_stroke(width=0) sector.set_fill(GREY_D, 1) t_label = VGroup(OldTex("t = ", font_size=30), DecimalNumber(0, font_size=20)) t_label.arrange(RIGHT, buff=SMALL_BUFF) t_label.next_to(arc.pfp(0.5), UR, SMALL_BUFF) self.play( Rotate(rot_group, 1, about_point=axes.get_origin()), ShowCreation(arc), ChangeDecimalToValue(t_label[1], 1.0), VFadeIn(t_label), run_time=2, rate_func=linear, ) self.add(sector, axes, ps_arrow, arc) self.play(FadeIn(sector)) self.wait() radius = Line(axes.get_origin(), arc.get_start()) radius.set_stroke(RED, 5) self.play(ShowCreation(radius)) self.play(Rotate(radius, -PI / 2, about_point=radius.get_end())) radius.rotate(PI) self.play(radius.animate.match_points(arc)) self.play(FadeOut(radius)) self.wait() # One radian per unit time self.play( t_label.animate.shift(UP).scale(2), ) t_label[1].data["font_size"] *= 2 for x in range(5): VGroup(sector, arc).rotate(1, about_point=axes.get_origin()) self.play( Rotate(rot_group, 1, about_point=axes.get_origin()), ChangeDecimalToValue(t_label[1], t_label[1].get_value() + 1), run_time=2, rate_func=linear, ) self.play( FadeOut(VGroup(sector, arc)), Rotate(rot_group, TAU - 6, about_point=axes.get_origin()), ChangeDecimalToValue(t_label[1], TAU), run_time=2 * (TAU - 6), rate_func=linear, ) self.wait(2) t_label[1].set_value(0) self.play( Rotate(rot_group, PI, about_point=axes.get_origin()), ChangeDecimalToValue(t_label[1], PI), run_time=2 * PI, rate_func=linear, ) self.wait(2) class Show90DegreeRotation(Scene): def construct(self): plane = NumberPlane() plane.scale(2.5) back_plane = plane.deepcopy() back_plane.set_stroke(color=GREY, opacity=0.5) back_plane.add_coordinate_labels() vects = VGroup( Arrow(plane.get_origin(), plane.c2p(1, 0), fill_color=GREEN, buff=0, thickness=0.075), Arrow(plane.get_origin(), plane.c2p(0, 1), fill_color=RED, buff=0, thickness=0.075), ) plane.add(*vects) plane.set_stroke(background=True) self.add(back_plane, plane) self.wait() self.play(Rotate(plane, 90 * DEGREES, run_time=3)) self.wait() class Show90DegreeRotationColumnByColumn(Scene): def construct(self): plane = NumberPlane() plane.scale(2.5) back_plane = plane.deepcopy() back_plane.set_stroke(color=GREY, opacity=0.5) back_plane.add_coordinate_labels() plane2 = plane.copy() plane3 = plane.copy() plane2.apply_matrix([[0, 0], [1, 1]]) plane3.apply_matrix([[0, -1], [1, 0]]) vects = VGroup( Arrow(plane.get_origin(), plane.c2p(1, 0), fill_color=GREEN, buff=0, thickness=0.075), Arrow(plane.get_origin(), plane.c2p(0, 1), fill_color=RED, buff=0, thickness=0.075), ) self.add(back_plane, plane, *vects) self.wait() self.play( Transform(plane, plane2, path_arc=90 * DEGREES), Rotate(vects[0], 90 * DEGREES, about_point=plane.get_origin()), run_time=2 ) self.wait() self.play( Transform(plane, plane3, path_arc=90 * DEGREES), Rotate(vects[1], 90 * DEGREES, about_point=plane.get_origin()), run_time=2 ) self.wait() arc = Arc(5 * DEGREES, 80 * DEGREES, buff=0.1, radius=1.5) arc.set_stroke(width=3) arc.add_tip(width=0.15, length=0.15) arc2 = arc.copy().rotate(PI, about_point=ORIGIN) arcs = VGroup(arc, arc2) arcs.set_color(GREY_B) self.play(*map(ShowCreation, arcs)) self.wait() class DistanceOverTimeEquation(Scene): def construct(self): equation = OldTex( "{\\text{Distance}", " \\over", " \\text{Time} }", "=", "\\text{Radius}", ) # equation[:3].set_color(RED_B) equation.add(SurroundingRectangle(equation[:3], color=RED, stroke_width=1)) equation[4].set_color(BLUE) self.play(FadeIn(equation, UP)) self.wait() class ExplicitSolution(Scene): def construct(self): kw = {"tex_to_color_map": { "x_0": BLUE_D, "y_0": BLUE_B, "{t}": GREY_B, }} solutions = VGroup( OldTex("x({t}) = \\cos(t) x_0 - \\sin(t) y_0", **kw), OldTex("y({t}) = \\sin(t) x_0 + \\cos(t) y_0", **kw), ) solutions.arrange(DOWN, buff=MED_LARGE_BUFF) for solution in solutions: self.play(Write(solution)) self.wait() class TwoDifferetViewsWrapper(Scene): def construct(self): self.add(FullScreenRectangle()) screens = VGroup(*(ScreenRectangle() for x in range(2))) screens.arrange(RIGHT) screens.set_width(FRAME_WIDTH - 1) screens.set_fill(BLACK, 1) screens[0].set_stroke(BLUE, 2) screens[1].set_stroke(GREY_BROWN, 2) self.add(screens) titles = VGroup( Text("Geometric"), Text("Analytic"), ) for title, screen in zip(titles, screens): title.next_to(screen, UP) title.align_to(titles[0], UP) self.play(Write(title)) self.wait() self.wait() class EulersFormulaWrapper(VideoWrapper): title = "Video on $e^{it}$" class ImaginaryExponent(ExternallyAnimatedScene): pass class ComplexEquation(Scene): def construct(self): # Equation equation = OldTex( """ \\frac{d}{d{t} } \\Big[ x(t) + {i}y(t)\\Big] = {i} \\cdot \\Big[ x(t) + {i}y(t) \\Big] """, tex_to_color_map={ "x": BLUE_B, "y": BLUE_D, "{t}": GREY_B, "=": WHITE, "\\cdot": WHITE, "{i}": RED, } ) equation.move_to(2 * UP) braces = VGroup(*( Brace(equation[i:j], UP, buff=SMALL_BUFF) for i, j in [(2, 8), (11, 17)] )) braces.set_fill(GREY_A, 1) for brace in braces: brace.zt = OldTex("z(t)", tex_to_color_map={"z": BLUE, "t": GREY_B}) brace.zt.next_to(brace, UP, SMALL_BUFF) self.add(equation) self.play( *(GrowFromCenter(b) for b in braces), *(FadeIn(b.zt, 0.25 * UP) for b in braces) ) self.wait() # Show romeo and juilet x_part = equation.get_part_by_tex("x") y_part = equation.get_part_by_tex("y") juliet_label = OldTexText("Juliet's love", font_size=30) juliet_label.next_to(x_part, DOWN, LARGE_BUFF) romeo_label = OldTexText("Romeo's love", font_size=30) romeo_label.next_to(y_part, DOWN, LARGE_BUFF) juliet_label.align_to(romeo_label, DOWN) VGroup(juliet_label, romeo_label).space_out_submobjects(1.5) juliet_arrow = Arrow(x_part, juliet_label, buff=0.1, fill_color=BLUE_B) romeo_arrow = Arrow(y_part, romeo_label, buff=0.1, fill_color=BLUE_D) self.play( GrowArrow(juliet_arrow), FadeIn(juliet_label), ) self.play( GrowArrow(romeo_arrow), FadeIn(romeo_label), ) self.wait() # Describe i i_part = equation.get_parts_by_tex("{i}")[1] i_label = OldTexText("90-degree rotation", font_size=30) i_label.set_color(RED) i_label.next_to(romeo_label, RIGHT, MED_LARGE_BUFF, aligned_edge=DOWN) i_arrow = Arrow(i_part, i_label, fill_color=RED) self.play( GrowArrow(i_arrow), FadeIn(i_label, DR), ) self.wait() all_labels = VGroup(romeo_label, juliet_label, i_label) # Show solution solution = OldTex( "z(t) = e^{it} z_0", tex_to_color_map={ "i": RED, "t": GREY_B, "z": BLUE, "=": WHITE, } ) solution.scale(1.5) solution.next_to(all_labels, DOWN, LARGE_BUFF) solution[8:].set_color(BLUE_D) self.play( TransformFromCopy(braces[0].zt, solution[:4]), Write(solution[4]), ) self.play( Write(solution[5]), TransformFromCopy(equation[9], solution[6]), Write(solution[7]), ) self.play( FadeIn(solution[8:], 0.1 * DOWN) ) self.wait() class JulietChidingRomeo(Scene): def construct(self): juliet = PiCreature(color=BLUE_B) romeo = PiCreature(color=BLUE_D) romeo.flip() pis = VGroup(juliet, romeo) pis.set_height(2) pis.arrange(RIGHT, buff=LARGE_BUFF) pis.to_edge(DOWN) romeo.make_eye_contact(juliet) self.add(pis) self.play( PiCreatureSays( juliet, OldTexText("It just seems like \\\\ your feelings aren't \\\\ real"), bubble_config={"height": 2.5, "width": 3.5}, target_mode="sassy", ), romeo.change("guilty"), ) for x in range(2): self.play(Blink(juliet)) self.play(Blink(romeo)) self.wait() class General90DegreeRotationExponents(Scene): def construct(self): # Setup exps = VGroup( get_matrix_exponential([["0", "-1"], ["1", "0"]]), OldTex("e^{it}", tex_to_color_map={"i": RED}), OldTex( "e^{(ai + bj + ck)t}", tex_to_color_map={ "i": RED, "j": GREEN, "k": BLUE, } ), OldTex( "e^{i \\sigma_x t}, \\quad ", "e^{i \\sigma_y t}, \\quad ", "e^{i \\sigma_z t}", tex_to_color_map={ "\\sigma_x": RED, "\\sigma_y": GREEN, "\\sigma_z": BLUE, } ), ) exps[0][1].set_color(TEAL) exps[0].scale(0.5) exps.arrange(DOWN, buff=1.5, aligned_edge=LEFT) labels = VGroup( OldTexText("$90^\\circ$ rotation matrix"), OldTexText("Imaginary numbers"), OldTexText("Quaternions"), OldTexText("Pauli matrices"), ) for label, exp in zip(labels, exps): label.scale(0.75) label.next_to(exp, LEFT, LARGE_BUFF, aligned_edge=DOWN) label.align_to(labels[0], LEFT) VGroup(exps, labels).to_edge(LEFT) quat_note = OldTex("(a^2 + b^2 + c^2 = 1)", font_size=24) quat_note.next_to(exps[2], DOWN, aligned_edge=LEFT) exps[2].add(quat_note) for exp, label in zip(exps, labels): self.play( FadeIn(exp), FadeIn(label), ) self.wait() class RotationIn3dPlane(Scene): def construct(self): # Axes and frame axes = ThreeDAxes() axes.set_stroke(width=2) axes.set_flat_stroke(False) frame = self.camera.frame frame.set_height(2.0 * FRAME_HEIGHT) frame.reorient(-40, 70) frame.add_updater(lambda f, dt: f.increment_theta(0.03 * dt)) self.add(axes, frame) # Plane plane = Surface() plane.replace(VGroup(axes.x_axis, axes.y_axis), stretch=True) plane.set_color(GREY_C, opacity=0.75) plane.set_gloss(1) grid = NumberPlane((-6, 6), (-5, 5), faded_line_ratio=0) radius = 3 p_vect = Vector(radius * RIGHT, fill_color=BLUE) v_vect = p_vect.copy() arc = Arc(0, PI / 2, radius=radius / 4) circle = Circle(radius=radius) circle.set_stroke(WHITE, 2) randy = Randolph(mode="pondering") randy.set_gloss(0.7) rot_group = Group(plane, grid, p_vect, v_vect, arc, circle, randy) normal = OUT for angle, axis in [(30 * DEGREES, RIGHT), (20 * DEGREES, UP)]: rot_group.rotate(angle, axis) normal = rotate_vector(normal, angle, axis) self.play( ShowCreation(plane), FadeIn(randy), ) self.play(GrowArrow(p_vect)) self.wait(2) self.play( Rotate(v_vect, PI / 2, axis=normal, about_point=axes.get_origin()), Rotate(randy, PI / 2, axis=normal, about_point=axes.get_origin()), UpdateFromAlphaFunc(v_vect, lambda m, a: m.set_fill(interpolate_color(BLUE, RED, a))), ShowCreation(arc), run_time=2, ) self.wait(3) self.play( v_vect.animate.shift(p_vect.get_end() - v_vect.get_start()), FadeOut(arc), FadeOut(randy), ) rot_group = VGroup(grid, p_vect, v_vect) rot_group.set_stroke(background=True) self.add(circle, rot_group) self.play( FadeIn(circle), Rotate( rot_group, 2 * TAU, axis=normal, about_point=axes.get_origin(), run_time=4 * TAU, rate_func=linear, ), VFadeIn(grid), ) class StoryForAnotherTime(TeacherStudentsScene): def construct(self): self.teacher_says( OldTexText("The full story\\\\takes more time."), bubble_config={"height": 3, "width": 3.5}, added_anims=[self.change_students("confused", "erm", "hesitant", look_at=self.screen)] ) self.wait(5) class SchrodingerSum(Scene): def construct(self): # Add title equation_label = VGroup( OldTexText("Schrödinger equation:"), OldTex( "{i} \\hbar \\frac{\\partial}{\\partial t} |\\psi(t)\\rangle = \\hat{H} |\\psi(t)\\rangle", tex_to_color_map={ "|\\psi(t)\\rangle": BLUE, "{i}": WHITE, "\\frac{\\partial}{\\partial t}": GREY_A, }, font_size=36 ) ) equation_label.arrange(RIGHT, buff=MED_LARGE_BUFF) equation_label.set_width(FRAME_WIDTH - 1) equation_label.to_edge(UP) i_part = equation_label[1].get_part_by_tex("{i}") self.add(equation_label) # Axes x_range = np.array([-5, 5, 1]) y_range = np.array([-1, 1, 0.5]) axes = ThreeDAxes( x_range=x_range, y_range=y_range, z_range=y_range, height=1.25, depth=1.25, width=4, axis_config={"include_tip": False, "tick_size": 0.05}, ) # plane = ComplexPlane(y_range, y_range) # plane.rotate(PI / 2, DOWN) # plane.match_depth(axes) # axes.add(plane) # axes.y_axis.set_opacity(0) # axes.z_axis.set_opacity(0) lil_axes = VGroup(*(axes.deepcopy() for x in range(3))) lil_axes.arrange(DOWN, buff=MED_LARGE_BUFF) lil_axes.to_corner(DL) brace = Brace(lil_axes, RIGHT, buff=MED_LARGE_BUFF) axes.scale(2) axes.next_to(brace, RIGHT) for ax in [axes, *lil_axes]: ax.rotate(-30 * DEGREES, UP) ax.rotate(10 * DEGREES, RIGHT) ax.set_flat_stroke(False) # Graphs def func0(x, t): magnitude = np.exp(-x * x / 2) phase = np.exp(complex(0, 0.5 * t)) return magnitude * phase def func1(x, t): magnitude = np.exp(-x * x / 2) * 2 * x magnitude *= 1 / math.sqrt(2) phase = np.exp(complex(0, 1.5 * t)) return magnitude * phase def func2(x, t): magnitude = -1 * np.exp(-x * x / 2) * (2 - 4 * x * x) magnitude *= 1 / math.sqrt(8) phase = np.exp(complex(0, 2.5 * t)) return magnitude * phase def comb_func(x, t): return (func0(x, t) + func1(x, t) + func2(x, t)) / 3 def to_xyz(func, x): z = func(x, get_t()) return (x, z.real, z.imag) t_tracker = ValueTracker() t_tracker.add_updater(lambda m, dt: m.increment_value(dt)) self.add(t_tracker) get_t = t_tracker.get_value def get_graph(axes, func, color): fade_tracker = ValueTracker(1) result = VGroup() graph = always_redraw(lambda: ParametricCurve( lambda x: axes.c2p(*to_xyz(func, x)), t_range=x_range[:2], color=color, stroke_opacity=fade_tracker.get_value(), flat_stroke=False, )) result.add(graph) for x in np.linspace(0, 1, 100): line = Line(stroke_color=color, stroke_width=2) line.x = x line.axes = axes line.graph = graph line.fade_tracker = fade_tracker line.add_updater(lambda m: m.set_points_as_corners([ m.axes.x_axis.pfp(m.x), m.graph.pfp(m.x), ]).set_opacity(0.5 * m.fade_tracker.get_value())) result.add(line) result.fade_tracker = fade_tracker return result graph0, graph1, graph2, comb_graph = graphs = [ get_graph(axes, func, color) for axes, func, color in zip( [*lil_axes, axes], [func0, func1, func2, comb_func], [BLUE, TEAL, GREEN, YELLOW] ) ] lil_axes[1].save_state() lil_axes[1].scale(2) lil_axes[1].move_to(DOWN) self.add(lil_axes[1], graph1) self.wait(10) self.add(*graphs) self.play( FadeIn(lil_axes[::2]), FadeIn(axes), Restore(lil_axes[1]), GrowFromCenter(brace), *( UpdateFromAlphaFunc(g.fade_tracker, lambda m, a: m.set_value(a)) for g in (*graphs[::2], comb_graph) ) ) self.wait(15) self.play( FlashAround(i_part, color=RED), i_part.animate.set_color(RED) ) self.wait(30) class BasicVectorFieldIdea(Scene): matrix = [[-1.5, -1], [3, 0.5]] def construct(self): # Equation v_tex = "\\vec{\\textbf{v} }(t)" equation = OldTex( "{d \\over dt}", v_tex, "=", "M", v_tex, tex_to_color_map={ "M": GREY_A, v_tex: YELLOW, } ) equation.set_height(1.5) equation.to_corner(UL, buff=0.25) background_rect = SurroundingRectangle(equation, buff=SMALL_BUFF) background_rect.set_fill(BLACK, opacity=0.9).set_stroke(WHITE, 2) # Plane and field matrix = np.array(self.matrix) def func(x, y): return 0.15 * np.dot(matrix.T, [x, y]) plane = NumberPlane() vector_field = VectorField( func, plane, magnitude_range=(0, 2), vector_config={"thickness": 0.025} ) dots = VGroup(*( Dot(v.get_start(), radius=0.02, fill_color=YELLOW) for v in vector_field )) # Velocity and position vel_rect = SurroundingRectangle(equation[:2], stroke_color=RED) pos_rect = SurroundingRectangle(equation[4], stroke_color=YELLOW) pos_rect.match_height(vel_rect, stretch=True) pos_rect.match_y(vel_rect) vel_words = Text("Velocity", color=RED) vel_words.next_to(vel_rect, DOWN) vel_words.shift_onto_screen(buff=0.2) pos_words = Text("Position", color=YELLOW) pos_words.next_to(pos_rect, DOWN) for word in vel_words, pos_words: word.add_background_rectangle() self.add(plane, background_rect, equation) self.play( ShowCreation(vel_rect), FadeIn(vel_words, 0.5 * DOWN), ) self.wait() self.play( ShowCreation(pos_rect), FadeIn(pos_words, 0.5 * DOWN), ) self.wait() term_labels = VGroup(vel_rect, vel_words, pos_rect, pos_words) foreground = [background_rect, equation, term_labels] self.add(dots, *foreground) self.play(LaggedStartMap(GrowFromCenter, dots)) self.add(dots, vector_field, *foreground) self.play(LaggedStartMap(GrowArrow, vector_field, lag_ratio=0.01)) self.wait() self.play( FadeOut(dots), FadeOut(term_labels), vector_field.animate.set_opacity(0.25) ) # Show Mv being attached to v index = 326 lil_vect = vector_field[index] coords = plane.p2c(lil_vect.get_start()) dot = Dot(color=YELLOW, radius=0.05) dot.move_to(plane.c2p(*coords)) dot_label = OldTex("\\vec{\\textbf{v}}", color=YELLOW) dot_label.next_to(dot, UR, SMALL_BUFF) vector = Arrow(plane.get_origin(), dot.get_center(), buff=0) vector.set_fill(YELLOW, opacity=1) vector.set_stroke(BLACK, 0.5) Mv = Arrow(plane.get_origin(), plane.c2p(*3 * func(*coords)), buff=0) Mv.set_fill(RED, 1) Mv_label = OldTex("M", "\\vec{\\textbf{v}}") Mv_label[0].set_color(GREY_B) Mv_label.next_to(Mv.get_end(), DOWN) attached_Mv = lil_vect.copy().set_opacity(1) self.play( GrowFromPoint(dot, equation[-1].get_center()), FadeTransform(equation[-1][0].copy(), dot_label), ) self.wait() self.play( FadeIn(vector), ReplacementTransform(vector.copy().set_opacity(0), Mv, path_arc=-45 * DEGREES), FadeTransform(equation[3:5].copy(), Mv_label), ) self.wait() self.play( TransformFromCopy(Mv, attached_Mv) ) self.remove(attached_Mv) lil_vect.set_opacity(1) self.wait() for x in range(100): index += 1 lil_vect = vector_field[index] coords = plane.p2c(lil_vect.get_start()) vector.put_start_and_end_on(plane.get_origin(), plane.c2p(*coords)) Mv.put_start_and_end_on(plane.get_origin(), plane.c2p(*3 * func(*coords))) Mv_label.next_to(Mv.get_end(), DOWN) dot.move_to(vector.get_end()) dot_label.next_to(dot, UR, SMALL_BUFF) lil_vect.set_opacity(1) if x < 20: self.wait(0.25) else: self.wait(0.1) self.play( LaggedStartMap(FadeOut, VGroup(Mv_label, dot_label, Mv, vector, dot)), vector_field.animate.set_opacity(1) ) self.wait() # Show example initial condition evolving def get_flow_lines(step_multiple, arc_len): return StreamLines( func, plane, step_multiple=step_multiple, magnitude_range=(0, 2), color_by_magnitude=False, stroke_color=GREY_A, stroke_width=2, stroke_opacity=1, arc_len=arc_len, ) dot = Dot() vect = Vector() vect.set_color(RED) def update_vect(vect): coords = plane.p2c(dot.get_center()) end = plane.c2p(*func(*coords)) vect.put_start_and_end_on(plane.get_origin(), end) vect.shift(dot.get_center() - plane.get_origin()) vect.add_updater(update_vect) flow_line = get_flow_lines(4, 20)[10] flow_line.insert_n_curves(100) flow_line.set_stroke(width=3) dot.move_to(flow_line.get_start()) self.add(flow_line, vect, dot) self.play( MoveAlongPath(dot, flow_line, run_time=10, rate_func=linear), ShowCreation(flow_line, run_time=10, rate_func=linear), VFadeIn(dot), VFadeIn(vect), ) self.play(LaggedStartMap(FadeOut, VGroup(flow_line, dot, vect))) self.wait() # Show exponential solution solution = OldTex( v_tex, "=", "e^{M t}", "\\vec{\\textbf{v} }(0)" ) solution[0].set_color(YELLOW) solution[2][1].set_color(GREY_B) solution.match_width(equation) solution.next_to(equation, DOWN, MED_LARGE_BUFF) new_br = SurroundingRectangle(VGroup(equation, solution), buff=MED_SMALL_BUFF) new_br.match_style(background_rect) self.play( Transform(background_rect, new_br), FadeIn(solution, 0.5 * DOWN) ) self.wait() foreground = VGroup(background_rect, equation, solution) self.play(FadeOut(foreground)) # Show flow of all initial conditions initial_points = np.array([ plane.c2p(x, y) for x in np.arange(-16, 16, 0.5) for y in np.arange(-6, 6, 0.5) ]) dots = DotCloud(initial_points) dots.set_radius(0.06) dots.set_color(WHITE) initial_points = np.array(dots.get_points()) self.add(dots) self.play(vector_field.animate.set_opacity(0.75)) time_tracker = ValueTracker() def update_dots(dots): time = time_tracker.get_value() transformation = np.identity(3) transformation[:2, :2] = mat_exp(0.15 * matrix * time) dots.set_points(np.dot(initial_points, transformation)) streaks = Group() def update_streaks(streaks): dc = dots.copy() dc.clear_updaters() dc.set_opacity(0.25) dc.set_radius(0.01) streaks.add(dc) dots.add_updater(update_dots) streaks.add_updater(update_streaks) self.add(plane, vector_field, streaks, dots) self.play(time_tracker.animate.set_value(3), run_time=6, rate_func=linear) # Flow # animated_flow = AnimatedStreamLines(get_flow_lines(0.25, 3)) class DefineVectorFieldWithHyperbolicFlow(BasicVectorFieldIdea): matrix = np.array([[0.0, 1.0], [1.0, 0.0]]) / 0.45 class MoreShakesperianRomeoJuliet(RomeoAndJuliet): def construct(self): # Add plane/vector field plane = NumberPlane((-5, 5), (-5, 5), faded_line_ratio=0) plane.set_height(5) plane.to_corner(DL) self.add(plane) def func0(x, y): return (x, y) def func1(x, y): return (-y, x) def func2(x, y): return (y, x) vector_fields = VGroup(*( VectorField( func, plane, step_multiple=1, magnitude_range=(0, 8), vector_config={"thickness": 0.025}, length_func=lambda norm: 0.9 * sigmoid(norm) ) for func in [func0, func1, func2] )) # Put differential equation above it equations = VGroup( get_2d_equation([["0", "-1"], ["+1", "0"]]), get_2d_equation([["0", "+1"], ["+1", "0"]]), ) equations.to_corner(UL) m1 = equations[0][3] m2 = equations[1][3] self.add(equations[0]) vector_fields[0].set_opacity(0) vf = vector_fields[0] self.play(Transform(vf, vector_fields[1])) self.wait() # Add Romeo and Juliet romeo, juliet = lovers = self.get_romeo_and_juliet() lovers.set_height(2) lovers.arrange(LEFT, buff=0.5) lovers.to_corner(DR, buff=1.5) self.make_romeo_and_juliet_dynamic(romeo, juliet) scales = VGroup( self.get_love_scale(romeo, RIGHT, "y", BLUE_D), self.get_love_scale(juliet, LEFT, "x", BLUE_B), ) x0, y0 = (5, 5) ps_point = Dot(color=BLUE_B) ps_point.move_to(plane.c2p(x0, y0)) romeo.love_tracker.add_updater(lambda m: m.set_value(plane.p2c(ps_point.get_center())[0])) juliet.love_tracker.add_updater(lambda m: m.set_value(plane.p2c(ps_point.get_center())[1])) self.add(*lovers, scales, self.get_romeo_juilet_name_labels(lovers)) self.add(*(pi.love_tracker for pi in lovers)) self.add(*(pi.heart_eyes for pi in lovers)) self.add(ps_point) self.wait() # Transition to alternate field self.play( Transform(vf, vector_fields[2]), FadeOut(m1, UP), FadeIn(m2, UP), ) self.wait() last_rect = VMobject() for row in m2.get_rows(): rect = SurroundingRectangle(row) self.play(FadeIn(rect), FadeOut(last_rect)) self.wait() last_rect = rect self.play(FadeOut(last_rect)) self.play(ShowIncreasingSubsets(vf, run_time=6, rate_func=linear)) # Show flow def get_flow_line(x0, y0): line = ParametricCurve( lambda t: plane.c2p( math.cosh(t) * x0 + math.sinh(t) * y0, math.sinh(t) * x0 + math.cosh(t) * y0, ), t_range=(0, 4), ) line.set_stroke(WHITE, 3) return line def move_along_line(line, run_time=8): self.add(line, ps_point) self.play( MoveAlongPath(ps_point, line.copy()), ShowCreation(line), rate_func=linear, run_time=run_time, ) line1 = get_flow_line(4, -3) # line2 = get_flow_line(-3, 4) line3 = get_flow_line(-4, 3) # move_along_line(line1) # self.wait() ps_point.move_to(line1.get_start()) self.remove(line1) low_vects = VGroup() mid_vects = VGroup() high_vects = VGroup() for vector in vf: x, y = plane.p2c(vector.get_start()) if x + y < -1e-6: low_vects.add(vector) elif -1e-6 < x + y < 1e-6: mid_vects.add(vector) else: high_vects.add(vector) low_vects.set_opacity(0.1) mid_vects.set_opacity(0.5) self.wait() move_along_line(line1) self.wait() self.remove(line1) ps_point.move_to(line3) low_vects.set_opacity(1) high_vects.set_opacity(0.1) move_along_line(line3) self.wait() class NotAllThatRomanticLabel(Scene): def construct(self): text = OldTexText("Not all that\n\n romantic!") arrow = Vector(LEFT) arrow.next_to(text, LEFT) text.set_color(RED) arrow.set_color(RED) self.add(text) self.play(ShowCreation(arrow)) self.wait() class TransitionWrapper(Scene): def construct(self): self.add(FullScreenRectangle()) screens = VGroup(*(ScreenRectangle() for x in range(2))) screens.set_width(0.4 * FRAME_WIDTH) screens[0].to_edge(LEFT) screens[1].to_edge(RIGHT) screens.set_fill(BLACK, 1) screens[0].set_stroke(BLUE, 2) screens[1].set_stroke(GREY_BROWN, 2) self.add(screens) arrow = Arrow(*screens) exp = OldTex("e^{Mt}") exp.next_to(arrow, UP) titles = VGroup( OldTexText("Time: $0$"), OldTexText("Time: $t$"), ) for screen, title in zip(screens, titles): title.next_to(screen, UP) screen.add(title) vf_words = OldTexText("Vector field defined by $\\vec{\\textbf{v} } \\rightarrow M\\vec{\\textbf{v} }$") vf_words.match_width(screens[0]) vf_words.next_to(screens[0], DOWN) self.add(vf_words) self.play(ShowCreation(arrow)) self.play(Write(exp)) self.wait() class DerivativeOfExpMt(Scene): def construct(self): # For all tex v0_tex = "\\vec{\\textbf{v} }_0" kw = { "tex_to_color_map": { "M": GREY_B, "{t}": YELLOW, v0_tex: BLUE, "=": WHITE, "\\cdots": WHITE, "+": WHITE, "\\left(": WHITE, "\\right)": WHITE, } } # Show claim solution = OldTex("\\vec{\\textbf{v} }({t}) = e^{M {t} } " + v0_tex, **kw) equation = OldTex("{d \\over dt} \\vec{\\textbf{v} }({t}) = M \\vec{\\textbf{v} }({t})", **kw) arrow = Vector(1.5 * RIGHT) top_line = VGroup(solution, arrow, equation) top_line.arrange(RIGHT, buff=MED_LARGE_BUFF) top_line.set_width(FRAME_WIDTH - 1) solves = Text("Solves(?)", font_size=24) solves.next_to(arrow, UP, SMALL_BUFF) self.add(solution) self.play( GrowArrow(arrow), FadeIn(equation, RIGHT), FadeIn(solves, lag_ratio=0.1) ) self.wait() arrow.add(solves) # Try it... # Show calculations... tex_expressions = [ """ e^{ {t}M } v_0 = \\left( {t}^0 M^0 + {t}^1 M^1 + { {t}^2 \\over 2} M^2 + { {t}^3 \\over 6} M^3 + \\cdots + { {t}^n \\over n!} M^n + \\cdots \\right) v_0 """, """ e^{ {t}M } v_0 = {t}^0 M^0 v_0 + {t}^1 M^1 v_0 + { {t}^2 \\over 2} M^2 v_0 + { {t}^3 \\over 6} M^3 v_0 + \\cdots + { {t}^n \\over n!} M^n v_0 + \\cdots """, """ {d \\over dt} e^{ {t}M } v_0 = 0 + 1 \\cdot {t}^0 M^1 v_0 + {2 {t}^1 \\over 2} M^2 v_0 + {3 {t}^2 \\over 6} M^3 v_0 + \\cdots + {n {t}^{n - 1} \\over n!} M^n v_0 + \\cdots """, """ {d \\over dt} e^{ {t}M } v_0 = 0 + 1 \\cdot {t}^0 M^1 v_0 + {t}^1 M^2 v_0 + { {t}^2 \\over 2} M^3 v_0 + \\cdots + { {t}^{n - 1} \\over (n - 1)!} M^n v_0 + \\cdots """, """ {d \\over dt} e^{ {t}M } v_0 = M \\left( {t}^0 M^0 v_0 + {t}^1 M^1 v_0 + { {t}^2 \\over 2} M^2 v_0 + \\cdots + { {t}^{n - 1} \\over (n - 1)!} M^{n - 1} v_0 + \\cdots \\right) """, """ {d \\over dt} e^{ {t}M } v_0 = M \\left( e^{ {t}M } v_0 \\right) """ ] lines = VGroup(*( OldTex(tex.replace("v_0", v0_tex), **kw) for tex in tex_expressions )) lines.set_width(FRAME_WIDTH - 1) max_height = 1.0 for line in lines: line.set_width(FRAME_WIDTH - 2) if line.get_height() > max_height: line.set_height(max_height) line.center() def match_lines(l1, l2): eq_centers = [eq.get_part_by_tex("=").get_center() for eq in (l1, l2)] l1.shift(eq_centers[1] - eq_centers[0]) # Line 0 self.play(top_line.animate.set_width(6).to_edge(UP)) lines[0].set_y(1) self.play(TransformMatchingTex(solution[4:].copy(), lines[0]), run_time=2) self.wait() # 0 -> 1 match_lines(lines[1], lines[0]) lines[1].set_y(-1) self.play( TransformMatchingTex( VGroup(*( sm for sm in lines[0][5:] if sm.get_tex() not in ["\\left(", "\\right)"] )).copy(), lines[1][5:] ), TransformFromCopy(lines[0][:5], lines[1][:5]) ) self.play( lines[1].animate.set_y(1), FadeOut(lines[0], UP) ) self.wait() # 1 -> 2 -> 3 match_lines(lines[2], lines[1]) match_lines(lines[3], lines[2]) lines[2:4].set_y(-1) self.play(FadeIn(lines[2], DOWN)) l1_indices, l2_indices, l3_indices = [ [ lines[i].index_of_part(part) for part in it.chain(lines[i].get_parts_by_tex("="), lines[i].get_parts_by_tex("+")) ] for i in (1, 2, 3) ] last_rects = VMobject() for l1i, l1j, l2i, l2j in zip(l1_indices, l1_indices[1:], l2_indices, l2_indices[1:]): if l1i is l1_indices[4]: continue r1 = SurroundingRectangle(lines[1][l1i + 1:l1j]) r2 = SurroundingRectangle(lines[2][l2i + 1:l2j]) rects = VGroup(r1, r2) self.play(FadeIn(rects), FadeOut(last_rects)) self.wait(0.5) last_rects = rects self.play(FadeOut(last_rects)) self.play( lines[2].animate.set_y(1), FadeOut(lines[1]), FadeIn(lines[3]), ) self.wait() last_rects = VMobject() for l2i, l2j, l3i, l3j in zip(l2_indices, l2_indices[1:], l3_indices, l3_indices[1:]): # Such terrible style...please no on look if l2i in [l2_indices[0], l2_indices[1], l2_indices[4]]: continue r2 = SurroundingRectangle(lines[2][l2i + 1:l2j]) r3 = SurroundingRectangle(lines[3][l3i + 1:l3j]) rects = VGroup(r2, r3) self.play(FadeIn(rects), FadeOut(last_rects)) self.wait(0.5) last_rects = rects self.play(FadeOut(last_rects)) self.wait() # 3 -> 4 match_lines(lines[4], lines[3]) lines[4].set_y(-1) self.play( FadeIn(lines[1], DOWN), FadeOut(lines[2], DOWN) ) self.wait() self.play(LaggedStart(*( FlashUnder(sm, time_width=2, run_time=1) for sm in lines[3].get_parts_by_tex("M")[1:] ), lag_ratio=0.2)) self.wait() self.play( TransformMatchingTex(lines[3][:5], lines[4][:5]), FadeTransform(lines[3][5:], lines[4][7:34]), FadeIn(lines[4].get_part_by_tex("\\left(")), FadeIn(lines[4].get_part_by_tex("\\right)")), TransformFromCopy( lines[3].get_parts_by_tex("M")[1:], VGroup(lines[4][5]), path_arc=-45 * DEGREES, ) ) self.wait() # 4 -> 5 match_lines(lines[5], lines[4]) lines[5].set_y(-3) self.play( TransformFromCopy(lines[4][:7], lines[5][:7]), TransformFromCopy(lines[4][34], lines[5][11]), FadeTransform(lines[4][7:34].copy(), lines[5][7:11], stretch=False), ) self.wait() class TryIt(Scene): def construct(self): morty = Mortimer() morty.to_corner(DR) self.add(morty) self.play(PiCreatureSays(morty, "Try it!", target_mode="surprised", run_time=1)) self.play(Blink(morty)) self.wait(2) self.remove(morty.bubble, morty.bubble.content) self.play(PiCreatureSays(morty, "Brace yourself now...", target_mode="hesitant")) morty.look(ORIGIN) self.wait(2) class TracePropertyAndComputation(TeacherStudentsScene): def construct(self): trace_eq = OldTex( "\\text{Det}\\left(e^{Mt}\\right) = e^{\\text{Tr}(M) t}", tex_to_color_map={ "\\text{Det}": GREEN_D, "\\text{Tr}": RED_B, } ) trace_eq.move_to(self.hold_up_spot, DOWN) self.play( self.teacher.change("raise_right_hand", trace_eq), FadeIn(trace_eq, 0.5 * UP), ) self.play_student_changes("pondering", "confused", "pondering", look_at=trace_eq) self.wait(2) text = OldTexText("Diagonalization $\\rightarrow$ Easier computation") text.move_to(self.hold_up_spot, DOWN) text.shift_onto_screen() self.play( trace_eq.animate.shift(UP), FadeIn(text, 0.5 * UP), self.change_students("erm", "tease", "maybe"), ) for pi in self.pi_creatures: # Why? pi.eyes[0].refresh_bounding_box() pi.eyes[1].refresh_bounding_box() self.look_at(text) self.wait(3) topics = VGroup(trace_eq, text) exp_deriv = OldTex("e", "{d \\over dx}") exp_deriv[0].scale(2) exp_deriv[1].move_to(exp_deriv[0].get_corner(UR), DL) exp_deriv.move_to(self.hold_up_spot, DOWN) self.play( FadeIn(exp_deriv, scale=2), topics.animate.scale(0.5).to_corner(UL), self.teacher.change("tease", exp_deriv), ) self.play_student_changes("confused", "sassy", "angry") self.wait(6) class EndScreen(PatreonEndScreen): pass # GENERIC flow scenes class ExponentialPhaseFlow(Scene): CONFIG = { "field_config": { "color_by_magnitude": False, "magnitude_range": (0.5, 5), "arc_len": 5, }, "plane_config": { "x_range": [-4, 4], "y_range": [-2, 2], "height": 8, "width": 16, }, "matrix": [ [1, 0], [0, 1], ], "label_height": 3, "run_time": 30, "slow_factor": 0.25, } def construct(self): mr = np.array(self.field_config["magnitude_range"]) self.field_config["magnitude_range"] = self.slow_factor * mr plane = NumberPlane(**self.plane_config) plane.add_coordinate_labels() vector_field, animated_lines = get_vector_field_and_stream_lines( self.func, plane, **self.field_config, ) box = Square() box.replace(Line(plane.c2p(-1, -1), plane.c2p(1, 1)), stretch=True) box.set_stroke(GREY_A, 1) box.set_fill(BLUE_E, 0.8) move_points_along_vector_field(box, self.func, plane) basis_vectors = VGroup( Vector(RIGHT, fill_color=GREEN), Vector(UP, fill_color=RED), ) basis_vectors[0].add_updater(lambda m: m.put_start_and_end_on( plane.get_origin(), box.pfp(7 / 8) )) basis_vectors[1].add_updater(lambda m: m.put_start_and_end_on( plane.get_origin(), box.pfp(1 / 8) )) self.add(plane) self.add(vector_field) self.add(animated_lines) self.add(box) self.add(*basis_vectors) self.wait(self.run_time) def func(self, x, y): return self.slow_factor * np.dot([x, y], np.transpose(self.matrix)) def get_label(self): exponential = get_matrix_exponential(self.matrix) changing_t = DecimalNumber(0, color=YELLOW) changing_t.match_height(exponential[2]) changing_t.move_to(exponential[2], DL) exponential.replace_submobject(2, changing_t) equals = OldTex("=") rhs = DecimalMatrix( np.zeros((2, 2)), element_to_mobject_config={"num_decimal_places": 3}, h_buff=1.8, ) rhs.match_height(exponential) equation = VGroup( exponential, equals, rhs, ) equation.arrange(RIGHT) equation.to_corner(UL) class ExponentialEvaluationWithTime(Scene): flow_scene_class = ExponentialPhaseFlow def construct(self): flow_scene_attrs = merge_dicts_recursively( ExponentialPhaseFlow.CONFIG, self.flow_scene_class.CONFIG, ) matrix = np.array(flow_scene_attrs["matrix"]) slow_factor = flow_scene_attrs["slow_factor"] def get_t(): return slow_factor * self.time exponential = get_matrix_exponential(matrix) dot = OldTex("\\cdot") dot.move_to(exponential[2], LEFT) changing_t = DecimalNumber(0) changing_t.match_height(exponential[2]) changing_t.next_to(dot, RIGHT, SMALL_BUFF) changing_t.align_to(exponential[1], DOWN) changing_t.add_updater(lambda m: m.set_value(get_t()).set_color(YELLOW)) lhs = VGroup(*exponential[:2], dot, changing_t) equals = OldTex("=") rhs = DecimalMatrix( np.zeros((2, 2)), element_to_mobject_config={"num_decimal_places": 2}, element_alignment_corner=ORIGIN, h_buff=2.0, ) for mob in rhs.get_entries(): mob.edge_to_fix = ORIGIN rhs.match_height(lhs) def update_rhs(rhs): result = mat_exp(matrix * get_t()) for mob, value in zip(rhs.get_entries(), result.flatten()): mob.set_value(value) return rhs rhs.add_updater(update_rhs) equation = VGroup(lhs, equals, rhs) equation.arrange(RIGHT) equation.center() self.add(equation) self.wait(flow_scene_attrs["run_time"]) self.embed() class CircularPhaseFlow(ExponentialPhaseFlow): CONFIG = { "field_config": { "magnitude_range": (0.5, 8), }, "matrix": [ [0, -1], [1, 0], ] } class CircularFlowEvaluation(ExponentialEvaluationWithTime): flow_scene_class = CircularPhaseFlow class EllipticalPhaseFlow(ExponentialPhaseFlow): CONFIG = { "field_config": { "magnitude_range": (0.5, 8), }, "matrix": [ [0.5, -3], [1, -0.5], ] } class EllipticalFlowEvaluation(ExponentialEvaluationWithTime): flow_scene_class = EllipticalPhaseFlow class HyperbolicPhaseFlow(ExponentialPhaseFlow): CONFIG = { "field_config": { "sample_freq": 8, }, "matrix": [ [1, 0], [0, -1], ] } class HyperbolicFlowEvaluation(ExponentialEvaluationWithTime): flow_scene_class = HyperbolicPhaseFlow class ShearPhaseFlow(ExponentialPhaseFlow): CONFIG = { "field_config": { "sample_freq": 2, "magnitude_range": (0.5, 8), }, "plane_config": { "x_range": [-8, 8], "y_range": [-4, 4], }, "matrix": [ [1, 1], [0, 1], ], "slow_factor": 0.1, } class ShearFlowEvaluation(ExponentialEvaluationWithTime): flow_scene_class = ShearPhaseFlow class HyperbolicTrigFlow(ExponentialPhaseFlow): CONFIG = { "field_config": { "sample_freq": 2, "magnitude_range": (0.5, 7), }, "plane_config": { "x_range": [-8, 8], "y_range": [-4, 4], }, "matrix": [ [0, 1], [1, 0], ], "slow_factor": 0.1, } class HyperbolicTrigFlowEvaluation(ExponentialEvaluationWithTime): flow_scene_class = HyperbolicTrigFlow class DampedRotationPhaseFlow(ExponentialPhaseFlow): CONFIG = { "matrix": [ [-1, -1], [1, 0], ], } class DampedRotationFlowEvaluation(ExponentialEvaluationWithTime): flow_scene_class = DampedRotationPhaseFlow class FrameForFlow(Scene): def construct(self): self.add(FullScreenRectangle(fill_color=GREY_D)) screen_rect = ScreenRectangle() screen_rect.set_height(5.5) screen_rect.set_stroke(WHITE, 3) screen_rect.set_fill(BLACK, 1) screen_rect.to_edge(DOWN) self.add(screen_rect) class ThumbnailBackdrop(DampedRotationPhaseFlow): CONFIG = { "run_time": 10, } def construct(self): super().construct() for mob in self.mobjects: if isinstance(mob, Square) or isinstance(mob, Arrow): self.remove(mob) if isinstance(mob, NumberPlane): self.remove(mob.coordinate_labels) class Thumbnail(Scene): def construct(self): im = ImageMobject("ExpMatThumbnailBackdrop") im.set_height(FRAME_HEIGHT) im.set_opacity(0.7) self.add(im) # rect = FullScreenFadeRectangle() # rect.set_fill(opacity=0.3) # self.add(rect) exp = get_matrix_exponential([[-1, -1], [1, 0]], scalar_tex="") exp.set_height(5) exp.set_stroke(BLACK, 50, opacity=0.5, background=True) fuzz = VGroup() N = 100 for w in np.linspace(150, 0, N): ec = exp.copy() ec.set_stroke(BLUE_E, width=w, opacity=(1 / N)) ec.set_fill(opacity=0) fuzz.add(ec) self.add(fuzz, exp) self.embed() # Older class LetsSumUp(TeacherStudentsScene): def construct(self): self.teacher_says( "Let's review", added_anims=[self.change_students("thinking", "pondering", "thinking")] ) self.wait(3) class PrerequisitesWrapper(Scene): def construct(self): self.add(FullScreenRectangle()) title = Text("Helpful background knowledge") title.to_edge(UP) self.add(title) screens = VGroup(*(ScreenRectangle() for x in range(2))) screens.arrange(RIGHT, buff=LARGE_BUFF) screens.set_width(FRAME_WIDTH - 1) screens.move_to(DOWN) screens.set_fill(BLACK, 1) screens.set_stroke(WHITE, 2) topics = VGroup( OldTexText("Basics of $e^x$"), OldTexText("How matrices act\\\\as transformations"), ) for topic, screen in zip(topics, screens): topic.next_to(screen, UP) topic.set_color(WHITE) for topic, screen in zip(topics, screens): sc = screen.copy() sc.set_fill(opacity=0) sc.set_stroke(width=3) self.play( FadeIn(topic, 0.5 * UP), FadeIn(screen), VShowPassingFlash(sc, time_width=1.0, run_time=1.5), ) self.wait(2) class SchroedingersComplicatingFactors(TeacherStudentsScene): def construct(self): pass class OldComputationCode(Scene): def construct(self): # Taylor series example ex_rhs = OldTex( """ {2}^0 + {2}^1 + { {2}^2 \\over 2} + { {2}^3 \\over 6} + { {2}^4 \\over 24} + { {2}^5 \\over 120} + { {2}^6 \\over 720} + { {2}^7 \\over 5040} + \\cdots """, tex_to_color_map={"{2}": YELLOW, "+": WHITE}, ) ex_rhs.next_to(real_equation[3:], DOWN, buff=0.75) ex_parts = VGroup(*( ex_rhs[i:j] for i, j in [ (0, 2), (3, 5), (6, 8), (9, 11), (12, 14), (15, 17), (18, 20), (21, 23), (24, 25), ] )) term_brace = Brace(ex_parts[0], DOWN) frac = OldTex("1", font_size=36) frac.next_to(term_brace, DOWN, SMALL_BUFF) rects = VGroup(*( Rectangle(height=2**n / math.factorial(n), width=1) for n in range(11) )) rects.arrange(RIGHT, buff=0, aligned_edge=DOWN) rects.set_fill(opacity=1) rects.set_submobject_colors_by_gradient(BLUE, GREEN) rects.set_stroke(WHITE, 1) rects.set_width(7) rects.to_edge(DOWN) self.play( ReplacementTransform(taylor_brace, term_brace), FadeTransform(real_equation[3:].copy(), ex_rhs), FadeOut(false_group, shift=DOWN), FadeOut(taylor_label, shift=DOWN), FadeIn(frac), ) term_values = VGroup() for n in range(11): rect = rects[n] fact = math.factorial(n) ex_part = ex_parts[min(n, len(ex_parts) - 1)] value = DecimalNumber(2**n / fact) value.set_color(GREY_A) max_width = 0.6 * rect.get_width() if value.get_width() > max_width: value.set_width(max_width) value.next_to(rects[n], UP, SMALL_BUFF) new_brace = Brace(ex_part, DOWN) if fact == 1: new_frac = OldTex(f"{2**n}", font_size=36) else: new_frac = OldTex(f"{2**n} / {fact}", font_size=36) new_frac.next_to(new_brace, DOWN, SMALL_BUFF) self.play( term_brace.animate.become(new_brace), FadeTransform(frac, new_frac), ) frac = new_frac rect.save_state() rect.stretch(0, 1, about_edge=DOWN) rect.set_opacity(0) value.set_value(0) self.play( Restore(rect), ChangeDecimalToValue(value, 2**n / math.factorial(n)), UpdateFromAlphaFunc(value, lambda m, a: m.next_to(rect, UP, SMALL_BUFF).set_opacity(a)), randy.animate.look_at(rect), morty.animate.look_at(rect), ) term_values.add(value) self.play(FadeOut(frac)) new_brace = Brace(ex_rhs, DOWN) sum_value = DecimalNumber(math.exp(2), num_decimal_places=4, font_size=36) sum_value.next_to(new_brace, DOWN) self.play( term_brace.animate.become(new_brace), randy.change("thinking", sum_value), morty.change("tease", sum_value), *(FadeTransform(dec.copy().set_opacity(0), sum_value) for dec in term_values) ) self.play(Blink(randy)) lhs = OldTex("e \\cdot e =") lhs.match_height(real_equation[0]) lhs.next_to(ex_rhs, LEFT) self.play(Write(lhs)) self.play(Blink(morty)) self.play(Blink(randy)) # Increment input twos = ex_rhs.get_parts_by_tex("{2}") threes = VGroup(*( OldTex("3").set_color(YELLOW).replace(two) for two in twos )) new_lhs = OldTex("e \\cdot e \\cdot e = ") new_lhs.match_height(lhs) new_lhs[0].space_out_submobjects(0.8) new_lhs[0][-1].shift(SMALL_BUFF * RIGHT) new_lhs.move_to(lhs, RIGHT) anims = [] unit_height = 0.7 * rects[0].get_height() for n, rect, value_mob in zip(it.count(0), rects, term_values): rect.generate_target() new_value = 3**n / math.factorial(n) rect.target.set_height(unit_height * new_value, stretch=True, about_edge=DOWN) value_mob.rect = rect anims += [ MoveToTarget(rect), ChangeDecimalToValue(value_mob, new_value), UpdateFromFunc(value_mob, lambda m: m.next_to(m.rect, UP, SMALL_BUFF)) ] self.play( FadeOut(twos, 0.5 * UP), FadeIn(threes, 0.5 * UP), ) twos.set_opacity(0) self.play( ChangeDecimalToValue(sum_value, math.exp(3)), *anims, ) self.play( FadeOut(lhs, 0.5 * UP), FadeIn(new_lhs, 0.5 * UP), ) self.wait() class PreviewVisualizationWrapper(Scene): def construct(self): background = FullScreenFadeRectangle(fill_color=GREY_E, fill_opacity=1) self.add(background) screen = ScreenRectangle(height=6) screen.set_fill(BLACK, 1) screen.set_stroke(GREY_A, 3) screen.to_edge(DOWN) self.add(screen) titles = VGroup( Text("How to think about matrix exponentiation"), Text( "How to visualize matrix exponentiation", t2s={"visualize": ITALIC}, ), Text("What problems matrix exponentiation solves?"), ) for title in titles: title.next_to(screen, UP) title.get_parts_by_text("matrix exponentiation").set_color(TEAL) self.play(FadeIn(titles[0], 0.5 * UP)) self.wait(2) self.play(*( FadeTransform( titles[0].get_parts_by_text(w1), titles[1].get_parts_by_text(w2), ) for w1, w2 in [ ("How to", "How to"), ("think about", "visualize"), ("matrix exponentiation", "matrix exponentiation"), ] )) self.wait(2) self.play( *( FadeTransform( titles[1].get_parts_by_text(w1), titles[2].get_parts_by_text(w2), ) for w1, w2 in [ ("How to visualize", "What problems"), ("matrix exponentiation", "matrix exponentiation"), ] ), FadeIn(titles[2].get_parts_by_text("solves?")) ) self.wait(2)
from manim_imports_ext import * from _2022.newton_fractal import * MANDELBROT_COLORS = [ "#00065c", "#061e7e", "#0c37a0", "#205abc", "#4287d3", "#D9EDE4", "#F0F9E4", "#BA9F6A", "#573706", ] def get_c_dot_label(dot, get_c, font_size=24, direction=UP): c_label = VGroup( OldTex("c = ", font_size=font_size), DecimalNumber(get_c(), font_size=font_size, include_sign=True) ).arrange(RIGHT, buff=0.075) c_label[0].shift(0.02 * DOWN) c_label.set_color(YELLOW) c_label.set_stroke(BLACK, 5, background=True) c_label.add_updater(lambda m: m.next_to(dot, direction, SMALL_BUFF)) c_label.add_updater(lambda m: m[1].set_value(get_c())) return c_label def get_iteration_label(font_size=36): kw = { "tex_to_color_map": { "z_0": BLUE_C, "z_1": BLUE_D, "z_2": GREEN_D, "z_3": GREEN_E, "z_{n + 1}": GREEN_D, "z_n": BLUE, "\\longrightarrow": WHITE, }, "font_size": font_size, } iterations = OldTex( """ z_0 \\longrightarrow z_1 \\longrightarrow z_2 \\longrightarrow z_3 \\longrightarrow \\cdots """, **kw ) for part in iterations.get_parts_by_tex("\\longrightarrow"): f = OldTex("f", **kw) f.scale(0.5) f.next_to(part, UP, buff=0) part.add(f) rule = OldTex("z_{n + 1} &= f(z_n)", **kw) result = VGroup(rule, iterations) result.arrange(DOWN, buff=MED_LARGE_BUFF) return result class MandelbrotFractal(NewtonFractal): CONFIG = { "shader_folder": "mandelbrot_fractal", "shader_dtype": [ ('point', np.float32, (3,)), ], "scale_factor": 1.0, "offset": ORIGIN, "colors": MANDELBROT_COLORS, "n_colors": 9, "parameter": complex(0, 0), "n_steps": 300, "mandelbrot": True, } def init_uniforms(self): Mobject.init_uniforms(self) self.uniforms["mandelbrot"] = float(self.mandelbrot) self.set_parameter(self.parameter) self.set_opacity(self.opacity) self.set_scale(self.scale_factor) self.set_colors(self.colors) self.set_offset(self.offset) self.set_n_steps(self.n_steps) def set_parameter(self, c): self.uniforms["parameter"] = np.array([c.real, c.imag]) return self def set_opacity(self, opacity): self.uniforms["opacity"] = opacity return self def set_colors(self, colors): for n in range(len(colors)): self.uniforms[f"color{n}"] = color_to_rgb(colors[n]) return self class JuliaFractal(MandelbrotFractal): CONFIG = { "n_steps": 100, "mandelbrot": False, } def set_c(self, c): self.set_parameter(c) # Scenes class MandelbrotSetPreview(Scene): def construct(self): plane = ComplexPlane( (-2, 1), (-2, 2), background_line_style={ "stroke_color": GREY_B, "stroke_opacity": 0.5, } ) plane.set_width(0.7 * FRAME_WIDTH) plane.axes.set_stroke(opacity=0.5) plane.add_coordinate_labels(font_size=18) mandelbrot = MandelbrotFractal(plane) mandelbrot.set_n_steps(0) self.add(mandelbrot, plane) self.play( mandelbrot.animate.set_n_steps(300), rate_func=lambda a: a**3, run_time=10, ) self.wait() class HolomorphicDynamics(Scene): def construct(self): self.show_goals() self.complex_functions() self.repeated_functions() self.example_fractals() def show_goals(self): background = FullScreenRectangle() self.add(background) title = self.title = Text("Holomorphic Dynamics", font_size=60) title.to_edge(UP) title.set_stroke(BLACK, 3, background=True) underline = Underline(title, buff=-0.05) underline.scale(1.2) underline.insert_n_curves(20) underline.set_stroke(YELLOW, [1, *5 * [3], 1]) self.add(title) self.add(underline, title) self.play(ShowCreation(underline)) self.wait() frames = Square().replicate(2) frames.set_height(5) frames.set_width(6, stretch=True) frames.set_stroke(WHITE, 2) frames.set_fill(BLACK, 1) frames.arrange(RIGHT, buff=1) frames.to_edge(DOWN) goals = VGroup( # OldTexText("Newton's fractal $\\leftrightarrow$ Mandelbrot"), # OldTexText("Tie up loose ends"), OldTexText("Goal 1: Other Mandelbrot occurrences"), OldTexText("Goal 2: Tie up loose ends"), ) goals.set_width(frames[0].get_width()) goals.set_fill(GREY_A) for goal, frame in zip(goals, frames): goal.next_to(frame, UP) goal.align_to(goals[0], UP) self.play( FadeIn(frames[0]), FadeIn(goals[0], 0.5 * UP), ) self.wait() self.play( FadeIn(frames[1]), FadeIn(goals[1], 0.5 * UP), ) self.wait() # Transition rect = SurroundingRectangle(title.get_part_by_text("Holomorphic")) rect.set_stroke(YELLOW, 2) self.play( ReplacementTransform(underline, rect), FadeOut(background), LaggedStartMap(FadeOut, VGroup( *goals, *frames, )) ) self.title_rect = rect def complex_functions(self): kw = { "tex_to_color_map": { "\\mathds{C}": BLUE, "z": YELLOW, } } f_def = VGroup( OldTex("f : \\mathds{C} \\rightarrow \\mathds{C}", **kw), OldTex("f'(z) \\text{ exists}", **kw) ) f_def.arrange(RIGHT, aligned_edge=DOWN, buff=LARGE_BUFF) f_def.next_to(self.title, DOWN, buff=MED_LARGE_BUFF) for part in f_def: self.play(Write(part, stroke_width=1)) self.wait() # Examples examples = VGroup( OldTex("f(z) = z^2 + 1", **kw), OldTex("f(z) = e^z", **kw), OldTex("f(z) = \\sin\\left(z\\right)", **kw), OldTex("\\vdots") ) examples.arrange(DOWN, buff=0.35, aligned_edge=LEFT) examples[-1].shift(0.25 * RIGHT) examples.set_width(2.5) examples.to_corner(UL) self.play(LaggedStartMap( FadeIn, examples, shift=0.25 * DOWN, run_time=3, lag_ratio=0.5 )) # Transition rect = self.title_rect new_rect = SurroundingRectangle(self.title.get_part_by_text("Dynamics")) new_rect.match_style(rect) self.play( FadeOut(examples, lag_ratio=0.1), FadeOut(f_def, lag_ratio=0.1), Transform(rect, new_rect) ) self.wait() def repeated_functions(self): words = OldTexText("For some function $f(z)$,") rule, iterations = get_iteration_label() group = VGroup(words, iterations, rule) group.arrange(DOWN, buff=MED_LARGE_BUFF) group.next_to(self.title, DOWN, LARGE_BUFF) group.to_edge(LEFT) self.play( FadeIn(words), FadeIn(iterations, lag_ratio=0.2, run_time=2) ) self.play(FadeIn(rule, 0.5 * DOWN)) self.wait() self.play(LaggedStartMap(FadeOut, VGroup( words, iterations, rule, self.title_rect ))) def example_fractals(self): newton = OldTex("z - {P(z) \\over P'(z)}") mandelbrot = OldTex("z^2 + c") exponential = OldTex("a^z") rhss = VGroup(newton, mandelbrot, exponential) f_eqs = VGroup() lhss = VGroup() for rhs in rhss: rhs.generate_target() lhs = OldTex("f(z) = ") lhs.next_to(rhs, LEFT) f_eqs.add(VGroup(lhs, rhs)) lhss.add(lhs) VGroup(exponential, mandelbrot).shift(0.05 * UP) f_eqs.arrange(RIGHT, buff=1.5) f_eqs.next_to(self.title, DOWN, MED_LARGE_BUFF) rects = Square().replicate(3) rects.arrange(RIGHT, buff=0.2 * rects.get_width()) rects.set_width(FRAME_WIDTH - 1) rects.center().to_edge(DOWN, buff=LARGE_BUFF) rects.set_stroke(WHITE, 1) arrows = VGroup() for rect, f_eq in zip(rects, f_eqs): arrow = Vector(0.5 * DOWN) arrow.next_to(rect, UP) arrows.add(arrow) f_eq.next_to(arrow, UP) f_eqs[0].match_y(f_eqs[1]) self.play( FadeOut(self.title, UP), LaggedStartMap(Write, rhss), LaggedStartMap(FadeIn, lhss), LaggedStartMap(FadeIn, rects), LaggedStartMap(ShowCreation, arrows), ) self.wait() class HolomorphicPreview(Scene): def construct(self): in_plane = ComplexPlane( (-2, 2), (-2, 2), height=5, width=5, ) in_plane.add_coordinate_labels(font_size=18) in_plane.to_corner(DL) out_plane = in_plane.deepcopy() out_plane.to_corner(DR) input_word = Text("Input") output_word = Text("Output") input_word.next_to(in_plane, UP) output_word.next_to(out_plane, UP) self.add(in_plane, out_plane, input_word, output_word) # Show tiny neighborhood tiny_plane = ComplexPlane( (-2, 2), (-2, 2), height=0.5, width=0.5, axis_config={ "stroke_width": 1.0, }, background_line_style={ "stroke_width": 1.0, }, faded_line_ratio=1, ) tiny_plane.move_to(in_plane.c2p(1, 1)) for plane in in_plane, out_plane: plane.generate_target() for mob in plane.target.family_members_with_points(): mob.set_opacity(mob.get_opacity() * 0.25) self.play( ShowCreation(tiny_plane), MoveToTarget(in_plane), ) self.wait() def f(z): w = z - complex(1, 1) return complex(-1, 0.5) + complex(-1, 1) * w + 0.2 * w**2 tiny_plane.prepare_for_nonlinear_transform() tiny_plane_image = tiny_plane.copy() tiny_plane_image.apply_function( lambda p: out_plane.n2p(f(in_plane.p2n(p))) ) arrow = Arrow( tiny_plane, tiny_plane_image, path_arc=-PI / 4, stroke_width=5, ) f_label = OldTex("f(z)") f_label.next_to(arrow, UP, SMALL_BUFF) words = Text("Looks roughly like\nscaling + rotating") words.set_width(2.5) words.move_to(VGroup(in_plane, out_plane)) self.play( ShowCreation(arrow), FadeIn(f_label, 0.1 * UP), ) self.play( TransformFromCopy(tiny_plane, tiny_plane_image), MoveToTarget(out_plane), FadeIn(words), run_time=2, ) self.wait(2) class AmbientRepetition(Scene): n_steps = 30 # c = -0.6436875 + -0.441j c = -0.5436875 + -0.641j show_labels = True def construct(self): plane = ComplexPlane((-2, 2), (-2, 2)) plane.set_height(6) plane.add_coordinate_labels(font_size=18) plane.to_corner(DR, buff=SMALL_BUFF) self.add(plane) font_size = 30 z0 = complex(0, 0) dot = Dot(color=BLUE) dot.move_to(plane.n2p(z0)) z_label = OldTex("z", font_size=font_size) z_label.set_stroke(BLACK, 5, background=True) z_label.next_to(dot, UP, SMALL_BUFF) if not self.show_labels: z_label.set_opacity(0) self.add(dot, z_label) self.add(TracedPath(dot.get_center, stroke_width=1)) func = self.func def get_new_point(): z = plane.p2n(dot.get_center()) return plane.n2p(func(z)) for n in range(self.n_steps): new_point = get_new_point() arrow = Arrow(dot.get_center(), new_point, buff=dot.get_height() / 2) dot_copy = dot.copy() dot_copy.move_to(new_point) dot_copy.set_color(YELLOW) fz_label = OldTex("f(z)", font_size=font_size) fz_label.set_stroke(BLACK, 8, background=True) fz_label.next_to(dot_copy, normalize(new_point - dot.get_center()), buff=0) if not self.show_labels: fz_label.set_opacity(0) self.add(dot, dot_copy, arrow, z_label) self.play( ShowCreation(arrow), TransformFromCopy(dot, dot_copy), FadeInFromPoint(fz_label, z_label.get_center()), ) self.wait(0.5) to_fade = VGroup( dot.copy(), z_label.copy(), dot_copy, arrow, fz_label, ) dot.move_to(dot_copy) z_label.next_to(dot, UP, SMALL_BUFF) self.remove(z_label) self.play( *map(FadeOut, to_fade), FadeIn(z_label), ) def func(self, z): return 2 * ((z / 2)**2 + self.c) class AmbientRepetitionLimitPoint(AmbientRepetition): n_steps = 30 c = complex() c = 0.234 + 0.222j show_labels = False class AmbientRepetitionInfty(AmbientRepetition): c = -0.7995 + 0.3503j n_steps = 12 class AmbientRepetitionChaos(AmbientRepetition): def func(self, c): return complex( random.random() * 4 - 2, random.random() * 4 - 2, ) class Recap(VideoWrapper): title = "Newton's fractal quick recap" animate_boundary = False screen_height = 6.3 class RepeatedNewtonPlain(RepeatedNewton): n_steps = 20 colors = ROOT_COLORS_DEEP class RationalFunctions(Scene): def construct(self): # Show function equation = OldTex( "f(z)", "=", "z - {P(z) \\over P'(z)}", "=", "z - {z^3 - 1 \\over 3z^2}", "=", "{2z^3 + 1 \\over 3z^2}" ) iter_brace = Brace(equation[2], UP) iter_text = iter_brace.get_text("What's being iterated") VGroup(iter_brace, iter_text).set_color(BLUE_D) example_brace = Brace(equation[4], DOWN) example_text = example_brace.get_text("For example") VGroup(example_brace, example_text).set_color(TEAL_D) self.play( FadeIn(equation[:3]), GrowFromCenter(iter_brace), FadeIn(iter_text, 0.5 * UP) ) self.wait() self.play( FadeIn(equation[3:5]), GrowFromCenter(example_brace), FadeIn(example_text, 0.5 * DOWN), ) self.wait() self.play( Write(equation[5]), LaggedStart(*( FadeTransform(equation[4][i].copy(), equation[6][j]) for i, j in zip( [1, 0, *range(2, 10)], [0, 0, *range(1, 9)], ) ), lag_ratio=0.02) ) self.add(equation[6]) self.play( LaggedStart(*( FadeTransform(equation[4][i].copy().set_opacity(0), equation[6][j].copy().set_opacity(0)) for i, j in zip( [0, 0, 0, 0], [0, 0, 0, 0], ) ), lag_ratio=0.02) ) self.add(equation) self.wait() # Name rational function box = SurroundingRectangle(equation[6], buff=SMALL_BUFF) box.set_stroke(YELLOW, 2) rational_name = OldTexText("``Rational function''") rational_name.next_to(box, UP, buff=1.5) arrow = Arrow(rational_name, box) self.play( Write(rational_name), ShowCreation(arrow), ShowCreation(box), ) self.wait() # Forget about the Newton's method origins self.play( equation[:2].animate.next_to(ORIGIN, LEFT, SMALL_BUFF), equation[2:6].animate.set_opacity(0.5).scale(0.5).to_corner(DR), VGroup(equation[6], box).animate.next_to(ORIGIN, RIGHT, SMALL_BUFF), MaintainPositionRelativeTo( VGroup(rational_name, arrow), box, ), FadeOut( VGroup(example_brace, example_text, iter_brace, iter_text), shift=2 * RIGHT + DOWN ) ) self.wait() # Other rational functions frame = self.camera.frame rhs = equation[6] functions = VGroup( OldTex("3z^4 + z^3 + 4 \\over z^5 + 5z + 9"), OldTex("2z^6 + 7z^4 + 1z \\over 8z^3 + 2z^2 + 8"), OldTex("(z^2 + 1)^2 \\over 4z(z^2 - 1)"), OldTex("az + b \\over cz + d"), OldTex("z^2 + az + b \\over z^2 + cz + d"), OldTex( "a_n z^n + \\cdots + a_0 \\over " "b_m z^m + \\cdots + b_0" ), OldTex("z^2 + c \\over 1"), ) for function in functions: function.replace(rhs, dim_to_match=1) function.move_to(rhs, LEFT) function.set_max_width(rhs.get_width() + 2) for n, function in enumerate(functions): self.play( FadeOut(rhs, lag_ratio=0.1), FadeIn(function, lag_ratio=0.1), box.animate.set_opacity(0), ) self.remove(box) self.wait() if n == 0: self.play( rational_name.animate.next_to(box, UP), arrow.animate.scale(0, about_edge=DOWN), ApplyMethod(frame.shift, 2 * DOWN, run_time=2), FadeOut(equation[2:6]), ) else: self.wait() rhs = function[0] self.play( FadeOut(box), FadeOut(rational_name), FadeOut(rhs[4:]), rhs[:4].animate.next_to(ORIGIN, RIGHT, SMALL_BUFF).shift(0.07 * UP), frame.animate.shift(DOWN), ) self.wait() class ShowFatouAndJulia(Scene): def construct(self): time_range = (1900, 2020) timeline = NumberLine( (*time_range, 1), tick_size=0.025, longer_tick_multiple=4, numbers_with_elongated_ticks=range(*time_range, 10), ) timeline.stretch(0.25, 0) timeline.add_numbers( range(*time_range, 10), group_with_commas=False, ) timeline.set_y(-3) timeline.to_edge(LEFT, buff=0) line = Line(timeline.n2p(1917), timeline.n2p(1920)) line.scale(2) brace = Brace(line, UP) brace.stretch(1 / 2, 0) line.stretch(0.6, 0) line.insert_n_curves(20) line.set_stroke(BLUE, [1, *3 * [5], 1]) kw = {"label_direction": UP, "height": 3} figures = Group( get_figure("Pierre_Fatou", "Pierre Fatou", "1878-1929", **kw), get_figure("Gaston_Julia", "Gaston Julia", "1893-1978", **kw), ) figures.set_height(3) figures.arrange(RIGHT, buff=LARGE_BUFF) figures.next_to(brace, UP) self.add(timeline) self.add(figures) for figure in figures: self.remove(*figure[2:]) frame = self.camera.frame frame.save_state() frame.align_to(timeline, RIGHT) self.play(Restore(frame, run_time=3)) self.play(LaggedStart(*( Write(VGroup(*figure[2:])) for figure in figures ), lag_ratio=0.7)) self.play( GrowFromCenter(brace), ShowCreation(line), ) self.wait() # Names names = VGroup(*(figure[2][-5:] for figure in figures)) rects = VGroup(*(SurroundingRectangle(name, buff=0.05) for name in names)) rects.set_stroke(BLUE, 2) self.play(LaggedStartMap(ShowCreation, rects)) class IveSeenThis(TeacherStudentsScene): def construct(self): equation = OldTex("f(z) = z^2 + c") equation.to_edge(UP) self.add(equation) mandelbrot_outline = ImageMobject("Mandelbrot_boundary") mandelbrot_outline.set_height(3) mandelbrot_outline.move_to(self.students[2].get_corner(UR)) mandelbrot_outline.shift(1.2 * UP) self.student_says( "I've seen this one", target_mode="surprised", look_at=equation, added_anims=[ self.students[0].change("tease", equation), self.students[1].change("happy", equation), self.teacher.change("happy", equation), ] ) self.play(self.teacher.change("tease")) self.wait(2) self.add(mandelbrot_outline, *self.mobjects) self.play( FadeOut(self.background), RemovePiCreatureBubble( self.students[2], target_mode="raise_right_hand", look_at=mandelbrot_outline, ), FadeIn(mandelbrot_outline, 0.5 * UP, scale=2), self.students[0].change("pondering", mandelbrot_outline), self.students[1].change("thinking", mandelbrot_outline), self.teacher.change("happy", self.students[2].eyes), ) self.wait(4) self.embed() class MandelbrotIntro(Scene): n_iterations = 30 def construct(self): self.add_process_description() self.add_plane() self.show_iterations() self.add_mandelbrot_image() def add_process_description(self): kw = { "tex_to_color_map": { "{c}": YELLOW, } } terms = self.terms = VGroup( OldTex("z_{n + 1} = z_n^2 + {c}", **kw), OldTex("{c} \\text{ can be changed}", **kw), OldTex("z_0 = 0", **kw), ) terms.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) terms.to_corner(UL) equation = OldTex("f(z) = z^2 + c") equation.to_edge(UP) self.process_terms = terms self.add(equation) self.wait() self.play(FadeTransform(equation, terms[0])) def add_plane(self): plane = self.plane = ComplexPlane((-2, 1), (-2, 2)) plane.set_height(4) plane.set_height(1.5 * FRAME_HEIGHT) plane.next_to(2 * LEFT, RIGHT, buff=0) plane.add_coordinate_labels(font_size=24) self.add(plane) def show_iterations(self): plane = self.plane # c0 = complex(-0.2, 0.95) c0 = complex(-0.6, 0.4) c_dot = self.c_dot = Dot() c_dot.set_fill(YELLOW) c_dot.set_stroke(BLACK, 5, background=True) c_dot.move_to(plane.n2p(c0)) c_dot.add_updater(lambda m: m) # Null n_iter_tracker = ValueTracker(1) def get_n_iters(): return int(n_iter_tracker.get_value()) def get_c(): return plane.p2n(c_dot.get_center()) def update_lines(lines): z1 = 0 c = get_c() new_lines = [] for n in range(get_n_iters()): try: z2 = z1**2 + c new_lines.append(Line( plane.n2p(z1), plane.n2p(z2), stroke_color=GREY, stroke_width=2, )) new_lines.append(Dot( plane.n2p(z2), fill_color=YELLOW, fill_opacity=0.5, radius=0.05, )) z1 = z2 except Exception: pass lines.set_submobjects(new_lines) c_label = get_c_dot_label(c_dot, get_c) lines = VGroup() lines.set_stroke(background=True) lines.add_updater(update_lines) self.add(lines, c_dot, c_label) def increase_step(run_time=1.0): n_iter_tracker.increment_value(1) lines.update() lines.suspend_updating() self.add(*lines, c_dot, c_label) self.play( ShowCreation(lines[-2]), TransformFromCopy(lines[-3], lines[-1]), run_time=run_time ) self.add(lines, c_dot, c_label) lines.resume_updating() kw = { "tex_to_color_map": { "c": YELLOW, } } new_lines = VGroup( OldTex("z_1 = 0^2 + c = c", **kw), OldTex("z_2 = c^2 + c", **kw), OldTex("z_3 = (c^2 + c)^2 + c", **kw), OldTex("z_4 = ((c^2 + c)^2 + c)^2 + c", **kw), OldTex("\\vdots", **kw), ) new_lines.arrange(DOWN, aligned_edge=LEFT) new_lines[-2].scale(0.8, about_edge=LEFT) new_lines.next_to(self.process_terms[2], DOWN, aligned_edge=LEFT) new_lines[-1].match_x(new_lines[-2][0][2]) # Show c self.wait() self.play(Write(self.process_terms[1])) self.wait(10) # Show first step dot = Dot(plane.n2p(0)) self.play(FadeIn(self.process_terms[2], 0.5 * DOWN)) self.play(FadeIn(dot, scale=0.2, run_time=2)) self.play(FadeOut(dot)) self.play(FadeIn(new_lines[0], 0.5 * DOWN)) self.play(ShowCreationThenFadeOut( lines[0].copy().set_stroke(BLUE, 5) )) self.wait(3) # Show second step self.play(FadeIn(new_lines[1], 0.5 * DOWN)) increase_step() self.wait(10) # Show 3rd to nth steps self.play(FadeIn(new_lines[2], 0.5 * DOWN)) increase_step() self.play(FadeIn(new_lines[3], 0.5 * DOWN)) increase_step() self.wait(5) self.play(FadeIn(new_lines[4])) for n in range(self.n_iterations): increase_step(run_time=0.25) # Play around self.wait(15) def add_mandelbrot_image(self): mandelbrot_set = MandelbrotFractal(self.plane) self.add(mandelbrot_set, *self.mobjects) self.play( FadeIn(mandelbrot_set, run_time=2), # self.plane.animate.set_opacity(0.5) self.plane.animate.set_stroke(WHITE, opacity=0.25) ) # Listeners def on_mouse_motion(self, point, d_point): super().on_mouse_motion(point, d_point) if self.window.is_key_pressed(ord(" ")): self.c_dot.move_to(point) class BenSparksVideoWrapper(VideoWrapper): title = "Heavily inspired from Ben Sparks" class AckoNet(VideoWrapper): title = "Acko.net, How to Fold a Julia Fractal" class ParameterSpaceVsSeedSpace(Scene): def construct(self): boxes = Square().get_grid(2, 2, buff=0) boxes.set_stroke(WHITE, 2) boxes.set_height(6) boxes.set_width(10, stretch=True) boxes.to_corner(DR) self.add(boxes) f_labels = VGroup( OldTex("f(z) = z^2 + c"), OldTex("f(z) = z - {P(z) \\over P'(z)}"), ) kw = { "tex_to_color_map": { "function": YELLOW, "seed": BLUE_D, } } top_labels = VGroup( OldTexText("One seed\\\\Pixel $\\leftrightarrow$ function", **kw), OldTexText("One function\\\\Pixel $\\leftrightarrow$ seed", **kw), ) for f_label, box in zip(f_labels, boxes[::2]): f_label.set_max_width(3.25) f_label.next_to(box, LEFT) for top_label, box in zip(top_labels, boxes): top_label.next_to(box, UP, buff=0.2) for f_label in f_labels: self.play(FadeIn(f_label, 0.25 * LEFT)) self.wait() self.play(FadeIn(top_labels[0])) self.wait() self.play(TransformMatchingTex( top_labels[0].copy(), top_labels[1] )) self.wait() class MandelbrotStill(Scene): def construct(self): plane = ComplexPlane((-3, 2), (-1.3, 1.3)) plane.set_height(FRAME_HEIGHT) fractal = MandelbrotFractal(plane) self.add(fractal) class JuliaStill(Scene): def construct(self): plane = ComplexPlane((-4, 4), (-1.5, 1.5)) plane.set_height(FRAME_HEIGHT) fractal = JuliaFractal(plane) fractal.set_c(-0.03 + 0.74j) fractal.set_n_steps(100) self.add(fractal) class ClassicJuliaSetDemo(MandelbrotIntro): def construct(self): # Init planes kw = { "background_line_style": { "stroke_width": 0.5, } } planes = VGroup( ComplexPlane((-2, 1), (-1.6, 1.6), **kw), ComplexPlane((-2, 2), (-2, 2), **kw), ) for plane, corner in zip(planes, [DL, DR]): plane.set_stroke(WHITE, opacity=0.5) plane.set_height(6) plane.to_corner(corner, buff=MED_SMALL_BUFF) plane.to_edge(DOWN, SMALL_BUFF) planes[1].add_coordinate_labels(font_size=18) planes[0].add_coordinate_labels( (-1, 0, 1, 1j, -1j), font_size=18 ) # Init fractals mandelbrot = MandelbrotFractal(planes[0]) julia = JuliaFractal(planes[1]) fractals = Group(mandelbrot, julia) self.add(*fractals, *planes) # Add c_dot c_dot = self.c_dot = Dot(radius=0.05) c_dot.set_fill(YELLOW, 1) c_dot.move_to(planes[0].c2p(-0.5, 0.5)) c_dot.add_updater(lambda m: m) def get_c(): return planes[0].p2n(c_dot.get_center()) c_label = get_c_dot_label(c_dot, get_c, direction=UR) julia.add_updater(lambda m: m.set_c(get_c())) self.add(c_dot, c_label) # Add labels kw = { "tex_to_color_map": { "{z_0}": GREY_A, "{c}": YELLOW, "\\text{Pixel}": BLUE_D, }, } title = OldTexText("Iterate\\\\$z^2 + c$") title.move_to(Line(*planes)) title[0][-1].set_color(YELLOW) self.add(title) labels = VGroup( VGroup( OldTex("{c} \\leftrightarrow \\text{Pixel}", **kw), OldTex("z_0 = 0", **kw), ), VGroup( OldTex("{c} = \\text{const.}", **kw), OldTex("z_0 \\leftrightarrow \\text{Pixel}", **kw), ) ) for label, plane in zip(labels, planes): label.arrange(DOWN, aligned_edge=LEFT) label.next_to(plane, UP) space_labels = VGroup( OldTex("{c}\\text{-space}", **kw), OldTex("{z_0}\\text{-space}", **kw), ) for label, plane in zip(space_labels, planes): label.scale(0.5) label.move_to(plane, UL).shift(SMALL_BUFF * DR) self.add(space_labels) # Animations self.add(labels[0]) self.wait(2) self.play( TransformFromCopy( labels[0][0][0], labels[1][0][0], ), FadeIn(labels[1][0][1]), ) self.wait(2) self.play( TransformFromCopy( labels[0][1].get_part_by_tex("z_0"), labels[1][1].get_part_by_tex("z_0"), ), FadeTransform( labels[0][0][1:].copy(), labels[1][1][1:], ), ) class AskAboutGeneralTheory(TeacherStudentsScene): def construct(self): self.teacher_says( OldTexText("Think about constructing\\\\a general theory"), added_anims=[self.change_students( "pondering", "thinking", "pondering", look_at=UP, )] ) self.wait(3) self.teacher_says( OldTexText("What questions would\\\\you ask?"), target_mode="tease", ) self.play_student_changes("thinking", "pondering") self.wait(3) self.embed() class NewtonRuleLabel(Scene): def construct(self): rule = get_newton_rule() rule.scale(1.5) rule.set_stroke(BLACK, 5, background=True) rule.to_corner(UL) box = SurroundingRectangle(rule, buff=0.2) box.set_fill(BLACK, 0.9) box.set_stroke(WHITE, 1) VGroup(box, rule).to_corner(UL, buff=0) self.add(box, rule) class FixedPoints(Scene): def construct(self): # Set the stage iter_label = self.add_labels() rule, iterations = iter_label plane = self.add_plane() z_dot, z_label = self.add_z_dot() # Ask question question = OldTexText("When does $z$ stay fixed in place?") question.next_to(plane, RIGHT, MED_LARGE_BUFF, aligned_edge=UP) arrow = self.get_arrow_loop(z_dot) # f(z) = z t2c = {"z": BLUE} kw = { "tex_to_color_map": t2c, "isolate": ["=", "\\Rightarrow", "A(", "B(", ")"], } equation = OldTex("f(z) = z", **kw) equation.next_to(question, DOWN, MED_LARGE_BUFF) newton_example = OldTex( "z - {P(z) \\over P'(z)} = z", "\\quad \\Leftrightarrow \\quad ", "P(z) = 0", **kw, ) newton_example.next_to(equation, DOWN, buff=LARGE_BUFF) mandelbrot_example = OldTex( "\\text{Exercise 1a: Find the fixed points}\\\\", "\\text{of }", "f(z) = z^2 + c", alignment="\\centering", **kw ) mandelbrot_example[1:].match_x(mandelbrot_example[0]) mandelbrot_example.move_to(newton_example) fixed_point = Text("Fixed point") fixed_point.next_to(equation, DOWN, LARGE_BUFF) fixed_point.to_edge(RIGHT) fp_arrow = Arrow( fixed_point.get_left(), equation[1].get_bottom(), path_arc=-PI / 4, ) fp_group = VGroup(fixed_point, fp_arrow) fp_group.set_color(YELLOW) self.play(FadeIn(equation, DOWN)) self.wait(2) self.play( FadeIn(fixed_point), ShowCreation(fp_arrow), ) self.wait() self.play( FadeIn(newton_example, shift=0.5 * DOWN), FadeOut(fp_group), ) self.wait(2) self.play( FadeOut(newton_example, 0.5 * DOWN), FadeIn(mandelbrot_example, 0.5 * DOWN), ) self.wait(2) # Rational function question_group = VGroup(question, equation) question_group.generate_target() iterations.generate_target() VGroup(question_group.target, iterations.target).to_edge(UP) rational_parts = VGroup( OldTex("{A(z) \\over B(z)} = z", **kw), OldTex("A(z) = z \\cdot B(z)", **kw), OldTex("A(z) - z \\cdot B(z) = 0", **kw), ) rational_parts.arrange(DOWN, buff=MED_LARGE_BUFF) for part, tex in zip(rational_parts[1:], ("=", "-")): curr_x = part.get_part_by_tex(tex).get_x() target_x = rational_parts[0].get_part_by_tex("=").get_x() part.shift((target_x - curr_x) * RIGHT) rational_parts.next_to(question_group.target, DOWN, LARGE_BUFF) self.play( FadeOut(rule, UP), MoveToTarget(question_group), MoveToTarget(iterations), FadeOut(mandelbrot_example), FadeIn(rational_parts[0]) ) self.wait() for p1, p2 in zip(rational_parts, rational_parts[1:]): self.play( TransformMatchingTex( p1.copy(), p2, path_arc=PI / 2, run_time=2, fade_transform_mismatches=True, ) ) self.wait(2) rect = SurroundingRectangle(rational_parts[-1]) solution_words = Text("Must have\nsolutions!", font_size=36) solution_words.set_color(YELLOW) solution_words.next_to(rect, RIGHT) solution_words.shift_onto_screen() self.play( ShowCreation(rect), Write(solution_words, run_time=1), ) self.wait() example_roots = [ -1.5 + 0.5j, -1.5 - 0.5j, -1.0 + 1.2j, -1.0 - 1.2j, 1.0 + 1.0j, 1.0 - 1.0j, 0.5, 1.7, ] glow_dots = VGroup(*( glow_dot(plane.n2p(root)) for root in example_roots )) self.play(LaggedStartMap( FadeIn, glow_dots, scale=0.5, lag_ratio=0.2, )) self.wait() # Ask about stability def get_arrows(point, inward=False): arrows = VGroup(*( Arrow(ORIGIN, vect, buff=0.3) for vect in compass_directions(8) )) arrows.set_height(1) arrows.move_to(point) if inward: for arrow in arrows: arrow.rotate(PI) return arrows outward_arrows = get_arrows(glow_dots[2]) inward_arrows = get_arrows(glow_dots[4], inward=True) arrow_groups = VGroup(inward_arrows, outward_arrows) stability_words = VGroup( Text("Attracting"), Text("Repelling"), ) for words, arrows in zip(stability_words, arrow_groups): words.scale(0.7) words.next_to(arrows, UP, SMALL_BUFF) words.set_color(GREY_A) words.set_stroke(BLACK, 5, background=True) stability_question = Text( "When are fixed points stable?" ) stability_question.move_to(question) stable_underline = Underline( stability_question.get_part_by_text("stable") ) stable_underline.insert_n_curves(20) stable_underline.scale(1.2) stable_underline.set_stroke(MAROON_B, [1, *4 * [4], 1]) self.play( FadeOut(question, RIGHT), FadeIn(stability_question, RIGHT), FadeOut(arrow), FadeOut(z_dot), FadeOut(z_label), ) self.play(ShowCreation(stable_underline)) self.wait() for words, arrows in zip(stability_words, arrow_groups): self.play( FadeIn(words), ShowCreation(arrows, lag_ratio=0.2, run_time=3) ) self.wait() # Show derivative condition morty = Mortimer(height=2) morty.to_corner(DR) deriv_ineq = OldTex("|f'(z)| < 1", **kw) deriv_ineq.next_to(equation, DOWN, MED_LARGE_BUFF) equation.generate_target() group = VGroup(equation.target, deriv_ineq) group.arrange(RIGHT, buff=LARGE_BUFF) group.move_to(equation) attracting_condition = deriv_ineq.copy() repelling_condition = OldTex("|f'(z)| > 1", **kw) conditions = VGroup(attracting_condition, repelling_condition) for condition, words in zip(conditions, stability_words): condition.scale(0.7) condition.set_stroke(BLACK, 5, background=True) condition.move_to(words, DOWN) if conditions is conditions[0]: condition.shift(SMALL_BUFF * UP) words.generate_target() words.target.next_to(condition, UP, buff=MED_SMALL_BUFF) self.play( LaggedStartMap(FadeOut, VGroup( *rational_parts, rect, solution_words, )), VFadeIn(morty), morty.change("tease"), ) self.play(PiCreatureSays( morty, "Use derivatives!", target_mode="hooray", bubble_config={ "height": 2, "width": 4, } )) self.play(Blink(morty)) self.wait() self.play(RemovePiCreatureBubble(morty, target_mode="happy")) for condition, words in zip(conditions, stability_words): self.play( Write(condition), MoveToTarget(words), ) self.wait() self.play( FadeInFromPoint(deriv_ineq, morty.get_corner(UL)), MoveToTarget(equation), morty.change("raise_right_hand") ) self.play(Blink(morty)) # Newton derivative examples newton_case = VGroup( OldTex("f(z) = z - {P(z) \\over P'(z)}", **kw), OldTex("f'(z) = {P(z)P''(z) \\over P'(z)^2}", **kw), OldTex("P(z) = 0 \\quad \\Rightarrow \\quad f'(z) = 0", **kw), ) newton_case.arrange(DOWN, aligned_edge=LEFT, buff=MED_LARGE_BUFF) newton_case.scale(0.8) newton_case.next_to(equation, DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) alt_line1 = OldTex("f'(z) = 1 - {P'(z)P'(z) - P(z)P''(z) \\over P'(z)^2}", **kw) alt_line1.match_height(newton_case[1]) alt_line1.move_to(newton_case[1], LEFT) self.play( TransformMatchingTex(equation.copy()[:3], newton_case[0]), morty.change("pondering", newton_case[0]), ) self.wait() self.play( TransformMatchingTex( deriv_ineq[:-1].copy(), alt_line1[:4], ) ) self.wait() self.play( FadeIn(alt_line1[4:], lag_ratio=0.1, run_time=1.5), morty.animate.scale(0.8, about_edge=DR).change("sassy", alt_line1), ) self.play(Blink(morty)) self.wait() self.play( TransformMatchingTex(alt_line1[4:], newton_case[1][4:]), morty.change("tease", alt_line1), ) self.remove(alt_line1) self.add(newton_case[1]) self.wait() self.play(Blink(morty)) self.wait() self.play( morty.change("pondering", newton_case[2]), FadeIn(newton_case[2]) ) self.play(Blink(morty)) self.wait() # Show super-attraction super_arrows = VGroup(*( get_arrows(dot, inward=True) for dot in glow_dots )) attraction_anims = [] for cluster in super_arrows: for arrow in cluster: new_arrow = arrow.copy() new_arrow.scale(1.5) new_arrow.set_stroke(YELLOW, 8) attraction_anims.append( ShowCreationThenFadeOut(new_arrow) ) rect = SurroundingRectangle(newton_case[2][6:]) super_words = OldTexText("``Superattracting''", font_size=36) super_words.set_color(YELLOW) super_words.next_to(rect, DOWN, SMALL_BUFF) self.play( morty.change("thinking"), ShowCreation(rect), FadeIn(super_words) ) self.play( LaggedStartMap(FadeOut, VGroup( *conditions, *stability_words, outward_arrows, inward_arrows, )), LaggedStartMap(FadeIn, super_arrows, scale=0.5) ) self.play( LaggedStart(*attraction_anims, lag_ratio=0.02), run_time=3 ) self.wait() self.play( LaggedStartMap(FadeOut, VGroup( *super_arrows, *newton_case, rect, super_words, morty, glow_dots, )) ) # Mandelbrot exercise part1 = mandelbrot_example part1.set_height(0.9) part2 = OldTexText( "Exercise 1b: Determine when at least\\\\" "one fixed point is attracting.", ) part3 = OldTexText( "Exercise 1c$^{**}$: Show that the set of values\\\\", "$c$ satisfying this form a cardioid.", tex_to_color_map={"$c$": YELLOW} ) parts = VGroup(part1, part2, part3) for part in part2, part3: part.scale(part1[0][0].get_height() / part[0][0].get_height()) parts.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) parts.next_to( VGroup(equation, deriv_ineq), DOWN, buff=LARGE_BUFF, ) mandelbrot = MandelbrotFractal(plane) R = 0.25 cardioid = ParametricCurve( lambda t: plane.c2p( 2 * R * math.cos(t) - R * math.cos(2 * t), 2 * R * math.sin(t) - R * math.sin(2 * t), ), t_range=(0, TAU) ) cardioid.set_stroke(YELLOW, 4) self.add(mandelbrot, plane) plane.generate_target(use_deepcopy=True) plane.target.set_stroke(WHITE, opacity=0.5) self.play( MoveToTarget(plane), FadeIn(mandelbrot), FadeIn(part1), ) self.wait() self.play(Write(part2)) self.wait() print(self.num_plays) self.play(Write(part3)) self.play(ShowCreation(cardioid, run_time=4, rate_func=linear)) self.play( cardioid.animate.set_fill(YELLOW, 0.25), run_time=2 ) self.wait() def add_labels(self): iter_label = get_iteration_label(48) iter_label.to_edge(UP) self.add(iter_label) return iter_label def add_plane(self): plane = self.plane = ComplexPlane( (-2, 2), (-2, 2), background_line_style={ "stroke_width": 1, } ) plane.set_height(5) plane.to_corner(DL) plane.add_coordinate_labels(font_size=16) self.add(plane) return plane def add_z_dot(self, z=1 + 1j, z_tex="z"): z_dot = Dot(radius=0.05, color=BLUE) z_dot.move_to(self.plane.n2p(z)) z_label = OldTex(z_tex, font_size=30) z_label.next_to(z_dot, UL, buff=0) self.add(z_dot, z_label) return z_dot, z_label def get_arrow_loop(self, dot): arrow = Line( dot.get_bottom(), dot.get_right(), path_arc=330 * DEGREES, buff=0.05, ) arrow.add_tip(width=0.15, length=0.15) arrow.set_color(GREY_A) return arrow class UseNewton(TeacherStudentsScene): def construct(self): self.teacher_says( OldTexText( "You could solve\\\\ $A(z) - z\\cdot B(z) = 0$ \\\\", "using Newton's method" ), bubble_config={ "width": 4, "height": 3, }, target_mode="hooray", added_anims=[ self.change_students("confused", "erm", "maybe") ] ) self.wait(2) self.student_says( Text("Too meta..."), target_mode="sassy", index=2, ) self.wait(3) class DescribeDerivative(Scene): zoom_in_frame = False z = 1 z_str = "{1}" fz_str = "1" fpz_str = "2" def construct(self): # Add plane plane = ComplexPlane((-4, 4), (-2, 2)) plane.set_height(FRAME_HEIGHT) plane.add_coordinate_labels(font_size=18) self.add(plane) # Add function labels z_str = self.z_str fz_str = self.fz_str fpz_str = self.fpz_str kw = { "tex_to_color_map": { "z": GREY_A, z_str: YELLOW, }, "isolate": ["f", "(", ")", "=", z_str, fz_str, fpz_str], } f_label = OldTex("f(z) = z^2", **kw) df_label = OldTex("f'(z) = 2z", **kw) labels = VGroup(f_label, df_label) labels.arrange(DOWN) labels.to_corner(UL) labels.set_stroke(BLACK, 5, background=True) corner_rect = SurroundingRectangle(labels, buff=0.25) corner_rect.set_stroke(WHITE, 2) corner_rect.set_fill(BLACK, 0.9) corner_group = VGroup(corner_rect, *labels) corner_group.to_corner(UL, buff=0) df_question = Text("Derivative?") df_question.set_stroke(BLACK, 5, background=True) df_arrow = Vector(LEFT) df_arrow.next_to(f_label, RIGHT, SMALL_BUFF) df_question.next_to(df_arrow, RIGHT, SMALL_BUFF) self.add(corner_rect, f_label) self.play( FadeIn(df_question, 0.2 * RIGHT), ShowCreation(df_arrow) ) self.wait() self.play( FadeIn(df_label, shift=0.5 * DOWN), FadeOut(df_question), Uncreate(df_arrow), ) # Add dots density = 10 dot_radius = 0.025 dots = DotCloud([ plane.c2p(x, y) for x in np.arange(-3.7, 3.7, 1.0 / density) for y in np.arange(-2.0, 2.1, 1.0 / density) ]) dots.set_radius(dot_radius) dots.set_color(GREY_B) dots.set_gloss(0.2) dots.set_opacity(0.5) dots.add_updater(lambda m: m) epsilon = 5e-3 tiny_dots = DotCloud([ plane.n2p(self.z + epsilon * complex(x, y)) for x in np.arange(-20, 20) for y in np.arange(-10, 10) ]) tiny_dots.set_radius(dot_radius * 15 * epsilon) tiny_dots.set_opacity(0.75) tiny_dots.set_color_by_gradient(YELLOW, BLUE) tiny_dots.set_gloss(0.2) self.add(dots, corner_group) self.play(ShowCreation(dots), run_time=2) self.wait() # Show function evaluation ex_labels = VGroup( OldTex(f"f({z_str}) = {fz_str}", **kw), OldTex(f"f'({z_str}) = {fpz_str}", **kw), ) for ex_label, gen_label in zip(ex_labels, labels): ex_label.next_to(gen_label, RIGHT, MED_LARGE_BUFF) ex_labels[0].align_to(ex_labels[1], LEFT) corner_rect.generate_target() corner_rect.target.set_width( VGroup(ex_labels, labels).get_width() + 0.5, about_edge=LEFT, stretch=True, ) self.add(*corner_group) self.play( MoveToTarget(corner_rect), FadeIn(ex_labels), ) self.wait() # Apply function fade_anims = [] if self.zoom_in_frame: rect = self.camera.frame plane.generate_target() fade_anims = [ ApplyMethod(dots.set_opacity, 0, rate_func=squish_rate_func(smooth, 0.5, 1.0)), plane.animate.set_stroke(width=0.25), ] else: rect = ScreenRectangle() rect.set_height(FRAME_HEIGHT) rect.set_stroke(WHITE, 2) self.play( rect.animate.replace(tiny_dots, 1).move_to(plane.n2p(self.z)), *fade_anims, FadeIn(tiny_dots), run_time=3, ) self.wait() # def func(p): # z = plane.p2n(p) # return plane.n2p(z**2) def homotopy(x, y, z, t): z = plane.p2n([x, y, z]) return plane.n2p(z**(1 + t)) rc = rect.get_center() path = ParametricCurve(lambda t: homotopy(*rc, t)) self.play( Homotopy(homotopy, dots), Homotopy(homotopy, tiny_dots), MoveAlongPath(rect, path), # dots.animate.apply_function(func), # tiny_dots.animate.apply_function(func), # rect.animate.move_to(func(rect.get_center())), run_time=5, ) self.wait() class DescribeDerivativeInnerFrame(DescribeDerivative): zoom_in_frame = True class DescribeDerivativeIExample(DescribeDerivative): z = 1j z_str = "{i}" fz_str = "-1" fpz_str = "2i" class DescribeDerivativeIExampleInnerFrame(DescribeDerivativeIExample): zoom_in_frame = True class LooksLikeTwoMult(Scene): const = "2" def construct(self): tex = OldTexText(f"Looks like $z \\rightarrow {self.const}\\cdot z$") tex.set_stroke(BLACK, 5, background=True) self.play(FadeIn(tex, lag_ratio=0.1)) self.wait() class LooksLikeTwoiMult(LooksLikeTwoMult): const = "2i" class Cycles(FixedPoints): def construct(self): # Set the stage iter_label = self.add_labels() rule, iterations = iter_label self.remove(rule) iterations.to_edge(UP) plane = self.add_plane() z0_dot, z0_label = self.add_z_dot(complex(-1.1, 0.6), "z_0") z1_dot, z1_label = self.add_z_dot(complex(0.2, -0.5), "z_1") z1_label.next_to(z1_dot, UR, SMALL_BUFF) z_dots = VGroup(z0_dot, z1_dot) z_labels = VGroup(z0_label, z1_label) # Ask question question = OldTexText("When does $z$ cycle?") question.next_to(plane, UP, MED_SMALL_BUFF) kw = {"path_arc": PI / 3, "buff": 0.1} arrows = VGroup( Arrow(z0_dot, z1_dot, **kw), Arrow(z1_dot, z0_dot, **kw), ) arrows.set_stroke(opacity=0.75) z_dot = z0_dot.copy() z_dot.set_color(YELLOW) self.add(question) self.play( ShowCreation(arrows[0]), TransformFromCopy(z0_dot, z1_dot, path_arc=-PI / 3), TransformFromCopy(z0_label, z1_label, path_arc=-PI / 3), ) self.wait() self.play( TransformFromCopy(z1_dot, z_dot, path_arc=-PI / 3), ShowCreation(arrows[1]), ) self.wait() for n in range(1, 5): self.play(z_dot.move_to, z_dots[n % 2], path_arc=PI / 3) self.wait() # Show formula kw = { "tex_to_color_map": {"z": BLUE}, "isolate": ["f"], } f2_equation = OldTex("f(f(z)) = z", **kw) f2_equation.next_to(plane, RIGHT, MED_LARGE_BUFF, aligned_edge=UP) julia_fractal = JuliaFractal(plane) julia_fractal.set_c(-0.18 + 0.77j) z2c = OldTex("f(z) = z^2 + c", **kw) z2c.next_to(f2_equation, RIGHT, LARGE_BUFF) self.play(FadeIn(f2_equation, 0.25 * DOWN)) self.wait() self.add(julia_fractal, plane, z_dots, z_dot, z_labels, arrows, z_dot) julia_fractal.set_opacity(0) self.play( julia_fractal.animate.set_opacity(0.75), Write(z2c), ) self.wait() # Example with z^2 + c julia_f2_eqs = VGroup( OldTex("(z^2 + c)^2 + c = z", **kw), OldTex("z^4 + 2cz^2 -z + c^2 + c = 0", **kw), ) julia_f2_eqs.arrange(DOWN, buff=0.7, aligned_edge=LEFT) julia_f2_eqs.next_to(f2_equation, DOWN, buff=1.0, aligned_edge=LEFT) eq_arrows = VGroup( Arrow(f2_equation.get_bottom(), julia_f2_eqs.get_top()), Arrow(z2c.get_bottom(), julia_f2_eqs.get_top()), ) self.play( *map(ShowCreation, eq_arrows), FadeIn(julia_f2_eqs[0], 0.5 * DOWN) ) self.wait() self.play( TransformMatchingShapes( julia_f2_eqs[0].copy(), julia_f2_eqs[1] ) ) self.wait() # Add fixed_points fixed_dots = VGroup( Dot(plane.c2p(0.8, -0.5), color=GREY_A), Dot(plane.c2p(-0.9, -0.6), color=GREY_A), ) arrow_loops = VGroup(*( self.get_arrow_loop(dot) for dot in fixed_dots )) for dot, loop in zip(fixed_dots, arrow_loops): loop.set_color(GREY_B) self.play( FadeIn(dot, scale=0.3), ShowCreation(loop), ) self.wait() self.play( LaggedStartMap(FadeOut, VGroup( eq_arrows, *julia_f2_eqs, *fixed_dots, *arrow_loops, )) ) # N cycles fn_eq = OldTex( "f(f(\\cdots f(z) \\cdots)) = z", **kw ) fn_eq.move_to(f2_equation, LEFT) fn_eq.shift(SMALL_BUFF * DOWN) brace = Brace( fn_eq[:fn_eq.index_of_part_by_tex("z")], DOWN ) brace_tex = brace.get_tex("n \\text{ times}", buff=SMALL_BUFF) brace_tex.scale(0.7, about_edge=UP) for z in [-0.2 + 0.6j, 1.1 - 0.6j, 0.4 + 0.2j]: dot = z0_dot.copy() dot.set_fill(BLUE_D) dot.move_to(plane.n2p(z)) z_dots.add(dot) n_arrows = VGroup() for d1, d2 in adjacent_pairs(z_dots): arrow = Arrow(d1, d2, buff=0.1, path_arc=PI / 8) arrow.set_stroke(WHITE, opacity=0.7) n_arrows.add(arrow) dot_anims = [] n = len(z_dots) for k in range(1, n + 1): dot_anims.append( ApplyMethod(z_dot.move_to, z_dots[k % n], path_arc=PI / 8) ) self.play( TransformMatchingShapes(f2_equation, fn_eq), FadeOut(z2c), ReplacementTransform(arrows, n_arrows), *map(GrowFromCenter, z_dots[2:]) ) self.play( GrowFromCenter(brace), FadeIn(brace_tex, SMALL_BUFF * DOWN), Succession(*dot_anims, run_time=3), ) self.wait() # Ask about how many solutions morty = Mortimer(height=2) morty.to_corner(DR) z2c.next_to(fn_eq, UP, buff=MED_LARGE_BUFF) self.play( PiCreatureSays( morty, "How many solutions?", bubble_config={"height": 2, "width": 4} ), ) self.play(Blink(morty)) self.wait() self.play( FadeIn(z2c), RemovePiCreatureBubble( morty, target_mode="pondering", look_at=z2c, ) ) self.wait() # 1,000,000-cycles million = Integer(1e6, font_size=36) million.next_to(brace, DOWN) million.set_value(0) mega_poly = OldTex( "z^{2^{1{,}000{,}000}} +", "\\cdots \\text{(nightmare)} \\cdots", "= 0", **kw ) mega_poly.next_to(million, DOWN, buff=0.75) mega_poly.align_to(fn_eq, LEFT) expr = self.show_composition(million, morty, **kw) self.play( ChangeDecimalToValue(million, 1e6, run_time=2), VFadeIn(million), FadeOut(brace_tex), morty.change("raise_right_hand", fn_eq) ) self.play(Blink(morty)) self.play( FadeOut(expr), Write(mega_poly), morty.animate.set_height(1.8, about_edge=DR).change("horrified", mega_poly), ) self.play(morty.animate.look_at(mega_poly.get_right())) self.wait() # Show "million" dots N = 5000 points = np.random.random((N, 3)) points[:, 2] = 0 dots = DotCloud(points, radius=0) dots.replace(plane) dots.set_radius(0.01) dots.set_color(GREY_B) dots.set_opacity(1) dots.add_updater(lambda m: m) self.play( FadeOut(z_labels), FadeOut(z_dots), FadeOut(n_arrows), morty.change("erm", dots), ShowCreation(dots, run_time=5), ) self.wait() self.play( FadeOut(dots), FadeOut(mega_poly), FadeOut(morty), FadeOut(z2c), ) # Rational map rational = OldTex("f(z) = {A(z) \\over B(z)}", **kw) rational.next_to(million, DOWN, LARGE_BUFF) rational.align_to(fn_eq, LEFT) self.play(FadeIn(rational)) for arrow, dot in zip(n_arrows, [*z_dots[1:], z_dots[0]]): self.play( ShowCreation(arrow), z_dot.animate.move_to(dot), path_arc=PI / 6, ) self.add(dot, z_dot) # Ask about attracting cycle new_question = Text("When is a cycle attracting?") new_question.get_part_by_text("attracting").set_color(YELLOW) new_question.next_to(question, RIGHT, LARGE_BUFF) self.play( Write(new_question, run_time=1), fn_eq.animate.shift(0.5 * DOWN), FadeOut(brace), FadeOut(million), ) circle = Circle(radius=0.5) circle.set_stroke(YELLOW, 1, 1) circle.set_fill(YELLOW, 0.25) h_tracker = ValueTracker(1.0) circle.add_updater(lambda m: m.set_height(h_tracker.get_value())) circle.add_updater(lambda m: m.move_to(z_dot)) multipliers = [0.9, 0.9, 1.2, 0.5, 1.1] self.add(circle, z_dot) self.play(GrowFromCenter(circle)) for n in range(3): for mult, dot in zip(multipliers, [*z_dots[1:], z_dots[0]]): self.play( ApplyMethod(z_dot.move_to, dot, path_arc=PI / 6), h_tracker.animate.set_value(h_tracker.get_value() * mult), ) # Possibly add on a bit for Fatou's theorem? theorem = OldTexText( "Theorem (Fatou 1919): If $f(z)$ has an\\\\", "attracting cycle, then at least one solution\\\\", "to $f'(z) = 0$ will fall into it.", font_size=36, ) theorem.arrange(DOWN, buff=0.15, aligned_edge=LEFT) theorem.next_to(fn_eq, DOWN, LARGE_BUFF, aligned_edge=LEFT) self.play( rational.animate.set_height(0.8).next_to(fn_eq, RIGHT, LARGE_BUFF), FadeIn(theorem), ) def show_composition(self, ref_mob, morty, **kwargs): tex = "z^2 + c" polys = VGroup(OldTex(tex, **kwargs)) for n in range(20): new_tex_parts = ["\\left(", tex, "\\right)^2 + c"] polys.add(OldTex(*new_tex_parts)) if n < 3: tex = "".join(new_tex_parts) for poly in polys: poly.set_max_width(5) poly.next_to(ref_mob, DOWN, LARGE_BUFF, aligned_edge=LEFT) degree = VGroup(Text("Degree: "), Integer(2)) degree.arrange(RIGHT) degree.next_to(polys, DOWN, aligned_edge=LEFT) curr_poly = polys[0] self.play( FadeIn(curr_poly), FadeIn(degree), morty.change("tease", curr_poly), ) for n, poly in enumerate(polys[1:]): anims = [] if n == 4: anims.append(morty.change("erm")) self.play( curr_poly.animate.replace(poly[1]), FadeIn(poly[::2]), UpdateFromAlphaFunc( degree, lambda m, a: m[1].set_value( (2**(n + 1) if a < 0.5 else 2**(n + 2)) ) ), *anims, run_time=(1 if n < 5 else 0.25) ) poly.replace_submobject(1, curr_poly) self.add(poly) curr_poly = poly self.wait() self.play(FadeOut(degree)) return poly class TwoToMillionPoints(Scene): c = -0.18 + 0.77j plane_height = 7 def construct(self): plane, julia_fractal = self.get_plane_and_fractal() words = OldTexText("$\\approx 2^{1{,}000{,}000}$ solutions!") words.set_stroke(BLACK, 8, background=True) words.move_to(plane, UL) words.shift(MED_SMALL_BUFF * DR) points = self.get_julia_set_points(plane, 100000, 1000) dots = DotCloud(points) dots.set_color(YELLOW) dots.set_opacity(1) dots.set_radius(0.025) dots.add_updater(lambda m: m) dots.make_3d() self.add(julia_fractal, plane, words) self.play(ShowCreation(dots, run_time=10)) def get_plane_and_fractal(self): plane = ComplexPlane((-2, 2), (-2, 2)) plane.set_height(self.plane_height) fractal = JuliaFractal(plane) fractal.set_c(self.c) return plane, fractal def get_julia_set_points(self, plane, n_points, n_steps): values = np.array([ complex(math.cos(x), math.sin(x)) for x in np.linspace(0, TAU, n_points) ]) c = self.c for n in range(n_steps): units = -1 + 2 * np.random.randint(0, 2, len(values)) values[:] = (units * np.sqrt(values[:])) - c values += c return np.array(list(map(plane.n2p, values))) class CyclesHaveSolutions(Scene): def construct(self): text = VGroup( OldTex( "f^n(z) = z \\text{ has solutions}", tex_to_color_map={"z": BLUE}, ), OldTex("\\sim D^n \\text{ of them...}"), ) text.arrange(DOWN) for part in text: self.play(FadeIn(part)) self.wait() class MandelbrotFunctions(Scene): def construct(self): kw = {"tex_to_color_map": {"c": YELLOW}} group = VGroup( OldTex("f(z) = z^2 + c", **kw), OldTex("f'(z) = 2z"), ) group.arrange(DOWN, aligned_edge=LEFT) self.add(group) class AmbientNewtonRepetition(RepeatedNewton): coefs = [-4, 0, -3, 0, 1] show_fractal_background = True show_coloring = False n_steps = 20 dot_density = 10.0 points_scalar = 2.0 dots_config = { "radius": 0.025, "color": GREY_A, "gloss": 0.4, "shadow": 0.1, "opacity": 0.5, } class AmbientNewtonBoundary(AmbientNewtonRepetition): def construct(self): self.add_plane() fractal = self.get_fractal() self.remove(self.plane) fractal.set_julia_highlight(1e-4) fractal.set_colors(5 * [WHITE]) self.play(GrowFromPoint( fractal, fractal.get_corner(UL), run_time=5 )) self.wait() class CyclicAttractor(RepeatedNewton): coefs = [2, -2, 0, 1] n_steps = 20 show_coloring = False cluster_radius = 0.5 def add_plane(self): super().add_plane() self.plane.axes.set_stroke(GREY_B, 1) self.plane.scale(1.7) def add_labels(self): super().add_labels() eq = self.corner_group[1] self.play(FlashAround(eq, run_time=3)) def get_original_points(self): return [ (r * np.cos(theta), r * np.sin(theta), 0) for r in np.linspace(0, self.cluster_radius, 10) for theta in np.linspace(0, TAU, int(50 * r)) + TAU * np.random.random() ] class CyclicAttractorSmallRadius(CyclicAttractor): cluster_radius = 0.25 colors = ROOT_COLORS_DEEP[0::2] def construct(self): super().construct() fractal = NewtonFractal( self.plane, coefs=self.coefs, colors=self.colors, black_for_cycles=True, ) dots = VGroup(*( Dot(rd.get_center()) for rd in self.root_dots )) dots.set_stroke(BLACK, 3) dots.set_fill(opacity=0) self.add(fractal, *self.mobjects, dots) self.play( FadeIn(fractal), self.plane.animate.fade(0.5) ) self.wait() class CyclicExercise(Scene): def construct(self): words = OldTexText( "Exercise 2: If $f(z) = z - {z^3 - 2z + 2 \\over 3z^2 - 2}$,\\\\", "and $g(z) = f(f(z))$, confirm that $|g'(0)| < 1$." ) words[1].shift(SMALL_BUFF * DOWN) box = SurroundingRectangle(words, buff=0.45) box.set_stroke(WHITE, 2) box.set_fill(BLACK, 1) group = VGroup(box, words) group.to_edge(UP, buff=0) hint = OldTexText( "Hint: Don't expand out $g(z)$. Use\\\\", "the chain rule: $g'(0) = f'(f(0))f'(0)$" ) hint.scale(0.8) hint.set_color(GREY_A) hint_box = SurroundingRectangle(hint, buff=0.25) hint_box.match_style(box) hint_group = VGroup(hint_box, hint) hint_group.next_to(group, DOWN, buff=0) self.add(group) self.wait(2) self.play(FadeIn(hint_group)) self.wait() class AskHowOftenThisHappensAlt(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("How often does\\\\this happen?"), bubble_config={ "height": 3, "width": 4, }, index=0, ) self.play( self.teacher.change("raise_right_hand", 3 * UR), self.change_students( "raise_left_hand", "pondering", "pondering", look_at=3 * UR, ) ) self.play_student_changes( "raise_left_hand", "erm", "erm", look_at=3 * UR, ) self.wait() self.play(self.teacher.change("tease", 3 * UR)) self.play_student_changes( "confused", "pondering", "thinking", look_at=3 * UR, ) self.wait(8) return self.wait(2) self.play( PiCreatureSays( self.teacher, "You'll like this", target_mode="tease", run_time=1, ), self.students[1].change("thinking", self.teacher.eyes), self.students[2].change("thinking", self.teacher.eyes), ) self.wait(2) class WhatDoesBlackMean(Scene): def construct(self): lhs = OldTexText("$z_n$ never gets\\\\near a root") rhs = OldTexText("$\\Rightarrow$ ", "Black ", ) rhs.next_to(lhs, RIGHT) words = VGroup(lhs, rhs) words.next_to(ORIGIN, UR, MED_LARGE_BUFF) words.to_edge(RIGHT) words.set_stroke(BLACK, 5, background=True) # lhs[0].set_color(BLACK) # lhs[0].set_stroke(width=0) arrow = Arrow(ORIGIN, words.get_left(), buff=0.1) self.play( ShowCreation(arrow), Write(lhs), ) self.wait() self.play(FadeIn(rhs)) self.wait() class PlayWithRootsSeekingCycles(ThreeRootFractal): coefs = [2, -2, 0, 1] def construct(self): super().construct() self.fractal.uniforms["black_for_cycles"] = 1.0 class ShowCenterOfMassPoint(PlayWithRootsSeekingCycles): display_root_values = True only_center = False def construct(self): super().construct() mean_dot = glow_dot(ORIGIN) mean_dot.add_updater(lambda m: m.move_to( sum([rd.get_center() for rd in self.root_dots]) / 3 )) self.add(mean_dot) if self.only_center: mean_dot.set_opacity(0) self.fractal.replace(mean_dot, stretch=True) self.fractal.add_updater(lambda m: m.move_to(mean_dot)) window = Square() window.set_stroke(WHITE, 1) window.set_fill(BLACK, 0) window.replace(self.fractal, stretch=True) window.add_updater(lambda m: m.move_to(mean_dot)) self.add(window) mean_label = OldTex("(r_1 + r_2 + r_3) / 3", font_size=24) mean_label.set_stroke(BLACK, 2, background=True) mean_label.add_updater(lambda m: m.next_to(mean_dot, UP, buff=0.1)) self.add(mean_label) circle = Circle(radius=2) circle.rotate(PI) circle.stretch(0.9) circle.move_to(self.root_dots, LEFT) self.play( MoveAlongPath( self.root_dots[2], circle, rate_func=linear, run_time=20 ) ) self.play( self.root_dots[2].animate.move_to(self.plane.n2p(-3)), rate_func=there_and_back, run_time=10, ) class ShowCenterOfMassPointFocusIn(ShowCenterOfMassPoint): only_center = True class CenterOfMassStatement(Scene): def construct(self): words = OldTexText( "If there's an attracting cycle, the seed\\\\", "$z_0 = (r_1 + r_2 + r_3) / 3$ will fall into it." ) words.set_stroke(BLACK, 8, background=True) words.to_corner(UL) self.play(Write(words)) self.wait() class GenerateCubicParameterPlot(Scene): colors = ROOT_COLORS_DEEP[0::2] def construct(self): # Title colors = self.colors kw = { "tex_to_color_map": { "\\lambda": colors[2], } } title = OldTex( "z_{n+1} = z_n - {P(z_n) \\over P'(z_n)} \\qquad\\qquad ", "P(z) = (z - 1)(z + 1)(z - \\lambda)", font_size=30, **kw ) title.to_edge(UP) self.add(title) # Planes planes = VGroup(*( ComplexPlane( (-2, 2), (-2, 2), background_line_style={ "stroke_color": GREY_B, "stroke_opacity": 0.5, }, ) for x in range(2) )) for plane, vect in zip(planes, [DL, DR]): plane.add_coordinate_labels(font_size=18) plane.set_height(5) plane.to_corner(vect, buff=MED_SMALL_BUFF) root_dots = VGroup(*( Dot(planes[0].n2p(z), color=color) for color, z in zip(colors, [-1, 1, 1j]) )) root_dots.set_stroke(BLACK, 2) lambda_label = OldTex("\\lambda", font_size=36) lambda_label.set_color(interpolate_color(colors[2], WHITE, 0.75)) lambda_label.set_stroke(BLACK, 3, background=True) lambda_label.add_updater(lambda m: m.next_to( root_dots[2], UR, buff=SMALL_BUFF, )) # Fractals left_fractal = NewtonFractal( planes[0], coefs=[-1, 0, 0, 1], colors=colors, black_for_cycles=True, ) left_fractal.add_updater(lambda m: m.set_roots([ planes[0].p2n(rd.get_center()) for rd in root_dots ])) right_fractal = MetaNewtonFractal( planes[1], colors=colors, fixed_roots=[-1, 1], ) row_meta_fractal = right_fractal.deepcopy() col_meta_fractal = right_fractal.deepcopy() self.add(left_fractal, planes[0], planes, root_dots, lambda_label) # Plane titles plane_titles = VGroup( OldTexText("Pixel $\\leftrightarrow z_0$"), OldTexText("Pixel $\\leftrightarrow$ ", "$\\lambda$"), ) plane_titles[1][-1].set_color(colors[2]) for plane_title, plane in zip(plane_titles, planes): plane_title.next_to(plane, UP, MED_SMALL_BUFF) plane_titles[0].align_to(plane_titles[1], UP) self.add(plane_titles[0]) # Show left plane pins = VGroup() for rd in root_dots[:2]: pin = SVGMobject("push_pin") pin.set_fill(GREY_C) pin.set_stroke(width=0) pin.set_gloss(0.5) pin.set_height(0.3) pin.rotate(10 * DEGREES) pin.move_to(rd.get_center(), DR) pins.add(pin) self.play( FadeIn(pin, 0.25 * DR), FlashAround(rd), ) self.wait() circle = Circle() circle.scale(0.5) circle.rotate(PI / 2) circle.move_to(root_dots[2].get_center(), UP) self.play(MoveAlongPath(root_dots[2], circle, run_time=5)) self.play( root_dots[2].animate.move_to(planes[0].get_corner(UL)), run_time=2 ) self.wait() # Center of mass dot com_dot = Dot() com_dot.set_fill(opacity=0) com_dot.set_stroke(YELLOW, 3) com_dot.add_updater(lambda m: m.move_to( np.array([rd.get_center() for rd in root_dots]).mean(0) )) self.play(FadeIn(com_dot, scale=0.5), FadeOut(pins)) self.wait() # Right plane self.play(Write(plane_titles[1])) self.wait() # Show filling process step = 0.1 square = Square() square.set_stroke(WHITE, 2) arrow = Arrow(LEFT, RIGHT, stroke_width=3) self.add(row_meta_fractal, col_meta_fractal, planes[1]) self.add(square, arrow) x_range = np.arange(-2, 2 + step, step) y_range = np.arange(2, -2, -step) thin_height = plane.get_y_unit_size() * step col_meta_fractal.set_height(thin_height) square.set_height(thin_height) epsilon = 1e-6 for y, back in zip(y_range, it.cycle([False, True])): height = max(epsilon, plane.get_y_unit_size() * abs(2 - y)) row_meta_fractal.set_height(height, stretch=True) row_meta_fractal.move_to(planes[1], UP) x0 = (2 if back else -2) for x in (x_range[::-1] if back else x_range): width = max(epsilon, planes[1].get_x_unit_size() * abs(x - x0)) col_meta_fractal.set_width(width, stretch=True) col_meta_fractal.next_to(row_meta_fractal, DOWN, buff=0) col_meta_fractal.align_to(row_meta_fractal, RIGHT if back else LEFT) root_dots[2].move_to(planes[0].c2p(x, y)) square.move_to( col_meta_fractal, DOWN + (LEFT if back else RIGHT) ) self.update_mobjects(0) arrow.put_start_and_end_on( com_dot.get_center(), square.get_center(), ) self.wait(1 / 15) self.play(FadeOut(arrow), FadeOut(square)) self.wait() # Zoom in to meta fractal frame = self.camera.frame self.play( frame.animate.replace(planes[1], 1), run_time=3, ) self.wait() class Z0RuleLabel(Scene): def construct(self): label = OldTex("z_0 = (r_1 + r_2 + r_3) / 3") self.add(label) class WhyFractals(Scene): def construct(self): words = Text("Why fractals?") words.set_stroke(BLACK, 5, background=True) self.play(Write(words)) self.wait() class SmallCircleProperty(Scene): def construct(self): # Titles rule = OldTexText( "For any rational map, color points\\\\based on their limiting behavior...\\\\", "(which limit point, which limit cycle, etc.)", font_size=36, ) rule.to_corner(UL) rule[-1].shift(SMALL_BUFF * DOWN) rule[-1].set_color(GREY_B) r_map = OldTex("z_{n + 1} = A(z_n) / B(z_n)") r_map.to_corner(UR) # Fractal colors = [ MANDELBROT_COLORS[0], BLUE_C, BLUE_E, ROOT_COLORS_DEEP[1], ] plane = ComplexPlane((-2, 2), (-2, 2)) plane.set_height(5) plane.to_corner(DR) fractal = NewtonFractal(plane, coefs=[5, 4j, 3, 2, 1], colors=colors) # Circles circles = Circle(radius=0.6).get_grid(3, 1, buff=0.5) circles.replace(plane, 1) circles.set_x(-1) circles.set_stroke(WHITE, 2) circles[0].set_fill(colors[2], 1) semis = circles[1].copy().pointwise_become_partial(circles[1], 0, 0.5).replicate(2) semis[1].rotate(PI, about_point=circles[1].get_center()) semis[0].set_fill(colors[0], 1) semis[1].set_fill(colors[1], 1) circles[1].add(semis) multi_color_image = ImageMobject("MulticoloredNewtonsMapCircle") multi_color_image.add_updater(lambda m: m.replace(circles[2])) # Circle label circle_labels = VGroup( Text("One color"), Text("Some colors"), Text("All colors"), ) marks = VGroup(Checkmark(), Exmark(), Checkmark()) for label, mark, circle in zip(circle_labels, marks, circles): mark.set_height(0.5 * circle.get_height()) mark.next_to(circle, LEFT, MED_LARGE_BUFF) label.next_to(mark, LEFT, MED_LARGE_BUFF) # Little circles lil_circles = circles[0].replicate(2) lil_circles.set_height(0.2) lil_circles[0].move_to(plane.get_corner(UL) + MED_SMALL_BUFF * DR) lil_circles[1].move_to(plane).shift([0.22, -0.12, 0]) lil_circles[1].set_fill(opacity=0) lines = VGroup() for big, lil in zip(circles[::2], lil_circles): vect = normalize(lil.get_center() - big.get_center()) v1 = rotate_vector(vect, 75 * DEGREES) v2 = rotate_vector(vect, -75 * DEGREES) big.insert_n_curves(20) lines.add(VGroup( Line(lil.get_top(), big.get_boundary_point(v1)), Line(lil.get_bottom(), big.get_boundary_point(v2)), )) lines.set_stroke(WHITE, 1) # Intro anims self.add(rule[0]) self.play(FadeIn(r_map)) self.wait() fractal.set_opacity(0) self.add(fractal) for i in range(1, 5): opacities = np.zeros(4) opacities[:i] = 1 self.play(fractal.animate.set_opacities(*opacities)) self.wait() self.play(FadeIn(rule[-1], lag_ratio=0.1, run_time=2)) self.wait() # Show circles self.add(lil_circles[0]) self.play( TransformFromCopy(lil_circles[0], circles[0]), *map(ShowCreation, lines[0]), FadeIn(circle_labels[0]), ) self.play(Write(marks[0])) self.wait() self.add(multi_color_image) self.add(lil_circles[1]) self.play( TransformFromCopy(lil_circles[1], circles[2]), *map(ShowCreation, lines[1]), FadeIn(circle_labels[2]), ) self.play(Write(marks[2])) self.wait() self.play( FadeIn(circle_labels[1]), FadeIn(circles[1]), ) self.play(Write(marks[1])) self.wait() class MentionFatouSetsAndJuliaSets(Scene): colors = [RED_E, BLUE_E, TEAL_E, MAROON_E] def construct(self): # Introduce terms f_group, j_group = self.get_fractals() f_name, j_name = VGroup( Text("Fatou set"), Text("Julia set"), ) f_name.next_to(f_group, UP, MED_LARGE_BUFF) j_name.next_to(j_group, UP, MED_LARGE_BUFF) self.play( Write(j_name), GrowFromCenter(j_group) ) self.wait() self.play( Write(f_name), *map(GrowFromCenter, f_group) ) self.wait() # Define Fatou set fatou_condition = self.get_fatou_condition() fatou_condition.set_width(FRAME_WIDTH - 1) fatou_condition.center().to_edge(UP, buff=1.0) lhs, arrow, rhs = fatou_condition f_line = Line(LEFT, RIGHT) f_line.match_width(fatou_condition) f_line.next_to(fatou_condition, DOWN) f_line.set_stroke(WHITE, 1) self.play( FadeOut(j_name, RIGHT), FadeOut(j_group, RIGHT), Write(lhs) ) self.wait() for words in lhs[-1]: self.play(FlashUnder( words, buff=0, time_width=1.5 )) self.play(Write(arrow)) self.play(LaggedStart( FadeTransform(f_name.copy(), rhs[1][:8]), FadeIn(rhs), lag_ratio=0.5 )) self.wait() # Show Julia set otherwise = Text("Otherwise...") otherwise.next_to(rhs, DOWN, LARGE_BUFF) j_condition = OldTexText("$z_0 \\in$", " Julia set", " of $f$") j_condition.match_height(rhs) j_condition.next_to(otherwise, DOWN, LARGE_BUFF) j_group.set_height(4.0) j_group.to_edge(DOWN) j_group.set_x(-1.0) j_name = j_condition.get_part_by_tex("Julia set") j_underline = Underline(j_name, buff=0.05) j_underline.set_color(YELLOW) arrow = Arrow( j_name.get_bottom(), j_group.get_right(), path_arc=-45 * DEGREES, ) arrow.set_stroke(YELLOW, 5) julia_set = j_group[0] julia_set.update() julia_set.suspend_updating() julia_copy = julia_set.copy() julia_copy.clear_updaters() julia_copy.set_colors(self.colors) julia_copy.set_julia_highlight(0) mover = f_group[:-4] mover.generate_target() mover.target.match_width(rhs) mover.target.next_to(rhs, UP, MED_LARGE_BUFF) mover.target.shift_onto_screen(buff=SMALL_BUFF) self.play( ShowCreation(f_line), FadeOut(f_name), MoveToTarget(mover), ) self.play( Write(otherwise), FadeIn(j_condition, 0.5 * DOWN) ) self.wait() self.play( ShowCreation(j_underline), ShowCreation(arrow), FadeIn(j_group[1]), FadeIn(julia_copy) ) self.play( GrowFromPoint(julia_set, julia_set.get_corner(UL), run_time=2), julia_copy.animate.set_opacity(0.2) ) self.wait() def get_fractals(self, jy=1.5, fy=-2.5): coefs = roots_to_coefficients([-1.5, 1.5, 1j, -1j]) n = len(coefs) - 1 colors = self.colors f_planes = VGroup(*(self.get_plane() for x in range(n))) f_planes.arrange(RIGHT, buff=LARGE_BUFF) plusses = OldTex("+").replicate(n - 1) f_group = Group(*it.chain(*zip(f_planes, plusses))) f_group.add(f_planes[-1]) f_group.arrange(RIGHT) fatou = Group(*( NewtonFractal(f_plane, coefs=coefs, colors=colors) for f_plane in f_planes )) for i, fractal in enumerate(fatou): opacities = n * [0.2] opacities[i] = 1 fractal.set_opacities(*opacities) f_group.add(*fatou) f_group.set_y(fy) j_plane = self.get_plane() j_plane.set_y(jy) julia = NewtonFractal(j_plane, coefs=coefs, colors=5 * [GREY_A]) julia.set_julia_highlight(1e-3) j_group = Group(julia, j_plane) for fractal, plane in zip((*fatou, julia), (*f_planes, j_plane)): fractal.plane = plane fractal.add_updater( lambda m: m.set_offset( m.plane.get_center() ).set_scale( m.plane.get_x_unit_size() ).replace(m.plane) ) fractals = Group(f_group, j_group) return fractals def get_plane(self): plane = ComplexPlane( (-2, 2), (-2, 2), background_line_style={"stroke_width": 1, "stroke_color": GREY} ) plane.set_height(2) plane.set_opacity(0) box = SurroundingRectangle(plane, buff=0) box.set_stroke(WHITE, 1) plane.add(box) return plane def get_fatou_condition(self): zn = OldTex( "z_0", "\\overset{f}{\\longrightarrow}", "z_1", "\\overset{f}{\\longrightarrow}", "z_2", "\\overset{f}{\\longrightarrow}", "\\dots", "\\longrightarrow" ) words = VGroup( OldTexText("Stable fixed point"), OldTexText("Stable cycle"), OldTexText("$\\infty$"), ) words.arrange(DOWN, aligned_edge=LEFT) brace = Brace(words, LEFT) zn.next_to(brace, LEFT) lhs = VGroup(zn, brace, words) arrow = OldTex("\\Rightarrow") arrow.scale(2) arrow.next_to(lhs, RIGHT, MED_LARGE_BUFF) rhs = OldTex("z_0 \\in", " \\text{Fatou set of $f$}") rhs.next_to(arrow, RIGHT, buff=MED_LARGE_BUFF) result = VGroup(lhs, arrow, rhs) return result class ShowJuliaSetPoint(TwoToMillionPoints): plane_height = 14 show_disk = False n_steps = 60 disk_radius = 0.02 def construct(self): # Background plane, fractal = self.get_plane_and_fractal() plane.add_coordinate_labels(font_size=24) for mob in plane.family_members_with_points(): if isinstance(mob, Line): mob.set_stroke(opacity=0.5 * mob.get_stroke_opacity()) self.add(fractal, plane) # Points points = list(self.get_julia_set_points(plane, n_points=1, n_steps=1000)) def func(p): z = plane.p2n(p) return plane.n2p(z**2 + self.c) for n in range(100): points.append(func(points[-1])) dot = Dot(points[0]) dot.set_color(YELLOW) self.add(dot) if self.show_disk: dot.scale(0.5) disk = dot.copy() disk.insert_n_curves(10000) disk.set_height(plane.get_x_unit_size() * self.disk_radius) disk.set_fill(YELLOW, 0.25) disk.set_stroke(YELLOW, 2, 1) self.add(disk, dot) frame = self.camera.frame path_arc = 30 * DEGREES point = dot.get_center().copy() for n in range(self.n_steps): new_point = func(point) arrow = Arrow(point, new_point, path_arc=path_arc, buff=0) arrow.set_stroke(WHITE, opacity=0.9) self.add(dot.copy().set_opacity(0.5)) anims = [] if self.show_disk: disk.generate_target() disk.target.apply_function(func) disk.target.make_smooth(approx=True) anims.append(MoveToTarget(disk, path_arc=path_arc)) if disk.target.get_height() > frame.get_height(): anims.extend([ mob.animate.scale(2.0) for mob in [frame, fractal] ]) self.play( ApplyMethod(dot.move_to, new_point, path_arc=path_arc), ShowCreation(arrow), *anims, ) self.play(FadeOut(arrow)) point = new_point class ShowJuliaSetPointWithDisk(ShowJuliaSetPoint): show_disk = True n_steps = 11 class AboutFatouDisks(Scene): disk_style = { "fill_color": YELLOW, "fill_opacity": 0.5, "stroke_color": YELLOW, "stroke_width": 1, } def construct(self): words = Text("(Small enough) disks around points in the Fatou set...") words.to_edge(UP) disks, arrows = self.get_disks_and_arrow() arrows[-1].add(OldTex("\\dots").next_to(arrows[-1], RIGHT)) group = VGroup(disks, arrows) group.next_to(words, DOWN) shrink_words = Text("...eventually shrink to 0") shrink_words.next_to(group, DOWN, aligned_edge=RIGHT) self.add(words) self.play_disk_progression(disks, arrows) self.play( FadeIn(arrows[-1]), Write(shrink_words, run_time=2) ) self.wait() def play_disk_progression(self, disks, arrows): self.add(disks[0]) for d1, d2, arrow in zip(disks, disks[1:], arrows): self.play( TransformFromCopy(d1.copy().fade(1), d2), FadeIn(arrow), ) def get_disks(self): radii = [ *np.linspace(0.5, 1, 3), *np.linspace(1, 0, 7)**2 + 0.05, ] disks = VGroup(*(Circle(radius=r, **self.disk_style) for r in radii)) for disk in disks: disk.add(Dot(disk.get_center(), radius=0.01)) return disks def get_disks_and_arrow(self): disks = self.get_disks() arrows = OldTex("\\rightarrow").replicate(len(disks)) group = VGroup(*it.chain(*zip(disks, arrows))) group.arrange(RIGHT) group.set_width(FRAME_WIDTH - 2) return disks, arrows class AboutFatouDisksJustWords(Scene): def construct(self): words = OldTexText( "(Small enough) disks around points in the Fatou set...\\\\", "...eventually shrink to 0" ) words.arrange(DOWN, aligned_edge=LEFT) words.to_corner(UL) words.set_stroke(BLACK, 6, background=True) self.play(FadeIn(words[0], lag_ratio=0.1)) self.wait() self.play(FadeIn(words[1], lag_ratio=0.1)) self.wait() class ShowFatouDiskExample(Scene): disk_radius = 0.1 n_steps = 14 def construct(self): c = -1.06 + 0.11j plane = ComplexPlane((-3, 3), (-2, 2)) for line in plane.family_members_with_points(): line.set_stroke(opacity=0.5 * line.get_stroke_opacity()) plane.set_height(1.8 * FRAME_HEIGHT) plane.add_coordinate_labels(font_size=18) fractal = JuliaFractal(plane, parameter=c) # z0 = -1.1 + 0.1j z0 = -0.3 + 0.2j dot = Dot(plane.n2p(z0), radius=0.025) dot.set_fill(YELLOW) disk = dot.copy() disk.set_height(2 * self.disk_radius * plane.get_x_unit_size()) disk.set_fill(YELLOW, 0.5) disk.set_stroke(YELLOW, 1.0) disk.insert_n_curves(1000) def func(point): return plane.n2p(plane.p2n(point)**2 + c) self.add(fractal, plane) self.add(disk, dot) self.play(DrawBorderThenFill(disk)) path_arc = 10 * DEGREES for n in range(self.n_steps): point = dot.get_center() new_point = func(point) arrow = Arrow(point, new_point, path_arc=path_arc, buff=0.1) self.play( dot.animate.move_to(new_point), disk.animate.apply_function(func), ShowCreation(arrow), path_arc=path_arc, ) self.play(FadeOut(arrow)) self.embed() class AboutJuliaDisks(AboutFatouDisks): def construct(self): words1 = Text("Any tiny disk around a Julia set point...") words1.to_edge(UP) disks, arrows = self.get_disks_and_arrow() group = VGroup(disks, arrows) group.next_to(words1, DOWN) arrows[-1].add(disks[-1].copy().scale(5).next_to(arrows[-1], RIGHT)) words2 = Text("...eventually hits every point in the plane,") words2.next_to(disks, DOWN, aligned_edge=RIGHT) words2.get_part_by_text("every point in the plane").set_color(BLUE) words3 = Text("with at most two exceptions.") words3.next_to(words2, DOWN, MED_LARGE_BUFF, aligned_edge=RIGHT) words4 = OldTexText( "``Stuff goes everywhere'' principle of Julia sets", font_size=60 ) words4.to_edge(DOWN, LARGE_BUFF) VGroup(words1, words2, words3, words4).set_stroke(BLACK, 5, background=True) plane = ComplexPlane((-100, 100), (-50, 50)) plane.scale(2) plane.add_coordinate_labels() plane.add(BackgroundRectangle(plane, opacity=0.25)) plane.set_stroke(background=True) plane.add_updater(lambda m, dt: m.scale(1 - 0.15 * dt)) self.add(words1) self.play_disk_progression(disks, arrows) self.add(plane, *self.mobjects) self.play( FadeIn(arrows[-1]), FadeIn(words2, run_time=2, lag_ratio=0.1), VFadeIn(plane, suspend_updating=False), ) self.wait() self.play( FadeIn(words3, run_time=2, lag_ratio=0.1), ) self.wait(2) self.play(Write(words4)) self.wait(6) self.play(VFadeOut(plane, suspend_updating=False)) def get_disks(self): c = -0.18 + 0.77j z = -0.491 - 0.106j plane = ComplexPlane() disk = Circle(radius=0.1, **self.disk_style) disk.move_to(plane.n2p(z)) disk.insert_n_curves(200) disks = VGroup(disk) for n in range(5): new_disk = disks[-1].copy() new_disk.apply_complex_function(lambda z: z**2 + c) new_disk.make_smooth(approx=True) disks.add(new_disk) for disk in disks: disk.center() disks.set_height(1) return disks class MontelCorrolaryScreenGrab(ExternallyAnimatedScene): pass class DescribeChaos(Scene): def construct(self): j_point = 3 * LEFT j_value = -0.36554 - 0.29968j plane = ComplexPlane((-3, 3), (-2, 2)) plane.scale(50) plane.shift(j_point - plane.n2p(j_value)) fractal = JuliaFractal(plane) fractal.set_c(-0.5 + 0.5j) self.add(fractal, plane) j_dot = Dot(color=YELLOW, radius=0.05) j_dot.move_to(j_point) j_label = Text("Julia set point", color=YELLOW) j_label.next_to(j_dot, UP, buff=1.0).shift(LEFT) j_arrow = Line(j_label.get_bottom(), j_dot.get_center(), buff=0.1) j_arrow.set_stroke(width=3) j_arrow.set_color(YELLOW) surrounding_dots = VGroup(*( Dot(radius=0.05).move_to(j_dot.get_center() + buff * vect) for n, buff in [(6, 0.2), (12, 0.4)] for vect in compass_directions(n) )) surrounding_dots.set_color(GREY_B) # for dot in surrounding_dots: # dot.shift(0.1 * (random.random() - 0.5)) dots_label = Text("Immediate neighbors") dots_label.next_to(surrounding_dots, DOWN) dots_label.set_color(GREY_A) sublabel = Text("drift far away") sublabel.set_color(GREY_A) sublabel.next_to(dots_label, DOWN) fa = sublabel.get_part_by_text("far away") strike = Line(LEFT, RIGHT) strike.set_stroke(RED, 10) strike.replace(fa, 0) new_words = Text("everywhere!") new_words.next_to(fa, DOWN) new_words.set_color(RED) all_words = VGroup(j_label, dots_label, sublabel, new_words) all_words.set_stroke(BLACK, 5, background=True) arrows = VGroup() for dot in surrounding_dots[-12:]: point = dot.get_center() vect = 0.6 * normalize(point - j_dot.get_center()) arrows.add(Arrow(point, point + vect, buff=0.1)) arrows.set_stroke(RED) self.add(j_dot) self.add(surrounding_dots) self.add(j_label, j_arrow) self.add(dots_label) frame = self.camera.frame frame.save_state() frame.replace(plane) self.play(Restore(frame, run_time=5)) self.wait() self.play(FadeIn(sublabel, lag_ratio=0.1)) self.wait() self.play( ShowCreation(strike), FadeIn(new_words, shift=0.25 * DOWN) ) self.add(arrows, all_words, strike) self.play(LaggedStartMap(ShowCreation, arrows)) self.wait() class SimulationOfTinyDisk(RepeatedNewton): coefs = [1, 1, 0, 1] plane_config = { "x_range": (-4, 4), "y_range": (-2, 2), "height": 12, "width": 24, } colors = ROOT_COLORS_DEEP[::2] n_steps = 20 def construct(self): frame = self.camera.frame frame.save_state() def get_height_ratio(): return frame.get_height() / FRAME_HEIGHT self.add_plane() self.add_true_roots() self.add_labels() self.add_fractal_background() fractal = self.fractal julia_set = self.fractal_boundary fractal.set_n_steps(40) julia_set.set_n_steps(40) fractal.set_opacity(0.3) julia_set.set_opacity(1) julia_set.add_updater(lambda m: m.set_julia_highlight( get_height_ratio() * 1e-3 )) julia_set.set_opacity(0.5) # Generate dots point = [1.10049904, 1.38962415, 0.] target_height = 0.0006 cluster_radius = target_height / 50 dots = self.dots = DotCloud() n_radii = 200 dots.set_points([ [cluster_radius * r * math.cos(theta), cluster_radius * r * math.sin(theta), 0] for r in np.linspace(1, 0, n_radii) for theta in np.linspace(0, TAU, int(r * 20)) + random.random() * TAU ]) dots.set_height(0.3) dots.set_gloss(0.5) dots.set_shadow(0.5) dots.set_color(GREY_A) dots.move_to(point) dots.add_updater(lambda m: m.set_radius(0.05 * get_height_ratio())) self.play( frame.animate.set_height(target_height).move_to(point), run_time=6, rate_func=lambda a: smooth(a**0.5), ) self.play(ShowCreation(dots)) self.wait() self.play(Restore(frame, run_time=6, rate_func=lambda a: smooth(a**3))) fractal.set_n_steps(12) julia_set.set_n_steps(12) self.run_iterations() class SimulationAnnotations(Scene): def construct(self): dots = self.dots = DotCloud() n_radii = 200 cluster_radius = 0.5 dots.set_points([ [cluster_radius * r * math.cos(theta), cluster_radius * r * math.sin(theta), 0] for r in np.linspace(1, 0, n_radii) for theta in np.linspace(0, TAU, int(r * 20)) + random.random() * TAU ]) n_points_label = OldTexText("$\\sim 2{,}000$ points") n_points_label.next_to(dots, UP) brace = Brace( # Line(dots.get_bottom(), dots.get_corner(DR)), Line(dots.get_center(), dots.get_right()), DOWN, buff=0 ) brace_tex = OldTex("\\text{Radius } \\approx 1 / 1{,}000{,}000") brace_tex.next_to(dots, DOWN) group = VGroup(n_points_label, brace, brace_tex) group.set_stroke(BLACK, 5, background=True) self.play(Write(n_points_label)) self.play( GrowFromCenter(brace), FadeIn(brace_tex, DOWN) ) self.wait() self.play(FadeOut(group)) class LattesExample(TeacherStudentsScene): def construct(self): example = VGroup( OldTexText("Lattè's example: "), OldTex(r"L(z)=\frac{\left(z^{2}+1\right)^{2}}{4 z\left(z^{2}-1\right)}"), ) example.arrange(RIGHT) example[0].shift(SMALL_BUFF * DOWN) example.move_to(self.hold_up_spot, DOWN) example.set_x(0) j_fact = OldTexText("Julia set of $L(z)$ is all of $\\mathds{C}$") j_fact.move_to(example) subwords = OldTexText("(and the point at $\\infty$)", font_size=36) subwords.set_fill(GREY_A) subwords.next_to(j_fact, DOWN) self.play( self.teacher.change("raise_right_hand", 3 * UR), self.change_students( "pondering", "happy", "tease", look_at=3 * UR ) ) self.wait(3) self.play( self.teacher.change("sassy", example), Write(example) ) self.play_student_changes( "pondering", "pondering", "pondering", look_at=example, ) self.play( example.animate.to_edge(UP), FadeIn(j_fact), self.change_students( "erm", "erm", "erm", look_at=j_fact, ), self.teacher.change("raise_right_hand", j_fact) ) self.play(FadeIn(subwords)) self.wait(3) class JFunctionMention(Scene): def construct(self): image = ImageMobject("j_invariant") image.set_height(5) name = OldTexText("Klein's $j$ function") name.next_to(image, UP) words = Text("A whole story...") words.next_to(image, RIGHT) self.play( FadeIn(image), Write(name) ) self.wait() self.play(Write(words)) self.wait() class LinksBelow(TeacherStudentsScene): def construct(self): self.pi_creatures.flip().flip() self.teacher_says("Links below") self.play_student_changes( "pondering", "thinking", "pondering", look_at=FRAME_HEIGHT * DOWN, ) self.wait(2) self.play(self.teacher.change("happy")) self.wait(4) class MoreAmbientChaos(TwoToMillionPoints): def construct(self): plane = ComplexPlane((-2, 2), (-2, 2)) plane.set_height(7) self.add(plane) point = self.get_julia_set_points(plane, n_points=1, n_steps=1000)[0] epsilon = 1e-6 dots = DotCloud([ point + epsilon * rotate_vector(RIGHT, random.random() * TAU) for x in range(10) ]) dots.set_gloss(0.5) dots.set_shadow(0.5) dots.set_radius(0.075) dots.set_color(YELLOW) def func(p): z = plane.p2n(p) return plane.n2p(z**2 + self.c) n_steps = 100 for n in range(n_steps): points = dots.get_points() values = list(map(plane.p2n, points)) new_values = np.array(list(map(lambda z: z**2 + self.c, values))) new_points = list(map(plane.n2p, new_values)) nn_points = [] for p in new_points: if p[0] < plane.get_left()[0]: p[0] += 2 * (plane.get_left()[0] - p[0]) if p[0] > plane.get_right()[0]: p[0] -= 2 * (p[0] - plane.get_right()[0]) if p[1] < plane.get_bottom()[1]: p[1] += 2 * (plane.get_bottom()[1] - p[1]) if p[1] > plane.get_top()[1]: p[1] -= 2 * (p[1] - plane.get_top()[1]) nn_points.append(p) new_points = nn_points lines = VGroup(*( Line(p1, p2) for p1, p2 in zip(points, new_points) )) lines.set_stroke(WHITE, 1) self.play( dots.animate.set_points(new_points), ShowCreation(lines, lag_ratio=0), ) self.add(lines[0].copy().set_opacity(0.25)) for line in lines: line.rotate(PI) self.play(FadeOut(lines)) class HighlightedJulia(IntroNewtonFractal): coefs = [-1.0, 0.0, 0.0, 1.0, 0.0, 1.0] def construct(self): # self.init_fractal(root_colors=ROOT_COLORS_DEEP[0::2]) self.init_fractal(root_colors=ROOT_COLORS_DEEP) fractal = self.fractal def get_height_ratio(): return self.camera.frame.get_height() / FRAME_HEIGHT fractal.set_colors(5 * [WHITE]) fractal.add_updater(lambda m: m.set_julia_highlight(get_height_ratio() * 1e-3)) fractal.set_n_steps(50) # self.play( # fractal.animate.set_julia_highlight(1e-3), # run_time=5 # ) # self.embed() class MetaFractal(IntroNewtonFractal): fixed_roots = [-1, 1] z0 = complex(0.5, 0) n_steps = 200 def construct(self): colors = ROOT_COLORS_DEEP[0::2] self.plane_config["faded_line_ratio"] = 3 plane = self.get_plane() root_dots = self.root_dots = VGroup(*( Dot(plane.n2p(root), color=color) for root, color in zip(self.fixed_roots, colors) )) root_dots.set_stroke(BLACK, 3) fractal = MetaNewtonFractal( plane, fixed_roots=self.fixed_roots, colors=colors, n_steps=self.n_steps, # z0=self.z0, ) fractal.add_updater(lambda f: f.set_fixed_roots([ plane.p2n(dot.get_center()) for dot in root_dots ])) self.add(fractal, plane) self.add(root_dots) point1 = np.array([1.62070862, 1.68700851, 0.]) point2 = np.array([0.81263967, 2.84042313, 0.]) height1 = 0.083 height2 = 0.035 frame = self.camera.frame frame.save_state() frame.generate_target() frame.target.move_to(point1) frame.target.set_height(height1) fractal.set_saturation_factor(2) plane.remove(plane.coordinate_labels) self.play( MoveToTarget(frame), run_time=8, rate_func=bezier([0, 0, 1, 1]) ) self.play( fractal.animate.set_saturation_factor(4), run_time=3 ) self.play( UpdateFromAlphaFunc( frame, lambda m, a: m.set_height( interpolate( interpolate(height1, 2, a), interpolate(2, height2, a), a, ), ).move_to( interpolate(point1, point2, a) ) ), run_time=10 ) self.wait(2) self.play( Restore(frame), fractal.animate.set_saturation_factor(0), run_time=7 ) self.wait() class Part1EndScroll(PatreonEndScreen): CONFIG = { # "title_text": "", "scroll_time": 30, # "show_pis": False, } class AmbientJulia(Scene): def construct(self): plane = ComplexPlane( (-4, 4), (-2, 2), background_line_style={ "stroke_color": GREY_A, "stroke_width": 1, } ) plane.axes.set_stroke(width=1, opacity=0.5) plane.set_height(14) fractal = JuliaFractal(plane) fractal.set_n_steps(100) R = 0.25 cardioid = ParametricCurve( lambda t: plane.c2p( 2 * R * math.cos(t) - R * math.cos(2 * t), 2 * R * math.sin(t) - R * math.sin(2 * t), ), t_range=(0, TAU) ) t_tracker = ValueTracker(0) get_t = t_tracker.get_value fractal.add_updater(lambda m: m.set_c( plane.p2n(cardioid.pfp(get_t())) )) self.add(fractal, plane) self.play( t_tracker.animate.set_value(1), rate_func=linear, run_time=300 )
from manim_imports_ext import * from manimlib.logger import log import urllib.request WINNERS = [ ("That weird light at the bottom of a mug — ENVELOPES", "Paralogical", "fJWnA4j0_ho"), ("Hiding Images in Plain Sight: The Physics Of Magic Windows", "Matt Ferraro", "CatInCausticImage"), ("The Beauty of Bézier Curves", "Freya Holmér", "aVwxzDHniEw"), ("What Is The Most Complicated Lock Pattern?", "Dr. Zye", "PKjbBQ0PBCQ"), ("Pick's theorem: The wrong, amazing proof", "spacematt", "uh-yRNqLpOg"), ] HONORABLE_MENTIONS = [ ("Dirac's belt trick, Topology, and Spin ½ particles", "Noah Miller", "ACZC_XEyg9U"), ("Galois-Free Guarantee! | The Insolubility of the Quintic", "Carl Turner", "BSHv9Elk1MU"), ("The Two Envelope Problem - a Mystifying Probability Paradox", "Formant", "_NGPncypY68"), ("The Math Behind Font Rasterization | How it Works", "GamesWithGabe", "LaYPoMPRSlk"), ("What is a Spinor?", "Mia Hughes", "SpinorArticle"), ("Understanding e", "Veli Peltola", "e_comic"), ("Ancient Multiplication Trick", "Inigo Quilez", "CsMrHzp850M"), ("对称多项式基本定理自我探究", "凡人忆拾", "FiveIntsTheorem"), ("Lehmer Factor Stencils", "Proof of Concept", "QzohwKT6TNA"), ("What is the limit of a sequence of graphs?", "Spectral Collective", "7Gj9BH4IZ-4"), ("Steiner's Porism: proving a cool animation", "Joseph Newton", "fKAyaP8IzlE"), ("Wait, Probabilities can be Negative?!", "Steven G", "std9EBbtOC0"), ("This random graph fact will blow your mind", "Snarky Math", "3QjZ31lj974"), ("Why is pi here? Estimating π by Buffon's n̶e̶e̶d̶l̶e noodle!", "Mihai Nica", "e-RUyCs9B08"), ("Introduction to Waves", "Rob Schlub", "IntroToWaves"), ("ComplexFunctions", "Treena", "Treena"), ("I spent an entire summer to find this spiral", "Sort of School", "n-e9C8g5x68"), ("HACKENBUSH: a window to a new world of math", "Owen Maitzen", "ZYj4NkeGPdM"), ("The Tale of the Lights Puzzle", "Throw Math At It", "9aZsABF-Vj4"), ("The BEST Way to Find a Random Point in a Circle", "nubDotDev", "4y_nmpv-9lI"), ("Secrets of the Fibonacci Tiles", "Eric Severson", "Ct7oltmdJrM"), ("The Tale of Three Triangles", "Robin Truax", "5nuYD2M2AX8"), ("How Karatsuba's algorithm gave us new ways to multiply", "Nemean", "cCKOl5li6YM"), ("Can you change a sum by rearranging its numbers? --- The Riemann Series Theorem", "Morphocular", "U0w0f0PDdPA"), ("Neural manifolds - The Geometry of Behaviour", "Artem Kirsanov", "QHj9uVmwA_0"), ] def get_youtube_slugs(file="some1_video_urls.txt"): full_path = os.path.join(get_directories()["data"], file) slugs = [] prefix = "https://youtu.be/" with open(full_path, "r") as fp: for url in fp.readlines(): if not url.startswith(prefix): continue slugs.append(url[len(prefix):-1]) return remove_list_redundancies(slugs) def save_thumbnail_locally(slug, rewrite=False): file = yt_slug_to_image_file(slug) if os.path.exists(file) and not rewrite: return file suffixes = ["maxresdefault", "hqdefault", "mqdefault", "sddefault"] urls = [ *( f"https://img.youtube.com/vi/{slug}/{suffix}.jpg" for suffix in suffixes ), *( f"https://i.ytimg.com/vi/{slug}/{suffix}.jpg" for suffix in suffixes ) ] for url in urls: try: urllib.request.urlretrieve(url, file) return file except urllib.request.HTTPError: pass log.warning(f"Thumbnail not found: {slug}") def save_thumbnails_locally(slugs): map(save_thumbnail_locally, slugs) def yt_slug_to_image_file(slug): return os.path.join( get_raster_image_dir(), "some1_thumbnails", slug + ".jpg" ) class Introduction(TeacherStudentsScene): def construct(self): # Kill background self.clear() morty = self.teacher # Add title this_summer = Text("This Summer", font_size=72) this = this_summer.get_part_by_text("This") summer = this_summer.get_part_by_text("Summer") this_summer.to_edge(UP) some = Text("Summer of Math Exposition", font_size=72) some.to_edge(UP) some.shift(0.7 * RIGHT) this_summer.generate_target() this_summer.target.shift(some[0].get_left() - summer[0].get_left()) logos = Group( ImageMobject("Leios"), Logo(), ) for logo in logos: logo.set_height(1.0) logos.arrange(RIGHT, buff=2) logos.next_to(this_summer.target, RIGHT, buff=1.5) james_name = Text("James Schloss") james_name.set_color(GREY_A) james_name.next_to(logos[0], DOWN) logos.generate_target() logos.target.set_height(0.5) logos.target.arrange(RIGHT, buff=0.25) logos.target.replace(this_summer.target[:4], 0) self.add(this) self.wait(0.3) self.add(summer) self.wait(0.5) self.play( MoveToTarget(this_summer), FadeIn(james_name, lag_ratio=0.1), FadeIn(logos[0], LEFT), ) self.play( Write(logos[1], lag_ratio=0.01, stroke_width=0.05, run_time=1), Animation(logos[1][-1].copy(), remover=True), FadeOut(james_name), ) self.wait() self.play( FadeIn(some[len("Summer"):], lag_ratio=0.1), FadeOut(this), MoveToTarget(logos, path_arc=-PI / 3, run_time=2) ) self.remove(this_summer) self.add(some) self.wait() title = Group(logos, some) # Mention blog post url = VGroup( Text("Full details: "), Text("https://3b1b.co/some1-results") ) url[1].set_color(BLUE_C) url.arrange(RIGHT) url[0].shift(0.05 * UP) url.to_edge(UP) self.play( FadeOut(title, UP), FadeIn(url[0]), ShowIncreasingSubsets(url[1], rate_func=linear, run_time=2) ) self.wait() # Key points dots = Dot().get_grid(3, 1) dots.arrange(DOWN, buff=1.5) dots.align_to(url, LEFT) dots.set_y(-0.5) points = VGroup( Text("Extremely open-ended"), Text("Promise to feature 4 to 5 winners"), Text("Brilliant offered $5k in cash prizes"), ) colors = [GREEN_A, GREEN_B, GREEN_C] for dot, point, color in zip(dots, points, colors): point.next_to(dot, RIGHT) point.set_color(color) self.play( LaggedStartMap( FadeInFromPoint, dots, lambda m: (m, url.get_bottom()), ), ) self.wait() for point in points: self.play(Write(point)) if point is points[1]: self.play( morty.change("hooray").look(ORIGIN), FadeOut(BackgroundRectangle(morty, buff=0.25, fill_opacity=1)) ) self.play(Blink(morty)) self.play(morty.change("tease", points[2])) else: self.wait() # Discuss winner winner_word = OldTexText("``Winners''", font_size=72)[0] winner_word.move_to(self.hold_up_spot, DOWN) pre_winner_word = points[1].get_part_by_text("winner").copy() self.students.flip().flip() self.add(self.background, pre_winner_word, *self.pi_creatures) self.play( LaggedStartMap(FadeOut, VGroup( url, dots, points, )), FadeIn(self.background), morty.change("hesitant", winner_word), FadeTransform(pre_winner_word, winner_word[2:9]), LaggedStartMap(FadeIn, self.students), ) self.play( Write(winner_word[:2]), Write(winner_word[-2:]), self.change_students("sassy", "raise_right_hand", "raise_left_hand"), ) self.wait(4) # Spirit of the event (start at 25) salt = Text("Take with a grain of salt") salt.to_edge(UP) strange = Text("(what a strange phrase...)", font_size=20) strange.set_color(GREY_B) strange.next_to(salt, RIGHT) arrow = Arrow(salt, winner_word) self.play( FadeIn(salt, lag_ratio=0.1), ShowCreation(arrow), self.change_students( "pondering", "pondering", "erm", look_at=salt, ) ) self.play( Blink(self.students[2]), FadeIn(strange, lag_ratio=0.1), ) self.play(FadeOut(strange)) self.wait() spirit = Text("The spirit of the event") spirit.to_edge(UP) bubble = ThoughtBubble(height=3, width=3) bubble.pin_to(self.students[0]) bubble.shift(SMALL_BUFF * UR) bubble.add_content(OldTex( r"|fg|_1 \leq |f|_p |g|_q", tex_to_color_map={ "f": GREEN, "g": TEAL, } )) bubble.add(bubble.content) arrow.target = Arrow(spirit, bubble) video = VideoIcon() video.set_height(0.7) video.next_to(self.students, UP, MED_LARGE_BUFF).to_edge(LEFT) video.set_color(GREY_C) video.set_gloss(1) self.play( FadeOut(salt, 0.5 * UP), FadeIn(spirit, 0.5 * UP), ) self.play( MoveToTarget(arrow), FadeIn(bubble), self.students[0].change("thinking", bubble), self.students[1].change("pondering", bubble), self.students[2].change("pondering", bubble), self.teacher.change("happy", bubble), winner_word.animate.scale(0.3).set_opacity(0.5).to_corner(UR), ) self.play( self.students[0].change("raise_left_hand", video), FadeIn(video, 0.5 * UP), ) self.wait() bubble_copies = bubble.replicate(2).scale(0.7) for bc, student in zip(bubble_copies, self.students[1:]): bc.move_to(student.get_corner(UR), DL) self.play( LaggedStart(*( TransformFromCopy(bubble, bc) for bc in bubble_copies ), lag_ratio=0.5), LaggedStart(*( student.change("thinking", UR) for student in self.students[1:] ), lag_ratio=0.5), run_time=2, ) self.wait(3) class ProsConsOfContext(Scene): def construct(self): title = Text("Framing as a contest", font_size=60) title.to_edge(UP) h_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) h_line.next_to(title, DOWN) v_line = Line(h_line.get_center(), FRAME_HEIGHT * DOWN / 2) pro_label = Text("Pros", font_size=60) pro_label.set_color(GREEN) pro_label.next_to(h_line, DOWN) pro_label.set_x(-FRAME_WIDTH / 4) con_label = Text("Cons", font_size=60) con_label.set_color(RED) con_label.next_to(h_line, DOWN) con_label.set_x(FRAME_WIDTH / 4) self.play( LaggedStart( ShowCreation(h_line), ShowCreation(v_line), lag_ratio=0.5, ), LaggedStart( FadeIn(title, 0.25 * UP), FadeIn(pro_label), FadeIn(con_label), lag_ratio=0.5, ) ) self.wait() pros = VGroup( Text("Clear deadline"), Text("Extra push for quality"), ) pros.set_color(GREEN_A) pros.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) pros.next_to(pro_label, DOWN, LARGE_BUFF) con = Text("Suggests that\nsuccess = winning") con.set_color(RED_B) con.match_x(con_label) con.align_to(pros[0], UP) for words in (*pros, con): dot = Dot() dot.next_to(words[0], LEFT) words.add_to_back(dot) self.play(Write(words, run_time=2)) self.wait() self.embed() class FiltrationProcess(Scene): def construct(self): total = OldTexText("$>1{,}200(!)$ submissions") hundred = OldTexText("$\\sim 100$") hundred.next_to(total, RIGHT, buff=4) arrow = Arrow(total, hundred, stroke_width=5) VGroup(total, arrow, hundred).center().to_edge(UP) peer_words = Text("Peer review process", font_size=36) peer_words.set_color(BLUE) peer_words.next_to(arrow, DOWN, buff=SMALL_BUFF) peer_subwords = OldTexText( "(actually quite interesting\\\\see the blog post)", font_size=24, fill_color=GREY_B, ) peer_subwords.next_to(peer_words, DOWN, MED_SMALL_BUFF) self.play(FadeIn(total, lag_ratio=0.1)) self.wait() self.play( ShowCreation(arrow), FadeIn(peer_words, lag_ratio=0.1) ) self.play( FadeIn(hundred), FadeIn(peer_subwords, 0.25 * DOWN) ) self.wait() # Guest judges guest_words = Text("Guest judges:") guest_words.next_to(peer_subwords, DOWN, buff=LARGE_BUFF) guest_words.add(Underline(guest_words)) guest_words.to_edge(RIGHT, buff=1.5) guests = VGroup( Text("Alex Kontorovich"), Text("Henry Reich"), Text("Nicky Case"), Text("Tai-Danae Bradley"), Text("Bukard Polster"), Text("Mithuna Yoganathan"), Text("Steven Strogatz"), ) guests.scale(0.75) guests.set_color(GREY_B) guests.arrange(DOWN, aligned_edge=LEFT) guests.next_to(guest_words, DOWN, aligned_edge=LEFT) self.play( FadeIn(guest_words), LaggedStartMap( FadeIn, guests, shift=0.25 * DOWN, lag_ratio=0.5, run_time=4, ) ) self.wait() class AllVideosOrdered(Scene): slug_file = "some1_video_urls_ordered.txt" grid_size = 3 time_per_image = 0.2 def construct(self): n = self.grid_size N = n**2 time_per_image = self.time_per_image buffer_size = 2 * N slugs = get_youtube_slugs(self.slug_file) random.shuffle(slugs) log.info(f"Number of slugs: {len(slugs)}") image_slots = ScreenRectangle().get_grid(n, n, buff=0.2) image_slots.set_height(FRAME_HEIGHT) image_slots.set_stroke(WHITE, 1) images = buffer_size * [None] self.add(image_slots) def update_image(image, dt): image.time += dt image.set_opacity(clip(5 * image.time / (N * time_per_image), 0, 1)) k = 0 for slug in ProgressDisplay(slugs): slot = image_slots[k % N] save_thumbnail_locally(slug) file = yt_slug_to_image_file(slug) if not os.path.exists(file): continue if k > buffer_size: old_image = images[k % buffer_size] self.camera.release_texture(old_image.path) self.remove(old_image) image = ImageMobject(file) image.replace(slot, stretch=True) images[k % buffer_size] = image image.time = 0 image.add_updater(update_image) self.add(image) self.wait(time_per_image) k += 1 # Hack to keep OpenGL from tracking too many textures. # Should be fixed more intelligently in Camera if k % (buffer_size) == 0: self.camera.n_textures = buffer_size + 2 class RevealingTiles(Scene): def construct(self): self.five_winners() self.honorable_mentions() def five_winners(self): # title = Text("SoME1 Winners", font_size=72) title = OldTexText("Summer of Math Exposition\\\\", "Winners", font_size=72) title[1].scale(2, about_edge=UP) title[1].set_color(YELLOW) title.to_edge(UP, buff=0.2) # # title.to_edge(UP) subtitle = Text("(in no particular order)", font_size=36) subtitle.next_to(title, DOWN, buff=0.2) subtitle.set_color(GREY_B) self.add(title) tiles = self.get_mystery_tile().replicate(5) colors = color_gradient([BLUE_B, BLUE_D], 5) for tile, color in zip(tiles, colors): # tile[0].set_stroke(color, 1) tile[0].set_stroke(YELLOW, 2) tiles.set_height(2) tiles.arrange_in_grid(2, 3, buff=MED_SMALL_BUFF) tiles[3:].match_x(tiles[:3]) tiles.set_width(FRAME_WIDTH - 2) # tiles.to_edge(DOWN, buff=1) tiles.to_edge(DOWN, buff=0.25) reorder = list(range(5)) random.seed(1) random.shuffle(reorder) # Animations self.play( Write(title), LaggedStartMap(GrowFromCenter, tiles, lag_ratio=0.15) ) self.wait() self.play( FadeIn(subtitle, lag_ratio=0.2), LaggedStart(*( ApplyMethod( tile.move_to, tiles[reorder[i]], path_arc=PI / 2 ) for i, tile in enumerate(tiles) ), lag_ratio=0.25, run_time=2) ) self.wait() # for tile, triple in zip(tiles, WINNERS): self.reveal_tile(tile, *triple) self.title = title self.subtitle = subtitle self.tiles = tiles def honorable_mentions(self): tiles = self.tiles new_title = OldTexText("Others you'll enjoy", font_size=72) new_title.to_edge(UP, buff=MED_SMALL_BUFF) tiles.generate_target() new_tile = self.get_mystery_tile() new_tile.replace(tiles[0]) new_tiles = Group( *tiles.target, *new_tile.replicate(len(HONORABLE_MENTIONS)) ) new_tiles.arrange_in_grid(5, 6, buff=0.25) new_tiles.set_height(6.5) new_tiles.next_to(new_title, DOWN) self.play( FadeTransform(self.title, new_title), FadeOut(self.subtitle), MoveToTarget(tiles), LaggedStartMap( FadeInFromPoint, new_tiles[5:], lambda m: (m, ORIGIN), lag_ratio=0.1, run_time=5, ) ) self.wait() reorder_tail = list(range(5, len(new_tiles))) random.shuffle(reorder_tail) reorder = [*range(5), *reorder_tail] centers = [nt.get_center().copy() for nt in new_tiles] for i, tile in enumerate(new_tiles): tile.move_to(centers[reorder[i]]) for tile, triple in zip(new_tiles[5:], HONORABLE_MENTIONS): self.reveal_tile(tile, *triple) def reveal_tile(self, tile, title, author, image_name): # Flip tile try: image_path = get_full_raster_image_path(image_name) except IOError: # Try to redownload best YT slug save_thumbnail_locally(image_name) image_path = yt_slug_to_image_file(image_name) # Trim to be 16x9 arr = np.array(Image.open(image_path)) h, w, _ = arr.shape nh = w * 9 // 16 if nh < h: trimmed_arr = arr[(h - nh) // 2:(h - nh) // 2 + nh, :, :] Image.fromarray(trimmed_arr).save(image_path) image = ImageMobject(image_path) image.rotate(PI, RIGHT) image.replace(tile, dim_to_match=1) image.set_max_width(tile.get_width()) self.play( Rotate(image, PI, RIGHT), Rotate(tile, PI, RIGHT), UpdateFromAlphaFunc( tile, lambda m, a: m.set_opacity(1 if a < 0.5 else 0), ), UpdateFromAlphaFunc( image, lambda m, a: m.set_opacity(0 if a < 0.5 else 1), ), ) tile.remove(tile[1]) tile[0].set_fill(BLACK, 1) tile.add(image) # Expand full_rect = FullScreenRectangle() full_rect.set_fill(GREY_E) title = Text(title) title.set_max_width(FRAME_WIDTH - 1) title.to_edge(UP, buff=MED_SMALL_BUFF) byline = Text(f"by {author}", font_size=30) byline.set_color(GREY_B) byline.next_to(title, DOWN, buff=0.2) tile.save_state() tile.generate_target() tile.target.set_height(6) tile.target.next_to(byline, DOWN) tile.saved_state[0].set_stroke(opacity=1) self.add(full_rect, tile) self.play( FadeIn(full_rect), MoveToTarget(tile, run_time=2), FadeInFromPoint(title, tile.get_top(), run_time=2), ) self.play(FadeIn(byline, 0.25 * DOWN)) self.wait() self.play( Restore(tile), FadeOut(full_rect), FadeOut(title, 0.75 * UP), FadeOut(byline, 1.0 * UP), ) def get_mystery_tile(self): rect = ScreenRectangle(height=1) rect.set_stroke(BLUE_D, 1) rect.set_fill(GREY_D, 1) q_marks = OldTex("???") q_marks.flip().flip() q_marks.set_fill(GREY_A) q_marks.move_to(rect) q_marks.shift(1e-3 * OUT) return Group(rect, q_marks) class AlmostTooGood(TeacherStudentsScene): def construct(self): self.pi_creatures.flip().flip() self.teacher_says( OldTexText("Almost \\emph{too} good"), look_at=self.students[2].eyes, added_anims=[self.change_students("happy", "tease", "hesitant")], ) self.wait(4) class ViewRect(Scene): views = 596 def construct(self): rect = Rectangle(3.5, 1) rect.set_height(0.25) rect.set_stroke(RED, 3) number = Integer(self.views, font_size=96) number.set_fill(RED) number.next_to(rect, DOWN, LARGE_BUFF) number.shift(3 * RIGHT) arrow = Arrow(rect, number) arrow.set_color(RED) self.play( ShowCreation(rect) ) number.set_value(0) self.play( ShowCreation(arrow), # FadeInFromPoint(number, arrow.get_start()) ChangeDecimalToValue(number, self.views, run_time=2), VFadeIn(number), UpdateFromFunc(number, lambda m: m.set_fill(RED)) ) self.wait() class ViewRect700k(ViewRect): views = 795095 class SureSure(TeacherStudentsScene): def construct(self): self.students.flip().flip() self.teacher_says( "The point is \n not the winners", look_at=self.students[2].eyes, bubble_config={"height": 3, "width": 4} ) self.play(PiCreatureSays( self.students[0], "Yeah, yeah, sure\n it isn't...", bubble_config={"height": 2, "width": 3} )) self.play_student_changes("sassy", "angry", "hesitant") self.play(self.teacher.change("guilty")) self.wait(4) class Narrative(Scene): def construct(self): question = Text("What makes a good piece of exposition?", font_size=60) question.to_edge(UP) question.add(Underline(question)) self.add(question) properties = VGroup( Text("Clarity"), Text("Motivation"), Text("Memorability"), Text("Narrative"), ) properties.scale(60 / 48) properties.arrange(DOWN, buff=0.75, aligned_edge=LEFT) properties.next_to(question, DOWN, LARGE_BUFF) properties.set_fill(BLUE) narrative = properties[-1] for prop in properties: dot = Dot() dot.next_to(prop, LEFT) self.play( FadeIn(dot, scale=0.5), FadeIn(prop, lag_ratio=0.1) ) rect = FullScreenFadeRectangle() rect.set_opacity(0.5) self.add(rect, narrative) self.play( FadeIn(rect), FlashAround(narrative, run_time=2, time_width=1), narrative.animate.set_color(YELLOW), ) self.wait() class Traction(Scene): def construct(self): slug_count_pairs = [ ("PKjbBQ0PBCQ", "$\\sim$800,000"), ("ACZC_XEyg9U", "$\\sim$100,000"), ("4y_nmpv-9lI", "$\\sim$140,000"), ("cCKOl5li6YM", "$\\sim$400,000"), ] groups = Group() for slug, count in slug_count_pairs: rect = ScreenRectangle() rect.set_height(3) rect.set_stroke(BLUE, 2) image = ImageMobject(yt_slug_to_image_file(slug)) image.replace(rect, 1) text = OldTexText(f"{count} views") text.next_to(image, DOWN, MED_SMALL_BUFF) groups.add(Group(image, rect, text)) groups.arrange_in_grid(v_buff=MED_LARGE_BUFF, h_buff=LARGE_BUFF) groups.set_height(FRAME_HEIGHT - 1) for elem in groups: self.play( FadeIn(elem[:2]), FadeIn(elem[-1], 0.5 * DOWN, scale=2) ) self.wait() class EndScreen(PatreonEndScreen): pass
from manim_imports_ext import * import scipy.spatial # Helpers def project_to_xy_plane(p1, p2): """ Draw a line from source to p1 to p2. Where does it intersect the xy plane? """ x1, y1, z1 = p1 x2, y2, z2 = p2 if z2 < z1: z2 = z1 + 1e-2 # TODO, bad hack vect = p2 - p1 return p1 - (z2 / vect[2]) * vect def flat_project(point): # return [*point[:2], 0] return [*point[:2], 0.05 * point[2]] # TODO def get_pre_shadow(mobject, opacity): result = mobject.deepcopy() if isinstance(result, Group) and all((isinstance(sm, VMobject) for sm in mobject)): result = VGroup(*result) result.clear_updaters() for sm in result.family_members_with_points(): color = interpolate_color(sm.get_color(), BLACK, opacity) sm.set_color(color) sm.set_opacity(opacity) if isinstance(sm, VMobject): sm.set_stroke( interpolate_color(sm.get_stroke_color(), BLACK, opacity) ) sm.set_gloss(sm.get_gloss() * 0.5) sm.set_shadow(0) sm.set_reflectiveness(0) return result def update_shadow(shadow, mobject, light_source): lp = light_source.get_center() if light_source is not None else None def project(point): if lp is None: return flat_project(point) else: return project_to_xy_plane(lp, point) for sm, mm in zip(shadow.family_members_with_points(), mobject.family_members_with_points()): sm.set_points(np.apply_along_axis(project, 1, mm.get_points())) if isinstance(sm, VMobject) and sm.get_unit_normal()[2] < 0: sm.reverse_points() if isinstance(sm, VMobject): sm.set_fill(opacity=mm.get_fill_opacity()) else: sm.set_opacity(mm.get_opacity()) def get_shadow(mobject, light_source=None, opacity=0.7): shadow = get_pre_shadow(mobject, opacity) shadow.add_updater(lambda s: update_shadow(s, mobject, light_source)) return shadow def get_area(shadow): return 0.5 * sum( get_norm(sm.get_area_vector()) for sm in shadow.get_family() ) def get_convex_hull(mobject): points = mobject.get_all_points() hull = scipy.spatial.ConvexHull(points[:, :2]) return points[hull.vertices] def sort_to_camera(mobject, camera_frame): cl = camera_frame.get_implied_camera_location() mobject.sort(lambda p: -get_norm(p - cl)) return mobject def cube_sdf(point, cube): c = cube.get_center() vect = point - c face_vects = [face.get_center() - c for face in cube] return max(*( abs(np.dot(fv, vect) / np.dot(fv, fv)) for fv in face_vects )) - 1 def is_in_cube(point, cube): return cube_sdf(point, cube) < 0 def get_overline(mob): overline = Underline(mob).next_to(mob, UP, buff=0.05) overline.set_stroke(WHITE, 2) return overline def get_key_result(solid_name, color=BLUE): eq = OldTex( "\\text{Area}\\big(\\text{Shadow}(\\text{" + solid_name + "})\\big)", "=", "\\frac{1}{2}", "{c}", "\\cdot", "(\\text{Surface area})", tex_to_color_map={ "\\text{Shadow}": GREY_B, f"\\text{{{solid_name}}}": color, "\\text{Solid}": BLUE, "{c}": RED, } ) eq.add_to_back(get_overline(eq[:5])) return eq def get_surface_area(solid): return sum(get_norm(f.get_area_vector()) for f in solid) # Scenes class ShadowScene(ThreeDScene): object_center = [0, 0, 3] frame_center = [0, 0, 2] area_label_center = [0, -1.5, 0] surface_area = 6.0 num_reorientations = 10 plane_dims = (20, 20) plane_style = { "stroke_width": 0, "fill_color": GREY_A, "fill_opacity": 0.5, "gloss": 0.5, "shadow": 0.2, } limited_plane_extension = 0 object_style = { "stroke_color": WHITE, "stroke_width": 0.5, "fill_color": BLUE_E, "fill_opacity": 0.7, "reflectiveness": 0.3, "gloss": 0.1, "shadow": 0.5, } inf_light = False glow_radius = 10 glow_factor = 10 area_label_center = [-2, -1, 0] unit_size = 2 def setup(self): self.camera.frame.reorient(-30, 75) self.camera.frame.move_to(self.frame_center) self.add_plane() self.add_solid() self.add_shadow() self.setup_light_source() def add_plane(self): width, height = self.plane_dims grid = NumberPlane( x_range=(-width // 2, width // 2, 2), y_range=(-height // 2, height // 2, 2), background_line_style={ "stroke_color": GREY_B, "stroke_width": 1, }, faded_line_ratio=4, ) grid.shift(-grid.get_origin()) grid.set_width(width) grid.axes.match_style(grid.background_lines) grid.set_flat_stroke(True) grid.insert_n_curves(3) plane = Rectangle() plane.replace(grid, stretch=True) plane.set_style(**self.plane_style) plane.set_stroke(width=0) if self.limited_plane_extension > 0: plane.set_height(height // 2 + self.limited_plane_extension, about_edge=UP, stretch=True) self.plane = plane plane.add(grid) self.add(plane) def add_solid(self): self.solid = self.get_solid() self.solid.move_to(self.object_center) self.add(self.solid) def get_solid(self): cube = VCube() cube.deactivate_depth_test() cube.set_height(2) cube.set_style(**self.object_style) # Wrap in group so that strokes and fills # are rendered in separate passes cube = self.cube = Group(*cube) cube.add_updater(lambda m: self.sort_to_camera(m)) return cube def add_shadow(self): light_source = None if self.inf_light else self.camera.light_source shadow = get_shadow(self.solid, light_source) self.add(shadow, self.solid) self.shadow = shadow def setup_light_source(self): self.light = self.camera.light_source if self.inf_light: self.light.move_to(100 * OUT) else: glow = self.glow = TrueDot( radius=self.glow_radius, glow_factor=self.glow_factor, ) glow.set_color(interpolate_color(YELLOW, WHITE, 0.5)) glow.add_updater(lambda m: m.move_to(self.light)) self.add(glow) def sort_to_camera(self, mobject): return sort_to_camera(mobject, self.camera.frame) def get_shadow_area_label(self): text = OldTexText("Shadow area: ") decimal = DecimalNumber(100) label = VGroup(text, decimal) label.arrange(RIGHT) label.move_to(self.area_label_center - decimal.get_center()) label.fix_in_frame() label.set_backstroke() decimal.add_updater(lambda d: d.set_value( get_area(self.shadow) / (self.unit_size**2) ).set_backstroke()) return label def begin_ambient_rotation(self, mobject, speed=0.2, about_point=None, initial_axis=[1, 1, 1]): mobject.rot_axis = np.array(initial_axis) def update_mob(mob, dt): mob.rotate(speed * dt, mob.rot_axis, about_point=about_point) mob.rot_axis = rotate_vector(mob.rot_axis, speed * dt, OUT) return mob mobject.add_updater(update_mob) return mobject def get_shadow_outline(self, stroke_width=1): outline = VMobject() outline.set_stroke(WHITE, stroke_width) outline.add_updater(lambda m: m.set_points_as_corners(get_convex_hull(self.shadow)).close_path()) return outline def get_light_lines(self, outline=None, n_lines=100, only_vertices=False): if outline is None: outline = self.get_shadow_outline() def update_lines(lines): lp = self.light.get_center() if only_vertices: points = outline.get_vertices() else: points = [outline.pfp(a) for a in np.linspace(0, 1, n_lines)] for line, point in zip(lines, points): if self.inf_light: line.set_points_as_corners([point + 10 * OUT, point]) else: line.set_points_as_corners([lp, point]) line = Line(IN, OUT) light_lines = line.replicate(n_lines) light_lines.set_stroke(YELLOW, 0.5, 0.1) light_lines.add_updater(update_lines) return light_lines def random_toss(self, mobject=None, angle=TAU, about_point=None, meta_speed=5, **kwargs): if mobject is None: mobject = self.solid mobject.rot_axis = normalize(np.random.random(3)) mobject.rot_time = 0 def update(mob, time): dt = time - mob.rot_time mob.rot_time = time mob.rot_axis = rotate_vector(mob.rot_axis, meta_speed * dt, normalize(np.random.random(3))) mob.rotate(angle * dt, mob.rot_axis, about_point=about_point) self.play( UpdateFromAlphaFunc(mobject, update), **kwargs ) def randomly_reorient(self, solid=None, about_point=None): solid = self.solid if solid is None else solid solid.rotate( random.uniform(0, TAU), axis=normalize(np.random.uniform(-1, 1, 3)), about_point=about_point, ) return solid def init_frame_rotation(self, factor=0.0025, max_speed=0.01): frame = self.camera.frame frame.d_theta = 0 def update_frame(frame, dt): frame.d_theta += -factor * frame.get_theta() frame.increment_theta(clip( factor * frame.d_theta, -max_speed * dt, max_speed * dt )) frame.add_updater(update_frame) return frame class SimpleWriting(Scene): text = "" font = "Better Grade" color = WHITE font_size = 48 def construct(self): words = Text(self.text, font=self.font, font_size=self.font_size) words.set_color(self.color) self.play(Write(words)) self.wait() class AliceName(SimpleWriting): text = "Alice" font_size = 72 class BobName(SimpleWriting): text = "Bob" font = "Kalam" class BobWords(SimpleWriting): font = "Kalam" font_size = 24 words1 = "Embraces calculations" words2 = "Loves specifics" def construct(self): words = VGroup(*( Text(text, font=self.font, font_size=self.font_size) for text in (self.words1, self.words2) )) words.arrange(DOWN) for word in words: self.play(Write(word)) self.wait() class AliceWords(BobWords): font = "Better Grade" words1 = "Procrastinates calculations" words2 = "Seeks generality" font_size = 48 class AskAboutConditions(SimpleWriting): text = "Which properties matter?" class IntroduceShadow(ShadowScene): area_label_center = [-2.5, -2, 0] plane_dims = (28, 20) def construct(self): # Setup light = self.light light.move_to([0, 0, 20]) self.add(light) cube = self.solid cube.scale(0.945) # Hack to make the appropriate area 1 shadow = self.shadow outline = self.get_shadow_outline() frame = self.camera.frame frame.add_updater(lambda f, dt: f.increment_theta(0.01 * dt)) # Ambient rotation area_label = self.get_shadow_area_label() light_lines = self.get_light_lines(outline) # Question question = OldTexText( "Puzzle: Find the average\\\\area of a cube's shadow", font_size=48, ) question.to_corner(UL) question.fix_in_frame() subquestion = Text("(Averaged over all orientations)") subquestion.match_width(question) subquestion.next_to(question, DOWN, MED_LARGE_BUFF) subquestion.set_fill(BLUE_D) subquestion.fix_in_frame() subquestion.set_backstroke() # Introductory animations self.shadow.update() self.play( FadeIn(question, UP), *( LaggedStartMap(DrawBorderThenFill, mob, lag_ratio=0.1, run_time=3) for mob in (cube, shadow) ) ) self.random_toss(run_time=3, angle=TAU) # Change size and orientation outline.update() area_label.update() self.play( FadeIn(area_label), ShowCreation(outline), ) self.play( cube.animate.scale(0.5), run_time=2, rate_func=there_and_back, ) self.random_toss(run_time=2, angle=PI) self.wait() self.begin_ambient_rotation(cube) self.play(FadeIn(subquestion, 0.5 * DOWN)) self.wait(7) # Where is the light? light_comment = Text("Where is the light?") light_comment.set_color(YELLOW) light_comment.to_corner(UR) light_comment.set_backstroke() light_comment.fix_in_frame() cube.clear_updaters() cube.add_updater(lambda m: self.sort_to_camera(cube)) self.play( FadeIn(light_comment, 0.5 * UP), light.animate.next_to(cube, OUT, buff=1.5), run_time=2, ) light_lines.update() self.play( ShowCreation(light_lines, lag_ratio=0.01, run_time=3), ) self.play( light.animate.shift(1.0 * IN), rate_func=there_and_back, run_time=3 ) self.play( light.animate.shift(4 * RIGHT), run_time=5 ) self.play( Rotate(light, PI, about_point=light.get_z() * OUT), run_time=8, ) self.play(light.animate.shift(4 * RIGHT), run_time=5) self.wait() # Light straight above self.play( frame.animate.set_height(12).set_z(4), light.animate.set_z(10), run_time=3, ) self.wait() self.play(light.animate.move_to(75 * OUT), run_time=3) self.wait() self.play( frame.animate.set_height(8).set_z(2), LaggedStart(*map(FadeOut, (question, subquestion, light_comment))), run_time=2 ) # Flat projection verts = np.array([*cube[0].get_vertices(), *cube[5].get_vertices()]) vert_dots = DotCloud(verts) vert_dots.set_glow_factor(0.5) vert_dots.set_color(WHITE) proj_dots = vert_dots.copy() proj_dots.apply_function(flat_project) proj_dots.set_color(GREY_B) vert_proj_lines = VGroup(*( DashedLine(*pair) for pair in zip(verts, proj_dots.get_points()) )) vert_proj_lines.set_stroke(WHITE, 1, 0.5) point = verts[np.argmax(verts[:, 0])] xyz_label = OldTex("(x, y, z)") xy0_label = OldTex("(x, y, 0)") for label in xyz_label, xy0_label: label.rotate(PI / 2, RIGHT) label.set_backstroke() xyz_label.next_to(point, RIGHT) xy0_label.next_to(flat_project(point), RIGHT) vert_dots.save_state() vert_dots.set_glow_factor(5) vert_dots.set_radius(0.5) vert_dots.set_opacity(0) self.play( Restore(vert_dots), Write(xyz_label), ) self.wait() self.play( TransformFromCopy( cube.deepcopy().clear_updaters().set_opacity(0.5), shadow.deepcopy().clear_updaters().set_opacity(0), remover=True ), TransformFromCopy(vert_dots, proj_dots), TransformFromCopy(xyz_label, xy0_label), *map(ShowCreation, vert_proj_lines), ) self.wait(3) self.play(LaggedStart(*map(FadeOut, ( vert_dots, vert_proj_lines, proj_dots, xyz_label, xy0_label )))) # Square projection top_face = cube[np.argmax([f.get_z() for f in cube])] normal_vect = top_face.get_unit_normal() theta = np.arccos(normal_vect[2]) axis = normalize(rotate_vector([*normal_vect[:2], 0], PI / 2, OUT)) self.play(Rotate(cube, -theta, axis)) top_face = cube[np.argmax([f.get_z() for f in cube])] verts = top_face.get_vertices() vect = verts[3] - verts[2] angle = angle_of_vector(vect) self.play(Rotate(cube, -angle, OUT)) self.wait() corner = cube.get_corner(DL + OUT) edge_lines = VGroup( Line(corner, cube.get_corner(DR + OUT)), Line(corner, cube.get_corner(UL + OUT)), Line(corner, cube.get_corner(DL + IN)), ) edge_lines.set_stroke(RED, 2) s_labels = OldTex("s").replicate(3) s_labels.set_color(RED) s_labels.rotate(PI / 2, RIGHT) s_labels.set_stroke(BLACK, 3, background=True) for label, line, vect in zip(s_labels, edge_lines, [OUT, LEFT, LEFT]): label.next_to(line, vect, buff=SMALL_BUFF) s_labels[1].next_to(edge_lines[1], OUT) s_labels[2].next_to(edge_lines[2], LEFT) s_squared = OldTex("s^2") s_squared.match_style(s_labels[0]) s_squared.move_to(self.shadow) frame.generate_target() frame.target.reorient(10, 60) frame.target.set_height(6.5) self.play( LaggedStartMap(ShowCreation, edge_lines), LaggedStartMap(FadeIn, s_labels, scale=2), MoveToTarget(frame, run_time=3) ) self.wait() self.play( TransformFromCopy(s_labels[:2], s_squared), ) self.wait(2) rect = SurroundingRectangle(area_label) rect.fix_in_frame() rect.set_stroke(YELLOW, 3) s_eq = OldTex("s = 1") s_eq.next_to(area_label, DOWN) s_eq.set_color(RED) s_eq.set_stroke(BLACK, 3, background=True) s_eq.fix_in_frame() self.play(ShowCreation(rect)) self.play(FadeIn(s_eq, 0.5 * DOWN)) self.wait() self.play(LaggedStart(*map(FadeOut, ( rect, s_eq, *edge_lines, *s_labels, s_squared, )))) self.wait() # Hexagonal orientation axis = UL angle = np.arccos(1 / math.sqrt(3)) area_label.suspend_updating() self.play( Rotate(cube, -angle, axis), frame.animate.reorient(-10, 70), ChangeDecimalToValue(area_label[1], math.sqrt(3)), UpdateFromFunc(area_label[1], lambda m: m.fix_in_frame()), run_time=2 ) self.add(area_label) diagonal = Line(cube.get_nadir(), cube.get_zenith()) diagonal.set_stroke(WHITE, 2) diagonal.scale(2) diagonal.move_to(ORIGIN, IN) self.add(diagonal, cube) self.play(ShowCreation(diagonal)) self.wait(2) frame.save_state() cube_opacity = cube[0].get_fill_opacity() cube.save_state() angle = angle_of_vector(outline.get_anchors()[-1] - outline.get_anchors()[-2]) self.play( frame.animate.reorient(0, 0), cube.animate.rotate(-angle).set_opacity(0.2), run_time=3, ) frame.suspend_updating() outline_copy = outline.copy().clear_updaters() outline_copy.set_stroke(RED, 5) title = Text("Regular hexagon") title.set_color(RED) title.next_to(outline_copy, UP) title.set_backstroke() self.play( ShowCreationThenFadeOut(outline_copy), Write(title, run_time=1), ) self.play( FadeOut(title), Restore(frame), cube.animate.set_opacity(cube_opacity).rotate(angle), run_time=3, ) frame.resume_updating() hex_area_label = OldTex("\\sqrt{3} s^2") hex_area_label.set_color(RED) hex_area_label.move_to(self.shadow) hex_area_label.shift(0.35 * DOWN) self.play(Write(hex_area_label)) self.wait(10) area_label.resume_updating() self.play( Uncreate(diagonal), FadeOut(hex_area_label), Rotate(cube, 4, RIGHT) ) # Talk about averages light_lines.clear_updaters() self.begin_ambient_rotation(cube) self.play( FadeOut(light_lines), FadeIn(question, 0.5 * UP), ApplyMethod(frame.set_height, 8, run_time=2) ) self.play(FadeIn(subquestion, 0.5 * UP)) self.wait(7) cube.clear_updaters() cube.add_updater(lambda m: self.sort_to_camera(m)) samples = VGroup(VectorizedPoint()) samples.to_corner(UR) samples.shift(1.5 * LEFT) self.add(samples) for x in range(9): self.random_toss() sample = area_label[1].copy() sample.clear_updaters() sample.fix_in_frame() self.play( sample.animate.next_to(samples, DOWN), run_time=0.5 ) samples.add(sample) v_dots = OldTex("\\vdots") v_dots.next_to(samples, DOWN) v_dots.fix_in_frame() samples.add(v_dots) brace = Brace(samples, LEFT) brace.fix_in_frame() brace.next_to(samples, LEFT, SMALL_BUFF) text = OldTexText( "Take the mean.", "\\\\What does that\\\\approach?", font_size=30 ) text[0].shift(MED_SMALL_BUFF * UP) text.next_to(brace, LEFT) text.fix_in_frame() VGroup(text, brace).set_stroke(BLACK, 3, background=True) self.play( GrowFromCenter(brace), FadeIn(text), Write(v_dots), ) self.wait() for x in range(10): self.random_toss() self.wait() class AskAboutAveraging(TeacherStudentsScene): def construct(self): self.remove(self.background) sts = self.students tch = self.teacher self.play_student_changes( "maybe", "thinking", "erm", look_at=self.screen, added_anims=[self.teacher.change("raise_right_hand", self.screen)] ) self.wait(3) self.play( PiCreatureBubbleIntroduction( sts[2], OldTexText("What does that\\\\mean, exactly?"), target_mode="hesitant", look_at=self.screen, bubble_config={"direction": LEFT} ), LaggedStart( sts[0].change("confused", self.screen), sts[1].change("pondering", self.screen), tch.change("tease", sts[2].eyes), ) ) self.wait(4) self.student_says( "Can we do an experiment?", target_mode="raise_left_hand", index=1, ) self.wait(4) self.student_says( OldTexText("But what defines a\\\\``random'' toss?"), look_at=self.screen, target_mode="hesitant", index=2, added_anims=[ self.teacher.change("guilty"), self.students[0].change("erm"), ] ) self.wait(4) self.play(LaggedStart( self.students[0].change("pondering", self.screen), self.students[1].change("maybe", self.screen), self.teacher.change("tease", self.screen), )) self.wait(2) self.teacher_says(OldTexText("Hold off until\\\\the end")) self.wait(3) self.play_student_changes( "thinking", "tease", "pondering", look_at=self.screen, added_anims=[self.teacher.change("tease", self.students)] ) self.wait(4) class MeanCalculation(Scene): def construct(self): values = [1.55, 1.33, 1.46, 1.34, 1.50, 1.26, 1.42, 1.54, 1.51] nums = VGroup(*( DecimalNumber(x) for x in values )) nums.arrange(DOWN, aligned_edge=LEFT) nums.to_corner(UR, buff=LARGE_BUFF).shift(0.5 * LEFT) self.add(nums) mean_label = Text("Mean", font_size=36) mean_label.set_color(GREEN) mean_label.set_backstroke() mean_arrow = Vector(0.25 * UR) mean_arrow.match_color(mean_label) mean_arrow.next_to(mean_label, UR, SMALL_BUFF) mean_label.add(mean_arrow) for n in range(len(nums)): brace = Brace(nums[:n + 1], LEFT, buff=SMALL_BUFF) mean = DecimalNumber(np.mean(values[:n + 1])) mean.next_to(brace, LEFT) mean.match_color(mean_label) VGroup(brace, mean).set_backstroke() mean_label.next_to(mean, DL, SMALL_BUFF) self.add(brace, mean, mean_label) self.wait(0.5) self.remove(brace, mean) self.add(brace, mean) self.wait() # Embed self.embed() class DescribeSO3(ShadowScene): def construct(self): frame = self.camera.frame frame.set_z(1) frame.reorient(0) cube = self.solid cube.set_opacity(0.95) cube.move_to(ORIGIN) self.remove(self.plane) self.remove(self.shadow) x_point = VectorizedPoint(cube.get_right()) y_point = VectorizedPoint(cube.get_top()) z_point = VectorizedPoint(cube.get_zenith()) cube.add(x_point, y_point, z_point) def get_matrix(): return np.array([ x_point.get_center(), y_point.get_center(), z_point.get_center(), ]).T def get_mat_mob(): matrix = DecimalMatrix( get_matrix(), element_to_mobject_config=dict( num_decimal_places=2, edge_to_fix=LEFT, include_sign=True, ), h_buff=2.0, element_alignment_corner=LEFT, ) matrix.fix_in_frame() matrix.set_height(1.25) brackets = matrix.get_brackets() brackets[1].move_to(brackets[0].get_center() + 3.45 * RIGHT) matrix.to_corner(UL) return matrix matrix = always_redraw(get_mat_mob) self.add(matrix) # Space of orientations self.begin_ambient_rotation(cube, speed=0.4) self.wait(2) question = Text("What is the space of all orientations?") question.to_corner(UR) question.fix_in_frame() SO3 = OldTex("SO(3)") SO3.next_to(question, DOWN) SO3.set_color(BLUE) SO3.fix_in_frame() self.play(Write(question)) self.wait(2) self.play(FadeIn(SO3, DOWN)) self.wait(2) self.play(SO3.animate.next_to(matrix, DOWN, MED_LARGE_BUFF)) self.wait(5) new_question = Text( "What probability distribution are we placing\n" "on the space of all orientations?", t2c={"probability distribution": YELLOW}, t2s={"probability distribution": ITALIC}, ) new_question.match_width(question) new_question.move_to(question, UP) new_question.fix_in_frame() n = len("the space of all orientations?") self.play( FadeTransform(question[-n:], new_question[-n:]), FadeOut(question[:-n]), FadeIn(new_question[:-n]), ) self.wait() cube.clear_updaters() N = 15 cube_field = cube.get_grid(N, N) cube_field.set_height(10) for n, c in enumerate(cube_field): c.rotate(PI * (n // N) / N, axis=RIGHT) c.rotate(PI * (n % N) / N, axis=UP) for face in c: face.set_stroke(width=0) self.sort_to_camera(c) matrix.clear_updaters() self.play( FadeTransform(cube, cube_field[0]), LaggedStartMap(FadeIn, cube_field, run_time=15, lag_ratio=0.1) ) self.add(cube_field) self.wait() class PauseAndPonder(TeacherStudentsScene): def construct(self): self.remove(self.background) self.teacher_says( OldTexText("The goal is\\\\not speed."), added_anims=[self.change_students( "tease", "well", "pondering", look_at=self.screen )] ) self.wait(2) self.play( RemovePiCreatureBubble(self.teacher, target_mode="tease"), PiCreatureBubbleIntroduction( self.students[2], Lightbulb(), bubble_type=ThoughtBubble, bubble_creation_class=lambda m: FadeIn(m, lag_ratio=0.1), bubble_config=dict( height=3, width=3, direction=LEFT, ), target_mode="thinking", look_at=self.screen, ) ) self.wait(3) self.teacher_says( "Pause and ponder!", target_mode="well", added_anims=[self.change_students( "pondering", "tease", "thinking" )], run_time=1 ) self.wait(5) self.embed() class StartSimple(Scene): def construct(self): # Words title = Text("Universal problem-solving advice") title.set_width(FRAME_WIDTH - 4) title.to_edge(UP) title.set_color(BLUE) title.set_backstroke() line = Underline(title, buff=-0.035) line.set_width(FRAME_WIDTH - 1) line.set_color(BLUE_B) line.set_stroke(width=[0, 3, 3, 3, 0]) line.insert_n_curves(101) words = Text( "Start with the simplest non-trivial\n" "variant of the problem you can." ) words.next_to(line, DOWN, MED_SMALL_BUFF) rect = BackgroundRectangle(words, fill_opacity=1, buff=SMALL_BUFF) words.set_backstroke(width=5) # Shapes cube = VCube() cube.deactivate_depth_test() cube.set_color(BLUE_E) cube.set_opacity(0.75) cube.set_stroke(WHITE, 0.5, 0.5) cube.set_height(2) cube.rotate(PI / 4, [1, 2, 0]) cube.sort(lambda p: p[2]) cube = Group(*cube) cube.set_gloss(1) arrow = Arrow(LEFT, RIGHT) face = cube[np.argmax([f.get_z() for f in cube])].copy() group = Group(cube, arrow, face) group.arrange(RIGHT, buff=MED_LARGE_BUFF) group.next_to(words, DOWN, LARGE_BUFF) group.set_width(2) group.to_edge(RIGHT) group.set_y(0) self.camera.light_source.set_x(-4) self.play( ShowCreation(line), Write(title, run_time=1), ) self.wait() self.play( FadeIn(rect), FadeIn(words, lag_ratio=0.1), run_time=2 ) self.wait() self.play(FlashAround(words.get_part_by_text("non-trivial"), run_time=2)) self.wait() self.play( LaggedStart(*map(DrawBorderThenFill, cube)), ShowCreation(arrow), TransformFromCopy(cube[-1], face) ) self.wait(3) class FocusOnOneFace(ShadowScene): inf_light = True limited_plane_extension = 10 def construct(self): # Some random tumbling cube = self.solid shadow = self.shadow frame = self.camera.frame words = VGroup( Text("Just one orientation"), Text("Just one face"), ) words.fix_in_frame() words.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) words.to_corner(UL) average_words = Text("Average over all orientations") average_words.move_to(words[0], LEFT) average_words.fix_in_frame() self.add(average_words) self.random_toss(run_time=3, rate_func=linear) self.play( FadeIn(words[0], 0.75 * UP), FadeOut(average_words, 0.75 * UP), run_time=0.5, ) self.wait() # Just one face cube.update() index = np.argmax([f.get_z() for f in cube]) face = cube[index] prev_opacity = face.get_fill_opacity() cube.generate_target(use_deepcopy=True) cube.target.clear_updaters() cube.target.space_out_submobjects(2, about_point=face.get_center()) cube.target.set_opacity(0) cube.target[index].set_opacity(prev_opacity) self.shadow.set_stroke(width=0) self.play( MoveToTarget(cube), FadeIn(words[1]), ) self.play( frame.animate.reorient(-10, 65), FlashAround(words[1], rate_func=squish_rate_func(smooth, 0.2, 0.5)), FlashAround(words[0], rate_func=squish_rate_func(smooth, 0.5, 0.8)), run_time=5, ) frame.add_updater(lambda f, dt: f.increment_theta(0.01 * dt)) self.solid = face self.remove(shadow) self.add_shadow() shadow = self.shadow # Ask about area area_q = Text("Area?") area_q.add_updater(lambda m: m.move_to(shadow)) self.play(Write(area_q)) self.wait() # Orient straight up unit_normal = face.get_unit_normal() axis = rotate_vector(normalize([*unit_normal[:2], 0]), PI / 2, OUT) angle = np.arccos(unit_normal[2]) face.generate_target() face.target.rotate(-angle, axis) face.target.move_to(3 * OUT) face.target.rotate(-PI / 4, OUT) self.play(MoveToTarget(face)) light_lines = self.get_light_lines(n_lines=4, outline=shadow, only_vertices=True) light_lines.set_stroke(YELLOW, 1, 0.5) self.play( frame.animate.set_phi(70 * DEGREES), FadeIn(light_lines, lag_ratio=0.5), TransformFromCopy(face, face.deepcopy().set_opacity(0).set_z(0), remover=True), run_time=3, ) self.wait(3) self.play( Rotate(face, PI / 2, UP), FadeOut(area_q, scale=0), run_time=3, ) self.wait(3) self.play( Rotate(face, -PI / 3, UP), UpdateFromAlphaFunc(light_lines, lambda m, a: m.set_opacity(0.5 * (1 - a)), remover=True), run_time=2, ) # Show normal vector z_axis = VGroup( Line(ORIGIN, face.get_center()), Line(face.get_center(), 10 * OUT), ) z_axis.set_stroke(WHITE, 1) normal_vect = Vector() get_fc = face.get_center def get_un(): return face.get_unit_normal(recompute=True) def get_theta(): return np.arccos(get_un()[2]) normal_vect.add_updater(lambda v: v.put_start_and_end_on( get_fc(), get_fc() + get_un(), )) arc = always_redraw(lambda: Arc( start_angle=PI / 2, angle=-get_theta(), radius=0.5, stroke_width=2, ).rotate(PI / 2, RIGHT, about_point=ORIGIN).shift(get_fc())) theta = OldTex("\\theta", font_size=30) theta.set_backstroke() theta.rotate(PI / 2, RIGHT) theta.add_updater(lambda m: m.move_to( get_fc() + 1.3 * (arc.pfp(0.5) - get_fc()) )) theta.add_updater(lambda m: m.set_width(min(0.123, max(0.01, arc.get_width())))) self.play(ShowCreation(normal_vect)) self.wait() self.add(z_axis[0], face, z_axis[1], normal_vect) self.play(*map(FadeIn, z_axis)) self.play( FadeIn(theta, 0.5 * OUT), ShowCreation(arc), ) # Vary Theta frame.reorient(2) face.rotate(-35 * DEGREES, get_un(), about_point=face.get_center()) self.play( Rotate(face, 50 * DEGREES, UP), rate_func=there_and_back, run_time=8, ) # Show shadow area in the corner axes = Axes( (0, 180, 22.5), (0, 1, 0.25), width=5, height=2, axis_config={ "include_tip": False, "tick_size": 0.05, "numbers_to_exclude": [], }, ) axes.to_corner(UR, buff=MED_SMALL_BUFF) axes.x_axis.add_numbers([0, 45, 90, 135, 180], unit="^\\circ") y_label = OldTexText("Shadow's area", font_size=24) y_label.next_to(axes.y_axis.get_top(), RIGHT, MED_SMALL_BUFF) y_label.set_backstroke() ly_label = OldTex("s^2", font_size=24) ly_label.next_to(axes.y_axis.get_top(), LEFT, SMALL_BUFF) ly_label.shift(0.05 * UP) axes.add(y_label, ly_label) axes.fix_in_frame() graph = axes.get_graph( lambda x: math.cos(x * DEGREES), x_range=(0, 90), ) graph.set_stroke(RED, 3) graph.fix_in_frame() question = Text("Can you guess?", font_size=36) question.to_corner(UR) question.set_color(RED) dot = Dot(color=RED) dot.scale(0.5) dot.move_to(axes.c2p(0, 1)) dot.fix_in_frame() self.play( FadeIn(axes), Rotate(face, -get_theta(), UP, run_time=2), ) self.play(FadeIn(dot, shift=2 * UP + RIGHT)) self.wait(2) self.add(graph, axes) self.play( UpdateFromFunc(dot, lambda d: d.move_to(graph.get_end())), ShowCreation(graph), Rotate(face, PI / 2, UP), run_time=5 ) self.play(frame.animate.reorient(45), run_time=2) self.play(frame.animate.reorient(5), run_time=4) # Show vertical plane plane = Rectangle(width=self.plane.get_width(), height=5) plane.insert_n_curves(100) plane.set_fill(WHITE, 0.25) plane.set_stroke(width=0) plane.apply_depth_test() plane.rotate(PI / 2, RIGHT) plane.move_to(ORIGIN, IN) plane.save_state() plane.stretch(0, 2, about_edge=IN) face.apply_depth_test() z_axis.apply_depth_test() self.shadow.apply_depth_test() self.play( LaggedStartMap(FadeOut, VGroup(*words, graph, axes, dot)), Restore(plane, run_time=3) ) self.play(Rotate(face, -60 * DEGREES, UP, run_time=2)) # Slice up face face_copy = face.deepcopy() face_copy.rotate(-get_theta(), UP) face_copy.move_to(ORIGIN) n_slices = 25 rects = Rectangle().replicate(n_slices) rects.arrange(DOWN, buff=0) rects.replace(face_copy, stretch=True) slices = VGroup(*(Intersection(face_copy, rect) for rect in rects)) slices.match_style(face_copy) slices.set_stroke(width=0) slices.rotate(get_theta(), UP) slices.move_to(face) slices.apply_depth_test() slices.save_state() slice_outlines = slices.copy() slice_outlines.set_stroke(RED, 1) slice_outlines.set_fill(opacity=0) slice_outlines.deactivate_depth_test() frame.clear_updaters() self.play( frame.animate.set_euler_angles(PI / 2, get_theta()), FadeOut(VGroup(theta, arc)), run_time=2 ) self.play(ShowCreation(slice_outlines, lag_ratio=0.05)) self.remove(face) self.add(slices) self.remove(self.shadow) self.solid = slices self.add_shadow() self.shadow.set_stroke(width=0) self.add(normal_vect, plane, slice_outlines) slices.insert_n_curves(10) slices.generate_target() for sm in slices.target: sm.stretch(0.5, 1) self.play( MoveToTarget(slices), FadeOut(slice_outlines), run_time=2 ) self.wait(2) # Focus on one slice long_slice = slices[len(slices) // 2].deepcopy() line = Line(long_slice.get_corner(LEFT + OUT), long_slice.get_corner(RIGHT + IN)) line.scale(0.97) line.set_stroke(BLUE, 3) frame.generate_target() frame.target.reorient(0, 90) frame.target.set_height(6) frame.target.move_to(2.5 * OUT) self.shadow.clear_updaters() self.play( MoveToTarget(frame), *map(FadeIn, (theta, arc)), FadeOut(plane), FadeOut(slices), FadeOut(self.shadow), FadeIn(line), run_time=2, ) self.wait() # Analyze slice shadow = line.copy() shadow.stretch(0, 2, about_edge=IN) shadow.set_stroke(BLUE_E) vert_line = Line(line.get_start(), shadow.get_start()) vert_line.set_stroke(GREY_B, 3) shadow_label = Text("Shadow") shadow_label.set_fill(BLUE_E) shadow_label.set_backstroke() shadow_label.rotate(PI / 2, RIGHT) shadow_label.next_to(shadow, IN, SMALL_BUFF) self.play( TransformFromCopy(line, shadow), FadeIn(shadow_label, 0.5 * IN), ) self.wait() self.play(ShowCreation(vert_line)) self.wait() top_theta_group = VGroup( z_axis[1].copy(), arc.copy().clear_updaters(), theta.copy().clear_updaters(), Line(*normal_vect.get_start_and_end()).match_style(z_axis[1].copy()), ) self.play( top_theta_group.animate.move_to(line.get_start(), LEFT + IN) ) elbow = Elbow(angle=-get_theta()) elbow.set_stroke(WHITE, 2) ul_arc = Arc( radius=0.4, start_angle=-get_theta(), angle=-(PI / 2 - get_theta()) ) ul_arc.match_style(elbow) supl = OldTex("90^\\circ - \\theta", font_size=24) supl.next_to(ul_arc, DOWN, SMALL_BUFF, aligned_edge=LEFT) supl.set_backstroke() supl[0][:3].shift(SMALL_BUFF * RIGHT / 2) ul_angle_group = VGroup(elbow, ul_arc, supl) ul_angle_group.rotate(PI / 2, RIGHT, about_point=ORIGIN) ul_angle_group.shift(line.get_start()) dr_arc = Arc( radius=0.4, start_angle=PI, angle=-get_theta(), ) dr_arc.match_style(ul_arc) dr_arc.rotate(PI / 2, RIGHT, about_point=ORIGIN) dr_arc.shift(line.get_end()) dr_theta = OldTex("\\theta", font_size=24) dr_theta.rotate(PI / 2, RIGHT) dr_theta.next_to(dr_arc, LEFT, SMALL_BUFF) dr_theta.shift(SMALL_BUFF * OUT / 2) self.play(ShowCreation(elbow)) self.play( ShowCreation(ul_arc), FadeTransform(top_theta_group[2].copy(), supl), ) self.play( TransformFromCopy(ul_arc, dr_arc), TransformFromCopy(supl[0][4].copy().set_stroke(width=0), dr_theta[0][0]), ) self.wait() # Highlight lower right rect = Rectangle(0.8, 0.5) rect.set_stroke(YELLOW, 2) rect.rotate(PI / 2, RIGHT) rect.move_to(dr_theta, LEFT).shift(SMALL_BUFF * LEFT) self.play( ShowCreation(rect), top_theta_group.animate.fade(0.8), ul_angle_group.animate.fade(0.8), ) self.wait() # Show cosine cos_formula = OldTex( "\\cos(\\theta)", "=", "{\\text{Length of }", "\\text{shadow}", "\\over", "\\text{Length of }", "\\text{slice}" "}", ) cos_formula[2:].scale(0.75, about_edge=LEFT) cos_formula.to_corner(UR) cos_formula.fix_in_frame() lower_formula = OldTex( "\\text{shadow}", "=", "\\cos(\\theta)", "\\cdot", "\\text{slice}" ) lower_formula.match_width(cos_formula) lower_formula.next_to(cos_formula, DOWN, MED_LARGE_BUFF) lower_formula.fix_in_frame() for tex in cos_formula, lower_formula: tex.set_color_by_tex("shadow", BLUE_D) tex.set_color_by_tex("slice", BLUE_B) self.play(Write(cos_formula)) self.wait() self.play(TransformMatchingTex( VGroup(*(cos_formula[i].copy() for i in [0, 1, 3, 6])), lower_formula, path_arc=PI / 4, )) self.wait() # Bring full face back frame.generate_target() frame.target.reorient(20, 75) frame.target.set_height(6) frame.target.set_z(2) line_shadow = get_shadow(line) line_shadow.set_stroke(BLUE_E, opacity=0.5) self.solid = face self.add_shadow() self.add(z_axis[0], face, z_axis[1], line, normal_vect, theta, arc) self.play( MoveToTarget(frame, run_time=5), FadeIn(face, run_time=3), FadeIn(self.shadow, run_time=3), FadeIn(line_shadow, run_time=3), LaggedStart(*map(FadeOut, [ top_theta_group, ul_angle_group, rect, dr_theta, dr_arc, vert_line, shadow, shadow_label, ]), run_time=4), ) frame.add_updater(lambda f, dt: f.increment_theta(0.01 * dt)) self.wait(2) # Show perpendicular perp = Line( face.pfp(binary_search( lambda a: face.pfp(a)[2], face.get_center()[2], 0, 0.5, )), face.pfp(binary_search( lambda a: face.pfp(a)[2], face.get_center()[2], 0.5, 1.0, )), ) perp.set_stroke(RED, 3) perp_shadow = get_shadow(perp) perp_shadow.set_stroke(RED_E, 3, opacity=0.2) self.add(perp, normal_vect, arc) self.play( ShowCreation(perp), ShowCreation(perp_shadow), ) face.add(line) self.play(Rotate(face, 45 * DEGREES, UP), run_time=3) self.play(Rotate(face, -55 * DEGREES, UP), run_time=3) self.play(Rotate(face, 20 * DEGREES, UP), run_time=2) # Give final area formula final_formula = OldTex( "\\text{Area}(", "\\text{shadow}", ")", "=", "|", "\\cos(\\theta)", "|", "s^2" ) final_formula.set_color_by_tex("shadow", BLUE_D) final_formula.match_width(lower_formula) final_formula.next_to(lower_formula, DOWN, MED_LARGE_BUFF) final_formula.fix_in_frame() final_formula.get_parts_by_tex("|").set_opacity(0) final_formula.set_stroke(BLACK, 3, background=True) rect = SurroundingRectangle(final_formula) rect.set_stroke(YELLOW, 2) rect.fix_in_frame() self.play(Write(final_formula)) self.play(ShowCreation(rect)) final_formula.add(rect) self.wait(10) # Absolute value face.remove(line) self.play( frame.animate.shift(0.5 * DOWN + RIGHT).reorient(10), LaggedStart(*map(FadeOut, [cos_formula, lower_formula])), FadeIn(graph), FadeIn(axes), FadeOut(line), FadeOut(line_shadow), FadeOut(perp), FadeOut(perp_shadow), final_formula.animate.shift(2 * DOWN), run_time=2 ) self.play( Rotate(face, PI / 2 - get_theta(), UP), run_time=2 ) new_graph = axes.get_graph( lambda x: math.cos(x * DEGREES), (90, 180), ) new_graph.match_style(graph) new_graph.fix_in_frame() self.play( Rotate(face, PI / 2, UP), ShowCreation(new_graph), run_time=5, ) self.play( Rotate(face, -PI / 4, UP), run_time=2, ) self.wait(3) alt_normal = normal_vect.copy() alt_normal.clear_updaters() alt_normal.rotate(PI, UP, about_point=face.get_center()) alt_normal.set_color(YELLOW) self.add(alt_normal, face, normal_vect, arc, theta) self.play(ShowCreation(alt_normal)) self.wait() self.play(FadeOut(alt_normal)) new_graph.generate_target() new_graph.target.flip(RIGHT) new_graph.target.move_to(graph.get_end(), DL) self.play( MoveToTarget(new_graph), final_formula.get_parts_by_tex("|").animate.set_opacity(1), ) self.play( final_formula.animate.next_to(axes, DOWN) ) self.wait() self.play(Rotate(face, -PI / 2, UP), run_time=5) self.wait(10) class NotQuiteRight(TeacherStudentsScene): def construct(self): self.remove(self.background) self.teacher_says( "Not quite right...", target_mode="hesitant", bubble_config={"height": 3, "width": 4}, added_anims=[ self.change_students( "pondering", "thinking", "erm", look_at=self.screen, ) ] ) self.wait(4) class DiscussLinearity(Scene): def construct(self): # Set background background = FullScreenRectangle() self.add(background) panels = Rectangle(4, 4).replicate(3) panels.set_fill(BLACK, 1) panels.set_stroke(WHITE, 2) panels.set_height(FRAME_HEIGHT - 1) panels.arrange(RIGHT, buff=LARGE_BUFF) panels.set_width(FRAME_WIDTH - 1) panels.center() self.add(panels) # Arrows arrows = VGroup(*( Arrow( p1.get_top(), p2.get_top(), path_arc=-0.6 * PI ).scale(0.75, about_edge=DOWN) for p1, p2 in zip(panels, panels[1:]) )) arrows.space_out_submobjects(0.8) arrows.rotate(PI, RIGHT, about_point=panels.get_center()) arrow_labels = VGroup( Text("Rotation", font_size=30), Text("Flat projection", font_size=30), ) arrow_labels.set_backstroke() for arrow, label in zip(arrows, arrow_labels): label.next_to(arrow.pfp(0.5), UP, buff=0.35) shape_labels = VGroup( Text("Some shape"), Text("Any shape"), ) shape_labels.next_to(panels[0].get_top(), UP, SMALL_BUFF) # self.play(Write(shape_labels[0], run_time=1)) # self.wait() for arrow, label in zip(arrows, arrow_labels): self.play( ShowCreation(arrow), FadeIn(label, lag_ratio=0.1) ) self.wait() # Linear! lin_text = Text( "Both are linear transformations!", t2c={"linear": YELLOW} ) lin_text.next_to(panels, UP, MED_SMALL_BUFF) self.play(FadeIn(lin_text, lag_ratio=0.1)) self.wait() # Stretch words uniform_words = Text("Uniform stretching here", font_size=36).replicate(2) for words, panel in zip(uniform_words, panels[0::2]): words.next_to(panel.get_top(), DOWN, SMALL_BUFF) words.set_color(YELLOW) words.set_backstroke() self.play( FadeIn(words, lag_ratio=0.1), ) self.wait() # Transition lin_part = lin_text.get_part_by_text("linear") lin_copies = lin_part.copy().replicate(2) lin_copies.scale(0.6) for lin_copy, arrow in zip(lin_copies, arrows): lin_copy.next_to(arrow.pfp(0.5), DOWN, buff=0.15) self.play( TransformFromCopy(lin_part.replicate(2), lin_copies), LaggedStart( FadeOut(lin_text, lag_ratio=0.1), *map(FadeOut, uniform_words) ) ) # Areas area_labels = VGroup( Text("Area(shape)", t2c={"shape": BLUE}), Text("Area(shadow)", t2c={"shadow": BLUE_E}), ) area_exprs = VGroup( OldTex("A").set_color(BLUE), OldTex("(\\text{some factor})", "\\cdot ", "A"), ) area_exprs[1][2].set_color(BLUE) area_exprs[1][0].set_color(GREY_C) equals = VGroup() for label, expr, panel in zip(area_labels, area_exprs, panels[0::2]): label.match_x(panel) label.to_edge(UP, buff=MED_SMALL_BUFF) eq = OldTex("=") eq.rotate(PI / 2) eq.next_to(label, DOWN, buff=0.15) equals.add(eq) expr.next_to(eq, DOWN, buff=0.15) self.play( *map(Write, area_labels), run_time=1 ) self.play( *(FadeIn(eq, 0.5 * DOWN) for eq in equals), *(FadeIn(expr, DOWN) for expr in area_exprs), ) self.wait() f_rot = OldTex("f(\\text{Rot})") f_rot.set_color(GREY_B) times_A = area_exprs[1][1:] f_rot.next_to(times_A, LEFT, buff=0.2) times_A.generate_target() VGroup(f_rot, times_A.target).match_x(panels[2]) self.play( FadeTransform(area_exprs[1][0], f_rot), MoveToTarget(times_A) ) self.play(ShowCreationThenFadeAround(f_rot, run_time=2)) self.wait(1) # Determinant factor = area_exprs[1].get_part_by_tex('factor') rect = SurroundingRectangle(factor, buff=SMALL_BUFF) rect.set_stroke(YELLOW, 2) rot = Matrix([["v_1", "w_1"], ["v_2", "w_2"], ["v_3", "w_3"]], h_buff=1.0) rot.set_column_colors(GREEN, RED) proj = Matrix([["1", "0", "0"], ["0", "1", "0"]], h_buff=0.6) prod = VGroup(proj, rot) prod.arrange(RIGHT, buff=SMALL_BUFF) prod.set_height(0.8) det = OldTex( "\\text{det}", "\\Big(", "\\Big)", tex_to_color_map={ "\\text{det}": YELLOW, # "rot": BLUE_D, # "proj": BLUE_B, }, font_size=36 ) det[1:].match_height(prod, stretch=True) det.to_edge(UP) prod.next_to(det[1], RIGHT, SMALL_BUFF) det[2].next_to(prod, RIGHT, SMALL_BUFF) det.add(prod) det.center().to_edge(UP, buff=0.25) det_rect = SurroundingRectangle(det, buff=SMALL_BUFF) det_rect.set_stroke(YELLOW, 1) rot_brace = Brace(rot, DOWN, buff=SMALL_BUFF) details = Text("Need to work out rotation matrix...", font_size=20) details.next_to(rot_brace, DOWN, SMALL_BUFF) details.set_color(GREY_A) arrow = Arrow(rect.get_corner(UL), det.get_right()) arrow.set_color(YELLOW) self.play(ShowCreation(rect)) self.play( FadeTransform(rect.copy(), det_rect), FadeTransform(factor.copy(), det), ShowCreation(arrow) ) self.wait() self.play( FadeOut(det_rect), GrowFromCenter(rot_brace), FadeIn(details), ) self.wait() self.play(LaggedStart(*map(FadeOut, ( *det, rot_brace, details )), lag_ratio=0.3, run_time=2)) # Any shape ind_words = Text("Independent of the shape!", font_size=30) ind_words.move_to(det) ind_words.set_color(GREEN) self.play( arrow.animate.match_points(Arrow(factor.get_corner(UL), ind_words.get_corner(DR))), Write(ind_words, run_time=1), ) self.wait() self.play(LaggedStart(*map(FadeOut, (ind_words, arrow, rect)))) self.wait() # Cross out right cross = Cross(VGroup(equals[1], f_rot, times_A)) cross.insert_n_curves(20) self.play(ShowCreation(cross)) self.wait(3) class Matrices(Scene): def construct(self): self.add(FullScreenRectangle()) kw = { "v_buff": 0.7, "bracket_v_buff": 0.15, "bracket_h_buff": 0.15, } matrices = VGroup( Matrix([["v_1", "w_1"], ["v_2", "w_2"], ["v_3", "w_3"]], h_buff=1.0, **kw), Matrix([["1", "0", "0"], ["0", "1", "0"]], h_buff=0.6, **kw), ) matrices.set_color(GREY_A) matrices[0].set_column_colors(GREEN, RED) matrices.arrange(LEFT, buff=SMALL_BUFF) matrices.scale(0.5) mat_product = matrices[:2].copy() vectors = VGroup( Matrix([["x_0"], ["y_0"]], **kw), Matrix([["x_1"], ["y_1"], ["z_1"]], **kw), Matrix([["x_2"], ["y_2"]], **kw), ) for vect, x in zip(vectors, [-6, 0, 6]): vect.set_x(x) vect.set_y(2.5) arrows = VGroup( Arrow(vectors[0], vectors[1]), Arrow(vectors[1], vectors[2]), Arrow(vectors[0], vectors[2]), ) for mat, arrow in zip((*matrices[:2], mat_product), arrows): mat.next_to(arrow, UP, SMALL_BUFF) # Animations self.add(vectors[0]) for i in range(2): self.play( FadeTransform(vectors[i].copy(), vectors[i + 1]), ShowCreation(arrows[i]), FadeIn(matrices[i], 0.5 * RIGHT) ) self.wait() self.play( Transform(arrows[0], arrows[2]), Transform(arrows[1], arrows[2]), Transform(matrices, mat_product), FadeOut(vectors[1], scale=0), ) class DefineDeterminant(Scene): def construct(self): # Planes plane = NumberPlane((-2, 2), (-3, 3)) plane.set_height(FRAME_HEIGHT) planes = VGroup(plane, plane.deepcopy()) planes[0].to_edge(LEFT, buff=0) planes[1].to_edge(RIGHT, buff=0) planes[1].set_stroke(GREY_A, 1, 0.5) planes[1].faded_lines.set_opacity(0) titles = VGroup( Text("Input"), Text("Output"), ) for title, plane in zip(titles, planes): title.next_to(plane.get_top(), DOWN) title.add_background_rectangle() self.add(planes) # Area square = Square() square.set_stroke(YELLOW, 2) square.set_fill(YELLOW, 0.5) square.replace(Line(planes[0].c2p(-1, -1), planes[0].c2p(1, 1))) area_label = OldTexText("Area", "=", "$A$") area_label.set_color_by_tex("$A$", YELLOW) area_label.next_to(square, UP) area_label.add_background_rectangle() self.play( DrawBorderThenFill(square), FadeIn(area_label, 0.25 * UP, rate_func=squish_rate_func(smooth, 0.5, 1)) ) self.wait() # Arrow arrow = Arrow(*planes) arrow_label = Text("Linear transformation", font_size=30) arrow_label.next_to(arrow, UP) mat_mob = Matrix([["a", "b"], ["c", "d"]], h_buff=0.7, v_buff=0.7) mat_mob.set_height(0.7) mat_mob.next_to(arrow, DOWN) # Apply matrix matrix = [ [0.5, 0.4], [0.25, 0.75], ] for mob in planes[0], square: mob.output = mob.deepcopy() mob.output.apply_matrix(matrix, about_point=planes[0].c2p(0, 0)) mob.output.move_to(planes[1].get_center()) planes[0].output.set_stroke(width=1, opacity=1) planes[0].output.faded_lines.set_opacity(0) self.play( ReplacementTransform(planes[0].copy().fade(1), planes[0].output, run_time=2), ReplacementTransform(square.copy().fade(1), square.output, run_time=2), ShowCreation(arrow), FadeIn(arrow_label, 0.25 * RIGHT), FadeIn(mat_mob, 0.25 * RIGHT), ) self.wait() # New area new_area_label = OldTex( "\\text{Area} = ", "{c}", "\\cdot", "{A}", tex_to_color_map={ "{c}": RED, "{A}": YELLOW, } ) new_area_label.add_background_rectangle() new_area_label.next_to(square.output, UP) new_area_label.shift(0.5 * RIGHT) mmc = mat_mob.copy() mmc.scale(1.5) det = VGroup(get_det_text(mmc), mmc) det.set_height(new_area_label.get_height() * 1.2) det.move_to(new_area_label.get_part_by_tex("c"), RIGHT) det.match_y(new_area_label[-1]) det_name = OldTexText("``Determinant''", font_size=36) det_name.next_to(det, UP, MED_LARGE_BUFF) det_name.set_color(RED) det_name.add_background_rectangle() self.play(FadeTransform(area_label.copy(), new_area_label)) self.wait() self.play( FadeTransform(mat_mob.copy(), det), FadeTransform(new_area_label.get_part_by_tex("c"), det_name), new_area_label[1].animate.next_to(det, LEFT, SMALL_BUFF).match_y(new_area_label[1]), ) self.wait() class AmbientShapeRotationPreimage(ShadowScene): inf_light = False display_mode = "preimage_only" # Or "full_3d" or "shadow_only" rotate_in_3d = True only_show_shadow = False def construct(self): # Setup display_mode = self.display_mode frame = self.camera.frame frame.set_height(6) light = self.light light.move_to(75 * OUT) shape = self.solid fc = 2.5 * OUT shape.move_to(fc) self.solid.rotate(-0.5 * PI) self.solid.insert_n_curves(20) preimage = self.solid.deepcopy() preimage.move_to(ORIGIN) rotated = self.solid self.remove(self.shadow) shadow = rotated.deepcopy() shadow.set_fill(interpolate_color(BLUE_E, BLACK, 0.5), 0.7) shadow.set_stroke(BLACK, 1) def update_shadow(shadow): shadow.set_points( np.apply_along_axis( lambda p: project_to_xy_plane(self.light.get_center(), p), 1, rotated.get_points() ) ) shadow.refresh_triangulation() return shadow shadow.add_updater(update_shadow) rotated.axis_tracker = VectorizedPoint(RIGHT) rotated.angle_tracker = ValueTracker(0) rotated.rot_speed_tracker = ValueTracker(0.15) def update_rotated(mob, dt): mob.set_points(preimage.get_points()) mob.shift(fc) mob.refresh_triangulation() axis = mob.axis_tracker.get_location() angle = mob.angle_tracker.get_value() speed = mob.rot_speed_tracker.get_value() mob.axis_tracker.rotate(speed * dt, axis=OUT, about_point=ORIGIN) mob.angle_tracker.increment_value(speed * dt) mob.rotate(angle, axis, about_point=fc) return rotated rotated.add_updater(update_rotated) # Conditionals if display_mode == "full_3d": preimage.set_opacity(0) self.add(shadow) self.add(rotated) z_axis = VGroup( Line(ORIGIN, fc), Line(fc, 10 * OUT), ) z_axis.set_stroke(WHITE, 1) self.add(z_axis[0], rotated, z_axis[1]) orientation_arrows = VGroup( Vector(RIGHT, stroke_color=RED_D), Vector(UP, stroke_color=GREEN_D), Vector(OUT, stroke_color=BLUE_D), ) orientation_arrows.set_stroke(opacity=0.85) orientation_arrows.shift(fc) orientation_arrows.save_state() orientation_arrows.add_updater(lambda m: m.restore().rotate( rotated.angle_tracker.get_value(), rotated.axis_tracker.get_location(), )) orientation_arrows.add_updater(lambda m: m.shift(fc - m[0].get_start())) orientation_arrows.apply_depth_test() self.add(orientation_arrows) proj_lines = always_redraw(lambda: VGroup(*( Line( rotated.pfp(a), flat_project(rotated.pfp(a)) ).set_stroke(WHITE, 0.5, 0.2) for a in np.linspace(0, 1, 100) ))) self.add(proj_lines) frame.reorient(20, 70) self.init_frame_rotation() # frame_speed = -0.02 # frame.add_updater(lambda f, dt: f.increment_theta(frame_speed * dt)) elif display_mode == "shadow_only": frame.reorient(0, 0) frame.set_height(3) rotated.set_opacity(0) preimage.set_opacity(0) self.glow.set_opacity(0.2) self.add(rotated) self.add(shadow) elif display_mode == "preimage_only": self.glow.set_opacity(0) self.remove(self.plane) self.add(preimage) frame.reorient(0, 0) frame.set_height(3) rotated.set_opacity(0) # Just hang around self.wait(15) # Change to cat cat = SVGMobject("cat_outline").family_members_with_points()[0] dog = SVGMobject("dog_outline").family_members_with_points()[0] dog.insert_n_curves(87) for mob in cat, dog: mob.match_style(preimage) mob.replace(preimage, dim_to_match=0) pass # Stretch self.play(rotated.rot_speed_tracker.animate.set_value(0)) rotated.rot_speed = 0 for axis, diag in zip((0, 1, 0, 1), (False, False, True, True)): preimage.generate_target() if diag: preimage.target.rotate(PI / 4) preimage.target.stretch(2, axis) if diag: preimage.target.rotate(-PI / 4) self.play( MoveToTarget(preimage), rate_func=there_and_back, run_time=4 ) self.wait(5) self.play(rotated.rot_speed_tracker.animate.set_value(0.1)) # Change shape cat = SVGMobject("cat_outline").family_members_with_points()[0] dog = SVGMobject("dog_outline").family_members_with_points()[0] dog.insert_n_curves(87) for mob in cat, dog: mob.match_style(preimage) mob.replace(preimage, dim_to_match=0) self.play(Transform(preimage, cat, run_time=4)) cat.insert_n_curves(87) preimage.become(cat) self.wait(2) # More shape changes self.play( preimage.animate.scale(2), rate_func=there_and_back, run_time=3, ) self.play( preimage.animate.become(dog), path_arc=PI, rate_func=there_and_back_with_pause, # Or rather, with paws... run_time=5, ) self.wait(6) # Bring light source closer self.play(rotated.rot_speed_tracker.animate.set_value(0)) anims = [ light.animate.move_to(4 * OUT) ] angle = rotated.angle_tracker.get_value() angle_anim = rotated.angle_tracker.animate.set_value(np.round(angle / TAU, 0) * TAU) if self.display_mode == "full_3d": light_lines = self.get_light_lines(shadow) lso = light_lines[0].get_stroke_opacity() pso = proj_lines[0].get_stroke_opacity() proj_lines.clear_updaters() anims += [ UpdateFromAlphaFunc(proj_lines, lambda m, a: m.set_stroke(opacity=pso * (1 - a))), UpdateFromAlphaFunc(light_lines, lambda m, a: m.set_stroke(opacity=lso * a)), angle_anim, frame.animate.reorient(20, 70).set_height(8), ] frame.clear_updaters() if self.display_mode == "shadow_only": anims += [ frame.animate.set_height(10), angle_anim, ] self.play(*anims, run_time=4) self.wait() rotated.axis_tracker.move_to(UP) self.play( rotated.angle_tracker.animate.set_value(70 * DEGREES + TAU), run_time=2 ) self.play( preimage.animate.stretch(1.5, 0), rate_func=there_and_back, run_time=5, ) anims = [rotated.axis_tracker.animate.move_to(RIGHT)] if self.display_mode == "full_3d": anims.append(frame.animate.reorient(-20, 70)) self.play(*anims, run_time=2) self.play( preimage.animate.stretch(2, 1), rate_func=there_and_back, run_time=7, ) # More ambient motion self.play(rotated.rot_speed_tracker.animate.set_value(0.1)) self.wait(30) def get_solid(self): face = Square(side_length=2) face.set_fill(BLUE, 0.5) face.set_stroke(WHITE, 1) return face class AmbientShapeRotationFull3d(AmbientShapeRotationPreimage): display_mode = "full_3d" class AmbientShapeRotationShadowOnly(AmbientShapeRotationPreimage): display_mode = "shadow_only" class IsntThatObvious(TeacherStudentsScene): def construct(self): self.remove(self.background) self.student_says( OldTexText("Isn't that obvious?"), bubble_config={ "height": 3, "width": 4, "direction": LEFT, }, target_mode="angry", look_at=self.screen, added_anims=[LaggedStart( self.teacher.change("guilty"), self.students[0].change("pondering", self.screen), self.students[1].change("erm", self.screen), )] ) self.wait(2) self.play( self.students[0].change("hesitant"), ) self.wait(2) class StretchLabel(Scene): def construct(self): label = VGroup( Vector(0.5 * LEFT), OldTex("1.5 \\times"), Vector(0.5 * RIGHT) ) label.set_color(YELLOW) label.arrange(RIGHT, buff=SMALL_BUFF) self.play( *map(ShowCreation, label[::2]), Write(label[1]), ) self.wait() class WonderAboutAverage(Scene): def construct(self): randy = Randolph() randy.to_edge(DOWN) randy.look(RIGHT) self.play(PiCreatureBubbleIntroduction( randy, OldTexText("How do you think\\\\about this average"), target_mode="confused", run_time=2 )) for x in range(2): self.play(Blink(randy)) self.wait(2) class SingleFaceRandomRotation(ShadowScene): initial_wait_time = 0 inf_light = True n_rotations = 1 total_time = 60 plane_dims = (8, 8) frame_rot_speed = 0.02 theta0 = -20 * DEGREES CONFIG = {"random_seed": 0} def setup(self): super().setup() np.random.seed(self.random_seed) frame = self.camera.frame frame.set_height(5.0) frame.set_z(1.75) frame.set_theta(self.theta0) face = self.solid face.shift(0.25 * IN) fc = face.get_center() z_axis = self.z_axis = VGroup(Line(ORIGIN, fc), Line(fc, 10 * OUT)) z_axis.set_stroke(WHITE, 0.5) self.add(z_axis[0], face, z_axis[1]) arrows = VGroup( Line(ORIGIN, RIGHT, color=RED_D), Line(ORIGIN, UP, color=GREEN_D), VGroup( Vector(OUT, stroke_width=4, stroke_color=BLACK), Vector(OUT, stroke_width=3, stroke_color=BLUE_D), ) ) arrows[:2].set_stroke(width=2) arrows.set_stroke(opacity=0.8) arrows.shift(fc) arrows.set_stroke(opacity=0.8) face.add(arrows[:2]) face = Group(face, arrows[2]) face.add_updater(lambda m: self.sort_to_camera(face)) self.face = self.solid = face arrow_shadow = get_shadow(arrows) arrow_shadow.set_stroke(width=1) arrow_shadow[2].set_stroke(width=[1, 1, 4, 0]) self.add(arrow_shadow) self.add(z_axis[0], face, z_axis[1]) def construct(self): frame = self.camera.frame face = self.face frame.add_updater(lambda f, dt: f.increment_theta(self.frame_rot_speed * dt)) self.wait(self.initial_wait_time) for x in range(self.n_rotations): self.random_toss( face, about_point=fc, angle=3 * PI, # run_time=1.5, run_time=8, rate_func=smooth, ) self.wait() self.wait(self.total_time - 2 - self.initial_wait_time) def get_solid(self): face = Square(side_length=2) face.set_fill(BLUE_E, 0.75) face.set_stroke(WHITE, 0.5) return face class RandomRotations1(SingleFaceRandomRotation): initial_wait_time = 1 theta0 = -30 * DEGREES CONFIG = {"random_seed": 10} class RandomRotations2(SingleFaceRandomRotation): initial_wait_time = 1.5 theta0 = -25 * DEGREES CONFIG = {"random_seed": 4} class RandomRotations3(SingleFaceRandomRotation): initial_wait_time = 2 theta0 = -20 * DEGREES CONFIG = {"random_seed": 5} class RandomRotations4(SingleFaceRandomRotation): initial_wait_time = 2.5 theta0 = -15 * DEGREES CONFIG = {"random_seed": 6} class AverageFaceShadow(SingleFaceRandomRotation): inf_light = True plane_dims = (16, 8) n_samples = 50 def construct(self): # Random shadows self.camera.frame.set_height(6) face = self.face shadow = self.shadow shadow.add_updater(lambda m: m.set_fill(BLACK, 0.25)) shadow.update() point = face[0].get_center() shadows = VGroup() n_samples = self.n_samples self.remove(self.z_axis) self.init_frame_rotation() self.add(shadows) for n in range(n_samples): self.randomly_reorient(face, about_point=point) if n == n_samples - 1: normal = next( sm.get_unit_normal() for sm in face.family_members_with_points() if isinstance(sm, VMobject) and sm.get_fill_opacity() > 0 ) mat = z_to_vector(normal) # face.apply_matrix(np.linalg.inv(mat), about_point=point) shadow.update() sc = shadow.copy() sc.clear_updaters() shadows.add(sc) shadows.set_fill(BLACK, 1.5 / len(shadows)) shadows.set_stroke(opacity=10 / len(shadows)) self.wait(0.1) # Fade out shadow self.remove(shadow) sc = shadow.copy().clear_updaters() self.play(FadeOut(sc)) self.wait() # Scaling self.play( face.animate.scale(0.5, about_point=point), shadows.animate.scale(0.5, about_point=ORIGIN), run_time=3, rate_func=there_and_back, ) for axis in [0, 1]: self.play( face.animate.stretch(2, axis, about_point=point), shadows.animate.stretch(2, axis, about_point=ORIGIN), run_time=3, rate_func=there_and_back, ) self.wait() # Ambient rotations 106 plays self.play( self.camera.frame.animate.reorient(-10).shift(2 * LEFT), ) self.add(shadow) for n in range(100): self.randomly_reorient(face, about_point=point) self.wait(0.2) class AverageCatShadow(AverageFaceShadow): n_samples = 50 def setup(self): super().setup() self.replace_face() def replace_face(self): face = self.face shape = self.get_shape().family_members_with_points()[0] shape.match_style(face[0]) shape.replace(face[0]) face[0].set_points(shape.get_points()) face[0].set_gloss(0.25) face[0][0].set_gloss(0) self.solid = face self.remove(self.shadow) self.add_shadow() def get_shape(self): return SVGMobject("cat_outline") class AveragePentagonShadow(AverageCatShadow): def get_shape(self): return RegularPolygon(5) class AverageShadowAnnotation(Scene): def construct(self): # Many shadows many_shadows = Text("Many shadows") many_shadows.move_to(3 * DOWN) self.play(Write(many_shadows)) self.wait(2) # Formula # shape_name = "2d shape" shape_name = "Square" t2c = { "Shadow": GREY_B, shape_name: BLUE, "$c$": RED, } formula = VGroup( OldTexText( f"Area(Shadow({shape_name}))", tex_to_color_map=t2c, ), OldTex("=").rotate(PI / 2), OldTexText( "$c$", " $\\cdot$", f"(Area({shape_name}))", tex_to_color_map=t2c ) ) overline = get_overline(formula[0]) formula[0].add(overline) formula.arrange(DOWN) formula.to_corner(UL) self.play(FadeTransform(many_shadows, formula[0])) self.wait() self.play( VShowPassingFlash( overline.copy().insert_n_curves(100).set_stroke(YELLOW, 5), time_width=0.75, run_time=2, ) ) self.wait() self.play( Write(formula[1]), FadeIn(formula[2], DOWN) ) self.wait() # Append half half = OldTex("\\frac{1}{2}") half.set_color(RED) c = formula[2].get_part_by_tex("$c$") half.move_to(c, RIGHT) self.play( FadeOut(c, 0.5 * UP), FadeIn(half, 0.5 * UP), ) self.wait() class AlicesFaceAverage(Scene): def construct(self): # Background background = FullScreenRectangle() self.add(background) panels = Rectangle(2, 2.5).replicate(5) panels.set_stroke(WHITE, 1) panels.set_fill(BLACK, 1) dots = OldTex("\\dots") panels.replace_submobject(3, dots) panels.arrange(RIGHT, buff=0.25) panels.set_width(FRAME_WIDTH - 1) panels.move_to(2 * DOWN, DOWN) self.add(panels) panels = VGroup(*panels[:-2], panels[-1]) # Label the rotations indices = ["1", "2", "3", "n"] rot_labels = VGroup(*( OldTex(f"R_{i}") for i in indices )) for label, panel in zip(rot_labels, panels): label.set_height(0.3) label.next_to(panel, DOWN) rot_words = Text("Sequence of random rotations") rot_words.next_to(rot_labels, DOWN, MED_LARGE_BUFF) self.play(Write(rot_words, run_time=2)) self.wait(2) self.play(LaggedStartMap( FadeIn, rot_labels, shift=0.25 * DOWN, lag_ratio=0.5 )) self.wait() # Show the shadow areas font_size = 30 fra_labels = VGroup(*( OldTex( f"f(R_{i})", "\\cdot ", "A", tex_to_color_map={"A": BLUE}, font_size=font_size ) for i in indices )) DARK_BLUE = interpolate_color(BLUE_D, BLUE_E, 0.5) area_shadow_labels = VGroup(*( OldTex( "\\text{Area}(", "\\text{Shadow}_" + i, ")", tex_to_color_map={"\\text{Shadow}_" + i: DARK_BLUE}, font_size=font_size ) for i in indices )) s_labels = VGroup(*( OldTex( f"S_{i}", "=", tex_to_color_map={f"S_{i}": DARK_BLUE}, font_size=font_size ) for i in indices )) label_arrows = VGroup() for fra, area, s_label, panel in zip(fra_labels, area_shadow_labels, s_labels, panels): fra.next_to(panel, UP, SMALL_BUFF) area.next_to(fra, UP) area.to_edge(UP, buff=LARGE_BUFF) label_arrows.add(Arrow(area, fra, buff=0.2, stroke_width=3)) fra.generate_target() eq = VGroup(s_label, fra.target) eq.arrange(RIGHT, buff=SMALL_BUFF) eq.move_to(fra, DOWN) self.add(area_shadow_labels) self.add(fra_labels) self.add(label_arrows) lr = 0.2 self.play( LaggedStartMap(FadeIn, area_shadow_labels, lag_ratio=lr), LaggedStartMap(ShowCreation, label_arrows, lag_ratio=lr), LaggedStartMap(FadeIn, fra_labels, shift=DOWN, lag_ratio=lr), ) self.wait() self.play( LaggedStart(*( FadeTransform(area, area_s) for area, area_s in zip(area_shadow_labels, s_labels) ), lag_ratio=lr), LaggedStartMap(MoveToTarget, fra_labels, lag_ratio=lr), LaggedStartMap(Uncreate, label_arrows, lag_ratio=lr), ) # Show average sample_average = OldTex( "\\text{Sample average}", "=", "\\frac{1}{n}", "\\left(", "f(R_1)", "\\cdot ", "A", "+", "f(R_2)", "\\cdot ", "A", "+", "f(R_3)", "\\cdot ", "A", "+", "\\cdots ", "f(R_n)", "\\cdot ", "A", "\\right)", font_size=font_size ) sample_average.set_color_by_tex("A", BLUE) sample_average.to_edge(UP, buff=MED_SMALL_BUFF) for tex in ["\\left", "\\right"]: part = sample_average.get_part_by_tex(tex) part.scale(1.5) part.stretch(1.5, 1) self.play(FadeIn(sample_average[:2])) self.play( TransformMatchingShapes( fra_labels.copy(), sample_average[4:-1] ) ) self.wait() self.play( Write(VGroup(*sample_average[2:4], sample_average[-1])) ) self.wait() # Factor out A sample_average.generate_target() cdots = sample_average.target.get_parts_by_tex("\\cdot", substring=False) As = sample_average.target.get_parts_by_tex("A", substring=False) new_pieces = VGroup(*( sm for sm in sample_average.target if sm.get_tex() not in ["A", "\\cdot"] )) new_A = As[0].copy() new_cdot = cdots[0].copy() new_pieces.insert_submobject(2, new_cdot) new_pieces.insert_submobject(2, new_A) new_pieces.arrange(RIGHT, buff=SMALL_BUFF) new_pieces.move_to(sample_average) for group, target in (As, new_A), (cdots, new_cdot): for sm in group: sm.replace(target) group[1:].set_opacity(0) self.play(LaggedStart( *( FlashAround(mob, time_width=3) for mob in sample_average.get_parts_by_tex("A") ), lag_ratio=0.1, run_time=2 )) self.play(MoveToTarget(sample_average, path_arc=-PI / 5)) self.wait() # True average brace = Brace(new_pieces[4:], DOWN, buff=SMALL_BUFF, font_size=30) lim = OldTex("n \\to \\infty", font_size=30) lim.next_to(brace, DOWN) VGroup(brace, lim).set_color(YELLOW) sample = sample_average[0][:len("Sample")] cross = Cross(sample) cross.insert_n_curves(20) cross.scale(1.5) self.play( FlashAround(sample_average[2:], run_time=3, time_width=1.5) ) self.play( FlashUnder(sample_average[:2], color=RED), run_time=2 ) self.play( GrowFromCenter(brace), FadeIn(lim, 0.25 * DOWN), ShowCreation(cross) ) self.play( LaggedStart(*map(FadeOut, [ *fra_labels, *s_labels, *panels, dots, *rot_labels, rot_words ])) ) self.wait() # Some constant rect = SurroundingRectangle( VGroup(new_pieces[4:], brace, lim), buff=SMALL_BUFF, ) rect.set_stroke(YELLOW, 1) rect.stretch(0.98, 0) words = Text("Some constant") words.next_to(rect, DOWN) subwords = Text("Independent of the size and shape of the 2d piece") subwords.scale(0.5) subwords.next_to(words, DOWN) subwords.set_fill(GREY_A) self.play( ShowCreation(rect), FadeIn(words, 0.25 * DOWN) ) self.wait() self.play(Write(subwords)) self.wait() class ManyShadows(SingleFaceRandomRotation): plane_dims = (4, 4) limited_plane_extension = 2 def construct(self): self.clear() self.camera.frame.reorient(0, 0) plane = self.plane face = self.solid shadow = self.shadow n_rows = 3 n_cols = 10 planes = plane.replicate(n_rows * n_cols) for n, plane in zip(it.count(1), planes): face.rotate(angle=random.uniform(0, TAU), axis=normalize(np.random.uniform(-1, 1, 3))) shadow.update() sc = shadow.deepcopy() sc.clear_updaters() sc.set_fill(interpolate_color(BLUE_E, BLACK, 0.5), 0.75) plane.set_gloss(0) plane.add_to_back(sc) area = DecimalNumber(get_norm(sc.get_area_vector() / 4.0), font_size=56) label = VGroup(OldTex(f"f(R_{n}) = "), area) label.arrange(RIGHT) label.set_width(0.8 * plane.get_width()) label.next_to(plane, UP, SMALL_BUFF) label.set_color(WHITE) plane.add(label) planes.arrange_in_grid(n_rows, n_cols, buff=LARGE_BUFF) planes.set_width(15) planes.to_edge(DOWN) planes.update() self.play( LaggedStart( *( FadeIn(plane, scale=1.1) for plane in planes ), lag_ratio=0.6, run_time=10 ) ) self.wait() self.embed() class ComingUp(VideoWrapper): title = "Bob will compute this directly" wait_time = 10 animate_boundary = False class AllPossibleOrientations(ShadowScene): inf_light = True limited_plane_extension = 6 plane_dims = (12, 8) def construct(self): # Setup frame = self.camera.frame frame.reorient(-20, 80) frame.set_height(5) frame.d_theta = 0 def update_frame(frame, dt): frame.d_theta += -0.0025 * frame.get_theta() frame.increment_theta(clip(0.0025 * frame.d_theta, -0.01 * dt, 0.01 * dt)) frame.add_updater(update_frame) face = self.solid square, normal_vect = face normal_vect.set_flat_stroke() self.solid = square self.remove(self.shadow) self.add_shadow() self.shadow.deactivate_depth_test() self.solid = face fc = square.get_center().copy() # Sphere points sphere = Sphere(radius=1) sphere.set_color(GREY_E, 0.7) sphere.move_to(fc) sphere.always_sort_to_camera(self.camera) n_lat_lines = 40 theta_step = PI / n_lat_lines sphere_points = np.array([ sphere.uv_func(phi, theta + theta_step * (phi / TAU)) for theta in np.arange(0, PI, theta_step) for phi in np.linspace( 0, TAU, int(2 * n_lat_lines * math.sin(theta)) + 1 ) ]) sphere_points[:, 2] *= -1 original_sphere_points = sphere_points.copy() sphere_points += fc sphere_dots = DotCloud(sphere_points) sphere_dots.set_radius(0.0125) sphere_dots.set_glow_factor(0.5) sphere_dots.make_3d() sphere_dots.apply_depth_test() sphere_dots.add_updater(lambda m: m) sphere_lines = VGroup(*( Line(sphere.get_center(), p) for p in sphere_dots.get_points() )) sphere_lines.set_stroke(WHITE, 1, 0.05) sphere_words = OldTexText("All normal vectors = Sphere") uniform_words = OldTexText("All points equally likely") for words in [sphere_words, uniform_words]: words.fix_in_frame() words.to_edge(UP) # Trace sphere N = len(original_sphere_points) self.play(FadeIn(sphere_words)) self.play( ShowCreation(sphere_dots), ShowIncreasingSubsets(sphere_lines), UpdateFromAlphaFunc( face, lambda m, a: m.apply_matrix( rotation_between_vectors( normal_vect.get_vector(), original_sphere_points[int(a * (N - 1))], ), about_point=fc ) ), run_time=30, rate_func=smooth, ) self.play( FadeOut(sphere_words, UP), FadeIn(uniform_words, UP), ) last_dot = Mobject() for x in range(20): point = random.choice(sphere_points) dot = TrueDot( point, radius=1, glow_factor=10, color=YELLOW, ) self.add(dot) self.play( face.animate.apply_matrix(rotation_between_vectors( normal_vect.get_vector(), point - fc ), about_point=fc), FadeOut(last_dot, run_time=0.25), FadeIn(dot), run_time=0.5, ) self.wait(0.25) last_dot = dot self.play(FadeOut(last_dot)) self.wait() # Sphere itself sphere_mesh = SurfaceMesh(sphere, resolution=(21, 11)) sphere_mesh.set_stroke(BLUE_E, 1, 1) for sm in sphere_mesh.get_family(): sm.uniforms["anti_alias_width"] = 0 v1 = normal_vect.get_vector() normal_vect.scale(0.99, about_point=fc) v2 = DR + OUT frame.reorient(-5) self.play( Rotate( face, angle_between_vectors(v1, v2), axis=normalize(cross(v1, v2)) ), UpdateFromAlphaFunc( self.plane, lambda m, a: square.scale(0.9).set_opacity(0.5 - a * 0.5) ), ) self.play( ShowCreation(sphere_mesh, lag_ratio=0.5), FadeIn(sphere), sphere_dots.animate.set_radius(0), FadeOut(sphere_lines), frame.animate.reorient(0), run_time=3, ) self.remove(sphere_dots) # Show patch def get_patch(u, v, delta_u=0.05, delta_v=0.1): patch = ParametricSurface( sphere.uv_func, u_range=(u * TAU, (u + delta_u) * TAU), v_range=(v * PI, (v + delta_v) * PI), ) patch.shift(fc) patch.set_color(YELLOW, 0.75) patch.always_sort_to_camera(self.camera) return patch patch = get_patch(0.85, 0.6) self.add(patch, sphere) self.play( ShowCreation(patch), frame.animate.reorient(10, 75), run_time=2, ) # Probability expression patch_copy = patch.deepcopy() sphere_copy = sphere.deepcopy() sphere_copy.set_color(GREY_D, 0.7) for mob in patch_copy, sphere_copy: mob.apply_matrix(frame.get_inverse_camera_rotation_matrix()) mob.fix_in_frame() mob.center() patch_copy2 = patch_copy.copy() prob = Group(*Tex( "P(", "0.", ")", "=", "{Num ", "\\over ", "Den}", font_size=60 )) prob.fix_in_frame() prob.to_corner(UR) prob.shift(DOWN) for i, mob in [(1, patch_copy), (4, patch_copy2), (6, sphere_copy)]: mob.replace(prob[i], dim_to_match=1) prob.replace_submobject(i, mob) sphere_copy.scale(3, about_edge=UP) self.play(FadeIn(prob, lag_ratio=0.1)) self.wait() for i in (4, 6): self.play(ShowCreationThenFadeOut( SurroundingRectangle(prob[i], stroke_width=2).fix_in_frame() )) self.wait() # Many patches patches = Group( get_patch(0.65, 0.5), get_patch(0.55, 0.8), get_patch(0.85, 0.8), get_patch(0.75, 0.4, 0.1, 0.2), ) patch.deactivate_depth_test() self.add(sphere, patch) for new_patch in patches: self.play( Transform(patch, new_patch), ) self.wait() # Non-specified orientation self.play( LaggedStart(*map(FadeOut, (sphere, sphere_mesh, patch, *prob, uniform_words))) ) self.play( square.animate.set_fill(opacity=0.5), frame.animate.reorient(-30), run_time=3, ) self.play( Rotate(square, TAU, normal_vect.get_vector()), run_time=8, ) self.wait() # Show theta def get_normal(): return normal_vect.get_vector() def get_theta(): return np.arccos(get_normal()[2] / get_norm(get_normal())) def get_arc(): result = Arc(PI / 2, -get_theta(), radius=0.25) result.rotate(PI / 2, RIGHT, about_point=ORIGIN) result.rotate(angle_of_vector([*get_normal()[:2], 0]), OUT, about_point=ORIGIN) result.shift(fc) result.set_stroke(WHITE, 1) result.apply_depth_test() return result arc = always_redraw(get_arc) theta = OldTex("\\theta", font_size=20) theta.rotate(PI / 2, RIGHT) theta.set_backstroke(width=2) theta.add_updater(lambda m: m.next_to(arc.pfp(0.5), OUT + RIGHT, buff=0.05)) z_axis = Line(ORIGIN, 10 * OUT) z_axis.set_stroke(WHITE, 1) z_axis.apply_depth_test() self.add(z_axis, face, theta, arc) self.play( ShowCreation(z_axis), ShowCreation(arc), FadeIn(theta, 0.5 * OUT), ) self.wait() # Show shadow area shadow_area = OldTexText("Shadow area =", "$|\\cos(\\theta)|s^2$") shadow_area.fix_in_frame() shadow_area.to_edge(RIGHT) shadow_area.set_y(-3) shadow_area.set_backstroke() self.play( Write(shadow_area, run_time=3), Rotate(face, TAU, normal_vect.get_vector(), run_time=10), ) self.wait(4) shadow_area[1].generate_target() shadow_area[1].target.to_corner(UR, buff=MED_LARGE_BUFF) shadow_area[1].target.shift(LEFT) brace = Brace(shadow_area[1].target, DOWN) brace_text = OldTexText("How do you average this\\\\over the sphere?", font_size=36) brace_text.next_to(brace, DOWN, SMALL_BUFF) brace.fix_in_frame() brace_text.fix_in_frame() self.play( GrowFromCenter(brace), MoveToTarget(shadow_area[1]), FadeOut(shadow_area[0]), square.animate.set_fill(opacity=0), ) face.generate_target() face.target[1].set_length(0.98, about_point=fc) sphere.set_opacity(0.35) sphere_mesh.set_stroke(width=0.5) self.play( MoveToTarget(face), FadeIn(brace_text, 0.5 * DOWN), Write(sphere_mesh, run_time=2, stroke_width=1), FadeIn(sphere), ) # Sum expression def update_theta_ring(ring): theta = get_theta() phi = angle_of_vector([*get_normal()[:2], 0]) ring.set_width(max(2 * 1.01 * math.sin(theta), 1e-3)) ring.rotate(phi - angle_of_vector([*ring.get_start()[:2], 0])) ring.move_to(fc + math.cos(theta) * OUT) return ring theta_ring = Circle() theta_ring.set_stroke(YELLOW, 2) theta_ring.apply_depth_test() theta_ring.uniforms["anti_alias_width"] = 0 loose_sum = OldTex( "\\sum_{\\theta \\in [0, \\pi]}", "P(\\theta)", "\\cdot ", "|\\cos(\\theta)|s^2" ) loose_sum.fix_in_frame() loose_sum.next_to(brace_text, DOWN, LARGE_BUFF) loose_sum.to_edge(RIGHT) prob_words = OldTexText("How likely is a given value of $\\theta$?", font_size=36) prob_words.fix_in_frame() prob_words.next_to(loose_sum[1], DOWN) prob_words.to_edge(RIGHT, buff=MED_SMALL_BUFF) finite_words = Text("If finite...") finite_words.next_to(brace_text, DOWN, LARGE_BUFF).fix_in_frame() self.add(finite_words) face.rotate(-angle_of_vector([*get_normal()[:2], 0])) face.shift(fc - normal_vect.get_start()) for d_theta in (*[-0.2] * 10, *[0.2] * 10): face.rotate(d_theta, np.cross(get_normal(), OUT), about_point=fc) self.wait(0.25) self.play( Write(loose_sum.get_part_by_tex("P(\\theta)")), FadeIn(prob_words, 0.5 * DOWN), FadeOut(finite_words), ApplyMethod(frame.set_x, 1, run_time=2) ) update_theta_ring(theta_ring) self.add(theta_ring, sphere) self.play( Rotate(face, TAU, OUT, about_point=fc, run_time=4), ShowCreation(theta_ring, run_time=4), ) theta_ring.add_updater(update_theta_ring) self.wait() self.play( FadeTransform(shadow_area[1].copy(), loose_sum.get_part_by_tex("cos")), Write(loose_sum.get_part_by_tex("\\cdot")), FadeOut(prob_words, 0.5 * DOWN) ) self.wait(2) self.play( Write(loose_sum[0], run_time=2), run_time=3, ) face.rotate(get_theta(), axis=np.cross(get_normal(), OUT), about_point=fc) for x in np.arange(0.2, PI, 0.2): face.rotate(0.2, UP, about_point=fc) self.wait(0.5) self.wait(5) # Continuous sum_brace = Brace(loose_sum[0], DOWN, buff=SMALL_BUFF) continuum = OldTexText("Continuum\\\\(uncountably infinite)", font_size=36) continuum.next_to(sum_brace, DOWN, SMALL_BUFF) zero = OldTex('0') zero.next_to(loose_sum[1], DOWN, buff=1.5) zero.shift(1.5 * RIGHT) zero_arrow = Arrow(loose_sum[1], zero, buff=SMALL_BUFF) nonsense_brace = Brace(loose_sum, UP) nonsense = nonsense_brace.get_text("Not really a sensible expression", font_size=36) for mob in [sum_brace, continuum, zero, zero_arrow, nonsense_brace, nonsense]: mob.fix_in_frame() mob.set_color(YELLOW) VGroup(nonsense_brace, nonsense).set_color(RED) face.start_time = self.time face.clear_updaters() face.add_updater(lambda f, dt: f.rotate( angle=0.25 * dt * math.cos(0.1 * (self.time - f.start_time)), axis=np.cross(get_normal(), OUT), about_point=fc, ).shift(fc - f[1].get_start())) self.play( GrowFromCenter(sum_brace), FadeIn(continuum, 0.5 * DOWN) ) self.wait(4) self.play( ShowCreation(zero_arrow), GrowFromPoint(zero, zero_arrow.get_start()), ) self.wait(2) inf_sum_group = VGroup( nonsense_brace, nonsense, sum_brace, continuum, zero_arrow, zero, loose_sum, ) top_part = inf_sum_group[:2] top_part.set_opacity(0) self.play( inf_sum_group.animate.to_corner(UR), FadeOut(VGroup(brace, brace_text, shadow_area[1])), run_time=2, ) top_part.set_fill(opacity=1) self.play( GrowFromCenter(nonsense_brace), Write(nonsense), ) self.wait(10) # Swap for an integral integral = OldTex( "\\int_0^\\pi ", "p(\\theta)", "\\cdot ", "|\\cos(\\theta)| s^2", "d\\theta", ) integral.shift(loose_sum[-1].get_right() - integral[-1].get_right()) integral.fix_in_frame() self.play(LaggedStart(*map(FadeOut, inf_sum_group[:-1]))) self.play( TransformMatchingShapes( loose_sum[0], integral[0], fade_transform_mismatches=True, ) ) self.play( FadeTransformPieces(loose_sum[1:4], integral[1:4]), Write(integral[4]) ) self.wait(5) face.clear_updaters() self.wait(5) # Show 2d slice back_half_sphere = Sphere(u_range=(0, PI)) back_half_sphere.match_color(sphere) back_half_sphere.set_opacity(sphere.get_opacity()) back_half_sphere.shift(fc) back_half_mesh = SurfaceMesh(back_half_sphere, resolution=(11, 11)) back_half_mesh.set_stroke(BLUE_D, 1, 0.75) circle = Circle() circle.set_stroke(TEAL, 1) circle.rotate(PI / 2, RIGHT) circle.move_to(fc) frame.clear_updaters() theta_ring.deactivate_depth_test() theta_ring.uniforms.pop("anti_alias_width") theta_ring.set_stroke(width=1) self.play( FadeOut(sphere), sphere_mesh.animate.set_stroke(opacity=0.25), FadeIn(circle), theta_ring.animate.set_stroke(width=1), frame.animate.reorient(-6, 87).set_height(4), integral.animate.set_height(0.5).set_opacity(0).to_corner(UR), run_time=2, ) self.remove(integral) # Finite sample def get_tick_marks(theta_samples, tl=0.05): return VGroup(*( Line((1 - tl / 2) * p, (1 + tl / 2) * p).shift(fc) for theta in theta_samples for p in [np.array([math.sin(theta), 0, math.cos(theta)])] )).set_stroke(YELLOW, 1) factor = 1 theta_samples = np.linspace(0, PI, factor * sphere_mesh.resolution[0]) dtheta = theta_samples[1] - theta_samples[0] tick_marks = get_tick_marks(theta_samples) def set_theta(face, theta): face.apply_matrix(rotation_between_vectors( normal_vect.get_vector(), OUT ), about_point=fc) face.rotate(theta, UP, about_point=fc) self.play( ShowIncreasingSubsets(tick_marks[:-1]), UpdateFromAlphaFunc( face, lambda f, a: set_theta(face, theta_samples[int(a * (len(theta_samples) - 2))]) ), run_time=4 ) self.add(tick_marks) self.wait(2) tsi = factor * 6 # theta sample index dt_line = Line(tick_marks[tsi].get_center(), tick_marks[tsi + 1].get_center()) dt_brace = Brace( Line(ORIGIN, RIGHT), UP ) dt_brace.scale(0.5) dt_brace.set_width(dt_line.get_length(), stretch=True) dt_brace.rotate(PI / 2, RIGHT) dt_brace.rotate(theta_samples[tsi], UP) dt_brace.move_to(dt_line) dt_brace.shift(SMALL_BUFF * normalize(dt_line.get_center() - fc)) dt_label = OldTex("\\Delta\\theta", font_size=24) dt_label.rotate(PI / 2, RIGHT) dt_label.next_to(dt_brace, OUT + RIGHT, buff=0.05) self.play( Write(dt_brace), Write(dt_label), run_time=1, ) sphere.set_opacity(0.1) self.play( frame.animate.reorient(10, 70), Rotate(face, -get_theta() + theta_samples[tsi], UP, about_point=fc), sphere_mesh.animate.set_stroke(opacity=0.5), FadeIn(sphere), run_time=3 ) frame.add_updater(update_frame) self.wait() # Latitude band def get_band(index): band = Sphere( u_range=(0, TAU), v_range=theta_samples[index:index + 2], prefered_creation_axis=1, ) band.set_color(YELLOW, 0.5) band.stretch(-1, 2, about_point=ORIGIN) band.shift(fc) return band band = get_band(tsi) self.add(band, sphere_mesh, sphere) self.play( ShowCreation(band), Rotate(face, dtheta, UP, about_point=fc), run_time=3, ) self.play(Rotate(face, -dtheta, UP, about_point=fc), run_time=3) self.wait(2) area_question = Text("Area of this band?") area_question.set_color(YELLOW) area_question.fix_in_frame() area_question.set_y(1.75) area_question.to_edge(RIGHT, buff=2.5) self.play(Write(area_question)) self.wait() random_points = [sphere.pfp(random.random()) - fc for x in range(30)] random_points.append(normal_vect.get_end() - fc) glow_dots = Group(*(TrueDot(p) for p in random_points)) for dot in glow_dots: dot.shift(fc) dot.set_radius(0.2) dot.set_color(BLUE) dot.set_glow_factor(2) theta_ring.suspend_updating() last_dot = VectorizedPoint() for dot in glow_dots: face.apply_matrix(rotation_between_vectors( get_normal(), dot.get_center() - fc, ), about_point=fc) self.add(dot) self.play(FadeOut(last_dot), run_time=0.25) last_dot = dot self.play(FadeOut(last_dot)) self.wait() # Find the area of the band frame.clear_updaters() self.play( frame.animate.reorient(-7.5, 78), sphere_mesh.animate.set_stroke(opacity=0.2), band.animate.set_opacity(0.2), ) one = OldTex("1", font_size=24) one.rotate(PI / 2, RIGHT) one.next_to(normal_vect.get_center(), IN + RIGHT, buff=0.05) radial_line = Line( [0, 0, normal_vect.get_end()[2]], normal_vect.get_end() ) radial_line.set_stroke(BLUE, 2) r_label = OldTex("r", font_size=20) sin_label = OldTex("\\sin(\\theta)", font_size=16) for label in r_label, sin_label: label.rotate(PI / 2, RIGHT) label.next_to(radial_line, OUT, buff=0.05) label.set_color(BLUE) label.set_backstroke() self.play(Write(one)) self.wait() self.play( TransformFromCopy(normal_vect, radial_line), FadeTransform(one.copy(), r_label) ) self.wait() self.play(FadeTransform(r_label, sin_label)) self.wait() band_area = OldTex("2\\pi \\sin(\\theta)", "\\Delta\\theta") band_area.next_to(area_question, DOWN, LARGE_BUFF) band_area.set_backstroke() band_area.fix_in_frame() circ_label, dt_copy = band_area circ_brace = Brace(circ_label, DOWN, buff=SMALL_BUFF) circ_words = circ_brace.get_text("Circumference") approx = OldTex("\\approx") approx.rotate(PI / 2) approx.move_to(midpoint(band_area.get_top(), area_question.get_bottom())) VGroup(circ_brace, circ_words, approx).set_backstroke().fix_in_frame() self.play( frame.animate.reorient(10, 60), ) theta_ring.update() self.play( ShowCreation(theta_ring), Rotate(face, TAU, OUT, about_point=fc), FadeIn(circ_label, 0.5 * DOWN, rate_func=squish_rate_func(smooth, 0, 0.5)), GrowFromCenter(circ_brace), Write(circ_words), run_time=3, ) self.wait() self.play(frame.animate.reorient(-5, 75)) self.play(FadeTransform(area_question[-1], approx)) area_question.remove(area_question[-1]) self.play(Write(dt_copy)) self.wait(3) # Probability of falling in band prob = OldTex( "P(\\text{Vector} \\text{ in } \\text{Band})", "=", "{2\\pi \\sin(\\theta) \\Delta\\theta", "\\over", " 4\\pi}", tex_to_color_map={ "\\text{Vector}": GREY_B, "\\text{Band}": YELLOW, } ) prob.fix_in_frame() prob.to_edge(RIGHT) prob.set_y(1) prob.set_backstroke() numer = prob.get_part_by_tex("\\sin") numer_rect = SurroundingRectangle(numer, buff=0.05) numer_rect.set_stroke(YELLOW, 1) numer_rect.fix_in_frame() area_question.generate_target() area_question.target.match_width(numer_rect) area_question.target.next_to(numer_rect, UP, SMALL_BUFF) denom_rect = SurroundingRectangle(prob.get_part_by_tex("4\\pi"), buff=0.05) denom_rect.set_stroke(BLUE, 2) denom_rect.fix_in_frame() denom_label = OldTexText("Surface area of\\\\a unit sphere") denom_label.scale(area_question.target[0].get_height() / denom_label[0][0].get_height()) denom_label.set_color(BLUE) denom_label.next_to(denom_rect, DOWN, SMALL_BUFF) denom_label.fix_in_frame() i = prob.index_of_part_by_tex("sin") self.play( FadeTransform(band_area, prob.get_part_by_tex("sin"), remover=True), MoveToTarget(area_question), FadeIn(prob[:i]), FadeIn(prob[i + 1:]), FadeIn(numer_rect), *map(FadeOut, [approx, circ_brace, circ_words]), frame.animate.set_x(1.5), ) self.add(prob) self.remove(band_area) self.wait() self.play( ShowCreation(denom_rect), FadeIn(denom_label, 0.5 * DOWN), ) sc = sphere.copy().flip(UP).scale(1.01).set_color(BLUE, 0.5) self.add(sc, sphere_mesh) self.play(ShowCreation(sc), run_time=3) self.play(FadeOut(sc)) self.wait() # Expression for average sphere_group = Group( sphere, sphere_mesh, theta_ring, band, circle, radial_line, sin_label, one, tick_marks, dt_brace, dt_label, ) average_eq = OldTex( "\\text{Average shadow} \\\\", "\\sum_{\\theta}", "{2\\pi", "\\sin(\\theta)", " \\Delta\\theta", "\\over", " 4\\pi}", "\\cdot", "|\\cos(\\theta)|", "s^2" ) average_eq.fix_in_frame() average_eq.move_to(prob).to_edge(UP) average_eq[0].scale(1.25) average_eq[0].shift(MED_SMALL_BUFF * UP) average_eq[0].match_x(average_eq[1:]) new_prob = average_eq[2:7] prob_rect = SurroundingRectangle(new_prob) prob_rect.set_stroke(YELLOW, 2) prob_rect.fix_in_frame() self.play( FadeIn(average_eq[:1]), FadeIn(prob_rect), prob[:5].animate.match_width(prob_rect).next_to(prob_rect, DOWN, buff=0.15), FadeTransform(prob[-3:], new_prob), *map(FadeOut, [prob[5], numer_rect, denom_rect, area_question, denom_label]) ) self.wait() self.play( FadeOut(sphere_group), FadeIn(average_eq[-3:]), UpdateFromAlphaFunc(face, lambda f, a: f[0].set_fill(opacity=0.5 * a)) ) self.wait() band.set_opacity(0.5) bands = Group(*(get_band(i) for i in range(len(theta_samples) - 1))) sphere_mesh.set_stroke(opacity=0.5) self.add(sphere_mesh, sphere, bands) self.play( FadeIn(average_eq[1]), UpdateFromAlphaFunc(face, lambda f, a: f[0].set_fill(opacity=0.5 * (1 - a))), FadeIn(sphere), FadeIn(tick_marks), FadeIn(sphere_mesh), LaggedStartMap( FadeIn, bands, rate_func=there_and_back, lag_ratio=0.5, run_time=8, remover=True ), ) # Simplify average2 = OldTex( "{2\\pi", "\\over", "4\\pi}", "s^2", "\\sum_{\\theta}", "\\sin(\\theta)", "\\Delta\\theta", "\\cdot", "|\\cos(\\theta)|" ) average2.fix_in_frame() average2.move_to(average_eq[1:], RIGHT) half = OldTex("1 \\over 2") pre_half = average2[:3] half.move_to(pre_half, RIGHT) half_rect = SurroundingRectangle(pre_half, buff=SMALL_BUFF) half_rect.set_stroke(RED, 1) VGroup(half, half_rect).fix_in_frame() self.play( FadeOut(prob_rect), FadeOut(prob[:5]), *( FadeTransform(average_eq[i], average2[j], path_arc=10 * DEGREES) for i, j in [ (1, 4), (2, 0), (3, 5), (4, 6), (5, 1), (6, 2), (7, 7), (8, 8), (9, 3), ] ), run_time=2, ) self.play(ShowCreation(half_rect)) self.play( FadeTransform(pre_half, half), FadeOut(half_rect), ) sin, dt, dot, cos = average2[5:] tail = VGroup(cos, dot, sin, dt) tail.generate_target() tail.target.arrange(RIGHT, buff=SMALL_BUFF) tail.target.move_to(tail, LEFT) tail.target[-1].align_to(sin[0], DOWN) self.play( MoveToTarget(tail, path_arc=PI / 2), ) self.wait(2) integral = OldTex("\\int_0^\\pi ") integral.next_to(tail, LEFT, SMALL_BUFF) integral.fix_in_frame() dtheta = OldTex("d\\theta").fix_in_frame() dtheta.move_to(tail[-1], LEFT) average_copy = VGroup(half, average2[3:]).copy() average_copy.set_backstroke() self.play( VGroup(half, average2[3]).animate.next_to(integral, LEFT, SMALL_BUFF), FadeTransform(average2[4], integral), FadeTransform(tail[-1], dtheta), average_copy.animate.shift(2.5 * DOWN), frame.animate.set_phi(80 * DEGREES), ) self.wait() self.play(LaggedStart( ShowCreationThenFadeOut(SurroundingRectangle(average_copy[1][-3]).fix_in_frame()), ShowCreationThenFadeOut(SurroundingRectangle(dtheta).fix_in_frame()), lag_ratio=0.5 )) self.wait() # The limit brace = Brace(average_copy, UP, buff=SMALL_BUFF) brace_text = brace.get_text( "What does this approach for finer subdivisions?", font_size=30 ) arrow = Arrow(integral.get_bottom(), brace_text) VGroup(brace, brace_text, arrow).set_color(YELLOW).fix_in_frame() brace_text.set_backstroke() self.play( GrowFromCenter(brace), ShowCreation(arrow), FadeIn(brace_text, lag_ratio=0.1) ) for n in range(1, 4): new_ticks = get_tick_marks( np.linspace(0, PI, sphere_mesh.resolution[0] * 2**n), tl=0.05 / n ) self.play( ShowCreation(new_ticks), FadeOut(tick_marks), run_time=2, ) self.wait() tick_marks = new_ticks # Make room for computation face[0].set_fill(BLUE_D, opacity=0.75) face[0].set_stroke(WHITE, 0.5, 1) rect = Rectangle(fill_color=BLACK, fill_opacity=1, stroke_width=0) rect.replace(self.plane, stretch=True) rect.stretch(4 / 12, dim=0, about_edge=RIGHT) rect.scale(1.01) top_line = VGroup(half, average2[3], integral, tail[:-1], dtheta) self.add(face[0], sphere) self.play( LaggedStart(*map(FadeOut, [arrow, brace_text, brace, average_copy])), # UpdateFromAlphaFunc(face, lambda f, a: f[0].set_fill(opacity=0.5 * a)), GrowFromCenter(face[0], remover=True), frame.animate.set_height(6).set_x(3.5), FadeIn(rect), FadeOut(tick_marks), top_line.animate.set_width(4).to_edge(UP).to_edge(RIGHT, buff=LARGE_BUFF), FadeOut(average_eq[0], UP), run_time=2, ) self.add(face, sphere) self.begin_ambient_rotation(face, about_point=fc, speed=0.1) # Computation new_lines = VGroup( OldTex("{1 \\over 2} s^2 \\cdot 2 \\int_0^{\\pi / 2} \\cos(\\theta)\\sin(\\theta)\\,d\\theta"), OldTex("{1 \\over 2} s^2 \\cdot \\int_0^{\\pi / 2} \\sin(2\\theta)\\,d\\theta"), OldTex("{1 \\over 2} s^2 \\cdot \\left[ -\\frac{1}{2} \\cos(2\\theta) \\right]_0^{\\pi / 2}"), OldTex("{1 \\over 2} s^2 \\cdot \\left(-\\left(-\\frac{1}{2}\\right) - \\left(-\\frac{1}{2}\\right)\\right)"), OldTex("{1 \\over 2} s^2"), ) new_lines.scale(top_line.get_height() / new_lines[0].get_height()) kw = {"buff": 0.35, "aligned_edge": LEFT} new_lines.arrange(DOWN, **kw) new_lines.next_to(top_line, DOWN, **kw) new_lines.fix_in_frame() annotations = VGroup( OldTexText("To avoid the annoying absolute value, just\\\\cover the northern hemisphere and double it."), OldTexText("Trig identity: $\\sin(2\\theta) = 2\\cos(\\theta)\\sin(\\theta)$"), OldTexText("Antiderivative"), OldTexText("Try not to get lost in\\\\the sea of negatives..."), OldTexText("Whoa, that turned out nice!"), ) annotations.fix_in_frame() annotations.set_color(YELLOW) annotations.scale(0.5) rect = SurroundingRectangle(new_lines[-1], buff=SMALL_BUFF) rect.set_stroke(YELLOW, 2).fix_in_frame() for note, line in zip(annotations, new_lines): note.next_to(line, LEFT, MED_LARGE_BUFF) self.play( LaggedStartMap(FadeIn, new_lines, lag_ratio=0.7), LaggedStartMap(FadeIn, annotations, lag_ratio=0.7), run_time=5, ) self.wait(20) self.play( new_lines[:-1].animate.set_opacity(0.5), annotations[:-1].animate.set_opacity(0.5), ShowCreation(rect), ) self.wait(10) def get_solid(self): face = Square(side_length=2) face.set_fill(BLUE, 0.5) face.set_stroke(width=0) normal = Vector(OUT) normal.shift(2e-2 * OUT) face = VGroup(face, normal) face.set_stroke(background=True) face.apply_depth_test() return face class AskAboutAverageCosValue(AllPossibleOrientations): def construct(self): self.remove(self.solid) self.remove(self.shadow) frame = self.camera.frame frame.set_height(5) frame.reorient(-5, 80) frame.shift(2 * RIGHT) self.init_frame_rotation() # Copy pasting from above...not great fc = 3 * OUT sphere = Sphere(radius=1) sphere.set_color(GREY_E, 0.25) sphere.move_to(fc) sphere.always_sort_to_camera(self.camera) sphere_mesh = SurfaceMesh(sphere, resolution=(21, 11)) sphere_mesh.set_stroke(BLUE_E, 1, 0.5) for sm in sphere_mesh.get_family(): sm.uniforms["anti_alias_width"] = 0 self.add(sphere, sphere_mesh) normal_vect = Arrow(sphere.get_center(), sphere.pfp(0.2), buff=0) def randomly_place_vect(): theta = random.uniform(0.1, PI - 0.1) phi = random.uniform(-PI / 4, PI / 4) + random.choice([0, PI]) point = fc + np.array([ math.sin(theta) * math.cos(phi), math.sin(theta) * math.sin(phi), math.cos(theta), ]) normal_vect.put_start_and_end_on(sphere.get_center(), point) def get_normal(): return normal_vect.get_vector() def get_theta(): return np.arccos(get_normal()[2] / get_norm(get_normal())) def get_arc(): result = Arc(PI / 2, -get_theta(), radius=0.25) result.rotate(PI / 2, RIGHT, about_point=ORIGIN) result.rotate(angle_of_vector([*get_normal()[:2], 0]), OUT, about_point=ORIGIN) result.shift(fc) result.set_stroke(WHITE, 1) result.apply_depth_test() return result arc = always_redraw(get_arc) theta = OldTex("\\theta", font_size=20) theta.rotate(PI / 2, RIGHT) theta.set_backstroke(width=2) theta.add_updater(lambda m: m.next_to( arc.pfp(0.5), arc.pfp(0.5) - fc, buff=0.05) ) z_axis = Line(ORIGIN, 10 * OUT) z_axis.set_stroke(WHITE, 1) z_axis.apply_depth_test() self.add(z_axis, normal_vect, arc, theta) self.add(sphere_mesh, sphere) # Show random samples question = OldTexText("What's the mean?") question.to_corner(UR) question.to_edge(UP, buff=MED_SMALL_BUFF) question.fix_in_frame() arrow = Arrow(question, question.get_center() + DOWN) arrow.fix_in_frame() values = VGroup() lhss = VGroup() self.add(question, arrow) for n in range(15): randomly_place_vect() lhs = OldTex("|\\cos(\\theta_{" + str(n + 1) + "})| = ", font_size=30) value = DecimalNumber(abs(math.cos(get_theta())), font_size=30) value.next_to(values, DOWN) for mob in lhs, value: mob.fix_in_frame() mob.set_backstroke() values.add(value) values.next_to(arrow, DOWN) lhs.next_to(value, LEFT, buff=SMALL_BUFF) lhss.add(lhs) self.add(values, lhss) self.wait(0.5) class ThreeCamps(TeacherStudentsScene): def construct(self): self.remove(self.background) # Setup teacher = self.teacher students = self.students image = ImageMobject("Shadows_Integral_Intro") image.center().set_height(FRAME_HEIGHT) image.generate_target() image.target.replace(self.screen) self.screen.set_stroke(WHITE, 1) self.screen.save_state() self.screen.replace(image).set_stroke(width=0) self.play( LaggedStart(*( student.change("pondering", image.target) for student in students ), run_time=2, lag_ratio=0.2), teacher.change("tease") ) self.wait() # Reactions phrases = [ Text("How fun!", font_size=40), Text("Wait, what?", font_size=40), Text("Okay give\nme a sec...", font_size=35), ] modes = ["hooray", "erm", "confused"] heights = np.linspace(2.0, 2.5, 3) for student, phrase, mode, height in zip(reversed(students), phrases, modes, heights): self.play( PiCreatureSays( student, phrase, target_mode=mode, look_at=image, bubble_config={ "direction": LEFT, "width": 3, "height": height, }, bubble_type=ThoughtBubble, run_time=2 ) ) self.wait(4) # Let's go over the definition integral = OldTex("\\int_0^\\pi \\dots d\\theta") integral.move_to(self.hold_up_spot, DOWN) brace = Brace(integral, UP) words = OldTexText("Let's go over the definition", font_size=36) words.next_to(brace, UP, SMALL_BUFF) words2 = OldTexText("It can't hurt, right?", font_size=36) words2.move_to(words) VGroup(brace, words, words2).set_color(YELLOW) self.play( LaggedStart(*( FadeOut(VGroup(student.bubble, student.bubble.content)) for student in reversed(students) )), LaggedStart(*( student.change("pondering", integral) for student in students )), FadeIn(integral, UP), teacher.change("raise_right_hand", integral), ) self.play( GrowFromCenter(brace), Write(words) ) self.wait(2) self.play( words.animate.shift(0.75 * UP).set_opacity(0.5), FadeIn(words2, 0.2 * UP), LaggedStart( self.teacher.change("shruggie"), self.students[0].change("sassy", words2), self.students[1].change("thinking", words2), self.students[2].change("well", words2), ) ) self.wait(2) self.play(self.teacher.change("speaking", words2)) self.wait(3) class ParticularValuesUnhelpfulOverlay(Scene): def construct(self): # Particular value expr = OldTex("P(\\theta =", "\\pi / 4", ")", "=", "0") expr.set_color_by_tex("\\pi / 4", YELLOW) brace = Brace(expr.get_part_by_tex("\\pi / 4"), UP, buff=SMALL_BUFF) brace.stretch(0.5, 1, about_edge=DOWN) words = Text("Some specific value", font_size=24) words.next_to(brace, UP, SMALL_BUFF) VGroup(brace, words).set_color(YELLOW) VGroup(expr, brace, words).to_corner(UR) self.play(FadeIn(expr, lag_ratio=1)) self.play( GrowFromCenter(brace), FadeIn(words, shift=0.2 * UP), ) self.wait() # Unhelpful question = OldTexText("What are you going\\\\to do with that?", font_size=24) question.next_to(expr, DOWN, LARGE_BUFF) arrow = Arrow(question, expr.get_part_by_tex("0"), buff=SMALL_BUFF) self.play( FadeIn(question), ShowCreation(arrow), ) self.wait() # New expr range_expr = OldTex( "P(\\pi / 4 < \\theta < \\pi / 4 + \\Delta\\theta) > 0", tex_to_color_map={ "\\pi / 4": YELLOW, "\\Delta\\theta": GREY_A, }, font_size=40 ) range_expr.move_to(expr, RIGHT) new_brace = Brace(range_expr.slice_by_tex("\\pi / 4", ")"), UP, buff=SMALL_BUFF) new_words = Text("Range of values", font_size=24) new_words.next_to(new_brace, UP, SMALL_BUFF) VGroup(new_brace, new_words).set_color(YELLOW) self.play( FadeOut(question), FadeOut(arrow), TransformMatchingShapes(expr, range_expr), FadeTransform(brace, new_brace), FadeTransform(words, new_words), ) self.wait() class SurfaceAreaOfSphere(Scene): def construct(self): sphere = Sphere(radius=3) sphere.set_color(BLUE_E, 1) sphere.always_sort_to_camera(self.camera) sphere.rotate(5 * DEGREES, OUT) sphere.rotate(80 * DEGREES, LEFT) sphere.move_to(0.5 * DOWN) sphere_mesh = SurfaceMesh(sphere) sphere_mesh.set_stroke(WHITE, 0.5, 0.5) equation = OldTex( "\\text{Surface area} = 4\\pi R^2", tex_to_color_map={ "R": YELLOW, "\\text{Surface area}": BLUE, }, ) equation.to_edge(UP) self.add(equation, sphere, sphere_mesh) self.play( Write(sphere_mesh, lag_ratio=0.02, stroke_width=1), ShowCreation(sphere, rate_func=squish_rate_func(smooth, 0.25, 1)), run_time=5, ) self.wait() class IntegralOverlay(Scene): def construct(self): integral = OldTex("\\int_0^\\pi") integral.set_color(YELLOW) self.play(Write(integral, run_time=2)) self.play(integral.animate.set_color(WHITE)) self.play(LaggedStart(*( FlashAround(sm, time_width=3) for sm in integral[0][:0:-1] ), lag_ratio=0.5, run_time=3)) self.wait() class AlicesInsights(Scene): def construct(self): title = OldTexText("Alice's insights", font_size=72) title.to_edge(UP) title.set_backstroke() underline = Underline(title, buff=-0.05) underline.scale(1.5) underline.insert_n_curves(50) underline.set_stroke(WHITE, width=[0, *4 * [3], 0], opacity=1) self.add(underline, title) kw = dict( t2c={ "double cover": YELLOW, "mean": RED, "means": RED, "sum": BLUE, "Sum": BLUE, "Average": RED, } ) insights = VGroup( Text("1. The face shadows double cover the cube shadow", **kw), # Text("2. The mean of the sum is the sum of the means", **kw), Text("2. Average(Sum(Face shadows)) = Sum(Average(Face shadow))", **kw), Text("3. Use a sphere to deduce the unknown constant", **kw), ) insights.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) insights.next_to(underline, DOWN, LARGE_BUFF) insights.to_edge(LEFT) self.play(LaggedStart(*( FadeIn(insight[:2], 0.25 * DOWN) for insight in insights ))) self.wait() for insight in insights: self.play(FadeIn(insight[2:], lag_ratio=0.1)) self.wait() class HalfBathedInLight(ShadowScene): def construct(self): frame = self.camera.frame frame.set_height(12) frame.add_updater(lambda m, dt: m.increment_theta(0.05 * dt)) cube = self.solid light = self.light light.next_to(cube, OUT, 2) self.add(light) self.remove(self.plane) self.shadow.add_updater(lambda m: m.set_opacity(0)) cube.move_to(OUT) cube.set_opacity(0.95) cube.rotate(PI / 2, DL) # cube.add_updater(lambda m: self.sort_to_camera(cube)) cube.update() cube.clear_updaters() light_lines = self.get_light_lines() light_lines.add_updater(lambda m: m.set_stroke(YELLOW, 2)) self.add(light_lines, light) self.wait(2) for s, color in zip([slice(3, None), slice(0, 3)], [WHITE, GREY_D]): cube.generate_target() sorted_cube = Group(*cube.target) sorted_cube.sort(lambda p: p[2]) sorted_cube[s].space_out_submobjects(2) sorted_cube[s].set_color(color) self.play( MoveToTarget(cube), rate_func=there_and_back_with_pause, run_time=3, ) self.wait(5) # Embed self.embed() class TwoToOneCover(ShadowScene): inf_light = True plane_dims = (20, 12) limited_plane_extension = 8 highlighted_face_color = YELLOW def construct(self): # Setup frame = self.camera.frame frame.reorient(-20, 75) frame.set_z(3) self.init_frame_rotation() cube = self.solid for face in cube: face.set_fill(opacity=0.9) face.set_reflectiveness(0.1) face.set_gloss(0.2) cube.add_updater(lambda m: self.sort_to_camera(m)) cube.rotate(PI / 3, normalize([3, 4, 5])) shadow = self.shadow outline = self.get_shadow_outline() # Inequality ineq = self.get_top_expression("$<$") ineq.fix_in_frame() lhs = ineq.slice_by_tex(None, "<") lt = ineq.get_part_by_tex("<") rhs = ineq.slice_by_tex("sum", None) af_label = ineq[-7:] lhs.save_state() lhs.set_x(0) # Shadow of the cube wireframe = cube.copy() for face in wireframe: face.set_fill(opacity=0) face.set_stroke(WHITE, 1) wireframe_shadow = wireframe.copy() wireframe_shadow.apply_function(flat_project) wireframe_shadow.set_gloss(0) wireframe_shadow.set_reflectiveness(0) wireframe_shadow.set_shadow(0) for face in wireframe_shadow: face.set_stroke(GREY_D, 1) self.play( ShowCreation(wireframe, lag_ratio=0.1), Write(lhs[2:-1]) ) self.play(TransformFromCopy(wireframe, wireframe_shadow)) self.play(*map(FadeOut, (wireframe, wireframe_shadow))) self.wait() self.play( FadeIn(lhs[:2]), FadeIn(lhs[-1]), Write(outline), VShowPassingFlash( outline.copy().set_stroke(YELLOW, 4), time_width=1.5 ), ) self.wait() # Show faces and shadows cube.save_state() faces, face_shadows = self.get_faces_and_face_shadows() faces[:3].set_opacity(0.1) face_shadow_lines = VGroup(*( VGroup(*( Line(v1, v2) for v1, v2 in zip(f.get_vertices(), fs.get_vertices()) )) for f, fs in zip(faces, face_shadows) )) face_shadow_lines.set_stroke(YELLOW, 0.5, 0.5) self.play( Restore(lhs), FadeIn(af_label, shift=0.5 * RIGHT) ) self.play( *( LaggedStart(*( VFadeInThenOut(sm) for sm in reversed(mobject) ), lag_ratio=0.5, run_time=6) for mobject in [faces, face_shadows, face_shadow_lines] ), ) self.play( ApplyMethod(cube.space_out_submobjects, 1.7, rate_func=there_and_back_with_pause, run_time=8), ApplyMethod(frame.reorient, 20, run_time=8), Write(lt), Write(rhs[0]), ) self.wait(2) # Show a given pair of faces face_pair = Group(faces[3], faces[5]).copy() face_pair[1].set_color(RED) face_pair.save_state() fp_shadow = get_shadow(face_pair) self.add(fp_shadow) self.play( FadeOut(cube), *map(VFadeOut, shadow), FadeOut(outline), *map(Write, face_pair), ) self.wait(1) self.play(Rotate( face_pair, PI / 2, DOWN, about_point=cube.get_center(), run_time=3, )) self.wait() self.random_toss(face_pair, about_point=cube.get_center(), run_time=6) fp_shadow.clear_updaters() self.play( FadeIn(cube), *map(VFadeIn, shadow), FadeOut(face_pair, scale=0), FadeOut(fp_shadow, scale=0), ) self.add(shadow) # Half of sum new_expression = self.get_top_expression(" = ", "$\\displaystyle \\frac{1}{2}$") new_expression.fix_in_frame() eq_half = VGroup( new_expression.get_part_by_tex("="), new_expression.get_part_by_tex("frac"), ) cube.save_state() cube.generate_target(use_deepcopy=True) cube.target.clear_updaters() z_sorted_faces = Group(*sorted(list(cube.target), key=lambda f: f.get_z())) z_sorted_faces[:3].shift(2 * LEFT) z_sorted_faces[3:].shift(2 * RIGHT) cube.clear_updaters() self.play( MoveToTarget(cube), ApplyMethod(frame.reorient, 0, run_time=2) ) self.play( FadeOut(lt, UP), Write(eq_half), ReplacementTransform(rhs, new_expression[-len(rhs):]), ReplacementTransform(lhs, new_expression[:len(lhs)]), ) self.remove(ineq) self.add(new_expression) self.wait(2) anims = [] for part in z_sorted_faces: pc = part.copy() pc.set_fill(YELLOW, 0.25) pc_shadow = get_shadow(pc) pc_shadow.clear_updaters() pc_shadow.match_style(pc) lines = VGroup(*( Line(v, flat_project(v)) for v in pc.get_vertices() )) lines.set_stroke(YELLOW, 1, 0.1) anims.append(AnimationGroup( VFadeInThenOut(pc), VFadeInThenOut(pc_shadow), VFadeInThenOut(lines), )) self.play(LaggedStart(*anims, lag_ratio=0.4, run_time=6)) self.play(Restore(cube)) # Show the double cover shadow_point = shadow.get_bottom() + [0.5, 0.75, 0] dot = GlowDot(shadow_point) line = DashedLine( shadow_point + 5 * OUT, shadow_point, dash_length=0.025 ) line.set_stroke(YELLOW, 1) def update_line(line): line.move_to(dot.get_center(), IN) for dash in line: dist = cube_sdf(dash.get_center(), cube) dash.set_stroke( opacity=interpolate(0.1, 1.0, clip(10 * dist, -0.5, 0.5) + 0.5) ) dash.inside = (dist < 0) line.add_updater(update_line) entry_point = next(dash for dash in line if dash.inside).get_center() exit_point = next(dash for dash in reversed(line) if dash.inside).get_center() arrows = VGroup(*( Arrow(point + RIGHT, point, buff=0.1) for point in (entry_point, exit_point) )) self.play(ShowCreation(line, rate_func=rush_into)) self.play(FadeIn(dot, scale=10, rate_func=rush_from, run_time=0.5)) self.wait() self.play( Rotate( dot, TAU, about_point=ORIGIN, run_time=6, ), ) self.wait() for arrow in arrows: self.play(ShowCreation(arrow)) self.wait() self.play(FadeOut(arrows)) cube.add_updater(lambda m: self.sort_to_camera(m)) self.random_toss(cube, angle=1.5 * TAU, run_time=8) # Just show wireframe cube.save_state() cube.generate_target() for sm in cube.target: sm.set_fill(opacity=0) sm.set_stroke(WHITE, 2) outline = self.get_shadow_outline() outline.rotate(PI) self.play( MoveToTarget(cube), dot.animate.move_to(outline.get_start()) ) self.play(MoveAlongPath(dot, outline, run_time=8)) self.wait(2) self.play(Restore(cube)) self.play(dot.animate.move_to(outline.get_center()), run_time=2) # Make room for equation animations # Start here for new scene area_label = self.get_shadow_area_label() area_label.shift(1.75 * DOWN + 2.25 * RIGHT) area_label[0].scale(0, about_edge=RIGHT) area_label.scale(0.7) outline.update() line.clear_updaters() self.play( FadeOut(dot), FadeOut(line), ShowCreation(outline), VFadeIn(area_label), ) # Single out a face self.remove(new_expression) self.wait(2) face = cube[np.argmax([f.get_z() for f in cube])].copy() face.set_color(YELLOW) face_shadow = get_shadow(face) face_shadow_area = DecimalNumber(get_norm(face_shadow.get_area_vector()) / (self.unit_size**2)) face_shadow_area.scale(0.65) face_shadow_area.move_to(area_label) face_shadow_area.shift(flat_project(face.get_center() - cube.get_center())) face_shadow_area.shift(SMALL_BUFF * UR) face_shadow_area.fix_in_frame() cube.save_state() self.remove(cube) self.play( *( f.animate.set_fill(opacity=0) for f in cube ), FadeOut(outline), FadeOut(area_label), Write(face), FadeIn(face_shadow), FadeIn(face_shadow_area), ) self.wait(2) self.play( Restore(cube), *map(FadeOut, (face, face_shadow, face_shadow_area)), *map(FadeIn, (outline, area_label)), ) # Show simple rotations for x in range(2): self.random_toss(cube) self.wait() self.wait() # Many random orientations for x in range(40): self.randomly_reorient(cube) self.wait(0.25) # Show sum of faces again (play 78) self.random_toss(cube, 2 * TAU, run_time=8, meta_speed=10) self.wait() cube.save_state() sff = 1.5 self.play( VFadeOut(outline), VFadeOut(area_label), cube.animate.space_out_submobjects(sff) ) for x in range(3): self.random_toss(cube, angle=PI) self.wait() self.play(cube.animate.space_out_submobjects(1 / sff)) # Mean shadow of a single face cube_style = cube[0].get_style() def isolate_face_anims(i, color=YELLOW): return ( shadow.animate.set_fill( interpolate_color(color, BLACK, 0.75) ), *( f.animate.set_fill( color if f is cube[i] else BLUE, 0.75 if f is cube[i] else 0, ) for f in cube ) ) def tour_orientations(): self.random_toss(cube, 2 * TAU, run_time=5, meta_speed=10) self.play(*isolate_face_anims(5)) tour_orientations() for i, color in ((4, GREEN), (3, RED)): self.play( *isolate_face_anims(i, color), ) tour_orientations() cube.update() self.play( *( f.animate.set_style(**cube_style) for f in cube ), shadow.animate.set_fill(interpolate_color(BLUE, BLACK, 0.85)), VFadeIn(outline), VFadeIn(area_label), ) self.add(cube) # Ambient rotation self.add(cube) self.begin_ambient_rotation(cube, speed=0.4) self.wait(20) def get_top_expression(self, *mid_tex, n_faces=6): t2c = { "Shadow": GREY_B, "Cube": BLUE_D, "Face$_j$": YELLOW, } ineq = OldTexText( "Area(Shadow(Cube))", *mid_tex, " $\\displaystyle \\sum_{j=1}^" + f"{{{n_faces}}}" + "$ ", "Area(Shadow(Face$_j$))", tex_to_color_map=t2c, isolate=["(", ")"], ) ineq.to_edge(UP, buff=MED_SMALL_BUFF) return ineq def get_faces_and_face_shadows(self): faces = self.solid.deepcopy() VGroup(*faces).set_fill(self.highlighted_face_color) shadows = get_pre_shadow(faces, opacity=0.7) shadows.apply_function(flat_project) return faces, shadows class ConvexityPrelude(Scene): def construct(self): square = Square(side_length=3) square.rotate(-PI / 4) square.flip() square.set_stroke(BLUE, 2) points = [square.pfp(1 / 8), square.pfp(7 / 8)] beam = VGroup( Line(points[0] + 3 * UP, points[0], stroke_width=3), Line(points[0], points[1], stroke_width=2), Line(points[1], points[1] + 3 * DOWN, stroke_width=1), ) beam.set_stroke(YELLOW) words = OldTexText("2 intersections\\\\", "(almost always)") words[1].scale(0.7, about_edge=UP).set_color(GREY_B) words.to_edge(LEFT) arrows = VGroup(*( Arrow(words[0].get_right(), point) for point in points )) dots = GlowDot() dots.set_points(points) dots.set_color(WHITE) dots.set_radius(0.2) dots.set_glow_factor(3) self.add(square) self.add(words) self.play( ShowCreation(beam), FadeIn(arrows, lag_ratio=0.7), FadeIn(dots, lag_ratio=0.7), ) self.wait() question1 = Text("Why is this true?") question2 = Text("Is this true for all shapes?") question2.next_to(question1, DOWN, aligned_edge=LEFT) VGroup(question1, question2).to_corner(UR) self.play(Write(question1, run_time=1)) self.wait() self.play(FadeIn(question2, 0.25 * DOWN)) self.wait() # Convexity square.generate_target() convex_shapes = VGroup( square.target, RegularPolygon(5, color=TEAL), Rectangle(2, 1, color=TEAL_E), RegularPolygon(6, color=GREEN), Circle(color=GREEN_B), ) convex_shapes[2].apply_matrix([[1, 0.5], [0, 1]]) convex_shapes[3].shift(2 * RIGHT).apply_complex_function(np.exp) convex_shapes[3].make_jagged() for shape in convex_shapes: shape.set_height(1) shape.set_stroke(width=2) convex_shapes.arrange(DOWN) convex_shapes.set_height(6) v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) h_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) h_line.set_y(3) VGroup(v_line, h_line).set_stroke(WHITE, 2) convex_title = Text("Convex") non_convex_title = Text("Non-convex") for title, vect in zip([convex_title, non_convex_title], [LEFT, RIGHT]): title.scale(1.5) title.next_to(h_line, UP) title.shift(vect * FRAME_WIDTH / 4) convex_shapes.next_to(h_line, DOWN) convex_shapes.match_x(convex_title) self.play( MoveToTarget(square), FadeIn(convex_shapes[1:], lag_ratio=0.5), FadeTransform(beam, v_line), ShowCreation(h_line), FadeIn(convex_title), LaggedStart(*map(FadeOut, ( dots, arrows, words, question1, question2, ))), ) self.wait() # Non-convex shapes pi = OldTex("\\pi").family_members_with_points()[0] pent = RegularPolygon(5) pent.set_points_as_corners([ORIGIN, *pent.get_vertices()[1:], ORIGIN]) n_mob = OldTex("N").family_members_with_points()[0] nc_shapes = VGroup(pi, pent, n_mob) nc_shapes.set_fill(opacity=0) nc_shapes.set_stroke(width=2) nc_shapes.set_submobject_colors_by_gradient(RED, PINK) for shape in nc_shapes: shape.set_height(1) nc_shapes.arrange(DOWN) nc_shapes.replace(convex_shapes, dim_to_match=1) nc_shapes.match_x(non_convex_title) self.play( Write(non_convex_title, run_time=1), LaggedStartMap(FadeIn, nc_shapes), ) self.wait() # Embed self.embed() class DefineConvexity(Scene): def construct(self): # Shape definition = "A set is convex if the line connecting any\n"\ "two points within it is contained in the set" set_color = BLUE line_color = GREEN title = Text( definition, t2c={ "convex": set_color, "line connecting any\ntwo points": line_color, }, t2s={"convex": ITALIC}, ) title.to_edge(UP) title.set_opacity(0.2) shape = Square(4.5) shape.set_fill(set_color, 0.25) shape.set_stroke(set_color, 2) shape.next_to(title, DOWN, LARGE_BUFF) self.add(title) self.play( title.get_part_by_text("A set is convex").animate.set_opacity(1), Write(shape) ) self.wait() # Show two points line = Line(shape.pfp(0.1), shape.pfp(0.5)) line.scale(0.7) line.set_stroke(line_color, 2) dots = DotCloud(line.get_start_and_end()) dots.set_color(line_color) dots.make_3d(0.5) dots.save_state() dots.set_radius(0) dots.set_opacity(0) self.play( title[definition.index("if"):definition.index("is", 16)].animate.set_opacity(1), Restore(dots), ) self.play(ShowCreation(line)) self.wait() self.play( title[definition.index("is", 16):].animate.set_opacity(1), ) # Alternate places dots.add_updater(lambda m: m.set_points(line.get_start_and_end())) def show_sample_lines(n=5): for x in range(5): self.play( line.animate.put_start_and_end_on( shape.pfp(random.random()), shape.pfp(random.random()), ).scale(random.random(), about_point=shape.get_center()) ) self.wait(0.5) show_sample_lines() # Letter π def tex_to_shape(tex): result = OldTex(tex).family_members_with_points()[0] result.match_style(shape) result.match_height(shape) result.move_to(shape) result_points = result.get_points().copy() index = np.argmax([np.dot(p, UR) for p in result_points]) index = 3 * (index // 3) result.set_points([*result_points[index:], *result_points[:index]]) return result pi = tex_to_shape("\\pi") letter_c = tex_to_shape("\\textbf{C}") letter_c.insert_n_curves(50) line.generate_target() line.target.put_start_and_end_on(*( pi.get_boundary_point(v) for v in (DL, DR) )) line.target.scale(0.9) not_convex_label = Text("Not convex!", color=RED) not_convex_label.next_to(pi, LEFT) shape.insert_n_curves(100) self.play( Transform(shape, pi, path_arc=PI / 2), MoveToTarget(line), run_time=2, ) self.play( FadeIn(not_convex_label, scale=2) ) self.wait() shape.insert_n_curves(80) self.play( Transform(shape, letter_c), line.animate.put_start_and_end_on(*( letter_c.pfp(a) for a in (0, 0.5) )), run_time=2, ) self.play(UpdateFromAlphaFunc( line, lambda l, a: l.put_start_and_end_on( letter_c.pfp(0.4 * a), l.get_end() ), run_time=6, )) self.wait() # Polygon convex_label = OldTexText("Convex \\ding{51}") convex_label.set_color(YELLOW) convex_label.move_to(not_convex_label) polygon = RegularPolygon(7) polygon.match_height(shape) polygon.move_to(shape) polygon.match_style(shape) self.remove(not_convex_label) self.play( FadeTransform(shape, polygon), line.animate.put_start_and_end_on( polygon.get_vertices()[1], polygon.get_vertices()[-1], ), TransformMatchingShapes(not_convex_label.copy(), convex_label), run_time=2 ) self.wait() polygon.generate_target() new_tip = 2 * line.get_center() - polygon.get_start() polygon.target.set_points_as_corners([ new_tip, *polygon.get_vertices()[1:], new_tip ]) self.play( MoveToTarget(polygon), TransformMatchingShapes(convex_label, not_convex_label), ) self.wait() # Show light beam beam = DashedLine(ORIGIN, FRAME_WIDTH * RIGHT) beam.set_stroke(YELLOW, 1) beam.next_to(line, DOWN, MED_SMALL_BUFF) flash_line = Line(beam.get_start(), beam.get_end()) flash_line.set_stroke(YELLOW, 5) flash_line.insert_n_curves(100) self.play( ShowCreation(beam), VShowPassingFlash(flash_line), run_time=1, ) self.wait() class NonConvexDoughnut(ShadowScene): def construct(self): # Setup frame = self.camera.frame self.remove(self.solid, self.shadow) torus = Torus() torus.set_width(4) torus.set_z(3) torus.set_color(BLUE_D) torus.set_opacity(0.7) torus.set_reflectiveness(0) torus.set_shadow(0.5) torus.always_sort_to_camera(self.camera) shadow = get_shadow(torus) shadow.always_sort_to_camera(self.camera) self.add(torus) self.add(shadow) self.play(ShowCreation(torus), run_time=2) self.play(Rotate(torus, PI / 2, LEFT), run_time=2) self.wait() # Light beam dot = GlowDot(0.25 * LEFT) line = DashedLine(dot.get_center(), dot.get_center() + 10 * OUT) line.set_stroke(YELLOW, 1) line_shadow = line.copy().set_stroke(opacity=0.1) self.add(line, torus, line_shadow) self.play( FadeIn(dot), ShowCreation(line), ShowCreation(line_shadow), ApplyMethod(frame.reorient, 20, run_time=7) ) self.wait() class ShowGridSum(TwoToOneCover): def construct(self): # Setup self.clear() shape_name = "Cube" n_faces = 6 # shape_name = "Dodec." # n_faces = 12 frame = self.camera.frame frame.reorient(0, 0) frame.move_to(ORIGIN) equation = self.get_top_expression(" = ", "$\\displaystyle \\frac{1}{2}$", n_faces=n_faces) self.add(equation) lhs = equation.slice_by_tex(None, "=") summand = equation.slice_by_tex("sum", None)[1:] # Abbreviate t2c = { f"\\text{{{shape_name}}}": BLUE, "\\text{F}_j": YELLOW, "\\text{Face}": YELLOW, "\\text{Total}": GREEN, "S": GREY_B, "{c}": RED, } kw = { "tex_to_color_map": t2c } lhs.alt1 = OldTex(f"S(\\text{{{shape_name}}})", **kw) summand.alt1 = OldTex("S(\\text{F}_j)", **kw) def get_s_cube_term(i="i"): return OldTex(f"S\\big(R_{{{i}}}", f"(\\text{{{shape_name}}})\\big)", **kw) def get_s_f_term(i="i", j="j"): result = OldTex( f"S\\big(R_{{{i}}}", "(", "\\text{F}_{" + str(j) + "}", ")", "\\big)", **kw ) result[3].set_color(YELLOW) return result lhs.alt2 = get_s_cube_term(1) summand.alt2 = get_s_f_term(1) for mob, vect in (lhs, RIGHT), (summand, LEFT): mob.brace = Brace(mob, DOWN, buff=SMALL_BUFF) mob.alt1.next_to(mob.brace, DOWN) self.play( GrowFromCenter(mob.brace), FadeIn(mob.alt1, shift=0.5 * DOWN), ) self.wait() self.play( FadeOut(mob.brace, scale=0.5), FadeOut(mob, shift=0.5 * UP), mob.alt1.animate.move_to(mob, vect), ) mob.alt2.move_to(mob, vect) self.wait() for mob in lhs, summand: self.play(TransformMatchingShapes(mob.alt1, mob.alt2)) self.wait() # Add up many rotations lhss = VGroup( get_s_cube_term(1), get_s_cube_term(2), get_s_cube_term(3), OldTex("\\vdots"), get_s_cube_term("n"), ) buff = 0.6 lhss.arrange(DOWN, buff=buff) lhss.move_to(lhs.alt2, UP) self.remove(lhs.alt2) self.play( LaggedStart(*( ReplacementTransform(lhs.alt2.copy(), target) for target in lhss )), frame.animate.set_height(10, about_edge=UP), run_time=2, ) # Show empirical mean h_line = Line(LEFT, RIGHT) h_line.set_width(lhss.get_width() + 0.75) h_line.next_to(lhss, DOWN, MED_SMALL_BUFF, aligned_edge=RIGHT) plus = OldTex("+") plus.align_to(h_line, LEFT).shift(0.1 * RIGHT) plus.match_y(lhss[-1]) total = Text("Total", font_size=60) total.set_color(GREEN) total.next_to(h_line, DOWN, buff=0.35) total.match_x(lhss) mean_sa = OldTex( f"S(\\text{{{shape_name}}})", "=", "\\frac{1}{n}", "\\sum_{i=1}^n S\\big(R_i(" + f"\\text{{{shape_name}}})\\big)", **kw, ) mean_sa.add_to_back(get_overline(mean_sa.slice_by_tex(None, "="))) mean_sa.next_to(total, DOWN, LARGE_BUFF, aligned_edge=RIGHT) corner_rect = SurroundingRectangle(mean_sa, buff=0.25) corner_rect.set_stroke(WHITE, 2) corner_rect.set_fill(GREY_E, 1) corner_rect.move_to(frame, DL) corner_rect.shift(0.025 * UR) mean_sa.move_to(corner_rect) sum_part = mean_sa.slice_by_tex("sum") sigma = sum_part[0] sigma.save_state() lhss_rect = SurroundingRectangle(lhss) lhss_rect.set_stroke(BLUE, 2) sigma.next_to(lhss_rect, LEFT) sum_group = VGroup(lhss, lhss_rect) self.play( Write(lhss_rect), Write(sigma), ) self.wait() self.add(corner_rect, sigma) self.play( FadeIn(corner_rect), *( FadeTransform(term.copy(), sum_part[1:]) for term in lhss ), Restore(sigma), ) self.play(Write(mean_sa.get_part_by_tex("frac"))) self.wait() self.play( FadeIn(mean_sa.slice_by_tex(None, "frac")), ) self.wait() # Create grid sf = get_s_f_term grid_terms = [ [sf(1, 1), sf(1, 2), OldTex("\\dots"), sf(1, n_faces)], [sf(2, 1), sf(2, 2), OldTex("\\dots"), sf(2, n_faces)], [sf(3, 1), sf(3, 2), OldTex("\\dots"), sf(3, n_faces)], [Tex("\\vdots"), OldTex("\\vdots"), OldTex("\\ddots"), OldTex("\\vdots")], [sf("n", 1), sf("n", 2), OldTex("\\dots"), sf("n", n_faces)], ] grid = VGroup(*(VGroup(*row) for row in grid_terms)) for lhs, row in zip(lhss, grid): for i in range(len(row) - 1, 0, -1): is_dots = "dots" in row[0].get_tex() sym = VectorizedPoint() if is_dots else OldTex("+") row.insert_submobject(i, sym) row.arrange(RIGHT, buff=MED_SMALL_BUFF) for m1, m2 in zip(row, grid[0]): m1.match_x(m2) m1.match_y(lhs) if not is_dots: parens = OldTex("[]", font_size=72)[0] parens.set_stroke(width=2) parens.set_color(BLUE_B) parens[0].next_to(row, LEFT, buff=SMALL_BUFF) parens[1].next_to(row, RIGHT, buff=SMALL_BUFF) row.add(*parens) eq_half = OldTex("=", "\\frac{1}{2}") eq_half[1].match_height(parens) eq_half.next_to(parens[0], LEFT, MED_SMALL_BUFF) row.add(*eq_half) grid.set_x(frame.get_right()[0] - 1.5, RIGHT) self.remove(summand.alt2) self.play( sum_group.animate.set_x(grid.get_left()[0] - MED_SMALL_BUFF, RIGHT), TransformMatchingShapes( VGroup( equation.get_part_by_tex("frac"), equation.get_part_by_tex("="), ), grid[0][-4:], ), LaggedStart(*( FadeTransform(summand.alt2.copy(), part) for part in grid[0][0:7:2] )), FadeOut(equation.get_part_by_tex("sum"), scale=0.25), Write(grid[0][1:7:2]), # Plus signs ) self.wait(2) self.play(FadeTransform(grid[0].copy(), grid[1])) self.play(FadeTransform(grid[1].copy(), grid[2])) self.play(FadeTransform(grid[2].copy(), grid[4]), FadeIn(grid[3])) self.wait(2) # Average along columns cols = VGroup(*( VGroup(*(row[i] for row in grid)).copy() for i in [0, 2, 6] )) col_rects = VGroup(*( SurroundingRectangle(col, buff=SMALL_BUFF) for col in cols )) col_rects.set_stroke(YELLOW, 1) mean_face = OldTex("S(\\text{Face})", **kw) mean_face.add_to_back(get_overline(mean_face)) mean_face.next_to(grid, DOWN, buff=2) mean_face_words = OldTexText("Average shadow\\\\of one face") mean_face_words.move_to(mean_face, UP) arrows = VGroup(*( Arrow(rect.get_bottom(), mean_face) for rect in col_rects )) arrow_labels = OldTex("\\frac{1}{n} \\sum \\cdots", font_size=30).replicate(3) for arrow, label in zip(arrows, arrow_labels): vect = rotate_vector(normalize(arrow.get_vector()), PI / 2) label.next_to(arrow.pfp(0.5), vect, SMALL_BUFF) self.add(cols[0]) self.play( grid.animate.set_opacity(0.4), ShowCreation(col_rects[0]) ) self.wait() self.play( ShowCreation(arrows[0]), FadeIn(arrow_labels[0]), FadeIn(mean_face_words, DR), ) self.wait() self.play( mean_face_words.animate.scale(0.7).next_to(mean_face, DOWN, MED_LARGE_BUFF), FadeIn(mean_face, scale=2), ) self.wait() for i in [1, 2]: self.play( FadeOut(cols[i - 1]), FadeIn(cols[i]), *( ReplacementTransform(group[i - 1], group[i]) for group in (col_rects, arrows, arrow_labels) ) ) self.wait() self.wait() # Reposition frame.generate_target() frame.target.align_to(total, DOWN) frame.target.shift(0.5 * DOWN) frame.target.scale(1.15) frame.target.align_to(lhss, LEFT).shift(0.25 * LEFT) self.play(LaggedStart( VGroup(corner_rect, mean_sa).animate.scale(1.25).move_to( frame.target, UL ).shift(0.1 * DR), MoveToTarget(frame), FadeOut(mean_face_words), FadeOut(mean_face), grid.animate.set_opacity(1), *( FadeOut(group[-1]) for group in (cols, col_rects, arrows, arrow_labels) ), run_time=3 )) mean_sa.refresh_bounding_box() # ?? # Show final result rhss = VGroup( OldTex("=", "\\frac{1}{2}", "\\sum_{j=1}^" + f"{{{n_faces}}}", " S(\\text{F}_j})", **kw), OldTex("=", "\\frac{1}{2}", "\\sum_{j=1}^" + f"{{{n_faces}}}", " {c}", "\\cdot ", "A(\\text{F}_j)", **kw), OldTex("=", "\\frac{1}{2}", "{c}", "\\cdot ", "(\\text{Surface area})", **kw), ) rhss[0].add(get_overline(rhss[0].slice_by_tex("S"))) rhss[2][-2].set_color(WHITE) rhss.arrange(RIGHT) rhss.next_to(mean_sa, RIGHT) corner_rect.generate_target() corner_rect.target.set_width( frame.get_width() - 0.2, stretch=True, about_edge=LEFT, ) grid_rect = SurroundingRectangle(grid, buff=SMALL_BUFF) grid_rect.set_stroke(YELLOW, 1) grid_rect.set_fill(YELLOW, 0.25) rects = VGroup( SurroundingRectangle(mean_sa.slice_by_tex("frac")), SurroundingRectangle(rhss[0][1:]) ) for rect in rects: rect.match_height(corner_rect.target, stretch=True) rect.match_y(corner_rect.target) rects[0].set_color(BLUE) rects[1].set_color(YELLOW) rects.set_stroke(width=2) rects.set_fill(opacity=0.25) rows_first = Text("Rows first") rows_first.next_to(rects[0], DOWN) rows_first.match_color(rects[0]) cols_first = Text("Columns first") cols_first.next_to(rects[1], DOWN) cols_first.match_color(rects[1]) self.add(corner_rect, mean_sa) self.play( MoveToTarget(corner_rect), Write(rhss[0]) ) self.add(grid_rect, grid) self.play(VFadeInThenOut(grid_rect, run_time=2)) self.wait() self.play( Write(rects[0]), Write(rows_first), ) self.wait() self.play( Write(rects[1]), Write(cols_first), ) self.wait() self.play(LaggedStart(*map(FadeOut, ( *rects, rows_first, cols_first )))) self.play( TransformMatchingShapes(rhss[0].copy(), rhss[1]) ) self.wait() self.play( FadeTransform(rhss[1].copy(), rhss[2]), ) self.wait() key_part = rhss[2][1:] final_rect = SurroundingRectangle(key_part) final_rect.set_stroke(YELLOW, 1) self.play( corner_rect.animate.set_stroke(width=0).scale(1.1), FlashAround(key_part, time_width=1.5), FadeIn(final_rect), run_time=2, ) class LimitBrace(Scene): def construct(self): brace = Brace(Line().set_width(3), UP) tex = brace.get_tex("n \\to \\infty") VGroup(brace, tex).set_color(TEAL) VGroup(brace, tex).set_backstroke() self.play( GrowFromCenter(brace), FadeIn(tex, shift=0.25 * UP) ) self.wait() class FromRowsToColumns(Scene): def construct(self): n = 5 grid = Dot().get_grid(n, n, buff=MED_LARGE_BUFF) grids = grid.get_grid(1, 2, buff=3) buff = 0.2 row_rects = VGroup(*( SurroundingRectangle(grids[0][k:k + n], buff=buff) for k in range(0, n * n, n) )) col_rects = VGroup(*( SurroundingRectangle(grids[1][k::n], buff=buff) for k in range(n) )) rects = VGroup(row_rects, col_rects) rects.set_fill(opacity=0.25) rects.set_stroke(width=2) row_rects.set_color(BLUE) col_rects.set_color(YELLOW) # plus_template = OldTex("+") # plus_template.match_height(grids[0][0]) # for grid in grids: # plusses = VGroup() # for k, dot in enumerate(grid): # if k % n != n - 1: # pc = plus_template.copy() # pc.move_to(midpoint(dot.get_center(), grid[k + 1].get_center())) # plusses.add(pc) # grid.add(plusses) arrow = Arrow(grids[0], grids[1], buff=0.5) self.add(grids[0]) self.play(FadeIn(row_rects, lag_ratio=0.2)) self.wait() self.play( TransformFromCopy(grids[0], grids[1]), ShowCreation(arrow) ) self.play(FadeIn(col_rects, lag_ratio=0.2)) self.wait() class ComplainAboutProgress(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("Wait, is that all\\\\we've accomplished?"), target_mode="angry", ) self.play_student_changes( "guilty", "erm", look_at=self.students[2].eyes, added_anims=[self.teacher.change("guilty")], ) self.wait(4) class SupposedlyObviousProportionality(ShadowScene): solid_name = "Cube" def construct(self): # Setup cube = self.solid shadow = self.shadow frame = self.camera.frame frame.set_z(3) frame.reorient(-20, 80) self.init_frame_rotation() light = self.light light.next_to(cube, OUT, 50) equation = get_key_result(self.solid_name) equation.fix_in_frame() equation.to_edge(UP) self.add(equation) # Rotation self.begin_ambient_rotation(cube) self.wait() # Ask about constant question = OldTexText( "What is $c$?!", font_size=72, tex_to_color_map={"$c$": RED} ) question.fix_in_frame() question.next_to(equation, DOWN, LARGE_BUFF) question.to_edge(RIGHT, buff=LARGE_BUFF) c_arrow = Arrow( equation.get_part_by_tex("{c}"), question.get_corner(UL), ) c_arrow.set_color(RED) c_arrow.fix_in_frame() self.play( ShowCreation(c_arrow), Write(question) ) self.wait(4) # "Obvious" obvious_words = OldTexText("Isn't this obvious?", font_size=36) obvious_words.set_color(GREY_A) obvious_words.match_y(question) obvious_words.to_edge(LEFT) obvious_arrow = Arrow( obvious_words, equation.get_corner(DL) + RIGHT ) VGroup(obvious_words, obvious_arrow).fix_in_frame() self.play( TransformMatchingShapes(question, obvious_words), ReplacementTransform(c_arrow, obvious_arrow), ) self.wait() # 2d quantities cube.clear_updaters() shadow_label = OldTexText("2D") shadow_label.move_to(shadow) face_labels = VGroup() for face in cube[3:]: lc = shadow_label.copy() normal = face.get_unit_normal() lc.rotate(angle_of_vector(flat_project(normal)) + PI / 2) lc.apply_matrix( rotation_between_vectors(OUT, normal) ) lc.move_to(face) face.label = lc face_labels.add(lc) self.play( Write(shadow_label), Write(face_labels), run_time=2, ) self.wait() scalars = [cube, face_labels, shadow_label] self.play( *( mob.animate.scale(0.5) for mob in scalars ), rate_func=there_and_back, run_time=3 ) self.play( *( mob.animate.stretch(2, 0) for mob in scalars ), rate_func=there_and_back, run_time=3 ) self.wait() # No not really no_words = Text("No, not really", font_size=30) no_words.set_color(RED) no_words.fix_in_frame() no_words.next_to(obvious_words, DOWN, MED_LARGE_BUFF) self.play( FadeIn(no_words, 0.25 * DOWN), FadeOut(shadow_label), FadeOut(face_labels), ) # Move light self.play( light.animate.next_to(cube, OUT + RIGHT, 2), run_time=4, rate_func=rush_from, ) for s in (1.5, 0.25, 2 / 0.75): self.play( cube.animate.scale(s), run_time=2, ) # To finish cube.add_updater(lambda m: self.sort_to_camera(m)) self.begin_ambient_rotation(cube) self.play( light.animate.next_to(cube, OUT, 50), LaggedStart(*map(FadeOut, ( no_words, obvious_words, obvious_arrow, ))), run_time=3, ) self.wait(33) class LurkingAssumption(VideoWrapper): title = "There's a subtle hidden assumption..." wait_time = 4 animate_boundary = False class WhatIsC(Scene): def construct(self): words = OldTexText( "What is $c$?!", tex_to_color_map={"$c$": RED}, font_size=72, ) self.play(Write(words)) self.play(FlashUnder(words, color=RED)) self.wait() class BobsFinalAnswer(Scene): def construct(self): answer = OldTex( "S(\\text{Cube})", "=", "\\frac{1}{2}", "\\cdot", "{\\frac{1}{2}}", "(\\text{Surface area})", "=", "\\frac{1}{4} \\big(6s^2\\big)", "=", "\\frac{3}{2} s^2", tex_to_color_map={ "\\text{Cube}": BLUE, "{\\frac{1}{2}}": RED, } ) answer.add_to_back(get_overline(answer[:3])) equals = answer.get_parts_by_tex("=") eq_indices = list(map(answer.index_of_part, equals)) eq1 = answer[:eq_indices[1]].deepcopy() eq2 = answer[:eq_indices[2]].deepcopy() eq3 = answer.deepcopy() for eq in eq1, eq2, eq3: eq.to_edge(RIGHT) eq.shift(1.25 * UP) self.play(FadeIn(eq1, DOWN)) self.wait() for m1, m2 in (eq1, eq2), (eq2, eq3): self.play( FadeIn(m2[len(m1):]), m1.animate.move_to(m2, LEFT), ) self.remove(m1) self.add(m2) self.wait() rect = SurroundingRectangle(eq3[-1]) rect.set_stroke(YELLOW, 2) self.play( ShowCreation(rect), FlashAround(eq3[-1], stroke_width=5, time_width=1.5, run_time=1.5) ) self.wait() class ShowSeveralConvexShapes(Scene): def construct(self): frame = self.camera.frame frame.reorient(0, 70) dodec = Dodecahedron() dodec.set_fill(BLUE_D) spike = VGroup() hexagon = RegularPolygon(6) spike.add(hexagon) for v1, v2 in adjacent_pairs(hexagon.get_vertices()): spike.add(Polygon(v1, v2, 2 * OUT)) spike.set_fill(BLUE_E) blob = Group(Sphere()) blob.stretch(0.5, 0) blob.stretch(0.5, 1) blob.set_color(BLUE_E) blob.apply_function( lambda p: [*(2 - p[2]) * p[:2], p[2]] ) blob.set_color(BLUE_E) cylinder = Group(Cylinder()) cylinder.set_color(GREY_BROWN) cylinder.rotate(PI / 4, UP) examples = Group(*( Group(*mob) for mob in (dodec, spike, blob, cylinder) )) for ex in examples: ex.set_depth(2) ex.deactivate_depth_test() ex.set_gloss(0.5) ex.set_shadow(0.5) ex.set_reflectiveness(0.2) ex.rotate(20 * DEGREES, OUT) sort_to_camera(ex, self.camera.frame) for sm in ex: if isinstance(sm, VMobject): sm.set_stroke(WHITE, 1) sm.set_fill(opacity=0.9) else: sm.always_sort_to_camera(self.camera) examples.arrange(RIGHT, buff=LARGE_BUFF) self.play(LaggedStart(*( LaggedStartMap(Write, ex, run_time=1) if isinstance(ex[0], VMobject) else ShowCreation(ex[0]) for ex in examples ), lag_ratio=0.5, run_time=8)) self.wait() class KeyResult(Scene): def construct(self): eq1, eq2 = [ get_key_result(word) for word in ("Cube", "Solid") ] VGroup(eq1, eq2).to_edge(UP) self.play(FadeIn(eq1, lag_ratio=0.1)) self.wait() cube_underline = Underline(eq2.get_part_by_tex("Solid"), buff=0.05) cube_underline.set_stroke(BLUE, 1) general_words = Text("Assume convex", font_size=36) general_words.set_color(BLUE) general_words.next_to(cube_underline, DOWN, buff=1.0) general_words.shift(LEFT) general_arrow = Arrow(general_words, cube_underline.get_center(), buff=0.1) self.play( ShowCreation(cube_underline), FadeIn(general_words), ShowCreation(general_arrow), FadeTransformPieces(eq1, eq2), ) self.wait() const_rect = SurroundingRectangle(VGroup( eq.get_part_by_tex("frac"), eq.get_part_by_tex("{c}") ), buff=SMALL_BUFF) const_rect.set_stroke(RED, 1) const_words = Text("Universal constant!", font_size=36) const_words.set_color(RED) const_words.match_y(general_words) const_words.set_x(const_rect.get_x() + 1) const_arrow = Arrow(const_words, const_rect, buff=0.1) self.play( ShowCreation(const_rect), FadeIn(const_words), ShowCreation(const_arrow), ) self.wait() class ShadowsOfDodecahedron(ShadowScene): inf_light = True def construct(self): # Setup self.camera.frame.set_height(7) self.camera.frame.shift(OUT) dodec = self.solid dodec.scale(5 / dodec[0].get_arc_length()) outline = self.get_shadow_outline() area = DecimalNumber(font_size=36) area.move_to(outline) area.add_updater(lambda m: m.set_value(get_norm(outline.get_area_vector()) / (self.unit_size**2))) area.add_updater(lambda m: m.fix_in_frame()) area.move_to(3.15 * DOWN) self.init_frame_rotation() ssf = 1.5 self.wait() self.play(dodec.animate.space_out_submobjects(ssf)) self.play(Rotate(dodec, PI, axis=RIGHT, run_time=6)) self.play(dodec.animate.space_out_submobjects(1 / ssf)) self.begin_ambient_rotation(dodec) self.play( VFadeIn(outline), VFadeIn(area), ) # Add dot and line dot = GlowDot(0.5 * DR) line = DashedLine(10 * OUT, ORIGIN) line.set_stroke(YELLOW, 1) def dodec_sdf(point): return max(*( np.dot(point - pent.get_center(), pent.get_unit_normal()) for pent in dodec )) def update_line(line): line.move_to(dot.get_center(), IN) for dash in line: dist = dodec_sdf(dash.get_center()) dash.set_stroke( opacity=interpolate(0.1, 1.0, clip(10 * dist, -0.5, 0.5) + 0.5) ) dash.inside = (dist < 0) line.add_updater(update_line) self.play(ShowCreation(line, rate_func=rush_into)) self.play(FadeIn(dot, rate_func=rush_from)) # Just wait for n in range(8): self.play(dot.animate.move_to(midpoint( outline.get_center(), outline.pfp(random.random()), )), run_time=5) def get_solid(self): solid = self.get_solid_no_style() solid.set_stroke(WHITE, 1) solid.set_fill(self.solid_fill_color, 0.8) solid.set_gloss(0.1) solid.set_shadow(0.4) solid.set_reflectiveness(0.4) group = Group(*solid) group.deactivate_depth_test() group.add_updater(lambda m: self.sort_to_camera(m)) return group def get_solid_no_style(self): dodec = Dodecahedron() dodec.scale((32 / get_surface_area(dodec))**0.5) return dodec class AmbientDodecahedronShadow(ShadowsOfDodecahedron): solid_name = "Dodecahedron" solid_fill_color = BLUE_E name_color = BLUE_D def construct(self): self.camera.frame.reorient(20, 80) self.camera.frame.set_z(3) eq = get_key_result(self.solid_name, color=self.name_color) eq.to_edge(UP) eq.fix_in_frame() self.add(eq) self.init_frame_rotation() self.play(LaggedStart(*map(Write, self.solid))) self.add(self.solid) outline = self.get_shadow_outline() area_label = self.get_shadow_area_label() # area_label.scale(0.7) area_label.move_to(2.75 * DOWN).to_edge(LEFT) area_label.add_updater(lambda m: m.fix_in_frame()) surface_area = get_surface_area(self.solid) surface_area /= (self.unit_size**2) sa_label = VGroup(Text("Surface area: "), DecimalNumber(surface_area)) sa_label.arrange(RIGHT) sa_label.match_y(area_label) sa_label.to_edge(RIGHT) sa_label.set_backstroke() sa_label.fix_in_frame() self.play( *map(VFadeIn, (outline, area_label, sa_label)) ) self.add(outline) self.add(area_label) self.begin_ambient_rotation(self.solid, about_point=self.solid.get_center()) self.wait(30) class AmbientTriPrismSum(AmbientDodecahedronShadow): solid_name = "Triangular Prism" solid_fill_color = interpolate_color(TEAL_E, BLACK, 0.25) name_color = TEAL_D def get_solid_no_style(self): triangle = RegularPolygon(3) tri1, tri2 = triangle.replicate(2) tri2.shift(3 * OUT) sides = [] verts1 = tri1.get_anchors() verts2 = tri2.get_anchors() for (a, b), (c, d) in zip(adjacent_pairs(verts1), adjacent_pairs(verts2)): sides.append(Polygon(a, b, d, c)) result = VGroup(tri1, *sides, tri2) result.scale((16 / get_surface_area(result))**0.5) return result class AmbientPyramidSum(AmbientDodecahedronShadow): solid_name = "Pyramid" solid_fill_color = GREY_BROWN name_color = interpolate_color(GREY_BROWN, WHITE, 0.5) def get_solid_no_style(self): base = Square(side_length=1) result = VGroup(base) for v1, v2 in adjacent_pairs(base.get_vertices()): result.add(Polygon(v1, v2, math.sqrt(3) * OUT / 2)) result.set_height(2) return result class AmbientCubeWithLabels(AmbientDodecahedronShadow): solid_name = "Cube" def get_solid_no_style(self): return VCube() class DodecahedronFaceSum(Scene): def construct(self): expr = OldTexText( "Area(Shadow(Dodecahedron))", "=", "$\\displaystyle \\frac{1}{2}$", " $\\displaystyle \\sum_{j=1}^{12}$ ", "Area(Shadow(Face$_j$))", tex_to_color_map={ "Shadow": GREY_B, "Dodecahedron": BLUE_D, "Face$_j$": YELLOW, } ) expr.to_edge(UP, buff=MED_SMALL_BUFF) self.add(expr.slice_by_tex(None, "=")) self.wait() self.play(FadeIn(expr.slice_by_tex("="), shift=0.25 * UP)) self.wait() self.play(FlashAround(expr.get_part_by_tex("frac"), run_time=2)) self.play(FlashUnder(expr[-5:], run_time=2)) self.wait(2) class SphereShadow(ShadowScene): inf_light = True def construct(self): frame = self.camera.frame frame.set_height(7) frame.shift(OUT) sphere = self.solid shadow = self.shadow # shadow[1].always_sort_to_camera(self.camera) shadow_circle = Circle() shadow_circle.set_fill(BLACK, 0.8) shadow_circle.replace(shadow) shadow_circle.set_stroke(WHITE, 1) self.add(shadow_circle) self.begin_ambient_rotation( sphere, speed=0.3, initial_axis=[-1, -1, 0.5] ) self.wait(60) def get_solid(self): ep = 1e-3 sphere = Sphere( radius=1.5, u_range=(ep, TAU - ep), v_range=(ep, PI - ep), ) sphere = TexturedSurface(sphere, "EarthTextureMap", "NightEarthTextureMap") sphere.set_opacity(1) sphere.always_sort_to_camera(self.camera) mesh = SurfaceMesh(sphere) mesh.set_stroke(WHITE, 0.5, 0.25) return Group(sphere, mesh) class SphereInfo(Scene): def construct(self): kw = { "tex_to_color_map": { "{c}": RED, "=": WHITE, "R": BLUE }, "font_size": 36 } shadow = OldTex("\\text{Average shadow area} = \\pi R^2", **kw) surface = OldTex("\\text{Surface area} = 4 \\pi R^2", **kw) conclusion = OldTex("\\frac{1}{2}", "{c}", "=", "\\frac{1}{4}", **kw) eqs = VGroup(shadow, surface, conclusion) eqs.arrange(DOWN, buff=MED_LARGE_BUFF) for eq in eqs: eq.shift(eq.get_part_by_tex("=").get_x() * LEFT) eqs.to_corner(UR) for eq in eqs[:2]: eq[0].set_color(GREY_A) for eq in eqs: self.play(FadeIn(eq, lag_ratio=0.1)) self.wait() self.play(eqs[2].animate.scale(2, about_edge=UP)) rect = SurroundingRectangle(eqs[2]) rect.set_stroke(YELLOW, 2) self.play(ShowCreation(rect)) self.wait() class PiRSquared(Scene): def construct(self): form = OldTex("\\pi R^2")[0] form[1].set_color(BLUE) self.play(Write(form)) self.wait() class SwapConstantForFourth(Scene): def construct(self): eq = get_key_result("Dodecahedron") eq.to_edge(UP) parts = VGroup( eq.get_part_by_tex("frac"), eq.get_part_by_tex("{c}") ) fourth = OldTex("\\frac{1}{4}") fourth.move_to(parts, LEFT) fourth.set_color(RED) self.add(eq) self.wait() self.play( FadeOut(parts, UP), FadeIn(fourth, UP), eq.slice_by_tex("\\cdot").animate.next_to(fourth, RIGHT), ) self.wait() class ButSpheresAreSmooth(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("But spheres don't\\\\have flat faces!"), target_mode="angry", index=2, added_anims=[self.teacher.change("guilty")] ) self.play_student_changes( "erm", "hesitant", "angry", look_at=self.screen, ) self.wait(6) class RepeatedRelation(Scene): def construct(self): # Relations relation = VGroup( Text("Average shadow"), OldTex("=").rotate(PI / 2), OldTex("\\frac{1}{2}", "c", "\\cdot (", "\\text{Surface area}", ")") ) relation[0].set_color(GREY_A) relation[2][1].set_color(RED) relation[2][3].set_color(BLUE) relation.arrange(DOWN) relation.scale(0.6) repeats = relation.get_grid(1, 4, buff=0.8) repeats.to_edge(LEFT, buff=MED_LARGE_BUFF) repeats.shift(0.5 * DOWN) for repeat in repeats: self.play(FadeIn(repeat[0], lag_ratio=0.1)) self.play( Write(repeat[1]), FadeIn(repeat[2], 0.5 * DOWN) ) self.wait() # Limit limit = OldTex( "\\lim_{|F| \\to 0}", "\\left(", "{\\text{Average shadow}", "\\over ", "\\text{Surface area}}", "\\right)", "=", "\\frac{1}{2}", "{c}", ) limit.set_color_by_tex("Average shadow", GREY_A) limit.set_color_by_tex("Surface area", BLUE) limit.set_color_by_tex("{c}", RED) limit.move_to(2.5 * DOWN) limit.match_x(repeats) new_rhs = OldTex("=", "{\\pi R^2", "\\over", "4\\pi R^2}") new_rhs.set_color_by_tex("\\pi R^2", GREY_A) new_rhs.set_color_by_tex("4\\pi R^2", BLUE) new_rhs.move_to(limit.get_part_by_tex("="), LEFT) self.play(Write(limit)) self.wait() self.play( limit.slice_by_tex("=").animate.next_to(new_rhs, RIGHT), GrowFromCenter(new_rhs) ) self.wait() class SimpleCross(Scene): def construct(self): lines = VGroup( Line(UP, DOWN).set_height(FRAME_HEIGHT), Line(LEFT, RIGHT).set_width(FRAME_WIDTH), ) self.play(ShowCreation(lines, lag_ratio=0.5)) self.wait() # Not needed? class AmbientCubeTurningIntoNewShapes(Scene): def construct(self): pass class PopularizaitonVsDoing(Scene): def construct(self): # Words popular = Text("Popularization of math") doing = Text("Doing math") words = VGroup(popular, doing) words.arrange(DOWN, buff=3) words.move_to(UP) self.play(FadeIn(popular, UP)) self.wait() self.play( TransformFromCopy( popular.get_part_by_text("math"), doing.get_part_by_text("math"), ), Write(doing[:len("Doing")]) ) self.wait() # Bars width = 8 bar = Rectangle(width, 0.5) bar.set_stroke(WHITE, 1) bar.next_to(popular, DOWN) left_bar, right_bar = bar.replicate(2) left_bar.set_fill(BLUE_E, 1) right_bar.set_fill(RED_E, 1) left_bar.stretch(0.5, 0, about_edge=LEFT) right_bar.stretch(0.5, 0, about_edge=RIGHT) left_brace = always_redraw(lambda: Brace(left_bar, DOWN, buff=SMALL_BUFF)) right_brace = always_redraw(lambda: Brace(right_bar, DOWN, buff=SMALL_BUFF)) left_label = Text("Insights", font_size=30, color=GREY_B) right_label = Text("Computations", font_size=30, color=GREY_B) always(left_label.next_to, left_brace, DOWN, SMALL_BUFF) always(right_label.next_to, right_brace, DOWN, SMALL_BUFF) bar_group = VGroup( bar, left_bar, right_bar, left_brace, right_brace, left_label, right_label, ) def set_bar_alpha(alpha, **kwargs): self.play( left_bar.animate.set_width(alpha * width, about_edge=LEFT, stretch=True), right_bar.animate.set_width((1 - alpha) * width, about_edge=RIGHT, stretch=True), **kwargs ) self.play(FadeIn(bar_group, lag_ratio=0.1)) set_bar_alpha(0.95, run_time=2) self.wait() self.add(bar_group.deepcopy().clear_updaters()) self.play( bar_group.animate.shift(doing.get_center() - popular.get_center()) ) set_bar_alpha(0.05, run_time=5) self.wait() # Embed self.embed() class MultipleMathematicalBackgrounds(TeacherStudentsScene): def construct(self): self.remove(self.background) labels = VGroup( OldTexText("$\\le$ High school"), OldTexText("$\\approx$ Undergrad"), OldTexText("$\\ge$ Ph.D."), ) for student, label in zip(self.students, labels): label.scale(0.7) label.next_to(student, UP) words = OldTexText("Explanation doesn't vary\\\\with backgrounds") words.to_edge(UP) lines = VGroup(*( DashedLine(words, label, buff=0.5) for label in labels )) lines.set_stroke(WHITE, 2) self.add(words) self.play( self.teacher.change("raise_right_hand"), self.change_students( "pondering", "thinking", "pondering", look_at=self.teacher.eyes, ), ) self.play( LaggedStartMap(ShowCreation, lines, lag_ratio=0.5), LaggedStartMap(FadeIn, labels, lag_ratio=0.5), ) self.wait(3) self.play( self.teacher.change("dejected").look(UP), self.change_students("hesitant", "well", "thinking"), LaggedStartMap(FadeOut, lines, scale=0.5), FadeOut(words, DOWN), ) self.wait(4) # Different levels kw = {"font_size": 30} methods = VGroup( OldTexText("Calculus\\\\primer", **kw), OldTexText("Quickly show\\\\key steps", **kw), OldTexText("Describe as a\\\\measure on SO(3)", **kw), ) new_lines = VGroup() colors = [GREEN_B, GREEN_C, GREEN_D] for method, label, color in zip(methods, labels, colors): method.move_to(label) method.shift(2.5 * UP) method.set_color(color) line = DashedLine(method, label, buff=0.25) line.set_stroke(color, 2) new_lines.add(line) self.play( self.teacher.change("raise_right_hand"), self.change_students( "erm", "pondering", "thinking", look_at=self.students.get_center() + 4 * UP ), LaggedStartMap(FadeIn, methods, lag_ratio=0.5), LaggedStartMap(ShowCreation, new_lines, lag_ratio=0.5), ) self.wait(4) class WatchingAVideo(Scene): def construct(self): self.add(FullScreenRectangle()) randy = Randolph() randy.to_corner(DL) screen = ScreenRectangle(height=5) screen.set_fill(BLACK, 1) screen.to_corner(UR) def blink_wait(n=1): for x in range(n): self.wait() self.play(Blink(randy)) self.wait() self.add(screen) self.add(randy) self.play(randy.change("pondering", screen)) blink_wait() self.play(randy.change("thinking", screen)) blink_wait() self.play(randy.change("hesitant", screen)) blink_wait(2) class CleverProofExample(Scene): def construct(self): initial_sum = OldTex("1^2 + 2^2 + 3^2 + \\cdots + n^2") tripple_tris, final_tri = self.get_triangle_sums() initial_sum.set_width(10) self.play(FadeIn(initial_sum, lag_ratio=0.1)) self.wait() tripple_tris.set_width(10) tripple_tris.to_edge(DOWN, buff=2) tris = tripple_tris[0] tri = tris[0] tri.save_state() tri.set_height(4) tri.center().to_edge(DOWN, buff=1) self.play( initial_sum.animate.set_width(8).to_edge(UP), FadeIn(tri, lag_ratio=0.1) ) self.wait() self.play( Restore(tri), FadeIn(tripple_tris[1:]) ) for i in (0, 1): bt1 = tris[i].copy() bt1.generate_target() bt1.target.rotate(120 * DEGREES) bt1.target.replace(tris[i + 1]) bt1.target.set_opacity(0) tris[i + 1].save_state() tris[i + 1].rotate(-120 * DEGREES) tris[i + 1].replace(tris[i]) tris[i + 1].set_opacity(0) self.play( MoveToTarget(bt1, remover=True), Restore(tris[i + 1]) ) self.wait() final_tri.set_height(3) final_tri.move_to(tripple_tris, UP) initial_sum.generate_target() eq = OldTex("=").scale(2) tripple_tris.generate_target() top_row = VGroup(initial_sum.target, eq, tripple_tris.target) top_row.arrange(RIGHT, buff=0.5) top_row.set_width(FRAME_WIDTH - 1) top_row.center().to_edge(UP) self.play( MoveToTarget(initial_sum), FadeIn(eq), MoveToTarget(tripple_tris), FadeTransform(tripple_tris.copy(), final_tri) ) self.wait() final1 = OldTex("= \\frac{2n + 1}{3} (1 + 2 + 3 + \\cdots + n)") final2 = OldTex("= \\frac{2n + 1}{3} \\frac{(n + 1)n}{2}") final3 = OldTex("= \\frac{(2n + 1)(n + 1)(n)}{6}") final_tri.generate_target() final_tri.target.set_height(2).to_edge(LEFT) for final in (final1, final2, final3): final.next_to(final_tri.target, RIGHT) self.play( MoveToTarget(final_tri), Write(final1), ) self.wait() self.play( FadeOut(final1, UP), FadeIn(final2, UP), ) self.wait() self.play( FadeOut(final2, UP), FadeIn(final3, UP), ) self.play(VGroup(final_tri, final3).animate.set_x(0)) self.wait() # Embed self.embed() def get_triangle_sums(self): dl_dots = OldTex("\\vdots").rotate(-30 * DEGREES) dr_dots = OldTex("\\vdots").rotate(30 * DEGREES) blank = Integer(0).set_opacity(0) n = OldTex("n") np1 = OldTex("(2n + 1)") dots = OldTex("\\dots") tri1 = VGroup( Integer(1).replicate(1), Integer(2).replicate(2), Integer(3).replicate(3), VGroup(dl_dots, blank.copy(), blank.copy(), dr_dots), VGroup(n.copy(), n.copy(), dots, n.copy(), n.copy()), ) tri2 = VGroup( n.replicate(1), VGroup(dl_dots, n).copy(), VGroup(Integer(3), blank, dr_dots).copy(), VGroup(Integer(2), Integer(3), dots, n).copy(), VGroup(Integer(1), Integer(2), Integer(3), dots, n).copy(), ) tri3 = VGroup( n.replicate(1), VGroup(n, dr_dots).copy(), VGroup(dl_dots, blank, Integer(3)).copy(), VGroup(n, dots, Integer(3), Integer(2)).copy(), VGroup(n, dots, Integer(3), Integer(2), Integer(1)).copy(), ) sum_tri = VGroup( np1.replicate(1), np1.replicate(2), np1.replicate(3), VGroup(dl_dots, *blank.replicate(6), dr_dots).copy(), VGroup(np1.copy(), np1.copy(), dots.copy(), np1.copy(), np1.copy()), ) tris = VGroup(tri1, tri2, tri3) for tri in (*tris, sum_tri): for row in tri: row.arrange(RIGHT, buff=0.5) tri.arrange(DOWN, buff=0.5) tris.arrange(RIGHT, buff=2.0) tris.set_width(6) plusses = VGroup( OldTex("+").move_to(tris[:2]), OldTex("+").move_to(tris[1:]), ) parens = OldTex("()")[0] parens.stretch(2, 1) parens.match_height(tris) parens[0].next_to(tris, LEFT) parens[1].next_to(tris, RIGHT) frac = OldTex("\\frac{1}{3}") frac.next_to(parens, LEFT) lhs = VGroup(tris, frac, parens, plusses) parens_copy = parens.copy() sum_tri.match_height(lhs) sum_tri.move_to(tris, LEFT) parens_copy[1].next_to(sum_tri, RIGHT) rhs = VGroup(frac.copy(), sum_tri, parens_copy) rhs.next_to(lhs, DOWN, LARGE_BUFF, aligned_edge=LEFT) # eq = OldTex("=") # eq.next_to(rhs, LEFT) return VGroup(lhs, rhs) class BlendOfMindsets(Scene): def construct(self): Text("Calculate specifics") Text("Understand generalities") Text("You need both") class ListernerEmail(Scene): def construct(self): # Letter rect = Rectangle(4, 7) rect.set_stroke(WHITE, 2) rect.set_fill("#060606", 1) lines = Line(LEFT, RIGHT).get_grid(15, 1) lines.set_width(0.8 * rect.get_width()) lines.arrange(DOWN) lines.set_height(0.7 * rect.get_height(), stretch=True) for n in [3, 8, -1]: lines[n].stretch(0.5, 0, about_edge=LEFT) if n > 0: lines[n + 1].set_opacity(0) lines.move_to(rect) salutation = Text("Hi Prof. Kontorovich,", font_size=30) salutation.next_to(lines, UP, aligned_edge=LEFT) lines.shift(0.2 * DOWN) letter = VGroup(rect, lines, salutation) self.add(rect) self.play( Write(salutation, run_time=1), ShowCreation(lines, rate_func=linear, run_time=3, lag_ratio=0.5), ) self.add(letter) self.wait() self.play(letter.animate.to_edge(LEFT)) # Phrases phrases = VGroup( Text("I’m a PhD student..."), Text( "...I had noticed my mathematical capabilities\n" "starting to fade (to which I attributed getting\n" "older and not being as sharp)..." ), Text( "...I realized that the entire problem, for me at least,\n" "was entirely about my lack of problems and drills." ), ) phrases.arrange(DOWN, buff=2.0, aligned_edge=LEFT) phrases.set_width(8) phrases.next_to(letter, RIGHT, LARGE_BUFF) highlights = VGroup() for i, w in [(0, 1), (5, 3), (11, 2.5)]: hrect = Rectangle(w, 0.1) hrect.set_stroke(width=0) hrect.set_fill(YELLOW, 0.5) hrect.move_to(lines[i], LEFT) highlights.add(hrect) highlights[0].shift(1.5 * RIGHT) highlights[2].align_to(lines, RIGHT) hlines = VGroup() for highlight, phrase in zip(highlights, phrases): hlines.add(VGroup( DashedLine(highlight.get_corner(UR), phrase.get_corner(UL), buff=0.1), DashedLine(highlight.get_corner(DR), phrase.get_corner(DL), buff=0.1), )) hlines.set_stroke(YELLOW, 1) for i in range(3): self.play( FadeIn(highlights[i]), *map(ShowCreation, hlines[i]), GrowFromPoint(phrases[i], highlights[i].get_right()) ) self.wait(2) # Embed self.embed() class FamousMathematicians(Scene): im_height = 3.5 def construct(self): # Portraits images = Group( ImageMobject("Newton"), ImageMobject("Euler"), ImageMobject("Gauss"), ImageMobject("Fourier"), ImageMobject("Riemann_cropped"), ImageMobject("Cauchy"), ImageMobject("Noether"), ImageMobject("Ramanujan"), ) names = VGroup( Text("Isaac Newton"), Text("Leonhard Euler"), Text("Carl Friedrich Gauss"), Text("Joseph Fourier"), Text("Bernhard Riemann"), Text("Augustin Cauchy"), Text("Emmy Noether"), Text("Srinivasa Ramanujan"), ) im_groups = Group() for im, name in zip(images, names): im.set_height(self.im_height) name.scale(0.6) name.set_color(GREY_A) name.next_to(im, DOWN) im_groups.add(Group(im, name)) # im_groups.arrange(RIGHT, aligned_edge=UP, buff=LARGE_BUFF) im_groups.arrange_in_grid(2, 4, aligned_edge=UP, buff=LARGE_BUFF) im_groups.set_width(FRAME_WIDTH - 2) im_groups.to_edge(LEFT) dots = OldTex("\\dots", font_size=72).replicate(2) dots[0].next_to(images[-5], RIGHT, MED_LARGE_BUFF) dots[1].next_to(images[-1], RIGHT, MED_LARGE_BUFF) self.play( LaggedStart(*map(FadeIn, (*im_groups, dots)), lag_ratio=0.25), run_time=5 ) self.wait() self.play( im_groups[0].animate.set_height(6).center().to_edge(LEFT), LaggedStart(*( FadeOut(mob, DR) for mob in (*im_groups[1:], dots) ), lag_ratio=0.25), run_time=2, ) self.wait() # Papers (do in editor) class InventingMath(Scene): def construct(self): pass class AmbientHourglass(ShadowScene): inf_light = True def construct(self): frame = self.camera.frame frame.set_z(3) self.init_frame_rotation() self.remove(self.solid, self.shadow) qint_func = bezier([0, 1, -1.25, 1, 0]) def func(u, v): qf = qint_func(v) x = qf * math.cos(u) y = qf * math.sin(u) x = np.sign(x) * abs(x)**0.5 y = np.sign(y) * abs(y)**0.5 return [x, y, 0.5 - v] ep = 1e-6 hourglass = ParametricSurface(func, (0, TAU), (0 + ep, 1 - ep)) hourglass.set_depth(2) hourglass.set_z(3) hourglass.set_color(BLUE_D) hourglass.set_opacity(0.5) hourglass.set_reflectiveness(0.1) hourglass.set_gloss(0.1) hourglass.set_shadow(0.5) hourglass.always_sort_to_camera(self.camera) mesh = SurfaceMesh(hourglass) mesh.set_flat_stroke(False) mesh.set_stroke(BLUE_B, 0.2, 0.5) mesh_shadow = mesh.copy() mesh_shadow.deactivate_depth_test() solid_group = Group(mesh_shadow, hourglass, mesh) shadow = self.shadow = get_shadow(solid_group) shadow[1].always_sort_to_camera(self.camera) self.add(solid_group, shadow) for x in range(30): self.random_toss(solid_group) self.wait() self.begin_ambient_rotation( solid_group, speed=0.5, initial_axis=[1, 0, 1], ) self.wait(35) class QuantifyConvexity(Scene): def construct(self): # Ask question nonconvex = Text("Non-convex") nonconvex.to_edge(UP) nonconvex.set_color(RED) question = Text("Can we quantify this?") question.next_to(nonconvex, DOWN, buff=1.5) question.to_edge(LEFT) arrow = Arrow(question, nonconvex.get_corner(DL)) self.play(Write(nonconvex)) self.wait() self.play( FadeIn(question, 0.5 * DOWN), ShowCreation(arrow), ) self.wait() # Binary choice double_arrow = OldTex("\\leftrightarrow") double_arrow.move_to(nonconvex) convex = Text("Convex") convex.set_color(GREEN) convex.next_to(double_arrow, RIGHT) self.play( nonconvex.animate.next_to(double_arrow, LEFT), Write(double_arrow), FadeIn(convex, shift=0.25 * RIGHT), Uncreate(arrow), FadeOut(question, 0.5 * DOWN), ) self.wait() # Spectrum interval = UnitInterval(width=7) interval.add_numbers() interval.to_corner(UL, buff=LARGE_BUFF) self.play( FadeTransform(double_arrow, interval), convex.animate.scale(0.5).next_to(interval.n2p(1), UP), nonconvex.animate.scale(0.5).next_to(interval.n2p(0), UP), ) self.wait() # Fraction shadow = get_key_result("Solid").slice_by_tex(None, "=") shadow.add(shadow[0].copy()) shadow.remove(shadow[0]) four_shadow = VGroup(OldTex("4 \\cdot"), shadow) four_shadow.arrange(RIGHT, buff=SMALL_BUFF) sa = Text("Surface area") frac = VGroup( four_shadow, Line().match_width(four_shadow).set_stroke(width=2), sa ) frac.arrange(DOWN) frac.set_width(3) frac.to_corner(UR) frac.match_y(interval) self.play(Write(shadow)) self.play(FadeIn(four_shadow[0])) self.wait() self.play(ShowCreation(frac[1])) self.play(FadeIn(sa)) self.wait() # Dot dot = GlowDot() dot.scale(2) dot.move_to(interval.n2p(1)) self.play(FadeIn(dot, RIGHT)) self.wait() self.play(dot.animate.move_to(interval.n2p(0.6)), run_time=2) self.wait() class GoalsOfMath(TeacherStudentsScene): def construct(self): words = Text("The goal of math\nis to answer questions") words.move_to(self.hold_up_spot, DOWN) words.to_edge(RIGHT, buff=2.0) aq = words.get_part_by_text("answer questions") aq.set_color(BLUE) dni = Text( "develop new ideas", t2c={"new ideas": YELLOW}, t2s={"new ideas": ITALIC}, ) dni.move_to(aq, LEFT) self.play( self.teacher.change("raise_right_hand", words), self.change_students(*3 * ["pondering"], look_at=words), Write(words) ) self.wait(2) self.add(aq, self.teacher) self.play( aq.animate.shift(0.5 * DOWN).set_opacity(0.2), Write(dni), self.teacher.change("well", words), self.change_students(*3 * ["thinking"], look_at=words) ) self.wait(3) class InfatuationWithGenerality(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("Why are mathematicians\\\\obsessed with abstractions?"), index=0, added_anims=[ self.students[1].change("tease"), self.students[2].change("pondering"), ] ) self.play( self.teacher.change("well"), ) self.wait(6) class NumberphileFrame(VideoWrapper): animate_boundary = True title = "Bertrand's Paradox (with Numberphile)" title_config = { "font_size": 48 } wait_time = 16 class ByLine(Scene): def construct(self): lines = VGroup( OldTexText("Artwork by\\\\", "Kurt Bruns"), OldTexText("Music by\\\\", "Vince Rubinetti"), OldTexText("Other stuff\\\\", "Grant Sanderson"), ) for line in lines: line[0].set_color(GREY_B) line[1].scale(1.2, about_edge=UP) lines.arrange(DOWN, buff=1.5) self.add(lines) class EndScreen(PatreonEndScreen): pass class ThumbnailBackground(ShadowScene): plane_dims = (32, 20) def construct(self): frame = self.camera.frame frame.reorient(0) cube = self.solid cube.set_shadow(0.5) light = self.light light.next_to(cube, OUT, buff=2) light.shift(2 * LEFT) light.move_to(50 * OUT) gc = self.glow.replicate(10) gc.set_opacity(0.3) gc.clear_updaters() gc.arrange(RIGHT).match_width(cube) gc.move_to(6 * OUT) self.add(gc) outline = self.get_shadow_outline() light_lines = self.get_light_lines(outline) self.add(outline, light_lines) self.randomly_reorient(cube) self.randomly_reorient(cube) self.wait()
from manim_imports_ext import * def get_tripple_underline(mobject, buff=0.1): ul1 = Underline(mobject, buff=buff).set_stroke(BLUE_C, 3) ul2 = Underline(ul1).scale(0.9).set_stroke(BLUE_D, 2) ul3 = Underline(ul2).scale(0.9).set_stroke(BLUE_E, 1) return VGroup(ul1, ul2, ul3) def get_h_line(): line = DashedLine(ORIGIN, FRAME_WIDTH * RIGHT) line.center() return line # Scenes class TableOfContents(Scene): def construct(self): # plane = NumberPlane() # self.add(plane, FullScreenFadeRectangle(opacity=0.8)) items = VGroup( Text("Summer of Math Exposition"), Text("The Universal Advice"), Text("How to structure math explanations"), Text("Thoughts on animation software"), Text("The 3b1b Podcast/Second channel"), ) items.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) items.to_edge(LEFT, buff=0.5) self.add(items) for i in range(len(items)): for item in items: item.generate_target() if item is items[i]: height = 0.55 opacity = 1.0 else: height = 0.3 opacity = 0.25 item.target.scale( height / item[0].get_height(), about_edge=LEFT ) item.target.set_opacity(opacity) self.play(*map(MoveToTarget, items)) self.wait() class SoME1Name(Scene): def construct(self): strings = ["Summer", "of", "Math", "Exposition", "#1"] lens = list(map(lambda s: len(s) + 1, strings)) indices = [0, *np.cumsum(lens)] phrase = Text(" ".join(strings)) phrase.set_width(12) words = VGroup() for i1, i2 in zip(indices, indices[1:]): words.add(phrase[i1:i2]) acronym = VGroup(*(word[0].copy() for word in words[:-1])) acronym.add(words[-1][-1].copy()) acronym.generate_target() acronym.target.arrange(RIGHT, buff=SMALL_BUFF, aligned_edge=DOWN) acronym.target.move_to(DOWN) self.play(LaggedStartMap(FadeIn, words, lag_ratio=0.5, run_time=1)) self.wait() self.play( # FadeOut(phrase), phrase.animate.move_to(UP), MoveToTarget(acronym) ) self.wait() self.play( ShowCreation(get_tripple_underline(words[2])), words[2].animate.set_color(BLUE_B), ) self.wait() class LinkAndDate(Scene): def construct(self): words = link, date = VGroup( Text("https://3b1b.co/SoME1", font="CMU Serif"), Text("August 22nd", font="CMU Serif") ) words.set_width(10) words.arrange(DOWN, buff=0.5) words.set_stroke(BLACK, 5, background=True) lines = get_tripple_underline(date) details = Text("(Full details here)") details.to_corner(UR) arrow = Arrow(details, link, buff=0.5) self.play(Write(link), run_time=1) self.wait() self.add(lines, words) self.play( FadeIn(date, scale=1.2, rate_func=squish_rate_func(smooth, 0.3, 0.7)), ShowCreation(lines, lag_ratio=0.25) ) self.wait() self.play(FadeIn(details), GrowArrow(arrow)) self.wait() class Featuring(TeacherStudentsScene): def construct(self): screen = ScreenRectangle() screen.set_height(4) screen.to_corner(UL) screen.set_stroke(WHITE, 2) screen.set_fill(BLACK, 1) self.add(screen) words = OldTexText("Your work here") words.set_width(screen.get_width() - 1) words.move_to(screen) self.play( self.teacher.change("tease"), self.change_students(*3 * ["hooray"], look_at=screen), FadeIn(screen, UP) ) self.play(Write(words)) self.play(ShowCreation(get_tripple_underline(words))) self.wait(5) self.student_says( OldTexText("Anything\\\\else?"), target_mode="raise_left_hand", look_at=self.teacher, ) self.play(self.teacher.change("sassy")) self.wait(2) class Constraints(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("What are the\\\\constraints?"), added_anims=[self.teacher.change("tease")] ) self.wait(3) class TopicChoice(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("What kind of\\\\topics?"), added_anims=[self.teacher.change("tease")], index=1, ) self.wait(3) class PartialFraction(Scene): def construct(self): frac = OldTex( r"\frac{x+9}{(x-3)(x+5)} = \frac{?}{x - 3} + \frac{?}{x + 5}" ) frac.set_width(10) self.add(frac) class TrigIdentity(Scene): def construct(self): plane = NumberPlane().scale(2) circle = Circle(radius=2) circle.set_stroke(YELLOW, 2) theta_tracker = ValueTracker(60 * DEGREES) get_theta = theta_tracker.get_value def get_point(): return circle.pfp(get_theta() / TAU) dot = Dot() f_always(dot.move_to, get_point) radial_line = always_redraw(lambda: Line(plane.c2p(0, 0), get_point())) tan_line = always_redraw( lambda: Line(get_point(), plane.c2p(1 / math.cos(get_theta()), 0), stroke_color=RED) ) sec_line = always_redraw( lambda: Line(plane.c2p(0, 0), tan_line.get_end(), stroke_color=PINK) ) def get_one_label(): one = Integer(1) one.next_to(radial_line.get_center(), UL, SMALL_BUFF) return one def get_tan_label(): label = OldTex("\\tan(\\theta)") label.set_color(RED) point = tan_line.get_center() label.next_to(point, UP, SMALL_BUFF) label.rotate(tan_line.get_angle(), about_point=point) label.set_stroke(BLACK, 3, background=True) return label def get_sec_label(): label = OldTex("\\sec(\\theta)") label.set_color(PINK) label.next_to(sec_line, DOWN, SMALL_BUFF) label.set_stroke(BLACK, 3, background=True) return label one_label = always_redraw(get_one_label) tan_label = always_redraw(get_tan_label) sec_label = always_redraw(get_sec_label) arc = always_redraw(lambda: Arc(0, get_theta(), radius=0.25)) arc_label = OldTex("\\theta", font_size=36) arc_label.next_to(arc, RIGHT, SMALL_BUFF, DOWN).shift(SMALL_BUFF * UP) equation = OldTex( "\\tan^2(\\theta) + 1 = \\sec^2(\\theta)", tex_to_color_map={ "\\tan": RED, "\\sec": PINK, }, font_size=60 ) equation.to_corner(UL) equation.set_stroke(BLACK, 7, background=True) self.add(plane) self.add(circle) self.add(equation) self.add(radial_line) self.add(tan_line) self.add(sec_line) self.add(dot) self.add(one_label) self.add(tan_label) self.add(sec_label) self.add(arc) self.add(arc_label) angles = [40 * DEGREES, 70 * DEGREES] for angle in angles: self.play(theta_tracker.animate.set_value(angle), run_time=4) class TeacherStudentPairing(Scene): def construct(self): randy = Randolph(height=2.5) morty = Mortimer(height=3.0) pis = VGroup(randy, morty) pis.arrange(RIGHT, buff=3, aligned_edge=DOWN) pis.to_edge(DOWN, buff=1.5) self.add(pis) self.add(Text("Teacher").next_to(morty, DOWN)) self.add(Text("Student").next_to(randy, DOWN)) teacher_label = Text("Delivers/writes lesson", font_size=36) student_label = Text("Produces/edits/animates", font_size=36) teacher_label.next_to(morty, UP, buff=1.5).shift(RIGHT) student_label.next_to(randy, UP, buff=1.5).shift(LEFT) teacher_arrow = Arrow(teacher_label, morty) student_arrow = Arrow(student_label, randy) self.play( Write(student_label), GrowArrow(student_arrow), randy.change("hooray", student_label) ) self.wait() self.play( Write(teacher_label), GrowArrow(teacher_arrow), morty.change("pondering", teacher_label) ) self.wait() for x in range(4): self.play(Blink(random.choice(pis))) self.wait(random.random()) class Grey(Scene): def construct(self): self.add(FullScreenRectangle().set_fill(GREY_D, 1)) class ButIHaveNoExperience(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("But I have no\\\\experience!"), index=0, target_mode="pleading", ) self.play_student_changes( "pleading", "pondering", "pondering", look_at=self.students[0].bubble, ) self.students[0].look_at(self.teacher.eyes) self.play(self.teacher.change("tease", self.students[0].eyes)) self.wait(4) class ContentAdvice(Scene): def construct(self): title = Text("Advice for structuring math explanations") title.set_width(10) title.to_edge(UP) underline = Underline(title).scale(1.2).set_stroke(GREY_B, 2) self.play(FadeIn(title, UP)) self.play(ShowCreation(underline)) points = VGroup( Text("1) Concrete before abstract"), Text("2) Topic choice > production quality"), Text("3) Be niche"), Text("4) Know your genre"), Text("5) Definitions are not the beginning"), ) points.arrange(DOWN, buff=0.7, aligned_edge=LEFT) points.next_to(title, DOWN, buff=1.0) self.play(LaggedStartMap( FadeIn, VGroup(*(point[:2] for point in points)), shift=0.25 * RIGHT )) self.wait() for point in points: self.play(Write(point[2:])) self.wait() gt0 = OldTex("> 0") gt0.next_to(points[1], RIGHT) self.play( VGroup(points[0], *points[2:]).animate.set_opacity(0.25) ) self.play(Write(gt0)) self.play(ShowCreation(get_tripple_underline( VGroup(points[1].get_part_by_text("production quality"), gt0) ))) self.wait() class LayersOfAbstraction(Scene): 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.play(FadeIn(layer, shift=0.1 * UP)) def show_pairwise_relations(self): p1, p2 = [layer.get_left() for layer 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.play( GrowArrow(down_arrow), FadeIn(down_words) ) self.wait() self.play( ReplacementTransform(down_arrow, up_arrow, path_arc=PI), FadeTransform(down_words, up_words) ) self.wait() self.play(FadeOut(up_arrow), FadeOut(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.wait() 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_gloss(1) # 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(UL), 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(-np.arctan(1 / 2)).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 FractionsExample(Scene): def construct(self): expr = OldTex("{2 \\over 3}", "+", "{1 \\over 5}") expr.scale(1.5) h_line = DashedLine(ORIGIN, FRAME_WIDTH * RIGHT).center() quantities = Text("Quantities") quantities.to_corner(UL, buff=MED_SMALL_BUFF) quantities.shift(FRAME_HEIGHT * DOWN / 2) numbers = Text("Numbers") numbers.to_corner(UL, buff=MED_SMALL_BUFF) def get_pie(numer, denom, color=BLUE, height=1.5): pie = VGroup(*( AnnularSector( angle=TAU / denom, start_angle=i * TAU / denom, inner_radius=0.0, outer_radius=1.0, ) for i in range(denom) )) pie.set_stroke(WHITE, 2) pie.set_fill(BLACK, 1) pie[:numer].set_fill(color) pie.set_height(height) return pie pies = VGroup( get_pie(2, 3, color=BLUE_C), OldTex("+"), get_pie(1, 5, color=BLUE_D), ) pies.arrange(RIGHT) pies.move_to(FRAME_HEIGHT * DOWN / 4) self.add(expr) self.wait() self.play( expr.animate.move_to(FRAME_HEIGHT * UP / 4), ShowCreation(h_line), Write(numbers), ) self.play( *( FadeTransform(expr[i].copy(), pies[i]) for i in range(len(pies)) ), FadeTransform(numbers.copy(), quantities) ) self.wait() # Evaluate bottom bottom_eq = OldTex("=") bottom_eq.move_to(pies[2]) self.play( pies.animate.next_to(bottom_eq, LEFT), Write(bottom_eq), ) bottom_rhs = VGroup( *pies[0][:2].copy(), pies[2][0].copy() ) bottom_rhs.generate_target() bottom_rhs.target[2].shift(pies[0].get_center() - pies[2].get_center()) bottom_rhs.target[2].rotate(TAU * 2 / 3, about_point=pies[0].get_center()) bottom_rhs.target.next_to(bottom_eq, RIGHT) self.play(MoveToTarget(bottom_rhs)) self.wait() # Evaluate top rhs = OldTex( "=", "{10 \\over 15}", "+", "{3 \\over 15}", "=", "{13 \\over 15}" ) rhs.match_height(expr) rhs.next_to(expr, RIGHT) expr.generate_target() VGroup(expr.target, rhs).set_x(0) self.play( MoveToTarget(expr), FadeIn(rhs, lag_ratio=0.1) ) self.wait() # Show overlays overlays = VGroup() for pie in (*pies[::2], bottom_rhs): overlay = get_pie(0, 15) overlay.set_fill(BLACK, 0) overlay.set_stroke(WHITE, 1, opacity=0.5) overlay.move_to(pie) overlays.add(overlay) self.play(ShowCreation(overlays)) self.wait() class CalculusStatement(Scene): def construct(self): statement = VGroup( OldTexText( "If $f(x)$ has a local maximum or minimum\\\\" "at $x_0$, and $f$ is differentiable at $x_0$, then" ), OldTex("\\frac{df}{dx}(x_0) = 0.") ) statement.arrange(DOWN) statement[1].scale(1.5, about_edge=UP).shift(0.25 * DOWN) self.add(statement) class ExamplesOfFunctions(Scene): def construct(self): plane = NumberPlane((-15, 15, 5), (-10, 10, 5)) plane.scale(0.5) self.add(plane) graphs = VGroup( plane.get_graph(lambda x: -x * (x - 4)), plane.get_graph(lambda x: x / 3), plane.get_graph(lambda x: (1 / 3) * x**3 - 2 * x + 1), plane.get_graph(lambda x: -5 * x * np.exp(-x**2 / 2)), ) graph_labels = VGroup( OldTex("f(x) = ", "-x^2 - 4x"), OldTex("f(x) = ", "x / 3"), OldTex("f(x) = ", "x^3 / 3- 2x + 1"), OldTex("f(x) = ", "-(5x) e^{-{1 \\over 2} x^2}"), ) colors = [YELLOW, RED, TEAL, PINK] for graph, color, label in zip(graphs, colors, graph_labels): graph.set_stroke(color) label.scale(1.5) label[1].set_color(color) label.next_to(plane.c2p(0, 5), UR, SMALL_BUFF) label.set_stroke(BLACK, 3, background=True) self.play( FadeIn(graph_labels[0]), ShowCreation(graphs[0]), run_time=1.5 ) self.wait() for i in range(1, len(graphs)): self.play( ReplacementTransform(graphs[i - 1], graphs[i]), FadeTransform(graph_labels[i - 1], graph_labels[i]), run_time=0.5 ) self.wait(1.5) class SpecificCases(Scene): def construct(self): self.add(FullScreenRectangle()) title = Text("Applications for optimization", font_size=72) title.to_edge(UP) self.add(title) grid = Square().get_grid(1, 2, buff=0) grid.set_height(6) grid.set_width(13, stretch=True) grid.to_edge(DOWN) grid.set_fill(BLACK, 1) labels = VGroup( Text("Profit maximization"), Text("Distance between curves"), ) for label, square in zip(labels, grid): label.next_to(square.get_top(), DOWN) self.add(grid) self.add(labels) # Fill 'em r_axes = Axes( x_range=(-3, 3), y_range=(-3, 3), width=6, height=4.5, axis_config={"include_tip": False}, ) r_axes.move_to(grid[1], DOWN).shift(0.25 * UP) circle = Circle() circle.set_height(get_norm(r_axes.c2p(0, 0) - r_axes.c2p(0, 2))) circle.move_to(r_axes.c2p(1, 1)) circle.set_stroke(YELLOW) parabola = r_axes.get_graph( lambda x: 0.2 * (x**2 - 4) ) parabola.set_stroke(RED_D) smallest_line = Line( circle.pfp(0.83), parabola.pfp(0.76), stroke_width=3 ) self.add(circle, parabola, smallest_line) l_axes = Axes( (0, 10), (-3, 8), width=6, height=4.5, ) l_axes.move_to(grid[0], DOWN).shift(0.25 * UP) x_label = Text("production", font_size=24) x_label.next_to(l_axes.x_axis, DOWN, SMALL_BUFF, aligned_edge=RIGHT) y_label = Text("profit", font_size=24) y_label.next_to(l_axes.y_axis, RIGHT, SMALL_BUFF, aligned_edge=UP) graph = l_axes.get_graph( lambda x: -0.07 * x * (x - 4) * (x - 9.5) ) graph.set_stroke(GREEN, 3) self.add(l_axes, x_label, y_label, graph) class ConcreteToAbstract(Scene): def construct(self): self.add( get_h_line().move_to(FRAME_HEIGHT * UP / 6), get_h_line().move_to(FRAME_HEIGHT * DOWN / 6), ) labels = VGroup( Text("Algebra"), Text("Numbers"), Text("Quantities"), ) for i, label in enumerate(labels): label.scale(30 / label.font_size) label.to_corner(UL, buff=SMALL_BUFF) label.shift(i * FRAME_HEIGHT * DOWN / 3) self.add(labels) # Algebra expr = OldTex( "x^2 - y^2 = (x + y)(x - y)", tex_to_color_map={"x": BLUE_D, "y": BLUE_B} ) expr.scale(1.5) expr.move_to(FRAME_HEIGHT * UP / 3) expr.to_edge(LEFT, buff=LARGE_BUFF) self.add(expr) # Numbers tricks = VGroup( OldTex("143 = (12 + 1)(12 - 1) = 13 \\cdot 11"), OldTex("3{,}599 = (60 + 1)(60 - 1) = 61 \\cdot 59"), OldTex("9{,}991 = (100 + 3)(100 - 3) = 103 \\cdot 97"), ) tricks.arrange(DOWN, aligned_edge=LEFT) tricks[0].shift((tricks[1][0][5].get_x() - tricks[0][0][3].get_x()) * RIGHT) tricks.set_height(FRAME_HEIGHT / 3 - 1) tricks.center() brace = Brace(tricks, LEFT) words = OldTexText("Factoring\\\\tricks", font_size=30) words.set_color(GREY_A) words.next_to(brace, LEFT) VGroup(tricks, brace, words).to_edge(LEFT, buff=MED_LARGE_BUFF) self.add(tricks, brace, words) self.wait() # Arrows arrow = Arrow( ORIGIN, FRAME_HEIGHT * UP / 3, path_arc=60 * DEGREES, thickness=0.15, fill_color=YELLOW, stroke_color=YELLOW, ) up_arrows = VGroup(arrow.copy().shift(FRAME_HEIGHT * DOWN / 3), arrow) up_arrows.to_edge(RIGHT, buff=1.5) self.play(Write(up_arrows, lag_ratio=0.5)) self.wait() top_words = Text("Once you understand\n algebra...") top_words.next_to(up_arrows, UP) top_words.shift_onto_screen() top_words.set_color(YELLOW) self.play(FadeIn(top_words, lag_ratio=0.05)) self.play(LaggedStartMap(Rotate, up_arrows, angle=PI, axis=RIGHT)) self.wait() new_top_words = Text("If you're learning\n algebra.") new_top_words.move_to(top_words) new_top_words.match_color(top_words) self.play( FadeTransform(top_words, new_top_words), LaggedStartMap(Rotate, up_arrows, angle=PI, axis=RIGHT) ) self.wait() self.embed() class DifferenceOfSquares(Scene): def construct(self): x = 6 y = 1 squares = VGroup(*[ VGroup(*[ Square() for x in range(x) ]).arrange(RIGHT, buff=0) for y in range(x) ]).arrange(DOWN, buff=0) squares.set_height(4) squares.set_stroke(BLUE_D, 3) squares.set_fill(BLUE_D, 0.5) last_row_parts = VGroup() for row in squares[-y:]: row[-y:].set_color(GREY_E) row[:-y].set_color(BLUE_B) last_row_parts.add(row[:-y]) squares.to_edge(LEFT) arrow = Vector(RIGHT, color=WHITE) arrow.shift(1.5 * LEFT) squares.next_to(arrow, LEFT) new_squares = squares[:-y].copy() new_squares.next_to(arrow, RIGHT) new_squares.align_to(squares, UP) x1 = OldTex(str(x)).set_color(BLUE_D) x2 = x1.copy() x1.next_to(squares, UP) x2.next_to(squares, LEFT) y1 = OldTex(str(y)).set_color(BLUE_B) y2 = y1.copy() y1.next_to(squares[-int(np.ceil(y / 2))], RIGHT) y2.next_to(squares[-1][-int(np.ceil(y / 2))], DOWN) xpy = OldTex(str(x), "+", str(y)) xmy = OldTex(str(x), "-", str(y)) for mob in xpy, xmy: mob[0].set_color(BLUE) mob[2].set_color(BLUE_B) xpy.next_to(new_squares, UP) # xmy.rotate(90 * DEGREES) xmy.next_to(new_squares, RIGHT) xmy.shift(squares[0][0].get_width() * RIGHT) self.add(squares, x1, x2, y1, y2) self.play( ReplacementTransform( squares[:-y].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 AbstractVectorSpace(Scene): def construct(self): self.add(get_h_line()) top_title = Text("Abstract vector space axioms") top_title.to_edge(UP, buff=MED_SMALL_BUFF) low_title = Text("Concrete vectors") low_title.next_to(ORIGIN, DOWN, buff=MED_SMALL_BUFF) self.add(top_title, low_title) # Vectors kw = {"bracket_h_buff": 0.1} columns = VGroup( Matrix([["1"], ["1"]], **kw).set_color(BLUE_B), OldTex("+"), Matrix([["-2"], ["3"]], **kw).set_color(BLUE_D), OldTex("="), Matrix([["1 - 2"], ["1 + 3"]], **kw).set_color(GREEN), ) columns.arrange(RIGHT, buff=SMALL_BUFF) columns.next_to(low_title, DOWN, LARGE_BUFF) columns.to_edge(LEFT) arrows = VGroup( Arrow(ORIGIN, (1, 1), fill_color=BLUE_B, buff=0), Arrow((1, 1), (-1, 4), fill_color=BLUE_D, buff=0), Arrow(ORIGIN, (-1, 4), fill_color=GREEN, buff=0), ) arrows.match_height(columns) arrows.scale(1.5) arrows.match_y(columns) arrows.match_x(low_title) funcs = OldTex( "(f + g)(x) = f(x) + g(x)", tex_to_color_map={"f": BLUE_B, "g": BLUE_D} ) funcs.next_to(arrows, RIGHT, LARGE_BUFF) self.add(columns) self.add(arrows) self.add(funcs) # Axioms u_tex = "\\vec{\\textbf{u}}" w_tex = "\\vec{\\textbf{w}}" v_tex = "\\vec{\\textbf{v}}" axioms = VGroup(*it.starmap(Tex, [ ( "1. \\,", u_tex, "+", "(", v_tex, "+", w_tex, ")=(", u_tex, "+", v_tex, ")+", w_tex ), ( "2. \\,", v_tex, "+", w_tex, "=", w_tex, "+", v_tex ), ( "3. \\,", "\\textbf{0}+", v_tex, "=", v_tex, "\\text{ for all }", v_tex ), ( "4. \\,", "\\forall", v_tex, "\\;\\exists", w_tex, "\\text{ s.t. }", v_tex, "+", w_tex, "=\\textbf{0}" ), ( "5. \\,", "a", "(", "b", v_tex, ")=(", "a", "b", ")", v_tex ), ( "6. \\,", "1", v_tex, "=", v_tex ), ( "7. \\,", "a", "(", v_tex, "+", w_tex, ")", "=", "a", v_tex, "+", "a", w_tex ), ( "8. \\,", "(", "a", "+", "b", ")", v_tex, "=", "a", v_tex, "+", "b", v_tex ), ])) for axiom in axioms: axiom.set_color_by_tex_to_color_map({ u_tex: BLUE_B, w_tex: BLUE_D, v_tex: GREEN, }) axioms[:4].arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) axioms[4:].arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) axioms[4:].next_to(axioms[:4], RIGHT, buff=1.5) axioms.set_height(2.5) axioms.next_to(top_title, DOWN) for axiom in axioms: self.play(FadeIn(axiom)) self.add(axioms) class Nicheness(Scene): def construct(self): words = OldTexText( "Perceived ", "nicheness", " $>$ ", "Actual ", "nichness", ) words[:2].set_color(BLUE_B) words[3:].set_color(BLUE_D) self.add(words[:2]) self.wait() self.play( FadeTransformPieces(words[:2].copy(), words[3:], path_arc=PI / 2), GrowFromCenter(words[2]), ) self.wait() class TransitionToProductionQuality(TeacherStudentsScene): def construct(self): self.play( self.students[0].change("pondering"), self.students[2].change("pondering"), ) self.student_says( OldTexText("What parts of\\\\production quality matter?"), index=1 ) self.play( self.teacher.change("happy"), ) self.wait(3) class SurfaceExample(Scene): CONFIG = { "camera_class": ThreeDCamera, } def construct(self): torus1 = Torus(r1=1, r2=1) torus2 = Torus(r1=3, r2=1) sphere = Sphere(radius=2.5, resolution=torus1.resolution) # You can texture a surface with up to two images, which will # be interpreted as the side towards the light, and away from # the light. These can be either urls, or paths to a local file # in whatever you've set as the image directory in # the custom_config.yml file day_texture = "EarthTextureMap" night_texture = "NightEarthTextureMap" surfaces = [ TexturedSurface(surface, day_texture, night_texture) for surface in [sphere, torus1, torus2] ] for mob in surfaces: mob.mesh = SurfaceMesh(mob) mob.mesh.set_stroke(BLUE, 1, opacity=0.5) # Set perspective frame = self.camera.frame frame.set_euler_angles( theta=-30 * DEGREES, phi=70 * DEGREES, ) surface = surfaces[0] self.play( FadeIn(surface), ShowCreation(surface.mesh, lag_ratio=0.01, run_time=3), ) for mob in surfaces: mob.add(mob.mesh) surface.save_state() self.play(Rotate(surface, PI / 2), run_time=2) for mob in surfaces[1:]: mob.rotate(PI / 2) self.play( Transform(surface, surfaces[1]), run_time=3 ) self.play( Transform(surface, surfaces[2]), # Move camera frame during the transition frame.animate.increment_phi(-10 * DEGREES), frame.animate.increment_theta(-20 * DEGREES), run_time=3 ) # Add ambient rotation frame.add_updater(lambda m, dt: m.increment_theta(-0.1 * dt)) # Play around with where the light is light = self.camera.light_source self.add(light) light.save_state() self.play(light.animate.move_to(3 * IN), run_time=5) self.play(light.animate.shift(10 * OUT), run_time=5) class Spotlight(Scene): def construct(self): self.add(FullScreenRectangle()) screen = ScreenRectangle() screen.set_height(6.0) screen.set_stroke(WHITE, 2) screen.set_fill(BLACK, 1) screen.to_edge(DOWN) animated_screen = AnimatedBoundary(screen) self.add(screen, animated_screen) self.wait(16) class BadManimExample(Scene): def construct(self): words = OldTexText( "Does any of this ", "need to be ", "animated?\\\\", "Much less programatically?" ) words[-1].shift(MED_SMALL_BUFF * DOWN) words.set_width(FRAME_WIDTH - 2) self.play(Write(words[0]), run_time=1) self.play(FadeIn(words[1], scale=10, shift=0.25 * UP)) self.play(TransformMatchingShapes(words[0].copy(), words[2], path_arc=PI / 2)) self.wait() self.play(Transform( VGroup(*words[0], *words[1], *words[2]).copy(), words[3], lag_ratio=0.03, run_time=1 )) self.wait() class WhereCanIEngageWithOthers(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("Where can I find\\\\others joining SoME1?"), index=0, added_anims=[ self.students[1].change("pondering", UL), self.students[2].change("pondering", UL), ] ) self.play( self.teacher.change("tease"), ) self.wait(4) class BeTheFirst(Scene): def construct(self): circ = Circle(color=RED) circ.stretch(5, 0) circ.set_height(0.4) circ.to_edge(LEFT) words = Text("Be the first!") words.next_to(circ, RIGHT, aligned_edge=UP) words.set_color(RED) self.play(ShowCreation(circ)) self.play(Write(words)) self.wait() class SoME1EndScreen(PatreonEndScreen): pass
from manim_imports_ext import * # Colors COL_COLORS = [MAROON_B, MAROON_C] EIGEN_COLORS = [TEAL_A, TEAL_D] MEAN_COLOR = BLUE_B PROD_COLOR = BLUE_D def det_path_anim(matrix, run_time=2): path = VMobject() path.set_points_smoothly([ matrix.get_corner(UL), *[ matrix.get_entries()[i].get_center() for i in [0, 3, 1, 2] ], matrix.get_corner(DL), ]) path.set_stroke(BLUE, 3) return VShowPassingFlash(path, time_width=1, run_time=run_time, rate_function=linear) def get_diag_rects(matrix, color=MEAN_COLOR, off_diagonal=False): if off_diagonal: entries = matrix.get_entries()[1:3] else: entries = matrix.get_entries()[0::3] return VGroup(*( SurroundingRectangle(entry, buff=SMALL_BUFF, color=color) for entry in entries )) def get_prism(verts, depth=2): result = VGroup() result.add(Polygon(*verts)) zv = depth * OUT for v1, v2 in zip(verts, [*verts[1:], verts[0]]): result.add(Polygon(v1, v2, v2 + zv, v1 + zv)) result.add(Polygon(*verts).shift(zv)) result.set_stroke(width=0) result.set_fill(GREY, 1) result.set_gloss(1) for mob in list(result): m2 = mob.copy() m2.reverse_points() result.add(m2) result.apply_depth_test() return result def get_mod_mat(matrix, h_buff=1.3, v_buff=0.8, t2c={}): t2c["\\lambda"] = EIGEN_COLORS[1] mod_mat = Matrix( [ [matrix[0][0] + " - \\lambda", matrix[0][1]], [matrix[1][0], matrix[1][1] + " - \\lambda"], ], element_to_mobject_config={"tex_to_color_map": t2c}, h_buff=h_buff, v_buff=v_buff, ) return mod_mat def get_det_mod_mat(mod_mat): parens = OldTex("(", ")") parens.stretch(2, 1) parens.match_height(mod_mat) parens[0].next_to(mod_mat, LEFT, SMALL_BUFF) parens[1].next_to(mod_mat, RIGHT, SMALL_BUFF) det = Text("det") det.next_to(parens, LEFT, SMALL_BUFF) return VGroup(det, parens, mod_mat) def get_shadow(vmobject, width=50, n_copies=25): shadow = VGroup() for w in np.linspace(width, 0, n_copies): part = vmobject.copy() part.set_fill(opacity=0) part.set_stroke(BLACK, width=w, opacity=1.0 / width) shadow.add(part) return shadow # Scenes class Thumbnail(Scene): def construct(self): grid = NumberPlane(faded_line_ratio=0) grid.apply_matrix([[3, 1], [0, 2]]) grid.set_opacity(0.5) self.add(grid) mat_mob = IntegerMatrix([[3, 1], [4, 3]], h_buff=0.8) mat_mob.set_height(3) mat_mob.add_to_back(BackgroundRectangle(mat_mob)) mat_mob.to_edge(UP, buff=MED_SMALL_BUFF) self.add(mat_mob) a, b, c, d = mat_mob.get_entries() a_to_d = d.get_center() - a.get_center() rect = Rectangle(height=1, width=get_norm(a_to_d) + 1) rect.round_corners() rect.set_stroke(MEAN_COLOR, 3) rect.rotate(angle_of_vector(a_to_d)) rect.move_to(VGroup(a, d)) rect2 = rect.copy() rect2.set_color(PROD_COLOR) rect2.rotate(-2 * angle_of_vector(a_to_d)) rect2.move_to(rect) dashed_rects = VGroup( DashedVMobject(rect.insert_n_curves(100), num_dashes=50), DashedVMobject(rect2.insert_n_curves(100), num_dashes=50), ) self.add(dashed_rects) answer = OldTex( "\\lambda_1, \\lambda_2 = {3} \\pm \\sqrt{\\,{3}^2 - {5}} = 5, 1", tex_to_color_map={"{3}": MEAN_COLOR, "{p}": PROD_COLOR} ) answer.add_background_rectangle() answer.set_width(12) answer.to_edge(DOWN) # answer.shift(SMALL_BUFF * UP) self.add(answer) arrow = Arrow(mat_mob, answer, fill_color=YELLOW, thickness=0.15, buff=0.3) arrow.set_stroke(BLACK, 30, background=True) arrow.shift(0.2 * UP) self.add(arrow) return #old backdrop = ImageMobject("QuickEigenThumbnailBackdrop") backdrop.set_height(FRAME_HEIGHT) backdrop.set_opacity(0.5) self.add(backdrop) buff = 0.75 det = get_det_mod_mat(get_mod_mat([["3", "1"], ["4", "1"]])) det.set_height(2.25) det.to_corner(UR, buff=buff) self.add(get_shadow(det), det) not_this = OldTexText("Not\\\\this") not_this.match_height(det) not_this.to_corner(UL, buff=buff) not_this.set_color(RED) self.add(not_this) kw = { "tex_to_color_map": { "\\lambda_1": EIGEN_COLORS[0], "\\lambda_2": EIGEN_COLORS[1], "M": YELLOW, } } facts = VGroup( OldTex("\\text{det}(M) = \\,\\, \\lambda_1 \\cdot \\lambda_2", **kw), OldTex("\\text{tr}(M) = \\lambda_1 + \\lambda_2", **kw), ) facts.arrange(DOWN, buff=MED_SMALL_BUFF, index_of_submobject_to_align=2) facts.match_height(det) facts.match_x(det) facts.set_y(-det.get_y()) self.add(get_shadow(facts), facts) use_these = OldTexText("Use\\\\these") use_these.match_height(not_this) use_these.to_corner(DL, buff=buff) use_these.set_color(BLUE) not_this.match_x(use_these) self.add(use_these) not_arrow = Arrow(not_this, det, fill_color=RED, thickness=0.1, buff=0.5) use_arrow = Arrow(use_these, facts, fill_color=BLUE, thickness=0.1, buff=0.5) self.add(get_shadow(not_arrow), not_arrow) self.add(get_shadow(use_arrow), use_arrow) ## DELETE # mp = OldTex( # "{m} \\pm \\sqrt{\\,{m}^2 - {p}}", # tex_to_color_map={ # "{m}": MEAN_COLOR, # "{p}": MEAN_COLOR, # } # ) # for mob, u in [(det, -1), (mp, 1)]: # mob.set_width(FRAME_WIDTH / 2 - 1) # mob.set_x(u * FRAME_WIDTH / 4) # mob.set_y(-1) # v_line = DashedLine(4 * UP, 4 * DOWN) # ex = Exmark() # check = Checkmark() # VGroup(ex, check).scale(5) # ex.move_to(det).to_edge(UP, LARGE_BUFF) # check.move_to(mp).to_edge(UP, LARGE_BUFF) # self.add(v_line) # self.add(det) # self.add(mp) # self.add(ex) # self.add(check) self.embed() class Assumptions(TeacherStudentsScene): def construct(self): self.play( PiCreatureSays(self.teacher, OldTexText("I'm assuming you know\\\\ what eigenvalues are.")), self.change_students( "erm", "happy", "tease", look_at=ORIGIN, ), run_time=2, ) self.play(self.students[0].change("guilty").look(LEFT)) self.wait() eigen_expression = OldTex(""" \\text{det}\\left( \\left[ \\begin{array}{cc} 3 - \\lambda & 1 \\\\ 4 & 1 - \\lambda \\end{array} \\right] \\right) """) eigen_expression.move_to(self.hold_up_spot, DOWN) eigen_expression.to_edge(RIGHT, buff=2) VGroup(eigen_expression[0][7], eigen_expression[0][12]).set_color(TEAL) cross = Cross(eigen_expression) cross.set_stroke(RED, width=(2, 5, 5, 2)) words = Text("Not this!") words.set_color(RED) words.next_to(cross, UP, MED_LARGE_BUFF) self.play( RemovePiCreatureBubble(self.teacher, target_mode="raise_right_hand"), FadeIn(eigen_expression, UP), self.students[1].change("hesitant"), self.students[2].change("sassy"), ) self.play( ShowCreation(cross), FadeIn(words, 0.25 * UP), self.teacher.change("tease", cross), self.students[1].change("pondering", cross), self.students[2].change("hesitant", cross), ) self.wait(3) fade_rect = FullScreenFadeRectangle() fade_rect.set_fill(BLACK, opacity=0.7) self.add(fade_rect, self.students[0]) self.play(FadeIn(fade_rect)) self.play(self.students[0].change("maybe", cross)) self.play(Blink(self.students[0])) class ExamplesStart(Scene): def construct(self): words = OldTexText("Examples start\\\\at", " 4:53") words.set_width(8) words[-1].set_color(YELLOW) self.play(Write(words, run_time=1)) self.play(FlashAround(words[1], stroke_width=8)) self.wait() class PreviousVideoWrapper(Scene): def construct(self): self.add(FullScreenRectangle()) screen = ScreenRectangle(height=6) screen.set_fill(BLACK, 1) screen.set_stroke(BLUE, 3) screen.to_edge(DOWN) im = ImageMobject("eigen_thumbnail") im.replace(screen) screen = Group(screen, im) title = Text("Introduction", font_size=48) # title.match_width(screen) title.next_to(screen, UP, MED_LARGE_BUFF) # screen.next_to(title, DOWN) self.add(screen) self.play(Write(title)) self.wait(2) self.play( FadeOut(title, UP), screen.animate.set_height(7).center(), ) self.wait() class GoalOfRediscovery(TeacherStudentsScene): def construct(self): self.play( PiCreatureSays(self.teacher, OldTexText("The goal is\\\\rediscovery")), self.change_students( "happy", "tease", "hooray", run_time=1.5, ) ) self.wait(2) recap_words = Text("Quick recap") recap_words.move_to(self.screen, UP) self.play( RemovePiCreatureBubble(self.teacher, target_mode="raise_right_hand", look_at=recap_words), self.change_students("pondering", "hesitant", "pondering", look_at=recap_words), GrowFromPoint(recap_words, self.teacher.get_corner(UL)), ) self.wait(4) class RecapWrapper(Scene): def construct(self): self.add(FullScreenRectangle()) screen = ScreenRectangle(height=6.75) screen.set_stroke(BLUE_B, 2) screen.set_fill(BLACK, 1) screen.to_edge(DOWN, buff=0.25) title = Text("Quick review") title.to_edge(UP, buff=0.25) self.add(title, screen) class VisualizeEigenvector(Scene): def construct(self): plane = NumberPlane(faded_line_ratio=0) plane.set_stroke(width=3) coords = [-1, 1] vector = Vector(plane.c2p(*coords), fill_color=YELLOW) array = IntegerMatrix([[-1], [1]], v_buff=0.9) array.scale(0.7) array.set_color(vector.get_color()) array.add_to_back(BackgroundRectangle(array)) array.generate_target() array.next_to(vector.get_end(), LEFT) array.target.next_to(2 * vector.get_end(), LEFT) two_times = OldTex("2 \\cdot") two_times.set_stroke(BLACK, 8, background=True) two_times.next_to(array.target, LEFT) span_line = Line(-4 * vector.get_end(), 4 * vector.get_end()) span_line.set_stroke(YELLOW_E, 1) matrix = [[3, 1], [0, 2]] mat_mob = IntegerMatrix(matrix) mat_mob.set_x(4).to_edge(UP) mat_mob.set_column_colors(GREEN, RED) mat_mob.add_to_back(BackgroundRectangle(mat_mob)) plane.set_stroke(background=True) bases = VGroup( Vector(RIGHT, fill_color=GREEN_E), Vector(UP, fill_color=RED_E), ) faint_plane = plane.copy() faint_plane.set_stroke(GREY, width=1, opacity=0.5) self.add(faint_plane, plane, bases) self.add(vector) self.add(mat_mob) self.play(Write(array)) self.add(span_line, vector, array) self.play(ShowCreation(span_line)) self.wait() self.play( plane.animate.apply_matrix(matrix), bases[0].animate.put_start_and_end_on(ORIGIN, plane.c2p(3, 0)), bases[1].animate.put_start_and_end_on(ORIGIN, plane.c2p(1, 2)), vector.animate.scale(2, about_point=ORIGIN), MoveToTarget(array), GrowFromPoint(two_times, array.get_left() + SMALL_BUFF * LEFT), run_time=3, path_arc=0, ) self.wait() self.remove(mat_mob) self.remove(array) self.remove(two_times) class EigenvalueEquationRearranging(Scene): def construct(self): v_tex = "\\vec{\\textbf{v}}" zero_tex = "\\vec{\\textbf{0}}" kw = { "tex_to_color_map": { "A": BLUE, "\\lambda": EIGEN_COLORS[1], v_tex: YELLOW, "=": WHITE, } } lines = VGroup( OldTex("A", v_tex, "=", "\\lambda ", v_tex, **kw), OldTex("A", v_tex, "=", "\\lambda ", " I ", v_tex, **kw), OldTex("A", v_tex, "-", "\\lambda ", " I ", v_tex, "=", zero_tex, **kw), OldTex("(A", "-", "\\lambda ", "I)", v_tex, "=", zero_tex, **kw), OldTex("\\text{det}", "(A", "-", "\\lambda ", "I)", "=", "0", **kw), ) for line in lines: line.shift(-line.get_part_by_tex("=").get_center()) mat_prod_brace = Brace(lines[0][:2]) mat_prod_label = Text("Matrix product", color=BLUE, font_size=24) mat_prod_label.next_to(mat_prod_brace, DOWN, SMALL_BUFF, aligned_edge=RIGHT) scalar_prod_brace = Brace(lines[0][3:5]) scalar_prod_label = Text("Scalar product", color=EIGEN_COLORS[1], font_size=24) scalar_prod_label.next_to(scalar_prod_brace, DOWN, SMALL_BUFF, aligned_edge=LEFT) self.add(lines[0]) self.play( LaggedStart( GrowFromCenter(mat_prod_brace), GrowFromCenter(scalar_prod_brace), lag_ratio=0.3 ), LaggedStart( FadeIn(mat_prod_label, 0.25 * DOWN), FadeIn(scalar_prod_label, 0.25 * DOWN), lag_ratio=0.3 ) ) self.wait() id_brace = Brace(lines[1].get_part_by_tex("I")) id_label = Text("Identity matrix", font_size=24) id_label.next_to(id_brace, DOWN, SMALL_BUFF, aligned_edge=LEFT) self.play( TransformMatchingTex(lines[0], lines[1]), ReplacementTransform(scalar_prod_brace, id_brace), FadeTransform(scalar_prod_label, id_label), VGroup(mat_prod_label, mat_prod_brace).animate.shift(lines[1].get_left() - lines[0].get_left()), ) self.wait() for shift_value, line in zip(it.count(1), lines[2:5]): line.shift(shift_value * 0.75 * DOWN) self.play( TransformMatchingTex(lines[1].copy(), lines[2], path_arc=-45 * DEGREES), FadeOut(VGroup(mat_prod_label, mat_prod_brace, id_brace, id_label), 0.5 * DOWN) ) self.wait() self.play( TransformMatchingShapes(lines[2].copy(), lines[3]), ) self.wait() v_part = lines[3].get_part_by_tex(v_tex) nz_label = Text("Non-zero vector", color=YELLOW, font_size=24) nz_label.next_to(v_part, DR, MED_LARGE_BUFF) arrow = Arrow(nz_label.get_corner(UL), v_part, fill_color=YELLOW, buff=0.1, thickness=0.025) self.play( Write(nz_label, run_time=2), GrowArrow(arrow) ) self.wait() self.play( TransformMatchingShapes(lines[3].copy(), lines[4]), FadeOut(nz_label), FadeOut(arrow), ) self.wait() class SneakierEigenVector(ExternallyAnimatedScene): pass class TypicalComputation(Scene): def construct(self): # Task words, mat = task = VGroup( Text("Find the eigenvalues of ", t2c={"eigenvalues": TEAL}), IntegerMatrix([[3, 1], [4, 1]]).set_height(1), ) task.arrange(RIGHT, buff=MED_LARGE_BUFF) task.to_edge(UP) self.add(task) # Top line of the computation det_expression = OldTex(""" \\text{det}\\left( \\left[ \\begin{array}{cc} 3 - \\lambda & 1 \\\\ 4 & 1 - \\lambda \\end{array} \\right] \\right) """)[0] lambdas = VGroup(det_expression[7], det_expression[12]) lambdas.set_color(TEAL) t0, t1, t2, t3 = terms = VGroup( det_expression[5:8], det_expression[8:9], det_expression[9:10], det_expression[10:13], ).copy() p_height = terms[0].get_height() * 1.5 for term in terms: parens = OldTex("(", ")") parens.set_height(p_height) parens[0].next_to(term, LEFT, 0.5 * SMALL_BUFF) parens[1].next_to(term, RIGHT, 0.5 * SMALL_BUFF) term.parens = parens term.parens.set_opacity(0) term.add(term.parens) eq = OldTex("=") eq.next_to(det_expression, RIGHT) rhs = VGroup( t0.copy(), t3.copy(), OldTex("-"), t1.copy(), t2.copy() ) rhs.arrange(RIGHT) rhs.next_to(eq, RIGHT) rhs.set_opacity(1) VGroup(det_expression, terms, eq, rhs).next_to(task, DOWN, LARGE_BUFF) movers = VGroup(det_expression[5], det_expression[10]) movers.save_state() movers[0].move_to(det_expression[6]) movers[1].move_to(det_expression[11]) self.play( TransformFromCopy(mat.get_brackets(), VGroup(*(det_expression[i] for i in [4, 13]))), TransformFromCopy(mat.get_entries(), VGroup(*(det_expression[i] for i in [5, 8, 9, 10]))), FadeTransform( mat.get_brackets().copy().set_opacity(0), VGroup(*(det_expression[i] for i in [0, 1, 2, 3, 14])) ), run_time=1 ) self.play( Write(VGroup(*(det_expression[i] for i in [6, 7, 11, 12]))), Restore(movers), ) self.wait() self.add(det_expression) self.play( FadeIn(eq), TransformFromCopy(VGroup(t0, t3), rhs[:2]), ) self.play( FadeIn(rhs[2]), TransformFromCopy(VGroup(t1, t2), rhs[3:]) ) self.wait() # Line 2 eq2 = eq.copy() eq2.shift(DOWN) self.add(eq2) rhs2 = OldTex("\\left( 3 - 4\\lambda + \\lambda^2 \\right) - 4")[0] rhs2.next_to(eq2, RIGHT) VGroup(rhs2[4], rhs2[6]).set_color(TEAL) top_terms = VGroup( VGroup(rhs[0][0], rhs[0][2]), VGroup(rhs[1][0], rhs[1][2]), ) alt_mid = OldTex("-3\\lambda", tex_to_color_map={"\\lambda": TEAL}) alt_mid.move_to(rhs2[2:5], DL) bottom_terms = VGroup(rhs2[1], alt_mid, rhs2[2:5], rhs2[5:8]) for pair, bt in zip(it.product(*top_terms), bottom_terms): rects = VGroup(*(SurroundingRectangle(t, buff=SMALL_BUFF) for t in pair)) self.add(rects) self.add(bt) self.wait(0.5) if bt is alt_mid: self.remove(bt) self.remove(rects) self.play( FadeIn(VGroup(rhs2[0], rhs2[8])), FadeTransform(rhs[2:].copy(), rhs2[9:]) ) self.wait() # Line 3 eq3 = eq2.copy().shift(DOWN) rhs3 = OldTex("\\lambda^2 - 4 \\lambda - 1")[0] rhs3.next_to(eq3, RIGHT) VGroup(rhs3[0], rhs3[4]).set_color(TEAL) kw = {"path_arc": 45 * DEGREES} self.play(LaggedStart( TransformFromCopy(eq2, eq3, **kw), Transform(rhs2[1].copy(), rhs3[6].copy(), remover=True, **kw), TransformFromCopy(rhs2[9:11], rhs3[5:], **kw), TransformFromCopy(rhs2[2:5], rhs3[2:5], **kw), TransformFromCopy(rhs2[6:8], rhs3[0:2], **kw), run_time=1.5, lag_ratio=0.02, )) self.wait() # Characteristic polynomial brace = Brace(rhs3, DOWN) char_poly = VGroup( Text("Characteristic polynomial of", font_size=30, fill_color=BLUE), mat.copy() ) char_poly.arrange(RIGHT) char_poly.next_to(brace, DOWN) char_poly.shift_onto_screen() self.play( GrowFromCenter(brace), FadeIn(char_poly, DOWN), ) self.wait() # Roots equals_zero = OldTex("= 0") equals_zero.next_to(rhs3, RIGHT) root_words = OldTex( "\\lambda_1, \\lambda_2 \\,=\\, \\text{roots}", tex_to_color_map={ "\\lambda_1": TEAL_C, "\\lambda_2": TEAL_B, "=": WHITE, } ) new_rhs3 = VGroup(rhs3, equals_zero) root_words.next_to(brace, DOWN) root_words.match_x(new_rhs3) self.play( FadeIn(root_words, DOWN), FadeOut(char_poly, DOWN), brace.animate.become(Brace(new_rhs3)), Write(equals_zero), ) self.wait() # Quadratic formula formula = OldTex("\\frac{4 \\pm \\sqrt{4^2 - 4(1)(-1)}}{2}") formula2 = OldTex("=\\frac{4 \\pm \\sqrt{20}}{2}") formula3 = OldTex("= 2 \\pm \\sqrt{5}") formula.move_to(root_words[-1], LEFT) formula.shift(0.5 * DL) self.play( TransformMatchingShapes(rhs3.copy(), formula), FadeOut(root_words[-1]), root_words[:-1].animate.shift(0.5 * DL), ) self.wait() solution = VGroup(root_words[:-1], formula) self.play( solution.animate.shift(formula2.get_width() * LEFT), ) formula2.next_to(formula, RIGHT) self.play(FadeIn(formula2)) self.wait() solution.add(formula2) self.play( solution.animate.shift(formula3.get_width() * LEFT), ) formula3.next_to(formula2, RIGHT) self.play(FadeIn(formula3)) self.wait() # Straight line full_rect = FullScreenFadeRectangle() arrow = Arrow(mat, formula3, thickness=0.05) arrow.set_fill(YELLOW) self.add(full_rect, task, formula3) self.play(FadeIn(full_rect)) self.play(GrowArrow(arrow)) self.wait() class TweakDiagonalValue(ExternallyAnimatedScene): pass class DetEquationLineOfReasoning(ExternallyAnimatedScene): pass class OutlineThreeFacts(Scene): def construct(self): # Matrix to lambdas mat = Matrix([["a", "b"], ["c", "d"]], v_buff=0.8, h_buff=0.8) mat.set_column_colors(COL_COLORS[0], COL_COLORS[1]) lambdas = OldTex("\\lambda_1", "\\,,\\,", "\\lambda_2") lambdas[0].set_color(EIGEN_COLORS[0]) lambdas[2].set_color(EIGEN_COLORS[1]) arrow = Vector(1.5 * RIGHT) group = VGroup(mat, arrow, lambdas) group.arrange(RIGHT) arrow_label = Text("Quick?", font_size=24) arrow_label.next_to(arrow, UP, buff=0) self.add(mat) self.play( GrowArrow(arrow), Write(arrow_label, run_time=1), LaggedStart(*( AnimationGroup(*( Transform(entry, lambdas[i]) for entry in mat.get_entries().deepcopy() )) for i in [0, 2] ), lag_ratio=0.3), FadeIn(lambdas[1]), ) self.clear() self.add(group, arrow_label) self.wait() # Three steps indices = VGroup(*(Text(str(i) + ")", font_size=48) for i in range(1, 4))) indices.set_color(GREY_B) indices.arrange(DOWN, aligned_edge=LEFT, buff=2) indices.to_edge(LEFT) group.generate_target() group.target[1].rotate(-90 * DEGREES) group.target[1].scale(0.5) group.target.arrange(DOWN) group.target.to_corner(DR) self.play( LaggedStartMap(FadeIn, indices, shift=0.25 * UP, lag_ratio=0.3), FadeOut(arrow_label), MoveToTarget(group), ) self.wait() # Trace tr_mat = mat.deepcopy() tr = OldTex("\\text{tr}", "\\Big(", "\\Big)", font_size=60) tr[1:].match_height(tr_mat, stretch=True) tr.set_submobjects([*tr[:-1], tr_mat, tr[-1]]) tr.arrange(RIGHT, buff=SMALL_BUFF) tr.next_to(indices[0], RIGHT, MED_LARGE_BUFF) tr_rects = VGroup( SurroundingRectangle(tr_mat.get_entries()[0]), SurroundingRectangle(tr_mat.get_entries()[3]), ) tr_rects.set_color(BLUE_C) moving_tr_rects = tr_rects.copy() moving_tr_rects.generate_target() tex_kw = { "tex_to_color_map": { "a": COL_COLORS[0], "b": COL_COLORS[1], "c": COL_COLORS[0], "d": COL_COLORS[1], "=": WHITE, "\\lambda_1": EIGEN_COLORS[0], "\\lambda_2": EIGEN_COLORS[1], } } tr_rhs = OldTex("= a + d = \\lambda_1 + \\lambda_2", **tex_kw) tr_rhs.next_to(tr, RIGHT) for term, rect in zip(tr_rhs[1:4:2], moving_tr_rects.target): rect.move_to(term) self.play( TransformFromCopy(mat, tr_mat), Write(VGroup(*tr[:2], tr[-1])), ) self.play(LaggedStart(*map(ShowCreation, tr_rects))) tr.add(tr_rects) self.play( MoveToTarget(moving_tr_rects), TransformFromCopy(tr_mat.get_entries()[0], tr_rhs.get_part_by_tex("a")), TransformFromCopy(tr_mat.get_entries()[3], tr_rhs.get_part_by_tex("d")), FadeIn(tr_rhs[0:4:2]), ) self.play(FadeOut(moving_tr_rects)) self.wait() self.play( TransformMatchingShapes(lambdas.copy(), tr_rhs[4:]), ) self.wait() # Mean of eigenvalues half = OldTex("1 \\over 2") half.move_to(tr, LEFT) tr.generate_target() tr.target.next_to(half, RIGHT, SMALL_BUFF) new_tr_rhs = OldTex("= {a + d \\over 2} = {\\lambda_1 + \\lambda_2 \\over 2}", **tex_kw) new_tr_rhs.next_to(tr.target, RIGHT) self.play( GrowFromCenter(half), MoveToTarget(tr), TransformMatchingShapes(tr_rhs, new_tr_rhs), ) self.wait() # Determinant det_mat = mat.deepcopy() det = OldTex("\\text{det}", "\\Big(", "\\Big)", font_size=60) det[1:].match_height(det_mat, stretch=True) det.set_submobjects([*det[:-1], det_mat, det[-1]]) det.arrange(RIGHT, buff=SMALL_BUFF) det.next_to(indices[1], RIGHT, MED_LARGE_BUFF) det_rhs = OldTex("= ad - bc = \\lambda_1 \\lambda_2", **tex_kw) det_rhs.next_to(det, RIGHT) self.play( TransformFromCopy(mat, det_mat), Write(VGroup(*det[:2], det[-1])), ) self.play( det_path_anim(det_mat), LaggedStart( Animation(Mobject(), remover=True), FadeIn(det_rhs[:3]), FadeIn(det_rhs[3:6]), lag_ratio=0.7, ) ) self.wait() self.play( TransformMatchingShapes(lambdas.copy(), det_rhs[6:]) ) self.wait() # Mean and product eq_m = OldTexText("=", " $m$", "\\quad (mean)") eq_m[1].set_color(MEAN_COLOR) eq_m.next_to(new_tr_rhs, RIGHT) eq_p = OldTexText("=", " $p$", "\\quad (product)") eq_p[1].set_color(PROD_COLOR) eq_p.next_to(det_rhs, RIGHT) form_lhs = lambdas.copy() form_rhs = OldTex("= {m} \\pm \\sqrt{\\,{m}^2 - {p}}", tex_to_color_map={"{m}": MEAN_COLOR, "{p}": PROD_COLOR}) form_lhs.next_to(indices[2], RIGHT) form_rhs.next_to(form_lhs, RIGHT) third_point_placeholder = Text("(We'll get to this...)", font_size=30) third_point_placeholder.set_fill(GREY_C) third_point_placeholder.next_to(indices[2], RIGHT, MED_LARGE_BUFF) form = VGroup(indices[2], form_lhs, form_rhs) rect = SurroundingRectangle(VGroup(form), buff=MED_SMALL_BUFF) randy = Randolph(height=2) randy.next_to(rect, RIGHT) randy.to_edge(DOWN) self.play( FadeIn(third_point_placeholder), VFadeIn(randy), randy.change("erm", third_point_placeholder) ) self.play(Blink(randy)) self.wait() self.play( randy.change("thinking", eq_m), Write(eq_m) ) self.play( randy.animate.look_at(eq_p), Write(eq_p), mat.animate.set_height(1, about_edge=DOWN) ) self.play(Blink(randy)) self.wait() # Example matrix ex_mat = IntegerMatrix([[8, 4], [2, 6]]) ex_mat.set_height(1.25) ex_mat.set_column_colors(COL_COLORS[0], COL_COLORS[1]) ex_mat.next_to(randy, RIGHT, aligned_edge=UP) kw = {"tex_to_color_map": {"m": MEAN_COLOR, "p": PROD_COLOR, "=": WHITE, "-": WHITE}} m_eq = OldTex("m = 7", **kw) p_eq1 = OldTex("p = 48 - 8", **kw) p_eq2 = OldTex("p = 40", **kw) for mob in (m_eq, p_eq1, p_eq2): mob.next_to(ex_mat, RIGHT, buff=MED_LARGE_BUFF) m_eq.shift(0.5 * UP) VGroup(p_eq1, p_eq2).shift(0.5 * DOWN) diag_rects = VGroup( SurroundingRectangle(ex_mat.get_entries()[0]), SurroundingRectangle(ex_mat.get_entries()[3]), ) off_diag_rects = VGroup( SurroundingRectangle(ex_mat.get_entries()[1]), SurroundingRectangle(ex_mat.get_entries()[2]), ) diag_rects.set_color(PROD_COLOR) off_diag_rects.set_color(PROD_COLOR) mean_rect = SurroundingRectangle(m_eq[2]) mean_rect.set_color(MEAN_COLOR) tr_rect = SurroundingRectangle(VGroup(indices[0], tr, eq_m)).set_stroke(MEAN_COLOR) det_rect = SurroundingRectangle(VGroup(indices[1], det, eq_p)).set_stroke(PROD_COLOR) self.play( randy.change("raise_right_hand", ex_mat), FadeIn(ex_mat, RIGHT), FadeOut(group, RIGHT), ) self.play(Blink(randy)) self.wait() self.play(FadeIn(tr_rect), randy.change("pondering", tr_rhs)) self.play( Write(m_eq[:2]), LaggedStartMap(ShowCreation, diag_rects, lag_ratio=0.5, run_time=1), randy.animate.look_at(m_eq), ) self.wait() self.remove(diag_rects) self.play( TransformFromCopy(diag_rects, mean_rect), FadeTransform(ex_mat.get_entries()[0].copy(), m_eq[2]), FadeTransform(ex_mat.get_entries()[3].copy(), m_eq[2]), ) self.play(Blink(randy)) self.wait() self.play(FadeOut(tr_rect), FadeIn(det_rect), randy.animate.look_at(tr_rhs)) self.play( Write(p_eq1[:2]), randy.change("hesitant", p_eq1), FadeOut(mean_rect), ) self.play(det_path_anim(ex_mat)) self.wait() self.play( FadeIn(diag_rects), FadeIn(p_eq1[2]), ) self.play( FadeOut(diag_rects), FadeIn(off_diag_rects), FadeIn(p_eq1[3:]), ) self.play( FadeOut(off_diag_rects), ) self.play( randy.change("tease", p_eq2), FadeOut(p_eq1), FadeIn(p_eq2), ) self.play(FadeOut(det_rect)) self.wait() # Let other stuff happen up top full_rect = FullScreenFadeRectangle() full_rect.set_fill(BLACK, 1) ex = VGroup(ex_mat, m_eq, p_eq2) self.add(full_rect, randy, ex) self.play( FadeIn(full_rect), randy.change("pondering", ORIGIN) ) for x in range(10): if random.random() < 0.5: self.play(Blink(randy)) else: self.wait() # Show final formula ex_rect = SurroundingRectangle(ex, buff=0.35) ex_rect.set_stroke(GREY_A) ex_rect.set_fill(interpolate_color(GREY_E, BLACK, 0.25)) ex_rect.set_opacity(0) ex_group = VGroup(ex_rect, ex) ex_group.generate_target() ex_group.target.set_height(1.5) ex_group.target.to_corner(DR) ex_group.target[0].set_opacity(1) self.play( FadeOut(full_rect), FadeOut(randy), MoveToTarget(ex_group) ) self.play( FadeIn(form_lhs, 0.25 * UP), FadeOut(third_point_placeholder, 0.25 * UP) ) self.play(TransformMatchingShapes( VGroup(m_eq[0], p_eq2[0]).copy(), form_rhs, )) self.play(ShowCreation(rect)) self.wait() class MeansMatch(Scene): def construct(self): t2c = { "{a}": COL_COLORS[0], "{d}": COL_COLORS[1], "\\lambda_1": EIGEN_COLORS[0], "\\lambda_2": EIGEN_COLORS[1], "=": WHITE, } equation = OldTex( "{{a} + {d} \\over 2} = {\\lambda_1 + \\lambda_2 \\over 2}", tex_to_color_map=t2c ) mean_eq = OldTex( "\\text{mean}({a}, {d}) = \\text{mean}(\\lambda_1, \\lambda_2)", tex_to_color_map=t2c ) mean_eq.next_to(equation, DOWN, LARGE_BUFF) self.add(equation) self.play(TransformMatchingShapes(equation[5:].copy(), mean_eq[6:])) self.wait() self.play(TransformMatchingShapes(equation[:5].copy(), mean_eq[:6])) self.wait() class ShowSquishingAndStretching(Scene): def construct(self): self.camera.frame.set_height((3 / 4) * FRAME_HEIGHT) # Transform plane = NumberPlane( (-20, 20), (-20, 20), background_line_style={"stroke_width": 3}, faded_line_ratio=0, ) plane.axes.set_stroke(BLUE, 3) back_plane = NumberPlane( faded_line_ratio=0, ) back_plane.set_stroke(GREY_B, 1, opacity=0.5) mat = [[2, 2], [1, 2]] eigenvalues, eigenvectors = np.linalg.eig(mat) eigenvectors = [normalize(v) for v in eigenvectors.T] eigenlines = VGroup(*( Line(10 * ev, -10 * ev, color=color) for ev, color in zip(eigenvectors, EIGEN_COLORS) )) eigenlines.set_stroke(GREY_B, 2) globals().update(locals()) eigenvect_mobs = VGroup(*( Vector(ev, fill_color=color) for ev, color in zip(eigenvectors, EIGEN_COLORS) )) eigenvect_mobs[0].add_updater(lambda m: m.put_start_and_end_on(plane.c2p(0, 0), plane.c2p(*eigenvectors[0][:2]))) eigenvect_mobs[1].add_updater(lambda m: m.put_start_and_end_on(plane.c2p(0, 0), plane.c2p(*eigenvectors[1][:2]))) # Basis vectors bases = VGroup( Vector(RIGHT, fill_color=GREEN, thickness=0.05), Vector(UP, fill_color=RED, thickness=0.05), ) globals().update(locals()) bases[0].add_updater(lambda m: m.put_start_and_end_on(plane.c2p(0, 0), plane.c2p(1, 0))) bases[1].add_updater(lambda m: m.put_start_and_end_on(plane.c2p(0, 0), plane.c2p(0, 1))) disk = Circle(radius=1) disk.set_fill(YELLOW, 0.25) disk.set_stroke(YELLOW, 3) morpher = VGroup(plane, disk) self.add(back_plane, morpher, eigenlines, *eigenvect_mobs) self.play( morpher.animate.apply_matrix(mat), run_time=4 ) self.wait() # Labels labels = VGroup(*( OldTex("\\text{Stretch by }", f"\\lambda_{i}", color=color, font_size=30) for i, color in zip((1, 2), EIGEN_COLORS) )) for label, vect in zip(labels, eigenvect_mobs): label.next_to( vect.get_center(), rotate_vector(normalize(vect.get_vector()), 90 * DEGREES), buff=0.1, index_of_submobject_to_align=1, ) labels.set_stroke(BLACK, 5, background=True) self.play(LaggedStartMap(FadeIn, labels, lag_ratio=0.7)) self.wait() class MeanProductExample(Scene): def construct(self): # Number line and midpoint number_line = NumberLine((0, 14)) number_line.add_numbers() number_line.set_width(FRAME_WIDTH - 1) number_line.to_edge(UP, buff=1.5) nl = number_line mean = 7 m_dot = Dot(nl.n2p(mean)) m_dot.set_color(MEAN_COLOR) m_label = OldTex("m", color=MEAN_COLOR) m_label.next_to(m_dot, UP, buff=MED_SMALL_BUFF) label7 = OldTex("7", color=MEAN_COLOR) # Distance tracking d_tracker = ValueTracker(4) def get_l1_point(): return nl.n2p(mean - d_tracker.get_value()) def get_l2_point(): return nl.n2p(mean + d_tracker.get_value()) l1_dot, l2_dot = (Dot(color=TEAL) for x in range(2)) l1_label = OldTex("\\lambda_1", color=EIGEN_COLORS[0]) l2_label = OldTex("\\lambda_2", color=EIGEN_COLORS[1]) l1_arrow, l2_arrow = (Arrow(color=WHITE) for x in range(2)) l1_dot.add_updater(lambda m: m.move_to(get_l1_point())) l2_dot.add_updater(lambda m: m.move_to(get_l2_point())) always(l1_label.next_to, l1_dot, UP, buff=MED_SMALL_BUFF) always(l2_label.next_to, l2_dot, UP, buff=MED_SMALL_BUFF) m_label.match_y(l1_label) l1_arrow.add_updater(lambda m: m.set_points_by_ends( m_label.get_left() + SMALL_BUFF * LEFT, l1_label.get_right() + SMALL_BUFF * RIGHT, )) l2_arrow.add_updater(lambda m: m.set_points_by_ends( m_label.get_right() + SMALL_BUFF * RIGHT, l2_label.get_left() + SMALL_BUFF * LEFT, )) minus_d = OldTex("-d") plus_d = OldTex("+d") always(minus_d.next_to, l1_arrow, UP, SMALL_BUFF) always(plus_d.next_to, l2_arrow, UP, SMALL_BUFF) plus_qm = OldTex("+??") minus_qm = OldTex("-??") always(plus_qm.move_to, plus_d) always(minus_qm.move_to, minus_d) VGroup(plus_d, minus_d).set_opacity(0) label7.move_to(m_label) self.add(number_line) self.add(m_dot) self.add(label7) self.add(l1_dot) self.add(l2_dot) self.add(l1_label) self.add(l2_label) self.add(l1_arrow) self.add(l2_arrow) self.add(minus_d) self.add(plus_d) self.add(minus_qm) self.add(plus_qm) d_tracker.add_updater(lambda m: m.set_value(4 - 2.5 * np.sin(0.25 * self.time))) self.add(d_tracker) self.wait(20) self.play( UpdateFromAlphaFunc( Mobject(), lambda m, a: VGroup(plus_d, minus_d).set_opacity(a), remover=True ), UpdateFromAlphaFunc( Mobject(), lambda m, a: VGroup(plus_qm, minus_qm).set_opacity(1 - a), remover=True ), ) self.remove(plus_qm, minus_qm) self.wait(5) # Write the product kw = {"tex_to_color_map": {"\\,7": MEAN_COLOR, "d": GREY_A, "=": WHITE, "-": WHITE}} texs = VGroup(*(OldTex(tex, **kw) for tex in [ "(\\,7 + d\\,)(\\,7 - d\\,)", "\\,7^2 - d^2 = ", "40 =", "d^2 = \\,7^2 - 40", "d^2 = 9", "d = 3", ])) texs[:3].arrange(LEFT) texs[1].align_to(texs[2], DOWN) texs[:3].next_to(nl, DOWN, MED_LARGE_BUFF).to_edge(LEFT, buff=LARGE_BUFF) for t1, t2 in zip(texs[2:], texs[3:]): t2.next_to(t1, DOWN, MED_LARGE_BUFF) t2.shift((t1.get_part_by_tex("=").get_x() - t2.get_part_by_tex("=").get_x()) * RIGHT) texs[0].save_state() texs[0].move_to(texs[1], UL) self.play(Write(VGroup(texs[2], texs[0]))) self.wait(3) self.play(Restore(texs[0])) self.play(TransformMatchingShapes(texs[0].copy(), texs[1], path_arc=45 * DEGREES)) self.wait(3) self.play(LaggedStart( TransformFromCopy(texs[2][0], texs[3][6], path_arc=-45 * DEGREES), TransformFromCopy(texs[2][1], texs[3][2]), TransformFromCopy(texs[1][:3], texs[3][3:6]), TransformFromCopy(texs[1][3:5], texs[3][0:2], path_arc=45 * DEGREES), lag_ratio=0.1 )) self.wait(2) self.play(FadeIn(texs[4], DOWN)) self.wait() self.play(FadeIn(texs[5], DOWN)) # Show final d geometrically d_tracker.clear_updaters() self.play(d_tracker.animate.set_value(3), rate_func=rush_into) minus_d.clear_updaters() plus_d.clear_updaters() plus_3 = OldTex("+3").move_to(plus_d) minus_3 = OldTex("-3").move_to(minus_d) self.play( LaggedStart( FadeOut(minus_d, 0.25 * UP), FadeOut(plus_d, 0.25 * UP), lag_ratio=0.25 ), LaggedStart( FadeIn(minus_3, 0.25 * UP), FadeIn(plus_3, 0.25 * UP), lag_ratio=0.25 ) ) self.wait() # Highlight solutions rects = VGroup( SurroundingRectangle(VGroup(l1_label, nl.numbers[4])), SurroundingRectangle(VGroup(l2_label, nl.numbers[10])), ) self.play(LaggedStartMap(ShowCreation, rects), lag_ratio=0.3) self.wait(2) self.play(LaggedStartMap(FadeOut, rects), lag_ratio=0.3) # Replace with general variables ms = VGroup(m_label.copy()) sevens = VGroup(label7) ps = VGroup() fourties = VGroup() for tex in texs[:-2]: for fourty in tex.get_parts_by_tex("40"): fourties.add(fourty) ps.add(OldTex("p").set_color(PROD_COLOR).move_to(fourty).shift(0.1 * DOWN)) for seven in tex.get_parts_by_tex("7"): sevens.add(seven) m = OldTex("m").set_color(MEAN_COLOR) m.scale(0.95) m.move_to(seven, DR) m.shift(0.04 * RIGHT) ms.add(m) ps[0].shift(0.05 * RIGHT) ps[1].shift(0.1 * LEFT) for g1, g2 in ((sevens, ms), (fourties, ps)): self.play( LaggedStartMap(FadeOut, g1, shift=0.25 * UP, lag_ratio=0.3), LaggedStartMap(FadeIn, g2, shift=0.25 * UP, lag_ratio=0.3), texs[-2:].animate.set_opacity(0) ) self.remove(texs[-2:]) self.wait() self.play(FlashUnder(texs[3])) self.wait() plus_form, minus_form = [ OldTex( c + "\\sqrt{\\,m^2 - p}", tex_to_color_map={"m": MEAN_COLOR, "p": PROD_COLOR}, font_size=24, ).move_to(d, DOWN) for c, d in [("+", plus_d), ("-", minus_d)] ] pre_group = VGroup(*texs[3][4:6], ms[-1], ps[-1]) self.play( TransformMatchingShapes(pre_group.copy(), minus_form), TransformMatchingShapes(pre_group.copy(), plus_form), FadeOut(VGroup(minus_3, plus_3), shift=0.25 * UP), ) self.wait() class AskIfThatsBetter(Scene): def construct(self): randy = Randolph(height=2) randy.to_edge(DOWN) randy.change("pondering", UL) self.add(BackgroundRectangle(randy, fill_opacity=1), randy) self.play( PiCreatureSays( randy, "Is that better?", target_mode="sassy", bubble_config={"direction": LEFT, "width": 4, "height": 2}, look_at=UL ) ) self.play(Blink(randy)) self.wait() self.play( RemovePiCreatureBubble(randy, target_mode="thinking") ) self.wait(2) self.play(randy.change("pondering", UL)) self.play(Blink(randy)) self.wait() class OutstandingChannel(Scene): def construct(self): morty = Mortimer() morty.to_corner(DR) self.play(PiCreatureSays( morty, OldTexText("Outstanding\\\\channel"), target_mode="hooray", bubble_config={"height": 3, "width": 4} )) self.play(Blink(morty)) self.wait() class JingleAnimation(Scene): def construct(self): form = OldTex("m \\pm \\sqrt{m^2 - p}")[0] form.set_height(2) m, old_pm, sqrt, root, m2, squared, minus, p = form VGroup(m, m2).set_color(MEAN_COLOR) VGroup(p).set_color(PROD_COLOR) m.refresh_bounding_box() # Why? p.refresh_bounding_box() # Why? pm = VGroup(OldTex("+"), OldTex("-")) pm.arrange(DOWN, buff=0) pm.replace(old_pm) pm.save_state() pm.scale(1.5) pm.arrange(DOWN, buff=2) mean = Text("mean", color=WHITE).next_to(m, DOWN) product = Text("product", color=WHITE).next_to(p, DOWN) plus_word = Text("plus", color=YELLOW).next_to(pm, UP) minus_word = Text("minus", color=YELLOW).next_to(pm, DOWN) def snap(t): return t**5 self.play(FadeIn(m, scale=0.5, rate_func=snap, run_time=0.5)) self.add(mean) self.wait(0.4) self.add(pm[0], plus_word) self.wait(0.2) self.add(pm[1], minus_word) self.wait(0.2) self.play( Restore(pm, rate_func=smooth, run_time=0.5), FadeOut(VGroup(plus_word, minus_word, mean), run_time=0.5), ) sqrt_outline = sqrt.copy() sqrt_outline.set_stroke(YELLOW, 10) sqrt_outline.set_fill(opacity=0) sqrt_outline.insert_n_curves(100) root.save_state() root.stretch(0, 0, about_edge=LEFT) self.play( FadeIn(sqrt, rate_func=squish_rate_func(smooth, 0.25, 0.75)), VShowPassingFlash(sqrt_outline, time_width=2), Restore(root, rate_func=squish_rate_func(snap, 0.25, 1)), run_time=1, ) self.play( TransformFromCopy(m, m2, path_arc=-120 * DEGREES, rate_func=smooth, run_time=0.6), ) self.play(FadeTransform(m2.copy(), squared, run_time=0.5)) minus.save_state() minus.stretch(0, 0, about_edge=LEFT) self.play(Restore(minus), run_time=0.5, rate_func=smooth) self.wait(0.2) self.play( FadeIn(p, scale=0.5, rate_func=snap, run_time=0.5), ) self.add(product) self.wait(0.4) self.play( Flash(p, flash_radius=0.8 * p.get_height(), run_time=0.5), ) self.wait(0.3) self.remove(product) self.wait() class Example1(TeacherStudentsScene): def construct(self): # Show matrix mat = IntegerMatrix([[3, 1], [4, 1]]) mat.set_column_colors(*COL_COLORS) mat.move_to(self.hold_up_spot, DOWN) self.play( self.teacher.change("raise_right_hand", mat), FadeIn(mat.get_brackets(), UP) ) self.play( Write(mat.get_entries(), lag_ratio=0.1, run_time=2), self.change_students("pondering", "pondering", "thinking", look_at=mat) ) self.wait() bubble = ThoughtBubble(height=4, width=7) bubble.pin_to(self.students[2]) self.play( self.students[2].change("tease", bubble), Write(bubble) ) self.wait(3) # Write formula shift_vect = 5 * LEFT arrow = Vector(0.75 * RIGHT) arrow.next_to(mat, RIGHT) formula = OldTex( "\\lambda_1, \\, \\lambda_2 = {2} \\pm \\sqrt{\\,{2}^2 - (-1)}", tex_to_color_map={ "\\lambda_1": EIGEN_COLORS[0], "\\lambda_2": EIGEN_COLORS[1], "(-1)": PROD_COLOR, "{2}": MEAN_COLOR, } ) formula.next_to(arrow, RIGHT) VGroup(formula, arrow).shift(shift_vect) twos = formula.get_parts_by_tex("{2}") min1 = formula.get_part_by_tex("(-1)") m_rects = VGroup(*(SurroundingRectangle(two, buff=0) for two in twos)) m_rects.set_stroke(MEAN_COLOR) p_rect = SurroundingRectangle(min1, buff=0) p_rect.set_stroke(PROD_COLOR) form_rects = VGroup(m_rects, p_rect) VGroup(twos, min1).set_opacity(0) self.play( FadeOut(bubble), mat.animate.shift(shift_vect), FadeIn(arrow, shift_vect), FadeIn(formula), FadeIn(form_rects), self.change_students("pondering", "pondering", "pondering", look_at=ORIGIN) ) self.play( self.teacher.change("tease", formula), *(pi.animate.look_at(formula) for pi in self.students), ) self.wait() # Show mean m_eq = OldTex("m", "=", "2", tex_to_color_map={"m": MEAN_COLOR, "2": MEAN_COLOR}) m_eq.next_to(mat, UP, LARGE_BUFF) t2c = { "\\lambda_1": EIGEN_COLORS[0], "\\lambda_2": EIGEN_COLORS[1], "{m}": MEAN_COLOR, "{p}": PROD_COLOR, "=": WHITE, } diag_rects = VGroup(*(SurroundingRectangle(mat.get_entries()[i]) for i in [0, 3])) diag_rects.set_stroke(MEAN_COLOR) two_rect = SurroundingRectangle(m_eq[2]) two_rect.set_stroke(MEAN_COLOR) self.play( Write(m_eq[:2]), *(pi.animate.look_at(m_eq) for pi in self.pi_creatures) ) self.play( ShowCreation(diag_rects), self.teacher.change("tease", diag_rects), *(pi.animate.look_at(diag_rects) for pi in self.students), ) self.wait() self.play( FadeTransform(diag_rects[0].copy(), m_eq[2], remover=True), FadeTransform(diag_rects[1].copy(), m_eq[2], remover=True), *(pi.animate.look_at(two_rect) for pi in self.pi_creatures), ) self.wait(2) self.remove(twos, min1) VGroup(twos, min1).set_opacity(1) for i in (0, 1): self.play( TransformFromCopy(m_eq[2], twos[i]), FadeOut(m_rects[i]), self.teacher.change("raise_right_hand", twos), *(pi.change("thinking", twos) for pi in self.students) ) self.wait() # Show product prod_eq = OldTex( # "\\lambda_1 \\lambda_2 =", "{p} = {3} - {4} = -1", tex_to_color_map={ "{3}": COL_COLORS[0], "{4}": COL_COLORS[0], **t2c } ) prod_eq.next_to(mat, UP, LARGE_BUFF) prod_eq.set_x(mat.get_center()[0], LEFT) lhs = prod_eq[:1] self.play( m_eq.animate.scale(0.7).next_to(mat, LEFT).to_edge(LEFT), FadeIn(lhs), FadeOut(diag_rects), self.teacher.change("happy"), self.change_students("erm", "hesitant", "thinking", look_at=prod_eq) ) self.play(det_path_anim(mat, run_time=1)) self.play( FadeIn(prod_eq[1]), FadeTransform(mat.get_entries()[0].copy(), prod_eq[2]), FadeTransform(mat.get_entries()[3].copy(), prod_eq[2]), VFadeInThenOut(VGroup(*(SurroundingRectangle(e) for e in mat.get_entries()[0::3]))), self.teacher.change("coin_flip_1"), ) self.play( FadeIn(prod_eq[3]), FadeTransform(mat.get_entries()[1].copy(), prod_eq[4]), FadeTransform(mat.get_entries()[2].copy(), prod_eq[4]), VFadeInThenOut(VGroup(*(SurroundingRectangle(e) for e in mat.get_entries()[1:3]))), ) self.wait() self.play( Write(prod_eq[-2:]), self.change_students("tease", "tease", "happy", look_at=prod_eq.get_right()), ) self.play( FadeOut(p_rect), FadeTransform(prod_eq[-1].copy(), min1), self.teacher.change("raise_left_hand", min1), *(pi.animate.look_at(min1) for pi in self.students) ) self.wait() self.play( prod_eq.animate.scale(0.7).next_to(m_eq, UP).to_edge(LEFT) ) self.wait(2) # Final answer rhs = OldTex("2\\pm\\sqrt{5}") rhs.move_to(formula[4], LEFT) self.play( self.teacher.change("tease", rhs), TransformMatchingShapes(formula[4:6].copy(), rhs), formula[4:].animate.shift(UP), ) self.wait() class SameExampleWrapper(Scene): def construct(self): self.add(FullScreenRectangle()) screen = ScreenRectangle() screen.set_fill(BLACK, 1) screen.set_stroke(BLUE, 3) screen.set_height(6) screen.to_edge(DOWN) title = Text("Same example from before") title.next_to(screen, UP) self.add(screen, title) class GeneralExample(Scene): matrix = [[3, 1], [4, 1]] def construct(self): mat = IntegerMatrix(self.matrix) mat.move_to(2 * LEFT) mat.set_column_colors(*COL_COLORS) matrix = np.array(self.matrix) a, b, c, d = matrix.flatten() mean = (a + d) / 2 if (a + d) % 2 == 0: mean = int(mean) prod = a * d - b * c mean_str = "{" + str(mean) + "}" prod_str = "{" + str(prod) + "}" self.add(mat) self.wait() mean_eq = OldTex(f"m = {mean_str}", tex_to_color_map={"m": MEAN_COLOR, mean_str: MEAN_COLOR}) mean_eq.next_to(mat, UP, LARGE_BUFF) diag_rects = get_diag_rects(mat) self.play( FadeIn(mean_eq[:2], 0.25 * UP) ) self.play(LaggedStartMap(ShowCreation, diag_rects, lag_ratio=0.3, run_time=1)) self.play( FadeTransform(diag_rects[0].copy(), mean_eq[2]), FadeTransform(diag_rects[1].copy(), mean_eq[2]), ) self.play(FadeOut(diag_rects)) last_part = "(" + prod_str + ")}" if prod < 0 else prod_str + "}" formula = OldTex( mean_str, "\\pm \\sqrt{\\,", mean_str, "^2 - ", last_part, font_size=60, tex_to_color_map={mean_str: MEAN_COLOR, prod_str: PROD_COLOR}, ) formula.next_to(mat, RIGHT, buff=1.5) self.play( Write(formula[1]), Write(formula[3]), FadeTransform(mean_eq[2].copy(), formula[0]), FadeTransform(mean_eq[2].copy(), formula[2]), ) self.wait() # Product prod_eq = OldTex( f"p = {a * d} - {b * c} = {prod}", tex_to_color_map={ str(prod): PROD_COLOR, str(a * d): COL_COLORS[0], str(b * c): COL_COLORS[0], "=": WHITE, } ) prod_eq.move_to(mean_eq) self.play( FadeIn(prod_eq[:2]), mean_eq.animate.shift(UP), ) self.play( FadeIn(prod_eq[2]), VFadeInThenOut(get_diag_rects(mat, color=YELLOW), run_time=1.5), ) self.play( FadeIn(prod_eq[3:5]), VFadeInThenOut(get_diag_rects(mat, color=YELLOW, off_diagonal=True), run_time=1.5), ) self.wait() self.play(Write(prod_eq[5:])) self.play(FadeTransform(prod_eq[-1].copy(), formula[4:])) self.wait() # Simplify line2 = OldTex(mean_str, "\\pm", "\\sqrt{\\,", str(mean**2 - prod), "}", font_size=60) if mean == 0: line2[0].scale(0, about_point=line2[1].get_left()) line2[0].set_color(MEAN_COLOR) line2.next_to(formula, DOWN, buff=0.7, aligned_edge=LEFT) self.play(FadeTransform(formula.copy()[:4], line2)) self.wait() line3 = self.get_final_simplification() if line3: line3.next_to(line2, DOWN, buff=0.7, aligned_edge=LEFT) self.play(FadeIn(line3, DOWN)) self.wait() answer = line3[-1] else: answer = line2 self.play(ShowCreation(SurroundingRectangle(answer))) self.wait() def get_final_simplification(self): return None class Example2(GeneralExample): matrix = [[2, 7], [1, 8]] def get_final_simplification(self): return OldTex("5 \\pm 4", "=", "9,\\,1", font_size=60) class Example3(GeneralExample): matrix = [[3, 11], [1, 11]] class Example4(GeneralExample): matrix = [[2, -1], [2, 0]] class Example5(GeneralExample): matrix = [[2, 3], [5, 7]] class PauliMatrices(Scene): def construct(self): self.camera.frame.focal_distance = 20 # Matrices colors = [RED, GREEN, BLUE] lhss, matrices = self.get_lhss_and_matrices(colors) self.add(lhss) self.play(LaggedStartMap(FadeIn, matrices, shift=0.25 * RIGHT, lag_ratio=0.3, run_time=2)) self.wait() # Title title = Text("Pauli spin matrices") title.next_to(group, RIGHT, buff=1.25) self.play(Write(title, run_time=2)) self.wait() # Axes axes = ThreeDAxes( (-2, 2), (-2, 2), (-2, 2), axis_config={"include_tip": False} ) axes.set_flat_stroke(False) axes.rotate(20 * DEGREES, OUT) axes.rotate(70 * DEGREES, LEFT) axes.set_height(1.7) axes.labels = VGroup(*( OldTex(ch, font_size=24).next_to(axis.get_end(), vect, buff=SMALL_BUFF) for ch, axis, vect in zip("xyz", axes.get_axes(), [RIGHT, UP, UP]) )) axes.add(axes.labels) axes.set_stroke(background=True) axes_copies = VGroup() for i, matrix, color, (v1, v2) in zip(it.count(), matrices, colors, [(UP, DOWN), (LEFT, RIGHT), (RIGHT, RIGHT)]): ac = axes.deepcopy() ac.labels.set_fill(GREY_C, 1) ac.labels[i].set_fill(color, 1) axis = ac.get_axes()[i] vp1, vm1 = ( Arrow(axis.n2p(0), axis.n2p(n), buff=0.05, fill_color=color, thickness=0.05) for n in (2, -2) ) for vector, tex, v in [(vp1, "+1", v1), (vm1, "-1", v2)]: vector.add(OldTex(tex, font_size=24).next_to(vector, v, buff=0.05)) ac.add(vp1, vm1) ac.next_to(matrix, RIGHT, buff=LARGE_BUFF) axes_copies.add(ac) acx, acy, acz = axes_copies self.play( FadeOut(title), Write(acx, stroke_width=0.5), ) self.wait() self.play(TransformFromCopy(acx, acy)) self.wait() self.play(TransformFromCopy(acy, acz)) self.wait() self.play(LaggedStartMap(FadeOut, axes_copies, shift=0.25 * DOWN, run_time=1, lag_ratio=0.3)) # Compute means means_rects = VGroup(*( get_diag_rects(matrix) for matrix in matrices )) mean_eqs = VGroup(*( OldTex("m = 0", tex_to_color_map={"m": MEAN_COLOR, "0": WHITE}).next_to(matrix, RIGHT, buff=MED_LARGE_BUFF) for matrix in matrices )) kw = { "tex_to_color_map": { "0": MEAN_COLOR, "{p}": PROD_COLOR, } } forms = VGroup(*( OldTex("0 \\pm \\sqrt{\\,0^2 - {p}}", **kw).next_to(matrix, RIGHT).to_edge(RIGHT) for matrix in matrices )) simple_forms = VGroup(*( OldTex("\\pm \\sqrt{-{p}}", **kw).move_to(form, LEFT) for form in forms )) for me, mr, form in zip(mean_eqs, means_rects, forms): self.play( FadeIn(mr), Write(me[:2], run_time=1), ) self.play( TransformFromCopy(mr, me[2], run_time=0.7) ) self.wait() self.play( LaggedStart(*( FadeIn(VGroup(form[1], form[3], form[4])) for form in forms ), lag_ratio=0.2), LaggedStart(*( TransformFromCopy(me.get_parts_by_tex("0"), form.get_parts_by_tex("0")) for me, form in zip(mean_eqs, forms) ), lag_ratio=0.2), ) self.wait() self.play(LaggedStart(*( TransformMatchingShapes(form, simple_form) for form, simple_form in zip(forms, simple_forms) ))) self.wait() # Products prod_eqs = VGroup(*( OldTex("p = -1", tex_to_color_map={"p": PROD_COLOR, "-1": WHITE}).next_to( matrix, RIGHT, buff=MED_LARGE_BUFF ).shift(0.5 * DOWN) for matrix in matrices )) self.play( mean_eqs.animate.shift(0.5 * UP), LaggedStart(*(FadeIn(pe[:2]) for pe in prod_eqs)), FadeOut(means_rects) ) self.play(LaggedStart(*(det_path_anim(matrix) for matrix in matrices), lag_ratio=0.2)) for matrix, pe in zip(matrices, prod_eqs): r1 = get_diag_rects(matrix) r2 = get_diag_rects(matrix, off_diagonal=True) VGroup(r1, r2).set_color(YELLOW) self.play(FadeIn(r1)) self.play(FadeOut(r1), FadeIn(r2), FadeIn(pe[2])) self.play(FadeOut(r2)) self.wait() final_forms = VGroup(*( OldTex("= \\pm 1").move_to(sf.get_center(), LEFT) for sf in simple_forms )) self.play( LaggedStart(*( FadeTransform(pe[2].copy(), ff) for pe, ff in zip(prod_eqs, final_forms) ), lag_ratio=0.3), LaggedStart(*( sf.animate.next_to(ff, LEFT) for sf, ff in zip(simple_forms, final_forms) )) ) self.wait() # Bring back axes axes_copies.shift(2 * RIGHT) self.play( FadeOut(simple_forms), FadeOut(final_forms), FadeIn(acx), ) self.play(FadeIn(acy)) self.play(FadeIn(acz)) self.wait() def get_lhss_and_matrices(self, colors): lhss = VGroup(*(OldTex(f"\\sigma_{c} = ") for c in "xyz")) kw = {"h_buff": 0.7, "v_buff": 0.7} matrices = VGroup( Matrix([["0", "1"], ["1", "0"]], **kw), Matrix([["0", "-i"], ["i", "0"]], **kw), Matrix([["1", "0"], ["0", "-1"]], **kw), ) lhss.set_submobject_colors_by_gradient(*colors) lhss.arrange(DOWN, buff=2.5) for lhs, matrix in zip(lhss, matrices): matrix.set_height(1.5) matrix.next_to(lhs, RIGHT) group = VGroup(lhss, matrices) group.move_to(2 * LEFT) return group class SpinMeasurements(ThreeDScene): def construct(self): # Reorient frame = self.camera.frame frame.reorient(-70, 70) frame.add_updater(lambda m, dt: m.increment_theta(0.01 * dt)) self.add(frame) # Create machine north_verts = [UL + 0.5 * DOWN, UR + 0.5 * DOWN, DR, 2 * DOWN, DL] south_verts = [DOWN + 2 * LEFT, UP + 2 * LEFT, UL, LEFT, RIGHT, UR, UP + 2 * RIGHT, DOWN + 2 * RIGHT] north_bar = get_prism(north_verts, depth=2) south_bar = get_prism(south_verts, depth=2) N_text = Text("N").move_to(north_bar, OUT).shift(0.025 * OUT) S_text = Text("S").move_to(south_bar, OUT).shift(0.025 * OUT) S_text.set_y(-0.5) north_bar.add(N_text) south_bar.add(S_text) south_bar.move_to(ORIGIN, UP).shift(0.5 * UP) north_bar.move_to(south_bar.get_top(), DOWN) machine = VGroup(north_bar, south_bar) machine.set_stroke(width=0) # for bar in machine: # bar.space_out_submobjects(1.1) # Screen screen = FullScreenRectangle() axes = Axes((-3, 3), (-3, 3)) for sm in axes.get_family(): sm.flat_stroke = False sm.insert_n_curves(10) axes.add(OldTex("+z").next_to(axes.c2p(0, 2), RIGHT)) axes.add(OldTex("-z").next_to(axes.c2p(0, -2), RIGHT)) axes.shift(0.1 * OUT) screen.set_height(5) screen.set_fill(GREY_D, 1) screen.set_stroke(WHITE, 2) screen.shift(5 * IN) axes.shift(5 * IN) # Rotate all everything = VGroup(screen, axes, machine) everything.apply_depth_test() self.add(everything) self.update_frame() # Why? everything.rotate(89.5 * DEGREES, RIGHT, about_point=ORIGIN) self.play( FadeIn(screen), FadeIn(axes), FadeIn(machine, lag_ratio=0.05), ) self.wait() # Paths def path(t): if t < -1: z = 0 elif t < 1: z = (1 / 4) * (t + 1)**2 else: z = t return [0, t, z] high_beam = ParametricCurve(path, (-5, 5)) high_beam.set_stroke(BLUE, 10) high_beam.set_depth(1, stretch=True, about_point=ORIGIN) high_beam.apply_depth_test() low_beam = high_beam.copy() low_beam.stretch(-1, 2, about_point=ORIGIN) def hit_anim(spin=1): circ = Circle(radius=0.5) circ.set_stroke(BLUE, 0) circ.rotate(90 * DEGREES, RIGHT) circ.move_to(5 * UP + spin * OUT) tex = OldTex("+1" if spin == 1 else "-1") tex.shift(20 * OUT) self.add(tex) self.update_frame() tex.rotate(90 * DEGREES, RIGHT) tex.move_to(circ.get_left()) pre_circ = circ.copy() pre_circ.scale(0) pre_circ.set_stroke(BLUE, 10) return AnimationGroup( Transform(pre_circ, circ, remover=True), VFadeInThenOut(tex), ) for x in range(20): if random.random() < 0.5: beam = high_beam spin = +1 else: beam = low_beam spin = -1 self.play(LaggedStart( VShowPassingFlash(beam, time_width=0.5), hit_anim(spin), lag_ratio=0.6 )) class HeresTheThing(TeacherStudentsScene): def construct(self): self.student_says( "Wait, why?", target_mode="raise_right_hand", look_at=self.screen, index=2, ) self.play( self.change_students("maybe", "confused", "raise_right_hand", look_at=self.screen), self.teacher.change("happy"), ) self.wait(3) self.teacher_says( OldTexText("Here's the thing..."), added_anims=[self.change_students("sassy", "plain", "hesitant")], target_mode="hesitant", ) self.wait(2) self.play(RemovePiCreatureBubble(self.teacher, target_mode="raise_right_hand")) for pi in self.pi_creatures: for eye in pi.eyes: eye.refresh_bounding_box() self.look_at(self.screen) self.play_student_changes("tease", "thinking", "happy", look_at=self.screen) self.wait(3) words = OldTexText("Somewhat\\\\self-defeating") words.next_to(self.screen, RIGHT) words.shift(RIGHT) self.play( self.teacher.change("guilty"), self.change_students("sassy", "hesitant", "sassy"), Write(words), ) self.wait(4) class NotAllHopeIsLost(TeacherStudentsScene): def construct(self): self.teacher_says( OldTexText("There's still a\\\\good example here"), target_mode="speaking", bubble_config={"height": 3, "width": 4}, added_anims=[self.change_students("erm", "sassy", "hesitant")], ) self.wait(2) class PauliMatricesWithCharacteristicPolynomial(PauliMatrices): def construct(self): # Set up determinants colors = [RED, GREEN, BLUE] lhss, matrices = group = self.get_lhss_and_matrices(colors) group.to_edge(LEFT) kw = { "element_to_mobject_config": { "tex_to_color_map": { "-\\lambda": EIGEN_COLORS[1], } }, "v_buff": 0.7, "h_buff": 1.3, } new_matrices = VGroup( Matrix([["-\\lambda", "1"], ["1", "-\\lambda"]], **kw), Matrix([["-\\lambda", "-i"], ["i", "-\\lambda"]], **kw), Matrix([["1 -\\lambda", "0"], ["0", "-1 -\\lambda"]], **kw), ) arrows = VGroup() det_terms = VGroup() for mat, new_mat in zip(matrices, new_matrices): mat.set_height(1.0, about_edge=LEFT) new_mat.replace(mat, dim_to_match=1) new_mat.shift(3.75 * RIGHT) parens = OldTex("()", font_size=60)[0] parens.match_height(new_mat, stretch=True) parens[0].next_to(new_mat, LEFT, buff=0.1) parens[1].next_to(new_mat, RIGHT, buff=0.1) det = Text("det", font_size=30) det.next_to(parens, LEFT, SMALL_BUFF) det_terms.add(VGroup(det, parens, new_mat)) arrows.add(Arrow(mat, det, buff=0.2)) self.add(lhss, matrices) self.wait() self.play( LaggedStart(*( TransformMatchingShapes(mat.copy(), det_term) for mat, det_term in zip(matrices, det_terms) ), lag_ratio=0.8), LaggedStartMap(GrowArrow, arrows, lag_ratio=0.8), ) self.wait() # Polynomials kw = {"tex_to_color_map": { "\\lambda": EIGEN_COLORS[1], "=": WHITE, }} rhss = VGroup( OldTex("= \\lambda^2 - 1 = 0", **kw), OldTex("= \\lambda^2 - 1 = 0", **kw), OldTex("= (1 - \\lambda)(-1 - \\lambda) = 0", **kw), ) lpm1s = VGroup() for rhs, det_term in zip(rhss, det_terms): rhs.next_to(det_term, RIGHT, SMALL_BUFF, submobject_to_align=rhs[0]) self.play(LaggedStart( det_path_anim(det_term[-1]), TransformMatchingShapes(det_term[-1].get_entries().copy(), rhs), lag_ratio=0.5 )) if rhs is rhss[-1]: continue self.play(FlashUnder(rhs)) self.wait() lpm1 = OldTex("\\lambda = \\pm 1", **kw) lpm1.next_to(rhs, DOWN, buff=0.75) lpm1s.add(lpm1) self.play(TransformMatchingShapes(rhs[1:4].copy(), lpm1)) self.wait() # Comment on last rect = SurroundingRectangle(matrices[2]) words = Text("Already diagonal!", font_size=24) words.next_to(rect, UP) words.set_color(YELLOW) diag_rects = get_diag_rects(matrices[2], color=EIGEN_COLORS[1]) self.play(FadeInFromLarge(rect)) self.play(Write(words, run_time=1)) self.wait() self.play(ShowCreation(diag_rects)) self.wait() self.play(LaggedStartMap(FadeOut, VGroup( *arrows, *det_terms, *rhss, *lpm1s, rect, words, diag_rects, ))) # Show combinations colors = [YELLOW_B, YELLOW_C, YELLOW_D] def get_combo(triplet): group = VGroup( OldTex("a"), triplet[0].copy(), OldTex("+"), OldTex("b"), triplet[1].copy(), OldTex("+"), OldTex("c"), triplet[2].copy() ) group.arrange(RIGHT, buff=0.15) group[3].align_to(group[0], DOWN) group[6].align_to(group[0], DOWN) group.set_color(WHITE) group[0::3].set_submobject_colors_by_gradient(*colors) return group true_lhss = VGroup(*(lhs[0][:2] for lhs in lhss)) row1 = get_combo(true_lhss) row1[1::3].shift(0.06 * DOWN) row2 = get_combo(matrices) rows = VGroup(row1, row2) rows.arrange(DOWN, buff=LARGE_BUFF) rows.to_corner(UR, buff=LARGE_BUFF) kw = {"tex_to_color_map": { "a": colors[0], "b": colors[1], "c": colors[2], "\\lambda": EIGEN_COLORS[1], }} normalized_eq = OldTex("\\left(a^2 + b^2 + c^2 = 1\\right)", **kw) normalized_eq.next_to(row2, DOWN, LARGE_BUFF) normalized_eq.to_edge(DOWN) full_mat = Matrix( [ ["c", "a - bi"], ["a + bi", "-c"], ], element_to_mobject_config=kw, h_buff=1.5 ) full_mat.next_to(row2, DOWN, LARGE_BUFF) self.play(TransformMatchingShapes(true_lhss.copy(), row1)) self.wait() self.play(FadeTransformPieces(row1.copy(), row2)) self.wait() self.play(TransformMatchingShapes(row2.copy(), full_mat)) self.wait() # Let some physics happen self.play(TransformMatchingShapes(row2[0::3].copy(), normalized_eq)) self.wait() # Talk about eigen computations self.play(FadeOut(lhss), FadeOut(matrices)) randy = Randolph() randy.set_height(2) randy.next_to(full_mat, LEFT).to_edge(DOWN) randy.set_opacity(0) diag_rects = get_diag_rects(full_mat) bubble = ThoughtBubble(height=2, width=2) bubble.pin_to(randy) m_eq = OldTex("m = 0", tex_to_color_map={"m": MEAN_COLOR}) p_eq = OldTex("p = ??", tex_to_color_map={"p": PROD_COLOR}) bubble.position_mobject_inside(m_eq) bubble.position_mobject_inside(p_eq) p_eq2 = OldTex("p = -1", tex_to_color_map={"p": PROD_COLOR}) p_eq2.next_to(full_mat, RIGHT, aligned_edge=DOWN) self.play( VFadeIn(randy), randy.animate.set_opacity(1).change("hesitant", full_mat) ) self.play(ShowCreation(diag_rects)) self.play( Write(bubble), Write(m_eq), randy.change("pondering", bubble) ) self.play(randy.change("thinking", bubble)) self.play(Blink(randy)) self.wait() self.play( FadeIn(p_eq, 0.25 * UP), m_eq.animate.next_to(full_mat, RIGHT, aligned_edge=UP), randy.change("hesitant", full_mat), FadeOut(diag_rects), ) self.play(det_path_anim(full_mat)) self.play(Blink(randy)) self.wait() self.play( FadeOut(bubble), randy.change("tease", p_eq2), Transform(p_eq, p_eq2), ) self.play(Blink(randy)) self.wait() # Characteristic polynomial mod_mat = Matrix( [ ["c - \\lambda", "a - bi"], ["a + bi", "-c - \\lambda"], ], element_to_mobject_config=kw, h_buff=2.0 ) parens = OldTex("(", ")") parens.stretch(2, 1) parens.match_height(mod_mat) parens[0].next_to(mod_mat, LEFT, SMALL_BUFF) parens[1].next_to(mod_mat, RIGHT, SMALL_BUFF) det = Text("det") det.next_to(parens, LEFT, SMALL_BUFF) char_poly = VGroup(det, parens, mod_mat) char_poly.next_to(randy, UL) self.play( TransformMatchingShapes(full_mat.copy(), char_poly, run_time=2), randy.change("raise_left_hand", char_poly), ) self.play(randy.change("horrified", char_poly)) self.play(Blink(randy)) self.wait() self.play(randy.change("tired")) self.wait() class ThreeSpinExamples(Scene): def construct(self): frame = self.camera.frame frame.focal_distance = 20 frame.reorient(-20, 70) axes = ThreeDAxes( (-1, 1), (-1, 1), (-1, 1), axis_config={"tick_size": 0, "include_tip": False} ) axes.insert_n_curves(10) axes.flat_stroke = False axes.set_stroke(WHITE, 3) axes.apply_depth_test() all_axes = axes.get_grid(3, 1) all_axes.arrange(IN, buff=0.8) self.add(all_axes) for axes, vect, color in zip(all_axes, [RIGHT, UP, OUT], [RED, GREEN, BLUE]): sphere = Sphere() sphere.scale(0.9) mesh = SurfaceMesh(sphere, resolution=(21, 11)) mesh.set_stroke(color, width=1, opacity=0.8) mesh.apply_matrix(z_to_vector(vect)) sphere = Group(sphere, mesh) sphere.scale(0.5) sphere.move_to(axes) axes.sphere = sphere sphere.vect = vect sphere.add_updater(lambda m, dt: m.rotate(dt, m.vect)) self.add(sphere) self.wait(2 * TAU) class GeneralDirection(Scene): def construct(self): frame = self.camera.frame frame.reorient(-30, 70) frame.add_updater(lambda m, dt: m.increment_theta(0.01 * dt)) self.add(frame) axes = ThreeDAxes( (-2, 2), (-2, 2), (-4, 4), axis_config={'include_tip': False}, depth=6, ) axes.set_stroke(width=1) self.add(axes) vect = axes.c2p(2, 2, 2) vector = Vector(vect) vector.set_fill(YELLOW) label = Matrix([["a"], ["b"], ["c"]], v_buff=0.6) # label.get_entries().set_submobject_colors_by_gradient( # YELLOW_B, YELLOW_C, YELLOW_D # ) label.get_entries().set_color(YELLOW) label.rotate(89 * DEGREES, RIGHT) label.next_to(vector.get_end(), RIGHT) sphere = Sphere() sphere.scale(0.5) mesh = SurfaceMesh(sphere, resolution=(21, 11)) mesh.set_stroke(BLUE, width=0.5, opacity=0.5) for mob in sphere, mesh: mob.apply_matrix(z_to_vector(vect)) mob.add_updater(lambda m, dt: m.rotate(0.75 * dt, axis=vect)) axes.apply_depth_test() for sm in axes.get_family(): sm.insert_n_curves(10) self.add(vector, sphere, mesh) self.play( GrowArrow(vector), UpdateFromAlphaFunc(sphere, lambda m, a: m.set_opacity(a)), Write(mesh), ) self.play(Write(label)) self.wait(6) self.play( vector.animate.scale(0.5, about_point=ORIGIN), label.animate.shift(-0.5 * vect) ) self.wait(24) class TwoValuesEvenlySpaceAroundZero(Scene): def construct(self): nl = NumberLine((-2, 2, 0.25), width=6) nl.add_numbers(np.arange(-2, 3, 1.0), num_decimal_places=1, font_size=24) d_tracker = ValueTracker(2) get_d = d_tracker.get_value dots = VGroup(*(Dot() for x in range(2))) labels = VGroup(OldTex("\\lambda_1"), OldTex("\\lambda_2")) for group in dots, labels: group.set_submobject_colors_by_gradient(*EIGEN_COLORS) def update_dots(dots): dots[0].move_to(nl.n2p(-get_d())) dots[1].move_to(nl.n2p(get_d())) def update_labels(labels): for label, dot in zip(labels, dots): label.match_color(dot) label.next_to(dot, UP, SMALL_BUFF) dots.add_updater(update_dots) labels.add_updater(update_labels) prod_label = VGroup( labels.copy().clear_updaters().arrange(RIGHT, buff=SMALL_BUFF), OldTex("="), DecimalNumber(-4), ) prod_label[-1].match_height(prod_label[0]) prod_label.arrange(RIGHT) prod_label.next_to(labels, UP, LARGE_BUFF) prod_label[-1].add_updater(lambda m: m.set_value(-get_d()**2)) self.add(nl, dots, labels, prod_label) self.play(d_tracker.animate.set_value(0.5), run_time=3) self.play(d_tracker.animate.set_value(1.5), run_time=3) self.play(d_tracker.animate.set_value(1.0), run_time=2) self.wait() class MPIsSolvingCharPoly(TeacherStudentsScene): def construct(self): formula = OldTex( "{m} \\pm \\sqrt{\\,{m}^2 - {p}}", tex_to_color_map={"{m}": MEAN_COLOR, "{p}": PROD_COLOR}, font_size=72 ) char_poly = get_det_mod_mat(get_mod_mat([["a", "b"], ["c", "d"]])) eq0 = OldTex("=0") eq0.next_to(char_poly, RIGHT, SMALL_BUFF) char_poly.add(eq0) char_poly.move_to(self.hold_up_spot, DOWN) arrow = Arrow(RIGHT, LEFT) arrow.next_to(char_poly, LEFT) self.teacher_holds_up(formula) self.play_student_changes( "happy", "thinking", "tease", look_at=formula ) self.wait() self.play( self.teacher.change("hooray", char_poly), formula.animate.next_to(arrow, LEFT), FadeIn(char_poly, 0.5 * UP), ) self.play_student_changes( "erm", "pondering", "pondering", look_at=char_poly, added_anims=[GrowArrow(arrow)] ) self.wait(3) class QuadraticPolynomials(Scene): def construct(self): # Set up equation kw = { "tex_to_color_map": { "\\lambda_1": EIGEN_COLORS[0], "\\lambda_2": EIGEN_COLORS[1], "=": WHITE, } } equation = VGroup( OldTex("x^2 - 10x + 9", **kw)[0], OldTex("=").rotate(PI / 2), OldTex("x^2 - (\\lambda_1 + \\lambda_2)x + \\lambda_1 \\lambda_2", **kw), OldTex("=").rotate(PI / 2), OldTex("(x - \\lambda_1)(x - \\lambda_2)", **kw), ) equation.arrange(DOWN) equation.to_edge(LEFT) line1, eq1, line2, eq2, line3 = equation for line in line2, line3: line.set_submobjects(line.family_members_with_points()) line3.save_state() line3.move_to(line2) # Graph axes = Axes( (-5, 10), (-20, 20), height=7, width=FRAME_WIDTH / 2, ) axes.y_axis.ticks.stretch(0.75, 0) axes.to_edge(RIGHT) graph = axes.get_graph(lambda x: x**2 - 10 * x + 9) graph.set_color(BLUE) graph_label = line1.copy() graph_label.set_color(BLUE) graph_label.next_to(graph.get_end(), UP) graph_label.to_edge(RIGHT) root_dots = VGroup() root_labels = VGroup() for i, n, vect in zip((0, 1), (1, 9), (RIGHT, LEFT)): dot = Dot(axes.c2p(n, 0), color=EIGEN_COLORS[i]) label = OldTex(f"\\lambda_{i + 1}") label.match_color(dot) label.next_to(dot, UP + vect, buff=0.05) root_dots.add(dot) root_labels.add(label) root_dots.set_stroke(BLACK, 5, background=True) self.play(Write(axes)) self.play( ShowCreation(graph, run_time=3), FadeIn(graph_label, UP) ) self.play( LaggedStartMap(GrowFromCenter, root_dots), LaggedStart( GrowFromPoint(root_labels[0], root_dots[0].get_center()), GrowFromPoint(root_labels[1], root_dots[1].get_center()), ) ) self.wait() # Animate to equation self.play(TransformFromCopy(graph_label, line1)) self.play( Write(eq1), TransformMatchingShapes(root_labels.copy(), line3) ) self.wait() self.play(Restore(line3)) xs = VGroup(line3[1], line3[7]) self.play(TransformFromCopy(xs, line2[:2])) # x^2 self.play(LaggedStart( # x AnimationGroup( TransformFromCopy(line3[1], line2[10].copy()), TransformFromCopy(line3[9:11], line2[7:9]), FadeIn(line2[2]) ), AnimationGroup( TransformFromCopy(line3[7], line2[10].copy(), remover=True), TransformFromCopy(line3[3:5], line2[4:6]), FadeIn(VGroup(line2[3], line2[6], line2[9])) ), )) self.play( TransformFromCopy( VGroup(*line3[3:5], *line3[9:11]), VGroup(*line2[12:16]), ), FadeIn(line2[11]), FadeIn(eq2), ) self.wait() # Highlight sum and product for i, j, k, l in [(3, 5, 3, 10), (7, 8, 12, 16)]: self.play( FadeIn(SurroundingRectangle(line1[i:j])), FadeIn(SurroundingRectangle(line2[k:l])), run_time=2, rate_func=there_and_back_with_pause, remover=True ) # Show mean and product line2 = VGroup(*line2.family_members_with_points()) line3 = VGroup(*line3.family_members_with_points()) quad_terms = VGroup(line1[0:2], line2[0:2]) lin_terms = VGroup(line1[2:5], line2[2:10]) const_terms = VGroup(line1[6:], line2[11:]) mean_arrow = Vector(UP) mean_arrow.next_to(lin_terms[0], UP, MED_SMALL_BUFF) times_half = OldTex("\\times -\\frac{1}{2}", font_size=24) times_half.next_to(mean_arrow, RIGHT, buff=0) m_eq = OldTex( "{\\lambda_1 + \\lambda_2 \\over 2}", "=", "5", tex_to_color_map={"\\lambda_1": EIGEN_COLORS[0], "\\lambda_2": EIGEN_COLORS[1]} ) m_eq.next_to(mean_arrow, UP, SMALL_BUFF, submobject_to_align=m_eq[-1]) m_eq[:-2].scale(0.7, about_edge=RIGHT) m_dot = Dot(axes.c2p(5, 0)) m_dot.scale(0.5) m_label = Integer(5, font_size=30) m_label.next_to(m_dot, UP, SMALL_BUFF) p_rects = VGroup(*map(SurroundingRectangle, const_terms)) p_rects.set_stroke(PROD_COLOR) fade_rect = FullScreenFadeRectangle() fade_rect.set_fill(BLACK, 0.75) fade_rect.replace(equation, stretch=True) self.add(fade_rect, *quad_terms) self.play(FadeIn(fade_rect)) self.wait() self.add(fade_rect, *lin_terms) self.wait() self.play( GrowArrow(mean_arrow), FadeIn(times_half, shift=0.25 * UP, scale=2), FadeIn(m_eq[:-1]) ) self.play(Write(m_eq[-1])) self.play( FadeTransform(m_eq[-1].copy(), m_dot), FadeTransform(m_eq[-1].copy(), m_label), ) self.wait() self.add(fade_rect, *const_terms) VGroup(mean_arrow, times_half).set_opacity(0.5) self.play(ShowCreation(p_rects)) self.wait() # Show final roots d_terms = VGroup(*( OldTex(u, "\\sqrt{25 - 9}", font_size=24) for u in ["+", "-"] )) my = m_label.get_y() arrows = VGroup( Arrow(m_label.get_left(), [root_dots[0].get_left()[0], my, 0], buff=0.1), Arrow(m_label.get_right(), [root_dots[1].get_right()[0], my, 0], buff=0.1), ) for d_term, arrow in zip(d_terms, arrows): d_term.next_to(arrow, UP, buff=0) self.play(FadeOut(p_rects)) self.play( TransformMatchingShapes(equation[0][-2:].copy(), d_terms), FadeOut(root_labels), *map(GrowArrow, arrows) ) self.wait() self.play( FadeOut(fade_rect), ) self.wait() class SimplerQuadraticFormula(Scene): def construct(self): # Show comparison form1 = OldTex( "{m} \\pm \\sqrt{\\,{m}^2 - {p}}", tex_to_color_map={"{m}": MEAN_COLOR, "{p}": PROD_COLOR}, font_size=72 ) words = OldTexText("takes less to\\\\remember than") form2 = OldTex( "{-b \\pm \\sqrt{\\,b^2 - 4ac} \\over 2a}", tex_to_color_map={ "a": MAROON_A, "b": MAROON_B, "c": MAROON_C, }, font_size=72 ) group = VGroup(form1, words, form2) group.arrange(DOWN, buff=1.5) self.add(form1) self.play(Write(words, run_time=1)) self.play(FadeIn(form2, DOWN)) self.wait() class SkipTheMiddleStep(Scene): def construct(self): matrix = IntegerMatrix([[3, 1], [4, 1]]) matrix.set_column_colors(*COL_COLORS) char_poly = OldTex( "\\lambda^2 - 4\\lambda - 1", tex_to_color_map={"\\lambda": EIGEN_COLORS[0]} ) mp_formula = OldTex( "{2} \\pm \\sqrt{\\,{2}^2 - (-1)}", tex_to_color_map={ "{2}": MEAN_COLOR, "(-1)": PROD_COLOR, } ) group = VGroup(matrix, char_poly, mp_formula) group.arrange(RIGHT, buff=2) mat_label, char_poly_label, eigen_label = labels = VGroup( OldTexText("Matrix"), OldTexText("Characteristic\\\\polynomial"), OldTexText("Eigenvalues"), ) for label, mob, color in zip(labels, group, [COL_COLORS[0], EIGEN_COLORS[0], MEAN_COLOR]): label.set_color(color) label.next_to(mob, DOWN, MED_LARGE_BUFF) label.align_to(labels[0], UP) arc = -90 * DEGREES arrows = VGroup( Arrow(matrix.get_corner(UR), char_poly.get_top(), path_arc=arc), Arrow(char_poly.get_top(), mp_formula.get_top(), path_arc=arc), Arrow(matrix.get_corner(UR), mp_formula.get_top(), path_arc=0.8 * arc), ) arrows.shift(0.5 * UP) self.add(matrix, mat_label) self.play( DrawBorderThenFill(arrows[0]), GrowFromPoint(char_poly, matrix.get_top(), path_arc=arc), FadeTransform(mat_label.copy(), char_poly_label), ) self.wait() self.play( DrawBorderThenFill(arrows[1]), TransformFromCopy(char_poly, mp_formula), FadeTransform(char_poly_label.copy(), eigen_label), ) self.wait() self.play( VFadeInThenOut(get_diag_rects(matrix), run_time=2), LaggedStart(*( ShowCreationThenFadeOut(SurroundingRectangle(sm, buff=0.1, color=WHITE), run_time=2) for sm in mp_formula.get_parts_by_tex("{2}") )) ) self.play( det_path_anim(matrix), ShowCreationThenFadeOut(SurroundingRectangle( mp_formula.get_parts_by_tex("(-1)"), buff=0.1, color=WHITE, ), run_time=2) ) self.wait() self.play( Transform(arrows[0], arrows[2]), Transform(arrows[1], arrows[2]), VGroup(char_poly, char_poly_label).animate.set_opacity(0.15), ) self.wait() # frame = self.camera.frame quad_form = OldTex( "{-b \\pm \\sqrt{\\,b^2 - 4ac} \\over 2a}", tex_to_color_map={ "a": BLUE_B, "b": BLUE_C, "c": BLUE_D, } ) words = OldTexText("Never could\\\\have worked!") group = VGroup(quad_form, words) group.arrange(RIGHT, buff=LARGE_BUFF) group.next_to(arrows, UP, LARGE_BUFF) cross = Cross(quad_form) cross.set_stroke(width=(1, 3, 3, 1)) self.play( frame.animate.set_y(1), FadeIn(quad_form, DOWN), ) self.wait() self.play( Write(words), ShowCreation(cross) ) self.wait() class GeneralCharPoly(Scene): def construct(self): t2c = { "a": COL_COLORS[0], "b": COL_COLORS[1], "c": COL_COLORS[0], "d": COL_COLORS[1], "\\lambda": EIGEN_COLORS[1], "-": WHITE, "+": WHITE, "=": WHITE, } det = get_det_mod_mat(get_mod_mat([["a", "b"], ["c", "d"]], t2c=t2c)) rhs1 = OldTex("= (a - \\lambda)(d - \\lambda) - bc", tex_to_color_map=t2c) rhs2 = OldTex("= \\lambda^2 - (a + d)\\lambda + (ad - bc)", tex_to_color_map=t2c) rhs1.next_to(det, RIGHT) rhs2.next_to(rhs1, DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) VGroup(det, rhs1, rhs2).center() self.add(det) self.wait() self.play(TransformMatchingShapes( det[-1].get_entries()[0::3].copy(), rhs1[:10], )) self.play(TransformMatchingShapes( det[-1].get_entries()[1:3].copy(), rhs1[10:], path_arc=45 * DEGREES, )) self.wait() self.play(TransformMatchingShapes(rhs1.copy(), rhs2, run_time=1.5)) self.wait() self.play(ShowCreation(SurroundingRectangle(rhs2[3:9], buff=0.05, color=MEAN_COLOR))) self.play(ShowCreation(SurroundingRectangle(rhs2[11:], buff=0.05, color=PROD_COLOR))) self.wait() self.embed() class EndScreen(PatreonEndScreen): pass
from manim_imports_ext import * from _2022.quintic import coefficients_to_roots from _2022.quintic import roots_to_coefficients from _2022.quintic import dpoly from _2022.quintic import poly ROOT_COLORS_BRIGHT = [RED, GREEN, BLUE, YELLOW, MAROON_B] ROOT_COLORS_DEEP = ["#440154", "#3b528b", "#21908c", "#5dc963", "#29abca"] CUBIC_COLORS = [RED_E, TEAL_E, BLUE_E] def glow_dot(point, r_min=0.05, r_max=0.15, color=YELLOW, n=20, opacity_mult=1.0): result = VGroup(*( Dot(point, radius=interpolate(r_min, r_max, a)) for a in np.linspace(0, 1, n) )) result.set_fill(color, opacity=opacity_mult / n) return result def get_newton_rule(font_size=36, var="z", **kwargs): terms = [f"{var}_n", f"{var}_{{n + 1}}"] t0, t1 = terms return OldTex( t1, "=", t0, "-", "{P(", t0, ")", "\\over ", "P'(", t0, ")}", font_size=36, **kwargs ) def coefs_to_poly_string(coefs): n = len(coefs) - 1 tex_str = "" if coefs[-1] == 1 else str(int(coefs[-1])) tex_str += f"z^{{{n}}}" for c, k in zip(coefs[-2::-1], it.count(n - 1, -1)): if c == 0: continue if isinstance(c, complex): num_str = "({:+}".format(int(c.real)) num_str += "+ {:+})".format(int(c.imag)) else: num_str = "{:+}".format(int(c)) if abs(c) == 1 and k > 0: num_str = num_str[:-1] tex_str += num_str if k == 0: continue elif k == 1: tex_str += "z" else: tex_str += f"z^{{{k}}}" return tex_str def get_figure(image_name, person_name, year_text, height=3, label_direction=DOWN): image = ImageMobject(image_name) image.set_height(height) rect = SurroundingRectangle(image, buff=0) rect.set_stroke(WHITE, 2) name = Text(f"{person_name}", font_size=36) name.set_color(GREY_A) year_label = Text(f"{year_text}", font_size=30) year_label.match_color(name) year_label.next_to(name, DOWN, buff=0.2) VGroup(name, year_label).next_to(image, label_direction) return Group(rect, image, name, year_label) class NewtonFractal(Mobject): CONFIG = { "shader_folder": "newton_fractal", "shader_dtype": [ ('point', np.float32, (3,)), ], "colors": ROOT_COLORS_DEEP, "coefs": [1.0, -1.0, 1.0, 0.0, 0.0, 1.0], "scale_factor": 1.0, "offset": ORIGIN, "n_steps": 30, "julia_highlight": 0.0, "max_degree": 5, "saturation_factor": 0.0, "opacity": 1.0, "black_for_cycles": False, "is_parameter_space": False, } def __init__(self, plane, **kwargs): super().__init__( scale_factor=plane.get_x_unit_size(), offset=plane.n2p(0), **kwargs, ) self.replace(plane, stretch=True) def init_data(self): self.set_points([UL, DL, UR, DR]) def init_uniforms(self): super().init_uniforms() self.set_colors(self.colors) self.set_julia_highlight(self.julia_highlight) self.set_coefs(self.coefs) self.set_scale(self.scale_factor) self.set_offset(self.offset) self.set_n_steps(self.n_steps) self.set_saturation_factor(self.saturation_factor) self.set_opacity(self.opacity) self.uniforms["black_for_cycles"] = float(self.black_for_cycles) self.uniforms["is_parameter_space"] = float(self.is_parameter_space) def set_colors(self, colors): self.uniforms.update({ f"color{n}": np.array(color_to_rgba(color)) for n, color in enumerate(colors) }) return self def set_julia_highlight(self, value): self.uniforms["julia_highlight"] = value def set_coefs(self, coefs, reset_roots=True): full_coefs = [*coefs] + [0] * (self.max_degree - len(coefs) + 1) self.uniforms.update({ f"coef{n}": np.array([coef.real, coef.imag], dtype=np.float64) for n, coef in enumerate(map(complex, full_coefs)) }) if reset_roots: self.set_roots(coefficients_to_roots(coefs), False) self.coefs = coefs return self def set_roots(self, roots, reset_coefs=True): self.uniforms["n_roots"] = float(len(roots)) full_roots = [*roots] + [0] * (self.max_degree - len(roots)) self.uniforms.update({ f"root{n}": np.array([root.real, root.imag], dtype=np.float64) for n, root in enumerate(map(complex, full_roots)) }) if reset_coefs: self.set_coefs(roots_to_coefficients(roots), False) self.roots = roots return self def set_scale(self, scale_factor): self.uniforms["scale_factor"] = scale_factor return self def set_offset(self, offset): self.uniforms["offset"] = np.array(offset) return self def set_n_steps(self, n_steps): self.uniforms["n_steps"] = float(n_steps) return self def set_saturation_factor(self, saturation_factor): self.uniforms["saturation_factor"] = float(saturation_factor) return self def set_opacities(self, *opacities): for n, opacity in enumerate(opacities): self.uniforms[f"color{n}"][3] = opacity return self def set_opacity(self, opacity, recurse=True): self.set_opacities(*len(self.roots) * [opacity]) return self class MetaNewtonFractal(NewtonFractal): CONFIG = { "coefs": [-1.0, 0.0, 0.0, 1.0], "colors": [*ROOT_COLORS_DEEP[::2], BLACK, BLACK], "fixed_roots": [-1, 1], "n_roots": 3, "black_for_cycles": True, "is_parameter_space": True, "n_steps": 300, } def init_uniforms(self): super().init_uniforms() self.set_fixed_roots(self.fixed_roots) def set_fixed_roots(self, roots): super().set_roots(roots, reset_coefs=False) self.uniforms["n_roots"] = 3.0 # Scenes class AmbientRootFinding(Scene): def construct(self): pass class PragmaticOrigins(Scene): title = "Pragmatic origins" include_pi = False def construct(self): # Title title = Text(self.title, font_size=72) title.set_stroke(BLACK, 5, background=True) title.to_edge(UP, buff=MED_SMALL_BUFF) underline = Underline(title, buff=-0.05) underline.insert_n_curves(30) underline.set_stroke(BLUE, width=[0, 3, 3, 3, 0]) underline.scale(1.5) # Axes axes = NumberPlane( x_range=(-3, 3), y_range=(-4, 4), width=6, height=8, background_line_style={ "stroke_color": GREY_A, "stroke_width": 1, } ) axes.set_height(5.0) axes.to_corner(DL) axes.shift(0.5 * UP) coefs = np.array([2, -3, 1, -2, -1, 1], dtype=np.float) roots = [ r.real for r in coefficients_to_roots(coefs) if abs(r.imag) < 1e-2 ] roots.sort() coefs *= 0.2 solve = OldTexText("Solve $f(x) = 0$", font_size=36) solve.next_to(axes, UP, aligned_edge=LEFT) expr = OldTex("f(x) = x^5 - x^4 - 2x^3 + x^2 -3x + 2") expr.match_width(axes) expr.next_to(axes, DOWN) graph_x_range = (-2, 2.4) graph = axes.get_graph( lambda x: poly(x, coefs), x_range=graph_x_range ) graph.set_stroke(BLUE, [0, *50 * [4], 0]) root_dots = VGroup(*( glow_dot(axes.c2p(root, 0)) for root in roots )) root_eqs = VGroup() root_groups = VGroup() for i, root, dot in zip(it.count(1), roots, root_dots): lhs = OldTex(f"x_{i} = ") rhs = DecimalNumber(root, num_decimal_places=3) rhs.set_color(YELLOW) eq = VGroup(lhs, rhs) eq.arrange(RIGHT, aligned_edge=DOWN) rhs.align_to(lhs.family_members_with_points()[0], DOWN) root_eqs.add(eq) root_groups.add(VGroup(eq, dot)) root_eqs.arrange(RIGHT, buff=LARGE_BUFF) root_eqs.next_to(axes, RIGHT, aligned_edge=UP) self.add(axes) self.add(solve) self.add(expr) # Pi if self.include_pi: morty = Mortimer(height=2) morty.to_corner(DR) self.play(PiCreatureSays( morty, "How do you\nfind theses?", target_mode="tease", bubble_config={ "width": 4, "height": 2.5, } )) # Animations self.add(underline, title) self.play( ShowCreation(underline), ) self.wait() alphas = [inverse_interpolate(*graph_x_range, root) for root in roots] self.play( ShowCreation(graph, rate_func=linear), *( FadeIn( rg, rate_func=squish_rate_func(rush_from, a, min(a + 0.2, 1)) ) for rg, a in zip(root_groups, alphas) ), run_time=4, ) self.wait() class SeekingRoots(PragmaticOrigins): title = "Seeking roots" include_pi = True class AskAboutComplexity(Scene): def construct(self): self.add(FullScreenRectangle()) question = Text("What does this complexity reflect?") question.set_width(FRAME_WIDTH - 2) question.to_edge(UP) self.add(question) screen = ScreenRectangle() screen.set_height(6.0) screen.set_fill(BLACK, 1) screen.next_to(question, DOWN) self.add(screen) class WhoCares(TeacherStudentsScene): def construct(self): self.students.refresh_triangulation() screen = self.screen screen.set_height(4, about_edge=UL) screen.set_fill(BLACK, 1) image = ImageMobject("RealNewtonStill") image.replace(screen) self.add(screen) self.add(image) self.wait() self.play(LaggedStart( PiCreatureSays( self.students[1], "Ooh, quintics...", target_mode="thinking", look_at=self.screen, bubble_config={ "direction": LEFT, "width": 4, "height": 2, } ), self.teacher.change("happy"), self.students[0].change("thinking", screen), self.students[2].change("sassy", screen), lag_ratio=0.1, )) self.wait(3) self.play(LaggedStart( PiCreatureSays( self.students[2], "Who cares?", target_mode="tired", bubble_config={ "direction": LEFT, "width": 4, "height": 3, } ), self.teacher.change("guilty"), self.students[0].change("confused", screen), RemovePiCreatureBubble( self.students[1], look_at=self.students[2].eyes, target_mode="erm", ), lag_ratio=0.1, )) self.wait(2) self.teacher_says( "Who doesn't", target_mode="hooray", bubble_config={"height": 3, "width": 4}, added_anims=[self.change_students("pondering", "pondering", "confused")] ) self.wait(3) class SphereExample(Scene): def construct(self): # Shape axes = ThreeDAxes(z_range=(-4, 4)) axes.shift(IN) sphere = Sphere(radius=1.0) # sphere = TexturedSurface(sphere, "EarthTextureMap", "NightEarthTextureMap") sphere.move_to(axes.c2p(0, 0, 0)) sphere.set_gloss(1.0) sphere.set_opacity(0.5) sphere.sort_faces_back_to_front(DOWN) mesh = SurfaceMesh(sphere, resolution=(21, 11)) mesh.set_stroke(BLUE, 0.5, 0.5) sphere = Group(sphere, mesh) frame = self.camera.frame frame.reorient(20, 80) frame.move_to(2 * RIGHT) light = self.camera.light_source self.add(axes) self.add(sphere) frame.add_updater( lambda m, dt: m.increment_theta(1 * dt * DEGREES) ) # Expression equation = OldTex( "1.00", "\\,x^2", "+", "1.00", "\\,y^2", "+", "1.00", "\\,z^2", "=", "1.00", ) decimals = VGroup() for i in range(0, len(equation), 3): decimal = DecimalNumber(1.0, edge_to_fix=RIGHT) decimal.replace(equation[i]) equation.replace_submobject(i, decimal) decimals.add(decimal) decimal.add_updater(lambda m: m.fix_in_frame()) equation.fix_in_frame() equation.to_corner(UR) self.add(equation) # Animations light.move_to([-10, -10, 20]) self.wait() self.play( ChangeDecimalToValue(decimals[3], 9.0), VFadeInThenOut(SurroundingRectangle(decimals[3]).fix_in_frame()), sphere.animate.scale(3), run_time=3 ) self.wait() self.play( ChangeDecimalToValue(decimals[2], 4.0), VFadeInThenOut(SurroundingRectangle(decimals[2]).fix_in_frame()), sphere.animate.stretch(0.5, 2), run_time=3 ) self.wait() self.play( ChangeDecimalToValue(decimals[0], 9.0), VFadeInThenOut(SurroundingRectangle(decimals[0]).fix_in_frame()), sphere.animate.stretch(1 / 3, 0), run_time=3 ) self.wait(10) class ExamplePixels(Scene): def construct(self): pixels = Square().get_grid(5, 5, buff=0) pixels.set_height(2) pixels.to_corner(UL) pixels.set_stroke(WHITE, 1) pixels.set_fill(BLACK, 1) self.add(pixels) y, x = 1066, 1360 endpoint = np.array([x, -y, 0], dtype=np.float) endpoint *= FRAME_HEIGHT / 2160 endpoint += np.array([-FRAME_WIDTH / 2, FRAME_HEIGHT / 2, 0]) lines = VGroup( Line(pixels.get_corner(UR), endpoint), Line(pixels.get_corner(DL), endpoint), ) lines.set_stroke(WHITE, 2) self.add(lines) def match_values(pixels, values): for pixel, value in zip(pixels, it.chain(*values)): value = value[::-1] pixel.set_fill(rgb_to_color(value / 255)) values = np.load( os.path.join(get_directories()["data"], "sphere_pixel_values.npy") ) match_values(pixels, values[0]) # for value in values[60::60]: for value in values[1:]: # pixels.generate_target() # match_values(pixels.target, value) # self.play(MoveToTarget(pixels)) match_values(pixels, value) self.wait(1 / 60) class CurvesDefiningFonts(Scene): def construct(self): # Setup frame = self.camera.frame chars = OldTexText("When a computer\\\\renders text...")[0] chars.set_width(FRAME_WIDTH - 3) chars.refresh_triangulation() filled_chars = chars.copy() filled_chars.insert_n_curves(50) chars.set_stroke(WHITE, 0.5) chars.set_fill(opacity=0.0) dot_groups = VGroup() line_groups = VGroup() for char in chars: dots = VGroup() lines = VGroup() for a1, h, a2 in char.get_bezier_tuples(): for pair in (a1, h), (h, a2): lines.add(Line( *pair, stroke_width=0.25, # dash_length=0.0025, stroke_color=YELLOW, )) for point in (a1, h, a2): dots.add(Dot(point, radius=0.005)) dot_groups.add(dots) line_groups.add(lines) dot_groups.set_fill(BLUE, opacity=0) self.play(ShowIncreasingSubsets(filled_chars, run_time=1, rate_func=linear)) self.wait() # Zoom in on one letter char_index = 2 char = chars[char_index] lines = line_groups[char_index] dots = dot_groups[char_index] char.refresh_bounding_box() frame.generate_target() frame.target.set_height(char.get_height() * 2) frame.target.move_to(char.get_bottom(), DOWN) frame.target.shift(0.1 * char.get_height() * DOWN) self.play( MoveToTarget(frame), filled_chars.animate.set_opacity(0.2), FadeIn(chars), ShowCreation(line_groups, rate_func=linear), dot_groups.animate.set_opacity(1), run_time=5, ) for group in (line_groups, dot_groups): group.remove(*group[0:char_index - 1]) group.remove(*group[char_index + 2:]) self.wait() # Pull out one curve char.become(CurvesAsSubmobjects(char)) index = 26 curve = char[index] sublines = lines[2 * index:2 * index + 2] subdots = dots[3 * index:3 * index + 3] curve_group = VGroup(curve, sublines, subdots) curve_group.set_stroke(background=True) curve_group.generate_target() curve_group.save_state() curve_group.target.scale(3) curve_group.target.next_to(frame.get_top(), DOWN, buff=0.15) curve_group.target.shift(0.3 * LEFT) for dot in curve_group.target[2]: dot.scale(1 / 2) labels = VGroup(*( OldTex(f"P_{i}").set_height(0.05) for i in range(3) )) for label, dot, vect in zip(labels, curve_group.target[2], [LEFT, UP, UP]): label.insert_n_curves(20) label.next_to(dot, vect, buff=0.025) label.match_color(dot) self.play( MoveToTarget(curve_group), *( GrowFromPoint(label, curve_group.get_center()) for label in labels ) ) equation = OldTex( "(1-t)^{2} P_0 +2(1-t)t P_1 +t^2 P_2", tex_to_color_map={ "P_0": BLUE, "P_1": BLUE, "P_2": BLUE, } ) equation.set_height(0.07) equation.next_to(curve_group, RIGHT, buff=0.25) equation.insert_n_curves(20) poly_label = Text("Polynomial") poly_label.insert_n_curves(20) poly_label.set_width(2) poly_label.apply_function( lambda p: [ p[0], p[1] - 0.2 * p[0]**2, p[2], ] ) poly_label.rotate(30 * DEGREES) poly_label.match_height(curve_group) poly_label.scale(0.8) poly_label.move_to(curve, DR) poly_label.shift(0.01 * UL) self.play( ShowCreationThenDestruction(curve.copy().set_color(PINK), run_time=2), Write(poly_label, stroke_width=0.5) ) self.play( LaggedStart(*( TransformFromCopy( labels[i], equation.get_part_by_tex(f"P_{i}").copy(), remover=True ) for i in range(3) )), FadeIn(equation, rate_func=squish_rate_func(smooth, 0.5, 1)), run_time=2, ) self.wait() self.add(curve_group.copy()) self.play(Restore(curve_group)) self.wait() class PlayingInFigma(ExternallyAnimatedScene): pass class RasterizingBezier(Scene): def construct(self): # Add curve and pixels self.add(FullScreenRectangle()) curve = SVGMobject("bezier_example")[0] curve.set_width(FRAME_WIDTH - 3) curve.set_stroke(WHITE, width=1.0) curve.set_fill(opacity=0) curve.to_edge(DOWN, buff=1) curve.insert_n_curves(10) # To better uniformize it thick_curve = curve.copy() thick_curve.set_stroke(YELLOW, 30.0) thick_curve.reverse_points() pixels = Square().get_grid(90 // 2, 160 // 2, buff=0, fill_rows_first=False) pixels.set_height(FRAME_HEIGHT) pixels.set_stroke(WHITE, width=0.25) # I fully recognize the irony is implementing this without # solving polynomials, but I'm happy to be inificient on runtime # to just code up the quickest thing I can think of. samples = np.array([curve.pfp(x) for x in np.linspace(0, 1, 100)]) sw_tracker = ValueTracker(0.15) get_sw = sw_tracker.get_value for pixel in pixels: diffs = samples - pixel.get_center() dists = np.apply_along_axis(lambda p: np.dot(p, p), 1, diffs) index = np.argmin(dists) if index == 0 or index == len(samples) - 1: pixel.dist = np.infty else: pixel.dist = dists[index] def update_pixels(pixels): for pixel in pixels: pixel.set_fill( YELLOW, 0.5 * clip(10 * (get_sw() - pixel.dist), 0, 1) ) update_pixels(pixels) fake_pixels = pixels.copy() fake_pixels.set_stroke(width=0) fake_pixels.set_fill(GREY_E, 1) self.add(thick_curve) self.wait() self.add(fake_pixels, pixels) self.play( FadeIn(fake_pixels), ShowCreation(pixels), lag_ratio=10 / len(pixels), run_time=4 ) self.remove(thick_curve) self.wait() # Pixel pixel = pixels[725].deepcopy() pixel.set_fill(opacity=0) label = OldTexText("Pixel $\\vec{\\textbf{p}}$") label.refresh_triangulation() label.set_fill(YELLOW) label.set_stroke(BLACK, 4, background=True) label.next_to(pixel, UL, buff=LARGE_BUFF) label.shift_onto_screen() arrow = Arrow(label, pixel, buff=0.1, stroke_width=3.0) arrow.set_color(YELLOW) self.play( FadeIn(label), ShowCreation(arrow), pixel.animate.set_stroke(YELLOW, 2.0), ) pixels.add_updater(update_pixels) self.play(sw_tracker.animate.set_value(2.0), run_time=2) self.play(sw_tracker.animate.set_value(0.2), run_time=2) pixels.suspend_updating() self.play(ShowCreation(curve)) # Show P(t) value ct = VGroup(OldTex("\\vec{\\textbf{c}}(")[0], DecimalNumber(0), OldTex(")")[0]) ct.arrange(RIGHT, buff=0) ct.add_updater(lambda m: m.set_stroke(BLACK, 4, background=True)) t_tracker = ValueTracker(0) get_t = t_tracker.get_value P_dot = Dot(color=GREEN) globals().update(locals()) ct[1].add_updater(lambda m: m.set_value(get_t())) ct[1].next_to(ct[0], RIGHT, buff=0) P_dot.add_updater(lambda m: m.move_to(curve.pfp(get_t() / 2))) ct.add_updater(lambda m: m.move_to(P_dot).shift( (0.3 - 0.5 * get_t() * (1 - get_t())) * rotate_vector(np.array([-3, 1, 0]), -0.8 * get_t() * PI) )) curve_copy = curve.copy() curve_copy.pointwise_become_partial(curve, 0, 0.5) curve_copy.set_points(curve_copy.get_points_without_null_curves()) curve_copy.set_stroke(YELLOW, 3.0) self.play( VFadeIn(ct), ApplyMethod(t_tracker.set_value, 1.0, run_time=3), ShowCreation(curve_copy, run_time=3), VFadeIn(P_dot), ) new_ct = OldTex("\\vec{\\textbf{c}}(", "t", ")") new_ct.move_to(ct, LEFT) new_ct.set_stroke(BLACK, 4, background=True) self.play(FadeTransformPieces(ct, new_ct)) ct = new_ct self.wait() # Show distance graph_group = self.get_corner_graph_group(pixel, curve) bg_rect, axes, y_label, graph = graph_group t_tracker = ValueTracker(0) dist_line = Line() dist_line.set_stroke(TEAL, 5) dist_line.add_updater(lambda l: l.put_start_and_end_on( pixel.get_center(), curve_copy.pfp(t_tracker.get_value()) )) dist_lines = VGroup() graph_v_lines = VGroup() for t in np.linspace(0, 1, 20): t_tracker.set_value(t) dist_lines.add(dist_line.update().copy().clear_updaters()) graph_v_lines.add(axes.get_v_line( axes.input_to_graph_point(t, graph) )) dist_lines.set_stroke(RED, 1, opacity=1.0) graph_v_lines.set_stroke(RED, 1, opacity=1.0) t_tracker.set_value(0) self.play( *map(FadeIn, graph_group[:-1]), ) self.play( FadeIn(dist_lines, lag_ratio=1), FadeIn(graph_v_lines, lag_ratio=1), run_time=4 ) self.wait() t_tracker.set_value(0.0) self.play( VFadeIn(dist_line, rate_func=squish_rate_func(smooth, 0, 0.25)), ApplyMethod(t_tracker.set_value, 1.0), ShowCreation(graph), run_time=3, ) self.play(dist_line.animate.set_stroke(RED, 1.0)) self.wait() # Show width again pixels.resume_updating() self.play(sw_tracker.animate.set_value(1.5), run_time=2) self.play(sw_tracker.animate.set_value(0.5), run_time=1) pixels.suspend_updating() self.wait() # Show derivative deriv_graph_group = self.get_deriv_graph_group(graph_group) d_graph = deriv_graph_group[-1] d_graph.set_points_smoothly([d_graph.pfp(x) for x in np.linspace(0, 1, 20)]) deriv_axes = deriv_graph_group[1] t_tracker = ValueTracker(0) get_t = t_tracker.get_value tan_line = always_redraw( lambda: axes.get_tangent_line( get_t(), graph, length=3, ).set_stroke( color=MAROON_B, width=1.0, opacity=clip(20 * get_t() * (1 - get_t()), 0, 1) ) ) self.play(*map(FadeIn, deriv_graph_group[:-1])) self.add(tan_line) self.play( t_tracker.animate.set_value(1), ShowCreation(d_graph), run_time=4 ) self.remove(tan_line) self.wait() points = graph.get_points() min_point = points[np.argmin([p[1] for p in points])] min_line = Line(min_point, [min_point[0], deriv_axes.c2p(0, 0)[1], 0]) min_line.set_stroke(WHITE, 1) question = Text("What is\nthis value?", font_size=30) question.to_corner(DR) arrow = Arrow( question.get_left(), min_line.get_bottom(), stroke_width=3, buff=0.1 ) self.play(ShowCreation(min_line)) self.play( Write(question), ShowCreation(arrow), ) self.wait() def get_corner_graph_group(self, pixel, curve, t_range=(0, 0.5)): axes = Axes( x_range=(0, 1, 0.2), y_range=(0, 20, 5), height=3, width=5, axis_config={"include_tip": False} ) axes.to_corner(UR, buff=SMALL_BUFF) y_label = OldTex( "&\\text{Distance}^2\\\\", "&||\\vec{\\textbf{p}} - \\vec{\\textbf{c}}(t)||^2", font_size=24, ) # For future transition y_label = VGroup(VectorizedPoint(y_label.get_left()), *y_label) y_label.next_to(axes.y_axis.get_top(), RIGHT, aligned_edge=UP) y_label.shift_onto_screen(buff=MED_SMALL_BUFF) graph = axes.get_graph(lambda t: get_norm( pixel.get_center() - curve.pfp(interpolate(*t_range, t)) )**2) graph.set_stroke(RED, 2) bg_rect = BackgroundRectangle(axes, buff=SMALL_BUFF) result = VGroup(bg_rect, axes, y_label, graph) return result def get_deriv_graph_group(self, graph_group): top_bg_rect, top_axes, top_y_label, top_graph = graph_group axes = Axes( x_range=top_axes.x_range, y_range=(-60, 60, 10), height=top_axes.get_height(), width=top_axes.get_width(), axis_config={"include_tip": False} ) axes.to_corner(DR, buff=SMALL_BUFF) axes.shift((top_axes.c2p(0, 0) - axes.c2p(0, 0))[0] * RIGHT) dt = 1e-5 f = top_graph.underlying_function globals().update(locals()) graph = axes.get_graph(lambda t: (f(t + dt) - f(t)) / dt) graph.set_stroke(MAROON_B) # Dumb hack, not sure why it's needed graph.get_points()[:133] += 0.015 * UP y_label = VGroup(OldTex("\\frac{d}{dt}", font_size=24), top_y_label[2].copy()) y_label.arrange(RIGHT, buff=0.05) y_label.next_to(axes.y_axis.get_top(), RIGHT, buff=2 * SMALL_BUFF) bg_rect = BackgroundRectangle(VGroup(axes, graph), buff=SMALL_BUFF) bg_rect.stretch(1.05, 1, about_edge=DOWN) result = VGroup(bg_rect, axes, y_label, graph) return result class WriteThisIsPolynomial(Scene): def construct(self): text = OldTexText("(Some polynomial in $t$)", font_size=24) self.play(Write(text)) self.wait() class DontWorryAboutDetails(TeacherStudentsScene): CONFIG = { "background_color": BLACK, } def construct(self): screen = self.screen screen.set_height(4, about_edge=UL) screen.set_fill(BLACK, 1) image1, image2 = [ ImageMobject(f"RasterizingBezier_{i}").replace(screen) for i in range(1, 3) ] frame = self.camera.frame frame.save_state() frame.replace(image1) self.add(screen, image1) self.play(Restore(frame)) # Student asks about what the function is. self.student_says( OldTexText("Wait, what is that\\\\function exactly?"), look_at=image1, index=2, added_anims=[ self.students[0].change("confused", image1), self.students[1].change("confused", image1), ] ) self.play(self.teacher.change("tease")) self.wait(2) self.play( self.students[0].change("maybe", image1), ) self.play( self.students[1].change("erm", image1), ) self.wait(3) self.teacher_says( OldTexText("Just some\\\\polynomial"), bubble_config={ "width": 4, "height": 3, }, added_anims=[self.change_students("confused", "maybe", "pondering")] ) self.wait() self.look_at(image1) self.play( frame.animate.replace(image1), RemovePiCreatureBubble(self.teacher), run_time=2 ) self.wait() # Image 2 self.remove(image1) self.add(image2) self.play(Restore(frame)) self.play_all_student_changes( "confused", look_at=image1, ) self.teacher_says( OldTex("P(x) = 0"), target_mode="tease", bubble_config={ "width": 3, "height": 3, } ) self.wait(4) self.play( RemovePiCreatureBubble(self.teacher, target_mode="raise_right_hand", look_at=image1), self.change_students( *3 * ["pondering"], look_at=image1, ), FadeOut(image2), ) self.wait(4) class ShowManyGraphs(Scene): def construct(self): # Add plots root_groups = [ (-2, 6), (-5, 0, 3), (-7, -2, 3, 8), (-5, 1, 5, complex(0, 1), complex(0, -1)), ] coef_groups = list(map(roots_to_coefficients, root_groups)) scalars = [0.5, 0.2, 0.01, -0.01] colors = [BLUE_C, BLUE_D, BLUE_B, RED] plots = Group(*( self.get_plot(coefs, scalar, color) for coefs, scalar, color in zip(coef_groups, scalars, colors) )) plots.arrange_in_grid(v_buff=0.5) axes, graphs, root_dots = [ Group(*(plot[i] for plot in plots)) for i in range(3) ] self.play( LaggedStartMap(FadeIn, axes, lag_ratio=0.3), LaggedStartMap(ShowCreation, graphs, lag_ratio=0.3), run_time=3, ) self.play( LaggedStart(*( FadeIn(dot, scale=0.1) for dot in it.chain(*root_dots) ), lag_ratio=0.1) ) self.add(plots) self.wait() quadratic, cubic, quartic, quintic = plots for plot in plots: plot.save_state() # Show quadratic kw = {"tex_to_color_map": { "{a}": BLUE_B, "{b}": BLUE_C, "{c}": BLUE_D, "{d}": TEAL_E, "{e}": TEAL_D, "{f}": TEAL_C, "{p}": BLUE_B, "{q}": BLUE_C, "\\text{root}": YELLOW, "r_1": YELLOW, "r_2": YELLOW, "+": WHITE, "-": WHITE, }} quadratic.generate_target() quadratic.target.set_height(6) quadratic.target.center().to_edge(LEFT) equation = OldTex("{a}x^2 + {b}x + {c} = 0", **kw) equation.next_to(quadratic.target, UP) form = OldTex( "r_1, r_2 = {-{b} \\pm \\sqrt{\\,{b}^2 - 4{a}{c}} \\over 2{a}}", **kw ) form.next_to(quadratic.target, RIGHT, buff=MED_LARGE_BUFF) form_name = Text("Quadratic formula") form_name.match_width(form) form_name.next_to(form, UP, LARGE_BUFF) randy = Randolph(height=2) randy.flip() randy.next_to(form, RIGHT) randy.align_to(quadratic.target, DOWN) randy.shift_onto_screen() self.play( MoveToTarget(quadratic), Write(equation), *map(FadeOut, plots[1:]), FadeIn(randy), ) self.play(randy.change("hooray")) self.play( TransformMatchingShapes( VGroup(*( equation.get_part_by_tex(f"{{{c}}}") for c in "abc" )).copy(), form, lag_ratio=0, run_time=2, ), randy.animate.look_at(form), FadeIn(form_name), FlashAround(form_name), ) self.play(Blink(randy)) self.wait() # Coco sidenote form_group = VGroup(form_name, form) form_group.save_state() form_group.set_stroke(BLACK, 5, background=True) plot_group = Group(quadratic, equation) plot_group.save_state() self.play( plot_group.animate.shift(4 * LEFT).set_opacity(0), form_group.animate.to_corner(UR), FadeOut(randy), ) pixar_image = ImageMobject("PixarCampus") pixar_image.set_height(FRAME_HEIGHT + 4) pixar_image.to_corner(UL, buff=0) pixar_image.shift(LEFT) pixar_image.add_updater(lambda m, dt: m.shift(0.1 * dt * LEFT)) coco_logo = ImageMobject("Coco_logo") coco_logo.set_width(4) coco_logo.match_y(form) coco_logo.to_edge(RIGHT, buff=LARGE_BUFF) arrow = Arrow(form.copy().to_edge(LEFT), coco_logo, buff=0.3, stroke_width=10) self.add(pixar_image, *self.mobjects) self.play(FadeIn(pixar_image)) self.wait(6) self.add(coco_logo, *self.mobjects) self.play( FadeOut(pixar_image), form_group.animate.to_corner(UL), FadeIn(randy), ShowCreation(arrow), FadeIn(coco_logo), ) over_trillion = OldTex("> 1{,}000{,}000{,}000{,}000")[0] over_trillion.next_to(form, RIGHT) over_trillion.shift(3 * DOWN) form_copies = form[4:].replicate(50) self.play( ShowIncreasingSubsets(over_trillion, run_time=1), randy.change("thinking", over_trillion), LaggedStart(*( FadeOut(form_copy, 4 * DOWN) for form_copy in form_copies ), lag_ratio=0.15, run_time=5) ) self.play( FadeOut(over_trillion), FadeOut(coco_logo), FadeOut(arrow), randy.change("happy"), Restore(form_group), Restore(plot_group), ) self.embed() # Cubic low_fade_rect = BackgroundRectangle( Group(quartic, quintic), buff=0.01, fill_opacity=0.95, ) cubic_eq = OldTex("x^3 + {p}x + {q} = 0", **kw) cubic_eq.next_to(cubic, LEFT, LARGE_BUFF, aligned_edge=UP) cubic_eq.shift_onto_screen() cubic_name = OldTexText("Cubic\\\\", "Formula") cubic_name.to_corner(UL) cubic_form = OldTex( "\\text{root}", "=", "\\sqrt[3]{\\,-{{q} \\over 2} + \\sqrt{\\, {{q}^2 \\over 4} + {{p}^3 \\over 27}} }+", "\\sqrt[3]{\\,-{{q} \\over 2} - \\sqrt{\\, {{q}^2 \\over 4} + {{p}^3 \\over 27}} }", **kw, ) cubic_form.set_width(7) cubic_form.next_to(cubic_eq, DOWN, buff=1.25) cubic_form.to_edge(LEFT) cubic_arrow = Arrow( cubic_eq, cubic_form, stroke_width=5, buff=0.1, ) self.add(*plots, randy) self.play( Restore(quadratic), *map(FadeIn, plots[1:]), FadeOut(form), FadeOut(form_name), FadeOut(equation), randy.change("plain"), ) self.play(randy.change("erm", cubic)) self.wait() self.play( FadeOut(quadratic), FadeIn(low_fade_rect), Write(cubic_eq), FadeIn(cubic_name), ) self.play( ShowCreation(cubic_arrow), FadeIn(cubic_form, DOWN), randy.change("confused", cubic_name), ) self.play(Blink(randy)) # Quartic quartic_name = OldTexText("Quartic ", "Formula") quartic_name.move_to(quartic).to_edge(UP) cubic_fade_rect = BackgroundRectangle(cubic, buff=0.01, fill_opacity=0.95) quartic_eq = OldTex("{a}x^4 + {b}x^3 + {c}x^2 + {d}x + {e} = 0", **kw) quartic_eq.next_to(quartic, UP) main_form = OldTex(r"r_{i}&=-\frac{b}{4 a}-S \pm \frac{1}{2} \sqrt{-4 S^{2}-2 p \pm \frac{q}{S}}") details = OldTex(r""" &\text{Where}\\\\ p&=\frac{8 a c-3 b^{2}}{8 a^{2}} \qquad \qquad\\\\ q&=\frac{b^{3}-4 a b c+8 a^{2} d}{8 a^{3}}\\\\ S&=\frac{1}{2} \sqrt{-\frac{2}{3} p+\frac{1}{3 a}\left(Q+\frac{\Delta_{0}}{Q}\right)}\\\\ Q&=\sqrt[3]{\frac{\Delta_{1}+\sqrt{\Delta_{1}^{2}-4 \Delta_{0}^{3}}}{2}}\\\\ \Delta_{0}&=c^{2}-3 b d+12 a e\\\\ \Delta_{1}&=2 c^{3}-9 b c d+27 b^{2} e+27 a d^{2}-72 a c e\\\\ """) main_form.match_width(quartic_eq) main_form.move_to(VGroup(quartic_name, quartic_eq)) details.scale(0.5) details.to_corner(UR) details.set_stroke(BLACK, 3, background=True) self.play( FadeOut(cubic_eq), FadeOut(cubic_form), FadeOut(cubic_arrow), FadeIn(cubic_fade_rect), FadeTransform(cubic_name[0], quartic_name[0]), FadeTransform(cubic_name[1], quartic_name[1]), randy.change("erm", quartic_name), low_fade_rect.animate.replace(quintic, stretch=True).scale(1.01), FadeIn(quartic_eq), ) self.play(Write(main_form)) self.wait() self.play( randy.change("horrified", details), Write(details, run_time=5) ) self.play(randy.animate.look_at(details.get_bottom())) self.play(Blink(randy)) self.wait() # Quintic quintic.generate_target() quintic.target.set_height(5) quintic.target.to_corner(UL).shift(DOWN) quintic_eq = OldTex( "{a}x^5 + {b}x^4 + {c}x^3 + {d}x^2 + {e}x + {f}", **kw ) quintic_eq.match_width(quintic.target) quintic_eq.next_to(quintic.target, UP) quintic_name = Text("Quintic formula?", font_size=60) quintic_name.move_to(3 * RIGHT) quintic_name.to_edge(UP) subwords = VGroup( OldTexText("There is none.", "$^*$"), OldTexText("And there never can be."), ) subwords.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) subwords.next_to(quintic_name, DOWN, LARGE_BUFF, aligned_edge=LEFT) footnote = OldTex( "^*\\text{Using }", "+,\\,", "-,\\,", "\\times,\\,", "/,\\,", "\\sqrt[n]{\\quad},\\,", "\\text{exp},\\,", "\\log,\\,", "\\sin,\\,", "\\cos,\\,", "etc.\\\\", font_size=36, alignment="", ) footnote.set_color(GREY_A) footnote.next_to(subwords, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) footnote.shift_onto_screen(buff=MED_SMALL_BUFF) self.play( FadeOut(cubic), FadeOut(quartic), FadeOut(quartic_eq), FadeOut(main_form), FadeOut(details), FadeTransform(quartic_name, quintic_name), MoveToTarget(quintic), UpdateFromFunc( low_fade_rect, lambda m: m.replace(quintic, stretch=True), ), VFadeOut(low_fade_rect), randy.change("tease", quintic_name), FadeIn(quintic_eq), ) self.play(Blink(randy)) self.wait() self.play( FadeIn(subwords[0][0], 0.5 * DOWN), randy.change("erm", subwords), ) self.wait() self.play(FadeIn(subwords[1], 0.5 * DOWN)) self.wait() self.play( FadeIn(subwords[0][1]), LaggedStartMap(FadeIn, footnote, run_time=6, lag_ratio=0.5), randy.change("pondering", footnote) ) self.play(Blink(randy)) self.wait() def get_plot(self, coefs, scalar=1.0, color=YELLOW, stroke_width=3, height=3.5, bound=10): axes = NumberPlane( (-bound, bound, 5), (-bound, bound, 5), faded_line_ratio=4, background_line_style={ "stroke_width": 1.0, "stroke_color": GREY_A, } ) axes.set_height(height) axes.add_coordinate_labels( x_values=[-5, 0, 5, 10], y_values=[-5, 5, 10], font_size=16, excluding=[], ) def f(x): return scalar * poly(x, coefs) x_min = binary_search( lambda x: abs(f(x)), bound, -bound, 0 ) x_max = binary_search( lambda x: abs(f(x)), bound, 0, bound, ) graph = axes.get_graph(f, x_range=(x_min, x_max)) graph.set_stroke(color, stroke_width) roots = [ root.real for root in coefficients_to_roots(coefs) if np.isclose(root.imag, 0) ] def get_glow_dot(point): result = DotCloud([point] * 10) result.set_radii([ interpolate(0.03, 0.06, t**2) for t in np.linspace(0, 1, 10) ]) result.set_opacity(0.2) result.set_color(YELLOW) return result root_dots = Group(*( get_glow_dot(axes.c2p(root, 0)) for root in roots )) result = Group(axes, graph, root_dots) return result class ComingVideoWrapper(VideoWrapper): animate_boundary = False title = "Unsolvability of the Quintic (future topic?)" class QuinticAppletPlay(ExternallyAnimatedScene): pass class AskAboutFractals(TeacherStudentsScene): def construct(self): self.screen.set_height(4, about_edge=UL) self.screen.set_fill(BLACK, 1) self.add(self.screen) self.student_says( "Fractals?", target_mode="raise_right_hand", index=2, added_anims=[ self.students[0].change("confused"), self.students[1].change("sassy"), ] ) self.wait() self.teacher_says( OldTexText("We're getting\\\\there"), bubble_config={ "height": 3, "width": 4, }, target_mode="happy" ) self.play_all_student_changes( "pondering", look_at=self.screen ) self.wait(2) class RealNewtonsMethod(Scene): coefs = [-0.2, -1, 1, 0, 0, 1] poly_tex = "x^5 + x^2 - x - 0.2" dpoly_tex = "5x^4 + 2x - 1" seed = 1.3 graph_x_range = (-1.5, 1.5) axes_config = { "x_range": (-2, 2, 0.2), "y_range": (-2, 6, 0.2), "height": 8, "width": 8, "axis_config": { "tick_size": 0.05, "longer_tick_multiple": 2.0, "tick_offset": 0, # Change name "numbers_with_elongated_ticks": list(range(-2, 3)), "include_tip": False, } } graph_color = BLUE_C guess_color = YELLOW rule_font_size = 42 n_search_steps = 5 def construct(self): self.add_graph() self.add_title(self.axes) self.draw_graph() self.highlight_roots() self.preview_iterative_root_finding() self.introduce_step() self.find_root() def add_graph(self): axes = self.axes = Axes(**self.axes_config) axes.to_edge(RIGHT) axes.add_coordinate_labels( np.arange(*self.axes.x_range[:2]), np.arange(self.axes.y_range[0] + 1, self.axes.y_range[1]), ) self.add(axes) graph = self.graph = axes.get_graph( lambda x: poly(x, self.coefs), x_range=self.graph_x_range, ) graph.set_color(self.graph_color) self.add(graph) def add_title(self, axes, opacity=0): title = OldTexText("Newton's method", font_size=60) title.move_to(midpoint(axes.get_left(), LEFT_SIDE)) title.to_edge(UP) title.set_opacity(opacity) poly = OldTex(f"P({self.poly_tex[0]}) = ", self.poly_tex, "= 0 ") poly.match_width(title) poly.next_to(title, DOWN, buff=MED_LARGE_BUFF) poly.set_fill(GREY_A) title.add(poly) self.title = title self.poly = poly self.add(title) def draw_graph(self): rect = SurroundingRectangle(self.poly[:-1]) rect.set_stroke(self.graph_color, 2) self.play( FlashAround(self.poly[:-1], color=self.graph_color, run_time=2), ShowCreation(rect, run_time=2), ShowCreation(self.graph, run_time=4), ) self.wait() self.play( rect.animate.replace(self.poly[-1], stretch=True).scale(1.2) ) self.wait() self.play(FadeOut(rect)) def highlight_roots(self): roots = coefficients_to_roots(self.coefs) real_roots = [ root.real for root in roots if abs(root.imag) < 1e-6 ] real_roots.sort() dots = VGroup(*( # Dot(self.axes.c2p(r, 0), radius=0.05) glow_dot(self.axes.c2p(r, 0)) for r in real_roots )) squares = VGroup(*[ Square().set_height(0.25).move_to(dot) for dot in dots ]) squares.set_stroke(YELLOW, 3) squares.set_fill(opacity=0) self.play( LaggedStart( *[ FadeIn(dot, scale=0.1) for dot in dots ] + [ VShowPassingFlash(square, time_width=2.0, run_time=2) for square in squares ], lag_ratio=0.15 ), ) self.wait() # Show values numerically root_strs = ["{0:.4}".format(root) for root in real_roots] equations = VGroup(*( OldTex( "P(", root_str, ")", "=", "0", font_size=self.rule_font_size ).set_color_by_tex(root_str, YELLOW) for root_str in root_strs )) equations.arrange(DOWN, buff=0.5, aligned_edge=LEFT) equations.next_to(self.poly, DOWN, LARGE_BUFF, aligned_edge=LEFT) question = Text("How do you\ncompute these?") question.next_to(equations, RIGHT, buff=LARGE_BUFF) question.set_color(YELLOW) arrows = VGroup(*( Arrow( question.get_corner(UL) + 0.2 * DL, eq[1].get_corner(UR) + 0.25 * LEFT, path_arc=arc, stroke_width=3, buff=0.2, ) for eq, arc in zip(equations, [0.7 * PI, 0.5 * PI, 0.0 * PI]) )) arrows.set_color(YELLOW) self.play( LaggedStartMap(FadeIn, equations, lag_ratio=0.25), LaggedStart(*( FadeTransform(dot.copy(), eq[1]) for dot, eq in zip(dots, equations) ), lag_ratio=0.25) ) self.wait() self.play( Write(question), Write(arrows) ) self.wait() self.play(LaggedStart( FadeOut(dots), FadeOut(question), FadeOut(arrows), FadeOut(equations), lag_ratio=0.25 )) self.wait() def preview_iterative_root_finding(self): axes = self.axes axis = axes.x_axis coefs = self.coefs n_steps = 5 root_seekers = VGroup(*( ArrowTip().set_height(0.2).rotate(-PI / 2).move_to(axis.n2p(x), DOWN) for x in np.arange(-2, 2.0, 0.2)[:-1] )) root_seekers.set_stroke(YELLOW, 2, opacity=0.5) root_seekers.set_fill(YELLOW, opacity=0.3) words = Text("Approximate\nSolutions", alignment="\\flushleft") words.move_to(axes.c2p(0, 3)) words.align_to(axis, LEFT) words.set_color(YELLOW) self.play( FadeIn(root_seekers, lag_ratio=0.1), Write(words), ) for n in range(n_steps): for rs in root_seekers: rs.generate_target() x = axis.p2n(rs.get_center()) if n == 0 and abs(x - 0.4) < 0.1: x = 0.6 new_x = x - poly(x, coefs) / dpoly(x, coefs) rs.target.set_x(axis.n2p(new_x)[0]) self.play(*map(MoveToTarget, root_seekers), run_time=1.0) self.wait() values = VGroup(*( DecimalNumber( axis.p2n(rs.get_center()), num_decimal_places=5, show_ellipsis=True, ).next_to(rs, UP, SMALL_BUFF) for rs in root_seekers[0::len(root_seekers) // 2] )) values.set_fill(YELLOW) values.set_stroke(BLACK, 8, background=True) last_value = VMobject() for value in values: self.play( FadeIn(value), FadeOut(last_value) ) self.wait(0.5) last_value = value self.play(FadeOut(last_value)) self.play( FadeOut(words), FadeOut(root_seekers), ) def introduce_step(self): axes = self.axes graph = self.graph # Add labels guess_label = OldTex( "\\text{Guess: } x_0 = " + f"{self.seed}", tex_to_color_map={"x_0": YELLOW} ) guess_label.next_to(self.poly, DOWN, LARGE_BUFF) guess_marker, guess_value, guess_tracker = self.get_guess_group() get_guess = guess_tracker.get_value self.play(self.title.animate.set_opacity(1)) self.wait() self.play(Write(guess_label)) self.play( FadeTransform( guess_label[1].copy(), VGroup(guess_marker, guess_value) ) ) self.wait() # Add lines v_line = axes.get_v_line(axes.i2gp(get_guess(), graph)) tan_line = self.get_tan_line(get_guess()) v_line_label = OldTex("P(x_0)", font_size=30, fill_color=GREY_A) v_line_label.next_to(v_line, RIGHT, SMALL_BUFF) self.add(v_line, guess_marker, guess_value) self.play(ShowCreation(v_line)) self.play(FadeIn(v_line_label, 0.2 * RIGHT)) self.wait() self.play( ShowCreation(tan_line), graph.animate.set_stroke(width=2), ) # Mention next guess next_guess_label = Text("Next guess", font_size=30) next_guess_label.set_color(RED) next_guess_label.next_to(axes.c2p(0, 0), RIGHT, MED_LARGE_BUFF) next_guess_label.shift(UP) next_guess_arrow = Arrow(next_guess_label, tan_line.get_start(), buff=0.1) next_guess_arrow.set_stroke(RED, 3) coord = axes.coordinate_labels[0][-1] coord_copy = coord.copy() coord.set_opacity(0) self.play( coord_copy.animate.scale(0), ShowCreation(next_guess_arrow), FadeIn(next_guess_label), ) self.wait() # Show derivative dpoly = OldTex("P'(x) = ", self.dpoly_tex) dpoly.match_height(self.poly) dpoly.match_style(self.poly) dpoly.next_to(self.poly, DOWN, aligned_edge=LEFT) self.play( FadeIn(dpoly, 0.5 * DOWN), guess_label.animate.shift(0.25 * DOWN) ) self.play(FlashAround(dpoly)) self.wait() # Show step step_arrow = Arrow(v_line.get_start(), tan_line.get_start(), buff=0) step_arrow.set_stroke(GREY_A, 3) step_arrow.shift(0.1 * UP) step_word = Text("Step", font_size=24) step_word.set_stroke(BLACK, 3, background=True) step_word.next_to(step_arrow, UP, SMALL_BUFF) self.play( ShowCreation(step_arrow), FadeIn(step_word) ) self.wait() # Show slope slope_eq_texs = [ "P'(x_0) = {P(x_0) \\over -\\text{Step}}", "\\text{Step} = -{P(x_0) \\over P'(x_0)}", ] slope_eqs = [ OldTex( tex, isolate=[ "P'(x_0)", "P(x_0)", "\\text{Step}", "-" ], font_size=self.rule_font_size, ) for tex in slope_eq_texs ] for slope_eq in slope_eqs: slope_eq.set_fill(GREY_A) slope_eq.set_color_by_tex("Step", WHITE) slope_eq.next_to(guess_label, DOWN, LARGE_BUFF) rule = self.rule = self.get_update_rule() rule.next_to(guess_label, DOWN, LARGE_BUFF) for line in [v_line, Line(tan_line.get_start(), v_line.get_start())]: self.play( VShowPassingFlash( Line(line.get_start(), line.get_end()).set_stroke(YELLOW, 10).insert_n_curves(20), time_width=1.0, run_time=1.5 ) ) self.wait() self.play( FadeTransform(v_line_label.copy(), slope_eqs[0].get_part_by_tex("P(x_0)")), FadeTransform(step_word.copy(), slope_eqs[0].get_part_by_tex("\\text{Step}")), FadeIn(slope_eqs[0][3:5]), ) self.wait() self.play(FadeIn(slope_eqs[0][:2])) self.wait() self.play(TransformMatchingTex(*slope_eqs, path_arc=PI / 2)) self.wait() self.play( FadeIn(rule), slope_eqs[1].animate.to_edge(DOWN) ) self.wait() # Transition to x1 self.add(tan_line, guess_value) self.play( FadeOut(next_guess_label), FadeOut(next_guess_arrow), FadeOut(step_word), FadeOut(step_arrow), FadeOut(v_line), FadeOut(v_line_label), guess_tracker.animate.set_value(self.get_next_guess(get_guess())), ) self.play(FadeOut(tan_line)) def find_root(self, cycle_run_time=1.0): for n in range(self.n_search_steps): self.play(*self.cycle_rule_entries_anims(), run_time=cycle_run_time) self.step_towards_root() def step_towards_root(self, fade_tan_with_vline=False, added_anims=None): guess = self.guess_tracker.get_value() next_guess = self.get_next_guess(guess) v_line = self.axes.get_v_line(self.axes.i2gp(guess, self.graph)) tan_line = self.get_tan_line(guess) self.add(v_line, tan_line, self.guess_marker, self.guess_value) self.play( ShowCreation(v_line), GrowFromCenter(tan_line) ) anims = [ FadeOut(v_line), self.guess_tracker.animate.set_value(next_guess) ] if added_anims is not None: anims += added_anims tan_fade = FadeOut(tan_line) if fade_tan_with_vline: self.play(*anims, tan_fade) else: self.play(*anims) self.play(tan_fade) # def get_guess_group(self): axes = self.axes guess_tracker = ValueTracker(self.seed) get_guess = guess_tracker.get_value guess_marker = Triangle(start_angle=PI / 2) guess_marker.set_height(0.1) guess_marker.set_width(0.1, stretch=True) guess_marker.set_fill(self.guess_color, 1) guess_marker.set_stroke(width=0) guess_marker.add_updater(lambda m: m.move_to( axes.c2p(get_guess(), 0), UP )) guess_value = DecimalNumber(0, num_decimal_places=3, font_size=24) def update_guess_value(gv): gv.set_value(get_guess()) gv.next_to(guess_marker, DOWN, SMALL_BUFF) gv.set_fill(self.guess_color) gv.set_stroke(BLACK, 3, background=True) return gv guess_value.add_updater(update_guess_value) self.guess_tracker = guess_tracker self.guess_marker = guess_marker self.guess_value = guess_value return (guess_marker, guess_value, guess_tracker) def get_next_guess(self, curr_guess): x = curr_guess return x - poly(x, self.coefs) / dpoly(x, self.coefs) def get_tan_line(self, curr_guess): next_guess = self.get_next_guess(curr_guess) start = self.axes.c2p(next_guess, 0) end = self.axes.i2gp(curr_guess, self.graph) line = Line(start, start + 2 * (end - start)) line.set_stroke(RED, 3) return line def get_update_rule(self, char="x"): rule = OldTex( """ z_1 = z_0 - {P(z_0) \\over P'(z_0)} """.replace("z", char), tex_to_color_map={ f"{char}_1": self.guess_color, f"{char}_0": self.guess_color }, font_size=self.rule_font_size, ) rule.n = 0 rule.zns = rule.get_parts_by_tex(f"{char}_0") rule.znp1 = rule.get_parts_by_tex(f"{char}_1") return rule def cycle_rule_entries_anims(self): rule = self.rule rule.n += 1 char = rule.get_tex().strip()[0] zns = VGroup() for old_zn in rule.zns: zn = OldTex(f"{char}_{{{rule.n}}}", font_size=self.rule_font_size) zn[0][1:].set_max_width(0.2, about_edge=DL) zn.move_to(old_zn) zn.match_color(old_zn) zns.add(zn) znp1 = OldTex(f"{char}_{{{rule.n + 1}}}", font_size=self.rule_font_size) znp1.move_to(rule.znp1) znp1.match_color(rule.znp1[0]) result = ( FadeOut(rule.zns), FadeTransformPieces(rule.znp1, zns), FadeIn(znp1, 0.5 * RIGHT) ) rule.zns = zns rule.znp1 = znp1 return result class FasterNewtonExample(RealNewtonsMethod): coefs = [0.1440, -1.0, 1.2, 1] poly_tex = "x^3 + 1.2x^2 - x + 0.144" dpoly_tex = "3x^2 + 2.4x - 1" n_search_steps = 6 graph_x_range = (-2, 2) seed = 1.18 axes_config = { "x_range": (-2, 2, 0.2), "y_range": (-1, 3, 0.2), "height": 8, "width": 8, "axis_config": { "tick_size": 0.05, "longer_tick_multiple": 2.0, "tick_offset": 0, # Change name "numbers_with_elongated_ticks": list(range(-2, 3)), "include_tip": False, } } def construct(self): self.add_graph() self.add_title(self.axes) self.draw_graph() self.introduce_step() self.find_root() def find_root(self, cycle_run_time=1.0): for n in range(self.n_search_steps): self.step_towards_root( added_anims=self.cycle_rule_entries_anims(), fade_tan_with_vline=True ) class AssumingItsGood(TeacherStudentsScene): def construct(self): self.pi_creatures.refresh_triangulation() self.teacher_says( OldTexText("Assuming this\\\\approximation\\\\is decent...", font_size=42), bubble_config={ "height": 3, "width": 4, } ) self.play_student_changes( "pondering", "pondering", "tease", look_at=self.screen ) self.pi_creatures.refresh_triangulation() self.wait(3) class PauseAndPonder(TeacherStudentsScene): def construct(self): self.teacher_says("Pause and\nponder", target_mode="hooray") self.play_all_student_changes("thinking", look_at=self.screen) self.wait(4) class AltPauseAndPonder(Scene): def construct(self): morty = Mortimer(height=2) morty.flip().to_corner(DL) self.play(PiCreatureSays( morty, OldTexText("Pause and\\\\Ponder", font_size=36), target_mode="hooray", bubble_config={ "height": 2, "width": 3, } )) self.play(Blink(morty)) self.wait(2) self.play(morty.change("thinking")) self.play(Blink(morty)) self.wait() class WhatIsThis(Scene): def construct(self): words = Text("What is this", color=RED) arrow = Vector(UR) arrow.set_color(RED) words.next_to(ORIGIN, DOWN) self.play(FadeIn(words, lag_ratio=0.1), ShowCreation(arrow)) self.wait() class GutCheckFormula(RealNewtonsMethod): seed = 5.0 def construct(self): self.add_axes_and_graph() self.add_rule() self.add_guess() self.sample_values() def add_axes_and_graph(self): axes = NumberPlane( (-2, 15), (-2, 8), faded_line_ratio=1, background_line_style={ "stroke_opacity": 0.5, "stroke_color": GREY, } ) axes.to_corner(DL, buff=0) axes.add_coordinate_labels(font_size=16, fill_opacity=0.5) axes.x_axis.numbers.next_to(axes.x_axis, UP, buff=0.05) self.add(axes) roots = [-1, 3, 4.5] coefs = 0.1 * np.array(roots_to_coefficients(roots)) graph = axes.get_graph(lambda x: poly(x, coefs)) graph.set_stroke(BLUE, 3) self.add(graph) self.root_point = axes.c2p(roots[-1], 0) self.axes = axes self.graph = graph def add_rule(self): rule = OldTex( "x_{n + 1}", "=", "x_{n}", " - ", "{P(x) ", "\\over ", "P'(x)}" ) rule.set_stroke(BLACK, 5, background=True) rule.to_corner(UR) step_box = SurroundingRectangle(rule[3:], buff=0.1) step_box.set_stroke(YELLOW, 1.0) step_word = Text("Step size", font_size=36) step_word.set_color(YELLOW) step_word.next_to(step_box, DOWN) self.add(rule) self.add(step_box) self.add(step_word) self.rule = rule self.step_box = step_box self.step_word = step_word def add_guess(self, include_px=True): guess_group = self.get_guess_group() marker, value, tracker = guess_group self.guess_tracker = tracker def update_v_line(v_line): x = tracker.get_value() graph_point = self.graph.pfp( inverse_interpolate(*self.graph.x_range[:2], x) ) v_line.put_start_and_end_on( self.axes.c2p(x, 0), graph_point, ) v_line = Line() v_line.set_stroke(WHITE, 2) v_line.add_updater(update_v_line) self.add(*guess_group) self.add(v_line) if include_px: px_label = OldTex("P(x)", font_size=36) px_label.add_updater(lambda m: m.next_to(v_line, RIGHT, buff=0.05)) self.add(px_label) def sample_values(self): box = self.step_box rule = self.rule tracker = self.guess_tracker graph = self.graph words = Text("Gut check!") words.next_to(self.step_word, DOWN, LARGE_BUFF) words.shift(2 * LEFT) arrow = Arrow(words, self.rule) self.play( Write(words, run_time=1), ShowCreation(arrow), ) self.wait() self.play( FadeOut(words), FadeOut(arrow), FadeOut(self.step_word), box.animate.replace(rule[4], stretch=True).scale(1.2).set_stroke(width=2.0), ) self.play( tracker.animate.set_value(6.666), run_time=3, ) arrow = Arrow( self.axes.c2p(tracker.get_value(), 0), self.root_point, buff=0, stroke_color=RED, ) self.play(ShowCreation(arrow)) self.wait() # Large p_prime self.play( FadeOut(arrow), tracker.animate.set_value(5.0), ) self.play( graph.animate.stretch(8, 1, about_point=self.axes.c2p(0, 0)), box.animate.replace(self.rule[-1]).scale(1.2), run_time=3 ) self.wait() tan_line = self.get_tan_line(graph, tracker.get_value(), 15) self.play(ShowCreation(tan_line)) self.wait() def get_tan_line(self, graph, x, length=5, epsilon=1e-3): alpha = inverse_interpolate(*graph.x_range[:2], x) tan_line = Line( graph.pfp(alpha - epsilon), graph.pfp(alpha + epsilon), ) tan_line.set_length(length) tan_line.set_stroke(RED, 5) return tan_line class HistoryWithNewton(Scene): def construct(self): # Add title title = Text("Newton's method", font_size=60) title.to_edge(UP) self.add(title) # Add timeline time_range = (1620, 2020) timeline = NumberLine( (*time_range, 1), tick_size=0.025, longer_tick_multiple=4, numbers_with_elongated_ticks=range(*time_range, 10), ) timeline.stretch(0.2 / timeline.get_unit_size(), 0) timeline_center = 2 * DOWN timeline.move_to(timeline_center) timeline.to_edge(RIGHT) timeline.add_numbers( range(*time_range, 10), group_with_commas=False, ) timeline.shift(timeline_center - timeline.n2p(1680)) self.add(timeline) # Newton newton = get_figure("Newton", "Isaac Newton", "1669") newton.next_to(title, DOWN, buff=0.5) newton.to_edge(LEFT, buff=1.5) newton_point = timeline.n2p(1669) newton_arrow = Arrow(newton_point, newton[0].get_right() + DOWN, path_arc=PI / 3) newton_words = Text("Overly\ncomplicated", font_size=36) newton_words.next_to(newton[0], RIGHT) raphson_point = timeline.n2p(1690) raphson = get_figure("Newton", "Joseph Raphson", "1690") raphson.move_to(newton) raphson.set_x(raphson_point[0] + 2) raphson[1].set_opacity(0) raphson_arrow = Arrow(raphson_point, raphson[0].get_left() + DOWN, path_arc=-PI / 3) raphson_word = Text("Simplified", font_size=36) raphson_word.next_to(raphson[0], LEFT) no_image_group = VGroup( Text("No image"), Text("(sorry)"), # Randolph(mode="shruggie", height=1) ) no_image_group[:2].set_fill(GREY) no_image_group.arrange(DOWN, buff=0.5) no_image_group.set_width(raphson[0].get_width() - 0.5) no_image_group.move_to(raphson[0]) self.add(newton, newton_arrow) frame = self.camera.frame frame.save_state() title.fix_in_frame() frame.move_to(timeline, RIGHT) self.play( frame.animate.match_width(timeline).set_x(timeline.get_center()[0]), run_time=2 ) self.play(Restore(frame, run_time=2)) # self.play( # GrowFromPoint(newton, newton_point), # ShowCreation(newton_arrow) # ) self.wait() self.play(Write(newton_words)) self.wait() self.play( GrowFromPoint(raphson, raphson_point), ShowCreation(raphson_arrow), ) self.play(LaggedStartMap(FadeIn, no_image_group, lag_ratio=0.2)) self.play(FadeIn(raphson_word)) self.wait() new_title = Text("Newton-Raphson method", font_size=60) new_title.to_edge(UP) self.play( FadeOut(title), TransformFromCopy( newton[2].get_part_by_text("Newton"), new_title.get_part_by_text("Newton"), ), TransformFromCopy( raphson[2].get_part_by_text("Raphson"), new_title.get_part_by_text("Raphson"), ), TransformFromCopy( title.get_part_by_text("method"), new_title.get_part_by_text("method"), ), FadeIn(new_title.get_part_by_text("-")) ) self.play(FlashAround(new_title, run_time=2)) self.wait() class CalcHomework(GutCheckFormula): seed = 3.0 def construct(self): # Title old_title = Text("Newton-Raphson method", font_size=60) old_title.to_edge(UP) title = Text("Calc 1", font_size=72) title.to_edge(UP, buff=MED_SMALL_BUFF) line = Underline(title) line.scale(2) line.set_stroke(WHITE, 2) self.add(old_title) # Axes axes = NumberPlane( x_range=(-5, 5, 1), y_range=(-8, 10, 2), height=6.5, width=FRAME_WIDTH, faded_line_ratio=4, background_line_style={ "stroke_color": GREY_C, "stroke_width": 1, } ) axes.to_edge(DOWN, buff=0) axes.add_coordinate_labels(font_size=18) self.add(axes) # Homework hw = OldTexText( "Homework:\\\\", "\\quad Approximate $\\sqrt{7}$ by hand using\\\\", "\\quad the ", "Newton-Raphson method.", alignment="", font_size=36, color=GREY_A, ) hw[1:].shift(MED_SMALL_BUFF * RIGHT + SMALL_BUFF * DOWN) hw.add_to_back( BackgroundRectangle(hw, fill_opacity=0.8, buff=0.25) ) hw.move_to(axes, UL) hw.to_edge(LEFT, buff=0) self.wait() self.play( FadeIn(hw, lag_ratio=0.1, run_time=2), FadeTransform( old_title, hw[-1] ), FadeIn(title), ShowCreation(line), ) self.wait() # Graph graph = axes.get_graph( lambda x: x**2 - 7, x_range=(-math.sqrt(17), math.sqrt(17)) ) graph.set_stroke(BLUE, 2) graph_label = OldTex("x^2 - 7", font_size=36) graph_label.set_color(BLUE) graph_label.next_to(graph.pfp(0.99), LEFT) self.add(graph, hw) self.play(ShowCreation(graph, run_time=3)) self.play(FadeIn(graph_label)) self.wait() # Marker axes.x_axis.numbers.remove(axes.x_axis.numbers[-3]) self.axes = axes self.graph = graph self.add_guess(include_px=False) self.wait() # Update tan_line = self.get_tan_line(graph, 3) tan_line.set_stroke(width=3) update_tex = OldTex( "3 \\rightarrow 3 - {3^2 - 7 \\over 2 \\cdot 3}", tex_to_color_map={"3": YELLOW}, font_size=28 ) update_tex.next_to(axes.c2p(1.2, 0), UR, buff=SMALL_BUFF) self.add(tan_line, self.guess_marker, self.guess_value) self.play( GrowFromCenter(tan_line), FadeIn(update_tex), ) self.wait() self.play( self.guess_tracker.animate.set_value(8 / 3), run_time=2 ) class RealNewtonsMethodHigherGraph(FasterNewtonExample): coefs = [1, -1, 1, 0, 0, 0.99] poly_tex = "x^5 + x^2 - x + 1" n_search_steps = 20 class FactorPolynomial(RealNewtonsMethodHigherGraph): def construct(self): self.add_graph() self.add_title(self.axes) self.show_factors() def show_factors(self): poly = self.poly colors = color_gradient((BLUE, YELLOW), 5) factored = OldTex( "P(x) = ", *( f"(x - r_{n})" for n in range(5) ), tex_to_color_map={ f"r_{n}": color for n, color in enumerate(colors) } ) factored.match_height(poly[0]) factored.next_to(poly, DOWN, LARGE_BUFF, LEFT) self.play( FadeTransform(poly.copy(), factored) ) self.wait() words = OldTexText("Potentially complex\\\\", "$r_n = a_n + b_n i$") words.set_color(GREY_A) words.next_to(factored, DOWN, buff=1.5) words.shift(LEFT) lines = VGroup(*( Line(words, part, buff=0.15).set_stroke(part.get_color(), 2) for n in range(5) for part in [factored.get_part_by_tex(f"r_{n}")] )) self.play( FadeIn(words[0]), Write(lines), ) self.play(FadeIn(words[1], 0.5 * DOWN)) self.wait() class TransitionToComplexPlane(RealNewtonsMethodHigherGraph): poly_tex = "z^5 + z^2 - z + 1" def construct(self): self.add_graph() self.add_title(self.axes) self.poly.save_state() self.poly.to_corner(UL) self.center_graph() self.show_example_point() self.separate_input_and_output() self.move_input_around_plane() def center_graph(self): shift_vect = DOWN - self.axes.c2p(0, 0) self.play( self.axes.animate.shift(shift_vect), self.graph.animate.shift(shift_vect), ) self.wait() def show_example_point(self): axes = self.axes input_tracker = ValueTracker(1) get_x = input_tracker.get_value def get_px(): return poly(get_x(), self.coefs) def get_graph_point(): return axes.c2p(get_x(), get_px()) marker = ArrowTip().set_height(0.1) input_marker = marker.copy().rotate(PI / 2) input_marker.set_color(YELLOW) output_marker = marker.copy() output_marker.set_color(MAROON_B) input_marker.add_updater(lambda m: m.move_to(axes.x_axis.n2p(get_x()), UP)) output_marker.add_updater(lambda m: m.shift(axes.y_axis.n2p(get_px()) - m.get_start())) v_line = always_redraw( lambda: axes.get_v_line(get_graph_point(), line_func=Line).set_stroke(YELLOW, 1) ) h_line = always_redraw( lambda: axes.get_h_line(get_graph_point(), line_func=Line).set_stroke(MAROON_B, 1) ) self.add( input_tracker, input_marker, output_marker, v_line, h_line, ) self.play(input_tracker.animate.set_value(-0.5), run_time=3) self.play(input_tracker.animate.set_value(1.0), run_time=3) self.play(ShowCreationThenFadeOut( axes.get_tangent_line(get_x(), self.graph).set_stroke(RED, 3) )) self.input_tracker = input_tracker self.input_marker = input_marker self.output_marker = output_marker self.v_line = v_line self.h_line = h_line def separate_input_and_output(self): axes = self.axes x_axis, y_axis = axes.x_axis, axes.y_axis graph = self.graph input_marker = self.input_marker output_marker = self.output_marker v_line = self.v_line h_line = self.h_line in_plane = ComplexPlane( (-2, 2), (-2, 2), height=5, width=5, ) in_plane.add_coordinate_labels(font_size=18) in_plane.to_corner(DL) out_plane = in_plane.deepcopy() out_plane.to_corner(DR) input_word = Text("Input") output_word = Text("Output") input_word.next_to(in_plane.x_axis, UP) output_word.rotate(PI / 2) output_word.next_to(out_plane.y_axis, RIGHT, buff=0.5) cl_copy = axes.coordinate_labels.copy() axes.coordinate_labels.set_opacity(0) self.play( *map(FadeOut, (v_line, h_line, graph, cl_copy)), ) for axis1, axis2 in [(x_axis, in_plane.x_axis), (y_axis, out_plane.y_axis)]: axis1.generate_target() axis1.target.scale(axis2.get_unit_size() / axis1.get_unit_size()) axis1.target.shift(axis2.n2p(0) - axis1.target.n2p(0)) self.play( MoveToTarget(x_axis), MoveToTarget(y_axis), FadeIn(input_word), FadeIn(output_word), ) self.wait() self.add(in_plane, input_marker) self.play( input_word.animate.next_to(in_plane, UP), x_axis.animate.set_stroke(width=0), Write(in_plane, lag_ratio=0.03), ) self.play( Rotate( VGroup(y_axis, output_word, output_marker), -PI / 2, about_point=out_plane.n2p(0) ) ) self.add(out_plane, output_marker) self.play( output_word.animate.next_to(out_plane, UP), y_axis.animate.set_stroke(width=0), Write(out_plane, lag_ratio=0.03), ) self.wait() self.in_plane = in_plane self.out_plane = out_plane self.input_word = input_word self.output_word = output_word def move_input_around_plane(self): in_plane = self.in_plane out_plane = self.out_plane input_marker = self.input_marker output_marker = self.output_marker in_dot, out_dot = [ Dot(radius=0.05).set_fill(marker.get_fill_color()).move_to(marker.get_start()) for marker in (input_marker, output_marker) ] in_dot.set_fill(YELLOW, 1) in_tracer = TracingTail(in_dot, stroke_color=in_dot.get_color()) out_tracer = TracingTail(out_dot, stroke_color=out_dot.get_color()) self.add(in_tracer, out_tracer) out_dot.add_updater(lambda m: m.move_to(out_plane.n2p( poly(in_plane.p2n(in_dot.get_center()), self.coefs) ))) z_label = OldTex("z", font_size=24) z_label.set_fill(YELLOW) z_label.add_background_rectangle() z_label.add_updater(lambda m: m.next_to(in_dot, UP, SMALL_BUFF)) pz_label = OldTex("P(z)", font_size=24) pz_label.set_fill(MAROON_B) pz_label.add_background_rectangle() pz_label.add_updater(lambda m: m.next_to(out_dot, UP, SMALL_BUFF)) self.play( *map(FadeOut, (input_marker, output_marker)), *map(FadeIn, (in_dot, out_dot)), FadeIn(z_label), FlashAround(z_label), ) self.play( FadeTransform(z_label.copy(), pz_label) ) z_values = [ complex(-0.5, 0.5), complex(-0.5, -0.5), complex(-0.25, 0.25), complex(0.5, -0.5), complex(0.5, 0.5), complex(1, 0.25), ] for z in z_values: self.play( in_dot.animate.move_to(in_plane.n2p(z)), run_time=2, path_arc=PI / 2 ) self.wait() self.remove(in_tracer, out_tracer) in_plane.generate_target() in_dot.generate_target() group = VGroup(in_plane.target, in_dot.target) group.set_height(8).center().to_edge(RIGHT, buff=0), self.play( MoveToTarget(in_plane), MoveToTarget(in_dot), FadeOut(self.input_word), FadeOut(self.output_word), FadeOut(out_plane), FadeOut(out_dot), FadeOut(pz_label), self.poly.animate.restore().shift(0.32 * RIGHT), ) class ComplexNewtonsMethod(RealNewtonsMethod): coefs = [1, -1, 1, 0, 0, 1] poly_tex = "z^5 + z^2 - z + 1" plane_config = { "x_range": (-2, 2), "y_range": (-2, 2), "height": 8, "width": 8, } seed = complex(-0.5, 0.5) seed_tex = "-0.5 + 0.5i" guess_color = YELLOW pz_color = MAROON_B step_arrow_width = 5 step_arrow_opacity = 1.0 step_arrow_len = None n_search_steps = 9 def construct(self): self.add_plane() self.add_title() self.add_z0_def() self.add_pz_dot() self.add_rule() self.find_root() def add_plane(self): plane = ComplexPlane(**self.plane_config) plane.add_coordinate_labels(font_size=24) plane.to_edge(RIGHT, buff=0) self.plane = plane self.add(plane) def add_title(self, opacity=1): super().add_title(self.plane, opacity) def add_z0_def(self): seed_text = Text("(Arbitrary seed)") z0_def = OldTex( f"z_0 = {self.seed_tex}", tex_to_color_map={"z_0": self.guess_color}, font_size=self.rule_font_size ) z0_group = VGroup(seed_text, z0_def) z0_group.arrange(DOWN) z0_group.next_to(self.title, DOWN, buff=LARGE_BUFF) guess_dot = Dot(self.plane.n2p(self.seed), color=self.guess_color) guess = DecimalNumber(self.seed, num_decimal_places=3, font_size=30) guess.add_updater( lambda m: m.set_value(self.plane.p2n( guess_dot.get_center() )).set_fill(self.guess_color).add_background_rectangle() ) guess.add_updater(lambda m: m.next_to(guess_dot, UP, buff=0.15)) self.play( Write(seed_text, run_time=1), FadeIn(z0_def), ) self.play( FadeTransform(z0_def[0].copy(), guess_dot), FadeIn(guess), ) self.wait() self.z0_group = z0_group self.z0_def = z0_def self.guess_dot = guess_dot self.guess = guess def add_pz_dot(self): plane = self.plane guess_dot = self.guess_dot def get_pz(): z = plane.p2n(guess_dot.get_center()) return poly(z, self.coefs) pz_dot = Dot(color=self.pz_color) pz_dot.add_updater(lambda m: m.move_to(plane.n2p(get_pz()))) pz_label = OldTex("P(z)", font_size=24) pz_label.set_color(self.pz_color) pz_label.add_background_rectangle() pz_label.add_updater(lambda m: m.next_to(pz_dot, UL, buff=0)) self.play( FadeTransform(self.poly[0].copy(), pz_label), FadeIn(pz_dot), ) self.wait() def add_rule(self): self.rule = rule = self.get_update_rule("z") rule.next_to(self.z0_group, DOWN, buff=LARGE_BUFF) self.play( FadeTransformPieces(self.z0_def[0].copy(), rule.zns), FadeIn(rule), ) self.wait() def find_root(self): for x in range(self.n_search_steps): self.root_search_step() def root_search_step(self): dot = self.guess_dot dot_step_anims = self.get_dot_step_anims(VGroup(dot)) diff_rect = SurroundingRectangle( self.rule.slice_by_tex("-"), buff=0.1, stroke_color=GREY_A, stroke_width=1, ) self.play( ShowCreation(diff_rect), dot_step_anims[0], ) self.play( dot_step_anims[1], FadeOut(diff_rect), *self.cycle_rule_entries_anims(), run_time=2 ) self.wait() def get_dot_step_anims(self, dots): plane = self.plane arrows = VGroup() dots.generate_target() for dot, dot_target in zip(dots, dots.target): try: z0 = plane.p2n(dot.get_center()) pz = poly(z0, self.coefs) dpz = dpoly(z0, self.coefs) if abs(pz) < 1e-3: z1 = z0 else: if dpz == 0: dpz = 0.1 # ??? z1 = z0 - pz / dpz if np.isnan(z1): z1 = z0 arrow = Arrow( plane.n2p(z0), plane.n2p(z1), buff=0, stroke_width=self.step_arrow_width, storke_opacity=self.step_arrow_opacity, ) if self.step_arrow_len is not None: if arrow.get_length() > self.step_arrow_len: arrow.set_length(self.step_arrow_len, about_point=arrow.get_start()) if not hasattr(dot, "history"): dot.history = [dot.get_center().copy()] dot.history.append(plane.n2p(z1)) arrows.add(arrow) dot_target.move_to(plane.n2p(z1)) except ValueError: pass return [ ShowCreation(arrows, lag_ratio=0), AnimationGroup( MoveToTarget(dots), FadeOut(arrows), ) ] class OutputIsZero(Scene): def construct(self): words = OldTexText("Output $\\approx 0$") words.set_stroke(BLACK, 5, background=True) arrow = Vector(0.5 * UL) words.next_to(arrow, DR) words.shift(0.5 * LEFT) self.play( Write(words), ShowCreation(arrow) ) self.wait() class FunPartWords(Scene): def construct(self): text = OldTexText("Now here's \\\\ the fun part", font_size=72) self.add(text) class ComplexNewtonsMethodManySeeds(ComplexNewtonsMethod): dot_radius = 0.035 dot_color = WHITE dot_opacity = 0.8 step_arrow_width = 3 step_arrow_opacity = 0.1 step_arrow_len = 0.15 plane_config = { "x_range": (-2, 2), "y_range": (-2, 2), "height": 8, "width": 8, } step = 0.2 n_search_steps = 20 colors = ROOT_COLORS_BRIGHT def construct(self): self.add_plane() self.add_title() self.add_z0_def() self.add_rule() self.add_true_root_circles() self.find_root() self.add_color() def add_z0_def(self): seed_text = Text("Many seeds: ") z0_def = OldTex( "z_0", tex_to_color_map={"z_0": self.guess_color}, font_size=self.rule_font_size ) z0_group = VGroup(seed_text, z0_def) z0_group.arrange(RIGHT) z0_group.next_to(self.title, DOWN, buff=LARGE_BUFF) x_range = self.plane_config["x_range"] y_range = self.plane_config["y_range"] step = self.step x_vals = np.arange(x_range[0], x_range[1] + step, step) y_vals = np.arange(y_range[0], y_range[1] + step, step) guess_dots = VGroup(*( Dot( self.plane.c2p(x, y), radius=self.dot_radius, fill_opacity=self.dot_opacity, ) for i, x in enumerate(x_vals) for y in (y_vals if i % 2 == 0 else reversed(y_vals)) )) guess_dots.set_submobject_colors_by_gradient(WHITE, GREY_B) guess_dots.set_fill(opacity=self.dot_opacity) guess_dots.set_stroke(BLACK, 2, background=True) self.play( Write(seed_text, run_time=1), FadeIn(z0_def), ) self.play( LaggedStart(*( FadeTransform(z0_def[0].copy(), guess_dot) for guess_dot in guess_dots ), lag_ratio=0.1 / len(guess_dots)), run_time=3 ) self.add(guess_dots) self.wait() self.z0_group = z0_group self.z0_def = z0_def self.guess_dots = guess_dots def add_true_root_circles(self): roots = coefficients_to_roots(self.coefs) root_points = list(map(self.plane.n2p, roots)) colors = self.colors root_circles = VGroup(*( Dot(radius=0.1).set_fill(color, opacity=0.75).move_to(rp) for rp, color in zip(root_points, colors) )) self.play( LaggedStart(*( FadeIn(rc, scale=0.5) for rc in root_circles ), lag_ratio=0.7, run_time=1), ) self.wait() self.root_circles = root_circles def root_search_step(self): dots = self.guess_dots dot_step_anims = self.get_dot_step_anims(dots) self.play(dot_step_anims[0], run_time=0.25) self.play( dot_step_anims[1], *self.cycle_rule_entries_anims(), run_time=1 ) def add_color(self): root_points = [circ.get_center() for circ in self.root_circles] colors = [circ.get_fill_color() for circ in self.root_circles] dots = self.guess_dots dots.generate_target() for dot, dot_target in zip(dots, dots.target): dc = dot.get_center() dot_target.set_color(colors[ np.argmin([get_norm(dc - rp) for rp in root_points]) ]) rect = SurroundingRectangle(self.rule) rect.set_fill(BLACK, 1) rect.set_stroke(width=0) self.play( FadeIn(rect), MoveToTarget(dots) ) self.wait() len_history = max([len(dot.history) for dot in dots if hasattr(dot, "history")], default=0) for n in range(len_history): dots.generate_target() for dot, dot_target in zip(dots, dots.target): try: dot_target.move_to(dot.history[len_history - n - 1]) except Exception: pass self.play(MoveToTarget(dots, run_time=0.5)) class ZeroStepColoring(ComplexNewtonsMethodManySeeds): n_search_steps = 0 class ComplexNewtonsMethodManySeedsHigherRes(ComplexNewtonsMethodManySeeds): step = 0.05 class IntroNewtonFractal(Scene): coefs = [1.0, -1.0, 1.0, 0.0, 0.0, 1.0] plane_config = { "x_range": (-4, 4), "y_range": (-4, 4), "height": 16, "width": 16, "background_line_style": { "stroke_color": GREY_A, "stroke_width": 1.0, }, "axis_config": { "stroke_width": 1.0, } } n_steps = 30 def construct(self): self.init_fractal(root_colors=ROOT_COLORS_BRIGHT) fractal, plane, root_dots = self.group # Transition from last scene frame = self.camera.frame frame.shift(plane.n2p(2) - RIGHT_SIDE) blocker = BackgroundRectangle(plane, fill_opacity=1) blocker.move_to(plane.n2p(-2), RIGHT) self.add(blocker) self.play( frame.animate.center(), FadeOut(blocker), run_time=2, ) self.wait() self.play( fractal.animate.set_colors(ROOT_COLORS_DEEP), *( dot.animate.set_fill(interpolate_color(color, WHITE, 0.2)) for dot, color in zip(root_dots, ROOT_COLORS_DEEP) ) ) self.wait() # Zoom in fractal.set_n_steps(40) zoom_points = [ [-3.12334879, 1.61196545, 0.], [1.21514006, 0.01415811, 0.], ] for point in zoom_points: self.play( frame.animate.set_height(2e-3).move_to(point), run_time=25, rate_func=bezier(2 * [0] + 6 * [1]) ) self.wait() self.play( frame.animate.center().set_height(8), run_time=10, rate_func=bezier(6 * [0] + 2 * [1]) ) # Allow for play self.tie_fractal_to_root_dots(fractal) fractal.set_n_steps(12) def init_fractal(self, root_colors=ROOT_COLORS_DEEP): plane = self.get_plane() fractal = self.get_fractal( plane, colors=root_colors, n_steps=self.n_steps, ) root_dots = self.get_root_dots(plane, fractal) self.tie_fractal_to_root_dots(fractal) self.plane = plane self.fractal = fractal self.group = Group(fractal, plane, root_dots) self.add(*self.group) def get_plane(self): plane = ComplexPlane(**self.plane_config) plane.add_coordinate_labels(font_size=24) self.plane = plane return plane def get_fractal(self, plane, colors=ROOT_COLORS_DEEP, n_steps=30): return NewtonFractal( plane, colors=colors, coefs=self.coefs, n_steps=n_steps, ) def get_root_dots(self, plane, fractal): self.root_dots = VGroup(*( Dot(plane.n2p(root), color=color) for root, color in zip( coefficients_to_roots(fractal.coefs), fractal.colors ) )) self.root_dots.set_stroke(BLACK, 5, background=True) return self.root_dots def tie_fractal_to_root_dots(self, fractal): fractal.add_updater(lambda f: f.set_roots([ self.plane.p2n(dot.get_center()) for dot in self.root_dots ])) def on_mouse_press(self, point, button, mods): super().on_mouse_press(point, button, mods) mob = self.point_to_mobject(point, search_set=self.root_dots) if mob is None: return self.mouse_drag_point.move_to(point) mob.add_updater(lambda m: m.move_to(self.mouse_drag_point)) self.unlock_mobject_data() self.lock_static_mobject_data() def on_mouse_release(self, point, button, mods): super().on_mouse_release(point, button, mods) self.root_dots.clear_updaters() class ChaosOnBoundary(TeacherStudentsScene): def construct(self): self.teacher_says( OldTexText("Chaos at\\\\the boundary"), bubble_config={ "height": 3, "width": 3, } ) self.play_all_student_changes("pondering", look_at=self.screen) self.wait(3) class DeepZoomFractal(IntroNewtonFractal): coefs = [-1.0, 0.0, 0.0, 1.0, 0.0, 1.0] plane_config = { "x_range": (-4, 4), "y_range": (-4, 4), "height": 16 * 1, "width": 16 * 1, "background_line_style": { "stroke_color": GREY_A, "stroke_width": 1.0, }, "axis_config": { "stroke_width": 1.0, } } def construct(self): self.init_fractal(root_colors=ROOT_COLORS_DEEP) fractal, plane, root_dots = self.group he_tracker = ValueTracker(0) frame = self.camera.frame zoom_point = np.array([ # -1.91177811, 0.52197285, 0. 0.72681252, -0.66973296, 0. ], dtype=np.float64) initial_fh = FRAME_HEIGHT frame.add_updater(lambda m: m.set_height( initial_fh * 2**(-he_tracker.get_value()), )) # rd_height = root_dots.get_height() # root_dots.add_updater(lambda m: m.set_height( # rd_height * 2**(he_tracker.get_value() / 8), # about_point=zoom_point # )) self.add(frame) self.play( UpdateFromAlphaFunc( frame, lambda m, a: m.move_to(zoom_point * a), run_time=15, ), ApplyMethod( he_tracker.set_value, 14, run_time=30, rate_func=bezier([0, 0, 1, 1]), ), ) self.wait() class IncreasingStepsNewtonFractal(IntroNewtonFractal): play_mode = False def construct(self): self.init_fractal() fractal, plane, root_dots = self.group fractal.set_n_steps(0) steps_label = VGroup(Integer(0, edge_to_fix=RIGHT), Text("Steps")) steps_label.arrange(RIGHT, aligned_edge=UP) steps_label.next_to(ORIGIN, UP).to_edge(LEFT) steps_label.set_stroke(BLACK, 5, background=True) self.add(steps_label) step_tracker = ValueTracker(0) get_n_steps = step_tracker.get_value fractal.add_updater(lambda m: m.set_n_steps(int(get_n_steps()))) steps_label[0].add_updater( lambda m: m.set_value(int(get_n_steps())) ) steps_label[0].add_updater(lambda m: m.set_stroke(BLACK, 5, background=True)) if self.play_mode: self.wait(20) for n in range(20): step_tracker.set_value(n) if n == 1: self.wait(15) elif n == 2: self.wait(10) else: self.wait() else: self.play( step_tracker.animate.set_value(20), run_time=10 ) class ManyQuestions(Scene): def construct(self): self.add(FullScreenRectangle()) questions = VGroup( Text("Lower order polynomials?"), Text("Do points ever cycle?"), Text("Fractal dimension?"), Text("Connection to Mandelbrot?"), ) screens = VGroup(*(ScreenRectangle() for q in questions)) screens.arrange_in_grid( v_buff=1.5, h_buff=3.0, ) screens.set_fill(BLACK, 1) questions.match_width(screens[0]) for question, screen in zip(questions, screens): question.next_to(screen, UP) screen.add(question) screens.set_height(FRAME_HEIGHT - 0.5) screens.center() self.play(LaggedStartMap( FadeIn, screens, lag_ratio=0.9, ), run_time=8) self.wait() class WhatsGoingOn(TeacherStudentsScene): def construct(self): self.screen.set_height(4, about_edge=UL) self.screen.set_fill(BLACK, 1) self.add(self.screen) self.student_says( "What the %$!* is\ngoing on?", target_mode="angry", look_at=self.screen, index=2, added_anims=[LaggedStart(*( pi.change("guilty", self.students[2].eyes) for pi in [self.teacher, *self.students[:2]] ), run_time=2)] ) self.wait(4) class EquationToFrame(Scene): def construct(self): self.add(FullScreenRectangle()) screens = self.get_screens() arrow = Arrow(*screens) equation = get_newton_rule() equation.next_to(screens[0], UP) title = OldTexText("Unreasonable intricacy") title.next_to(screens[1], UP) self.wait() self.add(screens) self.add(equation) self.play( ShowCreation(arrow), FadeTransform(equation.copy(), title), ) self.wait() def get_screens(self): screens = Square().get_grid(1, 2) screens.set_height(6) screens.set_width(FRAME_WIDTH - 1, stretch=True) screens.set_stroke(WHITE, 3) screens.set_fill(BLACK, 1) screens.arrange(RIGHT, buff=2.0) screens.to_edge(DOWN) return screens class RepeatedNewton(Scene): coefs = [1.0, -1.0, 1.0, 0.0, 0.0, 1.0] plane_config = { "x_range": (-4, 4), "y_range": (-2, 2), "height": 8, "width": 16, } dots_config = { "radius": 0.05, "color": GREY_A, "gloss": 0.4, "shadow": 0.1, "opacity": 0.5, } arrow_style = { "stroke_color": WHITE, "stroke_opacity": 0.5, } dot_density = 5.0 points_scalar = 1.0 n_steps = 10 colors = ROOT_COLORS_BRIGHT show_coloring = True show_arrows = True highlight_equation = False corner_group_height = 2.0 step_run_time = 1.0 show_fractal_background = False def construct(self): self.add_plane() self.add_true_roots() self.add_labels() if self.show_fractal_background: self.add_fractal_background() self.add_dots() self.run_iterations() if self.show_coloring: self.color_points() self.revert_to_original_positions() def add_plane(self): plane = self.plane = ComplexPlane(**self.plane_config) plane.add_coordinate_labels(font_size=24) self.add(plane) def add_labels(self): eq_label = self.eq_label = OldTex( "P(z) = " + coefs_to_poly_string(self.coefs), font_size=36 ) rule_label = self.rule_label = get_newton_rule() rule_label.next_to(eq_label, DOWN, MED_LARGE_BUFF) corner_rect = SurroundingRectangle( VGroup(eq_label, rule_label), buff=MED_SMALL_BUFF ) corner_rect.set_fill(BLACK, 0.9) corner_rect.set_stroke(WHITE, 1) self.corner_group = VGroup( corner_rect, eq_label, rule_label, ) self.corner_group.set_height(self.corner_group_height) self.corner_group.to_corner(UL, buff=0) self.add(self.corner_group) def add_true_roots(self): roots = self.roots = coefficients_to_roots(self.coefs) root_dots = self.root_dots = VGroup(*( glow_dot(self.plane.n2p(root), color=color, opacity_mult=2.0) for root, color in zip(roots, self.colors) )) self.add(root_dots) def add_dots(self): dots = self.dots = DotCloud( self.get_original_points(), **self.dots_config ) self.add(dots, self.corner_group) self.play(ShowCreation(dots)) def get_original_points(self): step = 1.0 / self.dot_density return self.points_scalar * np.array([ self.plane.c2p(x, y) for x in np.arange(*self.plane.x_range[:2], step) for y in np.arange(*self.plane.y_range[:2], step) ]) def run_iterations(self): self.points_history = [] for x in range(self.n_steps): self.points_history.append(self.dots.get_points().copy()) self.take_step(run_time=self.step_run_time) def update_z(self, z, epsilon=1e-6): denom = dpoly(z, self.coefs) if abs(denom) < epsilon: denom = epsilon return z - poly(z, self.coefs) / denom def take_step(self, run_time=1.0): plane = self.plane points = self.dots.get_points() zs = map(plane.p2n, points) new_zs = map(self.update_z, zs) new_points = list(map(plane.n2p, new_zs)) added_anims = [] if self.show_arrows: arrows = [] max_len = 0.5 * plane.get_x_unit_size() / self.dot_density for p1, p2 in zip(points, new_points): vect = p2 - p1 norm = get_norm(vect) if norm > max_len: vect = normalize(vect) * max_len arrows.append(Vector(vect, **self.arrow_style).shift(p1)) arrows = VGroup(*arrows) self.add(arrows, self.dots, self.corner_group) self.play(ShowCreation(arrows, lag_ratio=0)) added_anims.append(FadeOut(arrows)) self.play( self.dots.animate.set_points(new_points), *added_anims, run_time=run_time, ) self.dots.filter_out(lambda p: get_norm(p) > FRAME_WIDTH) def color_points(self): root_points = [rd.get_center() for rd in self.root_dots] rgbas = list(map(color_to_rgba, self.colors)) def get_rgba(point): norms = [get_norm(point - rp) for rp in root_points] return rgbas[np.argmin(norms)] rgbas = list(map(get_rgba, self.dots.get_points())) fractal = NewtonFractal( self.plane, coefs=self.coefs, colors=self.colors, n_steps=0, ) fractal.set_opacity(0) self.add(fractal, self.plane, self.dots, self.corner_group) radius = self.dots.get_radius() self.play( fractal.animate.set_opacity(0.5), self.dots.animate.set_rgba_array(rgbas).set_radius(1.5 * radius), ) self.play( fractal.animate.set_opacity(0), self.dots.animate.set_radius(radius), ) self.remove(fractal) def revert_to_original_positions(self): for ph in self.points_history[::-1]: self.play( self.dots.animate.set_points(ph), run_time=0.5, ) def reveal_fractal(self, **kwargs): plane = self.plane fractal = self.fractal = self.get_fractal(**kwargs) root_dot_backs = VGroup(*(Dot(rd.get_center(), radius=0.1) for rd in self.root_dots)) root_dot_backs.set_stroke(BLACK, 2) root_dot_backs.set_fill(opacity=0) plane.generate_target(use_deepcopy=True) for lines in plane.target.background_lines, plane.target.faded_lines: lines.set_stroke(WHITE) for line in lines.family_members_with_points(): line.set_opacity(line.get_stroke_opacity() * 0.5) self.root_dots.generate_target() for rd, color in zip(self.root_dots.target, fractal.colors): rd.set_fill(color) self.add(fractal, *self.mobjects, root_dot_backs) self.play( FadeIn(fractal), FadeOut(self.dots), FadeIn(root_dot_backs), MoveToTarget(plane), MoveToTarget(self.root_dots), ) self.wait() def get_fractal(self, **kwargs): if "colors" not in kwargs: kwargs["colors"] = self.colors self.fractal = NewtonFractal(self.plane, coefs=self.coefs, **kwargs) return self.fractal def add_fractal_background(self): fractal = self.get_fractal() fractal.set_opacity(0.1) fractal.set_n_steps(12) boundary = self.fractal_boundary = fractal.copy() boundary.set_colors(5 * [WHITE]) boundary.set_julia_highlight(1e-4) boundary.set_opacity(0.25) self.add(fractal, boundary, *self.mobjects) class AmbientQuinticSolving(RepeatedNewton): coefs = [-23.125, -11.9375, -6.875, 0.3125, 2.5, 1] show_fractal_background = True dots_config = { "radius": 0.03, "color": GREY_A, "gloss": 0.4, "shadow": 0.1, "opacity": 0.5, } dot_density = 10.0 def add_labels(self): super().add_labels() self.corner_group.set_opacity(0) class WhyNotThisWrapper(VideoWrapper): title = "Why not something like this?" animate_boundary = False title_config = { "font_size": 60, "color": RED, } wait_time = 2 class SimplyTendingToNearestRoot(RepeatedNewton): def update_z(self, z): norms = [abs(r - z) for r in self.roots] nearest_root = self.roots[np.argmin(norms)] norm = min(norms) step_size = np.log(1 + norm * 3) / 3 return z + step_size * (nearest_root - z) class UnrelatedIdeas(TeacherStudentsScene): def construct(self): self.screen.set_height(4, about_edge=UL) self.add(self.screen) self.play_student_changes( "tease", "thinking", "raise_right_hand", look_at=self.screen, added_anims=[self.teacher.change("happy")] ) self.wait(2) self.teacher_says( OldTexText("Unrelated\\\\ideas"), bubble_config={ "height": 3, "width": 4, }, added_anims=[ s.change("sassy", self.teacher.eyes) for s in self.students ] ) self.play(LaggedStart( self.students[2].change("angry"), self.teacher.change("guilty"), lag_ratio=0.7, )) self.wait(2) self.embed() class RepeatedNewtonCubic(RepeatedNewton): coefs = [-1, 0, 0, 1] # colors = [RED_E, GREEN_E, BLUE_E] colors = ROOT_COLORS_DEEP[::2] def construct(self): super().construct() self.reveal_fractal() frame = self.camera.frame self.play( frame.animate.move_to([0.86579359, -0.8322599, 0.]).set_height(0.0029955), rate_func=bezier([0, 0, 1, 1, 1, 1, 1, 1]), run_time=10, ) class RepeatedNewtonQuadratic(RepeatedNewton): coefs = [-1, 0, 1] colors = [RED, BLUE] n_steps = 10 class SimpleFractalScene(IntroNewtonFractal): colors = ROOT_COLORS_DEEP display_polynomial_label = False display_root_values = False n_steps = 25 def construct(self): self.init_fractal(root_colors=self.colors) if self.display_polynomial_label: self.add_polynomial_label() if self.display_root_values: self.add_root_labels() def add_polynomial_label(self): n = len(self.fractal.roots) t2c = { f"r_{i + 1}": interpolate_color(self.colors[i], WHITE, 0.5) for i in range(n) } label = OldTex( "p(z) = ", *( f"(z - r_{i})" for i in range(1, n + 1) ), tex_to_color_map=t2c, font_size=36 ) label.to_corner(UL) label.set_stroke(BLACK, 5, background=True) self.add(label) def add_root_labels(self): for n, root_dot in zip(it.count(1), self.root_dots): self.add(self.get_root_label(root_dot, n)) def get_root_label(self, root_dot, n): def get_z(): return self.plane.p2n(root_dot.get_center()) label = VGroup( OldTex(f"r_{n} = "), DecimalNumber(get_z(), include_sign=True), ) label.scale(0.5) label.set_stroke(BLACK, 3, background=True) def update_label(label): label.arrange(RIGHT, buff=0.1) label[0].shift(0.1 * label[0].get_height() * DOWN) label.next_to(root_dot, UR, SMALL_BUFF) label[1].set_value(get_z()) label.add_updater(update_label) return label class TwoRootFractal(SimpleFractalScene): coefs = [-1.0, 0.0, 1.0] colors = [ROOT_COLORS_DEEP[0], ROOT_COLORS_DEEP[4]] n_steps = 0 # Doesn't really matter, does it? class TwoRootFractalWithLabels(TwoRootFractal): display_polynomial_label = True display_root_values = True class ThreeRootFractal(SimpleFractalScene): coefs = [-1.0, 0.0, 0.0, 1.0] colors = ROOT_COLORS_DEEP[::2] n_steps = 30 class ThreeRootFractalWithLabels(ThreeRootFractal): display_polynomial_label = True display_root_values = True class FromTwoToThree(EquationToFrame): def construct(self): self.add(FullScreenRectangle()) screens = self.get_screens() arrow = Arrow(*screens) quadratic = OldTex("x^2 + c_1 x + c_0") cubic = OldTex("x^3 + c_2 x^2 + c_1 x + c_0") quadratic.next_to(screens[0], UP) cubic.next_to(screens[1], UP) self.add(screens) self.add(quadratic, cubic) self.play(ShowCreation(arrow)) self.wait() class StudentAsksAboutComplexity(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("Why is it\\\\so complicated?"), index=0, bubble_config={ "height": 3, "width": 4, }, added_anims=[ self.students[1].change("confused", self.teacher.eyes), self.students[2].change("erm", self.teacher.eyes), ], ) self.wait() self.play( self.teacher.change("shruggie"), ) self.wait() self.play(LaggedStart( PiCreatureSays( self.teacher, OldTexText("Math is what\\\\it is"), target_mode="well", bubble_config={ "height": 3, "width": 4, } ), self.students[1].change("maybe"), self.students[2].change("sassy"), lag_ratio=0.7, )) self.wait(2) why = self.students[0].bubble.content[0][:3] question = Text("Is this meaningful?") question.to_corner(UL) question.set_color(YELLOW) arrow = Arrow(question, why) arrow.set_stroke(YELLOW, 5) self.play( why.animate.set_color(YELLOW), Write(question), ShowCreation(arrow), LaggedStart(*( pi.change(mode, question) for pi, mode in zip(self.pi_creatures, ("well", "erm", "sassy", "hesitant")) )) ) self.wait(2) cross = Cross(question) cross.set_stroke(RED, [1, *4 * [8], 1]) words = Text("Surprisingly answerable!") words.next_to(question, RIGHT, LARGE_BUFF) new_arrow = Arrow(words[:10], why) new_arrow.set_stroke(WHITE, 5) self.play( RemovePiCreatureBubble(self.teacher, target_mode="erm"), ShowCreation(cross), FadeIn(words), ShowCreation(new_arrow), ) self.wait(2) class NextVideoWrapper(VideoWrapper): title = "Next video" class PeculiarBoundaryProperty(Scene): coefs = [-1, 0, 0, 1] colors = [RED_E, TEAL_E, BLUE_E] def construct(self): # Title title = Text("Peculiar property", font_size=60) title.to_edge(UP, buff=MED_SMALL_BUFF) title.set_stroke(BLACK, 5, background=True) underline = Underline(title, buff=-0.05) underline.set_width(title.get_width() + 1) underline.insert_n_curves(20) underline.set_stroke(BLUE, [1, *5 * [3], 1]) subtitle = OldTexText( "Boundary of one color", " = " "Boundary of any other", tex_to_color_map={ "one color": BLUE_D, "any other": RED_D, } ) subtitle.next_to(underline, DOWN, MED_LARGE_BUFF) # Setup for planes grid = VGroup(*( ComplexPlane( x_range=(-3, 3), y_range=(-2, 2), ) for n in range(6) )) grid.arrange_in_grid(2, 3, v_buff=2, h_buff=3) grid.set_width(FRAME_WIDTH - 2) grid.to_edge(DOWN, buff=MED_LARGE_BUFF) arrows = VGroup() bound_words = VGroup() for p1, p2 in zip(grid[:3], grid[3:]): arrow = Arrow(p1, p2, stroke_width=4, buff=0.1) arrows.add(arrow) bound_word = Text("Boundary", font_size=24) bound_word.next_to(arrow, RIGHT, buff=SMALL_BUFF) bound_words.add(bound_word) low_equals = VGroup( OldTex("=").move_to(grid[3:5]), OldTex("=").move_to(grid[4:6]), ) # Fractals fractals = Group(*( NewtonFractal(plane, coefs=self.coefs, colors=self.colors) for plane in grid )) alpha = 0.2 for k in 0, 3: fractals[0 + k].set_opacities(alpha, 1, alpha) fractals[1 + k].set_opacities(alpha, alpha, 1) fractals[2 + k].set_opacities(1, alpha, alpha) boxes = VGroup(*( SurroundingRectangle(fractal, buff=0) for fractal in fractals )) boxes.set_stroke(GREY_B, 1) # Initial fractal big_plane = grid[0].deepcopy() big_plane.set_height(6.5) big_plane.center().to_edge(DOWN) big_fractal = NewtonFractal(big_plane, coefs=self.coefs, colors=self.colors) big_julia = big_fractal.copy() big_julia.set_julia_highlight(1e-3) big_julia.set_colors(3 * [WHITE]) self.add(big_fractal) # Animations def get_show_border_anims(fractal): f_copy = fractal.copy() fractal.set_julia_highlight(5e-3) fractal.set_colors(3 * [WHITE]) return (FadeOut(f_copy), GrowFromCenter(fractal)) def high_to_low_anims(index): return ( ShowCreation(arrows[index]), FadeIn(bound_words[index]), TransformFromCopy(fractals[index], fractals[index + 3]), TransformFromCopy(boxes[index], boxes[index + 3]), ) self.add(underline, title) self.play( ShowCreation(underline), GrowFromCenter(big_julia, run_time=4) ) self.play( big_julia.animate.set_julia_highlight(0.02).set_colors(CUBIC_COLORS).set_opacity(0) ) self.wait() self.play( big_fractal.animate.set_opacities(alpha, alpha, 1) ) self.wait() self.play( ReplacementTransform(big_fractal, fractals[1]), FadeIn(subtitle[:2]), ReplacementTransform( boxes[1].copy().replace(big_fractal).set_opacity(0), boxes[1], ), ) self.play(*high_to_low_anims(1)) self.play(*get_show_border_anims(fractals[4])) self.wait(2) subtitle[2:].set_opacity(0) self.add(subtitle[2:]) for i in 2, 0: self.play( FadeIn(fractals[i]), FadeIn(boxes[i]), subtitle[2:].animate.set_opacity(1), ) self.play(*high_to_low_anims(i)) self.play(*get_show_border_anims(fractals[i + 3])) self.wait() self.play(Write(low_equals)) class DefineBoundary(Scene): def construct(self): # Add set blob = VMobject() blob.set_fill(BLUE_E, 1) blob.set_stroke(width=0) blob.set_points_as_corners([ (1 + 0.3 * random.random()) * p for p in compass_directions(12) ]) blob.close_path() blob.set_height(3) blob.set_width(1.0, stretch=True) blob.move_to(2 * RIGHT) blob.apply_complex_function(np.exp) blob.make_smooth() blob.rotate(90 * DEGREES) blob.center() blob.set_height(4) blob.insert_n_curves(50) set_text = Text("Set", font_size=72) set_text.set_stroke(BLACK, 3, background=True) set_text.move_to(interpolate(blob.get_top(), blob.get_bottom(), 0.35)) self.add(blob) self.add(set_text) # Preview boundary point = Dot(radius=0.05) point.move_to(blob.get_start()) boundary_word = Text("Boundary") boundary_word.set_color(YELLOW) boundary_word.next_to(blob, LEFT) outline = blob.copy() outline.set_fill(opacity=0) outline.set_stroke(YELLOW, 2) self.add(point) kw = { "rate_func": bezier([0, 0, 1, 1]), "run_time": 5, } self.play( FadeIn(boundary_word), ShowCreation(outline, **kw), MoveAlongPath(point, blob, **kw) ) self.play(FadeOut(outline)) # Mention formality boundary_word.generate_target() boundary_word.target.to_corner(UL) formally_word = Text("More formally") formally_word.next_to(boundary_word.target, DOWN, aligned_edge=LEFT) self.play( MoveToTarget(boundary_word), FadeTransform(boundary_word.copy(), formally_word) ) self.wait() # Draw circle circle = Circle() circle.move_to(point) circle.set_stroke(TEAL, 3.0) self.play( ShowCreation(circle), point.animate.scale(0.5), ) self.wait() group = VGroup(blob, set_text) self.add(group, point, circle) self.play( ApplyMethod( group.scale, 2, {"about_point": point.get_center()}, run_time=4 ), ApplyMethod( circle.set_height, 0.5, run_time=2, ), ) # Labels inside_words = Text("Points inside", font_size=36) outside_words = Text("Points outside", font_size=36) inside_words.next_to(circle, DOWN, buff=0.5).shift(0.5 * LEFT) outside_words.next_to(circle, UP, buff=0.5).shift(0.5 * RIGHT) inside_arrow = Arrow( inside_words, point, stroke_width=3, buff=0.1, ) outside_arrow = Arrow( outside_words, point, stroke_width=3, buff=0.1, ) self.play( FadeIn(inside_words), ShowCreation(inside_arrow) ) self.play( FadeIn(outside_words), ShowCreation(outside_arrow) ) self.wait() # Show interior point_group = VGroup(point, circle) self.play( point_group.animate.shift(circle.get_height() * DOWN / 4), LaggedStartMap( FadeOut, VGroup(inside_words, inside_arrow, outside_words, outside_arrow) ) ) self.wait() self.play(circle.animate.set_height(0.2)) self.wait() # Show exterior point_group.generate_target() point_group.target.move_to(blob.get_start() + 0.25 * UP) point_group.target[1].set_height(1.0) self.play(MoveToTarget(point_group)) self.wait() self.play(circle.animate.set_height(0.2)) self.wait() # Back to boundary self.play(point_group.animate.move_to(blob.get_start())) frame = self.camera.frame frame.generate_target() frame.target.set_height(0.2) frame.target.move_to(point) point_group.generate_target() point_group.target.set_height(0.2 / 8) point_group.target[1].set_stroke(width=0.1) self.play(MoveToTarget(point_group)) self.play( MoveToTarget(frame), run_time=4 ) class VariousCirclesOnTheFractal(SimpleFractalScene): coefs = [-1.0, 0.0, 0.0, 1.0] colors = CUBIC_COLORS sample_density = 0.02 def construct(self): super().construct() frame = self.camera.frame plane = self.plane fractal = self.fractal frame.save_state() # Setup samples n_steps = 20 density = self.sample_density samples = np.array([ [complex(x, y), 0] for x in np.arange(0, 2, density) for y in np.arange(0, 2, density) ]) roots = coefficients_to_roots(self.coefs) for i in range(len(samples)): z = samples[i, 0] for n in range(n_steps): z = z - poly(z, self.coefs) / dpoly(z, self.coefs) norms = [abs(z - root) for root in roots] samples[i, 1] = np.argmin(norms) unit_size = plane.get_x_unit_size() circle = Circle() circle.set_stroke(WHITE, 3.0) circle.move_to(2 * UR) words = VGroup( Text("#Colors inside: "), Integer(3), ) words.arrange(RIGHT) words[1].align_to(words[0][-2], DOWN) height_ratio = words.get_height() / FRAME_HEIGHT def get_interior_count(circle): radius = circle.get_height() / 2 / unit_size norms = abs(samples[:, 0] - plane.p2n(circle.get_center())) true_result = len(set(samples[norms < radius, 1])) # In principle this would work, but the samples are not perfect return 3 if true_result > 1 else 1 def get_frame_ratio(): return frame.get_height() / FRAME_HEIGHT def update_words(words): words.set_height(height_ratio * frame.get_height()) ratio = get_frame_ratio() words.next_to(circle, UP, buff=SMALL_BUFF * ratio) count = get_interior_count(circle) words[1].set_value(count) words.set_stroke(BLACK, 5 * ratio, background=True) return words words.add_updater(update_words) circle.add_updater(lambda m: m.set_stroke(width=3.0 * get_frame_ratio())) self.play(ShowCreation(circle)) self.play(FadeIn(words)) self.wait() self.play(circle.animate.set_height(0.25)) self.wait() point = plane.c2p(0.5, 0.5) self.play(circle.animate.move_to(point)) self.play(frame.animate.set_height(2).move_to(point)) self.wait() point = plane.c2p(0.25, 0.4) self.play(circle.animate.move_to(point).set_height(0.1)) self.wait() for xy in (0.6, 0.4), (0.2, 0.6): self.play( circle.animate.move_to(plane.c2p(*xy)), run_time=4 ) self.wait() # Back to larger self.play( Restore(frame), circle.animate.set_height(0.5) ) self.wait() # Show smooth boundary count_tracker = ValueTracker(3) words.add_updater(lambda m: m[1].set_value(count_tracker.get_value())) def change_count_at(new_value, alpha): curr_value = count_tracker.get_value() return UpdateFromAlphaFunc( count_tracker, lambda m, a: m.set_value(curr_value if a < alpha else new_value) ) fractal.set_n_steps(10) self.play( fractal.animate.set_n_steps(3), run_time=2 ) self.play( circle.animate.move_to(plane.c2p(0, 0.3)), change_count_at(2, 0.75), run_time=2 ) self.wait() self.play( circle.animate.move_to(plane.c2p(0, 0)), change_count_at(3, 0.5), run_time=2 ) self.wait() self.play( circle.animate.move_to(plane.c2p(-0.6, 0.2)), Succession( change_count_at(2, 0.9), change_count_at(3, 0.7), ), run_time=3 ) self.play( circle.animate.set_height(0.1).move_to(plane.c2p(-0.6, 0.24)), change_count_at(2, 0.8), frame.animate.set_height(2.5).move_to(plane.c2p(-0.5, 0.5)), run_time=3 ) self.wait(2) self.play( fractal.animate.set_n_steps(20), change_count_at(3, 0.1), run_time=3, ) self.wait() # Just show boundary boundary = fractal.copy() boundary.set_colors(3 * [WHITE]) boundary.add_updater( lambda m: m.set_julia_highlight(get_frame_ratio() * 1e-3) ) boundary.set_n_steps(50) frame.generate_target() frame.target.set_height(0.0018), frame.target.move_to([-1.15535091, 0.23001433, 0.]) self.play( FadeOut(circle), FadeOut(words), FadeOut(self.root_dots), GrowFromCenter(boundary, run_time=3), fractal.animate.set_opacity(0.35), MoveToTarget( frame, run_time=10, rate_func=bezier([0, 0, 1, 1, 1, 1, 1]) ), ) self.wait() class ArtPuzzle(Scene): def construct(self): words = VGroup( Text("Art Puzzle:", font_size=60), OldTexText("- Use $\\ge 3$ colors"), OldTexText("- Boundary of one color = Boundary of all"), ) words.set_color(BLACK) words.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) words[1:].shift(0.5 * DOWN + 0.5 * RIGHT) words.to_corner(UL) for word in words: self.play(FadeIn(word, lag_ratio=0.1)) self.wait() class ZoomInOnCubic(ThreeRootFractal): colors = CUBIC_COLORS coefs = [complex(0, -1), 0, 0, 1] n_steps = 30 def construct(self): super().construct() frame = self.camera.frame height_exp_tracker = ValueTracker() get_height_exp = height_exp_tracker.get_value center_tracker = VectorizedPoint(ORIGIN) frame.add_updater(lambda m: m.move_to(center_tracker)) frame.add_updater(lambda m: m.set_height(FRAME_HEIGHT * 2**(-get_height_exp()))) self.play( ApplyMethod(center_tracker.move_to, [0.2986952, 1.11848235, 0], run_time=4), ApplyMethod( height_exp_tracker.set_value, 7, run_time=15, rate_func=bezier([0, 0, 1, 1]), ), ) self.wait() class BlobsOnBlobsOnBlobs(Scene): def construct(self): words = OldTexText( "Blobs", *( " on blobs " + ("\\\\" if n == 2 else "") for n in range(6) ), "..." ) words.set_width(FRAME_WIDTH - 2) words.to_edge(UP) words.set_color(BLACK) self.add(words[0]) for word in words[1:]: self.play(FadeIn(word, 0.25 * UP)) self.wait() class FractalDimensionWords(Scene): def construct(self): text = OldTexText("Fractal dimension $\\approx$ 1.44", font_size=60) text.to_corner(UL) self.play(Write(text)) self.wait() class ThinkAboutWhatPropertyMeans(TeacherStudentsScene): def construct(self): self.screen.set_height(4, about_edge=UL) self.add(self.screen) image = ImageMobject("NewtonBoundaryProperty") image.replace(self.screen) self.add(image) self.teacher_says( OldTexText("Think about what\\\\this tells us."), bubble_config={ "height": 3, "width": 4, } ) self.play_student_changes( "pondering", "thinking", "pondering", look_at=self.screen ) self.wait(4) class InterpretBoundaryProperty(RepeatedNewton): plane_config = { "x_range": (-4, 4), "y_range": (-2, 2), "height": 12, "width": 24, } n_steps = 15 def construct(self): self.add_plane() plane = self.plane plane.shift(2 * RIGHT) self.add_true_roots() self.add_labels() self.add_fractal_background() # Show sensitive point point = plane.c2p(-0.8, 0.4) dots = self.dots = DotCloud() dots.set_points([ [r * math.cos(theta), r * math.sin(theta), 0] for r in np.linspace(0, 1, 20) for theta in np.linspace(0, TAU, int(r * 20)) + random.random() * TAU ]) dots.set_height(2).center() dots.filter_out(lambda p: get_norm(p) > 1) dots.set_height(0.3) dots.set_radius(0.04) dots.make_3d() dots.set_color(GREY_A) dots.move_to(point) sensitive_words = Text("Sensitive area") sensitive_words.next_to(dots, RIGHT, buff=SMALL_BUFF) sensitive_words.set_stroke(BLACK, 5, background=True) def get_arrows(): root_dots = self.root_dots if plane.p2n(dots.get_center()).real < -1.25: root_dots = [root_dots[4]] return VGroup(*( Arrow( dots, root_dot, buff=0.1, stroke_color=root_dot[0].get_color() ) for root_dot in root_dots )) arrows = get_arrows() self.play( FadeIn(dots, scale=2), FadeIn(sensitive_words, shift=0.25 * UP) ) self.wait() self.play(ShowCreation(arrows[2])) self.play(ShowCreation(arrows[4])) self.wait() self.play( FadeOut(sensitive_words), LaggedStartMap(ShowCreation, VGroup(*( arrows[i] for i in (0, 1, 3) ))) ) self.wait() arrows.add_updater(lambda m: m.become(get_arrows())) self.add(arrows) self.play(dots.animate.move_to(plane.c2p(-1.4, 0.4)), run_time=3) self.wait() self.play(dots.animate.move_to(point), run_time=3) self.wait() not_allowed = Text("Not allowed!") not_allowed.set_color(RED) not_allowed.set_stroke(BLACK, 8, background=True) not_allowed.next_to(dots, RIGHT, SMALL_BUFF) arrows.clear_updaters() self.play( arrows[:2].animate.set_opacity(0), FadeIn(not_allowed, scale=0.7) ) self.wait() self.play(FadeOut(arrows), FadeOut(not_allowed)) # For fun self.run_iterations() class CommentsOnNaming(Scene): def construct(self): self.setup_table() self.show_everyone() def setup_table(self): titles = VGroup( OldTexText("How it started", font_size=60), OldTexText("How it's going", font_size=60), ) titles.to_edge(UP, buff=MED_SMALL_BUFF) titles.set_color(GREY_A) titles[0].set_x(-FRAME_WIDTH / 4) titles[1].set_x(FRAME_WIDTH / 4) h_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) h_line.next_to(titles, DOWN).set_x(0) v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) lines = VGroup(h_line, v_line) lines.set_stroke(WHITE, 2) self.left_point = [-FRAME_WIDTH / 4, -1, 0] self.right_point = [FRAME_WIDTH / 4, -1, 0] self.add(titles, lines) def show_everyone(self): # Newton newton = get_figure( "Newton", "Isaac Newton", "1643-1727", height=4, ) newton.move_to(self.left_point) newton_formula = get_newton_rule(var="x") newton_formula.next_to(newton, UP) nf_label = OldTexText("``Newton's'' fractal") nf_label.align_to(newton_formula, UP) nf_label.set_x(self.right_point[0]) self.play( FadeIn(newton_formula), LaggedStartMap(FadeIn, newton) ) self.wait() self.play(Write(nf_label)) self.wait(2) # Hamilton hamilton = get_figure( "Hamilton", "William Rowan Hamilton", "1805 - 1865", height=4, ) hamilton.move_to(self.left_point) hamiltons_equation = OldTex( r"\frac{\mathrm{d} \boldsymbol{q}}{\mathrm{d} t}=\frac{\partial \mathcal{H}}{\partial \boldsymbol{p}}, \quad \frac{\mathrm{d} \boldsymbol{p}}{\mathrm{d} t}=-\frac{\partial \mathcal{H}}{\partial \boldsymbol{q}}" ) hamiltons_equation.match_width(hamilton[0]) hamiltons_equation.next_to(hamilton, UP) hamiltonians = Text("Hamiltonians") hamiltonians.move_to(nf_label) self.play( LaggedStart( FadeOut(newton, shift=0.25 * LEFT), FadeOut(newton_formula, shift=0.25 * LEFT), FadeOut(nf_label, shift=0.25 * RIGHT), ), LaggedStart( FadeIn(hamilton, shift=0.25 * LEFT), FadeIn(hamiltons_equation, shift=0.25 * LEFT), FadeIn(hamiltonians, shift=0.25 * RIGHT), ) ) self.wait(2) # Fourier fourier = get_figure( "Joseph Fourier", "Joseph Fourier", "1768-1830", height=4 ) fourier.move_to(self.left_point) fourier_transform = OldTex( r"f(t)=\int_{0}^{\infty}(a(\lambda) \cos (2 \pi \lambda t)+b(\lambda) \sin (2 \pi \lambda t)) d \lambda" ) fourier_transform.set_width(fourier.get_width() * 1.5) fourier_transform.next_to(fourier, UP) FFT = Text("FFT") FFT.move_to(hamiltonians) FFT_diagram = ImageMobject("FFT_Diagram") FFT_diagram.move_to(self.right_point), self.play( LaggedStart( FadeOut(hamilton, shift=0.25 * LEFT), FadeOut(hamiltons_equation, shift=0.25 * LEFT), FadeOut(hamiltonians, shift=0.25 * RIGHT), ), LaggedStart( FadeIn(fourier, shift=0.25 * LEFT), FadeIn(fourier_transform, shift=0.25 * LEFT), FadeIn(FFT, shift=0.25 * RIGHT), ), FadeIn(FFT_diagram), ) self.wait(2) # Everyone people = Group(newton, hamilton, fourier) people.generate_target() people.target.arrange(DOWN, buff=LARGE_BUFF) people.target.set_height(6.4) people.target.move_to(self.left_point) people.target.to_edge(DOWN, buff=SMALL_BUFF) self.play( FadeOut(fourier_transform), FadeOut(FFT), MoveToTarget(people, run_time=2), FFT_diagram.animate.scale(1 / 3).match_y(people.target[2]), ) arrow = Arrow( fourier, FFT_diagram, buff=1.0, stroke_width=8 ) arrows = VGroup( arrow.copy().match_y(newton), arrow.copy().match_y(hamilton), arrow, ) self.play(LaggedStartMap(ShowCreation, arrows, lag_ratio=0.5, run_time=3)) self.wait() class MakeFunOfNextVideo(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("``Next part''...I've\\\\heard that before."), target_mode="sassy", index=2, added_anims=[LaggedStart( self.teacher.change("guilty"), self.students[0].change("sassy"), self.students[1].change("hesitant"), )] ) self.wait() self.teacher_says( OldTexText("Wait, for real\\\\this time!"), bubble_config={ "height": 3, "width": 3, }, target_mode="speaking", added_anims=[ self.students[0].change("hesitant"), ] ) self.wait(3) class Part1EndScroll(PatreonEndScreen): CONFIG = { "title_text": "", "scroll_time": 60, "show_pis": False, } class Thanks(Scene): def construct(self): morty = Mortimer(mode="happy") thanks = Text("Thank you") thanks.next_to(morty, LEFT) self.play( morty.change("gracious"), FadeIn(thanks, lag_ratio=0.1) ) for n in range(5): self.play(morty.animate.look([DL, DR][n % 2])) self.wait(random.random() * 5) self.play(Blink(morty)) class HolomorphicDynamics(Scene): def construct(self): self.ask_about_property() self.repeated_functions() def ask_about_property(self): back_plane = FullScreenRectangle() self.add(back_plane) image = ImageMobject("NewtonBoundaryProperty") border = SurroundingRectangle(image, buff=0) border.set_stroke(WHITE, 2) image = Group(border, image) image.set_height(FRAME_HEIGHT) image.generate_target() image.target.set_height(6) image.target.to_corner(DL) question = Text("Why is this true?") question.to_corner(UR) arrow = Arrow( question.get_left(), image.target.get_top() + RIGHT, path_arc=45 * DEGREES ) self.play( image.animate.set_height(6).to_corner(DL), Write(question), ShowCreation(arrow, rate_func=squish_rate_func(smooth, 0.5, 1), run_time=2) ) self.wait() title = self.title = Text("Holomorphic Dynamics", font_size=60) title.to_edge(UP) self.play( image.animate.set_height(1).to_corner(DL), FadeOut(question, shift=DL, scale=0.2), FadeOut(arrow, shift=DL, scale=0.2), FadeIn(title, shift=3 * DL, scale=0.5), FadeOut(back_plane), ) self.wait() self.image = image def repeated_functions(self): basic_expr = OldTex( "z", "\\rightarrow ", " f(z)" ) fz = basic_expr.get_part_by_tex("f(z)") basic_expr.next_to(self.title, DOWN, LARGE_BUFF) basic_expr.to_edge(LEFT, buff=LARGE_BUFF) brace = Brace(fz, DOWN) newton = OldTex("z - {P(z) \\over P'(z)}") newton.next_to(brace, DOWN) newton.align_to(basic_expr[1], LEFT) newton_example = OldTex("z - {z^3 + z - 1 \\over 3z^2 + 1}") eq = OldTex("=").rotate(PI / 2) eq.next_to(newton, DOWN) newton_example.next_to(eq, DOWN) newton_group = VGroup(newton, eq, newton_example) newton_group.generate_target() newton_group.target[1].rotate(-PI / 2) newton_group.target.arrange(RIGHT, buff=0.2) newton_group.target[2].shift(SMALL_BUFF * UP) newton_group.target.scale(0.7) newton_group.target.to_corner(DL) mandelbrot = OldTex("z^2 + c") mandelbrot.next_to(brace, DOWN) exponential = OldTex("a^z") exponential.next_to(brace, DOWN) self.play( FadeIn(basic_expr), FadeOut(self.image) ) self.wait() self.describe_holomorphic(fz, brace) self.wait() self.play( FadeIn(newton), ) self.play( FadeIn(eq), FadeIn(newton_example), ) self.wait() self.play( MoveToTarget(newton_group), FadeIn(mandelbrot, DOWN), ) self.wait() self.play( mandelbrot.animate.scale(0.7).next_to(newton, UP, LARGE_BUFF, LEFT), FadeIn(exponential, DOWN) ) self.wait() # Show fractals rhss = VGroup(exponential, mandelbrot, newton) f_eqs = VGroup() lhss = VGroup() for rhs in rhss: rhs.generate_target() if rhs is not exponential: rhs.target.scale(1 / 0.7) lhs = OldTex("f(z) = ") lhs.next_to(rhs.target, LEFT) f_eqs.add(VGroup(lhs, rhs.target)) lhss.add(lhs) f_eqs.arrange(RIGHT, buff=1.5) f_eqs.next_to(self.title, DOWN, MED_LARGE_BUFF) rects = ScreenRectangle().replicate(3) rects.arrange(DOWN, buff=0.5) rects.set_height(6.5) rects.next_to(ORIGIN, RIGHT, MED_LARGE_BUFF) rects.to_edge(DOWN, MED_SMALL_BUFF) rects.set_stroke(WHITE, 1) arrows = VGroup() for rect, f_eq in zip(rects, f_eqs): arrow = Vector(0.7 * RIGHT) arrow.next_to(rect, LEFT) arrows.add(arrow) f_eq.next_to(arrow, LEFT) self.play( LaggedStartMap(MoveToTarget, rhss), LaggedStartMap(Write, lhss), LaggedStartMap(FadeIn, rects), LaggedStartMap(ShowCreation, arrows), FadeOut(brace), basic_expr.animate.to_edge(UP), FadeOut(newton_group[1:]), ) self.wait() def describe_holomorphic(self, fz, brace): self.title.set_stroke(BLACK, 5, background=True) word = self.title.get_part_by_text("Holomorphic") underline = Underline(word, buff=-0.05) underline.scale(1.2) underline.insert_n_curves(40) underline.set_stroke(YELLOW, [1, *6 * [3], 1]) self.add(underline, self.title) self.play( word.animate.set_fill(YELLOW), ShowCreation(underline) ) in_words = Text("Complex\ninputs", font_size=36) in_words.to_corner(UL) in_arrow = Arrow( in_words.get_right(), fz[2].get_top(), path_arc=-80 * DEGREES, buff=0.2, ) VGroup(in_words, in_arrow).set_color(YELLOW) out_words = Text("Complex\noutputs", font_size=36) out_words.next_to(brace, DOWN) out_words.set_color(YELLOW) f_prime = OldTexText("$f'(z)$ exists") f_prime.set_color(YELLOW) f_prime.next_to(underline, DOWN, MED_LARGE_BUFF) f_prime.match_y(fz) self.wait() self.play( Write(in_words), ShowCreation(in_arrow), run_time=1, ) self.play( GrowFromCenter(brace), FadeIn(out_words, lag_ratio=0.05) ) self.wait() self.play(FadeIn(f_prime, 0.5 * DOWN)) self.wait() self.play( LaggedStartMap(FadeOut, VGroup( in_words, in_arrow, out_words, f_prime, underline, )), word.animate.set_fill(WHITE) ) class AmbientRepetition(Scene): n_steps = 30 def construct(self): plane = ComplexPlane((-2, 2), (-2, 2)) plane.set_height(FRAME_HEIGHT) plane.add_coordinate_labels(font_size=24) self.add(plane) font_size = 36 z0 = complex(0, 0) dot = Dot(color=BLUE) dot.move_to(plane.n2p(z0)) z_label = OldTex("z", font_size=font_size) z_label.set_stroke(BLACK, 5, background=True) z_label.next_to(dot, UP, SMALL_BUFF) self.add(dot, z_label) def func(z): return z**2 + complex(-0.6436875, -0.441) def get_new_point(): z = plane.p2n(dot.get_center()) return plane.n2p(func(z)) for n in range(self.n_steps): new_point = get_new_point() arrow = Arrow(dot.get_center(), new_point, buff=dot.get_height() / 2) dot_copy = dot.copy() dot_copy.move_to(new_point) dot_copy.set_color(YELLOW) fz_label = OldTex("f(z)", font_size=font_size) fz_label.set_stroke(BLACK, 8, background=True) fz_label.next_to(dot_copy, UP, SMALL_BUFF) self.add(dot, dot_copy, arrow, z_label) self.play( ShowCreation(arrow), TransformFromCopy(dot, dot_copy), FadeInFromPoint(fz_label, z_label.get_center()), ) self.wait(0.5) to_fade = VGroup( dot.copy(), z_label.copy(), dot_copy, arrow, fz_label, ) dot.move_to(dot_copy) z_label.next_to(dot, UP, SMALL_BUFF) self.remove(z_label) self.play( *map(FadeOut, to_fade), FadeIn(z_label), ) self.embed() class BriefMandelbrot(Scene): n_iterations = 30 def construct(self): self.add_plane() self.add_process_description() self.show_iterations() self.wait(10) # Time to play self.add_mandelbrot_image() def add_plane(self): plane = self.plane = ComplexPlane((-2, 1), (-2, 2)) plane.set_height(4) plane.scale(FRAME_HEIGHT / 2.307) plane.next_to(2 * LEFT, RIGHT, buff=0) plane.add_coordinate_labels(font_size=24) self.add(plane) def add_process_description(self): kw = { "tex_to_color_map": { "{c}": YELLOW, } } terms = self.terms = VGroup( OldTex("z_{n + 1} = z_n^2 + {c}", **kw), OldTex("z_0 = 0", **kw), OldTex("{c} \\text{ can be changed}", **kw), ) terms.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) terms.next_to(self.plane, LEFT, MED_LARGE_BUFF) self.add(terms) def show_iterations(self): plane = self.plane c0 = complex(-0.2, 0.95) c_dot = self.c_dot = Dot() c_dot.set_fill(YELLOW) c_dot.set_stroke(BLACK, 5, background=True) c_dot.move_to(plane.n2p(c0)) lines = VGroup() lines.set_stroke(background=True) def get_c(): return plane.p2n(c_dot.get_center()) def update_lines(lines): z1 = 0 c = get_c() new_lines = [] for n in range(self.n_iterations): try: z2 = z1**2 + c new_lines.append(Line( plane.n2p(z1), plane.n2p(z2), stroke_color=GREY, stroke_width=2, )) new_lines.append(Dot( plane.n2p(z2), fill_color=YELLOW, fill_opacity=0.5, radius=0.05, )) z1 = z2 except Exception: pass lines.set_submobjects(new_lines) update_lines(lines) self.add(lines[:2], c_dot) last_dot = Dot(plane.n2p(0)).scale(0) for line, dot in zip(lines[0:20:2], lines[1:20:2]): self.add(line, dot, c_dot) self.play( ShowCreation(line), TransformFromCopy(last_dot, dot) ) last_dot = dot self.remove(*lines) lines.add_updater(update_lines) self.add(lines, c_dot) def add_mandelbrot_image(self): image = ImageMobject("MandelbrotSet") image.set_height(FRAME_HEIGHT) image.shift(self.plane.n2p(-0.7) - image.get_center()) rect = FullScreenFadeRectangle() rect.set_fill(BLACK, 1) rect.next_to(self.plane, LEFT, buff=0) self.add(image, rect, *self.mobjects) self.play( FadeIn(image, run_time=2), self.plane.animate.set_opacity(0.5) ) def on_mouse_press(self, point, button, mods): # TODO, copy-pasted, should factor out super().on_mouse_press(point, button, mods) mob = self.point_to_mobject(point, search_set=[self.c_dot]) if mob is None: return self.mouse_drag_point.move_to(point) mob.add_updater(lambda m: m.move_to(self.mouse_drag_point)) self.unlock_mobject_data() self.lock_static_mobject_data() def on_mouse_release(self, point, button, mods): super().on_mouse_release(point, button, mods) self.c_dot.clear_updaters() class CyclicAttractor(RepeatedNewton): coefs = [2, -2, 0, 1] n_steps = 20 show_coloring = False def construct(self): super().construct() def add_plane(self): super().add_plane() self.plane.axes.set_stroke(GREY_B, 1) def add_labels(self): super().add_labels() eq = self.corner_group[1] self.play(FlashAround(eq, run_time=3)) def get_original_points(self): return [ (r * np.cos(theta), r * np.sin(theta), 0) for r in np.linspace(0, 0.2, 10) for theta in np.linspace(0, TAU, int(50 * r)) + TAU * np.random.random() ] class HighlightedJulia(IntroNewtonFractal): coefs = [-1.0, 0.0, 0.0, 1.0, 0.0, 1.0] def construct(self): # self.init_fractal(root_colors=ROOT_COLORS_DEEP[0::2]) self.init_fractal(root_colors=ROOT_COLORS_DEEP) fractal = self.fractal def get_height_ratio(): return self.camera.frame.get_height() / FRAME_HEIGHT fractal.set_colors(5 * [WHITE]) fractal.add_updater(lambda m: m.set_julia_highlight(get_height_ratio() * 1e-3)) fractal.set_n_steps(50) # self.play( # fractal.animate.set_julia_highlight(1e-3), # run_time=5 # ) # self.embed() class MontelCorrolaryScreenGrab(Scene): def construct(self): pass class MetaFractal(IntroNewtonFractal): fixed_roots = [-1, 1] z0 = complex(0.5, 0) n_steps = 200 def construct(self): colors = ROOT_COLORS_DEEP[0::2] self.plane_config["faded_line_ratio"] = 3 plane = self.get_plane() root_dots = self.root_dots = VGroup(*( Dot(plane.n2p(root), color=color) for root, color in zip(self.fixed_roots, colors) )) root_dots.set_stroke(BLACK, 3) fractal = MetaNewtonFractal( plane, fixed_roots=self.fixed_roots, colors=colors, n_steps=self.n_steps, ) fractal.add_updater(lambda f: f.set_fixed_roots([ plane.p2n(dot.get_center()) for dot in root_dots ])) self.add(fractal, plane) self.add(root_dots) point1 = np.array([1.62070862, 1.68700851, 0.]) point2 = np.array([0.81263967, 2.84042313, 0.]) height1 = 0.083 height2 = 0.035 frame = self.camera.frame frame.generate_target() frame.target.move_to(point1) frame.target.set_height(height1) self.play( MoveToTarget(frame), run_time=10, rate_func=bezier([0, 0, 1, 1]) ) self.wait() self.play( UpdateFromAlphaFunc( frame, lambda m, a: m.set_height( interpolate( interpolate(height1, 2, a), interpolate(2, height2, a), a, ), ).move_to( interpolate(point1, point2, a) ) ), run_time=10 ) class Thumbnail2(SimpleFractalScene): def construct(self): super().construct() fractal = self.fractal fractal.set_saturation_factor(4.5) self.remove(self.plane) self.remove(self.root_dots) frame = self.camera.frame frame.set_height(4) fc = fractal.copy() fc.set_saturation_factor(2) fc.set_julia_highlight(0.01) self.add(fc) # self.clear() # back = fractal.copy() # back.set_saturation_factor(0) # back.set_opacity(0.1) # self.add(back) # N = 20 # for x in np.linspace(np.log(1e-3), np.log(0.1), N): # jh = np.exp(x) # fc = fractal.copy() # fc.set_saturation_factor(1) # fc.set_julia_highlight(jh) # fc.set_opacity(2 / N) # self.add(fc) self.embed()
from manim_imports_ext import * class RandomChordScene(Scene): title = "" radius = 3.5 n_samples = 1000 long_color = BLUE short_color = WHITE chord_width = 0.5 chord_opacity = 0.35 run_time = 20 include_triangle = True def construct(self): circle = self.circle = Circle(radius=self.radius) circle.set_stroke(GREY_B, 3) circle.to_edge(LEFT) chords = self.get_chords(circle) flash_chords = chords.copy() flash_chords.set_stroke(width=3, opacity=1) indicators = Group(*map(self.get_method_indicator, chords)) title = Text(self.title) title.set_x(FRAME_WIDTH / 4).to_edge(UP) triangle = self.get_triangle(circle) if not self.include_triangle: triangle.set_opacity(0) self.add(circle, title, triangle) for s, rt in (slice(0, 16), 8), (slice(18, None), self.run_time): fraction = self.get_fraction([c.long for c in chords[s]]) fraction.match_x(title) fraction.match_y(circle) self.add(fraction) self.remove(triangle) self.play( ShowIncreasingSubsets(chords[s]), ShowSubmobjectsOneByOne(flash_chords[s]), ShowSubmobjectsOneByOne(indicators[s]), Animation(triangle), fraction.alpha_update, rate_func=linear, run_time=rt, ) self.remove(flash_chords) self.remove(indicators) self.remove(fraction) self.add(fraction) self.wait() def get_fraction(self, data): tex = OldTex( "{100", "\\over ", "100", "+", "100}", "= ", "0.500" ) nl1 = Integer(100, edge_to_fix=ORIGIN) # Number of long chords nl2 = Integer(100, edge_to_fix=RIGHT) ns = Integer(100, edge_to_fix=LEFT) # Number of short chords ratio = DecimalNumber(0, num_decimal_places=4) fraction = VGroup( nl1.move_to(tex[0]), tex[1], nl2.move_to(tex[2]), tex[3], ns.move_to(tex[4]), tex[5], ratio.move_to(tex[6], LEFT), ) def update_fraction(frac, alpha): subdata = data[:int(np.floor(alpha * len(data)))] n_long = sum(subdata) n_short = len(subdata) - n_long frac[0].set_value(n_long) frac[0].set_color(self.long_color) frac[2].set_value(n_long) frac[2].set_color(self.long_color) frac[4].set_value(n_short) frac[4].set_color(self.short_color) if len(subdata) == 0: frac[-2:].set_opacity(0) else: frac[-2:].set_opacity(1) frac[6].set_value(n_long / len(subdata)) return frac fraction.alpha_update = UpdateFromAlphaFunc( fraction, update_fraction ) return fraction def get_chords(self, circle, chord_generator=None): if chord_generator is None: chord_generator = self.get_random_chord tri_len = np.sqrt(3) * circle.get_width() / 2 chords = VGroup(*( chord_generator(circle) for x in range(self.n_samples) )) for chord in chords: chord.long = (chord.get_length() > tri_len) chord.set_color( self.long_color if chord.long else self.short_color ) chords.set_stroke( width=self.chord_width, opacity=self.chord_opacity ) return chords def get_triangle(self, circle): verts = [circle.pfp(a) for a in np.arange(0, 1, 1 / 3)] triangle = Polygon(*verts) triangle.rotate(-PI / 6, about_point=circle.get_center()) triangle.set_stroke(RED, 2, 1) return triangle def get_random_chord(self, circle): return NotImplemented def get_method_indicator(self, chord): return NotImplemented class PairOfPoints(RandomChordScene): title = "Random pair of circle points" @staticmethod def get_random_chord(circle): return Line( circle.pfp(random.random()), circle.pfp(random.random()), ) @staticmethod def get_method_indicator(chord): dots = DotCloud([ chord.get_start(), chord.get_end(), ]) dots.set_glow_factor(2) dots.set_radius(0.25) dots.set_color(YELLOW) return dots class CenterPoint(RandomChordScene): title = "Random point in circle" @staticmethod def get_random_chord(circle): x = y = 1 while x * x + y * y > 1: x = random.uniform(-1, 1) y = random.uniform(-1, 1) return CenterPoint.chord_from_xy(x, y, circle) @staticmethod def chord_from_xy(x, y, circle): n2 = x * x + y * y temp_x = math.sqrt(n2) temp_y = math.sqrt(1 - n2) line = Line( [temp_x, -temp_y, 0], [temp_x, temp_y, 0], ) line.rotate(angle_of_vector([x, y, 0]), about_point=ORIGIN) line.scale(circle.get_width() / 2, about_point=ORIGIN) line.shift(circle.get_center()) return line @staticmethod def get_method_indicator(chord): dots = DotCloud([chord.get_center()]) dots.set_glow_factor(2) dots.set_radius(0.25) dots.set_color(YELLOW) return dots class RadialPoint(CenterPoint): title = "Random point along radial line" @staticmethod def get_random_chord(circle): angle = random.uniform(0, TAU) dist = random.uniform(0, 1) return CenterPoint.chord_from_xy( dist * math.cos(angle), dist * math.sin(angle), circle ) @staticmethod def get_method_indicator(chord): dot = super().get_method_indicator(chord) line = Line(self.circle.get_center(), dot.get_center()) line.set_length(self.radius, about_point=line.get_start()) line.set_stroke(YELLOW, 1) return Group(dot, line) class CompareFirstTwoMethods(RandomChordScene): chord_width = 0.1 chord_opacity = 0.8 def construct(self): circles = Circle().get_grid(1, 2, buff=1) circles.set_height(5) circles.to_edge(DOWN, buff=LARGE_BUFF) circles.set_stroke(GREY_B, 3) titles = VGroup( Text("Choose a pair of points"), Text("Chose a center point"), ) for title, circle in zip(titles, circles): title.next_to(circle, UP, MED_LARGE_BUFF) chord_groups = VGroup( self.get_chords(circles[0], PairOfPoints.get_random_chord), self.get_chords(circles[1], CenterPoint.get_random_chord), ) flash_chord_groups = chord_groups.copy() flash_chord_groups.set_stroke(width=3, opacity=1) indicator_groups = Group( Group(*(PairOfPoints.get_method_indicator(c) for c in chord_groups[0])), Group(*(CenterPoint.get_method_indicator(c) for c in chord_groups[1])), ) self.add(circles, titles) self.play( *map(ShowIncreasingSubsets, chord_groups), *map(ShowSubmobjectsOneByOne, flash_chord_groups), *map(ShowSubmobjectsOneByOne, indicator_groups), rate_func=linear, run_time=15, ) self.play( *map(FadeOut, ( flash_chord_groups[0][-1], flash_chord_groups[1][-1], indicator_groups[0][-1], indicator_groups[1][-1], )), ) self.wait() class SparseWords(Scene): def construct(self): words = Text("Sparser in the middle") words.to_edge(DOWN, buff=MED_LARGE_BUFF) arrow = Arrow( words.get_top(), [3.5, -0.5, 0], ) arrow.set_color(YELLOW) words.set_color(YELLOW) self.play( Write(words, run_time=1), ShowCreation(arrow), ) self.wait() class PortionOfRadialLineInTriangle(Scene): def construct(self): # Circle and triangle circle = Circle(radius=3.5) circle.set_stroke(GREY_B, 4) circle.rotate(-PI / 6) triangle = Polygon(*( circle.pfp(a) for a in np.arange(0, 1, 1 / 3) )) triangle.set_stroke(GREEN, 2) center_dot = Dot(circle.get_center().copy(), radius=0.04) center_dot.set_fill(GREY_C, 1) self.add(circle, center_dot, triangle) # Radial line radial_line = Line(circle.get_center().copy(), circle.pfp(1 / 6)) radial_line.set_stroke(WHITE, 2) elbow = Elbow() elbow.rotate(PI + radial_line.get_angle(), about_point=ORIGIN) elbow.shift(radial_line.pfp(0.5) - ORIGIN) elbow.match_style(radial_line) half_line = radial_line.copy() half_line.pointwise_become_partial(radial_line, 0, 0.5) half_line.set_stroke(RED, 2) half_label = OldTex("\\frac{1}{2}", font_size=30) half_label.next_to(half_line.get_center(), DR, SMALL_BUFF) half_label.set_color(RED) self.play(ShowCreation(radial_line)) self.play(ShowCreation(elbow)) self.wait() self.play( ShowCreation(half_line), FadeIn(half_label, 0.2 * DOWN), ) # Show sample chords along line dot = TrueDot() dot.set_glow_factor(5) dot.set_radius(0.5) dot.set_color(YELLOW) dot.move_to(radial_line.pfp(0.1)) circle.rotate(PI / 6) def get_chord(): p = dot.get_center().copy() p /= (circle.get_width() / 2) chord = CenterPoint.chord_from_xy(p[0], p[1], circle) chord.set_stroke(BLUE, 4) return chord chord = always_redraw(get_chord) self.play( FadeIn(dot), GrowFromCenter(chord) ) self.wait() for alpha in (0.5, 0.01, 0.4): self.play( dot.animate.move_to(radial_line.pfp(alpha)), run_time=4, ) self.add(dot) # Embed self.embed() class RandomPointsFromVariousSpaces(Scene): def construct(self): # Interval interval = UnitInterval() interval.add_numbers() top_words = OldTexText("Choose a random$^{*}$ ", "number between 0 and 1") top_words.to_edge(UP) subwords = OldTexText( "($^{*}$Implicitly: According to a \\emph{uniform} distribution)", color=GREY_A, tex_to_color_map={"\\emph{uniform}": YELLOW}, font_size=36 ) subwords.next_to(top_words, DOWN, buff=MED_LARGE_BUFF) dots = DotCloud([ interval.n2p(random.random()) for x in range(100) ]) dots.set_radius(0.5) dots.set_glow_factor(10) dots.set_color(YELLOW) dots.add_updater(lambda m: m) turn_animation_into_updater( ShowCreation(dots, rate_func=linear, run_time=10) ) self.add(interval, dots) self.play(Write(top_words, run_time=1)) self.wait(2) self.play(FadeIn(subwords, 0.5 * DOWN)) self.wait(6) # Circle circle = Circle() circle.set_stroke(BLUE, 2) circle.set_height(5) circle.next_to(subwords, DOWN, buff=MED_LARGE_BUFF) dots.clear_updaters() dots.generate_target(use_deepcopy=True) dots.target.set_points([ circle.pfp(interval.p2n(p)) for p in dots.get_points() ]) dots.target.set_radius(0) circle_words = Text("point on a circle") circle_words.move_to(top_words[1], UL) circle_words.set_color(BLUE) top_words[0].generate_target() VGroup(top_words[0].target, circle_words).set_x(0) self.play( MoveToTarget(dots, run_time=1), TransformFromCopy( Line(interval.n2p(0), interval.n2p(1)).set_stroke(GREY_B, 1), circle, run_time=1, ), FadeOut(interval), FadeOut(top_words[1], UP), FadeIn(circle_words, UP), MoveToTarget(top_words[0]), ) dots.set_points([ circle.pfp(random.random()) for x in range(25) ]) dots.set_radius(0.5) dots.set_glow_factor(5) dots.add_updater(lambda m: m) self.add(dots) self.play(ShowCreation(dots, rate_func=linear, run_time=2)) # Sphere sphere_words = Text("point on a sphere") sphere_words.move_to(circle_words, LEFT) sphere_words.set_color(BLUE) sphere = Sphere() sphere.set_color(BLUE_D) sphere.set_opacity(0.5) sphere.set_shadow(0.5) sphere.set_gloss(0.5) sphere.set_reflectiveness(0.5) sphere.replace(circle) sphere.rotate(0.05 * PI) sphere.rotate(0.4 * PI, LEFT) sphere.sort_faces_back_to_front() mesh = SurfaceMesh(sphere) mesh.set_stroke(WHITE, 1, 0.5) self.play( FadeOut(dots), FadeOut(circle, run_time=2), ShowCreation(sphere, run_time=2), ShowCreation(mesh, lag_ratio=0.1, run_time=2), FadeOut(circle_words, UP), FadeIn(sphere_words, UP), ) dots.set_points([ random.choice(sphere.get_points()) for x in range(100) ]) dots.set_radius(0.25) self.play(ShowCreation(dots, run_time=10, rate_func=linear)) # Ambiguity underline = Underline( subwords.get_part_by_tex("uniform"), buff=0 ) underline.set_stroke(YELLOW, width=[0, 2, 2, 2, 0]) underline.scale(1.25) underline.insert_n_curves(50) question = Text("Is this well-defined?") question.to_edge(RIGHT).shift(UP) arrow = Arrow(underline, question, buff=0.1) arrow.set_color(YELLOW) turn_animation_into_updater( ShowCreation(dots, run_time=10, rate_func=lambda t: 0.5 + 0.5 * t), ) dots.clear_updaters() dots.set_points(dots.get_points()[12:16]) dots.set_radius(0.5) dots.add_updater(lambda m: m) self.play( ShowCreation(underline), ShowCreation(arrow), FadeIn(question, shift=0.5 * DR), ShowCreation(dots, run_time=4, rate_func=linear) ) self.wait() class CoinFlips(Scene): CONFIG = { "random_seed": 2, } def construct(self): n_rows = 15 n_cols = 40 heads = [bool(random.randint(0, 1)) for x in range(n_rows * n_cols)] coins = VGroup(*(self.get_coin(h) for h in heads)) coins.arrange_in_grid(n_rows, n_cols, buff=SMALL_BUFF) coins.set_width(FRAME_WIDTH - 0.5) coins.to_edge(DOWN) eq = OldTex( "{\\# \\text{Heads} \\over \\# \\text{Flips}} = ", "{Num \\over Den}", "=", "0.500", isolate={"Num", "Den", "\\# \\text{Heads}"} ) eq.set_color_by_tex("Heads", RED) num = Integer(100, edge_to_fix=ORIGIN) den = Integer(100, edge_to_fix=ORIGIN) dec = DecimalNumber(0.5, num_decimal_places=3, edge_to_fix=LEFT) num_i = eq.index_of_part_by_tex("Num") den_i = eq.index_of_part_by_tex("Den") dec_i = eq.index_of_part_by_tex("0.500") num.replace(eq[num_i], dim_to_match=1) den.replace(eq[den_i], dim_to_match=1) dec.replace(eq[dec_i], dim_to_match=1) eq.replace_submobject(num_i, num) eq.replace_submobject(den_i, den) eq.replace_submobject(dec_i, dec) eq.to_edge(UP) def update_eq(eq, alpha): n_flips = max(int(alpha * len(heads)), 1) n_heads = sum(heads[:n_flips]) num.set_value(n_heads).set_color(RED) den.set_value(n_flips) dec.set_value(n_heads / n_flips) return eq for sm in eq: sm.add_updater(lambda m: m) words = OldTexText("What does\\\\this approach?", font_size=36) words.to_corner(UR) arrow = Arrow(words, dec) VGroup(words, arrow).set_color(YELLOW) self.add(coins, *eq) srf = squish_rate_func(smooth, 0.3, 0.4) self.play( ShowIncreasingSubsets(coins, rate_func=linear), UpdateFromAlphaFunc(Mobject(), update_eq, rate_func=linear), Write(words, rate_func=srf), ShowCreation(arrow, rate_func=srf), run_time=18 ) self.wait(2) def get_coin(self, heads=True, radius=0.25): circle = Dot(radius=radius) circle.set_fill(RED_E if heads else BLUE_E) circle.set_stroke(WHITE, 0.5, 0.5) symbol = OldTex("H" if heads else "T") symbol.set_height(radius) symbol.move_to(circle) return VGroup(circle, symbol) class ChordsInSpaceWithCircle(RandomChordScene): def construct(self): # Introduce chords n_lines = 500 big_circle = Circle(radius=FRAME_WIDTH + FRAME_HEIGHT) lines = VGroup(*( RadialPoint.get_random_chord(big_circle) for x in range(n_lines) )) lines.set_stroke(WHITE, 0.5, 0.5) circle = Circle(radius=2) circle.set_stroke(WHITE, 2) triangle = Polygon(*(circle.pfp(a) for a in np.arange(0, 1, 1 / 3))) triangle.rotate(-PI / 6, about_point=circle.get_center()) triangle.set_stroke(YELLOW, 3) triangle = VGroup( triangle.copy().set_stroke(BLACK, 8), triangle.copy(), ) self.play(Write(lines, lag_ratio=(1 / n_lines), run_time=6)) self.wait() def get_chords(): return VGroup(*( self.line_to_chord(line, circle) for line in lines )) chords = get_chords() chords.save_state(RED) chords.set_stroke(WHITE, 1) self.play( ShowCreation(circle), VFadeIn(chords), ) self.wait() self.play(ShowCreation(triangle, lag_ratio=0)) circle.add(triangle) self.wait() # Show colors key = OldTexText( "Blue $\\Rightarrow$ Chord > \\text{Triangle side}\\\\" "Red $\\Rightarrow$ Chord < \\text{Triangle side}\\\\", tex_to_color_map={ "Blue": BLUE, "Red": RED, } ) key.to_edge(UP) key.set_backstroke(width=5) key[len(key) // 2:].align_to(key[:len(key) // 2], RIGHT) self.play( Restore(chords), FadeIn(key), ) self.wait(2) # Move around chords.add_updater(lambda m: m.become(get_chords())) self.add(chords, circle) self.play(circle.animate.to_edge(RIGHT), run_time=6) self.play(circle.animate.to_edge(LEFT), run_time=6) self.wait() self.play( circle.animate.set_height(7, about_edge=LEFT), FadeOut(key, rate_func=squish_rate_func(smooth, 0, 0.5)), run_time=4 ) self.play(circle.animate.set_height(4, about_edge=RIGHT), run_time=4) # Show center point method big_circle = Circle(radius=3.25) big_circle.set_stroke(GREY_B, 2) big_circle.to_edge(DOWN) title = Text("Random center point method") title.to_edge(UP, buff=MED_SMALL_BUFF) chords.clear_updaters() self.play( FadeOut(chords), FadeOut(lines), FadeIn(big_circle), FadeIn(title), circle.animate.set_height(0.5).to_corner(DR), ) triangle.set_stroke(width=2) n_lines = 1000 lines.become(VGroup(*( CenterPoint.get_random_chord(big_circle) for x in range(n_lines) ))) lines.set_stroke(WHITE, self.chord_width, self.chord_opacity) flash_lines = lines.copy() flash_lines.set_stroke(width=3, opacity=1) indicators = Group(*map(CenterPoint.get_method_indicator, lines)) self.play( ShowIncreasingSubsets(lines), ShowSubmobjectsOneByOne(flash_lines), ShowSubmobjectsOneByOne(indicators), rate_func=linear, run_time=8, ) self.play( FadeOut(indicators[-1]), FadeOut(flash_lines[-1]), ) self.wait() # Put circle back inside self.play( circle.animate.set_height(2).move_to(big_circle), run_time=1 ) chords.become(get_chords().set_stroke(opacity=0.7)) self.add(chords, circle) self.play(VFadeIn(chords)) self.wait() chords.add_updater(lambda m: m.become(get_chords().set_stroke(opacity=0.7))) self.play( circle.animate.move_to(big_circle, RIGHT), run_time=10, rate_func=there_and_back, ) self.wait() def line_to_chord(self, line, circle, stroke_width=1): r = circle.get_radius() tangent = normalize(line.get_vector()) normal = rotate_vector(tangent, PI / 2) center = circle.get_center() d1 = np.dot(line.get_start() - center, normal) if d1 > r: return VectorizedPoint(center + r * normal) d2 = np.sqrt(r**2 - d1**2) chord = Line( center + d1 * normal - d2 * tangent, center + d1 * normal + d2 * tangent, ) chord.set_stroke( (BLUE if chord.get_length() > math.sqrt(3) * r else RED), width=stroke_width, ) return chord class TransitiveSymmetries(Scene): def construct(self): circle = Circle(radius=3) circle.set_stroke(GREY_B, 2) circle.rotate(PI / 2) dots = DotCloud([circle.pfp(a) for a in np.linspace(0, 1, 49)]) dots.set_glow_factor(5) dots.set_radius(0.5) dots.set_color(WHITE) dots.set_opacity(0.5) dot = dots.copy() dot.set_points([dots.get_points()[0]]) dot.set_color(YELLOW) dot.set_opacity(1) top_words = Text("By acting on any one point...") top_words.match_x(dot) top_words.to_edge(UP, buff=MED_SMALL_BUFF) low_words = Text("...you can map\nto any other") low_words.to_edge(RIGHT).shift(2 * DOWN) self.add(circle, top_words, dot) dots.add_updater(lambda m: m) self.play( Rotate( Group(circle, dot), TAU, about_point=circle.get_center(), ), ShowCreation( dots, rate_func=lambda a: smooth(a * (1 - 1 / 48) + 1 / 48) ), Write(low_words, rate_func=squish_rate_func(smooth, 0.3, 0.5)), run_time=10, ) class NonTransitive(Scene): def construct(self): circle = Circle(radius=3) circle.set_stroke(GREY_B, 2) words = OldTexText( "Rotational symmetries do \\emph{not} act\\\\" "transitively on the space of all chords", tex_to_color_map={"\\emph{not}": RED}, ) words.to_edge(UP, MED_SMALL_BUFF) circle.next_to(words, DOWN, MED_SMALL_BUFF) chord1 = Line(circle.pfp(0.4), circle.pfp(0.5)) chord1.set_stroke(RED, 3) chord1_shadow = chord1.copy().set_stroke(opacity=0.5) chord2 = Line(circle.pfp(0.8), circle.pfp(0.25)) chord2.set_stroke(BLUE, 3) left_words = Text("No action on\nthis chord...") right_words = Text("...will ever map\nto this chord.") left_words.to_edge(LEFT).shift(UP) right_words.to_edge(RIGHT).shift(DOWN) left_arrow = Arrow(left_words, chord1.get_center(), buff=0.1) right_arrow = Arrow(right_words.get_left(), chord2.get_center(), buff=0.1) VGroup(left_words, left_arrow).set_color(RED) VGroup(right_words, right_arrow).set_color(BLUE) chords = VGroup(*( RadialPoint.get_random_chord(circle) for x in range(100) )) chords.set_stroke(WHITE, 1, 0.5) group = VGroup(circle, chords) self.add(words) self.play( Rotate(group, TAU, about_point=circle.get_center(), run_time=6) ) self.wait() self.add(chord1_shadow, chord1) self.play( FadeOut(chords), ShowCreation(chord1_shadow), ShowCreation(chord1), FadeIn(left_words), ShowCreation(left_arrow), ) group = VGroup(circle, chord1) self.add(group, left_arrow) self.play( Rotate( group, TAU, about_point=circle.get_center(), ), FadeIn( VGroup(right_words, right_arrow, chord2), rate_func=squish_rate_func(smooth, 0.3, 0.4), ), run_time=10, ) # Embed self.embed() class RandomSpherePoint(Scene): def construct(self): # Setup frame = self.camera.frame frame.reorient(-20, 70) frame.add_updater(lambda m, dt: m.increment_theta(0.015 * dt)) grid = NumberPlane( (-6, 6), (-4, 4), background_line_style={ "stroke_color": GREY_B, "stroke_width": 1, "stroke_opacity": 0.5, }, axis_config={ "stroke_width": 1, } ) grid.scale(2) plane = Rectangle() plane.set_stroke(width=0) plane.set_gloss(0.5) plane.set_fill(GREY_C, 0.5) plane.replace(grid, stretch=True) plane.add(grid) plane.shift(2 * IN) self.add(plane) sphere_radius = 2 sphere = Sphere(radius=sphere_radius) sphere.set_color(BLUE_E) sphere.set_opacity(1.0) sphere.move_to(1.5 * OUT) mesh = SurfaceMesh(sphere) mesh.set_stroke(width=0.5, opacity=0.5) mesh.apply_depth_test() mesh_shadow = mesh.copy().set_stroke(opacity=0.1) mesh_shadow.deactivate_depth_test() sphere = Group(sphere, mesh, mesh_shadow) self.add(*sphere) # Random point words = OldTexText("Choose a random$^{*}$\\\\point on a sphere") words.fix_in_frame() words.to_corner(UL) technicality = OldTexText( "$^{*}$From a distribution that's\\\\", "invariant under rotational symmetries.", font_size=30 ) technicality[1].set_color(YELLOW) technicality.fix_in_frame() technicality.to_corner(UR) technicality.to_edge(RIGHT, buff=MED_SMALL_BUFF) def random_sphere_point(): p = [1, 1, 1] while get_norm(p) > 1: p = np.random.uniform(-1, 1, 3) p = sphere_radius * normalize(p) return p + sphere.get_center() dot = TrueDot() dot.set_radius(0.5) dot.set_color(YELLOW) dot.set_glow_factor(5) dot.move_to(random_sphere_point()) self.add(words) dot.set_radius(0) self.play(dot.animate.set_radius(0.5)) for x in range(11): dot.move_to(random_sphere_point()) dot.set_opacity(random.choice([0.25, 1.0])) if x == 5: self.play(FadeIn(technicality), run_time=0.5) else: self.wait(0.5) self.play(FadeOut(dot)) # Little patch band = sphere[0].copy() band.pointwise_become_partial(sphere[0], 0.7, 0.8) patch = band.copy() patch.pointwise_become_partial(band, 0.7, 0.75, axis=0) patch.set_color(TEAL) patch.set_opacity(0.8) patch.deactivate_depth_test() dot.move_to(patch) def show_dots_in_patch(n=2000): dots = DotCloud([ random_sphere_point() for x in range(n) ]) dots.set_color(WHITE) dots.set_radius(0.02) dots.set_glow_factor(1) dots.set_opacity([ 0.25 if point[1] > 0 else 1.0 for point in dots.get_points() ]) dots.add_updater(lambda m: m) self.play(ShowCreation(dots, run_time=6, rate_func=linear)) self.wait() self.play(FadeOut(dots)) self.play(GrowFromCenter(patch)) self.wait() show_dots_in_patch() self.wait() # patch_copy = patch.copy() self.play(*( Rotate( sm, PI / 3, axis=OUT + RIGHT, about_point=sphere.get_center(), run_time=2, ) for sm in (*sphere, patch) )) show_dots_in_patch() self.wait() # Embed self.embed() class CorrectionInsert(Scene): def construct(self): # Words title = OldTexText("Looking for an unambiguous ``uniform'' distribution?") title.to_edge(UP, buff=0.25) kw = dict( # font_size=36, # color=GREY_A, t2c={"compact": YELLOW, "transitively": BLUE}, t2s={"compact": ITALIC}, ) conditions = VGroup( Text("1) Find a symmetry which acts transitively", **kw), Text("2) The space must be compact", **kw), ) conditions.arrange(DOWN, aligned_edge=LEFT) conditions.next_to(title, DOWN, MED_LARGE_BUFF) conditions.to_edge(UP) # Add shapes radius = 1.5 interval = UnitInterval(width=4) interval.add_numbers([0, 0.5, 1.0], num_decimal_places=1) circle = Circle(radius=radius) circle.set_stroke(GREY_B, 2) sphere = Sphere(radius=radius) sphere.set_color(BLUE_D, 1) sphere.set_opacity(0.5) mesh = SurfaceMesh(sphere) mesh.set_stroke(width=0.5) mesh_shadow = mesh.copy().set_stroke(opacity=0.35) sphere_group = Group(mesh_shadow, sphere, mesh) sphere_group.rotate(80 * DEGREES, LEFT) sphere_group.rotate(2.5 * DEGREES, OUT) sphere.sort_faces_back_to_front() shapes = Group(interval, circle, sphere_group) shapes.arrange(RIGHT, buff=LARGE_BUFF) shapes.set_y(-1) # Dots interval_dots = DotCloud([interval.pfp(random.random()) for n in range(100)]) circle_dots = DotCloud([circle.pfp(random.random()) for n in range(100)]) sphere_dots = DotCloud([ sphere.pfp(math.acos(random.random()) / PI) for n in range(300) ]) all_dots = Group(interval_dots, circle_dots, sphere_dots) for dots in all_dots: dots.set_glow_factor(5) dots.set_radius(0.1) dots.set_color(YELLOW) dots.add_updater(lambda m: m) sphere_dots.set_opacity(np.random.choice([1, 0.2], sphere_dots.get_num_points())) circle_dots.set_radius(0.15) # Animations self.add(conditions[0]) self.add(shapes) self.add(*dots) self.play(*(ShowCreation(dots, rate_func=linear, run_time=15) for dots in all_dots)) self.wait(4) self.play(Write(conditions[1][:2])) self.wait(2) self.play(Write(conditions[1][2:])) self.wait() # Compact rects = Rectangle(height=4.75, width=6).get_grid(1, 2, buff=0.5) rects.set_stroke(GREY, 1) rects.to_edge(DOWN) rect_titles = VGroup(Text("Compact"), Text("Not compact")) for rt, r, color in zip(rect_titles, rects, [YELLOW, RED]): rt.scale(0.7) rt.next_to(r, UP, buff=SMALL_BUFF) rt.set_color(color) compact_spaces = Group( Group(interval, interval_dots), Group(circle, circle_dots), Group(*sphere_group, sphere_dots) ) compact_spaces.generate_target() compact_spaces.target.arrange(DOWN) compact_spaces.target.set_height(0.9 * rects[0].get_height()) compact_spaces.target.move_to(rects[0]) movers = [] for cs, cst in zip(compact_spaces, compact_spaces.target): for m, mt in zip(cs, cst): m.generate_target() m.target.replace(mt) movers.append(m) self.play( *map(MoveToTarget, movers), *map(ShowCreation, rects), *map(FadeIn, rect_titles), ) self.wait() # Non-compact reals = NumberLine((-5, 5), include_tip=True) reals.ticks.remove(reals.ticks[0]) reals.add(reals.copy().flip()) reals.add_numbers(font_size=20) reals.set_width(0.9 * rects[1].get_width()) reals.next_to(rects[1].get_top(), DOWN, buff=LARGE_BUFF) reals_label = Text("Real number line", font_size=30) reals_label.next_to(reals, UP, SMALL_BUFF) plane = Square(4) plane.set_stroke(width=0) plane.set_fill(GREY_D, 1) plane.set_gloss(0.5) plane.set_reflectiveness(0.4) arrows = VGroup(*( Arrow(v, 2 * v, stroke_width=2) for v in compass_directions(8) )) group = VGroup(plane, arrows) group.rotate(80 * DEGREES, LEFT) group.set_width(4.5) group.next_to(reals, DOWN, buff=1.5) group.shift(0.25 * LEFT) self.play( ShowCreation(reals), FadeIn(reals_label), ) self.wait() self.play( GrowFromCenter(plane), *map(ShowCreation, arrows), ) self.wait(3)
from manim_imports_ext import * def q_mult(q1, q2): w1, x1, y1, z1 = q1 w2, x2, y2, z2 = q2 w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2 x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2 y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2 z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2 return np.array([w, x, y, z]) 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 stereo_project(mobject, axis=0, r=1, outer_r=10, **kwargs): epsilon = 1 for submob in mobject.family_members_with_points(): points = submob.get_points() n = len(points) for i in range(n): if points[i, axis] == -r: js = it.chain( range(i + 1, n), range(i - 1, -1, -1) ) for j in js: if points[j, axis] == -r: continue else: vect = points[j] - points[i] points[i] += epsilon * vect break submob.apply_function( lambda p: stereo_project_point(p, axis, r, **kwargs) ) # If all points are outside a certain range, this # shouldn't be displayed norms = np.apply_along_axis(get_norm, 1, submob.get_points()) if np.all(norms > outer_r): # TODO, instead set opacity? # submob.get_points()[:, :] = 0 submob.set_fill(opacity=0) submob.set_stroke(opacity=0) return mobject class Linus(VGroup): CONFIG = { "body_config": { "stroke_width": 15, "stroke_color": GREY_B, "sheen": 0.4, }, "height": 2, } def __init__(self, **kwargs): VGroup.__init__(self, **kwargs) self.body = self.get_body_line() self.eyes = Eyes(self.body) self.add(self.body, self.eyes) self.set_height(self.height) self.center() def change_mode(self, mode, thing_to_look_at=None): self.eyes.change_mode(mode, thing_to_look_at) if mode == "sad": self.become_squiggle() elif mode == "confused": self.become_squiggle(factor=-0.1) elif mode == "pleading": self.become_squiggle(factor=0.3) else: self.become_line() return self def change(self, *args, **kwargs): self.change_mode(*args, **kwargs) return self def look_at(self, thing_to_look_at=None): self.eyes.look_at(thing_to_look_at) return self def blink(self): self.eyes.blink() return self def get_squiggle(self, factor=0.2): sine_curve = FunctionGraph( lambda x: factor * np.sin(x), x_min=0, x_max=TAU, ) sine_curve.rotate(TAU / 4) sine_curve.match_style(self.body) sine_curve.match_height(self.body) sine_curve.move_to(self.body, UP) return sine_curve def get_body_line(self, **kwargs): config = dict(self.body_config) config.update(kwargs) line = Line(ORIGIN, 1.5 * UP, **config) if hasattr(self, "body"): line.match_style(self.body) line.match_height(self.body) line.move_to(self.body, UP) return line def become_squiggle(self, **kwargs): self.body.become(self.get_squiggle(**kwargs)) return self def become_line(self, **kwargs): self.body.become(self.get_body_line(**kwargs)) return self def copy(self): return self.deepcopy() class Felix(PiCreature): CONFIG = { "color": GREEN_D } class PushPin(SVGMobject): CONFIG = { "file_name": "push_pin", "height": 0.5, "sheen": 0.7, "fill_color": GREY, } def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) self.rotate(20 * DEGREES) def pin_to(self, point): self.move_to(point, DR) class Hand(SVGMobject): CONFIG = { "file_name": "pinch_hand", "height": 0.5, "sheen": 0.2, "fill_color": ORANGE, } def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) # self.rotate(30 * DEGREES) self.add(VectorizedPoint().next_to(self, UP, buff=0.17)) class CheckeredCircle(Circle): CONFIG = { "n_pieces": 16, "colors": [BLUE_E, BLUE_C], "stroke_width": 5, } def __init__(self, **kwargs): Circle.__init__(self, **kwargs) pieces = self.get_pieces(self.n_pieces) self.set_points(np.zeros((0, 3))) self.add(*pieces) n_colors = len(self.colors) for i, color in enumerate(self.colors): self[i::n_colors].set_color(color) class StereoProjectedSphere(Sphere): CONFIG = { "stereo_project_config": { "axis": 2, }, "max_r": 32, "max_width": FRAME_WIDTH, "max_height": FRAME_WIDTH, "max_depth": FRAME_WIDTH, "radius": 1, } def __init__(self, rotation_matrix=None, **kwargs): digest_config(self, kwargs) if rotation_matrix is None: rotation_matrix = np.identity(3) self.rotation_matrix = rotation_matrix self.stereo_project_config["r"] = self.radius ParametricSurface.__init__( self, self.post_projection_func, **kwargs ) self.submobjects.sort( key=lambda m: -m.get_width() ) self.fade_far_out_submobjects() def post_projection_func(self, u, v): point = self.radius * Sphere.func(self, u, v) rot_point = np.dot(point, self.rotation_matrix.T) result = stereo_project_point( rot_point, **self.stereo_project_config ) epsilon = 1e-4 if np.any(np.abs(result) == np.inf) or np.any(np.isnan(result)): return self.func(u + epsilon, v) return result def fade_far_out_submobjects(self, **kwargs): max_r = kwargs.get("max_r", self.max_r) max_width = kwargs.get("max_width", self.max_width) max_height = kwargs.get("max_height", self.max_height) max_depth = kwargs.get("max_depth", self.max_depth) for submob in self.submobjects: violations = [ np.any(np.apply_along_axis(get_norm, 1, submob.get_anchors()) > max_r), submob.get_width() > max_width, submob.get_height() > max_height, submob.get_depth() > max_depth ] if any(violations): # self.remove(submob) submob.fade(1) return self class StereoProjectedSphereFromHypersphere(StereoProjectedSphere): CONFIG = { "stereo_project_config": { "axis": 0, }, "radius": 2, "multiply_from_right": False, } def __init__(self, quaternion=None, null_axis=0, **kwargs): if quaternion is None: quaternion = np.array([1, 0, 0, 0]) self.quaternion = quaternion self.null_axis = null_axis ParametricSurface.__init__(self, self.q_mult_projection_func, **kwargs) self.fade_far_out_submobjects() def q_mult_projection_func(self, u, v): point = list(Sphere.func(self, u, v)) point.insert(self.null_axis, 0) if self.multiply_from_right: post_q_mult = q_mult(point, self.quaternion) else: post_q_mult = q_mult(self.quaternion, point) projected = list(self.radius * stereo_project_point( post_q_mult, **self.stereo_project_config )) if np.any(np.abs(projected) == np.inf): return self.func(u + 0.001, v) ignored_axis = self.stereo_project_config["axis"] projected.pop(ignored_axis) return np.array(projected) class StereoProjectedCircleFromHypersphere(CheckeredCircle): CONFIG = { "n_pieces": 48, "radius": 2, "max_length": 3 * FRAME_WIDTH, "max_r": 50, "basis_vectors": [ [1, 0, 0, 0], [0, 1, 0, 0], ], "multiply_from_right": False, } def __init__(self, quaternion=None, **kwargs): CheckeredCircle.__init__(self, **kwargs) if quaternion is None: quaternion = [1, 0, 0, 0] self.quaternion = quaternion self.pre_positioning_matrix = self.get_pre_positioning_matrix() self.apply_function(self.projection) self.remove_large_pieces() self.set_shade_in_3d(True) def get_pre_positioning_matrix(self): v1, v2 = [np.array(v) for v in self.basis_vectors] v1 = normalize(v1) v2 = v2 - np.dot(v1, v2) * v1 v2 = normalize(v2) return np.array([v1, v2]).T def projection(self, point): q1 = self.quaternion q2 = np.dot(self.pre_positioning_matrix, point[:2]).flatten() if self.multiply_from_right: new_q = q_mult(q2, q1) else: new_q = q_mult(q1, q2) projected = stereo_project_point( new_q, axis=0, r=self.radius, ) if np.any(projected == np.inf) or np.any(np.isnan(projected)): epsilon = 1e-6 return self.projection(rotate_vector(point, epsilon)) return projected[1:] def remove_large_pieces(self): for piece in self: length = get_norm(piece.get_points()[0] - piece.get_points()[-1]) violations = [ length > self.max_length, get_norm(piece.get_center()) > self.max_r, ] if any(violations): piece.fade(1) class QuaternionTracker(ValueTracker): CONFIG = { "force_unit": True, "dim": 4, } def __init__(self, four_vector=None, **kwargs): Mobject.__init__(self, **kwargs) if four_vector is None: four_vector = np.array([1, 0, 0, 0]) self.set_value(four_vector) if self.force_unit: self.add_updater(lambda q: q.normalize()) def set_value(self, vector): self.set_points(np.array(vector).reshape((1, 4))) return self def get_value(self): return self.get_points()[0] def normalize(self): self.set_value(normalize( self.get_value(), fall_back=np.array([1, 0, 0, 0]) )) return self class RubiksCube(VGroup): CONFIG = { "colors": [ "#FFD500", # Yellow "#C41E3A", # Orange "#009E60", # Green "#FF5800", # Red "#0051BA", # Blue "#FFFFFF" # White ], } def __init__(self, **kwargs): digest_config(self, kwargs) vectors = [OUT, RIGHT, UP, LEFT, DOWN, IN] faces = [ self.create_face(color, vector) for color, vector in zip(self.colors, vectors) ] VGroup.__init__(self, *it.chain(*faces), **kwargs) self.set_shade_in_3d(True) def create_face(self, color, vector): squares = VGroup(*[ self.create_square(color) for x in range(9) ]) squares.arrange_in_grid( 3, 3, buff=0 ) squares.set_width(2) squares.move_to(OUT, OUT) squares.apply_matrix(z_to_vector(vector)) return squares def create_square(self, color): square = Square( stroke_width=3, stroke_color=BLACK, fill_color=color, fill_opacity=1, side_length=1, ) square.flip() return square # back = square.copy() # back.set_fill(BLACK, 0.85) # back.set_stroke(width=0) # back.shift(0.5 * IN) # return VGroup(square, back) def get_face(self, vect): self.sort(lambda p: np.dot(p, vect)) return self[-(12 + 9):] # Abstract scenes class ManyNumberSystems(Scene): def construct(self): # Too much dumb manually positioning in here... title = Title("Number systems") name_location_color_example_tuples = [ ("Reals", [-4, 2, 0], YELLOW, "1.414"), ("Complex numbers", [4, 0, 0], BLUE, "2 + i"), ("Quaternions", [0, 2, 0], PINK, "2 + 7i + 1j + 8k"), ("Rationals", [3, -2, 0], RED, "1 \\over 3"), ("p-adic numbers", [-2, -2, 0], GREEN, "\\overline{142857}2"), ("Octonions", [-3, 0, 0], GREY_B, "3e_1 - 2.3e_2 + \\dots + 1.6e_8"), ] systems = VGroup() for name, location, color, ex in name_location_color_example_tuples: system = OldTexText(name) system.set_color(color) system.move_to(location) example = OldTex(ex) example.next_to(system, DOWN) system.add(example) systems.add(system) R_label, C_label, H_label = systems[:3] number_line = NumberLine(x_min=-3, x_max=3) number_line.add_numbers() number_line.shift(0.25 * FRAME_WIDTH * LEFT) number_line.shift(0.5 * DOWN) R_example_dot = Dot(number_line.number_to_point(1.414)) plane = ComplexPlane(x_radius=3.5, y_radius=2.5) plane.add_coordinates() plane.shift(0.25 * FRAME_WIDTH * RIGHT) plane.shift(0.5 * DOWN) C_example_dot = Dot(plane.coords_to_point(2, 1)) self.add(title) self.play(FadeInFromLarge(H_label)) self.play(LaggedStartMap( FadeInFromLarge, VGroup(*it.chain(systems[:2], systems[3:])), lambda m: (m, 4) )) self.wait() self.add(number_line, plane, systems) self.play( R_label.move_to, 0.25 * FRAME_WIDTH * LEFT + 2 * UP, C_label.move_to, 0.25 * FRAME_WIDTH * RIGHT + 2 * UP, H_label.move_to, 0.75 * FRAME_WIDTH * RIGHT + 2 * UP, FadeOut(systems[3:], 2 * DOWN), Write(number_line), Write(plane), GrowFromCenter(R_example_dot), R_label[-1].next_to, R_example_dot, UP, GrowFromCenter(C_example_dot), C_label[-1].next_to, C_example_dot, UR, SMALL_BUFF, C_label[-1].shift, 0.4 * LEFT, ) number_line.add(R_example_dot) plane.add(C_example_dot) self.wait(2) self.play(LaggedStartMap( ApplyMethod, VGroup( H_label, VGroup(plane, C_label), VGroup(number_line, R_label), ), lambda m: (m.shift, 0.5 * FRAME_WIDTH * LEFT), lag_ratio=0.8, )) randy = Randolph(height=1.5) randy.next_to(plane, RIGHT) randy.to_edge(DOWN) self.play( randy.change, "maybe", H_label, VFadeIn(randy), ) self.play(Blink(randy)) self.play(randy.change, "confused", H_label.get_top()) self.wait() class RotationsIn3d(SpecialThreeDScene): def construct(self): self.set_camera_orientation(**self.get_default_camera_position()) self.begin_ambient_camera_rotation(rate=0.02) sphere = self.get_sphere() vectors = VGroup(*[ Vector(u * v, color=color).next_to(sphere, u * v, buff=0) for v, color in zip( [RIGHT, UP, OUT], [GREEN, RED, BLUE], ) for u in [-1, 1] ]) vectors.set_shade_in_3d(True) sphere.add(vectors) self.add(self.get_axes()) self.add(sphere) angle_axis_pairs = [ (90 * DEGREES, RIGHT), (120 * DEGREES, UR), (-45 * DEGREES, OUT), (60 * DEGREES, IN + DOWN), (90 * DEGREES, UP), (30 * DEGREES, UP + OUT + RIGHT), ] for angle, axis in angle_axis_pairs: self.play(Rotate( sphere, angle, axis=axis, run_time=2, )) self.wait() class IntroduceHamilton(Scene): def construct(self): hamilton = ImageMobject("Hamilton", height=6) hamilton.to_corner(UL) shamrock = SVGMobject(file_name="shamrock") shamrock.set_height(1) shamrock.set_color("#009a49") shamrock.set_fill(opacity=0.25) shamrock.next_to(hamilton.get_corner(UL), DR) shamrock.align_to(hamilton, UP) hamilton_name = OldTexText( "William Rowan Hamilton" ) hamilton_name.match_width(hamilton) hamilton_name.next_to(hamilton, DOWN) quote = OldTexText( """\\huge ...Every morning in the early part of the above-cited month, on my coming down to breakfast, your (then) little brother William Edwin, and yourself, used to ask me,""", "``Well, Papa, can you multiply triplets''?", """Whereto I was always obliged to reply, with a sad shake of the head: ``No, I can only add and subtract them.''...""", alignment="" ) quote.set_color_by_tex("Papa", YELLOW) quote = VGroup(*it.chain(*quote)) quote.set_width(FRAME_WIDTH - hamilton.get_width() - 2) quote.to_edge(RIGHT) quote_rect = SurroundingRectangle(quote, buff=MED_SMALL_BUFF) quote_rect.set_stroke(WHITE, 2) quote_rect.stretch(1.1, 1) quote_label = OldTexText( "August 5, 1865 Letter\\\\from Hamilton to his son" ) quote_label.next_to(quote_rect, UP) quote_label.set_color(BLUE) VGroup(quote, quote_rect, quote_label).to_edge(UP) plaque = ImageMobject("BroomBridgePlaque") plaque.set_width(FRAME_WIDTH / 2) plaque.to_edge(LEFT) plaque.shift(UP) equation = OldTex( "i^2 = j^2 = k^2 = ijk = -1", tex_to_color_map={"i": GREEN, "j": RED, "k": BLUE} ) equation_rect = Rectangle(width=3.25, height=0.7) equation_rect.move_to(3.15 * LEFT + 0.25 * DOWN) equation_rect.set_color(WHITE) equation_arrow = Vector(DOWN) equation_arrow.match_color(equation_rect) equation_arrow.next_to(equation_rect, DOWN) equation.next_to(equation_arrow, DOWN) self.play( FadeInFromDown(hamilton), Write(hamilton_name), ) self.play(DrawBorderThenFill(shamrock)) self.wait() self.play( LaggedStartMap( FadeIn, quote, lag_ratio=0.2, run_time=4 ), FadeInFromDown(quote_label), ShowCreation(quote_rect) ) self.wait(3) self.play( ApplyMethod( VGroup(hamilton, shamrock, hamilton_name).to_edge, RIGHT, run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1), ), LaggedStartMap( FadeOutAndShiftDown, VGroup(*it.chain( quote, quote_rect, quote_label )) ) ) self.wait() self.play(FadeIn(plaque)) self.play( ShowCreation(equation_rect), GrowArrow(equation_arrow) ) self.play(ReplacementTransform( equation.copy().replace(equation_rect).fade(1), equation )) self.wait() class QuaternionHistory(Scene): CONFIG = { "names_and_quotes": [ ( "Oliver Heaviside", """\\huge ``As far as the vector analysis I required was concerned, the quaternion was not only not required, but was a positive evil of no inconsiderable magnitude.''""" ), ( "Lord Kelvin", """\\huge ``Quaternions... though beautifully \\\\ ingenious, have been an unmixed evil to those who have touched them in any way, including Clerk Maxwell.''""" ), ] } def construct(self): self.show_dot_product_and_cross_product() self.teaching_students_quaternions() self.show_anti_quaternion_quote() self.mad_hatter() def show_dot_product_and_cross_product(self): date = OldTex("1843") date.scale(2) date.to_edge(UP) t2c = self.t2c = { "x_1": GREEN, "x_2": GREEN, "y_1": RED, "y_2": RED, "z_1": BLUE, "z_2": BLUE, } def get_colored_tex_mobject(tex): return OldTex(tex, tex_to_color_map=t2c) v1, v2 = [ Matrix([ ["{}_{}".format(c, i)] for c in "xyz" ], element_to_mobject=get_colored_tex_mobject) for i in (1, 2) ] dot_rhs = get_colored_tex_mobject( "x_1 x_2 + y_1 y_2 + z_1 z_2", ) cross_rhs = Matrix([ ["y_1 z_2 - z_1 y_2"], ["z_1 x_2 - x_1 z_2"], ["x_1 y_2 - y_1 x_2"], ], element_to_mobject=get_colored_tex_mobject) dot_product = VGroup( v1.copy(), OldTex("\\cdot").scale(2), v2.copy(), OldTex("="), dot_rhs ) cross_product = VGroup( v1.copy(), OldTex("\\times"), v2.copy(), OldTex("="), cross_rhs ) for product in dot_product, cross_product: product.arrange(RIGHT, buff=2 * SMALL_BUFF) product.set_height(1.5) dot_product.next_to(date, DOWN, buff=MED_LARGE_BUFF) dot_product.to_edge(LEFT, buff=LARGE_BUFF) cross_product.next_to( dot_product, DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT, ) self.play(FadeIn(dot_product, 2 * RIGHT)) self.play(FadeIn(cross_product, 2 * LEFT)) self.wait() self.play(FadeInFromDown(date)) self.play(ApplyMethod(dot_product.fade, 0.7)) self.play(ApplyMethod(cross_product.fade, 0.7)) self.wait() self.play( FadeOut(dot_product, 2 * LEFT), FadeOut(cross_product, 2 * RIGHT), ) self.date = date def teaching_students_quaternions(self): hamilton = ImageMobject("Hamilton") hamilton.set_height(4) hamilton.pixel_array = hamilton.pixel_array[:, ::-1, :] hamilton.to_corner(UR) hamilton.shift(MED_SMALL_BUFF * DOWN) colors = color_gradient([BLUE_E, GREY_BROWN, BLUE_B], 7) random.shuffle(colors) students = VGroup(*[ PiCreature(color=color) for color in colors ]) students.set_height(2) students.arrange(RIGHT) students.set_width(FRAME_WIDTH - hamilton.get_width() - 1) students.to_corner(DL) equation = OldTex(""" (x_1 i + y_1 j + z_1 k) (x_2 i + y_2 j + z_2 k) = (-x_1 x_2 - y_1 y_2 - z_1 z_2) + (y_1 z_2 - z_1 y_2)i + (z_1 x_2 - x_1 z_2)j + (x_1 y_2 - y_1 x_2)k """, tex_to_color_map=self.t2c) equation.set_width(FRAME_WIDTH - 1) equation.to_edge(UP, buff=MED_SMALL_BUFF) images = Group() image_labels = VGroup() images_with_labels = Group() names = ["Peter Tait", "Robert Ball", "Macfarlane Alexander"] for name in names: image = ImageMobject(name) image.set_height(3) label = OldTexText(name) label.scale(0.5) label.next_to(image, DOWN) image.label = label image_labels.add(label) images.add(image) images_with_labels.add(Group(image, label)) images_with_labels.arrange(RIGHT) images_with_labels.next_to(hamilton, LEFT, LARGE_BUFF) images_with_labels.shift(MED_LARGE_BUFF * DOWN) society_title = OldTexText("Quaternion society") society_title.next_to(images, UP, MED_LARGE_BUFF, UP) def blink_wait(n_loops): for x in range(n_loops): self.play(Blink(random.choice(students))) self.wait(random.random()) self.play( FadeInFromDown(hamilton), Write( self.date, rate_func=lambda t: smooth(1 - t), remover=True ) ) self.play(LaggedStartMap( FadeInFrom, students, lambda m: (m, LEFT), )) self.play( LaggedStartMap( ApplyMethod, students, lambda pi: ( pi.change, random.choice(["confused", "maybe", "erm"]), 3 * LEFT + 2 * UP, ), ), Write(equation), ) blink_wait(3) self.play( LaggedStartMap(FadeInFromDown, images), LaggedStartMap(FadeInFromLarge, image_labels), Write(society_title) ) blink_wait(3) self.play( FadeOut(hamilton, RIGHT), LaggedStartMap( FadeOutAndShift, images_with_labels, lambda m: (m, UP) ), FadeOut(students, DOWN), FadeOut(society_title), run_time=1 ) self.equation = equation def show_anti_quaternion_quote(self): group = self.get_dissenter_images_quotes_and_names() images, quotes, names = group self.play( LaggedStartMap(FadeInFromDown, images), LaggedStartMap(FadeInFromLarge, names), lag_ratio=0.75, run_time=2, ) for quote in quotes: self.play(LaggedStartMap( FadeIn, VGroup(*quote.family_members_with_points()), lag_ratio=0.3 )) self.wait() self.play(FadeOut(images_with_quotes)) def mad_hatter(self): title = OldTexText( "Lewis Carroll's", "``Alice in wonderland''" ) title.to_edge(UP, buff=LARGE_BUFF) author_brace = Brace(title[0], DOWN) aka = OldTexText("a.k.a. Mathematician Charles Dodgson") aka.scale(0.8) aka.set_color(BLUE) aka.next_to(author_brace, DOWN) quote = OldTexText( """ ``Why, you might just as well say that\\\\ ‘I see what I eat’ is the same thing as\\\\ ‘I eat what I see’!'' """, tex_to_color_map={ "I see what I eat": BLUE, "I eat what I see": YELLOW, }, alignment="" ) quote.to_edge(UP, buff=LARGE_BUFF) hatter = PiCreature(color=RED, mode="surprised") hat = SVGMobject(file_name="hat") hat_back = hat.copy() hat_back[0].remove(*[ sm for sm in hat_back[0] if sm.is_subpath ]) hat_back.set_fill(GREY_D) hat.add_to_back(hat_back) hat.set_height(1.25) hat.next_to(hatter.body, UP, buff=-MED_SMALL_BUFF) hatter.add(hat) hatter.look(DL) hatter.pupils[1].save_state() hatter.look(UL) hatter.pupils[1].restore() hatter.set_height(2) hare = SVGMobject(file_name="bunny") mouse = SVGMobject(file_name="mouse") for mob in hare, mouse: mob.set_color(GREY_B) mob.set_sheen(0.2, UL) mob.set_height(1.5) characters = VGroup(hatter, hare, mouse) for mob, p in zip(characters, [UP, DL, DR]): mob.move_to(p) hare.shift(MED_SMALL_BUFF * LEFT) characters.space_out_submobjects(1.5) characters.to_edge(DOWN) def change_single_place(char, **kwargs): i = characters.submobjects.index(char) target = characters[(i + 1) % 3] return ApplyMethod( char.move_to, target, path_arc=-90 * DEGREES, **kwargs ) def get_change_places(): return LaggedStartMap( change_single_place, characters, lag_ratio=0.6 ) self.play( Write(title), LaggedStartMap(FadeInFromDown, characters) ) self.play( get_change_places(), GrowFromCenter(author_brace), FadeIn(aka) ) for x in range(4): self.play(get_change_places()) self.play( FadeOut(VGroup(title, author_brace, aka)), FadeInFromDown(quote), ) self.play(get_change_places()) self.play( get_change_places(), VFadeOut(characters, run_time=2) ) self.remove(characters) self.wait() # def get_dissenter_images_quotes_and_names(self): names_and_quotes = self.names_and_quotes images = Group() quotes = VGroup() names = VGroup() images_with_quotes = Group() for name, quote_text in names_and_quotes: image = Group(ImageMobject(name)) image.set_height(4) label = OldTexText(name) label.next_to(image, DOWN) names.add(label) quote = OldTexText( quote_text, tex_to_color_map={ "positive evil": RED, "unmixed evil": RED, }, alignment="" ) quote.scale(0.3) quote.next_to(image, UP) images.add(image) quotes.add(quote) images_with_quotes.add(Group(image, label, quote)) images_with_quotes.arrange(RIGHT, buff=LARGE_BUFF) images_with_quotes.to_edge(DOWN, MED_LARGE_BUFF) return Group(images, quotes, names) class QuaternionRotationOverlay(Scene): def construct(self): equations = VGroup( OldTex( "p", "\\rightarrow", "{}", "{}", "\\left(q_1", "p", "q_1^{-1}\\right)", "{}", "{}", ), OldTex( "p", "\\rightarrow", "{}", "\\left(q_2", "\\left(q_1", "p", "q_1^{-1}\\right)", "q_2^{-1}\\right)", "{}", ), OldTex( "p", "\\rightarrow", "\\left(q_3", "\\left(q_2", "\\left(q_1", "p", "q_1^{-1}\\right)", "q_2^{-1}\\right)", "q_3^{-1}\\right)", ), ) for equation in equations: equation.set_color_by_tex_to_color_map({ "1": GREEN, "2": RED, "3": BLUE, }) equation.set_color_by_tex("rightarrow", WHITE) equation.to_corner(UL) equation = equations[0].copy() self.play(Write(equation)) self.wait() for new_equation in equations[1:]: self.play( Transform(equation, new_equation) ) self.wait(2) class RotateCubeThreeTimes(SpecialThreeDScene): def construct(self): cube = RubiksCube() cube.set_fill(opacity=0.8) cube.set_stroke(width=1) randy = Randolph(mode="pondering") randy.set_height(cube.get_height() - 2 * SMALL_BUFF) randy.move_to(cube.get_edge_center(OUT)) randy.set_fill(opacity=0.8) # randy.set_shade_in_3d(True) cube.add(randy) axes = self.get_axes() self.add(axes, cube) self.move_camera( phi=70 * DEGREES, theta=-140 * DEGREES, ) self.begin_ambient_camera_rotation(rate=0.02) self.wait(2) self.play(Rotate(cube, TAU / 4, RIGHT, run_time=3)) self.wait(2) self.play(Rotate(cube, TAU / 4, UP, run_time=3)) self.wait(2) self.play(Rotate(cube, -TAU / 3, np.ones(3), run_time=3)) self.wait(7) class QuantumSpin(Scene): def construct(self): title = Title("Two-state system") electron = Dot(color=BLUE) electron.set_height(1) electron.set_sheen(0.3, UL) electron.set_fill(opacity=0.8) kwargs = { "path_arc": PI, } curved_arrows = VGroup( Arrow(RIGHT, LEFT, **kwargs), Arrow(LEFT, RIGHT, **kwargs), ) curved_arrows.set_color(GREY_B) curved_arrows.set_stroke(width=2) y_arrow = Vector(UP) y_arrow.set_color(RED) y_ca = curved_arrows.copy() y_ca.rotate(70 * DEGREES, LEFT) y_group = VGroup(y_ca[0], y_arrow, electron.copy(), y_ca[1]) x_arrow = y_arrow.copy().rotate(90 * DEGREES, IN, about_point=ORIGIN) x_arrow.set_color(GREEN) x_ca = curved_arrows.copy() x_ca.rotate(70 * DEGREES, UP) x_group = VGroup(x_ca[0], x_arrow, electron.copy(), x_ca[1]) z_ca = curved_arrows.copy() z_group = VGroup(electron.copy(), z_ca, Dot(color=BLUE)) groups = VGroup(x_group, y_group, z_group) groups.arrange(RIGHT, buff=1.5) groups.move_to(UP) y_ca.rotation = Rotating( y_ca, axis=rotate_vector(OUT, 70 * DEGREES, LEFT) ) x_ca.rotation = Rotating( x_ca, axis=rotate_vector(OUT, 70 * DEGREES, UP) ) z_ca.rotation = Rotating(z_ca, axis=OUT) rotations = [ca.rotation for ca in [x_ca, y_ca, z_ca]] matrices = VGroup( Matrix([["0", "1"], ["1", "0"]]), Matrix([["0", "-i"], ["i", "0"]]), Matrix([["1", "0"], ["0", "-1"]]), ) for matrix, group in zip(matrices, groups): matrix.next_to(group, DOWN) for matrix in matrices[1:]: matrix.align_to(matrices[0], DOWN) self.add(title, groups) self.play() self.play( LaggedStartMap(FadeInFromDown, matrices, run_time=3), *rotations ) for x in range(2): self.play(*rotations) class HereWeTackle4d(TeacherStudentsScene): def construct(self): titles = VGroup( OldTexText( "This video:\\\\", "Quaternions in 4d" ), OldTexText( "Next video:\\\\", "Quaternions acting on 3d" ) ) for title in titles: title.move_to(self.hold_up_spot, DOWN) titles[0].set_color(YELLOW) self.play( self.teacher.change, "raise_right_hand", FadeInFromDown(titles[0]), self.change_students("confused", "horrified", "sad") ) self.look_at(self.screen) self.wait() self.play_student_changes( "erm", "thinking", "pondering", look_at=self.screen ) self.wait(3) self.play_student_changes( "pondering", "confused", "happy" ) self.look_at(self.screen) self.wait(3) self.play( self.teacher.change, "hooray", FadeIn(titles[1]), ApplyMethod( titles[0].shift, 2 * UP, rate_func=squish_rate_func(smooth, 0.2, 1) ) ) self.play_all_student_changes("hooray") self.play(self.teacher.change, "happy") self.look_at(self.screen) self.wait(3) self.play_student_changes("pondering", "happy", "thinking") self.wait(4) class TableOfContents(Scene): def construct(self): chapters = VGroup( OldTexText( "\\underline{Chapter 1}\\\\", "Linus the Linelander" ), OldTexText( "\\underline{Chapter 2}\\\\", "Felix the Flatlander" ), OldTexText( "\\underline{Chapter 3}\\\\", " You, the 3d-lander" ), ) for chapter in chapters: chapter.space_out_submobjects(1.5) chapters.arrange( DOWN, buff=1.5, aligned_edge=LEFT ) chapters.to_edge(LEFT) for chapter in chapters: self.play(FadeInFromDown(chapter)) self.wait(2) for chapter in chapters: chapters.save_state() other_chapters = VGroup(*[ c for c in chapters if c is not chapter ]) self.play( chapter.set_width, 0.5 * FRAME_WIDTH, chapter.center, other_chapters.fade, 1 ) self.wait(3) self.play(chapters.restore) class IntroduceLinusTheLinelander(Scene): def construct(self): self.introduce_linus() self.show_real_number_line() self.look_at_complex_plane() def introduce_linus(self): linus = Linus() linus.move_to(3 * LEFT) name = OldTexText("Linus the Linelander") name.next_to(linus, DR, buff=MED_LARGE_BUFF) arrow = Arrow(name.get_top(), linus.get_right()) self.play(FadeInFromDown(linus)) self.play( Write(name), GrowArrow(arrow), linus.change, "gracious", name, ) self.play( linus.become_squiggle, {"factor": -0.1}, ) self.play(Blink(linus)) self.wait() self.name_text = name self.name_arrow = arrow self.linus = linus def show_real_number_line(self): linus = self.linus number_line = NumberLine() number_line.add_numbers() number_line.to_edge(UP) algebra = VGroup( OldTex("3 \\cdot 4 = 12"), OldTex("3 + 4 = 7"), OldTex("(-2) \\cdot 3 = -6"), ) algebra.arrange(DOWN) algebra.next_to(number_line, DOWN, LARGE_BUFF) algebra.shift(3 * RIGHT) self.play( ShowCreation(number_line), linus.look_at, number_line ) self.play( LaggedStartMap(FadeInFromDown, number_line.numbers), LaggedStartMap(ShowCreation, number_line.tick_marks), linus.change, "happy" ) self.play( LaggedStartMap(FadeInFromDown, algebra), linus.look_at, algebra ) self.play(Blink(linus)) self.wait() self.algebra = algebra def look_at_complex_plane(self): linus = self.linus to_fade = VGroup( self.name_text, self.name_arrow, self.algebra, ) frame = ScreenRectangle() frame.set_width(8) frame.to_corner(DR) q_marks = VGroup(*[ OldTex("?").shift( random.random() * RIGHT, random.random() * UP, ) for x in range(50) ]) q_marks.next_to(linus.body, UP, buff=0) q_marks.set_color_by_gradient(BLUE, GREEN, YELLOW) random.shuffle(q_marks.submobjects) q_marks_anim = LaggedStartMap( FadeIn, q_marks, run_time=15, rate_func=there_and_back, lag_ratio=0.1 ) q_marks_continual = turn_animation_into_updater(q_marks_anim) self.play( FadeOut(to_fade), ShowCreation(frame), linus.look_at, frame ) self.add(q_marks_continual) self.play(linus.change_mode, "confused") self.wait() self.play(Blink(linus)) self.play(linus.change, "confused", frame.get_bottom()) self.wait() self.play(linus.change, "sad", frame.get_center()) self.wait(10) class ShowComplexMultiplicationExamples(Scene): CONFIG = { "plane_config": { "x_radius": 9, "y_radius": 9, "stroke_width": 3, }, "background_plane_config": { "color": GREY_B, "secondary_color": GREY_D, "stroke_width": 0.5, "stroke_opacity": 0.5, "secondary_line_ratio": 0, } } def construct(self): self.add_planes() z_tuples = [ (complex(2, 1), "2 + i", UP), (complex(5, 2), "5 + 2i", LEFT), ( complex(-np.sqrt(2) / 2, np.sqrt(2) / 2), "-\\frac{\\sqrt{2}}{2} + \\frac{\\sqrt{2}}{2} i", LEFT, ), (complex(-4, 1.5), "-4 + 1.5i", RIGHT), (complex(3, 0), "3 + 0i", UP), (complex(4, -3), "4 + -3i", UP), ] for z, z_tex, label_vect in z_tuples: self.show_multiplication(z, z_tex, label_vect) def add_planes(self, include_title=True): plane = ComplexPlane(**self.plane_config) self.plane = plane background_plane = ComplexPlane(**self.background_plane_config) background_plane.add_coordinates() self.background_plane = background_plane self.add(background_plane) self.add(plane) if include_title: title = OldTexText("Complex plane") title.scale(1.5) title.to_corner(UL, buff=MED_LARGE_BUFF) title.shift(SMALL_BUFF * UR) self.title = title self.add_foreground_mobjects(title) def show_multiplication(self, z, z_tex, label_vect): z_color = WHITE plane = self.plane new_plane = plane.deepcopy() real_tex, imag_tex = z_tex.split("+") label = OldTex( "\\text{Multiply by}\\\\", real_tex, "+", imag_tex, alignment="", ) label[1].set_color(GREEN) label[3].set_color(RED) label.scale(1.2) h_line = Line( plane.number_to_point(0), plane.number_to_point(z.real), color=GREEN, stroke_width=5, ) v_line = Line( plane.number_to_point(z.real), plane.number_to_point(z), color=RED, stroke_width=5, ) lines = VGroup(h_line, v_line) z_point = plane.number_to_point(z) z_dot = Dot(z_point) z_dot.set_color(z_color) label[1:].next_to(z_dot, label_vect) label[0].next_to(label[1:], UP) for mob in label: label.add_to_back(BackgroundRectangle(mob)) one_dot = Dot(plane.number_to_point(1)) one_dot.set_color(YELLOW) for dot in z_dot, one_dot: dot.save_state() dot.scale(5) dot.set_fill(opacity=0) dot.set_stroke(width=1, opacity=0.5) to_fade_out = VGroup( plane, label, lines, z_dot, one_dot ) self.play( ShowCreation(lines), FadeInFromDown(label), Restore(z_dot), ) self.play(Restore(one_dot)) angle = np.log(z).imag self.play( one_dot.move_to, z_dot, plane.apply_complex_function, lambda w: z * w, path_arc=angle, run_time=3 ) self.wait() self.play( FadeOut(to_fade_out), FadeIn(new_plane), ) self.plane = new_plane class DefineComplexNumbersPurelyAlgebraically(Scene): def construct(self): self.add_linus() self.add_title() self.show_example_number() self.show_multiplication() self.emphsize_result_has_same_form() def add_linus(self): linus = self.linus = Linus() linus.move_to(3 * LEFT) def add_title(self): title = self.title = Title( "No spatial reasoning, just symbols" ) self.play( FadeInFromDown(title[:-1]), ShowCreation(title[-1]), self.linus.look_at, title ) def show_example_number(self): linus = self.linus number = OldTex("2.35", "+", "3.14", "i") number.next_to(self.title, DOWN, buff=1.5) number.shift(3 * RIGHT) real, imag = number[0], number[2] real_brace = Brace(real, UP) imag_brace = Brace(imag, DOWN) real_label = real_brace.get_text("Some real number") imag_label = imag_brace.get_text("Some other real number") VGroup(real, real_label).set_color(GREEN) VGroup(imag, imag_label).set_color(RED) i = number[-1] i_def = OldTex("i", "^2", "=", "-1") i_def.next_to( self.title, DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT, ) i_def_rect = SurroundingRectangle(i_def, color=YELLOW, buff=MED_SMALL_BUFF) definition_label = OldTexText("Definition") definition_label.next_to(i_def_rect, DOWN) definition_label.match_color(i_def_rect) self.play(Write(number, run_time=1)) self.play( GrowFromCenter(real_brace), LaggedStartMap(FadeIn, real_label), linus.change, "confused", number, run_time=1 ) self.wait() self.play( GrowFromCenter(imag_brace), LaggedStartMap(FadeIn, imag_label), run_time=1 ) self.play(Blink(linus)) self.play( linus.change, "erm", i_def, ReplacementTransform( i.copy(), i_def[0], path_arc=-30 * DEGREES ), FadeIn(i_def_rect), FadeIn(definition_label), ) self.play(Write(i_def[1:])) self.wait() self.play(Blink(linus)) self.to_fade = VGroup( real_brace, real_label, imag_brace, imag_label, ) self.number = number def show_multiplication(self): linus = self.linus to_fade = self.to_fade z1 = self.number z2 = OldTex("4", "+", "5", "i") z2.match_style(z1) for z in z1, z2: lp, rp = z.parens = OldTex("()") lp.next_to(z, LEFT, SMALL_BUFF) rp.next_to(z, RIGHT, SMALL_BUFF) z.real = z[0] z.imag = z[2:] for part in z.real, z.imag: part.targets = [part.copy(), part.copy()] z1.generate_target() product = VGroup( VGroup(z1.target, z1.parens), VGroup(z2, z2.parens), ) product.arrange(RIGHT, SMALL_BUFF) product.move_to(2 * RIGHT + 2 * UP) foil = VGroup(*map(TexText, [ "First", "Outside", "Inside", "Last", ])) foil.arrange( DOWN, buff=MED_SMALL_BUFF, aligned_edge=LEFT ) foil.scale(1.25) for word in foil: word[0].set_color(BLUE) foil.move_to(product).to_edge(DOWN, LARGE_BUFF) def get_cdot(): return OldTex("\\cdot") def get_lp(): return OldTex("(") def get_rp(): return OldTex(")") def get_plus(): return OldTex("+") expansion = VGroup( z1.real.targets[0], get_cdot(), z2.real.targets[0], get_plus(), z1.real.targets[1], get_cdot(), z2.imag.targets[0], get_plus(), z1.imag.targets[0], get_cdot(), z2.real.targets[1], get_plus(), z1.imag.targets[1], get_cdot(), z2.imag.targets[1], ) expansion.arrange(RIGHT, buff=0.15) expansion.next_to(product, DOWN, buff=LARGE_BUFF) expansion_parts = VGroup(*[ expansion[4 * i: 4 * i + 3] for i in range(4) ]) expansion_part_braces = VGroup(*[ Brace(part, DOWN) for part in expansion_parts ]) for word, brace in zip(foil, expansion_part_braces): word.next_to(brace, DOWN) final_prouct = VGroup( get_lp(), z1[0].copy(), get_cdot(), z2[0].copy(), OldTex("-"), z1[2].copy(), get_cdot(), z2[2].copy(), get_rp(), get_plus(), get_lp(), z1[0].copy(), get_cdot(), z2[2].copy(), get_plus(), z1[2].copy(), get_cdot(), z2[0].copy(), get_rp(), OldTex("i") ) final_prouct.arrange(RIGHT, buff=0.15) final_prouct.next_to(expansion, DOWN, buff=2) final_arrows = VGroup() for i, brace in zip([1, 11, 15, 5], expansion_part_braces): target = final_prouct[i:i + 3] if i == 5: arrow = Line( brace.get_bottom() + SMALL_BUFF * DOWN, target.get_top() + MED_SMALL_BUFF * UP, ) arrow.get_points()[1] = arrow.get_points()[0] + DOWN arrow.get_points()[2] = arrow.get_points()[3] + UP tip = RegularPolygon(3, start_angle=-100 * DEGREES) tip.set_height(0.2) tip.set_stroke(width=0) tip.set_fill(WHITE, opacity=1) tip.move_to(arrow.get_end()) arrow.add(tip) else: arrow = Arrow( brace.get_bottom(), target.get_top(), ) final_arrows.add(arrow) final_arrows.set_stroke(BLACK, width=6, background=True) # Move example number into product self.play( FadeOut(to_fade), MoveToTarget(z1), FadeIn(z1.parens), FadeInFromDown(z2), FadeIn(z2.parens), linus.change, "happy", product, ) self.wait() # Show distribution pairs = list(it.product([z1.real, z1.imag], [z2.real, z2.imag])) for i in range(4): left, right = pair = VGroup(*pairs[i]) word = foil[i] dot = expansion[4 * i + 1] plus = expansion[4 * i + 3] if i < 3 else VMobject() brace = expansion_part_braces[i] self.play(pair.shift, 0.5 * DOWN) self.play( FadeIn(dot), GrowFromCenter(brace), FadeInFromDown(word), linus.move_to, 4 * LEFT + DOWN, *[ ReplacementTransform( part.copy(), part.targets.pop(0) ) for part in pair ] ) self.play( pair.shift, 0.5 * UP, FadeIn(plus) ) self.play(Blink(linus)) self.play( FadeOut(foil), FadeInFromDown(final_prouct), linus.look_at, final_prouct, ) self.play( LaggedStartMap(ShowCreation, final_arrows), run_time=3, ) self.play(linus.change, "confused") self.wait() self.final_prouct = final_prouct def emphsize_result_has_same_form(self): final_product = self.final_prouct real = final_product[1:1 + 7] imag = final_product[11:11 + 7] real_brace = Brace(real, DOWN) real_label = real_brace.get_text("Some real number") real_label.set_color(GREEN) imag_brace = Brace(imag, DOWN) imag_label = imag_brace.get_text( "Some other \\\\ real number" ) imag_label.set_color(RED) braces = VGroup(real_brace, imag_brace) labels = VGroup(real_label, imag_label) self.play( LaggedStartMap(GrowFromCenter, braces), LaggedStartMap(Write, labels), ) self.wait() class TextbookQuaternionDefinition(TeacherStudentsScene): CONFIG = { "random_seed": 1, } def construct(self): equation = OldTex( """ (w_1 + x_1 i + y_1 j + z_1 k) (w_2 + x_2 i + y_2 j + z_2 k) = &(w_1 w_2 - x_1 x_2 - y_1 y_2 - z_1 z_2) \\, +\\\\ &(w_1 x_2 + x_1 w_2 + y_1 z_2 - z_1 y_2)i \\, +\\\\ &(w_1 y_2 + y_1 w_2 + z_1 x_2 - x_1 z_2)j \\, +\\\\ &(w_1 z_2 + z_1 w_2 + x_1 y_2 - y_1 x_2)k \\\\ """, tex_to_color_map={ "w_1": YELLOW, "w_2": YELLOW, "x_1": GREEN, "x_2": GREEN, "y_1": RED, "y_2": RED, "z_1": BLUE, "z_2": BLUE, } ) equation.set_width(FRAME_WIDTH - 1) equation.to_edge(UP) defining_products = VGroup(*[ OldTex( tex, tex_to_color_map={ "i": GREEN, "j": RED, "k": BLUE, } ) for tex in [ "i^2 = j^2 = k^2 = -1", "ij = -ji = k", "ki = -ik = j", "jk = -kj = i", ] ]) defining_products.arrange(DOWN) defining_products.next_to(self.students, UP, LARGE_BUFF) def_rect = SurroundingRectangle(defining_products) self.play( LaggedStartMap(FadeInFromDown, defining_products), self.change_students(*3 * ["confused"]), self.teacher.change, "raise_right_hand", ) self.play(ShowCreation(def_rect)) self.play( Write(equation, run_time=4, lag_ratio=0.2), self.change_students( "horrified", "pleading", "sick", equation ), self.teacher.change, "erm", equation, ) self.blink() self.look_at(equation.get_corner(UL)) self.blink() self.look_at(equation.get_corner(UR)) self.play(self.teacher.change, "sassy", equation) self.wait(2) self.play_all_student_changes("pondering") self.look_at(equation) self.wait() self.play(self.teacher.change, "thinking", equation) self.wait(8) class ProblemsWhereComplexNumbersArise(Scene): def construct(self): text = "Problems where complex numbers are surprisingly useful" title = OldTexText(*text.split(" ")) title.to_edge(UP) title.set_color(BLUE) underline = Line(LEFT, RIGHT) underline.set_width(title.get_width() + 0.5) underline.next_to(title, DOWN) problems = VGroup( OldTexText( "Integer solutions to\\\\ $a^2 + b^2 = c^2$", alignment="" ), OldTexText( "Understanding\\\\", "$1 - \\frac{1}{3} + \\frac{1}{5} - \\frac{1}{7} + \\cdots" + "=\\frac{\\pi}{4}$", alignment="", ), OldTexText("Frequency analysis") ) problems.arrange( DOWN, buff=LARGE_BUFF, aligned_edge=LEFT ) for problem in problems: problems.add(Dot().next_to(problem[0], LEFT)) problems.next_to(underline, DOWN, buff=MED_LARGE_BUFF) problems.to_edge(LEFT) v_dots = OldTex("\\vdots") v_dots.scale(2) v_dots.next_to(problems, DOWN, aligned_edge=LEFT) self.add(problems, v_dots) self.play( ShowCreation(underline), LaggedStartMap(FadeInFromDown, title, lag_ratio=0.5), run_time=3 ) self.wait() class WalkThroughComplexMultiplication(ShowComplexMultiplicationExamples): CONFIG = { "z": complex(2, 3), "w": complex(1, -1), "z_color": YELLOW, "w_color": PINK, "product_color": RED, } def construct(self): self.add_planes(include_title=False) self.introduce_z_and_w() self.show_action_on_all_complex_numbers() def introduce_z_and_w(self): # Tolerating code repetition here in case I want # to specialize behavior for z or w... plane = self.plane origin = plane.number_to_point(0) z_point = plane.number_to_point(self.z) z_dot = Dot(z_point) z_line = Line(origin, z_point) z_label = VGroup( OldTex("z="), DecimalNumber(self.z, num_decimal_places=0) ) z_label.arrange( RIGHT, buff=SMALL_BUFF, ) z_label.next_to(z_dot, UP, buff=SMALL_BUFF) z_label.set_color(self.z_color) z_label.add_background_rectangle() VGroup(z_line, z_dot).set_color(self.z_color) w_point = plane.number_to_point(self.w) w_dot = Dot(w_point) w_line = Line(origin, w_point) w_label = VGroup( OldTex("w="), DecimalNumber(self.w, num_decimal_places=0) ) w_label.arrange(RIGHT, buff=SMALL_BUFF) w_label.next_to(w_dot, DOWN, buff=SMALL_BUFF) w_label.set_color(self.w_color) w_label.add_background_rectangle() VGroup(w_line, w_dot).set_color(self.w_color) VGroup( z_label[1], w_label[1] ).shift(0.25 * SMALL_BUFF * DOWN) product = OldTex("z", "\\cdot", "w") z_sym, w_sym = product[0], product[2] z_sym.set_color(self.z_color) w_sym.set_color(self.w_color) product.scale(2) product.to_corner(UL) product.add_background_rectangle() self.add( z_line, z_label, w_line, w_label, ) self.play(LaggedStartMap( FadeInFromLarge, VGroup(z_dot, w_dot), lambda m: (m, 5), lag_ratio=0.8, run_time=1.5 )) self.play( ReplacementTransform(z_label[1][0].copy(), z_sym) ) self.add(product[:-1]) self.play( ReplacementTransform(w_label[1][0].copy(), w_sym), FadeIn(product[2], LEFT), FadeIn(product[0]), ) self.wait() self.set_variables_as_attrs( product, z_point, w_point, z_dot, w_dot, z_line, w_line, ) def show_action_on_all_complex_numbers(self): plane = self.plane plane.save_state() origin = plane.number_to_point(0) z = self.z angle = np.log(z).imag product_tex = self.product[1:] z_sym, cdot, w_sym = product_tex product = self.z * self.w product_point = plane.number_to_point(product) product_dot = Dot(product_point) product_line = Line(origin, product_point) for mob in product_line, product_dot: mob.set_color(self.product_color) rect = SurroundingRectangle(VGroup(z_sym, cdot)) rect.set_fill(BLACK, opacity=1) func_words = OldTexText("Function on the plane") func_words.next_to( rect, DOWN, buff=MED_SMALL_BUFF, aligned_edge=LEFT, ) func_words.set_color(self.z_color) sparkly_plane = VGroup() for line in plane.family_members_with_points(): if self.camera.is_in_frame(line): for piece in line.get_pieces(10): p1, p2 = piece.get_pieces(2) p1.rotate(PI) pair = VGroup(p1, p2) pair.scale(0.3) sparkly_plane.add(pair) sparkly_plane.sort( lambda p: 0.1 * get_norm(p) + random.random() ) sparkly_plane.set_color_by_gradient(YELLOW, RED, PINK, BLUE) sparkly_plane.set_stroke(width=4) pin = PushPin() pin.move_to(origin, DR) one_dot = Dot(plane.number_to_point(1)) one_dot.set_fill(WHITE) one_dot.set_stroke(BLACK, 1) hand = Hand() hand.move_to(plane.number_to_point(1), LEFT) zero_eq = OldTex("z \\cdot 0 = 0") one_eq = OldTex("z \\cdot 1 = z") equations = VGroup(zero_eq, one_eq) equations.arrange(DOWN) equations.scale(1.5) for eq in equations: eq.add_background_rectangle() equations.next_to(func_words, DOWN) equations.to_edge(LEFT) product_label = VGroup( OldTex("z \\cdot w ="), DecimalNumber(product, num_decimal_places=0) ) product_label.arrange(RIGHT) product_label[0].shift(0.025 * DOWN) product_label.next_to(product_dot, UP, SMALL_BUFF) product_label.add_background_rectangle() big_rect = Rectangle( height=4, width=6, fill_color=BLACK, fill_opacity=0.9, stroke_width=0, ) big_rect.to_corner(UL, buff=0) self.add(big_rect, product_tex, rect, z_sym, cdot) self.play( FadeIn(big_rect), ShowCreation(rect), Write(func_words), run_time=1 ) self.play( ReplacementTransform( self.w_line.copy(), product_line, ), ReplacementTransform( self.w_dot.copy(), product_dot, ), path_arc=angle, run_time=3 ) self.wait() self.play(FadeOut(VGroup(product_line, product_dot))) self.play(LaggedStartMap( ShowCreationThenDestruction, sparkly_plane, lag_ratio=0.5, run_time=2 )) self.play( plane.apply_complex_function, lambda w: z * w, Transform(self.w_line, product_line), Transform(self.w_dot, product_dot), path_arc=angle, run_time=9, rate_func=lambda t: there_and_back_with_pause(t, 2 / 9) ) self.wait() self.play(FadeIn(pin, UL)) self.play(Write(zero_eq)) self.play( FadeInFromLarge(one_dot), FadeIn(hand, UR) ) self.play(Write(one_eq)) self.wait() self.play( plane.apply_complex_function, lambda w: z * w, ReplacementTransform(self.w_line.copy(), product_line), ReplacementTransform(self.w_dot.copy(), product_dot), one_dot.move_to, self.z_point, hand.move_to, self.z_point, LEFT, path_arc=angle, run_time=4, ) self.play(Write(product_label)) class ShowUnitCircleActions(ShowComplexMultiplicationExamples): CONFIG = { "random_seed": 0, "plane_config": { "secondary_line_ratio": 0, } } def construct(self): self.add_planes(include_title=False) self.show_unit_circle_actions() def show_unit_circle_actions(self): plane = self.plane origin = plane.number_to_point(0) one_point = plane.number_to_point(1) one_dot = Dot(one_point) one_dot.set_fill(WHITE) one_dot.set_stroke(BLACK, 1) plane.add(one_dot) pin = PushPin() pin.move_to(origin, DR) hand = Hand() update_hand = UpdateFromFunc( hand, lambda m: m.move_to(one_dot.get_center(), LEFT) ) circle = Circle( color=YELLOW, radius=get_norm(one_point - origin) ) self.add(circle) self.add(pin, one_dot) self.add_foreground_mobjects(hand) title = OldTexText( "Numbers on the unit circle", "$\\rightarrow$", "pure rotation." ) title.set_width(FRAME_WIDTH - 1) title.to_edge(UP, buff=MED_SMALL_BUFF) title.add_background_rectangle(buff=SMALL_BUFF) self.add_foreground_mobjects(title) self.background_plane.coordinate_labels.submobjects.pop(-1) n_angles = 12 angles = list(np.linspace(-PI, PI, n_angles + 2)[1:-1]) random.shuffle(angles) for angle in angles: plane.save_state() temp_plane = plane.copy() z = np.exp(complex(0, angle)) if angle is angles[0]: z_label = DecimalNumber( z, num_decimal_places=2, ) z_label.set_stroke(BLACK, width=11, background=True) z_label_rect = BackgroundRectangle(z_label) z_label_rect.set_fill(opacity=0) z_point = plane.number_to_point(z) z_arrow = Arrow(2.5 * z_point, z_point, buff=SMALL_BUFF) z_dot = Dot(z_point) z_label_start_center = z_label.get_center() z_label.next_to( z_arrow.get_start(), np.sign(z_arrow.get_start()[1]) * UP, ) z_label_end_center = z_label.get_center() z_group = VGroup(z_arrow, z_dot, z_label) z_group.set_color(GREEN) z_group.add_to_back(z_label_rect) z_arrow.set_stroke(BLACK, 1) z_dot.set_stroke(BLACK, 1) if angle is angles[0]: self.play( FadeInFromDown(z_label_rect), FadeInFromDown(z_label), GrowArrow(z_arrow), FadeInFromLarge(z_dot), ) else: alpha_tracker = ValueTracker(0) self.play( ReplacementTransform(old_z_dot, z_dot), ReplacementTransform(old_z_arrow, z_arrow), UpdateFromFunc( z_label_rect, lambda m: m.replace(z_label) ), ChangeDecimalToValue( z_label, z, position_update_func=lambda m: m.move_to( interpolate( z_label_start_center, z_label_end_center, alpha_tracker.get_value() ) ) ), alpha_tracker.set_value, 1, # hand.move_to, one_point, LEFT ) old_z_dot = z_dot old_z_arrow = z_arrow VGroup(old_z_arrow, old_z_dot) self.play( Rotate(plane, angle, run_time=2), update_hand, Animation(z_group), ) self.wait() self.add(temp_plane, z_group) self.play( FadeOut(plane), FadeOut(hand), FadeIn(temp_plane), ) plane.restore() self.remove(temp_plane) self.add(plane, *z_group) class IfYouNeedAWarmUp(TeacherStudentsScene): def construct(self): screen = self.screen screen.set_height(4) screen.to_corner(UL) self.add(screen) self.teacher_says( "If you need \\\\ a warm up", bubble_config={"width": 3.5, "height": 3}, ) self.play_all_student_changes( "pondering", look_at=screen, ) self.wait(3) self.play(RemovePiCreatureBubble(self.teacher)) self.wait(3) class LinusThinksAboutStretching(Scene): def construct(self): linus = Linus() top_line = NumberLine(color=GREY) top_line.to_edge(UP) top_line.add_numbers() linus.move_to(3 * LEFT + DOWN) self.add(linus, top_line) scalars = [3, 0.5, 2] for scalar in scalars: lower_line = NumberLine( x_min=-14, x_max=14, color=BLUE ) lower_line.next_to(top_line, DOWN, MED_LARGE_BUFF) lower_line.numbers = lower_line.get_number_mobjects() for number in lower_line.numbers: number.add_updater(lambda m: m.next_to( lower_line.number_to_point(m.get_value()), DOWN, MED_SMALL_BUFF, )) lower_line.save_state() lower_line.numbers.save_state() self.add(lower_line, *lower_line.numbers) words = OldTexText("Multiply by {}".format(scalar)) words.next_to(lower_line.numbers, DOWN) self.play( ApplyMethod( lower_line.stretch, scalar, 0, run_time=2 ), # LaggedStartMap(FadeIn, words, run_time=1), FadeInFromLarge(words, 1.0 / scalar), linus.look_at, top_line.number_to_point(scalar) ) self.play(Blink(linus)) self.play( FadeOut(lower_line), FadeOut(lower_line.numbers), FadeOut(words), FadeIn(lower_line.saved_state, remover=True), FadeIn(lower_line.numbers.saved_state, remover=True), linus.look_at, top_line.number_to_point(0) ) self.play(linus.change, "confused", DOWN + RIGHT) self.wait(2) self.play(Blink(linus)) self.wait(2) class LinusReactions(Scene): def construct(self): linus = Linus() for mode in "confused", "sad", "erm", "angry", "pleading": self.play(linus.change, mode, 2 * RIGHT) self.wait() self.play(Blink(linus)) self.wait() class OneDegreeOfFreedomForRotation(Scene): def construct(self): circle = CheckeredCircle(radius=2, stroke_width=10) r_line = Line(circle.get_center(), circle.get_right()) moving_r_line = r_line.copy() right_dot = Dot(color=WHITE) right_dot.move_to(circle.get_right()) circle.add(moving_r_line, right_dot) center_dot = Dot(color=WHITE) def get_angle(): return moving_r_line.get_angle() % TAU angle_label = Integer(0, unit="^\\circ") angle_label.scale(2) angle_label.add_updater( lambda m: m.set_value(get_angle() / DEGREES) ) angle_label.add_updater( lambda m: m.next_to(circle, UP, MED_LARGE_BUFF) ) def get_arc(): return Arc( angle=get_angle(), radius=0.5, color=GREY_B, ) arc = get_arc() arc.add_updater(lambda m: m.become(get_arc())) self.add(circle, center_dot, r_line, angle_label, arc) angles = IntroduceStereographicProjection.CONFIG.get( "example_angles" ) for angle in angles: self.play(Rotate(circle, angle, run_time=4)) self.wait() class StereographicProjectionTitle(Scene): def construct(self): title = OldTexText("Stereographic projection") final_title = title.copy() final_title.set_width(10) final_title.to_edge(UP) title.rotate(-90 * DEGREES) title.next_to(RIGHT, RIGHT, SMALL_BUFF) title.apply_complex_function(np.exp) title.rotate(90 * DEGREES) title.set_height(6) title.to_edge(UP) self.play(Write(title)) self.play(Transform(title, final_title, run_time=2)) self.wait() class IntroduceStereographicProjection(MovingCameraScene): CONFIG = { "n_sample_points": 16, "circle_config": { "n_pieces": 16, "radius": 2, "stroke_width": 7, }, "example_angles": [ 30 * DEGREES, 120 * DEGREES, 240 * DEGREES, 80 * DEGREES, -60 * DEGREES, 135 * DEGREES, ] } def construct(self): self.setup_plane() self.draw_lines() self.describe_individual_points() self.remind_that_most_points_are_not_projected() def setup_plane(self): self.plane = self.get_plane() self.circle = self.get_circle() self.circle_shadow = self.get_circle_shadow() self.add(self.plane) self.add(self.circle_shadow) self.add(self.circle) def draw_lines(self): plane = self.plane circle = self.circle circle.save_state() circle.generate_target() self.project_mobject(circle.target) circle_points = self.get_sample_circle_points() dots = VGroup(*[Dot(p) for p in circle_points]) dots.set_sheen(-0.2, DR) dots.set_stroke(GREY_D, 2, background=True) arrows = VGroup() for dot in dots: dot.scale(0.75) dot.generate_target() dot.target.move_to( self.project(dot.get_center()) ) arrow = Arrow( dot.get_center(), dot.target.get_center(), ) arrows.add(arrow) neg_one_point = plane.number_to_point(-1) neg_one_dot = Dot(neg_one_point) neg_one_dot.set_fill(YELLOW) lines = self.get_lines() special_index = self.n_sample_points // 2 + 1 line = lines[special_index] dot = dots[special_index] arrow = arrows[special_index] dot_target_outline = dot.target.copy() dot_target_outline.set_stroke(RED, 2) dot_target_outline.set_fill(opacity=0) dot_target_outline.scale(1.5) v_line = Line(UP, DOWN) v_line.set_height(FRAME_HEIGHT) v_line.set_stroke(RED, 5) self.play(LaggedStartMap(FadeInFromLarge, dots)) self.play(FadeInFromLarge(neg_one_dot)) self.add(lines, neg_one_dot, dots) self.play(LaggedStartMap(ShowCreation, lines)) self.wait() self.play( lines.set_stroke, {"width": 0.5}, line.set_stroke, {"width": 4}, ) self.play(ShowCreation(dot_target_outline)) self.play(ShowCreationThenDestruction(v_line)) self.play(MoveToTarget(dot)) self.wait() self.play( lines.set_stroke, {"width": 1}, FadeOut(dot_target_outline), MoveToTarget(circle), *map(MoveToTarget, dots), run_time=2, ) self.wait() self.lines = lines self.dots = dots def describe_individual_points(self): plane = self.plane one_point, zero_point, i_point, neg_i_point, neg_one_point = [ plane.number_to_point(n) for n in [1, 0, complex(0, 1), complex(0, -1), -1] ] i_pin = PushPin() i_pin.pin_to(i_point) neg_i_pin = PushPin() neg_i_pin.pin_to(neg_i_point) dot = Dot() dot.set_stroke(RED, 3) dot.set_fill(opacity=0) dot.scale(1.5) dot.move_to(one_point) arc1 = Arc(angle=TAU / 4, radius=2) arc2 = Arc( angle=85 * DEGREES, radius=2, start_angle=TAU / 4, ) arc3 = Arc( angle=-85 * DEGREES, radius=2, start_angle=-TAU / 4, ) VGroup(arc1, arc2, arc3).set_stroke(RED) frame = self.camera_frame frame_height_tracker = ValueTracker(frame.get_height()) frame_height_growth = frame_height_tracker.add_updater( lambda m, dt: m.set_value(m.get_value + 0.5 * dt) ) neg_one_tangent = VGroup( Line(ORIGIN, UP), Line(ORIGIN, DOWN), ) neg_one_tangent.set_height(25) neg_one_tangent.set_stroke(YELLOW, 5) neg_one_tangent.move_to(neg_one_point) self.play(ShowCreation(dot)) self.wait() self.play(dot.move_to, zero_point) self.wait() dot.move_to(i_point) self.play(ShowCreation(dot)) self.play(FadeIn(i_pin, UL)) self.wait() self.play( dot.move_to, neg_i_point, path_arc=-60 * DEGREES ) self.play(FadeIn(neg_i_pin, UL)) self.wait() self.play( dot.move_to, one_point, path_arc=-60 * DEGREES ) frame.add_updater( lambda m: m.set_height(frame_height_tracker.get_value()) ) triplets = [ (arc1, i_point, TAU / 4), (arc2, neg_one_point, TAU / 4), (arc3, neg_one_point, -TAU / 4), ] for arc, point, path_arc in triplets: self.play( ShowCreation(arc), dot.move_to, point, path_arc=path_arc, run_time=2 ) self.wait() self.play( ApplyFunction(self.project_mobject, arc, run_time=2) ) self.wait() self.play(FadeOut(arc)) self.wait() if arc is arc1: self.add(frame, frame_height_growth) elif arc is arc2: self.play(dot.move_to, neg_i_point) self.wait(2) self.play(*map(ShowCreation, neg_one_tangent)) self.wait() self.play(FadeOut(neg_one_tangent)) self.wait(2) frame.clear_updaters() self.play( frame.set_height, FRAME_HEIGHT, self.lines.set_stroke, {"width": 0.5}, FadeOut(self.dots), FadeOut(dot), run_time=2, ) def remind_that_most_points_are_not_projected(self): plane = self.plane circle = self.circle sample_values = [0, complex(1, 1), complex(-2, -1)] sample_points = [ plane.number_to_point(value) for value in sample_values ] sample_dots = VGroup(*[Dot(p) for p in sample_points]) sample_dots.set_fill(GREEN) self.play( FadeOut(self.lines), Restore(circle), ) for value, dot in zip(sample_values, sample_dots): cross = Cross(dot) cross.scale(2) label = Integer(value) if value is sample_values[1]: label.next_to(dot, UL, SMALL_BUFF) else: label.next_to(dot, UR, SMALL_BUFF) self.play( FadeInFromLarge(dot, 3), FadeInFromDown(label) ) self.play(ShowCreation(cross)) self.play(*map(FadeOut, [dot, cross, label])) self.wait() self.play( FadeIn(self.lines), MoveToTarget(circle, run_time=2), ) self.wait() # Helpers def get_plane(self): plane = ComplexPlane( unit_size=2, color=GREY, secondary_color=GREY_D, x_radius=FRAME_WIDTH, y_radius=FRAME_HEIGHT, stroke_width=2, ) plane.add_coordinates() return plane def get_circle(self): circle = CheckeredCircle( **self.circle_config ) circle.set_stroke(width=7) return circle def get_circle_shadow(self): circle_shadow = CheckeredCircle( **self.circle_config ) circle_shadow.set_stroke(opacity=0.65) return circle_shadow def get_sample_circle_points(self): plane = self.plane n = self.n_sample_points rotater = 1 if hasattr(self, "circle_shadow"): point = self.circle_shadow[0].get_points()[0] rotater = complex(*point[:2]) rotater /= abs(rotater) numbers = [ rotater * np.exp(complex(0, TAU * x / n)) for x in range(-(n // 2) + 1, n // 2) ] return [ plane.number_to_point(number) for number in numbers ] def get_lines(self): plane = self.plane neg_one_point = plane.number_to_point(-1) circle_points = self.get_sample_circle_points() lines = VGroup(*[ Line(neg_one_point, point) for point in circle_points ]) for line in lines: length = line.get_length() line.scale(20 / length, about_point=neg_one_point) line.set_stroke(YELLOW, np.clip(length, 0, 1)) return lines def project(self, point): return stereo_project_point(point, axis=0, r=2) def project_mobject(self, mobject): return stereo_project(mobject, axis=0, r=2, outer_r=6) class IntroduceStereographicProjectionLinusView(IntroduceStereographicProjection): def construct(self): self.describe_individual_points() self.point_at_infinity() self.show_90_degree_rotation() self.talk_through_90_degree_rotation() self.show_four_rotations() self.show_example_angles() def describe_individual_points(self): plane = self.plane = self.get_plane() circle = self.circle = self.get_circle() linus = self.linus = self.get_linus() angles = np.arange(-135, 180, 45) * DEGREES sample_numbers = [ np.exp(complex(0, angle)) for angle in angles ] sample_points = [ plane.number_to_point(number) for number in sample_numbers ] projected_sample_points = [ self.project(point) for point in sample_points ] dots = VGroup(*[Dot() for x in range(8)]) dots.set_fill(WHITE) dots.set_stroke(BLACK, 1) def generate_dot_updater(circle_piece): return lambda d: d.move_to(circle_piece.get_points()[0]) for dot, piece in zip(dots, circle[::(len(circle) // 8)]): dot.add_updater(generate_dot_updater(piece)) stot = "(\\sqrt{2} / 2)" labels_tex = [ "-{}-{}i".format(stot, stot), "-i", "{}-{}i".format(stot, stot), "1", "{}+{}i".format(stot, stot), "i", "-{}+{}i".format(stot, stot), ] labels = VGroup(*[Tex(tex) for tex in labels_tex]) vects = it.cycle([RIGHT, RIGHT]) arrows = VGroup() for label, point, vect in zip(labels, projected_sample_points, vects): arrow = Arrow(vect, ORIGIN) arrow.next_to(point, vect, 2 * SMALL_BUFF) arrows.add(arrow) label.set_stroke(width=0, background=True) if stot in label.get_tex(): label.set_height(0.5) else: label.set_height(0.5) label.set_stroke(WHITE, 2, background=True) label.next_to(arrow, vect, SMALL_BUFF) frame = self.camera_frame frame.set_height(12) self.add(linus) self.add(circle, *dots) self.play( ApplyFunction(self.project_mobject, circle), run_time=2 ) self.play(linus.change, "confused") self.wait() for i in [1, 0]: self.play( LaggedStartMap(GrowArrow, arrows[i::2]), LaggedStartMap(Write, labels[i::2]) ) self.play(Blink(linus)) self.dots = dots def point_at_infinity(self): circle = self.circle linus = self.linus label = OldTexText( "$-1$ is \\\\ at $\\pm \\infty$" ) label.scale(1.5) label.next_to(circle, LEFT, buff=1.25) arrows = VGroup(*[ Vector(3 * v + 0.0 * RIGHT).next_to(label, v, buff=MED_LARGE_BUFF) for v in [UP, DOWN] ]) arrows.set_color(YELLOW) self.play( Write(label), linus.change, "awe", label, *map(GrowArrow, arrows) ) self.neg_one_label = VGroup(label, arrows) def show_90_degree_rotation(self): angle_tracker = ValueTracker(0) circle = self.circle linus = self.linus hand = Hand() hand.flip() one_dot = self.dots[0] hand.add_updater( lambda h: h.move_to(one_dot.get_center(), RIGHT) ) def update_circle(circle): angle = angle_tracker.get_value() new_circle = self.get_circle() new_circle.rotate(angle) self.project_mobject(new_circle) circle.become(new_circle) circle.add_updater(update_circle) self.play( FadeIn(hand), one_dot.set_fill, RED, ) for angle in 90 * DEGREES, 0: self.play( ApplyMethod( angle_tracker.set_value, angle, run_time=3, ), linus.change, "confused", hand ) self.wait() self.play(Blink(linus)) self.hand = hand self.angle_tracker = angle_tracker def talk_through_90_degree_rotation(self): linus = self.linus dots = self.dots one_dot = dots[0] i_dot = dots[2] neg_i_dot = dots[-2] kwargs1 = { "path_arc": -90 * DEGREES, "buff": SMALL_BUFF, } kwargs2 = dict(kwargs1) kwargs2["path_arc"] = -40 * DEGREES arrows = VGroup( Arrow(one_dot, i_dot, **kwargs1), Arrow(i_dot, 6 * UP + LEFT, **kwargs2), Arrow(6 * DOWN + LEFT, neg_i_dot, **kwargs2), Arrow(neg_i_dot, one_dot, **kwargs1) ) arrows.set_stroke(WHITE, 3) one_to_i, i_to_neg_1, neg_one_to_neg_i, neg_i_to_one = arrows for arrow in arrows: self.play( ShowCreation(arrow), linus.look_at, arrow ) self.wait(2) self.arrows = arrows def show_four_rotations(self): angle_tracker = self.angle_tracker linus = self.linus hand = self.hand linus.add_updater(lambda l: l.look_at(hand)) linus.add_updater(lambda l: l.eyes.next_to(l.body, UP, 0)) for angle in np.arange(TAU / 4, 5 * TAU / 4, TAU / 4): self.play( ApplyMethod( angle_tracker.set_value, angle, run_time=3, ), ) self.wait() self.play(FadeOut(self.arrows)) def show_example_angles(self): angle_tracker = self.angle_tracker angle_tracker.set_value(0) for angle in self.example_angles: self.play( ApplyMethod( angle_tracker.set_value, angle, run_time=4, ), ) self.wait() # def get_linus(self): linus = Linus() linus.move_to(3 * RIGHT) linus.to_edge(DOWN) linus.look_at(ORIGIN) return linus class ShowRotationUnderStereographicProjection(IntroduceStereographicProjection): def construct(self): self.setup_plane() self.apply_projection() self.show_90_degree_rotation() self.talk_through_90_degree_rotation() self.show_four_rotations() self.show_example_angles() def apply_projection(self): plane = self.plane circle = self.circle neg_one_point = plane.number_to_point(-1) neg_one_dot = Dot(neg_one_point) neg_one_dot.set_fill(YELLOW) lines = always_redraw(self.get_lines) def generate_dot_updater(circle_piece): return lambda d: d.move_to(circle_piece.get_points()[0]) for circ, color in [(self.circle_shadow, RED), (self.circle, WHITE)]: for piece in circ[::(len(circ) // 8)]: dot = Dot(color=color) dot.set_fill(opacity=circ.get_stroke_opacity()) dot.add_updater(generate_dot_updater(piece)) self.add(dot) self.add(lines, neg_one_dot) self.play(*map(ShowCreation, lines)) self.play( ApplyFunction(self.project_mobject, circle), lines.set_stroke, {"width": 0.5}, run_time=2 ) self.play( self.camera_frame.set_height, 12, run_time=2 ) self.wait() def show_90_degree_rotation(self): circle = self.circle circle_shadow = self.circle_shadow def get_rotated_one_point(): return circle_shadow[0].get_points()[0] def get_angle(): return angle_of_vector(get_rotated_one_point()) self.get_angle = get_angle one_dot = Dot(color=RED) one_dot.add_updater( lambda m: m.move_to(get_rotated_one_point()) ) hand = Hand() hand.move_to(one_dot.get_center(), LEFT) def update_circle(circle): new_circle = self.get_circle() new_circle.rotate(get_angle()) self.project_mobject(new_circle) circle.become(new_circle) circle.add_updater(update_circle) self.add(one_dot, hand) hand.add_updater( lambda h: h.move_to(one_dot.get_center(), LEFT) ) self.play( FadeIn(hand, RIGHT), FadeInFromLarge(one_dot, 3), ) for angle in 90 * DEGREES, -90 * DEGREES: self.play( Rotate(circle_shadow, angle, run_time=3), ) self.wait(2) def talk_through_90_degree_rotation(self): plane = self.plane points = [ plane.number_to_point(z) for z in [1, complex(0, 1), -1, complex(0, -1)] ] arrows = VGroup() for p1, p2 in adjacent_pairs(points): arrow = Arrow( p1, p2, path_arc=180 * DEGREES, ) arrow.set_stroke(GREY_B, width=3) arrow.tip.set_fill(GREY_B) arrows.add(arrow) for arrow in arrows: self.play(ShowCreation(arrow)) self.wait(2) self.arrows = arrows def show_four_rotations(self): circle_shadow = self.circle_shadow for x in range(4): self.play( Rotate(circle_shadow, TAU / 4, run_time=3) ) self.wait() self.play(FadeOut(self.arrows)) def show_example_angles(self): circle_shadow = self.circle_shadow angle_label = Integer(0, unit="^\\circ") angle_label.scale(1.5) angle_label.next_to( circle_shadow.get_top(), UR, ) self.play(FadeInFromDown(angle_label)) self.add(angle_label) for angle in self.example_angles: d_angle = angle - self.get_angle() self.play( Rotate(circle_shadow, d_angle), ChangingDecimal( angle_label, lambda a: (self.get_angle() % TAU) / DEGREES ), run_time=4 ) self.wait() class WriteITimesW(Scene): def construct(self): mob = OldTex("i", "\\cdot", "w") mob[0].set_color(GREEN) mob.scale(3) self.play(Write(mob)) self.wait() class IntroduceFelix(PiCreatureScene, SpecialThreeDScene): def setup(self): PiCreatureScene.setup(self) SpecialThreeDScene.setup(self) def construct(self): self.introduce_felix() self.add_plane() self.show_in_three_d() def introduce_felix(self): felix = self.felix = self.pi_creature arrow = Vector(DL, color=WHITE) arrow.next_to(felix, UR) label = OldTexText("Felix the Flatlander") label.next_to(arrow.get_start(), UP) self.add(felix) self.play( felix.change, "wave_1", label, Write(label), GrowArrow(arrow), ) self.play(Blink(felix)) self.play(felix.change, "thinking", label) self.to_fade = VGroup(label, arrow) def add_plane(self): plane = NumberPlane(y_radius=10) axes = self.get_axes() to_fade = self.to_fade felix = self.felix self.add(axes, plane, felix) self.play( ShowCreation(axes), ShowCreation(plane), FadeOut(to_fade), ) self.wait() self.plane = plane self.axes = axes def show_in_three_d(self): felix = self.pi_creature plane = self.plane axes = self.axes # back_plane = Rectangle().replace(plane, stretch=True) # back_plane.shade_in_3d = True # back_plane.set_fill(GREY_B, opacity=0.5) # back_plane.set_sheen(1, UL) # back_plane.shift(SMALL_BUFF * IN) # back_plane.set_stroke(width=0) # back_plane = ParametricSurface( # lambda u, v: u * RIGHT + v * UP # ) # back_plane.replace(plane, stretch=True) # back_plane.set_stroke(width=0) # back_plane.set_fill(GREY_B, opacity=0.5) sphere = self.get_sphere() # sphere.set_fill(BLUE_E, 0.5) self.move_camera( phi=70 * DEGREES, theta=-110 * DEGREES, added_anims=[FadeOut(plane)], run_time=2 ) self.begin_ambient_camera_rotation() self.add(axes, sphere) self.play( Write(sphere), felix.change, "confused" ) self.wait() axis_angle_pairs = [ (RIGHT, 90 * DEGREES), (OUT, 45 * DEGREES), (UR + OUT, 120 * DEGREES), (RIGHT, 90 * DEGREES), ] for axis, angle in axis_angle_pairs: self.play(Rotate( sphere, angle=angle, axis=axis, run_time=2, )) self.wait(2) # def create_pi_creature(self): return Felix().move_to(4 * LEFT + 2 * DOWN) class IntroduceThreeDNumbers(SpecialThreeDScene): CONFIG = { "camera_config": { "exponential_projection": False, } } def construct(self): self.add_third_axis() self.reorient_axes() self.show_example_number() def add_third_axis(self): plane = ComplexPlane( y_radius=FRAME_WIDTH / 4, unit_size=2, secondary_line_ratio=1, ) plane.add_coordinates() title = OldTexText("Complex Plane") title.scale(1.8) title.add_background_rectangle() title.to_corner(UL, buff=MED_SMALL_BUFF) real_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) imag_line = Line(DOWN, UP).set_height(FRAME_HEIGHT) real_line.set_color(YELLOW) imag_line.set_color(RED) for label in plane.coordinate_labels: label.remove(label.background_rectangle) label.shift(SMALL_BUFF * IN) self.add_fixed_orientation_mobjects(label) reals = plane.coordinate_labels[:7] imags = plane.coordinate_labels[7:] self.add(plane, title) for line, group in (real_line, reals), (imag_line, imags): line.set_stroke(width=5) self.play( ShowCreationThenDestruction(line), LaggedStartMap( Indicate, group, rate_func=there_and_back, color=line.get_color(), ), run_time=2, ) self.plane = plane self.title = title def reorient_axes(self): z_axis = NumberLine(unit_size=2) z_axis.rotate(90 * DEGREES, axis=DOWN) z_axis.rotate(90 * DEGREES, axis=OUT) z_axis.set_color(WHITE) z_axis_top = Line( z_axis.number_to_point(0), z_axis.get_end(), ) z_axis_top.match_style(z_axis) z_unit_line = Line( z_axis.number_to_point(0), z_axis.number_to_point(1), color=RED, stroke_width=5 ) j_labels = VGroup( OldTex("-2j"), OldTex("-j"), OldTex("j"), OldTex("2j"), ) for label, num in zip(j_labels, [-2, -1, 1, 2]): label.next_to(z_axis.number_to_point(num), RIGHT, MED_SMALL_BUFF) self.add_fixed_orientation_mobjects(label) plane = self.plane colored_ = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) y_line = Line(DOWN, UP).set_height(FRAME_WIDTH) z_line = Line(IN, OUT).set_depth(FRAME_WIDTH) colored_.set_stroke(GREEN, 5) y_line.set_stroke(RED, 5) z_line.set_stroke(YELLOW, 5) colored_coord_lines = VGroup(colored_, y_line, z_line) coord_lines = VGroup( plane.axes[0], plane.axes[1], z_axis, ) for i1, i2 in [(0, 2), (1, 0), (2, 1)]: coord_lines[i1].target = coord_lines[i2].copy() new_title = OldTexText("Imaginary plane") new_title.replace(self.title) new_title.move_to(self.title) self.add(z_axis, plane, z_axis_top) self.move_camera( phi=70 * DEGREES, theta=-80 * DEGREES, added_anims=[ plane.set_stroke, {"opacity": 0.5}, ], run_time=2, ) self.begin_ambient_camera_rotation(rate=0.02) self.wait() self.play(FadeIn(j_labels, IN)) z_axis.add(j_labels) self.play( ShowCreationThenDestruction(z_unit_line), run_time=2 ) self.wait(4) group = VGroup(*it.chain(plane.coordinate_labels, j_labels)) for label in group: label.generate_target() axis = np.ones(3) label.target.rotate_about_origin(-120 * DEGREES, axis=axis) label.target.rotate(120 * DEGREES, axis=axis) for y, label in zip([-2, -1, 1, 2], j_labels): label.target.scale(0.65) label.target.next_to( 2 * y * UP, RIGHT, 2 * SMALL_BUFF ) self.remove(z_axis_top) self.play( LaggedStartMap(MoveToTarget, group, lag_ratio=0.8), LaggedStartMap(MoveToTarget, coord_lines, lag_ratio=0.8), FadeOut(self.title), FadeIn(new_title), run_time=3 ) self.add(z_axis_top) self.wait(3) for line, wait in zip(colored_coord_lines, [False, True, True]): self.play( ShowCreationThenDestruction(line), run_time=2 ) if wait: self.wait() def show_example_number(self): x, y, z = coords = 2 * np.array([1.5, -1, 1.25]) dot = Sphere(radius=0.05) dot.set_fill(GREY_B) dot.move_to(coords) point_line = Line(ORIGIN, coords) point_line.set_stroke(WHITE, 1) z_line = Line(ORIGIN, z * OUT) x_line = Line(z_line.get_end(), z_line.get_end() + x * RIGHT) y_line = Line(x_line.get_end(), x_line.get_end() + y * UP) x_line.set_stroke(GREEN, 5) y_line.set_stroke(RED, 5) z_line.set_stroke(YELLOW, 5) lines = VGroup(z_line, x_line, y_line) number_label = OldTex( str(z / 2), "+", str(x / 2), "i", "+", str(y / 2), "j", tex_to_color_map={ str(z / 2): YELLOW, str(x / 2): GREEN, str(y / 2): RED, } ) number_label.next_to(ORIGIN, RIGHT, LARGE_BUFF) number_label.to_edge(UP) self.add_fixed_in_frame_mobjects(number_label) self.play( ShowCreation(point_line), FadeIn(dot, -coords), FadeInFromDown(number_label) ) self.wait() for num, line in zip([z, x, y], lines): tex = number_label.get_part_by_tex(str(num / 2)) rect = SurroundingRectangle(tex) rect.set_color(WHITE) self.add_fixed_in_frame_mobjects(rect) self.play( ShowCreation(line), ShowCreationThenDestruction(rect), run_time=2 ) self.remove_fixed_in_frame_mobjects(rect) self.wait() self.wait(15) class MentionImpossibilityOf3dNumbers(TeacherStudentsScene): def construct(self): equations = VGroup( OldTex("ij = ?"), OldTex("ji = ?"), ) equations.arrange(RIGHT, buff=LARGE_BUFF) equations.scale(1.5) equations.to_edge(UP) self.add(equations) why = OldTexText("Why not?") why.next_to(self.students[1], UP) self.teacher_says( "Such 3d numbers \\\\ have no good \\\\ multiplication rule", bubble_config={"width": 4, "height": 3}, ) self.play_all_student_changes("confused") self.wait(2) self.play( self.students[1].change, "maybe", FadeInFromLarge(why), ) self.wait(4) class SphereExamplePointsDecimal(Scene): CONFIG = { "point_rotation_angle_axis_pairs": [ (45 * DEGREES, DOWN), (120 * DEGREES, OUT), (35 * DEGREES, rotate_vector(RIGHT, 30 * DEGREES)), (90 * DEGREES, IN), ] } def construct(self): decimals = VGroup(*[ DecimalNumber( 0, num_decimal_places=3, color=color, include_sign=True, edge_to_fix=RIGHT, ) for color in [YELLOW, GREEN, RED] ]) number_label = VGroup( decimals[0], OldTex("+"), decimals[1], OldTex("i"), OldTex("+"), decimals[2], OldTex("j"), ) number_label.arrange(RIGHT, buff=SMALL_BUFF) number_label.to_corner(UL) point = VectorizedPoint(OUT) def generate_decimal_updater(decimal, index): shifted_i = (index - 1) % 3 decimal.add_updater(lambda d: d.set_value( point.get_location()[shifted_i] )) return decimal for i, decimal in enumerate(decimals): self.add(generate_decimal_updater(decimal, i)) decimal_braces = VGroup() for decimal, char in zip(decimals, "wxy"): brace = Brace(decimal, DOWN, buff=SMALL_BUFF) label = brace.get_tex(char, buff=SMALL_BUFF) label.match_color(decimal) brace.add(label) decimal_braces.add(brace) equation = OldTex( "w^2 + x^2 + y^2 = 1", tex_to_color_map={ "w": YELLOW, "x": GREEN, "y": RED, } ) equation.next_to(decimal_braces, DOWN, MED_LARGE_BUFF) self.add(number_label) self.add(decimal_braces) self.add(equation) pairs = self.point_rotation_angle_axis_pairs for angle, axis in pairs: self.play( Rotate(point, angle, axis=axis, about_point=ORIGIN), run_time=2 ) self.wait() class TwoDStereographicProjection(IntroduceFelix): CONFIG = { "camera_config": { "exponential_projection": False, }, "sphere_sample_point_u_range": np.arange( 0, PI, PI / 16, ), "sphere_sample_point_v_range": np.arange( 0, TAU, TAU / 16, ), "n_sample_rotation_cycles": 2, "lift_labels": True, } def construct(self): self.add_parts() self.talk_through_sphere() self.draw_projection_lines() self.show_point_at_infinity() self.show_a_few_rotations() def add_parts(self, run_time=1): felix = self.felix = self.pi_creature felix.shift(1.5 * DL) axes = self.axes = self.get_axes() sphere = self.sphere = self.get_sphere() c2p = axes.coords_to_point labels = self.labels = VGroup( OldTex("i").next_to(c2p(1, 0, 0), DR, SMALL_BUFF), OldTex("-i").next_to(c2p(-1, 0, 0), DL, SMALL_BUFF), OldTex("j").next_to(c2p(0, 1, 0), UL, SMALL_BUFF), OldTex("-j").next_to(c2p(0, -1, 0), DL, SMALL_BUFF), OldTex("1").rotate( 90 * DEGREES, RIGHT, ).next_to(c2p(0, 0, 1), RIGHT + OUT, SMALL_BUFF), OldTex("-1").rotate( 90 * DEGREES, RIGHT, ).next_to(c2p(0, 0, -1), RIGHT + IN, SMALL_BUFF), ) if self.lift_labels: for sm in labels[:4].family_members_with_points(): sm.add(VectorizedPoint( 0.25 * DOWN + 0.25 * OUT )) labels.set_stroke(width=0, background=True) for submob in labels.get_family(): submob.shade_in_3d = True self.add(felix, axes, sphere, labels) self.move_camera( **self.get_default_camera_position(), run_time=run_time ) self.begin_ambient_camera_rotation(rate=0.01) self.play( felix.change, "pondering", sphere, run_time=run_time, ) def talk_through_sphere(self): point = VectorizedPoint(OUT) arrow = Vector(IN, shade_in_3d=True) arrow.set_fill(PINK) arrow.set_stroke(BLACK, 1) def get_dot(): dot = Sphere(radius=0.05, u_max=PI / 2) dot.set_fill(PINK) dot.set_stroke(width=0) dot.move_to(2.05 * OUT) dot.apply_matrix( z_to_vector(normalize(point.get_location())), about_point=ORIGIN ) return dot dot = get_dot() dot.add_updater( lambda d: d.become(get_dot()) ) def update_arrow(arrow): target_point = 2.1 * point.get_location() rot_matrix = np.dot( z_to_vector(normalize(target_point)), np.linalg.inv( z_to_vector(normalize(-arrow.get_vector())) ) ) arrow.apply_matrix(rot_matrix) arrow.shift(target_point - arrow.get_end()) return arrow arrow.add_updater(update_arrow) self.add(self.sphere, dot, arrow) pairs = SphereExamplePointsDecimal.CONFIG.get( "point_rotation_angle_axis_pairs" ) for angle, axis in pairs: self.play( Rotate(point, angle, axis=axis, about_point=ORIGIN), run_time=2 ) self.wait() self.play(FadeOut(dot), FadeOut(arrow)) def draw_projection_lines(self): sphere = self.sphere axes = self.axes radius = sphere.get_width() / 2 neg_one_point = axes.coords_to_point(0, 0, -1) neg_one_dot = Dot( neg_one_point, color=YELLOW, shade_in_3d=True ) xy_plane = StereoProjectedSphere( u_max=15 * PI / 16, **self.sphere_config ) xy_plane.set_fill(WHITE, 0.25) xy_plane.set_stroke(width=0) point_mob = VectorizedPoint(2 * OUT) point_mob.add_updater( lambda m: m.move_to(radius * normalize(m.get_center())) ) point_mob.move_to([1, -1, 1]) point_mob.update(0) def get_projection_line(sphere_point): to_sphere = Line(neg_one_point, sphere_point) to_plane = Line( sphere_point, self.project_point(sphere_point) ) line = VGroup(to_sphere, to_plane) line.set_stroke(YELLOW, 3) for submob in line: submob.shade_in_3d = True return line def get_sphere_dot(sphere_point): dot = Dot() dot.set_shade_in_3d(True) dot.set_fill(PINK) dot.shift(OUT) dot.apply_matrix( z_to_vector(sphere_point), about_point=ORIGIN, ) dot.move_to(1.01 * sphere_point) dot.add(VectorizedPoint(5 * sphere_point)) return dot def get_projection_dot(sphere_point): projection = self.project_point(sphere_point) dot = Dot(projection, shade_in_3d=True) dot.add(VectorizedPoint(dot.get_center() + 0.1 * OUT)) dot.set_fill(WHITE) return dot point = point_mob.get_location() dot = get_sphere_dot(point) line = get_projection_line(point) projection_dot = get_projection_dot(point) sample_points = [ radius * sphere.func(u, v) for u in self.sphere_sample_point_u_range for v in self.sphere_sample_point_v_range ] lines = VGroup(*[get_projection_line(p) for p in sample_points]) lines.set_stroke(width=1) north_lines = lines[:len(lines) // 2] south_lines = lines[len(lines) // 2:] self.add(xy_plane, sphere) self.play(Write(xy_plane)) self.wait(2) self.play(sphere.set_fill, BLUE_E, 0.5) self.play(FadeInFromLarge(dot)) self.play( FadeIn(neg_one_dot), ShowCreation(line), ) self.wait(2) self.play(ReplacementTransform( dot.copy(), projection_dot )) def get_point(): return 2 * normalize(point_mob.get_location()) dot.add_updater( lambda d: d.become(get_sphere_dot(get_point())) ) line.add_updater( lambda l: l.become(get_projection_line(get_point())) ) projection_dot.add_updater( lambda d: d.become(get_projection_dot(get_point())) ) self.play( point_mob.move_to, radius * normalize(np.array([1, -1, -1])), run_time=3 ) self.move_camera( theta=-150 * DEGREES, run_time=3 ) self.add(axes, sphere, xy_plane, dot, line) for point in np.array([-2, 1, -0.5]), np.array([-0.01, -0.01, 1]): self.play( point_mob.move_to, radius * normalize(point), run_time=3 ) self.wait(2) # Project norther hemisphere north_hemisphere = self.get_sphere() n = len(north_hemisphere) north_hemisphere.remove(*north_hemisphere[n // 2:]) north_hemisphere.generate_target() self.project_mobject(north_hemisphere.target) north_hemisphere.set_fill(opacity=0.8) self.play( LaggedStartMap(ShowCreation, north_lines), FadeIn(north_hemisphere) ) self.play( MoveToTarget(north_hemisphere), run_time=3, rate_func=lambda t: smooth(0.99 * t) ) self.play(FadeOut(north_lines)) self.wait(2) # Unit circle circle = Sphere( radius=2.01, u_min=PI / 2 - 0.01, u_max=PI / 2 + 0.01, resolution=(1, 24), ) for submob in circle: submob.add(VectorizedPoint(1.5 * submob.get_center())) circle.set_fill(YELLOW) circle_path = Circle(radius=2) circle_path.rotate(-90 * DEGREES) self.play(FadeInFromLarge(circle)) self.play(point_mob.move_to, circle_path.get_points()[0]) self.play(MoveAlongPath(point_mob, circle_path, run_time=6)) self.move_camera( phi=0, theta=-90 * DEGREES, rate_func=there_and_back_with_pause, run_time=6, ) self.play(point_mob.move_to, OUT) self.wait() # Southern hemisphere south_hemisphere = self.get_sphere() n = len(south_hemisphere) south_hemisphere.remove(*south_hemisphere[:n // 2]) south_hemisphere.remove( *south_hemisphere[-sphere.resolution[1]:] ) south_hemisphere.generate_target() self.project_mobject(south_hemisphere.target) south_hemisphere.set_fill(opacity=0.8) south_hemisphere.target[-sphere.resolution[1] // 2:].set_fill( opacity=0 ) self.play( LaggedStartMap(ShowCreation, south_lines), FadeIn(south_hemisphere) ) self.play( MoveToTarget(south_hemisphere), FadeOut(south_lines), FadeOut(xy_plane), run_time=3, rate_func=lambda t: smooth(0.99 * t) ) self.wait(3) self.projected_sphere = VGroup( north_hemisphere, south_hemisphere, ) self.equator = circle self.point_mob = point_mob def show_point_at_infinity(self): points = list(compass_directions( 12, start_vect=rotate_vector(RIGHT, 3.25 * DEGREES) )) points.pop(7) points.pop(2) arrows = VGroup(*[ Arrow(6 * p, 11 * p) for p in points ]) arrows.set_fill(RED) arrows.set_stroke(RED, 5) neg_ones = VGroup(*[ OldTex("-1").next_to(arrow.get_start(), -p) for p, arrow in zip(points, arrows) ]) neg_ones.set_stroke(width=0, background=True) sphere_arcs = VGroup() for angle in np.arange(0, TAU, TAU / 12): arc = Arc(PI, radius=2) arc.set_stroke(RED) arc.rotate(PI / 2, axis=DOWN, about_point=ORIGIN) arc.rotate(angle, axis=OUT, about_point=ORIGIN) sphere_arcs.add(arc) sphere_arcs.set_stroke(RED) self.play( LaggedStartMap(GrowArrow, arrows), LaggedStartMap(Write, neg_ones) ) self.wait(3) self.play( FadeOut(self.projected_sphere), FadeOut(arrows), FadeOut(neg_ones), ) for x in range(2): self.play( ShowCreationThenDestruction( sphere_arcs, lag_ratio=0, run_time=3, ) ) def show_a_few_rotations(self): sphere = self.sphere felix = self.felix point_mob = self.point_mob point_mob.add_updater( lambda m: m.move_to(sphere.get_all_points()[0]) ) coord_point_mobs = VGroup( VectorizedPoint(RIGHT), VectorizedPoint(UP), VectorizedPoint(OUT), ) for pm in coord_point_mobs: pm.shade_in_3d = True def get_rot_matrix(): return np.array([ pm.get_location() for pm in coord_point_mobs ]).T def get_projected_sphere(): result = StereoProjectedSphere( get_rot_matrix(), max_r=10, **self.sphere_config, ) result.set_fill(opacity=0.2) result.fade_far_out_submobjects(max_r=32) for submob in result: if submob.get_center()[1] < -11: submob.fade(1) return result projected_sphere = get_projected_sphere() projected_sphere.add_updater( lambda m: m.become(get_projected_sphere()) ) def get_projected_equator(): equator = CheckeredCircle( n_pieces=24, radius=2, ) for submob in equator.get_family(): submob.shade_in_3d = True equator.set_stroke(YELLOW, 5) equator.apply_matrix(get_rot_matrix()) self.project_mobject(equator) return equator projected_equator = get_projected_equator() projected_equator.add_updater( lambda m: m.become(get_projected_equator()) ) self.add(sphere, projected_sphere) self.move_camera(phi=60 * DEGREES) self.play( sphere.set_fill_by_checkerboard, BLUE_E, BLUE_D, {"opacity": 0.8}, FadeIn(projected_sphere) ) sphere.add(coord_point_mobs) sphere.add(self.equator) self.add(projected_equator) pairs = self.get_sample_rotation_angle_axis_pairs() for x in range(self.n_sample_rotation_cycles): for angle, axis in pairs: self.play( Rotate( sphere, angle=angle, axis=axis, about_point=ORIGIN, run_time=3, ), felix.change, "confused", ) self.wait() self.projected_sphere = projected_sphere # def project_mobject(self, mobject): return stereo_project(mobject, axis=2, r=2, outer_r=20) def project_point(self, point): return stereo_project_point(point, axis=2, r=2) def get_sample_rotation_angle_axis_pairs(self): return SphereExamplePointsDecimal.CONFIG.get( "point_rotation_angle_axis_pairs" ) class FelixViewOfProjection(TwoDStereographicProjection): CONFIG = {} def construct(self): self.add_axes() self.show_a_few_rotations() def add_axes(self): axes = Axes( axis_config={ "unit_size": 2, "color": WHITE, } ) labels = VGroup( OldTex("i"), OldTex("-i"), OldTex("j"), OldTex("-j"), OldTex("1"), ) coords = [(1, 0), (-1, 0), (0, 1), (0, -1), (0, 0)] vects = [DOWN, DOWN, RIGHT, RIGHT, 0.25 * DR] for label, coords, vect in zip(labels, coords, vects): point = axes.coords_to_point(*coords) label.next_to(point, vect, buff=MED_SMALL_BUFF) self.add(axes, labels) self.pi_creature.change("confused") def show_a_few_rotations(self): felix = self.pi_creature coord_point_mobs = VGroup([ VectorizedPoint(point) for point in [RIGHT, UP, OUT] ]) def get_rot_matrix(): return np.array([ pm.get_location() for pm in coord_point_mobs ]).T def get_projected_sphere(): return StereoProjectedSphere( get_rot_matrix(), **self.sphere_config, ) def get_projected_equator(): equator = Circle(radius=2, num_anchors=24) equator.set_stroke(YELLOW, 5) equator.apply_matrix(get_rot_matrix()) self.project_mobject(equator) return equator projected_sphere = get_projected_sphere() projected_sphere.add_updater( lambda m: m.become(get_projected_sphere()) ) equator = get_projected_equator() equator.add_updater( lambda m: m.become(get_projected_equator()) ) dot = Dot(color=PINK) dot.add_updater( lambda d: d.move_to( self.project_point( np.dot(2 * OUT, get_rot_matrix().T) ) ) ) hand = Hand() hand.add_updater( lambda h: h.move_to(dot.get_center(), LEFT) ) felix.add_updater(lambda f: f.look_at(dot)) self.add(projected_sphere) self.add(equator) self.add(dot) self.add(hand) pairs = self.get_sample_rotation_angle_axis_pairs() for x in range(self.n_sample_rotation_cycles): for angle, axis in pairs: self.play( Rotate( coord_point_mobs, angle=angle, axis=axis, about_point=ORIGIN, run_time=3, ), ) self.wait() class ShowRotationsJustWithReferenceCircles(TwoDStereographicProjection): CONFIG = { "flat_view": False, } def construct(self): self.add_parts(run_time=1) self.begin_ambient_camera_rotation(rate=0.03) self.edit_parts() self.show_1i_circle() self.show_1j_circle() self.show_random_circle() self.show_rotations() def edit_parts(self): sphere = self.sphere axes = self.axes axes.set_stroke(width=1) xy_plane = StereoProjectedSphere(u_max=15 * PI / 16) xy_plane.set_fill(WHITE, 0.2) xy_plane.set_stroke(width=0, opacity=0) self.add(xy_plane, sphere) self.play( FadeIn(xy_plane), sphere.set_fill, BLUE_E, {"opacity": 0.2}, sphere.set_stroke, {"width": 0.1, "opacity": 0.5} ) def show_1i_circle(self): axes = self.axes circle = self.get_circle(GREEN_E, GREEN) circle.rotate(TAU / 4, RIGHT) circle.rotate(TAU / 4, DOWN) projected = self.get_projected_circle(circle) labels = VGroup(*map(Tex, ["0", "2i", "3i"])) labels.set_shade_in_3d(True) if self.flat_view: labels.fade(1) for label, x in zip(labels, [0, 2, 3]): label.next_to( axes.coords_to_point(x, 0, 0), DR, SMALL_BUFF ) self.play(ShowCreation(circle, run_time=3)) self.wait() self.play(ReplacementTransform( circle.copy(), projected, run_time=3 )) # self.axes.x_axis.pieces.set_stroke(width=0) self.wait(7) self.move_camera( phi=60 * DEGREES, ) self.play( LaggedStartMap( FadeInFrom, labels, lambda m: (m, UP) ) ) self.wait(2) self.play(FadeOut(labels)) self.one_i_circle = circle self.projected_one_i_circle = projected def show_1j_circle(self): circle = self.get_circle(RED_E, RED) circle.rotate(TAU / 4, DOWN) projected = self.get_projected_circle(circle) self.move_camera(theta=-170 * DEGREES) self.play(ShowCreation(circle, run_time=3)) self.wait() self.play(ReplacementTransform( circle.copy(), projected, run_time=3 )) # self.axes.y_axis.pieces.set_stroke(width=0) self.wait(3) self.one_j_circle = circle self.projected_one_j_circle = projected def show_random_circle(self): sphere = self.sphere circle = self.get_circle(BLUE_E, BLUE) circle.set_width(2 * sphere.radius * np.sin(30 * DEGREES)) circle.shift(sphere.radius * np.cos(30 * DEGREES) * OUT) circle.rotate(150 * DEGREES, UP, about_point=ORIGIN) projected = self.get_projected_circle(circle) self.play(ShowCreation(circle, run_time=2)) self.wait() self.play(ReplacementTransform( circle.copy(), projected, run_time=2 )) self.wait(3) self.play( FadeOut(circle), FadeOut(projected), ) def show_rotations(self): sphere = self.sphere c1i = self.one_i_circle pc1i = self.projected_one_i_circle c1j = self.one_j_circle pc1j = self.projected_one_j_circle cij = self.get_circle(YELLOW_E, YELLOW) pcij = self.get_projected_circle(cij) circles = VGroup(c1i, c1j, cij) x_axis = self.axes.x_axis y_axis = self.axes.y_axis arrow = Arrow( 2 * RIGHT, 2 * UP, buff=SMALL_BUFF, path_arc=PI, ) arrow.set_stroke(GREY_B, 3) arrow.tip.set_fill(GREY_B) arrows = VGroup(arrow, *[ arrow.copy().rotate(angle, about_point=ORIGIN) for angle in np.arange(TAU / 4, TAU, TAU / 4) ]) arrows.rotate(TAU / 4, RIGHT, about_point=ORIGIN) arrows.rotate(TAU / 2, OUT, about_point=ORIGIN) arrows.rotate(TAU / 4, UP, about_point=ORIGIN) arrows.space_out_submobjects(1.2) self.play(FadeInFromLarge(cij)) sphere.add(circles) pc1i.add_updater( lambda c: c.become(self.get_projected_circle(c1i)) ) pc1j.add_updater( lambda c: c.become(self.get_projected_circle(c1j)) ) pcij.add_updater( lambda c: c.become(self.get_projected_circle(cij)) ) self.add(pcij) # About j-axis self.play(ShowCreation(arrows, run_time=3, rate_func=linear)) self.wait(3) for x in range(2): y_axis.pieces.set_stroke(width=1) self.play( Rotate(sphere, 90 * DEGREES, axis=UP), run_time=4, ) y_axis.pieces.set_stroke(width=0) self.wait(2) # About i axis self.move_camera(theta=-45 * DEGREES) self.play(Rotate(arrows, TAU / 4, axis=OUT)) self.wait(2) for x in range(2): x_axis.pieces.set_stroke(width=1) self.play( Rotate(sphere, -90 * DEGREES, axis=RIGHT), run_time=4, ) x_axis.pieces.set_stroke(width=0) self.wait(2) self.wait(2) # About real axis self.move_camera( theta=-135 * DEGREES, added_anims=[FadeOut(arrows)] ) self.ambient_camera_rotation.rate = 0.01 for x in range(2): x_axis.pieces.set_stroke(width=1) y_axis.pieces.set_stroke(width=1) self.play( Rotate(sphere, 90 * DEGREES, axis=OUT), run_time=4, ) # x_axis.pieces.set_stroke(width=0) # y_axis.pieces.set_stroke(width=0) self.wait(2) # def get_circle(self, *colors): sphere = self.sphere circle = CheckeredCircle(colors=colors, n_pieces=48) circle.set_shade_in_3d(True) circle.match_width(sphere) if self.flat_view: circle[::2].fade(1) return circle def get_projected_circle(self, circle): result = circle.deepcopy() self.project_mobject(result) result[::2].fade(1) for sm in result: if sm.get_width() > FRAME_WIDTH: sm.fade(1) if sm.get_height() > FRAME_HEIGHT: sm.fade(1) return result class ReferernceSpheresFelixView(ShowRotationsJustWithReferenceCircles): CONFIG = { "flat_view": True, "lift_labels": False, } def add_parts(self, **kwargs): ShowRotationsJustWithReferenceCircles.add_parts(self, **kwargs) one = OldTex("1") one.next_to(ORIGIN, DR, SMALL_BUFF) self.add(one) def get_default_camera_position(self): return {} def move_camera(self, **kwargs): kwargs["phi"] = 0 kwargs["theta"] = -90 * DEGREES ShowRotationsJustWithReferenceCircles.move_camera(self, **kwargs) def begin_ambient_camera_rotation(self, rate): self.ambient_camera_rotation = VectorizedPoint() def capture_mobjects_in_camera(self, mobjects, **kwargs): mobs_on_xy = [ sm for sm in self.camera.extract_mobject_family_members( mobjects, only_those_with_points=True ) if abs(sm.get_center()[2]) < 0.001 ] return Scene.capture_mobjects_in_camera(self, mobs_on_xy, **kwargs) class IntroduceQuaternions(Scene): def construct(self): self.compare_three_number_systems() self.mention_four_perpendicular_axes() self.bring_back_complex() self.show_components_of_quaternion() def compare_three_number_systems(self): numbers = self.get_example_numbers() labels = VGroup( OldTexText("Complex number"), OldTexText("Not-actually-a-number-system 3d number"), OldTexText("Quaternion"), ) for number, label in zip(numbers, labels): label.next_to(number, UP, aligned_edge=LEFT) self.play( FadeInFromDown(number), Write(label), ) self.play(ShowCreationThenFadeAround( number[2:], surrounding_rectangle_config={"color": BLUE} )) self.wait() shift_size = FRAME_HEIGHT / 2 - labels[2].get_top()[1] - MED_LARGE_BUFF self.play( numbers.shift, shift_size * UP, labels.shift, shift_size * UP, ) self.numbers = numbers self.labels = labels def mention_four_perpendicular_axes(self): number = self.numbers[2] three_axes = VGroup(*[ self.get_simple_axes(label, color) for label, color in zip( ["i", "j", "k"], [GREEN, RED, BLUE], ) ]) three_axes.arrange(RIGHT, buff=LARGE_BUFF) three_axes.next_to(number, DOWN, LARGE_BUFF) self.play(LaggedStartMap(FadeInFromLarge, three_axes)) self.wait(2) self.three_axes = three_axes def bring_back_complex(self): numbers = self.numbers labels = self.labels numbers[0].move_to(numbers[1], LEFT) labels[0].move_to(labels[1], LEFT) numbers.remove(numbers[1]) labels.remove(labels[1]) group = VGroup(numbers, labels) self.play( group.to_edge, UP, FadeOut(self.three_axes, DOWN) ) self.wait() def show_components_of_quaternion(self): quat = self.numbers[-1] real_part = quat[0] imag_part = quat[2:] real_brace = Brace(real_part, DOWN) imag_brace = Brace(imag_part, DOWN) real_word = OldTexText("Real \\\\ part") imag_word = OldTexText("Imaginary \\\\ part") scalar_word = OldTexText("Scalar \\\\ part") vector_word = OldTexText("``Vector'' \\\\ part") for word in real_word, scalar_word: word.next_to(real_brace, DOWN, SMALL_BUFF) for word in imag_word, vector_word: word.next_to(imag_brace, DOWN, SMALL_BUFF) braces = VGroup(real_brace, imag_brace) VGroup(scalar_word, vector_word).set_color(YELLOW) self.play( LaggedStartMap(GrowFromCenter, braces), LaggedStartMap( FadeInFrom, VGroup(real_word, imag_word), lambda m: (m, UP) ) ) self.wait() self.play( FadeOut(real_word, DOWN), FadeIn(scalar_word, DOWN), ) self.wait(2) self.play(ChangeDecimalToValue(real_part, 0)) self.wait() self.play( FadeOut(imag_word, DOWN), FadeIn(vector_word, DOWN) ) self.wait(2) # def get_example_numbers(self): number_2d = VGroup( DecimalNumber(3.14), OldTex("+"), DecimalNumber(1.59), OldTex("i") ) number_3d = VGroup( DecimalNumber(2.65), OldTex("+"), DecimalNumber(3.58), OldTex("i"), OldTex("+"), DecimalNumber(9.79), OldTex("j"), ) number_4d = VGroup( DecimalNumber(3.23), OldTex("+"), DecimalNumber(8.46), OldTex("i"), OldTex("+"), DecimalNumber(2.64), OldTex("j"), OldTex("+"), DecimalNumber(3.38), OldTex("k"), ) numbers = VGroup(number_2d, number_3d, number_4d) for number in numbers: number.arrange(RIGHT, buff=SMALL_BUFF) for part in number: if isinstance(part, Tex): # part.set_color_by_tex_to_color_map({ # "i": GREEN, # "j": RED, # "k": BLUE, # }) if part.get_tex() == "j": part.shift(0.5 * SMALL_BUFF * DL) number[2].set_color(GREEN) if len(number) > 5: number[5].set_color(RED) if len(number) > 8: number[8].set_color(BLUE) numbers.arrange( DOWN, buff=2, aligned_edge=LEFT ) numbers.center() numbers.shift(LEFT) return numbers def get_simple_axes(self, label, color): axes = Axes( x_min=-2.5, x_max=2.5, y_min=-2.5, y_max=2.5, ) axes.set_height(2.5) label_mob = OldTex(label) label_mob.set_color(color) label_mob.next_to(axes.coords_to_point(0, 1.5), RIGHT, SMALL_BUFF) reals_label_mob = OldTexText("Reals") reals_label_mob.next_to( axes.coords_to_point(1, 0), DR, SMALL_BUFF ) axes.add(label_mob, reals_label_mob) return axes class SimpleImaginaryQuaternionAxes(SpecialThreeDScene): def construct(self): self.three_d_axes_config.update({ "axis_config": {"unit_size": 2}, "x_min": -2, "x_max": 2, "y_min": -2, "y_max": 2, "z_min": -1.25, "z_max": 1.25, }) axes = self.get_axes() labels = VGroup(*[ OldTex(tex).set_color(color) for tex, color in zip( ["i", "j", "k"], [GREEN, RED, BLUE] ) ]) labels[0].next_to(axes.coords_to_point(1, 0, 0), DOWN + IN, SMALL_BUFF) labels[1].next_to(axes.coords_to_point(0, 1, 0), RIGHT, SMALL_BUFF) labels[2].next_to(axes.coords_to_point(0, 0, 1), RIGHT, SMALL_BUFF) self.add(axes) self.add(labels) for label in labels: self.add_fixed_orientation_mobjects(label) self.move_camera(**self.get_default_camera_position()) self.begin_ambient_camera_rotation(rate=0.05) self.wait(15) class ShowDotProductCrossProductFromOfQMult(Scene): def construct(self): v_tex = "\\vec{\\textbf{v}}" product = OldTex( "(", "w_1", "+", "x_1", "i", "+", "y_1", "j", "+", "z_1", "k", ")" "(", "w_2", "+", "x_2", "i", "+", "y_2", "j", "+", "z_2", "k", ")", "=", "(w_1", ",", v_tex + "_1", ")", "(w_2", ",", v_tex + "_2", ")", "=" ) product.set_width(FRAME_WIDTH - 1) i1 = product.index_of_part_by_tex("x_1") i2 = product.index_of_part_by_tex(")") i3 = product.index_of_part_by_tex("x_2") i4 = product.index_of_part_by_tex("z_2") + 2 vector_parts = [product[i1:i2], product[i3:i4]] vector_defs = VGroup() braces = VGroup() for i, vp in zip(it.count(1), vector_parts): brace = Brace(vp, UP) vector = Matrix([ ["x_" + str(i)], ["y_" + str(i)], ["z_" + str(i)], ]) colors = [GREEN, RED, BLUE] for mob, color in zip(vector.get_entries(), colors): mob.set_color(color) group = VGroup( OldTex("{}_{} = ".format(v_tex, i)), vector, ) group.arrange(RIGHT, SMALL_BUFF) group.next_to(brace, UP) braces.add(brace) vector_defs.add(group) result = OldTex( "\\left(", "w_1", "w_2", "-", v_tex + "_1", "\\cdot", v_tex, "_2", ",\\,", "w_1", v_tex + "_2", "+", "w_2", v_tex + "_1", "+", "{}_1 \\times {}_2".format(v_tex, v_tex), "\\right)" ) result.match_width(product) result.next_to(product, DOWN, LARGE_BUFF) for mob in product, result: mob.set_color_by_tex_to_color_map({ "w": YELLOW, "x": GREEN, "y": RED, "z": BLUE, }) mob.set_color_by_tex(v_tex, WHITE) self.add(product) self.add(braces) self.add(vector_defs) self.play(LaggedStartMap(FadeInFromLarge, result)) self.wait() class ShowComplexMagnitude(ShowComplexMultiplicationExamples): def construct(self): self.add_planes() plane = self.plane tex_to_color_map = { "a": YELLOW, "b": GREEN, } z = complex(3, 2) z_point = plane.number_to_point(z) z_dot = Dot(z_point) z_dot.set_color(PINK) z_line = Line(plane.number_to_point(0), z_point) z_line.set_stroke(WHITE, 2) z_label = OldTex( "z", "=", "a", "+", "b", "i", tex_to_color_map=tex_to_color_map ) z_label.add_background_rectangle() z_label.next_to(z_dot, UR, buff=SMALL_BUFF) z_norm_label = OldTex("||z||") z_norm_label.add_background_rectangle() z_norm_label.next_to(ORIGIN, UP, SMALL_BUFF) z_norm_label.rotate(z_line.get_angle(), about_point=ORIGIN) z_norm_label.shift(z_line.get_center()) h_line = Line( plane.number_to_point(0), plane.number_to_point(z.real), stroke_color=YELLOW, stroke_width=5, ) v_line = Line( plane.number_to_point(z.real), plane.number_to_point(z), stroke_color=GREEN, stroke_width=5, ) z_norm_equation = OldTex( "||z||", "=", "\\sqrt", "{a^2", "+", "b^2", "}", tex_to_color_map=tex_to_color_map ) z_norm_equation.set_background_stroke(width=0) z_norm_equation.add_background_rectangle() z_norm_equation.next_to(z_label, UP) self.add(z_line, h_line, v_line, z_dot, z_label) self.play(ShowCreation(z_line)) self.play(FadeInFromDown(z_norm_label)) self.wait() self.play( FadeIn(z_norm_equation[0]), FadeIn(z_norm_equation[2:]), TransformFromCopy( z_norm_label[1:], VGroup(z_norm_equation[1]), ), ) self.wait() class BreakUpQuaternionMultiplicationInParts(Scene): def construct(self): q1_color = MAROON_B q2_color = YELLOW product = OldTex( "q_1", "\\cdot", "q_2", "=", "\\left(", "{q_1", "\\over", "||", "q_1", "||}", "\\right)", "||", "q_1", "||", "\\cdot", "q_2", ) product.set_color_by_tex("q_1", q1_color) product.set_color_by_tex("q_2", q2_color) lhs = product[:3] scale_part = product[-5:] rotate_part = product[4:-5] lhs_rect = SurroundingRectangle(lhs) lhs_rect.set_color(YELLOW) lhs_words = OldTexText("Quaternion \\\\ multiplication") lhs_words.next_to(lhs_rect, UP, LARGE_BUFF) scale_brace = Brace(scale_part, UP) rotate_brace = Brace(rotate_part, DOWN) scale_words = OldTexText("Scale", "$q_2$") scale_words.set_color_by_tex("q_2", q2_color) scale_words.next_to(scale_brace, UP) rotate_words = OldTexText("Apply special \\\\ 4d rotation") rotate_words.next_to(rotate_brace, DOWN) norm_equation = OldTex( "||", "q_1", "||", "=", "||", "w_1", "+", "x_1", "i", "+", "y_1", "j", "+", "z_1", "k", "||", "=", "\\sqrt", "{w_1^2", "+", "x_1^2", "+", "y_1^2", "+", "z_1^2", "}", ) # norm_equation.set_color_by_tex_to_color_map({ # "w": YELLOW, # "x": GREEN, # "y": RED, # "z": BLUE, # }) norm_equation.set_color_by_tex("q_1", q1_color) norm_equation.to_edge(UP) norm_equation.set_background_stroke(width=0) line1 = Line(ORIGIN, 0.5 * LEFT + 3 * UP) line2 = Line(ORIGIN, UR) zero_dot = Dot() zero_label = OldTex("0") zero_label.next_to(zero_dot, DOWN, SMALL_BUFF) q1_dot = Dot(line1.get_end()) q2_dot = Dot(line2.get_end()) q1_label = OldTex("q_1").next_to(q1_dot, UP, SMALL_BUFF) q2_label = OldTex("q_2").next_to(q2_dot, UR, SMALL_BUFF) VGroup(q1_dot, q1_label).set_color(q1_color) VGroup(q2_dot, q2_label).set_color(q2_color) dot_group = VGroup( line1, line2, q1_dot, q2_dot, q1_label, q2_label, zero_dot, zero_label, ) dot_group.set_height(3) dot_group.center() dot_group.to_edge(LEFT) q1_dot.add_updater(lambda d: d.move_to(line1.get_end())) q1_label.add_updater(lambda l: l.next_to(q1_dot, UP, SMALL_BUFF)) q2_dot.add_updater(lambda d: d.move_to(line2.get_end())) q2_label.add_updater(lambda l: l.next_to(q2_dot, UR, SMALL_BUFF)) self.add(norm_equation) self.wait() self.play( FadeInFromDown(lhs), Write(dot_group), ) self.add(*dot_group) self.add( VGroup(line2, q2_dot, q2_label).copy().fade(0.5) ) self.play( ShowCreation(lhs_rect), FadeIn(lhs_words) ) self.play(FadeOut(lhs_rect)) self.wait() self.play( TransformFromCopy(lhs, product[3:]), # FadeOut(lhs_words) ) self.play( GrowFromCenter(scale_brace), Write(scale_words), ) self.play( line2.scale, 2, {"about_point": line2.get_start()} ) self.wait() self.play( GrowFromCenter(rotate_brace), FadeIn(rotate_words, UP), ) self.play( Rotate( line2, -line1.get_angle(), about_point=line2.get_start(), run_time=3 ) ) self.wait() # Ask randy = Randolph(height=2) randy.flip() randy.next_to(rotate_words, RIGHT) randy.to_edge(DOWN) q_marks = OldTex("???") random.shuffle(q_marks.submobjects) q_marks.next_to(randy, UP) self.play( FadeIn(randy) ) self.play( randy.change, "confused", rotate_words, ShowCreationThenFadeAround(rotate_words), ) self.play(LaggedStartMap( FadeInFrom, q_marks, lambda m: (m, LEFT), lag_ratio=0.8, )) self.play(Blink(randy)) self.wait(2) class SphereProjectionsWrapper(Scene): def construct(self): rect_rows = VGroup(*[ VGroup(*[ ScreenRectangle(height=3) for x in range(3) ]).arrange(RIGHT, buff=LARGE_BUFF) for y in range(2) ]).arrange(DOWN, buff=2 * LARGE_BUFF) rect_rows.set_width(FRAME_WIDTH - 1) sphere_labels = VGroup( OldTexText("Circle in 2d"), OldTexText("Sphere in 3d"), OldTexText("Hypersphere in 4d"), ) for label, rect in zip(sphere_labels, rect_rows[0]): label.next_to(rect, UP) projected_labels = VGroup( OldTexText("Sterographically projected \\\\ circle in 1d"), OldTexText("Sterographically projected \\\\ sphere in 2d"), OldTexText("Sterographically projected \\\\ hypersphere in 3d"), ) for label, rect in zip(projected_labels, rect_rows[1]): label.match_width(rect) label.next_to(rect, UP) q_marks = OldTex("???") q_marks.scale(2) q_marks.move_to(rect_rows[0][2]) self.add(rect_rows) for l1, l2 in zip(sphere_labels, projected_labels): added_anims = [] if l1 is sphere_labels[2]: added_anims.append(FadeIn(q_marks)) self.play(FadeIn(l1), *added_anims) self.play(FadeIn(l2)) self.wait() class HypersphereStereographicProjection(SpecialThreeDScene): CONFIG = { # "fancy_dot": False, "fancy_dot": True, "initial_quaternion_sample_values": [ [0, 1, 0, 0], [-1, 1, 0, 0], [0, 0, 1, 1], [0, 1, -1, 1], ], "unit_labels_scale_factor": 1, } def construct(self): self.setup_axes() self.introduce_quaternion_label() self.show_one() self.show_unit_sphere() self.show_quaternions_with_nonzero_real_part() self.emphasize_only_units() self.show_reference_spheres() def setup_axes(self): axes = self.axes = self.get_axes() axes.set_stroke(width=1) self.add(axes) self.move_camera( **self.get_default_camera_position(), run_time=0 ) self.begin_ambient_camera_rotation(rate=0.01) def introduce_quaternion_label(self): q_tracker = QuaternionTracker() coords = [ DecimalNumber(0, color=color, include_sign=sign, edge_to_fix=RIGHT) for color, sign in zip( [YELLOW, GREEN, RED, BLUE], [False, True, True, True], ) ] label = VGroup( coords[0], VectorizedPoint(), coords[1], OldTex("i"), coords[2], OldTex("j"), coords[3], OldTex("k"), ) label.arrange(RIGHT, buff=SMALL_BUFF) label.to_corner(UR) def update_label(label): self.remove_fixed_in_frame_mobjects(label) quat = q_tracker.get_value() for value, coord in zip(quat, label[::2]): coord.set_value(value) self.add_fixed_in_frame_mobjects(label) return label label.add_updater(update_label) self.pink_dot_label = label def get_pq_point(): point = self.project_quaternion(q_tracker.get_value()) if get_norm(point) > 100: return point * 100 / get_norm(point) return point pq_dot = self.get_dot() pq_dot.add_updater(lambda d: d.move_to(get_pq_point())) dot_radius = pq_dot.get_width() / 2 def get_pq_line(): point = get_pq_point() norm = get_norm(point) origin = self.axes.coords_to_point(0, 0, 0) if norm > dot_radius: point -= origin point *= (norm - dot_radius) / norm point += origin result = Line(origin, point) result.set_stroke(width=1) return result pq_line = get_pq_line() pq_line.add_updater(lambda cl: cl.become(get_pq_line())) self.add(q_tracker, label, pq_line, pq_dot) self.q_tracker = q_tracker self.q_label = label self.pq_line = pq_line self.pq_dot = pq_dot rect = SurroundingRectangle(label, color=WHITE) self.add_fixed_in_frame_mobjects(rect) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.remove_fixed_orientation_mobjects(rect) for value in self.initial_quaternion_sample_values: self.set_quat(value) self.wait() def show_one(self): q_tracker = self.q_tracker one_label = OldTex("1") one_label.rotate(TAU / 4, RIGHT) one_label.next_to(ORIGIN, IN + RIGHT, SMALL_BUFF) one_label.set_shade_in_3d(True) one_label.set_background_stroke(width=0) self.play( ApplyMethod( q_tracker.set_value, [1, 0, 0, 0], run_time=2 ), FadeInFromDown(one_label) ) self.wait(4) def show_unit_sphere(self): sphere = self.sphere = self.get_projected_sphere( quaternion=[1, 0, 0, 0], null_axis=0, solid=False, stroke_width=0.5 ) self.specially_color_sphere(sphere) labels = self.get_unit_labels() labels.remove(labels[3]) real_part = self.q_label[0] brace = Brace(real_part, DOWN) words = OldTexText("Real part zero") words.next_to(brace, DOWN, SMALL_BUFF, LEFT) self.play(Write(sphere)) self.play(LaggedStartMap( FadeInFrom, labels, lambda m: (m, IN) )) self.add_fixed_in_frame_mobjects(brace, words) self.set_quat( [0, 1, 0, 0], added_anims=[ GrowFromCenter(brace), Write(words), ] ) self.wait() self.set_quat([0, 1, -1, 1]) self.wait(2) self.set_quat([0, -1, -1, 1]) self.wait(2) self.set_quat([0, 0, 0, 1]) self.wait(2) self.set_quat([0, 0, -1, 0]) self.wait(2) self.set_quat([0, 1, 0, 0]) self.wait(2) self.play(FadeOut(words)) self.remove_fixed_in_frame_mobjects(words) self.real_part_brace = brace def show_quaternions_with_nonzero_real_part(self): # Positive real part self.set_quat( [1, 1, 2, 0], added_anims=[ ApplyMethod( self.sphere.copy().scale, 0, remover=True ) ] ) self.wait(2) self.set_quat([4, 0, -1, -1]) self.wait(2) # Negative real part self.set_quat( [-1, 1, 2, 0], added_anims=[ ApplyFunction( lambda s: s.scale(10).fade(1), self.sphere.copy(), remover=True ) ] ) self.wait(2) self.set_quat([-2, 0, -1, 1]) self.wait(2) self.set_quat([-1, 1, 0, 0]) self.move_camera(theta=-160 * DEGREES, run_time=3) self.set_quat([-1, 0.001, 0, 0]) self.wait(2) def emphasize_only_units(self): q_label = self.q_label brace = self.real_part_brace brace.target = Brace(q_label, DOWN, buff=SMALL_BUFF) words = OldTexText( "Only those where \\\\", "$w^2 + x^2 + y^2 + z^2 = 1$" ) words.next_to(brace.target, DOWN, SMALL_BUFF) self.add_fixed_in_frame_mobjects(words) self.play( MoveToTarget(brace), Write(words) ) self.set_quat([1, 1, 1, 1]) self.wait(2) self.set_quat([1, 1, -1, 1]) self.wait(2) self.set_quat([-1, 1, -1, 1]) self.wait(8) self.play(FadeOut(brace), FadeOut(words)) self.remove_fixed_in_frame_mobjects(brace, words) # TODO def show_reference_spheres(self): sphere = self.sphere self.move_camera( phi=60 * DEGREES, theta=-150 * DEGREES, added_anims=[ self.q_tracker.set_value, [1, 0, 0, 0] ] ) sphere_ijk = self.get_projected_sphere(null_axis=0) sphere_1jk = self.get_projected_sphere(null_axis=1) sphere_1ik = self.get_projected_sphere(null_axis=2) sphere_1ij = self.get_projected_sphere(null_axis=3) circle = StereoProjectedCircleFromHypersphere(axes=[0, 1]) circle_words = OldTexText( "Circle through\\\\", "$1, i, -1, -i$" ) sphere_1ij_words = OldTexText( "Sphere through\\\\", "$1, i, j, -1, -i, -j$" ) sphere_1jk_words = OldTexText( "Sphere through\\\\", "$1, j, k, -1, -j, -k$" ) sphere_1ik_words = OldTexText( "Sphere through\\\\", "$1, i, k, -1, -i, -k$" ) for words in [circle_words, sphere_1ij_words, sphere_1jk_words, sphere_1ik_words]: words.to_corner(UL) self.add_fixed_in_frame_mobjects(words) self.play( ShowCreation(circle), Write(circle_words), ) self.set_quat([0, 1, 0, 0]) self.set_quat([1, 0, 0, 0]) self.remove(sphere) sphere_ijk.match_style(sphere) self.add(sphere_ijk) # Show xy plane self.play( FadeOut(circle_words, DOWN), FadeInFromDown(sphere_1ij_words), FadeOut(circle), sphere_ijk.set_stroke, {"width": 0.0} ) self.play(Write(sphere_1ij)) self.wait(10) return # Show yz plane self.play( FadeOut(sphere_1ij_words, DOWN), FadeInFromDown(sphere_1jk_words), sphere_1ij.set_fill, BLUE_E, 0.25, sphere_1ij.set_stroke, {"width": 0.0}, Write(sphere_1jk) ) self.wait(5) # Show xz plane self.play( FadeOut(sphere_1jk_words, DOWN), FadeInFromDown(sphere_1ik_words), sphere_1jk.set_fill, GREEN_E, 0.25, sphere_1jk.set_stroke, {"width": 0.0}, Write(sphere_1ik) ) self.wait(5) self.play( sphere_1ik.set_fill, RED_E, 0.25, sphere_1ik.set_stroke, {"width": 0.0}, FadeOut(sphere_1ik_words) ) # Start applying quaternion multiplication kwargs = {"solid": False, "stroke_width": 0} sphere_ijk.add_updater( lambda s: s.become(self.get_projected_sphere(0, **kwargs)) ) sphere_1jk.add_updater( lambda s: s.become(self.get_projected_sphere(1, **kwargs)) ) sphere_1ik.add_updater( lambda s: s.become(self.get_projected_sphere(2, **kwargs)) ) sphere_1ij.add_updater( lambda s: s.become(self.get_projected_sphere(3, **kwargs)) ) self.set_quat([0, 1, 1, 1]) # def project_quaternion(self, quat): return self.axes.coords_to_point( *stereo_project_point(quat, axis=0, r=1)[1:] ) def get_dot(self): if self.fancy_dot: sphere = self.get_sphere() sphere.set_width(0.2) sphere.set_stroke(width=0) sphere.set_fill(PINK) return sphere else: return VGroup( Dot(color=PINK), Dot(color=PINK).rotate(TAU / 4, RIGHT), ) def get_unit_labels(self): c2p = self.axes.coords_to_point tex_coords_vects = [ ("i", [1, 0, 0], IN + RIGHT), ("-i", [-1, 0, 0], IN + LEFT), ("j", [0, 1, 0], UP + OUT + RIGHT), ("-j", [0, -1, 0], RIGHT + DOWN), ("k", [0, 0, 1], OUT + RIGHT), ("-k", [0, 0, -1], IN + RIGHT), ] labels = VGroup() for tex, coords, vect in tex_coords_vects: label = OldTex(tex) label.scale(self.unit_labels_scale_factor) label.rotate(90 * DEGREES, RIGHT) label.next_to(c2p(*coords), vect, SMALL_BUFF) labels.add(label) labels.set_shade_in_3d(True) labels.set_background_stroke(width=0) return labels def set_quat(self, value, run_time=3, added_anims=None): if added_anims is None: added_anims = [] self.play( self.q_tracker.set_value, value, *added_anims, run_time=run_time ) def get_projected_sphere(self, null_axis, quaternion=None, solid=True, **kwargs): if quaternion is None: quaternion = self.get_multiplier() axes_to_color = { 0: interpolate_color(YELLOW, BLACK, 0.5), 1: GREEN_E, 2: RED_D, 3: BLUE_E, } color = axes_to_color[null_axis] config = dict(self.sphere_config) config.update({ "stroke_color": WHITE, "stroke_width": 0.5, "stroke_opacity": 0.5, "max_r": 24, }) if solid: config.update({ "checkerboard_colors": [ color, interpolate_color(color, BLACK, 0.5) ], "fill_opacity": 1, }) else: config.update({ "checkerboard_colors": [], "fill_color": color, "fill_opacity": 0.25, }) config.update(kwargs) sphere = StereoProjectedSphereFromHypersphere( quaternion=quaternion, null_axis=null_axis, **config ) sphere.set_shade_in_3d(True) return sphere def get_projected_circle(self, quaternion=None, **kwargs): if quaternion is None: quaternion = self.get_multiplier() return StereoProjectedCircleFromHypersphere(quaternion, **kwargs) def get_multiplier(self): return self.q_tracker.get_value() def specially_color_sphere(self, sphere): sphere.set_color_by_gradient(BLUE, GREEN, PINK) return sphere # for submob in sphere: # u, v = submob.u1, submob.v1 # x = np.cos(v) * np.sin(u) # y = np.sin(v) * np.sin(u) # z = np.cos(u) # # rgb = sum([ # # (x**2) * hex_to_rgb(GREEN), # # (y**2) * hex_to_rgb(RED), # # (z**2) * hex_to_rgb(BLUE), # # ]) # # clip_in_place(rgb, 0, 1) # # color = rgb_to_hex(rgb) # color = interpolate_color(BLUE, RED, ((z**3) + 1) / 2) # submob.set_fill(color) # return sphere class MissingLabels(Scene): def construct(self): labels = VGroup( OldTex("i").move_to(UR), OldTex("1").move_to(0.3 * DOWN), OldTex("-i").move_to(DOWN + 1.2 * LEFT), OldTex("-j").move_to(1.7 * RIGHT + 0.8 * DOWN), ) labels.set_background_stroke(width=0) self.add(labels) class RuleOfQuaternionMultiplicationOverlay(Scene): def construct(self): q_mob, times_mob, p_mob = q_times_p = OldTex( "q", "\\cdot", "p" ) q_times_p.scale(2) q_mob.set_color(MAROON_B) p_mob.set_color(YELLOW) q_arrow = Vector(DOWN, color=WHITE) q_arrow.next_to(q_mob, UP) p_arrow = Vector(UP, color=WHITE) p_arrow.next_to(p_mob, DOWN) q_words = OldTexText("Think of as\\\\ an action") q_words.next_to(q_arrow, UP) p_words = OldTexText("Think of as\\\\ a point") p_words.next_to(p_arrow, DOWN) i_mob = OldTex("i")[0] i_mob.scale(2) i_mob.move_to(q_mob, RIGHT) i_mob.set_color(GREEN) self.add(q_times_p) self.play( FadeIn(q_words, UP), GrowArrow(q_arrow), ) self.play( FadeIn(p_words, DOWN), GrowArrow(p_arrow), ) self.wait() self.play(*map(FadeOut, [ q_words, q_arrow, p_words, p_arrow, ])) self.play( FadeInFromDown(i_mob), FadeOut(q_mob, UP) ) product = VGroup(i_mob, times_mob, p_mob) self.play(product.to_edge, UP) # Show i products underline = Line(LEFT, RIGHT) underline.set_width(product.get_width() + MED_SMALL_BUFF) underline.next_to(product, DOWN) kwargs = { "tex_to_color_map": { "i": GREEN, "j": RED, "k": BLUE } } i_products = VGroup( OldTex("i", "\\cdot", "1", "=", "i", **kwargs), OldTex("i", "\\cdot", "i", "=", "-1", **kwargs), OldTex("i", "\\cdot", "j", "=", "k", **kwargs), OldTex("i", "\\cdot", "k", "=", "-j", **kwargs), ) i_products.scale(2) i_products.arrange( DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT, ) i_products.next_to(underline, DOWN, LARGE_BUFF) i_products.align_to(i_mob, LEFT) self.play(ShowCreation(underline)) self.wait() for i_product in i_products: self.play(TransformFromCopy( product, i_product[:3] )) self.wait() self.play(TransformFromCopy( i_product[:3], i_product[3:], )) self.wait() rect = SurroundingRectangle( VGroup(product, i_products), buff=0.4 ) rect.set_stroke(WHITE, width=5) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) class RuleOfQuaternionMultiplication(HypersphereStereographicProjection): CONFIG = { "fancy_dot": True, "initial_quaternion_sample_values": [], } def construct(self): self.setup_all_trackers() self.show_multiplication_by_i_on_circle_1i() self.show_multiplication_by_i_on_circle_jk() self.show_multiplication_by_i_on_ijk_sphere() def setup_all_trackers(self): self.setup_multiplier_tracker() self.force_skipping() self.setup_axes() self.introduce_quaternion_label() self.add_unit_labels() self.revert_to_original_skipping_status() def setup_multiplier_tracker(self): self.multiplier_tracker = QuaternionTracker([1, 0, 0, 0]) self.multiplier_tracker.add_updater( lambda m: m.set_value(normalize( m.get_value(), fall_back=[1, 0, 0, 0] )) ) self.add(self.multiplier_tracker) def add_unit_labels(self): labels = self.unit_labels = self.get_unit_labels() one_label = OldTex("1") one_label.scale(self.unit_labels_scale_factor) one_label.set_shade_in_3d(True) one_label.rotate(90 * DEGREES, RIGHT) one_label.next_to(ORIGIN, IN + RIGHT, SMALL_BUFF) labels.add(one_label) self.add(labels) def show_multiplication_by_i_on_circle_1i(self): m_tracker = self.multiplier_tracker def get_circle_1i(): return self.get_projected_circle( basis_vectors=[ [1, 0, 0, 0], [1, 1, 0, 0], ], colors=[GREEN, YELLOW], quaternion=m_tracker.get_value(), ) circle = get_circle_1i() arrows = self.get_i_circle_arrows() def set_to_q_value(mt): mt.set_value(self.q_tracker.get_value()) self.play(ShowCreation(circle, run_time=2)) self.play(LaggedStartMap(ShowCreation, arrows, lag_ratio=0.25)) self.wait() circle.add_updater(lambda c: c.become(get_circle_1i())) m_tracker.add_updater(set_to_q_value) self.add(m_tracker) self.set_quat([0, 1, 0, 0]) self.wait() self.set_quat([-1, 0.001, 0, 0]) self.wait() self.q_tracker.set_value([-1, -0.001, 0, 0]) self.set_quat([0, -1, 0, 0]) self.wait() self.set_quat([1, 0, 0, 0]) self.wait(3) self.play(FadeOut(arrows)) m_tracker.remove_updater(set_to_q_value) self.circle_1i = circle def show_multiplication_by_i_on_circle_jk(self): def get_circle_jk(): return self.get_projected_circle( basis_vectors=[ [0, 0, 1, 0], [0, 0, 0, 1], ], colors=[RED, BLUE_E] ) circle = get_circle_jk() arrows = self.get_jk_circle_arrows() m_tracker = self.multiplier_tracker q_tracker = self.q_tracker def set_q_to_mj(qt): qt.set_value(q_mult( m_tracker.get_value(), [0, 0, 1, 0] )) self.move_camera(theta=-50 * DEGREES) self.play(ShowCreation(circle, run_time=2)) circle.add_updater(lambda c: c.become(get_circle_jk())) self.wait(10) self.stop_ambient_camera_rotation() self.begin_ambient_camera_rotation(rate=-0.01) self.play(*map(ShowCreation, arrows)) self.wait() self.set_quat([0, 0, 1, 0], run_time=1) q_tracker.add_updater(set_q_to_mj, index=0) self.add(self.circle_1i) self.play( m_tracker.set_value, [0, 1, 0, 0], run_time=3 ) self.wait() self.play( m_tracker.set_value, [-1, 0.001, 0, 0], run_time=3 ) self.wait() m_tracker.set_value([-1, 0.001, 0, 0]) self.play( m_tracker.set_value, [0, -1, 0, 0], run_time=3 ) self.wait() self.play( m_tracker.set_value, [1, 0, 0, 0], run_time=3 ) self.wait() q_tracker.remove_updater(set_q_to_mj) self.play( FadeOut(arrows), q_tracker.set_value, [1, 0, 0, 0], ) self.wait(10) self.circle_jk = circle def show_multiplication_by_i_on_ijk_sphere(self): m_tracker = self.multiplier_tracker q_tracker = self.q_tracker m_tracker.add_updater(lambda m: m.set_value(q_tracker.get_value())) def get_sphere(): result = self.get_projected_sphere(null_axis=0, solid=False) self.specially_color_sphere(result) return result sphere = get_sphere() self.play(Write(sphere)) sphere.add_updater(lambda s: s.become(get_sphere())) self.set_quat([0, 1, 0, 0]) self.wait() self.set_quat([-1, 0.001, 0, 0]) self.wait() self.q_tracker.set_value([-1, -0.001, 0, 0]) self.set_quat([0, -1, 0, 0]) self.wait() self.set_quat([1, 0, 0, 0]) self.wait(3) # def get_multiplier(self): return self.multiplier_tracker.get_value() def get_i_circle_arrows(self): c2p = self.axes.coords_to_point i_arrow = Arrow( ORIGIN, 2 * RIGHT, path_arc=-120 * DEGREES, buff=SMALL_BUFF, ) neg_one_arrow = Arrow( ORIGIN, 5.5 * RIGHT + UP, path_arc=-30 * DEGREES, buff=SMALL_BUFF, ) neg_i_arrow = Arrow( 4.5 * LEFT + 1.5 * UP, ORIGIN, path_arc=-30 * DEGREES, buff=SMALL_BUFF, ) one_arrow = i_arrow.copy() result = VGroup(i_arrow, neg_one_arrow, neg_i_arrow, one_arrow) for arrow in result: arrow.set_color(GREY_B) arrow.set_stroke(width=3) arrow.rotate(90 * DEGREES, RIGHT) i_arrow.next_to(c2p(0, 0, 0), OUT + RIGHT, SMALL_BUFF) neg_one_arrow.next_to(c2p(1, 0, 0), OUT + RIGHT, SMALL_BUFF) neg_i_arrow.next_to(c2p(-1, 0, 0), OUT + LEFT, SMALL_BUFF) one_arrow.next_to(c2p(0, 0, 0), OUT + LEFT, SMALL_BUFF) return result def get_jk_circle_arrows(self): arrow = Arrow( 1.5 * RIGHT, 1.5 * UP, path_arc=90 * DEGREES, buff=SMALL_BUFF, use_rectangular_stem=False ) arrow.set_color(GREY_B) arrow.set_stroke(width=3) arrows = VGroup(*[ arrow.copy().rotate(angle, about_point=ORIGIN) for angle in np.arange(0, TAU, TAU / 4) ]) arrows.rotate(90 * DEGREES, RIGHT) arrows.rotate(90 * DEGREES, OUT) return arrows class ShowDistributionOfI(TeacherStudentsScene): def construct(self): tex_to_color_map = { "q": PINK, "w": YELLOW, "x": GREEN, "y": RED, "z": BLUE, } top_product = OldTex( "q", "\\cdot", "\\left(", "w", "1", "+", "x", "i", "+", "y", "j", "+", "z", "k", "\\right)" ) top_product.to_edge(UP) self.add(top_product) bottom_product = OldTex( "w", "q", "\\cdot", "1", "+", "x", "q", "\\cdot", "i", "+", "y", "q", "\\cdot", "j", "+", "z", "q", "\\cdot", "k", ) bottom_product.next_to(top_product, DOWN, MED_LARGE_BUFF) for product in [top_product, bottom_product]: for tex, color in tex_to_color_map.items(): product.set_color_by_tex(tex, color, substring=False) self.student_says( "What does it do \\\\ to other quaternions?", target_mode="raise_left_hand" ) self.play_student_changes( "pondering", "raise_left_hand", "erm", look_at=top_product, ) self.wait(2) self.play( self.teacher.change, "raise_right_hand", RemovePiCreatureBubble(self.students[1], target_mode="pondering"), *[ TransformFromCopy( top_product.get_parts_by_tex(tex, substring=False), bottom_product.get_parts_by_tex(tex, substring=False), run_time=2 ) for tex in ["1", "w", "x", "i", "y", "j", "z", "k", "+"] ] ) self.play(*[ TransformFromCopy( top_product.get_parts_by_tex(tex, substring=False), bottom_product.get_parts_by_tex(tex, substring=False), run_time=2 ) for tex in ["q", "\\cdot"] ]) self.play_all_student_changes("thinking") self.wait(3) class ComplexPlane135(Scene): def construct(self): plane = ComplexPlane(unit_size=2) plane.add_coordinates() for mob in plane.coordinate_labels: mob.scale(2, about_edge=UR) angle = 3 * TAU / 8 circle = Circle(radius=2, color=YELLOW) arc = Arc(angle, radius=0.5) angle_label = Integer(0, unit="^\\circ") angle_label.next_to(arc.point_from_proportion(0.5), UR, SMALL_BUFF) line = Line(ORIGIN, 2 * RIGHT) point = circle.point_from_proportion(angle / TAU) dot = Dot(point, color=PINK) arrow = Vector(DR) arrow.next_to(dot, UL, SMALL_BUFF) arrow.match_color(dot) label = OldTex("-\\frac{\\sqrt{2}}{2} + \\frac{\\sqrt{2}}{2} i") label.next_to(arrow.get_start(), UP, SMALL_BUFF) label.set_background_stroke(width=0) self.add(plane, circle, line, dot, label, arrow) self.play( Rotate(line, angle, about_point=ORIGIN), ShowCreation(arc), ChangeDecimalToValue(angle_label, 135), run_time=3 ) self.wait() class ShowMultiplicationBy135Example(RuleOfQuaternionMultiplication): CONFIG = { "fancy_dot": True, } def construct(self): self.setup_all_trackers() self.add_circles() self.add_ijk_sphere() self.show_multiplication() def add_circles(self): self.circle_1i = self.add_auto_updating_circle( basis_vectors=[ [1, 0, 0, 0], [0, 1, 0, 0], ], colors=[YELLOW, GREEN_E] ) self.circle_jk = self.add_auto_updating_circle( basis_vectors=[ [0, 0, 1, 0], [0, 0, 0, 1], ], colors=[RED, BLUE_E] ) def add_auto_updating_circle(self, **circle_config): circle = self.get_projected_circle(**circle_config) circle.add_updater( lambda c: c.become(self.get_projected_circle(**circle_config)) ) self.add(circle) return circle def add_ijk_sphere(self): def get_sphere(): result = self.get_projected_sphere( null_axis=0, solid=False, stroke_width=0.5, stroke_opacity=0.2, fill_opacity=0.2, ) self.specially_color_sphere(result) return result sphere = get_sphere() sphere.add_updater(lambda s: s.become(get_sphere())) self.add(sphere) self.sphere = sphere def show_multiplication(self): m_tracker = self.multiplier_tracker quat = normalize(np.array([-1, 1, 0, 0])) point = self.project_quaternion(quat) arrow = Vector(DR) arrow.next_to(point, UL, MED_SMALL_BUFF) arrow.set_color(PINK) label = OldTex( "-{\\sqrt{2} \\over 2}", "+", "{\\sqrt{2} \\over 2}", "i", ) label.next_to(arrow.get_start(), UP) label.set_background_stroke(width=0) def get_one_point(): return self.circle_1i[0].get_points()[0] def get_j_point(): return self.circle_jk[0].get_points()[0] one_point = VectorizedPoint() one_point.add_updater(lambda v: v.set_location(get_one_point())) self.add(one_point) hand = Hand() hand.rotate(45 * DEGREES, RIGHT) hand.add_updater( lambda h: h.move_to(get_one_point(), LEFT) ) j_line = Line(ORIGIN, get_j_point()) moving_j_line = j_line.deepcopy() moving_j_line.add_updater( lambda m: m.put_start_and_end_on(ORIGIN, get_j_point()) ) self.add(j_line, moving_j_line) self.set_camera_orientation( phi=60 * DEGREES, theta=-70 * DEGREES ) self.play( FadeInFromLarge(label, 3), GrowArrow(arrow) ) self.set_quat(quat) self.wait(5) self.play(FadeInFromLarge(hand)) self.add(m_tracker) for q in [quat, [1, 0, 0, 0], quat]: self.play( m_tracker.set_value, q, UpdateFromFunc( m_tracker, lambda m: m.set_value(normalize(m.get_value())) ), run_time=5 ) self.wait() class JMultiplicationChart(Scene): def construct(self): # Largely copy-pasted....what are you gonna do about it? product = OldTex("j", "\\cdot", "p") product[0].set_color(RED) product.scale(2) product.to_edge(UP) underline = Line(LEFT, RIGHT) underline.set_width(product.get_width() + MED_SMALL_BUFF) underline.next_to(product, DOWN) kwargs = { "tex_to_color_map": { "i": GREEN, "j": RED, "k": BLUE } } j_products = VGroup( OldTex("j", "\\cdot", "1", "=", "j", **kwargs), OldTex("j", "\\cdot", "j", "=", "-1", **kwargs), OldTex("j", "\\cdot", "i", "=", "-k", **kwargs), OldTex("j", "\\cdot", "k", "=", "i", **kwargs), ) j_products.scale(2) j_products.arrange( DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT, ) j_products.next_to(underline, DOWN, LARGE_BUFF) j_products.align_to(product, LEFT) self.play(FadeInFromDown(product)) self.play(ShowCreation(underline)) self.wait() for j_product in j_products: self.play(TransformFromCopy( product, j_product[:3] )) self.wait() self.play(TransformFromCopy( j_product[:3], j_product[3:], )) self.wait() rect = SurroundingRectangle( VGroup(product, j_products), buff=MED_SMALL_BUFF ) rect.set_stroke(WHITE, width=5) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) class ShowJMultiplication(ShowMultiplicationBy135Example): CONFIG = { "fancy_dot": True, "run_time_per_rotation": 4, } def construct(self): self.setup_all_trackers() self.add_circles() self.add_ijk_sphere() self.show_multiplication() def add_circles(self): self.circle_1j = self.add_auto_updating_circle( basis_vectors=[ [1, 0, 0, 0], [0, 0, 1, 0], ], colors=[YELLOW, RED] ) self.circle_ik = self.add_auto_updating_circle( basis_vectors=[ [0, 1, 0, 0], [0, 0, 0, 1], ], colors=[GREEN, BLUE_E] ) def show_multiplication(self): self.set_camera_orientation(theta=-80 * DEGREES) q_tracker = self.q_tracker m_tracker = self.multiplier_tracker def normalize_tracker(t): t.set_value(normalize(t.get_value())) updates = [ UpdateFromFunc(tracker, normalize_tracker) for tracker in (q_tracker, m_tracker) ] run_time = self.run_time_per_rotation self.play( m_tracker.set_value, [0, 0, 1, 0], q_tracker.set_value, [0, 0, 1, 0], *updates, run_time=run_time, ) self.wait(2) self.play( m_tracker.set_value, [-1, 0, 1e-3, 0], q_tracker.set_value, [-1, 0, 1e-3, 0], *updates, run_time=run_time, ) self.wait(2) # Show ik circle circle = self.circle_ik.deepcopy() circle.clear_updaters() self.play(FadeInFromLarge(circle, remover=True)) m_tracker.set_value([-1, 0, 0, 0]) q_tracker.set_value([0, 1, 0, 0]) self.wait() self.play( m_tracker.set_value, [0, 0, -1, 0], q_tracker.set_value, [0, 0, 0, -1], *updates, run_time=run_time, ) self.wait(2) self.play( m_tracker.set_value, [1, 0, -1e-3, 0], q_tracker.set_value, [0, -1, 0, 0], *updates, run_time=run_time, ) self.wait(2) class ShowArbitraryMultiplication(ShowMultiplicationBy135Example): CONFIG = { "fancy_dot": True, "run_time_per_rotation": 4, "special_quaternion": [-0.5, 0.5, 0.5, 0.5], } def construct(self): self.setup_all_trackers() self.add_circles() self.add_ijk_sphere() self.show_multiplication() def add_circles(self): self.circle1 = self.add_auto_updating_circle( basis_vectors=[ [1, 0, 0, 0], [0, 1, 1, 1], ], colors=[YELLOW_E, YELLOW] ) bv1 = normalize([0, -1, -1, 2]) bv2 = [0] + list(normalize(np.cross([1, 1, 1], bv1[1:]))) self.circle2 = self.add_auto_updating_circle( basis_vectors=[bv1, bv2], colors=[WHITE, GREY] ) def show_multiplication(self): q_tracker = self.q_tracker m_tracker = self.multiplier_tracker run_time = self.run_time_per_rotation def normalize_tracker(t): t.set_value(normalize(t.get_value())) # for tracker in q_tracker, m_tracker: # self.add(Mobject.add_updater(tracker, normalize_tracker)) updates = [ UpdateFromFunc(tracker, normalize_tracker) for tracker in (q_tracker, m_tracker) ] special_q = self.special_quaternion pq_point = self.project_quaternion(special_q) label = OldTexText("Some unit quaternion") label.set_color(PINK) label.rotate(90 * DEGREES, RIGHT) label.next_to(pq_point, IN + RIGHT, SMALL_BUFF) circle1, circle2 = self.circle1, self.circle2 for circle in [circle1, circle2]: circle.tucked_away_updaters = circle.updaters circle.clear_updaters() self.remove(circle) hand = Hand() hand.rotate(90 * DEGREES, RIGHT) hand.move_to(ORIGIN, LEFT) hand.set_shade_in_3d(True) one_dot = self.get_dot() one_dot.set_color(YELLOW_E) one_dot.move_to(ORIGIN) one_dot.add_updater( lambda m: m.move_to(circle1[0].get_points()[0]) ) self.add(one_dot) self.stop_ambient_camera_rotation() self.begin_ambient_camera_rotation(rate=0.02) self.set_quat(special_q) self.play(FadeIn(label, IN)) self.wait(3) for circle in [circle1, circle2]: self.play(ShowCreation(circle, run_time=3)) circle.updaters = circle.tucked_away_updaters self.wait(2) self.play( FadeIn(hand, 2 * IN + 2 * RIGHT), run_time=2 ) hand.add_updater( lambda h: h.move_to(circle1[0].get_points()[0], LEFT) ) for quat in [special_q, [1, 0, 0, 0], special_q]: self.play( m_tracker.set_value, special_q, *updates, run_time=run_time, ) self.wait() class MentionCommutativity(TeacherStudentsScene): def construct(self): kwargs = { "tex_to_color_map": { "q": MAROON_B, "p": YELLOW, "i": GREEN, "j": RED, "k": BLUE, } } general_eq = OldTex("q \\cdot p \\ne p \\cdot q", **kwargs) general_eq.get_part_by_tex("\\ne").submobjects.reverse() ij_eq = OldTex("i \\cdot j = k", **kwargs) ji_eq = OldTex("j \\cdot i = -k", **kwargs) for mob in [general_eq, ij_eq, ji_eq]: mob.move_to(self.hold_up_spot, DOWN) words = OldTexText("Multiplication doesn't \\\\ commute") words.next_to(general_eq, UP, MED_LARGE_BUFF) words.shift_onto_screen() joke = OldTexText("Quaternions work from home") joke.scale(0.75) joke.to_corner(UL, MED_SMALL_BUFF) self.play( FadeInFromDown(general_eq), self.teacher.change, "raise_right_hand", self.change_students("erm", "confused", "sassy") ) self.play(FadeIn(words, RIGHT)) self.wait(2) self.play( ReplacementTransform(words, joke), general_eq.shift, UP, FadeInFromDown(ij_eq), self.change_students(*["pondering"] * 3) ) self.look_at(self.screen) self.wait(3) self.play( FadeIn(ji_eq), LaggedStartMap( ApplyMethod, VGroup(ij_eq, general_eq), lambda m: (m.shift, UP), lag_ratio=0.8, ) ) self.look_at(self.screen) self.wait(5) class RubuiksCubeOperations(SpecialThreeDScene): def construct(self): self.set_camera_orientation(**self.get_default_camera_position()) self.begin_ambient_camera_rotation() cube = RubiksCube() cube.shift(2.5 * RIGHT) cube2 = cube.copy() self.add(cube) self.play( Rotate(cube.get_face(RIGHT), 90 * DEGREES, RIGHT), run_time=2 ) self.play( Rotate(cube.get_face(DOWN), 90 * DEGREES, UP), run_time=2 ) self.wait() self.play( cube.shift, 5 * LEFT, FadeIn(cube2) ) self.play( Rotate(cube2.get_face(DOWN), 90 * DEGREES, UP), run_time=2 ) self.play( Rotate(cube2.get_face(RIGHT), 90 * DEGREES, RIGHT), run_time=2 ) self.wait(6) class RotationsOfCube(SpecialThreeDScene): def construct(self): self.set_camera_orientation(**self.get_default_camera_position()) self.begin_ambient_camera_rotation(0.0001) cube = RubiksCube() cube2 = cube.copy() axes = self.get_axes() axes.scale(0.75) label1 = OldTexText( "z-axis\\\\", "then x-axis" ) label2 = OldTexText( "x-axis\\\\", "then z-axis" ) for label in [label1, label2]: for part in label: part.add_background_rectangle() label.rotate(90 * DEGREES, RIGHT) label.move_to(3 * OUT + 0.5 * IN) self.add(axes, cube) self.play( Rotate(cube, 90 * DEGREES, OUT, run_time=2), FadeIn(label1[0], IN), ) self.play( Rotate(cube, 90 * DEGREES, RIGHT, run_time=2), FadeIn(label1[1], IN), ) self.wait() self.play( cube.shift, 5 * RIGHT, label1.shift, 5 * RIGHT, Write(cube2, run_time=1) ) self.play( Rotate(cube2, 90 * DEGREES, RIGHT, run_time=2), FadeIn(label2[0], IN), ) self.play( Rotate(cube2, 90 * DEGREES, OUT, run_time=2), FadeIn(label2[1], IN), ) self.wait(5) class OneFinalPoint(TeacherStudentsScene): def construct(self): self.teacher_says("One final point!") self.play_student_changes("happy", "tease", "thinking") self.wait(3) class MultiplicationFromTheRight(Scene): def construct(self): i, dot, j = product = OldTex("i", "\\cdot", "j") product.set_height(1.5) product.to_edge(UP, buff=LARGE_BUFF) i.set_color(GREEN) j.set_color(RED) i_rect = SurroundingRectangle(i) j_rect = SurroundingRectangle(j) i_rect.match_height(j_rect, about_edge=UP, stretch=True) VGroup(i_rect, j_rect).set_color(WHITE) action_words = OldTexText("Think of as \\\\ an action") point_words = OldTexText("Think of as \\\\ a point") action_words.next_to(i_rect, LEFT) point_words.next_to(j_rect, RIGHT) arrow = Arrow( i.get_top(), j.get_top(), path_arc=-PI, ) arrow.set_stroke(width=2) self.add(product) self.play(ShowCreation(arrow)) self.play( FadeIn(i_rect), Write(action_words) ) self.wait() self.play( FadeIn(j_rect), Write(point_words) ) self.wait(2) self.play(arrow.flip) self.play(Swap(point_words, action_words)) class MultiplicationByJFromRight(ShowJMultiplication): def show_multiplication(self): self.set_camera_orientation(theta=-80 * DEGREES) q_tracker = self.q_tracker m_tracker = self.multiplier_tracker def normalize_tracker(t): t.set_value(normalize(t.get_value())) updates = [ UpdateFromFunc(tracker, normalize_tracker) for tracker in (q_tracker, m_tracker) ] run_time = self.run_time_per_rotation m_values = [[1, 0, 0, 0]] q_values = [[0, 1, 0, 0]] for values in m_values, q_values: for x in range(4): values.append( q_mult(values[-1], [0, 0, 1, 0]) ) for m_val, q_val in zip(m_values, q_values): self.play( m_tracker.set_value, m_val, q_tracker.set_value, q_val, *updates, run_time=run_time, ) self.wait(2) def get_projected_sphere(self, *args, **kwargs): kwargs["multiply_from_right"] = True return ShowJMultiplication.get_projected_sphere( self, *args, **kwargs ) def get_projected_circle(self, *args, **kwargs): kwargs["multiply_from_right"] = True return ShowJMultiplication.get_projected_circle( self, *args, **kwargs ) class HowQuaternionsRotate3dPoints(Scene): def construct(self): title = OldTexText( "Coming up:\\\\", "How quaternions act on 3d points" ) title.to_edge(UP) expression = OldTex( "q", "\\cdot", "p", "\\cdot", "q^{-1}" ) expression.scale(2) expression.set_color_by_tex("q", PINK) expression.set_color_by_tex("p", YELLOW) right_arrow = Arrow( expression[0].get_top(), expression[2].get_top(), path_arc=-PI, color=WHITE, ) right_arrow.set_stroke(width=4) left_arrow = right_arrow.copy() left_arrow.flip(about_point=expression[2].get_top()) left_arrow.shift(SMALL_BUFF * RIGHT) self.add(title) self.play(Write(expression)) self.play(ShowCreation(right_arrow)) self.play(ShowCreation(left_arrow)) self.wait() class HoldUpQuanta(TeacherStudentsScene): def construct(self): logo = ImageMobject("Quanta logo") logo.set_width(6) logo.next_to(self.teacher, UR) logo.to_edge(RIGHT, buff=2) words = OldTexText("Associated quaternion post") words.to_edge(UP, buff=LARGE_BUFF) arrow = Arrow(logo.get_top(), words.get_bottom()) self.play( FadeInFromDown(logo), self.teacher.change, "raise_right_hand" ) self.play_all_student_changes("hooray") self.play( GrowArrow(arrow), GrowFromPoint(words, arrow.get_start()) ) self.wait(3) class ShareWithFriends(PiCreatureScene): def construct(self): pi1, pi2 = self.pi_creatures self.pi_creature_says( pi1, "Come learn about \\\\ quaternions!", bubble_config={ "direction": LEFT, "width": 4, "height": 3, }, target_mode="hooray", look_at=pi2.eyes, added_anims=[ ApplyMethod( pi2.change, "confused", run_time=1.5, rate_func=squish_rate_func(smooth, 0.3, 1) ) ] ) bubble = ThoughtBubble( direction=RIGHT, width=4, height=4, ) bubble.pin_to(pi2) bubble.write("What's that, some\\\\kind of particle?") bubble.resize_to_content() VGroup(bubble, bubble.content).shift_onto_screen(buff=SMALL_BUFF) self.play( pi2.look_at, pi1.eyes, pi1.look_at, pi2.eyes, ShowCreation(bubble), Write(bubble.content), ) self.wait(1) self.play( RemovePiCreatureBubble(pi1, target_mode="raise_right_hand") ) self.wait() time_words = OldTexText("Oh man...\\\\30 minutes") time_words.move_to(bubble.content) self.play( Animation(VectorizedPoint().next_to(pi1, UL, LARGE_BUFF)), pi2.change, "sad", FadeOut(bubble.content, DOWN), FadeInFromDown(time_words, DOWN), ) self.wait(7) def create_pi_creatures(self): pi1 = PiCreature(color=BLUE) pi1.to_edge(DOWN) pi1.flip() pi1.shift(2.5 * RIGHT) pi2 = PiCreature(color=RED) pi2.to_edge(DOWN) pi2.shift(2 * LEFT) return [pi1, pi2] class QuaternionEndscreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "Juan Benet", "Matt Russell", "soekul", "Desmos", "Burt Humburg", "Dinesh Dharme", "Scott Walter", "Brice Gower", "Peter Mcinerney", "brian tiger chow", "Joseph Kelly", "Roy Larson", "Andrew Sachs", "Hoàng Tùng Lâm", "Devin Scott", "Akash Kumar", "Arthur Zey", "David Kedmey", "Ali Yahya", "Mayank M. Mehrotra", "Lukas Biewald", "Yana Chernobilsky", "Kaustuv DeBiswas", "Yu Jun", "dave nicponski", "Jordan Scales", "Markus Persson", "Lukáš Nový", "Fela", "Randy C. Will", "Britt Selvitelle", "Jonathan Wilson", "Ryan Atallah", "Joseph John Cox", "Luc Ritchie", "Ryan Williams", "Michael Hardel", "Federico Lebron", "L0j1k", "Ayan Doss", "Dylan Houlihan", "Steven Soloway", "Art Ianuzzi", "Nate Heckmann", "Michael Faust", "Richard Comish", "Nero Li", "Valeriy Skobelev", "Adrian Robinson", "Solara570", "Peter Ehrnstrom", "Kai Siang Ang", "Alexis Olson", "Ludwig Schubert", "Omar Zrien", "Sindre Reino Trosterud", "Jeff Straathof", "Matt Langford", "Matt Roveto", "Magister Mugit", "Stevie Metke", "Cooper Jones", "James Hughes", "John V Wertheim", "Song Gao", "Richard Burgmann", "John Griffith", "Chris Connett", "Steven Tomlinson", "Jameel Syed", "Bong Choung", "Zhilong Yang", "Giovanni Filippi", "Eric Younge", "Prasant Jagannath", "Cody Brocious", "James H. Park", "Norton Wang", "Kevin Le", "Oliver Steele", "Yaw Etse", "Dave B", "Delton Ding", "Thomas Tarler", "1stViewMaths", "Jacob Magnuson", "Clark Gaebel", "Mathias Jansson", "David Clark", "Michael Gardner", "Mads Elvheim", "Awoo", "Dr David G. Stork", "Ted Suzman", "Linh Tran", "Andrew Busey", "John Haley", "Ankalagon", "Eric Lavault", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Robert Teed", "Jason Hise", "Bernd Sing", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], } class ThumbnailP1(RuleOfQuaternionMultiplication): CONFIG = { "three_d_axes_config": { "num_axis_pieces": 20, }, "unit_labels_scale_factor": 1.5, "quaternion": [1, 0, 0, 0], } def construct(self): self.setup_all_trackers() self.remove(self.pink_dot_label) q_tracker = self.q_tracker m_tracker = self.multiplier_tracker # quat = normalize([-0.5, 0.5, -0.5, 0.5]) quat = normalize(self.quaternion) m_tracker.set_value(quat) q_tracker.set_value(quat) proj_sphere = self.get_projected_sphere(0, solid=False) # self.specially_color_sphere(proj_sphere) proj_sphere.set_color_by_gradient( BLUE, YELLOW ) proj_sphere.set_stroke(WHITE) proj_sphere.set_fill(opacity=0.4) for i, face in enumerate(proj_sphere): alpha = i / len(proj_sphere) opacity = 0.7 * (1 - there_and_back(alpha)) face.set_fill(opacity=opacity) # unit_sphere = self.get_projected_sphere(0, quaternion=[1, 0, 0, 0], solid=False) # self.specially_color_sphere(unit_sphere) # unit_sphere.set_stroke(width=0) # proj_sphere.set_fill_by_checkerboard(BLUE_E, BLUE, opacity=0.8) for face in proj_sphere: face.set_points(face.get_points()[::-1]) max_r = np.max(np.apply_along_axis(get_norm, 1, face.get_points())) if max_r > 30: face.fade(1) for label in self.unit_labels: label.set_shade_in_3d(False) label.set_background_stroke(color=BLACK, width=2) self.add(proj_sphere) # self.add(unit_sphere) for mobject in self.mobjects: try: mobject.shift(IN) except ValueError: pass self.set_camera_orientation( phi=70 * DEGREES, theta=-110 * DEGREES, ) class ThumbnailP2(ThumbnailP1): CONFIG = { "quaternion": [0, 1, 0, 0], } class ThumbnailOverlay(Scene): def construct(self): title = OldTexText("Quaternions \\\\", "visualized") title.set_width(7) # title[1].scale(0.7, about_edge=UP) title.to_edge(UP, buff=MED_SMALL_BUFF) v_line = Line(DOWN, UP) v_line.set_height(FRAME_HEIGHT) title.set_background_stroke(color=BLACK, width=1) for part in (title[0][4:6], title[1][4:5]): rect = BackgroundRectangle(part) rect.set_fill(opacity=1) rect.stretch(0.9, 0) rect.stretch(1.1, 1) title.add_to_back(rect) # title.add_to_back(BackgroundRectangle(title[0])) arrow = Arrow(LEFT, RIGHT) arrow.scale(1.5) arrow.tip.scale(2) arrow.set_stroke(width=10) arrow.set_color(YELLOW) self.add(v_line) self.add(arrow) self.add(title)
from manim_imports_ext import * from _2018.div_curl import PureAirfoilFlow from _2018.div_curl import move_submobjects_along_vector_field from _2018.div_curl import move_points_along_vector_field from _2018.div_curl import four_swirls_function from _2018.lost_lecture import ShowWord class CreationDestructionMobject(VMobject): CONFIG = { "start_time": 0, "frequency": 0.25, "max_ratio_shown": 0.3, "use_copy": True, } def __init__(self, template, **kwargs): VMobject.__init__(self, **kwargs) if self.use_copy: self.ghost_mob = template.copy().fade(1) self.add(self.ghost_mob) else: self.ghost_mob = template # Don't add self.shown_mob = template.deepcopy() self.shown_mob.clear_updaters() self.add(self.shown_mob) self.total_time = self.start_time def update(mob, dt): mob.total_time += dt period = 1.0 / mob.frequency unsmooth_alpha = (mob.total_time % period) / period alpha = bezier([0, 0, 1, 1])(unsmooth_alpha) mrs = mob.max_ratio_shown mob.shown_mob.pointwise_become_partial( mob.ghost_mob, max(interpolate(-mrs, 1, alpha), 0), min(interpolate(0, 1 + mrs, alpha), 1), ) self.add_updater(update) class Eddy(VMobject): CONFIG = { "cd_mob_config": { "frequency": 0.2, "max_ratio_shown": 0.3 }, "n_spirils": 5, "n_layers": 20, "radius": 1, "colors": [BLUE_A, BLUE_E], } def __init__(self, **kwargs): VMobject.__init__(self, **kwargs) lines = self.get_lines() # self.add(lines) self.add(*[ CreationDestructionMobject(line, **self.cd_mob_config) for line in lines ]) self.randomize_times() def randomize_times(self): for submob in self.submobjects: if hasattr(submob, "total_time"): T = 1.0 / submob.frequency submob.total_time = T * random.random() def get_lines(self): a = 0.2 return VGroup(*[ self.get_line(r=self.radius * (1 - a + 2 * a * random.random())) for x in range(self.n_layers) ]) def get_line(self, r): return ParametricCurve( lambda t: r * (t + 1)**(-1) * np.array([ np.cos(TAU * t), np.sin(TAU * t), 0, ]), t_min=0.1 * random.random(), t_max=self.n_spirils, stroke_width=1, color=interpolate_color(*self.colors, random.random()) ) class Chaos(Eddy): CONFIG = { "n_lines": 12, "height": 1, "width": 2, "n_midpoints": 4, "cd_mob_config": { "use_copy": False, "frequency": 1, "max_ratio_shown": 0.8 } } def __init__(self, **kwargs): VMobject.__init__(self, **kwargs) rect = Rectangle(height=self.height, width=self.width) rect.move_to(ORIGIN, DL) rect.fade(1) self.rect = rect self.add(rect) lines = self.get_lines() self.add(*[ CreationDestructionMobject(line, **self.cd_mob_config) for line in lines ]) self.randomize_times() lines.fade(1) self.add(lines) def get_lines(self): return VGroup(*[ self.get_line(y) for y in np.linspace(0, self.height, self.n_lines) ]) def get_line(self, y): frequencies = [0] + list(2 + 2 * np.random.random(self.n_midpoints)) + [0] rect = self.rect line = Line( y * UP, y * UP + self.width * RIGHT, stroke_width=1 ) line.insert_n_curves(self.n_midpoints) line.total_time = random.random() delta_h = self.height / (self.n_lines - 1) def update(line, dt): x0, y0 = rect.get_corner(DL)[:2] x1, y1 = rect.get_corner(UR)[:2] line.total_time += dt xs = np.linspace(x0, x1, self.n_midpoints + 2) new_anchors = [ np.array([ x + 1.0 * delta_h * np.cos(f * line.total_time), y0 + y + 1.0 * delta_h * np.cos(f * line.total_time), 0 ]) for (x, f) in zip(xs, frequencies) ] line.set_points_smoothly(new_anchors) line.add_updater(update) return line class DoublePendulum(VMobject): CONFIG = { "start_angles": [3 * PI / 7, 3 * PI / 4], "color1": BLUE, "color2": RED, } def __init__(self, **kwargs): VMobject.__init__(self, **kwargs) line1 = Line(ORIGIN, UP) dot1 = Dot(color=self.color1) dot1.add_updater(lambda d: d.move_to(line1.get_end())) line2 = Line(UP, 2 * UP) dot2 = Dot(color=self.color2) dot2.add_updater(lambda d: d.move_to(line2.get_end())) self.add(line1, line2, dot1, dot2) # Largely copied from https://scipython.com/blog/the-double-pendulum/ # Pendulum rod lengths (m), bob masses (kg). L1, L2 = 1, 1 m1, m2 = 1, 1 # The gravitational acceleration (m.s-2). g = 9.81 self.state_vect = np.array([ self.start_angles[0], 0, self.start_angles[1], 0, ]) self.state_vect += np.random.random(4) * 1e-7 def update(group, dt): for x in range(2): line1, line2 = group.submobjects[:2] theta1, z1, theta2, z2 = group.state_vect c, s = np.cos(theta1 - theta2), np.sin(theta1 - theta2) theta1dot = z1 z1dot = (m2 * g * np.sin(theta2) * c - m2 * s * (L1 * (z1**2) * c + L2 * z2**2) - (m1 + m2) * g * np.sin(theta1)) / L1 / (m1 + m2 * s**2) theta2dot = z2 z2dot = ((m1 + m2) * (L1 * (z1**2) * s - g * np.sin(theta2) + g * np.sin(theta1) * c) + m2 * L2 * (z2**2) * s * c) / L2 / (m1 + m2 * s**2) group.state_vect += 0.5 * dt * np.array([ theta1dot, z1dot, theta2dot, z2dot, ]) group.state_vect[1::2] *= 0.9999 p1 = L1 * np.sin(theta1) * RIGHT - L1 * np.cos(theta1) * UP p2 = p1 + L2 * np.sin(theta2) * RIGHT - L2 * np.cos(theta2) * UP line1.put_start_and_end_on(ORIGIN, p1) line2.put_start_and_end_on(p1, p2) self.add_updater(update) class DoublePendulums(VGroup): def __init__(self, **kwargs): colors = [BLUE, RED, YELLOW, PINK, MAROON_B, PURPLE, GREEN] VGroup.__init__( self, *[ DoublePendulum( color1=random.choice(colors), color2=random.choice(colors), ) for x in range(5) ], **kwargs, ) class Diffusion(VMobject): CONFIG = { "height": 1.5, "n_dots": 1000, "colors": [RED, BLUE] } def __init__(self, **kwargs): VMobject.__init__(self, **kwargs) self.add_dots() self.add_invisible_circles() def add_dots(self): dots = VGroup(*[Dot() for x in range(self.n_dots)]) dots.arrange_in_grid(buff=SMALL_BUFF) dots.center() dots.set_height(self.height) dots.sort(lambda p: p[0]) dots[:len(dots) // 2].set_color(self.colors[0]) dots[len(dots) // 2:].set_color(self.colors[1]) dots.set_fill(opacity=0.8) self.dots = dots self.add(dots) def add_invisible_circles(self): circles = VGroup() for dot in self.dots: point = dot.get_center() radius = get_norm(point) circle = Circle(radius=radius) circle.rotate(angle_of_vector(point)) circle.fade(1) circles.add(circle) self.add_updater_to_dot(dot, circle) self.add(circles) def add_updater_to_dot(self, dot, circle): dot.total_time = 0 radius = get_norm(dot.get_center()) freq = 0.1 + 0.05 * random.random() + 0.05 / radius def update(dot, dt): dot.total_time += dt prop = (freq * dot.total_time) % 1 dot.move_to(circle.point_from_proportion(prop)) dot.add_updater(update) class NavierStokesEquations(Tex): CONFIG = { "tex_to_color_map": { "\\rho": YELLOW, "\\mu": GREEN, "\\textbf{v}": BLUE, "p{}": RED, }, "width": 10, } def __init__(self, **kwargs): v_tex = "\\textbf{v}" Tex.__init__( self, "\\rho", "\\left(" "{\\partial", v_tex, "\\over", "\\partial", "t}", "+", v_tex, "\\cdot", "\\nabla", v_tex, "\\right)", "=", "-", "\\nabla", "p{}", "+", "\\mu", "\\nabla^2", v_tex, "+", # "\\frac{1}{3}", "\\mu", "\\nabla", # "(", "\\nabla", "\\cdot", v_tex, ")", "+", "\\textbf{F}", "\\qquad\\qquad", "\\nabla", "\\cdot", v_tex, "=", "0", **kwargs ) self.set_width(self.width) def get_labels(self): parts = self.get_parts() words = [ "Analogous to \\\\ mass $\\times$ acceleration", "Pressure\\\\forces", "Viscous\\\\forces", "External\\\\forces", ] result = VGroup() braces = VGroup() word_mobs = VGroup() for i, part, word in zip(it.count(), parts, words): brace = Brace(part, DOWN, buff=SMALL_BUFF) word_mob = brace.get_text(word) word_mob.scale(0.7, about_edge=UP) word_mobs.add(word_mob) braces.add(brace) result.add(VGroup(brace, word_mob)) word_mobs[1:].arrange(RIGHT, buff=MED_SMALL_BUFF) word_mobs[1:].next_to(braces[2], DOWN, SMALL_BUFF) word_mobs[1].set_color(RED) word_mobs[2].set_color(GREEN) return result def get_parts(self): return VGroup( self[:12], self[13:16], self[17:20], self[21:22], ) class Test(Scene): def construct(self): self.add(DoublePendulums()) self.wait(30) # Scenes class EddyReference(Scene): CONFIG = { "radius": 1, "label": "Eddy", "label": "", } def construct(self): eddy = Eddy(radius=self.radius) new_eddy = eddy.get_lines() for line in new_eddy: line.set_stroke( width=(3 + 3 * random.random()) ) label = OldTexText(self.label) label.next_to(new_eddy, UP) self.play( LaggedStartMap(ShowCreationThenDestruction, new_eddy), FadeIn( label, rate_func=there_and_back_with_pause, ), run_time=3 ) class EddyReferenceWithLabel(EddyReference): CONFIG = { "label": "Eddy" } class EddyLabels(Scene): def construct(self): labels = VGroup( OldTexText("Large eddy"), OldTexText("Medium eddy"), OldTexText("Small eddy"), ) for label in labels: self.play(FadeIn( label, rate_func=there_and_back_with_pause, run_time=3 )) class LargeEddyReference(EddyReference): CONFIG = { "radius": 2, "label": "" } class MediumEddyReference(EddyReference): CONFIG = { "radius": 0.8, "label": "Medium eddy" } class SmallEddyReference(EddyReference): CONFIG = { "radius": 0.25, "label": "Small eddy" } class SomeTurbulenceEquations(PiCreatureScene): def construct(self): randy, morty = self.pi_creatures navier_stokes = NavierStokesEquations() line = Line(randy.get_right(), morty.get_left()) navier_stokes.replace(line, dim_to_match=0) navier_stokes.scale(1.2) distribution = OldTex( "E(k) \\propto k^{-5/3}", tex_to_color_map={ "k": GREEN, "-5/3": YELLOW, } ) distribution.next_to(morty, UL) brace = Brace(distribution, DOWN, buff=SMALL_BUFF) brace_words = brace.get_text("Explained soon...") brace_group = VGroup(brace, brace_words) self.play( Write(navier_stokes), randy.change, "confused", navier_stokes, morty.change, "confused", navier_stokes, ) self.wait(3) self.play( morty.change, "raise_right_hand", distribution, randy.look_at, distribution, FadeInFromDown(distribution), navier_stokes.fade, 0.5, ) self.play(GrowFromCenter(brace_group)) self.play(randy.change, "pondering", distribution) self.wait(3) dist_group = VGroup(distribution, brace_group) self.play( LaggedStartMap(FadeOut, VGroup(randy, morty, navier_stokes)), dist_group.scale, 1.5, dist_group.center, dist_group.to_edge, UP, ) self.wait() def create_pi_creatures(self): randy, morty = Randolph(), Mortimer() randy.to_corner(DL) morty.to_corner(DR) return (randy, morty) class JokeRingEquation(Scene): def construct(self): items = VGroup( OldTexText("Container with a lip"), OldTexText("Fill with smoke (or fog)"), OldTexText("Hold awkwardly"), ) line = Line(LEFT, RIGHT).set_width(items.get_width() + 1) items.add(line) items.add(OldTexText("Vortex ring")) items.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) line.shift(LEFT) plus = OldTex("+") plus.next_to(line.get_left(), UR, SMALL_BUFF) line.add(plus) items.to_edge(RIGHT) point = 3.8 * LEFT + 0.2 * UP arrow1 = Arrow( items[0].get_left(), point + 0.8 * UP + 0.3 * RIGHT, path_arc=90 * DEGREES, ) arrow1.pointwise_become_partial(arrow1, 0, 0.99) arrow2 = Arrow( items[1].get_left(), point, ) arrows = VGroup(arrow1, arrow2) for i in 0, 1: self.play( FadeInFromDown(items[i]), ShowCreation(arrows[i]) ) self.wait() self.play(LaggedStartMap(FadeIn, items[2:])) self.wait() self.play(FadeOut(arrows)) self.wait() class VideoOnPhysicsGirlWrapper(Scene): def construct(self): rect = ScreenRectangle(height=6) title = OldTexText("Video on Physics Girl") title.scale(1.5) title.to_edge(UP) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class LightBouncingOffFogParticle(Scene): def construct(self): words = OldTexText( "Light bouncing\\\\", "off fog particles" ) arrow = Vector(UP + 0.5 * RIGHT) arrow.next_to(words, UP) arrow.set_color(WHITE) self.add(words) self.play(GrowArrow(arrow)) self.wait() class NightHawkInLightWrapper(Scene): def construct(self): title = OldTexText("NightHawkInLight") 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 CarefulWithLasers(TeacherStudentsScene): def construct(self): morty = self.teacher randy = self.students[1] randy2 = self.students[2] # randy.change('hooray') laser = VGroup( Rectangle( height=0.1, width=0.3, fill_color=GREY_B, fill_opacity=1, stroke_color=GREY_D, stroke_width=1, ), Line(ORIGIN, 10 * RIGHT, color=GREEN_SCREEN) ) laser.arrange(RIGHT, buff=0) laser.rotate(45 * DEGREES) laser.shift(randy.get_corner(UR) - laser[0].get_center() + 0.1 * DR) laser.time = 0 def update_laser(laser, dt): laser.time += dt laser.rotate( 0.5 * dt * np.sin(laser.time), about_point=laser[0].get_center() ) laser.add_updater(update_laser) self.play(LaggedStartMap(FadeInFromDown, self.pi_creatures, run_time=1)) self.add(self.pi_creatures, laser) for pi in self.pi_creatures: pi.add_updater(lambda p: p.look_at(laser[1])) self.play( ShowCreation(laser), self.change_students( "surprised", "hooray", "horrified", look_at=laser ) ) self.teacher_says( "Careful with \\\\ the laser!", target_mode="angry" ) self.wait(2.2) morty.save_state() randy2.save_state() self.play( morty.blink, randy2.blink, run_time=0.3 ) self.wait(2) self.play( morty.restore, randy2.restore, run_time=0.3 ) self.wait(2) class SetAsideTurbulence(PiCreatureScene): def construct(self): self.pi_creature_says( "Forget vortex rings", target_mode="speaking" ) self.wait() self.pi_creature_says( "look at that\\\\ turbulence!", target_mode="surprised" ) self.wait() def create_pi_creature(self): morty = Mortimer() morty.to_corner(DR) return morty class WavingRodLabel(Scene): def construct(self): words = OldTexText( "(Waving a small flag \\\\ through the air)" ) self.play(Write(words)) self.wait() class SeekOrderWords(Scene): def construct(self): words = OldTexText("Seek order amidst chaos") words.scale(1.5) self.play(Write(words)) self.wait() class LongEddy(Scene): def construct(self): self.add(Eddy()) self.wait(30) class LongDoublePendulum(Scene): def construct(self): self.add(DoublePendulums()) self.wait(30) class LongDiffusion(Scene): def construct(self): self.add(Diffusion()) self.wait(30) class AskAboutTurbulence(TeacherStudentsScene): def construct(self): self.pi_creatures_ask() self.divide_by_qualitative_quantitative() self.three_qualitative_descriptors() self.rigorous_definition() def pi_creatures_ask(self): morty = self.teacher randy = self.students[1] morty.change("surprised") words = OldTexText("Wait,", "what", "exactly \\\\", "is turbulence?") question = OldTexText("What", "is turbulence?") question.to_edge(UP, buff=MED_SMALL_BUFF) h_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH - 1) h_line.next_to(question, DOWN, buff=MED_LARGE_BUFF) self.student_says( words, target_mode='raise_left_hand', added_anims=[morty.change, 'pondering'] ) self.play_student_changes( "erm", "raise_left_hand", "confused", ) self.wait(3) self.play( morty.change, "raise_right_hand", FadeOut(randy.bubble), ReplacementTransform(VGroup(words[1], words[3]), question), FadeOut(VGroup(words[0], words[2])), self.change_students( *3 * ["pondering"], look_at=question ) ) self.play( ShowCreation(h_line), LaggedStartMap( FadeOutAndShiftDown, self.pi_creatures, run_time=1, lag_ratio=0.8 ) ) self.wait() self.question = question self.h_line = h_line def divide_by_qualitative_quantitative(self): v_line = Line( self.h_line.get_center(), FRAME_HEIGHT * DOWN / 2, ) words = VGroup( OldTexText("Features", color=YELLOW), OldTexText("Rigorous definition", color=BLUE), ) words.next_to(self.h_line, DOWN) words[0].shift(FRAME_WIDTH * LEFT / 4) words[1].shift(FRAME_WIDTH * RIGHT / 4) self.play( ShowCreation(v_line), LaggedStartMap(FadeInFromDown, words) ) self.wait() self.words = words def three_qualitative_descriptors(self): words = VGroup( OldTexText("- Eddies"), OldTexText("- Chaos"), OldTexText("- Diffusion"), ) words.arrange( DOWN, buff=1.25, aligned_edge=LEFT ) words.to_edge(LEFT) words.shift(MED_LARGE_BUFF * DOWN) # objects = VGroup( # Eddy(), # DoublePendulum(), # Diffusion(), # ) # for word, obj in zip(words, objects): for word in words: # obj.next_to(word, RIGHT) self.play( FadeInFromDown(word), # VFadeIn(obj) ) self.wait(3) def rigorous_definition(self): randy = Randolph() randy.move_to(FRAME_WIDTH * RIGHT / 4) randy.change("pondering", self.words[1]) self.play(FadeIn(randy)) self.play(Blink(randy)) self.wait() self.play(randy.change, "shruggie") for x in range(2): self.play(Blink(randy)) self.wait() self.play(randy.look, LEFT) self.wait(2) self.play(randy.look, UP) self.play(Blink(randy)) self.wait() class BumpyPlaneRide(Scene): def construct(self): plane = SVGMobject(file_name="plane2") self.add(plane) total_time = 0 while total_time < 10: point = 2 * np.append(np.random.random(2), 2) + DL point *= 0.2 time = 0.2 * random.random() total_time += time arc = PI * random.random() - PI / 2 self.play( plane.move_to, point, run_time=time, path_arc=arc ) class PureAirfoilFlowCopy(PureAirfoilFlow): def modify_vector_field(self, vector_field): PureAirfoilFlow.modify_vector_field(self, vector_field) vector_field.set_fill(opacity=0.1) vector_field.set_stroke(opacity=0.1) class LaminarFlowLabel(Scene): def construct(self): words = OldTexText("Laminar flow") words.scale(1.5) words.to_edge(UP) subwords = OldTexText( "`Lamina', in Latin, means \\\\" "``a thin sheet of material''", tex_to_color_map={"Lamina": YELLOW}, arg_separator="", ) subwords.next_to(words, DOWN, MED_LARGE_BUFF) VGroup(words, subwords).set_background_stroke(width=4) self.play(Write(words)) self.wait() self.play(FadeInFromDown(subwords)) self.wait() class HighCurlFieldBreakingLayers(Scene): CONFIG = { "flow_anim": move_submobjects_along_vector_field, } def construct(self): lines = VGroup(*[ self.get_line() for x in range(20) ]) lines.arrange(DOWN, buff=MED_SMALL_BUFF) lines[0::2].set_color(BLUE) lines[1::2].set_color(RED) all_dots = VGroup(*it.chain(*lines)) def func(p): vect = four_swirls_function(p) norm = get_norm(vect) if norm > 2: vect *= 4.0 / get_norm(vect)**2 return vect self.add(lines) self.add(self.flow_anim(all_dots, func)) self.wait(16) def get_line(self): line = VGroup(*[Dot() for x in range(100)]) line.set_height(0.1) line.arrange(RIGHT, buff=0) line.set_width(10) return line class HighCurlFieldBreakingLayersLines(HighCurlFieldBreakingLayers): CONFIG = { "flow_anim": move_points_along_vector_field } def get_line(self): line = Line(LEFT, RIGHT) line.insert_n_curves(500) line.set_width(5) return line class VorticitySynonyms(Scene): def construct(self): words = VGroup( OldTexText("High", "vorticity"), OldTex( "\\text{a.k.a} \\,", "|\\nabla \\times \\vec{\\textbf{v}}| > 0" ), OldTexText("a.k.a", "high", "swirly-swirly", "factor"), ) words[0].set_color_by_tex("vorticity", BLUE) words[1].set_color_by_tex("nabla", BLUE) words[2].set_color_by_tex("swirly", BLUE) words.arrange( DOWN, aligned_edge=LEFT, buff=MED_LARGE_BUFF ) for word in words: word.add_background_rectangle() self.play(FadeInFromDown(word)) self.wait() class VorticityDoesNotImplyTurbulence(TeacherStudentsScene): def construct(self): t_to_v = OldTexText( "Turbulence", "$\\Rightarrow$", "Vorticity", ) v_to_t = OldTexText( "Vorticity", "$\\Rightarrow$", "Turbulence", ) for words in t_to_v, v_to_t: words.move_to(self.hold_up_spot, DR) words.set_color_by_tex_to_color_map({ "Vorticity": BLUE, "Turbulence": GREEN, }) v_to_t.submobjects.reverse() cross = Cross(v_to_t[1]) morty = self.teacher self.play( morty.change, "raise_right_hand", FadeInFromDown(t_to_v) ) self.wait() self.play(t_to_v.shift, 2 * UP,) self.play( TransformFromCopy(t_to_v, v_to_t, path_arc=PI / 2), self.change_students( "erm", "confused", "sassy", run_time=1 ), ShowCreation(cross, run_time=2), ) self.add(cross) self.wait(4) class SurroundingRectangleSnippet(Scene): def construct(self): rect = Rectangle() rect.set_color(YELLOW) rect.set_stroke(width=5) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) class FeynmanOnTurbulence(Scene): def construct(self): feynman = ImageMobject("Feynman_Woods", height=4) name = OldTexText("Richard Feynman") name.next_to(feynman, DOWN) quote = OldTexText( "``", "Turbulence", "is the most\\\\" "important", "unsolved problem\\\\", "of classical physics.''", tex_to_color_map={ "Turbulence": BLUE, "unsolved problem\\\\": YELLOW, }, ) quote[0].shift(SMALL_BUFF * RIGHT) quote.next_to(feynman, RIGHT) Group(feynman, name, quote).center() self.play( FadeIn(feynman, UP), FadeIn(name, DOWN), Write(quote, run_time=4) ) self.wait() class ShowNavierStokesEquations(Scene): def construct(self): self.introduce_equations() self.ask_about_evolution() self.ask_about_reasonable() self.ask_about_blowup() self.show_money() def introduce_equations(self): name = OldTexText("Navier-Stokes equations (incompressible)") equations = NavierStokesEquations() name.to_edge(UP) equations.next_to(name, DOWN, MED_LARGE_BUFF) labels = equations.get_labels() parts = equations.get_parts() newtons_second = OldTexText( "Newton's 2nd law \\\\ $ma = F$" ) newtons_second.next_to(parts, DOWN) variables = OldTex( "&\\textbf{v}", "\\text{ is velocity}\\\\", "&\\rho", "\\text{ is density}\\\\", "&p{}", "\\text{ is pressure}\\\\", "&\\mu", "\\text{ is viscosity}\\\\", tex_to_color_map=NavierStokesEquations.CONFIG["tex_to_color_map"] ) variables.to_corner(DL) self.play(FadeInFromDown(equations)) self.play(Write(name)) self.play(LaggedStartMap( FadeInFrom, variables, lambda m: (m, RIGHT), )) self.wait() self.play(Write(newtons_second)) self.wait() self.play( FadeInFromDown(labels[0]), newtons_second.next_to, variables, RIGHT, LARGE_BUFF ) self.play(ShowCreationThenFadeAround(parts[0])) self.wait() self.play(LaggedStartMap(FadeInFrom, labels[1:])) self.wait(3) self.play(LaggedStartMap( FadeOut, VGroup(*it.chain(labels, variables, newtons_second)) )) self.equations = equations def ask_about_evolution(self): words = OldTexText( "Given a start state...", "...how does it evolve?" ) words.arrange(RIGHT, buff=2) words.next_to(self.equations, DOWN, LARGE_BUFF) self.play(Write(words[0])) self.wait() self.play(Write(words[1])) self.wait(2) self.play(FadeOut(words)) def ask_about_reasonable(self): question = OldTexText( "Do ``reasonable'' \\\\" "solutions always\\\\" "exist?" ) self.play(FadeInFromDown(question)) self.wait() self.reasonable_question = question def ask_about_blowup(self): axes, graph = self.get_axes_and_graph() question = OldTexText("Is this possible?") question.set_color(YELLOW) question.move_to(axes.get_corner(UR), LEFT) question.align_to(axes, UP) q_arrow = Arrow( question.get_bottom(), graph.point_from_proportion(0.8), buff=SMALL_BUFF, path_arc=-60 * DEGREES ) q_arrow.set_stroke(WHITE, 3) morty = Mortimer() morty.to_corner(DR) morty.change('confused', graph) self.play( Write(axes, run_time=1), self.reasonable_question.to_edge, LEFT, self.reasonable_question.shift, DOWN, ) self.play( Write(question), ShowCreation(graph), FadeIn(morty), ) self.add(q_arrow, morty) self.play(ShowCreation(q_arrow), Blink(morty)) self.wait() self.play(morty.look_at, question) self.wait() self.play(morty.change, "maybe", graph) self.wait(2) to_fade = VGroup(question, q_arrow, axes, graph) self.play( LaggedStartMap(FadeOut, to_fade), morty.change, "pondering" ) self.wait(2) self.play(Blink(morty)) self.wait(2) self.morty = morty def show_money(self): # Million dollar problem problem = OldTexText( "Navier-Stokes existence \\\\ and smoothness problems" ) money = OldTexText("\\$1{,}000{,}000") money.set_color(GREEN) money.next_to(problem, DOWN) pi1 = Randolph() pi2 = self.morty pi1.to_corner(DL) pis = VGroup(pi1, pi2) for pi in pis: pi.change("pondering") pi.money_eyes = VGroup() for eye in pi.eyes: cash = OldTex("\\$") cash.set_color(GREEN) cash.replace(eye, dim_to_match=1) pi.money_eyes.add(cash) self.play( ReplacementTransform( self.reasonable_question, problem, ), pi2.look_at, problem, pi1.look_at, problem, VFadeIn(pi1), ) self.wait() self.play(FadeInFromLarge(money)) self.play( pi1.change, "hooray", pi2.change, "hooray", ) self.play( ReplacementTransform(pi1.pupils, pi1.money_eyes), ReplacementTransform(pi2.pupils, pi2.money_eyes), ) self.wait() # Helpers def get_axes_and_graph(self): axes = Axes( x_min=-1, x_max=5, y_min=-1, y_max=5, ) time = OldTexText("Time") time.next_to(axes.x_axis, RIGHT) ke = OldTexText("Kinetic energy") ke.next_to(axes.y_axis, UP) axes.add(time, ke) axes.set_height(4) axes.center() axes.to_edge(DOWN) v_line = DashedLine( axes.coords_to_point(4, 0), axes.coords_to_point(4, 5), ) axes.add(v_line) graph = axes.get_graph( lambda x: -1.0 / (x - 4), x_min=0.01, x_max=3.8, ) graph.set_color(BLUE) return axes, graph class NewtonsSecond(Scene): def construct(self): square = Square( stroke_color=WHITE, fill_color=GREY_B, fill_opacity=0.5, side_length=1 ) label = OldTex("m") label.scale(1.5) label.move_to(square) square.add(label) square.save_state() arrows = VGroup( Vector(0.5 * UP).next_to(square, UP, buff=0), Vector(RIGHT).next_to(square, RIGHT, buff=0), ) self.play( square.shift, 4 * RIGHT + 2 * UP, rate_func=lambda t: t**2, run_time=2 ) self.wait() square.restore() self.play( LaggedStartMap(GrowArrow, arrows) ) square.add(arrows) self.play( square.shift, 4 * RIGHT + 2 * UP, rate_func=lambda t: t**2, run_time=2 ) self.wait() class CandleLabel(Scene): def construct(self): word = OldTexText("Candle") arrow = Vector(DR, color=WHITE) arrow.move_to(word.get_bottom() + SMALL_BUFF * DOWN, UL) self.play( FadeInFromDown(word), GrowArrow(arrow) ) self.wait() class FiguresOfFluidDynamics(Scene): def construct(self): names = [ "Leonhard Euler", "George Stokes", "Hermann von Helmholtz", "Lewis Richardson", "Geoffrey Taylor", "Andrey Kolmogorov", ] images = Group(*[ ImageMobject(name.replace(" ", "_"), height=3) for name in names ]) images.arrange(RIGHT, buff=MED_SMALL_BUFF) image_groups = Group() for image, name in zip(images, names): name_mob = OldTexText(name) name_mob.scale(0.6) name_mob.next_to(image, DOWN) image_groups.add(Group(image, name_mob)) image_groups.arrange_in_grid(2, 3) image_groups.set_height(FRAME_HEIGHT - 1) self.play(LaggedStartMap( FadeInFromDown, image_groups, lag_ratio=0.5, run_time=3 )) self.wait() to_fade = image_groups[:-1] to_fade.generate_target() to_fade.target.space_out_submobjects(3) to_fade.target.shift(3 * UL) to_fade.target.fade(1) self.play( MoveToTarget(to_fade, remover=True), image_groups[-1].set_height, 5, image_groups[-1].center, ) self.wait() class KineticEnergyBreakdown(Scene): def construct(self): title = OldTexText("Kinetic energy breakdown") title.to_edge(UP) h_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) h_line.next_to(title, DOWN) v_line = Line(h_line.get_center(), FRAME_HEIGHT * DOWN / 2) lc_title = OldTexText("Simpler physics") lc_title.set_color(YELLOW) rc_title = OldTexText("Turbulence physics") rc_title.set_color(GREEN) for word, vect in (lc_title, LEFT), (rc_title, RIGHT): word.next_to(h_line, DOWN) word.shift(FRAME_WIDTH * vect / 4) left_items = VGroup( OldTexText("- Big moving things"), OldTexText("- Heat"), ) left_items.arrange(DOWN, aligned_edge=LEFT) left_items.next_to(lc_title, DOWN, MED_LARGE_BUFF) left_items.to_edge(LEFT) self.play( Write(VGroup(*it.chain( title, h_line, v_line, lc_title, rc_title ))) ) self.wait() for item in left_items: self.play(FadeIn(item)) self.wait() class MovingCar(Scene): def construct(self): car = Car() x = 3 car.move_to(x * LEFT) self.play(MoveCar(car, x * RIGHT, run_time=4)) class Heat(Scene): def construct(self): box = Square( side_length=2, stroke_color=WHITE, ) balls = VGroup(*[ self.get_ball(box) for x in range(20) ]) self.add(box, balls) self.wait(20) def get_ball(self, box): speed_factor = random.random() ball = Dot( radius=0.05, color=interpolate_color(BLUE, RED, speed_factor) ) speed = 2 + 3 * speed_factor direction = rotate_vector(RIGHT, TAU * random.random()) ball.velocity = speed * direction x0, y0, z0 = box.get_corner(DL) x1, y1, z1 = box.get_corner(UR) ball.move_to(np.array([ interpolate(x0, x1, random.random()), interpolate(y0, y1, random.random()), 0 ])) def update(ball, dt): ball.shift(ball.velocity * dt) if ball.get_left()[0] < box.get_left()[0]: ball.velocity[0] = abs(ball.velocity[0]) if ball.get_right()[0] > box.get_right()[0]: ball.velocity[0] = -abs(ball.velocity[0]) if ball.get_bottom()[1] < box.get_bottom()[1]: ball.velocity[1] = abs(ball.velocity[1]) if ball.get_top()[1] > box.get_top()[1]: ball.velocity[1] = -abs(ball.velocity[1]) return ball ball.add_updater(update) return ball class GrowArrowScene(Scene): def construct(self): arrow = Arrow(UP, DOWN, color=WHITE) self.play(GrowArrow(arrow)) self.wait() class Poem(Scene): def construct(self): picture = ImageMobject("Lewis_Richardson") picture.set_height(4) picture.center().to_edge(LEFT, buff=LARGE_BUFF) title = OldTexText("Poem by Lewis F. Richardson") title.to_edge(UP) poem_text = """ Big{\\,\\,}whirls have little{\\,\\,}whirls\\\\ which feed on their velocity,\\\\ And little{\\,\\,}whirls have lesser{\\,\\,}whirls\\\\ And so on to viscosity.\\\\ """ poem_words = [s for s in poem_text.split(" ") if s] poem = OldTexText(*poem_words, alignment="") poem.next_to(picture, RIGHT, LARGE_BUFF) self.add(picture) self.play(FadeIn(title, DOWN)) self.wait() for word in poem: if "whirl" in word.get_tex(): word.set_color(BLUE) self.play(ShowWord(word)) self.wait(0.005 * len(word)**1.5) class SwirlDiameterD(Scene): def construct(self): kwargs = { "path_arc": PI, "buff": SMALL_BUFF, "color": WHITE } swirl = VGroup( Arrow(RIGHT, LEFT, **kwargs), Arrow(LEFT, RIGHT, **kwargs), ) swirl.set_stroke(width=5) f = 1.5 swirl.scale(f) h_line = DashedLine( f * LEFT, f * RIGHT, color=YELLOW, ) D_label = OldTex("D") D_label.scale(2) D_label.next_to(h_line, UP, SMALL_BUFF) D_label.match_color(h_line) # diam = VGroup(h_line, D_label) self.play(*map(ShowCreation, swirl)) self.play( GrowFromCenter(h_line), FadeIn(D_label, UP), ) self.wait() class KolmogorovGraph(Scene): def construct(self): axes = Axes( x_min=-1, y_min=-1, x_max=7, y_max=9, y_axis_config={ "unit_size": 0.7, } ) axes.center().shift(1.5 * RIGHT) x_label = OldTex("\\log(D)") x_label.next_to(axes.x_axis.get_right(), UP) y_label = OldTex("\\log(\\text{K.E. at length scale D})") y_label.scale(0.8) y_label.next_to(axes.y_axis.get_top(), LEFT) y_label.shift_onto_screen() axes.add(x_label, y_label) v_lines = VGroup(*[ DashedLine( axes.coords_to_point(x, 0), axes.coords_to_point(x, 9), color=YELLOW, stroke_width=1 ) for x in [0.5, 5] ]) inertial_subrange = OldTexText("``Inertial subrange''") inertial_subrange.scale(0.7) inertial_subrange.next_to(v_lines.get_bottom(), UP) def func(x): if 0.5 < x < 5: return (5 / 3) * x elif x < 0.5: return 5 * (x - 0.5) + 0.5 * (5 / 3) elif x > 5: return np.log(x) + (5 / 3) * 5 - np.log(5) graph = axes.get_graph(func, x_min=0.3, x_max=7) prop_label = OldTex("\\text{K.E.} \\propto D^{5/3}") prop_label.next_to( graph.point_from_proportion(0.5), UL, buff=0 ) self.add(axes) self.play(ShowCreation(graph)) self.play(FadeInFromDown(prop_label)) self.wait() self.add(v_lines) self.play(Write(inertial_subrange)) self.wait() class TechnicalNote(Scene): def construct(self): title = OldTexText("Technical note:") title.to_edge(UP) title.set_color(RED) self.add(title) words = OldTexText(""" This idea of quantifying the energy held at different length scales is typically defined in terms of an ``energy spectrum'' involving the Fourier transform of a function measuring the correlations between the fluid's velocities at different points in space. I know, yikes! \\quad\\\\ \\quad\\\\ Building up the relevant background for that is a bit cumbersome, so we'll be thinking about the energy at different scales in terms of all eddy's with a given diameter. This is admittedly a less well-defined notion, but it does capture the spirit of Kolmogorov's result. \\quad\\\\ \\quad\\\\ See the links in the description for more details, if you're curious. """, alignment="") words.scale(0.75) words.next_to(title, DOWN, LARGE_BUFF) self.add(title, words) class FiveThirds(TeacherStudentsScene): def construct(self): words = OldTexText( "5/3", "is a sort of fundamental\\\\ constant of turbulence" ) self.teacher_says(words) self.play_student_changes("pondering", "maybe", "erm") self.play( FadeOut(self.teacher.bubble), FadeOut(words[1]), self.teacher.change, "raise_right_hand", words[0].scale, 1.5, words[0].move_to, self.hold_up_spot ) self.play_student_changes("thinking", "pondering", "hooray") self.wait(3) class TurbulenceGifLabel(Scene): def construct(self): title = OldTexText("Turbulence in 2d") title.to_edge(UP) attribution = OldTexText( "Animation by Gabe Weymouth (@gabrielweymouth)" ) attribution.scale(0.5) attribution.to_edge(DOWN) self.play(Write(title)) self.play(FadeIn(attribution, UP)) self.wait() class VortexStretchingLabel(Scene): def construct(self): title = OldTexText("Vortex stretching") self.play(Write(title)) self.wait() class VortedStretching(ThreeDScene): CONFIG = { "n_circles": 200, } def construct(self): axes = ThreeDAxes() axes.set_stroke(width=1) self.add(axes) self.move_camera( phi=70 * DEGREES, theta=-145 * DEGREES, run_time=0, ) self.begin_ambient_camera_rotation() short_circles = self.get_cylinder_circles(2, 0.5, 0.5) tall_circles = short_circles.copy().scale(0.125) tall_circles.stretch(16 * 4, 2) torus_circles = tall_circles.copy() for circle in torus_circles: circle.shift(RIGHT) z = circle.get_center()[2] circle.shift(z * IN) angle = PI * z / 2 circle.rotate(angle, axis=DOWN, about_point=ORIGIN) circles = short_circles.copy() flow_lines = self.get_flow_lines(circles) self.add(circles, flow_lines) self.play(LaggedStartMap(ShowCreation, circles)) self.wait(5) self.play(Transform(circles, tall_circles, run_time=3)) self.wait(10) self.play(Transform( circles, torus_circles, run_time=3 )) self.wait(10) def get_cylinder_circles(self, radius, radius_var, max_z): return VGroup(*[ ParametricCurve( lambda t: np.array([ np.cos(TAU * t) * r, np.sin(TAU * t) * r, z ]), **self.get_circle_kwargs() ) for z in sorted(max_z * np.random.random(self.n_circles)) for r in [radius + radius_var * random.random()] ]).center() def get_torus_circles(self, out_r, in_r, in_r_var): result = VGroup() for u in sorted(np.random.random(self.n_circles)): r = in_r + in_r_var * random.random() circle = ParametricCurve( lambda t: r * np.array([ np.cos(TAU * t), np.sin(TAU * t), 0, ]), **self.get_circle_kwargs() ) circle.shift(out_r * RIGHT) circle.rotate( TAU * u - PI, about_point=ORIGIN, axis=DOWN, ) result.add(circle) return result def get_flow_lines(self, circle_group): window = 0.3 def update_circle(circle, dt): circle.total_time += dt diameter = get_norm( circle.template.point_from_proportion(0) - circle.template.point_from_proportion(0.5) ) modulus = np.sqrt(diameter) + 0.1 alpha = (circle.total_time % modulus) / modulus circle.pointwise_become_partial( circle.template, max(interpolate(-window, 1, alpha), 0), min(interpolate(0, 1 + window, alpha), 1), ) result = VGroup() for template in circle_group: circle = template.deepcopy() circle.set_stroke( color=interpolate_color(BLUE_A, BLUE_E, random.random()), # width=3 * random.random() width=1, ) circle.template = template circle.total_time = 4 * random.random() circle.add_updater(update_circle) result.add(circle) return result def get_circle_kwargs(self): return { "stroke_color": BLACK, "stroke_width": 0, } class TurbulenceEndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "1stViewMaths", "Adrian Robinson", "Alexis Olson", "Andrew Busey", "Ankalagon", "Art Ianuzzi", "Awoo", "Ayan Doss", "Bernd Sing", "Boris Veselinovich", "Brian Staroselsky", "Britt Selvitelle", "Carla Kirby", "Charles Southerland", "Chris Connett", "Christian Kaiser", "Clark Gaebel", "Cooper Jones", "Danger Dai", "Dave B", "Dave Kester", "David Clark", "Delton Ding", "Devarsh Desai", "eaglle", "Eric Younge", "Eryq Ouithaqueue", "Federico Lebron", "Florian Chudigiewitsch", "Giovanni Filippi", "Hal Hildebrand", "Igor Napolskikh", "Jacob Magnuson", "Jameel Syed", "James Hughes", "Jan Pijpers", "Jason Hise", "Jeff Linse", "Jeff Straathof", "Jerry Ling", "John Griffith", "John Haley", "John V Wertheim", "Jonathan Eppele", "Jonathan Wilson", "Jordan Scales", "Joseph John Cox", "Julian Pulgarin", "Kai-Siang Ang", "Kanan Gill", "L0j1k", "Linh Tran", "Luc Ritchie", "Ludwig Schubert", "Lukas -krtek.net- Novy", "Magister Mugit", "Magnus Dahlström", "Mark B Bahu", "Markus Persson", "Mathew Bramson", "Mathias Jansson", "Matt Langford", "Matt Roveto", "Matthew Cocke", "Mehdi Razavi", "Michael Faust", "Michael Hardel", "Mustafa Mahdi", "Márton Vaitkus", "Nero Li", "Oliver Steele", "Omar Zrien", "Peter Ehrnstrom", "Prasant Jagannath", "Randy C. Will", "Richard Burgmann", "Ripta Pasay", "Rish Kundalia", "Robert Teed", "Roobie", "Ryan Atallah", "Ryan Williams", "Sindre Reino Trosterud", "Solara570", "Song Gao", "Steven Soloway", "Steven Tomlinson", "Stevie Metke", "Ted Suzman", "Valeriy Skobelev", "Xavier Bernard", "Yaw Etse", "YinYangBalance.Asia", "Zach Cardwell", ], } class LaserWord(Scene): def construct(self): self.add(OldTexText("Laser").scale(2)) class TurbulenceWord(Scene): def construct(self): self.add(OldTexText("Turbulence").scale(2)) class ArrowScene(Scene): def construct(self): arrow = Arrow(LEFT, RIGHT, color=WHITE) arrow.add_to_back(arrow.copy().set_stroke(BLACK, 5)) self.add(arrow)
from manim_imports_ext import * from _2017.efvgt import get_confetti_animations class CrossingOneMillion(TeacherStudentsScene): def construct(self): self.increment_count() self.comment_on_real_milestone() self.reflect() def increment_count(self): number = self.number = Integer(0) number.move_to(UP, LEFT) number.scale(3) self.look_at(number, run_time=0) confetti_spirils = self.confetti_spirils = list(map( turn_animation_into_updater, get_confetti_animations(50) )) self.add(*confetti_spirils) self.play( ChangeDecimalToValue( number, 10**6, position_update_func=lambda m: m.move_to( UP, LEFT ), rate_func=bezier([0, 0, 0, 1, 1, 1]), run_time=5, ), LaggedStartMap( ApplyMethod, self.get_pi_creatures(), lambda m: (m.change, "hooray", number), rate_func=squish_rate_func(smooth, 0, 0.5), run_time=4, ), ) self.wait() def comment_on_real_milestone(self): number = self.number remainder = Integer(2**20 - 10**6) words = OldTexText( "Just", "{:,}".format(remainder.number), "to go \\\\ before the real milestone", ) self.student_says( words, added_anims=[ ApplyMethod(self.teacher.change, "hesitant"), self.change_students( "sassy", "speaking", "happy" ), number.scale, 0.5, number.center, number.to_edge, UP, ] ) self.wait() self.remove(*self.confetti_spirils) remainder.replace(words[1]) words.submobjects[1] = remainder self.play( ChangeDecimalToValue(number, 2**20, run_time=3), ChangeDecimalToValue(remainder, 0.1, run_time=3), self.teacher.change, "pondering", number, self.change_students( *["pondering"] * 3, look_at=number ), ) self.play( FadeOut(self.students[1].bubble), FadeOut(self.students[1].bubble.content), ) self.wait(2) def reflect(self): bubble = ThoughtBubble( direction=RIGHT, height=4, width=7, ) bubble.pin_to(self.teacher) q_marks = OldTex("???") q_marks.scale(2) q_marks.set_color_by_gradient(BLUE_D, BLUE_B) q_marks.next_to(bubble[-1].get_top(), DOWN) arrow = Vector(0.5 * DOWN, color=WHITE) arrow.next_to(q_marks, DOWN) number = self.number number.generate_target() number.target.next_to(arrow, DOWN) self.play( ShowCreation( bubble, rate_func=squish_rate_func(smooth, 0, 0.3) ), Write(q_marks), GrowArrow(arrow), MoveToTarget(number), run_time=3 ) self.wait() class ShareWithFriends(PiCreatureScene): def construct(self): randy, morty = self.pi_creatures self.pi_creature_says( randy, "Wanna see why \\\\" + "$1 - \\frac{1}{3} + \\frac{1}{5}" + "- \\frac{1}{7} + \\cdots = \\frac{\\pi}{4}$?", target_mode="tease", added_anims=[morty.look, UP] ) self.play(morty.change, "maybe", UP) self.wait() def create_pi_creatures(self): randy = Randolph(color=GREEN) morty = Mortimer(color=RED_E) randy.to_edge(DOWN).shift(4 * LEFT) morty.to_edge(DOWN) return randy, morty class AllFeaturedCreators(MortyPiCreatureScene): def construct(self): morty = self.pi_creature title = Title("Featured creators") dots = VGroup(*[Dot(color=WHITE) for x in range(4)]) dots.arrange(DOWN, buff=LARGE_BUFF) dots.to_edge(LEFT, buff=2) creators = VGroup(*list(map(TexText, [ "Think Twice", "LeiosOS", "Welch Labs", "Infinity plus one", ]))) for creator, dot in zip(creators, dots): creator.next_to(dot, RIGHT) dot.save_state() dot.scale(4) dot.set_fill(opacity=0) rects = VGroup(*list(map(SurroundingRectangle, creators))) rects.set_stroke(WHITE, 2) rects.set_fill(BLUE_E, 1) think_words = VGroup(*list(map(TexText, [ "(thinks visually)", "(thinks in terms of communities)", "(thinks in terms of series)", "(thinks playfully)", ]))) for word, creator in zip(think_words, creators): # word.move_to(creator, RIGHT) # word.align_to(RIGHT, LEFT) word.next_to(creator, RIGHT) word.set_color(YELLOW) self.play( morty.change, "raise_right_hand", Write(title) ) self.wait() self.play(LaggedStartMap( ApplyMethod, dots, lambda m: (m.restore,) )) self.play( LaggedStartMap(FadeIn, rects, lag_ratio=0.7), morty.change, "happy" ) self.add(creators, rects) self.wait() modes = ["hooray", "tease", "raise_right_hand", "hooray"] for rect, word, mode in zip(rects, think_words, modes): self.play( self.get_rect_removal(rect), morty.change, mode, ) self.wait() self.play(Write(word)) self.wait() self.add(think_words) def get_rect_removal(self, rect): rect.generate_target() rect.target.stretch(0, 0, about_edge=LEFT) rect.target.set_stroke(width=0) return MoveToTarget(rect) class GeneralWrapper(Scene): CONFIG = { "title_text": "" } def construct(self): title = OldTexText(self.title_text) title.to_edge(UP) rect = ScreenRectangle(height=6.5) rect.next_to(title, DOWN) self.play(Write(title), ShowCreation(rect)) self.wait() class ThinkTwiceWrapper(GeneralWrapper): CONFIG = {"title_text": "Think Twice"} class LeiosOSWrapper(GeneralWrapper): CONFIG = {"title_text": "LeiosOS"} class WelchLabsWrapper(GeneralWrapper): CONFIG = {"title_text": "Welch Labs"} class InfinityPlusOneWrapper(GeneralWrapper): CONFIG = {"title_text": "Infinity Plus One"} 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
from manim_imports_ext import * from _2018.quaternions import * W_COLOR = YELLOW I_COLOR = GREEN J_COLOR = RED K_COLOR = BLUE class QuaternionLabel(VGroup): CONFIG = { "decimal_config": {} } def __init__(self, quat, **kwargs): VGroup.__init__(self, **kwargs) dkwargs = dict(self.decimal_config) decimals = VGroup() decimals.add(DecimalNumber(quat[0], color=W_COLOR, **dkwargs)) dkwargs["include_sign"] = True decimals.add( DecimalNumber(quat[1], color=I_COLOR, **dkwargs), DecimalNumber(quat[2], color=J_COLOR, **dkwargs), DecimalNumber(quat[3], color=K_COLOR, **dkwargs), ) self.add( decimals[0], decimals[1], OldTex("i"), decimals[2], OldTex("j"), decimals[3], OldTex("k"), ) self.arrange(RIGHT, buff=SMALL_BUFF) self.decimals = decimals def set_value(self, quat): for decimal, coord in zip(self.decimals, quat): decimal.set_value(coord) return self class RandyPrism(Cube): CONFIG = { "height": 0.25, "width": 1, "depth": 1.2, "fill_color": BLUE_D, "fill_opacity": 0.9, "stroke_color": WHITE, "stroke_width": 1, } def __init__(self, **kwargs): Cube.__init__(self, **kwargs) self.set_height(1) randy = Randolph(mode="pondering") randy.set_height(0.8) randy.rotate(TAU / 4, RIGHT) randy.shift(0.7 * DOWN) randy.set_shade_in_3d(True, z_index_as_group=True) self.randy = randy self.add(randy) self.set_height(self.height, stretch=True) self.set_width(self.width, stretch=True) self.set_depth(self.depth, stretch=True) self.center() class Gimbal(VGroup): CONFIG = { "inner_r": 1.2, "outer_r": 2.6, } def __init__(self, alpha=0, beta=0, gamma=0, inner_mob=None, **kwargs): VGroup.__init__(self, **kwargs) r1, r2, r3, r4, r5, r6, r7 = np.linspace( self.inner_r, self.outer_r, 7 ) rings = VGroup( self.get_ring(r5, r6), self.get_ring(r3, r4), self.get_ring(r1, r2), ) for i, p1, p2 in [(0, r6, r7), (1, r4, r5), (2, r2, r3)]: annulus = rings[i] lines = VGroup( Line(p1 * UP, p2 * UP), Line(p1 * DOWN, p2 * DOWN), ) lines.set_stroke(RED) annulus.lines = lines annulus.add(lines) rings[1].lines.rotate(90 * DEGREES, about_point=ORIGIN) rings.rotate(90 * DEGREES, RIGHT, about_point=ORIGIN) rings.set_shade_in_3d(True) self.rings = rings self.add(rings) if inner_mob is not None: corners = [ inner_mob.get_corner(v1 + v2) for v1 in [LEFT, RIGHT] for v2 in [IN, OUT] ] lines = VGroup() for corner in corners: corner[1] = 0 line = Line( corner, self.inner_r * normalize(corner), color=WHITE, stroke_width=1 ) lines.add(line) lines.set_shade_in_3d(True) rings[2].add(lines, inner_mob) # Rotations angles = [alpha, beta, gamma] for i, angle in zip(it.count(), angles): vect = rings[i].lines[0].get_vector() rings[i:].rotate(angle=angle, axis=vect) def get_ring(self, in_r, out_r, angle=TAU / 4): result = VGroup() for start_angle in np.arange(0, TAU, angle): start_angle += angle / 2 sector = AnnularSector( inner_radius=in_r, outer_radius=out_r, angle=angle, start_angle=start_angle ) sector.set_fill(GREY_B, 0.8) arcs = VGroup(*[ Arc( angle=angle, start_angle=start_angle, radius=r ) for r in [in_r, out_r] ]) arcs.set_stroke(BLACK, 1, opacity=0.5) sector.add(arcs) result.add(sector) return result # Scenes class ButFirst(TeacherStudentsScene): def construct(self): for student in self.students: student.change("surprised") self.teacher_says("But first!") self.play_all_student_changes("happy") self.play(RemovePiCreatureBubble( self.teacher, target_mode="raise_right_hand" )) self.play_student_changes( *["pondering"] * 3, look_at=self.screen, ) self.play(self.teacher.look_at, self.screen) self.wait(4) class Introduction(QuaternionHistory): CONFIG = { "names_and_quotes": [ ( "Oliver Heaviside", """\\Huge ``the quaternion was not only not required, but was a positive evil''""" ), ( "Lord Kelvin", """\\Huge ``Quaternions... though beautifully \\\\ ingenious, have been an unmixed evil'' """ ), ] } def construct(self): title_word = OldTexText("Quaternions:") title_equation = OldTex( "i^2 = j^2 = k^2 = ijk = -1", tex_to_color_map={ "i": I_COLOR, "j": J_COLOR, "k": K_COLOR, } ) # label = QuaternionLabel([ # float(str((TAU * 10**(3 * k)) % 10)[:4]) # for k in range(4) # ]) title = VGroup(title_word, title_equation) title.arrange(RIGHT) title.to_edge(UP) images_group = self.get_dissenter_images_quotes_and_names() images_group.to_edge(DOWN) images, quotes, names = images_group for pair in images_group: pair[1].align_to(pair[0], UP) self.play( FadeInFromDown(title_word), Write(title_equation) ) self.wait() for image, name, quote in zip(images, names, quotes): self.play( FadeIn(image, 3 * DOWN), FadeInFromLarge(name), LaggedStartMap( FadeIn, VGroup(*it.chain(*quote)), lag_ratio=0.3, run_time=2 ) ) self.wait(2) self.play( title.shift, 2 * UP, *[ ApplyMethod(mob.shift, FRAME_WIDTH * vect / 2) for pair in images_group for mob, vect in zip(pair, [LEFT, RIGHT]) ], ) class WhoCares(TeacherStudentsScene): def construct(self): quotes = Group(*[ ImageMobject( "CoderQuaternionResponse_{}".format(d), height=2 ) for d in range(4) ]) logos = Group(*[ ImageMobject(name, height=0.5) for name in [ "TwitterLogo", "HackerNewsLogo", "RedditLogo", "YouTubeLogo", ] ]) for quote, logo in zip(quotes, logos): logo.move_to(quote.get_corner(UR)) quote.add(logo) quotes.arrange_in_grid() quotes.set_height(4) quotes.to_corner(UL) self.student_says( "Um...who cares?", target_mode="sassy", added_anims=[self.teacher.change, "guilty"] ) self.play_student_changes("angry", "sassy", "sad") self.wait(2) self.play( RemovePiCreatureBubble(self.students[1]), self.teacher.change, "raise_right_hand" ) # self.play( # LaggedStartMap( # FadeInFromDown, quotes, # run_time=3 # ), # self.change_students(*3 * ["pondering"], look_at=quotes) # ) # self.wait(2) # # Show HN # hn_quote = quotes[1] # hn_context = OldTexText("news.ycombinator.com/item?id=17933908") # hn_context.scale(0.7) # hn_context.to_corner(UL) # vr_headsets = VGroup() # for pi in self.students: # vr_headset = SVGMobject("VR_headset") # vr_headset.set_fill(GREY_B, opacity=0.9) # vr_headset.set_width(pi.eyes.get_width() + 0.3) # vr_headset.move_to(pi.eyes) # vr_headsets.add(vr_headset) # self.play( # hn_quote.scale, 2, {"about_edge": DL}, # FadeOut(quotes[0], 5 * UP), # FadeOut(quotes[2], UR), # FadeOut(quotes[3], RIGHT), # FadeInFromDown(hn_context), # ) # hn_rect = Rectangle( # height=0.1 * hn_quote.get_height(), # width=0.6 * hn_quote.get_width(), # color=RED # ) # hn_rect.move_to(hn_quote, UL) # hn_rect.shift(0.225 * RIGHT + 0.75 * DOWN) # self.play( # ShowCreation(hn_rect), # self.change_students( # "erm", "thinking", "confused", # look_at=hn_quote, # ) # ) # self.add_foreground_mobjects(vr_headsets) # self.play( # LaggedStartMap( # FadeInFrom, vr_headsets, # lambda m: (m, UP), # ), # self.change_students( # *3 * ["sick"], # look_at=hn_quote, # run_time=3 # ) # ) # self.wait(3) # Show Twitter t_quote = quotes[0] # t_quote.next_to(FRAME_WIDTH * LEFT / 2 + FRAME_WIDTH * UP / 2, UR) # t_quote.set_opacity(0) # self.play( # FadeOut(hn_quote, 4 * LEFT), # FadeOut(hn_rect, 4 * LEFT), # FadeOut(hn_context, UP), # FadeOut(vr_headsets), # t_quote.set_opacity, 1, # t_quote.scale, 2, # t_quote.to_corner, UL, # ) # self.remove_foreground_mobjects(vr_headsets) t_quote.fade(1) t_quote.to_corner(UL) self.play( self.change_students(*3 * ["pondering"], look_at=quotes), t_quote.set_opacity, 1, t_quote.scale, 2, t_quote.to_corner, UL, ) self.wait(2) self.play_student_changes( "pondering", "happy", "tease", look_at=t_quote ) self.wait(2) self.play(FadeOut(t_quote)) self.wait(5) class ShowSeveralQuaternionRotations(SpecialThreeDScene): CONFIG = { "quaternions": [ [0, 1, 0, 0], [1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 1, -1], [0, -1, 2, 1], [1, 0, 0, -1], [1, -1, 0, 0], [1, -1, 1, 0], [1, -1, 1, -1], [1, 0, 0, 0], ], "start_phi": 70 * DEGREES, "start_theta": -140 * DEGREES, "ambient_rotation_rate": 0.01, } def construct(self): self.add_q_tracker() self.setup_labels() self.setup_camera_position() self.add_prism() self.add_axes() self.apply_quaternions() def add_q_tracker(self): self.q_tracker = QuaternionTracker() self.q_tracker.add_updater(lambda m: m.normalize()) self.add(self.q_tracker) def setup_labels(self): left_q_label = QuaternionLabel([1, 0, 0, 0]) right_q_label = QuaternionLabel([1, 0, 0, 0]) for label in left_q_label, right_q_label: lp, rp = OldTex("()") lp.next_to(label, LEFT, SMALL_BUFF) rp.next_to(label, RIGHT, SMALL_BUFF) label.add(lp, rp) point_label = OldTex( *"(xi+yj+zk)", tex_to_color_map={ "i": I_COLOR, "j": J_COLOR, "k": K_COLOR, } ) left_q_label.next_to(point_label, LEFT) right_q_label.next_to(point_label, RIGHT) group = VGroup(left_q_label, point_label, right_q_label) group.arrange(RIGHT) group.set_width(FRAME_WIDTH - 1) group.to_edge(UP) self.add_fixed_in_frame_mobjects(BackgroundRectangle(group)) for label, text in zip(group, ["$q$", "Some 3d point", "$q^{-1}$"]): brace = Brace(label, DOWN) text_mob = OldTexText(text) if text_mob.get_width() > brace.get_width(): text_mob.match_width(brace) text_mob.next_to(brace, DOWN, buff=SMALL_BUFF) text_mob.add_background_rectangle() label.add(brace, text_mob) self.add_fixed_in_frame_mobjects(*group) left_q_label.add_updater( lambda m: m.set_value(self.q_tracker.get_value()) ) left_q_label.add_updater(lambda m: self.add_fixed_in_frame_mobjects(m)) right_q_label.add_updater( lambda m: m.set_value(quaternion_conjugate( self.q_tracker.get_value() )) ) right_q_label.add_updater(lambda m: self.add_fixed_in_frame_mobjects(m)) def setup_camera_position(self): self.set_camera_orientation( phi=self.start_phi, theta=self.start_theta, ) self.begin_ambient_camera_rotation(self.ambient_rotation_rate) def add_prism(self): prism = self.prism = self.get_prism() prism.add_updater( lambda p: p.become(self.get_prism( self.q_tracker.get_value() )) ) self.add(prism) def add_axes(self): axes = self.axes = always_redraw(self.get_axes) self.add(axes) def apply_quaternions(self): for quat in self.quaternions: self.change_q(quat) self.wait(2) # def get_unrotated_prism(self): return RandyPrism().scale(2) def get_prism(self, quaternion=[1, 0, 0, 0]): prism = self.get_unrotated_prism() angle, axis = angle_axis_from_quaternion(quaternion) prism.rotate(angle=angle, axis=axis, about_point=ORIGIN) return prism def get_axes(self): prism = self.prism centers = [sm.get_center() for sm in prism[:6]] axes = VGroup() for i in range(3): for u in [-1, 1]: vect = np.zeros(3) vect[i] = u dots = [np.dot(normalize(c), vect) for c in centers] max_i = np.argmax(dots) ec = centers[max_i] prism.get_edge_center(vect) p1 = np.zeros(3) p1[i] = ec[i] p1 *= dots[max_i] p2 = 10 * vect axes.add(Line(p1, p2)) axes.set_stroke(GREY_B, 1) axes.set_shade_in_3d(True) return axes def change_q(self, value, run_time=3, added_anims=None, **kwargs): if added_anims is None: added_anims = [] self.play( self.q_tracker.set_value, value, *added_anims, run_time=run_time, **kwargs ) class PauseAndPlayOverlay(Scene): def construct(self): pause = OldTex("=").rotate(TAU / 4) pause.stretch(2, 0) pause.scale(1.5) arrow = Vector(RIGHT, color=WHITE) interact = OldTexText("Interact...") group = VGroup(pause, arrow, interact) group.arrange(RIGHT) group.scale(2) not_yet = OldTexText("...well, not yet") not_yet.scale(2) not_yet.next_to(group, DOWN, MED_LARGE_BUFF) self.play(Write(pause)) self.play( GrowFromPoint( interact, arrow.get_left(), rate_func=squish_rate_func(smooth, 0.3, 1) ), VFadeIn(interact), GrowArrow(arrow), ) self.wait(2) self.play(Write(not_yet)) self.wait() class RotationMatrix(ShowSeveralQuaternionRotations): CONFIG = { "start_phi": 60 * DEGREES, "start_theta": -60 * DEGREES, } def construct(self): self.add_q_tracker() self.setup_camera_position() self.add_prism() self.add_basis_vector_labels() self.add_axes() title = OldTexText("Rotation matrix") title.scale(1.5) title.to_corner(UL) self.add_fixed_in_frame_mobjects(title) angle = 75 * DEGREES axis = [0.3, 1, 0.3] matrix = rotation_matrix(angle=angle, axis=axis) matrix_mob = DecimalMatrix(matrix, h_buff=1.6) matrix_mob.next_to(title, DOWN) matrix_mob.to_edge(LEFT) title.next_to(matrix_mob, UP) self.add_fixed_in_frame_mobjects(matrix_mob) colors = [I_COLOR, J_COLOR, K_COLOR] matrix_mob.set_column_colors(*colors) columns = matrix_mob.get_columns() column_rects = VGroup(*[ SurroundingRectangle(c).match_color(c[0]) for c in columns ]) labels = VGroup(*[ OldTexText( "Where", tex, "goes", tex_to_color_map={tex: rect.get_color()} ).next_to(rect, DOWN) for letter, rect in zip(["\\i", "\\j", "k"], column_rects) for tex in ["$\\hat{\\textbf{%s}}$" % (letter)] ]) labels.space_out_submobjects(0.8) quaternion = quaternion_from_angle_axis(angle, axis) self.play(Write(matrix_mob)) self.change_q(quaternion) self.wait() last_label = VectorizedPoint(matrix_mob.get_bottom()) last_rect = VMobject() for label, rect in zip(labels, column_rects): self.add_fixed_in_frame_mobjects(rect, label) self.play( FadeIn(label), FadeOut(last_label), ShowCreation(rect), FadeOut(last_rect) ) self.wait() last_label = label last_rect = rect self.play(FadeOut(last_label), FadeOut(last_rect)) self.wait(5) def get_unrotated_prism(self): prism = RandyPrism() prism.scale(1.5) arrows = VGroup() for i, color in enumerate([I_COLOR, J_COLOR, K_COLOR]): vect = np.zeros(3) vect[i] = 1 arrow = Arrow( prism.get_edge_center(vect), 2 * vect, preserve_tip_size_when_scaling=False, color=color, buff=0, ) arrows.add(arrow) arrows.set_shade_in_3d(True) prism.arrows = arrows prism.add(arrows) return prism def add_basis_vector_labels(self): labels = VGroup( OldTex("\\hat{\\textbf{\\i}}"), OldTex("\\hat{\\textbf{\\j}}"), OldTex("\\hat{\\textbf{k}}"), ) def generate_updater(arrow): return lambda m: m.move_to( arrow.get_end() + 0.2 * normalize(arrow.get_vector()), ) for arrow, label in zip(self.prism.arrows, labels): label.match_color(arrow) label.add_updater(generate_updater(arrow)) self.add_fixed_orientation_mobjects(label) class EulerAnglesAndGimbal(ShowSeveralQuaternionRotations): def construct(self): self.setup_position() self.setup_angle_trackers() self.setup_gimbal() self.add_axes() self.add_title() self.show_rotations() def setup_position(self): self.set_camera_orientation( theta=-140 * DEGREES, phi=70 * DEGREES, ) self.begin_ambient_camera_rotation(rate=0.015) def setup_angle_trackers(self): self.alpha_tracker = ValueTracker(0) self.beta_tracker = ValueTracker(0) self.gamma_tracker = ValueTracker(0) def setup_gimbal(self): gimbal = always_redraw(self.get_gimbal) self.gimbal = gimbal self.add(gimbal) def add_title(self): title = OldTexText("Euler angles") title.scale(1.5) title.to_corner(UL) angle_labels = VGroup( OldTex("\\alpha").set_color(YELLOW), OldTex("\\beta").set_color(GREEN), OldTex("\\gamma").set_color(PINK), ) angle_labels.scale(2) angle_labels.arrange(RIGHT, buff=MED_LARGE_BUFF) angle_labels.next_to(title, DOWN, aligned_edge=LEFT) self.angle_labels = angle_labels gl_label = VGroup( Arrow(LEFT, RIGHT, color=WHITE), OldTexText("Gimbal lock").scale(1.5), ) gl_label.arrange(RIGHT) gl_label.next_to(title, RIGHT) self.gimbal_lock_label = gl_label VGroup(title, angle_labels, gl_label).center().to_edge(UP) self.add_fixed_in_frame_mobjects(title, angle_labels, gl_label) self.remove(angle_labels) self.remove(gl_label) def show_rotations(self): gimbal = self.gimbal alpha_tracker = self.alpha_tracker beta_tracker = self.beta_tracker gamma_tracker = self.gamma_tracker angles = [-60 * DEGREES, 50 * DEGREES, 45 * DEGREES] trackers = [alpha_tracker, beta_tracker, gamma_tracker] in_rs = [0.6, 0.5, 0.6] for i in range(3): tracker = trackers[i] angle = angles[i] in_r = in_rs[i] ring = gimbal.rings[i] vect = ring.lines[0].get_vector() line = self.get_dotted_line(vect, in_r=in_r) angle_label = self.angle_labels[i] line.match_color(angle_label) self.play( ShowCreation(line), FadeInFromDown(angle_label) ) self.play( tracker.set_value, angle, run_time=3 ) self.play(FadeOut(line)) self.wait() self.wait(3) self.play(Write(self.gimbal_lock_label)) self.play( alpha_tracker.set_value, 0, beta_tracker.set_value, 0, run_time=2 ) self.play( alpha_tracker.set_value, 90 * DEGREES, gamma_tracker.set_value, -90 * DEGREES, run_time=3 ) self.play( FadeOut(self.gimbal_lock_label), *[ApplyMethod(t.set_value, 0) for t in trackers], run_time=3 ) self.play( alpha_tracker.set_value, 30 * DEGREES, beta_tracker.set_value, 120 * DEGREES, gamma_tracker.set_value, -50 * DEGREES, run_time=3 ) self.play( alpha_tracker.set_value, 120 * DEGREES, beta_tracker.set_value, -30 * DEGREES, gamma_tracker.set_value, 90 * DEGREES, run_time=4 ) self.play( beta_tracker.set_value, 150 * DEGREES, run_time=2 ) self.play( alpha_tracker.set_value, 0, beta_tracker.set_value, 0, gamma_tracker.set_value, 0, run_time=4 ) self.wait() # def get_gimbal(self): self.prism = RandyPrism() return Gimbal( alpha=self.alpha_tracker.get_value(), beta=self.beta_tracker.get_value(), gamma=self.gamma_tracker.get_value(), inner_mob=self.prism ) def get_dotted_line(self, vect, in_r=0, out_r=10): line = VGroup(*it.chain(*[ DashedLine( in_r * normalize(u * vect), out_r * normalize(u * vect), ) for u in [-1, 1] ])) line.sort(get_norm) line.set_shade_in_3d(True) line.set_stroke(YELLOW, 5) line.center() return line class InterpolationFail(Scene): def construct(self): words = OldTexText( "Sometimes interpolating 3d\\\\" "orientations is tricky..." ) words.to_edge(UP) self.add(words) class QuaternionInterpolation(ShowSeveralQuaternionRotations): def construct(self): self.add_q_tracker() self.setup_camera_position() self.add_prism() self.add_axes() self.change_q([1, 1, 1, 0], run_time=0) self.wait(2) self.change_q([1, 0.2, 0.6, -0.5], run_time=4) self.wait(2) self.change_q([1, -0.6, 0.2, -1], run_time=4) self.wait(2) class QuaternionInterpolationScematic(Scene): def construct(self): title = OldTexText("Slice of a hypersphere") title.to_edge(UP, buff=MED_SMALL_BUFF) self.add(title) radius = 3 circle = Circle(radius=radius) circle.set_stroke(GREY_B, 1) qs = [circle.point_from_proportion(p) for p in (0.55, 0.35, 0.15)] colors = [YELLOW, PINK, RED] q_dots = [Dot(q, color=c) for q, c in zip(qs, colors)] q_labels = [ OldTex("q_{}".format(i + 1)).next_to( dot, normalize(dot.get_center()), SMALL_BUFF ).match_color(dot) for i, dot in enumerate(q_dots) ] q1, q2, q3 = qs lines = [ DashedLine(q1, q2) for q1, q2 in zip(qs, qs[1:]) ] for color, line in zip([GREEN, BLUE], lines): line.set_stroke(color, 3) line.proj = line.copy().apply_function( lambda p: radius * normalize(p) ) dot = Dot(qs[0], color=WHITE) self.add(circle) self.add(dot) self.add(*q_dots + q_labels) self.wait(2) for line, q in zip(lines, qs[1:]): self.play( ShowCreation(line), ShowCreation(line.proj), dot.move_to, q, run_time=4 ) self.wait(2) class RememberComplexNumbers(TeacherStudentsScene): def construct(self): complex_number = OldTex( "\\cos(\\theta) + \\sin(\\theta)i", tex_to_color_map={ "\\cos(\\theta)": GREEN, "\\sin(\\theta)": RED } ) complex_number.scale(1.2) complex_number.next_to(self.students, UP, MED_LARGE_BUFF) self.teacher_says( "Remember how \\\\ complex numbers \\\\ compute rotations" ) self.play_all_student_changes("pondering") self.wait() self.play( FadeInFromDown(complex_number), self.change_students( "thinking", "confused", "happy", look_at=complex_number.get_center() + UP ), run_time=2 ) self.play_student_changes( ) self.wait(5) class ComplexNumberRotation(Scene): CONFIG = { "angle": 30 * DEGREES, } def construct(self): self.add_plane() self.add_number() self.show_complex_unit() self.show_product() def add_plane(self): plane = self.plane = ComplexPlane() self.play(Write(plane)) def add_number(self): plane = self.plane origin = plane.coords_to_point(0, 0) angle = self.angle point = plane.coords_to_point(4, 1) dot = Dot(point, color=YELLOW) label = OldTex("(4, 1)") label.next_to(dot, UR, buff=0) line = DashedLine(origin, point) rotated_line = line.copy().rotate(angle, about_point=origin) rotated_line.set_color(GREY) rotated_dot = dot.copy().rotate(angle, about_point=origin) rotated_dot.set_color(YELLOW_E) mystery_label = OldTex("(?, ?)") mystery_label.next_to(rotated_dot, UR, buff=0) arc = Arc( start_angle=line.get_angle(), angle=angle, radius=0.75 ) angle_tex = str(int(np.round(angle / DEGREES))) + "^\\circ" angle_label = OldTex(angle_tex) angle_label.next_to( arc.point_from_proportion(0.3), UR, buff=SMALL_BUFF ) self.play( FadeInFromDown(label), GrowFromCenter(dot), ShowCreation(line) ) self.wait() self.play( ShowCreation(arc), FadeInFromDown(angle_label), TransformFromCopy(line, rotated_line), TransformFromCopy(dot, rotated_dot), path_arc=angle, ) self.play(Write(mystery_label)) self.wait() self.rotation_mobs = VGroup( arc, angle_label, rotated_line, rotated_dot, mystery_label ) self.angle_tex = angle_tex self.number_label = label def show_complex_unit(self): plane = self.plane angle = self.angle angle_tex = self.angle_tex complex_coordinate_labels = plane.get_coordinate_labels() unit_circle = Circle(radius=1, color=YELLOW) origin = plane.number_to_point(0) z_point = plane.coords_to_point(np.cos(angle), np.sin(angle)) one_point = plane.number_to_point(1) z_dot = Dot(z_point, color=WHITE) one_dot = Dot(one_point, color=WHITE) one_dot.fade(1) z_line = Line(origin, z_point) one_line = Line(origin, one_point) VGroup(z_dot, one_dot, z_line, one_line).set_color(BLUE) cos_tex = "\\cos(" + angle_tex + ")" sin_tex = "\\sin(" + angle_tex + ")" label = OldTex( cos_tex, "+", sin_tex, "i", tex_to_color_map={cos_tex: GREEN, sin_tex: RED} ) label.add_background_rectangle() label.scale(0.8) label.next_to(plane.coords_to_point(0, 1), UR, SMALL_BUFF) arrow = Arrow(label.get_bottom(), z_point) number_label = self.number_label new_number_label = OldTex( "4 + 1i", tex_to_color_map={"4": GREEN, "1": RED} ) new_number_label.move_to(number_label, LEFT) new_number_label.add_background_rectangle() self.play( Write(complex_coordinate_labels, run_time=2), FadeOut(self.rotation_mobs) ) self.play(ShowCreation(unit_circle)) self.play( TransformFromCopy(one_dot, z_dot), TransformFromCopy(one_line, z_line), FadeInFromDown(label), GrowArrow(arrow), ) self.wait() self.play(FadeOutAndShiftDown(number_label)) self.play(FadeInFromDown(new_number_label)) self.wait() self.left_z_label = label self.right_z_label = new_number_label self.cos_tex = cos_tex self.sin_tex = sin_tex self.unit_z_group = VGroup( unit_circle, z_line, z_dot, label, arrow ) def show_product(self): plane = self.plane cos_tex = self.cos_tex sin_tex = self.sin_tex angle = self.angle line = Line( FRAME_WIDTH * LEFT / 2 + FRAME_HEIGHT * UP / 2, plane.coords_to_point(-0.5, 1.5) ) rect = BackgroundRectangle(line, buff=0) left_z = self.left_z_label right_z = self.right_z_label new_left_z = left_z.copy() new_right_z = right_z.copy() lp1, rp1, lp2, rp2 = parens = OldTex("()()") top_line = VGroup( lp1, new_left_z, rp1, lp2, new_right_z, rp2, ) top_line.arrange(RIGHT, buff=SMALL_BUFF) top_line.set_width(rect.get_width() - 1) top_line.next_to(rect.get_top(), DOWN, MED_SMALL_BUFF) mid_line = OldTex( "\\big(", "4", cos_tex, "-", "1", sin_tex, "\\big)", "+", "\\big(", "1", cos_tex, "+", "4", sin_tex, "\\big)", "i", tex_to_color_map={ cos_tex: GREEN, sin_tex: RED, "4": GREEN, "1": RED, } ) mid_line.set_width(rect.get_width() - 0.5) mid_line.next_to(top_line, DOWN, MED_LARGE_BUFF) new_z = np.exp(angle * complex(0, 1)) * complex(4, 1) low_line = OldTex( "\\approx", str(np.round(new_z.real, 2)), "+", str(np.round(new_z.imag, 2)), "i", ) low_line.next_to(mid_line, DOWN, MED_LARGE_BUFF) self.play(FadeIn(rect)) self.play( TransformFromCopy(left_z, new_left_z), TransformFromCopy(right_z, new_right_z), Write(parens) ) self.wait() self.play(FadeIn(mid_line, UP)) self.wait() self.play(FadeIn(low_line, UP)) self.wait(2) self.play(FadeOut(self.unit_z_group)) self.rotation_mobs.save_state() self.rotation_mobs.rotate(-angle, about_point=ORIGIN) self.rotation_mobs.fade(1) self.play(self.rotation_mobs.restore) self.wait() mystery_label = self.rotation_mobs[-1] result = low_line[1:].copy() result.add_background_rectangle() self.play( result.move_to, mystery_label, LEFT, FadeOutAndShiftDown(mystery_label), ) self.wait() class ISquaredRule(Scene): def construct(self): tex = OldTexText("Use", "$i^2 = -1$") tex[1].set_color(RED) tex.scale(2) self.add(tex) self.play(Write(tex)) self.wait() class RuleForQuaternionRotations(EulerAnglesAndGimbal): CONFIG = { "start_phi": 70 * DEGREES, "start_theta": -120 * DEGREES, "ambient_rotation_rate": 0.015, } def construct(self): self.add_q_tracker() self.setup_camera_position() self.add_prism() self.add_axes() self.show_axis() self.construct_quaternion() self.add_point_with_coordinates() self.add_inverse() def get_axes(self): axes = EulerAnglesAndGimbal.get_axes(self) for axis in axes: vect = normalize(axis.get_vector()) perp = rotate_vector(vect, TAU / 3, axis=[1, 1, 1]) for i in range(1, 4): tick = Line(-perp, perp).scale(0.1) tick.match_style(axis) tick.move_to(2 * i * vect) axis.add(tick) axes.set_shade_in_3d(True) return axes def show_axis(self): vect = normalize([1, -1, -0.5]) line = self.get_dotted_line(vect, 0, 4) quat = np.append(0, vect) axis_label = OldTexText("Axis of rotation") axis_label.next_to(line.get_corner(DR), DOWN, MED_LARGE_BUFF) axis_label.match_color(line) self.add_fixed_orientation_mobjects(axis_label) self.play( ShowCreation(line), Write(axis_label) ) self.change_q(quat, run_time=2) self.change_q([1, 0, 0, 0], run_time=2) # Unit vector vect_mob = Vector(2 * vect) vect_mob.pointwise_become_partial(vect_mob, 0, 0.95) pieces = VGroup(*vect_mob.get_pieces(25)) pieces.set_stroke(vect_mob.get_color(), 2) vect_mob.set_stroke(width=0) vect_mob.add_to_back(pieces) vect_mob.set_shade_in_3d(True) vect_label = OldTex( "{:.2f}".format(vect[0]), "i", "{:+.2f}".format(vect[1]), "j", "{:+.2f}".format(vect[2]), "k", ) magnitude_label = OldTex( "x", "^2 + ", "y", "^2 + ", "z", "^2 = 1", ) for label in vect_label, magnitude_label: decimals = label[::2] colors = [I_COLOR, J_COLOR, K_COLOR] for d1, color in zip(decimals, colors): d1.set_color(color) label.rotate(TAU / 4, RIGHT).scale(0.7) label.next_to(vect_mob.get_end(), RIGHT, SMALL_BUFF) magnitude_label.next_to(vect_label, IN) self.play( FadeOut(line), FadeOutAndShiftDown(axis_label), ShowCreation(vect_mob) ) # self.add_fixed_orientation_mobjects(vect_label) self.play(FadeInFromDown(vect_label)) self.wait(3) self.play(TransformFromCopy(vect_label, magnitude_label)) self.wait(3) self.vect = vect self.vect_mob = vect_mob self.vect_label = vect_label self.magnitude_label = magnitude_label def construct_quaternion(self): full_angle_q = self.get_quaternion_label("40^\\circ") half_angle_q = self.get_quaternion_label("40^\\circ / 2") for label in full_angle_q, half_angle_q: label.to_corner(UL) brace = Brace(half_angle_q, DOWN) q_label = brace.get_tex("q") full_angle_q.align_data_and_family(half_angle_q) rect = SurroundingRectangle(full_angle_q[5]) for mob in full_angle_q, half_angle_q, brace, q_label, rect: self.add_fixed_in_frame_mobjects(mob) self.remove(mob) self.play(FadeInFromDown(full_angle_q[1])) self.wait() self.play( FadeInFromDown(full_angle_q[0]), LaggedStartMap(FadeInFromDown, full_angle_q[2:]), ) self.play( GrowFromCenter(brace), Write(q_label) ) self.wait(2) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.wait(2) self.play(ReplacementTransform(full_angle_q, half_angle_q)) self.wait(6) # TODO def add_point_with_coordinates(self): prism = self.prism point = prism.get_corner(UR + OUT) template_sphere = Sphere(radius=0.1) template_sphere.set_stroke(width=0) template_sphere.set_color(PINK) ghost_sphere = template_sphere.copy() ghost_sphere.fade(0.8) for face in template_sphere: c = face.get_center() if c[0] < 0 and c[2] < 0: template_sphere.remove(face) template_sphere.move_to(point) ghost_sphere.move_to(point) def get_sphere(): result = template_sphere.copy() quat = self.q_tracker.get_value() angle, axis = angle_axis_from_quaternion(quat) result.rotate(angle=angle, axis=axis, about_point=ORIGIN) return result sphere = always_redraw(get_sphere) point_label = OldTex( "p", "=", "{:.2f}".format(point[0]), "i", "+" "{:.2f}".format(point[1]), "j", "+" "{:.2f}".format(point[2]), "k", ) colors = [PINK, I_COLOR, J_COLOR, K_COLOR] for part, color in zip(point_label[::2], colors): part.set_color(color) point_label.scale(0.7) point_label.rotate(TAU / 4, RIGHT) point_label.next_to(point, RIGHT) self.stop_ambient_camera_rotation() self.begin_ambient_camera_rotation(-0.01) self.play(FadeInFromLarge(sphere)) self.play(Write(point_label)) self.wait(3) # Rotate quat = quaternion_from_angle_axis(40 * DEGREES, self.vect) r = get_norm(point) curved_arrow = Arrow( r * RIGHT, rotate_vector(r * RIGHT, 30 * DEGREES, OUT), buff=0, path_arc=60 * DEGREES, color=GREY_B, ) curved_arrow.pointwise_become_partial(curved_arrow, 0, 0.9) curved_arrow.rotate(150 * DEGREES, about_point=ORIGIN) curved_arrow.apply_matrix(z_to_vector(self.vect)) self.add(ghost_sphere, sphere) self.change_q( quat, added_anims=[ShowCreation(curved_arrow)], run_time=3 ) mystery_label = OldTex("(?, ?, ?)") mystery_label.add_background_rectangle() arrow = Vector(0.5 * DR, color=WHITE) arrow.next_to(mystery_label, DR, buff=0) # mystery_label.add(arrow) mystery_label.rotate(TAU / 4, RIGHT) mystery_label.next_to(sphere, OUT + LEFT, buff=0) self.play(FadeInFromDown(mystery_label)) self.wait(5) def add_inverse(self): label = OldTex( "p", "\\rightarrow", "q", "\\cdot", "p", "\\cdot", "q^{-1}", tex_to_color_map={"p": PINK} ) label.to_corner(UR) label.shift(2 * LEFT) self.add_fixed_in_frame_mobjects(label) self.play(FadeInFromDown(label)) self.wait(3) self.change_q( [1, 0, 0, 0], rate_func=there_and_back, run_time=5 ) self.wait(3) # def get_quaternion_label(self, angle_tex): vect_label = self.vect_label.copy() vect_label.rotate(TAU / 4, LEFT) vect_label.replace(OldTex(vect_label.get_tex())) vect_label.add_background_rectangle() result = VGroup( OldTex("\\big("), OldTex("\\text{cos}(", angle_tex, ")"), OldTex("+"), OldTex("\\text{sin}(", angle_tex, ")"), OldTex("("), vect_label, OldTex(")"), OldTex("\\big)"), ) for i in 1, 3: result[i][1].set_color(YELLOW) result.arrange(RIGHT, buff=SMALL_BUFF) result.scale(0.7) return result class ExpandOutFullProduct(TeacherStudentsScene): def construct(self): product = OldTex( """ (w_0 + x_0 i + y_0 j + z_0 k) (x_1 i + y_1 j + z_1 k) (w_0 - x_0 i - y_0 j - z_0 k) """, tex_to_color_map={ "w_0": W_COLOR, "(": WHITE, ")": WHITE, "x_0": I_COLOR, "y_0": J_COLOR, "z_0": K_COLOR, "x_1": I_COLOR, "y_1": J_COLOR, "z_1": K_COLOR, } ) product.set_width(FRAME_WIDTH - 1) product.to_edge(UP) n = 10 q_brace = Brace(product[:n], DOWN) p_brace = Brace(product[n:-n], DOWN) q_inv_brace = Brace(product[-n:], DOWN) braces = VGroup(q_brace, p_brace, q_inv_brace) for brace, tex in zip(braces, ["q", "p", "q^{-1}"]): brace.add(brace.get_tex(tex)) words = OldTexText("= Rotation of $p$") words.next_to(braces, DOWN) self.play( self.teacher.change, "raise_right_hand", FadeInFromDown(product) ) self.play( LaggedStartMap(GrowFromCenter, braces), self.change_students( "confused", "horrified", "confused" ) ) self.wait(2) self.play(Write(words)) self.play_student_changes( "pondering", "confused", "erm", look_at=words ) self.wait(5) class Link(Scene): def construct(self): word = OldTexText("eater.net/quaternions") word.add_background_rectangle() rect = SurroundingRectangle(word) rect.set_color(BLUE) arrow = Vector(UR, color=GREEN) arrow.next_to(rect, UP) arrow.align_to(rect, RIGHT) short_arrow = arrow.copy().scale(0.8, about_edge=DL) self.add(word) self.play( ShowCreation(rect), GrowArrow(arrow), ) for x in range(10): self.play(Transform( arrow, short_arrow, rate_func=there_and_back, run_time=2 )) # Extra class QuaternionsDescribingRotation(EulerAnglesAndGimbal): CONFIG = { "use_lightweight_axes": True, "quaternions_and_imaginary_part_labels": [ ([1, 1, 0, 0], "{i}"), # ([1, 0, 1, 0], "{j}"), # ([0, 0, 0, 1], "{k}"), # ([1, 1, 1, 1], "\\left({{i} + {j} + {k} \\over \\sqrt{3}}\\right)"), ], } def construct(self): self.setup_position() self.show_rotations() def show_rotations(self): for quat, ipl in self.quaternions_and_imaginary_part_labels: quat = normalize(quat) axis = quat[1:] angle = 2 * np.arccos(quat[0]) label = self.get_label(angle, ipl) prism = RandyPrism() prism.scale(2) self.play( LaggedStartMap(FadeInFromDown, label), FadeIn(prism), ) self.play(Rotate( prism, angle=angle, axis=axis, run_time=3, about_point=ORIGIN, )) # def get_label(self, angle, imaginary_part_label): deg = int(angle / DEGREES) ipl = imaginary_part_label kwargs = { "tex_to_color_map": { "{i}": I_COLOR, "{j}": J_COLOR, "{k}": K_COLOR, } } p_label = OldTex( "x{i} + y{j} + z{k}", **kwargs ) arrow = OldTex( "\\rightarrow" ) q_label = OldTex( "\\big(\\cos(%d^\\circ) + \\sin(%d^\\circ)%s \\big)" % (deg, deg, ipl), **kwargs ) inner_p_label = OldTex( "\\left(x{i} + y{j} + z{k} \\right)", **kwargs ) q_inv_label = OldTex( "\\big(\\cos(-%d^\\circ) + \\sin(-%d^\\circ)%s \\big)" % (deg, deg, ipl), **kwargs ) equation = VGroup( p_label, arrow, q_label, inner_p_label, q_inv_label ) equation.arrange(RIGHT, buff=SMALL_BUFF) equation.set_width(FRAME_WIDTH - 1) equation.to_edge(UP) parts_text_colors = [ (p_label, "\\text{3d point}", YELLOW), (q_label, "q", PINK), (inner_p_label, "\\text{3d point}", YELLOW), (q_inv_label, "q^{-1}", PINK), ] braces = VGroup() for part, text, color in parts_text_colors: brace = Brace(part, DOWN, buff=SMALL_BUFF) label = brace.get_tex(text, buff=MED_SMALL_BUFF) label.set_color(color) brace.add(label) braces.add(brace) braces[-1][-1].shift(0.2 * UR) equation.add_to_back(BackgroundRectangle(equation)) equation.braces = braces equation.add(*braces) self.add_fixed_in_frame_mobjects(equation) self.add_fixed_in_frame_mobjects(braces) return equation
from manim_imports_ext import * from _2018.shadows import * # Abstract scenes class Cylinder(Sphere): """ Inherits from sphere so as to be as aligned as possible for transformations """ def func(self, u, v): return np.array([ np.cos(v), np.sin(v), np.cos(u) ]) class UnwrappedCylinder(Cylinder): def func(self, u, v): return np.array([ v - PI, -self.radius, np.cos(u) ]) class ParametricDisc(Sphere): CONFIG = { "u_min": 0, "u_max": 1, "stroke_width": 0, "checkerboard_colors": [BLUE_D], } def func(self, u, v): return np.array([ u * np.cos(v), u * np.sin(v), 0, ]) class SphereCylinderScene(SpecialThreeDScene): CONFIG = { "cap_config": { "stroke_width": 1, "stroke_color": WHITE, "fill_color": BLUE_D, "fill_opacity": 1, } } def get_cylinder(self, **kwargs): config = merge_dicts_recursively(self.sphere_config, kwargs) return Cylinder(**config) def get_cylinder_caps(self): R = self.sphere_config["radius"] caps = VGroup(*[ Circle( radius=R, **self.cap_config, ).shift(R * vect) for vect in [IN, OUT] ]) caps.set_shade_in_3d(True) return caps def get_unwrapped_cylinder(self): return UnwrappedCylinder(**self.sphere_config) def get_xy_plane(self): pass def get_ghost_surface(self, surface): result = surface.copy() result.set_fill(BLUE_E, opacity=0.5) result.set_stroke(WHITE, width=0.5, opacity=0.5) return result def project_point(self, point): radius = self.sphere_config["radius"] result = np.array(point) result[:2] = normalize(result[:2]) * radius return result def project_mobject(self, mobject): return mobject.apply_function(self.project_point) # Scenes for video class AskAboutShadowRelation(SpecialThreeDScene): CONFIG = { "R_color": YELLOW, "space_out_factor": 1.15, } def construct(self): self.show_surface_area() self.show_four_circles() self.ask_why() self.show_all_pieces() def show_surface_area(self): sphere = self.get_sphere() sphere.set_fill(BLUE_E, opacity=0.5) sphere.add_updater( lambda s, dt: s.rotate(0.1 * dt, axis=OUT) ) pieces = sphere.deepcopy() pieces.space_out_submobjects(1.5) pieces.shift(IN) pieces.set_color(GREEN) # radial_line = Line(ORIGIN, sphere.get_right()) # R_label = OldTex("R") # R_label.set_color(BLUE) # R_label.rotate(90 * DEGREES, RIGHT) # R_label.next_to(radial_line, OUT, SMALL_BUFF) sa_equation = OldTex( "\\text{Surface area} = 4\\pi R^2", tex_to_color_map={"R": BLUE} ) sa_equation.scale(1.5) sa_equation.to_edge(UP) self.set_camera_orientation( phi=70 * DEGREES, theta=-90 * DEGREES, ) self.add_fixed_in_frame_mobjects(sa_equation) self.play( Write(sphere, stroke_width=1), FadeInFromDown(sa_equation), # ShowCreation(radial_line), # FadeIn(R_label, IN), ) # self.play( # Transform( # sphere, pieces, # rate_func=there_and_back_with_pause, # run_time=2 # ) # ) self.play(LaggedStartMap( UpdateFromAlphaFunc, sphere, lambda mob: (mob, lambda m, a: m.set_fill( color=interpolate_color(BLUE_E, YELLOW, a), opacity=interpolate(0.5, 1, a) )), rate_func=there_and_back, lag_ratio=0.1, run_time=4 )) self.play( sphere.scale, 0.75, sphere.shift, 3 * LEFT, sa_equation.shift, 3 * LEFT, ) self.wait(2) self.sphere = sphere self.sa_equation = sa_equation def show_four_circles(self): sphere = self.sphere shadow = Circle( radius=sphere.get_width() / 2, stroke_color=WHITE, stroke_width=1, fill_color=BLUE_E, fill_opacity=1, ) radial_line = Line( shadow.get_center(), shadow.get_right(), color=YELLOW ) R_label = OldTex("R").set_color(self.R_color) R_label.scale(0.8) R_label.next_to(radial_line, DOWN, SMALL_BUFF) shadow.add(radial_line, R_label) shadow.move_to( self.camera.transform_points_pre_display(sphere, [sphere.get_center()])[0] ) shadows = VGroup(*[shadow.copy() for x in range(4)]) shadows.arrange_in_grid(buff=MED_LARGE_BUFF) shadows.to_edge(RIGHT) area_label = OldTex( "\\pi R^2", tex_to_color_map={"R": self.R_color} ) area_label.scale(1.2) area_labels = VGroup(*[ area_label.copy().move_to(interpolate( mob.get_center(), mob.get_top(), 0.5 )) for mob in shadows ]) # shadow.move_to(sphere) self.add_fixed_in_frame_mobjects(shadow) self.play(DrawBorderThenFill(shadow)) anims = [] for new_shadow in shadows: old_shadow = shadow.copy() self.add_fixed_in_frame_mobjects(old_shadow) anims.append(Transform( old_shadow, new_shadow, remover=True )) self.remove(shadow) self.play(*anims) self.add_fixed_in_frame_mobjects(shadows, area_labels) self.play(LaggedStartMap(FadeInFromLarge, area_labels)) self.wait() self.shadows = shadows self.shadow_area_labels = area_labels def ask_why(self): pass def show_all_pieces(self): shadows = self.shadows area_labels = self.shadow_area_labels sphere = self.sphere shadow_pieces_group = VGroup() for shadow in shadows: pieces = ParametricSurface( func=lambda u, v: np.array([ u * np.cos(TAU * v), u * np.sin(TAU * v), 0, ]), resolution=(12, 24) ) pieces.replace(shadow) pieces.match_style(sphere) shadow_pieces_group.add(pieces) self.add_fixed_in_frame_mobjects(shadow_pieces_group) self.play( FadeOut(shadows), FadeOut(area_labels), FadeIn(shadow_pieces_group) ) self.show_area_pieces(sphere) self.wait() self.show_area_pieces(*shadow_pieces_group) self.wait(2) self.unshow_area_pieces(sphere, *shadow_pieces_group) self.wait(3) def show_area_pieces(self, *mobjects): for mob in mobjects: mob.generate_target() mob.target.space_out_submobjects(self.space_out_factor) self.play(*map(MoveToTarget, mobjects)) self.play(*[ LaggedStartMap( ApplyMethod, mob, lambda m: (m.set_fill, YELLOW, 1), rate_func=there_and_back, lag_ratio=0.25, run_time=1.5 ) for mob in mobjects ]) def unshow_area_pieces(self, *mobjects): self.play(*[ ApplyMethod( mob.space_out_submobjects, 1.0 / self.space_out_factor ) for mob in mobjects ]) class ButWhy(TeacherStudentsScene): CONFIG = { "student_mode": "raise_right_hand", "question": "But why?", "teacher_mode": "guilty" } def construct(self): for student in self.students: student.change("pondering", self.screen) self.student_says( "But why?", index=2, target_mode=self.student_mode, bubble_config={"direction": LEFT}, ) self.play( self.teacher.change, self.teacher_mode, self.students[2] ) self.wait(5) class ButWhyHappy(ButWhy): CONFIG = { "teacher_mode": "happy" } class ButWhySassy(ButWhy): CONFIG = { "teacher_mode": "sassy" } class ButWhyHesitant(ButWhy): CONFIG = { "teacher_mode": "hesitant" } class ButWhyAngry(ButWhy): CONFIG = { "teacher_mode": "angry" } class TryFittingCirclesDirectly(ExternallyAnimatedScene): pass class PreviewTwoMethods(MovingCameraScene): def construct(self): thumbnails = Group( ImageMobject("SphereSurfaceProof1"), ImageMobject("SphereSurfaceProof2"), ) for thumbnail in thumbnails: thumbnail.set_width(FRAME_WIDTH / 2 - 1) thumbnail.add_to_back(SurroundingRectangle( thumbnail, buff=0, stroke_color=WHITE, stroke_width=5 )) thumbnails.arrange(RIGHT, buff=LARGE_BUFF) title = OldTexText("Two proofs") title.scale(2) title.to_edge(UP) frame = self.camera.frame self.add(title) for thumbnail in thumbnails: self.play(FadeInFromDown(thumbnail)) self.wait() for thumbnail in thumbnails: frame.save_state() self.play( frame.replace, thumbnail, run_time=2 ) self.wait() self.play(Restore(frame, run_time=2)) class MapSphereOntoCylinder(SphereCylinderScene): def construct(self): sphere = self.get_sphere() sphere_ghost = self.get_ghost_surface(sphere) sphere_ghost.set_stroke(width=0) axes = self.get_axes() cylinder = self.get_cylinder() cylinder.set_fill(opacity=0.75) radius = cylinder.get_width() / 2 self.add(axes, sphere_ghost, sphere) self.wait() self.begin_ambient_camera_rotation() self.move_camera( **self.default_angled_camera_position, run_time=2, ) self.wait(2) self.play( ReplacementTransform(sphere, cylinder), run_time=3 ) self.wait(3) # Get rid of caps caps = self.get_cylinder_caps() caps[1].set_shade_in_3d(False) label = OldTexText("Label") label.scale(1.5) label.stretch(0.8, 0) label.rotate(90 * DEGREES, RIGHT) label.rotate(90 * DEGREES, OUT) label.shift(np.log(radius + SMALL_BUFF) * RIGHT) label.apply_complex_function(np.exp) label.rotate(90 * DEGREES, IN, about_point=ORIGIN) label.shift(OUT) label.set_background_stroke(width=0) self.play(FadeIn(caps)) self.wait() self.play( caps.space_out_submobjects, 2, caps.fade, 1, remover=True ) self.play(Write(label)) self.wait(2) self.play(FadeOut(label)) # Unwrap unwrapped_cylinder = self.get_unwrapped_cylinder() unwrapped_cylinder.set_fill(opacity=0.75) self.play( ReplacementTransform(cylinder, unwrapped_cylinder), run_time=3 ) self.stop_ambient_camera_rotation() self.move_camera( phi=90 * DEGREES, theta=-90 * DEGREES, ) # Show dimensions stroke_width = 5 top_line = Line( PI * radius * LEFT + radius * OUT, PI * radius * RIGHT + radius * OUT, color=YELLOW, stroke_width=stroke_width, ) side_line = Line( PI * radius * LEFT + radius * OUT, PI * radius * LEFT + radius * IN, color=RED, stroke_width=stroke_width, ) lines = VGroup(top_line, side_line) lines.shift(radius * DOWN) two_pi_R = OldTex("2\\pi R") two_R = OldTex("2R") texs = VGroup(two_pi_R, two_R) for tex in texs: tex.scale(1.5) tex.rotate(90 * DEGREES, RIGHT) two_pi_R.next_to(top_line, OUT) two_R.next_to(side_line, RIGHT) self.play( ShowCreation(top_line), FadeIn(two_pi_R, IN) ) self.wait() self.play( ShowCreation(side_line), FadeIn(two_R, RIGHT) ) self.wait() class CircumferenceOfCylinder(SphereCylinderScene): def construct(self): sphere = self.get_sphere() sphere_ghost = self.get_ghost_surface(sphere) cylinder = self.get_cylinder() cylinder_ghost = self.get_ghost_surface(cylinder) cylinder_ghost.set_stroke(width=0) radius = self.sphere_config["radius"] circle = Circle(radius=radius) circle.set_stroke(YELLOW, 5) circle.shift(radius * OUT) height = Line(radius * IN, radius * OUT) height.shift(radius * LEFT) height.set_stroke(RED, 5) self.set_camera_orientation( phi=70 * DEGREES, theta=-95 * DEGREES, ) self.begin_ambient_camera_rotation(0.01) self.add(sphere_ghost, cylinder_ghost) self.wait() self.play(ShowCreation(circle)) self.wait(2) self.play(ShowCreation(height)) self.wait(5) class UnfoldCircles(Scene): CONFIG = { "circle_style": { "fill_color": GREY_BROWN, "fill_opacity": 0, "stroke_color": GREY_BROWN, "stroke_width": 2, }, "radius": 1.0, "dr": 0.01, } def construct(self): self.show_rectangle_with_formula() self.add_four_circles() def show_rectangle_with_formula(self): Tex.CONFIG["background_stroke_width"] = 1 R = self.radius rect = Rectangle(width=TAU * R, height=2 * R) rect.set_fill(BLUE_E, 1) rect.set_stroke(width=0) p0, p1, p2 = [rect.get_corner(v) for v in (DL, UL, UR)] h_line = Line(p0, p1) h_line.set_stroke(RED, 3) w_line = Line(p1, p2) w_line.set_stroke(YELLOW, 3) two_R = OldTex("2", "R") two_R.next_to(h_line, LEFT) two_pi_R = OldTex("2", "\\pi", "R") two_pi_R.next_to(w_line, UP) pre_area_label = OldTex( "2\\cdot", "2", "\\pi", "R", "\\cdot R" ) area_label = OldTex("4", "\\pi", "R^2") for label in [area_label, pre_area_label]: label.next_to(rect.get_center(), UP, SMALL_BUFF) self.rect_group = VGroup( rect, h_line, w_line, two_R, two_pi_R, area_label ) self.area_label = area_label self.rect = rect self.add(rect, h_line, w_line, two_R, two_pi_R) self.play( TransformFromCopy(two_R[0], pre_area_label[0]), TransformFromCopy(two_R[1], pre_area_label[-1]), TransformFromCopy(two_pi_R, pre_area_label[1:-1]), ) self.wait() self.play( ReplacementTransform(pre_area_label[:2], area_label[:1]), ReplacementTransform(pre_area_label[2], area_label[1]), ReplacementTransform(pre_area_label[3:], area_label[2:]), ) self.wait() self.play( self.rect_group.to_corner, UL, {"buff": MED_SMALL_BUFF} ) def add_four_circles(self): rect_group = self.rect_group radius = self.radius radii_lines = VGroup(*[ Line(radius * UP, ORIGIN).set_stroke(WHITE, 2) for x in range(4) ]) radii_lines.arrange_in_grid(buff=1.3) radii_lines[2:].shift(RIGHT) radii_lines.next_to(rect_group, DOWN, buff=1.3) R_labels = VGroup(*[ OldTex("R").next_to(line, LEFT, SMALL_BUFF) for line in radii_lines ]) unwrap_factor_tracker = ValueTracker(0) def get_circle(line): return always_redraw( lambda: self.get_unwrapped_circle( radius=radius, dr=self.dr, unwrap_factor=unwrap_factor_tracker.get_value(), center=line.get_top() ) ) circles = VGroup(*[get_circle(line) for line in radii_lines]) circle_copies = circles.copy() for mob in circle_copies: mob.clear_updaters() self.play( LaggedStartMap(Write, circle_copies, lag_ratio=0.7), LaggedStartMap(Write, R_labels), LaggedStartMap(ShowCreation, radii_lines), ) self.remove(circle_copies) self.add(circles, radii_lines, R_labels) self.wait() self.play( radii_lines[2:].shift, 2.9 * RIGHT, R_labels[2:].shift, 2.9 * RIGHT, VGroup( radii_lines[:2], R_labels[:2] ).to_edge, LEFT, {"buff": 1.0} ) self.play( unwrap_factor_tracker.set_value, 1, run_time=2 ) self.wait() # Move triangles triangles = circles.copy() for triangle in triangles: triangle.clear_updaters() border = Polygon(*[ triangle.get_corner(vect) for vect in (DL, UL, DR) ]) border.set_stroke(WHITE, 1) triangle.add(border) triangle.generate_target() rect = self.rect for i, triangle in enumerate(triangles): if i % 2 == 1: triangle.target.rotate(PI) vect = UP if i < 2 else DOWN triangle.target.move_to(rect, vect) self.play(FadeIn(triangles)) self.add(triangles, triangles.copy(), self.area_label) self.play(MoveToTarget(triangles[0])) self.wait() self.play(LaggedStartMap(MoveToTarget, triangles)) self.wait() # def get_unwrapped_circle(self, radius, dr, unwrap_factor=0, center=ORIGIN): radii = np.arange(0, radius + dr, dr) rings = VGroup() for r in radii: r_factor = 1 + 3 * (r / radius) alpha = unwrap_factor**r_factor alpha = np.clip(alpha, 0, 0.9999) angle = interpolate(TAU, 0, alpha) length = TAU * r arc_radius = length / angle ring = Arc( start_angle=-90 * DEGREES, angle=angle, radius=arc_radius, **self.circle_style ) ring.shift(center + (r - arc_radius) * DOWN) # ring = AnnularSector( # inner_radius=r1, # outer_radius=r2, # angle=TAU, # start_angle=-TAU / 4, # **self.circle_style # ) rings.add(ring) return rings class ShowProjection(SphereCylinderScene): CONFIG = { # "default_angled_camera_position": { # "theta": -155 * DEGREES, # } } def construct(self): self.setup_shapes() self.show_many_tiny_rectangles() self.project_all_rectangles() self.focus_on_one() self.label_sides() self.show_length_scaled_up() self.show_height_scaled_down() def setup_shapes(self): self.sphere = self.get_sphere() self.cylinder = self.get_cylinder() self.ghost_sphere = self.get_ghost_surface(self.sphere) self.ghost_sphere.scale(0.99) self.ghost_cylinder = self.get_ghost_surface(self.cylinder) self.ghost_cylinder.set_stroke(width=0) self.add(self.get_axes()) self.set_camera_to_default_position() self.begin_ambient_camera_rotation() def show_many_tiny_rectangles(self): ghost_sphere = self.ghost_sphere pieces = self.sphere.copy() random.shuffle(pieces.submobjects) for piece in pieces: piece.save_state() pieces.space_out_submobjects(2) pieces.fade(1) self.add(ghost_sphere) self.play(LaggedStartMap(Restore, pieces)) self.wait() self.pieces = pieces def project_all_rectangles(self): pieces = self.pieces for piece in pieces: piece.save_state() piece.generate_target() self.project_mobject(piece.target) piece.target.set_fill(opacity=0.5) example_group = self.get_example_group([1, -1, 2]) proj_lines = example_group[1] self.example_group = example_group self.play(*map(ShowCreation, proj_lines)) self.play( LaggedStartMap(MoveToTarget, pieces), ) self.wait() def focus_on_one(self): ghost_cylinder = self.ghost_cylinder pieces = self.pieces example_group = self.example_group original_rect, rect_proj_lines, rect = example_group equation = self.get_equation(rect) lhs, equals, rhs = equation[:3] lhs.save_state() rhs.save_state() self.play( FadeIn(ghost_cylinder), FadeOut(pieces), FadeIn(original_rect), ) self.play(TransformFromCopy(original_rect, rect)) self.wait() self.add_fixed_in_frame_mobjects(lhs, equals, rhs) self.move_fixed_in_frame_mob_to_unfixed_mob(lhs, original_rect) self.move_fixed_in_frame_mob_to_unfixed_mob(rhs, rect) self.play( Restore(lhs), Restore(rhs), FadeInFromDown(equals), ) self.wait(5) self.equation = equation self.example_group = example_group def label_sides(self): sphere = self.sphere equation = self.equation w_brace, h_brace = equation.braces width_label, height_label = equation.labels u_values, v_values = sphere.get_u_values_and_v_values() radius = sphere.radius lat_lines = VGroup(*[ ParametricCurve( lambda t: radius * sphere.func(u, t), t_min=sphere.v_min, t_max=sphere.v_max, ) for u in u_values ]) lon_lines = VGroup(*[ ParametricCurve( lambda t: radius * sphere.func(t, v), t_min=sphere.u_min, t_max=sphere.u_max, ) for v in v_values ]) for lines in lat_lines, lon_lines: for line in lines: line.add(DashedVMobject(line, spacing=-1)) line.set_points([]) line.set_stroke(width=2) lines.set_shade_in_3d(True) lat_lines.set_color(RED) lon_lines.set_color(PINK) self.play( *map(ShowCreationThenDestruction, lat_lines), run_time=2 ) self.add_fixed_in_frame_mobjects(w_brace, width_label) self.play( GrowFromCenter(w_brace), Write(width_label), ) self.wait() self.play( *map(ShowCreationThenDestruction, lon_lines), run_time=2 ) self.add_fixed_in_frame_mobjects(h_brace, height_label) self.play( GrowFromCenter(h_brace), Write(height_label), ) self.wait(2) def show_length_scaled_up(self): ghost_sphere = self.ghost_sphere example_group = self.example_group equation = self.equation equation.save_state() new_example_groups = [ self.get_example_group([1, -1, z]) for z in [6, 0.25] ] r1, lines, r2 = example_group self.stop_ambient_camera_rotation() self.move_camera( phi=65 * DEGREES, theta=-80 * DEGREES, added_anims=[ ghost_sphere.set_stroke, {"opacity": 0.1}, lines.set_stroke, {"width": 3}, ] ) for eg in new_example_groups: eg[1].set_stroke(width=3) self.show_length_stretch_of_rect(example_group) all_example_groups = [example_group, *new_example_groups] for eg1, eg2 in zip(all_example_groups, all_example_groups[1:]): if eg1 is new_example_groups[0]: self.move_camera( phi=70 * DEGREES, theta=-110 * DEGREES ) self.remove(eg1) self.play( ReplacementTransform(eg1.deepcopy(), eg2), Transform( equation, self.get_equation(eg2[2]) ) ) if eg1 is example_group: self.move_camera( phi=0, theta=-90 * DEGREES, ) self.show_length_stretch_of_rect(eg2) self.play( ReplacementTransform(all_example_groups[-1], example_group), Restore(equation) ) def show_length_stretch_of_rect(self, example_group): s_rect, proj_lines, c_rect = example_group rects = VGroup(s_rect, c_rect) line1, line2 = lines = VGroup(*[ Line(m.get_anchors()[1], m.get_anchors()[2]) for m in rects ]) lines.set_stroke(YELLOW, 5) lines.set_shade_in_3d(True) proj_lines_to_fade = VGroup( proj_lines[0], proj_lines[3], ) self.play( FadeIn(lines[0]), FadeOut(rects), FadeOut(proj_lines_to_fade) ) for x in range(3): anims = [] if lines[1] in self.mobjects: anims.append(FadeOut(lines[1])) self.play( TransformFromCopy(lines[0], lines[1]), *anims ) self.play( FadeOut(lines), FadeIn(rects), FadeIn(proj_lines_to_fade), ) self.remove(rects, proj_lines_to_fade) self.add(example_group) def show_height_scaled_down(self): ghost_sphere = self.ghost_sphere ghost_cylinder = self.ghost_cylinder example_group = self.example_group equation = self.equation r1, lines, r2 = example_group to_fade = VGroup(*[ mob for mob in it.chain(ghost_sphere, ghost_cylinder) if np.dot(mob.get_center(), [1, 1, 0]) < 0 ]) to_fade.save_state() new_example_groups = [ self.get_example_group([1, -1, z]) for z in [6, 0.25] ] for eg in new_example_groups: eg[::2].set_stroke(YELLOW, 2) eg.set_stroke(width=1) all_example_groups = VGroup(example_group, *new_example_groups) self.play( to_fade.shift, IN, to_fade.fade, 1, remover=True ) self.move_camera( phi=85 * DEGREES, theta=-135 * DEGREES, added_anims=[ lines.set_stroke, {"width": 1}, r1.set_stroke, YELLOW, 2, 1, r2.set_stroke, YELLOW, 2, 1, ] ) self.show_shadow(example_group) for eg1, eg2 in zip(all_example_groups, all_example_groups[1:]): self.remove(*eg1.get_family()) self.play( ReplacementTransform(eg1.deepcopy(), eg2), Transform( equation, self.get_equation(eg2[2]) ) ) self.show_shadow(eg2) self.move_camera( phi=70 * DEGREES, theta=-115 * DEGREES, added_anims=[ ReplacementTransform( all_example_groups[-1], example_group, ), Restore(equation), ] ) self.begin_ambient_camera_rotation() self.play(Restore(to_fade)) self.wait(5) def show_shadow(self, example_group): s_rect, lines, c_rect = example_group for x in range(3): self.play(TransformFromCopy(s_rect, c_rect)) # def get_projection_lines(self, piece): result = VGroup() radius = self.sphere_config["radius"] for corner in piece.get_anchors()[:-1]: start = np.array(corner) end = np.array(corner) start[:2] = np.zeros(2) end[:2] = (radius + 0.03) * normalize(end[:2]) kwargs = { "color": YELLOW, "stroke_width": 0.5, } result.add(VGroup(*[ Line(p1, p2, **kwargs) for p1, p2 in [(start, corner), (corner, end)] ])) result.set_shade_in_3d(True) return result def get_equation(self, rect): length = get_norm(rect.get_anchors()[1] - rect.get_anchors()[0]) height = get_norm(rect.get_anchors()[2] - rect.get_anchors()[1]) lhs = Rectangle(width=length, height=height) rhs = Rectangle(width=height, height=length) eq_rects = VGroup(lhs, rhs) eq_rects.set_stroke(width=0) eq_rects.set_fill(YELLOW, 1) eq_rects.scale(2) equals = OldTex("=") equation = VGroup(lhs, equals, rhs) equation.arrange(RIGHT) equation.to_corner(UR) brace = Brace(Line(ORIGIN, 0.5 * RIGHT), DOWN) w_brace = brace.copy().match_width(lhs, stretch=True) h_brace = brace.copy().rotate(-90 * DEGREES) h_brace.match_height(lhs, stretch=True) w_brace.next_to(lhs, DOWN, buff=SMALL_BUFF) h_brace.next_to(lhs, LEFT, buff=SMALL_BUFF) braces = VGroup(w_brace, h_brace) width_label = OldTexText("Width") height_label = OldTexText("Height") labels = VGroup(width_label, height_label) labels.scale(0.75) width_label.next_to(w_brace, DOWN, SMALL_BUFF) height_label.next_to(h_brace, LEFT, SMALL_BUFF) equation.braces = braces equation.labels = labels equation.add(braces, labels) return equation def move_fixed_in_frame_mob_to_unfixed_mob(self, m1, m2): phi = self.camera.phi_tracker.get_value() theta = self.camera.theta_tracker.get_value() target = m2.get_center() target = rotate_vector(target, -theta - 90 * DEGREES, OUT) target = rotate_vector(target, -phi, RIGHT) m1.move_to(target) m1.scale(0.1) m1.shift(SMALL_BUFF * UR) return m1 def get_example_group(self, vect): pieces = self.pieces rect = pieces[np.argmax([ np.dot(r.saved_state.get_center(), vect) for r in pieces ])].saved_state.copy() rect_proj_lines = self.get_projection_lines(rect) rect.set_fill(YELLOW, 1) original_rect = rect.copy() self.project_mobject(rect) rect.shift( 0.001 * np.array([*rect.get_center()[:2], 0]) ) result = VGroup(original_rect, rect_proj_lines, rect) result.set_shade_in_3d(True) return result class SlantedShadowSquishing(ShowShadows): CONFIG = { "num_reorientations": 4, "random_seed": 2, } def setup(self): ShowShadows.setup(self) self.surface_area_label.fade(1) self.shadow_area_label.fade(1) self.shadow_area_decimal.fade(1) def construct(self): # Show creation self.set_camera_orientation( phi=70 * DEGREES, theta=-150 * DEGREES, ) self.begin_ambient_camera_rotation(0.01) square = self.obj3d.deepcopy() square.clear_updaters() shadow = always_redraw(lambda: get_shadow(square)) # Reorient self.add(square, shadow) for n in range(self.num_reorientations): angle = 40 * DEGREES self.play( Rotate(square, angle, axis=RIGHT), run_time=2 ) def get_object(self): square = Square() square.set_shade_in_3d(True) square.set_height(2) square.set_stroke(WHITE, 0.5) square.set_fill(BLUE_C, 1) return square class JustifyLengthStretch(ShowProjection): CONFIG = { "R_color": RED, "d_color": WHITE, "d_ambiguity_iterations": 4, } def construct(self): self.setup_shapes() self.add_ghosts() self.add_example_group() self.cut_cross_section() self.label_R() self.label_d() self.show_similar_triangles() def add_ghosts(self): self.add(self.ghost_sphere, self.ghost_cylinder) def add_example_group(self): self.pieces = self.sphere for piece in self.pieces: piece.save_state() self.example_group = self.get_example_group([1, 0.1, 1.5]) self.add(self.example_group) self.set_camera_orientation(theta=-45 * DEGREES) def cut_cross_section(self): sphere = self.ghost_sphere cylinder = self.ghost_cylinder to_fade = VGroup(*[ mob for mob in it.chain(sphere, cylinder) if np.dot(mob.get_center(), DOWN) > 0 ]) self.lost_hemisphere = to_fade to_fade.save_state() circle = Circle( stroke_width=2, stroke_color=PINK, radius=self.sphere.radius ) circle.rotate(90 * DEGREES, RIGHT) self.circle = circle self.example_group.set_stroke(YELLOW, 1) self.stop_ambient_camera_rotation() self.play( Rotate( to_fade, -PI, axis=OUT, about_point=sphere.get_left(), run_time=2 ), VFadeOut(to_fade, run_time=2), FadeIn(circle), ) # self.move_camera( # phi=80 * DEGREES, # theta=-85 * DEGREES, # ) def label_R(self): circle = self.circle R_line = Line(ORIGIN, circle.get_right()) R_line.set_color(self.R_color) R_label = OldTex("R") R_label.next_to(R_line, IN) self.add_fixed_orientation_mobjects(R_label) self.play( ShowCreation(R_line), FadeIn(R_label, IN), ) self.wait() self.R_line = R_line self.R_label = R_label def label_d(self): example_group = self.example_group s_rect = example_group[0] d_line = self.get_d_line( s_rect.get_corner(IN + RIGHT + DOWN) ) alt_d_line = self.get_d_line( s_rect.get_corner(OUT + LEFT + DOWN) ) d_label = OldTex("d") d_label.next_to(d_line, IN) self.add_fixed_orientation_mobjects(d_label) self.play( ShowCreation(d_line), FadeIn(d_label, IN), ) self.wait() for x in range(self.d_ambiguity_iterations): to_fade_out = [d_line, alt_d_line][x % 2] to_fade_in = [d_line, alt_d_line][(x + 1) % 2] self.play( FadeIn(to_fade_in), FadeOut(to_fade_out), d_label.next_to, to_fade_in, IN, ) self.d_line = d_line self.d_label = d_label def show_similar_triangles(self): d_line = self.d_line d_label = self.d_label R_line = self.R_line R_label = self.R_label example_group = self.example_group s_rect, proj_lines, c_rect = example_group p1 = s_rect.get_anchors()[1] p2 = s_rect.get_anchors()[2] p0 = np.array(p1) p0[:2] = np.zeros(2) triangle = Polygon(p0, p1, p2) triangle.set_stroke(width=0) triangle.set_fill(GREEN, opacity=1) base = Line(p1, p2) base.set_stroke(PINK, 3) big_triangle = Polygon( p0, self.project_point(p1), self.project_point(p2) ) big_triangle.set_stroke(width=0) big_triangle.set_fill(RED, opacity=1) equation = VGroup( triangle.copy().rotate(-3 * DEGREES), OldTex("\\sim"), big_triangle.copy().rotate(-3 * DEGREES) ) equation.arrange(RIGHT, buff=SMALL_BUFF) equation.to_corner(UL) eq_d = OldTex("d").next_to(equation[0], DOWN, SMALL_BUFF) eq_R = OldTex("R").next_to(equation[2], DOWN, SMALL_BUFF) VGroup(equation, eq_d, eq_R).rotate(20 * DEGREES, axis=RIGHT) for mob in [triangle, big_triangle]: mob.set_shade_in_3d(True) mob.set_fill(opacity=0.8) self.move_camera( phi=40 * DEGREES, theta=-85 * DEGREES, added_anims=[ d_label.next_to, d_line, DOWN, SMALL_BUFF, d_line.set_stroke, {"width": 1}, FadeOut(proj_lines[0]), FadeOut(proj_lines[3]), FadeOut(R_label) ], run_time=2, ) point = VectorizedPoint(p0) point.set_shade_in_3d(True) self.play( ReplacementTransform(point, triangle), Animation(self.camera.phi_tracker) ) self.add_fixed_in_frame_mobjects(equation, eq_d, eq_R) self.play( FadeIn(equation[0], 7 * RIGHT + 2.5 * DOWN), FadeIn(equation[1:]), FadeInFromDown(eq_d), FadeInFromDown(eq_R), Animation(self.camera.phi_tracker) ) self.wait() for x in range(2): self.play(ShowCreationThenDestruction(base)) self.wait() d_line_copy = d_line.copy().set_stroke(WHITE, 3) self.play(ShowCreation(d_line_copy)) self.play(FadeOut(d_line_copy)) self.wait(2) R_label.next_to(R_line, DOWN, SMALL_BUFF) R_label.shift(0.25 * IN) self.play( ReplacementTransform(triangle, big_triangle), FadeIn(R_label), Animation(self.camera.phi_tracker) ) self.wait(3) self.move_camera( phi=70 * DEGREES, theta=-70 * DEGREES, added_anims=[ big_triangle.set_fill, {"opacity": 0.25}, d_label.next_to, d_line, IN, {"buff": 0.3}, ] ) self.begin_ambient_camera_rotation() lost_hemisphere = self.lost_hemisphere lost_hemisphere.restore() left_point = self.sphere.get_left() lost_hemisphere.rotate(-PI, axis=OUT, about_point=left_point) self.play( Rotate( lost_hemisphere, PI, axis=OUT, about_point=left_point, run_time=2, ), VFadeIn(lost_hemisphere), FadeOut(self.circle), R_line.set_color, self.R_color, ) self.wait(10) # def get_d_line(self, sphere_point): end = sphere_point start = np.array(end) start[:2] = np.zeros(2) d_line = Line(start, end) d_line.set_color(self.d_color) return d_line class JustifyLengthStretchHigherRes(JustifyLengthStretch): CONFIG = { "sphere_config": { "resolution": (2 * 24, 2 * 48) }, } class JustifyLengthStretchHighestRes(JustifyLengthStretch): CONFIG = { "sphere_config": { "resolution": (4 * 24, 4 * 48) }, } class ProTipNameThings(Scene): CONFIG = { "tip_descriptor": "(Deceptively simple) problem solving tip:", "tip": "Start with names", } def construct(self): words = OldTexText( self.tip_descriptor, self.tip, ) words[1].set_color(YELLOW) words.to_edge(UP) self.play(FadeIn(words[0])) self.wait() self.play(FadeInFromDown(words[1])) self.wait() class WidthScaleLabel(Scene): def construct(self): text = OldTex( "\\text{Width scale factor} =", "\\frac{R}{d}" ) self.play(Write(text)) self.wait() class HeightSquishLabel(Scene): def construct(self): text = OldTex( "\\text{Height squish factor} =", "\\frac{R}{d}" ) self.play(Write(text)) self.wait() class TinierAndTinerRectangles(SphereCylinderScene): CONFIG = { "n_iterations": 5, } def construct(self): spheres = [ self.get_sphere( resolution=(12 * (2**n), 24 * (2**n)), stroke_width=0, ) for n in range(self.n_iterations) ] self.set_camera_to_default_position() self.add(self.get_axes()) self.begin_ambient_camera_rotation() self.add(spheres[0]) for s1, s2 in zip(spheres, spheres[1:]): self.wait() random.shuffle(s2.submobjects) for piece in s2: piece.save_state() s2.space_out_submobjects(1.2) s2.fade(1) for piece in s1: piece.add(VectorizedPoint(piece.get_center() / 2)) self.play( LaggedStartMap(Restore, s2) ) self.remove(s1) self.wait(5) class LimitViewToCrossSection(JustifyLengthStretch): CONFIG = { "d_ambiguity_iterations": 0, } def construct(self): self.setup_shapes() self.add_ghosts() self.add_example_group() self.cut_cross_section() self.label_R() self.label_d() self.move_camera( phi=90 * DEGREES, theta=-90 * DEGREES, ) self.play( FadeOut(self.ghost_sphere), FadeOut(self.ghost_cylinder), ) class JustifyHeightSquish(MovingCameraScene): CONFIG = { # As measured from previous scene "top_phi": 0.5242654422649652, "low_phi": 0.655081802831207, "radius": 2, "R_color": RED, "d_color": WHITE, "little_triangle_color": BLUE, "big_triangle_color": GREY_BROWN, "alpha_color": WHITE, "beta_color": WHITE, } def construct(self): self.recreate_cross_section() self.show_little_triangle() self.show_tangent_to_radius() self.tweak_parameter() self.label_angles() def recreate_cross_section(self): axes = Axes( axis_config={ "unit_size": 2, } ) circle = Circle( radius=self.radius, stroke_color=PINK, stroke_width=2, ) R_line = self.get_R_line(90 * DEGREES) R_line.set_color(self.R_color) R_label = OldTex("R") R_label.next_to(R_line, DOWN, SMALL_BUFF) d_lines = VGroup(*[ self.get_d_line(phi) for phi in [self.low_phi, self.top_phi] ]) d_line = d_lines[0] d_line.set_color(self.d_color) d_label = OldTex("d") d_label.next_to(d_line, DOWN, SMALL_BUFF) proj_lines = VGroup(*[ self.get_R_line(phi) for phi in [self.top_phi, self.low_phi] ]) proj_lines.set_stroke(YELLOW, 1) s_rect_line, c_rect_line = [ Line( *[l.get_end() for l in lines], stroke_color=YELLOW, stroke_width=2, ) for lines in [d_lines, proj_lines] ] mobjects = [ axes, circle, R_line, d_line, R_label, d_label, proj_lines, s_rect_line, c_rect_line, ] self.add(*mobjects) self.set_variables_as_attrs(*mobjects) def show_little_triangle(self): phi = self.low_phi d_phi = abs(self.low_phi - self.top_phi) tri_group = self.get_double_triangle_group(phi, d_phi) lil_tri, big_tri = tri_group frame = self.camera_frame frame.save_state() scale_factor = 0.1 sw_sf = 0.2 # stroke_width scale factor d_sf = 0.3 # d_label scale factor hyp = lil_tri.hyp leg = lil_tri.leg2 leg.rotate(PI) VGroup(hyp, leg).set_stroke(YELLOW, 1) hyp_word = OldTexText("Rectangle height $\\rightarrow$") leg_word = OldTexText("$\\leftarrow$ Projection") words = VGroup(hyp_word, leg_word) words.set_height(0.4 * lil_tri.get_height()) words.set_background_stroke(width=0) hyp_word.next_to(hyp.get_center(), LEFT, buff=0.05) leg_word.next_to(leg, RIGHT, buff=0.02) stroke_width_changers = VGroup() for mob in self.mobjects: if mob in [self.d_label, frame]: continue mob.generate_target() mob.save_state() mob.target.set_stroke( width=sw_sf * mob.get_stroke_width() ) stroke_width_changers.add(mob) self.play( frame.scale, scale_factor, frame.move_to, lil_tri, self.d_label.scale, d_sf, {"about_edge": UP}, *map(MoveToTarget, stroke_width_changers) ) self.play(DrawBorderThenFill(lil_tri, stroke_width=0.5)) self.wait() self.play( ShowCreation(hyp), LaggedStartMap( DrawBorderThenFill, hyp_word, stroke_width=0.5, run_time=1, ), ) self.wait() self.play(TransformFromCopy(hyp, leg)) self.play(TransformFromCopy( hyp_word, leg_word, path_arc=-PI / 2, )) self.wait() self.play( frame.restore, self.d_label.scale, 1 / d_sf, {"about_edge": UP}, *map(Restore, stroke_width_changers), run_time=3 ) self.set_variables_as_attrs( hyp_word, leg_word, tri_group ) def show_tangent_to_radius(self): tri_group = self.tri_group lil_tri, big_tri = tri_group lil_hyp = lil_tri.hyp phi = self.low_phi circle_point = self.get_circle_point(phi) tangent = lil_hyp.copy() tangent.set_stroke(WHITE, 2) tangent.scale(5 / tangent.get_length()) tangent.move_to(circle_point) R_line = self.R_line R_label = self.R_label d_label = self.d_label elbow = Elbow(angle=(-phi - PI / 2), width=0.15) elbow.shift(circle_point) elbow.set_stroke(WHITE, 1) self.tangent_elbow = elbow self.play(GrowFromPoint(tangent, circle_point)) self.wait() self.play( Rotate( R_line, 90 * DEGREES - phi, about_point=ORIGIN, ), R_label.next_to, 0.5 * circle_point, DR, {"buff": 0}, d_label.shift, SMALL_BUFF * UL, ) self.play(ShowCreation(elbow)) self.wait() self.add(big_tri, d_label, R_line, elbow) d_label.set_background_stroke(width=0) self.play(DrawBorderThenFill(big_tri)) self.wait() self.set_variables_as_attrs(tangent, elbow) def tweak_parameter(self): tri_group = self.tri_group lil_tri = tri_group[0] d_label = self.d_label d_line = self.d_line R_label = self.R_label R_line = self.R_line frame = self.camera_frame to_fade = VGroup( self.proj_lines, self.s_rect_line, self.c_rect_line, self.hyp_word, self.leg_word, lil_tri.hyp, lil_tri.leg2, ) rad_tangent = VGroup( R_line, self.tangent, self.elbow, ) phi_tracker = ValueTracker(self.low_phi) self.play( frame.scale, 0.6, frame.shift, UR, R_label.scale, 0.6, {"about_edge": UL}, d_label.scale, 0.6, {"about_point": d_label.get_top() + SMALL_BUFF * DOWN}, *map(FadeOut, to_fade), ) curr_phi = self.low_phi d_phi = abs(self.top_phi - self.low_phi) alt_phis = [ 80 * DEGREES, 20 * DEGREES, 50 * DEGREES, curr_phi ] for new_phi in alt_phis: self.add(tri_group, d_label) self.play( phi_tracker.set_value, new_phi, UpdateFromFunc( tri_group, lambda tg: tg.become( self.get_double_triangle_group( phi_tracker.get_value(), d_phi ) ) ), Rotate( rad_tangent, -(new_phi - curr_phi), about_point=ORIGIN, ), MaintainPositionRelativeTo(R_label, R_line), UpdateFromFunc( d_line, lambda dl: dl.become( self.get_d_line(phi_tracker.get_value()) ), ), MaintainPositionRelativeTo(d_label, d_line), run_time=2 ) self.wait() curr_phi = new_phi for tri in tri_group: self.play(Indicate(tri)) self.wait() self.play(*map(FadeIn, to_fade)) self.remove(phi_tracker) def label_angles(self): # Getting pretty hacky here... tri_group = self.tri_group lil_tri, big_tri = tri_group d_label = self.d_label R_label = self.R_label frame = self.camera_frame alpha = self.low_phi beta = 90 * DEGREES - alpha circle_point = self.get_circle_point(alpha) alpha_arc = Arc( start_angle=90 * DEGREES, angle=-alpha, radius=0.2, stroke_width=2, ) beta_arc = Arc( start_angle=PI, angle=beta, radius=0.2, stroke_width=2, ) beta_arc.shift(circle_point) alpha_label = OldTex("\\alpha") alpha_label.scale(0.5) alpha_label.set_color(self.alpha_color) alpha_label.next_to(alpha_arc, UP, buff=SMALL_BUFF) alpha_label.shift(0.05 * DR) beta_label = OldTex("\\beta") beta_label.scale(0.5) beta_label.set_color(self.beta_color) beta_label.next_to(beta_arc, LEFT, buff=SMALL_BUFF) beta_label.shift(0.07 * DR) VGroup(alpha_label, beta_label).set_background_stroke(width=0) elbow = Elbow(width=0.15, angle=-90 * DEGREES) elbow.shift(big_tri.get_corner(UL)) elbow.set_stroke(width=2) equation = OldTex( "\\alpha", "+", "\\beta", "+", "90^\\circ", "=", "180^\\circ" ) equation.scale(0.6) equation.next_to(frame.get_corner(UR), DL) movers = VGroup( alpha_label.deepcopy(), beta_label.deepcopy(), elbow.copy() ) indices = [0, 2, 4] for mover, index in zip(movers, indices): mover.target = VGroup(equation[index]) # Show equation self.play( FadeOut(d_label), FadeOut(R_label), ShowCreation(alpha_arc), ShowCreation(beta_arc), ) self.wait() self.play(FadeIn(alpha_label, UP)) self.wait() self.play(FadeIn(beta_label, LEFT)) self.wait() self.play(ShowCreation(elbow)) self.wait() self.play( LaggedStartMap(MoveToTarget, movers), LaggedStartMap(FadeInFromDown, equation[1:4:2]) ) self.wait() self.play(FadeIn(equation[-2:], LEFT)) self.remove(equation, movers) self.add(equation) self.wait() # Zoom in self.remove(self.tangent_elbow) stroke_width_changers = VGroup(*[ mob for mob in self.mobjects if mob not in [ beta_arc, beta_label, frame, equation, ] ]) for mob in stroke_width_changers: mob.generate_target() mob.save_state() mob.target.set_stroke( width=0.3 * mob.get_stroke_width() ) equation.set_background_stroke(width=0) scaled_arcs = VGroup(beta_arc, self.tangent_elbow) beta_label.set_background_stroke(color=BLACK, width=0.3) self.play( ApplyMethod( VGroup(frame, equation).scale, 0.15, {"about_point": circle_point + 0.1 * LEFT}, ), ApplyMethod( beta_label.scale, 0.3, {"about_point": circle_point}, ), scaled_arcs.set_stroke, {"width": 0.3}, scaled_arcs.scale, 0.3, {"about_point": circle_point}, *map(MoveToTarget, stroke_width_changers) ) # Show small triangle angles Tex.CONFIG["background_stroke_width"] = 0 words = VGroup(self.hyp_word, self.leg_word) alpha_arc1 = Arc( start_angle=90 * DEGREES + beta, angle=0.95 * alpha, radius=0.3 * 0.2, stroke_width=beta_arc.get_stroke_width(), ).shift(circle_point) alpha_arc2 = Arc( start_angle=0, angle=-0.95 * alpha, radius=0.3 * 0.2, stroke_width=beta_arc.get_stroke_width(), ).shift(lil_tri.hyp.get_end()) beta_arc1 = Arc( start_angle=90 * DEGREES, angle=beta, radius=0.3 * 0.2, stroke_width=beta_arc.get_stroke_width(), ).shift(circle_point) deg90 = OldTex("90^\\circ") deg90.set_height(0.8 * beta_label.get_height()) deg90.next_to(self.tangent_elbow, DOWN, buff=0.025) # deg90.set_background_stroke(width=0) q_mark = OldTex("?") q_mark.set_height(0.5 * beta_label.get_height()) q_mark.next_to(alpha_arc1, LEFT, buff=0.025) q_mark.shift(0.01 * UP) alpha_label1 = OldTex("\\alpha") alpha_label1.set_height(0.7 * q_mark.get_height()) alpha_label1.move_to(q_mark) alpha_label2 = alpha_label1.copy() alpha_label2.next_to( alpha_arc2, RIGHT, buff=0.01 ) alpha_label2.set_background_stroke(color=BLACK, width=0.3) beta_label1 = beta_label.copy() beta_label1.scale(0.7) beta_label1.set_background_stroke(color=BLACK, width=0.3) beta_label1.next_to( beta_arc1, UP, buff=0.01 ) beta_label1.shift(0.01 * LEFT) self.play(FadeOut(words)) self.play(FadeIn(deg90, 0.1 * UP)) self.wait(0.25) self.play(WiggleOutThenIn(beta_label)) self.wait(0.25) self.play( ShowCreation(alpha_arc1), FadeIn(q_mark, 0.1 * RIGHT) ) self.wait() self.play(ShowPassingFlash( self.tangent.copy().scale(0.1).set_stroke(PINK, 0.5) )) self.wait() self.play(ReplacementTransform(q_mark, alpha_label1)) self.play(ShowCreationThenFadeAround( equation, surrounding_rectangle_config={ "buff": 0.015, "stroke_width": 0.5, }, )) self.wait() self.play( ShowCreation(alpha_arc2), FadeIn(alpha_label2), ) self.play( ShowCreation(beta_arc1), FadeIn(beta_label1), ) self.wait() # def get_double_triangle_group(self, phi, d_phi): p0 = self.get_circle_point(phi) p1 = self.get_circle_point(phi - d_phi) p2 = np.array(p1) p2[0] = p0[0] little_triangle = Polygon( p0, p1, p2, stroke_width=0, fill_color=self.little_triangle_color, fill_opacity=1, ) big_triangle = Polygon( p0, ORIGIN, p0 - p0[0] * RIGHT, stroke_width=0, fill_color=self.big_triangle_color, fill_opacity=1 ) result = VGroup(little_triangle, big_triangle) for tri in result: p0, p1, p2 = tri.get_anchors()[:3] tri.hyp = Line(p0, p1) tri.leg1 = Line(p1, p2) tri.leg2 = Line(p2, p0) tri.side_lines = VGroup( tri.hyp, tri.leg1, tri.leg2 ) tri.side_lines.set_stroke(WHITE, 1) result.set_stroke(width=0) return result def get_R_line(self, phi): y = self.radius * np.cos(phi) x = self.radius return Line(ORIGIN, x * RIGHT).shift(y * UP) def get_d_line(self, phi): end = self.get_circle_point(phi) start = np.array(end) start[0] = 0 return Line(start, end) def get_circle_point(self, phi): return rotate_vector(self.radius * UP, -phi) class ProTipTangentRadii(ProTipNameThings): CONFIG = { "tip_descriptor": "Pro tip:", "tip": "A circle's tangent is perpendicular to its radius", } class ProTipTweakParameters(ProTipNameThings): CONFIG = { "tip_descriptor": "Pro tip:", "tip": "Tweak parameters $\\rightarrow$ make", } class DrawSquareThenFade(Scene): def construct(self): square = Square(color=YELLOW, stroke_width=5) self.play(ShowCreation(square)) self.play(FadeOut(square)) class WhyAreWeDoingThis(TeacherStudentsScene): def construct(self): self.student_says( "Hang on, what \\\\ are we doing?", index=2, bubble_config={"direction": LEFT}, target_mode="hesitant" ) self.play_student_changes( "maybe", "pondering", "hesitant", added_anims=[self.teacher.change, "tease"] ) self.wait(3) self.play( RemovePiCreatureBubble(self.students[2]), self.teacher.change, "raise_right_hand", self.play_student_changes(*2 * ["pondering"]) ) self.look_at(self.screen) self.wait(2) class SameEffectAsRotating(Scene): CONFIG = { "rectangle_config": { "height": 2, "width": 1, "stroke_width": 0, "fill_color": YELLOW, "fill_opacity": 1, "background_stroke_width": 2, "background_stroke_color": BLACK, }, "x_stretch": 2, "y_stretch": 0.5, } def construct(self): rect1 = Rectangle(**self.rectangle_config) rect2 = rect1.copy() rect2.stretch(self.x_stretch, 0) rect2.stretch(self.y_stretch, 1) rotated_rect1 = rect1.copy() rotated_rect1.rotate(-90 * DEGREES) arrow = Arrow(ORIGIN, RIGHT, buff=0, color=WHITE) group = VGroup(rect1, arrow, rect2) group.arrange(RIGHT) group.center() moving_rect = rect1.copy() low_brace = always_redraw( lambda: Brace( moving_rect, DOWN, buff=SMALL_BUFF, min_num_quads=2, ) ) right_brace = always_redraw( lambda: Brace( moving_rect, RIGHT, buff=SMALL_BUFF, min_num_quads=2, ) ) times_R_over_d = OldTex("\\times \\frac{R}{d}") times_d_over_R = OldTex("\\times \\frac{d}{R}") times_R_over_d.add_updater( lambda m: m.next_to(low_brace, DOWN, SMALL_BUFF) ) times_d_over_R.add_updater( lambda m: m.next_to(right_brace, RIGHT, SMALL_BUFF) ) self.add(rect1, arrow) self.play(moving_rect.move_to, rect2) self.add(low_brace) self.play( moving_rect.match_width, rect2, {"stretch": True}, FadeIn(times_R_over_d), ) self.add(right_brace) self.play( moving_rect.match_height, rect2, {"stretch": True}, FadeIn(times_d_over_R), ) self.wait() rotated_rect1.move_to(moving_rect) self.play(TransformFromCopy( rect1, rotated_rect1, path_arc=-90 * DEGREES, run_time=2 )) class NotSameEffectAsRotating(SameEffectAsRotating): CONFIG = { "rectangle_config": { "width": 1.5, "height": 1.5, } } class ShowParameterization(Scene): def construct(self): u_color = PINK v_color = GREEN tex_kwargs = { "tex_to_color_map": { "u": u_color, "v": v_color, } } vector = Matrix( [ ["\\text{cos}(u)\\text{sin}(v)"], ["\\text{sin}(u)\\text{sin}(v)"], ["\\text{cos}(v)"] ], element_to_mobject_config=tex_kwargs, element_alignment_corner=DOWN, ) vector.to_edge(UP) ranges = VGroup( OldTex("0 \\le u \\le 2\\pi", **tex_kwargs), OldTex("0 \\le v \\le \\pi", **tex_kwargs), OldTexText( "Sample $u$ and $v$ with \\\\ the same density", tex_to_color_map={ "$u$": u_color, "$v$": v_color, } ) ) ranges.arrange(DOWN) ranges.next_to(vector, DOWN) self.add(vector) self.add(ranges) class RdLabels(Scene): def construct(self): rect = Rectangle(height=1, width=0.5) cR = OldTex("cR") cR.next_to(rect, LEFT, SMALL_BUFF) cd = OldTex("cd") cd.next_to(rect, DOWN, SMALL_BUFF) labels = VGroup(cd, cR) for label in labels: label[1].set_color(BLUE) self.play(FadeInFromDown(label)) class RotateAllPiecesWithExpansion(ShowProjection): CONFIG = { "sphere_config": { "radius": 1.5, }, "with_expansion": True } def construct(self): self.setup_shapes() self.rotate_all_pieces() def rotate_all_pieces(self): sphere = self.sphere cylinder = self.cylinder ghost_sphere = self.ghost_sphere ghost_sphere.scale(0.99) # Shuffle sphere and cylinder same way random.seed(0) random.shuffle(sphere.submobjects) random.seed(0) random.shuffle(cylinder.submobjects) sphere_target = VGroup() for piece in sphere: p0, p1, p2, p3 = piece.get_anchors()[:4] piece.set_points_as_corners([ p3, p0, p1, p2, p3 ]) piece.generate_target() sphere_target.add(piece.target) piece.target.move_to( (1 + random.random()) * piece.get_center() ) self.add(ghost_sphere, sphere) self.wait() if self.with_expansion: self.play(LaggedStartMap( MoveToTarget, sphere )) self.wait() self.play(*[ Rotate(piece, 90 * DEGREES, axis=piece.get_center()) for piece in sphere ]) self.wait() self.play(Transform(sphere, cylinder, run_time=2)) self.wait(5) class RotateAllPiecesWithoutExpansion(RotateAllPiecesWithExpansion): CONFIG = { "with_expansion": False, } class ThinkingCritically(PiCreatureScene): def construct(self): randy = self.pi_creature self.play(randy.change, "pondering") self.wait() self.play( randy.change, "hesitant", 2 * UP, ) self.wait() self.play(randy.change, "sassy") self.wait() self.play(randy.change, "angry") self.wait(4) class WriteNotEquals(Scene): def construct(self): symbol = OldTex("\\ne") symbol.scale(2) symbol.set_background_stroke(width=0) self.play(Write(symbol)) self.wait() class RectangulatedSphere(SphereCylinderScene): CONFIG = { "sphere_config": { "resolution": (10, 20) }, "uniform_color": False, "wait_time": 10, } def construct(self): sphere = self.get_sphere() if self.uniform_color: sphere.set_stroke(BLUE_E, width=0.5) sphere.set_fill(BLUE_E) self.set_camera_to_default_position() self.begin_ambient_camera_rotation(0.05) self.add(sphere) self.wait(self.wait_time) class SmoothSphere(RectangulatedSphere): CONFIG = { "sphere_config": { "resolution": (200, 400), }, "uniform_color": True, "wait_time": 0, } class SequenceOfSpheres(SphereCylinderScene): def construct(self): n_shapes = 4 spheres, cylinders = groups = VGroup(*[ VGroup(*[ func(resolution=(n, 2 * n)) for k in range(1, n_shapes + 1) for n in [3 * (2**k)] ]) for func in [self.get_sphere, self.get_cylinder] ]) groups.scale(0.5) for group in groups: for shape in group: for piece in shape: piece.make_jagged() shape.set_stroke(width=0) for group in groups: group.add(self.get_oriented_tex("?").scale(2)) group.arrange(RIGHT, buff=LARGE_BUFF) groups.arrange(IN, buff=1.5) all_equals = VGroup() for sphere, cylinder in zip(spheres, cylinders): equals = self.get_oriented_tex("=") equals.scale(1.5) equals.rotate(90 * DEGREES, UP) equals.move_to(interpolate( sphere.get_nadir(), cylinder.get_zenith(), 0.5 )) all_equals.add(equals) all_equals.remove(all_equals[-1]) arrow_groups = VGroup() for group in groups: arrow_group = VGroup() for m1, m2 in zip(group, group[1:]): arrow = self.get_oriented_tex("\\rightarrow") arrow.move_to(interpolate( m1.get_right(), m2.get_left(), 0.5 )) arrow_group.add(arrow) arrow_groups.add(arrow_group) q_marks = VGroup(*[ group[-1] for group in groups ]) final_arrows = VGroup( arrow_groups[0][-1], arrow_groups[1][-1], ) for arrow in final_arrows: dots = self.get_oriented_tex("\\dots") dots.next_to(arrow, RIGHT, SMALL_BUFF) arrow.add(dots) q_marks.shift(MED_LARGE_BUFF * RIGHT) tilted_final_arrows = VGroup( final_arrows[0].copy().rotate( -45 * DEGREES, axis=DOWN ).shift(0.75 * IN), final_arrows[1].copy().rotate( 45 * DEGREES, axis=DOWN ).shift(0.75 * OUT), ) final_q_mark = q_marks[0].copy() final_q_mark.move_to(q_marks) self.set_camera_orientation( phi=80 * DEGREES, theta=-90 * DEGREES, ) for i in range(n_shapes): anims = [ FadeIn(spheres[i], LEFT), FadeIn(cylinders[i], LEFT), ] if i > 0: anims += [ Write(arrow_group[i - 1]) for arrow_group in arrow_groups ] self.play(*anims, run_time=1) self.play(GrowFromCenter(all_equals[i])) self.play( FadeIn(q_marks, LEFT), Write(final_arrows) ) self.wait() self.play( Transform(final_arrows, tilted_final_arrows), Transform(q_marks, VGroup(final_q_mark)), ) self.wait() def get_oriented_tex(self, tex): result = OldTex(tex) result.rotate(90 * DEGREES, RIGHT) return result class WhatIsSurfaceArea(SpecialThreeDScene): CONFIG = { "change_power": True, } def construct(self): title = OldTexText("What is surface area?") title.scale(1.5) title.to_edge(UP) title.shift(0.035 * RIGHT) self.add_fixed_in_frame_mobjects(title) power_tracker = ValueTracker(1) surface = always_redraw( lambda: self.get_surface( radius=3, amplitude=1, power=power_tracker.get_value() ) ) pieces = surface.copy() pieces.clear_updaters() random.shuffle(pieces.submobjects) self.set_camera_to_default_position() self.begin_ambient_camera_rotation() # self.add(self.get_axes()) self.play(LaggedStartMap( DrawBorderThenFill, pieces, lag_ratio=0.2, )) self.remove(pieces) self.add(surface) if self.change_power: self.play( power_tracker.set_value, 5, run_time=2 ) self.play( power_tracker.set_value, 1, run_time=2 ) self.wait(2) def get_surface(self, radius, amplitude, power): def alt_pow(x, y): return np.sign(x) * (np.abs(x) ** y) return ParametricSurface( lambda u, v: radius * np.array([ v * np.cos(TAU * u), v * np.sin(TAU * u), 0, ]) + amplitude * np.array([ 0, 0, (v**2) * alt_pow(np.sin(5 * TAU * u), power), ]), resolution=(100, 20), v_min=0.01 ) class AltWhatIsSurfaceArea(WhatIsSurfaceArea): CONFIG = { "change_power": False, } def get_surface(self, radius, amplitude, power): return ParametricSurface( lambda u, v: radius * (1 - 0.8 * (v**2) ** power) * np.array([ np.cos(TAU * u) * (1 + 0.5 * v * np.sin(5 * TAU * u)), np.sin(TAU * u) * (1 + 0.5 * v * np.sin(5 * TAU * u)), v, ]), v_min=-1, v_max=1, resolution=(100, 25), ) class EoCWrapper(Scene): def construct(self): title = OldTexText("Essence of calculus") 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 RoleOfCalculus(SpecialThreeDScene): CONFIG = { "camera_config": { "light_source_start_point": [-4, 5, 7], } } def construct(self): calc = OldTex("\\int", "\\int") calc.space_out_submobjects(0.4) calc.scale(2) arrow = Vector(2 * RIGHT, color=WHITE) sphere = self.get_sphere() sphere.rotate(70 * DEGREES, axis=LEFT) group = VGroup(calc, arrow, sphere) group.arrange(RIGHT) group.shift(0.5 * RIGHT) cross = Cross(group[:2], stroke_width=10) # arrow2 = arrow.copy() self.add(calc, arrow) self.play(Write(sphere)) self.wait() self.play(ShowCreation(cross)) self.wait() self.play( sphere.next_to, ORIGIN, LEFT, 1.0, arrow.move_to, ORIGIN, LEFT, calc.next_to, ORIGIN, RIGHT, 2.25, FadeOut(cross), path_arc=PI, run_time=2, ) self.wait() class UnwrappedCircleLogic(UnfoldCircles): CONFIG = { "radius": 1.25, "dr": 0.01, } def construct(self): radius = self.radius dr = self.dr Tex.CONFIG["background_stroke_width"] = 2 unwrap_factor_tracker = ValueTracker(0) center_tracker = VectorizedPoint() highligt_prop_tracker = ValueTracker(0.5) def get_highlight_prop(): return highligt_prop_tracker.get_value() def get_r(): return radius * get_highlight_prop() center_tracker.move_to(4.5 * LEFT) def get_unwrapped_circle(): result = self.get_unwrapped_circle( radius=radius, dr=dr, unwrap_factor=unwrap_factor_tracker.get_value(), center=center_tracker.get_center() ) self.get_submob_from_prop( result, get_highlight_prop() ).set_stroke(YELLOW, 2) return result unwrapped_circle = always_redraw(get_unwrapped_circle) circle = unwrapped_circle.copy() circle.clear_updaters() R_line = Line(circle.get_center(), circle.get_bottom()) R_line.set_stroke(WHITE, 2) R_label = OldTex("R") R_label.next_to(R_line, LEFT) circle_group = VGroup(circle, R_line, R_label) tri_R_line = always_redraw( lambda: Line( ORIGIN, radius * DOWN ).shift(center_tracker.get_center()) ) # Unwrap self.play(FadeInFromDown(circle_group)) self.add(circle_group, unwrapped_circle, tri_R_line, R_label) circle_group.set_stroke(opacity=0.5) self.play( unwrap_factor_tracker.set_value, 1, run_time=2 ) self.play( center_tracker.move_to, circle.get_right() + (radius + MED_SMALL_BUFF) * RIGHT, circle_group.set_stroke, {"opacity": 1}, ) self.wait() # Change radius r_line = always_redraw( lambda: Line( ORIGIN, get_r() * DOWN, stroke_width=2, stroke_color=WHITE, ).shift(circle.get_center()) ) r_label = OldTex("r") r_label.add_updater( lambda m: m.next_to(r_line, LEFT, SMALL_BUFF) ) two_pi_r_label = OldTex("2\\pi r") two_pi_r_label.add_updater( lambda m: m.next_to( self.get_submob_from_prop( unwrapped_circle, get_highlight_prop(), ), DOWN, SMALL_BUFF ) ) circle.add_updater( lambda m: m.match_style(unwrapped_circle) ) self.play( ReplacementTransform(R_line, r_line), ReplacementTransform(R_label, r_label), FadeInFromDown( two_pi_r_label.copy().clear_updaters(), remover=True ) ) self.add(two_pi_r_label) for prop in [0.2, 0.8, 0.5]: self.play( highligt_prop_tracker.set_value, prop, run_time=2 ) # Show line line = Line(*[ unwrapped_circle.get_corner(vect) for vect in (UL, DR) ]) line.set_color(PINK) line.set_fill(BLACK, 1) line_word = OldTexText("Line") line_word.next_to(ORIGIN, UP, SMALL_BUFF) line_word.rotate(line.get_angle(), about_point=ORIGIN) line_word.shift(line.get_center()) curve = line.copy() curve.get_points()[1] = unwrapped_circle.get_corner(DL) not_line = OldTexText("Not line") not_line.rotate(line.get_angle() / 2) not_line.move_to(line_word) not_line.shift(0.3 * DOWN) self.play( ShowCreation(line), Write(line_word), ) self.wait() self.play(highligt_prop_tracker.set_value, 1) self.wait() # Bend line.save_state() line_word.save_state() self.play( Transform(line, curve), Transform(line_word, not_line), ) self.wait() self.play( Restore(line), Restore(line_word), # FadeIn(two_pi_r_label), ) self.wait() def get_submob_from_prop(self, mob, prop): n = len(mob.submobjects) return mob[min(int(prop * n), n - 1)] class AskAboutDirectConnection(TeacherStudentsScene, SpecialThreeDScene): CONFIG = { "camera_config": { "light_source_start_point": [-4, 5, 7], } } def construct(self): sphere = Sphere() cylinder = Cylinder() for mob in sphere, cylinder: mob.rotate(70 * DEGREES, LEFT) formula = OldTex("4\\pi R^2") formula.set_color(BLUE) circle = Circle() circle.set_stroke(width=0) circle.set_fill(GREY_BROWN, 1) area_label = OldTex("\\pi R^2", background_stroke_width=0) area_label.scale(1.5) circle.add(area_label) group = VGroup( sphere, cylinder, formula, circle ) for mob in group: mob.set_height(1.5) formula.scale(0.5) group.arrange(RIGHT, buff=1.5) group.to_edge(UP, buff=2) group[1:3].to_edge(UP) arrows = VGroup() for m1, m2 in zip(group, group[1:]): arrow = Arrow( m1.get_center(), m2.get_center(), buff=1, color=WHITE ) arrows.add(arrow) direct_arrow = Arrow( sphere, circle, color=WHITE ) q_marks = OldTex(*"???") q_marks.space_out_submobjects(1.5) q_marks.scale(1.5) q_marks.next_to(direct_arrow, DOWN) self.play( self.teacher.change, "raise_right_hand", self.change_students( *3 * ["pondering"], look_at=group, ), LaggedStartMap(FadeInFromDown, group), LaggedStartMap(GrowArrow, arrows) ) self.wait() self.play( self.teacher.change, "pondering", self.students[2].change, "raise_right_hand", GrowArrow(direct_arrow), LaggedStartMap( FadeInFrom, q_marks, lambda m: (m, UP), lag_ratio=0.8, run_time=1.5, ) ) self.play_student_changes( "erm", "sassy", "raise_right_hand", ) self.wait(2) self.look_at(group) self.wait(2) class ExercisesGiveLearning(MovingCameraScene): def construct(self): bulb = Lightbulb() arrow1 = Arrow(ORIGIN, RIGHT, buff=0) lectures = OldTexText("Lectures") exercises = OldTexText("Exercises") frame = self.camera_frame frame.scale(0.7) bulb.next_to(arrow1, RIGHT) for word in lectures, exercises: word.next_to(arrow1, LEFT) cross = Cross(lectures) # Knock down lectures self.add(lectures) self.play(GrowArrow(arrow1)) self.play(LaggedStartMap(DrawBorderThenFill, bulb)) self.play(ShowCreation(cross)) self.play( VGroup(lectures, cross).shift, DOWN, FadeIn(exercises, UP) ) self.wait() # Show self arrow2 = arrow1.copy() arrow2.next_to(lectures, LEFT) logo = Logo() logo.set_height(1) logo.next_to(arrow2, LEFT) pupil_copy = logo.pupil.copy() self.add(logo, pupil_copy) self.play( frame.shift, 1.5 * LEFT, Write(logo, run_time=1.5) ) self.remove(pupil_copy) self.play( GrowArrow(arrow2), FadeOut(cross) ) self.wait() self.play( VGroup(logo, arrow2).next_to, exercises, LEFT ) self.wait() class NobodyLikesHomework(TeacherStudentsScene): def construct(self): self.play_student_changes( "angry", "pleading", "angry", added_anims=[self.teacher.change, "guilty"] ) self.wait() self.play_all_student_changes( "tired", look_at=8 * RIGHT + 4 * DOWN, added_anims=[self.teacher.change, "tease"] ) self.wait(2) class ChallengeMode(Scene): def construct(self): words = OldTexText("Challenge mode: Predict the proof") words.scale(1.5) words.to_edge(UP) self.play(Write(words)) self.wait() class SecondProof(SpecialThreeDScene): CONFIG = { "sphere_config": { "resolution": (30, 30), }, "n_random_subsets": 12, } def construct(self): self.setup_shapes() self.divide_into_rings() self.show_shadows() self.correspond_to_every_other_ring() self.cut_cross_section() self.show_theta() self.enumerate_rings() self.ask_about_ring_circumference() self.ask_about_shadow_area() self.ask_about_2_to_1_correspondance() self.show_all_shadow_rings() self.ask_about_global_correspondance() def setup_shapes(self): sphere = self.get_sphere() sphere.set_stroke(WHITE, width=0.25) self.add(sphere) self.sphere = sphere u_values, v_values = sphere.get_u_values_and_v_values() rings = VGroup(*[VGroup() for u in u_values]) for piece in sphere: rings[piece.u_index].add(piece.copy()) self.set_ring_colors(rings) self.rings = rings self.axes = self.get_axes() self.add(self.axes) self.set_camera_to_default_position() self.begin_ambient_camera_rotation() def divide_into_rings(self): rings = self.rings self.play(FadeIn(rings), FadeOut(self.sphere)) self.play( rings.space_out_submobjects, 1.5, rate_func=there_and_back_with_pause, run_time=3 ) self.wait(2) rings.save_state() def show_shadows(self): rings = self.rings north_rings = rings[:len(rings) // 2] ghost_rings = rings.copy() ghost_rings.set_fill(opacity=0.0) ghost_rings.set_stroke(WHITE, width=0.5, opacity=0.2) north_rings.submobjects.reverse() shadows = self.get_shadow(north_rings) for piece in shadows.family_members_with_points(): piece.set_stroke( piece.get_fill_color(), width=0.5, ) for shadow in shadows: shadow.save_state() shadows.become(north_rings) self.add(ghost_rings) self.play(FadeOut(rings), Animation(shadows)) self.play(LaggedStartMap(Restore, shadows)) self.wait() self.move_camera(phi=40 * DEGREES) self.wait(3) # Show circle radius = self.sphere_config["radius"] radial_line = Line(ORIGIN, radius * RIGHT) radial_line.set_stroke(RED) R_label = OldTex("R") R_label.set_background_stroke(width=1) R_label.next_to(radial_line, DOWN) self.play( FadeInFromDown(R_label), ShowCreation(radial_line) ) self.play(Rotating( radial_line, angle=TAU, about_point=ORIGIN, rate_func=smooth, run_time=3, )) self.wait() self.set_variables_as_attrs( shadows, ghost_rings, radial_line, R_label ) def correspond_to_every_other_ring(self): rings = self.rings shadows = self.shadows shadows.submobjects.reverse() rings.restore() self.set_ring_colors(rings) every_other_ring = rings[1::2] self.move_camera( phi=70 * DEGREES, theta=-135 * DEGREES, added_anims=[ FadeOut(self.R_label), FadeOut(self.radial_line), ], run_time=2, ) shadows_copy = shadows.copy() shadows.fade(1) self.play( ReplacementTransform( shadows_copy, every_other_ring ), FadeOut(self.ghost_rings), run_time=2, ) self.wait(5) self.every_other_ring = every_other_ring def cut_cross_section(self): shadows = self.shadows every_other_ring = self.every_other_ring rings = self.rings back_half = self.get_hemisphere(rings, UP) front_half = self.get_hemisphere(rings, DOWN) front_half_ghost = front_half.copy() front_half_ghost.set_fill(opacity=0.2) front_half_ghost.set_stroke(opacity=0) # shaded_back_half = back_half.copy() # for piece in shaded_back_half.family_members_with_points(): # piece.set_points(piece.get_points()[::-1]) # shaded_back_half.scale(0.999) # shaded_back_half.set_fill(opacity=0.5) radius = self.sphere_config["radius"] circle = Circle(radius=radius) circle.set_stroke(PINK, 2) circle.rotate(90 * DEGREES, RIGHT) every_other_ring_copy = every_other_ring.copy() self.add(every_other_ring_copy) self.remove(every_other_ring) rings.set_fill(opacity=0.8) rings.set_stroke(opacity=0.6) self.play( FadeIn(back_half), FadeIn(front_half_ghost), FadeIn(circle), FadeOut(shadows), FadeOut(every_other_ring_copy), ) self.wait() self.set_variables_as_attrs( back_half, front_half, front_half_ghost, slice_circle=circle ) def show_theta(self): theta_tracker = ValueTracker(0) get_theta = theta_tracker.get_value theta_group = always_redraw( lambda: self.get_theta_group(get_theta()) ) theta_mob_opacity_tracker = ValueTracker(0) get_theta_mob_opacity = theta_mob_opacity_tracker.get_value theta_mob = theta_group[-1] theta_mob.add_updater( lambda m: m.set_fill(opacity=get_theta_mob_opacity()) ) theta_mob.add_updater( lambda m: m.set_background_stroke( width=get_theta_mob_opacity() ) ) lit_ring = always_redraw( lambda: self.get_ring_from_theta( self.rings, get_theta() ).copy().set_color(YELLOW) ) self.stop_ambient_camera_rotation() self.move_camera(theta=-60 * DEGREES) self.add(theta_group, lit_ring) n_rings = len(self.rings) - 1 lit_ring_index = int((30 / 180) * n_rings) angle = PI * lit_ring_index / n_rings for alpha in [angle, 0, PI, angle]: self.play( theta_tracker.set_value, alpha, theta_mob_opacity_tracker.set_value, 1, Animation(self.camera.phi_tracker), run_time=2, ) self.wait() # Label d-theta radius = self.sphere_config["radius"] d_theta = PI / len(self.rings) alt_theta = get_theta() + d_theta alt_theta_group = self.get_theta_group(alt_theta) alt_R_line = alt_theta_group[1] # d_theta_arc = Arc( # start_angle=get_theta(), # angle=d_theta, # radius=theta_group[0].radius, # stroke_color=PINK, # stroke_width=3, # ) # d_theta_arc.rotate(90 * DEGREES, axis=RIGHT, about_point=ORIGIN) brace = Brace(Line(ORIGIN, radius * d_theta * RIGHT), UP) brace.rotate(90 * DEGREES, RIGHT) brace.next_to(self.sphere, OUT, buff=0) brace.add_to_back(brace.copy().set_stroke(BLACK, 3)) brace.rotate( get_theta() + d_theta / 2, axis=UP, about_point=ORIGIN, ) brace_label = OldTex("R\\,d\\theta") brace_label.rotate(90 * DEGREES, RIGHT) brace_label.next_to(brace, OUT + RIGHT, buff=0) radial_line = self.radial_line R_label = self.R_label R_label.rotate(90 * DEGREES, RIGHT) R_label.next_to(radial_line, IN, SMALL_BUFF) self.play( TransformFromCopy(theta_group[1], alt_R_line), GrowFromCenter(brace), Animation(self.camera.phi_tracker), ) self.wait() self.move_camera( phi=90 * DEGREES, theta=-90 * DEGREES, ) self.wait() self.play( FadeIn(brace_label, IN), ) self.play( ShowCreation(radial_line), FadeIn(R_label), ) self.wait() self.move_camera( phi=70 * DEGREES, theta=-70 * DEGREES, ) self.wait(3) self.set_variables_as_attrs( theta_tracker, lit_ring, theta_group, brace, brace_label, d_theta, alt_R_line, theta_mob_opacity_tracker, ) def enumerate_rings(self): pass # Skip, for now... def ask_about_ring_circumference(self): theta = self.theta_tracker.get_value() radius = self.sphere_config["radius"] circle = Circle( radius=radius * np.sin(theta) ) circle.shift(radius * np.cos(theta) * OUT) circle.set_stroke(Color("red"), 5) to_fade = VGroup( self.R_label, self.radial_line, self.brace, self.brace_label ) self.move_camera( phi=0 * DEGREES, theta=-90 * DEGREES, added_anims=[FadeOut(to_fade)] ) self.play(ShowCreation(circle)) self.wait() self.move_camera( phi=70 * DEGREES, theta=-70 * DEGREES, added_anims=[ FadeIn(to_fade), FadeOut(circle), ] ) self.wait() def ask_about_shadow_area(self): lit_ring = self.lit_ring lit_ring_copy = lit_ring.copy() lit_ring_copy.clear_updaters() all_shadows = self.shadows all_shadows.set_fill(BLUE_E, 0.5) for piece in all_shadows.family_members_with_points(): piece.set_stroke(width=0) radius = self.sphere_config["radius"] shadow = self.get_shadow(lit_ring) theta = self.theta_tracker.get_value() d_theta = self.d_theta def get_dashed_line(angle): p0 = np.cos(angle) * OUT + np.sin(angle) * RIGHT p0 *= radius p1 = np.array([*p0[:2], 0]) result = DashedLine(p0, p1) result.set_stroke(WHITE, 1) result.add_to_back( result.copy().set_stroke(BLACK, 2) ) result.set_shade_in_3d(True) return result dashed_lines = VGroup(*[ get_dashed_line(t) for t in [theta, theta + d_theta] ]) self.play( ReplacementTransform(lit_ring_copy, shadow), FadeOut(self.R_label), FadeOut(self.radial_line), Animation(self.camera.phi_tracker), *map(ShowCreation, dashed_lines), run_time=2, ) self.wait(2) self.set_variables_as_attrs( dashed_lines, lit_shadow=shadow, ) def ask_about_2_to_1_correspondance(self): theta_tracker = ValueTracker(0) get_theta = theta_tracker.get_value new_lit_ring = always_redraw( lambda: self.get_ring_from_theta( self.rings, get_theta() ).copy().set_color(PINK) ) self.add(new_lit_ring) for angle in [PI, 0, PI]: self.play( theta_tracker.set_value, angle, Animation(self.camera.phi_tracker), run_time=3 ) self.remove(new_lit_ring) self.remove(theta_tracker) def show_all_shadow_rings(self): lit_ring_copy = self.lit_ring.copy() lit_ring_copy.clear_updaters() self.remove(self.lit_ring) theta_group_copy = self.theta_group.copy() theta_group_copy.clear_updaters() self.remove(self.theta_group, *self.theta_group) to_fade = VGroup( theta_group_copy, self.alt_R_line, self.brace, self.brace_label, lit_ring_copy, self.lit_shadow, self.slice_circle, self.dashed_lines, ) R_label = self.R_label radial_line = self.radial_line R_label.rotate( -90 * DEGREES, axis=RIGHT, about_point=radial_line.get_center() ) shadows = self.shadows self.set_ring_colors(shadows, [GREY_BROWN, GREY_D]) for submob in shadows: submob.save_state() shadows.become(self.rings.saved_state[:len(shadows)]) self.play( FadeOut(to_fade), LaggedStartMap(FadeIn, shadows), self.theta_mob_opacity_tracker.set_value, 0, ) self.play( LaggedStartMap(Restore, shadows), ApplyMethod( self.camera.phi_tracker.set_value, 60 * DEGREES, ), ApplyMethod( self.camera.theta_tracker.set_value, -130 * DEGREES, ), run_time=3 ) self.play( ShowCreation(radial_line), FadeIn(R_label), Animation(self.camera.phi_tracker), ) self.begin_ambient_camera_rotation() self.wait() rings = self.rings rings_copy = rings.saved_state.copy() self.set_ring_colors(rings_copy) self.play( FadeOut(R_label), FadeOut(radial_line), FadeIn(rings_copy) ) self.remove(rings_copy) rings.become(rings_copy) self.add(rings) def ask_about_global_correspondance(self): rings = self.rings self.play( FadeOut(rings[::2]) ) self.wait(8) # def set_ring_colors(self, rings, colors=[BLUE_E, BLUE_D]): for i, ring in enumerate(rings): color = colors[i % len(colors)] ring.set_fill(color, opacity=1) ring.set_stroke(color, width=0.5, opacity=1) for piece in ring: piece.insert_n_curves(4) piece.on_sphere = True piece.set_points([ *piece.get_points()[3:-1], *piece.get_points()[:3], piece.get_points()[3] ]) return rings def get_shadow(self, mobject): result = mobject.copy() result.apply_function( lambda p: np.array([*p[:2], 0]) ) return result def get_hemisphere(self, group, vect): if len(group.submobjects) == 0: if np.dot(group.get_center(), vect) > 0: return group else: return VMobject() else: return VGroup(*[ self.get_hemisphere(submob, vect) for submob in group ]) def get_northern_hemisphere(self, group): return self.get_hemisphere(group, OUT) def get_theta(self, ring): piece = ring[0] point = piece.get_points()[3] return np.arccos(point[2] / get_norm(point)) def get_theta_group(self, theta): arc = Arc( start_angle=90 * DEGREES, angle=-theta, radius=0.5, ) arc.rotate(90 * DEGREES, RIGHT, about_point=ORIGIN) arc.set_stroke(YELLOW, 2) theta_mob = OldTex("\\theta") theta_mob.rotate(90 * DEGREES, RIGHT) vect = np.cos(theta / 2) * OUT + np.sin(theta / 2) * RIGHT theta_mob.move_to( (arc.radius + 0.25) * normalize(vect), ) theta_mob.set_background_stroke(width=1) radius = self.sphere_config["radius"] point = arc.point_from_proportion(1) radial_line = Line( ORIGIN, radius * normalize(point) ) radial_line.set_stroke(WHITE, 2) return VGroup(arc, radial_line, theta_mob) def get_ring_from_theta(self, rings, theta): n_rings = len(rings) index = min(int((theta / PI) * n_rings), n_rings - 1) return rings[index] class SecondProofHigherRes(SecondProof): CONFIG = { "sphere_config": { "resolution": (60, 60), }, } class SecondProofHighestRes(SecondProof): CONFIG = { "sphere_config": { "resolution": (120, 120), }, } class RangeFrom0To180(Scene): def construct(self): angle = Integer(0, unit="^\\circ") angle.scale(2) self.add(angle) self.wait() self.play(ChangeDecimalToValue( angle, 180, run_time=2, )) self.wait() class Question1(Scene): def construct(self): kwargs = { "tex_to_color_map": { "circumference": RED, } } question = OldTexText( """ \\small Question \\#1: What is the circumference of\\\\ one of these rings (in terms of $R$ and $\\theta$)?\\\\ """, **kwargs ) prompt = OldTexText( """ Multiply this circumference by $R\\,d\\theta$ to \\\\ get an approximation of the ring's area. """, **kwargs ) for words in question, prompt: words.set_width(FRAME_WIDTH - 1) self.play(FadeInFromDown(question)) self.wait(2) for word in question, prompt: word.circum = word.get_part_by_tex("circumference") word.remove(word.circum) self.play( FadeOut(question, UP), FadeInFromDown(prompt), question.circum.replace, prompt.circum, run_time=1.5 ) self.wait() class YouCouldIntegrate(TeacherStudentsScene): def construct(self): self.student_says( "Integrate?", index=2, bubble_config={"direction": LEFT}, ) self.play(self.teacher.change, "hesitant") self.wait() self.teacher_says( "We'll be a bit \\\\ more Archimedean", target_mode="speaking" ) self.play_all_student_changes("confused") self.wait() class Question2(Scene): def construct(self): question = OldTexText( """ Question \\#2: What is the area of the shadow of\\\\ one of these rings? (In terms of $R$, $\\theta$, and $d\\theta$). """, tex_to_color_map={ "shadow": YELLOW, } ) question.set_width(FRAME_WIDTH - 1) self.play(FadeInFromDown(question)) self.wait() class Question3(Scene): def construct(self): question = OldTexText("Question \\#3:") question.to_edge(LEFT) equation = OldTexText( "(Shadow area)", "=", "$\\frac{1}{2}$", "(Area of one of the rings)" ) equation[0][1:-1].set_color(YELLOW) equation[3][1:-1].set_color(PINK) equation.next_to(question, RIGHT) which_one = OldTexText("Which one?") # which_one.set_color(YELLOW) brace = Brace(equation[-1], DOWN, buff=SMALL_BUFF) which_one.next_to(brace, DOWN, SMALL_BUFF) self.add(question) self.play(FadeIn(equation)) self.wait() self.play( GrowFromCenter(brace), Write(which_one) ) self.wait() class ExtraHint(Scene): def construct(self): title = OldTexText("Extra hint") title.scale(2.5) title.shift(UP) equation = OldTex( "\\sin(2\\theta) = 2\\sin(\\theta)\\cos(\\theta)" ) equation.next_to(title, DOWN) self.add(title, equation) class Question4(Scene): def construct(self): question = OldTexText( "Question \\#4:", "Explain how the shadows relate to\\\\" "every other ring on the sphere.", tex_to_color_map={ "shadows": YELLOW, "every other ring": BLUE, } ) self.add(question[0]) self.wait() self.play(FadeInFromDown(question[1:])) self.wait() class Question5(Scene): def construct(self): question = OldTexText( """ Question \\#5: Why does this imply that the \\\\ shadow is $\\frac{1}{4}$ the surface area? """ ) self.play(FadeInFromDown(question)) self.wait() class SpherePatronThanks(Scene): CONFIG = { "specific_patrons": [ "1stViewMaths", "Adrian Robinson", "Alexis Olson", "Ali Yahya", "Andrew Busey", "Ankalagon", "Antonio Juarez", "Art Ianuzzi", "Arthur Zey", "Awoo", "Bernd Sing", "Boris Veselinovich", "Brian Staroselsky", "brian tiger chow", "Brice Gower", "Britt Selvitelle", "Burt Humburg", "Carla Kirby", "Charles Southerland", "Chris Connett", "Christian Kaiser", "Clark Gaebel", "Cooper Jones", "Danger Dai", "Dave B", "Dave Kester", "dave nicponski", "David Clark", "David Gow", "Delton Ding", "Devarsh Desai", "Devin Scott", "eaglle", "Eric Younge", "Eryq Ouithaqueue", "Evan Phillips", "Federico Lebron", "Florian Chudigiewitsch", "Giovanni Filippi", "Graham", "Hal Hildebrand", "J", "Jacob Magnuson", "Jameel Syed", "James Hughes", "Jan Pijpers", "Jason Hise", "Jeff Linse", "Jeff Straathof", "Jerry Ling", "John Griffith", "John Haley", "John Shaughnessy", "John V Wertheim", "Jonathan Eppele", "Jonathan Wilson", "Joseph John Cox", "Joseph Kelly", "Juan Benet", "Julian Pulgarin", "Kai-Siang Ang", "Kanan Gill", "Kaustuv DeBiswas", "L0j1k", "Linh Tran", "Luc Ritchie", "Ludwig Schubert", "Lukas -krtek.net- Novy", "Lukas Biewald", "Magister Mugit", "Magnus Dahlström", "Magnus Lysfjord", "Mark B Bahu", "Markus Persson", "Mathew Bramson", "Mathias Jansson", "Matt Langford", "Matt Roveto", "Matt Russell", "Matthew Cocke", "Maurício Collares", "Mehdi Razavi", "Michael Faust", "Michael Hardel", "MrSneaky", "Mustafa Mahdi", "Márton Vaitkus", "Nathan Jessurun", "Nero Li", "Oliver Steele", "Omar Zrien", "Peter Ehrnstrom", "Peter Mcinerney", "Quantopian", "Randy C. Will", "Richard Burgmann", "Ripta Pasay", "Rish Kundalia", "Robert Teed", "Roobie", "Roy Larson", "Ryan Atallah", "Ryan Williams", "Scott Walter, Ph.D.", "Sindre Reino Trosterud", "soekul", "Solara570", "Song Gao", "Steven Soloway", "Stevie Metke", "Ted Suzman", "Valeriy Skobelev", "Vassili Philippov", "Xavier Bernard", "Yana Chernobilsky", "Yaw Etse", "YinYangBalance Asia", "Zach Cardwell", ], } def construct(self): self.add_title() self.show_columns() def add_title(self): title = OldTexText("Funded by the community, with special thanks to:") title.set_color(YELLOW) title.to_edge(UP) underline = Line(LEFT, RIGHT) underline.set_width(title.get_width() + MED_SMALL_BUFF) underline.next_to(title, DOWN, SMALL_BUFF) title.add(underline) self.add(title) self.title = title def show_columns(self): random.seed(1) random.shuffle(self.specific_patrons) patrons = VGroup(*[ OldTexText(name) for name in self.specific_patrons ]) columns = VGroup() column_size = 15 for n in range(0, len(patrons), column_size): column = patrons[n:n + column_size] column.arrange( DOWN, aligned_edge=LEFT ) columns.add(column) columns.set_height(6) for group in columns[:4], columns[4:]: for k, column in enumerate(group): column.move_to( 6.5 * LEFT + 3.75 * k * RIGHT + 2.5 * UP, UL ) self.add(columns[:4]) self.wait() for k in range(4): self.play( FadeOut(columns[k]), FadeIn(columns[k + 4]), ) self.wait() class EndScreen(PatreonEndScreen): CONFIG = { "thanks_words": "", } class ForThoseStillAround(Scene): def construct(self): words = OldTexText("Still here?") words.scale(1.5) url = OldTexText("3blue1brown.com/store") # url.scale(1.5) url.to_edge(UP, buff=MED_SMALL_BUFF) self.play(Write(words)) self.wait() self.play(ReplacementTransform(words, url)) self.wait() class PatronWords(Scene): def construct(self): words = OldTexText("\\$2+ Patrons get \\\\ 50\\% off") words.to_corner(UL) words.set_color(RED) self.add(words) class PlushMe(TeacherStudentsScene): def construct(self): self.student_says("Plushie me?") self.play_student_changes("happy", None, "happy") self.play(self.teacher.change, "confused") self.wait() self.teacher_says("...why?", target_mode="maybe") self.wait(2) class Thumbnail(SpecialThreeDScene): CONFIG = { "camera_config": { "light_source_start_point": [-10, 5, 7], } } def construct(self): radius = 1.75 sphere = self.get_sphere(radius=radius) sphere.rotate(70 * DEGREES, LEFT) sphere.set_fill(BLUE_E) sphere.set_stroke(WHITE, 0.5) circles = VGroup(*[ Circle(radius=radius) for x in range(4) ]) circles.set_stroke(WHITE, 2) circles.set_fill(BLUE_E, 1) circles[0].set_fill(GREY_BROWN) circles.arrange_in_grid() for circle in circles: formula = OldTex("\\pi", "R", "^2") formula.set_color_by_tex("R", YELLOW) formula.scale(2) formula.move_to(circle) circle.add(formula) equals = OldTex("=") equals.scale(3) group = VGroup(sphere, equals, circles) group.arrange(RIGHT, buff=MED_SMALL_BUFF) equals.shift(3 * SMALL_BUFF * RIGHT) why = OldTexText("Why?!") why.set_color(YELLOW) why.scale(2.5) why.next_to(sphere, UP) sa_formula = OldTex("4\\pi", "R", "^2") sa_formula.set_color_by_tex("R", YELLOW) sa_formula.scale(2) sa_formula.next_to(sphere, DOWN) self.camera.distance_tracker.set_value(100) self.add(sphere, equals, circles, why, sa_formula)
from manim_imports_ext import * from _2018.lost_lecture import GeometryProofLand from _2018.quaternions import SpecialThreeDScene from _2018.uncertainty import Flash class Introduction(TeacherStudentsScene): CONFIG = { "random_seed": 2, } def construct(self): self.play( Animation(VectorizedPoint(self.hold_up_spot)), self.teacher.change, "raise_right_hand", ) self.play_student_changes( "angry", "sassy", "pleading" ) self.wait() movements = [] for student in self.students: student.center_tracker = VectorizedPoint() student.center_tracker.move_to(student) student.center_tracker.save_state() student.add_updater( lambda m: m.move_to(m.center_tracker) ) always_shift( student.center_tracker, direction=DOWN + 3 * LEFT, rate=1.5 * random.random() ) movements.append(student.center_tracker) self.add(*movements) self.play_student_changes( "pondering", "sad", "concerned_musician", look_at=10 * LEFT + 2 * DOWN ) self.teacher_says( "Wait, wait, wait!", target_mode="surprised" ) self.remove(*movements) self.play( self.change_students(*3 * ["hesitant"]), *[ Restore(student.center_tracker) for student in self.students ] ) class StudentsWatching(TeacherStudentsScene): def construct(self): self.play( self.teacher.change, "raise_right_hand", self.change_students( *3 * ["thinking"], look_at=self.screen ), VFadeIn(self.pi_creatures, run_time=2) ) self.wait(5) class UnexpectedConnection(Scene): def construct(self): primes = OldTex( "2,", "3,", "5,", "7,", "11,", "13,", "17,", "\\dots" ) primes.move_to(2.5 * UP) circle = Circle( color=YELLOW, stroke_width=1, radius=1.5, ) circle.shift(1.5 * DOWN) center = circle.get_center() center_dot = Dot(center) radius = Line(center, circle.get_right()) radius.set_stroke(WHITE, 3) arrow = DoubleArrow(primes, circle) arrow.tip[1].shift(SMALL_BUFF * UP) arrow.save_state() arrow.rotate(90 * DEGREES) arrow.scale(1.5) arrow.fade(1) formula = OldTex( "\\frac{\\pi^2}{6} = \\prod_{p \\text{ prime}}" "\\frac{1}{1 - p^{-2}}" ) formula.next_to(arrow.get_center(), RIGHT) def get_arc(): angle = radius.get_angle() return Arc( start_angle=0, angle=angle, radius=circle.radius, stroke_color=YELLOW, stroke_width=5 ).shift(center) arc = always_redraw(get_arc) decimal = DecimalNumber(0) decimal.add_updater( lambda d: d.move_to(interpolate( radius.get_start(), radius.get_end(), 1.5, )), ) decimal.add_updater( lambda d: d.set_value(radius.get_angle()) ) pi = OldTex("\\pi") pi.scale(2) pi.next_to(circle, LEFT) self.add(circle, radius, center_dot, decimal, arc) self.play( Rotate(radius, PI - 1e-7, about_point=center), LaggedStartMap(FadeInFromDown, primes), run_time=4 ) self.remove(decimal) self.add(pi) self.wait() self.play( Restore(arrow), FadeIn(formula, LEFT) ) self.wait() class MapOfVideo(MovingCameraScene): def construct(self): images = Group( ImageMobject("NecklaceThumbnail"), ImageMobject("BorsukUlamThumbnail"), ImageMobject("TopologyProofThumbnail"), ImageMobject("ContinuousNecklaceThumbnail"), ImageMobject("NecklaceSphereAssociationThumbnail") ) for image in images: rect = SurroundingRectangle(image, buff=0) rect.set_stroke(WHITE, 3) image.add(rect) image_line = Group(*images[:2], *images[3:]) image_line.arrange(RIGHT, buff=LARGE_BUFF) images[2].next_to(image_line, DOWN, buff=1.5) images.set_width(FRAME_WIDTH - 1) images.to_edge(UP, buff=LARGE_BUFF) arrows = VGroup( Arrow(images[0], images[1], buff=SMALL_BUFF), Arrow( images[1].get_corner(DR) + 0.5 * LEFT, images[2].get_top() + 0.5 * LEFT, ), Arrow( images[2].get_top() + 0.5 * RIGHT, images[3].get_corner(DL) + 0.5 * RIGHT, ), Arrow(images[3], images[4], buff=SMALL_BUFF), ) self.play(LaggedStartMap(FadeInFromDown, images, run_time=4)) self.play(LaggedStartMap(GrowArrow, arrows)) self.wait() group = Group(images, arrows) for image in images: group.save_state() group.generate_target() group.target.shift(-image.get_center()) group.target.scale( FRAME_WIDTH / image.get_width(), about_point=ORIGIN, ) self.play(MoveToTarget(group, run_time=3)) self.wait() self.play(Restore(group, run_time=3)) def get_curved_arrow(self, *points): line = VMobject() line.set_points(points) tip = Arrow(points[-2], points[-1], buff=SMALL_BUFF).tip line.pointwise_become_partial(line, 0, 0.9) line.add(tip) return line class MathIsDeep(PiCreatureScene): def construct(self): words = OldTexText( "Math", "is", "deep" ) words.scale(2) words.to_edge(UP) math = words[0].copy() math[1].remove(math[1][1]) math.set_fill(opacity=0) math.set_stroke(width=0, background=True) numbers = [13, 1, 20, 8] num_mobs = VGroup(*[Integer(d) for d in numbers]) num_mobs.arrange(RIGHT, buff=MED_LARGE_BUFF) num_mobs.next_to(math, DOWN, buff=1.5) num_mobs.set_color(YELLOW) top_arrows = VGroup(*[ Arrow(c.get_bottom(), n.get_top()) for c, n in zip(math, num_mobs) ]) n_sum = Integer(sum(numbers)) n_sum.scale(1.5) n_sum.next_to(num_mobs, DOWN, buff=1.5) low_arrows = VGroup(*[ Arrow(n.get_bottom(), n_sum.get_top()) for n in num_mobs ]) VGroup(top_arrows, low_arrows).set_color(WHITE) n_sum_border = n_sum.deepcopy() n_sum_border.set_fill(opacity=0) n_sum_border.set_stroke(YELLOW, width=1) n_sum_border.set_stroke(width=0, background=True) # pre_num_mobs = num_mobs.copy() # for pn, letter in zip(pre_num_mobs, math): # pn.fade(1) # pn.set_color(RED) # pn.move_to(letter) # num_mobs[1].add_subpath(num_mobs[1].get_points()) self.play( LaggedStartMap( FadeInFromLarge, words, scale_factor=1.5, run_time=0.6, lag_ratio=0.6, ), self.pi_creature.change, "pondering" ) self.play( TransformFromCopy(math, num_mobs), *map(GrowArrow, top_arrows), ) self.wait() self.play( TransformFromCopy(num_mobs, VGroup(n_sum)), self.pi_creature.change, "thinking", *map(GrowArrow, low_arrows), ) self.play(LaggedStartMap(ShowCreationThenDestruction, n_sum_border)) self.play(Blink(self.pi_creature)) self.wait() class MinimizeSharding(Scene): def construct(self): piece_groups = VGroup(*[ VGroup(*[ self.get_piece() for x in range(3) ]).arrange(RIGHT, buff=SMALL_BUFF) for y in range(4) ]).arrange(RIGHT, buff=SMALL_BUFF) self.add(piece_groups) self.play(*[ ApplyMethod(mob.space_out_submobjects, 0.7) for mob in piece_groups ]) self.wait() group1 = piece_groups[:2] group2 = piece_groups[2:] self.play( group1.arrange, DOWN, group1.next_to, ORIGIN, LEFT, LARGE_BUFF, group2.arrange, DOWN, group2.next_to, ORIGIN, RIGHT, LARGE_BUFF, ) self.wait() def get_piece(self): jagged_spots = [ ORIGIN, 2 * UP + RIGHT, 4 * UP + LEFT, 6 * UP, ] corners = list(it.chain( jagged_spots, [6 * UP + 10 * RIGHT], [ p + 10 * RIGHT for p in reversed(jagged_spots) ], [ORIGIN] )) piece = VMobject().set_points_as_corners(corners) piece.set_width(1) piece.center() piece.set_stroke(WHITE, width=0.5) piece.set_fill(BLUE, opacity=1) return piece class Antipodes(Scene): def construct(self): word = OldTexText("``Antipodes''") word.set_width(FRAME_WIDTH - 1) word.set_color(MAROON_B) self.play(Write(word)) self.wait() class TopologyWordBreak(Scene): def construct(self): word = OldTexText("Topology") word.scale(2) colors = [BLUE, YELLOW, RED] classes = VGroup(*[VGroup() for x in range(3)]) for letter in word: genus = len(letter.submobjects) letter.target_color = colors[genus] letter.generate_target() letter.target.set_color(colors[genus]) classes[genus].add(letter.target) signs = VGroup() for group in classes: new_group = VGroup() for elem in group[:-1]: new_group.add(elem) sign = OldTex("\\simeq") new_group.add(sign) signs.add(sign) new_group.add(group[-1]) group.submobjects = list(new_group.submobjects) group.arrange(RIGHT) word[2].target.shift(0.1 * DOWN) word[7].target.shift(0.1 * DOWN) classes.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) classes.shift(2 * RIGHT) genus_labels = VGroup(*[ OldTexText("Genus %d:" % d).scale(1.5).next_to( classes[d], LEFT, MED_LARGE_BUFF ) for d in range(3) ]) genus_labels.shift(SMALL_BUFF * UP) self.play(Write(word)) self.play(LaggedStartMap( ApplyMethod, word, lambda m: (m.set_color, m.target_color), run_time=1 )) self.play( LaggedStartMap(MoveToTarget, word), LaggedStartMap(FadeIn, signs), LaggedStartMap(FadeInFromDown, genus_labels), ) self.wait(3) class TopologyProofLand(GeometryProofLand): CONFIG = { "text": "Topology proof land" } class GreenLine(Scene): def construct(self): self.add(Line(LEFT, RIGHT, color=GREEN)) class Thief(Scene): def construct(self): self.play(Write(OldTexText("Thief"))) self.wait() class FunctionGInSymbols(Scene): def construct(self): p_tex = "\\vec{\\textbf{p}}" neg_p_tex = "-\\vec{\\textbf{p}}" def color_tex(tex_mob): pairs = [ (p_tex, YELLOW), (neg_p_tex, RED), ("{g}", GREEN), ] for tex, color in pairs: tex_mob.set_color_by_tex( tex, color, substring=False ) f_of_p = OldTex("f", "(", p_tex, ")") f_of_p.shift(2.5 * LEFT + 2.5 * UP) f_of_neg_p = OldTex("f", "(", neg_p_tex, ")") g_of_p = OldTex("g", "(", p_tex, ")") g_of_p[0].set_color(YELLOW) for mob in f_of_p, f_of_neg_p, g_of_p: color_tex(mob) dec_rhs = DecimalMatrix([[-0.9], [0.5]]) dec_rhs.next_to(f_of_p, RIGHT) minus = OldTex("-") equals = OldTex("=") equals.next_to(f_of_p, RIGHT) zero_zero = IntegerMatrix([[0], [0]]) for matrix in dec_rhs, zero_zero: matrix.space_out_submobjects(0.8) matrix.brackets.scale(0.9) matrix.next_to(equals, RIGHT) f_of_neg_p.next_to(equals, RIGHT) f = f_of_p.get_part_by_tex("f") p = f_of_p.get_part_by_tex(p_tex) f_brace = Brace(f, UP, buff=SMALL_BUFF) f_brace.add(f_brace.get_text("Continuous function")) p_brace = Brace(p, DOWN, buff=SMALL_BUFF) p_brace.add(p_brace.get_text("Sphere point").match_color(p)) f_of_p.save_state() f_of_p.space_out_submobjects(2) f_of_p.scale(2) f_of_p.fade(1) self.play(f_of_p.restore) self.play(GrowFromCenter(f_brace)) self.wait() self.play(GrowFromCenter(p_brace)) self.wait() self.play( FadeInFromDown(equals), Write(dec_rhs), FadeOut(f_brace), FadeOut(p_brace), ) self.wait(2) self.play(WiggleOutThenIn(f)) self.wait() self.play( FadeOut(dec_rhs, DOWN), FadeInFromDown(f_of_neg_p) ) self.wait() # Rearrange f_of_neg_p.generate_target() f_of_p.generate_target() group = VGroup(f_of_p.target, minus, f_of_neg_p.target) group.arrange(RIGHT, buff=SMALL_BUFF) group.next_to(equals, LEFT) self.play( MoveToTarget(f_of_p, path_arc=PI), MoveToTarget(f_of_neg_p, path_arc=-PI), FadeInFromLarge(minus), FadeIn(zero_zero, LEFT) ) self.wait() # Define g def_eq = OldTex(":=") def_eq.next_to(f_of_p, LEFT) g_of_p.next_to(def_eq, LEFT) rect = SurroundingRectangle(VGroup(g_of_p, f_of_neg_p)) rect.set_stroke(width=1) seeking_text = OldTex( "\\text{Looking for }", p_tex, "\\text{ where}" ) color_tex(seeking_text) seeking_text.next_to(zero_zero, DOWN, MED_LARGE_BUFF) seeking_text.to_edge(LEFT) g_equals_zero = VGroup( g_of_p.copy(), equals, zero_zero ) g_equals_zero.generate_target() g_equals_zero.target.arrange(RIGHT, SMALL_BUFF) g_equals_zero.target.next_to(seeking_text, DOWN) self.play( FadeInFromLarge(g_of_p), FadeIn(def_eq, LEFT) ) self.play( FadeInFromDown(seeking_text), MoveToTarget(g_equals_zero) ) self.play(ShowCreation(rect)) self.wait() self.play(FadeOut(rect)) # Show g is odd g_of_neg_p = OldTex("{g}", "(", neg_p_tex, ")") eq2 = OldTex("=") rhs = OldTex( "f", "(", neg_p_tex, ")", "-", "f", "(", p_tex, ")", "=", "-", "{g}", "(", p_tex, ")", ) for mob in g_of_neg_p, rhs: color_tex(mob) g_of_neg_p.next_to(g_of_p, DOWN, aligned_edge=LEFT, buff=LARGE_BUFF) eq2.next_to(g_of_neg_p, RIGHT, SMALL_BUFF) rhs.next_to(eq2, RIGHT, SMALL_BUFF) neg_g_of_p = rhs[-5:] neg_g_of_p.save_state() neg_g_of_p.next_to(eq2, RIGHT, SMALL_BUFF) self.play( FadeIn(g_of_neg_p), FadeIn(eq2), FadeIn(neg_g_of_p), VGroup(seeking_text, g_equals_zero).shift, 1.5 * DOWN ) self.wait() self.play(ShowCreationThenFadeAround(g_of_neg_p[2])) self.wait() self.play(ShowCreationThenFadeAround(neg_g_of_p)) self.wait() self.play(neg_g_of_p.restore) rects = VGroup(*map(SurroundingRectangle, [f_of_p, f_of_neg_p])) self.play(LaggedStartMap( ShowCreationThenDestruction, rects, lag_ratio=0.8 )) self.play( TransformFromCopy(f_of_p, rhs[5:9]), TransformFromCopy(f_of_neg_p, rhs[:4]), FadeIn(rhs[4]), FadeIn(rhs[-6]), ) self.wait() class FunctionGInputSpace(SpecialThreeDScene): def setup(self): self.init_tracked_point() sphere = self.get_sphere() sphere.set_fill(BLUE_E, opacity=0.5) self.sphere = sphere self.set_camera_orientation( phi=70 * DEGREES, theta=-120 * DEGREES, ) self.begin_ambient_camera_rotation(rate=0.02) self.init_dot() self.add(ThreeDAxes()) def construct(self): self.show_input_dot() self.show_start_path() self.show_antipodal_point() self.show_equator() self.deform_towards_north_pole() def show_input_dot(self): sphere = self.sphere dot = self.dot point_mob = self.tracked_point start_point = self.get_start_point() arrow = Arrow( start_point + (LEFT + OUT + UP), start_point, color=BLUE, buff=MED_LARGE_BUFF, ) arrow.rotate(90 * DEGREES, axis=arrow.get_vector()) arrow.add_to_back(arrow.copy().set_stroke(BLACK, 5)) p_label = self.p_label = OldTex("\\vec{\\textbf{p}}") p_label.set_color(YELLOW) p_label.next_to(arrow.get_start(), OUT, buff=0.3) p_label.set_shade_in_3d(True) self.play(Write(sphere, run_time=3)) self.add(dot) self.add_fixed_orientation_mobjects(p_label) self.play( point_mob.move_to, start_point, GrowArrow(arrow), FadeIn(p_label, IN) ) self.wait() self.play( arrow.scale, 0, {"about_point": arrow.get_end()}, p_label.next_to, dot, OUT + LEFT, SMALL_BUFF ) p_label.add_updater(lambda p: p.next_to(dot, OUT + LEFT, SMALL_BUFF)) self.wait(4) def show_start_path(self): path = self.get_start_path() self.draw_path(path, uncreate=True) self.wait() def show_antipodal_point(self): path = self.get_antipodal_path() end_dot = always_redraw( lambda: self.get_dot( path[-1].point_from_proportion(1) ).set_color(RED) ) neg_p = OldTex("-\\vec{\\textbf{p}}") neg_p.add_updater( lambda p: p.next_to(end_dot, UP + RIGHT + IN) ) neg_p.set_color(RED) neg_p.set_shade_in_3d(True) self.move_camera( phi=100 * DEGREES, theta=30 * DEGREES, added_anims=[ShowCreation(path)], run_time=4, ) self.wait() self.add_fixed_orientation_mobjects(neg_p) self.play( FadeInFromLarge(end_dot), Write(neg_p) ) self.wait(4) self.move_camera( phi=70 * DEGREES, theta=-120 * DEGREES, run_time=2 ) self.wait(7) # Flip self.move_camera( phi=100 * DEGREES, theta=30 * DEGREES, run_time=2, ) self.wait(7) self.move_camera( phi=70 * DEGREES, theta=-120 * DEGREES, added_anims=[ FadeOut(end_dot), FadeOut(neg_p), FadeOut(path), ], run_time=2, ) def show_equator(self): point_mob = self.tracked_point equator = self.get_lat_line() self.play(point_mob.move_to, equator[0].point_from_proportion(0)) self.play(ShowCreation(equator, run_time=4)) for x in range(2): self.play( Rotate(point_mob, PI, about_point=ORIGIN, axis=OUT), run_time=4 ) self.wait(3) self.play( FadeOut(self.dot), FadeOut(self.p_label), ) self.equator = equator def deform_towards_north_pole(self): equator = self.equator self.play(UpdateFromAlphaFunc( equator, lambda m, a: m.become(self.get_lat_line(a * PI / 2)), run_time=16 )) self.wait() # def init_tracked_point(self): self.tracked_point = VectorizedPoint([0, 0, 2]) self.tracked_point.add_updater( lambda p: p.move_to(2 * normalize(p.get_center())) ) self.add(self.tracked_point) def init_dot(self): self.dot = always_redraw( lambda: self.get_dot(self.tracked_point.get_center()) ) def get_start_path(self): path = ParametricCurve( lambda t: np.array([ -np.sin(TAU * t + TAU / 4), np.cos(2 * TAU * t + TAU / 4), 0 ]), color=RED ) path.scale(0.5) path.shift(0.5 * OUT) path.rotate(60 * DEGREES, RIGHT, about_point=ORIGIN) path.shift( self.get_start_point() - path.point_from_proportion(0) ) path.apply_function(lambda p: 2 * normalize(p)) return path def get_antipodal_path(self): start = self.get_start_point() path = ParametricCurve( lambda t: 2.03 * np.array([ 0, np.sin(PI * t), np.cos(PI * t), ]), color=YELLOW ) path.apply_matrix(z_to_vector(start)) dashed_path = DashedVMobject(path) dashed_path.set_shade_in_3d(True) return dashed_path def get_lat_line(self, lat=0): equator = ParametricCurve(lambda t: 2.03 * np.array([ np.cos(lat) * np.sin(TAU * t), np.cos(lat) * (-np.cos(TAU * t)), np.sin(lat) ])) equator.rotate(-90 * DEGREES) dashed_equator = DashedVMobject( equator, num_dashes=40, color=RED, ) dashed_equator.set_shade_in_3d(True) return dashed_equator def draw_path(self, path, run_time=4, dot_follow=True, uncreate=False, added_anims=None ): added_anims = added_anims or [] point_mob = self.tracked_point anims = [ShowCreation(path)] if dot_follow: anims.append(UpdateFromFunc( point_mob, lambda p: p.move_to(path.point_from_proportion(1)) )) self.add(path, self.dot) self.play(*anims, run_time=run_time) if uncreate: self.wait() self.play( Uncreate(path), run_time=run_time ) def modify_path(self, path): return path def get_start_point(self): return 2 * normalize([-1, -1, 1]) def get_dot(self, point): dot = Dot(color=WHITE) dot.shift(2.05 * OUT) dot.apply_matrix(z_to_vector(normalize(point))) dot.set_shade_in_3d(True) return dot class FunctionGOutputSpace(FunctionGInputSpace): def construct(self): self.show_input_dot() self.show_start_path() self.show_antipodal_point() self.show_equator() self.deform_towards_north_pole() def setup(self): axes = self.axes = Axes( x_min=-2.5, x_max=2.5, y_min=-2.5, y_max=2.5, axis_config={'unit_size': 1.5} ) for axis in axes: numbers = list(range(-2, 3)) numbers.remove(0) axis.add_numbers(*numbers) self.init_tracked_point() self.init_dot() def show_input_dot(self): axes = self.axes dot = self.dot point_mob = self.tracked_point point_mob.move_to(self.get_start_point()) self.add(dot) self.update_mobjects(0) self.remove(dot) p_tex = "\\vec{\\textbf{p}}" fp_label = self.fp_label = OldTex("f(", p_tex, ")") fp_label.set_color_by_tex(p_tex, YELLOW) self.play(Write(axes, run_time=3)) self.wait(3) dc = dot.copy() self.play( FadeIn(dc, 2 * UP, remover=True), UpdateFromFunc(fp_label, lambda fp: fp.next_to(dc, UL, SMALL_BUFF)) ) self.add(dot) fp_label.add_updater( lambda fp: fp.next_to(dot, UL, SMALL_BUFF) ) self.wait(2) def draw_path(self, path, run_time=4, dot_follow=True, uncreate=False, added_anims=None ): added_anims = added_anims or [] point_mob = self.tracked_point shadow_path = path.deepcopy().fade(1) flat_path = self.modify_path(path) anims = [ ShowCreation(flat_path), ShowCreation(shadow_path), ] if dot_follow: anims.append(UpdateFromFunc( point_mob, lambda p: p.move_to(shadow_path.point_from_proportion(1)) )) self.add(flat_path, self.dot) self.play(*anims, run_time=run_time) if uncreate: self.wait() self.remove(shadow_path) self.play( Uncreate(flat_path), run_time=run_time ) def show_antipodal_point(self): dot = self.dot pre_path = VMobject().set_points_smoothly([ ORIGIN, DOWN, DOWN + 2 * RIGHT, 3 * RIGHT + 0.5 * UP, 0.5 * RIGHT, ORIGIN ]) pre_path.rotate(-45 * DEGREES, about_point=ORIGIN) pre_path.shift(dot.get_center()) path = DashedVMobject(pre_path) fp_label = self.fp_label equals = OldTex("=") equals.next_to(fp_label, RIGHT, SMALL_BUFF) f_neg_p = OldTex("f(", "-\\vec{\\textbf{p}}", ")") f_neg_p[1].set_color(RED) f_neg_p.next_to(equals, RIGHT) gp_label = OldTex("g", "(", "\\vec{\\textbf{p}}", ")") gp_label[0].set_color(GREEN) gp_label[2].set_color(YELLOW) gp_label.add_updater(lambda m: m.next_to(dot, UL, SMALL_BUFF)) self.gp_label = gp_label # gp_label.next_to(Dot(ORIGIN), UL, SMALL_BUFF) self.play(ShowCreation(path, run_time=4)) self.wait() self.play( Write(equals), Write(f_neg_p), ) self.wait(6) self.play( FadeOut(VGroup(path, equals, f_neg_p)) ) dot.clear_updaters() self.add(fp_label, gp_label) gp_label.set_background_stroke(width=0) self.play( dot.move_to, ORIGIN, VFadeOut(fp_label), VFadeIn(gp_label), ) self.wait(4) self.play( dot.move_to, self.odd_func(self.get_start_point()) ) # Flip, 2 second for flip, 7 seconds after path = self.get_antipodal_path() path.apply_function(self.odd_func) end_dot = Dot(color=RED) end_dot.move_to(path[-1].point_from_proportion(1)) g_neg_p = OldTex( "g", "(", "-\\vec{\\textbf{p}}", ")" ) g_neg_p[0].set_color(GREEN) g_neg_p[2].set_color(RED) g_neg_p.next_to(end_dot, UR, SMALL_BUFF) reflection_line = DashedLine( dot.get_center(), end_dot.get_center(), stroke_width=0, ) vector = Vector(dot.get_center()) self.play(ShowCreation(path, run_time=1)) self.wait() self.play( ShowCreationThenDestruction(reflection_line, run_time=2), TransformFromCopy(dot, end_dot), ReplacementTransform( gp_label.deepcopy().clear_updaters(), g_neg_p ), ) self.wait() self.play(FadeIn(vector)) self.play(Rotate(vector, angle=PI, about_point=ORIGIN)) self.play(FadeOut(vector)) self.play( FadeOut(end_dot), FadeOut(g_neg_p), FadeOut(path), ) def show_equator(self): dot = self.dot point_mob = self.tracked_point equator = self.get_lat_line() flat_eq = equator.deepcopy().apply_function(self.odd_func) equator.fade(1) equator_start = equator[0].point_from_proportion(0) # To address self.play( point_mob.move_to, equator_start, dot.move_to, self.odd_func(equator_start) ) dot.add_updater(lambda m: m.move_to( self.odd_func(point_mob.get_center()) )) self.play( ShowCreation(equator), ShowCreation(flat_eq), run_time=4, ) for x in range(2): self.play( Rotate(point_mob, PI, about_point=ORIGIN, axis=OUT), run_time=4 ) self.wait(3) self.play( FadeOut(self.dot), FadeOut(self.gp_label), ) self.equator = equator self.flat_eq = flat_eq def deform_towards_north_pole(self): equator = self.equator flat_eq = self.flat_eq self.play( UpdateFromAlphaFunc( equator, lambda m, a: m.become(self.get_lat_line(a * PI / 2)).set_stroke(width=0), run_time=16 ), UpdateFromFunc( flat_eq, lambda m: m.become( equator.deepcopy().apply_function(self.odd_func).set_stroke( color=RED, width=3 ) ) ) ) self.wait() # def func(self, point): x, y, z = point return 0.5 * self.axes.coords_to_point( 2 * x + 0.5 * y + z, 2 * y - 0.5 * np.sin(PI * x) + z**2 + 1 - x, ) def odd_func(self, point): return (self.func(point) - self.func(-point)) / 2 def get_dot(self, point): return Dot(self.func(point)) def modify_path(self, path): path.apply_function(self.func) return path class RotationOfEquatorGraphInOuputSpace(FunctionGOutputSpace): def construct(self): self.add(self.axes) equator = self.get_lat_line(0) equator.remove(*equator[len(equator) // 2:]) flat_eq = equator.copy().apply_function(self.odd_func) vector = Vector(flat_eq[0].point_from_proportion(0)) vector_copy = vector.copy().fade(0.5) self.add(flat_eq) self.add(flat_eq.copy()) self.wait() self.play(FadeIn(vector)) self.add(vector_copy) self.play( Rotate( VGroup(flat_eq, vector), PI, about_point=ORIGIN, run_time=5 )) self.play(FadeOut(vector), FadeOut(vector_copy)) class WriteInputSpace(Scene): def construct(self): self.play(Write(OldTexText("Input space"))) self.wait() class WriteOutputSpace(Scene): def construct(self): self.play(Write(OldTexText("Output space"))) self.wait() class LineScene(Scene): def construct(self): self.add(DashedLine(5 * LEFT, 5 * RIGHT, color=WHITE)) class ShowFlash(Scene): def construct(self): dot = Dot(ORIGIN, color=YELLOW) dot.set_stroke(width=0) dot.set_fill(opacity=0) self.play(Flash(dot, flash_radius=0.8, line_length=0.6, run_time=2)) self.wait() class WaitForIt(Scene): def construct(self): words = OldTexText("Wait for it", "$\\dots$", arg_separator="") words.scale(2) self.add(words[0]) self.play(Write(words[1], run_time=3)) self.wait() class DrawSphere(SpecialThreeDScene): def construct(self): sphere = self.get_sphere() sphere.shift(IN) question = OldTexText("What \\emph{is} a sphere?") question.set_width(FRAME_WIDTH - 3) question.to_edge(UP) self.move_camera(phi=70 * DEGREES, run_time=0) self.begin_ambient_camera_rotation() self.add_fixed_in_frame_mobjects(question) self.play( Write(sphere), FadeInFromDown(question) ) self.wait(4) class DivisionOfUnity(Scene): def construct(self): factor = 2 line = Line(factor * LEFT, factor * RIGHT) lower_brace = Brace(line, DOWN) lower_brace.add(lower_brace.get_text("1")) v_lines = VGroup(*[ DashedLine(0.2 * UP, 0.2 * DOWN).shift(factor * v) for v in [LEFT, 0.3 * LEFT, 0.1 * RIGHT, RIGHT] ]) upper_braces = VGroup(*[ Brace(VGroup(vl1, vl2), UP) for vl1, vl2 in zip(v_lines[:-1], v_lines[1:]) ]) colors = color_gradient([GREEN, BLUE], 3) for i, color, brace in zip(it.count(1), colors, upper_braces): label = brace.get_tex("x_%d^2" % i) label.set_color(color) brace.add(label) self.add(line, lower_brace) self.play(LaggedStartMap( ShowCreation, v_lines[1:3], lag_ratio=0.8, run_time=1 )) self.play(LaggedStartMap( GrowFromCenter, upper_braces )) self.wait() class ThreeDSpace(ThreeDScene): def construct(self): axes = ThreeDAxes() self.add(axes) self.set_camera_orientation(phi=70 * DEGREES, theta=-130 * DEGREES) self.begin_ambient_camera_rotation() density = 1 radius = 3 lines = VGroup(*[ VGroup(*[ Line( radius * IN, radius * OUT, stroke_color=WHITE, stroke_width=1, stroke_opacity=0.5, ).shift(x * RIGHT + y * UP) for x in np.arange(-radius, radius + density, density) for y in np.arange(-radius, radius + density, density) ]).rotate(n * 120 * DEGREES, axis=[1, 1, 1]) for n in range(3) ]) self.play(Write(lines)) self.wait(30) class NecklaceSphereConnectionTitle(Scene): def construct(self): text = OldTexText("Necklace Sphere Association") text.set_width(FRAME_WIDTH - 1) self.add(text) class BorsukEndScreen(PatreonEndScreen): 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", ], "n_patron_columns": 2, } class Thumbnail(SpecialThreeDScene): def construct(self): sphere = ParametricSurface( func=lambda u, v: 2 * np.array([ np.cos(v) * np.sin(u) + 0.2 * np.cos(3 * u), np.sin(v) * np.sin(u), np.cos(u) + 0.2 * np.sin(4 * v) - 0.3 * np.cos(3 * u) ]), resolution=(24, 48), u_min=0.001, u_max=PI - 0.001, v_min=0, v_max=TAU, ) sphere.rotate(70 * DEGREES, DOWN) self.set_camera_orientation( phi=80 * DEGREES, theta=-90 * DEGREES, ) # randy = Randolph(mode="telepath") # eyes = VGroup(randy.eyes, randy.pupils) # eyes.scale(3.5) # eyes.rotate(90 * DEGREES, RIGHT) # eyes.next_to(sphere, OUT, buff=0) self.add(sphere)
from manim_imports_ext import * from _2018.div_curl import VectorField from _2018.div_curl import get_force_field_func COBALT = "#0047AB" # Warning, this file uses ContinualChangingDecimal, # which has since been been deprecated. Use a mobject # updater instead # TODO, this is untested after turning it from a # ContinualAnimation into a VGroup class Orbiting(VGroup): CONFIG = { "rate": 7.5, } def __init__(self, planet, star, ellipse, **kwargs): VGroup.__init__(self, **kwargs) self.add(planet) self.planet = planet self.star = star self.ellipse = ellipse # Proportion of the way around the ellipse self.proportion = 0 planet.move_to(ellipse.point_from_proportion(0)) self.add_updater(lambda m, dt: m.update(dt)) def update(self, dt): # time = self.internal_time planet = self.planet star = self.star ellipse = self.ellipse rate = self.rate radius_vector = planet.get_center() - star.get_center() rate *= 1.0 / get_norm(radius_vector) prop = self.proportion d_prop = 0.001 ds = get_norm(op.add( ellipse.point_from_proportion((prop + d_prop) % 1), -ellipse.point_from_proportion(prop), )) delta_prop = (d_prop / ds) * rate * dt self.proportion = (self.proportion + delta_prop) % 1 planet.move_to( ellipse.point_from_proportion(self.proportion) ) # TODO, this is untested after turning it from a # ContinualAnimation into a Group class SunAnimation(Group): CONFIG = { "rate": 0.2, "angle": 60 * DEGREES, } def __init__(self, sun, **kwargs): Group.__init__(self, **kwargs) self.sun = sun self.rotated_sun = sun.deepcopy() self.rotated_sun.rotate(60 * DEGREES) self.time = 0 self.add(self.sun, self.rotated_sun) self.add_updater(lambda m, dt: m.update(dt)) def update(self, dt): time = self.time self.time += dt a = (np.sin(self.rate * time * TAU) + 1) / 2.0 self.rotated_sun.rotate(-self.angle) self.rotated_sun.move_to(self.sun) self.rotated_sun.rotate(self.angle) self.rotated_sun.pixel_array = np.array( a * self.sun.pixel_array, dtype=self.sun.pixel_array.dtype ) class ShowWord(Animation): CONFIG = { "time_per_char": 0.06, "rate_func": linear, } def __init__(self, word, **kwargs): assert(isinstance(word, SingleStringTex)) digest_config(self, kwargs) run_time = kwargs.pop( "run_time", self.time_per_char * len(word) ) self.stroke_width = word.get_stroke_width() Animation.__init__(self, word, run_time=run_time, **kwargs) def interpolate_mobject(self, alpha): word = self.mobject stroke_width = self.stroke_width count = int(alpha * len(word)) remainder = (alpha * len(word)) % 1 word[:count].set_fill(opacity=1) word[:count].set_stroke(width=stroke_width) if count < len(word): word[count].set_fill(opacity=remainder) word[count].set_stroke(width=remainder * stroke_width) word[count + 1:].set_fill(opacity=0) word[count + 1:].set_stroke(width=0) # Animations class TakeOver(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs": { "color": GREY_BROWN, "flip_at_start": True, }, "default_pi_creature_start_corner": DR, } def construct(self): gradient = ImageMobject("white_black_gradient") gradient.set_height(FRAME_HEIGHT) self.add(gradient) morty = self.pi_creatures henry = ImageMobject("Henry_As_Stick") henry.set_height(4) henry.to_edge(LEFT) henry.to_edge(DOWN) self.add(morty, henry) self.pi_creature_says( "Muahaha! All \\\\ mine now.", bubble_config={"fill_opacity": 0.5}, bubble_creation_class=FadeIn, target_mode="conniving", added_anims=[henry.rotate, 5 * DEGREES] ) self.wait(2) class ShowEmergingEllipse(Scene): CONFIG = { "circle_radius": 3, "circle_color": BLUE, "num_lines": 150, "lines_stroke_width": 1, "eccentricity_vector": 2 * RIGHT, "ghost_lines_stroke_color": GREY_B, "ghost_lines_stroke_width": 0.5, "ellipse_color": PINK, } def construct(self): circle = self.get_circle() e_point = self.get_eccentricity_point() e_dot = Dot(e_point, color=YELLOW) lines = self.get_lines() ellipse = self.get_ellipse() fade_rect = FullScreenFadeRectangle() line = lines[len(lines) // 5] line_dot = Dot(line.get_center(), color=YELLOW) line_dot.scale(0.5) ghost_line = self.get_ghost_lines(line) ghost_lines = self.get_ghost_lines(lines) rot_words = OldTexText("Rotate $90^\\circ$ \\\\ about center") rot_words.next_to(line_dot, RIGHT) elbow = self.get_elbow(line) eccentric_words = OldTexText("``Eccentric'' point") eccentric_words.next_to(circle.get_center(), DOWN) ellipse_words = OldTexText("Perfect ellipse") ellipse_words.next_to(ellipse, UP, SMALL_BUFF) for text in rot_words, ellipse_words: text.add_to_back(text.copy().set_stroke(BLACK, 5)) shuffled_lines = VGroup(*lines) random.shuffle(shuffled_lines.submobjects) self.play(ShowCreation(circle)) self.play( FadeIn(e_dot, LEFT), Write(eccentric_words, run_time=1) ) self.wait() self.play( LaggedStartMap(ShowCreation, shuffled_lines), Animation(VGroup(e_dot, circle)), FadeOut(eccentric_words) ) self.add(ghost_lines) self.add(e_dot, circle) self.wait() self.play( FadeIn(fade_rect), Animation(line), GrowFromCenter(line_dot), FadeInFromDown(rot_words), ) self.wait() self.add(ghost_line) self.play( MoveToTarget(line, path_arc=90 * DEGREES), Animation(rot_words), ShowCreation(elbow) ) self.wait() self.play( FadeOut(fade_rect), FadeOut(line_dot), FadeOut(rot_words), FadeOut(elbow), Animation(line), Animation(ghost_line) ) self.play( LaggedStartMap(MoveToTarget, lines, run_time=4), Animation(VGroup(e_dot, circle)) ) self.wait() self.play( ShowCreation(ellipse), FadeInFromDown(ellipse_words) ) self.wait() def get_circle(self): circle = self.circle = Circle( radius=self.circle_radius, color=self.circle_color ) return circle def get_eccentricity_point(self): return self.circle.get_center() + self.eccentricity_vector def get_lines(self): center = self.circle.get_center() radius = self.circle.get_width() / 2 e_point = self.get_eccentricity_point() lines = VGroup(*[ Line( e_point, center + rotate_vector(radius * RIGHT, angle) ) for angle in np.linspace(0, TAU, self.num_lines) ]) lines.set_stroke(width=self.lines_stroke_width) for line in lines: line.generate_target() line.target.rotate(90 * DEGREES) return lines def get_ghost_lines(self, lines): return lines.copy().set_stroke( color=self.ghost_lines_stroke_color, width=self.ghost_lines_stroke_width ) def get_elbow(self, line): elbow = VGroup(Line(UP, UL), Line(UL, LEFT)) elbow.set_stroke(width=1) elbow.scale(0.2, about_point=ORIGIN) elbow.rotate( line.get_angle() - 90 * DEGREES, about_point=ORIGIN ) elbow.shift(line.get_center()) return elbow def get_ellipse(self): center = self.circle.get_center() e_point = self.get_eccentricity_point() radius = self.circle.get_width() / 2 # Ellipse parameters a = radius / 2 c = get_norm(e_point - center) / 2 b = np.sqrt(a**2 - c**2) result = Circle(radius=b, color=self.ellipse_color) result.stretch(a / b, 0) result.move_to(Line(center, e_point)) return result class ShowFullStory(Scene): def construct(self): directory = os.path.join( MEDIA_DIR, "animations/active_projects/lost_lecture/images" ) scene_names = [ "ShowEmergingEllipse", "ShowFullStory", "FeynmanFameStart", "TheMotionOfPlanets", "FeynmanElementaryQuote", "DrawingEllipse", "ShowEllipseDefiningProperty", "ProveEllipse", "KeplersSecondLaw", "AngularMomentumArgument", "HistoryOfAngularMomentum", "FeynmanRecountingNewton", "IntroduceShapeOfVelocities", "ShowEqualAngleSlices", "PonderOverOffCenterDiagram", "UseVelocityDiagramToDeduceCurve", ] images = Group(*[ ImageMobject(os.path.join(directory, name + ".png")) for name in scene_names ]) for image in images: image.add( SurroundingRectangle(image, buff=0, color=WHITE) ) images.arrange_in_grid(n_rows=4) images.scale( 1.01 * FRAME_WIDTH / images[0].get_width() ) images.shift(-images[0].get_center()) self.play( images.set_width, FRAME_WIDTH - 1, images.center, run_time=3, ) self.wait() self.play( images.shift, -images[2].get_center(), images.scale, FRAME_WIDTH / images[2].get_width(), {"about_point": ORIGIN}, run_time=3, ) self.wait() class FeynmanAndOrbitingPlannetOnEllipseDiagram(ShowEmergingEllipse): def construct(self): circle = self.get_circle() lines = self.get_lines() ghost_lines = self.get_ghost_lines(lines) for line in lines: MoveToTarget(line).update(1) ellipse = self.get_ellipse() e_dot = Dot(self.get_eccentricity_point()) e_dot.set_color(YELLOW) comet = ImageMobject("earth") comet.set_width(0.3) feynman = ImageMobject("Feynman") feynman.set_height(6) feynman.next_to(ORIGIN, LEFT) feynman.to_edge(UP) feynman_name = OldTexText("Richard Feynman") feynman_name.next_to(feynman, DOWN) feynman.save_state() feynman.shift(2 * DOWN) feynman_rect = BackgroundRectangle( feynman, fill_opacity=1 ) group = VGroup(circle, ghost_lines, lines, e_dot, ellipse) self.add(group) self.add(Orbiting(comet, e_dot, ellipse)) self.add_foreground_mobjects(comet) self.wait() self.play( feynman.restore, MaintainPositionRelativeTo(feynman_rect, feynman), VFadeOut(feynman_rect), group.to_edge, RIGHT, ) self.play(Write(feynman_name)) self.wait() self.wait(10) class FeynmanFame(Scene): def construct(self): books = VGroup( ImageMobject("Feynman_QED_cover"), ImageMobject("Surely_Youre_Joking_cover"), ImageMobject("Feynman_Lectures_cover"), ) for book in books: book.set_height(6) book.move_to(FRAME_WIDTH * LEFT / 4) feynman_diagram = self.get_feynman_diagram() feynman_diagram.next_to(ORIGIN, RIGHT) fd_parts = VGroup(*reversed(feynman_diagram.family_members_with_points())) # As a physicist self.play(self.get_book_intro(books[0])) self.play(LaggedStartMap( Write, feynman_diagram, run_time=4 )) self.wait() self.play( self.get_book_intro(books[1]), self.get_book_outro(books[0]), LaggedStartMap( ApplyMethod, fd_parts, lambda m: (m.scale, 0), run_time=1 ), ) self.remove(feynman_diagram) self.wait() # As a public figure safe = SVGMobject(file_name="safe", height=2) safe_rect = SurroundingRectangle(safe, buff=0) safe_rect.set_stroke(width=0) safe_rect.set_fill(GREY_D, 1) safe.add_to_back(safe_rect) bongo = SVGMobject(file_name="bongo") bongo.set_height(1) bongo.set_color(WHITE) bongo.next_to(safe, RIGHT, LARGE_BUFF) objects = VGroup(safe, bongo) feynman_smile = ImageMobject("Feynman_Los_Alamos") feynman_smile.set_height(4) feynman_smile.next_to(objects, DOWN) VGroup(objects, feynman_smile).next_to(ORIGIN, RIGHT) joke = OldTexText( "``Science is the belief \\\\ in the ignorance of \\\\ experts.''" ) joke.move_to(objects) self.play(LaggedStartMap( DrawBorderThenFill, objects, lag_ratio=0.75 )) self.play(self.get_book_intro(feynman_smile)) self.wait() self.play( objects.shift, 2 * UP, VFadeOut(objects) ) self.play(Write(joke)) self.wait(2) self.play( self.get_book_intro(books[2]), self.get_book_outro(books[1]), LaggedStartMap(FadeOut, joke, run_time=1), ApplyMethod( feynman_smile.shift, FRAME_HEIGHT * DOWN, remover=True ) ) # As a teacher feynman_teacher = ImageMobject("Feynman_teaching") feynman_teacher.set_width(FRAME_WIDTH / 2 - 1) feynman_teacher.next_to(ORIGIN, RIGHT) self.play(self.get_book_intro(feynman_teacher)) self.wait(3) def get_book_animation(self, book, initial_shift, animated_shift, opacity_func ): rect = BackgroundRectangle(book, fill_opacity=1) book.shift(initial_shift) return AnimationGroup( ApplyMethod(book.shift, animated_shift), UpdateFromAlphaFunc( rect, lambda r, a: r.move_to(book).set_fill( opacity=opacity_func(a) ), remover=True ) ) def get_book_intro(self, book): return self.get_book_animation( book, 2 * DOWN, 2 * UP, lambda a: 1 - a ) def get_book_outro(self, book): return ApplyMethod(book.shift, FRAME_HEIGHT * UP, remover=True) def get_feynman_diagram(self): x_min = -1.5 x_max = 1.5 arrow = Arrow(LEFT, RIGHT, buff=0) arrow.tip.move_to(arrow.get_center()) arrows = VGroup(*[ arrow.copy().rotate(angle).next_to(point, vect, buff=0) for (angle, point, vect) in [ (-45 * DEGREES, x_min * RIGHT, UL), (-135 * DEGREES, x_min * RIGHT, DL), (-135 * DEGREES, x_max * RIGHT, UR), (-45 * DEGREES, x_max * RIGHT, DR), ] ]) labels = VGroup(*[ OldTex(tex) for tex in ["e^-", "e^+", "\\text{\\=q}", "q"] ]) vects = [UR, DR, UL, DL] for arrow, label, vect in zip(arrows, labels, vects): label.next_to(arrow.get_center(), vect, buff=SMALL_BUFF) wave = FunctionGraph( lambda x: 0.2 * np.sin(2 * TAU * x), x_min=x_min, x_max=x_max, ) wave_label = OldTex("\\gamma") wave_label.next_to(wave, UP, SMALL_BUFF) labels.add(wave_label) squiggle = ParametricCurve( lambda t: np.array([ t + 0.5 * np.sin(TAU * t), 0.5 * np.cos(TAU * t), 0, ]), t_min=0, t_max=4, ) squiggle.scale(0.25) squiggle.set_color(BLUE) squiggle.rotate(-30 * DEGREES) squiggle.next_to( arrows[2].point_from_proportion(0.75), DR, buff=0 ) squiggle_label = OldTex("g") squiggle_label.next_to(squiggle, UR, buff=-MED_SMALL_BUFF) labels.add(squiggle_label) return VGroup(arrows, wave, squiggle, labels) class FeynmanLecturesScreenCaptureFrame(Scene): def construct(self): url = OldTexText("http://www.feynmanlectures.caltech.edu/") url.to_edge(UP) screen_rect = ScreenRectangle(height=6) screen_rect.next_to(url, DOWN) self.add(url) self.play(ShowCreation(screen_rect)) self.wait() class TheMotionOfPlanets(Scene): CONFIG = { "camera_config": {"background_opacity": 1}, "random_seed": 2, } def construct(self): self.add_title() self.setup_orbits() def add_title(self): title = OldTexText("``The motion of planets around the sun''") title.set_color(YELLOW) title.to_edge(UP) title.add_to_back(title.copy().set_stroke(BLACK, 5)) self.add(title) self.title = title def setup_orbits(self): sun = ImageMobject("sun") sun.set_height(0.7) planets, ellipses, orbits = self.get_planets_ellipses_and_orbits(sun) archivist_words = OldTexText( "Judith Goodstein (Caltech archivist)" ) archivist_words.to_corner(UL) archivist_words.shift(1.5 * DOWN) archivist_words.add_background_rectangle() alt_name = OldTexText("David Goodstein (Caltech physicist)") alt_name.next_to(archivist_words, DOWN, aligned_edge=LEFT) alt_name.add_background_rectangle() book = ImageMobject("Lost_Lecture_cover") book.set_height(4) book.next_to(alt_name, DOWN) self.add(SunAnimation(sun)) self.add(ellipses, planets) self.add(self.title) self.add(*orbits) self.add_foreground_mobjects(planets) self.wait(10) self.play( VGroup(ellipses, sun).shift, 3 * RIGHT, FadeInFromDown(archivist_words), Animation(self.title) ) self.add_foreground_mobjects(archivist_words) self.wait(3) self.play(FadeInFromDown(alt_name)) self.add_foreground_mobjects(alt_name) self.wait() self.play(FadeInFromDown(book)) self.wait(15) def get_planets_ellipses_and_orbits(self, sun): planets = VGroup( ImageMobject("mercury"), ImageMobject("venus"), ImageMobject("earth"), ImageMobject("mars"), ImageMobject("comet") ) sizes = [0.383, 0.95, 1.0, 0.532, 0.3] orbit_radii = [0.254, 0.475, 0.656, 1.0, 3.0] orbit_eccentricies = [0.206, 0.006, 0.0167, 0.0934, 0.967] for planet, size in zip(planets, sizes): planet.set_height(0.5) planet.scale(size) ellipses = VGroup(*[ Circle(radius=r, color=WHITE, stroke_width=1) for r in orbit_radii ]) for circle, ec in zip(ellipses, orbit_eccentricies): a = circle.get_height() / 2 c = ec * a b = np.sqrt(a**2 - c**2) circle.stretch(b / a, 1) c = np.sqrt(a**2 - b**2) circle.shift(c * RIGHT) for circle in ellipses: circle.rotate( TAU * np.random.random(), about_point=ORIGIN ) ellipses.scale(3.5, about_point=ORIGIN) orbits = [ Orbiting( planet, sun, circle, rate=0.25 * r**(2 / 3) ) for planet, circle, r in zip(planets, ellipses, orbit_radii) ] orbits[-1].proportion = 0.15 orbits[-1].rate = 0.5 return planets, ellipses, orbits class TeacherHoldingUp(TeacherStudentsScene): def construct(self): self.play( self.teacher.change, "raise_right_hand" ) self.play_all_student_changes("pondering") self.look_at(ORIGIN) self.wait(5) class AskAboutEllipses(TheMotionOfPlanets): CONFIG = { "camera_config": {"background_opacity": 1}, "sun_height": 0.5, "sun_center": ORIGIN, "animate_sun": True, "a": 3.5, "b": 2.0, "ellipse_color": WHITE, "ellipse_stroke_width": 1, "comet_height": 0.2, } def construct(self): self.add_title() self.add_sun() self.add_orbit() self.add_focus_lines() self.add_force_labels() self.comment_on_imperfections() self.set_up_differential_equations() def add_title(self): title = Title("Why are orbits ellipses?") self.add(title) self.title = title def add_sun(self): sun = ImageMobject("sun", height=self.sun_height) sun.move_to(self.sun_center) self.sun = sun self.add(sun) if self.animate_sun: sun_animation = SunAnimation(sun) self.add(sun_animation) self.add_foreground_mobjects( sun_animation.mobject ) else: self.add_foreground_mobjects(sun) def add_orbit(self): sun = self.sun comet = self.get_comet() ellipse = self.get_ellipse() orbit = Orbiting(comet, sun, ellipse) self.add(ellipse) self.add(orbit) self.ellipse = ellipse self.comet = comet self.orbit = orbit def add_focus_lines(self): f1, f2 = self.focus_points comet = self.comet lines = VGroup(Line(LEFT, RIGHT), Line(LEFT, RIGHT)) lines.set_stroke(GREY_B, 1) def update_lines(lines): l1, l2 = lines P = comet.get_center() l1.put_start_and_end_on(f1, P) l2.put_start_and_end_on(f2, P) return lines animation = Mobject.add_updater( lines, update_lines ) self.add(animation) self.wait(8) self.focus_lines = lines self.focus_lines_animation = animation def add_force_labels(self): radial_line = self.focus_lines[0] # Radial line measurement radius_measurement_kwargs = { "num_decimal_places": 3, "color": BLUE, } radius_measurement = DecimalNumber(1, **radius_measurement_kwargs) def update_radial_measurement(measurement): angle = -radial_line.get_angle() + np.pi radial_line.rotate(angle, about_point=ORIGIN) new_decimal = DecimalNumber( radial_line.get_length(), **radius_measurement_kwargs ) max_width = 0.6 * radial_line.get_width() if new_decimal.get_width() > max_width: new_decimal.set_width(max_width) new_decimal.next_to(radial_line, UP, SMALL_BUFF) VGroup(new_decimal, radial_line).rotate( -angle, about_point=ORIGIN ) Transform(measurement, new_decimal).update(1) radius_measurement_animation = Mobject.add_updater( radius_measurement, update_radial_measurement ) # Force equation force_equation = OldTex( "F = {GMm \\over (0.000)^2}", tex_to_color_map={ "F": YELLOW, "0.000": BLACK, } ) force_equation.next_to(self.title, DOWN) force_equation.to_edge(RIGHT) radius_in_denominator_ref = force_equation.get_part_by_tex("0.000") radius_in_denominator = DecimalNumber( 0, **radius_measurement_kwargs ) radius_in_denominator.scale(0.95) update_radius_in_denominator = ContinualChangingDecimal( radius_in_denominator, lambda a: radial_line.get_length(), position_update_func=lambda mob: mob.move_to( radius_in_denominator_ref, LEFT ) ) # Force arrow force_arrow, force_arrow_animation = self.get_force_arrow_and_update( self.comet ) inverse_square_law_words = OldTexText( "``Inverse square law''" ) inverse_square_law_words.next_to(force_equation, DOWN, MED_LARGE_BUFF) inverse_square_law_words.to_edge(RIGHT) force_equation.next_to(inverse_square_law_words, UP, MED_LARGE_BUFF) def v_fade_in(mobject): return UpdateFromAlphaFunc( mobject, lambda mob, alpha: mob.set_fill(opacity=alpha) ) self.add(update_radius_in_denominator) self.add(radius_measurement_animation) self.play( FadeIn(force_equation), v_fade_in(radius_in_denominator), v_fade_in(radius_measurement) ) self.add(force_arrow_animation) self.play(v_fade_in(force_arrow)) self.wait(8) self.play(Write(inverse_square_law_words)) self.wait(9) self.force_equation = force_equation self.inverse_square_law_words = inverse_square_law_words self.force_arrow = force_arrow self.radius_measurement = radius_measurement def comment_on_imperfections(self): planets, ellipses, orbits = self.get_planets_ellipses_and_orbits(self.sun) orbits.pop(-1) ellipses.submobjects.pop(-1) planets.submobjects.pop(-1) scale_factor = 20 center = self.sun.get_center() ellipses.save_state() ellipses.scale(scale_factor, about_point=center) self.add(*orbits) self.play(ellipses.restore, Animation(planets)) self.wait(7) self.play( ellipses.scale, scale_factor, {"about_point": center}, Animation(planets) ) self.remove(*orbits) self.remove(planets, ellipses) self.wait(2) def set_up_differential_equations(self): d_dt = OldTex("{d \\over dt}") in_vect = Matrix(np.array([ "x(t)", "y(t)", "\\dot{x}(t)", "\\dot{y}(t)", ])) equals = OldTex("=") out_vect = Matrix(np.array([ "\\dot{x}(t)", "\\dot{y}(t)", "-x(t) / (x(t)^2 + y(t)^2)^{3/2}", "-y(t) / (x(t)^2 + y(t)^2)^{3/2}", ]), element_alignment_corner=ORIGIN) equation = VGroup(d_dt, in_vect, equals, out_vect) equation.arrange(RIGHT, buff=SMALL_BUFF) equation.set_width(6) equation.to_corner(DR, buff=MED_LARGE_BUFF) cross = Cross(equation) self.play(Write(equation)) self.wait(6) self.play(ShowCreation(cross)) self.wait(6) # Helpers def get_comet(self): comet = ImageMobject("comet") comet.set_height(self.comet_height) return comet def get_ellipse(self): a = self.a b = self.b c = np.sqrt(a**2 - b**2) ellipse = Circle(radius=a) ellipse.set_stroke( self.ellipse_color, self.ellipse_stroke_width, ) ellipse.stretch(fdiv(b, a), dim=1) ellipse.move_to( self.sun.get_center() + c * LEFT, ) self.focus_points = [ self.sun.get_center(), self.sun.get_center() + 2 * c * LEFT, ] return ellipse def get_force_arrow_and_update(self, comet, scale_factor=1): force_arrow = Arrow(LEFT, RIGHT, color=YELLOW) sun = self.sun def update_force_arrow(arrow): radial_line = Line( sun.get_center(), comet.get_center() ) radius = radial_line.get_length() # target_length = 1 / radius**2 target_length = scale_factor / radius # Lies! arrow.scale( target_length / arrow.get_length() ) arrow.rotate( np.pi + radial_line.get_angle() - arrow.get_angle() ) arrow.shift( radial_line.get_end() - arrow.get_start() ) force_arrow_animation = Mobject.add_updater( force_arrow, update_force_arrow ) return force_arrow, force_arrow_animation def get_radial_line_and_update(self, comet): line = Line(LEFT, RIGHT) line.set_stroke(GREY_B, 1) line_update = Mobject.add_updater( line, lambda l: l.put_start_and_end_on( self.sun.get_center(), comet.get_center(), ) ) return line, line_update class FeynmanSaysItBest(TeacherStudentsScene): def construct(self): self.teacher_says( "Feynman says \\\\ it best", added_anims=[ self.change_students( "hooray", "happy", "erm" ) ] ) self.wait(3) class FeynmanElementaryQuote(Scene): def construct(self): quote_text = """ \\large I am going to give what I will call an \\emph{elementary} demonstration. But elementary does not mean easy to understand. Elementary means that very little is required to know ahead of time in order to understand it, except to have an infinite amount of intelligence. """ quote_parts = [s for s in quote_text.split(" ") if s] quote = OldTexText( *quote_parts, tex_to_color_map={ "\\emph{elementary}": BLUE, "elementary": BLUE, "Elementary": BLUE, "infinite": YELLOW, "amount": YELLOW, "of": YELLOW, "intelligence": YELLOW, "very": RED, "little": RED, }, alignment="" ) quote[-1].shift(2 * SMALL_BUFF * LEFT) quote.set_width(FRAME_WIDTH - 1) quote.to_edge(UP) quote.get_part_by_tex("of").set_color(WHITE) nothing = OldTexText("nothing") nothing.scale(0.9) very = quote.get_part_by_tex("very") nothing.shift(very[0].get_left() - nothing[0].get_left()) nothing.set_color(RED) for word in quote: if word is very: self.add_foreground_mobjects(nothing) self.play(ShowWord(nothing)) self.wait(0.2) nothing.sort(lambda p: -p[0]) self.play(LaggedStartMap( FadeOut, nothing, run_time=1 )) self.remove_foreground_mobject(nothing) back_word = word.copy().set_stroke(BLACK, 5) self.add_foreground_mobjects(back_word, word) self.play( ShowWord(back_word), ShowWord(word), ) self.wait(0.005 * len(word)**1.5) self.wait() # Show thumbnails images = Group( ImageMobject("Calculus_Thumbnail"), ImageMobject("Fourier_Thumbnail"), ) for image in images: image.set_height(3) images.arrange(RIGHT, buff=LARGE_BUFF) images.to_edge(DOWN, buff=LARGE_BUFF) images[1].move_to(images[0]) crosses = VGroup(*list(map(Cross, images))) crosses.set_stroke("RED", 10) for image, cross in zip(images, crosses): image.rect = SurroundingRectangle( image, stroke_width=3, stroke_color=WHITE, buff=0 ) cross.scale(1.1) self.play( FadeInFromDown(images[0]), FadeInFromDown(images[0].rect) ) self.play(ShowCreation(crosses[0])) self.wait() self.play( FadeOutAndShiftDown(images[0]), FadeOutAndShiftDown(images[0].rect), FadeOutAndShiftDown(crosses[0]), FadeInFromDown(images[1]), FadeInFromDown(images[1].rect), ) self.play(ShowCreation(crosses[1])) self.wait() class LostLecturePicture(TODOStub): CONFIG = {"camera_config": {"background_opacity": 1}} def construct(self): picture = ImageMobject("Feynman_teaching") picture.set_height(FRAME_WIDTH) picture.to_corner(UL, buff=0) picture.fade(0.5) self.play( picture.to_corner, DR, {"buff": 0}, picture.shift, 1.5 * DOWN, path_arc=60 * DEGREES, run_time=20, rate_func=bezier([0, 0, 1, 1]) ) class AskAboutInfiniteIntelligence(TeacherStudentsScene): def construct(self): self.student_says( "Infinite intelligence?", target_mode="confused" ) self.play( self.change_students("horrified", "confused", "sad"), self.teacher.change, "happy", ) self.wait() self.teacher_says( "Stay focused, \\\\ go full screen, \\\\ and you'll be fine.", added_anims=[self.change_students(*["happy"] * 3)] ) self.wait() self.look_at(self.screen) self.wait(5) class TableOfContents(Scene): def construct(self): items = VGroup( OldTexText("How the ellipse will arise"), OldTexText("Kepler's 2nd law"), OldTexText("The shape of velocities"), ) items.arrange( DOWN, buff=LARGE_BUFF, aligned_edge=LEFT ) items.to_edge(LEFT, buff=1.5) for item in items: item.add(Dot().next_to(item, LEFT)) item.generate_target() item.target.set_fill(GREY, opacity=0.5) title = Title("The plan") scale_factor = 1.2 self.add(title) self.play(LaggedStartMap( FadeIn, items, run_time=1, lag_ratio=0.7, )) self.wait() for item in items: other_items = VGroup(*[m for m in items if m is not item]) new_item = item.copy() new_item.scale(scale_factor, about_edge=LEFT) new_item.set_fill(WHITE, 1) self.play( Transform(item, new_item), *list(map(MoveToTarget, other_items)) ) self.wait() class DrawEllipseOverlay(Scene): def construct(self): ellipse = Circle() ellipse.stretch_to_fit_width(7.0) ellipse.stretch_to_fit_height(3.8) ellipse.shift(1.05 * UP + 0.48 * LEFT) ellipse.set_stroke(RED, 8) image = ImageMobject( os.path.join( get_image_output_directory(self.__class__), "HeldUpEllipse.jpg" ) ) image.set_height(FRAME_HEIGHT) # self.add(image) self.play(ShowCreation(ellipse)) self.wait() self.play(FadeOut(ellipse)) class ShowEllipseDefiningProperty(Scene): CONFIG = { "camera_config": {"background_opacity": 1}, "ellipse_color": BLUE, "a": 4.0, "b": 3.0, "distance_labels_scale_factor": 1.0, } def construct(self): self.add_ellipse() self.add_focal_lines() self.add_distance_labels() self.label_foci() self.label_focal_sum() def add_ellipse(self): a = self.a b = self.b ellipse = Circle(radius=a, color=self.ellipse_color) ellipse.stretch(fdiv(b, a), dim=1) ellipse.to_edge(LEFT, buff=LARGE_BUFF) self.ellipse = ellipse self.add(ellipse) def add_focal_lines(self): push_pins = VGroup(*[ SVGMobject( file_name="push_pin", color=GREY_B, fill_opacity=0.8, height=0.5, ).move_to(point, DR).shift(0.05 * RIGHT) for point in self.get_foci() ]) dot = Dot() dot.scale(0.5) position_tracker = ValueTracker(0.125) dot_update = Mobject.add_updater( dot, lambda d: d.move_to( self.ellipse.point_from_proportion( position_tracker.get_value() % 1 ) ) ) always_shift(position_tracker, rate=0.05) lines, lines_update_animation = self.get_focal_lines_and_update( self.get_foci, dot ) self.add_foreground_mobjects(push_pins, dot) self.add(dot_update) self.play(LaggedStartMap( FadeInFrom, push_pins, lambda m: (m, 2 * UP + LEFT), run_time=1, lag_ratio=0.75 )) self.play(ShowCreation(lines)) self.add(lines_update_animation) self.add(position_tracker) self.wait(2) self.position_tracker = position_tracker self.focal_lines = lines def add_distance_labels(self): lines = self.focal_lines colors = [YELLOW, PINK] distance_labels, distance_labels_animation = \ self.get_distance_labels_and_update(lines, colors) sum_expression, numbers, number_updates = \ self.get_sum_expression_and_update( lines, colors, lambda mob: mob.to_corner(UR) ) sum_expression_fading_rect = BackgroundRectangle( sum_expression, fill_opacity=1 ) sum_rect = SurroundingRectangle(numbers[-1]) constant_words = OldTexText("Stays constant") constant_words.next_to(sum_rect, DOWN, aligned_edge=RIGHT) VGroup(sum_rect, constant_words).set_color(BLUE) self.add(distance_labels_animation) self.add(*number_updates) self.add(sum_expression) self.add_foreground_mobjects(sum_expression_fading_rect) self.play( VFadeIn(distance_labels), FadeOut(sum_expression_fading_rect), ) self.remove_foreground_mobject(sum_expression_fading_rect) self.wait(7) self.play( ShowCreation(sum_rect), Write(constant_words) ) self.wait(7) self.play(FadeOut(sum_rect), FadeOut(constant_words)) self.sum_expression = sum_expression self.sum_rect = sum_rect def label_foci(self): foci = self.get_foci() focus_words = VGroup(*[ OldTexText("Focus").next_to(focus, DOWN) for focus in foci ]) foci_word = OldTexText("Foci") foci_word.move_to(focus_words) foci_word.shift(MED_SMALL_BUFF * UP) connecting_lines = VGroup(*[ Arrow( foci_word.get_edge_center(-edge), focus_word.get_edge_center(edge), buff=MED_SMALL_BUFF, stroke_width=2, ) for focus_word, edge in zip(focus_words, [LEFT, RIGHT]) ]) translation = OldTexText( "``Foco'' $\\rightarrow$ Fireplace" ) translation.to_edge(RIGHT) translation.shift(UP) sun = ImageMobject("sun", height=0.5) sun.move_to(foci[0]) sun_animation = SunAnimation(sun) self.play(FadeInFromDown(focus_words)) self.wait(2) self.play( ReplacementTransform(focus_words.copy(), foci_word), ) self.play(*list(map(ShowCreation, connecting_lines))) for word in list(focus_words) + [foci_word]: word.add_background_rectangle() self.add_foreground_mobjects(word) self.wait(4) self.play(Write(translation)) self.wait(2) self.play(GrowFromCenter(sun)) self.add(sun_animation) self.wait(8) def label_focal_sum(self): sum_rect = self.sum_rect focal_sum = OldTexText("``Focal sum''") focal_sum.scale(1.5) focal_sum.next_to(sum_rect, DOWN, aligned_edge=RIGHT) VGroup(sum_rect, focal_sum).set_color(RED) footnote = OldTexText( """ \\Large *This happens to equal the longest distance across the ellipse, so perhaps the more standard terminology would be ``major axis'', but I want some terminology that conveys the idea of adding two distances to the foci. """, alignment="", ) footnote.set_width(5) footnote.to_corner(DR) footnote.set_stroke(WHITE, 0.5) self.play(FadeInFromDown(focal_sum)) self.play(Write(sum_rect)) self.wait() self.play(FadeIn(footnote)) self.wait(2) self.play(FadeOut(footnote)) self.wait(8) # Helpers def get_foci(self): ellipse = self.ellipse a = ellipse.get_width() / 2 b = ellipse.get_height() / 2 c = np.sqrt(a**2 - b**2) center = ellipse.get_center() return [ center + c * RIGHT, center + c * LEFT, ] def get_focal_lines_and_update(self, get_foci, focal_sum_point): lines = VGroup(Line(LEFT, RIGHT), Line(LEFT, RIGHT)) lines.set_stroke(width=2) def update_lines(lines): foci = get_foci() for line, focus in zip(lines, foci): line.put_start_and_end_on( focus, focal_sum_point.get_center() ) lines[1].rotate(np.pi) lines_update_animation = Mobject.add_updater( lines, update_lines ) return lines, lines_update_animation def get_distance_labels_and_update(self, lines, colors): distance_labels = VGroup( DecimalNumber(0), DecimalNumber(0), ) for label in distance_labels: label.scale(self.distance_labels_scale_factor) def update_distance_labels(labels): for label, line, color in zip(labels, lines, colors): angle = -line.get_angle() if np.abs(angle) > 90 * DEGREES: angle = 180 * DEGREES + angle line.rotate(angle, about_point=ORIGIN) new_decimal = DecimalNumber(line.get_length()) new_decimal.scale( self.distance_labels_scale_factor ) max_width = 0.6 * line.get_width() if new_decimal.get_width() > max_width: new_decimal.set_width(max_width) new_decimal.next_to(line, UP, SMALL_BUFF) new_decimal.set_color(color) new_decimal.add_to_back( new_decimal.copy().set_stroke(BLACK, 5) ) VGroup(new_decimal, line).rotate( -angle, about_point=ORIGIN ) label.submobjects = list(new_decimal.submobjects) distance_labels_animation = Mobject.add_updater( distance_labels, update_distance_labels ) return distance_labels, distance_labels_animation def get_sum_expression_and_update(self, lines, colors, sum_position_func): sum_expression = OldTex("0.00", "+", "0.00", "=", "0.00") sum_position_func(sum_expression) number_refs = sum_expression.get_parts_by_tex("0.00") number_refs.set_fill(opacity=0) numbers = VGroup(*[DecimalNumber(0) for ref in number_refs]) for number, color in zip(numbers, colors): number.set_color(color) # Not the most elegant... number_updates = [ ContinualChangingDecimal( numbers[0], lambda a: lines[0].get_length(), position_update_func=lambda m: m.move_to( number_refs[1], LEFT ) ), ContinualChangingDecimal( numbers[1], lambda a: lines[1].get_length(), position_update_func=lambda m: m.move_to( number_refs[0], LEFT ) ), ContinualChangingDecimal( numbers[2], lambda a: sum(map(Line.get_length, lines)), position_update_func=lambda m: m.move_to( number_refs[2], LEFT ) ), ] return sum_expression, numbers, number_updates class GeometryProofLand(Scene): CONFIG = { "colors": [ PINK, RED, YELLOW, GREEN, GREEN_A, BLUE, MAROON_E, MAROON_B, YELLOW, BLUE, ], "text": "Geometry proof land", } def construct(self): word = self.get_geometry_proof_land_word() word_outlines = word.deepcopy() word_outlines.set_fill(opacity=0) word_outlines.set_stroke(WHITE, 1) colors = list(self.colors) random.shuffle(colors) word_outlines.set_color_by_gradient(*colors) word_outlines.set_stroke(width=5) circles = VGroup() for letter in word: circle = Circle() # circle = letter.copy() circle.replace(letter, dim_to_match=1) circle.scale(3) circle.set_stroke(WHITE, 0) circle.set_fill(letter.get_color(), 0) circles.add(circle) circle.target = letter self.play( LaggedStartMap(MoveToTarget, circles), run_time=2 ) self.add(word_outlines, circles) self.play(LaggedStartMap( FadeIn, word_outlines, run_time=3, rate_func=there_and_back, ), Animation(circles)) self.wait() def get_geometry_proof_land_word(self): word = OldTexText(self.text) word.rotate(-90 * DEGREES) word.scale(0.25) word.shift(3 * RIGHT) word.apply_complex_function(np.exp) word.rotate(90 * DEGREES) word.set_width(9) word.center() word.to_edge(UP) word.set_color_by_gradient(*self.colors) word.set_background_stroke(width=0) return word class ProveEllipse(ShowEmergingEllipse, ShowEllipseDefiningProperty): CONFIG = { "eccentricity_vector": 1.5 * RIGHT, "ellipse_color": PINK, "distance_labels_scale_factor": 0.7, } def construct(self): self.setup_ellipse() self.hypothesize_foci() self.setup_and_show_focal_sum() self.show_circle_radius() self.limit_to_just_one_line() self.look_at_perpendicular_bisector() self.show_orbiting_planet() def setup_ellipse(self): circle = self.circle = self.get_circle() circle.to_edge(LEFT) ep = self.get_eccentricity_point() ep_dot = self.ep_dot = Dot(ep, color=YELLOW) lines = self.lines = self.get_lines() for line in lines: line.save_state() ghost_lines = self.ghost_lines = self.get_ghost_lines(lines) ellipse = self.ellipse = self.get_ellipse() self.add(ghost_lines, circle, lines, ep_dot) self.play( LaggedStartMap(MoveToTarget, lines), Animation(ep_dot), ) self.play(ShowCreation(ellipse)) self.wait() def hypothesize_foci(self): circle = self.circle ghost_lines = self.ghost_lines ghost_lines_copy = ghost_lines.copy().set_stroke(YELLOW, 3) center = circle.get_center() center_dot = Dot(center, color=RED) # ep = self.get_eccentricity_point() ep_dot = self.ep_dot dots = VGroup(center_dot, ep_dot) center_label = OldTexText("Circle center") ep_label = OldTexText("Eccentric point") labels = VGroup(center_label, ep_label) vects = [UL, DR] arrows = VGroup() for label, dot, vect in zip(labels, dots, vects): label.next_to(dot, vect, MED_LARGE_BUFF) label.match_color(dot) label.add_to_back( label.copy().set_stroke(BLACK, 5) ) arrow = Arrow( label.get_corner(-vect), dot.get_corner(vect), buff=SMALL_BUFF ) arrow.match_color(dot) arrow.add_to_back(arrow.copy().set_stroke(BLACK, 5)) arrows.add(arrow) labels_target = labels.copy() labels_target.arrange( DOWN, aligned_edge=LEFT ) guess_start = OldTexText("Guess: Foci = ") brace = Brace(labels_target, LEFT) full_guess = VGroup(guess_start, brace, labels_target) full_guess.arrange(RIGHT) full_guess.to_corner(UR) self.play( FadeInFromDown(labels[1]), GrowArrow(arrows[1]), ) self.play(LaggedStartMap( ShowPassingFlash, ghost_lines_copy )) self.wait() self.play(ReplacementTransform(circle.copy(), center_dot)) self.add_foreground_mobjects(dots) self.play( FadeInFromDown(labels[0]), GrowArrow(arrows[0]), ) self.wait() self.play( Write(guess_start), GrowFromCenter(brace), run_time=1 ) self.play( ReplacementTransform(labels.copy(), labels_target) ) self.wait() self.play(FadeOut(labels), FadeOut(arrows)) self.center_dot = center_dot def setup_and_show_focal_sum(self): circle = self.circle ellipse = self.ellipse focal_sum_point = VectorizedPoint() focal_sum_point.move_to(circle.get_top()) dots = [self.ep_dot, self.center_dot] colors = list(map(Mobject.get_color, dots)) def get_foci(): return list(map(Mobject.get_center, dots)) focal_lines, focal_lines_update_animation = \ self.get_focal_lines_and_update(get_foci, focal_sum_point) distance_labels, distance_labels_update_animation = \ self.get_distance_labels_and_update(focal_lines, colors) sum_expression, numbers, number_updates = \ self.get_sum_expression_and_update( focal_lines, colors, lambda mob: mob.to_edge(RIGHT).shift(UP) ) to_add = self.focal_sum_things_to_add = [ focal_lines_update_animation, distance_labels_update_animation, sum_expression, ] + list(number_updates) self.play( ShowCreation(focal_lines), Write(distance_labels), FadeIn(sum_expression), Write(numbers), run_time=1 ) self.wait() self.add(*to_add) points = [ ellipse.get_top(), circle.point_from_proportion(0.2), ellipse.point_from_proportion(0.2), ellipse.point_from_proportion(0.4), ] for point in points: self.play( focal_sum_point.move_to, point ) self.wait() self.remove(*to_add) self.play(*list(map(FadeOut, [ focal_lines, distance_labels, sum_expression, numbers ]))) self.set_variables_as_attrs( focal_lines, focal_lines_update_animation, focal_sum_point, distance_labels, distance_labels_update_animation, sum_expression, numbers, number_updates ) def show_circle_radius(self): circle = self.circle center = circle.get_center() point = circle.get_right() color = GREEN radius = Line(center, point, color=color) radius_measurement = DecimalNumber(radius.get_length()) radius_measurement.set_color(color) radius_measurement.next_to(radius, UP, SMALL_BUFF) radius_measurement.add_to_back( radius_measurement.copy().set_stroke(BLACK, 5) ) group = VGroup(radius, radius_measurement) group.rotate(30 * DEGREES, about_point=center) self.play(ShowCreation(radius)) self.play(Write(radius_measurement)) self.wait() self.play(Rotating( group, rate_func=smooth, run_time=7, about_point=center )) self.play(FadeOut(group)) def limit_to_just_one_line(self): lines = self.lines ghost_lines = self.ghost_lines ep_dot = self.ep_dot index = int(0.2 * len(lines)) line = lines[index] ghost_line = ghost_lines[index] to_fade = VGroup(*list(lines) + list(ghost_lines)) to_fade.remove(line, ghost_line) P_dot = Dot(line.saved_state.get_end()) P_label = OldTex("P") P_label.next_to(P_dot, UP, SMALL_BUFF) self.add_foreground_mobjects(self.ellipse) self.play(LaggedStartMap(Restore, lines)) self.play( FadeOut(to_fade), ghost_line.set_stroke, YELLOW, 3, line.set_stroke, WHITE, 3, ReplacementTransform(ep_dot.copy(), P_dot), ) self.play(FadeInFromDown(P_label)) self.wait() for l in lines: l.generate_target() l.target.rotate( 90 * DEGREES, about_point=l.get_center() ) self.set_variables_as_attrs( line, ghost_line, P_dot, P_label ) def look_at_perpendicular_bisector(self): # Alright, this method's gonna blow up. Let's go! circle = self.circle ellipse = self.ellipse ellipse.save_state() lines = self.lines line = self.line ghost_lines = self.ghost_lines ghost_line = self.ghost_line P_dot = self.P_dot P_label = self.P_label elbow = self.get_elbow(line) self.play( MoveToTarget(line, path_arc=90 * DEGREES), ShowCreation(elbow) ) # Perpendicular bisector label label = OldTexText("``Perpendicular bisector''") label.scale(0.75) label.set_color(YELLOW) label.next_to(ORIGIN, UP, MED_SMALL_BUFF) label.add_background_rectangle() angle = line.get_angle() + np.pi label.rotate(angle, about_point=ORIGIN) label.shift(line.get_center()) # Dot defining Q point Q_dot = Dot(color=GREEN) Q_dot.move_to(self.focal_sum_point) focal_sum_point_animation = turn_animation_into_updater( MaintainPositionRelativeTo( self.focal_sum_point, Q_dot ) ) self.add(focal_sum_point_animation) Q_dot.move_to(line.point_from_proportion(0.9)) Q_dot.save_state() Q_label = OldTex("Q") Q_label.scale(0.7) Q_label.match_color(Q_dot) Q_label.add_to_back(Q_label.copy().set_stroke(BLACK, 5)) Q_label.next_to(Q_dot, UL, buff=0) Q_label_animation = turn_animation_into_updater( MaintainPositionRelativeTo(Q_label, Q_dot) ) # Pretty hacky... def distance_label_shift_update(label): line = self.focal_lines[0] if line.get_end()[0] > line.get_start()[0]: vect = label.get_center() - line.get_center() label.shift(-2 * vect) distance_label_shift_update_animation = Mobject.add_updater( self.distance_labels[0], distance_label_shift_update ) self.focal_sum_things_to_add.append( distance_label_shift_update_animation ) # Define QP line QP_line = Line(LEFT, RIGHT) QP_line.match_style(self.focal_lines) QP_line_update = Mobject.add_updater( QP_line, lambda l: l.put_start_and_end_on( Q_dot.get_center(), P_dot.get_center(), ) ) QE_line = Line(LEFT, RIGHT) QE_line.set_stroke(YELLOW, 3) QE_line_update = Mobject.add_updater( QE_line, lambda l: l.put_start_and_end_on( Q_dot.get_center(), self.get_eccentricity_point() ) ) # Define similar triangles triangles = VGroup(*[ Polygon( Q_dot.get_center(), line.get_center(), end_point, fill_opacity=1, ) for end_point in [ P_dot.get_center(), self.get_eccentricity_point() ] ]) triangles.set_color_by_gradient(RED_C, COBALT) triangles.set_stroke(WHITE, 2) # Add even more distant label updates def distance_label_rotate_update(label): QE_line_update.update(0) angle = QP_line.get_angle() - QE_line.get_angle() label.rotate(angle, about_point=Q_dot.get_center()) return label distance_label_rotate_update_animation = Mobject.add_updater( self.distance_labels[0], distance_label_rotate_update ) # Hook up line to P to P_dot radial_line = DashedLine(ORIGIN, 3 * RIGHT) radial_line_update = UpdateFromFunc( radial_line, lambda l: l.put_start_and_end_on( circle.get_center(), P_dot.get_center() ) ) def put_dot_at_intersection(dot): point = line_intersection( line.get_start_and_end(), radial_line.get_start_and_end() ) dot.move_to(point) return dot keep_Q_dot_at_intersection = UpdateFromFunc( Q_dot, put_dot_at_intersection ) Q_dot.restore() ghost_line_update_animation = UpdateFromFunc( ghost_line, lambda l: l.put_start_and_end_on( self.get_eccentricity_point(), P_dot.get_center() ) ) def update_perp_bisector(line): line.scale(ghost_line.get_length() / line.get_length()) line.rotate(ghost_line.get_angle() - line.get_angle()) line.rotate(90 * DEGREES) line.move_to(ghost_line) perp_bisector_update_animation = UpdateFromFunc( line, update_perp_bisector ) elbow_update_animation = UpdateFromFunc( elbow, lambda e: Transform(e, self.get_elbow(ghost_line)).update(1) ) P_dot_movement_updates = [ radial_line_update, keep_Q_dot_at_intersection, MaintainPositionRelativeTo( P_label, P_dot ), ghost_line_update_animation, perp_bisector_update_animation, elbow_update_animation, ] # Comment for tangency sum_rect = SurroundingRectangle( self.numbers[-1] ) tangency_comment = OldTexText( "Always $\\ge$ radius" ) tangency_comment.next_to( sum_rect, DOWN, aligned_edge=RIGHT ) VGroup(sum_rect, tangency_comment).set_color(GREEN) # Why is this needed?!? self.add(*self.focal_sum_things_to_add) self.wait(0.01) self.remove(*self.focal_sum_things_to_add) # Show label self.play(Write(label)) self.wait() # Show Q_dot moving about a little self.play( FadeOut(label), FadeIn(self.focal_lines), FadeIn(self.distance_labels), FadeIn(self.sum_expression), FadeIn(self.numbers), ellipse.set_stroke, {"width": 0.5}, ) self.add(*self.focal_sum_things_to_add) self.play( FadeInFromDown(Q_label), GrowFromCenter(Q_dot) ) self.wait() self.add_foreground_mobjects(Q_dot) self.add(Q_label_animation) self.play( Q_dot.move_to, line.point_from_proportion(0.05), rate_func=there_and_back, run_time=4 ) self.wait() # Show similar triangles self.play( FadeIn(triangles[0]), ShowCreation(QP_line), Animation(elbow), ) self.add(QP_line_update) for i in range(3): self.play( FadeIn(triangles[(i + 1) % 2]), FadeOut(triangles[i % 2]), Animation(self.distance_labels), Animation(elbow) ) self.play( FadeOut(triangles[1]), Animation(self.distance_labels) ) # Move first distance label # (boy, this got messy...hopefully no one ever has # to read this.) angle = QP_line.get_angle() - QE_line.get_angle() Q_point = Q_dot.get_center() for x in range(2): self.play(ShowCreationThenDestruction(QE_line)) distance_label_copy = self.distance_labels[0].copy() self.play( ApplyFunction( distance_label_rotate_update, distance_label_copy, path_arc=angle ), Rotate(QE_line, angle, about_point=Q_point) ) self.play(FadeOut(QE_line)) self.remove(distance_label_copy) self.add(distance_label_rotate_update_animation) self.focal_sum_things_to_add.append( distance_label_rotate_update_animation ) self.wait() self.play( Q_dot.move_to, line.point_from_proportion(0), run_time=4, rate_func=there_and_back ) # Trace out ellipse self.play(ShowCreation(radial_line)) self.wait() self.play( ApplyFunction(put_dot_at_intersection, Q_dot), run_time=3, ) self.wait() self.play( Rotating( P_dot, about_point=circle.get_center(), rate_func=bezier([0, 0, 1, 1]), run_time=10, ), ellipse.restore, *P_dot_movement_updates ) self.wait() # Talk through tangency self.play( ShowCreation(sum_rect), Write(tangency_comment), ) points = [line.get_end(), line.get_start(), Q_dot.get_center()] run_times = [1, 3, 2] for point, run_time in zip(points, run_times): self.play(Q_dot.move_to, point, run_time=run_time) self.wait() self.remove(*self.focal_sum_things_to_add) self.play(*list(map(FadeOut, [ radial_line, QP_line, P_dot, P_label, Q_dot, Q_label, elbow, self.distance_labels, self.numbers, self.sum_expression, sum_rect, tangency_comment, ]))) self.wait() # Show all lines lines.remove(line) ghost_lines.remove(ghost_line) for line in lines: line.generate_target() line.target.rotate(90 * DEGREES) self.play( LaggedStartMap(FadeIn, ghost_lines), LaggedStartMap(FadeIn, lines), ) self.play(LaggedStartMap(MoveToTarget, lines)) self.wait() def show_orbiting_planet(self): ellipse = self.ellipse ep_dot = self.ep_dot planet = ImageMobject("earth") planet.set_height(0.25) orbit = Orbiting(planet, ep_dot, ellipse) lines = self.lines def update_lines(lines): for gl, line in zip(self.ghost_lines, lines): intersection = line_intersection( [self.circle.get_center(), gl.get_end()], line.get_start_and_end() ) distance = get_norm( intersection - planet.get_center() ) if distance < 0.025: line.set_stroke(BLUE, 3) self.add(line) else: line.set_stroke(WHITE, 1) lines_update_animation = Mobject.add_updater( lines, update_lines ) self.add(orbit) self.add(lines_update_animation) self.add_foreground_mobjects(planet) self.wait(12) class Enthusiast(Scene): def construct(self): randy = Randolph(color=BLUE_C) randy.flip() self.play(randy.change, "surprised") self.play(Blink(randy)) self.wait() class SimpleThinking(Scene): def construct(self): randy = Randolph(color=BLUE_C) randy.flip() self.play(randy.change, "thinking", 3 * UP) self.play(Blink(randy)) self.wait() self.play(randy.change, "hooray", 3 * UP) self.play(Blink(randy)) self.wait() class EndOfGeometryProofiness(GeometryProofLand): def construct(self): geometry_word = self.get_geometry_proof_land_word() orbital_mechanics = OldTexText("Orbital Mechanics") orbital_mechanics.scale(1.5) orbital_mechanics.to_edge(UP) underline = Line(LEFT, RIGHT) underline.match_width(orbital_mechanics) underline.next_to(orbital_mechanics, DOWN, SMALL_BUFF) self.play(LaggedStartMap(FadeOutAndShiftDown, geometry_word)) self.play(FadeInFromDown(orbital_mechanics)) self.play(ShowCreation(underline)) self.wait() class KeplersSecondLaw(AskAboutEllipses): CONFIG = { "sun_center": 4 * RIGHT + 0.75 * DOWN, "animate_sun": True, "a": 5.0, "b": 3.0, "ellipse_stroke_width": 2, "area_color": COBALT, "area_opacity": 0.75, "arc_color": YELLOW, "arc_stroke_width": 3, "n_sample_sweeps": 5, "fade_sample_areas": True, } def construct(self): self.add_title() self.add_sun() self.add_orbit() self.add_foreground_mobjects(self.comet) self.show_several_sweeps() self.contrast_close_to_far() def add_title(self): title = OldTexText("Kepler's 2nd law:") title.scale(1.0) title.to_edge(UP) self.add(title) self.title = title subtitle = OldTexText( "Orbits sweep a constant area per unit time" ) subtitle.next_to(title, DOWN, buff=0.2) subtitle.set_color(BLUE) self.add(subtitle) def show_several_sweeps(self): shown_areas = VGroup() for x in range(self.n_sample_sweeps): self.wait() area = self.show_area_sweep() shown_areas.add(area) self.wait() if self.fade_sample_areas: self.play(FadeOut(shown_areas)) def contrast_close_to_far(self): orbit = self.orbit sun_point = self.sun.get_center() start_prop = 0.9 self.wait_until_proportion(start_prop) self.show_area_sweep() end_prop = orbit.proportion arc = self.get_arc(start_prop, end_prop) radius = Line(sun_point, arc.get_points()[0]) radius.set_color(WHITE) radius_words = self.get_radius_words(radius, "Short") radius_words.next_to(radius.get_center(), LEFT, SMALL_BUFF) arc_words = OldTexText("Long arc") arc_words.rotate(90 * DEGREES) arc_words.scale(0.5) arc_words.next_to(RIGHT, RIGHT) arc_words.apply_complex_function(np.exp) arc_words.scale(0.8) arc_words.next_to( arc, RIGHT, buff=-SMALL_BUFF ) arc_words.shift(4 * SMALL_BUFF * DOWN) arc_words.match_color(arc) # Show stubby arc # self.remove(orbit) # self.add(self.comet) self.play( ShowCreation(radius), Write(radius_words), ) self.play( ShowCreation(arc), Write(arc_words) ) # Show narrow arc # (Code repetition...uck) start_prop = 0.475 self.wait_until_proportion(start_prop) self.show_area_sweep() end_prop = orbit.proportion short_arc = self.get_arc(start_prop, end_prop) long_radius = Line(sun_point, short_arc.get_points()[0]) long_radius.set_color(WHITE) long_radius_words = self.get_radius_words(long_radius, "Long") short_arc_words = OldTexText("Short arc") short_arc_words.scale(0.5) short_arc_words.rotate(90 * DEGREES) short_arc_words.next_to(short_arc, LEFT, SMALL_BUFF) short_arc_words.match_color(short_arc) self.play( ShowCreation(long_radius), Write(long_radius_words), ) self.play( ShowCreation(short_arc), Write(short_arc_words) ) self.wait(15) # Helpers def show_area_sweep(self, time=1.0): orbit = self.orbit start_prop = orbit.proportion area = self.get_area(start_prop, start_prop) area_update = UpdateFromFunc( area, lambda a: Transform( a, self.get_area(start_prop, orbit.proportion) ).update(1) ) self.play(area_update, run_time=time) return area def get_area(self, prop1, prop2): """ Return a mobject illustrating the area swept out between a point prop1 of the way along the ellipse, and prop2 of the way. """ sun_point = self.sun.get_center() arc = self.get_arc(prop1, prop2) # Add lines from start result = VMobject() result.append_vectorized_mobject( Line(sun_point, arc.get_points()[0]) ) result.append_vectorized_mobject(arc) result.append_vectorized_mobject( Line(arc.get_points()[-1], sun_point) ) result.set_stroke(WHITE, width=0) result.set_fill( self.area_color, self.area_opacity, ) return result def get_arc(self, prop1, prop2): ellipse = self.get_ellipse() prop1 = prop1 % 1.0 prop2 = prop2 % 1.0 if prop2 > prop1: arc = VMobject().pointwise_become_partial( ellipse, prop1, prop2 ) elif prop1 > prop2: arc, arc_extension = [ VMobject().pointwise_become_partial( ellipse, p1, p2 ) for p1, p2 in [(prop1, 1.0), (0.0, prop2)] ] arc.append_vectorized_mobject(arc_extension) else: arc = VectorizedPoint( ellipse.point_from_proportion(prop1) ) arc.set_stroke( self.arc_color, self.arc_stroke_width, ) return arc def wait_until_proportion(self, prop): if self.skip_animations: self.orbit.proportion = prop else: while (self.orbit.proportion % 1) < prop: self.wait(self.frame_duration) def get_radius_words(self, radius, adjective): radius_words = OldTexText( "%s radius" % adjective, ) min_width = 0.8 * radius.get_length() if radius_words.get_width() > min_width: radius_words.set_width(min_width) radius_words.match_color(radius) radius_words.next_to(ORIGIN, UP, SMALL_BUFF) angle = radius.get_angle() angle = ((angle + PI) % TAU) - PI if np.abs(angle) > PI / 2: angle += PI radius_words.rotate(angle, about_point=ORIGIN) radius_words.shift(radius.get_center()) return radius_words class NonEllipticalKeplersLaw(KeplersSecondLaw): CONFIG = { "animate_sun": True, "sun_center": 2 * RIGHT, "n_sample_sweeps": 10, } def construct(self): self.add_sun() self.add_orbit() self.show_several_sweeps() def add_orbit(self): sun = self.sun comet = ImageMobject("comet", height=0.5) orbit_shape = self.get_ellipse() orbit = self.orbit = Orbiting(comet, sun, orbit_shape) self.add(orbit_shape) self.add(orbit) arrow, arrow_update = self.get_force_arrow_and_update( comet ) alt_arrow_update = Mobject.add_updater( arrow, lambda a: a.scale( 1.0 / a.get_length(), about_point=a.get_start() ) ) self.add(arrow_update, alt_arrow_update) self.add_foreground_mobjects(comet, arrow) self.ellipse = orbit_shape def get_ellipse(self): orbit_shape = ParametricCurve( lambda t: (1 + 0.2 * np.sin(5 * TAU * t)) * np.array([ np.cos(TAU * t), np.sin(TAU * t), 0 ]) ) orbit_shape.set_height(7) orbit_shape.stretch(1.5, 0) orbit_shape.shift(LEFT) orbit_shape.set_stroke(GREY_B, 1) return orbit_shape class AngularMomentumArgument(KeplersSecondLaw): CONFIG = { "animate_sun": False, "sun_center": 4 * RIGHT + DOWN, "comet_start_point": 4 * LEFT, "comet_end_point": 5 * LEFT + DOWN, "comet_height": 0.3, } def construct(self): self.add_sun() self.show_small_sweep() self.show_sweep_dimensions() self.show_conservation_of_angular_momentum() def show_small_sweep(self): sun_center = self.sun_center comet_start = self.comet_start_point comet_end = self.comet_end_point triangle = Polygon( sun_center, comet_start, comet_end, fill_opacity=1, fill_color=COBALT, stroke_width=0, ) triangle.save_state() alt_triangle = Polygon( sun_center, interpolate(comet_start, comet_end, 0.9), comet_end ) alt_triangle.match_style(triangle) comet = self.get_comet() comet.move_to(comet_start) velocity_vector = Arrow( comet_start, comet_end, color=WHITE, buff=0 ) velocity_vector_label = OldTex("\\vec{\\textbf{v}}") velocity_vector_label.next_to( velocity_vector.get_center(), UL, buff=SMALL_BUFF ) small_time_label = OldTexText( "Small", "time", "$\\Delta t$", ) small_time_label.to_edge(UP) small = small_time_label.get_part_by_tex("Small") small_rect = SurroundingRectangle(small) self.add_foreground_mobjects(comet) self.play( ShowCreation( triangle, rate_func=lambda t: interpolate(1.0 / 3, 2.0 / 3, t) ), MaintainPositionRelativeTo( velocity_vector, comet ), MaintainPositionRelativeTo( velocity_vector_label, velocity_vector, ), ApplyMethod( comet.move_to, comet_end, rate_func=linear, ), run_time=2, ) self.play(Write(small_time_label), run_time=2) self.wait() self.play( Transform(triangle, alt_triangle), ShowCreation(small_rect), small.set_color, YELLOW, ) self.wait() self.play( Restore(triangle), FadeOut(small_rect), small.set_color, WHITE, ) self.wait() self.triangle = triangle self.comet = comet self.delta_t = small_time_label.get_part_by_tex( "$\\Delta t$" ) self.velocity_vector = velocity_vector self.small_time_label = small_time_label def show_sweep_dimensions(self): triangle = self.triangle # velocity_vector = self.velocity_vector delta_t = self.delta_t comet = self.comet triangle_points = triangle.get_anchors()[:3] top = triangle_points[1] area_label = OldTex( "\\text{Area}", "=", "\\frac{1}{2}", "\\text{Base}", "\\times", "\\text{Height}", ) area_label.set_color_by_tex_to_color_map({ "Base": PINK, "Height": YELLOW, }) area_label.to_edge(UP) equals = area_label.get_part_by_tex("=") area_expression = OldTex( "=", "\\frac{1}{2}", "R", "\\times", "\\vec{\\textbf{v}}_\\perp", "\\Delta t", ) area_expression.set_color_by_tex_to_color_map({ "R": PINK, "textbf{v}": YELLOW, }) area_expression.next_to(area_label, DOWN) area_expression.align_to(equals, LEFT) self.R_v_perp = VGroup(*area_expression[-4:-1]) self.R_v_perp_rect = SurroundingRectangle( self.R_v_perp, stroke_color=BLUE, fill_color=BLACK, fill_opacity=1, ) base = Line(triangle_points[2], triangle_points[0]) base.set_stroke(PINK, 3) base_point = line_intersection( base.get_start_and_end(), [top, top + DOWN] ) height = Line(top, base_point) height.set_stroke(YELLOW, 3) radius_label = OldTexText("Radius") radius_label.next_to(base, DOWN, SMALL_BUFF) radius_label.match_color(base) R_term = area_expression.get_part_by_tex("R") R_term.save_state() R_term.move_to(radius_label[0]) R_term.set_fill(opacity=0.5) v_perp = Arrow(*height.get_start_and_end(), buff=0) v_perp.set_color(YELLOW) v_perp.shift(comet.get_center() - v_perp.get_start()) v_perp_label = OldTex( "\\vec{\\textbf{v}}_\\perp" ) v_perp_label.set_color(YELLOW) v_perp_label.next_to(v_perp, RIGHT, buff=SMALL_BUFF) v_perp_delta_t = VGroup(v_perp_label.copy(), delta_t.copy()) v_perp_delta_t.generate_target() v_perp_delta_t.target.arrange(RIGHT, buff=SMALL_BUFF) v_perp_delta_t.target.next_to(height, RIGHT, SMALL_BUFF) self.small_time_label.add(v_perp_delta_t[1]) self.play( FadeInFromDown(area_label), self.small_time_label.scale, 0.5, self.small_time_label.to_corner, UL, ) self.wait() self.play( ShowCreation(base), Write(radius_label), ) self.wait() self.play(ShowCreation(height)) self.wait() self.play( GrowArrow(v_perp), Write(v_perp_label, run_time=1), ) self.wait() self.play(MoveToTarget(v_perp_delta_t)) self.wait() self.play(*[ ReplacementTransform( area_label.get_part_by_tex(tex).copy(), area_expression.get_part_by_tex(tex), ) for tex in ("=", "\\frac{1}{2}", "\\times") ]) self.play(Restore(R_term)) self.play(ReplacementTransform( v_perp_delta_t.copy(), VGroup(*area_expression[-2:]) )) self.wait() def show_conservation_of_angular_momentum(self): R_v_perp = self.R_v_perp R_v_perp_rect = self.R_v_perp_rect sun_center = self.sun_center comet = self.comet comet.save_state() vector_field = VectorField( get_force_field_func((sun_center, -1)) ) vector_field.set_fill(opacity=0.8) vector_field.sort( lambda p: -get_norm(p - sun_center) ) stays_constant = OldTexText("Stays constant") stays_constant.next_to( R_v_perp_rect, DR, buff=MED_LARGE_BUFF ) stays_constant.match_color(R_v_perp_rect) stays_constant_arrow = Arrow( stays_constant.get_left(), R_v_perp_rect.get_bottom(), color=R_v_perp_rect.get_color() ) sun_dot = Dot(sun_center, fill_opacity=0.25) big_dot = Dot(fill_opacity=0, radius=FRAME_WIDTH) R_v_perp.save_state() R_v_perp.generate_target() R_v_perp.target.to_edge(LEFT, buff=MED_LARGE_BUFF) lp, rp = parens = OldTex("()") lp.next_to(R_v_perp.target, LEFT) rp.next_to(R_v_perp.target, RIGHT) self.play(Transform( big_dot, sun_dot, run_time=1, remover=True )) self.wait() self.play( DrawBorderThenFill(R_v_perp_rect), Animation(R_v_perp), Write(stays_constant, run_time=1), GrowArrow(stays_constant_arrow), ) self.wait() foreground = VGroup(*self.get_mobjects()) self.play( LaggedStartMap(GrowArrow, vector_field), Animation(foreground) ) for x in range(3): self.play( LaggedStartMap( ApplyFunction, vector_field, lambda mob: (lambda m: m.scale(1.1).set_fill(opacity=1), mob), rate_func=there_and_back, run_time=1 ), Animation(foreground) ) self.play( FadeIn(parens), MoveToTarget(R_v_perp), ) self.play( comet.scale, 2, comet.next_to, parens, RIGHT, {"buff": SMALL_BUFF} ) self.wait() self.play( FadeOut(parens), R_v_perp.restore, comet.restore, ) self.wait(3) class KeplersSecondLawImage(KeplersSecondLaw): CONFIG = { "animate_sun": False, "n_sample_sweeps": 8, "fade_sample_areas": False, } def construct(self): self.add_sun() self.add_foreground_mobjects(self.sun) self.add_orbit() self.add_foreground_mobjects(self.comet) self.show_several_sweeps() class HistoryOfAngularMomentum(TeacherStudentsScene): CONFIG = { "camera_config": {"fill_opacity": 1} } def construct(self): am = VGroup(OldTexText("Angular momentum")) k2l = OldTexText("Kepler's 2nd law") arrow = Arrow(ORIGIN, RIGHT) group = VGroup(am, arrow, k2l) group.arrange(RIGHT) group.next_to(self.hold_up_spot, UL) k2l_image = ImageMobject("Kepler2ndLaw") k2l_image.match_width(k2l) k2l_image.next_to(k2l, UP) k2l.add(k2l_image) angular_momentum_formula = OldTex( "R", "\\times", "m", "\\vec{\\textbf{v}}_\\perp", ) angular_momentum_formula.set_color_by_tex_to_color_map({ "R": PINK, "v": YELLOW, }) angular_momentum_formula.next_to(am, UP) am.add(angular_momentum_formula) self.play( self.teacher.change, "raise_right_hand", FadeInFromDown(group), self.change_students(*3 * ["pondering"]) ) self.wait() self.play( am.next_to, arrow, RIGHT, {"index_of_submobject_to_align": 0}, k2l.next_to, arrow, LEFT, {"index_of_submobject_to_align": 0}, path_arc=90 * DEGREES, run_time=2 ) self.wait(3) class FeynmanRecountingNewton(Scene): CONFIG = { "camera_config": {"background_opacity": 1}, } def construct(self): feynman_teaching = ImageMobject("Feynman_teaching") feynman_teaching.set_width(FRAME_WIDTH) newton = ImageMobject("Newton") principia = ImageMobject("Principia_equal_area") images = [newton, principia] for image in images: image.set_height(5) newton.to_corner(UL) principia.next_to(newton, RIGHT) for image in images: image.rect = SurroundingRectangle( image, color=WHITE, buff=0, ) self.play(FadeInFromDown(feynman_teaching, run_time=2)) self.wait() self.play( FadeInFromDown(newton), FadeInFromDown(newton.rect), ) self.wait() self.play(*[ FadeIn( mob, direction=3 * LEFT ) for mob in (principia, principia.rect) ]) self.wait() class IntroduceShapeOfVelocities(AskAboutEllipses, MovingCameraScene): CONFIG = { "animate_sun": True, "sun_center": 2 * RIGHT, "a": 4.0, "b": 3.5, "num_vectors": 25, } def construct(self): self.setup_orbit() self.warp_orbit() self.reference_inverse_square_law() self.show_velocity_vectors() self.collect_velocity_vectors() def setup_orbit(self): self.add_sun() self.add_orbit() self.add_foreground_mobjects(self.comet) def warp_orbit(self): def func(z, c=3.5): return 1 * (np.exp((1.0 / c) * (z) + 1) - np.exp(1)) ellipse = self.ellipse ellipse.save_state() ellipse.generate_target() ellipse.target.stretch(0.7, 1) ellipse.target.apply_complex_function(func) ellipse.target.replace(ellipse, dim_to_match=1) self.wait(5) self.play(MoveToTarget(ellipse, run_time=2)) self.wait(5) def reference_inverse_square_law(self): ellipse = self.ellipse force_equation = OldTex( "F", "=", "{G", "M", "m", "\\over", "R^2}" ) force_equation.move_to(ellipse) force_equation.set_color_by_tex("F", YELLOW) force_arrow, force_arrow_update = self.get_force_arrow_and_update( self.comet, scale_factor=3, ) radial_line, radial_line_update = self.get_radial_line_and_update( self.comet ) self.add(radial_line_update) self.add(force_arrow_update) self.play( Restore(ellipse), Write(force_equation), UpdateFromAlphaFunc( force_arrow, lambda m, a: m.set_fill(opacity=a) ), UpdateFromAlphaFunc( radial_line, lambda m, a: m.set_stroke(width=a) ), ) self.wait(10) def show_velocity_vectors(self): alphas = np.linspace(0, 1, self.num_vectors, endpoint=False) vectors = VGroup(*[ self.get_velocity_vector(alpha) for alpha in alphas ]) moving_vector, moving_vector_animation = self.get_velocity_vector_and_update() self.play(LaggedStartMap( ShowCreation, vectors, lag_ratio=0.2, run_time=3, )) self.wait(5) self.add(moving_vector_animation) self.play( FadeOut(vectors), VFadeIn(moving_vector) ) self.wait(10) vectors.set_fill(opacity=0.5) self.play( LaggedStartMap(ShowCreation, vectors), Animation(moving_vector) ) self.wait(5) self.velocity_vectors = vectors self.moving_vector = moving_vector def collect_velocity_vectors(self): vectors = self.velocity_vectors.copy() frame = self.camera_frame ellipse = self.ellipse frame_shift = 2.5 * LEFT root_point = ellipse.get_left() + 3 * LEFT + 1 * UP vector_targets = VGroup() for vector in vectors: vector.target = Arrow( root_point, root_point + vector.get_vector(), buff=0, rectangular_stem_width=0.025, tip_length=0.2, color=vector.get_color(), ) vector.target.add_to_back( vector.target.copy().set_stroke(BLACK, 5) ) vector_targets.add(vector.target) circle = Circle(color=YELLOW) circle.replace(vector_targets) circle.scale(1.04) velocity_space = OldTexText("Velocity space") velocity_space.next_to(circle, UP) rect = SurroundingRectangle( VGroup(circle, velocity_space), buff=MED_LARGE_BUFF, color=WHITE, ) self.play( ApplyMethod( frame.shift, frame_shift, run_time=2, ), LaggedStartMap( MoveToTarget, vectors, run_time=4, ), FadeInFromDown(velocity_space), FadeInFromDown(rect), ) self.wait(2) self.play( ShowCreation(circle), Animation(vectors) ) self.wait(24) # Helpers def get_velocity_vector(self, alpha, d_alpha=0.01, scalar=3.0): norm = get_norm ellipse = self.ellipse sun_center = self.sun.get_center() min_length = 0.1 * scalar max_length = 0.5 * scalar p1, p2 = [ ellipse.point_from_proportion(a) for a in (alpha, alpha + d_alpha) ] vector = Arrow( p1, p2, buff=0 ) radius_vector = p1 - sun_center curr_v_perp = norm(np.cross( vector.get_vector(), radius_vector / norm(radius_vector) )) vector.scale( scalar / (norm(curr_v_perp) * norm(radius_vector)), about_point=vector.get_start() ) vector.set_color( interpolate_color( BLUE, RED, inverse_interpolate( min_length, max_length, vector.get_length() ) ) ) vector.add_to_back( vector.copy().set_stroke(BLACK, 5) ) return vector def get_velocity_vector_and_update(self): moving_vector = self.get_velocity_vector(0) def update_moving_vector(vector): new_vector = self.get_velocity_vector( self.orbit.proportion, ) Transform(vector, new_vector).update(1) moving_vector_animation = Mobject.add_updater( moving_vector, update_moving_vector ) return moving_vector, moving_vector_animation class AskWhy(TeacherStudentsScene): def construct(self): self.student_says( "Um...why?", target_mode="confused", index=2, bubble_config={"direction": LEFT}, ) self.play( self.teacher.change, "happy", self.change_students( "raise_left_hand", "sassy", "confused" ) ) self.wait(5) class FeynmanConfusedByNewton(Scene): def construct(self): pass class ShowEqualAngleSlices(IntroduceShapeOfVelocities): CONFIG = { "animate_sun": True, "theta": 30 * DEGREES, } def construct(self): self.setup_orbit() self.show_equal_angle_slices() self.ask_about_time_per_slice() self.areas_are_proportional_to_radius_squared() self.show_inverse_square_law() self.directly_compare_velocity_vectors() def setup_orbit(self): IntroduceShapeOfVelocities.setup_orbit(self) self.remove(self.orbit) self.add(self.comet) def show_equal_angle_slices(self): sun_center = self.sun.get_center() ellipse = self.ellipse def get_cos_angle_diff(v1, v2): return np.dot( v1 / get_norm(v1), v2 / get_norm(v2), ) lines = VGroup() angle_arcs = VGroup() thetas = VGroup() angles = np.arange(0, TAU, self.theta) for angle in angles: prop = angle / TAU vect = rotate_vector(RIGHT, angle) end_point = ellipse.point_from_proportion(prop) curr_cos = get_cos_angle_diff( end_point - sun_center, vect ) coss_diff = (1 - curr_cos) while abs(coss_diff) > 0.00001: d_prop = 0.001 alt_end = ellipse.point_from_proportion( (prop + d_prop) % 1 ) alt_cos = get_cos_angle_diff(alt_end - sun_center, vect) d_cos = (alt_cos - curr_cos) delta_prop = (coss_diff / d_cos) * d_prop prop += delta_prop end_point = ellipse.point_from_proportion(prop) curr_cos = get_cos_angle_diff(end_point - sun_center, vect) coss_diff = 1 - curr_cos line = Line(sun_center, end_point) line.prop = prop lines.add(line) angle_arc = AnnularSector( angle=self.theta, inner_radius=1, outer_radius=1.05, ) angle_arc.rotate(angle, about_point=ORIGIN) angle_arc.scale(0.5, about_point=ORIGIN) angle_arc.shift(sun_center) angle_arc.mid_angle = angle + self.theta / 2 angle_arcs.add(angle_arc) theta = OldTex("\\theta") theta.scale(0.6) vect = rotate_vector(RIGHT, angle_arc.mid_angle) theta.move_to( angle_arc.get_center() + 0.2 * vect ) thetas.add(theta) arcs = VGroup() wedges = VGroup() for l1, l2 in adjacent_pairs(lines): arc = VMobject() arc.pointwise_become_partial( ellipse, l1.prop, (l2.prop or 1.0) ) arcs.add(arc) wedge = VMobject() wedge.append_vectorized_mobject( Line(sun_center, arc.get_points()[0]) ) wedge.append_vectorized_mobject(arc) wedge.append_vectorized_mobject( Line(arc.get_points()[-1], sun_center) ) wedges.add(wedge) lines.set_stroke(GREY_B, 2) angle_arcs.set_color_by_gradient( YELLOW, BLUE, RED, PINK, YELLOW ) arcs.set_color_by_gradient(BLUE, YELLOW) wedges.set_stroke(width=0) wedges.set_fill(opacity=1) wedges.set_color_by_gradient(BLUE, COBALT, BLUE_E, BLUE) kwargs = { "run_time": 6, "lag_ratio": 0.2, "rate_func": there_and_back, } faders = VGroup(wedges, angle_arcs, thetas) faders.set_fill(opacity=0.4) thetas.set_fill(opacity=0) self.play( FadeIn(faders), *list(map(ShowCreation, lines)) ) self.play(*[ LaggedStartMap( ApplyMethod, fader, lambda m: (m.set_fill, {"opacity": 1}), **kwargs ) for fader in faders ] + [Animation(lines)]) self.wait() self.lines = lines self.wedges = wedges self.arcs = arcs self.angle_arcs = angle_arcs self.thetas = thetas def ask_about_time_per_slice(self): wedge1 = self.wedges[0] wedge2 = self.wedges[len(self.wedges) / 2] arc1 = self.arcs[0] arc2 = self.arcs[len(self.arcs) / 2] comet = self.comet frame = self.camera_frame words1 = OldTexText( "Time spent \\\\ traversing \\\\ this slice?" ) words2 = OldTexText("How about \\\\ this one?") words1.to_corner(UR) words2.next_to(wedge2, LEFT, MED_LARGE_BUFF) arrow1 = Arrow( words1.get_bottom(), wedge1.get_center() + wedge1.get_height() * DOWN / 2, color=WHITE, ) arrow2 = Arrow( words2.get_right(), wedge2.get_center() + wedge2.get_height() * UL / 4, color=WHITE ) foreground = VGroup( self.ellipse, self.angle_arcs, self.lines, comet, ) self.play( Write(words1), wedge1.set_fill, {"opacity": 1}, GrowArrow(arrow1), Animation(foreground), frame.scale, 1.2, ) self.play(MoveAlongPath(comet, arc1, rate_func=linear)) self.play( Write(words2), wedge2.set_fill, {"opacity": 1}, Write(arrow2), Animation(foreground), ) self.play(MoveAlongPath(comet, arc2, rate_func=linear, run_time=3)) self.wait() self.area_questions = VGroup(words1, words2) self.area_question_arrows = VGroup(arrow1, arrow2) self.highlighted_wedges = VGroup(wedge1, wedge2) def areas_are_proportional_to_radius_squared(self): wedges = self.highlighted_wedges wedge = wedges[1] frame = self.camera_frame ellipse = self.ellipse sun_center = self.sun.get_center() line = self.lines[len(self.lines) / 2] thick_line = line.copy().set_stroke(PINK, 4) radius_word = OldTexText("Radius") radius_word.next_to(thick_line, UP, SMALL_BUFF) radius_word.match_color(thick_line) arc = self.arcs[len(self.arcs) / 2] thick_arc = arc.copy().set_stroke(RED, 4) scaling_group = VGroup( wedge, thick_line, radius_word, thick_arc ) expression = OldTexText( "Time", "$\\propto$", "Area", "$\\propto$", "$(\\text{Radius})^2$" ) expression.next_to(ellipse, UP, LARGE_BUFF) prop_to_brace = Brace(expression[1], DOWN, buff=SMALL_BUFF) prop_to_words = OldTexText("(proportional to)") prop_to_words.scale(0.7) prop_to_words.next_to(prop_to_brace, DOWN, SMALL_BUFF) VGroup(prop_to_words, prop_to_brace).set_color(GREEN) self.play( Write(expression[:3]), frame.shift, 0.5 * UP, FadeInFromDown(prop_to_words), GrowFromCenter(prop_to_brace), ) self.wait(2) self.play( ShowCreation(thick_line), FadeInFromDown(radius_word) ) self.wait() self.play(ShowCreationThenDestruction(thick_arc)) self.play(ShowCreation(thick_arc)) self.wait() self.play(Write(expression[3:])) self.play( scaling_group.scale, 0.5, {"about_point": sun_center}, Animation(self.area_question_arrows), Animation(self.comet), rate_func=there_and_back, run_time=4, ) self.wait() expression.add(prop_to_brace, prop_to_words) self.proportionality_expression = expression def show_inverse_square_law(self): prop_exp = self.proportionality_expression comet = self.comet frame = self.camera_frame ellipse = self.ellipse orbit = self.orbit next_line = self.lines[(len(self.lines) / 2) + 1] arc = self.arcs[len(self.arcs) / 2] force_expression = OldTex( "ma", "=", "\\text{Force}", "\\propto", "\\frac{1}{(\\text{Radius})^2}" ) force_expression.next_to(ellipse, LEFT, MED_LARGE_BUFF) force_expression.align_to(prop_exp, UP) force_expression.set_color_by_tex("Force", YELLOW) acceleration_expression = OldTex( "a", "=", "{\\Delta v", "\\over", "\\Delta t}", "\\propto", "{1 \\over (\\text{Radius})^2}" ) acceleration_expression.next_to( force_expression, DOWN, buff=0.75, aligned_edge=LEFT ) delta_v_expression = OldTex( "\\Delta v}", "\\propto", "{\\Delta t", "\\over", "(\\text{Radius})^2}" ) delta_v_expression.next_to( acceleration_expression, DOWN, buff=0.75, aligned_edge=LEFT ) delta_t_numerator = delta_v_expression.get_part_by_tex( "\\Delta t" ) moving_R_squared = prop_exp.get_part_by_tex("Radius").copy() moving_R_squared.generate_target() moving_R_squared.target.move_to(delta_t_numerator, DOWN) moving_R_squared.target.set_color(GREEN) randy = Randolph() randy.next_to(force_expression, DOWN, LARGE_BUFF) force_vector, force_vector_update = self.get_force_arrow_and_update( comet, scale_factor=3, ) moving_vector, moving_vector_animation = self.get_velocity_vector_and_update() self.play( FadeOut(self.area_questions), FadeOut(self.area_question_arrows), FadeInFromDown(force_expression), frame.shift, 2 * LEFT, ) self.remove(*self.area_questions) self.play( randy.change, "confused", force_expression, VFadeIn(randy) ) self.wait(2) self.play( randy.change, "pondering", force_expression[0], ShowPassingFlashAround(force_expression[:2]), ) self.play(Blink(randy)) self.play( FadeInFromDown(acceleration_expression), randy.change, "hooray", force_expression, randy.shift, 2 * DOWN, ) self.wait(2) self.play(Blink(randy)) self.play(randy.change, "thinking") self.wait() self.play( comet.move_to, arc.get_points()[0], path_arc=90 * DEGREES ) force_vector_update.update(0) self.play( Blink(randy), GrowArrow(force_vector) ) self.add(force_vector_update) self.add_foreground_mobjects(comet) # Slightly hacky orbit treatment here... orbit.proportion = 0.5 moving_vector_animation.update(0) start_velocity_vector = moving_vector.copy() self.play( GrowArrow(start_velocity_vector), randy.look_at, moving_vector ) self.add(moving_vector_animation) self.add(orbit) while orbit.proportion < next_line.prop: self.wait(self.frame_duration) self.remove(orbit) self.add_foreground_mobjects(comet) self.wait(2) self.play( randy.change, "pondering", force_expression, randy.shift, 2 * DOWN, FadeInFromDown(delta_v_expression) ) self.play(Blink(randy)) self.wait(2) self.play( delta_t_numerator.scale, 1.5, {"about_edge": DOWN}, delta_t_numerator.set_color, YELLOW ) self.play(ShowCreationThenFadeAround(prop_exp[:-2])) self.play( delta_t_numerator.fade, 1, MoveToTarget(moving_R_squared), randy.change, "happy", delta_v_expression ) delta_v_expression.add(moving_R_squared) self.wait() self.play(FadeOut(randy)) self.start_velocity_vector = start_velocity_vector self.end_velocity_vector = moving_vector.copy() self.moving_vector = moving_vector self.force_expressions = VGroup( force_expression, acceleration_expression, delta_v_expression, ) def directly_compare_velocity_vectors(self): ellipse = self.ellipse lines = self.lines expressions = self.force_expressions vectors = VGroup(*[ self.get_velocity_vector(line.prop) for line in lines ]) index = len(vectors) / 2 v1 = vectors[index] v2 = vectors[index + 1] root_point = ellipse.get_left() + 3 * LEFT + DOWN root_dot = Dot(root_point) for vector in vectors: vector.save_state() vector.target = Arrow( *vector.get_start_and_end(), color=vector.get_color(), buff=0 ) vector.target.scale(2) vector.target.shift( root_point - vector.target.get_start() ) vector.target.add_to_back( vector.target.copy().set_stroke(BLACK, 5) ) difference_vectors = VGroup() external_angle_lines = VGroup() external_angle_arcs = VGroup() for vect1, vect2 in adjacent_pairs(vectors): diff_vect = Arrow( vect1.target.get_end(), vect2.target.get_end(), buff=0, color=YELLOW, rectangular_stem_width=0.025, tip_length=0.15 ) diff_vect.add_to_back( diff_vect.copy().set_stroke(BLACK, 2) ) difference_vectors.add(diff_vect) line = Line( diff_vect.get_start(), diff_vect.get_start() + 2 * diff_vect.get_vector(), ) external_angle_lines.add(line) arc = Arc(self.theta, stroke_width=2) arc.rotate(line.get_angle(), about_point=ORIGIN) arc.scale(0.4, about_point=ORIGIN) arc.shift(line.get_center()) external_angle_arcs.add(arc) external_angle_lines.set_stroke(GREY_B, 2) diff_vect = difference_vectors[index] polygon = Polygon(*[ vect.target.get_end() for vect in vectors ]) polygon.set_fill(BLUE_E, opacity=0.8) polygon.set_stroke(WHITE, 3) self.play(ShowCreationThenFadeAround(v1)) self.play( MoveToTarget(v1), GrowFromCenter(root_dot), expressions.scale, 0.5, {"about_edge": UL} ) self.wait() self.play( ReplacementTransform( v1.saved_state.copy(), v2.saved_state, path_arc=self.theta ) ) self.play(MoveToTarget(v2), Animation(root_dot)) self.wait() self.play(GrowArrow(diff_vect)) self.wait() n = len(vectors) for i in range(n - 1): v1 = vectors[(i + index + 1) % n] v2 = vectors[(i + index + 2) % n] diff_vect = difference_vectors[(i + index + 1) % n] # TODO, v2.saved_state is on screen untracked self.play(ReplacementTransform( v1.saved_state.copy(), v2.saved_state, path_arc=self.theta )) self.play( MoveToTarget(v2), GrowArrow(diff_vect) ) self.add(self.orbit) self.wait() self.play( LaggedStartMap(ShowCreation, external_angle_lines), LaggedStartMap(ShowCreation, external_angle_arcs), Animation(difference_vectors), ) self.add_foreground_mobjects(difference_vectors) self.wait(2) self.play(FadeIn(polygon)) self.wait(5) self.play(FadeOut(polygon)) self.wait(15) self.play(FadeIn(polygon)) class ShowEqualAngleSlices15DegreeSlices(ShowEqualAngleSlices): CONFIG = { "animate_sun": True, "theta": 15 * DEGREES, } class ShowEqualAngleSlices5DegreeSlices(ShowEqualAngleSlices): CONFIG = { "animate_sun": True, "theta": 5 * DEGREES, } class IKnowThisIsTricky(TeacherStudentsScene): def construct(self): self.teacher_says( "All you need is \\\\ infinite intelligence", bubble_config={ "width": 4, "height": 3, }, added_anims=[ self.change_students( *3 * ["horrified"], look_at=self.screen ) ] ) self.look_at(self.screen) self.wait(3) class PonderOverOffCenterDiagram(PiCreatureScene): def construct(self): randy, morty = self.pi_creatures velocity_diagram = self.get_velocity_diagram() bubble = randy.get_bubble() rect = SurroundingRectangle( velocity_diagram, buff=MED_LARGE_BUFF, color=GREY_B ) rect.stretch(1.2, 1, about_edge=DOWN) words = OldTexText("Velocity space") words.next_to(rect.get_top(), DOWN) self.play( LaggedStartMap(GrowFromCenter, velocity_diagram), randy.change, "pondering", morty.change, "confused", ) self.wait(2) self.play(ShowCreation(bubble)) self.wait(2) self.play( FadeOut(bubble), randy.change, "confused", morty.change, "pondering", ShowCreation(rect) ) self.play(Write(words)) self.wait(2) def create_pi_creatures(self): randy = Randolph(height=2.5) randy.to_corner(DL) morty = Mortimer(height=2.5) morty.to_corner(DR) return randy, morty def get_velocity_diagram(self): circle = Circle(color=WHITE, radius=2) circle.rotate(90 * DEGREES) circle.to_edge(DOWN, buff=LARGE_BUFF) root_point = interpolate( circle.get_center(), circle.get_bottom(), 0.5, ) dot = Dot(root_point) vectors = VGroup() for a in np.arange(0, 1, 1.0 / 24): end_point = circle.point_from_proportion(a) vector = Arrow(root_point, end_point, buff=0) vector.set_color(interpolate_color( BLUE, RED, inverse_interpolate( 1, 3, vector.get_length(), ) )) vector.add_to_back(vector.copy().set_stroke(BLACK, 5)) vectors.add(vector) vectors.add_to_back(circle) vectors.add(dot) return vectors class OneMoreTrick(TeacherStudentsScene): def construct(self): for student in self.students: student.change("tired") self.teacher_says("Just one more \\\\ tricky bit!") self.play_all_student_changes("hooray") self.wait(3) class UseVelocityDiagramToDeduceCurve(ShowEqualAngleSlices): CONFIG = { "animate_sun": True, "theta": 15 * DEGREES, "index": 6, } def construct(self): self.setup_orbit() self.setup_velocity_diagram() self.show_theta_degrees() self.match_velocity_vector_to_tangency() self.replace_vectors_with_lines() self.not_that_velocity_vector_is_theta() self.ask_about_curve() self.show_90_degree_rotation() self.show_geometry_of_rotated_diagram() def setup_orbit(self): ShowEqualAngleSlices.setup_orbit(self) self.force_skipping() self.show_equal_angle_slices() self.revert_to_original_skipping_status() orbit_word = self.orbit_word = OldTexText("Orbit") orbit_word.scale(1.5) orbit_word.next_to(self.ellipse, UP, LARGE_BUFF) self.add(orbit_word) def setup_velocity_diagram(self): ellipse = self.ellipse root_point = ellipse.get_left() + 4 * LEFT + DOWN frame = self.camera_frame root_dot = Dot(root_point) vectors = VGroup() original_vectors = VGroup() for line in self.lines: vector = self.get_velocity_vector(line.prop) vector.save_state() original_vectors.add(vector.copy()) vector.target = self.get_velocity_vector( line.prop, scalar=8.0 ) vector.target.shift( root_point - vector.target.get_start() ) vectors.add(vector) circle = Circle() circle.rotate(92 * DEGREES) circle.replace(VGroup(*[v.target for v in vectors])) circle.set_stroke(WHITE, 2) circle.shift( (root_point[0] - circle.get_center()[0]) * RIGHT ) circle.shift(0.035 * LEFT) # ?!? velocities_word = OldTexText("Velocities") velocities_word.scale(1.5) velocities_word.next_to(circle, UP) velocities_word.align_to(self.orbit_word, DOWN) frame.scale(1.2) frame.shift(3 * LEFT + 0.5 * UP) self.play(ApplyWave(ellipse)) self.play(*list(map(GrowArrow, vectors))) self.play( LaggedStartMap( MoveToTarget, vectors, lag_ratio=1, run_time=2 ), GrowFromCenter(root_dot), FadeInFromDown(velocities_word), ) self.add_foreground_mobjects(root_dot) self.play( ShowCreation(circle), Animation(vectors), ) self.wait() self.vectors = vectors self.original_vectors = original_vectors self.velocity_circle = circle self.root_dot = root_dot self.circle = circle def show_theta_degrees(self): lines = self.lines ellipse = self.ellipse circle = self.circle vectors = self.vectors comet = self.comet sun_center = self.sun.get_center() index = self.index angle = fdiv(index, len(lines)) * TAU thick_line = lines[index].copy() thick_line.set_stroke(RED, 3) horizontal = lines[0].copy() horizontal.set_stroke(WHITE, 3) ellipse_arc = VMobject() ellipse_arc.pointwise_become_partial( ellipse, 0, thick_line.prop ) ellipse_arc.set_stroke(YELLOW, 3) ellipse_wedge = self.get_wedge(ellipse_arc, sun_center) ellipse_wedge_start = self.get_wedge( VectorizedPoint(ellipse.get_right()), sun_center ) ellipse_angle_arc = Arc( self.theta * index, radius=0.5 ) ellipse_angle_arc.shift(sun_center) ellipse_theta = OldTex("\\theta") ellipse_theta.next_to(ellipse_angle_arc, RIGHT, MED_SMALL_BUFF) ellipse_theta.shift(2 * SMALL_BUFF * UL) vector = vectors[index].deepcopy() vector.set_fill(YELLOW) vector.save_state() Transform(vector, vectors[0]).update(1) vector.set_fill(YELLOW) circle_arc = VMobject() circle_arc.pointwise_become_partial( circle, 0, fdiv(index, len(vectors)) ) circle_arc.set_stroke(RED, 4) circle_theta = OldTex("\\theta") circle_theta.scale(1.5) circle_theta.next_to(circle_arc, UP, SMALL_BUFF) circle_theta.shift(SMALL_BUFF * DL) circle_wedge = self.get_wedge(circle_arc, circle.get_center()) circle_wedge.set_fill(PINK) circle_wedge_start = self.get_wedge( Line(circle.get_top(), circle.get_top()), circle.get_center() ).match_style(circle_wedge) circle_center_dot = Dot(circle.get_center()) # circle_center_dot.set_color(BLUE) self.play(FocusOn(comet)) self.play( ReplacementTransform( ellipse_wedge_start, ellipse_wedge, path_arc=angle, ), FadeIn(ellipse_arc), ShowCreation(ellipse_angle_arc), Write(ellipse_theta), ReplacementTransform( lines[0].copy(), thick_line, path_arc=angle ), MoveAlongPath(comet, ellipse_arc), run_time=2 ) self.wait() self.play( ReplacementTransform( circle_wedge_start, circle_wedge, path_arc=angle ), ShowCreation(circle_arc), Write(circle_theta), Restore(vector, path_arc=angle), GrowFromCenter(circle_center_dot), FadeIn(horizontal), run_time=2 ) self.wait() self.set_variables_as_attrs( index, ellipse_wedge, ellipse_arc, ellipse_angle_arc, ellipse_theta, thick_line, horizontal, circle_wedge, circle_arc, circle_theta, circle_center_dot, highlighted_vector=vector ) def match_velocity_vector_to_tangency(self): vector = self.highlighted_vector comet = self.comet original_vector = self.original_vectors[self.index].copy() original_vector.set_fill(YELLOW) tangent_line = Line( *original_vector.get_start_and_end() ) tangent_line.set_stroke(GREY_B, 3) tangent_line.scale(5) tangent_line.move_to(comet) self.play( ReplacementTransform( vector.copy(), original_vector, run_time=2 ), Animation(comet), ) self.wait() self.play( ShowCreation(tangent_line), Animation(original_vector), Animation(comet), ) self.wait() self.set_variables_as_attrs( example_tangent_line=tangent_line, example_tangent_vector=original_vector, ) def replace_vectors_with_lines(self): vectors = self.vectors original_vectors = self.original_vectors root_dot = self.root_dot highlighted_vector = self.highlighted_vector lines = VGroup() tangent_lines = VGroup() for vect, o_vect in zip(vectors, original_vectors): line = Line(*vect.get_start_and_end()) t_line = Line(*o_vect.get_start_and_end()) t_line.scale(5) t_line.move_to(o_vect.get_start()) lines.add(line) tangent_lines.add(t_line) vect.generate_target() vect.target.scale(0, about_point=root_dot.get_center()) lines.set_stroke(GREEN, 2) tangent_lines.set_stroke(GREEN, 2) highlighted_line = Line( *highlighted_vector.get_start_and_end(), stroke_color=YELLOW, stroke_width=4 ) self.play( LaggedStartMap(MoveToTarget, vectors), highlighted_vector.scale, 0, {"about_point": root_dot.get_center()}, Animation(highlighted_vector), Animation(self.circle_wedge), Animation(self.circle_arc), Animation(self.circle), Animation(self.circle_center_dot), ) self.remove(vectors, highlighted_vector) self.play( LaggedStartMap(ShowCreation, lines), ShowCreation(highlighted_line), Animation(highlighted_vector), ) self.wait() self.play( ReplacementTransform( lines.copy(), tangent_lines, run_time=3, ) ) self.wait() self.play(FadeOut(tangent_lines)) self.eccentric_lines = lines self.highlighted_line = highlighted_line def not_that_velocity_vector_is_theta(self): vector = self.example_tangent_vector v_line = Line(DOWN, UP) v_line.move_to(vector.get_start(), DOWN) angle = vector.get_angle() - 90 * DEGREES arc = Arc(angle, radius=0.5) arc.rotate(90 * DEGREES, about_point=ORIGIN) arc.shift(vector.get_start()) theta_q = OldTex("\\theta ?") theta_q.next_to(arc, UP) theta_q.shift(SMALL_BUFF * LEFT) cross = Cross(theta_q) self.play(ShowCreation(v_line)) self.play( ShowCreation(arc), FadeInFromDown(theta_q), ) self.wait() self.play(ShowCreation(cross)) self.wait() self.play(*list(map(FadeOut, [v_line, arc, theta_q, cross]))) self.wait() self.play( ReplacementTransform( self.ellipse_theta.copy(), self.circle_theta, ), ReplacementTransform( self.ellipse_angle_arc.copy(), self.circle_arc, ), run_time=2, ) self.wait() self.play( ReplacementTransform( self.circle.copy(), self.circle_center_dot, ) ) self.wait() def ask_about_curve(self): ellipse = self.ellipse circle = self.circle line = self.highlighted_line.copy() vector = self.example_tangent_vector morty = Mortimer(height=2.5) morty.move_to(ellipse.get_corner(UL)) morty.shift(MED_SMALL_BUFF * LEFT) self.play(FadeIn(morty)) self.play( morty.change, "confused", ellipse, ShowCreationThenDestruction( ellipse.copy().set_stroke(BLUE, 3), run_time=2 ) ) self.play( Blink(morty), ApplyWave(ellipse), ) self.play(morty.look_at, circle) self.play(morty.change, "pondering", circle) self.play(Blink(morty)) self.play(morty.look_at, ellipse) self.play(morty.change, "maybe", ellipse) self.play( line.move_to, vector, run_time=2 ) self.play(FadeOut(line)) self.wait() self.play(morty.look_at, circle) self.wait() self.play(FadeOut(morty)) def show_90_degree_rotation(self): circle = self.circle circle_setup = VGroup( circle, self.eccentric_lines, self.circle_wedge, self.circle_arc, self.highlighted_line, self.circle_center_dot, self.root_dot, self.circle_theta, ) circle_setup.generate_target() angle = -90 * DEGREES circle_setup.target.rotate( angle, about_point=circle.get_center() ) circle_setup.target[-1].rotate(-angle) circle_setup.target[2].set_fill(opacity=0) circle_setup.target[2].set_stroke(WHITE, 4) self.play(MoveToTarget(circle_setup, path_arc=angle)) self.wait() lines = self.eccentric_lines highlighted_line = self.highlighted_line ghost_lines = lines.copy() ghost_lines.set_stroke(width=1) ghost_lines[self.index].set_stroke(YELLOW, 4) for mob in list(lines) + [highlighted_line]: mob.generate_target() mob.save_state() mob.target.rotate(-angle) foci = [ self.root_dot.get_center(), circle.get_center(), ] a = circle.get_width() / 4 c = get_norm(foci[1] - foci[0]) / 2 b = np.sqrt(a**2 - c**2) little_ellipse = Circle(radius=a) little_ellipse.stretch(b / a, 1) little_ellipse.move_to(center_of_mass(foci)) little_ellipse.set_stroke(PINK, 4) self.add(ghost_lines) self.play( LaggedStartMap( MoveToTarget, lines, lag_ratio=0.1, run_time=8, ), MoveToTarget(highlighted_line), path_arc=-angle, ) self.play(ShowCreation(little_ellipse)) self.wait(2) self.play( little_ellipse.replace, self.ellipse, run_time=4, rate_func=there_and_back_with_pause ) self.wait(2) self.play(*[ Restore( mob, path_arc=angle, run_time=4, rate_func=there_and_back_with_pause ) for mob in list(lines) + [highlighted_line] ] + [Animation(little_ellipse)]) self.ghost_lines = ghost_lines self.little_ellipse = little_ellipse def show_geometry_of_rotated_diagram(self): ellipse = self.ellipse little_ellipse = self.little_ellipse circle = self.circle perp_line = self.highlighted_line.copy() perp_line.rotate(PI) circle_arc = self.circle_arc arc_copy = circle_arc.copy() center = circle.get_center() velocity_vector = self.example_tangent_vector e_line = perp_line.copy().rotate(90 * DEGREES) c_line = Line(center, e_line.get_end()) c_line.set_stroke(WHITE, 4) # lines = [c_line, e_line, perp_line] tangency_point = line_intersection( perp_line.get_start_and_end(), c_line.get_start_and_end(), ) tangency_point_dot = Dot(tangency_point) tangency_point_dot.set_color(BLUE) tangency_point_dot.save_state() tangency_point_dot.scale(5) tangency_point_dot.set_fill(opacity=0) def indicate(line): red_copy = line.copy().set_stroke(RED, 5) return ShowPassingFlash(red_copy, run_time=2) self.play( self.ghost_lines.set_stroke, {"width": 0.5}, self.eccentric_lines.set_stroke, {"width": 0.5}, *list(map(WiggleOutThenIn, [e_line, c_line])) ) for x in range(3): self.play( indicate(e_line), indicate(c_line), ) self.play(WiggleOutThenIn(perp_line)) for x in range(2): self.play(indicate(perp_line)) self.play(Restore(tangency_point_dot)) self.add_foreground_mobjects(tangency_point_dot) self.wait(2) self.play( arc_copy.scale, 0.15, {"about_point": center}, run_time=2 ) self.wait(2) self.play( perp_line.move_to, velocity_vector, run_time=4, rate_func=there_and_back_with_pause ) self.wait() self.play( little_ellipse.replace, ellipse, run_time=4, rate_func=there_and_back_with_pause ) self.wait() # Helpers def get_wedge(self, arc, center_point, opacity=0.8): wedge = VMobject() wedge.append_vectorized_mobject( Line(center_point, arc.get_points()[0]) ) wedge.append_vectorized_mobject(arc) wedge.append_vectorized_mobject( Line(arc.get_points()[-1], center_point) ) wedge.set_stroke(width=0) wedge.set_fill(COBALT, opacity=opacity) return wedge class ShowSunVectorField(Scene): def construct(self): sun_center = IntroduceShapeOfVelocities.CONFIG["sun_center"] vector_field = VectorField( get_force_field_func((sun_center, -1)) ) vector_field.set_fill(opacity=0.8) vector_field.sort( lambda p: -get_norm(p - sun_center) ) for vector in vector_field: vector.generate_target() vector.target.set_fill(opacity=1) vector.target.set_stroke(YELLOW, 0.5) for x in range(3): self.play(LaggedStartMap( MoveToTarget, vector_field, rate_func=there_and_back, lag_ratio=0.5, )) class TryToRememberProof(PiCreatureScene): def construct(self): randy = self.pi_creature words = OldTexText("Oh god...how \\\\ did it go?") words.next_to(randy, UP) words.shift_onto_screen() self.play( randy.change, "telepath", FadeInFromDown(words) ) self.look_at(ORIGIN) self.wait(2) self.play(randy.change, "concerned_musician") self.look_at(ORIGIN) self.wait(3) class PatYourselfOnTheBack(TeacherStudentsScene): CONFIG = { "camera_config": {"background_opacity": 1}, } def construct(self): self.teacher_says( "Pat yourself \\\\ on the back!", target_mode="hooray" ) self.play_all_student_changes("happy") self.wait(3) self.play( RemovePiCreatureBubble( self.teacher, target_mode="raise_right_hand" ), self.change_students( *3 * ["pondering"], look_at=self.screen ) ) self.look_at(UP) self.wait(8) self.play_student_changes(*3 * ["thinking"]) self.look_at(UP) self.wait(12) self.teacher_says("I just love this!") feynman = ImageMobject("Feynman", height=4) feynman.to_corner(UL) chess = ImageMobject("ChessGameOfTheCentury") chess.set_height(4) chess.next_to(feynman) self.play(FadeInFromDown(feynman)) self.wait() self.play( RemovePiCreatureBubble(self.teacher, target_mode="happy"), FadeInFromDown(chess) ) self.wait(2) class Thumbnail(ShowEmergingEllipse): CONFIG = { "num_lines": 50, } def construct(self): background = ImageMobject("Feynman_teaching") background.set_width(FRAME_WIDTH) background.scale(1.05) background.to_corner(UR, buff=0) background.shift(2 * UP) self.add(background) circle = self.get_circle() circle.set_stroke(width=6) circle.set_height(6.5) circle.to_corner(UL) circle.set_fill(BLACK, 0.9) lines = self.get_lines() lines.set_stroke(YELLOW, 5) lines.set_color_by_gradient(YELLOW, RED) ghost_lines = self.get_ghost_lines(lines) for line in lines: line.rotate(90 * DEGREES) ellipse = self.get_ellipse() ellipse.set_stroke(BLUE, 6) sun = ImageMobject("sun", height=0.5) sun.move_to(self.get_eccentricity_point()) circle_group = VGroup(circle, ghost_lines, lines, ellipse, sun) self.add(circle_group) l1 = Line( circle.point_from_proportion(0.175), 6.25 * RIGHT + 0.75 * DOWN ) l2 = Line( circle.point_from_proportion(0.75), 6.25 * RIGHT + 2.5 * DOWN ) l2a = VMobject().pointwise_become_partial(l2, 0, 0.56) l2b = VMobject().pointwise_become_partial(l2, 0.715, 1) expand_lines = VGroup(l1, l2a, l2b) expand_lines.set_stroke("RED", 5) self.add(expand_lines) self.add(circle_group) small_group = circle_group.copy() small_group.scale(0.2) small_group.stretch(1.35, 1) small_group.move_to(6.2 * RIGHT + 1.6 * DOWN) for mob in small_group: if isinstance(mob, VMobject) and mob.get_stroke_width() > 1: mob.set_stroke(width=1) small_group[0].set_fill(opacity=0.25) self.add(small_group) title = OldTexText( "Feynman's \\\\", "Lost \\\\", "Lecture", alignment="" ) title.scale(2.4) for part in title: part.add_to_back( part.copy().set_stroke(BLACK, 12).set_fill(BLACK, 1) ) title.to_corner(UR) title[2].to_edge(RIGHT) title[1].shift(0.9 * RIGHT) title.shift(0.5 * LEFT) self.add(title)
# -*- coding: utf-8 -*- from manim_imports_ext import * from once_useful_constructs.light import AmbientLight from once_useful_constructs.light import Lighthouse from once_useful_constructs.light import SwitchOn from functools import reduce # from once_useful_constructs.light import LightSource PRODUCT_COLOR = BLUE DEFAULT_OPACITY_FUNCTION = inverse_power_law(1, 1.5, 1, 4) CHEAP_AMBIENT_LIGHT_CONFIG = { "num_levels": 5, "radius": 0.25, "opacity_function": DEFAULT_OPACITY_FUNCTION, } HIGHT_QUALITY_AMBIENT_LIGHT_CONFIG = { "opacity_function": DEFAULT_OPACITY_FUNCTION, "num_levels": 100, "radius": 5, "max_opacity": 0.8, "color": PRODUCT_COLOR, } def get_chord_f_label(chord, arg="f", direction=DOWN): chord_f = OldTexText("Chord(", "$%s$" % arg, ")", arg_separator="") chord_f.set_color_by_tex("$%s$" % arg, YELLOW) chord_f.add_background_rectangle() chord_f.next_to(chord.get_center(), direction, SMALL_BUFF) angle = ((chord.get_angle() + TAU / 2) % TAU) - TAU / 2 if np.abs(angle) > TAU / 4: angle += TAU / 2 chord_f.rotate(angle, about_point=chord.get_center()) chord_f.angle = angle return chord_f class WallisNumeratorDenominatorGenerator(object): def __init__(self): self.n = 0 def __iter__(self): return self def __next__(self): return next(self) def __next__(self): n = self.n self.n += 1 if n % 2 == 0: return (n + 2, n + 1) else: return (n + 1, n + 2) def get_wallis_product(n_terms=6, show_result=True): tex_mob_args = [] nd_generator = WallisNumeratorDenominatorGenerator() for x in range(n_terms): numerator, denominator = next(nd_generator) tex_mob_args += [ "{%d" % numerator, "\\over", "%d}" % denominator, "\\cdot" ] tex_mob_args[-1] = "\\cdots" if show_result: tex_mob_args += ["=", "{\\pi", "\\over", "2}"] result = OldTex(*tex_mob_args) return result def get_wallis_product_numerical_terms(n_terms=20): result = [] nd_generator = WallisNumeratorDenominatorGenerator() for x in range(n_terms): n, d = next(nd_generator) result.append(float(n) / d) return result # Scenes class Introduction(Scene): def construct(self): n_terms = 10 number_line = NumberLine( x_min=0, x_max=2, unit_size=5, tick_frequency=0.25, numbers_with_elongated_ticks=[0, 1, 2], color=GREY_B, ) number_line.add_numbers() number_line.move_to(DOWN) numerical_terms = get_wallis_product_numerical_terms(400) partial_products = np.cumprod(numerical_terms) curr_product = partial_products[0] arrow = Vector(DOWN, color=YELLOW) def get_arrow_update(): return ApplyFunction( lambda mob: mob.next_to( number_line.number_to_point(curr_product), UP, SMALL_BUFF ), arrow, ) get_arrow_update().update(1) decimal = DecimalNumber( curr_product, num_decimal_places=5, show_ellipsis=True) decimal.next_to(arrow, UP, SMALL_BUFF, submobject_to_align=decimal[:5]) decimal_anim = ChangingDecimal( decimal, lambda a: number_line.point_to_number(arrow.get_center()), tracked_mobject=arrow ) product_mob = get_wallis_product(n_terms) product_mob.to_edge(UP) rects = VGroup(*[ SurroundingRectangle(product_mob[:n]) for n in list(range(3, 4 * n_terms, 4)) + [4 * n_terms] ]) rect = rects[0].copy() pi_halves_arrow = Vector(UP, color=BLUE) pi_halves_arrow.next_to( number_line.number_to_point(np.pi / 2), DOWN, SMALL_BUFF ) pi_halves_term = OldTex("\\pi / 2") pi_halves_term.next_to(pi_halves_arrow, DOWN) self.add(product_mob, number_line, rect, arrow, decimal) self.add(pi_halves_arrow, pi_halves_term) for n in range(1, len(rects)): curr_product = partial_products[n] self.play( get_arrow_update(), decimal_anim, Transform(rect, rects[n]), run_time=0.5 ) self.wait(0.5) for n in range(len(rects), len(numerical_terms), 31): curr_product = partial_products[n] self.play( get_arrow_update(), decimal_anim, run_time=0.25 ) curr_product = np.pi / 2 self.play( get_arrow_update(), decimal_anim, run_time=0.5 ) self.wait() class TableOfContents(Scene): def construct(self): topics = VGroup( OldTexText("The setup"), OldTexText("Circle geometry with complex polynomials"), OldTexText("Proof of the Wallis product"), OldTexText("Formalities not discussed"), OldTexText( "Generalizing this proof to get \\\\ the product formula for sine"), ) for topic in topics: dot = Dot(color=BLUE) dot.next_to(topic, LEFT) topic.add(dot) topics.arrange( DOWN, aligned_edge=LEFT, buff=LARGE_BUFF ) self.add(topics) self.wait() for i in range(len(topics)): self.play( topics[i + 1:].set_fill, {"opacity": 0.25}, topics[:i].set_fill, {"opacity": 0.25}, topics[i].set_fill, {"opacity": 1}, ) self.wait(2) class SourcesOfOriginality(TeacherStudentsScene): def construct(self): self.mention_excitement() self.break_down_value_of_math_presentations() self.where_we_fit_in() def mention_excitement(self): self.teacher_says( "This one came about \\\\ a bit differently...", target_mode="speaking", run_time=1 ) self.play_student_changes("happy", "confused", "erm") self.wait(2) def break_down_value_of_math_presentations(self): title = OldTexText("The value of a", "math", "presentation") title.to_edge(UP, buff=MED_SMALL_BUFF) value_of, math, presentation = title MATH_COLOR = YELLOW COMMUNICATION_COLOR = BLUE big_rect = self.big_rect = Rectangle( width=title.get_width() + 2 * MED_LARGE_BUFF, height=3.5, color=WHITE ) big_rect.next_to(title, DOWN) left_rect, right_rect = self.left_rect, self.right_rect = [ Rectangle( height=big_rect.get_height() - 2 * SMALL_BUFF, width=0.5 * big_rect.get_width() - 2 * SMALL_BUFF, color=color ) for color in (MATH_COLOR, COMMUNICATION_COLOR) ] right_rect.flip() left_rect.next_to(big_rect.get_left(), RIGHT, SMALL_BUFF) right_rect.next_to(big_rect.get_right(), LEFT, SMALL_BUFF) underlying_math = OldTexText("Underlying", "math") underlying_math.set_color(MATH_COLOR) communication = OldTexText("Communication") communication.set_color(COMMUNICATION_COLOR) VGroup(underlying_math, communication).scale(0.75) underlying_math.next_to(left_rect.get_top(), DOWN, SMALL_BUFF) communication.next_to(right_rect.get_top(), DOWN, SMALL_BUFF) formula = OldTex( "\\sum_{n = 1}^\\infty \\frac{1}{n^2} = \\frac{\\pi^2}{2}", ) formula.scale(0.75) formula.next_to(underlying_math, DOWN) based_on_wastlund = OldTexText( "Previous video based on\\\\", "a paper by Johan W\\\"{a}stlund" ) based_on_wastlund.set_width( left_rect.get_width() - MED_SMALL_BUFF) based_on_wastlund.next_to(formula, DOWN, MED_LARGE_BUFF) communication_parts = OldTexText("Visuals, narrative, etc.") communication_parts.scale(0.75) communication_parts.next_to(communication, DOWN, MED_LARGE_BUFF) lighthouse = Lighthouse(height=0.5) lighthouse.next_to(communication_parts, DOWN, LARGE_BUFF) ambient_light = AmbientLight( num_levels=200, radius=5, opacity_function=DEFAULT_OPACITY_FUNCTION, ) ambient_light.move_source_to(lighthouse.get_top()) big_rect.save_state() big_rect.stretch(0, 1) big_rect.stretch(0.5, 0) big_rect.move_to(title) self.play( FadeInFromDown(title), RemovePiCreatureBubble( self.teacher, target_mode="raise_right_hand", look_at=title, ), self.change_students( *["pondering"] * 3, look_at=title ) ) self.play(big_rect.restore) self.play(*list(map(ShowCreation, [left_rect, right_rect]))) self.wait() self.play( math.match_color, left_rect, ReplacementTransform(VGroup(math.copy()), underlying_math) ) self.play(FadeIn(formula)) self.play( presentation.match_color, right_rect, ReplacementTransform(presentation.copy(), communication) ) self.play( FadeIn(communication_parts), FadeIn(lighthouse), SwitchOn(ambient_light) ) self.play(self.teacher.change, "tease") self.wait() self.play( FadeIn(based_on_wastlund), self.change_students( "sassy", "erm", "plain", look_at=based_on_wastlund ), ) self.wait() self.math_content = VGroup(formula, based_on_wastlund) def where_we_fit_in(self): right_rect = self.right_rect left_rect = self.left_rect points = [ right_rect.get_left() + SMALL_BUFF * RIGHT, right_rect.get_corner(UL), right_rect.get_corner(UR), right_rect.get_right() + SMALL_BUFF * LEFT, right_rect.get_corner(DR), right_rect.get_bottom() + SMALL_BUFF * UP, right_rect.get_corner(DL), ] added_points = [ left_rect.get_bottom(), left_rect.get_corner(DL), left_rect.get_corner(DL) + 1.25 * UP, left_rect.get_bottom() + 1.25 * UP, ] blob1, blob2 = VMobject(), VMobject() blob1.set_points_smoothly(points + [points[0]]) blob1.append_points(3 * len(added_points) * [points[0]]) blob2.set_points_smoothly(points + added_points + [points[0]]) for blob in blob1, blob2: blob.set_stroke(width=0) blob.set_fill(BLUE, opacity=0.5) our_contribution = OldTexText("Our target \\\\ contribution") our_contribution.scale(0.75) our_contribution.to_corner(UR) arrow = Arrow( our_contribution.get_bottom(), right_rect.get_right() + MED_LARGE_BUFF * LEFT, color=BLUE ) wallis_product = get_wallis_product(n_terms=4) wallis_product.set_width( left_rect.get_width() - 2 * MED_LARGE_BUFF) wallis_product.move_to(self.math_content, UP) wallis_product_name = OldTexText("``Wallis product''") wallis_product_name.scale(0.75) wallis_product_name.next_to(wallis_product, DOWN, MED_SMALL_BUFF) new_proof = OldTexText("New proof") new_proof.next_to(wallis_product_name, DOWN, MED_LARGE_BUFF) self.play( DrawBorderThenFill(blob1), Write(our_contribution), GrowArrow(arrow), ) self.wait(2) self.play(FadeOut(self.math_content)) self.play( FadeIn(wallis_product), Write(wallis_product_name, run_time=1) ) self.wait(2) self.play( Transform(blob1, blob2, path_arc=-90 * DEGREES), FadeIn(new_proof), self.teacher.change, "hooray", ) self.play_all_student_changes("hooray", look_at=new_proof) self.wait(5) class Six(Scene): def construct(self): six = OldTex("6") six.add_background_rectangle(opacity = 1) six.background_rectangle.stretch(1.5, 0) six.set_height(7) self.add(six) class SridharWatchingScene(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs": { "color": YELLOW_E, "flip_at_start": False, }, } def construct(self): laptop = Laptop() laptop.scale(1.8) laptop.to_corner(DR) sridhar = self.pi_creature sridhar.next_to(laptop, LEFT, SMALL_BUFF, DOWN) bubble = ThoughtBubble() bubble.flip() bubble.pin_to(sridhar) basel = OldTex( "{1", "\\over", "1^2}", "+" "{1", "\\over", "2^2}", "+" "{1", "\\over", "3^2}", "+", "\\cdots", "= \\frac{\\pi^2}{6}" ) wallis = get_wallis_product(n_terms=4) VGroup(basel, wallis).scale(0.7) basel.move_to(bubble.get_bubble_center()) basel.to_edge(UP, buff=MED_SMALL_BUFF) wallis.next_to(basel, DOWN, buff=0.75) arrow = OldTex("\\updownarrow") arrow.move_to(VGroup(basel, wallis)) basel.set_color(YELLOW) wallis.set_color(BLUE) self.play(LaggedStartMap(DrawBorderThenFill, laptop)) self.play(sridhar.change, "pondering", laptop.screen) self.wait() self.play(ShowCreation(bubble)) self.play(LaggedStartMap(FadeIn, basel)) self.play( ReplacementTransform(basel.copy(), wallis), GrowFromPoint(arrow, arrow.get_top()) ) self.wait(4) self.play(sridhar.change, "thinking", wallis) self.wait(4) self.play(LaggedStartMap( ApplyFunction, VGroup(*list(laptop) + [bubble, basel, arrow, wallis, sridhar]), lambda mob: (lambda m: m.set_color(BLACK).fade(1).scale(0.8), mob), run_time=3, )) class ShowProduct(Scene): def construct(self): self.setup_axes() self.setup_wallis_product() self.show_larger_terms() self.show_smaller_terms() self.interleave_terms() self.show_answer() def setup_axes(self): axes = self.axes = self.get_axes(unit_size=0.75) self.add(axes) def setup_wallis_product(self): full_wallis_product = get_wallis_product(n_terms=16, show_result=False) wallis_product_parts = VGroup(*[ full_wallis_product[i:i + 4] for i in range(0, len(full_wallis_product), 4) ]) larger_parts = self.larger_parts = wallis_product_parts[::2] larger_parts.set_color(YELLOW) dots = OldTex("\\cdots") dots.move_to(larger_parts[-1][-1], LEFT) larger_parts[-1][-1].submobjects = dots.submobjects smaller_parts = self.smaller_parts = wallis_product_parts[1::2] smaller_parts.set_color(BLUE) for parts in larger_parts, smaller_parts: parts.arrange(RIGHT, buff=2 * SMALL_BUFF) # Move around the dots for part1, part2 in zip(parts, parts[1:]): dot = part1.submobjects.pop(-1) part2.add_to_back(dot) larger_parts.to_edge(UP) smaller_parts.next_to(larger_parts, DOWN, LARGE_BUFF) self.wallis_product_terms = get_wallis_product_numerical_terms(40) def show_larger_terms(self): axes = self.axes parts = self.larger_parts terms = self.wallis_product_terms[::2] partial_products = np.cumprod(terms) dots = VGroup(*[ Dot(axes.coords_to_point(n + 1, prod)) for n, prod in enumerate(partial_products) ]) dots.match_color(parts) lines = VGroup(*[ Line(d1.get_center(), d2.get_center()) for d1, d2 in zip(dots, dots[1:]) ]) braces = VGroup(*[ Brace(parts[:n + 1], DOWN) for n in range(len(parts)) ]) brace = braces[0].copy() decimal = DecimalNumber(partial_products[0], num_decimal_places=4) decimal.next_to(brace, DOWN) self.add(brace, decimal, dots[0], parts[0]) tuples = list(zip(parts[1:], lines, dots[1:], partial_products[1:], braces[1:])) for part, line, dot, prod, new_brace in tuples: self.play( FadeIn(part), Transform(brace, new_brace), ChangeDecimalToValue( decimal, prod, position_update_func=lambda m: m.next_to(brace, DOWN) ), ShowCreation(line), GrowFromCenter(dot, rate_func=squish_rate_func(smooth, 0.5, 1)), run_time=0.5, ) self.wait(0.5) N = len(parts) self.play( LaggedStartMap(ShowCreation, lines[N - 1:], lag_ratio=0.2), LaggedStartMap(FadeIn, dots[N:], lag_ratio=0.2), brace.stretch, 1.2, 0, {"about_edge": LEFT}, ChangeDecimalToValue( decimal, partial_products[-1], position_update_func=lambda m: m.next_to(brace, DOWN) ), run_time=4, rate_func=linear, ) self.play( FadeOut(brace), ChangeDecimalToValue( decimal, partial_products[-1] + 2, position_update_func=lambda m: m.next_to(brace, DOWN) ), UpdateFromFunc( decimal, lambda d: d.shift(self.frame_duration * RIGHT) ), UpdateFromAlphaFunc( decimal, lambda d, a: d.set_fill(opacity=1 - a) ), ) self.remove(decimal) self.graph_to_remove = VGroup(dots, lines) def show_smaller_terms(self): larger_parts = self.larger_parts larger_parts.save_state() larger_parts_mover = larger_parts.copy() larger_parts.fade(0.5) smaller_parts = self.smaller_parts for parts in larger_parts_mover, smaller_parts: parts.denominators = VGroup( parts[0][2], *[part[3] for part in parts[1:]] ) vect = op.sub( smaller_parts.denominators[1].get_left(), smaller_parts.denominators[0].get_left(), ) smaller_parts.denominators.shift(vect) self.play( larger_parts_mover.move_to, smaller_parts, LEFT, FadeOut(self.graph_to_remove) ) self.play( larger_parts_mover.denominators.shift, -vect, smaller_parts.denominators.shift, -vect, UpdateFromAlphaFunc( larger_parts_mover, lambda m, a: m.set_fill(opacity=1 - a), remover=True ), UpdateFromAlphaFunc( smaller_parts, lambda m, a: m.set_fill(opacity=a) ), ) # Rescale axes new_axes = self.get_axes(unit_size=1.5) self.play(ReplacementTransform(self.axes, new_axes)) axes = self.axes = new_axes # Show graph terms = self.wallis_product_terms[1::2] partial_products = np.cumprod(terms)[:15] dots = VGroup(*[ Dot(axes.coords_to_point(n + 1, prod)) for n, prod in enumerate(partial_products) ]) dots.match_color(smaller_parts) lines = VGroup(*[ Line(d1.get_center(), d2.get_center()) for d1, d2 in zip(dots, dots[1:]) ]) self.play( ShowCreation(lines), LaggedStartMap(FadeIn, dots, lag_ratio=0.1), run_time=3, rate_func=linear, ) self.wait(2) self.play(FadeOut(VGroup(dots, lines))) def interleave_terms(self): larger_parts = self.larger_parts smaller_parts = self.smaller_parts index = 6 larger_parts.restore() for parts in larger_parts, smaller_parts: parts.prefix = parts[:index] parts.suffix = parts[index:] parts.prefix.generate_target() larger_parts.fade(0.5) full_product = VGroup(*it.chain( *list(zip(larger_parts.prefix.target, smaller_parts.prefix.target)) )) for i, tex, vect in (0, "\\cdot", LEFT), (-1, "\\cdots", RIGHT): part = smaller_parts.prefix.target[i] dot = OldTex(tex) dot.match_color(part) dot.next_to(part, vect, buff=2 * SMALL_BUFF) part.add(dot) full_product.arrange(RIGHT, buff=2 * SMALL_BUFF) full_product.to_edge(UP) for parts in larger_parts, smaller_parts: self.play( MoveToTarget(parts.prefix), FadeOut(parts.suffix) ) self.wait() # Dots and lines # In poor form, this is modified copy-pasted from show_larger_terms axes = self.axes parts = full_product terms = self.wallis_product_terms partial_products = np.cumprod(terms) partial_products_iter = iter(partial_products) print(partial_products) dots = VGroup(*[ Dot(axes.coords_to_point(n + 1, prod)) for n, prod in enumerate(partial_products) ]) dots.set_color(GREEN) lines = VGroup(*[ Line(d1.get_center(), d2.get_center()) for d1, d2 in zip(dots, dots[1:]) ]) braces = VGroup(*[ Brace(parts[:n + 1], DOWN) for n in range(len(parts)) ]) brace = braces[0].copy() decimal = DecimalNumber(next(partial_products_iter), num_decimal_places=4) decimal.next_to(brace, DOWN) self.play(*list(map(FadeIn, [brace, decimal, dots[0]]))) tuples = list(zip(lines, dots[1:], braces[1:])) for line, dot, new_brace in tuples: self.play( Transform(brace, new_brace), ChangeDecimalToValue( decimal, next(partial_products_iter), position_update_func=lambda m: m.next_to(brace, DOWN) ), ShowCreation(line), GrowFromCenter(dot, rate_func=squish_rate_func(smooth, 0.5, 1)), run_time=0.5, ) self.wait(0.5) def get_decimal_anim(): return ChangeDecimalToValue( decimal, next(partial_products_iter), run_time=1, rate_func=squish_rate_func(smooth, 0, 0.5), ) self.play( FadeIn(lines[len(parts) - 1:]), FadeIn(dots[len(parts):]), get_decimal_anim() ) for x in range(3): self.play(get_decimal_anim()) self.partial_product_decimal = decimal self.get_decimal_anim = get_decimal_anim def show_answer(self): decimal = self.partial_product_decimal axes = self.axes pi_halves = OldTex("{\\pi", "\\over", "2}") pi_halves.scale(1.5) pi_halves.move_to(decimal, UP) randy = Randolph(height=1.7) randy.next_to(decimal, DL) randy.change("confused") randy.save_state() randy.change("plain") randy.fade(1) h_line = DashedLine( axes.coords_to_point(0, np.pi / 2), axes.coords_to_point(20, np.pi / 2), color=RED ) self.play( ShowCreation(h_line), randy.restore, self.get_decimal_anim() ) self.play(Blink(randy), self.get_decimal_anim()) self.play(self.get_decimal_anim()) self.play( self.get_decimal_anim(), UpdateFromAlphaFunc( decimal, lambda m, a: m.set_fill(opacity=1 - a) ), ReplacementTransform(randy, pi_halves[0]), Write(pi_halves[1:]), ) self.remove(decimal) self.wait() # Helpers def get_axes(self, unit_size): y_max = 7 axes = Axes( x_min=-1, x_max=12.5, y_min=-0.5, y_max=y_max + 0.25, y_axis_config={ "unit_size": unit_size, "numbers_with_elongated_ticks": list(range(1, y_max + 1)), "tick_size": 0.05, }, ) axes.shift(6 * LEFT + 3 * DOWN - axes.coords_to_point(0, 0)) axes.y_axis.label_direction = LEFT axes.y_axis.add_numbers(*list(range(1, y_max + 1))) return axes class TeacherShowing(TeacherStudentsScene): def construct(self): screen = self.screen screen.set_height(4) screen.next_to(self.students, UP, MED_LARGE_BUFF, RIGHT) self.play( ShowCreation(screen), self.teacher.change, "raise_right_hand", screen, self.change_students( *["pondering"] * 3, look_at=screen ) ) self.wait(5) class DistanceProductScene(MovingCameraScene): CONFIG = { "ambient_light_config": HIGHT_QUALITY_AMBIENT_LIGHT_CONFIG, "circle_color": BLUE, "circle_radius": 3, "num_lighthouses": 6, "lighthouse_height": 0.5, "ignored_lighthouse_indices": [], "observer_config": { "color": MAROON_B, "mode": "pondering", "height": 0.25, "flip_at_start": True, }, "observer_fraction": 1.0 / 3, "d_label_height": 0.35, "numeric_distance_label_height": 0.25, "default_product_column_top": FRAME_WIDTH * RIGHT / 4 + 1.5 * UP, "include_lighthouses": True, "include_distance_labels_background_rectangle": True, } def setup(self): super(DistanceProductScene, self).setup() self.circle = Circle( color=self.circle_color, radius=self.circle_radius, ) def get_circle_point_at_proportion(self, alpha): radius = self.get_radius() center = self.circle.get_center() angle = alpha * TAU unit_circle_point = np.cos(angle) * RIGHT + np.sin(angle) * UP return radius * unit_circle_point + center def get_lh_points(self): return np.array([ self.get_circle_point_at_proportion(fdiv(i, self.num_lighthouses)) for i in range(self.num_lighthouses) if i not in self.ignored_lighthouse_indices ]) def get_observer_point(self, fraction=None): if fraction is None: fraction = self.observer_fraction return self.get_circle_point_at_proportion(fraction / self.num_lighthouses) def get_observer(self): observer = self.observer = PiCreature(**self.observer_config) observer.next_to(self.get_observer_point(), RIGHT, buff=SMALL_BUFF) return observer def get_observer_dot(self): self.observer_dot = Dot( self.get_observer_point(), color=self.observer_config["color"] ) return self.observer_dot def get_lighthouses(self): self.lighthouses = VGroup() for point in self.get_lh_points(): lighthouse = Lighthouse() lighthouse.set_height(self.lighthouse_height) lighthouse.move_to(point) self.lighthouses.add(lighthouse) return self.lighthouses def get_lights(self): self.lights = VGroup() for point in self.get_lh_points(): light = AmbientLight( source_point=VectorizedPoint(point), **self.ambient_light_config ) self.lights.add(light) return self.lights def get_distance_lines(self, start_point=None, line_class=Line): if start_point is None: start_point = self.get_observer_point() lines = VGroup(*[ line_class(start_point, point) for point in self.get_lh_points() ]) lines.set_stroke(width=2) self.distance_lines = lines return self.distance_lines def get_symbolic_distance_labels(self): if not hasattr(self, "distance_lines"): self.get_distance_lines() self.d_labels = VGroup() for i, line in enumerate(self.distance_lines): d_label = OldTex("d_%d" % i) d_label.set_height(self.d_label_height) vect = rotate_vector(line.get_vector(), 90 * DEGREES) vect *= 2.5 * SMALL_BUFF / get_norm(vect) d_label.move_to(line.get_center() + vect) self.d_labels.add(d_label) return self.d_labels def get_numeric_distance_labels(self, lines=None, num_decimal_places=3, show_ellipsis=True): radius = self.circle.get_width() / 2 if lines is None: if not hasattr(self, "distance_lines"): self.get_distance_lines() lines = self.distance_lines labels = self.numeric_distance_labels = VGroup() for line in lines: label = DecimalNumber( line.get_length() / radius, num_decimal_places=num_decimal_places, show_ellipsis=show_ellipsis, include_background_rectangle=self.include_distance_labels_background_rectangle, ) label.set_height(self.numeric_distance_label_height) max_width = 0.5 * max(line.get_length(), 0.1) if label.get_width() > max_width: label.set_width(max_width) angle = (line.get_angle() % TAU) - TAU / 2 if np.abs(angle) > TAU / 4: angle += np.sign(angle) * np.pi label.angle = angle label.next_to(line.get_center(), UP, SMALL_BUFF) label.rotate(angle, about_point=line.get_center()) labels.add(label) return labels def get_distance_product_column(self, column_top=None, labels=None, fraction=None): if column_top is None: column_top = self.default_product_column_top if labels is None: if not hasattr(self, "numeric_distance_labels"): self.get_numeric_distance_labels() labels = self.numeric_distance_labels stacked_labels = labels.copy() for label in stacked_labels: label.rotate(-label.angle) label.set_height(self.numeric_distance_label_height) stacked_labels.arrange(DOWN) stacked_labels.move_to(column_top, UP) h_line = Line(LEFT, RIGHT) h_line.set_width(1.5 * stacked_labels.get_width()) h_line.next_to(stacked_labels, DOWN, aligned_edge=RIGHT) times = OldTex("\\times") times.next_to(h_line, UP, SMALL_BUFF, aligned_edge=LEFT) product_decimal = DecimalNumber( self.get_distance_product(fraction), num_decimal_places=3, show_ellipsis=True, include_background_rectangle=self.include_distance_labels_background_rectangle, ) product_decimal.set_height(self.numeric_distance_label_height) product_decimal.next_to(h_line, DOWN) product_decimal.align_to(stacked_labels, RIGHT) product_decimal[1].set_color(BLUE) self.distance_product_column = VGroup( stacked_labels, h_line, times, product_decimal ) return self.distance_product_column def get_fractional_arc(self, fraction, start_fraction=0): arc = Arc( angle=fraction * TAU, start_angle=start_fraction * TAU, radius=self.get_radius(), ) arc.shift(self.circle.get_center()) return arc def get_halfway_indication_arcs(self): fraction = 0.5 / self.num_lighthouses arcs = VGroup( self.get_fractional_arc(fraction), self.get_fractional_arc(-fraction, start_fraction=2 * fraction), ) arcs.set_stroke(YELLOW, 4) return arcs def get_circle_group(self): group = VGroup(self.circle) if not hasattr(self, "observer_dot"): self.get_observer_dot() if not hasattr(self, "observer"): self.get_observer() if not hasattr(self, "lighthouses"): self.get_lighthouses() if not hasattr(self, "lights"): self.get_lights() group.add(self.observer_dot, self.observer) if self.include_lighthouses: group.add(self.lighthouses) group.add(self.lights) return group def setup_lighthouses_and_observer(self): self.add(*self.get_circle_group()) # Numerical results def get_radius(self): return self.circle.get_width() / 2.0 def get_distance_product(self, fraction=None): radius = self.get_radius() observer_point = self.get_observer_point(fraction) distances = [ get_norm(point - observer_point) / radius for point in self.get_lh_points() ] return reduce(op.mul, distances, 1.0) # Animating methods def add_numeric_distance_labels(self, show_line_creation=True): anims = [] if not hasattr(self, "distance_lines"): self.get_distance_lines() if not hasattr(self, "numeric_distance_labels"): self.get_numeric_distance_labels() if show_line_creation: anims.append(LaggedStartMap(ShowCreation, self.distance_lines)) anims.append(LaggedStartMap(FadeIn, self.numeric_distance_labels)) self.play(*anims) def show_distance_product_in_column(self, **kwargs): group = self.get_distance_product_column(**kwargs) stacked_labels, h_line, times, product_decimal = group labels = self.numeric_distance_labels self.play(ReplacementTransform(labels.copy(), stacked_labels)) self.play( ShowCreation(h_line), Write(times) ) self.play( ReplacementTransform( stacked_labels.copy(), VGroup(product_decimal) ) ) class IntroduceDistanceProduct(DistanceProductScene): CONFIG = { "ambient_light_config": {"color": YELLOW}, } def construct(self): self.draw_circle_with_points() self.turn_into_lighthouses_and_observer() self.show_sum_of_inverse_squares() self.transition_to_lemma_1() def draw_circle_with_points(self): circle = self.circle lh_dots = self.lh_dots = VGroup(*[ Dot(point) for point in self.get_lh_points() ]) lh_dot_arrows = VGroup(*[ Arrow(*[ interpolate(circle.get_center(), dot.get_center(), a) for a in (0.6, 0.9) ], buff=0) for dot in lh_dots ]) evenly_space_dots_label = OldTexText("Evenly-spaced \\\\ dots") evenly_space_dots_label.set_width(0.5 * circle.get_width()) evenly_space_dots_label.move_to(circle) special_dot = self.special_dot = self.get_observer_dot() special_dot_arrow = Vector(DL) special_dot_arrow.next_to(special_dot, UR, SMALL_BUFF) special_dot_arrow.match_color(special_dot) special_dot_label = OldTexText("Special dot") special_dot_label.next_to( special_dot_arrow.get_start(), UP, SMALL_BUFF) special_dot_label.match_color(special_dot) special_dot.save_state() special_dot.next_to(special_dot_arrow, UR) special_dot.set_fill(opacity=0) self.play(ShowCreation(circle)) self.play( LaggedStartMap(ShowCreation, lh_dots), LaggedStartMap(GrowArrow, lh_dot_arrows), Write(evenly_space_dots_label) ) self.wait() self.play( special_dot.restore, GrowArrow(special_dot_arrow), Write(special_dot_label, run_time=1), FadeOut(VGroup(lh_dot_arrows, evenly_space_dots_label)) ) self.wait() self.play(FadeOut(VGroup(special_dot_arrow, special_dot_label))) def turn_into_lighthouses_and_observer(self): lighthouses = self.get_lighthouses() lights = self.get_lights() observer = self.get_observer() observer.save_state() observer.set_height(2) observer.change_mode("happy") observer.to_edge(RIGHT) self.play( LaggedStartMap(FadeOut, self.lh_dots), LaggedStartMap(FadeIn, lighthouses), LaggedStartMap(SwitchOn, lights), ) self.wait() self.play(FadeIn(observer)) self.play(observer.restore) self.wait() def show_sum_of_inverse_squares(self): lines = self.get_distance_lines() labels = self.get_symbolic_distance_labels() sum_of_inverse_squares = OldTex(*it.chain(*[ ["{1", "\\over", "(", "d_%d" % i, ")", "^2}", "+"] for i in range(len(lines)) ])) sum_of_inverse_squares.submobjects.pop(-1) sum_of_inverse_squares.to_edge(UP) d_terms = sum_of_inverse_squares.get_parts_by_tex("d_") d_terms.set_color(YELLOW) plusses = sum_of_inverse_squares.get_parts_by_tex("+") last_term = sum_of_inverse_squares[-6:] non_d_terms = VGroup(*[m for m in sum_of_inverse_squares if m not in d_terms and m not in last_term]) brace = Brace(sum_of_inverse_squares, DOWN) brace_text = brace.get_text("Total intensity of light") arrow = Vector(DOWN, color=WHITE).next_to(brace, DOWN) basel_sum = OldTex( "{1 \\over 1^2} + ", "{1 \\over 2^2} + ", "{1 \\over 3^2} + ", "{1 \\over 4^2} + ", "\\cdots", ) basel_sum.next_to(arrow, DOWN) basel_cross = Cross(basel_sum) useful_for = OldTexText("Useful for") useful_for.next_to(arrow, RIGHT) wallis_product = OldTex( "{2 \\over 1} \\cdot", "{2 \\over 3} \\cdot", "{4 \\over 3} \\cdot", "{4 \\over 5} \\cdot", "{6 \\over 5} \\cdot", "{6 \\over 7} \\cdot", "\\cdots" ) wallis_product.move_to(basel_sum) light_rings = VGroup(*it.chain(*self.lights)) self.play( LaggedStartMap(ShowCreation, lines), LaggedStartMap(Write, labels), ) circle_group = VGroup(*self.get_top_level_mobjects()) self.wait() self.play( ReplacementTransform(labels[-1].copy(), last_term[3]), Write(VGroup(*it.chain(last_term[:3], last_term[4:]))) ) self.remove(last_term) self.add(last_term) self.wait() self.play( Write(non_d_terms), ReplacementTransform( labels[:-1].copy(), d_terms[:-1], ), circle_group.scale, 0.8, {"about_point": FRAME_Y_RADIUS * DOWN} ) self.wait() self.play(LaggedStartMap( ApplyMethod, light_rings, lambda m: (m.set_fill, {"opacity": 2 * m.get_fill_opacity()}), rate_func=there_and_back, run_time=3, )) self.wait() # Mention useful just to basel problem circle_group.save_state() v_point = VectorizedPoint( FRAME_X_RADIUS * LEFT + FRAME_Y_RADIUS * DOWN) self.play( circle_group.next_to, v_point, UR, { "submobject_to_align": self.circle}, circle_group.scale, 0.5, {"about_point": v_point.get_center()}, ) self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() self.play( FadeOut(brace_text), GrowArrow(arrow), FadeIn(useful_for), FadeIn(basel_sum), ) self.wait() self.play( ShowCreation(basel_cross), FadeOut(VGroup(arrow, useful_for, brace)) ) basel_group = VGroup(basel_sum, basel_cross) self.play( basel_group.scale, 0.5, basel_group.to_corner, DR, ) self.play(Write(wallis_product)) self.wait() # Transition to distance product self.play( circle_group.restore, wallis_product.match_width, basel_sum, wallis_product.next_to, basel_sum, UP, {"aligned_edge": RIGHT}, ) self.play( d_terms.shift, 0.75 * d_terms.get_height() * UP, d_terms.set_color, PRODUCT_COLOR, light_rings.set_fill, PRODUCT_COLOR, *[ FadeOut(mob) for mob in sum_of_inverse_squares if mob not in d_terms and mob not in plusses ] ) self.wait() self.play( FadeOut(plusses), d_terms.arrange, RIGHT, 0.25 * SMALL_BUFF, d_terms.move_to, sum_of_inverse_squares, DOWN, ) self.wait() # Label distance product brace = Brace(d_terms, UP, buff=SMALL_BUFF) distance_product_label = brace.get_text("``Distance product''") self.play( GrowFromCenter(brace), Write(distance_product_label) ) line_copies = lines.copy().set_color(RED) self.play(LaggedStartMap(ShowCreationThenDestruction, line_copies)) self.wait() self.play(LaggedStartMap( ApplyFunction, light_rings, lambda mob: ( lambda m: m.shift( MED_SMALL_BUFF * UP).set_fill(opacity=2 * m.get_fill_opacity()), mob ), rate_func=wiggle, run_time=6, )) self.wait() def transition_to_lemma_1(self): self.lighthouse_height = Lemma1.CONFIG["lighthouse_height"] self.circle_radius = Lemma1.CONFIG["circle_radius"] self.observer_fraction = Lemma1.CONFIG["observer_fraction"] self.ambient_light_config["color"] = BLUE circle = self.circle lighthouses = self.lighthouses lights = self.lights circle.generate_target() circle.target.set_width(2 * self.circle_radius) circle.target.to_corner(DL) self.circle = circle.target new_lighthouses = self.get_lighthouses() new_lights = self.get_lights() self.clear() self.play( MoveToTarget(circle), Transform(lighthouses, new_lighthouses), Transform(lights, new_lights), ApplyMethod( self.observer_dot.move_to, self.get_circle_point_at_proportion( self.observer_fraction / self.num_lighthouses ) ), MaintainPositionRelativeTo(self.observer, self.observer_dot), ) class Lemma1(DistanceProductScene): CONFIG = { "circle_radius": 2.5, "observer_fraction": 0.5, "lighthouse_height": 0.25, "lemma_text": "distance product = 2", "include_distance_labels_background_rectangle": False, # "ambient_light_config": CHEAP_AMBIENT_LIGHT_CONFIG, } def construct(self): self.add_title() self.add_circle_group() self.state_lemma_premise() self.show_product() self.wiggle_observer() def add_title(self): title = self.title = OldTexText("Two lemmas:") title.set_color(YELLOW) title.to_edge(UP, buff=MED_SMALL_BUFF) self.add(title) def add_circle_group(self): self.circle.to_corner(DL) circle_group = self.get_circle_group() self.play(LaggedStartMap(FadeIn, VGroup( *circle_group.family_members_with_points()))) def state_lemma_premise(self): premise = OldTexText( "Lemma 1: If observer is halfway between lighthouses,") self.premise = premise premise.next_to(self.title, DOWN) frac = 1.0 / self.num_lighthouses arc1, arc2 = arcs = VGroup(VMobject(), VMobject()) arc1.pointwise_become_partial(self.circle, 0, frac / 2) arc2.pointwise_become_partial(self.circle, frac / 2, frac) arc1.reverse_points() arcs.set_stroke(YELLOW, 5) show_arcs = ShowCreationThenDestruction( arcs, lag_ratio=0, run_time=2, ) self.play(Write(premise), show_arcs, run_time=2) self.wait() self.play(show_arcs) self.wait() def show_product(self): lemma = OldTexText(self.lemma_text) lemma.set_color(BLUE) lemma.next_to(self.premise, DOWN) self.add_numeric_distance_labels() self.play(Write(lemma, run_time=1)) self.show_distance_product_in_column() self.wait() def wiggle_observer(self): # Overwriting existing method self.get_observer_point = lambda dummy=None: self.observer_dot.get_center() center = self.circle.get_center() observer_angle = angle_of_vector(self.get_observer_point() - center) observer_angle_tracker = ValueTracker(observer_angle) def update_dot(dot): dot.move_to(self.get_circle_point_at_proportion( observer_angle_tracker.get_value() / TAU )) def update_distance_lines(lines): new_lines = self.get_distance_lines(start_point=self.get_observer_point()) lines.submobjects = new_lines.submobjects def update_numeric_distance_labels(labels): new_labels = self.get_numeric_distance_labels(self.distance_lines) labels.submobjects = new_labels.submobjects def update_distance_product_column(column): new_column = self.get_distance_product_column() column.submobjects = new_column.submobjects self.remove(*VGroup( self.observer, self.observer_dot, self.distance_lines, self.numeric_distance_labels, self.distance_product_column, ).get_family()) self.play( ApplyMethod( observer_angle_tracker.set_value, observer_angle + 0.05 * TAU, rate_func=wiggle ), UpdateFromFunc(self.observer_dot, update_dot), MaintainPositionRelativeTo(self.observer, self.observer_dot), UpdateFromFunc(self.distance_lines, update_distance_lines), UpdateFromFunc(self.numeric_distance_labels, update_numeric_distance_labels), UpdateFromFunc(self.distance_product_column, update_distance_product_column), run_time=5 ) self.distance_product_column[-1].set_color(BLUE).scale(1.05) self.wait() class Lemma1With7Lighthouses(Lemma1): CONFIG = { "num_lighthouses": 7, } class Lemma1With8Lighthouses(Lemma1): CONFIG = { "num_lighthouses": 8, } class Lemma1With9Lighthouses(Lemma1): CONFIG = { "num_lighthouses": 9, } class Lemma2(Lemma1): CONFIG = { # "ambient_light_config": CHEAP_AMBIENT_LIGHT_CONFIG, "lemma_text": "distance product = \\# Initial lighthouses" } def construct(self): self.add_title() self.add_circle_group() self.state_lemma_premise() self.replace_first_lighthouse() self.show_product() self.wiggle_observer() def state_lemma_premise(self): premise = self.premise = OldTexText( "Lemma 2: If the observer replaces a lighthouse," ) premise.next_to(self.title, DOWN) self.play(Write(premise, run_time=1)) def replace_first_lighthouse(self): dot = self.observer_dot observer_anim = MaintainPositionRelativeTo(self.observer, dot) lighthouse_group = VGroup(self.lighthouses[0], self.lights[0]) point = self.get_lh_points()[0] self.play( lighthouse_group.shift, 5 * RIGHT, lighthouse_group.fade, 1, run_time=1.5, rate_func=running_start, remover=True, ) self.play( dot.move_to, point, observer_anim, path_arc=(-120 * DEGREES), ) self.wait() self.ignored_lighthouse_indices = [0] self.observer_fraction = 0 for group in self.lighthouses, self.lights: self.lighthouses.submobjects.pop(0) class Lemma2With7Lighthouses(Lemma2): CONFIG = { "num_lighthouses": 7, } class Lemma2With8Lighthouses(Lemma2): CONFIG = { "num_lighthouses": 8, } class Lemma2With9Lighthouses(Lemma2): CONFIG = { "num_lighthouses": 9, } class ConfusedPiCreature(Scene): def construct(self): randy = Randolph(color=GREY_BROWN) self.add(randy) self.play(Blink(randy)) self.play(randy.change, "confused") self.play(Blink(randy)) self.wait() class FromGeometryToAlgebra(DistanceProductScene): CONFIG = { "num_lighthouses": 7, # "ambient_light_config": CHEAP_AMBIENT_LIGHT_CONFIG, } def construct(self): self.setup_lights() self.point_out_evenly_spaced() self.transition_to_complex_plane() self.discuss_powers() self.raise_everything_to_the_nth() def setup_lights(self): circle = self.circle circle.set_height(5, about_edge=DOWN) lights = self.get_lights() dots = VGroup(*[Dot(point) for point in self.get_lh_points()]) for dot, light in zip(dots, lights): light.add_to_back(dot) self.add(circle, lights) def point_out_evenly_spaced(self): circle = self.circle step = 1.0 / self.num_lighthouses / 2 alpha_range = np.arange(0, 1 + step, step) arcs = VGroup(*[ VMobject().pointwise_become_partial(circle, a1, a2) for a1, a2 in zip(alpha_range, alpha_range[1:]) ]) arcs.set_stroke(YELLOW, 5) for arc in arcs[::2]: arc.reverse_points() arcs_anim = ShowCreationThenDestruction( arcs, lag_ratio=0, run_time=2 ) spacing_words = self.spacing_words = OldTexText("Evenly-spaced") spacing_words.set_width(self.get_radius()) spacing_words.move_to(circle) arrows = self.get_arrows() geometric_words = self.geometric_words = OldTexText( "Geometric property") geometric_words.to_edge(UP) geometric_words.add_background_rectangle() self.add(geometric_words) self.play( FadeIn(spacing_words), arcs_anim, *list(map(GrowArrow, arrows)) ) self.play(FadeOut(arrows), arcs_anim) self.wait() def transition_to_complex_plane(self): plane = self.complex_plane = ComplexPlane( unit_size=2, y_radius=6, x_radius=9, ) plane.shift(1.5 * RIGHT) plane.add_coordinates() origin = plane.number_to_point(0) h_line = Line(plane.number_to_point(-1), plane.number_to_point(1)) circle = self.circle circle_group = VGroup(circle, self.lights) circle_group.generate_target() circle_group.target.scale(h_line.get_width() / circle.get_width()) circle_group.target.shift( origin - circle_group.target[0].get_center() ) circle_group.target[0].set_stroke(RED) geometric_words = self.geometric_words geometric_words.generate_target() arrow = OldTex("\\rightarrow") arrow.add_background_rectangle() algebraic_words = OldTexText("Algebraic property") algebraic_words.add_background_rectangle() word_group = VGroup(geometric_words.target, arrow, algebraic_words) word_group.arrange(RIGHT) word_group.move_to(origin) word_group.to_edge(UP) unit_circle_words = OldTexText("Unit circle", "") unit_circle_words.match_color(circle_group.target[0]) for part in unit_circle_words: part.add_background_rectangle() unit_circle_words.next_to(origin, UP) complex_plane_words = OldTexText("Complex Plane") self.complex_plane_words = complex_plane_words complex_plane_words.move_to(word_group) complex_plane_words.add_background_rectangle() roots_of_unity_words = OldTexText("Roots of\\\\", "unity") roots_of_unity_words.move_to(origin) roots_of_unity_words.set_color(YELLOW) for part in roots_of_unity_words: part.add_background_rectangle() self.play( Write(plane), MoveToTarget(circle_group), FadeOut(self.spacing_words), MoveToTarget(geometric_words), FadeIn(arrow), FadeIn(algebraic_words), ) word_group.submobjects[0] = geometric_words self.play(Write(unit_circle_words, run_time=1)) # Show complex values outer_arrows = self.outer_arrows = self.get_arrows() for arrow, point in zip(outer_arrows, self.get_lh_points()): arrow.rotate(np.pi, about_point=point) outer_arrow = self.outer_arrow = outer_arrows[3].copy() values = list(map(plane.point_to_number, self.get_lh_points())) complex_decimal = self.complex_decimal = DecimalNumber( values[3], num_decimal_places=3, include_background_rectangle=True ) complex_decimal.next_to(outer_arrow.get_start(), LEFT, SMALL_BUFF) complex_decimal_rect = SurroundingRectangle(complex_decimal) complex_decimal_rect.fade(1) self.play( FadeIn(complex_plane_words), FadeOut(word_group), FadeIn(complex_decimal), FadeIn(outer_arrow) ) self.wait(2) self.play( ChangeDecimalToValue( complex_decimal, values[1], tracked_mobject=complex_decimal_rect ), complex_decimal_rect.next_to, outer_arrows[1].get_start( ), UP, SMALL_BUFF, Transform(outer_arrow, outer_arrows[1]), run_time=1.5 ) self.wait() arrows = self.get_arrows() arrows.set_color(YELLOW) self.play( ReplacementTransform(unit_circle_words, roots_of_unity_words), LaggedStartMap(GrowArrow, arrows) ) self.wait() self.play( complex_plane_words.move_to, word_group, LaggedStartMap(FadeOut, VGroup(*it.chain( arrows, roots_of_unity_words ))) ) # Turn decimal into z x_term = self.x_term = OldTex("x") x_term.add_background_rectangle() x_term.move_to(complex_decimal, DOWN) x_term.shift(0.5 * SMALL_BUFF * (DR)) self.play(ReplacementTransform(complex_decimal, x_term)) def discuss_powers(self): x_term = self.x_term outer_arrows = self.outer_arrows outer_arrows.add(outer_arrows[0].copy()) plane = self.complex_plane origin = plane.number_to_point(0) question = OldTexText("What is $x^2$") question.next_to(x_term, RIGHT, LARGE_BUFF) question.set_color(YELLOW) lh_points = list(self.get_lh_points()) lh_points.append(lh_points[0]) lines = VGroup(*[ Line(origin, point) for point in lh_points ]) lines.set_color(GREEN) step = 1.0 / self.num_lighthouses angle_arcs = VGroup(*[ Arc(angle=alpha * TAU, radius=0.35).shift(origin) for alpha in np.arange(0, 1 + step, step) ]) angle_labels = VGroup() for i, arc in enumerate(angle_arcs): label = OldTex("(%d / %d)\\tau" % (i, self.num_lighthouses)) label.scale(0.5) label.add_background_rectangle() point = arc.point_from_proportion(0.5) point += 1.2 * (point - origin) label.move_to(point) angle_labels.add(label) if i == 0: label.shift(0.75 * label.get_height() * DOWN) line = self.angle_line = lines[1].copy() line_ghost = DashedLine(line.get_start(), line.get_end()) self.ghost_angle_line = line_ghost line_ghost.set_stroke(line.get_color(), 2) angle_arc = angle_arcs[1].copy() angle_label = angle_labels[1].copy() angle_label.shift(0.25 * SMALL_BUFF * DR) magnitude_label = OldTex("1") magnitude_label.next_to(line.get_center(), UL, buff=SMALL_BUFF) power_labels = VGroup() for i, arrow in enumerate(outer_arrows[:-1]): label = OldTex("x^%d" % i) label.next_to( arrow.get_start(), -arrow.get_vector(), submobject_to_align=label[0] ) label.add_background_rectangle() power_labels.add(label) power_labels[0].next_to(outer_arrows[-1].get_start(), UR, SMALL_BUFF) power_labels.submobjects[1] = x_term L_labels = self.L_labels = VGroup(*[ OldTex("L_%d" % i).move_to(power_label, DOWN).add_background_rectangle( opacity=1 ) for i, power_label in enumerate(power_labels) ]) # Ask about squaring self.play(Write(question)) self.wait() self.play( ShowCreation(line), Write(magnitude_label) ) self.wait() self.play( ShowCreation(angle_arc), Write(angle_label) ) self.wait() self.add(line_ghost) for i in list(range(2, self.num_lighthouses)) + [0]: anims = [ Transform(angle_arc, angle_arcs[i]), Transform(angle_label, angle_labels[i]), Transform(line, lines[i], path_arc=TAU / self.num_lighthouses), ] if i == 2: anims.append(FadeOut(magnitude_label)) if i == 3: anims.append(FadeOut(question)) self.play(*anims) new_anims = [ GrowArrow(outer_arrows[i]), Write(power_labels[i]), ] if i == 2: new_anims.append(FadeOut(self.complex_plane_words)) self.play(*new_anims) self.wait() self.play(ReplacementTransform(power_labels, L_labels)) self.wait() self.play( Rotate(self.lights, TAU / self.num_lighthouses / 2), rate_func=wiggle ) self.wait() self.play( FadeOut(angle_arc), FadeOut(angle_label), *list(map(ShowCreationThenDestruction, lines)) ) self.wait() def raise_everything_to_the_nth(self): func_label = OldTex("L \\rightarrow L^7") func_label.set_color(YELLOW) func_label.to_corner(UL, buff=LARGE_BUFF) func_label.add_background_rectangle() polynomial_scale_factor = 0.8 polynomial = OldTex("x^%d - 1" % self.num_lighthouses, "=", "0") polynomial.scale(polynomial_scale_factor) polynomial.next_to(func_label, UP) polynomial.to_edge(LEFT) factored_polynomial = OldTex( "(x-L_0)(x-L_1)\\cdots(x-L_{%d - 1})" % self.num_lighthouses, "=", "0" ) factored_polynomial.scale(polynomial_scale_factor) factored_polynomial.next_to(polynomial, DOWN, aligned_edge=LEFT) for group in polynomial, factored_polynomial: for part in group: part.add_background_rectangle() origin = self.complex_plane.number_to_point(0) lights = self.lights lights.save_state() rotations = [] for i, light in enumerate(lights): rotations.append(Rotating( light, radians=(i * TAU - i * TAU / self.num_lighthouses), about_point=origin, rate_func=bezier([0, 0, 1, 1]), )) self.play(Write(func_label, run_time=1)) for i, rotation in enumerate(rotations[:4]): if i == 3: rect = SurroundingRectangle(polynomial) rect.set_color(YELLOW) self.play( FadeIn(polynomial), ShowCreationThenDestruction(rect) ) self.play( rotation, run_time=np.sqrt(i + 1) ) self.play(*rotations[4:], run_time=3) self.wait() self.play(lights.restore) self.play( FadeOut(func_label), FadeIn(factored_polynomial) ) self.wait(3) self.play( factored_polynomial[0].next_to, polynomial[1], RIGHT, 1.5 * SMALL_BUFF, FadeOut(polynomial[2]), FadeOut(factored_polynomial[1:]), ) # Comment on formula formula = VGroup(polynomial[0], polynomial[1], factored_polynomial[0]) rect = SurroundingRectangle(formula) brace = Brace(factored_polynomial[0], DOWN) brace2 = Brace(polynomial[0], DOWN) morty = PiCreature(color=GREY_BROWN) morty.scale(0.5) morty.next_to(brace.get_center(), DL, buff=LARGE_BUFF) L1_rhs = OldTex("= \\cos(\\tau / 7) + \\\\", "\\sin(\\tau / 7)i") L1_rhs.next_to(self.L_labels[1], RIGHT, aligned_edge=UP) for part in L1_rhs: part.add_background_rectangle() self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.wait() self.play(GrowFromCenter(brace)) self.play(FadeIn(morty)) self.play(morty.change, "horrified", brace) self.play(Blink(morty)) self.wait() self.play( Write(L1_rhs), morty.change, "confused", L1_rhs ) self.play(Blink(morty)) self.wait() self.play( Transform(brace, brace2), morty.change, "hooray", brace2 ) self.play(Blink(morty)) self.wait() # Nothing special about 7 new_lights = self.lights.copy() new_lights.rotate( TAU / self.num_lighthouses / 2, about_point=origin ) sevens = VGroup(polynomial[0][1][1], factored_polynomial[0][1][-4]) n_terms = VGroup() for seven in sevens: n_term = OldTex("N") n_term.replace(seven, dim_to_match=1) n_term.scale(0.9) n_term.shift(0.25 * SMALL_BUFF * DR) n_terms.add(n_term) self.play(LaggedStartMap(FadeOut, VGroup(*it.chain( L1_rhs, self.outer_arrows, self.L_labels, self.outer_arrow, self.angle_line, self.ghost_angle_line )))) self.play(LaggedStartMap(SwitchOn, new_lights), morty.look_at, new_lights) self.play(Transform(sevens, n_terms)) self.wait() self.play(Blink(morty)) self.wait() # def get_arrows(self): return VGroup(*[ Arrow( interpolate(self.circle.get_center(), point, 0.6), interpolate(self.circle.get_center(), point, 0.9), buff=0 ) for point in self.get_lh_points() ]) class PlugObserverIntoPolynomial(DistanceProductScene): CONFIG = { # "ambient_light_config": CHEAP_AMBIENT_LIGHT_CONFIG, "num_lighthouses": 7, # This makes it look slightly better, but renders much slower "add_lights_in_foreground": True, } def construct(self): self.add_plane() self.add_circle_group() self.label_roots() self.add_polynomial() self.point_out_rhs() self.introduce_observer() self.raise_observer_to_the_N() def add_plane(self): plane = self.plane = ComplexPlane( unit_size=2, y_radius=5, ) plane.shift(DOWN) plane.add_coordinates() plane.coordinate_labels.submobjects.pop(-4) self.origin = plane.number_to_point(0) self.add(plane) def add_circle_group(self): self.circle.set_color(RED) self.circle.set_width( 2 * get_norm(self.plane.number_to_point(1) - self.origin) ) self.circle.move_to(self.origin) lights = self.lights = self.get_lights() dots = VGroup(*[ Dot(point) for point in self.get_lh_points() ]) for dot, light in zip(dots, lights): light.add_to_back(dot) self.add(self.circle, lights) if self.add_lights_in_foreground: self.add_foreground_mobject(lights) def label_roots(self): origin = self.origin labels = VGroup(*[ OldTex("L_%d" % d) for d in range(self.num_lighthouses) ]) self.root_labels = labels points = self.get_lh_points() for label, point in zip(labels, points): label.move_to(interpolate(origin, point, 1.2)) labels[0].align_to(origin, UP) labels[0].shift(SMALL_BUFF * DOWN) self.add(labels) def add_polynomial(self, arg="x"): self.polynomial = self.get_polynomial_equation(arg) self.add(self.polynomial) def point_out_rhs(self): rhs = self.get_polynomial_rhs(self.polynomial) brace = Brace(rhs, DOWN, buff=SMALL_BUFF) brace_text = brace.get_text( "Useful for distance product", buff=SMALL_BUFF) brace_text.set_color(YELLOW) brace_text.add_background_rectangle() self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() self.play(FadeOut(VGroup(brace, brace_text))) def introduce_observer(self): dot = self.observer_dot = Dot() dot.move_to(self.plane.coords_to_point(1.6, 0.8)) observer = PiCreature(**self.observer_config) observer.move_to(dot) dot.match_color(observer) vect = 2 * DOWN + LEFT vect /= get_norm(vect) arrow = self.arrow = Vector(0.5 * vect) arrow.next_to(observer, -vect, buff=SMALL_BUFF) arrow.set_color(WHITE) full_name = OldTexText("Observer") var_name = self.var_name = OldTex("O") for mob in full_name, var_name: mob.match_color(observer) mob.next_to(arrow.get_start(), UP, SMALL_BUFF) mob.add_background_rectangle() complex_decimal = DecimalNumber(0, include_background_rectangle=True) equals = OldTex("=") complex_decimal_animation = ChangingDecimal( complex_decimal, lambda a: self.plane.point_to_number(dot.get_center()), position_update_func=lambda m: m.next_to(equals, RIGHT, SMALL_BUFF) ) complex_decimal_animation.update(0) equals_decimal = VGroup(equals, complex_decimal) equals_decimal.next_to(var_name, RIGHT) new_polynomial = self.get_polynomial_equation("O") O_terms = new_polynomial.get_parts_by_tex("O") lhs, poly_eq, rhs = self.get_polynomial_split(new_polynomial) lhs_rect = SurroundingRectangle(lhs, color=YELLOW) rhs_rect = SurroundingRectangle(rhs, color=YELLOW) self.lhs, self.rhs = lhs, rhs self.lhs_rect, self.rhs_rect = lhs_rect, rhs_rect lines = self.lines = self.get_lines() lines_update = self.lines_update = UpdateFromFunc( lines, lambda l: Transform(l, self.get_lines()).update(1) ) anims_for_dot_movement = self.anims_for_dot_movement = [ MaintainPositionRelativeTo(arrow, dot), MaintainPositionRelativeTo(var_name, arrow), MaintainPositionRelativeTo(equals, var_name), complex_decimal_animation, lines_update, ] self.play( FadeIn(observer, direction=-vect), GrowArrow(arrow) ) self.play(Write(full_name)) self.wait() self.play( ReplacementTransform(full_name[0], var_name[0]), ReplacementTransform(full_name[1][0], var_name[1][0]), FadeOut(full_name[1][1:]), ReplacementTransform(observer, dot), FadeIn(equals_decimal) ) self.add_foreground_mobject(dot) # Substitute self.wait() self.play( ReplacementTransform(var_name.copy(), O_terms), ReplacementTransform(self.polynomial, new_polynomial) ) self.polynomial = new_polynomial self.wait() # Show distances self.play(ShowCreation(rhs_rect)) self.play( LaggedStartMap(ShowCreation, lines), Animation(dot) ) self.play( Rotating( dot, radians=TAU, rate_func=smooth, about_point=dot.get_center() + MED_LARGE_BUFF * LEFT, run_time=4 ), *anims_for_dot_movement ) self.wait() self.remove(rhs_rect) self.play(ReplacementTransform(rhs_rect.copy(), lhs_rect)) self.wait() # Move onto circle angle = self.observer_angle = TAU / self.num_lighthouses / 3.0 target_point = self.plane.number_to_point( np.exp(complex(0, angle)) ) self.play( dot.move_to, target_point, *anims_for_dot_movement ) self.play(FadeOut(VGroup( equals, complex_decimal, var_name, arrow, ))) def raise_observer_to_the_N(self): dot = self.observer_dot origin = self.origin radius = self.get_radius() text_scale_val = 0.8 question = OldTexText( "What fraction \\\\", "between $L_0$ and $L_1$", "?", arg_separator="" ) question.scale(text_scale_val) question.next_to(dot, RIGHT) question.add_background_rectangle_to_submobjects() f_words = OldTexText("$f$", "of the way") third_words = OldTexText("$\\frac{1}{3}$", "of the way") for words in f_words, third_words: words.scale(text_scale_val) words.move_to(question[0]) words[0].set_color(YELLOW) words.add_background_rectangle() obs_angle = self.observer_angle full_angle = TAU / self.num_lighthouses def get_arc(angle): result = Arc(angle=angle, radius=radius, color=YELLOW, stroke_width=4) result.shift(origin) return result arc = get_arc(obs_angle) O_to_N_arc = get_arc(obs_angle * self.num_lighthouses) O_to_N_dot = dot.copy().move_to(O_to_N_arc.point_from_proportion(1)) O_to_N_arrow = Vector(0.5 * DR).next_to(O_to_N_dot, UL, SMALL_BUFF) O_to_N_arrow.set_color(WHITE) O_to_N_label = OldTex("O", "^N") O_to_N_label.set_color_by_tex("O", dot.get_color()) O_to_N_label.next_to(O_to_N_arrow.get_start(), UP, SMALL_BUFF) O_to_N_label.shift(SMALL_BUFF * RIGHT) O_to_N_group = VGroup(O_to_N_arc, O_to_N_arrow, O_to_N_label) around_circle_words = OldTexText("around the circle") around_circle_words.scale(text_scale_val) around_circle_words.add_background_rectangle() around_circle_words.next_to(self.circle.get_top(), UR) chord = Line(O_to_N_dot.get_center(), self.circle.get_right()) chord.set_stroke(GREEN) chord_halves = VGroup( Line(chord.get_center(), chord.get_start()), Line(chord.get_center(), chord.get_end()), ) chord_halves.set_stroke(WHITE, 5) chord_label = OldTex("|", "O", "^N", "-", "1", "|") chord_label.set_color_by_tex("O", MAROON_B) chord_label.add_background_rectangle() chord_label.next_to(chord.get_center(), DOWN, SMALL_BUFF) chord_label.rotate( chord.get_angle(), about_point=chord.get_center() ) numeric_chord_label = DecimalNumber( np.sqrt(3), num_decimal_places=4, include_background_rectangle=True, show_ellipsis=True, ) numeric_chord_label.rotate(chord.get_angle()) numeric_chord_label.move_to(chord_label) self.play( FadeIn(question), ShowCreation(arc), ) for angle in [full_angle - obs_angle, -full_angle, obs_angle]: last_angle = angle_of_vector(dot.get_center() - origin) self.play( self.lines_update, UpdateFromAlphaFunc( arc, lambda arc, a: Transform( arc, get_arc(last_angle + a * angle) ).update(1) ), Rotate(dot, angle, about_point=origin), run_time=2 ) self.play( FadeOut(question[0]), FadeOut(question[2]), FadeIn(f_words), ) self.wait() self.play( FadeOut(self.lines), FadeOut(self.root_labels), ) self.play( ReplacementTransform(dot.copy(), O_to_N_dot), ReplacementTransform(arc, O_to_N_arc), path_arc=O_to_N_arc.angle - arc.angle, ) self.add_foreground_mobject(O_to_N_dot) self.play( FadeIn(O_to_N_label), GrowArrow(O_to_N_arrow), ) self.wait() self.play( FadeOut(question[1]), f_words.next_to, around_circle_words, UP, SMALL_BUFF, FadeIn(around_circle_words) ) self.wait() self.play( FadeIn(chord_label[0]), ReplacementTransform(self.lhs.copy(), chord_label[1]), ShowCreation(chord) ) self.wait() # Talk through current example light_rings = VGroup(*it.chain(self.lights)) self.play(LaggedStartMap( ApplyMethod, light_rings, lambda m: (m.shift, MED_SMALL_BUFF * UP), rate_func=wiggle )) self.play( FadeOut(around_circle_words), FadeIn(question[1]), ReplacementTransform(f_words, third_words) ) self.play( Rotate(dot, 0.05 * TAU, about_point=origin, rate_func=wiggle) ) self.wait(2) self.play(ReplacementTransform( dot.copy(), O_to_N_dot, path_arc=TAU / 3)) self.play( third_words.next_to, around_circle_words, UP, SMALL_BUFF, FadeIn(around_circle_words), FadeOut(question[1]) ) self.wait() self.play(Indicate(self.lhs)) for x in range(2): self.play(ShowCreationThenDestruction(chord_halves)) self.play( FadeOut(chord_label), FadeIn(numeric_chord_label) ) self.wait() self.remove(self.lhs_rect) self.play( FadeOut(chord), FadeOut(numeric_chord_label), FadeOut(O_to_N_group), FadeIn(self.lines), ReplacementTransform(self.lhs_rect.copy(), self.rhs_rect) ) self.wait() # Add new lights for light in self.lights: light[1:].fade(0.5) added_lights = self.lights.copy() added_lights.rotate(full_angle / 2, about_point=origin) new_lights = VGroup(*it.chain(*list(zip(self.lights, added_lights)))) self.num_lighthouses *= 2 dot.generate_target() dot.target.move_to(self.get_circle_point_at_proportion( obs_angle / TAU / 2 )) dot.save_state() dot.move_to(dot.target) new_lines = self.get_lines() dot.restore() self.play(Transform(self.lights, new_lights)) self.play( MoveToTarget(dot), Transform(self.lines, new_lines) ) self.wait() self.play( third_words.next_to, question[1], UP, SMALL_BUFF, FadeOut(around_circle_words), FadeIn(question[1]), ) self.wait() chord_group = VGroup(chord, numeric_chord_label[1]) chord_group.set_color(YELLOW) self.add_foreground_mobjects(*chord_group) self.play( FadeIn(chord), FadeIn(numeric_chord_label), ) self.wait() # Helpers def get_polynomial_equation(self, var="x", color=None): if color is None: color = self.observer_config["color"] equation = OldTex( "\\left(", var, "^N", "-", "1", "\\right)", "=", "\\left(", var, "-", "L_0", "\\right)", "\\left(", var, "-", "L_1", "\\right)", "\\cdots", "\\left(", var, "-", "L_{N-1}", "\\right)", ) equation.set_color_by_tex(var, color) equation.to_edge(UP) equation.add_background_rectangle() return equation def get_polynomial_rhs(self, polynomial): return self.get_polynomial_split(polynomial)[2] def get_polynomial_lhs(self, polynomial): return self.get_polynomial_split(polynomial)[0] def get_polynomial_split(self, polynomial): eq = polynomial.get_part_by_tex("=") i = polynomial[1].submobjects.index(eq) return polynomial[1][:i], polynomial[1][i], polynomial[1][i + 1:] def get_lines(self, start_point=None): return self.get_distance_lines( start_point=start_point, line_class=DashedLine ) def get_observer_point(self, dummy_arg=None): return self.observer_dot.get_center() class PlugObserverIntoPolynomial5Lighthouses(PlugObserverIntoPolynomial): CONFIG = { "num_lighthouses": 5, } class PlugObserverIntoPolynomial3Lighthouses(PlugObserverIntoPolynomial): CONFIG = { "num_lighthouses": 3, } class PlugObserverIntoPolynomial2Lighthouses(PlugObserverIntoPolynomial): CONFIG = { "num_lighthouses": 2, } class DefineChordF(Scene): def construct(self): radius = 2.5 full_chord_f = OldTexText( "``", "Chord(", "$f$", ")", "''", arg_separator="") full_chord_f.set_color_by_tex("$f$", YELLOW) full_chord_f.to_edge(UP) chord_f = full_chord_f[1:-1] chord_f.generate_target() circle = Circle(radius=2.5) circle.set_color(RED) radius_line = Line(circle.get_center(), circle.get_right()) one_label = OldTex("1") one_label.next_to(radius_line, DOWN, SMALL_BUFF) chord = Line(*[circle.point_from_proportion(f) for f in [0, 1. / 3]]) chord.set_color(YELLOW) chord_third = OldTexText("Chord(", "$1/3$", ")", arg_separator="") chord_third.set_color_by_tex("1/3", YELLOW) for term in chord_third, chord_f.target: term.next_to(chord.get_center(), UP, SMALL_BUFF) chord_angle = chord.get_angle() + np.pi term.rotate(chord_angle, about_point=chord.get_center()) brace = Brace(Line(ORIGIN, TAU * UP / 3), RIGHT, buff=0) brace.generate_target() brace.target.stretch(0.5, 0) brace.target.apply_complex_function(np.exp) VGroup(brace, brace.target).scale(radius) brace.next_to(circle.get_right(), RIGHT, SMALL_BUFF, DOWN) brace.scale(0.5, about_edge=DOWN) brace.target.move_to(brace, DR) brace.target.shift(2 * SMALL_BUFF * LEFT) f_label = OldTex("f") f_label.set_color(YELLOW) point = circle.point_from_proportion(1.0 / 6) f_label.move_to(point + 0.4 * (point - circle.get_center())) third_label = OldTex("\\frac{1}{3}") third_label.scale(0.7) third_label.move_to(f_label) third_label.match_color(f_label) alphas = np.linspace(0, 1, 4) third_arcs = VGroup(*[ VMobject().pointwise_become_partial(circle, a1, a2) for a1, a2 in zip(alphas, alphas[1:]) ]) third_arcs.set_color_by_gradient(BLUE, PINK, GREEN) # Terms for sine formula origin = circle.get_center() height = DashedLine(origin, chord.get_center()) half_chords = VGroup( Line(chord.get_start(), chord.get_center()), Line(chord.get_end(), chord.get_center()), ) half_chords.set_color_by_gradient(BLUE, PINK) alt_radius_line = Line(origin, chord.get_end()) alt_radius_line.set_color(WHITE) angle_arc = Arc( radius=0.3, angle=TAU / 6, ) angle_arc.shift(origin) angle_label = OldTex("\\frac{f}{2}", "2\\pi") angle_label[0][0].set_color(YELLOW) angle_label.scale(0.6) angle_label.next_to(angle_arc, RIGHT, SMALL_BUFF, DOWN) angle_label.shift(SMALL_BUFF * UR) circle_group = VGroup( circle, chord, radius_line, one_label, brace, f_label, chord_f, half_chords, height, angle_arc, angle_label, ) formula = OldTex( "= 2 \\cdot \\sin\\left(\\frac{f}{2} 2\\pi \\right)", "= 2 \\cdot \\sin\\left(f \\pi \\right)", ) for part in formula: part[7].set_color(YELLOW) # Draw circle and chord self.add(radius_line, circle, one_label) self.play(Write(full_chord_f)) self.play(ShowCreation(chord)) self.play( MoveToTarget(chord_f), FadeOut(VGroup(full_chord_f[0], full_chord_f[-1])) ) self.play(GrowFromEdge(brace, DOWN)) self.play(MoveToTarget(brace, path_arc=TAU / 3)) self.play(Write(f_label)) self.wait(2) # Show third self.remove(chord_f, f_label) self.play( ReplacementTransform(chord_f.copy(), chord_third), ReplacementTransform(f_label.copy(), third_label), ) chord_copies = VGroup() last_chord = chord for color in PINK, BLUE: chord_copy = last_chord.copy() old_color = chord_copy.get_color() self.play( Rotate(chord_copy, -TAU / 6, about_point=last_chord.get_end()), UpdateFromAlphaFunc( chord_copy, lambda m, a: m.set_stroke( interpolate_color(old_color, color, a)) ) ) chord_copy.reverse_points() last_chord = chord_copy chord_copies.add(chord_copy) self.wait() self.play( FadeOut(chord_copies), ReplacementTransform(chord_third, chord_f), ReplacementTransform(third_label, f_label), ) # Show sine formula top_chord_f = chord_f.copy() top_chord_f.generate_target() top_chord_f.target.rotate(-chord_angle) top_chord_f.target.center().to_edge(UP, buff=LARGE_BUFF) top_chord_f.target.shift(3 * LEFT) formula.next_to(top_chord_f.target, RIGHT) self.play( ShowCreation(height), FadeIn(half_chords), ShowCreation(angle_arc), Write(angle_label) ) self.wait() self.play( MoveToTarget(top_chord_f), circle_group.shift, 1.5 * DOWN, ) self.play(Write(formula[0], run_time=1)) self.wait() self.play(ReplacementTransform( formula[0].copy(), formula[1], path_arc=45 * DEGREES )) self.wait() class DistanceProductIsChordF(PlugObserverIntoPolynomial): CONFIG = { "include_lighthouses": False, "num_lighthouses": 8, # "ambient_light_config": CHEAP_AMBIENT_LIGHT_CONFIG, # "add_lights_in_foreground": False, } def construct(self): self.add_plane() self.add_circle_group() self.add_polynomial("O") self.show_all_animations() def show_all_animations(self): fraction = self.observer_fraction = 0.3 circle = self.circle O_dot = self.observer_dot = Dot() O_dot.set_color(self.observer_config["color"]) O_to_N_dot = O_dot.copy() O_dot.move_to(self.get_circle_point_at_proportion( fraction / self.num_lighthouses)) O_to_N_dot.move_to(self.get_circle_point_at_proportion(fraction)) for dot, vect, tex in [(O_dot, DL, "O"), (O_to_N_dot, DR, "O^N")]: arrow = Vector(0.5 * vect, color=WHITE) arrow.next_to(dot.get_center(), -vect, SMALL_BUFF) label = OldTex(tex) O_part = label[0] O_part.match_color(dot) label.add_background_rectangle() label.next_to(arrow.get_start(), -vect, buff=0, submobject_to_align=O_part) dot.arrow = arrow dot.label = label self.add_foreground_mobject(dot) self.add(arrow, label) # For the transition to f = 1 / 2 dot.generate_target() fraction_words = VGroup( OldTexText("$f$", "of the way"), OldTexText("between lighthouses") ) fraction_words.scale(0.8) fraction_words[0][0].set_color(YELLOW) fraction_words.arrange(DOWN, SMALL_BUFF, aligned_edge=LEFT) fraction_words.next_to(O_dot.label, RIGHT) list(map(Tex.add_background_rectangle, fraction_words)) f_arc, new_arc = [ Arc( angle=(TAU * f / self.num_lighthouses), radius=self.get_radius(), color=YELLOW, ).shift(circle.get_center()) for f in (fraction, 0.5) ] self.add(f_arc) lines = self.lines = self.get_lines() labels = self.get_numeric_distance_labels() black_rect = Rectangle(height=6, width=3.5) black_rect.set_stroke(width=0) black_rect.set_fill(BLACK, 0.8) black_rect.to_corner(DL, buff=0) colum_group = self.get_distance_product_column( column_top=black_rect.get_top() + MED_SMALL_BUFF * DOWN ) stacked_labels, h_line, times, product_decimal = colum_group chord = Line(*[ self.get_circle_point_at_proportion(f) for f in (0, fraction) ]) chord.set_stroke(YELLOW) chord_f = get_chord_f_label(chord) chord_f_as_product = chord_f.copy() chord_f_as_product.generate_target() chord_f_as_product.target.rotate(-chord_f_as_product.angle) chord_f_as_product.target.scale(0.8) chord_f_as_product.target.move_to(product_decimal, RIGHT) # Constructs for the case f = 1 / 2 new_chord = Line(circle.get_right(), circle.get_left()) new_chord.match_style(chord) chord_half = get_chord_f_label(new_chord, "1/2") f_terms = VGroup(fraction_words[0][1][0], chord_f_as_product[1][1]) half_terms = VGroup(*[ OldTex("\\frac{1}{2}").scale(0.6).set_color(YELLOW).move_to(f) for f in f_terms ]) half_terms[1].move_to(chord_f_as_product.target[1][1]) O_dot.target.move_to(self.get_circle_point_at_proportion( 0.5 / self.num_lighthouses)) O_to_N_dot .target.move_to(circle.get_left()) self.observer_dot = O_dot.target new_lines = self.get_lines() changing_decimals = [] radius = self.get_radius() for decimal, line in zip(stacked_labels, new_lines): changing_decimals.append( ChangeDecimalToValue(decimal, line.get_length() / radius) ) equals_two_terms = VGroup(*[ OldTex("=2").next_to(mob, DOWN, SMALL_BUFF) for mob in (chord_half, chord_f_as_product.target) ]) # Animations self.play(Write(fraction_words)) self.wait() self.play( LaggedStartMap(ShowCreation, lines), LaggedStartMap(FadeIn, labels), ) self.play( FadeIn(black_rect), ReplacementTransform(labels.copy(), stacked_labels), ShowCreation(h_line), Write(times), ) self.wait(2) self.add_foreground_mobjects( chord_f[1], chord, O_dot, O_to_N_dot ) self.play( FadeOut(labels), ShowCreation(chord), FadeIn(chord_f), ) self.play(MoveToTarget(chord_f_as_product)) self.wait(2) # Transition to f = 1 / 2 self.play( Transform(lines, new_lines), Transform(f_arc, new_arc), Transform(chord, new_chord), chord_f.rotate, -chord_f.angle, chord_f.move_to, chord_half, MoveToTarget(O_dot), MoveToTarget(O_to_N_dot), MaintainPositionRelativeTo(O_dot.arrow, O_dot), MaintainPositionRelativeTo(O_dot.label, O_dot), MaintainPositionRelativeTo(O_to_N_dot.arrow, O_to_N_dot), MaintainPositionRelativeTo(O_to_N_dot.label, O_to_N_dot), *changing_decimals, path_arc=(45 * DEGREES), run_time=2 ) self.play( Transform(chord_f, chord_half), Transform(f_terms, half_terms), ) self.wait() for term in equals_two_terms: term.add_background_rectangle() self.add_foreground_mobject(term[1]) self.play( Write(equals_two_terms) ) self.wait() class ProveLemma2(PlugObserverIntoPolynomial): CONFIG = { "include_lighthouses": False, "num_lighthouses": 8, # "ambient_light_config": CHEAP_AMBIENT_LIGHT_CONFIG, # "add_lights_in_foreground": False, } def construct(self): self.add_plane() self.add_circle_group() self.add_polynomial("O") self.replace_first_lighthouse() self.rearrange_polynomial() self.plug_in_one() def replace_first_lighthouse(self): light_to_remove = self.lights[0] dot = self.observer_dot = Dot(color=self.observer_config["color"]) dot.move_to(self.get_circle_point_at_proportion( 0.5 / self.num_lighthouses)) arrow = Vector(0.5 * DL, color=WHITE) arrow.next_to(dot, UR, SMALL_BUFF) O_label = self.O_dot_label = OldTex("O") O_label.match_color(dot) O_label.add_background_rectangle() O_label.next_to(arrow, UR, SMALL_BUFF) # First, move the lighthouse self.add_foreground_mobject(dot) self.play( dot.move_to, light_to_remove, MaintainPositionRelativeTo(arrow, dot), MaintainPositionRelativeTo(O_label, dot), path_arc=-TAU / 2 ) black_rect = Rectangle( height=6, width=3.5, stroke_width=0, fill_color=BLACK, fill_opacity=1, ) black_rect.to_corner(DL, buff=0) lines = self.get_lines(self.circle.get_right()) labels = self.get_numeric_distance_labels() column_group = self.get_distance_product_column( black_rect.get_top() + MED_SMALL_BUFF * DOWN ) stacked_labels, h_line, times, product_decimal = column_group q_marks = self.q_marks = OldTexText("???") q_marks.move_to(product_decimal, LEFT) q_marks.match_color(product_decimal) zero_rects = VGroup( *list(map(SurroundingRectangle, [dot, stacked_labels[0]]))) self.play( LaggedStartMap(ShowCreation, lines), LaggedStartMap(FadeIn, labels), ) self.play( FadeIn(black_rect), ShowCreation(h_line), Write(times), ReplacementTransform(labels.copy(), stacked_labels) ) self.wait() self.play(ReplacementTransform( stacked_labels.copy(), VGroup(product_decimal) )) self.wait() self.add_foreground_mobject(zero_rects) self.play(*list(map(ShowCreation, zero_rects))) self.wait(2) self.play( VGroup(light_to_remove, zero_rects[0] ).shift, FRAME_WIDTH * RIGHT / 2, path_arc=-60 * DEGREES, rate_func=running_start, remover=True ) self.play( VGroup(stacked_labels[0], zero_rects[1]).shift, 4 * LEFT, rate_func=running_start, remover=True, ) self.remove_foreground_mobjects(zero_rects) self.play( FadeOut(product_decimal), FadeIn(q_marks) ) self.play(FadeOut(labels)) self.wait() def rearrange_polynomial(self): dot = self.observer_dot lhs, equals, rhs = self.get_polynomial_split(self.polynomial) polynomial_background = self.polynomial[0] first_factor = rhs[:5] remaining_factors = rhs[5:] equals_remaining_factors = VGroup(equals, remaining_factors) # first_factor_rect = SurroundingRectangle(first_factor) lhs_rect = SurroundingRectangle(lhs) frac_line = Line(LEFT, RIGHT, color=WHITE) frac_line.match_width(lhs, stretch=True) frac_line.next_to(lhs, DOWN, SMALL_BUFF) O_minus_1 = OldTex("\\left(", "O", "-", "1", "\\right)") O_minus_1.next_to(frac_line, DOWN, SMALL_BUFF) new_lhs_background = BackgroundRectangle( VGroup(lhs, O_minus_1), buff=SMALL_BUFF) new_lhs_rect = SurroundingRectangle(VGroup(lhs, O_minus_1)) roots_of_unity_circle = VGroup(*[ Circle(radius=0.2, color=YELLOW).move_to(point) for point in self.get_lh_points() ]) for circle in roots_of_unity_circle: circle.save_state() circle.scale(4) circle.fade(1) self.play(ShowCreation(lhs_rect)) self.add_foreground_mobject(roots_of_unity_circle) self.play(LaggedStartMap( ApplyMethod, roots_of_unity_circle, lambda m: (m.restore,) )) self.wait() frac_line_copy = frac_line.copy() self.play( FadeIn(new_lhs_background), polynomial_background.stretch, 0.8, 0, polynomial_background.move_to, frac_line_copy, LEFT, equals_remaining_factors.arrange, RIGHT, SMALL_BUFF, equals_remaining_factors.next_to, frac_line_copy, RIGHT, MED_SMALL_BUFF, ReplacementTransform(first_factor, O_minus_1, path_arc=-90 * DEGREES), ShowCreation(frac_line), Animation(lhs), ReplacementTransform(lhs_rect, new_lhs_rect), ) self.play( roots_of_unity_circle[0].shift, FRAME_WIDTH * RIGHT / 2, path_arc=(-60 * DEGREES), rate_func=running_start, remover=True ) # Expand rhs expanded_rhs = self.expanded_rhs = OldTex( "=", "1", "+", "O", "+", "O", "^2", "+", "\\cdots", "O", "^{N-1}" ) expanded_rhs.next_to(frac_line, RIGHT) expanded_rhs.shift(LEFT) expanded_rhs.scale(0.9) expanded_rhs.set_color_by_tex("O", dot.get_color()) self.play( polynomial_background.stretch, 1.8, 0, {"about_edge": LEFT}, FadeIn(expanded_rhs), equals_remaining_factors.scale, 0.9, equals_remaining_factors.next_to, expanded_rhs, VGroup( new_lhs_background, lhs, frac_line, O_minus_1, new_lhs_rect, ).shift, LEFT, ) self.wait() def plug_in_one(self): expanded_rhs = self.expanded_rhs O_terms = expanded_rhs.get_parts_by_tex("O") ones = VGroup(*[ OldTex("1").move_to(O_term, RIGHT) for O_term in O_terms ]) ones.match_color(O_terms[0]) equals_1 = OldTex("= 1") equals_1.next_to(self.O_dot_label, RIGHT, SMALL_BUFF) brace = Brace(expanded_rhs[1:], DOWN) N_term = brace.get_text("N") product = DecimalNumber( self.num_lighthouses, num_decimal_places=3, show_ellipsis=True ) product.move_to(self.q_marks, LEFT) self.play(Write(equals_1)) self.play( FocusOn(brace), GrowFromCenter(brace) ) self.wait(2) self.play(ReplacementTransform(O_terms, ones)) self.wait() self.play(Write(N_term)) self.play(FocusOn(product)) self.play( FadeOut(self.q_marks), FadeIn(product) ) self.wait() class LocalMathematician(PiCreatureScene): def construct(self): randy, mathy = self.pi_creatures screen = ScreenRectangle(height=2) screen.to_corner(UL) screen.fade(1) mathy_name = OldTexText("Local \\\\ mathematician") mathy_name.next_to(mathy, LEFT, LARGE_BUFF) arrow = Arrow(mathy_name, mathy) self.play( Animation(screen), mathy.change, "pondering", PiCreatureSays( randy, "Check these \\\\ out!", target_mode="surprised", bubble_config={"height": 3, "width": 4}, look_at=screen, ), ) self.play( Animation(screen), RemovePiCreatureBubble( randy, target_mode="raise_right_hand", look_at=screen, ) ) self.wait(2) self.play( PiCreatureSays( mathy, "Ah yes, consider \\\\ $x^n - 1$ over $\\mathds{C}$...", look_at=randy.eyes ), randy.change, "happy", mathy.eyes ) self.wait(3) def create_pi_creatures(self): randy = Randolph().flip() mathy = Mathematician() randy.scale(0.9) randy.to_edge(DOWN).shift(4 * RIGHT) mathy.to_edge(DOWN).shift(4 * LEFT) return randy, mathy class ArmedWithTwoKeyFacts(TeacherStudentsScene, DistanceProductScene): CONFIG = { "num_lighthouses": 6, "ambient_light_config": { "opacity_function": inverse_power_law(1, 1, 1, 6), "radius": 1, "num_levels": 100, "max_opacity": 1, }, } def setup(self): TeacherStudentsScene.setup(self) DistanceProductScene.setup(self) def construct(self): circle1 = self.circle circle1.set_height(1.5) circle1.to_corner(UL) circle2 = circle1.copy() circle2.next_to(circle1, DOWN, MED_LARGE_BUFF) wallis_product = get_wallis_product(n_terms=8) N = self.num_lighthouses labels = VGroup() for circle, f, dp in (circle1, 0.5, "2"), (circle2, 0, "N"): self.circle = circle lights = self.get_lights() if f == 0: lights.submobjects.pop(0) observer = Dot(color=MAROON_B) frac = f / N point = self.get_circle_point_at_proportion(frac) observer.move_to(point) lines = self.get_distance_lines(point, line_class=DashedLine) label = OldTexText("Distance product = %s" % dp) label.scale(0.7) label.next_to(circle, RIGHT) labels.add(label) group = VGroup(lines, observer, label) self.play( FadeIn(circle), LaggedStartMap(FadeIn, VGroup(*it.chain(lights))), LaggedStartMap( FadeIn, VGroup( *it.chain(group.family_members_with_points())) ), self.teacher.change, "raise_right_hand", self.change_students(*["pondering"] * 3) ) wallis_product.move_to(labels).to_edge(RIGHT) self.play( LaggedStartMap(FadeIn, wallis_product), self.teacher.change_mode, "hooray", self.change_students( *["thinking"] * 3, look_at=wallis_product) ) self.wait(2) class Sailor(PiCreature): CONFIG = { "flip_at_start": True, "color": YELLOW_D, "hat_height_factor": 1.0 / 6, } def __init__(self, *args, **kwargs): PiCreature.__init__(self, *args, **kwargs) height = self.get_height() * self.hat_height_factor sailor_hat = SVGMobject(file_name="sailor_hat", height=height) # Rhombus is a horrible hack... rhombus = Polygon( UP, UP + 2 * RIGHT, 1.75 * RIGHT + 0.5 * UP, 0.5 * RIGHT + 0.1 * DOWN, 1.25 * LEFT + 0.15 * DOWN, ) rhombus.set_fill(BLACK, opacity=1) rhombus.set_stroke(width=0) rhombus.set_height(sailor_hat.get_height() / 3) rhombus.rotate(5 * DEGREES) rhombus.move_to(sailor_hat, DR) rhombus.shift(0.05 * sailor_hat.get_width() * LEFT) sailor_hat.add_to_back(rhombus) sailor_hat.rotate(-15 * DEGREES) sailor_hat.move_to(self.eyes.get_center(), DOWN) sailor_hat.shift( 0.1 * self.eyes.get_width() * RIGHT, 0.1 * self.eyes.get_height() * UP, ) self.add(sailor_hat) class KeeperAndSailor(DistanceProductScene, PiCreatureScene): CONFIG = { "num_lighthouses": 9, "circle_radius": 2.75, # "ambient_light_config": CHEAP_AMBIENT_LIGHT_CONFIG, "add_lights_in_foreground": False, # Keep this way "text_scale_val": 0.7, "observer_fraction": 0.5, "keeper_color": BLUE, "sailor_color": YELLOW_D, "include_distance_labels_background_rectangle": False, "big_circle_center": FRAME_WIDTH * LEFT / 2 + SMALL_BUFF * RIGHT, } def setup(self): DistanceProductScene.setup(self) PiCreatureScene.setup(self) self.remove(*self.pi_creatures) def construct(self): self.place_lighthouses() self.introduce_observers() self.write_distance_product_fraction() self.break_down_distance_product_by_parts() self.grow_circle_and_N() self.show_limit_for_each_fraction() self.show_limit_of_lhs() def place_lighthouses(self): circle = self.circle circle.to_corner(DL) circle.shift(MED_SMALL_BUFF * UR) circle.set_color(RED) lighthouses = self.get_lighthouses() lights = self.get_lights() for light in lights: dot = Dot(radius=0.06).move_to(light) dot.match_color(light) light.add_to_back(dot) origin = circle.get_center() arrows = VGroup(*[ Arrow(0.6 * (p - origin), 0.9 * (p - origin), buff=0).shift(origin) for p in self.get_lh_points() ]) arrows.set_color(WHITE) words = OldTexText("N evenly-spaced \\\\ lighthouses") words.scale(0.8) words.move_to(origin) self.add(circle) if self.add_lights_in_foreground: self.add_foreground_mobject(lights) self.add_foreground_mobject(words) self.play( LaggedStartMap(FadeIn, VGroup(*it.chain(lights))), LaggedStartMap(FadeIn, lighthouses), LaggedStartMap(GrowArrow, arrows), ) self.remove_foreground_mobjects(words) self.play(FadeOut(words), FadeOut(arrows)) self.wait() def introduce_observers(self): keeper, sailor = observers = self.observers keeper.target_point = self.get_keeper_point() sailor.target_point = self.get_sailor_point() for pi, text in (keeper, "Keeper"), (sailor, "Sailor"): pi.title = OldTexText(text) pi.title.next_to(pi, DOWN) pi.dot = Dot() pi.dot.match_color(pi) pi.dot.next_to(pi, LEFT) pi.dot.set_fill(opacity=0) self.play(LaggedStartMap( Succession, observers, lambda m: (FadeIn, m, ApplyMethod, m.change, "wave_1") )) for pi in observers: self.play( FadeIn(pi.title), pi.change, "plain" ) self.wait() if self.add_lights_in_foreground: self.add_foreground_mobjects(keeper, keeper.dot, keeper.title) for pi in observers: self.play( pi.set_height, 0.5, pi.next_to, pi.target_point, RIGHT, SMALL_BUFF, pi.dot.move_to, pi.target_point, pi.dot.set_fill, {"opacity": 1}, pi.title.scale, self.text_scale_val, pi.title.next_to, pi.target_point, RIGHT, {"buff": 0.6}, ) if pi is sailor: arcs = self.get_halfway_indication_arcs() self.play(*list(map(ShowCreationThenDestruction, arcs))) self.wait() def write_distance_product_fraction(self): fraction = self.distance_product_fraction = OldTex( "{\\text{Keeper's distance product}", "\\over", "\\text{Sailor's distance product}}" ) fraction.scale(self.text_scale_val) fraction.to_corner(UR) keeper_lines = self.get_distance_lines( self.get_keeper_point(), line_class=DashedLine ) sailor_lines = self.get_distance_lines( self.get_sailor_point(), line_class=DashedLine ) sailor_line_lengths = self.get_numeric_distance_labels(sailor_lines) keeper_line_lengths = self.get_numeric_distance_labels(keeper_lines) sailor_dp_column, keeper_dp_column = [ self.get_distance_product_column( 4 * RIGHT + 1.5 * UP, labels, frac ) for labels, frac in [ (sailor_line_lengths, 0.5), (keeper_line_lengths, 0), ] ] sailor_dp_decimal = sailor_dp_column[-1] sailor_dp_decimal_rect = SurroundingRectangle(sailor_dp_decimal) keeper_dp_decimal = keeper_dp_column[-1] keeper_dp_decimal_rect = SurroundingRectangle(keeper_dp_decimal) keeper_top_zero_rect = SurroundingRectangle(keeper_dp_column[0][0]) # stacked_labels, h_line, times, product_decimal = column # Define result fraction equals = self.distance_product_equals = OldTex("=") result_fraction = self.result_fraction = OldTex( "{N", "{\\text{distance} \\choose \\text{between obs.}}", "\\over", "2}" ) N, dist, frac_line, two = result_fraction result_fraction.to_corner(UR) equals.next_to(frac_line, LEFT) for part in result_fraction: part.save_state() part.generate_target() div = OldTex("/") first_denom = VGroup(two.target, div, dist) first_denom.arrange(RIGHT, buff=SMALL_BUFF) first_denom.move_to(two, UP) N.next_to(frac_line, UP, SMALL_BUFF) # Define terms to be removed first_light_group = VGroup(self.lights[0], self.lighthouses[0]) keeper_top_zero_group = VGroup( keeper_dp_column[0][0], keeper_top_zero_rect) new_keeper_dp_decimal = DecimalNumber( self.num_lighthouses, num_decimal_places=3, ) new_keeper_dp_decimal.replace(keeper_dp_decimal, dim_to_match=1) new_keeper_dp_decimal.set_color(YELLOW) self.play(*list(map(ShowCreation, keeper_lines))) self.play(ReplacementTransform( keeper_lines.copy(), VGroup(fraction[0]) )) self.play(FadeOut(keeper_lines)) self.play(*list(map(ShowCreation, sailor_lines))) self.play( ReplacementTransform( sailor_lines.copy(), VGroup(fraction[2]) ), ShowCreation(fraction[1]) ) self.wait() self.play(LaggedStartMap(FadeIn, sailor_line_lengths)) self.play(ReplacementTransform( sailor_line_lengths.copy(), sailor_dp_column[0] )) self.play(FadeIn(sailor_dp_column[1:])) self.play(ShowCreation(sailor_dp_decimal_rect)) self.play( fraction.next_to, equals, LEFT, FadeIn(equals), ShowCreation(frac_line), ReplacementTransform(sailor_dp_decimal.copy(), two), FadeOut(sailor_dp_decimal_rect) ) self.wait() # Note, sailor_lines and sailor_line_lengths get changed here self.remove(*list(sailor_lines) + list(sailor_line_lengths)) self.play( FadeOut(sailor_dp_column), ReplacementTransform(sailor_lines.deepcopy(), keeper_lines), ReplacementTransform( sailor_line_lengths.deepcopy(), keeper_line_lengths), ) self.play(ReplacementTransform( keeper_line_lengths.copy(), keeper_dp_column[0] )) self.play(FadeIn(keeper_dp_column[1:])) self.wait() self.play( ShowCreation(keeper_dp_decimal_rect), ShowCreation(keeper_top_zero_rect) ) self.wait(2) # Remove first lighthouse self.play( first_light_group.shift, 0.6 * FRAME_WIDTH * RIGHT, keeper_top_zero_group.shift, 0.4 * FRAME_WIDTH * RIGHT, FadeOut(keeper_dp_decimal), FadeOut(keeper_dp_decimal_rect), path_arc=-30 * DEGREES, rate_func=running_start, ) self.remove(first_light_group, keeper_top_zero_group) self.wait() self.play(ReplacementTransform( keeper_dp_column[0][1:].copy(), VGroup(new_keeper_dp_decimal), )) self.wait() self.play(ReplacementTransform(new_keeper_dp_decimal.copy(), N,)) self.wait(2) sailor_lines[0].set_color(RED) sailor_line_lengths[0].set_color(RED) sailor_line_lengths[0].set_stroke(RED, 1) self.remove(*list(keeper_lines) + list(keeper_line_lengths)) self.play( ReplacementTransform(keeper_lines.copy(), sailor_lines), ReplacementTransform( keeper_line_lengths.copy(), sailor_line_lengths), FadeOut(keeper_dp_column[:-1]), FadeOut(new_keeper_dp_decimal), ) self.play( Rotate(sailor_line_lengths[0], 30 * DEGREES, rate_func=wiggle) ) self.wait() self.play( ReplacementTransform(sailor_lines[0].copy(), dist), FadeIn(div), MoveToTarget(two), ) self.wait() self.play( two.restore, FadeOut(div), dist.restore, N.restore, ) self.play( FadeOut(sailor_lines), FadeOut(sailor_line_lengths), ) self.wait() def break_down_distance_product_by_parts(self): result_fraction = self.result_fraction result_fraction_rect = SurroundingRectangle(result_fraction) product_parts = self.product_parts = OldTex( "{|L_1 - K|", "\\over", "|L_1 - S|}", "\\cdot", "{|L_2 - K|", "\\over", "|L_2 - S|}", "\\cdot", "{|L_3 - K|", "\\over", "|L_3 - S|}", "\\cdots", ) product_parts.set_color_by_tex_to_color_map({ "K": BLUE, "S": YELLOW, }) product_parts.set_width(0.4 * FRAME_WIDTH) product_parts.next_to(result_fraction, DOWN, LARGE_BUFF, RIGHT) product_parts.shift(MED_SMALL_BUFF * RIGHT) sailor_lines = self.get_sailor_lines() sailor_lines.save_state() keeper_lines = self.get_keeper_lines() keeper_lines.save_state() sailor_length_braces = VGroup(VMobject()) # Add fluff first object keeper_length_braces = VGroup(VMobject()) # Add fluff first object triplets = [ ("S", sailor_length_braces, DOWN), ("K", keeper_length_braces, UP), ] for char, brace_group, vect in triplets: for part in product_parts.get_parts_by_tex(char): brace = Brace(part, vect, buff=SMALL_BUFF) brace.match_color(part) brace_group.add(brace) # Animations self.replace_lighthouses_with_labels() self.play( LaggedStartMap(FadeIn, product_parts), LaggedStartMap(FadeIn, sailor_lines, rate_func=there_and_back, remover=True), LaggedStartMap(FadeIn, keeper_lines, rate_func=there_and_back, remover=True), ) sailor_lines.restore() keeper_lines.restore() self.wait() keeper_line = self.keeper_line = keeper_lines[1].copy() sailor_line = self.sailor_line = sailor_lines[1].copy() keeper_brace = keeper_length_braces[1].copy() sailor_brace = sailor_length_braces[1].copy() self.play( ShowCreation(keeper_line), GrowFromCenter(keeper_brace), ) self.wait() self.play( ShowCreation(sailor_line), GrowFromCenter(sailor_brace), ) self.wait() for i in range(2, 4): self.play( Transform(keeper_line, keeper_lines[i]), Transform(keeper_brace, keeper_length_braces[i]), ) self.play( Transform(sailor_line, sailor_lines[i]), Transform(sailor_brace, sailor_length_braces[i]), ) self.wait() for i in range(4, self.num_lighthouses): anims = [ Transform(keeper_line, keeper_lines[i]), Transform(sailor_line, sailor_lines[i]), ] if i == 4: anims += [ FadeOut(sailor_brace), FadeOut(keeper_brace), ] self.play(*anims) self.play(FocusOn(result_fraction)) self.play(ShowPassingFlash(result_fraction_rect)) self.wait(3) def grow_circle_and_N(self, circle_scale_factor=2, N_multiple=3, added_anims=None): if added_anims is None: added_anims = [] circle = self.circle lights = self.lights labels = self.lighthouse_labels keeper = self.keeper sailor = self.sailor half_N = self.num_lighthouses / 2 anims = [] circle.generate_target() for pi in keeper, sailor: for mob in pi, pi.dot, pi.title: mob.generate_target() circle.target.scale(circle_scale_factor) circle.target.move_to(self.big_circle_center) self.circle = circle.target anims.append(MoveToTarget(circle)) self.num_lighthouses = int(N_multiple * self.num_lighthouses) new_lights = self.get_lights() for light in new_lights: light.scale(1.0 / circle_scale_factor) new_labels = self.get_light_labels() anims.append(ReplacementTransform(labels[1:], new_labels[1:])) if hasattr(self, "keeper_line"): keeper_line = self.keeper_line sailor_line = self.sailor_line self.keeper_lines = self.get_keeper_lines() self.sailor_lines = self.get_sailor_lines() anims += [ Transform(keeper_line, self.keeper_lines[-1]), Transform(sailor_line, self.sailor_lines[-1]), ] for group in lights, labels, new_lights, new_labels: group[0].fade(1) for mob in lights, labels: for x in range(len(new_lights) - len(mob)): mob.submobjects.insert( half_N + 1, VectorizedPoint(circle.get_left())) anims.append(ReplacementTransform(lights, new_lights)) keeper.dot.target.move_to(self.get_keeper_point()) sailor.dot.target.move_to(self.get_sailor_point()) for pi in keeper, sailor: pi.target.scale(0) pi.target.move_to(pi.dot.target) pi.title.target.scale(0.85) pi.title.target.next_to(pi.dot.target, RIGHT, SMALL_BUFF) anims += [ MoveToTarget(part) for pi in self.observers for part in [pi, pi.dot, pi.title] ] anims += added_anims self.circle = circle self.play(*anims, run_time=2) if self.add_lights_in_foreground: self.remove_foreground_mobjects(*self.lights) self.remove_foreground_mobjects(*self.lighthouse_labels) self.add_foreground_mobjects(new_lights, new_labels) self.wait() self.lights = new_lights self.lighthouse_labels = new_labels def show_limit_for_each_fraction(self): product_parts = self.product_parts keeper_line = self.keeper_line keeper_lines = self.keeper_lines sailor_line = self.sailor_line sailor_lines = self.sailor_lines labels = self.lighthouse_labels center = self.circle.get_center() center_dot = Dot(center) lh_points = self.get_lh_points() sailor_point = self.get_sailor_point() keeper_point = self.get_keeper_point() def get_angle_mob(p1, p2): angle1 = angle_of_vector(p1 - center) angle2 = angle_of_vector(p2 - center) arc = Arc(start_angle=angle1, angle=(angle2 - angle1), radius=1) arc.shift(center) return VGroup( center_dot, Line(center, p1), Line(center, p2), arc, ) angle_mob = get_angle_mob(lh_points[1], keeper_point) ratios = VGroup(*[ product_parts[i:i + 3] for i in [0, 4, 8] ]) term_rects = self.get_term_rects(ratios) limit_fractions = VGroup( OldTex("{2", "\\over", "1}"), OldTex("{4", "\\over", "3}"), OldTex("{6", "\\over", "5}"), ) limit_arrows = VGroup() for rect, fraction in zip(term_rects, limit_fractions): fraction.next_to(rect, DOWN, LARGE_BUFF) arrow = Arrow(rect, fraction, color=WHITE) limit_arrows.add(arrow) approx = OldTex("\\approx") approx.scale(1.5) approx.rotate(90 * DEGREES) approx.move_to(limit_arrows[0]) braces = self.get_all_circle_braces() # Show first lighthouse term_rect = term_rects[0].copy() self.play( Transform(keeper_line, keeper_lines[1]), Transform(sailor_line, sailor_lines[1]), FadeIn(term_rect), path_arc=-180 * DEGREES ) self.wait(2) self.play( FadeOut(VGroup(keeper_line, sailor_line)), FadeIn(braces[:2]), FadeIn(angle_mob) ) self.wait() self.play(Transform(angle_mob, get_angle_mob( lh_points[1], sailor_point))) self.wait(2) self.play( Write(approx), ReplacementTransform(ratios[0].copy(), limit_fractions[0]), FadeOut(angle_mob) ) self.wait() self.play(ReplacementTransform(approx, limit_arrows[0])) self.let_N_approach_infinity(braces[:2]) # Show second lighthouse self.play( Transform(term_rect, term_rects[1]), ReplacementTransform(limit_arrows[0].copy(), limit_arrows[1]), FadeIn(braces[2:4]) ) for group, color in (braces[:4], self.keeper_color), (braces[1:4], self.sailor_color): self.play( group.scale, 0.95, {"about_point": center}, group.set_color, color, rate_func=there_and_back ) self.wait(0.5) self.play( ReplacementTransform(ratios[1].copy(), limit_fractions[1]) ) self.wait() # Show third lighthouse braces[4:6].set_color(YELLOW) self.play( Transform(term_rect, term_rects[2]), ReplacementTransform(limit_arrows[1].copy(), limit_arrows[2]), FadeIn(braces[4:6]), braces[1:4].set_color, YELLOW, ReplacementTransform(limit_fractions[1].copy(), limit_fractions[2]) ) self.let_N_approach_infinity(braces[:6]) self.wait() # Set up for lighthouse "before" keeper ccw_product_group = VGroup( product_parts, limit_arrows, limit_fractions) cw_product_parts = OldTex( "\\cdots", "{|L_{-3} - K|", "\\over", "|L_{-3} - S|}", "\\cdot", "{|L_{-2} - K|", "\\over", "|L_{-2} - S|}", "\\cdot", "{|L_{-1} - K|", "\\over", "|L_{-1} - S|}", ) cw_product_parts.match_height(product_parts) cw_product_parts.set_color_by_tex_to_color_map({ "K": BLUE, "S": YELLOW, }) cw_product_parts.move_to(ratios, RIGHT) cw_ratios = VGroup(*[cw_product_parts[i:i + 3] for i in (9, 5, 1)]) cw_term_rects = self.get_term_rects(cw_ratios) cw_limit_fractions = VGroup( OldTex("{2", "\\over", "3}"), OldTex("{4", "\\over", "5}"), OldTex("{6", "\\over", "7}"), ) cw_limit_arrows = VGroup() for rect, fraction in zip(cw_term_rects, cw_limit_fractions): fraction.next_to(rect, DOWN, LARGE_BUFF) arrow = Arrow(rect, fraction, color=WHITE) cw_limit_arrows.add(arrow) cw_product_parts.save_state() cw_product_parts.next_to(product_parts, RIGHT, LARGE_BUFF) cw_label_rects = self.get_term_rects(labels[-1:-5:-1]) cw_label_rects.set_color(RED) braces[-8:].set_color(BLUE) braces[0].set_color(YELLOW) def show_braces(n): cw_group = braces[-2 * n:] for group in cw_group, VGroup(braces[0], *cw_group): self.play( group.scale, 0.95, {"about_point": center}, rate_func=there_and_back ) self.wait(0.5) # Animated clockwise-from-keeper terms self.play( ccw_product_group.scale, 0.5, {"about_edge": UL}, ccw_product_group.to_corner, UL, FadeOut(term_rect), FadeOut(braces[:6]), cw_product_parts.restore, ) term_rect = cw_term_rects[0].copy() self.play(LaggedStartMap(ShowCreationThenDestruction, cw_label_rects)) self.wait() self.play( FadeIn(term_rect), FadeIn(braces[-2:]), FadeIn(braces[0]), ) show_braces(1) self.play( GrowArrow(cw_limit_arrows[0]), FadeIn(cw_limit_fractions[0]) ) self.wait() # Second and third lighthouse before self.play( Transform(term_rect, cw_term_rects[1]), ReplacementTransform( cw_limit_arrows[0].copy(), cw_limit_arrows[1]), FadeIn(braces[-4:-2]), Write(cw_limit_fractions[1]) ) show_braces(2) self.wait() self.play( Transform(term_rect, cw_term_rects[2]), ReplacementTransform( cw_limit_arrows[1].copy(), cw_limit_arrows[2]), FadeIn(braces[-6:-4]), Write(cw_limit_fractions[2]) ) show_braces(3) self.let_N_approach_infinity(VGroup(braces[0], *braces[-6:])) self.wait() # Organize fractions fractions = VGroup(*it.chain(*list(zip( limit_fractions, cw_limit_fractions, )))) fractions.generate_target() wallis_product = VGroup() dots = VGroup() for fraction in fractions.target: fraction.match_height(cw_limit_fractions[0]) wallis_product.add(fraction) dot = OldTex("\\cdot") wallis_product.add(dot) dots.add(dot) final_dot = OldTex("\\cdots") for group in wallis_product, dots: group.submobjects[-1] = final_dot wallis_product.arrange(RIGHT, buff=MED_SMALL_BUFF) wallis_product.to_edge(RIGHT) self.play( FadeOut(limit_arrows), FadeOut(cw_limit_arrows), FadeOut(braces[-6:]), FadeOut(braces[0]), FadeOut(term_rect), ) self.play( cw_product_parts.scale, 0.5, cw_product_parts.next_to, product_parts, DOWN, { "aligned_edge": LEFT}, MoveToTarget(fractions), Write(dots), run_time=2, path_arc=90 * DEGREES ) self.wait() self.wallis_product = VGroup(dots, fractions) self.observers_brace = braces[0] def show_limit_of_lhs(self): brace = self.observers_brace wallis_product = self.wallis_product result_fraction = self.result_fraction N, dist, over, two = result_fraction distance_product_equals = self.distance_product_equals result_rect = SurroundingRectangle(result_fraction) result_rect.set_color(WHITE) equals = OldTex("=") equals.next_to(brace, LEFT, SMALL_BUFF) approx1, approx2, approx3 = [Tex("\\approx") for x in range(3)] approx1.next_to(brace, LEFT, SMALL_BUFF) half_two_pi_over_N = OldTex( "{1", "\\over", "2}", "{2", "\\pi", "\\over", "N}", ) pi = half_two_pi_over_N.get_part_by_tex("\\pi") half_two_pi_over_N.next_to(approx1, LEFT) approx2.next_to(half_two_pi_over_N, LEFT, SMALL_BUFF) approx3.move_to(distance_product_equals) pi_over_N = OldTex("(", "\\pi", "/", "N", ")") pi_over_N.next_to(N, RIGHT) N_shift = MED_LARGE_BUFF * RIGHT pi_over_N.shift(N_shift) pi_halves = OldTex("{\\pi", "\\over", "2}") pi_halves.next_to(result_rect, DOWN, LARGE_BUFF) pi_halves.shift(RIGHT) pi_halves_arrow = Arrow( result_rect.get_bottom(), pi_halves.get_top(), color=WHITE, buff=SMALL_BUFF ) last_equals = OldTex("=") last_equals.next_to(pi_halves, LEFT) self.play(ShowCreation(result_rect)) self.wait() self.play( dist.next_to, equals, LEFT, FadeIn(equals), GrowFromCenter(brace), ) self.wait() approx2.next_to(dist, LEFT, SMALL_BUFF) half_two_pi_over_N.next_to(approx2, LEFT) self.play( Write(half_two_pi_over_N), FadeIn(approx2) ) self.wait() self.play( FadeOut(half_two_pi_over_N[:4]), pi.shift, SMALL_BUFF * LEFT, ) self.wait() self.play( ReplacementTransform( half_two_pi_over_N[-3:].copy(), pi_over_N[1:4] ), FadeIn(pi_over_N[0]), FadeIn(pi_over_N[-1]), N.shift, N_shift * RIGHT, ReplacementTransform(distance_product_equals, approx3) ) self.wait() self.play( GrowArrow(pi_halves_arrow), wallis_product.shift, DOWN, ) self.play(Write(pi_halves)) self.wait(2) self.play( wallis_product.next_to, last_equals, LEFT, 2 * SMALL_BUFF, FadeIn(last_equals) ) final_rect = SurroundingRectangle( VGroup(wallis_product, pi_halves), buff=MED_SMALL_BUFF ) final_rect.set_color(YELLOW) self.play(ShowCreation(final_rect)) self.wait(2) # def let_N_approach_infinity(self, braces=None, factor=4, run_time=5, zoom_in_after=False): lights = self.lights labels = self.lighthouse_labels keeper, sailor = self.observers circle = self.circle if braces is None: braces = VGroup() start_fraction = 1.0 / self.num_lighthouses target_fraction = start_fraction / factor half_N = self.num_lighthouses / 2 fraction_tracker = ValueTracker(start_fraction) def get_fraction(): return fraction_tracker.get_value() def get_ks_distance(): return get_norm(keeper.dot.get_center() - sailor.dot.get_center()) def update_title_heights(*titles): for title in titles: if not hasattr(title, "original_height"): title.original_height = title.get_height() title.set_height(min( title.original_height, 0.8 * get_ks_distance(), )) if len(titles) > 1: return titles else: return titles[0] initial_light_width = lights[0].get_width() def update_lights(lights): for k in range(-half_N, half_N + 1): if k == 0: continue light = lights[k] light = light.set_width( (get_fraction() / start_fraction) * initial_light_width ) point = self.get_circle_point_at_proportion(k * get_fraction()) light.move_source_to(point) return lights def update_braces(braces): for brace in braces: f1 = brace.fraction1 * (get_fraction() / start_fraction) f2 = brace.fraction2 * (get_fraction() / start_fraction) new_brace = self.get_circle_brace(f1, f2) new_brace.match_style(brace) Transform(brace, new_brace).update(1) return braces light_update_anim = UpdateFromFunc(lights, update_lights) label_update_anim = UpdateFromFunc( labels, lambda ls: self.position_labels_outside_lights( update_title_heights(*ls)), ) sailor_dot_anim = UpdateFromFunc( sailor.dot, lambda d: d.move_to( self.get_circle_point_at_proportion(get_fraction() / 2)) ) sailor_title_anim = UpdateFromFunc( sailor.title, lambda m: update_title_heights(m).next_to( sailor.dot, RIGHT, SMALL_BUFF) ) keeper_title_anim = UpdateFromFunc( keeper.title, lambda m: update_title_heights(m).next_to( keeper.dot, RIGHT, SMALL_BUFF) ) braces_update_anim = UpdateFromFunc(braces, update_braces) lights[0].fade(1) labels[0].fade(1) all_updates = [ light_update_anim, label_update_anim, sailor_dot_anim, sailor_title_anim, keeper_title_anim, braces_update_anim, ] self.play( fraction_tracker.set_value, target_fraction, *all_updates, run_time=run_time ) if zoom_in_after: self.play( circle.scale, factor, {"about_point": circle.get_right()}, *all_updates, run_time=1 ) self.wait() self.play( circle.scale, 1.0 / factor, {"about_point": circle.get_right()}, *all_updates, run_time=1 ) self.wait() self.play( fraction_tracker.set_value, start_fraction, *all_updates, run_time=run_time / 2 ) def get_keeper_point(self): return self.get_circle_point_at_proportion(0) def get_sailor_point(self): return self.get_circle_point_at_proportion(0.5 / self.num_lighthouses) def create_pi_creatures(self): keeper = self.keeper = PiCreature(color=self.keeper_color).flip() sailor = self.sailor = Sailor() observers = self.observers = VGroup(keeper, sailor) observers.set_height(3) keeper.shift(4 * RIGHT + 2 * DOWN) sailor.shift(4 * RIGHT + 2 * UP) return VGroup(keeper, sailor) def replace_lighthouses_with_labels(self): lighthouse_labels = self.get_light_labels() self.lighthouse_labels = lighthouse_labels self.remove(self.lights[0], self.lighthouses[0]) self.play( FadeOut(self.lighthouses[1:]), FadeIn(lighthouse_labels[1:]), ) def get_light_labels(self): labels = VGroup() for count, point in enumerate(self.get_lh_points()): if count > self.num_lighthouses / 2: count -= self.num_lighthouses label = OldTex("L_{%d}" % count) label.scale(0.8) labels.add(label) self.position_labels_outside_lights(labels) return labels def position_labels_outside_lights(self, labels): center = self.circle.get_center() for light, label in zip(self.lights, labels): point = light[0].get_center() vect = (point - center) norm = get_norm(vect) buff = label.get_height() vect *= (norm + buff) / norm label.move_to(center + vect) return labels def get_keeper_lines(self, line_class=Line): lines = self.get_distance_lines(self.get_keeper_point()) lines.set_stroke(self.keeper_color, 3) return lines def get_sailor_lines(self, line_class=Line): lines = self.get_distance_lines(self.get_sailor_point()) lines.set_stroke(self.sailor_color, 3) return lines def get_term_rects(self, terms): return VGroup(*[ SurroundingRectangle(term, color=WHITE) for term in terms ]) def get_circle_brace(self, f1, f2): line = Line( self.get_circle_point_at_proportion(f1), self.get_circle_point_at_proportion(f2), ) angle = (line.get_angle() + TAU / 2) % TAU scale_factor = 1.5 line.rotate(-angle, about_point=ORIGIN) line.scale(scale_factor, about_point=ORIGIN) brace = Brace(line, DOWN, buff=SMALL_BUFF) group = VGroup(line, brace) group.scale(1.0 / scale_factor, about_point=ORIGIN) group.rotate(angle, about_point=ORIGIN) # Keep track of a fraction between -0.5 and 0.5 if f1 > 0.5: f1 -= 1 if f2 > 0.5: f2 -= 1 brace.fraction1 = f1 brace.fraction2 = f2 return brace def get_all_circle_braces(self): fractions = np.linspace(0, 1, 2 * self.num_lighthouses + 1) return VGroup(*[ self.get_circle_brace(f1, f2) for f1, f2 in zip(fractions, fractions[1:]) ]) class MentionJohnWallis(Scene): def construct(self): product = get_wallis_product(10) product.to_edge(UP) name = OldTexText("``Wallis product''") name.scale(1.5) name.set_color(BLUE) name.next_to(product, DOWN, MED_LARGE_BUFF) image = ImageMobject("John_Wallis") image.set_height(3) image.next_to(name, DOWN) image_name = OldTexText("John Wallis") image_name.next_to(image, DOWN) infinity = OldTex("\\infty") infinity.set_height(1.5) infinity.next_to(image, RIGHT, MED_LARGE_BUFF) self.add(product) self.wait() self.play(Write(name)) self.play(GrowFromEdge(image, UP)) self.play(Write(image_name)) self.wait(2) self.play(Write(infinity, run_time=3)) self.wait(2) class HowThisArgumentRequiresCommunitingLimits(PiCreatureScene): def construct(self): mathy, morty = self.pi_creatures scale_val = 0.7 factors = OldTex( "{|L_1 - K|", "\\over", "|L_1 - S|}", "\\cdot", "{|L_{-1} - K|", "\\over", "|L_{-1} - S|}", "\\cdot", "{|L_2 - K|", "\\over", "|L_2 - S|}", "\\cdot", "{|L_{-2} - K|", "\\over", "|L_{-2} - S|}", "\\cdot", "{|L_3 - K|", "\\over", "|L_3 - S|}", "\\cdot", "{|L_{-3} - K|", "\\over", "|L_{-3} - S|}", "\\cdots", ) factors.set_color_by_tex_to_color_map({ "K": BLUE, "S": YELLOW, }) equals = OldTex("=") result = OldTex( "{N", "{\\text{distance} \\choose \\text{between obs.}}", "\\over", "2}" ) top_line = VGroup(factors, equals, result) top_line.arrange(RIGHT, buff=SMALL_BUFF) result.shift(SMALL_BUFF * UP) top_line.scale(scale_val) top_line.to_edge(UP) fractions = VGroup(*[ factors[i:i + 3] for i in range(0, len(factors), 4) ]) fraction_limit_arrows = VGroup(*[ Vector(0.5 * DOWN).next_to(fraction, DOWN) for fraction in fractions ]) fraction_limit_arrows.set_color(WHITE) wallis_product = get_wallis_product(6) fraction_limits = VGroup(*[ wallis_product[i:i + 3] for i in range(0, 4 * 6, 4) ]) for lf, arrow in zip(fraction_limits, fraction_limit_arrows): lf.next_to(arrow, DOWN, MED_SMALL_BUFF) result_limit_arrow = fraction_limit_arrows[0].copy() result_limit_arrow.next_to(result, DOWN) result_limit_arrow.align_to(fraction_limit_arrows[0]) result_limit = wallis_product[-3:] result_limit.next_to(result_limit_arrow, DOWN, MED_SMALL_BUFF) lower_equals = OldTex("=") lower_equals.next_to(result_limit, LEFT) mult_signs = VGroup() for f1, f2 in zip(fraction_limits, fraction_limits[1:]): mult_sign = OldTex("\\times") mult_sign.move_to(VGroup(f1, f2)) mult_signs.add(mult_sign) cdots = OldTex("\\cdots") cdots.move_to(VGroup(fraction_limits[-1], lower_equals)) mult_signs.add(cdots) # Pi creatures react self.play( PiCreatureSays( mathy, "Whoa whoa whoa \\\\ there buddy", look_at=morty.eyes, target_mode="sassy", ), morty.change, "guilty", mathy.eyes, ) self.wait(2) # Write out commutative diagram self.play( RemovePiCreatureBubble( mathy, target_mode="raise_right_hand", look_at=factors, ), morty.change, "pondering", factors, LaggedStartMap(FadeIn, factors), ) self.wait() self.play( FadeIn(equals), Write(result) ) self.wait() self.play( LaggedStartMap(GrowArrow, fraction_limit_arrows), LaggedStartMap( FadeInFrom, fraction_limits, direction=UP ), run_time=4, lag_ratio=0.25, ) self.wait() self.play( LaggedStartMap(FadeIn, mult_signs), FadeIn(lower_equals), mathy.change, "sassy", ) self.play( GrowArrow(result_limit_arrow), FadeIn(result_limit, direction=UP), morty.change, "confused", ) self.wait(2) # Write general limit rule limit_rule = OldTex( "\\left( \\lim_{N \\to \\infty} a_N^{(1)} \\right)", "\\left( \\lim_{N \\to \\infty} a_N^{(2)} \\right)", "\\cdots", "=", "\\lim_{N \\to \\infty} \\left( a_N^{(1)} a_N^{(2)} \\cdots \\right)" ) limit_rule.next_to(self.pi_creatures, UP) q_marks = OldTex("???") q_marks.set_color(YELLOW) limit_equals = limit_rule.get_part_by_tex("=") q_marks.next_to(limit_equals, UP, SMALL_BUFF) index_of_equals = limit_rule.index_of_part(limit_equals) lhs_brace = Brace(limit_rule[:index_of_equals], UP) rhs_brace = Brace(limit_rule[index_of_equals + 1:], UP) self.play( FadeInFromDown(limit_rule), mathy.change, "angry", morty.change, "erm", ) self.play(GrowFromCenter(lhs_brace)) self.wait() self.play(ReplacementTransform(lhs_brace, rhs_brace)) self.wait(2) self.play(FadeOut(rhs_brace), Write(q_marks)) limit_rule.add(q_marks) self.wait(2) self.play(morty.change, "pondering") self.play(mathy.change, "tease") self.wait(3) self.play( Animation(limit_rule), morty.change, "pondering", mathy.change, "pondering", ) self.wait(3) # Write dominated convergence mover = VGroup( top_line, fraction_limits, fraction_limit_arrows, mult_signs, lower_equals, result_limit, result_limit_arrow, ) self.play( mover.next_to, FRAME_HEIGHT * UP / 2, UP, limit_rule.to_edge, UP, ) dominated_convergence = OldTexText("``Dominated convergence''") dominated_convergence.set_color(BLUE) dominated_convergence.next_to(limit_rule, DOWN, LARGE_BUFF) see_blog_post = OldTexText("(See supplementary blog post)") see_blog_post.next_to(dominated_convergence, DOWN) self.play( FadeInFromDown(dominated_convergence), mathy.change, "raise_right_hand", ) self.play(morty.change, "thinking") self.wait() self.play(Write(see_blog_post)) self.wait(4) def create_pi_creatures(self): group = VGroup(PiCreature(color=GREY), Mortimer()) group.set_height(2) group.arrange(RIGHT, buff=4) group.to_edge(DOWN) return group class NonCommunitingLimitsExample(Scene): CONFIG = { "num_terms_per_row": 6, "num_rows": 5, "x_spacing": 0.75, "y_spacing": 1, } def construct(self): rows = VGroup(*[ self.get_row(seven_index) for seven_index in range(self.num_rows) ]) rows.add(self.get_v_dot_row()) for n, row in enumerate(rows): row.move_to(n * self.y_spacing * DOWN) rows.center().to_edge(UP) rows[-1].shift(MED_SMALL_BUFF * UP) row_rects = VGroup(*list(map(SurroundingRectangle, rows[:-1]))) row_rects.set_color(YELLOW) columns = VGroup(*[ VGroup(*[row[0][i] for row in rows]) for i in range(len(rows[0][0])) ]) column_rects = VGroup(*list(map(SurroundingRectangle, columns))) column_rects.set_color(BLUE) row_arrows = VGroup(*[ OldTex("\\rightarrow").next_to(row, RIGHT) for row in rows[:-1] ]) row_products = VGroup(*[ Integer(7).next_to(arrow) for arrow in row_arrows ]) row_products.set_color(YELLOW) row_product_limit_dots = OldTex("\\vdots") row_product_limit_dots.next_to(row_products, DOWN) row_product_limit = Integer(7) row_product_limit.set_color(YELLOW) row_product_limit.next_to(row_product_limit_dots, DOWN) column_arrows = VGroup(*[ OldTex("\\downarrow").next_to(part, DOWN, SMALL_BUFF) for part in rows[-1][0] ]) column_limits = VGroup(*[ Integer(1).next_to(arrow, DOWN) for arrow in column_arrows ]) column_limits.set_color(BLUE) column_limit_dots = self.get_row_dots(column_limits) column_limits_arrow = OldTex("\\rightarrow").next_to( column_limit_dots, RIGHT ) product_of_limits = Integer(1).next_to(column_limits_arrow, RIGHT) product_of_limits.set_color(BLUE) self.add(rows) self.wait() self.play(LaggedStartMap(ShowCreation, row_rects)) self.wait(2) row_products_iter = iter(row_products) self.play( LaggedStartMap(Write, row_arrows), LaggedStartMap( ReplacementTransform, rows[:-1].copy(), lambda r: (r, next(row_products_iter)) ) ) self.wait() self.play(Write(row_product_limit_dots)) self.play(Write(row_product_limit)) self.wait() self.play(LaggedStartMap(FadeOut, row_rects)) self.play(LaggedStartMap(FadeIn, column_rects)) self.wait() column_limit_iter = iter(column_limits) self.play( LaggedStartMap(Write, column_arrows), LaggedStartMap( ReplacementTransform, columns.copy(), lambda c: (c, next(column_limit_iter)) ) ) self.wait() self.play(Write(column_limits_arrow)) self.play( Write(product_of_limits), FadeOut(row_product_limit) ) self.wait() def get_row(self, seven_index): terms = [1] * (self.num_terms_per_row) if seven_index < len(terms): terms[seven_index] = 7 row = VGroup(*list(map(Integer, terms))) self.arrange_row(row) dots = self.get_row_dots(row) return VGroup(row, dots) def get_v_dot_row(self): row = VGroup(*[ OldTex("\\vdots") for x in range(self.num_terms_per_row) ]) self.arrange_row(row) dots = self.get_row_dots(row) dots.fade(1) return VGroup(row, dots) def arrange_row(self, row): for n, part in enumerate(row): part.move_to(n * self.x_spacing * RIGHT) def get_row_dots(self, row): dots = VGroup() for p1, p2 in zip(row, row[1:]): dots.add(OldTex("\\cdot").move_to(VGroup(p1, p2))) dots.add(OldTex("\\cdots").next_to(row, RIGHT)) return dots class DelicacyInIntermixingSeries(Scene): def construct(self): n_terms = 6 top_product, bottom_product = products = VGroup(*[ OldTex(*it.chain(*[ ["{%d" % (2 * x), "\\over", "%d}" % (2 * x + u), "\\cdot"] for x in range(1, n_terms + 1) ])) for u in (-1, 1) ]) top_product.set_color(GREEN) bottom_product.set_color(BLUE) top_product.to_edge(UP) bottom_product.next_to(top_product, DOWN, LARGE_BUFF) infinity = OldTex("\\infty") top_product.limit = infinity zero = OldTex("0") bottom_product.limit = zero for product in products: cdots = OldTex("\\cdots") cdots.move_to(product[-1], LEFT) cdots.match_color(product) product.submobjects[-1] = cdots product.parts = VGroup(*[ product[i:i + 4] for i in range(0, len(product), 4) ]) arrow = Vector(0.75 * RIGHT) arrow.set_color(WHITE) arrow.next_to(product, RIGHT) product.arrow = arrow product.limit.next_to(arrow, RIGHT) product.limit.match_color(product) group = VGroup(products, infinity) h_line = Line(LEFT, RIGHT) h_line.stretch_to_fit_width(group.get_width() + LARGE_BUFF) h_line.next_to(group, DOWN, aligned_edge=RIGHT) times = OldTex("\\times") times.next_to(h_line, UP, aligned_edge=LEFT) q_marks = OldTex("?????") q_marks.set_color_by_gradient(BLUE, YELLOW) q_marks.scale(2) q_marks.next_to(h_line, DOWN) # Show initial products self.play( LaggedStartMap(FadeIn, top_product), LaggedStartMap(FadeIn, bottom_product), ) self.wait() for product in products: self.play( GrowArrow(product.arrow), FadeIn(product.limit, direction=LEFT) ) self.wait() self.play( Write(times), ShowCreation(h_line) ) self.play(Write(q_marks, run_time=3)) self.wait(2) # Show alternate interweaving top_parts_iter = iter(top_product.parts) bottom_parts_iter = iter(bottom_product.parts) movers1 = VGroup() while True: try: new_terms = [ next(bottom_parts_iter), next(top_parts_iter), next(top_parts_iter), ] movers1.add(*new_terms) except StopIteration: break new_product = VGroup() movers1.save_state() for mover in movers1: mover.generate_target() new_product.add(mover.target) new_product.arrange(RIGHT, buff=SMALL_BUFF) new_product.next_to(h_line, DOWN, LARGE_BUFF, aligned_edge=LEFT) new_arrow = top_product.arrow.copy() new_arrow.next_to(new_product, RIGHT) ghost_top = top_product.copy().fade() ghost_bottom = bottom_product.copy().fade() self.add(ghost_top, top_product) self.add(ghost_bottom, bottom_product) new_limit = OldTex("\\frac{\\pi}{2}", "\\sqrt{2}") new_limit.next_to(new_arrow, RIGHT) randy = Randolph(height=1.5) randy.flip() randy.to_corner(DR) movers2 = VGroup(*it.chain(*list(zip( top_product.parts, bottom_product.parts )))) final_product = VGroup() for mover in movers2: mover.final_position = mover.copy() if mover is movers2[-2]: # Excessive ellipses final_dot = mover.final_position[-1][0] mover.final_position.submobjects[-1] = final_dot final_product.add(mover.final_position) final_product.arrange(RIGHT, buff=SMALL_BUFF) final_product.move_to(new_product, RIGHT) self.play( FadeOut(q_marks), LaggedStartMap( MoveToTarget, movers1, run_time=5, lag_ratio=0.2, ) ) self.play( GrowArrow(new_arrow), FadeIn(new_limit, LEFT), bottom_product.parts[3:].fade, 1, ) self.play(FadeIn(randy)) self.play(randy.change, "confused", new_limit) self.wait() self.play(Blink(randy)) self.wait() self.play(LaggedStartMap( Transform, movers2, lambda m: (m, m.final_position), run_time=3, path_arc=TAU / 4, )) self.play( FadeOut(new_limit[1]), randy.change, "pondering", new_limit ) self.wait(2) self.play(Blink(randy)) self.wait(2) class JustTechnicalities(TeacherStudentsScene): def construct(self): self.teacher_says( "These are just \\\\ technicalities" ) self.play_all_student_changes("happy") self.play(RemovePiCreatureBubble( self.teacher, target_mode="raise_right_hand", )) self.look_at(self.screen) self.wait(4) class KeeperAndSailorForSineProduct(KeeperAndSailor): CONFIG = { # "ambient_light_config": CHEAP_AMBIENT_LIGHT_CONFIG, "new_sailor_fraction": 0.7, "big_circle_center": FRAME_WIDTH * LEFT / 2 + 2.6 * LEFT, } def construct(self): # Rerun old animation (probably to be skipped)g self.force_skipping() self.place_lighthouses() self.introduce_observers() self.write_distance_product_fraction() self.revert_to_original_skipping_status() # New animations self.replace_lighthouses_with_labels() self.move_sailor_to_new_spot() self.show_new_distance_product() self.show_new_limit_of_ratio() self.show_new_infinite_product() def move_sailor_to_new_spot(self): sailor = self.sailor fraction = self.new_sailor_fraction self.get_sailor_point = lambda: self.get_circle_point_at_proportion( fraction / self.num_lighthouses ) target_point = self.get_sailor_point() brace1 = self.get_circle_brace(0, 0.5 / self.num_lighthouses) brace2 = self.get_circle_brace(0, fraction / self.num_lighthouses) center = self.circle.get_center() radius = self.get_radius() def warp_func(point): vect = point - center norm = get_norm(vect) new_norm = norm + 0.5 * (radius - norm) return center + new_norm * vect / norm brace1.apply_function(warp_func) brace2.apply_function(warp_func) scale_val = 0.7 words1 = OldTexText("Instead of", "$\\frac{1}{2}$") words1.set_color_by_tex("$", YELLOW) words1.scale(scale_val) words1.next_to(brace1.get_center(), LEFT) words2 = OldTexText("Some other fraction", "$f$") words2.set_color_by_tex("$", GREEN) words2.scale(scale_val) words2.next_to(brace2.get_center(), LEFT) self.play( GrowFromCenter(brace1), Write(words1, run_time=1) ) self.wait() self.play( sailor.dot.move_to, target_point, sailor.dot.set_color, GREEN, sailor.set_color, GREEN, MaintainPositionRelativeTo(sailor, sailor.dot), MaintainPositionRelativeTo(sailor.title, sailor), ReplacementTransform(brace1, brace2), ReplacementTransform(words1, words2), run_time=1.5 ) self.fraction_label_group = VGroup(brace2, words2) def show_new_distance_product(self): result_fraction = self.result_fraction N, dist, over, two = result_fraction sailor_dp = self.distance_product_fraction[-1] sailor_dp_rect = SurroundingRectangle(sailor_dp) sailor_dp_rect.set_color(GREEN) sailor_lines = self.get_distance_lines( self.sailor.dot.get_center(), line_class=DashedLine ) chord_f = OldTexText("Chord(", "$f$", ")", arg_separator="") chord_f.set_color_by_tex("$f$", GREEN) chord_f.move_to(two, UP) two_cross = Cross(SurroundingRectangle(two)) two_group = VGroup(two, two_cross) self.play( ShowCreation(sailor_dp_rect), LaggedStartMap(ShowCreation, sailor_lines), ) self.wait() self.play(ShowCreation(two_cross)) self.play( two_group.next_to, chord_f, DOWN, ReplacementTransform( VGroup( sailor_dp[:-6].copy(), sailor_dp[-6:-4].copy(), sailor_dp[-4:-2].copy(), sailor_dp[-2:].copy(), ), chord_f ) ) self.wait() self.play(LaggedStartMap(FadeOut, VGroup( sailor_lines, sailor_dp_rect, two_group ))) result_fraction.submobjects[-1] = chord_f def show_new_limit_of_ratio(self): fraction_label_group = self.fraction_label_group fraction_brace, fraction_words = fraction_label_group frac1 = OldTex( "{N", "(", "f", " \\cdot 2\\pi / N)", "\\over", "\\text{Chord}(", "f", ")}" ) frac2 = OldTex( "{f", "\\cdot", "2", "\\pi", "\\over", "\\text{Chord}(", "f", ")}" ) for frac in frac1, frac2: frac.set_color_by_tex("f", GREEN, substring=False) arrow1, arrow2 = [ Vector(0.75 * DOWN, color=WHITE) for x in range(2) ] group = VGroup(arrow1, frac1, arrow2, frac2) group.arrange(DOWN) group.next_to(self.result_fraction, DOWN) big_group = VGroup(self.result_fraction, *group) arrow = OldTex("\\rightarrow") arrow.move_to(self.distance_product_equals) fraction_brace.generate_target() fraction_brace.target.rotate(-10 * DEGREES) fraction_brace.target.scale(0.65) fraction_brace.target.align_to(ORIGIN, DOWN) fraction_brace.target.shift(3.3 * LEFT) fraction_words.generate_target() fraction_words.target[0][:9].next_to( VGroup(fraction_words.target[0][9:], fraction_words.target[1]), UP, SMALL_BUFF ) fraction_words.target.next_to(fraction_brace.target, LEFT, SMALL_BUFF) self.play(LaggedStartMap(FadeIn, group)) self.grow_circle_and_N( added_anims=[ MoveToTarget(fraction_brace), MoveToTarget(fraction_words), ] ) self.wait() self.play( big_group.next_to, self.distance_product_equals, RIGHT, {"submobject_to_align": frac2}, UpdateFromAlphaFunc( big_group[:-1], lambda m, a: m.set_fill(opacity=1 - a), ), Transform(self.distance_product_equals, arrow) ) self.wait() self.result_fraction = frac2 def show_new_infinite_product(self): scale_val = 0.7 fractions = OldTex( "\\cdots", "{|L_{-2} - K|", "\\over", "|L_{-2} - S|}", "\\cdot", "{|L_{-1} - K|", "\\over", "|L_{-1} - S|}", "\\cdot", "{|L_1 - K|", "\\over", "|L_1 - S|}", "\\cdot", "{|L_2 - K|", "\\over", "|L_2 - S|}", "\\cdot", "{|L_3 - K|", "\\over", "|L_3 - S|}", "\\cdots", ) fractions.scale(scale_val) fractions.move_to(self.observers) fractions.to_edge(RIGHT) fractions.set_color_by_tex_to_color_map({ "K": BLUE, "S": GREEN, }) keeper_lines = self.get_keeper_lines() sailor_lines = self.get_sailor_lines() sailor_lines.set_color(GREEN) ratios = VGroup(*[ fractions[i:i + 3] for i in range(1, len(fractions), 4) ]) limit_arrows = VGroup(*[ Vector(0.5 * DOWN, color=WHITE).next_to(ratio, DOWN, SMALL_BUFF) for ratio in ratios ]) limits = VGroup(*[ OldTex("{%d" % k, "\\over", "%d" % k, "-", "f}") for k in (-2, -1, 1, 2, 3) ]) for limit, arrow in zip(limits, limit_arrows): limit.set_color_by_tex("f", GREEN) limit.scale(scale_val) limit.next_to(arrow, DOWN, SMALL_BUFF) dots = VGroup() dots.add(OldTex("\\cdots").next_to(limits, LEFT)) for l1, l2 in zip(limits, limits[1:]): dots.add(OldTex("\\cdot").move_to(VGroup(l1, l2))) dots.add(OldTex("\\cdots").next_to(limits, RIGHT)) full_limits_group = VGroup(*list(limits) + list(dots)) # brace = Brace(limits, DOWN) product = OldTex( "\\prod_{k \\ne 0}", "{k", "\\over", "k", "-", "f}" ) product.next_to(limits, DOWN, LARGE_BUFF) product_lines = VGroup( DashedLine(full_limits_group.get_corner(DL), product.get_corner(UL)), DashedLine(full_limits_group.get_corner(DR), product.get_corner(UR)), ) product_lines.set_color(YELLOW) self.play( LaggedStartMap(FadeIn, fractions), *[ LaggedStartMap( FadeIn, VGroup(*list(lines[-10:]) + list(lines[1:10])), rate_func=there_and_back, remover=True, run_time=3, lag_ratio=0.1 ) for lines in (keeper_lines, sailor_lines) ] ) self.wait() self.play( LaggedStartMap(GrowArrow, limit_arrows), LaggedStartMap( FadeInFrom, limits, lambda m: (m, UP), ), LaggedStartMap(FadeIn, dots) ) self.wait() self.play( # GrowFromCenter(brace), ShowCreation(product_lines, lag_ratio=0), FadeIn(product) ) self.wait() # Shift everything result_fraction = self.result_fraction big_group = VGroup( fractions, limit_arrows, full_limits_group, # brace, product_lines, product, ) big_group.generate_target() big_group.target.to_edge(UP) equals = OldTex("=") equals.next_to(big_group.target[-1], LEFT) result_fraction.generate_target() result_fraction.target.next_to(equals, LEFT) self.play( MoveToTarget(big_group), FadeIn(equals), MoveToTarget(result_fraction), FadeOut(self.distance_product_fraction), FadeOut(self.distance_product_equals), ) self.wait() # Replace chord with sine chord_f = result_fraction[-3:] f_pi = VGroup(result_fraction[0], result_fraction[3]) over = result_fraction.get_part_by_tex("\\over") dot_two = result_fraction[1:3] two_sine_f_pi = OldTex("2", "\\sin(", "f", "\\pi", ")") sine_f_pi = two_sine_f_pi[1:] two_sine_f_pi.set_color_by_tex("f", GREEN) two_sine_f_pi.move_to(chord_f) self.play( FadeIn(two_sine_f_pi), chord_f.shift, DOWN ) self.wait() self.play(FadeOut(chord_f)) self.wait() self.play( f_pi.arrange, RIGHT, {"buff": SMALL_BUFF}, f_pi.next_to, over, UP, SMALL_BUFF, FadeOut(dot_two), FadeOut(two_sine_f_pi[0]), sine_f_pi.shift, SMALL_BUFF * LEFT, ) self.wait() # Reciprocate pairs = VGroup() for num, denom in zip(fractions[1::4], fractions[3::4]): pairs.add(VGroup(num, denom)) for limit in limits: pairs.add(VGroup(limit[0], limit[2:])) pairs.add( VGroup(f_pi, sine_f_pi), VGroup(product[1], product[3:]), ) for pair in pairs: pair.generate_target() pair.target[0].move_to(pair[1], UP) pair.target[1].move_to(pair[0], DOWN) self.play( LaggedStartMap( MoveToTarget, pairs, path_arc=180 * DEGREES, run_time=3, ), product_lines[1].scale, 0.9, {"about_point": product_lines[1].get_start()}, product_lines[1].shift, SMALL_BUFF * UP ) self.wait() # Rearrange one_minus_f_over_k = OldTex( "\\left(", "1", "-", "{f", "\\over", "k}", "\\right)" ) # 0 1 2 3 4 # k / k - f one_minus_f_over_k.set_color_by_tex("{f", GREEN) one_minus_f_over_k.next_to(product[0], RIGHT, buff=SMALL_BUFF) one_minus_f_over_k.shift(SMALL_BUFF * UP) self.play( FadeIn(one_minus_f_over_k[0]), FadeIn(one_minus_f_over_k[-1]), FadeOut(product_lines), *[ ReplacementTransform(product[i], one_minus_f_over_k[j]) for i, j in [(3, 1), (4, 2), (5, 3), (2, 4), (1, 5)] ] ) self.wait() product = VGroup(product[0], *one_minus_f_over_k) product.generate_target() f_pi.generate_target() f_pi.target.next_to(equals, RIGHT, SMALL_BUFF) product.target.next_to(f_pi.target, RIGHT, SMALL_BUFF) product.target.shift(SMALL_BUFF * DOWN) self.play( sine_f_pi.next_to, equals, LEFT, SMALL_BUFF, FadeOut(over), MoveToTarget(f_pi), MoveToTarget(product), ) self.wait() # Show final result rect = SurroundingRectangle(VGroup(sine_f_pi, product)) rect.set_color(BLUE) pi_creatures = VGroup( PiCreature(color=BLUE_E), PiCreature(color=BLUE_C), PiCreature(color=BLUE_D), Mortimer() ) pi_creatures.arrange(RIGHT, LARGE_BUFF) pi_creatures.set_height(1) pi_creatures.next_to(rect, DOWN) for pi in pi_creatures: pi.change("hooray", rect) pi.save_state() pi.change("plain") pi.fade(1) self.play( ShowCreation(rect), LaggedStartMap(ApplyMethod, pi_creatures, lambda m: (m.restore,)) ) for x in range(4): self.play(Blink(random.choice(pi_creatures))) self.wait() class Conclusion(TeacherStudentsScene): CONFIG = { "camera_config": {"background_opacity": 1}, } def construct(self): wallis_product = get_wallis_product(6) wallis_product.move_to(self.hold_up_spot, DOWN) wallis_product.shift_onto_screen() for i in range(0, len(wallis_product) - 5, 4): color = GREEN if (i / 4) % 2 == 0 else BLUE wallis_product[i:i + 3].set_color(color) sine_formula = OldTex( "\\sin(", "f", "\\pi", ")", "=", "f", "\\pi", "\\prod_{k \\ne 0}", "\\left(", "1", "-", "{f", "\\over", "k}", "\\right)" ) sine_formula.set_color_by_tex("f", GREEN) sine_formula.set_color_by_tex("left", WHITE) sine_formula.move_to(self.hold_up_spot, DOWN) sine_formula.shift_onto_screen() euler = ImageMobject("Euler") euler.set_height(2.5) basel_problem = OldTex( "\\frac{1}{1^2} + ", "\\frac{1}{2^2} + ", "\\frac{1}{3^2} + ", "\\cdots", "\\frac{\\pi^2}{6}" ) basel_problem.move_to(self.hold_up_spot, DOWN) implication = OldTex("\\Rightarrow") implication.next_to(basel_problem[0][1], LEFT) self.play( self.teacher.change, "raise_right_hand", FadeInFromDown(wallis_product), self.change_students("thinking", "hooray", "surprised") ) self.wait() self.play( self.teacher.change, "hooray", FadeInFromDown(sine_formula), wallis_product.to_edge, UP, self.change_students("pondering", "thinking", "erm") ) self.wait(3) self.play( sine_formula.next_to, implication, LEFT, {"submobject_to_align": sine_formula[-1]}, FadeIn(implication), ) euler.next_to(sine_formula, UP) self.play( FadeIn(euler), LaggedStartMap(FadeIn, basel_problem), self.teacher.change, "happy", self.change_students("sassy", "confused", "hesitant") ) self.wait(2) wallis_rect = SurroundingRectangle(wallis_product) wallis_rect.set_color(BLUE) basel_rect = SurroundingRectangle(basel_problem) basel_rect.set_color(YELLOW) self.play( ShowCreation(wallis_rect), FadeOut(implication), FadeOut(euler), FadeOut(sine_formula), ) self.play( ShowCreation(basel_rect), self.teacher.change, "surprised", self.change_students(*["happy"] * 3) ) self.wait(5) class ByLine(Scene): def construct(self): self.add(OldTexText(""" Written and animated by \\\\ \\quad \\\\ Sridhar Ramesh \\\\ Grant Sanderson """).shift(2 * UP)) class SponsorUnderlay(PiCreatureScene): CONFIG = { "default_pi_creature_start_corner": DR, } def construct(self): url = OldTexText("https://udacity.com/3b1b/") url.to_corner(UL) rect = ScreenRectangle(height=5.5) rect.next_to(url, DOWN) rect.to_edge(LEFT) url.next_to(rect, UP) url.save_state() url.next_to(self.pi_creature.get_corner(UL), UP) logo = SVGMobject(file_name="udacity") logo.set_fill("#02b3e4") logo.to_corner(UR) self.add(logo) self.play( Write(url), self.pi_creature.change, "raise_right_hand" ) self.play( url.restore, ShowCreation(rect), path_arc=90 * DEGREES, ) 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, UL) url_rect = SurroundingRectangle(url) self.play(ShowCreation(url_rect)) self.play(FadeOut(url_rect)) self.wait(3) class EndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "Juan Benet", "Keith Smith", "Chloe Zhou", "Ross Garber", "Desmos", "Burt Humburg", "CrypticSwarm", "Hoang Tung Lam", "Sergei", "Devin Scott", "George John", "Akash Kumar", "Felix Tripier", "Arthur Zey", "David Kedmey", "Ali Yahya", "Mayank M. Mehrotra", "Lukas Biewald", "Yana Chernobilsky", "Kaustuv DeBiswas", "Yu Jun", "dave nicponski", "Damion Kistler", "Jordan Scales", "Markus Persson", "Fred Ehrsam", "Britt Selvitelle", "Jonathan Wilson", "Ryan Atallah", "Joseph John Cox", "Luc Ritchie", "Cooper Jones", "James Hughes", "John V Wertheim", "Chris Giddings", "Song Gao", "William Fritzon", "Alexander Feldman", # "孟子易", "Mengzi yi", "zheng zhang", "Matt Langford", "Max Mitchell", "Richard Burgmann", "John Griffith", "Chris Connett", "Steven Tomlinson", "Jameel Syed", "Bong Choung", "Ignacio Freiberg", "Zhilong Yang", "Dan Esposito (Guardion)", "Giovanni Filippi", "Eric Younge", "Prasant Jagannath", "Cody Brocious", "James H. Park", "Norton Wang", "Kevin Le", "Tianyu Ge", "David MacCumber", "Oliver Steele", "Yaw Etse", "Dave B", "Waleed Hamied", "George Chiesa", "supershabam", "Delton Ding", "Thomas Tarler", "Jonathan Eppele", "Isak Hietala", "1stViewMaths", "Jacob Magnuson", "Mark Govea", "Clark Gaebel", "Mathias Jansson", "David Clark", "Michael Gardner", "Mads Elvheim", "Awoo", "Dr David G. Stork", "Ted Suzman", "Linh Tran", "Andrew Busey", "John Haley", "Ankalagon", "Eric Lavault", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Ryan Dahl", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", # "世珉 匡", "Shi min kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] } class Thumbnail(DistanceProductScene): def construct(self): product = get_wallis_product() product.scale(1.5) product.move_to(2.5 * UP) frac_lines = product.get_parts_by_tex("\\over") frac_indices = list(map(product.index_of_part, frac_lines)) parts = VGroup(*[ product[i-1:i+2] for i in frac_indices ]) parts[::2].set_color(WHITE) parts[1::2].set_color(WHITE) parts[-1].set_color(WHITE) parts[-1].set_background_stroke(color=YELLOW, width=3) parts[-1].scale(1.5, about_edge=LEFT) product[-4:].next_to(product[:-4], DOWN, MED_LARGE_BUFF) product.scale(1.2).center().to_edge(UP) # new_proof = OldTexText("New proof") # new_proof.scale(2.5) # new_proof.set_color(YELLOW) # new_proof.set_stroke(RED, 0.75) # new_proof.next_to(product, DOWN, MED_LARGE_BUFF) circle = self.circle = Circle(radius=8, color=YELLOW) circle.move_to(3 * DOWN, DOWN) bottom_dot = Dot(color=BLUE) bottom_dot.move_to(circle.get_bottom()) observer = PiCreature(mode="pondering") observer.set_height(0.5) observer.next_to(bottom_dot, DOWN) lights = VGroup() lines = VGroup() light_config = dict(HIGHT_QUALITY_AMBIENT_LIGHT_CONFIG) # light_config = dict(CHEAP_AMBIENT_LIGHT_CONFIG) light_config["max_opacity"] = 1 step = 0.03 for frac in np.arange(step, 0.2, step): for u in -1, 1: light = AmbientLight(**light_config) dot = Dot(color=BLUE) dot.move_to(light) light.add_to_back(dot) light.move_to(self.get_circle_point_at_proportion(u * frac - 0.25)) lights.add(light) line = DashedLine(dot.get_center(), circle.get_bottom()) lines.add(line) self.add(circle) self.add(lights) self.add(product) # self.add(new_proof) self.add(bottom_dot, observer)
# -*- coding: utf-8 -*- import scipy.integrate from manim_imports_ext import * USE_ALMOST_FOURIER_BY_DEFAULT = True NUM_SAMPLES_FOR_FFT = 1000 DEFAULT_COMPLEX_TO_REAL_FUNC = lambda z : z.real def get_fourier_graph( axes, time_func, t_min, t_max, n_samples = NUM_SAMPLES_FOR_FFT, complex_to_real_func = lambda z : z.real, color = RED, ): # N = n_samples # T = time_range/n_samples time_range = float(t_max - t_min) time_step_size = time_range/n_samples time_samples = np.vectorize(time_func)(np.linspace(t_min, t_max, n_samples)) fft_output = np.fft.fft(time_samples) frequencies = np.linspace(0.0, n_samples/(2.0*time_range), n_samples//2) # #Cycles per second of fouier_samples[1] # (1/time_range)*n_samples # freq_step_size = 1./time_range graph = VMobject() graph.set_points_smoothly([ axes.coords_to_point( x, complex_to_real_func(y)/n_samples, ) for x, y in zip(frequencies, fft_output[:n_samples//2]) ]) graph.set_color(color) f_min, f_max = [ axes.x_axis.point_to_number(graph.get_points()[i]) for i in (0, -1) ] graph.underlying_function = lambda f : axes.y_axis.point_to_number( graph.point_from_proportion((f - f_min)/(f_max - f_min)) ) return graph def get_fourier_transform( func, t_min, t_max, complex_to_real_func = DEFAULT_COMPLEX_TO_REAL_FUNC, use_almost_fourier = USE_ALMOST_FOURIER_BY_DEFAULT, **kwargs ##Just eats these ): scalar = 1./(t_max - t_min) if use_almost_fourier else 1.0 def fourier_transform(f): z = scalar*scipy.integrate.quad( lambda t : func(t)*np.exp(complex(0, -TAU*f*t)), t_min, t_max )[0] return complex_to_real_func(z) return fourier_transform class TODOStub(Scene): def construct(self): pass ## class Introduction(TeacherStudentsScene): def construct(self): title = OldTexText("Fourier Transform") title.scale(1.2) title.to_edge(UP, buff = MED_SMALL_BUFF) func = lambda t : np.cos(2*TAU*t) + np.cos(3*TAU*t) graph = FunctionGraph(func, x_min = 0, x_max = 5) graph.stretch(0.25, 1) graph.next_to(title, DOWN) graph.to_edge(LEFT) graph.set_color(BLUE) fourier_graph = FunctionGraph( get_fourier_transform(func, 0, 5), x_min = 0, x_max = 5 ) fourier_graph.move_to(graph) fourier_graph.to_edge(RIGHT) fourier_graph.set_color(RED) arrow = Arrow(graph, fourier_graph, color = WHITE) self.add(title, graph) self.student_thinks( "What's that?", look_at = title, target_mode = "confused", index = 1, ) self.play( GrowArrow(arrow), ReplacementTransform(graph.copy(), fourier_graph) ) self.wait(2) self.student_thinks( "Pssht, I got this", target_mode = "tease", index = 2, added_anims = [RemovePiCreatureBubble(self.students[1])] ) self.play(self.teacher.change, "hesitant") self.wait(2) class TODOInsertUnmixingSound(TODOStub): CONFIG = { "message" : "Show unmixing sound" } class OtherContexts(PiCreatureScene): def construct(self): items = VGroup(*list(map(TexText, [ "Extracting frequencies from sound", "Uncertainty principle", "Riemann Zeta function and primes", "Differential equations", ]))) items.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) items.to_corner(UP+LEFT) items[1:].set_fill(opacity = 0.2) morty = self.pi_creature morty.to_corner(UP+RIGHT) self.add(items) for item in items[1:]: self.play( LaggedStartMap( ApplyMethod, item, lambda m : (m.set_fill, {"opacity" : 1}), ), morty.change, "thinking", ) self.wait() class TODOInsertCosineWrappingAroundCircle(TODOStub): CONFIG = { "message" : "Give a picture-in-picture \\\\ of cosine wrapping around circle", } class AddingPureFrequencies(PiCreatureScene): CONFIG = { "A_frequency" : 2.1, "A_color" : YELLOW, "D_color" : PINK, "F_color" : TEAL, "C_color" : RED, "sum_color" : GREEN, "equilibrium_height" : 1.5, } def construct(self): self.add_speaker() self.play_A440() self.measure_air_pressure() self.play_lower_pitch() self.play_mix() self.separate_out_parts() self.draw_sum_at_single_point() self.draw_full_sum() self.add_more_notes() def add_speaker(self): speaker = SVGMobject(file_name = "speaker") speaker.to_edge(DOWN) self.add(speaker) self.speaker = speaker def play_A440(self): randy = self.pi_creature A_label = OldTexText("A440") A_label.set_color(self.A_color) A_label.next_to(self.speaker, UP) self.broadcast( FadeIn(A_label), Succession( ApplyMethod, randy.change, "pondering", Animation, randy, Blink, randy ) ) self.set_variables_as_attrs(A_label) def measure_air_pressure(self): randy = self.pi_creature axes = Axes( y_min = -2, y_max = 2, x_min = 0, x_max = 10, axis_config = {"include_tip" : False}, ) axes.stretch_to_fit_height(2) axes.to_corner(UP+LEFT) axes.shift(LARGE_BUFF*DOWN) eh = self.equilibrium_height equilibrium_line = DashedLine( axes.coords_to_point(0, eh), axes.coords_to_point(axes.x_max, eh), stroke_width = 2, stroke_color = GREY_B ) frequency = self.A_frequency graph = self.get_wave_graph(frequency, axes) func = graph.underlying_function graph.set_color(self.A_color) pressure = OldTexText("Pressure") time = OldTexText("Time") for label in pressure, time: label.scale(0.8) pressure.next_to(axes.y_axis, UP) pressure.to_edge(LEFT, buff = MED_SMALL_BUFF) time.next_to(axes.x_axis.get_right(), DOWN+LEFT) axes.labels = VGroup(pressure, time) n = 10 brace = Brace(Line( axes.coords_to_point(n/frequency, func(n/frequency)), axes.coords_to_point((n+1)/frequency, func((n+1)/frequency)), ), UP) words = brace.get_text("Imagine 440 per second", buff = SMALL_BUFF) words.scale(0.8, about_point = words.get_bottom()) self.play( FadeIn(pressure), ShowCreation(axes.y_axis) ) self.play( Write(time), ShowCreation(axes.x_axis) ) self.broadcast( ShowCreation(graph, run_time = 4, rate_func=linear), ShowCreation(equilibrium_line), ) axes.add(equilibrium_line) self.play( randy.change, "erm", graph, GrowFromCenter(brace), Write(words) ) self.wait() graph.save_state() self.play( FadeOut(brace), FadeOut(words), VGroup(axes, graph, axes.labels).shift, 0.8*UP, graph.fade, 0.85, graph.shift, 0.8*UP, ) graph.saved_state.move_to(graph) self.set_variables_as_attrs(axes, A_graph = graph) def play_lower_pitch(self): axes = self.axes randy = self.pi_creature frequency = self.A_frequency*(2.0/3.0) graph = self.get_wave_graph(frequency, axes) graph.set_color(self.D_color) D_label = OldTexText("D294") D_label.set_color(self.D_color) D_label.move_to(self.A_label) self.play( FadeOut(self.A_label), GrowFromCenter(D_label), ) self.broadcast( ShowCreation(graph, run_time = 4, rate_func=linear), randy.change, "happy", n_circles = 6, ) self.play(randy.change, "confused", graph) self.wait(2) self.set_variables_as_attrs( D_label, D_graph = graph ) def play_mix(self): self.A_graph.restore() self.broadcast( self.get_broadcast_animation(n_circles = 6), self.pi_creature.change, "thinking", *[ ShowCreation(graph, run_time = 4, rate_func=linear) for graph in (self.A_graph, self.D_graph) ] ) self.wait() def separate_out_parts(self): axes = self.axes speaker = self.speaker randy = self.pi_creature A_axes = axes.deepcopy() A_graph = self.A_graph A_label = self.A_label D_axes = axes.deepcopy() D_graph = self.D_graph D_label = self.D_label movers = [A_axes, A_graph, A_label, D_axes, D_graph, D_label] for mover in movers: mover.generate_target() D_target_group = VGroup(D_axes.target, D_graph.target) A_target_group = VGroup(A_axes.target, A_graph.target) D_target_group.next_to(axes, DOWN, MED_LARGE_BUFF) A_target_group.next_to(D_target_group, DOWN, MED_LARGE_BUFF) A_label.fade(1) A_label.target.next_to(A_graph.target, UP) D_label.target.next_to(D_graph.target, UP) self.play(*it.chain( list(map(MoveToTarget, movers)), [ ApplyMethod(mob.shift, FRAME_Y_RADIUS*DOWN, remover = True) for mob in (randy, speaker) ] )) self.wait() self.set_variables_as_attrs(A_axes, D_axes) def draw_sum_at_single_point(self): axes = self.axes A_axes = self.A_axes D_axes = self.D_axes A_graph = self.A_graph D_graph = self.D_graph x = 2.85 A_line = self.get_A_graph_v_line(x) D_line = self.get_D_graph_v_line(x) lines = VGroup(A_line, D_line) sum_lines = lines.copy() sum_lines.generate_target() self.stack_v_lines(x, sum_lines.target) top_axes_point = axes.coords_to_point(x, self.equilibrium_height) x_point = np.array(top_axes_point) x_point[1] = 0 v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS).move_to(x_point) self.revert_to_original_skipping_status() self.play(GrowFromCenter(v_line)) self.play(FadeOut(v_line)) self.play(*list(map(ShowCreation, lines))) self.wait() self.play(MoveToTarget(sum_lines, path_arc = np.pi/4)) self.wait(2) # self.play(*[ # Transform( # line, # VectorizedPoint(axes.coords_to_point(0, self.equilibrium_height)), # remover = True # ) # for line, axes in [ # (A_line, A_axes), # (D_line, D_axes), # (sum_lines, axes), # ] # ]) self.lines_to_fade = VGroup(A_line, D_line, sum_lines) def draw_full_sum(self): axes = self.axes def new_func(x): result = self.A_graph.underlying_function(x) result += self.D_graph.underlying_function(x) result -= self.equilibrium_height return result sum_graph = axes.get_graph(new_func) sum_graph.set_color(self.sum_color) thin_sum_graph = sum_graph.copy().fade() A_graph = self.A_graph D_graph = self.D_graph D_axes = self.D_axes rect = Rectangle( height = 2.5*FRAME_Y_RADIUS, width = MED_SMALL_BUFF, stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.4 ) self.play( ReplacementTransform(A_graph.copy(), thin_sum_graph), ReplacementTransform(D_graph.copy(), thin_sum_graph), # FadeOut(self.lines_to_fade) ) self.play( self.get_graph_line_animation(self.A_axes, self.A_graph), self.get_graph_line_animation(self.D_axes, self.D_graph), self.get_graph_line_animation(axes, sum_graph.deepcopy()), ShowCreation(sum_graph), run_time = 15, rate_func=linear ) self.remove(thin_sum_graph) self.wait() for x in 2.85, 3.57: rect.move_to(D_axes.coords_to_point(x, 0)) self.play(GrowFromPoint(rect, rect.get_top())) self.wait() self.play(FadeOut(rect)) self.sum_graph = sum_graph def add_more_notes(self): axes = self.axes A_group = VGroup(self.A_axes, self.A_graph, self.A_label) D_group = VGroup(self.D_axes, self.D_graph, self.D_label) squish_group = VGroup(A_group, D_group) squish_group.generate_target() squish_group.target.stretch(0.5, 1) squish_group.target.next_to(axes, DOWN, buff = -SMALL_BUFF) for group in squish_group.target: label = group[-1] bottom = label.get_bottom() label.stretch_in_place(0.5, 0) label.move_to(bottom, DOWN) self.play( MoveToTarget(squish_group), FadeOut(self.lines_to_fade), ) F_axes = self.D_axes.deepcopy() C_axes = self.A_axes.deepcopy() VGroup(F_axes, C_axes).next_to(squish_group, DOWN) F_graph = self.get_wave_graph(self.A_frequency*4.0/5, F_axes) F_graph.set_color(self.F_color) C_graph = self.get_wave_graph(self.A_frequency*6.0/5, C_axes) C_graph.set_color(self.C_color) F_label = OldTexText("F349") C_label = OldTexText("C523") for label, graph in (F_label, F_graph), (C_label, C_graph): label.scale(0.5) label.set_color(graph.get_stroke_color()) label.next_to(graph, UP, SMALL_BUFF) graphs = VGroup(self.A_graph, self.D_graph, F_graph, C_graph) def new_sum_func(x): result = sum([ graph.underlying_function(x) - self.equilibrium_height for graph in graphs ]) result *= 0.5 return result + self.equilibrium_height new_sum_graph = self.axes.get_graph( new_sum_func, num_graph_points = 200 ) new_sum_graph.set_color(BLUE_C) thin_new_sum_graph = new_sum_graph.copy().fade() self.play(*it.chain( list(map(ShowCreation, [F_axes, C_axes, F_graph, C_graph])), list(map(Write, [F_label, C_label])), list(map(FadeOut, [self.sum_graph])) )) self.play(ReplacementTransform( graphs.copy(), thin_new_sum_graph )) kwargs = {"rate_func" : None, "run_time" : 10} self.play(ShowCreation(new_sum_graph.copy(), **kwargs), *[ self.get_graph_line_animation(curr_axes, graph, **kwargs) for curr_axes, graph in [ (self.A_axes, self.A_graph), (self.D_axes, self.D_graph), (F_axes, F_graph), (C_axes, C_graph), (axes, new_sum_graph), ] ]) self.wait() #### def broadcast(self, *added_anims, **kwargs): self.play(self.get_broadcast_animation(**kwargs), *added_anims) def get_broadcast_animation(self, **kwargs): kwargs["run_time"] = kwargs.get("run_time", 5) kwargs["n_circles"] = kwargs.get("n_circles", 10) return Broadcast(self.speaker[1], **kwargs) def get_wave_graph(self, frequency, axes): tail_len = 3.0 x_min, x_max = axes.x_min, axes.x_max def func(x): value = 0.7*np.cos(2*np.pi*frequency*x) if x - x_min < tail_len: value *= smooth((x-x_min)/tail_len) if x_max - x < tail_len: value *= smooth((x_max - x )/tail_len) return value + self.equilibrium_height ngp = 2*(x_max - x_min)*frequency + 1 graph = axes.get_graph(func, num_graph_points = int(ngp)) return graph def get_A_graph_v_line(self, x): return self.get_graph_v_line(x, self.A_axes, self.A_graph) def get_D_graph_v_line(self, x): return self.get_graph_v_line(x, self.D_axes, self.D_graph) def get_graph_v_line(self, x, axes, graph): result = Line( axes.coords_to_point(x, self.equilibrium_height), # axes.coords_to_point(x, graph.underlying_function(x)), graph.point_from_proportion(float(x)/axes.x_max), color = WHITE, buff = 0, ) return result def stack_v_lines(self, x, lines): point = self.axes.coords_to_point(x, self.equilibrium_height) A_line, D_line = lines A_line.shift(point - A_line.get_start()) D_line.shift(A_line.get_end()-D_line.get_start()) A_line.set_color(self.A_color) D_line.set_color(self.D_color) return lines def create_pi_creature(self): return Randolph().to_corner(DOWN+LEFT) def get_graph_line_animation(self, axes, graph, **kwargs): line = self.get_graph_v_line(0, axes, graph) x_max = axes.x_max def update_line(line, alpha): x = alpha*x_max Transform(line, self.get_graph_v_line(x, axes, graph)).update(1) return line return UpdateFromAlphaFunc(line, update_line, **kwargs) class BreakApartSum(Scene): CONFIG = { "frequencies" : [0.5, 1.5, 2, 2.5, 5], "equilibrium_height" : 2.0, } def construct(self): self.show_initial_sound() self.decompose_sound() self.ponder_question() def show_initial_sound(self): def func(x): return self.equilibrium_height + 0.2*np.sum([ np.cos(2*np.pi*f*x) for f in self.frequencies ]) axes = Axes( x_min = 0, x_max = 5, y_min = -1, y_max = 5, x_axis_config = { "include_tip" : False, "unit_size" : 2.0, }, y_axis_config = { "include_tip" : False, "unit_size" : 0.5, }, ) axes.stretch_to_fit_width(FRAME_WIDTH - 2) axes.stretch_to_fit_height(3) axes.center() axes.to_edge(LEFT) graph = axes.get_graph(func, num_graph_points = 200) graph.set_color(YELLOW) v_line = Line(ORIGIN, 4*UP) v_line.move_to(axes.coords_to_point(0, 0), DOWN) dot = Dot(color = PINK) dot.move_to(graph.point_from_proportion(0)) self.add(axes, graph) self.play( v_line.move_to, axes.coords_to_point(5, 0), DOWN, MoveAlongPath(dot, graph), run_time = 8, rate_func=linear, ) self.play(*list(map(FadeOut, [dot, v_line]))) self.set_variables_as_attrs(axes, graph) def decompose_sound(self): axes, graph = self.axes, self.graph pure_graphs = VGroup(*[ axes.get_graph( lambda x : 0.5*np.cos(2*np.pi*freq*x), num_graph_points = 100, ) for freq in self.frequencies ]) pure_graphs.set_color_by_gradient(BLUE, RED) pure_graphs.arrange(DOWN, buff = MED_LARGE_BUFF) h_line = DashedLine(6*LEFT, 6*RIGHT) self.play( FadeOut(axes), graph.to_edge, UP ) pure_graphs.next_to(graph, DOWN, LARGE_BUFF) h_line.next_to(graph, DOWN, MED_LARGE_BUFF) self.play(ShowCreation(h_line)) for pure_graph in reversed(pure_graphs): self.play(ReplacementTransform(graph.copy(), pure_graph)) self.wait() self.all_graphs = VGroup(graph, h_line, pure_graphs) self.pure_graphs = pure_graphs def ponder_question(self): all_graphs = self.all_graphs pure_graphs = self.pure_graphs randy = Randolph() randy.to_corner(DOWN+LEFT) self.play( FadeIn(randy), all_graphs.scale, 0.75, all_graphs.to_corner, UP+RIGHT, ) self.play(randy.change, "pondering", all_graphs) self.play(Blink(randy)) rect = SurroundingRectangle(pure_graphs, color = WHITE) self.play( ShowCreation(rect), LaggedStartMap( ApplyFunction, pure_graphs, lambda g : (lambda m : m.shift(SMALL_BUFF*UP).set_color(YELLOW), g), rate_func = wiggle ) ) self.play(FadeOut(rect)) self.play(Blink(randy)) self.wait() class Quadrant(VMobject): CONFIG = { "radius" : 2, "stroke_width": 0, "fill_opacity" : 1, "density" : 50, "density_exp" : 2.0, } def init_points(self): points = [r*RIGHT for r in np.arange(0, self.radius, 1./self.density)] points += [ self.radius*(np.cos(theta)*RIGHT + np.sin(theta)*UP) for theta in np.arange(0, TAU/4, 1./(self.radius*self.density)) ] points += [r*UP for r in np.arange(self.radius, 0, -1./self.density)] self.set_points_smoothly(points) class UnmixMixedPaint(Scene): CONFIG = { "colors" : [BLUE, RED, YELLOW, GREEN], } def construct(self): angles = np.arange(4)*np.pi/2 quadrants = VGroup(*[ Quadrant().rotate(angle, about_point = ORIGIN).set_color(color) for color, angle in zip(self.colors, angles) ]) quadrants.add(*it.chain(*[ quadrants.copy().rotate(angle) for angle in np.linspace(0, 0.02*TAU, 10) ])) quadrants.set_fill(opacity = 0.5) mud_color = average_color(*self.colors) mud_circle = Circle(radius = 2, stroke_width = 0) mud_circle.set_fill(mud_color, 1) mud_circle.save_state() mud_circle.scale(0) def update_quadrant(quadrant, alpha): points = quadrant.get_anchors() dt = 0.03 #Hmm, this has no dependency on frame rate... norms = np.apply_along_axis(get_norm, 1, points) points[:,0] -= dt*points[:,1]/np.clip(norms, 0.1, np.inf) points[:,1] += dt*points[:,0]/np.clip(norms, 0.1, np.inf) new_norms = np.apply_along_axis(get_norm, 1, points) new_norms = np.clip(new_norms, 0.001, np.inf) radius = np.max(norms) multiplier = norms/new_norms multiplier = multiplier.reshape((len(multiplier), 1)) multiplier.repeat(points.shape[1], axis = 1) points *= multiplier quadrant.set_points_smoothly(points) self.add(quadrants) run_time = 30 self.play( *[ UpdateFromAlphaFunc(quadrant, update_quadrant) for quadrant in quadrants ] + [ ApplyMethod(mud_circle.restore, rate_func=linear) ], run_time = run_time ) #Incomplete, and probably not useful class MachineThatTreatsOneFrequencyDifferently(Scene): def construct(self): graph = self.get_cosine_graph(0.5) frequency_mob = DecimalNumber(220, num_decimal_places = 0) frequency_mob.next_to(graph, UP, buff = MED_LARGE_BUFF) self.graph = graph self.frequency_mob = frequency_mob self.add(graph, frequency_mob) arrow1, q_marks, arrow2 = group = VGroup( Vector(DOWN), OldTexText("???").scale(1.5), Vector(DOWN) ) group.set_color(WHITE) group.arrange(DOWN) group.next_to(graph, DOWN) self.add(group) self.change_graph_frequency(1) graph.set_color(GREEN) self.wait() graph.set_color(YELLOW) self.change_graph_frequency(2) self.wait() def change_graph_frequency(self, frequency, run_time = 2): graph = self.graph frequency_mob = self.frequency_mob curr_frequency = graph.frequency self.play( UpdateFromAlphaFunc( graph, self.get_signal_update_func(graph, frequency), ), ChangingDecimal( frequency_mob, lambda a : 440*interpolate(curr_frequency, frequency, a) ), run_time = run_time, ) graph.frequency = frequency def get_signal_update_func(self, graph, target_frequency): curr_frequency = graph.frequency def update(graph, alpha): frequency = interpolate(curr_frequency, target_frequency, alpha) new_graph = self.get_cosine_graph(frequency) Transform(graph, new_graph).update(1) return graph return update def get_cosine_graph(self, frequency, num_steps = 200, color = YELLOW): result = FunctionGraph( lambda x : 0.5*np.cos(2*np.pi*frequency*x), num_steps = num_steps ) result.frequency = frequency result.shift(2*UP) return result class FourierMachineScene(Scene): CONFIG = { "time_axes_config" : { "x_min" : 0, "x_max" : 4.4, "x_axis_config" : { "unit_size" : 3, "tick_frequency" : 0.25, "numbers_with_elongated_ticks" : [1, 2, 3], }, "y_min" : 0, "y_max" : 2, "y_axis_config" : {"unit_size" : 0.8}, }, "time_label_t" : 3.4, "circle_plane_config" : { "x_radius" : 2.1, "y_radius" : 2.1, "x_unit_size" : 1, "y_unit_size" : 1, }, "frequency_axes_config" : { "axis_config" : { "color" : TEAL, }, "x_min" : 0, "x_max" : 5.0, "x_axis_config" : { "unit_size" : 1.4, "numbers_to_show" : list(range(1, 6)), }, "y_min" : -1.0, "y_max" : 1.0, "y_axis_config" : { "unit_size" : 1.8, "tick_frequency" : 0.5, "label_direction" : LEFT, }, "color" : TEAL, }, "frequency_axes_box_color" : TEAL_E, "text_scale_val" : 0.75, "default_graph_config" : { "num_graph_points" : 100, "color" : YELLOW, }, "equilibrium_height" : 1, "default_y_vector_animation_config" : { "run_time" : 5, "rate_func" : None, "remover" : True, }, "default_time_sweep_config" : { "rate_func" : None, "run_time" : 5, }, "default_num_v_lines_indicating_periods" : 20, } def get_time_axes(self): time_axes = Axes(**self.time_axes_config) time_axes.x_axis.add_numbers() time_label = OldTexText("Time") intensity_label = OldTexText("Intensity") labels = VGroup(time_label, intensity_label) for label in labels: label.scale(self.text_scale_val) time_label.next_to( time_axes.coords_to_point(self.time_label_t,0), DOWN ) intensity_label.next_to(time_axes.y_axis.get_top(), RIGHT) time_axes.labels = labels time_axes.add(labels) time_axes.to_corner(UP+LEFT) self.time_axes = time_axes return time_axes def get_circle_plane(self): circle_plane = NumberPlane(**self.circle_plane_config) circle_plane.to_corner(DOWN+LEFT) circle = DashedLine(ORIGIN, TAU*UP).apply_complex_function(np.exp) circle.scale(circle_plane.x_unit_size) circle.move_to(circle_plane.coords_to_point(0, 0)) circle_plane.circle = circle circle_plane.add(circle) circle_plane.fade() self.circle_plane = circle_plane return circle_plane def get_frequency_axes(self): frequency_axes = Axes(**self.frequency_axes_config) frequency_axes.x_axis.add_numbers() frequency_axes.y_axis.add_numbers( *frequency_axes.y_axis.get_tick_numbers() ) box = SurroundingRectangle( frequency_axes, buff = MED_SMALL_BUFF, color = self.frequency_axes_box_color, ) frequency_axes.box = box frequency_axes.add(box) frequency_axes.to_corner(DOWN+RIGHT, buff = MED_SMALL_BUFF) frequency_label = OldTexText("Frequency") frequency_label.scale(self.text_scale_val) frequency_label.next_to( frequency_axes.x_axis.get_right(), DOWN, buff = MED_LARGE_BUFF, aligned_edge = RIGHT, ) frequency_axes.label = frequency_label frequency_axes.add(frequency_label) self.frequency_axes = frequency_axes return frequency_axes def get_time_graph(self, func, **kwargs): if not hasattr(self, "time_axes"): self.get_time_axes() config = dict(self.default_graph_config) config.update(kwargs) graph = self.time_axes.get_graph(func, **config) return graph def get_cosine_wave(self, freq = 1, shift_val = 1, scale_val = 0.9): return self.get_time_graph( lambda t : shift_val + scale_val*np.cos(TAU*freq*t) ) def get_fourier_transform_graph(self, time_graph, **kwargs): if not hasattr(self, "frequency_axes"): self.get_frequency_axes() func = time_graph.underlying_function t_axis = self.time_axes.x_axis t_min = t_axis.point_to_number(time_graph.get_points()[0]) t_max = t_axis.point_to_number(time_graph.get_points()[-1]) f_max = self.frequency_axes.x_max # result = get_fourier_graph( # self.frequency_axes, func, t_min, t_max, # **kwargs # ) # too_far_right_point_indices = [ # i # for i, point in enumerate(result.get_points()) # if self.frequency_axes.x_axis.point_to_number(point) > f_max # ] # if too_far_right_point_indices: # i = min(too_far_right_point_indices) # prop = float(i)/len(result.get_points()) # result.pointwise_become_partial(result, 0, prop) # return result return self.frequency_axes.get_graph( get_fourier_transform(func, t_min, t_max, **kwargs), color = self.center_of_mass_color, **kwargs ) def get_polarized_mobject(self, mobject, freq = 1.0): if not hasattr(self, "circle_plane"): self.get_circle_plane() polarized_mobject = mobject.copy() polarized_mobject.apply_function(lambda p : self.polarize_point(p, freq)) # polarized_mobject.make_smooth() mobject.polarized_mobject = polarized_mobject polarized_mobject.frequency = freq return polarized_mobject def polarize_point(self, point, freq = 1.0): t, y = self.time_axes.point_to_coords(point) z = y*np.exp(complex(0, -2*np.pi*freq*t)) return self.circle_plane.coords_to_point(z.real, z.imag) def get_polarized_animation(self, mobject, freq = 1.0): p_mob = self.get_polarized_mobject(mobject, freq = freq) def update_p_mob(p_mob): Transform( p_mob, self.get_polarized_mobject(mobject, freq = freq) ).update(1) mobject.polarized_mobject = p_mob return p_mob return UpdateFromFunc(p_mob, update_p_mob) def animate_frequency_change(self, mobjects, new_freq, **kwargs): kwargs["run_time"] = kwargs.get("run_time", 3.0) added_anims = kwargs.get("added_anims", []) self.play(*[ self.get_frequency_change_animation(mob, new_freq, **kwargs) for mob in mobjects ] + added_anims) def get_frequency_change_animation(self, mobject, new_freq, **kwargs): if not hasattr(mobject, "polarized_mobject"): mobject.polarized_mobject = self.get_polarized_mobject(mobject) start_freq = mobject.polarized_mobject.frequency def update(pm, alpha): freq = interpolate(start_freq, new_freq, alpha) new_pm = self.get_polarized_mobject(mobject, freq) Transform(pm, new_pm).update(1) mobject.polarized_mobject = pm mobject.polarized_mobject.frequency = freq return pm return UpdateFromAlphaFunc(mobject.polarized_mobject, update, **kwargs) def get_time_graph_y_vector_animation(self, graph, **kwargs): config = dict(self.default_y_vector_animation_config) config.update(kwargs) vector = Vector(UP, color = WHITE) graph_copy = graph.copy() x_axis = self.time_axes.x_axis x_min = x_axis.point_to_number(graph.get_points()[0]) x_max = x_axis.point_to_number(graph.get_points()[-1]) def update_vector(vector, alpha): x = interpolate(x_min, x_max, alpha) vector.put_start_and_end_on( self.time_axes.coords_to_point(x, 0), self.time_axes.input_to_graph_point(x, graph_copy) ) return vector return UpdateFromAlphaFunc(vector, update_vector, **config) def get_polarized_vector_animation(self, polarized_graph, **kwargs): config = dict(self.default_y_vector_animation_config) config.update(kwargs) vector = Vector(RIGHT, color = WHITE) origin = self.circle_plane.coords_to_point(0, 0) graph_copy = polarized_graph.copy() def update_vector(vector, alpha): # Not sure why this is needed, but without smoothing # out the alpha like this, the vector would occasionally # jump around point = center_of_mass([ graph_copy.point_from_proportion(alpha+d) for d in np.linspace(-0.001, 0.001, 5) ]) vector.put_start_and_end_on_with_projection(origin, point) return vector return UpdateFromAlphaFunc(vector, update_vector, **config) def get_vector_animations(self, graph, draw_polarized_graph = True, **kwargs): config = dict(self.default_y_vector_animation_config) config.update(kwargs) anims = [ self.get_time_graph_y_vector_animation(graph, **config), self.get_polarized_vector_animation(graph.polarized_mobject, **config), ] if draw_polarized_graph: new_config = dict(config) new_config["remover"] = False anims.append(ShowCreation(graph.polarized_mobject, **new_config)) return anims def animate_time_sweep(self, freq, n_repeats = 1, t_max = None, **kwargs): added_anims = kwargs.pop("added_anims", []) config = dict(self.default_time_sweep_config) config.update(kwargs) circle_plane = self.circle_plane time_axes = self.time_axes ctp = time_axes.coords_to_point t_max = t_max or time_axes.x_max v_line = DashedLine( ctp(0, 0), ctp(0, time_axes.y_max), stroke_width = 6, ) v_line.set_color(RED) for x in range(n_repeats): v_line.move_to(ctp(0, 0), DOWN) self.play( ApplyMethod( v_line.move_to, ctp(t_max, 0), DOWN ), self.get_polarized_animation(v_line, freq = freq), *added_anims, **config ) self.remove(v_line.polarized_mobject) self.play(FadeOut(VGroup(v_line, v_line.polarized_mobject))) def get_v_lines_indicating_periods(self, freq, n_lines = None): if n_lines is None: n_lines = self.default_num_v_lines_indicating_periods period = np.divide(1., max(freq, 0.01)) v_lines = VGroup(*[ DashedLine(ORIGIN, 1.5*UP).move_to( self.time_axes.coords_to_point(n*period, 0), DOWN ) for n in range(1, n_lines + 1) ]) v_lines.set_stroke(GREY_B) return v_lines def get_period_v_lines_update_anim(self): def update_v_lines(v_lines): freq = self.graph.polarized_mobject.frequency Transform( v_lines, self.get_v_lines_indicating_periods(freq) ).update(1) return UpdateFromFunc( self.v_lines_indicating_periods, update_v_lines ) class WrapCosineGraphAroundCircle(FourierMachineScene): CONFIG = { "initial_winding_frequency" : 0.5, "signal_frequency" : 3.0, } def construct(self): self.show_initial_signal() self.show_finite_interval() self.wrap_around_circle() self.show_time_sweeps() self.compare_two_frequencies() self.change_wrapping_frequency() def show_initial_signal(self): axes = self.get_time_axes() graph = self.get_cosine_wave(freq = self.signal_frequency) self.graph = graph braces = VGroup(*self.get_peak_braces()[3:6]) v_lines = VGroup(*[ DashedLine( ORIGIN, 2*UP, color = RED ).move_to(axes.coords_to_point(x, 0), DOWN) for x in (1, 2) ]) words = self.get_bps_label() words.save_state() words.next_to(axes.coords_to_point(1.5, 0), DOWN, MED_LARGE_BUFF) self.add(axes) self.play(ShowCreation(graph, run_time = 2, rate_func=linear)) self.play( FadeIn(words), LaggedStartMap(FadeIn, braces), *list(map(ShowCreation, v_lines)) ) self.wait() self.play( FadeOut(VGroup(braces, v_lines)), words.restore, ) self.wait() self.beats_per_second_label = words self.graph = graph def show_finite_interval(self): axes = self.time_axes v_line = DashedLine( axes.coords_to_point(0, 0), axes.coords_to_point(0, axes.y_max), color = RED, stroke_width = 6, ) h_line = Line( axes.coords_to_point(0, 0), axes.coords_to_point(axes.x_max, 0), ) rect = Rectangle( stroke_width = 0, fill_color = TEAL, fill_opacity = 0.5, ) rect.match_height(v_line) rect.match_width(h_line, stretch = True) rect.move_to(v_line, DOWN+LEFT) right_v_line = v_line.copy() right_v_line.move_to(rect, RIGHT) rect.save_state() rect.stretch(0, 0, about_edge = ORIGIN) self.play(rect.restore, run_time = 2) self.play(FadeOut(rect)) for line in v_line, right_v_line: self.play(ShowCreation(line)) self.play(FadeOut(line)) self.wait() def wrap_around_circle(self): graph = self.graph freq = self.initial_winding_frequency low_freq = freq/3 polarized_graph = self.get_polarized_mobject(graph, low_freq) circle_plane = self.get_circle_plane() moving_graph = graph.copy() self.play(ShowCreation(circle_plane, lag_ratio = 0)) self.play(ReplacementTransform( moving_graph, polarized_graph, run_time = 3, path_arc = -TAU/2 )) self.animate_frequency_change([graph], freq) self.wait() pg_copy = polarized_graph.copy() self.remove(polarized_graph) self.play(pg_copy.fade, 0.75) self.play(*self.get_vector_animations(graph), run_time = 15) self.remove(pg_copy) self.wait() def show_time_sweeps(self): freq = self.initial_winding_frequency graph = self.graph v_lines = self.get_v_lines_indicating_periods(freq) winding_freq_label = self.get_winding_frequency_label() self.animate_time_sweep( freq = freq, t_max = 4, run_time = 6, added_anims = [FadeIn(v_lines)] ) self.play( FadeIn(winding_freq_label), *self.get_vector_animations(graph) ) self.wait() self.v_lines_indicating_periods = v_lines def compare_two_frequencies(self): bps_label = self.beats_per_second_label wps_label = self.winding_freq_label for label in bps_label, wps_label: label.rect = SurroundingRectangle( label, color = RED ) graph = self.graph freq = self.initial_winding_frequency braces = self.get_peak_braces(buff = 0) self.play(ShowCreation(bps_label.rect)) self.play(FadeOut(bps_label.rect)) self.play(LaggedStartMap(FadeIn, braces, run_time = 3)) self.play(FadeOut(braces)) self.play(ShowCreation(wps_label.rect)) self.play(FadeOut(wps_label.rect)) self.animate_time_sweep(freq = freq, t_max = 4) self.wait() def change_wrapping_frequency(self): graph = self.graph v_lines = self.v_lines_indicating_periods freq_label = self.winding_freq_label[0] count = 0 for target_freq in [1.23, 0.2, 0.79, 1.55, self.signal_frequency]: self.play( Transform( v_lines, self.get_v_lines_indicating_periods(target_freq) ), ChangeDecimalToValue(freq_label, target_freq), self.get_frequency_change_animation(graph, target_freq), run_time = 4, ) self.wait() if count == 2: self.play(LaggedStartMap( ApplyFunction, v_lines, lambda mob : ( lambda m : m.shift(0.25*UP).set_color(YELLOW), mob ), rate_func = there_and_back )) self.animate_time_sweep(target_freq, t_max = 2) count += 1 self.wait() self.play( *self.get_vector_animations(graph, False), run_time = 15 ) ## def get_winding_frequency_label(self): freq = self.initial_winding_frequency winding_freq_label = VGroup( DecimalNumber(freq, num_decimal_places=2), OldTexText("cycles/second") ) winding_freq_label.arrange(RIGHT) winding_freq_label.next_to( self.circle_plane, RIGHT, aligned_edge = UP ) self.winding_freq_label = winding_freq_label return winding_freq_label def get_peak_braces(self, **kwargs): peak_points = [ self.time_axes.input_to_graph_point(x, self.graph) for x in np.arange(0, 3.5, 1./self.signal_frequency) ] return VGroup(*[ Brace(Line(p1, p2), UP, **kwargs) for p1, p2 in zip(peak_points, peak_points[1:]) ]) def get_bps_label(self, freq = 3): braces = VGroup(*self.get_peak_braces()[freq:2*freq]) words = OldTexText("%d beats/second"%freq) words.set_width(0.9*braces.get_width()) words.move_to(braces, DOWN) return words class DrawFrequencyPlot(WrapCosineGraphAroundCircle, PiCreatureScene): CONFIG = { "initial_winding_frequency" : 3.0, "center_of_mass_color" : RED, "center_of_mass_multiple" : 1, } def construct(self): self.remove(self.pi_creature) self.setup_graph() self.indicate_weight_of_wire() self.show_center_of_mass_dot() self.change_to_various_frequencies() self.introduce_frequency_plot() self.draw_full_frequency_plot() self.recap_objects_on_screen() self.lower_graph() self.label_as_almost_fourier() def setup_graph(self): self.add(self.get_time_axes()) self.add(self.get_circle_plane()) self.graph = self.get_cosine_wave(self.signal_frequency) self.add(self.graph) self.add(self.get_polarized_mobject( self.graph, self.initial_winding_frequency )) self.add(self.get_winding_frequency_label()) self.beats_per_second_label = self.get_bps_label() self.add(self.beats_per_second_label) self.v_lines_indicating_periods = self.get_v_lines_indicating_periods( self.initial_winding_frequency ) self.add(self.v_lines_indicating_periods) self.change_frequency(1.03) self.wait() def indicate_weight_of_wire(self): graph = self.graph pol_graph = graph.polarized_mobject.copy() pol_graph.save_state() morty = self.pi_creature morty.change("raise_right_hand") morty.save_state() morty.change("plain") morty.fade(1) self.play( morty.restore, pol_graph.scale, 0.5, pol_graph.next_to, morty.get_corner(UP+LEFT), UP, -SMALL_BUFF, ) self.play( morty.change, "lower_right_hand", pol_graph.get_bottom(), pol_graph.shift, 0.45*DOWN, rate_func = there_and_back, run_time = 2, ) self.wait() metal_wire = pol_graph.copy().set_stroke(GREY_B) self.play( ShowCreationThenDestruction(metal_wire), run_time = 2, ) self.play( pol_graph.restore, morty.change, "pondering" ) self.remove(pol_graph) def show_center_of_mass_dot(self): color = self.center_of_mass_color dot = self.get_center_of_mass_dot() dot.save_state() arrow = Vector(DOWN+2*LEFT, color = color) arrow.next_to(dot.get_center(), UP+RIGHT, buff = SMALL_BUFF) dot.move_to(arrow.get_start()) words = OldTexText("Center of mass") words.next_to(arrow.get_start(), RIGHT) words.set_color(color) self.play( GrowArrow(arrow), dot.restore, ) self.play(Write(words)) self.play(FadeOut(arrow), FadeOut(self.pi_creature)) self.wait() self.generate_center_of_mass_dot_update_anim() self.center_of_mass_label = words def change_to_various_frequencies(self): self.change_frequency( 3.0, run_time = 30, rate_func = bezier([0, 0, 1, 1]) ) self.wait() self.play( *self.get_vector_animations(self.graph), run_time = 15 ) def introduce_frequency_plot(self): wps_label = self.winding_freq_label wps_label.add_to_back(BackgroundRectangle(wps_label)) com_label = self.center_of_mass_label com_label.add_background_rectangle() frequency_axes = self.get_frequency_axes() x_coord_label = OldTexText("$x$-coordinate for center of mass") x_coord_label.set_color(self.center_of_mass_color) x_coord_label.scale(self.text_scale_val) x_coord_label.next_to( frequency_axes.y_axis.get_top(), RIGHT, aligned_edge = UP, buff = LARGE_BUFF ) x_coord_label.add_background_rectangle() flower_path = ParametricCurve( lambda t : self.circle_plane.coords_to_point( np.sin(2*t)*np.cos(t), np.sin(2*t)*np.sin(t), ), t_min = 0, t_max = TAU, ) flower_path.move_to(self.center_of_mass_dot) self.play( wps_label.move_to, self.circle_plane.get_top(), com_label.move_to, self.circle_plane, DOWN, ) self.play(LaggedStartMap(FadeIn, frequency_axes)) self.wait() self.play(MoveAlongPath( self.center_of_mass_dot, flower_path, run_time = 4, )) self.play(ReplacementTransform( com_label.copy(), x_coord_label )) self.wait() self.x_coord_label = x_coord_label def draw_full_frequency_plot(self): graph = self.graph fourier_graph = self.get_fourier_transform_graph(graph) fourier_graph.save_state() fourier_graph_update = self.get_fourier_graph_drawing_update_anim( fourier_graph ) v_line = DashedLine( self.frequency_axes.coords_to_point(0, 0), self.frequency_axes.coords_to_point(0, 1), stroke_width = 6, color = fourier_graph.get_color() ) self.change_frequency(0.0) self.generate_fourier_dot_transform(fourier_graph) self.wait() self.play(ShowCreation(v_line)) self.play( GrowFromCenter(self.fourier_graph_dot), FadeOut(v_line) ) f_max = int(self.frequency_axes.x_max) for freq in [0.2, 1.5, 3.0, 4.0, 5.0]: fourier_graph.restore() self.change_frequency( freq, added_anims = [fourier_graph_update], run_time = 8, ) self.wait() self.fourier_graph = fourier_graph def recap_objects_on_screen(self): rect = FullScreenFadeRectangle() time_group = VGroup( self.graph, self.time_axes, self.beats_per_second_label, ).copy() circle_group = VGroup( self.graph.polarized_mobject, self.circle_plane, self.winding_freq_label, self.center_of_mass_label, self.center_of_mass_dot, ).copy() frequency_group = VGroup( self.fourier_graph, self.frequency_axes, self.x_coord_label, ).copy() groups = [time_group, circle_group, frequency_group] self.play(FadeIn(rect)) self.wait() for group in groups: graph_copy = group[0].copy().set_color(PINK) self.play(FadeIn(group)) self.play(ShowCreation(graph_copy)) self.play(FadeOut(graph_copy)) self.wait() self.play(FadeOut(group)) self.wait() self.play(FadeOut(rect)) def lower_graph(self): graph = self.graph time_axes = self.time_axes shift_vect = time_axes.coords_to_point(0, 1) shift_vect -= time_axes.coords_to_point(0, 0) fourier_graph = self.fourier_graph new_graph = self.get_cosine_wave( self.signal_frequency, shift_val = 0 ) new_fourier_graph = self.get_fourier_transform_graph(new_graph) for mob in graph, time_axes, fourier_graph: mob.save_state() new_freq = 0.03 self.change_frequency(new_freq) self.wait() self.play( time_axes.shift, shift_vect/2, graph.shift, -shift_vect/2, self.get_frequency_change_animation( self.graph, new_freq ), self.center_of_mass_dot_anim, self.get_period_v_lines_update_anim(), Transform(fourier_graph, new_fourier_graph), self.fourier_graph_dot.move_to, self.frequency_axes.coords_to_point(new_freq, 0), run_time = 2 ) self.wait() self.remove(self.fourier_graph_dot) self.generate_fourier_dot_transform(new_fourier_graph) self.change_frequency(3.0, run_time = 15, rate_func=linear) self.wait() self.play( graph.restore, time_axes.restore, self.get_frequency_change_animation( self.graph, 3.0 ), self.center_of_mass_dot_anim, self.get_period_v_lines_update_anim(), fourier_graph.restore, Animation(self.fourier_graph_dot), run_time = 2 ) self.generate_fourier_dot_transform(self.fourier_graph) self.wait() self.play(FocusOn(self.fourier_graph_dot)) self.wait() def label_as_almost_fourier(self): x_coord_label = self.x_coord_label almost_fourier_label = OldTexText( "``Almost Fourier Transform''", ) almost_fourier_label.move_to(x_coord_label, UP+LEFT) x_coord_label.generate_target() x_coord_label.target.next_to(almost_fourier_label, DOWN) self.play( MoveToTarget(x_coord_label), Write(almost_fourier_label) ) self.wait(2) ## def get_center_of_mass_dot(self): dot = Dot( self.get_pol_graph_center_of_mass(), color = self.center_of_mass_color ) self.center_of_mass_dot = dot return dot def get_pol_graph_center_of_mass(self): pg = self.graph.polarized_mobject result = center_of_mass(pg.get_anchors()) if self.center_of_mass_multiple != 1: mult = self.center_of_mass_multiple origin = self.circle_plane.coords_to_point(0, 0) result = mult*(result - origin) + origin return result def generate_fourier_dot_transform(self, fourier_graph): self.fourier_graph_dot = Dot(color = WHITE, radius = 0.05) def update_dot(dot): f = self.graph.polarized_mobject.frequency dot.move_to(self.frequency_axes.input_to_graph_point( f, fourier_graph )) self.fourier_graph_dot_anim = UpdateFromFunc( self.fourier_graph_dot, update_dot ) self.fourier_graph_dot_anim.update(0) def get_fourier_graph_drawing_update_anim(self, fourier_graph): fourier_graph_copy = fourier_graph.copy() max_freq = self.frequency_axes.x_max def update_fourier_graph(fg): freq = self.graph.polarized_mobject.frequency fg.pointwise_become_partial( fourier_graph_copy, 0, freq/max_freq ) return fg self.fourier_graph_drawing_update_anim = UpdateFromFunc( fourier_graph, update_fourier_graph ) return self.fourier_graph_drawing_update_anim def generate_center_of_mass_dot_update_anim(self, multiplier = 1): origin = self.circle_plane.coords_to_point(0, 0) com = self.get_pol_graph_center_of_mass self.center_of_mass_dot_anim = UpdateFromFunc( self.center_of_mass_dot, lambda d : d.move_to( multiplier*(com()-origin)+origin ) ) def change_frequency(self, new_freq, **kwargs): kwargs["run_time"] = kwargs.get("run_time", 3) rate_func = kwargs.pop("rate_func", None) if rate_func is None: rate_func = bezier([0, 0, 1, 1]) added_anims = kwargs.get("added_anims", []) anims = [self.get_frequency_change_animation(self.graph, new_freq)] if hasattr(self, "winding_freq_label"): freq_label = [ sm for sm in self.winding_freq_label if isinstance(sm, DecimalNumber) ][0] self.add(freq_label) anims.append( ChangeDecimalToValue(freq_label, new_freq) ) if hasattr(self, "v_lines_indicating_periods"): anims.append(self.get_period_v_lines_update_anim()) if hasattr(self, "center_of_mass_dot"): anims.append(self.center_of_mass_dot_anim) if hasattr(self, "fourier_graph_dot"): anims.append(self.fourier_graph_dot_anim) if hasattr(self, "fourier_graph_drawing_update_anim"): anims.append(self.fourier_graph_drawing_update_anim) for anim in anims: anim.rate_func = rate_func anims += added_anims self.play(*anims, **kwargs) def create_pi_creature(self): return Mortimer().to_corner(DOWN+RIGHT) class StudentsHorrifiedAtScene(TeacherStudentsScene): def construct(self): self.play_student_changes( *3*["horrified"], look_at = 2*UP + 3*LEFT ) self.wait(4) class AskAboutAlmostFouierName(TeacherStudentsScene): def construct(self): self.student_says( "``Almost'' Fourier transform?", target_mode = "sassy" ) self.play_student_changes("confused", "sassy", "confused") self.wait() self.teacher_says( "We'll get to the real \\\\ one in a few minutes", added_anims = [self.change_students(*["plain"]*3)] ) self.wait(2) class ShowLowerFrequency(DrawFrequencyPlot): CONFIG = { "signal_frequency" : 2.0, "higher_signal_frequency" : 3.0, "lower_signal_color" : PINK, } def construct(self): self.setup_all_axes() self.show_lower_frequency_signal() self.play_with_lower_frequency_signal() def setup_all_axes(self): self.add(self.get_time_axes()) self.add(self.get_circle_plane()) self.add(self.get_frequency_axes()) self.remove(self.pi_creature) def show_lower_frequency_signal(self): axes = self.time_axes start_graph = self.get_cosine_wave(freq = self.higher_signal_frequency) graph = self.get_cosine_wave( freq = self.signal_frequency, ) graph.set_color(self.lower_signal_color) self.graph = graph ratio = float(self.higher_signal_frequency)/self.signal_frequency braces = VGroup(*self.get_peak_braces()[2:4]) v_lines = VGroup(*[ DashedLine(ORIGIN, 1.5*UP).move_to( axes.coords_to_point(x, 0), DOWN ) for x in (1, 2) ]) bps_label = self.get_bps_label(2) bps_label.save_state() bps_label.next_to(braces, UP, SMALL_BUFF) # self.add(start_graph) self.play( start_graph.stretch, ratio, 0, {"about_edge" : LEFT}, start_graph.set_color, graph.get_color(), ) self.play(FadeOut(start_graph), Animation(graph)) self.remove(start_graph) self.play( Write(bps_label), LaggedStartMap(FadeIn, braces), *list(map(ShowCreation, v_lines)), run_time = 1 ) self.wait() self.play( FadeOut(v_lines), FadeOut(braces), bps_label.restore, ) def play_with_lower_frequency_signal(self): freq = 0.1 #Wind up graph graph = self.graph pol_graph = self.get_polarized_mobject(graph, freq) v_lines = self.get_v_lines_indicating_periods(freq) self.v_lines_indicating_periods = v_lines wps_label = self.get_winding_frequency_label() ChangeDecimalToValue(wps_label[0], freq).update(1) wps_label.add_to_back(BackgroundRectangle(wps_label)) wps_label.move_to(self.circle_plane, UP) self.play( ReplacementTransform( graph.copy(), pol_graph, run_time = 2, path_arc = -TAU/4, ), FadeIn(wps_label), ) self.change_frequency(freq, run_time = 0) self.change_frequency(0.7) self.wait() #Show center of mass dot = Dot( self.get_pol_graph_center_of_mass(), color = self.center_of_mass_color ) dot.save_state() self.center_of_mass_dot = dot com_words = OldTexText("Center of mass") com_words.add_background_rectangle() com_words.move_to(self.circle_plane, DOWN) arrow = Arrow( com_words.get_top(), dot.get_center(), buff = SMALL_BUFF, color = self.center_of_mass_color ) dot.move_to(arrow.get_start()) self.generate_center_of_mass_dot_update_anim() self.play( GrowArrow(arrow), dot.restore, Write(com_words) ) self.wait() self.play(*list(map(FadeOut, [arrow, com_words]))) self.change_frequency(0.0) self.wait() #Show fourier graph fourier_graph = self.get_fourier_transform_graph(graph) fourier_graph_update = self.get_fourier_graph_drawing_update_anim( fourier_graph ) x_coord_label = OldTexText( "x-coordinate of center of mass" ) x_coord_label.scale(self.text_scale_val) x_coord_label.next_to( self.frequency_axes.input_to_graph_point( self.signal_frequency, fourier_graph ), UP ) x_coord_label.set_color(self.center_of_mass_color) self.generate_fourier_dot_transform(fourier_graph) self.play(Write(x_coord_label)) self.change_frequency( self.signal_frequency, run_time = 10, rate_func = smooth, ) self.wait() self.change_frequency( self.frequency_axes.x_max, run_time = 15, rate_func = smooth, ) self.wait() self.set_variables_as_attrs( fourier_graph, fourier_graph_update, ) class MixingUnmixingTODOStub(TODOStub): CONFIG = { "message" : "Insert mixing and unmixing of signals" } class ShowLinearity(DrawFrequencyPlot): CONFIG = { "high_freq_color": YELLOW, "low_freq_color": PINK, "sum_color": GREEN, "low_freq" : 3.0, "high_freq" : 4.0, "circle_plane_config" : { "x_radius" : 2.5, "y_radius" : 2.7, "x_unit_size" : 0.8, "y_unit_size" : 0.8, }, } def construct(self): self.remove(self.pi_creature) self.show_sum_of_signals() self.show_winding_with_sum_graph() self.show_vector_rotation() def show_sum_of_signals(self): low_freq, high_freq = self.low_freq, self.high_freq axes = self.get_time_axes() axes_copy = axes.copy() low_freq_graph, high_freq_graph = [ self.get_cosine_wave( freq = freq, scale_val = 0.5, shift_val = 0.55, ) for freq in (low_freq, high_freq) ] sum_graph = self.get_time_graph( lambda t : sum([ low_freq_graph.underlying_function(t), high_freq_graph.underlying_function(t), ]) ) VGroup(axes_copy, high_freq_graph).next_to( axes, DOWN, MED_LARGE_BUFF ) low_freq_label = OldTexText("%d Hz"%int(low_freq)) high_freq_label = OldTexText("%d Hz"%int(high_freq)) sum_label = OldTexText( "%d Hz"%int(low_freq), "+", "%d Hz"%int(high_freq) ) trips = [ (low_freq_label, low_freq_graph, self.low_freq_color), (high_freq_label, high_freq_graph, self.high_freq_color), (sum_label, sum_graph, self.sum_color), ] for label, graph, color in trips: label.next_to(graph, UP) graph.set_color(color) label.set_color(color) sum_label[0].match_color(low_freq_graph) sum_label[2].match_color(high_freq_graph) self.add(axes, low_freq_graph) self.play( FadeIn(axes_copy), ShowCreation(high_freq_graph), ) self.play(LaggedStartMap( FadeIn, VGroup(high_freq_label, low_freq_label) )) self.wait() self.play( ReplacementTransform(axes_copy, axes), ReplacementTransform(high_freq_graph, sum_graph), ReplacementTransform(low_freq_graph, sum_graph), ReplacementTransform( VGroup(low_freq_label, high_freq_label), sum_label ) ) self.wait() self.graph = graph def show_winding_with_sum_graph(self): graph = self.graph circle_plane = self.get_circle_plane() frequency_axes = self.get_frequency_axes() pol_graph = self.get_polarized_mobject(graph, freq = 0.0) wps_label = self.get_winding_frequency_label() ChangeDecimalToValue(wps_label[0], 0.0).update(1) wps_label.add_to_back(BackgroundRectangle(wps_label)) wps_label.move_to(circle_plane, UP) v_lines = self.get_v_lines_indicating_periods(0.001) self.v_lines_indicating_periods = v_lines dot = Dot( self.get_pol_graph_center_of_mass(), color = self.center_of_mass_color ) self.center_of_mass_dot = dot self.generate_center_of_mass_dot_update_anim() fourier_graph = self.get_fourier_transform_graph(graph) fourier_graph_update = self.get_fourier_graph_drawing_update_anim( fourier_graph ) x_coord_label = OldTexText( "x-coordinate of center of mass" ) x_coord_label.scale(self.text_scale_val) x_coord_label.next_to( self.frequency_axes.input_to_graph_point( self.signal_frequency, fourier_graph ), UP ) x_coord_label.set_color(self.center_of_mass_color) almost_fourier_label = OldTexText( "``Almost-Fourier transform''" ) self.generate_fourier_dot_transform(fourier_graph) self.play(LaggedStartMap( FadeIn, VGroup( circle_plane, wps_label, frequency_axes, x_coord_label, ), run_time = 1, )) self.play( ReplacementTransform(graph.copy(), pol_graph), GrowFromCenter(dot) ) freqs = [ self.low_freq, self.high_freq, self.frequency_axes.x_max ] for freq in freqs: self.change_frequency( freq, run_time = 8, rate_func = bezier([0, 0, 1, 1]), ) def show_vector_rotation(self): self.fourier_graph_drawing_update_anim = Animation(Mobject()) self.change_frequency(self.low_freq) self.play(*self.get_vector_animations( self.graph, draw_polarized_graph = False, run_time = 20, )) self.wait() class ShowCommutativeDiagram(ShowLinearity): CONFIG = { "time_axes_config" : { "x_max" : 1.9, "y_max" : 2.0, "y_min" : -2.0, "y_axis_config" : { "unit_size" : 0.5, }, "x_axis_config" : { "numbers_to_show" : [1], } }, "time_label_t" : 1.5, "frequency_axes_config" : { "x_min" : 0.0, "x_max" : 4.0, "y_min" : -0.1, "y_max" : 0.5, "y_axis_config" : { "unit_size" : 1.5, "tick_frequency" : 0.5, }, } } def construct(self): self.show_diagram() self.point_out_spikes() def show_diagram(self): self.remove(self.pi_creature) #Setup axes time_axes = self.get_time_axes() time_axes.scale(0.8) ta_group = VGroup( time_axes, time_axes.deepcopy(), time_axes.deepcopy(), ) ta_group.arrange(DOWN, buff = MED_LARGE_BUFF) ta_group.to_corner(UP+LEFT, buff = MED_SMALL_BUFF) frequency_axes = Axes(**self.frequency_axes_config) frequency_axes.set_color(TEAL) freq_label = OldTexText("Frequency") freq_label.scale(self.text_scale_val) freq_label.next_to(frequency_axes.x_axis, DOWN, SMALL_BUFF, RIGHT) frequency_axes.label = freq_label frequency_axes.add(freq_label) frequency_axes.scale(0.8) fa_group = VGroup( frequency_axes, frequency_axes.deepcopy(), frequency_axes.deepcopy() ) VGroup(ta_group[1], fa_group[1]).shift(MED_LARGE_BUFF*UP) for ta, fa in zip(ta_group, fa_group): fa.next_to( ta.x_axis, RIGHT, submobject_to_align = fa.x_axis ) fa.to_edge(RIGHT) ta.remove(ta.labels) fa.remove(fa.label) ## Add graphs funcs = [ lambda t : np.cos(2*TAU*t), lambda t : np.cos(3*TAU*t), ] funcs.append(lambda t : funcs[0](t)+funcs[1](t)) colors = [ self.low_freq_color, self.high_freq_color, self.sum_color, ] labels = [ OldTexText("2 Hz"), OldTexText("3 Hz"), # OldTexText("2 Hz", "+", "3 Hz"), VectorizedPoint() ] for func, color, label, ta, fa in zip(funcs, colors, labels, ta_group, fa_group): time_graph = ta.get_graph(func) time_graph.set_color(color) label.set_color(color) label.scale(0.75) label.next_to(time_graph, UP, SMALL_BUFF) fourier = get_fourier_transform( func, ta.x_min, 4*ta.x_max ) fourier_graph = fa.get_graph(fourier) fourier_graph.set_color(self.center_of_mass_color) arrow = Arrow( ta.x_axis, fa.x_axis, color = WHITE, buff = MED_LARGE_BUFF, ) words = OldTexText("Almost-Fourier \\\\ transform") words.scale(0.6) words.next_to(arrow, UP) arrow.words = words ta.graph = time_graph ta.graph_label = label ta.arrow = arrow ta.add(time_graph, label) fa.graph = fourier_graph fa.add(fourier_graph) # labels[-1][0].match_color(labels[0]) # labels[-1][2].match_color(labels[1]) #Add arrows sum_arrows = VGroup() for group in ta_group, fa_group: arrow = Arrow( group[1].graph, group[2].graph, color = WHITE, buff = SMALL_BUFF ) arrow.scale(0.8, about_edge = UP) arrow.words = OldTexText("Sum").scale(0.75) arrow.words.next_to(arrow, RIGHT, buff = MED_SMALL_BUFF) sum_arrows.add(arrow) def apply_transform(index): ta = ta_group[index].deepcopy() fa = fa_group[index] anims = [ ReplacementTransform( getattr(ta, attr), getattr(fa, attr) ) for attr in ("x_axis", "y_axis", "graph") ] anims += [ GrowArrow(ta.arrow), Write(ta.arrow.words), ] if index == 0: anims.append(ReplacementTransform( ta.labels[0], fa.label )) self.play(*anims, run_time = 1.5) #Animations self.add(*ta_group[:2]) self.add(ta_group[0].labels) self.wait() apply_transform(0) apply_transform(1) self.wait() self.play( GrowArrow(sum_arrows[1]), Write(sum_arrows[1].words), *[ ReplacementTransform( fa.copy(), fa_group[2] ) for fa in fa_group[:2] ] ) self.wait(2) self.play( GrowArrow(sum_arrows[0]), Write(sum_arrows[0].words), *[ ReplacementTransform( mob.copy(), ta_group[2], run_time = 1 ) for mob in ta_group[:2] ] ) self.wait() apply_transform(2) self.wait() self.time_axes_group = ta_group self.frequency_axes_group = fa_group def point_out_spikes(self): fa_group = self.frequency_axes_group freqs = self.low_freq, self.high_freq flat_rects = VGroup() for freq, axes in zip(freqs, fa_group[:2]): flat_rect = SurroundingRectangle(axes.x_axis) flat_rect.stretch(0.5, 1) spike_rect = self.get_spike_rect(axes, freq) flat_rect.match_style(spike_rect) flat_rect.target = spike_rect flat_rects.add(flat_rect) self.play(LaggedStartMap(GrowFromCenter, flat_rects)) self.wait() self.play(LaggedStartMap(MoveToTarget, flat_rects)) self.wait() sum_spike_rects = VGroup(*[ self.get_spike_rect(fa_group[2], freq) for freq in freqs ]) self.play(ReplacementTransform( flat_rects, sum_spike_rects )) self.play(LaggedStartMap( WiggleOutThenIn, sum_spike_rects, run_time = 1, lag_ratio = 0.7, )) self.wait() ## def get_spike_rect(self, axes, freq): peak_point = axes.input_to_graph_point( freq, axes.graph ) f_axis_point = axes.coords_to_point(freq, 0) line = Line(f_axis_point, peak_point) spike_rect = SurroundingRectangle(line) spike_rect.set_stroke(width = 0) spike_rect.set_fill(YELLOW, 0.5) return spike_rect class PauseAndPonder(TeacherStudentsScene): def construct(self): self.teacher_says( "Pause and \\\\ ponder!", target_mode = "hooray" ) self.play_student_changes(*["thinking"]*3) self.wait(4) class BeforeGettingToTheFullMath(TeacherStudentsScene): def construct(self): formula = OldTex( "\\hat{g}(f) = \\int_{-\\infty}^{\\infty}" + \ "g(t)e^{-2\\pi i f t}dt" ) formula.next_to(self.teacher, UP+LEFT) self.play( Write(formula), self.teacher.change, "raise_right_hand", self.change_students(*["confused"]*3) ) self.wait() self.play( ApplyMethod( formula.next_to, FRAME_X_RADIUS*RIGHT, RIGHT, path_arc = TAU/16, rate_func = running_start, ), self.change_students(*["pondering"]*3) ) self.teacher_says("Consider sound editing\\dots") self.wait(3) class FilterOutHighPitch(AddingPureFrequencies, ShowCommutativeDiagram): def construct(self): self.add_speaker() self.play_sound() self.show_intensity_vs_time_graph() self.take_fourier_transform() self.filter_out_high_pitch() self.mention_inverse_transform() def play_sound(self): randy = self.pi_creature self.play( Succession( ApplyMethod, randy.look_at, self.speaker, Animation, randy, ApplyMethod, randy.change, "telepath", randy, Animation, randy, Blink, randy, Animation, randy, {"run_time" : 2}, ), *self.get_broadcast_anims(), run_time = 7 ) self.play(randy.change, "angry", self.speaker) self.wait() def show_intensity_vs_time_graph(self): randy = self.pi_creature axes = Axes( x_min = 0, x_max = 12, y_min = -6, y_max = 6, y_axis_config = { "unit_size" : 0.15, "tick_frequency" : 3, } ) axes.set_stroke(width = 2) axes.to_corner(UP+LEFT) time_label = OldTexText("Time") intensity_label = OldTexText("Intensity") labels = VGroup(time_label, intensity_label) labels.scale(0.75) time_label.next_to( axes.x_axis, DOWN, aligned_edge = RIGHT, buff = SMALL_BUFF ) intensity_label.next_to( axes.y_axis, RIGHT, aligned_edge = UP, buff = SMALL_BUFF ) axes.labels = labels func = lambda t : sum([ np.cos(TAU*f*t) for f in (0.5, 0.7, 1.0, 1.2, 3.0,) ]) graph = axes.get_graph(func) graph.set_color(BLUE) self.play( FadeIn(axes), FadeIn(axes.labels), randy.change, "pondering", axes, ShowCreation( graph, run_time = 4, rate_func = bezier([0, 0, 1, 1]) ), *self.get_broadcast_anims(run_time = 6) ) self.wait() self.time_axes = axes self.time_graph = graph def take_fourier_transform(self): time_axes = self.time_axes time_graph = self.time_graph randy = self.pi_creature speaker = self.speaker frequency_axes = Axes( x_min = 0, x_max = 3.5, x_axis_config = {"unit_size" : 3.5}, y_min = 0, y_max = 1, y_axis_config = {"unit_size" : 2}, ) frequency_axes.set_color(TEAL) frequency_axes.next_to(time_axes, DOWN, LARGE_BUFF, LEFT) freq_label = OldTexText("Frequency") freq_label.scale(0.75) freq_label.next_to(frequency_axes.x_axis, DOWN, MED_SMALL_BUFF, RIGHT) frequency_axes.label = freq_label fourier_func = get_fourier_transform( time_graph.underlying_function, t_min = 0, t_max = 30, ) # def alt_fourier_func(t): # bell = smooth(t)*0.3*np.exp(-0.8*(t-0.9)**2) # return bell + (smooth(t/3)+0.2)*fourier_func(t) fourier_graph = frequency_axes.get_graph( fourier_func, num_graph_points = 150, ) fourier_graph.set_color(RED) frequency_axes.graph = fourier_graph arrow = Arrow(time_graph, fourier_graph, color = WHITE) ft_words = OldTexText("Fourier \\\\ transform") ft_words.next_to(arrow, RIGHT) spike_rect = self.get_spike_rect(frequency_axes, 3) spike_rect.stretch(2, 0) self.play( ReplacementTransform(time_axes.copy(), frequency_axes), ReplacementTransform(time_graph.copy(), fourier_graph), ReplacementTransform(time_axes.labels[0].copy(), freq_label), GrowArrow(arrow), Write(ft_words), VGroup(randy, speaker).shift, FRAME_Y_RADIUS*DOWN, ) self.remove(randy, speaker) self.wait() self.play(DrawBorderThenFill(spike_rect)) self.wait() self.frequency_axes = frequency_axes self.fourier_graph = fourier_graph self.spike_rect = spike_rect self.to_fourier_arrow = arrow def filter_out_high_pitch(self): fourier_graph = self.fourier_graph spike_rect = self.spike_rect frequency_axes = self.frequency_axes def filtered_func(f): result = fourier_graph.underlying_function(f) result *= np.clip(smooth(3-f), 0, 1) return result new_graph = frequency_axes.get_graph( filtered_func, num_graph_points = 300 ) new_graph.set_color(RED) self.play(spike_rect.stretch, 4, 0) self.play( Transform(fourier_graph, new_graph), spike_rect.stretch, 0.01, 1, { "about_point" : frequency_axes.coords_to_point(0, 0) }, run_time = 2 ) self.wait() def mention_inverse_transform(self): time_axes = self.time_axes time_graph = self.time_graph fourier_graph = self.fourier_graph frequency_axes = self.frequency_axes f_min = frequency_axes.x_min f_max = frequency_axes.x_max filtered_graph = time_axes.get_graph( lambda t : time_graph.underlying_function(t)-np.cos(TAU*3*t) ) filtered_graph.set_color(BLUE_C) to_fourier_arrow = self.to_fourier_arrow arrow = to_fourier_arrow.copy() arrow.rotate(TAU/2, about_edge = LEFT) arrow.shift(MED_SMALL_BUFF*LEFT) inv_fourier_words = OldTexText("Inverse Fourier \\\\ transform") inv_fourier_words.next_to(arrow, LEFT) VGroup(arrow, inv_fourier_words).set_color(MAROON_B) self.play( GrowArrow(arrow), Write(inv_fourier_words) ) self.wait() self.play( time_graph.fade, 0.9, ReplacementTransform( fourier_graph.copy(), filtered_graph ) ) self.wait() ## def get_broadcast_anims(self, run_time = 7, **kwargs): return [ self.get_broadcast_animation( n_circles = n, run_time = run_time, big_radius = 7, start_stroke_width = 5, **kwargs ) for n in (5, 7, 10, 12) ] class AskAboutInverseFourier(TeacherStudentsScene): def construct(self): self.student_says("Inverse Fourier?") self.play_student_changes("confused", "raise_right_hand", "confused") self.wait(2) class ApplyFourierToFourier(DrawFrequencyPlot): CONFIG = { "time_axes_config" : { "y_min" : -1.5, "y_max" : 1.5, "x_max" : 5, "x_axis_config" : { "numbers_to_show" : list(range(1, 5)), "unit_size" : 2.5, }, }, "frequency_axes_config" : { "y_min" : -0.6, "y_max" : 0.6, }, "circle_plane_config" : { "x_radius" : 1.5, "y_radius" : 1.35, "x_unit_size" : 1.5, "y_unit_size" : 1.5, }, "default_num_v_lines_indicating_periods" : 0, "signal_frequency" : 2, } def construct(self): self.setup_fourier_display() self.swap_graphs() def setup_fourier_display(self): self.force_skipping() self.setup_graph() self.show_center_of_mass_dot() self.introduce_frequency_plot() self.draw_full_frequency_plot() self.time_axes.remove(self.time_axes.labels) self.remove(self.beats_per_second_label) VGroup( self.time_axes, self.graph, self.frequency_axes, self.fourier_graph, self.x_coord_label, self.fourier_graph_dot, ).to_edge(UP, buff = MED_SMALL_BUFF) self.revert_to_original_skipping_status() def swap_graphs(self): fourier_graph = self.fourier_graph time_graph = self.graph wound_up_graph = time_graph.polarized_mobject time_axes = self.time_axes frequency_axes = self.frequency_axes f_max = self.frequency_axes.x_max new_fourier_graph = time_axes.get_graph( lambda t : 2*fourier_graph.underlying_function(t) ) new_fourier_graph.match_style(fourier_graph) self.remove(fourier_graph) self.play( ReplacementTransform( fourier_graph.copy(), new_fourier_graph ), ApplyMethod( time_graph.shift, 3*UP+10*LEFT, remover = True, ), ) self.play( wound_up_graph.next_to, FRAME_X_RADIUS*LEFT, LEFT, remover = True ) self.wait() self.graph = new_fourier_graph wound_up_graph = self.get_polarized_mobject(new_fourier_graph, freq = 0) double_fourier_graph = frequency_axes.get_graph( lambda t : 0.25*np.cos(TAU*2*t) ).set_color(PINK) self.fourier_graph = double_fourier_graph self.remove(self.fourier_graph_dot) self.get_fourier_graph_drawing_update_anim(double_fourier_graph) self.generate_fourier_dot_transform(double_fourier_graph) self.center_of_mass_dot.set_color(PINK) self.generate_center_of_mass_dot_update_anim() def new_get_pol_graph_center_of_mass(): result = DrawFrequencyPlot.get_pol_graph_center_of_mass(self) result -= self.circle_plane.coords_to_point(0, 0) result *= 25 result += self.circle_plane.coords_to_point(0, 0) return result self.get_pol_graph_center_of_mass = new_get_pol_graph_center_of_mass self.play( ReplacementTransform(self.graph.copy(), wound_up_graph), ChangeDecimalToValue( self.winding_freq_label[1], 0.0, run_time = 0.2, ) ) self.change_frequency(5.0, run_time = 15, rate_func=linear) self.wait() ## def get_cosine_wave(self, freq, **kwargs): kwargs["shift_val"] = 0 kwargs["scale_val"] = 1.0 return DrawFrequencyPlot.get_cosine_wave(self, freq, **kwargs) class WriteComplexExponentialExpression(DrawFrequencyPlot): CONFIG = { "signal_frequency" : 2.0, "default_num_v_lines_indicating_periods" : 0, "time_axes_scale_val" : 0.7, "initial_winding_frequency" : 0.1, "circle_plane_config" : { "unit_size" : 2, "y_radius" : FRAME_Y_RADIUS+LARGE_BUFF, "x_radius" : FRAME_X_RADIUS+LARGE_BUFF } } def construct(self): self.remove(self.pi_creature) self.setup_plane() self.setup_graph() self.show_winding_with_both_coordinates() self.show_plane_as_complex_plane() self.show_eulers_formula() self.show_winding_graph_expression() self.find_center_of_mass() def setup_plane(self): circle_plane = ComplexPlane(**self.circle_plane_config) circle_plane.shift(DOWN+LEFT) circle = DashedLine(ORIGIN, TAU*UP) circle.apply_complex_function( lambda z : R3_to_complex( circle_plane.number_to_point(np.exp(z)) ) ) circle_plane.add(circle) time_axes = self.get_time_axes() time_axes.background_rectangle = BackgroundRectangle( time_axes, fill_opacity = 0.9, buff = MED_SMALL_BUFF, ) time_axes.add_to_back(time_axes.background_rectangle) time_axes.scale(self.time_axes_scale_val) time_axes.to_corner(UP+LEFT, buff = 0) time_axes.set_stroke(color = WHITE, width = 1) self.add(circle_plane) self.add(time_axes) self.circle_plane = circle_plane self.time_axes = time_axes def setup_graph(self): plane = self.circle_plane graph = self.graph = self.get_cosine_wave( freq = self.signal_frequency, scale_val = 0.5, shift_val = 0.75, ) freq = self.initial_winding_frequency pol_graph = self.get_polarized_mobject(graph, freq = freq) wps_label = self.get_winding_frequency_label() ChangeDecimalToValue(wps_label[0], freq).update(1) wps_label.add_to_back(BackgroundRectangle(wps_label)) wps_label.next_to(plane.coords_to_point(0, 1), DOWN) wps_label.to_edge(LEFT) self.get_center_of_mass_dot() self.generate_center_of_mass_dot_update_anim() self.add(graph, pol_graph, wps_label) self.set_variables_as_attrs(pol_graph, wps_label) self.time_axes_group = VGroup(self.time_axes, graph) def show_winding_with_both_coordinates(self): com_dot = self.center_of_mass_dot plane = self.circle_plane v_line = Line(ORIGIN, UP) h_line = Line(ORIGIN, RIGHT) lines = VGroup(v_line, h_line) lines.set_color(PINK) def lines_update(lines): point = com_dot.get_center() x, y = plane.point_to_coords(point) h_line.put_start_and_end_on( plane.coords_to_point(0, y), point ) v_line.put_start_and_end_on( plane.coords_to_point(x, 0), point ) lines_update_anim = Mobject.add_updater(lines, lines_update) lines_update_anim.update(0) self.add(lines_update_anim) self.change_frequency( 2.04, added_anims = [ self.center_of_mass_dot_anim, ], run_time = 15, rate_func = bezier([0, 0, 1, 1]) ) self.wait() self.dot_component_anim = lines_update_anim def show_plane_as_complex_plane(self): to_fade = VGroup( self.time_axes_group, self.pol_graph, self.wps_label ) plane = self.circle_plane dot = self.center_of_mass_dot complex_plane_title = OldTexText("Complex plane") complex_plane_title.add_background_rectangle() complex_plane_title.to_edge(UP) coordinate_labels = plane.get_coordinate_labels() number_label = DecimalNumber( 0, include_background_rectangle = True, ) number_label_update_anim = ContinualChangingDecimal( number_label, lambda a : plane.point_to_number(dot.get_center()), position_update_func = lambda l : l.next_to( dot, DOWN+RIGHT, buff = SMALL_BUFF ), ) number_label_update_anim.update(0) flower_path = ParametricCurve( lambda t : plane.coords_to_point( np.sin(2*t)*np.cos(t), np.sin(2*t)*np.sin(t), ), t_min = 0, t_max = TAU, ) flower_path.move_to(self.center_of_mass_dot) self.play(FadeOut(to_fade)) self.play(Write(complex_plane_title)) self.play(Write(coordinate_labels)) self.wait() self.play(FadeIn(number_label)) self.add(number_label_update_anim) self.play(MoveAlongPath( dot, flower_path, run_time = 10, rate_func = bezier([0, 0, 1, 1]) )) self.wait() self.play(ShowCreation( self.pol_graph, run_time = 3, )) self.play(FadeOut(self.pol_graph)) self.wait() self.play(FadeOut(VGroup( dot, self.dot_component_anim.mobject, number_label ))) self.remove(self.dot_component_anim) self.remove(number_label_update_anim) self.set_variables_as_attrs( number_label, number_label_update_anim, complex_plane_title, ) def show_eulers_formula(self): plane = self.circle_plane ghost_dot = Dot(ORIGIN, fill_opacity = 0) def get_t(): return ghost_dot.get_center()[0] def get_circle_point(scalar = 1, t_shift = 0): return plane.number_to_point( scalar*np.exp(complex(0, get_t()+t_shift)) ) vector = Vector(plane.number_to_point(1), color = GREEN) exp_base = OldTex("e").scale(1.3) exp_base.add_background_rectangle() exp_decimal = DecimalNumber(0, unit = "i", include_background_rectangle = True) exp_decimal.scale(0.75) VGroup(exp_base, exp_decimal).match_color(vector) exp_decimal_update = ContinualChangingDecimal( exp_decimal, lambda a : get_t(), position_update_func = lambda d : d.move_to( exp_base.get_corner(UP+RIGHT), DOWN+LEFT ) ) exp_base_update = Mobject.add_updater( exp_base, lambda e : e.move_to(get_circle_point( scalar = 1.1, t_shift = 0.01*TAU )) ) vector_update = Mobject.add_updater( vector, lambda v : v.put_start_and_end_on( plane.number_to_point(0), get_circle_point() ) ) updates = [exp_base_update, exp_decimal_update, vector_update] for update in updates: update.update(0) #Show initial vector self.play( GrowArrow(vector), FadeIn(exp_base), Write(exp_decimal) ) self.add(*updates) self.play(ghost_dot.shift, 2*RIGHT, run_time = 3) self.wait() #Show arc arc, circle = [ Line(ORIGIN, t*UP) for t in (get_t(), TAU) ] for mob in arc, circle: mob.insert_n_curves(20) mob.set_stroke(RED, 4) mob.apply_function( lambda p : plane.number_to_point( np.exp(R3_to_complex(p)) ) ) distance_label = DecimalNumber( exp_decimal.number, unit = "\\text{units}" ) distance_label[-1].shift(SMALL_BUFF*RIGHT) distance_label.match_color(arc) distance_label.add_background_rectangle() distance_label.move_to( plane.number_to_point( 1.1*np.exp(complex(0, 0.4*get_t())), ), DOWN+LEFT ) self.play(ShowCreation(arc)) self.play(ReplacementTransform( exp_decimal.copy(), distance_label )) self.wait() self.play(FadeOut(distance_label)) #Show full cycle self.remove(arc) self.play( ghost_dot.move_to, TAU*RIGHT, ShowCreation( circle, rate_func = lambda a : interpolate( 2.0/TAU, 1, smooth(a) ), ), run_time = 6, ) self.wait() #Write exponential expression exp_expression = OldTex("e", "^{-", "2\\pi i", "f", "t}") e, minus, two_pi_i, f, t = exp_expression exp_expression.next_to( plane.coords_to_point(1, 1), UP+RIGHT ) f.set_color(RED) t.set_color(YELLOW) exp_expression.add_background_rectangle() two_pi_i_f_t_group = VGroup(two_pi_i, f, t) two_pi_i_f_t_group.save_state() two_pi_i_f_t_group.move_to(minus, LEFT) exp_expression[1].remove(minus) t.save_state() t.align_to(f, LEFT) exp_expression[1].remove(f) labels = VGroup() for sym, word in (t, "Time"), (f, "Frequency"): label = OldTexText(word) label.match_style(sym) label.next_to(sym, UP, buff = MED_LARGE_BUFF) label.add_background_rectangle() label.arrow = Arrow(label, sym, buff = SMALL_BUFF) label.arrow.match_style(sym) labels.add(label) time_label, frequency_label = labels example_frequency = OldTex("f = 1/10") example_frequency.add_background_rectangle() example_frequency.match_style(frequency_label) example_frequency.move_to(frequency_label, DOWN) self.play(ReplacementTransform( VGroup(exp_base[1], exp_decimal[1]).copy(), exp_expression )) self.play(FadeOut(circle)) self.wait() ghost_dot.move_to(ORIGIN) always_shift(ghost_dot, rate = TAU) self.add(ghost_dot) self.play( Write(time_label), GrowArrow(time_label.arrow), ) self.wait(12.5) #Leave time to say let's slow down self.remove(ghost_dot) self.play( FadeOut(time_label), FadeIn(frequency_label), t.restore, GrowFromPoint(f, frequency_label.get_center()), ReplacementTransform( time_label.arrow, frequency_label.arrow, ) ) ghost_dot.move_to(ORIGIN) ghost_dot.clear_updaters() always_shift(ghost_dot, rate=0.1*TAU) self.add(ghost_dot) self.wait(3) self.play( FadeOut(frequency_label), FadeIn(example_frequency) ) self.wait(15) #Give time to reference other video #Reverse directions ghost_dot.clear_updaters() always_shift(ghost_dot, rate=-0.1 * TAU) self.play( FadeOut(example_frequency), FadeOut(frequency_label.arrow), GrowFromCenter(minus), two_pi_i_f_t_group.restore ) self.wait(4) ghost_dot.clear_updaters() self.remove(*updates) self.play(*list(map(FadeOut, [ update.mobject for update in updates if update.mobject is not vector ]))) self.play(ghost_dot.move_to, ORIGIN) exp_expression[1].add(minus, f) exp_expression[1].sort(lambda p : p[0]) self.set_variables_as_attrs( ambient_ghost_dot_movement, ghost_dot, vector, vector_update, exp_expression ) def show_winding_graph_expression(self): ambient_ghost_dot_movement = self.ambient_ghost_dot_movement ghost_dot = self.ghost_dot vector = self.vector exp_expression = self.exp_expression plane = self.circle_plane time_axes_group = self.time_axes_group graph = self.graph pol_graph = self.get_polarized_mobject(graph, freq = 0.2) g_label = OldTex("g(t)") g_label.match_color(graph) g_label.next_to(graph, UP) g_label.add_background_rectangle() g_scalar = g_label.copy() g_scalar.move_to(exp_expression, DOWN+LEFT) vector_animations = self.get_vector_animations(graph) vector_animations[1].mobject = vector graph_y_vector = vector_animations[0].mobject self.play( FadeIn(time_axes_group), FadeOut(self.complex_plane_title) ) self.play(Write(g_label)) self.wait() self.play( ReplacementTransform(g_label.copy(), g_scalar), exp_expression.next_to, g_scalar, RIGHT, SMALL_BUFF, exp_expression.shift, 0.5*SMALL_BUFF*UP, ) self.play(*vector_animations, run_time = 15) self.add(*self.mobjects_from_last_animation) self.wait() integrand = VGroup(g_scalar, exp_expression) rect = SurroundingRectangle(integrand) morty = Mortimer() morty.next_to(rect, DOWN+RIGHT) morty.shift_onto_screen() self.play( ShowCreation(rect), FadeIn(morty) ) self.play(morty.change, "raise_right_hand") self.play(Blink(morty)) self.play(morty.change, "hooray", rect) self.wait(2) self.play(*list(map(FadeOut, [ morty, rect, graph_y_vector, vector ]))) self.integrand = integrand def find_center_of_mass(self): integrand = self.integrand integrand.generate_target() integrand.target.to_edge(RIGHT, buff = LARGE_BUFF) integrand.target.shift(MED_LARGE_BUFF*DOWN) sum_expr = OldTex( "{1", "\\over", "N}", "\\sum", "_{k = 1}", "^N", ) sum_expr.add_background_rectangle() sum_expr.shift(SMALL_BUFF*(UP+5*RIGHT)) sum_expr.next_to(integrand.target, LEFT) integral = OldTex( "{1", "\\over", "t_2 - t_1}", "\\int", "_{t_1}", "^{t_2}" ) integral.move_to(sum_expr, RIGHT) time_interval_indicator = SurroundingRectangle(integral[2]) integral.add_background_rectangle() axes = self.time_axes time_interval = Line( axes.coords_to_point(axes.x_min, 0), axes.coords_to_point(axes.x_max, 0), ) time_interval.match_style(time_interval_indicator) time_interval_indicator.add(time_interval) dt_mob = OldTex("dt") dt_mob.next_to(integrand.target, RIGHT, SMALL_BUFF, DOWN) dt_mob.add_background_rectangle() dots = self.show_center_of_mass_sampling(20) self.wait() self.play( Write(sum_expr), MoveToTarget(integrand), ) #Add k subscript to t's t1 = integrand[0][1][2] t2 = integrand[1][1][-1] t_mobs = VGroup(t1, t2) t_mobs.save_state() t_mobs.generate_target() for i, t_mob in enumerate(t_mobs.target): k = OldTex("k") k.match_style(t_mob) k.match_height(t_mob) k.scale(0.5) k.move_to(t_mob.get_corner(DOWN+RIGHT), LEFT) k.add_background_rectangle() t_mob.add(k) if i == 0: t_mob.shift(0.5*SMALL_BUFF*LEFT) self.play(MoveToTarget(t_mobs)) self.play(LaggedStartMap( Indicate, dots[1], rate_func = there_and_back, color = TEAL, )) self.show_center_of_mass_sampling(100) dots = self.show_center_of_mass_sampling(500) self.wait() self.play(FadeOut(dots)) self.play( ReplacementTransform(sum_expr, integral), FadeIn(dt_mob), t_mobs.restore, ) self.wait() self.play(ShowCreation(time_interval_indicator)) self.wait() self.play(FadeOut(time_interval_indicator)) self.wait() #Show confusion randy = Randolph() randy.flip() randy.next_to(integrand, DOWN, LARGE_BUFF) randy.to_edge(RIGHT) full_expression_rect = SurroundingRectangle( VGroup(integral, dt_mob), color = RED ) com_dot = self.center_of_mass_dot self.center_of_mass_dot_anim.update(0) com_arrow = Arrow( full_expression_rect.get_left(), com_dot, buff = SMALL_BUFF ) com_arrow.match_color(com_dot) self.play(FadeIn(randy)) self.play(randy.change, "confused", integral) self.play(Blink(randy)) self.wait(2) self.play(ShowCreation(full_expression_rect)) self.play( randy.change, "thinking", self.pol_graph, GrowArrow(com_arrow), GrowFromCenter(com_dot), ) self.play(Blink(randy)) self.wait(2) def show_center_of_mass_sampling(self, n_dots): time_graph = self.graph pol_graph = self.graph.polarized_mobject axes = self.time_axes dot = Dot(radius = 0.05, color = PINK) pre_dots = VGroup(*[ dot.copy().move_to(axes.coords_to_point(t, 0)) for t in np.linspace(axes.x_min, axes.x_max, n_dots) ]) pre_dots.set_fill(opacity = 0) for graph in time_graph, pol_graph: if hasattr(graph, "dots"): graph.dot_fade_anims = [FadeOut(graph.dots)] else: graph.dot_fade_anims = [] graph.save_state() graph.generate_target() if not hasattr(graph, "is_faded"): graph.target.fade(0.7) graph.is_faded = True graph.dots = VGroup(*[ dot.copy().move_to(graph.point_from_proportion(a)) for a in np.linspace(0, 1, n_dots) ]) self.play( ReplacementTransform( pre_dots, time_graph.dots, lag_ratio = 0.5, run_time = 2, ), MoveToTarget(time_graph), *time_graph.dot_fade_anims ) self.play( ReplacementTransform( time_graph.copy(), pol_graph.target ), MoveToTarget(pol_graph), ReplacementTransform( time_graph.dots.copy(), pol_graph.dots, ), *pol_graph.dot_fade_anims, run_time = 2 ) return VGroup(time_graph.dots, pol_graph.dots) class EulersFormulaViaGroupTheoryWrapper(Scene): def construct(self): title = OldTexText("Euler's formula with introductory group theory") 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(2) class WhyAreYouTellingUsThis(TeacherStudentsScene): def construct(self): self.student_says("Why are you \\\\ telling us this?") self.play(self.teacher.change, "happy") self.wait(2) class BuildUpExpressionStepByStep(TeacherStudentsScene): def construct(self): expression = OldTex( "\\frac{1}{t_2 - t_1}", "\\int_{t_1}^{t_2}", "g(t)", "e", "^{-2\\pi i", "f", "t}", "dt" ) frac, integral, g, e, two_pi_i, f, t, dt = expression expression.next_to(self.teacher, UP+LEFT) t.set_color(YELLOW) g[2].set_color(YELLOW) dt[1].set_color(YELLOW) f.set_color(GREEN) t.save_state() t.move_to(f, LEFT) self.play( self.teacher.change, "raise_right_hand", FadeIn(e), FadeIn(two_pi_i), ) self.play( self.change_students(*["pondering"]*3), FadeIn(t), ) self.play( FadeIn(f), t.restore, ) self.wait() self.play(FadeIn(g), Blink(self.students[1])) self.wait() self.play( FadeIn(integral), FadeIn(frac), FadeIn(dt), ) self.wait(3) self.teacher_says( "Just one final \\\\ distinction.", bubble_config = {"height" : 2.5, "width" : 3.5}, added_anims = [expression.to_corner, UP+RIGHT] ) self.wait(3) class ScaleUpCenterOfMass(WriteComplexExponentialExpression): CONFIG = { "time_axes_scale_val" : 0.6, "initial_winding_frequency" : 2.05 } def construct(self): self.remove(self.pi_creature) self.setup_plane() self.setup_graph() self.add_center_of_mass_dot() self.add_expression() self.cross_out_denominator() self.scale_up_center_of_mass() self.comment_on_current_signal() def add_center_of_mass_dot(self): self.center_of_mass_dot = self.get_center_of_mass_dot() self.generate_center_of_mass_dot_update_anim() self.add(self.center_of_mass_dot) def add_expression(self): expression = OldTex( "\\frac{1}{t_2 - t_1}", "\\int_{t_1}^{t_2}", "g(t)", "e", "^{-2\\pi i", "f", "t}", "dt" ) frac, integral, g, e, two_pi_i, f, t, dt = expression expression.to_corner(UP+RIGHT) t.set_color(YELLOW) g[2].set_color(YELLOW) dt[1].set_color(YELLOW) f.set_color(GREEN) self.expression = expression self.add(expression) self.winding_freq_label.to_edge(RIGHT) self.winding_freq_label[1].match_color(f) self.winding_freq_label.align_to( self.circle_plane.coords_to_point(0, 0.1), DOWN ) def cross_out_denominator(self): frac = self.expression[0] integral = self.expression[1:] for mob in frac, integral: mob.add_to_back(BackgroundRectangle(mob)) self.add(mob) cross = Cross(frac) brace = Brace(integral, DOWN) label = brace.get_text("The actual \\\\ Fourier transform") label.add_background_rectangle() label.shift_onto_screen() rect = SurroundingRectangle(integral) self.play(ShowCreation(cross)) self.wait() self.play(ShowCreation(rect)) self.play( GrowFromCenter(brace), FadeIn(label) ) self.wait(2) self.integral = integral self.frac = frac self.frac_cross = cross self.integral_rect = rect self.integral_brace = brace self.integral_label = label def scale_up_center_of_mass(self): plane = self.circle_plane origin = plane.coords_to_point(0, 0) com_dot = self.center_of_mass_dot com_vector = Arrow( origin, com_dot.get_center(), buff = 0 ) com_vector.match_style(com_dot) vector_to_scale = com_vector.copy() def get_com_vector_copies(n): com_vector_copies = VGroup(*[ com_vector.copy().shift(x*com_vector.get_vector()) for x in range(1, n+1) ]) com_vector_copies.set_color(TEAL) return com_vector_copies com_vector_update = UpdateFromFunc( com_vector, lambda v : v.put_start_and_end_on(origin, com_dot.get_center()) ) circle = Circle(color = TEAL) circle.surround(com_dot, buffer_factor = 1.2) time_span = Rectangle( stroke_width = 0, fill_color = TEAL, fill_opacity = 0.4 ) axes = self.time_axes time_span.replace( Line(axes.coords_to_point(0, 0), axes.coords_to_point(3, 1.5)), stretch = True ) time_span.save_state() time_span.stretch(0, 0, about_edge = LEFT) graph = self.graph short_graph, long_graph = [ axes.get_graph( graph.underlying_function, x_min = 0, x_max = t_max, ).match_style(graph) for t_max in (3, 6) ] for g in short_graph, long_graph: self.get_polarized_mobject(g, freq = self.initial_winding_frequency) self.play( FocusOn(circle, run_time = 2), Succession( ShowCreation, circle, FadeOut, circle, ), ) self.play( com_dot.fade, 0.5, FadeIn(vector_to_scale) ) self.wait() self.play(vector_to_scale.scale, 4, {"about_point" : origin}) self.wait() self.play( FadeOut(vector_to_scale), FadeIn(com_vector), ) self.remove(graph.polarized_mobject) self.play( com_dot.move_to, center_of_mass(short_graph.polarized_mobject.get_points()), com_vector_update, time_span.restore, ShowCreation(short_graph.polarized_mobject), ) self.wait() # dot = Dot(fill_opacity = 0.5).move_to(time_span) # self.play( # dot.move_to, com_vector, # dot.set_fill, {"opacity" : 0}, # remover = True # ) com_vector_copies = get_com_vector_copies(2) self.play(*[ ReplacementTransform( com_vector.copy(), cvc, path_arc = -TAU/10 ) for cvc in com_vector_copies ]) self.wait() #Squish_graph to_squish = VGroup( axes, graph, time_span, ) to_squish.generate_target() squish_factor = 0.75 to_squish.target.stretch(squish_factor, 0, about_edge = LEFT) pairs = list(zip( to_squish.family_members_with_points(), to_squish.target.family_members_with_points() )) to_unsquish = list(axes.x_axis.numbers) + list(axes.labels) for sm, tsm in pairs: if sm in to_unsquish: tsm.stretch(1/squish_factor, 0) if sm is axes.background_rectangle: tsm.stretch(1/squish_factor, 0, about_edge = LEFT) long_graph.stretch(squish_factor, 0) self.play( MoveToTarget(to_squish), FadeOut(com_vector_copies) ) long_graph.move_to(graph, LEFT) self.play( com_dot.move_to, center_of_mass(long_graph.polarized_mobject.get_points()), com_vector_update, time_span.stretch, 2, 0, {"about_edge" : LEFT}, *[ ShowCreation( mob, rate_func = lambda a : interpolate( 0.5, 1, smooth(a) ) ) for mob in (long_graph, long_graph.polarized_mobject) ], run_time = 2 ) self.remove(graph, short_graph.polarized_mobject) self.graph = long_graph self.wait() self.play(FocusOn(com_dot)) com_vector_copies = get_com_vector_copies(5) self.play(*[ ReplacementTransform( com_vector.copy(), cvc, path_arc = -TAU/10 ) for cvc in com_vector_copies ]) self.wait() # Scale graph out even longer to_shift = VGroup(self.integral, self.integral_rect) to_fade = VGroup( self.integral_brace, self.integral_label, self.frac, self.frac_cross ) self.play( to_shift.shift, 2*DOWN, FadeOut(to_fade), axes.background_rectangle.stretch, 2, 0, {"about_edge" : LEFT}, Animation(axes), Animation(self.graph), FadeOut(com_vector_copies), ) self.change_frequency(2.0, added_anims = [com_vector_update]) very_long_graph = axes.get_graph( graph.underlying_function, x_min = 0, x_max = 12, ) very_long_graph.match_style(graph) self.get_polarized_mobject(very_long_graph, freq = 2.0) self.play( com_dot.move_to, center_of_mass(very_long_graph.polarized_mobject.get_points()), com_vector_update, ShowCreation( very_long_graph, rate_func = lambda a : interpolate(0.5, 1, a) ), ShowCreation(very_long_graph.polarized_mobject) ) self.remove(graph, graph.polarized_mobject) self.graph = very_long_graph self.wait() self.play( com_vector.scale, 12, {"about_point" : origin}, run_time = 2 ) # com_vector_copies = get_com_vector_copies(11) # self.play(ReplacementTransform( # VGroup(com_vector.copy()), # com_vector_copies, # path_arc = TAU/10, # run_time = 1.5, # lag_ratio = 0.5 # )) self.wait() self.com_vector = com_vector self.com_vector_update = com_vector_update self.com_vector_copies = com_vector_copies def comment_on_current_signal(self): graph = self.graph com_dot = self.center_of_mass_dot com_vector = self.com_vector com_vector_update = self.com_vector_update axes = self.time_axes origin = self.circle_plane.coords_to_point(0, 0) wps_label = self.winding_freq_label new_com_vector_update = UpdateFromFunc( com_vector, lambda v : v.put_start_and_end_on( origin, com_dot.get_center() ).scale(12, about_point = origin) ) v_lines = self.get_v_lines_indicating_periods( freq = 1.0, n_lines = 3 )[:2] graph_portion = axes.get_graph( graph.underlying_function, x_min = 1, x_max = 2 ) graph_portion.set_color(TEAL) bps_label = OldTexText("2 beats per second") bps_label.scale(0.75) bps_label.next_to(graph_portion, UP, aligned_edge = LEFT) bps_label.shift(SMALL_BUFF*RIGHT) bps_label.add_background_rectangle() self.play( ShowCreation(v_lines, lag_ratio = 0), ShowCreation(graph_portion), FadeIn(bps_label), ) self.wait() self.play(ReplacementTransform( bps_label[1][0].copy(), wps_label[1] )) self.wait() self.play( com_vector.scale, 0.5, {"about_point" : origin}, rate_func = there_and_back, run_time = 2 ) self.wait(2) self.change_frequency(2.5, added_anims = [new_com_vector_update], run_time = 20, rate_func=linear, ) self.wait() class TakeAStepBack(TeacherStudentsScene): def construct(self): self.student_says( "Hang on, go over \\\\ that again?", target_mode = "confused" ), self.play_student_changes(*["confused"]*3) self.play(self.teacher.change, "happy") self.wait(3) class SimpleCosineWrappingAroundCircle(WriteComplexExponentialExpression): CONFIG = { "initial_winding_frequency" : 0, "circle_plane_config" : { "unit_size" : 3, }, } def construct(self): self.setup_plane() self.setup_graph() self.remove(self.pi_creature) self.winding_freq_label.shift(7*LEFT) VGroup(self.time_axes, self.graph).shift(4*UP) VGroup( self.circle_plane, self.graph.polarized_mobject ).move_to(ORIGIN) self.add(self.get_center_of_mass_dot()) self.generate_center_of_mass_dot_update_anim() self.change_frequency( 2.0, rate_func=linear, run_time = 30 ) self.wait() class SummarizeTheFullTransform(DrawFrequencyPlot): CONFIG = { "time_axes_config" : { "x_max" : 4.5, "x_axis_config" : { "unit_size" : 1.2, "tick_frequency" : 0.5, # "numbers_with_elongated_ticks" : range(0, 10, 2), # "numbers_to_show" : range(0, 10, 2), } }, "frequency_axes_config" : { "x_max" : 5, "x_axis_config" : { "unit_size" : 1, "numbers_to_show" : list(range(1, 5)), }, "y_max" : 2, "y_min" : -2, "y_axis_config" : { "unit_size" : 0.75, "tick_frequency" : 1, }, }, } def construct(self): self.setup_all_axes() self.show_transform_function() self.show_winding() def setup_all_axes(self): time_axes = self.get_time_axes() time_label, intensity_label = time_axes.labels time_label.next_to( time_axes.x_axis.get_right(), DOWN, SMALL_BUFF ) intensity_label.next_to(time_axes.y_axis, UP, buff = SMALL_BUFF) intensity_label.to_edge(LEFT) frequency_axes = self.get_frequency_axes() frequency_axes.to_corner(UP+RIGHT) frequency_axes.shift(RIGHT) fy_axis = frequency_axes.y_axis for number in fy_axis.numbers: number.add_background_rectangle() fy_axis.remove(*fy_axis.numbers[1::2]) frequency_axes.remove(frequency_axes.box) frequency_axes.label.shift_onto_screen() circle_plane = self.get_circle_plane() self.set_variables_as_attrs(time_axes, frequency_axes, circle_plane) self.add(time_axes) def show_transform_function(self): time_axes = self.time_axes frequency_axes = self.frequency_axes def func(t): return 0.5*(2+np.cos(2*TAU*t) + np.cos(3*TAU*t)) fourier_func = get_fourier_transform( func, t_min = time_axes.x_min, t_max = time_axes.x_max, use_almost_fourier = False, ) graph = time_axes.get_graph(func) graph.set_color(GREEN) fourier_graph = frequency_axes.get_graph(fourier_func) fourier_graph.set_color(RED) g_t = OldTex("g(t)") g_t[-2].match_color(graph) g_t.next_to(graph, UP) g_hat_f = OldTex("\\hat g(f)") g_hat_f[-2].match_color(fourier_graph) g_hat_f.next_to( frequency_axes.input_to_graph_point(2, fourier_graph), UP ) morty = self.pi_creature time_label = time_axes.labels[0] frequency_label = frequency_axes.label for label in time_label, frequency_label: label.rect = SurroundingRectangle(label) time_label.rect.match_style(graph) frequency_label.rect.match_style(fourier_graph) self.add(graph) g_t.save_state() g_t.move_to(morty, UP+LEFT) g_t.fade(1) self.play( morty.change, "raise_right_hand", g_t.restore, ) self.wait() self.play(Write(frequency_axes, run_time = 1)) self.play( ReplacementTransform(graph.copy(), fourier_graph), ReplacementTransform(g_t.copy(), g_hat_f), ) self.wait(2) for label in time_label, frequency_label: self.play( ShowCreation(label.rect), morty.change, "thinking" ) self.play(FadeOut(label.rect)) self.wait() self.set_variables_as_attrs( graph, fourier_graph, g_t, g_hat_f ) def show_winding(self): plane = self.circle_plane graph = self.graph fourier_graph = self.fourier_graph morty = self.pi_creature g_hat_f = self.g_hat_f g_hat_f_rect = SurroundingRectangle(g_hat_f) g_hat_f_rect.set_color(TEAL) g_hat_rect = SurroundingRectangle(g_hat_f[0]) g_hat_rect.match_style(g_hat_f_rect) g_hat_f.generate_target() g_hat_f.target.next_to(plane, RIGHT) g_hat_f.target.shift(UP) arrow = Arrow( g_hat_f.target.get_left(), plane.coords_to_point(0, 0), color = self.center_of_mass_color, ) frequency_axes = self.frequency_axes imaginary_fourier_graph = frequency_axes.get_graph( get_fourier_transform( graph.underlying_function, t_min = self.time_axes.x_min, t_max = self.time_axes.x_max, real_part = False, use_almost_fourier = False, ) ) imaginary_fourier_graph.set_color(BLUE) imaginary_fourier_graph.shift( frequency_axes.x_axis.get_right() - \ imaginary_fourier_graph.get_points()[-1], ) real_part = OldTexText( "Real part of", "$\\hat g(f)$" ) real_part[1].match_style(g_hat_f) real_part.move_to(g_hat_f) real_part.to_edge(RIGHT) self.get_polarized_mobject(graph, freq = 0) update_pol_graph = UpdateFromFunc( graph.polarized_mobject, lambda m : m.set_stroke(width = 2) ) com_dot = self.get_center_of_mass_dot() winding_run_time = 40.0 g_hat_f_indication = Succession( Animation, Mobject(), {"run_time" : 4}, FocusOn, g_hat_f, ShowCreation, g_hat_f_rect, Animation, Mobject(), Transform, g_hat_f_rect, g_hat_rect, Animation, Mobject(), FadeOut, g_hat_f_rect, Animation, Mobject(), MoveToTarget, g_hat_f, UpdateFromAlphaFunc, com_dot, lambda m, a : m.set_fill(opacity = a), Animation, Mobject(), {"run_time" : 2}, GrowArrow, arrow, FadeOut, arrow, Animation, Mobject(), {"run_time" : 5}, Write, real_part, {"run_time" : 2}, Animation, Mobject(), {"run_time" : 3}, ShowCreation, imaginary_fourier_graph, {"run_time" : 3}, rate_func = squish_rate_func( lambda x : x, 0, 31./winding_run_time ), run_time = winding_run_time ) self.play( FadeIn(plane), ReplacementTransform( graph.copy(), graph.polarized_mobject ), morty.change, "happy", ) self.generate_center_of_mass_dot_update_anim(multiplier = 4.5) self.generate_fourier_dot_transform(fourier_graph) self.change_frequency( 5.0, rate_func=linear, run_time = winding_run_time, added_anims = [ g_hat_f_indication, update_pol_graph, Animation(frequency_axes.x_axis.numbers), Animation(self.fourier_graph_dot), ] ) self.wait() class SummarizeFormula(Scene): def construct(self): expression = self.get_expression() screen_rect = ScreenRectangle(height = 5) screen_rect.to_edge(DOWN) exp_rect, g_exp_rect, int_rect = [ SurroundingRectangle(VGroup( expression.get_part_by_tex(p1), expression.get_part_by_tex(p2), )) for p1, p2 in [("e", "t}"), ("g({}", "t}"), ("\\int", "dt")] ] self.add(expression) self.wait() self.play( ShowCreation(screen_rect), ShowCreation(exp_rect), ) self.wait(2) self.play(Transform(exp_rect, g_exp_rect)) self.wait(2) self.play(Transform(exp_rect, int_rect)) self.wait(2) def get_expression(self): expression = OldTex( "\\hat g(", "f", ")", "=", "\\int", "_{t_1}", "^{t_2}", "g({}", "t", ")", "e", "^{-2\\pi i", "f", "t}", "dt" ) expression.set_color_by_tex( "t", YELLOW, substring = False, ) expression.set_color_by_tex("t}", YELLOW) expression.set_color_by_tex( "f", RED, substring = False, ) expression.scale(1.2) expression.to_edge(UP) return expression class OneSmallNote(TeacherStudentsScene): def construct(self): self.teacher_says( "Just one \\\\ small note...", # target_mode = ) self.play_student_changes("erm", "happy", "sassy") self.wait(2) class BoundsAtInfinity(SummarizeFormula): def construct(self): expression = self.get_expression() self.add(expression) self.add_graph() axes = self.axes graph = self.graph time_interval = self.get_time_interval(-2, 2) wide_interval = self.get_time_interval(-FRAME_X_RADIUS, FRAME_X_RADIUS) bounds = VGroup(*reversed(expression.get_parts_by_tex("t_"))) bound_rects = VGroup(*[ SurroundingRectangle(b, buff = 0.5*SMALL_BUFF) for b in bounds ]) bound_rects.set_color(TEAL) inf_bounds = VGroup(*[ VGroup(OldTex(s + "\\infty")) for s in ("-", "+") ]) decimal_bounds = VGroup(*[DecimalNumber(0) for x in range(2)]) for bound, inf_bound, d_bound in zip(bounds, inf_bounds, decimal_bounds): for new_bound in inf_bound, d_bound: new_bound.scale(0.7) new_bound.move_to(bound, LEFT) new_bound.bound = bound def get_db_num_update(vect): return lambda a : axes.x_axis.point_to_number( time_interval.get_edge_center(vect) ) decimal_updates = [ ChangingDecimal( db, get_db_num_update(vect), position_update_func = lambda m : m.move_to( m.bound, LEFT ) ) for db, vect in zip(decimal_bounds, [LEFT, RIGHT]) ] for update in decimal_updates: update.update(1) time_interval.save_state() self.wait() self.play(ReplacementTransform( self.get_time_interval(0, 0.01), time_interval )) self.play(LaggedStartMap(ShowCreation, bound_rects)) self.wait() self.play(FadeOut(bound_rects)) self.play(ReplacementTransform(bounds, inf_bounds)) self.play(Transform( time_interval, wide_interval, run_time = 4, rate_func = there_and_back )) self.play( ReplacementTransform(inf_bounds, decimal_bounds), time_interval.restore, ) self.play( VGroup(axes, graph).stretch, 0.05, 0, Transform(time_interval, wide_interval), UpdateFromAlphaFunc( axes.x_axis.numbers, lambda m, a : m.set_fill(opacity = 1-a) ), *decimal_updates, run_time = 12, rate_func = bezier([0, 0, 1, 1]) ) self.wait() def add_graph(self): axes = Axes( x_min = -140, x_max = 140, y_min = -2, y_max = 2, axis_config = { "include_tip" : False, }, ) axes.x_axis.add_numbers(*list(filter( lambda x : x != 0, list(range(-8, 10, 2)), ))) axes.shift(DOWN) self.add(axes) def func(x): return np.exp(-0.1*x**2)*(1 + np.cos(TAU*x)) graph = axes.get_graph(func) self.add(graph) graph.set_color(YELLOW) self.set_variables_as_attrs(axes, graph) def get_time_interval(self, t1, t2): line = Line(*[ self.axes.coords_to_point(t, 0) for t in (t1, t2) ]) rect = Rectangle( stroke_width = 0, fill_color = TEAL, fill_opacity = 0.5, ) rect.match_width(line) rect.stretch_to_fit_height(2.5) rect.move_to(line, DOWN) return rect class MoreToCover(TeacherStudentsScene): def construct(self): self.teacher_says( "Much more to say...", target_mode = "hooray", run_time = 1, ) self.wait() self.teacher_says( "SO MUCH!", target_mode = "surprised", added_anims = [self.change_students(*3*["happy"])], run_time = 0.5 ) self.wait(2) class ShowUncertaintyPrinciple(Scene): def construct(self): title = OldTexText("Uncertainty principle") self.add(title) top_axes = Axes( x_min = -FRAME_X_RADIUS, x_max = FRAME_X_RADIUS, y_min = 0, y_max = 3, y_axis_config = { "unit_size" : 0.6, "include_tip" : False, } ) bottom_axes = top_axes.deepcopy() arrow = Vector(DOWN, color = WHITE) group = VGroup( title, top_axes, arrow, bottom_axes ) group.arrange(DOWN) title.shift(MED_SMALL_BUFF*UP) group.to_edge(UP) fourier_word = OldTexText("Fourier transform") fourier_word.next_to(arrow, RIGHT) self.add(group, fourier_word) ghost_dot = Dot(RIGHT, fill_opacity = 0) def get_bell_func(factor = 1): return lambda x : 2*np.exp(-factor*x**2) top_graph = top_axes.get_graph(get_bell_func()) top_graph.set_color(YELLOW) bottom_graph = bottom_axes.get_graph(get_bell_func()) bottom_graph.set_color(RED) def get_update_func(axes): def update_graph(graph): f = ghost_dot.get_center()[0] if axes == bottom_axes: f = 1./f new_graph = axes.get_graph(get_bell_func(f)) graph.set_points(new_graph.get_points()) return update_graph factors = [0.3, 0.1, 2, 10, 100, 0.01, 0.5] self.play(ShowCreation(top_graph)) self.play(ReplacementTransform( top_graph.copy(), bottom_graph, )) self.wait(2) self.add(*[ Mobject.add_updater(graph, get_update_func(axes)) for graph, axes in [(top_graph, top_axes), (bottom_graph, bottom_axes)] ]) for factor in factors: self.play( ghost_dot.move_to, factor*RIGHT, run_time = 2 ) self.wait() class XCoordinateLabelTypoFix(Scene): def construct(self): words = OldTexText("$x$-coordinate for center of mass") words.set_color(RED) self.add(words) class NextVideoWrapper(Scene): def construct(self): title = OldTexText("Next video") 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(2) class SubscribeOrBinge(PiCreatureScene): def construct(self): morty = self.pi_creature morty.center().to_edge(DOWN, LARGE_BUFF) subscribe = OldTexText("Subscribe") subscribe.set_color(RED) subscribe.next_to(morty, UP+RIGHT) binge = OldTexText("Binge") binge.set_color(BLUE) binge.next_to(morty, UP+LEFT) videos = VGroup(*[VideoIcon() for x in range(30)]) colors = it.cycle([BLUE_D, BLUE_E, BLUE_C, GREY_BROWN]) for video, color in zip(videos, colors): video.set_color(color) videos.move_to(binge.get_bottom(), UP) video_anim = LaggedStartMap( Succession, videos, lambda v : ( FadeIn, v, ApplyMethod, v.shift, 5*DOWN, {"run_time" : 6}, ), run_time = 10 ) sub_arrow = Arrow( subscribe.get_bottom(), Dot().to_corner(DOWN+RIGHT, buff = LARGE_BUFF), color = RED ) for word in subscribe, binge: word.save_state() word.shift(DOWN) word.set_fill(opacity = 0) self.play( subscribe.restore, morty.change, "raise_left_hand" ) self.play(GrowArrow(sub_arrow)) self.wait() self.play( video_anim, Succession( AnimationGroup( ApplyMethod(binge.restore), ApplyMethod(morty.change, "raise_right_hand", binge), ), Blink, morty, ApplyMethod, morty.change, "shruggie", videos, Animation, Mobject(), {"run_time" : 2}, Blink, morty, Animation, Mobject(), {"run_time" : 4} ) ) class CloseWithAPuzzle(TeacherStudentsScene): def construct(self): self.teacher_says("Close with a puzzle!", run_time = 1) self.play_student_changes(*["hooray"]*3) self.wait(3) class PuzzleDescription(Scene): def construct(self): lines = VGroup( OldTexText("Convex set", "$C$", "in $\\mathds{R}^3$"), OldTexText("Boundary", "$B$", "$=$", "$\\partial C$"), OldTexText("$D$", "$=\\{p+q | p, q \\in B\\}$"), OldTexText("Prove that", "$D$", "is convex") ) for line in lines: line.set_color_by_tex_to_color_map({ "$C$" : BLUE_D, "\\partial C" : BLUE_D, "$B$" : BLUE_C, "$D$" : YELLOW, }) VGroup(lines[2][1][2], lines[2][1][6]).set_color(RED) VGroup(lines[2][1][4], lines[2][1][8]).set_color(MAROON_B) lines[2][1][10].set_color(BLUE_C) lines.scale(1.25) lines.arrange(DOWN, buff = LARGE_BUFF, aligned_edge = LEFT) lines.to_corner(UP+RIGHT) for line in lines: self.play(Write(line)) self.wait(2) class SponsorScreenGrab(PiCreatureScene): def construct(self): morty = self.pi_creature screen = ScreenRectangle(height = 5) screen.to_corner(UP+LEFT) screen.shift(MED_LARGE_BUFF*DOWN) url = OldTexText("janestreet.com/3b1b") url.next_to(screen, UP) self.play( morty.change, "raise_right_hand", ShowCreation(screen) ) self.play(Write(url)) self.wait(2) for mode in "happy", "thinking", "pondering", "thinking": self.play(morty.change, mode, screen) self.wait(4) class FourierEndScreen(PatreonEndScreen): CONFIG = { "specific_patrons" : [ "CrypticSwarm", "Ali Yahya", "Juan Benet", "Markus Persson", "Damion Kistler", "Burt Humburg", "Yu Jun", "Dave Nicponski", "Kaustuv DeBiswas", "Joseph John Cox", "Luc Ritchie", "Achille Brighton", "Rish Kundalia", "Yana Chernobilsky", "Shìmín Kuang", "Mathew Bramson", "Jerry Ling", "Mustafa Mahdi", "Meshal Alshammari", "Mayank M. Mehrotra", "Lukas Biewald", "Robert Teed", "One on Epsilon", "Samantha D. Suplee", "Mark Govea", "John Haley", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Boris Veselinovich", "Ryan Dahl", "Ripta Pasay", "Eric Lavault", "Mads Elvheim", "Andrew Busey", "Randall Hunt", "Desmos", "Tianyu Ge", "Awoo", "Dr David G. Stork", "Linh Tran", "Jason Hise", "Bernd Sing", "Ankalagon", "Mathias Jansson", "David Clark", "Ted Suzman", "Eric Chow", "Michael Gardner", "Jonathan Eppele", "Clark Gaebel", "David Kedmey", "Jordan Scales", "Ryan Atallah", "supershabam", "1stViewMaths", "Jacob Magnuson", "Thomas Tarler", "Isak Hietala", "James Thornton", "Egor Gumenuk", "Waleed Hamied", "Oliver Steele", "Yaw Etse", "David B", "Julio Cesar Campo Neto", "Delton Ding", "George Chiesa", "Chloe Zhou", "Alexander Nye", "Ross Garber", "Wang HaoRan", "Felix Tripier", "Arthur Zey", "Norton", "Kevin Le", "Alexander Feldman", "David MacCumber", ], } class Thumbnail(Scene): def construct(self): title = OldTexText("Fourier\\\\", "Visualized") title.set_color(YELLOW) title.set_stroke(RED, 2) title.scale(2.5) title.add_background_rectangle() def func(t): return np.cos(2*TAU*t) + np.cos(3*TAU*t) + np.cos(5*t) fourier = get_fourier_transform(func, -5, 5) graph = FunctionGraph(func, (-5, 5, 0.01)) graph.set_color(BLUE) fourier_graph = FunctionGraph(fourier, (0, 6, 0.01)) fourier_graph.set_color(YELLOW) for g in graph, fourier_graph: g.stretch_to_fit_height(2) g.stretch_to_fit_width(10) g.set_stroke(width=6) pol_graphs = VGroup() for f in np.linspace(1.98, 2.02, 5): pol_graph = ParametricCurve( lambda t : complex_to_R3( (2+np.cos(2*TAU*t)+np.cos(3*TAU*t))*np.exp(-complex(0, TAU*f*t)) ), t_range=(-5, 5, 0.01), ) pol_graph.match_color(graph) pol_graph.set_height(2) pol_graphs.add(pol_graph) pol_graphs.arrange(RIGHT, buff=LARGE_BUFF) pol_graphs.set_color_by_gradient(BLUE_C, TEAL, GREEN) pol_graphs.match_width(graph) pol_graphs.set_stroke(width=1) parts = VGroup(graph, pol_graphs, fourier_graph) parts[1].set_width(parts[0].get_width() - 1) parts.arrange( DOWN, buff=LARGE_BUFF, aligned_edge=RIGHT ) parts.to_edge(RIGHT) self.add(parts) words = VGroup(OldTexText("Signal"), OldTexText("Winding"), OldTexText("Transform")) for word, part in zip(words, parts): word.scale(1.5) word.next_to(part, LEFT) word.to_edge(LEFT, MED_LARGE_BUFF) self.add(words) rect = SurroundingRectangle(pol_graphs[2]) rect.set_stroke(RED, 2) dot = Dot(fourier_graph.pfp(2 / 6), color=RED) dot.set_stroke(BLACK, 3, background=True) dot.shift(0.01 * RIGHT) line = Line(dot.get_center(), rect.get_corner(DL), buff=0.1) line.match_style(rect) self.add(dot, line, rect)