file_path
stringclasses
1 value
content
stringlengths
0
219k
from manim_imports_ext import * from _2018.lost_lecture import Orbiting from _2018.lost_lecture import ShowWord class LogoGeneration(LogoGenerationTemplate): CONFIG = { "random_seed": 2, } def get_logo_animations(self, logo): layers = logo.spike_layers for layer in 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) return [ FadeIn( logo.iris_background, rate_func=squish_rate_func(smooth, 0.25, 1), run_time=3, ), AnimationGroup(*[ LaggedStartMap( Restore, layer, run_time=3, path_arc=180 * DEGREES, rate_func=squish_rate_func(smooth, a / 3.0, (a + 0.9) / 3.0), lag_ratio=0.8, ) for layer, a in zip(layers, [0, 2, 1, 0]) ]), Animation(logo.pupil), ] class ThinkingAboutAProof(PiCreatureScene): def construct(self): randy = self.pi_creature randy.scale(0.5, about_edge=DL) bubble = ThoughtBubble() bubble.pin_to(randy) bubble.shift(MED_SMALL_BUFF * RIGHT) cloud = bubble[-1] cloud.rotate(90 * DEGREES) cloud.set_height(FRAME_HEIGHT - 0.5) cloud.stretch(2.8, 0) cloud.next_to(bubble[2], RIGHT) cloud.to_edge(UP, buff=0.25) bubble[1].shift(0.25 * UL) you_arrow = Vector(LEFT, color=WHITE) you_arrow.next_to(randy, RIGHT) you = OldTexText("You") you.next_to(you_arrow, RIGHT) lm_arrow = Vector(DOWN, color=WHITE) lm_arrow.next_to(randy, UP) love_math = OldTexText("Love math") love_math.next_to(lm_arrow, UP) love_math.shift_onto_screen() self.add(bubble) self.play( FadeIn(you, LEFT), GrowArrow(you_arrow), ) self.play( FadeInFromDown(love_math), GrowArrow(lm_arrow), randy.change, "erm" ) self.wait(2) self.play( randy.change, "pondering", cloud ) self.wait(10) class SumOfIntegersProof(Scene): CONFIG = { "n": 6, } def construct(self): equation = OldTex( "1", "+", "2", "+", "3", "+", "\\cdots", "+", "n", "=", "\\frac{n(n+1)}{2}" ) equation.scale(1.5) equation.to_edge(UP) one, two, three, dots, n = numbers = VGroup(*[ equation.get_part_by_tex(tex, substring=False).copy() for tex in ("1", "2", "3", "\\cdots", "n",) ]) for number in numbers: number.generate_target() number.target.scale(0.75) rows = self.get_rows() rows.next_to(equation, DOWN, buff=MED_LARGE_BUFF) flipped_rows = self.get_flipped_rows(rows) for row, num in zip(rows, [one, two, three]): num.target.next_to(row, LEFT) dots.target.rotate(90 * DEGREES) dots.target.next_to(rows[3:-1], LEFT) dots.target.align_to(one.target, LEFT) n.target.next_to(rows[-1], LEFT) for row in rows: row.save_state() for square in row: square.stretch(0, 0) square.move_to(row, LEFT) row.fade(1) self.play(LaggedStartMap(FadeInFromDown, equation[:-1])) self.wait() self.play( LaggedStartMap( MoveToTarget, numbers, path_arc=-90 * DEGREES, lag_ratio=1, run_time=1 ) ) self.play(LaggedStartMap(Restore, rows)) self.wait() self.play( ReplacementTransform( rows.copy().set_fill(opacity=0), flipped_rows, path_arc=-PI, run_time=2 ) ) self.wait() self.play(Write(equation[-1])) self.wait(5) def get_rows(self): rows = VGroup() for count in range(1, self.n + 1): row = VGroup(*[Square() for k in range(count)]) row.arrange(RIGHT, buff=0) rows.add(row) rows.arrange(DOWN, buff=0, aligned_edge=LEFT) rows.set_height(5) rows.set_stroke(WHITE, 3) rows.set_fill(BLUE, 0.5) return rows def get_flipped_rows(self, rows): result = rows.copy() result.rotate(PI) result.set_fill(RED_D, 0.5) result.move_to(rows, LEFT) result.shift(rows[0][0].get_width() * RIGHT) return result class FeynmansLostLectureWrapper(Scene): def construct(self): title = OldTexText("Feynman's Lost Lecture") 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 HoldUpProof(TeacherStudentsScene): def construct(self): title = OldTexText("One of my all-time favorite proofs") title.to_edge(UP) self.add(title) self.play( self.teacher.change, "raise_right_hand", self.screen, self.change_students( "pondering", "confused", "maybe", look_at=title ) ) self.look_at(title) self.wait(5) self.play_student_changes( "happy", "thinking", "hooray", look_at=title ) self.wait(5) class MultipleDefinitionsOfAnEllipse(Scene): def construct(self): title = Title("Multiple definitions of ``ellipse''") self.add(title) definitions = VGroup( OldTexText("1. Stretch a circle"), OldTexText("2. Thumbtack \\\\ \\quad\\, construction"), OldTexText("3. Slice a cone"), ) definitions.arrange( DOWN, buff=LARGE_BUFF, aligned_edge=LEFT ) definitions.next_to(title, DOWN, LARGE_BUFF) definitions.to_edge(LEFT) for definition in definitions: definition.saved_state = definition.copy() definition.saved_state.set_fill(GREY_B, 0.5) self.play(LaggedStartMap( FadeInFrom, definitions, lambda m: (m, RIGHT), run_time=4 )) self.wait() for definition in definitions: others = [d for d in definitions if d is not definition] self.play( definition.set_fill, WHITE, 1, definition.scale, 1.2, {"about_edge": LEFT}, *list(map(Restore, others)) ) self.wait(2) class StretchACircle(Scene): def construct(self): plane = NumberPlane( x_unit_size=2, y_unit_size=2 ) circle = Circle(radius=2) circle.set_stroke(YELLOW, 5) circle_ghost = circle.copy() circle_ghost.set_stroke(width=1) plane_circle_group = VGroup(plane, circle) plane_circle_group.save_state() arrows = self.get_arrows() prop = 1.0 / 8 start_point = Dot(circle.point_from_proportion(prop)) end_point = start_point.copy().stretch(2, 0, about_point=ORIGIN) end_point.stretch(0.5, 0) end_point.set_color(RED) xy = OldTex("(x, y)") cxy = OldTex("(c \\cdot x, y)") cxy[1].set_color(RED) for tex in xy, cxy: tex.scale(1.5) tex.add_background_rectangle() xy_arrow = Vector(DOWN, color=WHITE) cxy_arrow = Vector(DL, color=WHITE) xy_arrow.next_to(start_point, UP, SMALL_BUFF) xy.next_to(xy_arrow, UP, SMALL_BUFF) cxy_arrow.next_to(end_point, UR, SMALL_BUFF) cxy.next_to(cxy_arrow, UR, SMALL_BUFF) self.add(plane_circle_group) self.wait() self.play( ApplyMethod( plane_circle_group.stretch, 2, 0, run_time=2, ), LaggedStartMap( GrowArrow, arrows, run_time=1, lag_ratio=1 ), ) self.play(FadeOut(arrows)) self.wait() self.play(Restore(plane_circle_group)) self.play( GrowArrow(xy_arrow), Write(xy), FadeIn(start_point, UP), ) self.wait() self.add(circle_ghost) self.play( circle.stretch, 2, 0, ReplacementTransform(start_point.copy(), end_point), run_time=2 ) self.play( GrowArrow(cxy_arrow), Write(cxy) ) self.wait(2) def get_arrows(self): result = VGroup() for vect in [LEFT, RIGHT]: for y in range(-3, 4): arrow = Vector(vect) arrow.move_to(2 * vect + y * UP) result.add(arrow) result.set_color(RED) return result class ShowArrayOfEccentricities(Scene): def construct(self): eccentricities = np.linspace(0, 0.99, 6) eccentricity_labels = VGroup(*list(map( DecimalNumber, eccentricities ))) ellipses = self.get_ellipse_row(eccentricities) ellipses.set_color_by_gradient(BLUE, YELLOW) ellipses.move_to(DOWN) for label, ellipse in zip(eccentricity_labels, ellipses): label.next_to(ellipse, UP) name = OldTexText("Eccentricity") name.scale(1.5) name.to_edge(UP) alt_name = OldTexText("(read ``squishification'')") alt_name.set_color(YELLOW) alt_name.next_to(name, RIGHT) alt_name.shift_onto_screen() name.generate_target() name.target.next_to(alt_name, LEFT) arrows = VGroup(*[ Arrow(name.get_bottom(), label.get_top()) for label in eccentricity_labels ]) arrows.set_color_by_gradient(BLUE, YELLOW) for label, arrow in zip(eccentricity_labels, arrows): label.save_state() label.fade(1) label.scale(0.1) label.move_to(arrow.get_start()) morty = Mortimer(height=2) morty.next_to(alt_name, DOWN) self.add(ellipses[0]) for e1, e2 in zip(ellipses[:-1], ellipses[1:]): self.play(ReplacementTransform( e1.copy(), e2, path_arc=10 * DEGREES )) self.wait() self.play( Write(name), LaggedStartMap(GrowArrow, arrows), LaggedStartMap(Restore, eccentricity_labels) ) self.wait() self.play( Write(alt_name), MoveToTarget(name), morty.change, "hooray", alt_name, VFadeIn(morty), ) self.play(Blink(morty)) self.play(morty.change, "thinking", ellipses) self.wait() self.play(Blink(morty)) for i in 0, -1: e_copy = ellipses[i].copy() e_copy.set_color(RED) self.play(ShowCreation(e_copy)) self.play( ShowCreationThenFadeAround( eccentricity_labels[i], ), FadeOut(e_copy) ) self.wait() circle = ellipses[0] group = VGroup(*it.chain( eccentricity_labels, ellipses[1:], arrows, name, alt_name, [morty] )) self.play( LaggedStartMap(FadeOutAndShiftDown, group), circle.set_height, 5, circle.center, ) def get_ellipse(self, eccentricity, width=2): result = Circle(color=WHITE) result.set_width(width) a = width / 2.0 c = eccentricity * a b = np.sqrt(a**2 - c**2) result.stretch(b / a, 1) result.shift(c * LEFT) result.eccentricity = eccentricity return result def get_ellipse_row(self, eccentricities, buff=MED_SMALL_BUFF, **kwargs): result = VGroup(*[ self.get_ellipse(e, **kwargs) for e in eccentricities ]) result.arrange(RIGHT, buff=buff) return result def get_eccentricity(self, ellipse): """ Assumes that it's major/minor axes line up with x and y axes """ a = ellipse.get_width() b = ellipse.get_height() if b > a: a, b = b, a c = np.sqrt(a**2 - b**2) return fdiv(c, a) class ShowOrbits(ShowArrayOfEccentricities): CONFIG = {"camera_config": {"background_opacity": 1}} def construct(self): earth_eccentricity = 0.0167 comet_eccentricity = 0.9671 earth_orbit = self.get_ellipse(eccentricity=earth_eccentricity) comet_orbit = self.get_ellipse(eccentricity=comet_eccentricity) earth_orbit.set_height(5) comet_orbit.set_width( 0.7 * FRAME_WIDTH, about_point=ORIGIN, ) sun = ImageMobject("Sun") earth = ImageMobject("Earth") comet = ImageMobject("Comet") sun.set_height(1) earth.set_height(0.5) comet.set_height(0.1) earth_parts = VGroup(sun, earth_orbit, earth) eccentricity_label = DecimalNumber( earth_eccentricity, num_decimal_places=4 ) eccentricity_equals = OldTexText( "Eccentricity = " ) earth_orbit_words = OldTexText("Earth's orbit") earth_orbit_words.set_color(BLUE) full_label = VGroup( earth_orbit_words, eccentricity_equals, eccentricity_label ) full_label.arrange(RIGHT, SMALL_BUFF) earth_orbit_words.shift(0.5 * SMALL_BUFF * UL) full_label.to_edge(UP) comet_orbit_words = OldTexText("Halley's comet orbit") comet_orbit_words.set_color(GREY_B) comet_orbit_words.move_to(earth_orbit_words, RIGHT) orbiting_earth = Orbiting(earth, sun, earth_orbit) orbiting_comet = Orbiting(comet, sun, comet_orbit) self.add(full_label, earth_orbit_words) self.add(sun, earth_orbit, orbiting_earth) self.wait(10) orbiting_earth.rate = 1.5 orbiting_comet.rate = 1.5 self.play( earth_parts.set_height, comet_orbit.get_height() / 4.53, earth_parts.shift, 3 * RIGHT ) comet_orbit.shift(3 * RIGHT) comet_orbit.save_state() Transform(comet_orbit, earth_orbit).update(1) self.play( Restore(comet_orbit, run_time=2), ChangingDecimal( eccentricity_label, lambda a: self.get_eccentricity(comet_orbit) ), FadeOut(earth_orbit_words, UP), FadeInFromDown(comet_orbit_words) ) self.add(orbiting_comet) self.wait(10) class EccentricityInThumbtackCase(ShowArrayOfEccentricities): def construct(self): ellipse = self.get_ellipse(0.2, width=5) ellipse_target = self.get_ellipse(0.9, width=5) ellipse_target.scale(fdiv( sum(self.get_abc(ellipse)), sum(self.get_abc(ellipse_target)), )) for mob in ellipse, ellipse_target: mob.center() mob.set_color(BLUE) thumbtack_update = self.get_thumbtack_update(ellipse) ellipse_point_update = self.get_ellipse_point_update(ellipse) focal_lines_update = self.get_focal_lines_update( ellipse, ellipse_point_update.mobject ) focus_to_focus_line_update = self.get_focus_to_focus_line_update(ellipse) eccentricity_label = self.get_eccentricity_label() eccentricity_value_update = self.get_eccentricity_value_update( eccentricity_label, ellipse, ) inner_brace_update = self.get_focus_line_to_focus_line_brace_update( focus_to_focus_line_update.mobject ) outer_lines = self.get_outer_dashed_lines(ellipse) outer_lines_brace = Brace(outer_lines, DOWN) focus_distance = OldTexText("Focus distance") focus_distance.set_color(GREEN) focus_distance.next_to(inner_brace_update.mobject, DOWN, SMALL_BUFF) focus_distance.add_to_back(focus_distance.copy().set_stroke(BLACK, 5)) focus_distance_update = Mobject.add_updater( focus_distance, lambda m: m.set_width( inner_brace_update.mobject.get_width(), ).next_to(inner_brace_update.mobject, DOWN, SMALL_BUFF) ) diameter = OldTexText("Diameter") diameter.set_color(RED) diameter.next_to(outer_lines_brace, DOWN, SMALL_BUFF) fraction = OldTex( "{\\text{Focus distance}", "\\over", "\\text{Diameter}}" ) numerator = fraction.get_part_by_tex("Focus") numerator.set_color(GREEN) fraction.set_color_by_tex("Diameter", RED) fraction.move_to(2 * UP) fraction.to_edge(RIGHT, buff=MED_LARGE_BUFF) numerator_update = Mobject.add_updater( numerator, lambda m: m.set_width(focus_distance.get_width()).next_to( fraction[1], UP, MED_SMALL_BUFF ) ) fraction_arrow = Arrow( eccentricity_label.get_right(), fraction.get_top() + MED_SMALL_BUFF * UP, path_arc=-60 * DEGREES, ) fraction_arrow.pointwise_become_partial(fraction_arrow, 0, 0.95) ellipse_transformation = Transform( ellipse, ellipse_target, rate_func=there_and_back, run_time=8, ) self.add(ellipse) self.add(thumbtack_update) self.add(ellipse_point_update) self.add(focal_lines_update) self.add(focus_to_focus_line_update) self.add(eccentricity_label) self.add(eccentricity_value_update) self.play(ellipse_transformation) self.add(inner_brace_update) self.add(outer_lines) self.add(outer_lines_brace) self.add(fraction) self.add(fraction_arrow) self.add(focus_distance) self.add(diameter) self.add(focus_distance_update) self.add(numerator_update) self.play( ellipse_transformation, VFadeIn(inner_brace_update.mobject), VFadeIn(outer_lines), VFadeIn(outer_lines_brace), VFadeIn(fraction), VFadeIn(fraction_arrow), VFadeIn(focus_distance), VFadeIn(diameter), ) def get_thumbtack_update(self, ellipse): thumbtacks = VGroup(*[ self.get_thumbtack() for x in range(2) ]) def update_thumbtacks(thumbtacks): foci = self.get_foci(ellipse) for thumbtack, focus in zip(thumbtacks, foci): thumbtack.move_to(focus, DR) return thumbtacks return Mobject.add_updater(thumbtacks, update_thumbtacks) def get_ellipse_point_update(self, ellipse): dot = Dot(color=RED) return cycle_animation(MoveAlongPath( dot, ellipse, run_time=5, rate_func=linear )) def get_focal_lines_update(self, ellipse, ellipse_point): lines = VGroup(*[Line(LEFT, RIGHT) for x in range(2)]) lines.set_color_by_gradient(YELLOW, PINK) def update_lines(lines): foci = self.get_foci(ellipse) Q = ellipse_point.get_center() for line, focus in zip(lines, foci): line.put_start_and_end_on(focus, Q) return lines return Mobject.add_updater(lines, update_lines) def get_focus_to_focus_line_update(self, ellipse): return Mobject.add_updater( Line(LEFT, RIGHT, color=WHITE), lambda m: m.put_start_and_end_on(*self.get_foci(ellipse)) ) def get_focus_line_to_focus_line_brace_update(self, line): brace = Brace(Line(LEFT, RIGHT)) brace.add_to_back(brace.copy().set_stroke(BLACK, 5)) return Mobject.add_updater( brace, lambda b: b.match_width(line, stretch=True).next_to( line, DOWN, buff=SMALL_BUFF ) ) def get_eccentricity_label(self): words = OldTexText("Eccentricity = ") decimal = DecimalNumber(0, num_decimal_places=2) group = VGroup(words, decimal) group.arrange(RIGHT) group.to_edge(UP) return group def get_eccentricity_value_update(self, eccentricity_label, ellipse): decimal = eccentricity_label[1] decimal.add_updater(lambda d: d.set_value( self.get_eccentricity(ellipse) )) return decimal def get_outer_dashed_lines(self, ellipse): line = DashedLine(2.5 * UP, 2.5 * DOWN) return VGroup( line.move_to(ellipse, RIGHT), line.copy().move_to(ellipse, LEFT), ) # def get_abc(self, ellipse): a = ellipse.get_width() / 2 b = ellipse.get_height() / 2 c = np.sqrt(a**2 - b**2) return a, b, c def get_foci(self, ellipse): a, b, c = self.get_abc(ellipse) return [ ellipse.get_center() + c * RIGHT, ellipse.get_center() + c * LEFT, ] def get_thumbtack(self): angle = 10 * DEGREES result = SVGMobject(file_name="push_pin") result.set_height(0.5) result.set_fill(GREY_B) result.rotate(angle) return result class EccentricityForSlicedConed(Scene): def construct(self): equation = OldTex( "\\text{Eccentricity} = ", "{\\sin(", "\\text{angle of plane}", ")", "\\over", "\\sin(", "\\text{angle of cone slant}", ")}" ) equation.set_color_by_tex("plane", YELLOW) equation.set_color_by_tex("cone", BLUE) equation.to_edge(LEFT) self.play(FadeInFromDown(equation)) class AskWhyAreTheyTheSame(TeacherStudentsScene): def construct(self): morty = self.teacher self.student_says( "Why on earth \\\\ are these the same?", index=2, target_mode="sassy", bubble_config={"direction": LEFT} ) bubble = self.students[2].bubble self.play( morty.change, "awe", self.change_students("confused", "confused", "sassy") ) self.look_at(self.screen) self.wait(3) self.play(morty.change, "thinking", self.screen) self.play_student_changes("maybe", "erm", "confused") self.look_at(self.screen) self.wait(3) baby_morty = BabyPiCreature() baby_morty.match_style(morty) baby_morty.to_corner(DL) self.play( FadeOut(bubble), FadeOut(bubble.content), LaggedStartMap( FadeOutAndShift, self.students, lambda m: (m, 3 * DOWN), ), ReplacementTransform( morty, baby_morty, path_arc=30 * DEGREES, run_time=2, ) ) self.pi_creatures = VGroup(baby_morty) bubble = ThoughtBubble(height=6, width=7) bubble.set_fill(GREY_D, 0.5) bubble.pin_to(baby_morty) egg = Circle(radius=0.4) egg.stretch(0.75, 1) egg.move_to(RIGHT) egg.apply_function( lambda p: np.array([ p[0], p[0] * p[1], p[2] ]) ) egg.flip() egg.set_width(3) egg.set_stroke(RED, 5) egg.move_to(bubble.get_bubble_center()) self.play(baby_morty.change, "confused", 2 * DOWN) self.wait(2) self.play( baby_morty.change, "thinking", LaggedStartMap(DrawBorderThenFill, bubble) ) self.play(ShowCreation(egg)) self.wait(3) bubble_group = VGroup(bubble, egg) self.play( ApplyMethod( bubble_group.shift, FRAME_WIDTH * LEFT, rate_func=running_start, ), baby_morty.change, "awe" ) self.play(Blink(baby_morty)) self.wait() class TriangleOfEquivalences(Scene): def construct(self): title = Title("How do you prove this\\textinterrobang.") self.add(title) rects = VGroup(*[ScreenRectangle() for x in range(3)]) rects.set_height(2) rects[:2].arrange(RIGHT, buff=2) rects[2].next_to(rects[:2], DOWN, buff=1.5) rects.next_to(title, DOWN) arrows = VGroup(*[ OldTex("\\Leftrightarrow") for x in range(3) ]) arrows.scale(2) arrows[0].move_to(rects[:2]) arrows[1].rotate(60 * DEGREES) arrows[1].move_to(rects[1:]) arrows[2].rotate(-60 * DEGREES) arrows[2].move_to(rects[::2]) arrows[1:].shift(0.5 * DOWN) self.play(LaggedStartMap( DrawBorderThenFill, arrows, lag_ratio=0.7, run_time=3, )) self.wait() self.play(FadeOut(arrows[1:])) self.wait() class SliceCone(ExternallyAnimatedScene): pass class TiltPlane(ExternallyAnimatedScene): pass class IntroduceConeEllipseFocalSum(ExternallyAnimatedScene): pass class ShowMeasurementBook(TeacherStudentsScene): CONFIG = {"camera_config": {"background_opacity": 1}} def construct(self): measurement = ImageMobject("MeasurementCover") measurement.set_height(3.5) measurement.move_to(self.hold_up_spot, DOWN) words = OldTexText("Highly recommended") arrow = Vector(RIGHT, color=WHITE) arrow.next_to(measurement, LEFT) words.next_to(arrow, LEFT) self.play( self.teacher.change, "raise_right_hand", FadeInFromDown(measurement) ) self.play_all_student_changes("hooray") self.wait() self.play( GrowArrow(arrow), FadeIn(words, RIGHT), self.change_students( "thinking", "happy", "pondering", look_at=arrow ) ) self.wait(3) class IntroduceSpheres(ExternallyAnimatedScene): pass class TangencyAnimation(Scene): def construct(self): rings = VGroup(*[ Circle(color=YELLOW, stroke_width=3, radius=0.5) for x in range(5) ]) for ring in rings: ring.save_state() ring.scale(0) ring.saved_state.set_stroke(width=0) self.play(LaggedStartMap( Restore, rings, run_time=2, lag_ratio=0.7 )) class TwoSpheresRotating(ExternallyAnimatedScene): pass class TiltSlopeWithOnlySpheres(ExternallyAnimatedScene): pass class TiltSlopeWithOnlySpheresSideView(ExternallyAnimatedScene): pass class AskAboutWhyYouWouldAddSpheres(PiCreatureScene): def construct(self): randy = self.pi_creature randy.flip() randy.set_height(2) randy.set_color(BLUE_C) randy.to_edge(RIGHT) randy.shift(2 * UP) randy.look(UP) graph_spot = VectorizedPoint() why = OldTexText("...why?") why.next_to(randy, UP) bubble = ThoughtBubble(height=2, width=2) bubble.pin_to(randy) self.play(FadeInFromDown(randy)) self.play( Animation(graph_spot), randy.change, "maybe", Write(why), ) self.wait(3) self.play(randy.change, "pondering") self.play( why.to_corner, DR, why.set_fill, GREY_B, 0.5, ) self.wait() self.play( ShowCreation(bubble), randy.change, "thinking" ) self.wait() self.look_at(graph_spot) self.wait(2) class ShowTangencyPoints(ExternallyAnimatedScene): pass class ShowFocalLinesAsTangent(ExternallyAnimatedScene): pass class UseDefiningFeatures(Scene): def construct(self): title = OldTexText("Problem-solving tip:") title.scale(1.5) title.to_edge(UP) tip = OldTexText( """ - Make sure you're using all the \\\\ \\phantom{-} defining features of the objects \\\\ \\phantom{-} involved. """, alignment="" ) tip.next_to(title, DOWN, MED_LARGE_BUFF) tip.shift(MED_SMALL_BUFF * RIGHT) tip.set_color(YELLOW) self.add(title) self.play(Write(tip, run_time=4)) self.wait() class RemindAboutTangencyToCone(ExternallyAnimatedScene): pass class ShowCircleToCircleLine(ExternallyAnimatedScene): pass class ShowSegmentSplit(Scene): CONFIG = { "include_image": True, } def construct(self): if self.include_image: image = ImageMobject("ShowCircleToCircleLine") image.set_height(FRAME_HEIGHT) self.add(image) brace1 = Brace(Line(ORIGIN, 1.05 * UP), LEFT) brace2 = Brace(Line(1.7 * DOWN, ORIGIN), LEFT) braces = VGroup(brace1, brace2) braces.rotate(-14 * DEGREES) braces.move_to(0.85 * UP + 1.7 * LEFT) words = VGroup( OldTexText("Top segment"), OldTexText("Bottom segment") ) for word, brace in zip(words, braces): word.next_to( brace.get_center(), LEFT, buff=0.35 ) words[0].set_color(PINK) words[1].set_color(GOLD) for mob in it.chain(braces, words): mob.add_to_back(mob.copy().set_stroke(BLACK, 5)) for brace in braces: brace.save_state() brace.set_stroke(width=0) brace.scale(0) self.play( LaggedStartMap( Restore, braces, lag_ratio=0.7 ), ) for word in words: self.play(Write(word, run_time=1)) self.wait() class ShowSegmentSplitWithoutImage(ShowSegmentSplit): CONFIG = { "include_image": False, } class ShowCircleToCircleLineAtMultiplePoints(ExternallyAnimatedScene): pass class ConjectureLineEquivalence(ExternallyAnimatedScene): pass class WriteConjecture(Scene): CONFIG = { "image_name": "ConjectureLineEquivalenceBigSphere", "q_coords": 1.28 * UP + 0.15 * LEFT, "circle_point_coords": 0.84 * RIGHT + 0.05 * DOWN, "tangent_point_coords": 0.85 * UP + 1.75 * LEFT, "plane_line_color": GOLD, "text_scale_factor": 0.75, "shift_plane_word_down": False, "include_image": False, } def construct(self): if self.include_image: image = ImageMobject(self.image_name) image.set_height(FRAME_HEIGHT) self.add(image) title = OldTexText("Conjecture:") title.to_corner(UR) cone_line = Line(self.q_coords, self.circle_point_coords) plane_line = Line(self.q_coords, self.tangent_point_coords) plane_line.set_color(self.plane_line_color) lines = VGroup(cone_line, plane_line) cone_line_words = OldTexText("Cone line") plane_line_words = OldTexText("Plane line") plane_line_words.set_color(self.plane_line_color) words = VGroup(cone_line_words, plane_line_words) for word in words: word.add_to_back(word.copy().set_stroke(BLACK, 5)) word.in_equation = word.copy() equation = VGroup( OldTex("||"), words[0].in_equation, OldTex("||"), OldTex("="), OldTex("||"), words[1].in_equation, OldTex("||"), ) equation.arrange(RIGHT, buff=SMALL_BUFF) equation.scale(0.75) equation.next_to(title, DOWN, MED_LARGE_BUFF) equation.shift_onto_screen() title.next_to(equation, UP) for word, line in zip(words, lines): word.scale(self.text_scale_factor) word.next_to(ORIGIN, UP, SMALL_BUFF) if self.shift_plane_word_down and (word is plane_line_words): word.next_to(ORIGIN, DOWN, SMALL_BUFF) angle = line.get_angle() if abs(angle) > 90 * DEGREES: angle += PI word.rotate(angle, about_point=ORIGIN) word.shift(line.get_center()) self.play(LaggedStartMap( FadeInFromDown, VGroup(title, equation), lag_ratio=0.7 )) self.wait() for word, line in zip(words, lines): self.play(ShowCreation(line)) self.play(WiggleOutThenIn(line)) self.play(ReplacementTransform( word.in_equation.copy(), word )) self.wait() class WriteConjectureV2(WriteConjecture): CONFIG = { "image_name": "ConjectureLineEquivalenceSmallSphere", "q_coords": 2.2 * LEFT + 1.3 * UP, "circle_point_coords": 1.4 * LEFT + 2.25 * UP, "tangent_point_coords": 0.95 * LEFT + 1.51 * UP, "plane_line_color": PINK, "text_scale_factor": 0.5, "shift_plane_word_down": True, "include_image": False, } class ShowQ(Scene): def construct(self): mob = OldTex("Q") mob.scale(2) mob.add_to_back(mob.copy().set_stroke(BLACK, 5)) self.play(FadeInFromDown(mob)) self.wait() class ShowBigSphereTangentLines(ExternallyAnimatedScene): pass class LinesTangentToSphere(ExternallyAnimatedScene): pass class QuickGeometryProof(Scene): def construct(self): radius = 2 circle = Circle(color=BLUE, radius=radius) circle.shift(0.5 * DOWN) angle = 60 * DEGREES O = circle.get_center() p1 = circle.point_from_proportion(angle / TAU) p2 = circle.point_from_proportion(1 - angle / TAU) Q = O + (radius / np.cos(angle)) * RIGHT O_p1 = Line(O, p1) O_p2 = Line(O, p2) p1_Q = Line(p1, Q, color=MAROON_B) p2_Q = Line(p2, Q, color=MAROON_B) O_Q = DashedLine(O, Q) elbow = VGroup(Line(RIGHT, UR), Line(UR, UP)) elbow.set_stroke(WHITE, 1) elbow.scale(0.2, about_point=ORIGIN) ticks = VGroup(Line(DOWN, UP), Line(DOWN, UP)) ticks.scale(0.1) ticks.arrange(RIGHT, buff=SMALL_BUFF) equation = OldTex( "\\Delta OP_1Q \\cong \\Delta OP_2Q", tex_to_color_map={ "O": BLUE, "P_1": MAROON_B, "P_2": MAROON_B, "Q": YELLOW, } ) equation.to_edge(UP) self.add(*equation) self.add(circle) self.add( OldTex("O").next_to(O, LEFT), OldTex("P_1").next_to(p1, UP).set_color(MAROON_B), OldTex("P_2").next_to(p2, DOWN).set_color(MAROON_B), OldTex("Q").next_to(Q, RIGHT).set_color(YELLOW), ) self.add(O_p1, O_p2, p1_Q, p2_Q, O_Q) self.add( Dot(O, color=BLUE), Dot(p1, color=MAROON_B), Dot(p2, color=MAROON_B), Dot(Q, color=YELLOW) ) self.add( elbow.copy().rotate(angle + PI, about_point=ORIGIN).shift(p1), elbow.copy().rotate(-angle + PI / 2, about_point=ORIGIN).shift(p2), ) self.add( ticks.copy().rotate(angle).move_to(O_p1), ticks.copy().rotate(-angle).move_to(O_p2), ) everything = VGroup(*self.mobjects) self.play(LaggedStartMap( GrowFromCenter, everything, lag_ratio=0.25, run_time=4 )) class ShowFocalSumEqualsCircleDistance(ExternallyAnimatedScene): pass class FinalMovingEllipsePoint(ExternallyAnimatedScene): pass class TiltPlaneWithSpheres(ExternallyAnimatedScene): pass class NameDandelin(Scene): CONFIG = {"camera_config": {"background_opacity": 1}} def construct(self): title = OldTexText( "Proof by\\\\", "Germinal Pierre Dandelin (1822)" ) title.to_edge(UP) portrait = ImageMobject("GerminalDandelin") portrait.set_height(5) portrait.next_to(title, DOWN) google_result = ImageMobject("GoogleDandelin") google_result.set_height(4) google_result.center() google_result.to_corner(DR) cmon_google = OldTexText("C'mon Google...") cmon_google.set_color(RED) cmon_google.next_to(google_result, RIGHT) cmon_google.next_to(google_result, UP, aligned_edge=RIGHT) dandelion = ImageMobject("DandelionSphere", height=1.5) dandelion.to_edge(LEFT, buff=LARGE_BUFF) dandelion.shift(UP) big_dandelion = dandelion.copy().scale(2) big_dandelion.next_to(dandelion, DOWN, buff=0) dandelions = Group(dandelion, big_dandelion) self.add(title[0]) self.play(FadeInFromDown(portrait)) self.play(Write(title[1])) self.wait() self.play(FadeIn(google_result, LEFT)) self.play(Write(cmon_google, run_time=1)) self.wait() self.play(LaggedStartMap( FadeInFromDown, dandelions, lag_ratio=0.7, run_time=1 )) self.wait() class DandelinSpheresInCylinder(ExternallyAnimatedScene): pass class ProjectCircleOntoTiltedPlane(ExternallyAnimatedScene): pass class CylinderDandelinSpheresChangingSlope(ExternallyAnimatedScene): pass class DetailsLeftAsHomework(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs": { "color": GREY_BROWN, "flip_at_start": False, }, "default_pi_creature_start_corner": DL, } def construct(self): # morty = self.pi_creature self.pi_creature_says( "Details left \\\\ as homework", target_mode="hooray" ) self.wait(3) class AskWhyYouWouldChooseThisProof(PiCreatureScene): def construct(self): randy, other = self.pi_creatures screen = ScreenRectangle(height=4).to_edge(UP) for pi, vect, word in (randy, UP, "You"), (other, LEFT, "Non-math \\\\ enthusiast"): arrow = Vector(-vect, color=WHITE) arrow.next_to(pi, vect) label = OldTexText(word) label.next_to(arrow, vect) pi.arrow = arrow pi.label = label for pi, mode in (randy, "hooray"), (other, "tired"): self.play( GrowArrow(pi.arrow), FadeIn(pi.label, RIGHT), pi.change, mode, ) self.play( randy.change, "raise_right_hand", screen, other.look_at, screen, ) self.wait() self.play(other.change, "thinking", screen) self.wait(5) def create_pi_creatures(self): randy = Randolph(color=BLUE_C) other = PiCreature(color=RED_D) other.flip() group = VGroup(randy, other) group.arrange(RIGHT, buff=5) group.to_edge(DOWN) return group class CreativeConstruction(PiCreatureScene): def construct(self): randy = self.pi_creature self.remove(randy) dandelin = ImageMobject("GerminalDandelin") dandelin.set_height(4) dandelin.move_to(FRAME_WIDTH * RIGHT / 4) lightbulb = Lightbulb() lightbulb.next_to(dandelin, UP) kant = ImageMobject("Kant") kant.set_height(3) bubble = ThoughtBubble(height=3, width=4) bubble.pin_to(kant) kant_words = OldTexText( "How is synthetic a priori\\\\" + "reasoning possible?" ) kant_words.scale(0.75) bubble.position_mobject_inside(kant_words) kant_group = VGroup(bubble, kant_words, kant) kant_group.to_corner(UR) self.add(dandelin) self.add(lightbulb) self.play( Write(lightbulb, run_time=1), self.get_light_shine(lightbulb) ) self.wait() self.play( lightbulb.next_to, randy, RIGHT, {"buff": LARGE_BUFF, "aligned_edge": UP}, randy.change, "pondering", VFadeIn(randy), FadeOut(dandelin, DOWN), ) self.play( self.get_light_shine(lightbulb), Blink(randy), ) self.wait() self.play( FadeInFromDown(kant), Write(bubble), Write(kant_words), ) lightbulb.generate_target() q_marks = VGroup() for submob in lightbulb.target.family_members_with_points(): if True or get_norm(submob.get_center() - lightbulb.get_center()) > 0.25: q_mark = OldTex("?") q_mark.set_height(0.25) q_mark.move_to(submob) Transform(submob, q_mark).update(1) q_marks.add(submob) q_marks.space_out_submobjects(2) self.wait() self.play(randy.change, 'confused', lightbulb) self.play(MoveToTarget( lightbulb, run_time=3, rate_func=there_and_back, lag_ratio=0.5 )) self.play(Blink(randy)) self.wait() def get_rings(self, center, max_radius, delta_r): radii = np.arange(0, max_radius, delta_r) rings = VGroup(*[ Annulus( inner_radius=r1, outer_radius=r2, fill_opacity=0.75 * (1 - fdiv(r1, max_radius)), fill_color=YELLOW ) for r1, r2 in zip(radii, radii[1:]) ]) rings.move_to(center) return rings def get_light_shine(self, lightbulb, max_radius=15.0, delta_r=0.025): rings = self.get_rings( lightbulb.get_center(), max_radius=15.0, delta_r=0.025, ) return LaggedStartMap( FadeIn, rings, rate_func=there_and_back, run_time=2, lag_ratio=0.5 ) class LockhartQuote(Scene): CONFIG = { "camera_config": {"background_opacity": 1} } def construct(self): mb_string = "Madame\\,\\,Bovary" ml_string = "Mona\\,\\,Lisa." strings = (mb_string, ml_string) quote_text = """ \\large How do people come up with such ingenious arguments? It's the same way people come up with %s or %s I have no idea how it happens. I only know that when it happens to me, I feel very fortunate. """ % strings quote_parts = [s for s in quote_text.split(" ") if s] quote = OldTexText( *quote_parts, tex_to_color_map={ mb_string: BLUE, ml_string: YELLOW, }, alignment="" ) quote.set_width(FRAME_WIDTH - 2) quote.to_edge(UP) measurement = ImageMobject("MeasurementCover") madame_bovary = ImageMobject("MadameBovary") mona_lisa = ImageMobject("MonaLisa") pictures = Group(measurement, madame_bovary, mona_lisa) for picture in pictures: picture.set_height(4) pictures.arrange(RIGHT, buff=LARGE_BUFF) pictures.to_edge(DOWN) measurement.save_state() measurement.set_width(FRAME_WIDTH) measurement.center() measurement.fade(1) self.play(Restore(measurement)) self.wait() for word in quote: anims = [ShowWord(word)] for text, picture in zip(strings, pictures[1:]): if word is quote.get_part_by_tex(text): anims.append(FadeInFromDown( picture, run_time=1 )) self.play(*anims) self.wait(0.005 * len(word)**1.5) self.wait(2) self.play( LaggedStartMap( FadeOutAndShiftDown, quote, lag_ratio=0.2, run_time=5, ), LaggedStartMap( FadeOutAndShiftDown, pictures, run_time=3, ), ) class ImmersedInGeometryProblems(PiCreatureScene): def construct(self): randy = self.pi_creature randy.center().to_edge(DOWN) for vect in compass_directions(start_vect=UL): self.play(randy.change, "pondering", 4 * vect) self.wait(2) class ShowApollonianCircles(Scene): def construct(self): radii = [1.0, 2.0, 3.0] curvatures = [1.0 / r for r in radii] k4 = sum(curvatures) - 2 * np.sqrt( sum([ k1 * k2 for k1, k2 in it.combinations(curvatures, 2) ]) ) radii.append(1.0 / k4) centers = [ ORIGIN, 3 * RIGHT, 4 * UP, 4 * UP + 3 * RIGHT, ] circles = VGroup(*[ Circle(radius=r).shift(c) for r, c in zip(radii, centers) ]) circles.set_height(FRAME_HEIGHT - 3) circles.center().to_edge(DOWN) # circles.set_fill(opacity=1) circles.submobjects.reverse() circles.set_stroke(width=5) circles.set_color_by_gradient(BLUE, YELLOW) equation = OldTex(""" \\left( {1 \\over r_1} + {1 \\over r_2} + {1 \\over r_3} + {1 \\over r_4} \\right)^2 = 2\\left( {1 \\over r_1^2} + {1 \\over r_2^2} + {1 \\over r_3^2} + {1 \\over r_4^2} \\right) """) # equation.scale(1.5) equation.next_to(circles, UP) self.add(equation) self.play(LaggedStartMap( DrawBorderThenFill, circles )) self.wait() class EllipseLengthsLinedUp(EccentricityInThumbtackCase): def construct(self): ellipse = self.get_ellipse(eccentricity=0.6) ellipse.scale(2) foci = self.get_foci(ellipse) point = VectorizedPoint() point_movement = cycle_animation( MoveAlongPath( point, ellipse, run_time=5, rate_func=linear, ) ) arrow = Vector(RIGHT, color=WHITE) arrow.to_edge(LEFT) q_mark = OldTex("?") q_mark.next_to(arrow, UP) lines = VGroup(*[Line(UP, DOWN) for x in range(2)]) lines.set_color_by_gradient(PINK, GOLD) lines.set_stroke(width=5) h_line = Line(LEFT, RIGHT, color=WHITE) h_line.set_width(0.25) def update_lines(lines): for line, focus in zip(lines, foci): d = get_norm(point.get_center() - focus) line.put_start_and_end_on( ORIGIN, d * UP ) lines.arrange(DOWN, buff=0) lines.next_to(arrow, RIGHT) h_line.move_to(lines[0].get_bottom()) lines_animation = Mobject.add_updater( lines, update_lines ) self.add(point_movement) self.add(arrow) self.add(q_mark) self.add(h_line) self.add(lines_animation) self.wait(20) class ReactionToGlimpseOfGenius(TeacherStudentsScene, CreativeConstruction): def construct(self): morty = self.teacher lightbulb = Lightbulb() lightbulb.set_stroke(width=4) lightbulb.scale(1.5) lightbulb.move_to(self.hold_up_spot, DOWN) rings = self.get_rings( lightbulb.get_center(), max_radius=15, delta_r=0.1, ) arrow = Vector(RIGHT, color=WHITE) arrow.next_to(lightbulb, LEFT) clock = Clock() clock.next_to(arrow, LEFT) pi_lights = VGroup() for pi in self.students: light = Lightbulb() light.scale(0.75) light.next_to(pi, UP) pi.light = light pi_lights.add(light) q_marks = VGroup() for submob in lightbulb: q_mark = OldTex("?") q_mark.move_to(submob) q_marks.add(q_mark) q_marks.space_out_submobjects(2) self.student_says( "I think Lockhart was \\\\" "speaking more generally.", target_mode="sassy", added_anims=[morty.change, "guilty"] ) self.wait(2) self.play( morty.change, "raise_right_hand", FadeInFromDown(lightbulb), RemovePiCreatureBubble(self.students[1]), self.change_students(*3 * ["confused"]), run_time=1 ) self.play(Transform( lightbulb, q_marks, run_time=3, rate_func=there_and_back_with_pause, lag_ratio=0.5 )) self.play( ClockPassesTime(clock, hours_passed=4, run_tim=4), VFadeIn(clock), GrowArrow(arrow), self.change_students( *3 * ["pondering"], look_at=clock ) ) self.play( ClockPassesTime(clock, run_time=1, hours_passed=1), VFadeOut(clock), FadeOut(arrow), lightbulb.scale, 1.5, lightbulb.move_to, 2 * UP, self.change_students( *3 * ["awe"], look_at=2 * UP ), run_time=1 ) self.play(self.get_light_shine(lightbulb)) self.play( ReplacementTransform( VGroup(lightbulb), pi_lights ), morty.change, "happy", *[ ApplyMethod(pi.change, mode, pi.get_top()) for pi, mode in zip(self.students, [ "hooray", "tease", "surprised" ]) ] ) self.wait(3) class DandelinEndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "Juan Benet", "Matt Russell", "Soekul", "Keith Smith", "Burt Humburg", "CrypticSwarm", "Brian Tiger Chow", "Joseph Kelly", "Roy Larson", "Andrew Sachs", "Devin Scott", "Akash Kumar", "Arthur Zey", "Ali Yahya", "Mayank M. Mehrotra", "Lukas Biewald", "Yana Chernobilsky", "Kaustuv DeBiswas", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Jordan Scales", "Markus Persson", "Fela", "Fred Ehrsam", "Gary Kong", "Randy C. Will", "Britt Selvitelle", "Jonathan Wilson", "Ryan Atallah", "Joseph John Cox", "Luc Ritchie", "Valeriy Skobelev", "Adrian Robinson", "Michael Faust", "Solara570", "George M. Botros", "Peter Ehrnstrom", "Kai-Siang Ang", "Alexis Olson", "Ludwig", "Omar Zrien", "Sindre Reino Trosterud", "Jeff Straathof", "Matt Langford", "Matt Roveto", "Marek Cirkos", "Magister Mugit", "Stevie Metke", "Cooper Jones", "James Hughes", "John V Wertheim", "Chris Giddings", "Song Gao", "Richard Burgmann", "John Griffith", "Chris Connett", "Steven Tomlinson", "Jameel Syed", "Bong Choung", "Ignacio Freiberg", "Zhilong Yang", "Giovanni Filippi", "Eric Younge", "Prasant Jagannath", "James H. Park", "Norton Wang", "Kevin Le", "Oliver Steele", "Yaw Etse", "Dave B", "supershabam", "Delton Ding", "Thomas Tarler", "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", "Robert Teed", "Jason Hise", "Bernd Sing", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], }
# -*- coding: utf-8 -*- from manim_imports_ext import * from _2018.uncertainty import Flash from _2018.WindingNumber import * # Warning, this file uses ContinualChangingDecimal, # which has since been been deprecated. Use a mobject # updater instead class AltTeacherStudentsScene(TeacherStudentsScene): def setup(self): TeacherStudentsScene.setup(self) self.teacher.set_color(YELLOW_E) ############### class IntroSceneWrapper(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs" : { "color" : YELLOW_E, "flip_at_start" : False, "height" : 2, }, "default_pi_creature_start_corner" : DOWN+LEFT, } def construct(self): self.introduce_two_words() self.describe_main_topic() self.describe_meta_topic() def introduce_two_words(self): morty = self.pi_creature rect = ScreenRectangle(height = 5) rect.to_corner(UP+RIGHT) self.add(rect) h_line = Line(LEFT, RIGHT).scale(2) h_line.to_corner(UP+LEFT) h_line.shift(0.5*DOWN) main_topic, meta_topic = topics = VGroup( OldTexText("Main topic"), OldTexText("Meta topic"), ) topics.next_to(morty, UP) topics.shift_onto_screen() self.play( morty.change, "raise_left_hand", FadeInFromDown(main_topic) ) self.wait() self.play( morty.change, "raise_right_hand", main_topic.next_to, meta_topic.get_top(), UP, MED_SMALL_BUFF, FadeInFromDown(meta_topic) ) self.wait() self.play( morty.change, "happy", main_topic.next_to, h_line, UP, meta_topic.set_fill, {"opacity" : 0.2}, ) self.play(ShowCreation(h_line)) self.wait() self.set_variables_as_attrs(h_line, main_topic, meta_topic) def describe_main_topic(self): h_line = self.h_line morty = self.pi_creature main_topic = self.main_topic meta_topic = self.meta_topic solver = OldTexText("2d equation solver") solver.match_width(h_line) solver.next_to(h_line, DOWN) rainbow_solver1 = solver.copy() rainbow_solver2 = solver.copy() colors = ["RED", "ORANGE", "YELLOW", "GREEN", BLUE, "PURPLE", PINK] rainbow_solver1.set_color_by_gradient(*colors) rainbow_solver2.set_color_by_gradient(*reversed(colors)) xy_equation = OldTex(""" \\left[\\begin{array}{c} ye^x \\\\ \\sin(|xy|) \\end{array}\\right] = \\left[\\begin{array}{c} y^2 \\\\ 3y \\end{array}\\right] """) # xy_equation.set_color_by_tex_to_color_map({ # "x" : BLUE, # "y" : YELLOW # }) xy_equation.scale(0.8) xy_equation.next_to(solver, DOWN, MED_LARGE_BUFF) z_equation = OldTex("z", "^5", "+", "z", "+", "1", "=", "0") z_equation.set_color_by_tex("z", GREEN) z_equation.move_to(xy_equation, UP) zeta = OldTex("\\zeta(s) = 0") zeta[2].set_color(GREEN) zeta.next_to(z_equation, DOWN, MED_LARGE_BUFF) self.play(Write(solver)) self.play( LaggedStartMap(FadeIn, xy_equation, run_time = 1), morty.change, "pondering" ) self.wait(2) self.play( FadeOut(xy_equation), FadeIn(z_equation) ) self.wait() self.play(Write(zeta)) self.wait() solver.save_state() for rainbow_solver in rainbow_solver1, rainbow_solver2: self.play(Transform( solver, rainbow_solver, run_time = 2, lag_ratio = 0.5 )) self.play(solver.restore) self.wait() self.play(LaggedStartMap( FadeOut, VGroup(solver, z_equation, zeta) )) self.play( main_topic.move_to, meta_topic, main_topic.set_fill, {"opacity" : 0.2}, meta_topic.move_to, main_topic, meta_topic.set_fill, {"opacity" : 1}, morty.change, "hesitant", path_arc = TAU/8, ) def describe_meta_topic(self): h_line = self.h_line morty = self.pi_creature words = OldTexText("Seek constructs which \\\\ compose nicely") words.scale(0.7) words.next_to(h_line, DOWN) self.play(Write(words)) self.play(morty.change, "happy") self.wait(3) class Introduce1DFunctionCase(Scene): CONFIG = { "search_range_rect_height" : 0.15, "arrow_opacity" : 1, "show_dotted_line_to_f" : True, "arrow_config": { "max_tip_length_to_length_ratio" : 0.5, }, "show_midpoint_value" : True, } def construct(self): self.show_axes_one_at_a_time() self.show_two_graphs() self.transition_to_sqrt_2_case() self.show_example_binary_search() def show_axes_one_at_a_time(self): axes = Axes( x_min = -1, x_max = 3.2, x_axis_config = { "unit_size" : 3, "tick_frequency" : 0.25, "numbers_with_elongated_ticks" : list(range(-1, 4)) }, y_min = -2, y_max = 4.5, ) axes.to_corner(DOWN+LEFT) axes.x_axis.add_numbers(*list(range(-1, 4))) axes.y_axis.label_direction = LEFT axes.y_axis.add_numbers(-1, *list(range(1, 5))) inputs = OldTexText("Inputs") inputs.next_to(axes.x_axis, UP, aligned_edge = RIGHT) outputs = OldTexText("Outputs") outputs.next_to(axes.y_axis, UP, SMALL_BUFF) self.play( ShowCreation(axes.x_axis), Write(inputs) ) self.wait() self.play( ShowCreation(axes.y_axis), FadeOut(axes.x_axis.numbers[1], rate_func = squish_rate_func(smooth, 0, 0.2)), Write(outputs) ) self.wait() self.axes = axes self.inputs_label = inputs self.outputs_label = outputs def show_two_graphs(self): axes = self.axes f_graph = axes.get_graph( lambda x : 2*x*(x - 0.75)*(x - 1.5) + 1, color = BLUE ) g_graph = axes.get_graph( lambda x : 1.8*np.cos(TAU*x/2), color = YELLOW ) label_x_corod = 2 f_label = OldTex("f(x)") f_label.match_color(f_graph) f_label.next_to(axes.input_to_graph_point(label_x_corod, f_graph), LEFT) g_label = OldTex("g(x)") g_label.match_color(g_graph) g_label.next_to( axes.input_to_graph_point(label_x_corod, g_graph), UP, SMALL_BUFF ) solution = 0.24 cross_point = axes.input_to_graph_point(solution, f_graph) l_v_line, r_v_line, v_line = [ DashedLine( axes.coords_to_point(x, 0), axes.coords_to_point(x, f_graph.underlying_function(solution)), ) for x in (axes.x_min, axes.x_max, solution) ] equation = OldTex("f(x)", "=", "g(x)") equation[0].match_color(f_label) equation[2].match_color(g_label) equation.next_to(cross_point, UP, buff = 1.5, aligned_edge = LEFT) equation_arrow = Arrow( equation.get_bottom(), cross_point, buff = SMALL_BUFF, color = WHITE ) equation.target = OldTex("x^2", "=", "2") equation.target.match_style(equation) equation.target.to_edge(UP) for graph, label in (f_graph, f_label), (g_graph, g_label): self.play( ShowCreation(graph), Write(label, rate_func = squish_rate_func(smooth, 0.5, 1)), run_time = 2 ) self.wait() self.play( ReplacementTransform(r_v_line.copy().fade(1), v_line), ReplacementTransform(l_v_line.copy().fade(1), v_line), run_time = 2 ) self.play( ReplacementTransform(f_label.copy(), equation[0]), ReplacementTransform(g_label.copy(), equation[2]), Write(equation[1]), GrowArrow(equation_arrow), ) for x in range(4): self.play( FadeOut(v_line.copy()), ShowCreation(v_line, rate_func = squish_rate_func(smooth, 0.5, 1)), run_time = 1.5 ) self.wait() self.play( MoveToTarget(equation, replace_mobject_with_target_in_scene = True), *list(map(FadeOut, [equation_arrow, v_line])) ) self.set_variables_as_attrs( f_graph, f_label, g_graph, g_label, equation = equation.target ) def transition_to_sqrt_2_case(self): f_graph = self.f_graph f_label = VGroup(self.f_label) g_graph = self.g_graph g_label = VGroup(self.g_label) axes = self.axes for label in f_label, g_label: for x in range(2): label.add(VectorizedPoint(label.get_center())) for number in axes.y_axis.numbers: number.add_background_rectangle() squared_graph = axes.get_graph(lambda x : x**2) squared_graph.match_style(f_graph) two_graph = axes.get_graph(lambda x : 2) two_graph.match_style(g_graph) squared_label = OldTex("f(x)", "=", "x^2") squared_label.next_to( axes.input_to_graph_point(2, squared_graph), RIGHT ) squared_label.match_color(squared_graph) two_label = OldTex("g(x)", "=", "2") two_label.next_to( axes.input_to_graph_point(3, two_graph), UP, ) two_label.match_color(two_graph) find_sqrt_2 = self.find_sqrt_2 = OldTexText("(Find $\\sqrt{2}$)") find_sqrt_2.next_to(self.equation, DOWN) self.play( ReplacementTransform(f_graph, squared_graph), ReplacementTransform(f_label, squared_label), ) self.play( ReplacementTransform(g_graph, two_graph), ReplacementTransform(g_label, two_label), Animation(axes.y_axis.numbers) ) self.wait() self.play(Write(find_sqrt_2)) self.wait() self.set_variables_as_attrs( squared_graph, two_graph, squared_label, two_label, ) def show_example_binary_search(self): self.binary_search( self.squared_graph, self.two_graph, x0 = 1, x1 = 2, n_iterations = 8 ) ## def binary_search( self, f_graph, g_graph, x0, x1, n_iterations, n_iterations_with_sign_mention = 0, zoom = False, ): axes = self.axes rect = self.rect = Rectangle() rect.set_stroke(width = 0) rect.set_fill(YELLOW, 0.5) rect.replace(Line( axes.coords_to_point(x0, 0), axes.coords_to_point(x1, 0), ), dim_to_match = 0) rect.stretch_to_fit_height(self.search_range_rect_height) #Show first left and right mention_signs = n_iterations_with_sign_mention > 0 kwargs = {"mention_signs" : mention_signs} leftovers0 = self.compare_graphs_at_x(f_graph, g_graph, x0, **kwargs) self.wait() leftovers1 = self.compare_graphs_at_x(f_graph, g_graph, x1, **kwargs) self.wait() self.play(GrowFromCenter(rect)) self.wait() all_leftovers = VGroup(leftovers0, leftovers1) end_points = [x0, x1] if mention_signs: sign_word0 = leftovers0.sign_word sign_word1 = leftovers1.sign_word midpoint_line = Line(MED_SMALL_BUFF*UP, ORIGIN, color = YELLOW) midpoint_line_update = UpdateFromFunc( midpoint_line, lambda l : l.move_to(rect) ) decimal = DecimalNumber( 0, num_decimal_places = 3, show_ellipsis = True, ) decimal.scale(0.7) decimal_update = ChangingDecimal( decimal, lambda a : axes.x_axis.point_to_number(rect.get_center()), position_update_func = lambda m : m.next_to( midpoint_line, DOWN, SMALL_BUFF, submobject_to_align = decimal[:-1], ), ) if not self.show_midpoint_value: decimal.set_fill(opacity = 0) midpoint_line.set_stroke(width = 0) #Restrict to by a half each time kwargs = { "mention_signs" : False, "show_decimal" : zoom, } for x in range(n_iterations - 1): x_mid = np.mean(end_points) leftovers_mid = self.compare_graphs_at_x(f_graph, g_graph, x_mid, **kwargs) if leftovers_mid.too_high == all_leftovers[0].too_high: index_to_fade = 0 else: index_to_fade = 1 edge = [RIGHT, LEFT][index_to_fade] to_fade = all_leftovers[index_to_fade] all_leftovers.submobjects[index_to_fade] = leftovers_mid end_points[index_to_fade] = x_mid added_anims = [] if mention_signs: word = [leftovers0, leftovers1][index_to_fade].sign_word if x < n_iterations_with_sign_mention: added_anims = [word.next_to, leftovers_mid[0].get_end(), -edge] elif word in self.camera.extract_mobject_family_members(self.mobjects): added_anims = [FadeOut(word)] rect.generate_target() rect.target.stretch(0.5, 0, about_edge = edge) rect.target.stretch_to_fit_height(self.search_range_rect_height) self.play( MoveToTarget(rect), midpoint_line_update, decimal_update, Animation(all_leftovers), FadeOut(to_fade), *added_anims ) if zoom: factor = 2.0/rect.get_width() everything = VGroup(*self.mobjects) decimal_index = everything.submobjects.index(decimal) midpoint_line_index = everything.submobjects.index(midpoint_line) everything.generate_target() everything.target.scale(factor, about_point = rect.get_center()) everything.target[decimal_index].scale(1./factor, about_edge = UP) everything.target[midpoint_line_index].scale(1./factor) if factor > 1: self.play( everything.scale, factor, {"about_point" : rect.get_center()} ) else: self.wait() def compare_graphs_at_x( self, f_graph, g_graph, x, mention_signs = False, show_decimal = False, ): axes = self.axes f_point = axes.input_to_graph_point(x, f_graph) g_point = axes.input_to_graph_point(x, g_graph) arrow = Arrow( g_point, f_point, buff = 0, **self.arrow_config ) too_high = f_point[1] > g_point[1] if too_high: arrow.set_fill(GREEN, opacity = self.arrow_opacity) else: arrow.set_fill(RED, opacity = self.arrow_opacity) leftovers = VGroup(arrow) leftovers.too_high = too_high if self.show_dotted_line_to_f: v_line = DashedLine(axes.coords_to_point(x, 0), f_point) self.play(ShowCreation(v_line)) leftovers.add(v_line) added_anims = [] if show_decimal: decimal = DecimalNumber( axes.x_axis.point_to_number(arrow.get_start()), num_decimal_places = 3, # show_ellipsis = True, ) height = self.rect.get_height() decimal.set_height(height) next_to_kwargs = { "buff" : height, } if too_high: decimal.next_to(arrow, DOWN, **next_to_kwargs) if hasattr(self, "last_up_arrow_decimal"): added_anims += [FadeOut(self.last_up_arrow_decimal)] self.last_up_arrow_decimal = decimal else: decimal.next_to(arrow, UP, **next_to_kwargs) if hasattr(self, "last_down_arrow_decimal"): added_anims += [FadeOut(self.last_down_arrow_decimal)] self.last_down_arrow_decimal = decimal line = Line(decimal, arrow, buff = 0) # line.match_color(arrow) line.set_stroke(WHITE, 1) decimal.add(line) added_anims += [FadeIn(decimal)] if mention_signs: if too_high: sign_word = OldTexText("Positive") sign_word.set_color(GREEN) sign_word.scale(0.7) sign_word.next_to(arrow.get_end(), RIGHT) else: sign_word = OldTexText("Negative") sign_word.set_color(RED) sign_word.scale(0.7) sign_word.next_to(arrow.get_end(), LEFT) sign_word.add_background_rectangle() added_anims += [FadeIn(sign_word)] leftovers.sign_word = sign_word self.play(GrowArrow(arrow), *added_anims) return leftovers class PiCreaturesAreIntrigued(AltTeacherStudentsScene): def construct(self): self.teacher_says( "You can extend \\\\ this to 2d", bubble_config = {"width" : 4, "height" : 3} ) self.play_student_changes("pondering", "confused", "erm") self.look_at(self.screen) self.wait(3) class TransitionFromEquationSolverToZeroFinder(Introduce1DFunctionCase): CONFIG = { "show_dotted_line_to_f" : False, "arrow_config" : {}, "show_midpoint_value" : False, } def construct(self): #Just run through these without animating. self.force_skipping() self.show_axes_one_at_a_time() self.show_two_graphs() self.transition_to_sqrt_2_case() self.revert_to_original_skipping_status() ## self.transition_to_difference_graph() self.show_binary_search_with_signs() def transition_to_difference_graph(self): axes = self.axes equation = x_squared, equals, two = self.equation for s in "-", "0": tex_mob = OldTex(s) tex_mob.scale(0.01) tex_mob.fade(1) tex_mob.move_to(equation.get_right()) equation.add(tex_mob) find_sqrt_2 = self.find_sqrt_2 rect = SurroundingRectangle(VGroup(equation, find_sqrt_2)) rect.set_color(WHITE) f_graph = self.squared_graph g_graph = self.two_graph new_graph = axes.get_graph( lambda x : f_graph.underlying_function(x) - g_graph.underlying_function(x), color = GREEN ) zero_graph = axes.get_graph(lambda x : 0) zero_graph.set_stroke(BLACK, 0) f_label = self.squared_label g_label = self.two_label new_label = OldTex("f(x)", "-", "g(x)") new_label[0].match_color(f_label) new_label[2].match_color(g_label) new_label.next_to( axes.input_to_graph_point(2, new_graph), LEFT ) fg_labels = VGroup(f_label, g_label) fg_labels.generate_target() fg_labels.target.arrange(DOWN, aligned_edge = LEFT) fg_labels.target.to_corner(UP+RIGHT) new_equation = OldTex("x^2", "-", "2", "=", "0") new_equation[0].match_style(equation[0]) new_equation[2].match_style(equation[2]) new_equation.move_to(equation, RIGHT) for tex in equation, new_equation: tex.sort_alphabetically() self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.play( ReplacementTransform(equation, new_equation, path_arc = TAU/4), find_sqrt_2.next_to, new_equation, DOWN, ) self.play(MoveToTarget(fg_labels)) self.play( ReplacementTransform(f_graph, new_graph), ReplacementTransform(g_graph, zero_graph), ) self.play( ReplacementTransform(f_label[0].copy(), new_label[0]), ReplacementTransform(g_label[0].copy(), new_label[2]), Write(new_label[1]), ) self.wait() self.set_variables_as_attrs(new_graph, zero_graph) def show_binary_search_with_signs(self): self.play(FadeOut(self.axes.x_axis.numbers[2])) self.binary_search( self.new_graph, self.zero_graph, 1, 2, n_iterations = 9, n_iterations_with_sign_mention = 2, zoom = True, ) class RewriteEquationWithTeacher(AltTeacherStudentsScene): def construct(self): root_two_equations = VGroup( OldTex("x^2", "", "=", "2", ""), OldTex("x^2", "-", "2", "=", "0"), ) for equation in root_two_equations: equation.sort_alphabetically() for part in equation.get_parts_by_tex("text"): part[2:-1].set_color(YELLOW) part[2:-1].scale(0.9) equation.move_to(self.hold_up_spot, DOWN) brace = Brace(root_two_equations[1], UP) f_equals_0 = brace.get_tex("f(x) = 0") self.teacher_holds_up(root_two_equations[0]) self.wait() self.play(Transform( *root_two_equations, run_time = 1.5, path_arc = TAU/2 )) self.play(self.change_students(*["pondering"]*3)) self.play( GrowFromCenter(brace), self.teacher.change, "happy" ) self.play(Write(f_equals_0)) self.play_student_changes(*["happy"]*3) self.wait() # to_remove = VGroup(root_two_equations[0], brace, f_equals_0) two_d_equation = OldTex(""" \\left[\\begin{array}{c} ye^x \\\\ \\sin(xy) \\end{array}\\right] = \\left[\\begin{array}{c} y^2 + x^3 \\\\ 3y - x \\end{array}\\right] """) complex_equation = OldTex("z", "^5 + ", "z", " + 1 = 0") z_def = OldTexText( "(", "$z$", " is complex, ", "$a + bi$", ")", arg_separator = "" ) complex_group = VGroup(complex_equation, z_def) complex_group.arrange(DOWN) for tex in complex_group: tex.set_color_by_tex("z", GREEN) complex_group.move_to(self.hold_up_spot, DOWN) self.play( ApplyMethod( to_remove.next_to, FRAME_X_RADIUS*RIGHT, RIGHT, remover = True, rate_func = running_start, path_arc = -TAU/4, ), self.teacher.change, "hesitant", self.change_students(*["erm"]*3) ) self.teacher_holds_up(two_d_equation) self.play_all_student_changes("horrified") self.wait() self.play( FadeOut(two_d_equation), FadeInFromDown(complex_group), ) self.play_all_student_changes("confused") self.wait(3) class InputOutputScene(Scene): CONFIG = { "plane_width" : 6, "plane_height" : 6, "x_shift" : FRAME_X_RADIUS/2, "y_shift" : MED_LARGE_BUFF, "output_scalar" : 10, "non_renormalized_func" : plane_func_by_wind_spec( (-2, -1, 2), (1, 1, 1), (2, -2, -1), ), } ### def func(self, coord_pair): out_coords = np.array(self.non_renormalized_func(coord_pair)) out_norm = get_norm(out_coords) if out_norm > 1: angle = angle_of_vector(out_coords) factor = 0.5-0.1*np.cos(4*angle) target_norm = factor*np.log(out_norm) out_coords *= target_norm / out_norm else: out_coords = (0, 0) return tuple(out_coords) def point_function(self, point): in_coords = self.input_plane.point_to_coords(point) out_coords = self.func(in_coords) return self.output_plane.coords_to_point(*out_coords) def get_colorings(self): in_cmos = ColorMappedObjectsScene( func = lambda p : self.non_renormalized_func( (p[0]+self.x_shift, p[1]+self.y_shift) ) ) scalar = self.output_scalar out_cmos = ColorMappedObjectsScene( func = lambda p : ( scalar*(p[0]-self.x_shift), scalar*(p[1]+self.y_shift) ) ) input_coloring = Rectangle( height = self.plane_height, width = self.plane_width, stroke_width = 0, fill_color = WHITE, fill_opacity = 1, ) output_coloring = input_coloring.copy() colorings = VGroup(input_coloring, output_coloring) vects = [LEFT, RIGHT] cmos_pair = [in_cmos, out_cmos] for coloring, vect, cmos in zip(colorings, vects, cmos_pair): coloring.move_to(self.x_shift*vect + self.y_shift*DOWN) coloring.color_using_background_image(cmos.background_image_file) return colorings def get_planes(self): input_plane = self.input_plane = NumberPlane( x_radius = self.plane_width / 2.0, y_radius = self.plane_height / 2.0, ) output_plane = self.output_plane = input_plane.deepcopy() planes = VGroup(input_plane, output_plane) vects = [LEFT, RIGHT] label_texts = ["Input", "Output"] label_colors = [GREEN, RED] for plane, vect, text, color in zip(planes, vects, label_texts, label_colors): plane.stretch_to_fit_width(self.plane_width) plane.add_coordinates(x_vals = list(range(-2, 3)), y_vals = list(range(-2, 3))) plane.white_parts = VGroup(plane.axes, plane.coordinate_labels) plane.coordinate_labels.set_background_stroke(width=0) plane.lines_to_fade = VGroup(planes, plane.secondary_lines) plane.move_to(vect*FRAME_X_RADIUS/2 + self.y_shift*DOWN) label = OldTexText(text) label.scale(1.5) label.add_background_rectangle() label.move_to(plane) label.to_edge(UP, buff = MED_SMALL_BUFF) plane.add(label) plane.label = label for submob in plane.get_family(): if isinstance(submob, Tex) and hasattr(submob, "background_rectangle"): submob.remove(submob.background_rectangle) return planes def get_v_line(self): v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) v_line.set_stroke(WHITE, 5) return v_line def get_dots(self, input_plane, output_plane): step = self.dot_density x_min = -3.0 x_max = 3.0 y_min = -3.0 y_max = 3.0 dots = VGroup() for x in np.arange(x_min, x_max + step, step): for y in np.arange(y_max, y_min - step, -step): out_coords = self.func((x, y)) dot = Dot(radius = self.dot_radius) dot.set_stroke(BLACK, 1) dot.move_to(input_plane.coords_to_point(x, y)) dot.original_position = dot.get_center() dot.generate_target() dot.target.move_to(output_plane.coords_to_point(*out_coords)) dot.target_color = rgba_to_color(point_to_rgba( tuple(self.output_scalar*np.array(out_coords)) )) dots.add(dot) return dots class IntroduceInputOutputScene(InputOutputScene): CONFIG = { "dot_radius" : 0.05, "dot_density" : 0.25, } def construct(self): self.setup_planes() self.map_single_point_to_point() def setup_planes(self): self.input_plane, self.output_plane = self.get_planes() self.v_line = self.get_v_line() self.add(self.input_plane, self.output_plane, self.v_line) def map_single_point_to_point(self): input_plane = self.input_plane output_plane = self.output_plane #Dots dots = self.get_dots() in_dot = dots[int(0.55*len(dots))].copy() out_dot = in_dot.target for mob in in_dot, out_dot: mob.scale(1.5) in_dot.set_color(YELLOW) out_dot.set_color(PINK) input_label_arrow = Vector(DOWN+RIGHT) input_label_arrow.next_to(in_dot, UP+LEFT, SMALL_BUFF) input_label = OldTexText("Input point") input_label.next_to(input_label_arrow.get_start(), UP, SMALL_BUFF) for mob in input_label, input_label_arrow: mob.match_color(in_dot) input_label.add_background_rectangle() output_label_arrow = Vector(DOWN+LEFT) output_label_arrow.next_to(out_dot, UP+RIGHT, SMALL_BUFF) output_label = OldTexText("Output point") output_label.next_to(output_label_arrow.get_start(), UP, SMALL_BUFF) for mob in output_label, output_label_arrow: mob.match_color(out_dot) output_label.add_background_rectangle() path_arc = -TAU/4 curved_arrow = Arrow( in_dot, out_dot, buff = SMALL_BUFF, path_arc = path_arc, color = WHITE, ) curved_arrow.pointwise_become_partial(curved_arrow, 0, 0.95) function_label = OldTex("f(", "\\text{2d input}", ")") function_label.next_to(curved_arrow, UP) function_label.add_background_rectangle() self.play(LaggedStartMap(GrowFromCenter, dots)) self.play(LaggedStartMap( MoveToTarget, dots, path_arc = path_arc )) self.wait() self.play(FadeOut(dots)) self.play( GrowFromCenter(in_dot), GrowArrow(input_label_arrow), FadeIn(input_label) ) self.wait() self.play( ShowCreation(curved_arrow), ReplacementTransform( in_dot.copy(), out_dot, path_arc = path_arc ), FadeIn(function_label), ) self.play( GrowArrow(output_label_arrow), FadeIn(output_label) ) self.wait() self.play(*list(map(FadeOut, [ input_label_arrow, input_label, output_label_arrow, output_label, curved_arrow, function_label, ]))) #General movements and wiggles out_dot_continual_update = self.get_output_dot_continual_update(in_dot, out_dot) self.add(out_dot_continual_update) for vect in UP, RIGHT: self.play( in_dot.shift, 0.25*vect, rate_func = lambda t : wiggle(t, 8), run_time = 2 ) for vect in compass_directions(4, UP+RIGHT): self.play(Rotating( in_dot, about_point = in_dot.get_corner(vect), radians = TAU, run_time = 1 )) self.wait() for coords in (-2, 2), (-2, -2), (2, -2), (1.5, 1.5): self.play( in_dot.move_to, input_plane.coords_to_point(*coords), path_arc = -TAU/4, run_time = 2 ) self.wait() ### def get_dots(self): input_plane = self.input_plane dots = VGroup() step = self.dot_density x_max = input_plane.x_radius x_min = -x_max y_max = input_plane.y_radius y_min = -y_max reverse = False for x in np.arange(x_min+step, x_max, step): y_range = list(np.arange(x_min+step, x_max, step)) if reverse: y_range.reverse() reverse = not reverse for y in y_range: dot = Dot(radius = self.dot_radius) dot.move_to(input_plane.coords_to_point(x, y)) dot.generate_target() dot.target.move_to(self.point_function(dot.get_center())) dots.add(dot) return dots def get_output_dot_continual_update(self, input_dot, output_dot): return Mobject.add_updater( output_dot, lambda od : od.move_to(self.point_function(input_dot.get_center())) ) class IntroduceVectorField(IntroduceInputOutputScene): CONFIG = { "dot_density" : 0.5, } def construct(self): self.setup_planes() input_plane, output_plane = self.input_plane, self.output_plane dots = self.get_dots() in_dot = dots[0].copy() in_dot.move_to(input_plane.coords_to_point(1.5, 1.5)) out_dot = in_dot.copy() out_dot_continual_update = self.get_output_dot_continual_update(in_dot, out_dot) for mob in in_dot, out_dot: mob.scale(1.5) in_dot.set_color(YELLOW) out_dot.set_color(PINK) out_vector = Arrow( LEFT, RIGHT, color = out_dot.get_color(), ) out_vector.set_stroke(BLACK, 1) continual_out_vector_update = Mobject.add_updater( out_vector, lambda ov : ov.put_start_and_end_on( output_plane.coords_to_point(0, 0), out_dot.get_center(), ) ) in_vector = out_vector.copy() def update_in_vector(in_vector): Transform(in_vector, out_vector).update(1) in_vector.scale(0.5) in_vector.shift(in_dot.get_center() - in_vector.get_start()) continual_in_vector_update = Mobject.add_updater( in_vector, update_in_vector ) continual_updates = [ out_dot_continual_update, continual_out_vector_update, continual_in_vector_update ] self.add(in_dot, out_dot) self.play(GrowArrow(out_vector, run_time = 2)) self.wait() self.add_foreground_mobjects(in_dot) self.play(ReplacementTransform(out_vector.copy(), in_vector)) self.wait() self.add(*continual_updates) path = Square().rotate(-90*DEGREES) path.replace(Line( input_plane.coords_to_point(-1.5, -1.5), input_plane.coords_to_point(1.5, 1.5), ), stretch = True) in_vectors = VGroup() self.add(in_vectors) for a in np.linspace(0, 1, 25): self.play( in_dot.move_to, path.point_from_proportion(a), run_time = 0.2, rate_func=linear, ) in_vectors.add(in_vector.copy()) # Full vector field newer_in_vectors = VGroup() self.add(newer_in_vectors) for dot in dots: self.play(in_dot.move_to, dot, run_time = 1./15) newer_in_vectors.add(in_vector.copy()) self.remove(*continual_updates) self.remove() self.play(*list(map(FadeOut, [ out_dot, out_vector, in_vectors, in_dot, in_vector ]))) self.wait() target_length = 0.4 for vector in newer_in_vectors: vector.generate_target() if vector.get_length() == 0: continue factor = target_length / vector.get_length() vector.target.scale(factor, about_point = vector.get_start()) self.play(LaggedStartMap(MoveToTarget, newer_in_vectors)) self.wait() class TwoDScreenInOurThreeDWorld(AltTeacherStudentsScene, ThreeDScene): def construct(self): self.ask_about_2d_functions() self.show_3d() def ask_about_2d_functions(self): in_plane = NumberPlane(x_radius = 2.5, y_radius = 2.5) in_plane.add_coordinates() in_plane.set_height(3) out_plane = in_plane.copy() in_text = OldTexText("Input space") out_text = OldTexText("Output space") VGroup(in_text, out_text).scale(0.75) in_text.next_to(in_plane, UP, SMALL_BUFF) out_text.next_to(out_plane, UP, SMALL_BUFF) in_plane.add(in_text) out_plane.add(out_text) arrow = Arrow( LEFT, RIGHT, path_arc = -TAU/4, color = WHITE ) arrow.pointwise_become_partial(arrow, 0.0, 0.97) group = VGroup(in_plane, arrow, out_plane) group.arrange(RIGHT) arrow.shift(UP) group.move_to(self.students) group.to_edge(UP) dots = VGroup() dots_target = VGroup() for x in np.arange(-2.5, 3.0, 0.5): for y in np.arange(-2.5, 3.0, 0.5): dot = Dot(radius = 0.05) dot.move_to(in_plane.coords_to_point(x, y)) dot.generate_target() dot.target.move_to(out_plane.coords_to_point( x + 0.25*np.cos(5*y), y + 0.25*np.sin(3*x) )) dots.add(dot) dots_target.add(dot.target) dots.set_color_by_gradient(YELLOW, RED) dots_target.set_color_by_gradient(YELLOW, RED) self.play( self.teacher.change, "raise_right_hand", Write(in_plane, run_time = 1) ) self.play( ShowCreation(arrow), ReplacementTransform( in_plane.copy(), out_plane, path_arc = -TAU/4, ) ) self.play( LaggedStartMap(GrowFromCenter, dots, run_time = 1), self.change_students(*3*["erm"]), ) self.play(LaggedStartMap(MoveToTarget, dots, path_arc = -TAU/4)) self.wait(3) def show_3d(self): laptop = Laptop().scale(2) laptop.rotate(-TAU/12, DOWN) laptop.rotate(-5*TAU/24, LEFT) laptop.rotate(TAU/8, LEFT) laptop.scale(2.3*FRAME_X_RADIUS/laptop.screen_plate.get_width()) laptop.shift(-laptop.screen_plate.get_center() + 0.1*IN) should_shade_in_3d(laptop) everything = VGroup(laptop, *self.mobjects) everything.generate_target() # for mob in everything.target.get_family(): # if isinstance(mob, PiCreature): # mob.change_mode("confused") everything.target.rotate(TAU/12, LEFT) everything.target.rotate(TAU/16, UP) everything.target.shift(4*UP) self.move_camera( distance = 12, run_time = 4, added_anims = [MoveToTarget(everything, run_time = 4)], ) always_rotate(everything, axis=UP, rate=3 * DEGREES) self.wait(10) class EveryOutputPointHasAColor(ColorMappedObjectsScene): CONFIG = { "func" : lambda p : p, "dot_spacing" : 0.1, "dot_radius" : 0.01, } def construct(self): full_rect = FullScreenRectangle() full_rect.set_fill(WHITE, 1) full_rect.set_stroke(WHITE, 0) full_rect.color_using_background_image(self.background_image_file) title = OldTexText("Output Space") title.scale(1.5) title.to_edge(UP, buff = MED_SMALL_BUFF) title.set_stroke(BLACK, 1) # self.add_foreground_mobjects(title) plane = NumberPlane() plane.fade(0.5) plane.axes.set_stroke(WHITE, 3) # plane.add(BackgroundRectangle(title)) self.add(plane) dots = VGroup() step = self.dot_spacing for x in np.arange(-FRAME_X_RADIUS, FRAME_X_RADIUS+step, step): for y in np.arange(-FRAME_Y_RADIUS, FRAME_Y_RADIUS+step, step): dot = Dot(color = WHITE) dot.color_using_background_image(self.background_image_file) dot.move_to(x*RIGHT + y*UP) dots.add(dot) random.shuffle(dots.submobjects) m = 3 #exponential factor n = 1 dot_groups = VGroup() while n <= len(dots): dot_groups.add(dots[n-1:m*n-1]) n *= m self.play(LaggedStartMap( LaggedStartMap, dot_groups, lambda dg : (GrowFromCenter, dg), run_time = 8, lag_ratio = 0.2, )) class DotsHoppingToColor(InputOutputScene): CONFIG = { "dot_radius" : 0.05, "dot_density" : 0.25, } def construct(self): input_coloring, output_coloring = self.get_colorings() input_plane, output_plane = self.get_planes() v_line = self.get_v_line() dots = self.get_dots(input_plane, output_plane) right_half_block = Rectangle( height = FRAME_HEIGHT, width = FRAME_X_RADIUS - SMALL_BUFF, stroke_width = 0, fill_color = BLACK, fill_opacity = 0.8, ) right_half_block.to_edge(RIGHT, buff = 0) #Introduce parts self.add(input_plane, output_plane, v_line) self.play( FadeIn(output_coloring), Animation(output_plane), output_plane.white_parts.set_color, BLACK, output_plane.lines_to_fade.set_stroke, {"width" : 0}, ) self.wait() self.play(LaggedStartMap(GrowFromCenter, dots, run_time = 3)) self.wait() #Hop over and back self.play(LaggedStartMap( MoveToTarget, dots, path_arc = -TAU/4, run_time = 3, )) self.wait() self.play(LaggedStartMap( ApplyMethod, dots, lambda d : (d.set_fill, d.target_color), )) self.wait() self.play(LaggedStartMap( ApplyMethod, dots, lambda d : (d.move_to, d.original_position), path_arc = TAU/4, run_time = 3, )) self.wait() self.play( FadeIn(input_coloring), Animation(input_plane), input_plane.white_parts.set_color, BLACK, input_plane.lines_to_fade.set_stroke, {"width" : 0}, FadeOut(dots), ) self.wait() #Cover output half right_half_block.save_state() right_half_block.next_to(FRAME_X_RADIUS*RIGHT, RIGHT) self.play(right_half_block.restore) self.wait() # Show yellow points inspector = DashedLine( ORIGIN, TAU*UP, dash_length = TAU/24, fill_opacity = 0, stroke_width = 3, stroke_color = WHITE, ) inspector.add(*inspector.copy().set_color(BLACK).shift((TAU/24)*UP)) inspector.apply_complex_function(np.exp) inspector.scale(0.15) inspector_image = inspector.copy() def update_inspector_image(inspector_image): inspector_image.move_to(self.point_function(inspector.get_center())) inspector_image_update_anim = UpdateFromFunc( inspector_image, update_inspector_image ) pink_points_label = OldTexText("Pink points") pink_points_label.scale(0.7) pink_points_label.set_color(BLACK) self.play( inspector.move_to, input_plane.coords_to_point(-2.75, 2.75), inspector.set_stroke, {"width" : 2}, ) pink_points_label.next_to(inspector, RIGHT) self.play( Rotating( inspector, about_point = inspector.get_center(), rate_func = smooth, run_time = 2, ), Write(pink_points_label) ) self.wait() self.play(right_half_block.next_to, FRAME_X_RADIUS*RIGHT, RIGHT) inspector_image_update_anim.update(0) self.play(ReplacementTransform( inspector.copy(), inspector_image, path_arc = -TAU/4, )) self.play( ApplyMethod( inspector.move_to, input_plane.coords_to_point(-2, 0), path_arc = -TAU/8, run_time = 3, ), inspector_image_update_anim ) self.play( ApplyMethod( inspector.move_to, input_plane.coords_to_point(-2.75, 2.75), path_arc = TAU/8, run_time = 3, ), inspector_image_update_anim ) self.play(FadeOut(pink_points_label)) # Show black zero zeros = tuple(it.starmap(input_plane.coords_to_point, [ (-2., -1), (1, 1), (2, -2), ])) for x in range(2): for zero in zeros: path = ParametricCurve( bezier([ inspector.get_center(), input_plane.coords_to_point(0, 0), zero ]), t_min = 0, t_max = 1 ) self.play( MoveAlongPath(inspector, path, run_time = 2), inspector_image_update_anim, ) self.wait() self.play(FadeOut(VGroup(inspector, inspector_image))) # Show all dots and slowly fade them out for dot in dots: dot.scale(1.5) self.play( FadeOut(input_coloring), input_plane.white_parts.set_color, WHITE, LaggedStartMap(GrowFromCenter, dots) ) self.wait() random.shuffle(dots.submobjects) self.play(LaggedStartMap( FadeOut, dots, lag_ratio = 0.05, run_time = 10, )) # Ask about whether a region contains a zero question = OldTexText("Does this region \\\\ contain a zero?") question.add_background_rectangle(opacity = 1) question.next_to(input_plane.label, DOWN) square = Square() square.match_background_image_file(input_coloring) square.move_to(input_plane) self.play(ShowCreation(square), Write(question)) self.wait() quads = [ (0, 0.5, 6, 6.25), (1, 1, 0.5, 2), (-1, -1, 3, 4.5), (0, 1.25, 5, 1.7), (-2, -1, 1, 1), ] for x, y, width, height in quads: self.play( square.stretch_to_fit_width, width, square.stretch_to_fit_height, height, square.move_to, input_plane.coords_to_point(x, y) ) self.wait() class SoWeFoundTheZeros(AltTeacherStudentsScene): def construct(self): self.student_says( "Aha! So we \\\\ found the solutions!", target_mode = "hooray", index = 2, bubble_config = {"direction" : LEFT}, ) self.wait() self.teacher_says( "Er...only \\\\ kind of", target_mode = "hesitant" ) self.wait(3) class Rearrange2DEquation(AltTeacherStudentsScene): def construct(self): f_tex, g_tex, h_tex = [ "%s(\\text{2d point})"%char for char in ("f", "g", "h") ] zero_tex = "\\vec{\\textbf{0}}" equations = VGroup( OldTex(g_tex, "", "=", h_tex, ""), OldTex(g_tex, "-", h_tex, "=", zero_tex), ) equations.move_to(self.hold_up_spot, DOWN) equations.shift_onto_screen() brace = Brace(equations[1], UP) zero_eq = brace.get_tex("%s = %s"%(f_tex, zero_tex)) for equation in equations: equation.set_color_by_tex(g_tex, BLUE) equation.set_color_by_tex(h_tex, YELLOW) equation.sort_alphabetically() self.teacher_holds_up(equations[0]) self.play_all_student_changes("pondering") self.play(Transform( *equations, run_time = 1.5, path_arc = TAU/2 )) self.play( Succession( GrowFromCenter(brace), Write(zero_eq, run_time = 1) ), self.change_students(*["happy"]*3) ) self.play(*[ ApplyMethod(pi.change, "thinking", self.screen) for pi in self.pi_creatures ]) self.wait(3) class SearchForZerosInInputSpace(ColorMappedObjectsScene): CONFIG = { "func" : example_plane_func, } def construct(self): ColorMappedObjectsScene.construct(self) title = OldTexText("Input space") title.scale(2) title.to_edge(UP) title.set_stroke(BLACK, 1) title.add_background_rectangle() plane = NumberPlane() plane.fade(0.5) plane.axes.set_stroke(WHITE, 3) self.add(plane, title) looking_glass = Circle() looking_glass.set_stroke(WHITE, 3) looking_glass.set_fill(WHITE, 0.6) looking_glass.color_using_background_image(self.background_image_file) question = OldTexText("Which points go to 0?") question.next_to(looking_glass, DOWN) question.add_background_rectangle() mover = VGroup(looking_glass, question) mover.move_to(4*LEFT + UP) self.play(FadeIn(mover)) points = [4*RIGHT+UP, 2*RIGHT+2*DOWN, 2*LEFT+2*DOWN, 3*RIGHT+2.5*DOWN] for point in points: self.play(mover.move_to, point, run_time = 1.5) self.wait() class OneDRegionBoundary(Scene): CONFIG = { "graph_color" : BLUE, "region_rect_height" : 0.1, } def construct(self): x0 = self.x0 = 3 x1 = self.x1 = 6 fx0 = self.fx0 = -2 fx1 = self.fx1 = 2 axes = self.axes = Axes( x_min = -1, x_max = 10, y_min = -3, y_max = 3, ) axes.center() axes.set_stroke(width = 2) input_word = OldTexText("Input") input_word.next_to(axes.x_axis, UP, SMALL_BUFF, RIGHT) output_word = OldTexText("Output") output_word.next_to(axes.y_axis, UP) axes.add(input_word, output_word) self.add(axes) graph = self.get_graph_part(1, 1) alt_graphs = [ self.get_graph_part(*points) for points in [ (-1, -2), (-1, -1, -1), (1, 1, 1), (-0.75, 0, 1.75), (-3, -2, -1), ] ] #Region and boundary line = Line(axes.coords_to_point(x0, 0), axes.coords_to_point(x1, 0)) region = Rectangle( stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.5, height = self.region_rect_height ) region.match_width(line, stretch = True) region.move_to(line) region_words = OldTexText("Input region") region_words.set_width(0.8*region.get_width()) region_words.next_to(region, UP) x0_arrow, x1_arrow = arrows = VGroup(*[ Arrow( axes.coords_to_point(x, 0), axes.coords_to_point(x, fx), color = color, buff = 0 ) for x, fx, color in [(x0, fx0, RED), (x1, fx1, GREEN)] ]) minus = OldTex("-") minus.match_color(x0_arrow) minus.next_to(x0_arrow, UP) plus = OldTex("+") plus.match_color(x1_arrow) plus.next_to(x1_arrow, DOWN) signs = VGroup(plus, minus) self.play( GrowFromCenter(region), FadeIn(region_words) ) self.wait() self.play(*it.chain( list(map(GrowArrow, arrows)), list(map(Write, signs)) )) self.wait() self.play( ShowCreation(graph), FadeOut(region_words), ) self.wait() for alt_graph in alt_graphs + alt_graphs: self.play(Transform(graph, alt_graph, path_arc = 0.1*TAU)) self.wait() ### def get_graph_part(self, *interim_values): result = VMobject() result.set_stroke(self.graph_color, 3) result.set_fill(opacity = 0) values = [self.fx0] + list(interim_values) + [self.fx1] result.set_points_smoothly([ self.axes.coords_to_point(x, fx) for x, fx in zip( np.linspace(self.x0, self.x1, len(values)), values ) ]) return result class DirectionOfA2DFunctionAlongABoundary(InputOutputScene): def construct(self): colorings = self.get_colorings() colorings.set_fill(opacity = 0.25) input_plane, output_plane = planes = self.get_planes() for plane in planes: plane.lines_to_fade.set_stroke(width = 0) v_line = self.get_v_line() rect = Rectangle() rect.set_stroke(WHITE, 5) rect.set_fill(WHITE, 0) line = Line( input_plane.coords_to_point(-0.75, 2.5), input_plane.coords_to_point(2.5, -1.5), ) rect.replace(line, stretch = True) rect.insert_n_curves(50) rect.match_background_image_file(colorings[0]) rect_image = rect.copy() rect_image.match_background_image_file(colorings[1]) def update_rect_image(rect_image): rect_image.set_points(rect.get_points()) rect_image.apply_function(self.point_function) rect_image_update_anim = UpdateFromFunc(rect_image, update_rect_image) def get_input_point(): return rect.get_points()[-1] def get_output_coords(): in_coords = input_plane.point_to_coords(get_input_point()) return self.func(in_coords) def get_angle(): return angle_of_vector(get_output_coords()) def get_color(): return rev_to_color(get_angle()/TAU) #Negative? out_vect = Vector(RIGHT, color = WHITE) out_vect_update_anim = UpdateFromFunc( out_vect, lambda ov : ov.put_start_and_end_on( output_plane.coords_to_point(0, 0), rect_image.get_points()[-1] ).set_color(get_color()) ) dot = Dot() dot.set_stroke(BLACK, 1) dot_update_anim = UpdateFromFunc( dot, lambda d : d.move_to(get_input_point()).set_fill(get_color()) ) in_vect = Vector(RIGHT) def update_in_vect(in_vect): in_vect.put_start_and_end_on(ORIGIN, 0.5*RIGHT) in_vect.rotate(get_angle()) in_vect.set_color(get_color()) in_vect.shift(get_input_point() - in_vect.get_start()) return in_vect in_vect_update_anim = UpdateFromFunc(in_vect, update_in_vect) self.add(colorings, planes, v_line) self.play( GrowArrow(out_vect), GrowArrow(in_vect), Animation(dot), ) self.play( ShowCreation(rect), ShowCreation(rect_image), out_vect_update_anim, in_vect_update_anim, dot_update_anim, rate_func = bezier([0, 0, 1, 1]), run_time = 10, ) class AskAboutHowToGeneralizeSigns(AltTeacherStudentsScene): def construct(self): # 2d plane plane = NumberPlane(x_radius = 2.5, y_radius = 2.5) plane.scale(0.8) plane.to_corner(UP+LEFT) plane.add_coordinates() dot = Dot(color = YELLOW) label = OldTexText("Sign?") label.add_background_rectangle() label.scale(0.5) label.next_to(dot, UP, SMALL_BUFF) dot.add(label) dot.move_to(plane.coords_to_point(1, 1)) dot.save_state() dot.fade(1) dot.center() question = OldTexText( "Wait...what would \\\\ positive and negative \\\\ be in 2d?", ) # question.set_color_by_tex_to_color_map({ # "+" : "green", # "textminus" : "red" # }) self.student_says( question, target_mode = "sassy", index = 2, added_anims = [ self.teacher.change, "plain", ], bubble_config = {"direction" : LEFT}, run_time = 1, ) self.play( Write(plane, run_time = 1), self.students[0].change, "confused", self.students[1].change, "confused", ) self.play(dot.restore) for coords in (-1, 1), (1, -1), (0, -2), (-2, 1): self.wait(0.5) self.play(dot.move_to, plane.coords_to_point(*coords)) self.wait() class HypothesisAboutFullyColoredBoundary(ColorMappedObjectsScene): CONFIG = { "func" : plane_func_from_complex_func(lambda z : z**3), } def construct(self): ColorMappedObjectsScene.construct(self) square = Square(side_length = 4) square.color_using_background_image(self.background_image_file) hypothesis = OldTexText( "Working Hypothesis: \\\\", "If a 2d function hits outputs of all possible colors \\\\" + "on the boundary of a 2d region,", "that region \\\\ contains a zero.", alignment = "", ) hypothesis[0].next_to(hypothesis[1:], UP) hypothesis[0].set_color(YELLOW) s = hypothesis[1].get_tex() s = [c for c in s if c not in string.whitespace] n = s.index("colors") hypothesis[1][n:n+len("colors")].set_color_by_gradient( # RED, GOLD_E, YELLOW, GREEN, BLUE, PINK, BLUE, PINK, YELLOW, ) hypothesis.to_edge(UP) square.next_to(hypothesis, DOWN, MED_LARGE_BUFF) self.add(hypothesis[0]) self.play( LaggedStartMap(FadeIn, hypothesis[1]), ShowCreation(square, run_time = 8) ) self.play(LaggedStartMap(FadeIn, hypothesis[2])) self.play(square.set_fill, {"opacity" : 1}, run_time = 2) self.wait() class PiCreatureAsksWhatWentWrong(PiCreatureScene): def construct(self): randy = self.pi_creature randy.set_color(YELLOW_E) randy.flip() randy.to_corner(DOWN+LEFT) question = OldTexText("What went wrong?") question.next_to(randy, UP) question.shift_onto_screen() question.save_state() question.shift(DOWN).fade(1) self.play(randy.change, "erm") self.wait(2) self.play( Animation(VectorizedPoint(ORIGIN)), question.restore, randy.change, "confused", ) self.wait(5) class ForeverNarrowingLoop(InputOutputScene): CONFIG = { "target_coords" : (1, 1), "input_plane_corner" : UP+RIGHT, "shrink_time" : 20, "circle_start_radius" : 2.25, "start_around_target" : False, # Added as a flag to not mess up one clip already used and fine-timed # but to make it more convenient to do the other TinyLoop edits "add_convenient_waits" : False } def construct(self): input_coloring, output_coloring = colorings = VGroup(*self.get_colorings()) input_plane, output_plane = planes = VGroup(*self.get_planes()) for plane in planes: plane.white_parts.set_color(BLACK) plane.lines_to_fade.set_stroke(width = 0) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) v_line.set_stroke(WHITE, 5) self.add(colorings, v_line, planes) self.play(*it.chain( [ ApplyMethod(coloring.set_fill, {"opacity" : 0.2}) for coloring in colorings ], [ ApplyMethod(plane.white_parts.set_color, WHITE) for plane in planes ] ), run_time = 2) # circle circle = Circle(color = WHITE, radius = self.circle_start_radius) circle.flip(axis = RIGHT) circle.insert_n_curves(50) if self.start_around_target: circle.move_to(input_plane.coords_to_point(*self.target_coords)) else: circle.next_to( input_coloring.get_corner(self.input_plane_corner), -self.input_plane_corner, SMALL_BUFF ) circle.set_stroke(width = 5) circle_image = circle.copy() circle.match_background_image_file(input_coloring) circle_image.match_background_image_file(output_coloring) def update_circle_image(circle_image): circle_image.set_points(circle.get_points()) circle_image.apply_function(self.point_function) circle_image.make_smooth() circle_image_update_anim = UpdateFromFunc( circle_image, update_circle_image ) def optional_wait(): if self.add_convenient_waits: self.wait() optional_wait() self.play( ShowCreation(circle), ShowCreation(circle_image), run_time = 3, rate_func = bezier([0, 0, 1, 1]) ) optional_wait() self.play( circle.scale, 0, circle.move_to, input_plane.coords_to_point(*self.target_coords), circle_image_update_anim, run_time = self.shrink_time, rate_func = bezier([0, 0, 1, 1]) ) class AltForeverNarrowingLoop(ForeverNarrowingLoop): CONFIG = { "target_coords" : (-2, -1), "input_plane_corner" : DOWN+LEFT, "shrink_time" : 3, } class TinyLoop(ForeverNarrowingLoop): CONFIG = { "circle_start_radius" : 0.5, "start_around_target" : True, "shrink_time" : 1, "add_convenient_waits" : True, } class TinyLoopAroundZero(TinyLoop): CONFIG = { "target_coords" : (1, 1), } class TinyLoopAroundBlue(TinyLoop): CONFIG = { "target_coords" : (2.4, 0), } class TinyLoopAroundYellow(TinyLoop): CONFIG = { "target_coords" : (0, -1.3), } class TinyLoopAroundOrange(TinyLoop): CONFIG = { "target_coords" : (0, -0.5), } class TinyLoopAroundRed(TinyLoop): CONFIG = { "target_coords" : (-1, 1), } class ConfusedPiCreature(PiCreatureScene): def construct(self): morty = self.pi_creature morty.set_color(YELLOW_E) morty.flip() morty.center() self.play(morty.change, "awe", DOWN+3*RIGHT) self.wait(2) self.play(morty.change, "confused") self.wait(2) self.play(morty.change, "pondering") self.wait(2) class FailureOfComposition(ColorMappedObjectsScene): CONFIG = { "func" : lambda p : ( np.cos(TAU*p[1]/3.5), np.sin(TAU*p[1]/3.5) ) } def construct(self): ColorMappedObjectsScene.construct(self) big_square = Square(side_length = 4) big_square.move_to(ORIGIN, RIGHT) small_squares = VGroup(*[ Square(side_length = 2) for x in range(2) ]) small_squares.match_width(big_square, stretch = True) small_squares.arrange(DOWN, buff = 0) small_squares.move_to(big_square) small_squares.space_out_submobjects(1.1) all_squares = VGroup(big_square, *small_squares) all_squares.set_stroke(width = 6) for square in all_squares: square.set_color(WHITE) square.color_using_background_image(self.background_image_file) question = OldTexText("Does my border go through every color?") question.to_edge(UP) no_answers = VGroup() yes_answers = VGroup() for square in all_squares: if square is big_square: square.answer = OldTexText("Yes") square.answer.set_color(GREEN) yes_answers.add(square.answer) else: square.answer = OldTexText("No") square.answer.set_color(RED) no_answers.add(square.answer) square.answer.move_to(square) no_answers_in_equation = no_answers.copy() yes_answers_in_equation = yes_answers.copy() plus, equals = plus_equals = OldTex("+=") equation = VGroup( no_answers_in_equation[0], plus, no_answers_in_equation[1], equals, yes_answers_in_equation ) equation.arrange(RIGHT, buff = SMALL_BUFF) equation.next_to(big_square, RIGHT, MED_LARGE_BUFF) q_marks = OldTex("???") q_marks.next_to(equals, UP) self.add(question) self.play(LaggedStartMap(ShowCreation, small_squares, lag_ratio = 0.8)) self.play(LaggedStartMap(Write, no_answers)) self.wait() self.play( small_squares.arrange, DOWN, {"buff" : 0}, small_squares.move_to, big_square, no_answers.space_out_submobjects, 0.9, ) self.add(big_square) no_answers_copy = no_answers.copy() small_squares.save_state() self.play( Transform(no_answers, no_answers_in_equation), Write(plus_equals), small_squares.set_stroke, {"width" : 0}, ) self.play( Write(yes_answers), Write(yes_answers_in_equation), ) self.play(LaggedStartMap(FadeIn, q_marks, run_time = 1, lag_ratio = 0.8)) self.wait(2) self.play( small_squares.restore, FadeOut(yes_answers), FadeIn(no_answers_copy), ) self.wait() self.play( small_squares.set_stroke, {"width" : 0}, FadeOut(no_answers_copy), FadeIn(yes_answers), ) self.wait() # We can find a better notion of what we want cross = Cross(question) self.play( ShowCreation(cross, run_time = 2), FadeOut(equation), FadeOut(no_answers), FadeOut(q_marks), FadeOut(yes_answers), ) x, plus, y = x_plus_y = OldTex("x+y") x_plus_y.move_to(big_square) x_plus_y.save_state() x.move_to(no_answers_copy[0]) y.move_to(no_answers_copy[1]) plus.fade(1) for square, char in zip(small_squares, [x, y]): ghost = square.copy() ghost.set_stroke(width = 5) ghost.background_image_file = None self.play( small_squares.restore, ShowPassingFlash(ghost), Write(char) ) self.wait() ghost = big_square.copy() ghost.background_image_file = None self.play( small_squares.set_stroke, {"width" : 0}, x_plus_y.restore, ) self.play(ShowPassingFlash(ghost)) self.wait() class PathContainingZero(InputOutputScene, PiCreatureScene): CONFIG = { "default_pi_creature_kwargs" : { "flip_at_start" : False, "height" : 1.5, }, "default_pi_creature_start_corner" : DOWN+LEFT, } def construct(self): self.setup_planes() self.draw_path_hitting_zero() self.comment_on_zero() def setup_planes(self): colorings = VGroup(*self.get_colorings()) self.input_coloring, self.output_coloring = colorings colorings.set_fill(opacity = 0.3) planes = VGroup(*self.get_planes()) self.input_plane, self.output_plane = planes for plane in planes: # plane.white_parts.set_color(BLACK) plane.lines_to_fade.set_stroke(width = 0) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) v_line.set_stroke(WHITE, 5) self.add(colorings, planes) self.add(v_line) def draw_path_hitting_zero(self): morty = self.pi_creature path = self.path = VMobject( stroke_width = 5, stroke_color = WHITE, fill_opacity = 0, ) path.match_background_image_file(self.input_coloring) path.set_points_smoothly(list(it.starmap( self.input_plane.coords_to_point, [(1, 2.5), (2.5, 2.5), (2, 0.5), (1, 1), (0.5, 1), (0.5, 2), (1, 2.5)] ))) out_path = self.out_path = path.copy() out_path.apply_function(self.point_function) out_path.match_background_image_file(self.output_coloring) out_path.make_smooth() self.play( Flash( VectorizedPoint(self.output_plane.coords_to_point(0, 0)), color = WHITE, flash_radius = 0.3, line_length = 0.2, num_lines = 13, rate_func = squish_rate_func(smooth, 0.5, 0.6), ), morty.change, "pondering", *[ ShowCreation(mob, rate_func = bezier([0, 0, 1, 1])) for mob in (path, out_path) ], run_time = 5 ) def comment_on_zero(self): morty = self.pi_creature words = OldTexText( "Output is zero \\\\", "which has no direction" ) origin = self.output_plane.coords_to_point(0, 0) words.to_edge(DOWN, buff = LARGE_BUFF) background_rect = BackgroundRectangle( words, buff = SMALL_BUFF, opacity = 1.0 ) background_rect.stretch_to_fit_width(0.1) arrow = Arrow(words.get_top(), origin) circles = VGroup() for point in self.input_plane.coords_to_point(1, 1), origin: circle = Circle(color = BLACK, radius = 0.5, stroke_width = 0) circle.move_to(point) circle.generate_target() circle.target.scale(0) circle.target.set_stroke(width = 4) circles.add(circle) in_circle, out_circle = circles new_words = OldTexText( "But we want $\\vec{\\textbf{x}}$ \\\\", "where $f(\\vec{\\textbf{x}}) = 0$", ) new_words.move_to(words) self.play( FadeIn(background_rect), Write(words[0]), GrowArrow(arrow), ) self.play( Write(words[1]), morty.change, "pleading", MoveToTarget(out_circle, run_time = 2) ) self.wait() self.play(FadeOut(words)) self.play( FadeIn(new_words), morty.change, "happy" ) self.play(MoveToTarget(in_circle, run_time = 2)) self.play(morty.change, "hooray") self.wait(3) class TransitionFromPathsToBoundaries(ColorMappedObjectsScene): CONFIG = { "func" : plane_func_by_wind_spec( (-2, 0, 2), (2, 0, 1) ), "dot_fill_opacity" : 1, "dot_stroke_width" : 1, "include_walkers" : True, "include_question_mark" : True, } def construct(self): ColorMappedObjectsScene.construct(self) #Setup paths squares, joint_rect = self.get_squares_and_joint_rect() left_square, right_square = squares path1, path2 = paths = VGroup(*[ Line(square.get_corner(UP+LEFT), square.get_corner(UP+RIGHT)) for square in squares ]) joint_path = Line(path1.get_start(), path2.get_end()) for mob in it.chain(paths, [joint_path]): mob.set_stroke(WHITE, 4) mob.color_using_background_image(self.background_image_file) dot = self.get_dot_and_add_continual_animations() #Setup path braces for mob, tex in (path1, "x"), (path2, "y"), (joint_path, "x+y"): mob.brace = Brace(mob, DOWN) label = OldTexText("Winding =", "$%s$"%tex) label.next_to(mob.brace, DOWN) mob.brace.add(label) #Setup region labels sum_tex = "x+y" if self.include_question_mark: sum_tex += "\\, ?" for square, tex in (left_square, "x"), (right_square, "y"), (joint_rect, sum_tex): square.label = OldTexText("Winding = ", "$%s$"%tex) square.label.move_to(square) #Add paths self.position_dot(path1.get_start()) for path in path1, path2: self.position_dot(path.get_start()) self.play( MoveAlongPath(dot, path.copy()), ShowCreation(path), run_time = 2 ) self.play(GrowFromCenter(path.brace)) self.wait() self.position_dot(joint_path.get_start()) self.play( MoveAlongPath(dot, joint_path, run_time = 3), FadeOut(VGroup(path1.brace, path2.brace)), FadeIn(joint_path.brace), ) self.wait() #Add regions self.play( FadeOut(paths), FadeOut(joint_path.brace), dot.move_to, path1.get_start() ) for square in squares: self.position_dot(square.get_points()[0]) kwargs = { "run_time" : 4, "rate_func" : bezier([0, 0, 1, 1]), } self.play( MoveAlongPath(dot, square.copy(), **kwargs), ShowCreation(square, **kwargs), Write(square.label, run_time = 2), ) self.wait() self.play( dot.move_to, joint_rect.get_points()[0], FadeOut(squares), FadeIn(joint_rect), ) self.position_dot(joint_rect.get_points()[0]) self.play( Transform(left_square.label[0], joint_rect.label[0]), Transform( left_square.label[1], joint_rect.label[1][0], path_arc = TAU/6 ), FadeIn(joint_rect.label[1][1]), FadeIn(joint_rect.label[1][3:]), FadeOut(right_square.label[0]), Transform( right_square.label[1], joint_rect.label[1][2], path_arc = TAU/6 ), MoveAlongPath( dot, joint_rect, run_time = 6, rate_func = bezier([0, 0, 1, 1]) ) ) self.wait() ### def get_squares_and_joint_rect(self): squares = VGroup(*[ Square(side_length = 4).next_to(ORIGIN, vect, buff = 0) for vect in (LEFT, RIGHT) ]) joint_rect = SurroundingRectangle(squares, buff = 0) for mob in it.chain(squares, [joint_rect]): mob.set_stroke(WHITE, 4) mob.color_using_background_image(self.background_image_file) return squares, joint_rect def get_dot_and_add_continual_animations(self): #Define important functions for updates get_output = lambda : self.func(tuple(dot.get_center()[:2])) get_output_color = lambda : rgba_to_color(point_to_rgba(get_output())) get_output_rev = lambda : -point_to_rev(get_output()) self.get_output_rev = get_output_rev self.start_rev = 0 self.curr_winding = 0 def get_total_winding(dt = 0): rev = (get_output_rev() - self.start_rev)%1 possible_windings = [ np.floor(self.curr_winding)+k+rev for k in (-1, 0, 1) ] i = np.argmin([abs(pw - self.curr_winding) for pw in possible_windings]) self.curr_winding = possible_windings[i] return self.curr_winding #Setup dot, arrow and label dot = self.dot = Dot(radius = 0.1) dot.set_stroke(WHITE, self.dot_stroke_width) update_dot_color = Mobject.add_updater( dot, lambda d : d.set_fill( get_output_color(), self.dot_fill_opacity ) ) label = DecimalNumber(0, num_decimal_places = 1) label_upadte = ContinualChangingDecimal( label, get_total_winding, position_update_func = lambda l : l.next_to(dot, UP+LEFT, SMALL_BUFF) ) arrow_length = 0.75 arrow = Vector(arrow_length*RIGHT) arrow.set_stroke(WHITE, self.dot_stroke_width) def arrow_update_func(arrow): arrow.set_fill(get_output_color(), 1) arrow.rotate(-TAU*get_output_rev() - arrow.get_angle()) arrow.scale(arrow_length/arrow.get_length()) arrow.shift(dot.get_center() - arrow.get_start()) return arrow update_arrow = Mobject.add_updater(arrow, arrow_update_func) if self.include_walkers: self.add(update_arrow, update_dot_color, label_upadte) return dot def position_dot(self, point): self.dot.move_to(point) self.start_rev = self.get_output_rev() self.curr_winding = 0 class TransitionFromPathsToBoundariesArrowless(TransitionFromPathsToBoundaries): CONFIG = { "func" : plane_func_by_wind_spec( (-2, 0, 2), (2, 0, 1) ), "dot_fill_opacity" : 0, "dot_stroke_width" : 0, "include_walkers" : False, "include_question_mark" : False, } class BreakDownLoopWithNonzeroWinding(TransitionFromPathsToBoundaries): def construct(self): TransitionFromPathsToBoundaries.construct(self) zero_point = 2*LEFT squares, joint_rect = self.get_squares_and_joint_rect() left_square, right_square = squares VGroup(squares, joint_rect).shift(MED_LARGE_BUFF*DOWN) dot = self.get_dot_and_add_continual_animations() for rect, tex in (left_square, "x"), (right_square, "y"), (joint_rect, "3"): rect.label = OldTexText("Winding = ", "$%s$"%tex) rect.label.move_to(rect) sum_label = OldTex("x", "+", "y", "=", "3") x, plus, y, equals, three = sum_label sum_label.next_to(joint_rect, UP) both_cannot_be_zero = OldTexText("These cannot both be 0") both_cannot_be_zero.move_to(plus) both_cannot_be_zero.to_edge(UP) arrows = VGroup(*[ Arrow(both_cannot_be_zero.get_bottom(), var.get_top(), buff = SMALL_BUFF) for var in (x, y) ]) self.position_dot(joint_rect.get_points()[0]) self.add(joint_rect) self.play( MoveAlongPath(dot, joint_rect, rate_func = bezier([0, 0, 1, 1])), Write(joint_rect.label, rate_func = squish_rate_func(smooth, 0.7, 1)), run_time = 4 ) self.wait() self.play( ReplacementTransform(joint_rect.label, left_square.label), ReplacementTransform(joint_rect.label.copy(), right_square.label), ReplacementTransform(joint_rect.label[1].copy(), three), FadeIn(left_square), FadeIn(right_square), ) self.play( ReplacementTransform(left_square.label[1].copy(), x), ReplacementTransform(right_square.label[1].copy(), y), FadeIn(plus), FadeIn(equals), ) self.play( FadeIn(both_cannot_be_zero), *list(map(GrowArrow, arrows)) ) self.wait() class BackToEquationSolving(AltTeacherStudentsScene): def construct(self): self.teacher_says( "Back to solving \\\\ equations" ) self.play_all_student_changes("hooray") self.play(*[ ApplyMethod(pi.look_at, self.screen) for pi in self.pi_creatures ]) self.wait(3) class MonomialTerm(PathContainingZero): CONFIG = { "non_renormalized_func" : plane_func_from_complex_func(lambda z : z**5), "full_func_label" : "f(x) = x^5", "func_label" : "x^5", "loop_radius" : 1.1, "label_buff" : 0.3, "label_move_to_corner" : ORIGIN, "should_end_with_rescaling" : True, } def construct(self): self.setup_planes() self.relabel_planes() self.add_function_label() self.show_winding() if self.should_end_with_rescaling: self.rescale_output_plane() def relabel_planes(self): for plane in self.input_plane, self.output_plane: for mob in plane: if isinstance(mob, Tex): plane.remove(mob) if hasattr(plane, "numbers_to_show"): _range = plane.numbers_to_show else: _range = list(range(-2, 3)) for x in _range: if x == 0: continue label = OldTex(str(x)) label.scale(0.5) point = plane.coords_to_point(x, 0) label.next_to(point, DOWN, MED_SMALL_BUFF) plane.add(label) self.add_foreground_mobject(label) tick = Line(SMALL_BUFF*DOWN, SMALL_BUFF*UP) tick.move_to(point) plane.add(tick) for y in _range: if y == 0: continue label = OldTex("%di"%y) label.scale(0.5) point = plane.coords_to_point(0, y) label.next_to(point, LEFT, MED_SMALL_BUFF) plane.add(label) self.add_foreground_mobject(label) tick = Line(SMALL_BUFF*LEFT, SMALL_BUFF*RIGHT) tick.move_to(point) plane.add(tick) self.add(self.input_plane, self.output_plane) def add_function_label(self): label = OldTex(self.full_func_label) label.add_background_rectangle(opacity = 1, buff = SMALL_BUFF) arrow = Arrow( 2*LEFT, 2*RIGHT, path_arc = -TAU/3, ) arrow.pointwise_become_partial(arrow, 0, 0.95) label.next_to(arrow, UP) VGroup(arrow, label).to_edge(UP) self.add(label, arrow) def show_winding(self): loop = Arc(color = WHITE, angle = 1.02*TAU, num_anchors = 42) loop.scale(self.loop_radius) loop.match_background_image_file(self.input_coloring) loop.move_to(self.input_plane.coords_to_point(0, 0)) out_loop = loop.copy() out_loop.apply_function(self.point_function) out_loop.match_background_image_file(self.output_coloring) get_in_point = lambda : loop.get_points()[-1] get_out_point = lambda : out_loop.get_points()[-1] in_origin = self.input_plane.coords_to_point(0, 0) out_origin = self.output_plane.coords_to_point(0, 0) dot = Dot() update_dot = UpdateFromFunc(dot, lambda d : d.move_to(get_in_point())) out_dot = Dot() update_out_dot = UpdateFromFunc(out_dot, lambda d : d.move_to(get_out_point())) buff = self.label_buff def generate_label_update(label, point_func, origin): return UpdateFromFunc( label, lambda m : m.move_to( (1+buff)*point_func() - buff*origin, self.label_move_to_corner ) ) x = OldTex("x") fx = OldTex(self.func_label) update_x = generate_label_update(x, get_in_point, in_origin) update_fx = generate_label_update(fx, get_out_point, out_origin) morty = self.pi_creature kwargs = { "run_time" : 15, "rate_func" : None, } self.play( ShowCreation(loop, **kwargs), ShowCreation(out_loop, **kwargs), update_dot, update_out_dot, update_x, update_fx, ApplyMethod(morty.change, "pondering", out_dot), ) self.play( FadeOut(VGroup(dot, out_dot, x, fx)) ) self.loop = loop self.out_loop = out_loop def rescale_output_plane(self): output_stuff = VGroup(self.output_plane, self.output_coloring) self.play(*list(map(FadeOut, [self.loop, self.out_loop]))) self.play( output_stuff.scale, 3.0/50, run_time = 2 ) self.wait() ### def func(self, coords): return self.non_renormalized_func(coords) class PolynomialTerms(MonomialTerm): CONFIG = { "non_renormalized_func" : plane_func_from_complex_func(lambda z : z**5 - z - 1), "full_func_label" : "f(x) = x^5 - x - 1", "func_label" : "x^5 + \\cdots", "loop_radius" : 2.0, "label_buff" : 0.15, "label_move_to_corner" : DOWN+LEFT, "should_end_with_rescaling" : False, } def construct(self): self.pi_creature.change("pondering", VectorizedPoint(ORIGIN)) MonomialTerm.construct(self) self.cinch_loop() # self.sweep_through_loop_interior() def relabel_planes(self): self.output_plane.x_radius = 50 self.output_plane.y_radius = 50 self.output_plane.numbers_to_show = list(range(-45, 50, 15)) MonomialTerm.relabel_planes(self) def sweep_through_loop_interior(self): loop = self.loop morty = self.pi_creature line, line_target = [ Line( loop.get_left(), loop.get_right(), path_arc = u*TAU/2, n_arc_anchors = 40, background_image_file = self.input_coloring.background_image_file , stroke_width = 4, ) for u in (-1, 1) ] out_line = line.copy() update_out_line = UpdateFromFunc( out_line, lambda m : m.set_points(line.get_points()).apply_function(self.point_function), ) self.play( Transform( line, line_target, run_time = 10, rate_func = there_and_back ), update_out_line, morty.change, "hooray" ) self.wait() def cinch_loop(self): loop = self.loop out_loop = self.out_loop morty = self.pi_creature update_out_loop = UpdateFromFunc( out_loop, lambda m : m.set_points(loop.get_points()).apply_function(self.point_function) ) self.add( loop.copy().set_stroke(width = 1), out_loop.copy().set_stroke(width = 1), ) self.play( ApplyMethod( loop.scale, 0, {"about_point" : self.input_plane.coords_to_point(0.2, 1)}, run_time = 12, rate_func = bezier([0, 0, 1, 1]) ), update_out_loop, morty.change, "hooray" ) self.wait() class SearchSpacePerimeterVsArea(EquationSolver2d): CONFIG = { "func" : example_plane_func, "num_iterations" : 15, "display_in_parallel" : False, "use_fancy_lines" : True, } def construct(self): self.force_skipping() EquationSolver2d.construct(self) self.revert_to_original_skipping_status() all_parts = VGroup(*self.get_mobjects()) path_parts = VGroup() non_path_parts = VGroup() for part in all_parts: if part.get_background_image_file() is not None: path_parts.add(part) else: non_path_parts.add(part) path_parts.save_state() path_parts.generate_target() for path_target in path_parts.target: if isinstance(path_target, Line): path_target.rotate(-path_target.get_angle()) path_parts.target.arrange(DOWN, buff = MED_SMALL_BUFF) alt_path_parts = path_parts.copy() size = lambda m : m.get_height() + m.get_width() alt_path_parts.submobjects.sort( key=lambda m1: -size(m1) ) full_rect = SurroundingRectangle( path_parts, stroke_width = 0, fill_color = WHITE, fill_opacity = 1, background_image_file = path_parts[0].background_image_file ) full_rect.save_state() full_rect.stretch(0, 1, about_edge = UP) self.play( FadeOut(non_path_parts), path_parts.set_stroke, {"width" : 1}, ) self.remove(all_parts) for x in range(2): alt_path_parts.save_state() self.play(LaggedStartMap( FadeIn, alt_path_parts, rate_func = there_and_back, lag_ratio = 0.3, run_time = 3, remover = True )) alt_path_parts.restore() self.play( full_rect.restore, run_time = 2, ) self.wait() self.play(FadeOut(full_rect)) self.wait() class ShowPolynomialFinalState(SolveX5MinusXMinus1): CONFIG = { "num_iterations" : 15, } def construct(self): self.force_skipping() SolveX5MinusXMinus1.construct(self) self.revert_to_original_skipping_status() class PiCreatureInAwe(Scene): def construct(self): randy = Randolph() self.play(randy.change, "awe") self.play(Blink(randy)) self.play(randy.look, UP, run_time = 2) self.play( randy.look, RIGHT, run_time = 4, rate_func = there_and_back, path_arc = -TAU/4 ) self.wait() class ShowComplexFunction(Scene): def construct(self): plane = ComplexPlane() plane.add_coordinates() four_i = plane.coordinate_labels[-1] plane.coordinate_labels.remove(four_i) plane.remove(four_i) title = OldTexText("Complex Plane") title.to_edge(UP, buff = MED_SMALL_BUFF) rect = BackgroundRectangle(title, fill_opacity = 1, buff = MED_SMALL_BUFF) x = complex(1, 0.4) f = lambda x : x**5 - x - 1 x_point = plane.number_to_point(x) fx_point = plane.number_to_point(f(x)) x_dot = Dot(x_point) fx_dot = Dot(fx_point, color = YELLOW) arrow = Arrow( x_point, fx_point, path_arc = TAU/3, color = YELLOW ) arrow.pointwise_become_partial(arrow, 0, 0.95) x_label = OldTex("x = %d+%.1fi"%(x.real, x.imag)) x_label.next_to(x_dot, RIGHT) x_label.add_background_rectangle() fx_label = OldTex("f(x) = x^5 - x - 1") fx_label.next_to(fx_dot, DOWN, SMALL_BUFF) fx_label.set_color(YELLOW) fx_label.add_background_rectangle() fx_label.generate_target() fx_label.target.move_to(title) fx_label.target[1].set_color(WHITE) self.play( Write(plane), FadeIn(rect), LaggedStartMap(FadeIn, title) ) self.play(*list(map(FadeIn, [x_dot, x_label]))) self.wait() self.play( ReplacementTransform(x_dot.copy(), fx_dot, path_arc = arrow.path_arc), ShowCreation(arrow, rate_func = squish_rate_func(smooth, 0.2, 1)) ) self.play(FadeIn(fx_label)) self.wait(2) self.play( MoveToTarget(fx_label), *list(map(FadeOut, [title, x_dot, x_label, arrow, fx_dot])) ) self.play(FadeOut(plane.coordinate_labels)) self.wait() class WindingNumbersInInputOutputContext(PathContainingZero): CONFIG = { "in_loop_center_coords" : (-2, -1), "run_time" : 10, } def construct(self): self.remove(self.pi_creature) self.setup_planes() in_loop = Circle() in_loop.flip(RIGHT) # in_loop = Square(side_length = 2) in_loop.insert_n_curves(100) in_loop.move_to(self.input_plane.coords_to_point( *self.in_loop_center_coords )) in_loop.match_background_image_file(self.input_coloring) out_loop = in_loop.copy() out_loop.match_background_image_file(self.output_coloring) update_out_loop = Mobject.add_updater( out_loop, lambda m : m.set_points(in_loop.get_points()).apply_function(self.point_function) ) # self.add(update_out_loop) in_dot = Dot(radius = 0.04) update_in_dot = Mobject.add_updater( in_dot, lambda d : d.move_to(in_loop.point_from_proportion(1)) ) self.add(update_in_dot) out_arrow = Arrow(LEFT, RIGHT) update_out_arrow = Mobject.add_updater( out_arrow, lambda a : a.put_start_and_end_on( self.output_plane.coords_to_point(0, 0), out_loop.point_from_proportion(1) ) ) update_out_arrow_color = Mobject.add_updater( out_arrow, lambda a : a.set_color(rev_to_color(a.get_angle()/TAU)) ) self.add(update_out_arrow, update_out_arrow_color) words = OldTexText( "How many times does \\\\ the output wind around?" ) label = self.output_plane.label words.move_to(label, UP) self.output_plane.remove(label) self.add(words) decimal = DecimalNumber(0) decimal.next_to(self.output_plane.get_corner(UP+RIGHT), DOWN+LEFT) self.play( ShowCreation(in_loop), ShowCreation(out_loop), ChangeDecimalToValue(decimal, 2), Animation(in_dot), run_time = self.run_time, rate_func = bezier([0, 0, 1, 1]) ) class SolveX5SkipToEnd(SolveX5MinusXMinus1): CONFIG = { "num_iterations" : 4, } def construct(self): self.force_skipping() SolveX5MinusXMinus1.construct(self) self.revert_to_original_skipping_status() mobjects = VGroup(*self.get_mobjects()) lines = VGroup() rects = VGroup() for mob in mobjects: if mob.background_image_file is not None: mob.set_stroke(width = 2) lines.add(mob) elif isinstance(mob, Polygon): rects.add(mob) else: self.remove(mob) self.clear() self.add(lines, rects) class ZeroFoundOnBoundary(Scene): def construct(self): arrow = Vector(DOWN+LEFT, color = WHITE) words = OldTexText("Found zero on boundary!") words.next_to(arrow.get_start(), UP) words.shift(1.5*RIGHT) point = VectorizedPoint() point.next_to(arrow, DOWN+LEFT) self.play(Flash(point)) self.play( GrowArrow(arrow), Write(words), ) self.wait() class AllOfTheVideos(Scene): CONFIG = { "camera_config" : { "background_opacity" : 1, } } def construct(self): thumbnail_dir = os.path.join(MEDIA_DIR, "3b1b_videos/Winding/OldThumbnails") n = 4 images = Group(*[ ImageMobject(os.path.join(thumbnail_dir, file)) for file in os.listdir(thumbnail_dir)[:n**2] ]) for image in images: rect = SurroundingRectangle(image, buff = 0) rect.set_stroke(WHITE, 1) image.add(rect) images.arrange_in_grid(n, n, buff = 0) images.set_height(FRAME_HEIGHT) random.shuffle(images.submobjects) self.play(LaggedStartMap(FadeIn, images, run_time = 4)) self.wait() class EndingCredits(Scene): def construct(self): text = OldTexText( "Written and animated by: \\\\", "Sridhar Ramesh \\\\", "Grant Sanderson" ) text[0].shift(MED_SMALL_BUFF*UP) text.to_edge(UP) pi = PiCreature(color = YELLOW_E, height = 2) pi.to_edge(DOWN) pi.change_mode("happy") self.add(pi) self.play(LaggedStartMap(FadeIn, text), pi.look_at, text) self.play(pi.change, "wave_1", text) self.play(Blink(pi)) self.play(pi.change, "happy") self.wait() class MentionQAndA(Scene): def construct(self): title = OldTexText("Q\\&A with ", "Ben", "and", "Sridhar\\\\", "at", "Patreon") title.set_color_by_tex_to_color_map({ "Ben" : MAROON, "Sridhar" : YELLOW, }) patreon_logo = VGroup(*PatreonLogo().family_members_with_points()) patreon_logo.sort() patreon_logo.replace(title.get_parts_by_tex("Patreon")) patreon_logo.scale(1.3, about_edge = LEFT) patreon_logo.shift(0.5*SMALL_BUFF*DOWN) title.submobjects[-1] = patreon_logo title.to_edge(UP) self.add(title) questions = VGroup(*list(map(TexText, [ "If you think of the current videos as short stories, \\\\ what is the novel that you want to write?", "How did you get into mathematics?", "What motivated you to join 3b1b?", "$\\vdots$", ]))) questions.arrange(DOWN, buff = 0.75) questions.next_to(title, DOWN, LARGE_BUFF) self.play(LaggedStartMap(FadeIn, questions, run_time = 3)) self.wait(2) self.play(FadeOut(questions)) self.wait() class TickingClock(Scene): CONFIG = { "run_time" : 90, } def construct(self): clock = Clock() clock.set_height(FRAME_HEIGHT - 1) clock.to_edge(LEFT) lines = [clock.hour_hand, clock.minute_hand] def update_line(line): rev = line.get_angle()/TAU line.set_color(rev_to_color(rev)) for line in lines: self.add(Mobject.add_updater(line, update_line)) run_time = self.run_time self.play(ClockPassesTime( clock, run_time = run_time, hours_passed = 0.1*run_time )) class InfiniteListOfTopics(Scene): def construct(self): rect = Rectangle(width = 5, height = 7) rect.to_edge(RIGHT) title = OldTexText("Infinite list \\\\ of topics") title.next_to(rect.get_top(), DOWN) lines = VGroup(*[ OldTexText(words).scale(0.5) for words in [ "Winding number", "Laplace transform", "Wallis product", "Quantum information", "Elliptic curve cryptography", "Strange attractors", "Convolutional neural networks", "Fixed points", ] ] + [Tex("\\vdots")]) lines.arrange(DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT) lines.next_to(title, DOWN, MED_LARGE_BUFF) lines[-1].next_to(lines[-2], DOWN) self.add(rect, title) self.play(LaggedStartMap(FadeIn, lines, run_time = 5)) self.wait() class ManyIterations(Scene): def construct(self): words = VGroup(*[ OldTexText(word, alignment = "") for word in [ "Winding numbers, v1", "Winding numbers, v2 \\\\ (center on domain coloring)", "Winding numbers, v3 \\\\ (clarify visuals of 2d functions)", "Winding numbers, v4 \\\\ (postpone topology examples for part 2)", "Winding numbers, v5 \\\\ (start down wrong path)", ] ]) words.arrange(DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT) words.scale(0.75) words.to_edge(RIGHT) self.add(words[0]) for last_word, word in zip(words, words[1:]): cross = Cross(last_word) self.play(ShowCreation(cross)) self.play(FadeIn(word)) self.wait() class MentionFree(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs" : { "flip_at_start" : False, }, "default_pi_creature_start_corner" : DOWN, } def construct(self): morty = self.pi_creature morty.shift(RIGHT) items = VGroup( OldTexText("Movie:", "$>\\$10.00$"), OldTexText("College course:", "$>\\$1{,}000.00$"), OldTexText("YouTube video:", "$=\\$0.00$"), ) # items.arrange(DOWN, buff = MED_LARGE_BUFF) items.next_to(morty, UP, LARGE_BUFF) right_x = morty.get_right()[0] for item in items: item[1].set_color(GREEN) item.shift((right_x - item[0].get_right()[0])*RIGHT) self.play( morty.change, "raise_right_hand", FadeInFromDown(items[0]) ) self.wait() self.play( FadeInFromDown(items[1]), items[0].shift, UP, ) self.wait() self.play( items[:2].shift, UP, FadeInFromDown(items[2]), morty.change, "surprised" ) self.wait(4) self.play( morty.change, "raise_left_hand", VectorizedPoint(3*LEFT) ) self.wait(4) self.play(morty.change, "gracious", OUT) self.wait(4) class EndScreen(PatreonEndScreen, PiCreatureScene): CONFIG = { "run_time" : 0, } def construct(self): self.remove(self.pi_creature) PatreonEndScreen.construct(self) randy, morty = self.pi_creatures randy.change("plain") morty.change("plain") for mode in "thinking", "confused", "pondering", "hooray": self.play(randy.change, mode) self.wait() self.play(morty.change, mode) self.wait(2) class Thumbnail(SearchSpacePerimeterVsArea): CONFIG = { "num_iterations" : 18, "func" : plane_func_by_wind_spec( (-3, -1.3, 2), (0.1, 0.2, 1), (2.8, -2, 1) ), } def construct(self): self.force_skipping() EquationSolver2d.construct(self) self.revert_to_original_skipping_status() mobjects = VGroup(*self.get_mobjects()) lines = VGroup() rects = VGroup() get_length = lambda mob : max(mob.get_width(), mob.get_height()) for mob in mobjects: if mob.background_image_file is not None: mob.set_stroke(width = 4*np.sqrt(get_length(mob))) lines.add(mob) elif isinstance(mob, Polygon): rects.add(mob) else: self.remove(mob) self.clear() self.add(lines)
from manim_imports_ext import * X_COLOR = GREEN Y_COLOR = RED Z_COLOR = BLUE OUTPUT_COLOR = YELLOW INPUT_COLOR = MAROON_B OUTPUT_DIRECTORY = "eola2/cramer" def get_cramer_matrix(matrix, output_vect, index=0): """ The inputs matrix and output_vect should be Matrix mobjects """ new_matrix = np.array(matrix.mob_matrix) new_matrix[:, index] = output_vect.mob_matrix[:, 0] # Create a new Matrix mobject with copies of these entries result = Matrix(new_matrix, element_to_mobject=lambda m: m.copy()) result.match_height(matrix) return result class LinearSystem(VGroup): CONFIG = { "matrix_config": { "element_to_mobject": Integer, }, "dimensions": 3, "min_int": -9, "max_int": 10, "height": 4, } def __init__(self, matrix=None, output_vect=None, **kwargs): VGroup.__init__(self, **kwargs) if matrix is None: dim = self.dimensions matrix = np.random.randint( self.min_int, self.max_int, size=(dim, dim) ) else: dim = len(matrix) self.matrix_mobject = Matrix(matrix, **self.matrix_config) self.equals = OldTex("=") self.equals.scale(1.5) colors = [X_COLOR, Y_COLOR, Z_COLOR][:dim] chars = ["x", "y", "z"][:dim] self.input_vect_mob = Matrix(np.array(chars)) self.input_vect_mob.elements.set_color_by_gradient(*colors) if output_vect is None: output_vect = np.random.randint( self.min_int, self.max_int, size=(dim, 1)) self.output_vect_mob = IntegerMatrix(output_vect) self.output_vect_mob.elements.set_color(OUTPUT_COLOR) for mob in self.matrix_mobject, self.input_vect_mob, self.output_vect_mob: mob.set_height(self.height) self.add( self.matrix_mobject, self.input_vect_mob, self.equals, self.output_vect_mob, ) self.arrange(RIGHT, buff=SMALL_BUFF) # Scenes class AltOpeningQuote(OpeningQuote): def construct(self): kw = { "tex_to_color_map": { "Jerry": YELLOW, "Kramer": BLUE, }, "arg_separator": "", "alignment": "", } parts = VGroup( OldTexText("Jerry: Ah, you're crazy!", **kw), OldTexText( "Kramer:", "{} Am I? Or am I so sane that\\\\", "you just blew your mind?", **kw ), OldTexText("Jerry: It's impossible!", **kw), OldTexText( "Kramer:", "{} Is it?! Or is it so possible\\\\", "your head is spinning like a top?", **kw ) ) for part in parts[1::2]: part[-1].align_to(part[-2], LEFT) parts.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) self.add(parts[0]) self.play(FadeIn(parts[1], lag_ratio=0.1, run_time=2)) self.play(FadeIn(parts[2], lag_ratio=0)) self.play(FadeIn(parts[3], lag_ratio=0.1, run_time=2)) self.wait() class CramerOpeningQuote(OpeningQuote): CONFIG = { "quote": ["Computers are useless. They \\\\ can only give you answers."], "author": "Pablo Picasso", } class LeaveItToComputers(TeacherStudentsScene): CONFIG = { "random_seed": 1, } def construct(self): system = LinearSystem(height=3) system.next_to(self.pi_creatures, UP) system.generate_target() system.target.scale(0.5) system.target.to_corner(UL) cramer_groups = VGroup() for i in range(3): numer_matrix = get_cramer_matrix( system.matrix_mobject, system.output_vect_mob, index=i ) # color = colors[i] color = YELLOW VGroup(*numer_matrix.mob_matrix[:, i]).set_color(color) VGroup(*numer_matrix.mob_matrix[:, i]).set_stroke(color, 1) numer = VGroup( get_det_text(numer_matrix, initial_scale_factor=3), numer_matrix ) numer.to_corner(UP) denom_matrix_mobject = system.matrix_mobject.deepcopy() denom = VGroup( get_det_text(denom_matrix_mobject, initial_scale_factor=3), denom_matrix_mobject, ) rhs = VGroup(numer, Line(LEFT, RIGHT).match_width(numer), denom) rhs.arrange(DOWN) rhs.set_height(2.25) rhs.move_to(self.hold_up_spot, DOWN) rhs.to_edge(RIGHT, buff=LARGE_BUFF) equals = OldTex("=").next_to(rhs, LEFT) variable = system.input_vect_mob.elements[i].copy() variable.next_to(equals, LEFT) cramer_group = VGroup(variable, equals, rhs) cramer_group.variable = variable cramer_group.equals = equals cramer_group.rhs = rhs cramer_groups.add(cramer_group) self.play( Write(system), self.teacher.change, "raise_right_hand", self.change_students("pondering", "thinking", "hooray") ) self.wait(2) self.play( PiCreatureSays( self.teacher, "Let the computer \\\\ handle it", target_mode="shruggie", ), MoveToTarget(system, path_arc=90 * DEGREES), self.change_students(*["confused"] * 3) ) self.wait(3) cg = cramer_groups[0] scale_factor = 1.5 cg.scale(scale_factor, about_edge=DOWN) numer, line, denom = cg.rhs x_copy = system.input_vect_mob.elements[0].copy() self.play( RemovePiCreatureBubble( self.teacher, target_mode="raise_right_hand"), ShowCreation(line), ReplacementTransform( system.matrix_mobject.copy(), denom[1], ), Write(denom[0]), FadeIn(cg.equals), ReplacementTransform(x_copy, cg.variable), ) denom_mover = denom.deepcopy() denom_mover.target = numer.deepcopy() column1 = VGroup(*denom_mover.target[1].mob_matrix[:, 0]) column1.set_fill(opacity=0) column1.set_stroke(width=0) self.play(MoveToTarget(denom_mover)) self.look_at(system) self.play( ReplacementTransform( system.output_vect_mob.elements.copy(), VGroup(*numer[1].mob_matrix[:, 0]), path_arc=90 * DEGREES ), self.teacher.change, "happy", ) self.remove(denom_mover) self.add(cg) self.play_all_student_changes("sassy") self.wait(2) self.play( cramer_groups[0].scale, 1 / scale_factor, cramer_groups[0].next_to, cramer_groups[1], LEFT, MED_LARGE_BUFF, FadeIn(cramer_groups[1]), FadeOut(system), self.change_students(*3 * ["horrified"], look_at=UP), ) self.wait() self.play( FadeIn(cramer_groups[2]), cramer_groups[:2].next_to, cramer_groups[2], LEFT, MED_LARGE_BUFF, self.change_students(*3 * ["horrified"], look_at=UP), ) self.wait() brace = Brace(cramer_groups, UP) rule_text = brace.get_text("``Cramer's rule''") self.play( GrowFromCenter(brace), Write(rule_text), self.change_students( "pondering", "erm", "maybe", look_at=brace, ) ) self.wait(3) class ShowComputer(ThreeDScene): def construct(self): laptop = Laptop() laptop.add_updater(lambda m, dt: m.rotate(0.1 * dt, axis=UP)) self.play(DrawBorderThenFill( laptop, lag_ratio=0.1, rate_func=smooth )) self.wait(8) self.play(FadeOut(laptop)) class PrerequisiteKnowledge(TeacherStudentsScene): CONFIG = { "camera_config": {"background_opacity": 1} } def construct(self): self.remove(*self.pi_creatures) randy = self.students[1] self.add(randy) title = OldTexText("Prerequisites") title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(5) h_line.next_to(title, DOWN) images = Group(*[ ImageMobject("eola%d_thumbnail" % d) for d in [5, 7, 6] ]) images.arrange(RIGHT, buff=LARGE_BUFF) images.next_to(h_line, DOWN, MED_LARGE_BUFF) for image in images: rect = SurroundingRectangle(image, color=BLUE) image.rect = rect self.add(title) self.play( ShowCreation(h_line), randy.change, "erm" ) self.wait() for image in images: self.play( FadeInFromDown(image), FadeInFromDown(image.rect), randy.change, "pondering" ) self.wait() class NotTheMostComputationallyEfficient(Scene): CONFIG = { "words": "Not the most \\\\ computationally efficient", "word_height": 4, "opacity": 0.7, } def construct(self): big_rect = FullScreenFadeRectangle(opacity=self.opacity) self.add(big_rect) words = OldTexText(self.words) words.set_color(RED) words.set_stroke(WHITE, 1) words.set_width(FRAME_WIDTH - 2 * MED_LARGE_BUFF) self.play(Write(words)) self.wait() class GaussTitle(Scene): def construct(self): title = OldTexText("Gaussian Elimination") title.scale(1.5) title.to_edge(UP) line = Line(LEFT, RIGHT).scale(7) line.next_to(title, DOWN) self.play( FadeIn(title, lag_ratio=0.2), ShowCreation(line), ) self.wait() class WhyLearnIt(TeacherStudentsScene): def construct(self): self.student_says( "What?!? Then why \\\\ learn it?", bubble_config={"direction": LEFT}, index=2, target_mode="angry", ) self.play_all_student_changes("angry") self.wait() self.play( self.teacher.change, "raise_right_hand", self.change_students("erm", "happy" "pondering"), RemovePiCreatureBubble(self.students[2], target_mode="pondering"), ) self.look_at(self.screen) self.wait(10) class SetupSimpleSystemOfEquations(LinearTransformationScene): CONFIG = { "matrix": [[3, 2], [-1, 2]], "output_vect": [-4, -2], "quit_before_final_transformation": False, "array_scale_factor": 0.75, "compare_to_big_system": True, "transition_to_geometric_view": True, } def construct(self): self.remove_grid() self.introduce_system() self.from_system_to_matrix() self.show_geometry() def remove_grid(self): self.clear() def introduce_system(self): system = self.system = self.get_system(self.matrix, self.output_vect) dim = len(self.matrix) big_dim = 7 # Big system size big_matrix = np.random.randint(-9, 10, size=(big_dim, big_dim)) big_output_vect = np.random.randint(-9, 10, size=big_dim) big_matrix[:dim, :dim] = self.matrix big_output_vect[:dim] = self.output_vect big_system = self.get_system(big_matrix, big_output_vect) unknown_circles = VGroup(*[ Circle(color=YELLOW).replace(term).scale(1.5) for term in system.unknowns ]) unknown_circles.set_stroke(YELLOW, 2) for circle in unknown_circles: circle.save_state() circle.scale(5) circle.fade(1) row_rects = VGroup(*list(map(SurroundingRectangle, system))) row_rects.set_stroke(BLUE, 2) self.add(system) self.wait() self.play(LaggedStartMap( ApplyMethod, unknown_circles, lambda m: (m.restore,), lag_ratio=0.7 )) self.play(FadeOut(unknown_circles)) self.play(LaggedStartMap(ShowCreation, row_rects, run_time=1, lag_ratio=0.8)) self.play(FadeOut(row_rects)) self.wait() if self.compare_to_big_system: self.remove(system) self.play(ReplacementTransform(system.copy(), big_system)) self.wait(2) # Oh yeah, super readable line... cutoff = 3 * dim - 1 self.play(*[ ReplacementTransform(big_system[i][:cutoff], system[i][:cutoff]) for i in range(dim) ] + [ ReplacementTransform(big_system[i][-2:], system[i][-2:]) for i in range(dim) ] + [ FadeOut(big_system[i][start:end]) for i in range(big_dim) for start in [cutoff if i < dim else 0] for end in [-2 if i < dim else len(big_system[i])] ]) self.remove(big_system, system) self.add(system) def from_system_to_matrix(self): # dim = len(self.matrix) system_in_lines = self.system matrix_system = self.matrix_system = LinearSystem( self.matrix, self.output_vect, height=2 ) matrix_system.center() corner_rect = self.corner_rect = SurroundingRectangle( matrix_system, buff=MED_SMALL_BUFF ) corner_rect.set_stroke(width=0) corner_rect.set_fill(BLACK, opacity=0.8) corner_rect.set_height(2) corner_rect.to_corner(UL, buff=0) self.play(system_in_lines.to_edge, UP) system_in_lines_copy = system_in_lines.deepcopy() self.play( ReplacementTransform( VGroup(*list(map(VGroup, system_in_lines_copy.matrix_elements))), matrix_system.matrix_mobject.elements, ), Write(matrix_system.matrix_mobject.brackets), Write(matrix_system.output_vect_mob.brackets), Write(matrix_system.input_vect_mob.brackets), Write(matrix_system.equals) ) self.play(ReplacementTransform( VGroup(*list(map(VGroup, system_in_lines_copy.output_vect_elements))), matrix_system.output_vect_mob.elements, )) self.play(*[ ReplacementTransform(uk, elem) for uk, elem in zip( system_in_lines_copy.unknowns, it.cycle(matrix_system.input_vect_mob.elements) ) ]) self.wait() if self.transition_to_geometric_view: self.play( Write(self.background_plane), Write(self.plane), FadeOut(system_in_lines), FadeIn(corner_rect), matrix_system.set_height, corner_rect.get_height() - MED_LARGE_BUFF, matrix_system.move_to, corner_rect, ) self.play(*list(map(GrowArrow, self.basis_vectors))) self.add_foreground_mobject(corner_rect) self.add_foreground_mobject(matrix_system) def show_geometry(self): system = self.matrix_system matrix_mobject = system.matrix_mobject columns = VGroup(*[ VGroup(*matrix_mobject.mob_matrix[:, i]) for i in (0, 1) ]) matrix = np.array(self.matrix) first_half_matrix = np.identity(matrix.shape[0]) first_half_matrix[:, 0] = matrix[:, 0] second_half_matrix = np.dot( matrix, np.linalg.inv(first_half_matrix), ) scale_factor = self.array_scale_factor column_mobs = VGroup() for i in 0, 1: column_mob = IntegerMatrix(matrix[:, i]) column_mob.elements.set_color([X_COLOR, Y_COLOR][i]) column_mob.scale(scale_factor) column_mob.next_to( self.plane.coords_to_point(*matrix[:, i]), RIGHT) column_mob.add_to_back(BackgroundRectangle(column_mob)) column_mobs.add(column_mob) output_vect_mob = self.get_vector(self.output_vect, color=OUTPUT_COLOR) output_vect_label = system.output_vect_mob.deepcopy() output_vect_label.add_to_back(BackgroundRectangle(output_vect_label)) output_vect_label.generate_target() output_vect_label.target.scale(scale_factor) output_vect_label.target.next_to( output_vect_mob.get_end(), LEFT, SMALL_BUFF) input_vect = np.dot(np.linalg.inv(self.matrix), self.output_vect) input_vect_mob = self.get_vector(input_vect, color=INPUT_COLOR) q_marks = OldTex("????") q_marks.set_color_by_gradient(INPUT_COLOR, OUTPUT_COLOR) q_marks.next_to(input_vect_mob.get_end(), DOWN, SMALL_BUFF) q_marks_rect = SurroundingRectangle(q_marks, color=WHITE) # Show output vector self.play( GrowArrow(output_vect_mob), MoveToTarget(output_vect_label), ) self.add_foreground_mobjects(output_vect_mob, output_vect_label) self.wait() # Show columns for column, color in zip(columns, [X_COLOR, Y_COLOR]): rect = SurroundingRectangle(column, color=WHITE) self.play( column.set_color, color, system.input_vect_mob.elements.set_color, WHITE, ShowPassingFlash(rect), ) matrices = [first_half_matrix, second_half_matrix] for column, column_mob, m in zip(columns, column_mobs, matrices): column_mob.save_state() column_mob[0].scale(0).move_to(matrix_mobject) column_mob.elements.become(column) column_mob.brackets.become(matrix_mobject.brackets) self.add_foreground_mobject(column_mob) self.apply_matrix(m, added_anims=[ ApplyMethod(column_mob.restore, path_arc=90 * DEGREES) ]) self.wait() # Do inverse transformation to reveal input self.remove_foreground_mobjects(column_mobs) self.apply_inverse(self.matrix, run_time=1, added_anims=[ ReplacementTransform(output_vect_mob.copy(), input_vect_mob), ReplacementTransform(output_vect_label.elements.copy(), q_marks), FadeOut(column_mobs) ]) self.play(ShowPassingFlash(q_marks_rect)) self.wait(2) if not self.quit_before_final_transformation: self.apply_matrix(self.matrix, added_anims=[ FadeOut(q_marks), ReplacementTransform(input_vect_mob, output_vect_mob), FadeIn(column_mobs), ]) self.wait() self.q_marks = q_marks self.input_vect_mob = input_vect_mob self.output_vect_mob = output_vect_mob self.output_vect_label = output_vect_label self.column_mobs = column_mobs # Helpers def get_system(self, matrix, output_vect): if len(matrix) <= 3: chars = "xyzwv" else: chars = ["x_%d" % d for d in range(len(matrix))] colors = [ color for i, color in zip( list(range(len(matrix))), it.cycle([X_COLOR, Y_COLOR, Z_COLOR, YELLOW, MAROON_B, TEAL]) ) ] system = VGroup() system.matrix_elements = VGroup() system.output_vect_elements = VGroup() system.unknowns = VGroup() for row, num in zip(matrix, output_vect): args = [] for i in range(len(row)): if i + 1 == len(row): sign = "=" elif row[i + 1] < 0: sign = "-" else: sign = "+" args += [str(abs(row[i])), chars[i], sign] args.append(str(num)) line = OldTex(*args) line.set_color_by_tex_to_color_map(dict([ (char, color) for char, color in zip(chars, colors) ])) system.add(line) system.matrix_elements.add(*line[0:-1:3]) system.unknowns.add(*line[1:-1:3]) system.output_vect_elements.add(line[-1]) system.output_vect_elements.set_color(OUTPUT_COLOR) system.arrange( DOWN, buff=0.75, index_of_submobject_to_align=-2 ) return system class FloatingMinus(Scene): def construct(self): minus = OldTex("-") self.add(minus) self.play(minus.shift, 2.9 * UP, run_time=1) class ShowZeroDeterminantCase(LinearTransformationScene): CONFIG = { "show_basis_vectors": True, "matrix": [[3, -2.0], [1, -2.0 / 3]], "tex_scale_factor": 1.25, "det_eq_symbol": "=", } def construct(self): self.add_equation() self.show_det_zero() def add_equation(self): equation = self.equation = OldTex( "A", "\\vec{\\textbf{x}}", "=", "\\vec{\\textbf{v}}" ) equation.scale(self.tex_scale_factor) equation.set_color_by_tex("{x}", INPUT_COLOR) equation.set_color_by_tex("{v}", OUTPUT_COLOR) equation.add_background_rectangle() equation.to_corner(UL) self.add(equation) self.add_foreground_mobject(equation) def show_det_zero(self): matrix = self.matrix # vect_in_span = [2, 2.0 / 3] vect_in_span = [2, 2.0 / 3] vect_off_span = [1, 2] vect_in_span_mob = self.get_vector(vect_in_span, color=OUTPUT_COLOR) vect_off_span_mob = self.get_vector(vect_off_span, color=OUTPUT_COLOR) for vect_mob in vect_in_span_mob, vect_off_span_mob: circle = Circle(color=WHITE, radius=0.15, stroke_width=2) circle.move_to(vect_mob.get_end()) vect_mob.circle = circle vect_off_span_words = OldTexText("No input lands here") vect_off_span_words.next_to(vect_off_span_mob.circle, UP) vect_off_span_words.add_background_rectangle() vect_in_span_words = OldTexText("Many inputs lands here") vect_in_span_words.next_to(vect_in_span_mob.circle, DR) vect_in_span_words.shift_onto_screen() vect_in_span_words.add_background_rectangle() moving_group = VGroup(self.plane, self.basis_vectors) moving_group.save_state() solution = np.dot(np.linalg.pinv(matrix), vect_in_span) import sympy null_space_basis = np.array(sympy.Matrix(matrix).nullspace()) null_space_basis = null_space_basis.flatten().astype(float) solution_vectors = VGroup(*[ self.get_vector( solution + x * null_space_basis, rectangular_stem_width=0.025, tip_length=0.2, ) for x in np.linspace(-4, 4, 20) ]) solution_vectors.set_color_by_gradient(YELLOW, MAROON_B) self.apply_matrix(matrix, path_arc=0) self.wait() self.show_det_equation() self.wait() # Mention zero determinants self.play(GrowArrow(vect_off_span_mob)) self.play( ShowCreation(vect_off_span_mob.circle), Write(vect_off_span_words), ) self.wait() self.play( FadeOut(vect_off_span_mob.circle), ReplacementTransform(vect_off_span_mob, vect_in_span_mob), ReplacementTransform(vect_off_span_words, vect_in_span_words), ReplacementTransform(vect_off_span_mob.circle, vect_in_span_mob.circle), ) self.wait(2) self.play( FadeOut(vect_in_span_words), FadeOut(vect_in_span_mob.circle), ApplyMethod(moving_group.restore, run_time=2), ReplacementTransform( VGroup(vect_in_span_mob), solution_vectors, run_time=2, ), ) self.wait() # Helpers def show_det_equation(self): equation = self.equation det_equation = OldTex( "\\det(", "A", ")", self.det_eq_symbol, "0" ) det_equation.scale(self.tex_scale_factor) det_equation.next_to( equation, DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) det_rect = BackgroundRectangle(det_equation) self.play( FadeIn(det_rect), Write(det_equation[0]), ReplacementTransform( equation.get_part_by_tex("A").copy(), det_equation.get_part_by_tex("A").copy(), ), Write(det_equation[2:]), ) self.add_foreground_mobject(det_rect, det_equation) class NonZeroDeterminantCase(ShowZeroDeterminantCase, SetupSimpleSystemOfEquations): CONFIG = { "det_eq_symbol": "\\neq" } def construct(self): self.add_equation() self.show_det_equation() output_vect = self.output_vect matrix = self.matrix input_vect = np.dot(np.linalg.inv(matrix), output_vect) input_vect_mob = self.get_vector(input_vect, color=INPUT_COLOR) output_vect_mob = self.get_vector(output_vect, color=OUTPUT_COLOR) input_vect_label = OldTexText("Input") input_vect_label.next_to(input_vect_mob.get_end(), DOWN, SMALL_BUFF) input_vect_label.match_color(input_vect_mob) output_vect_label = OldTexText("Output") output_vect_label.next_to(output_vect_mob.get_end(), DOWN, SMALL_BUFF) output_vect_label.match_color(output_vect_mob) for label in input_vect_label, output_vect_label: label.scale(1.25, about_edge=UP) label.add_background_rectangle() self.apply_matrix(matrix) self.wait() self.apply_inverse(matrix) self.wait() self.play( GrowArrow(input_vect_mob), Write(input_vect_label), run_time=1 ) self.wait() self.remove(input_vect_mob, input_vect_label) self.apply_matrix(matrix, added_anims=[ ReplacementTransform(input_vect_mob.copy(), output_vect_mob), ReplacementTransform(input_vect_label.copy(), output_vect_label), ], run_time=2) self.wait() self.remove(output_vect_mob, output_vect_label) self.apply_inverse(matrix, added_anims=[ ReplacementTransform(output_vect_mob.copy(), input_vect_mob), ReplacementTransform(output_vect_label.copy(), input_vect_label), ], run_time=2) self.wait() class ThinkOfPuzzleAsLinearCombination(SetupSimpleSystemOfEquations): CONFIG = { "output_vect": [-4, -2], } def construct(self): self.force_skipping() super(ThinkOfPuzzleAsLinearCombination, self).construct() self.revert_to_original_skipping_status() self.rearrange_equation_as_linear_combination() self.show_linear_combination_of_vectors() def rearrange_equation_as_linear_combination(self): system = self.matrix_system corner_rect = self.corner_rect matrix, input_vect, equals, output_vect = system columns = VGroup(*[ VGroup(*matrix.mob_matrix[:, i].flatten()) for i in (0, 1) ]) column_arrays = VGroup(*[ MobjectMatrix(matrix.deepcopy().mob_matrix[:, i]) for i in (0, 1) ]) for column_array in column_arrays: column_array.match_height(output_vect) x, y = input_vect.elements movers = VGroup(x, y, equals, output_vect) for mover in movers: mover.generate_target() plus = OldTex("+") new_system = VGroup( x.target, column_arrays[0], plus, y.target, column_arrays[1], equals.target, output_vect.target ) new_system.arrange(RIGHT, buff=SMALL_BUFF) new_system.move_to(matrix, LEFT) corner_rect.generate_target() corner_rect.target.stretch_to_fit_width( new_system.get_width() + MED_LARGE_BUFF, about_edge=LEFT ) self.remove_foreground_mobjects(corner_rect, system) self.play( MoveToTarget(corner_rect), FadeOut(input_vect.brackets), ReplacementTransform(matrix.brackets, column_arrays[0].brackets), ReplacementTransform(matrix.brackets.copy(), column_arrays[1].brackets), ReplacementTransform(columns[0], column_arrays[0].elements), ReplacementTransform(columns[1], column_arrays[1].elements), Write(plus, rate_func=squish_rate_func(smooth, 0.5, 1)), *[ MoveToTarget(mover, replace_mobject_with_target_in_scene=True) for mover in movers ], path_arc=90 * DEGREES, run_time=2 ) self.add_foreground_mobject(corner_rect, new_system) self.wait() def show_linear_combination_of_vectors(self): basis_vectors = self.basis_vectors input_vect = np.dot(np.linalg.inv(self.matrix), self.output_vect) origin = self.plane.coords_to_point(0, 0) for basis, scalar in zip(basis_vectors, input_vect): basis.ghost = basis.copy() basis.ghost.set_color(average_color(basis.get_color(), BLACK)) self.add_foreground_mobjects(basis.ghost, basis) basis.generate_target() basis_coords = np.array( self.plane.point_to_coords(basis.get_end())) new_coords = scalar * basis_coords basis.target.put_start_and_end_on( origin, self.plane.coords_to_point(*new_coords), ) dashed_lines = VGroup(*[DashedLine(LEFT, RIGHT) for x in range(2)]) def update_dashed_lines(lines): for i in 0, 1: lines[i].put_start_and_end_on( basis_vectors[i].get_start(), basis_vectors[i].get_end(), ) lines[i].shift(basis_vectors[1 - i].get_end() - origin) return lines update_dashed_lines(dashed_lines) self.play(LaggedStartMap(ShowCreation, dashed_lines, lag_ratio=0.7)) for basis in basis_vectors: self.play( MoveToTarget(basis, run_time=2), UpdateFromFunc(dashed_lines, update_dashed_lines) ) self.wait() class WrongButHelpful(TeacherStudentsScene): def construct(self): self.teacher_says("What's next is wrong, \\\\ but helpful") self.play_student_changes("sassy", "sad", "angry") self.wait(3) class LookAtDotProducts(SetupSimpleSystemOfEquations): CONFIG = { "quit_before_final_transformation": True, "equation_scale_factor": 0.7, } def construct(self): self.force_skipping() super(LookAtDotProducts, self).construct() self.revert_to_original_skipping_status() self.remove_corner_system() self.show_dot_products() def remove_corner_system(self): to_remove = [self.corner_rect, self.matrix_system] self.remove_foreground_mobjects(*to_remove) self.remove(*to_remove) q_marks = self.q_marks input_vect_mob = self.input_vect_mob equations = self.equations = VGroup() for i in 0, 1: basis = [0, 0] basis[i] = 1 equation = VGroup( Matrix(["x", "y"]), OldTex("\\cdot"), IntegerMatrix(basis), OldTex("="), OldTex(["x", "y"][i]), ) for part in equation: if isinstance(part, Matrix): part.scale(self.array_scale_factor) equation[2].elements.set_color([X_COLOR, Y_COLOR][i]) equation.arrange(RIGHT, buff=SMALL_BUFF) equation.scale(self.equation_scale_factor) equations.add(equation) equations.arrange(DOWN, buff=MED_LARGE_BUFF) equations.to_corner(UL) corner_rect = self.corner_rect = BackgroundRectangle( equations, opacity=0.8) self.resize_corner_rect_to_mobjet(corner_rect, equations) corner_rect.save_state() self.resize_corner_rect_to_mobjet(corner_rect, equations[0]) xy_vect_mob = Matrix(["x", "y"], include_background_rectangle=True) xy_vect_mob.scale(self.array_scale_factor) xy_vect_mob.next_to(input_vect_mob.get_end(), DOWN, SMALL_BUFF) q_marks.add_background_rectangle() q_marks.next_to(xy_vect_mob, RIGHT) origin = self.plane.coords_to_point(0, 0) input_vect_end = input_vect_mob.get_end() x_point = (input_vect_end - origin)[0] * RIGHT + origin y_point = (input_vect_end - origin)[1] * UP + origin v_dashed_line = DashedLine(input_vect_end, x_point) h_dashed_line = DashedLine(input_vect_end, y_point) h_brace = Brace(Line(x_point, origin), UP, buff=SMALL_BUFF) v_brace = Brace(Line(y_point, origin), RIGHT, buff=SMALL_BUFF) self.add(xy_vect_mob) self.wait() self.play( FadeIn(corner_rect), FadeIn(equations[0][:-1]), ShowCreation(v_dashed_line), GrowFromCenter(h_brace), ) self.play( ReplacementTransform(h_brace.copy(), equations[0][-1]) ) self.wait() self.play( corner_rect.restore, Animation(equations[0]), FadeIn(equations[1]), ) self.wait() self.play( ReplacementTransform(equations[1][-1].copy(), v_brace), ShowCreation(h_dashed_line), GrowFromCenter(v_brace) ) self.wait() self.to_fade = VGroup( h_dashed_line, v_dashed_line, h_brace, v_brace, xy_vect_mob, q_marks, ) def show_dot_products(self): moving_equations = self.equations.copy() transformed_equations = VGroup() implications = VGroup() transformed_input_rects = VGroup() transformed_basis_rects = VGroup() for equation in moving_equations: equation.generate_target() xy_vect, dot, basis, equals, coord = equation.target T1, lp1, rp1 = OldTex("T", "(", ")") lp1.scale(1, about_edge=LEFT) rp1.scale(1, about_edge=LEFT) for paren in lp1, rp1: paren.stretch_to_fit_height(equation.get_height()) T2, lp2, rp2 = T1.copy(), lp1.copy(), rp1.copy() transformed_equation = VGroup( T1, lp1, xy_vect, rp1, dot, T2, lp2, basis, rp2, equals, coord ) transformed_equation.arrange(RIGHT, buff=SMALL_BUFF) # transformed_equation.scale(self.equation_scale_factor) implies = OldTex("\\Rightarrow").scale(1.2) implies.next_to(equation, RIGHT) implies.set_color(BLUE) transformed_equation.next_to(implies, RIGHT) implications.add(implies) transformed_input_rects.add(SurroundingRectangle( transformed_equation[:4], color=OUTPUT_COLOR )) transformed_basis_rects.add(SurroundingRectangle( transformed_equation[5:5 + 4], color=basis.elements.get_color() )) for mob in [implies]: mob.add(OldTex("?").next_to(mob, UP, SMALL_BUFF)) transformed_equation.parts_to_write = VGroup( T1, lp1, rp1, T2, lp2, rp2 ) transformed_equations.add(transformed_equation) corner_rect = self.corner_rect corner_rect.generate_target() group = VGroup(self.equations, transformed_equations) self.resize_corner_rect_to_mobjet(corner_rect.target, group) for array in [self.output_vect_label] + list(self.column_mobs): array.rect = SurroundingRectangle(array) array.rect.match_color(array.elements) self.play( MoveToTarget(corner_rect), Animation(self.equations), FadeOut(self.to_fade), LaggedStartMap(Write, implications), ) self.remove(self.input_vect_mob) self.apply_matrix(self.matrix, added_anims=[ Animation(VGroup(corner_rect, self.equations, implications)), MoveToTarget(moving_equations[0]), LaggedStartMap(FadeIn, transformed_equations[0].parts_to_write), FadeIn(self.column_mobs), ReplacementTransform( self.input_vect_mob.copy(), self.output_vect_mob) ]) self.play( MoveToTarget(moving_equations[1]), LaggedStartMap(FadeIn, transformed_equations[1].parts_to_write), path_arc=-30 * DEGREES, run_time=2 ) self.wait() # Show rectangles self.play( LaggedStartMap(ShowCreation, transformed_input_rects, lag_ratio=0.8), ShowCreation(self.output_vect_label.rect), ) for tbr, column_mob in zip(transformed_basis_rects, self.column_mobs): self.play( ShowCreation(tbr), ShowCreation(column_mob.rect), ) self.wait() self.play(FadeOut(VGroup( transformed_input_rects, transformed_basis_rects, self.output_vect_label.rect, *[cm.rect for cm in self.column_mobs] ))) # These computations assume plane is centered at ORIGIN output_vect = self.output_vect_mob.get_end() c1 = self.basis_vectors[0].get_end() c2 = self.basis_vectors[1].get_end() x_point = c1 * np.dot(output_vect, c1) / (get_norm(c1)**2) y_point = c2 * np.dot(output_vect, c2) / (get_norm(c2)**2) dashed_line_to_x = DashedLine(self.output_vect_mob.get_end(), x_point) dashed_line_to_y = DashedLine(self.output_vect_mob.get_end(), y_point) self.play(ShowCreation(dashed_line_to_x)) self.play(ShowCreation(dashed_line_to_y)) self.wait() # Helpers def resize_corner_rect_to_mobjet(self, rect, mobject): rect.stretch_to_fit_width( mobject.get_width() + MED_LARGE_BUFF + SMALL_BUFF) rect.stretch_to_fit_height( mobject.get_height() + MED_LARGE_BUFF + SMALL_BUFF) rect.to_corner(UL, buff=0) return rect class NotAtAllTrue(NotTheMostComputationallyEfficient): CONFIG = { "words": "Not at all \\\\ True", "word_height": 4, } class ShowDotProductChanging(LinearTransformationScene): CONFIG = { "matrix": [[2, -5.0 / 3], [-5.0 / 3, 2]], "v": [1, 2], "w": [2, 1], "v_label": "v", "w_label": "w", "v_color": YELLOW, "w_color": MAROON_B, "rhs1": "> 0", "rhs2": "< 0", "foreground_plane_kwargs": { "x_radius": 2 * FRAME_WIDTH, "y_radius": 2 * FRAME_HEIGHT, }, "equation_scale_factor": 1.5, } def construct(self): v_mob = self.add_vector(self.v, self.v_color, animate=False) w_mob = self.add_vector(self.w, self.w_color, animate=False) kwargs = { "transformation_name": "T", "at_tip": True, "animate": False, } v_label = self.add_transformable_label(v_mob, self.v_label, **kwargs) w_label = self.add_transformable_label(w_mob, self.w_label, **kwargs) start_equation = self.get_equation(v_label, w_label, self.rhs1) start_equation.to_corner(UR) self.play( Write(start_equation[0::2]), ReplacementTransform(v_label.copy(), start_equation[1]), ReplacementTransform(w_label.copy(), start_equation[3]), ) self.wait() self.add_foreground_mobject(start_equation) self.apply_matrix(self.matrix) self.wait() end_equation = self.get_equation(v_label, w_label, self.rhs2) end_equation.next_to(start_equation, DOWN, aligned_edge=RIGHT) self.play( FadeIn(end_equation[0]), ReplacementTransform( start_equation[2::2].copy(), end_equation[2::2], ), ReplacementTransform(v_label.copy(), end_equation[1]), ReplacementTransform(w_label.copy(), end_equation[3]), ) self.wait(2) def get_equation(self, v_label, w_label, rhs): equation = VGroup( v_label.copy(), OldTex("\\cdot"), w_label.copy(), OldTex(rhs), ) equation.arrange(RIGHT, buff=SMALL_BUFF) equation.add_to_back(BackgroundRectangle(equation)) equation.scale(self.equation_scale_factor) return equation class ShowDotProductChangingAwayFromZero(ShowDotProductChanging): CONFIG = { "matrix": [[2, 2], [0, -1]], "v": [1, 0], "w": [0, 1], "v_label": "x", "w_label": "y", "v_color": X_COLOR, "w_color": Y_COLOR, "rhs1": "= 0", "rhs2": "\\ne 0", } class OrthonormalWords(Scene): def construct(self): v_tex = "\\vec{\\textbf{v}}" w_tex = "\\vec{\\textbf{w}}" top_words = OldTex( "\\text{If }", "T(", v_tex, ")", "\\cdot", "T(", w_tex, ")", "=", v_tex, "\\cdot", w_tex, "\\text{ for all }", v_tex, "\\text{ and }", w_tex, ) top_words.set_color_by_tex_to_color_map({ v_tex: YELLOW, w_tex: MAROON_B, }) bottom_words = OldTexText( "$T$", "is", "``Orthonormal''" ) bottom_words.set_color_by_tex("Orthonormal", BLUE) words = VGroup(top_words, bottom_words) words.arrange(DOWN, buff=MED_LARGE_BUFF) for word in words: word.add_background_rectangle() words.to_edge(UP) self.play(Write(words)) self.wait() class ShowSomeOrthonormalTransformations(LinearTransformationScene): CONFIG = { "random_seed": 1, "n_angles": 7, } def construct(self): for x in range(self.n_angles): angle = TAU * np.random.random() - TAU / 2 matrix = rotation_matrix(angle, OUT)[:2, :2] if x in [2, 4]: matrix[:, 1] *= -1 self.apply_matrix(matrix, run_time=1) self.wait() class SolvingASystemWithOrthonormalMatrix(LinearTransformationScene): CONFIG = { "array_scale_factor": 0.6, } def construct(self): # Setup system angle = TAU / 12 matrix = np.array([ [np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)] ]) output_vect = [1, 2] symbolic_matrix = [ ["\\cos(30^\\circ)", "-\\sin(30^\\circ)"], ["\\sin(30^\\circ)", "\\cos(30^\\circ)"], ] system = LinearSystem( matrix=symbolic_matrix, output_vect=output_vect, matrix_config={ "h_buff": 2.5, "element_to_mobject": Tex, }, height=1.25, ) system.to_corner(UL) system.matrix_mobject.set_column_colors(X_COLOR, Y_COLOR) system.input_vect_mob.elements.set_color(WHITE) system_rect = BackgroundRectangle(system, buff=MED_SMALL_BUFF) matrix_brace = Brace(system.matrix_mobject, DOWN, buff=SMALL_BUFF) orthonomal_label = OldTexText("Orthonormal") orthonomal_label.set_color(WHITE) orthonomal_label.next_to(matrix_brace, DOWN, SMALL_BUFF) orthonomal_label.add_background_rectangle() # Input and output vectors output_vect_mob = self.get_vector(output_vect, color=OUTPUT_COLOR) output_vect_label = system.output_vect_mob.copy() output_vect_label.add_background_rectangle() output_vect_label.scale(self.array_scale_factor) output_vect_label.next_to( output_vect_mob.get_end(), RIGHT, buff=SMALL_BUFF) input_vect = np.dot(np.linalg.inv(matrix), output_vect) input_vect_mob = self.get_vector(input_vect, color=INPUT_COLOR) input_vect_label = OldTexText("Mystery input vector") input_vect_label.add_background_rectangle() input_vect_label.next_to(input_vect_mob.get_end(), RIGHT, SMALL_BUFF) input_vect_label.match_color(input_vect_mob) # Column arrays column_mobs = VGroup() for i, vect in zip(list(range(2)), [DR, DL]): elements = system.matrix_mobject.deepcopy().mob_matrix[:, i] column_mob = MobjectMatrix(elements) column_mob.add_background_rectangle() column_mob.scale(self.array_scale_factor) column_mob.next_to( self.get_vector(matrix[:, i]).get_end(), vect, buff=SMALL_BUFF ) column_mobs.add(column_mob) column_mobs[1].shift(SMALL_BUFF * UP) # Dot product lines x_point = self.plane.coords_to_point(input_vect[0], 0) y_point = self.plane.coords_to_point(0, input_vect[1]) input_dashed_lines = VGroup( DashedLine(input_vect_mob.get_end(), x_point), DashedLine(input_vect_mob.get_end(), y_point), ) output_dashed_lines = input_dashed_lines.copy() output_dashed_lines.apply_matrix(matrix) self.add_foreground_mobjects(system_rect, system) self.add_foreground_mobjects(matrix_brace, orthonomal_label) self.add_foreground_mobjects(output_vect_mob, output_vect_label) self.plane.set_stroke(width=2) self.apply_matrix(matrix) self.wait() self.play(LaggedStartMap(ShowCreation, output_dashed_lines)) self.play(*self.get_column_animations(system.matrix_mobject, column_mobs)) self.wait() self.remove(*output_dashed_lines) self.apply_inverse(matrix, added_anims=[ FadeOut(column_mobs), ReplacementTransform(output_vect_mob.copy(), input_vect_mob), ReplacementTransform( output_dashed_lines.copy(), input_dashed_lines), FadeIn(input_vect_label), ]) self.wait() self.remove(input_dashed_lines, input_vect_mob) self.apply_matrix(matrix, added_anims=[ FadeOut(input_vect_label), ReplacementTransform(input_vect_mob.copy(), output_vect_mob), ReplacementTransform(input_dashed_lines.copy(), output_dashed_lines), FadeIn(column_mobs), ]) # Write dot product equations equations = VGroup() for i in 0, 1: moving_output_vect_label = output_vect_label.copy() moving_column_mob = column_mobs[i].copy() moving_var = system.input_vect_mob.elements[i].copy() equation = VGroup( moving_var.generate_target(), OldTex("="), moving_output_vect_label.generate_target(), OldTex("\\cdot"), moving_column_mob.generate_target(use_deepcopy=True) ) equation.movers = VGroup( moving_var, moving_output_vect_label, moving_column_mob ) for element in moving_column_mob.target.get_family(): if not isinstance(element, Tex): continue tex_string = element.get_tex() if "sin" in tex_string or "cos" in tex_string: element.set_stroke(width=1) element.scale(1.25) equation.to_write = equation[1::2] equation[2].match_height(equation[4]) equation.arrange(RIGHT, buff=SMALL_BUFF) equation.background_rectangle = BackgroundRectangle(equation) equation.add_to_back(equation.background_rectangle) equations.add(equation) equations.arrange(DOWN, buff=MED_LARGE_BUFF) equations.scale(1.25) equations.to_corner(UR, buff=MED_SMALL_BUFF) equations_rect = BackgroundRectangle(equations, buff=MED_LARGE_BUFF) equations_rect.set_fill(opacity=0.9) for i, equation in enumerate(equations): anims = [ FadeIn(equation.background_rectangle), Write(equation.to_write), LaggedStartMap( MoveToTarget, equation.movers, path_arc=60 * DEGREES ) ] if i == 0: anims.insert(0, FadeIn(equations_rect)) self.play(*anims) self.wait() def get_column_animations(self, matrix_mobject, column_mobs): def get_kwargs(i): return { "rate_func": squish_rate_func(smooth, 0.4 * i, 0.6 + 0.4 * i), "run_time": 2, } return list(it.chain(*[ [ FadeIn(cm[0], **get_kwargs(i)), ReplacementTransform( matrix_mobject.brackets.copy(), cm.brackets, **get_kwargs(i) ), ReplacementTransform( VGroup(*matrix_mobject.mob_matrix[:, i]).copy(), cm.elements, **get_kwargs(i) ), ] for i, cm in enumerate(column_mobs) ])) class TransitionToParallelogramIdea(TeacherStudentsScene): def construct(self): teacher_words = OldTexText( "Now ask about \\\\ other geometric \\\\ views of", "$x$", "and", "$y$" ) teacher_words.set_color_by_tex_to_color_map({ "$x$": X_COLOR, "$y$": Y_COLOR, }) self.student_says( "But that's a super \\\\ specific case", target_mode="sassy", added_anims=[self.teacher.change, "guilty"] ) self.play_student_changes("confused", "sassy", "angry") self.wait() self.teacher_says( teacher_words, added_anims=[self.change_students(*["pondering"] * 3)] ) self.wait() class TransformingAreasYCoord(LinearTransformationScene): CONFIG = { # Determines whether x-coordinate or y-coordinate is computed "index": 1, "matrix": [[2, -1], [0, 1]], "input_vect": [3, 2], "array_scale_factor": 0.7, } def construct(self): self.init_matrix() self.init_plane() self.show_coord_parallelogram() self.transform_space() self.solve_for_coord() def init_matrix(self): self.matrix = np.array(self.matrix) def init_plane(self): self.plane.set_stroke(width=2) def show_coord_parallelogram(self): index = self.index non_index = (index + 1) % 2 input_vect = self.input_vect input_vect_mob = self.get_vector(input_vect, color=INPUT_COLOR) input_vect_label = Matrix(["x", "y"]) input_vect_label.add_background_rectangle() input_vect_label.scale(self.array_scale_factor) self.set_input_vect_label_position(input_vect_mob, input_vect_label) mystery_words = OldTexText("Mystery input vector") mystery_words.next_to(input_vect_label, RIGHT) mystery_words.add_background_rectangle() # Add basis vector labels basis_labels = self.basis_labels = VGroup() basis_vectors = self.basis_vectors chars = ["\\imath", "\\jmath"] directions = ["right", "left"] for basis, char, direction in zip(basis_vectors, chars, directions): label = self.get_vector_label( basis, "\\mathbf{\\hat{%s}}" % char, direction=direction ) self.basis_labels.add(label) ip = self.get_input_parallelogram(input_vect_mob) area_arrow_direction = 1.5 * DOWN + RIGHT if self.index == 0 else DR area_arrow = Vector( area_arrow_direction, color=WHITE, rectangular_stem_width=0.025, tip_length=0.2, ) area_arrow.shift(ip.get_center() - area_arrow.get_end() + SMALL_BUFF * DL) area_words = OldTex( "\\text{Area}", "=", "1", "\\times", ["x", "y"][index] ) area_words.next_to( area_arrow.get_start(), UL, SMALL_BUFF, submobject_to_align=area_words[0] ) area_words.set_color_by_tex_to_color_map({ "Area": YELLOW, "x": X_COLOR, "y": Y_COLOR, }) area_words.rect = BackgroundRectangle(area_words) origin = self.plane.coords_to_point(0, 0) unit_brace = Brace( Line(origin, basis_vectors[non_index].get_end()), [DOWN, LEFT][non_index], buff=SMALL_BUFF ) one = unit_brace.get_tex("1") one.add_background_rectangle() coord_brace = self.get_parallelogram_braces(ip)[index] self.add(input_vect_mob, input_vect_label) self.add(basis_labels) self.play( FadeIn(ip), Animation(VGroup(basis_vectors, input_vect_mob)) ) self.play( ShowCreationThenDestruction(SurroundingRectangle(basis_labels[non_index])), GrowArrow(self.basis_vectors[non_index].copy(), remover=True) ) self.play( ShowCreationThenDestruction(SurroundingRectangle(input_vect_label)), GrowArrow(input_vect_mob.copy(), remover=True), ) self.wait() self.play( FadeIn(area_words.rect), Write(area_words[:2]), GrowArrow(area_arrow), ) self.wait() self.play( FadeOut(basis_labels), GrowFromCenter(unit_brace), FadeIn(one), FadeIn(area_words[2]) ) self.wait() self.play( GrowFromCenter(coord_brace), FadeIn(coord_brace.label), FadeIn(area_words[3:]), ) self.wait() self.play( area_words.rect.stretch_to_fit_width, area_words[:3].get_width() + SMALL_BUFF, {"about_edge": LEFT}, FadeOut(area_words[2:4]), area_words[4].shift, (area_words[2].get_left()[0] - area_words[4].get_left()[0]) * RIGHT, Animation(area_words[:2]), ) area_words.remove(*area_words[2:4]) self.wait() # Run with me morty = Mortimer(height=2).flip() morty.to_corner(DL) randy = Randolph(height=2, color=BLUE_C).flip() randy.move_to(4 * RIGHT) randy.to_edge(DOWN) self.play(FadeIn(randy)) self.play(randy.change, "confused", ip) self.play(Blink(randy), FadeIn(morty)) self.play( PiCreatureSays(morty, "Run with \\\\ me here...", look_at=randy.eyes), randy.look_at, morty.eyes, ) self.play(Blink(morty)) self.play(FadeOut(VGroup(morty, morty.bubble, morty.bubble.content, randy))) # Signed area signed = OldTexText("Signed") signed.match_color(area_words[0]) signed.next_to(area_words, LEFT) brace_group = VGroup(coord_brace, coord_brace.label) def update_brace_group(brace_group): new_brace = self.get_parallelogram_braces(ip)[index] new_group = VGroup(new_brace, new_brace.label) Transform(brace_group, new_group).update(1) area_words.add_to_back(signed) self.play( area_words.rect.stretch_to_fit_width, area_words.get_width(), {"about_edge": RIGHT}, Write(signed), Animation(area_words), ) self.play( UpdateFromFunc( ip, lambda m: Transform(m, self.get_input_parallelogram(input_vect_mob)).update(1) ), input_vect_mob.rotate, np.pi, {"about_point": origin}, Animation(self.basis_vectors), UpdateFromFunc(brace_group, update_brace_group), UpdateFromFunc( input_vect_label, lambda ivl: self.set_input_vect_label_position(input_vect_mob, ivl) ), MaintainPositionRelativeTo(area_arrow, ip), MaintainPositionRelativeTo(area_words.rect, area_arrow), MaintainPositionRelativeTo(area_words, area_arrow), run_time=9, rate_func=there_and_back_with_pause, ) # Fade out unneeded bits self.play(LaggedStartMap(FadeOut, VGroup( unit_brace, one, coord_brace, coord_brace.label, ))) self.input_parallelogram = ip self.area_words = area_words self.area_arrow = area_arrow self.input_vect_mob = input_vect_mob self.input_vect_label = input_vect_label def transform_space(self): matrix = self.matrix ip = self.input_parallelogram area_words = self.area_words area_arrow = self.area_arrow input_vect_mob = self.input_vect_mob input_vect_label = self.input_vect_label basis_vectors = self.basis_vectors index = self.index non_index = (index + 1) % 2 apply_words = OldTexText("Apply") apply_words.add_background_rectangle() matrix_mobject = IntegerMatrix(self.matrix) matrix_mobject.set_column_colors(X_COLOR, Y_COLOR) matrix_mobject.add_background_rectangle() matrix_mobject.next_to(apply_words, RIGHT) matrix_brace = Brace(matrix_mobject, DOWN, buff=SMALL_BUFF) matrix_label = matrix_brace.get_tex("A") matrix_label.add_background_rectangle() apply_group = VGroup(apply_words, matrix_mobject, matrix_brace, matrix_label) apply_group.to_corner(UL, buff=MED_SMALL_BUFF) area_scale_words = OldTexText("All areas get scaled by", "$\\det(A)$") area_scale_words.scale(1.5) area_scale_words.move_to(2 * DOWN) area_scale_words.add_background_rectangle() blobs = VGroup( Circle(radius=0.5).move_to(2 * LEFT + UP), Square(side_length=1).rotate(TAU / 12).move_to(2 * UP + 0.5 * RIGHT), OldTex("\\pi").scale(3).move_to(3 * RIGHT) ) blobs.set_stroke(YELLOW, 3) blobs.set_fill(YELLOW, 0.3) # Initial transform self.add_transformable_mobject(ip) self.add(self.basis_vectors) self.add_vector(input_vect_mob, animate=False) self.play( Write(apply_words), FadeIn(matrix_mobject), GrowFromCenter(matrix_brace), Write(matrix_label), ) self.add_foreground_mobjects(apply_group) self.play(*list(map(FadeOut, [ area_words.rect, area_words, area_arrow, input_vect_label, ]))) self.apply_matrix(matrix) self.wait(2) self.apply_inverse(matrix, run_time=0) # Show many areas self.play( LaggedStartMap(DrawBorderThenFill, blobs), Write(area_scale_words) ) self.add_transformable_mobject(blobs) self.add_foreground_mobject(area_scale_words) self.apply_matrix(matrix) # Ask about parallelogram ip_copy = ip.copy() ip_copy.set_stroke(BLACK, 4) ip_copy.set_fill(BLACK, 0) q_marks = OldTex("???") q_marks.scale(1.5) q_marks.rect = BackgroundRectangle(q_marks) q_marks_group = VGroup(q_marks, q_marks.rect) q_marks_group.rotate(input_vect_mob.get_angle()) q_marks_group.move_to(ip) column_mobs = VGroup() for i, vect in zip(list(range(2)), [DOWN, LEFT]): column = matrix_mobject.deepcopy().mob_matrix[:, i] column_mob = MobjectMatrix(column) column_mob.scale(self.array_scale_factor) column_mob.next_to(basis_vectors[i].get_end(), vect) column_mob.add_background_rectangle() column_mobs.add(column_mob) column_mob = column_mobs[non_index] transformed_input_vect_label = VGroup(input_vect_label.copy()) transformed_input_vect_label.add_to_back(matrix_label.copy()) transformed_input_vect_label.arrange(RIGHT, buff=SMALL_BUFF) transformed_input_vect_label.next_to(input_vect_mob.get_end(), UP) self.play( ShowPassingFlash(ip_copy), FadeIn(q_marks.rect), Animation(ip), Animation(basis_vectors), Animation(input_vect_mob), Write(q_marks), LaggedStartMap(FadeOut, blobs), ) self.transformable_mobjects.remove(blobs) self.play( FadeIn(column_mob.background_rectangle), ReplacementTransform( matrix_mobject.brackets.copy(), column_mob.brackets ), ReplacementTransform( VGroup(*matrix_mobject.mob_matrix[:, non_index]).copy(), column_mob.elements ), ) self.wait() self.play( ReplacementTransform(matrix_label.copy(), transformed_input_vect_label[0]), FadeIn(transformed_input_vect_label[1]) ) self.wait(2) # Back to input state self.remove(q_marks.rect) self.apply_inverse(matrix, added_anims=[ FadeOut(q_marks), FadeOut(transformed_input_vect_label), FadeOut(column_mob), FadeIn(area_words.rect), FadeIn(area_words), FadeIn(area_arrow), ]) self.wait(2) # Show how parallelogram scales by det(A) self.apply_matrix(matrix, added_anims=[ UpdateFromFunc( area_arrow, lambda a: a.put_start_and_end_on( area_arrow.get_start(), ip.get_center() + SMALL_BUFF * DL ) ), Animation(area_words.rect), Animation(area_words), ]) det_A = area_scale_words.get_part_by_tex("det").copy() det_A.generate_target() det_A.target.scale(1.0 / 1.5) det_A.target.next_to( area_words[1:3], RIGHT, SMALL_BUFF, aligned_edge=DOWN, submobject_to_align=det_A.target[0] ) coord = area_words[-1] coord.generate_target() coord.target.next_to(det_A.target, RIGHT, SMALL_BUFF) self.play( area_words.rect.match_width, VGroup(area_words, coord.target), {"stretch": True, "about_edge": LEFT}, Animation(area_words), MoveToTarget(det_A), MoveToTarget(coord), ) self.wait(2) area_words.submobjects.insert(-1, det_A) self.area_scale_words = area_scale_words self.apply_group = apply_group def solve_for_coord(self): apply_group = self.apply_group area_words = self.area_words.copy() index = self.index non_index = (index + 1) % 2 # Setup rearrangement signed, area, equals, det, coord = area_words for part in area_words: part.add_background_rectangle() part.generate_target() apply_word, matrix_mobject, matrix_brace, matrix_label = apply_group h_line = Line(LEFT, RIGHT).match_width(det) frac = VGroup(area.target, h_line, det.target) frac.arrange(DOWN) coord_equation = VGroup(coord.target, equals.target, frac) equals.target.next_to(coord.target, RIGHT) frac.next_to(equals.target, RIGHT, submobject_to_align=h_line) coord_equation.next_to(ORIGIN, DOWN, buff=1.2) coord_equation.to_edge(LEFT) output_vect = np.dot(self.matrix, self.input_vect) new_matrix = np.array(self.matrix) new_matrix[:, self.index] = output_vect # Setup rhs frac_matrix_height = 1.5 matrix_mobject_copy = matrix_mobject.copy() matrix_mobject_copy.set_height(frac_matrix_height) denom_det_text = get_det_text(matrix_mobject_copy) top_matrix_mobject = IntegerMatrix(new_matrix) top_matrix_mobject.set_height(frac_matrix_height) top_matrix_mobject.set_column_colors(X_COLOR, Y_COLOR) VGroup(*top_matrix_mobject.mob_matrix[:, self.index]).set_color(MAROON_B) top_matrix_mobject.add_background_rectangle() num_det_text = get_det_text(top_matrix_mobject) rhs_h_line = Line(LEFT, RIGHT) rhs_h_line.match_width(num_det_text) rhs = VGroup( VGroup(num_det_text, top_matrix_mobject), rhs_h_line, VGroup(matrix_mobject_copy, denom_det_text) ) rhs.arrange(DOWN, buff=SMALL_BUFF) rhs_equals = OldTex("=") rhs_equals.next_to(h_line, RIGHT) rhs.next_to(rhs_equals, submobject_to_align=rhs_h_line) # Setup linear system output_vect_label = IntegerMatrix(output_vect) output_vect_label.elements.match_color(self.input_vect_mob) output_vect_label.scale(self.array_scale_factor) output_vect_label.add_background_rectangle() self.set_input_vect_label_position(self.input_vect_mob, output_vect_label) matrix_mobject.generate_target() system_input = Matrix(["x", "y"]) system_input.add_background_rectangle() system_output = output_vect_label.copy() system_output.generate_target() system_eq = OldTex("=") for array in system_input, system_output.target: array.match_height(matrix_mobject.target) system = VGroup( matrix_mobject.target, system_input, system_eq, system_output.target ) system.arrange(RIGHT, buff=SMALL_BUFF) system.to_corner(UL) # Rearrange self.play( FadeOut(self.area_scale_words), ShowCreation(h_line), *list(map(MoveToTarget, area_words[1:])), run_time=3 ) self.wait() self.play( ReplacementTransform(matrix_mobject.copy(), matrix_mobject_copy), Write(rhs_equals), Write(denom_det_text), ShowCreation(rhs_h_line) ) self.wait(2) # Show output coord self.play( FadeIn(output_vect_label.background_rectangle), ReplacementTransform( self.input_vect_mob.copy(), output_vect_label.elements, ), Write(output_vect_label.brackets), ) self.wait() self.play( FadeOut(apply_word), MoveToTarget(matrix_mobject), MaintainPositionRelativeTo(matrix_brace, matrix_mobject), MaintainPositionRelativeTo(matrix_label, matrix_mobject), ) self.play( FadeIn(system_input), FadeIn(system_eq), MoveToTarget(system_output), area_words.rect.stretch_to_fit_width, self.area_words[1:].get_width(), {"about_edge": RIGHT}, Animation(self.area_words[1:]), FadeOut(self.area_words[0]), ) self.wait() replaced_column = VGroup(*top_matrix_mobject.mob_matrix[:, self.index]) replaced_column.set_fill(opacity=0) self.play( ReplacementTransform(matrix_mobject_copy.copy(), top_matrix_mobject), ReplacementTransform(denom_det_text.copy(), num_det_text), ) self.wiggle_vector(self.basis_vectors[non_index]) self.wait() self.wiggle_vector(self.input_vect_mob) self.remove(replaced_column) self.play( Transform( output_vect_label.elements.copy(), replaced_column.copy().set_fill(opacity=1), remover=True ) ) replaced_column.set_fill(opacity=1) self.wait() # Circle equation equation = VGroup( area_words[1:], h_line, rhs_equals, rhs, ) equation_rect = SurroundingRectangle(equation) equation_rect.set_stroke(YELLOW, 3) equation_rect.set_fill(BLACK, 0.9) self.play( DrawBorderThenFill(equation_rect), Animation(equation) ) self.wait() # Helpers def get_input_parallelogram(self, input_vect_mob): input_vect = np.array(self.plane.point_to_coords(input_vect_mob.get_end())) matrix = self.matrix dim = matrix.shape[0] # Transofmration from unit square to input parallelogram square_to_ip = self.square_to_ip = np.identity(dim) square_to_ip[:, self.index] = np.array(input_vect) ip = self.get_unit_square() ip.apply_matrix(self.square_to_ip) if input_vect[self.index] < 0: ip.set_color(GOLD) return ip def get_parallelogram_braces(self, input_parallelogram): braces = VGroup(*[ Brace( input_parallelogram, vect, buff=SMALL_BUFF, min_num_quads=3, max_num_quads=3, ) for vect in (DOWN, RIGHT) ]) for brace, tex, color in zip(braces, "xy", [X_COLOR, Y_COLOR]): brace.label = brace.get_tex(tex, buff=SMALL_BUFF) brace.label.add_background_rectangle() brace.label.set_color(color) return braces def set_input_vect_label_position(self, input_vect_mob, input_vect_label): direction = np.sign(input_vect_mob.get_vector()) input_vect_label.next_to(input_vect_mob.get_end(), direction, buff=SMALL_BUFF) return input_vect_label def wiggle_vector(self, vector_mob): self.play( Rotate( vector_mob, 15 * DEGREES, about_point=ORIGIN, rate_func=wiggle, ) ) class TransformingAreasXCoord(TransformingAreasYCoord): CONFIG = { "index": 0, } class ThreeDDotVectorWithKHat(ExternallyAnimatedScene): pass class ZEqualsVDotK(Scene): def construct(self): equation = VGroup( OldTex("z"), OldTex("="), Matrix(["x", "y", "z"]), OldTex("\\cdot"), IntegerMatrix([0, 0, 1]), ) equation[2].elements.set_color_by_gradient(X_COLOR, Y_COLOR, Z_COLOR) equation[4].elements.set_color(BLUE) equation.arrange(RIGHT, buff=MED_SMALL_BUFF) equation.to_edge(LEFT) self.play(Write(equation)) self.wait() class InputParallelepipedAngledView(ExternallyAnimatedScene): pass class InputParallelepipedTopViewToSideView(ExternallyAnimatedScene): pass class ParallelepipedForXCoordinate(ExternallyAnimatedScene): pass class ParallelepipedForYCoordinate(ExternallyAnimatedScene): pass class ThreeDCoordinatesAsVolumes(Scene): def construct(self): colors = [X_COLOR, Y_COLOR, Z_COLOR] x, y, z = coords = VGroup(*list(map(Tex, "xyz"))) coords.set_color_by_gradient(*colors) matrix = IntegerMatrix(np.identity(3)) matrix.set_column_colors(*colors) det_text = get_det_text(matrix) equals = OldTex("=") equals.next_to(det_text[0], LEFT) equals.shift(SMALL_BUFF * DOWN) coords.next_to(equals, LEFT) columns = VGroup(*[ VGroup(*matrix.mob_matrix[:, i]) for i in range(3) ]) coord_column = coords.copy() for coord, m_elem in zip(coord_column, columns[2]): coord.move_to(m_elem) coord_column.set_color(WHITE) coord_column[2].set_color(BLUE) coord_column.generate_target() self.play(LaggedStartMap(FadeIn, VGroup( z, equals, det_text, matrix.brackets, VGroup(*matrix.mob_matrix[:, :2].flatten()), coord_column ))) self.wait(2) coord_column.target.move_to(columns[1]) coord_column.target.set_color_by_gradient(WHITE, Y_COLOR, WHITE) self.play( MoveToTarget(coord_column, path_arc=np.pi), FadeOut(columns[1]), FadeIn(columns[2]), FadeInFromDown(y), z.shift, UP, z.fade, 1, ) self.wait(2) coord_column.target.move_to(columns[0]) coord_column.target.set_color_by_gradient(X_COLOR, WHITE, WHITE) self.play( MoveToTarget(coord_column, path_arc=np.pi), FadeOut(columns[0]), FadeIn(columns[1]), FadeInFromDown(x), y.shift, UP, y.fade, 1, ) self.wait(2) class WriteCramersRule(Scene): def construct(self): words = OldTexText("``Cramer's Rule''") words.set_width(FRAME_WIDTH - LARGE_BUFF) words.add_background_rectangle() self.play(Write(words)) self.wait() class CramersYEvaluation(Scene): def construct(self): frac = OldTex("{(2)(2) - (4)(0) \\over (2)(1) - (-1)(0)}")[0] VGroup(frac[1], frac[11], frac[15], frac[26]).set_color(GREEN) VGroup(frac[4], frac[8]).set_color(MAROON_B) VGroup(frac[18], frac[22], frac[23]).set_color(RED) group = VGroup( OldTex("="), frac, OldTex("= \\frac{4}{2}"), OldTex("=2") ) group.arrange(RIGHT) self.add(group) self.wait(1) # Largely copy-pasted. Not great, but what are you gonna do. class CramersXEvaluation(Scene): def construct(self): frac = OldTex("{(4)(1) - (-1)(2) \\over (2)(1) - (-1)(0)}")[0] VGroup(frac[1], frac[12]).set_color(MAROON_B) VGroup(frac[4], frac[8], frac[9]).set_color(RED) VGroup(frac[16], frac[27]).set_color(GREEN) VGroup(frac[19], frac[23], frac[24]).set_color(RED) group = VGroup( OldTex("="), frac, OldTex("= \\frac{6}{2}"), OldTex("=3") ) group.arrange(RIGHT) group.add_to_back(BackgroundRectangle(group)) self.add(group) self.wait(1) class FourPlusTwo(Scene): def construct(self): p1 = OldTex("(4)(1)") p2 = OldTex("-(-1)(2)") p2.next_to(p1, RIGHT, SMALL_BUFF) b1 = Brace(p1, UP) b2 = Brace(p2, UP) t1 = b1.get_tex("4", buff=SMALL_BUFF) t2 = b2.get_tex("+2", buff=SMALL_BUFF) for b, t in (b1, t1), (b2, t2): t.set_stroke(BLACK, 3, background=True) self.play( GrowFromCenter(b), Write(t) ) self.wait() class Equals2(Scene): def construct(self): self.add(OldTex("=2").add_background_rectangle()) self.wait() class Equals3(Scene): def construct(self): self.add(OldTex("=3").add_background_rectangle()) self.wait() class Introduce3DSystem(SetupSimpleSystemOfEquations): CONFIG = { "matrix": [[3, 2, -7], [1, 2, -4], [4, 0, 1]], "output_vect": [4, 2, 5], "compare_to_big_system": False, "transition_to_geometric_view": False, } def construct(self): self.remove_grid() self.introduce_system() self.from_system_to_matrix() class MysteryInputLabel(Scene): def construct(self): brace = Brace(Line(ORIGIN, RIGHT), DOWN) text = brace.get_text("Mystery input") self.play( GrowFromCenter(brace), Write(text) ) self.wait() class ThinkItThroughYourself(TeacherStudentsScene): def construct(self): self.teacher_says( "Try thinking \\\\ it through!", target_mode="hooray" ) self.play_all_student_changes("pondering") self.wait(4) class TransformParallelepipedWithoutGrid(ExternallyAnimatedScene): pass class TransformParallelepipedWithGrid(ExternallyAnimatedScene): pass class AreYouPausingAndPondering(TeacherStudentsScene): def construct(self): self.teacher_says( "Are you pausing \\\\ and pondering?", target_mode="sassy", added_anims=[self.change_students(*3 * ["guilty"])] ) self.wait() self.play_all_student_changes( "thinking", added_anims=[ RemovePiCreatureBubble(self.teacher, target_mode="raise_right_hand") ], look_at=self.screen ) self.wait(6) class Thumbnail(TransformingAreasYCoord, MovingCameraScene): CONFIG = { "background_plane_kwargs": { "y_max": 6, }, } def setup(self): TransformingAreasYCoord.setup(self) MovingCameraScene.setup(self) def construct(self): self.matrix = np.array(self.matrix) vect = self.add_vector([1, 1.5], color=MAROON_B) ip = self.get_input_parallelogram(vect) self.add_transformable_mobject(ip) self.apply_transposed_matrix([[2, -0.5], [1, 2]]) self.square.set_fill(opacity=0.7) self.square.set_sheen(0.75, UR) self.camera_frame.shift(UP) words = OldTexText("Cramer's", "rule") words.scale(3) words.set_stroke(BLACK, 6, background=True) words.to_edge(UP, buff=-MED_LARGE_BUFF) words.add_background_rectangle() self.add(words)
from manim_imports_ext import * class HoldUpMultivariableChainRule(TeacherStudentsScene): def construct(self): title = OldTexText("Multivariable chain rule") title.to_edge(UP, buff=MED_SMALL_BUFF) screen = ScreenRectangle() screen.next_to(title, DOWN) morty = self.teacher self.add(title) self.play( morty.change, "raise_right_hand", FadeInFromDown(screen) ) self.play_all_student_changes( "confused", look_at=screen ) self.look_at(screen) self.wait(10) class ComputationalNetwork(MovingCameraScene): CONFIG = { "x_color": YELLOW, "f_color": BLUE, "g_color": GREEN, "h_color": RED, } def construct(self): self.draw_network() self.walk_through_parts() self.write_dh_dx_goal() self.feed_forward_input() self.compare_x_and_h_wiggling() self.expand_out_h_as_function_of_x() self.show_four_derivatives() self.show_chain_rule() self.talk_through_mvcr_parts() self.plug_in_expressions() self.plug_in_values() self.discuss_meaning_of_result() def draw_network(self): x = OldTex("x") f_formula = OldTex("f", "=", "x", "^2") g_formula = OldTex("g", "=", "\\cos(\\pi", "x", ")") h_formula = OldTex("h", "=", "f", "^2", "g") self.tex_to_color_map = { "x": self.x_color, "f": self.f_color, "g": self.g_color, "h": self.h_color, } formulas = VGroup(x, f_formula, g_formula, h_formula) formula_groups = VGroup() for formula in formulas: formula.box = SurroundingRectangle(formula) formula.box.set_color(WHITE) formula.group = VGroup(formula, formula.box) formula.set_color_by_tex_to_color_map( self.tex_to_color_map ) formula_groups.add(formula.group) f_formula.box.match_width( g_formula.box, stretch=True, about_edge=LEFT ) fg_group = VGroup(f_formula.group, g_formula.group) fg_group.arrange(DOWN, buff=LARGE_BUFF) fg_group.to_edge(UP) x.group.next_to(fg_group, LEFT, buff=2) h_formula.group.next_to(fg_group, RIGHT, buff=2) xf_line = Line(x.box.get_right(), f_formula.box.get_left()) xg_line = Line(x.box.get_right(), g_formula.box.get_left()) fh_line = Line(f_formula.box.get_right(), h_formula.box.get_left()) gh_line = Line(g_formula.box.get_right(), h_formula.box.get_left()) graph_edges = VGroup( xf_line, xg_line, fh_line, gh_line ) self.play( Write(x), FadeIn(x.box), ) self.play( ShowCreation(xf_line), ShowCreation(xg_line), ReplacementTransform(x.box.copy(), f_formula.box), ReplacementTransform(x.box.copy(), g_formula.box), ) self.play( Write(f_formula), Write(g_formula), ) self.play( ShowCreation(fh_line), ShowCreation(gh_line), ReplacementTransform(f_formula.box.copy(), h_formula.box), ReplacementTransform(g_formula.box.copy(), h_formula.box), ) self.play(Write(h_formula)) self.wait() network = VGroup(formula_groups, graph_edges) self.set_variables_as_attrs( x, f_formula, g_formula, h_formula, xf_line, xg_line, fh_line, gh_line, formulas, formula_groups, graph_edges, network ) def walk_through_parts(self): x = self.x f_formula = self.f_formula g_formula = self.g_formula h_formula = self.h_formula def indicate(mob): return ShowCreationThenDestructionAround( mob, surrounding_rectangle_config={ "buff": 0.5 * SMALL_BUFF, "color": mob.get_color() } ) for formula in f_formula, g_formula: self.play(indicate(formula[0])) self.play(ReplacementTransform( x.copy(), formula.get_parts_by_tex("x"), path_arc=PI / 3 )) self.wait() self.play(indicate(h_formula[0])) self.play(ReplacementTransform( f_formula[0].copy(), h_formula.get_part_by_tex("f"), path_arc=PI / 3 )) self.play(ReplacementTransform( g_formula[0].copy(), h_formula.get_part_by_tex("g"), path_arc=PI / 3 )) self.wait() def write_dh_dx_goal(self): deriv = OldTex( "{dh", "\\over", "dx}", "(", "2", ")" ) deriv.set_color_by_tex_to_color_map( self.tex_to_color_map ) deriv.scale(1.5) deriv.move_to(DOWN) self.play(FadeInFromDown(deriv[:3])) self.play(ShowCreationThenDestructionAround(deriv[:3])) self.wait(2) self.play(Write(deriv[3:])) self.wait() self.dh_dx_at_two = deriv def feed_forward_input(self): formula_groups = self.formula_groups x, f_formula, g_formula, h_formula = self.formulas dh_dx_at_two = self.dh_dx_at_two values = [2, 4, 1, 16] value_labels = VGroup() for formula_group, value in zip(formula_groups, values): label = OldTex("=", str(value)) eq, value_mob = label eq.rotate(90 * DEGREES) eq.next_to(value_mob, UP, SMALL_BUFF) var = formula_group[0][0] label[1].match_color(var) # label.next_to(formula_group, DOWN, SMALL_BUFF) label.next_to(var, DOWN, SMALL_BUFF) eq.add_background_rectangle(buff=SMALL_BUFF, opacity=1) value_labels.add(label) x_val_label, f_val_label, g_val_label, h_val_label = value_labels two, four, one, sixteen = [vl[1] for vl in value_labels] self.play( ReplacementTransform( dh_dx_at_two.get_part_by_tex("2").copy(), two, ), Write(x_val_label[0]) ) self.wait() two_copy1 = two.copy() two_copy2 = two.copy() four_copy = four.copy() one_copy = one.copy() x_in_f = f_formula.get_part_by_tex("x") x_in_g = g_formula.get_part_by_tex("x") f_in_h = h_formula.get_part_by_tex("f") g_in_h = h_formula.get_part_by_tex("g") self.play( two_copy1.move_to, x_in_f, DOWN, x_in_f.set_fill, {"opacity": 0}, ) self.wait() self.play(Write(f_val_label)) self.wait() self.play( two_copy2.move_to, x_in_g, DOWN, x_in_g.set_fill, {"opacity": 0}, ) self.wait() self.play(Write(g_val_label)) self.wait() self.play( four_copy.move_to, f_in_h, DOWN, f_in_h.set_fill, {"opacity": 0}, ) self.play( one_copy.move_to, g_in_h, DOWN, g_in_h.set_fill, {"opacity": 0}, ) self.wait() self.play(Write(h_val_label)) self.wait() self.value_labels = value_labels self.revert_to_formula_animations = [ ApplyMethod(term.set_fill, {"opacity": 1}) for term in (x_in_f, x_in_g, f_in_h, g_in_h) ] + [ FadeOut(term) for term in (two_copy1, two_copy2, four_copy, one_copy) ] def compare_x_and_h_wiggling(self): x_val = self.value_labels[0][1] h_val = self.value_labels[3][1] x_line = NumberLine( x_min=0, x_max=4, include_numbers=True, numbers_to_show=[0, 2, 4], unit_size=0.75, ) x_line.next_to( x_val, DOWN, LARGE_BUFF, aligned_edge=RIGHT ) h_line = NumberLine( x_min=0, x_max=32, include_numbers=True, numbers_with_elongated_ticks=[0, 16, 32], numbers_to_show=[0, 16, 32], tick_frequency=1, tick_size=0.05, unit_size=1.0 / 12, ) h_line.next_to( h_val, DOWN, LARGE_BUFF, aligned_edge=LEFT ) x_dot = Dot(color=self.x_color) x_dot.move_to(x_line.number_to_point(2)) x_arrow = Arrow(self.x.get_bottom(), x_dot.get_top()) x_arrow.match_color(x_dot) h_dot = Dot(color=self.h_color) h_dot.move_to(h_line.number_to_point(16)) h_arrow = Arrow(self.h_formula[0].get_bottom(), h_dot.get_top()) h_arrow.match_color(h_dot) self.play( ShowCreation(x_line), ShowCreation(h_line), ) self.play( GrowArrow(x_arrow), GrowArrow(h_arrow), ReplacementTransform(x_val.copy(), x_dot), ReplacementTransform(h_val.copy(), h_dot), ) self.wait() for x in range(2): self.play( x_dot.shift, 0.25 * RIGHT, h_dot.shift, 0.35 * RIGHT, rate_func=wiggle, run_time=1, ) self.set_variables_as_attrs( x_line, h_line, x_dot, h_dot, x_arrow, h_arrow, ) def expand_out_h_as_function_of_x(self): self.play(*self.revert_to_formula_animations) deriv = self.dh_dx_at_two expanded_formula = OldTex( "h = x^4 \\cos(\\pi x)", tex_to_color_map=self.tex_to_color_map ) expanded_formula.move_to(deriv) cross = Cross(expanded_formula) self.play( FadeInFromDown(expanded_formula), deriv.scale, 1.0 / 1.5, deriv.shift, DOWN, ) self.wait() self.play(ShowCreation(cross)) self.wait() self.play( FadeOut(VGroup(expanded_formula, cross)), deriv.shift, UP, ) for edge in self.graph_edges: self.play(ShowCreationThenDestruction( edge.copy().set_stroke(YELLOW, 6) )) def show_four_derivatives(self): lines = self.graph_edges xf_line, xg_line, fh_line, gh_line = lines df_dx = OldTex("df", "\\over", "dx") dg_dx = OldTex("dg", "\\over", "dx") dh_df = OldTex("\\partial h", "\\over", "\\partial f") dh_dg = OldTex("\\partial h", "\\over", "\\partial g") derivatives = VGroup(df_dx, dg_dx, dh_df, dh_dg) df_dx.next_to(xf_line.get_center(), UP, SMALL_BUFF) dg_dx.next_to(xg_line.get_center(), DOWN, SMALL_BUFF) dh_df.next_to(fh_line.get_center(), UP, SMALL_BUFF) dh_dg.next_to(gh_line.get_center(), DOWN, SMALL_BUFF) partial_terms = VGroup( dh_df[0][0], dh_df[2][0], dh_dg[0][0], dh_dg[2][0], ) partial_term_rects = VGroup(*[ SurroundingRectangle(pt, buff=0.05) for pt in partial_terms ]) partial_term_rects.set_stroke(width=0) partial_term_rects.set_fill(TEAL, 0.5) self.play(FadeOut(self.value_labels)) for derivative in derivatives: derivative.set_color_by_tex_to_color_map(self.tex_to_color_map) derivative.add_to_back(derivative.copy().set_stroke(BLACK, 5)) self.play(FadeInFromDown(derivative)) self.wait() self.play( LaggedStartMap(FadeIn, partial_term_rects), Animation(derivatives) ) self.wait() self.play( LaggedStartMap(FadeOut, partial_term_rects), Animation(derivatives) ) self.derivatives = derivatives def show_chain_rule(self): dh_dx_at_two = self.dh_dx_at_two dh_dx = dh_dx_at_two[:3] at_two = dh_dx_at_two[3:] derivatives = self.derivatives.copy() df_dx, dg_dx, dh_df, dh_dg = derivatives frame = self.camera_frame self.play( frame.shift, 3 * UP, dh_dx.to_edge, UP, dh_dx.shift, 3 * LEFT + 3 * UP, at_two.set_fill, {"opacity": 0}, ) for deriv in derivatives: deriv.generate_target() rhs = VGroup( OldTex("="), df_dx.target, dh_df.target, OldTex("+"), dg_dx.target, dh_dg.target ) rhs.arrange( RIGHT, buff=2 * SMALL_BUFF, ) rhs.next_to(dh_dx, RIGHT) for deriv in derivatives: y = rhs[0].get_center()[1] alt_y = deriv.target[2].get_center()[1] deriv.target.shift((y - alt_y) * UP) self.play( Write(rhs[::3]), LaggedStartMap(MoveToTarget, derivatives) ) self.wait() self.chain_rule_derivatives = derivatives self.chain_rule_rhs = rhs def talk_through_mvcr_parts(self): derivatives = self.derivatives cr_derivatives = self.chain_rule_derivatives df_dx, dg_dx, dh_df, dh_dg = cr_derivatives df, dx1 = df_dx[1::2] dg, dx2 = dg_dx[1::2] del_h1, del_f = dh_df[1::2] del_h2, del_g = dh_dg[1::2] terms = VGroup(df, dx1, dg, dx2, del_h1, del_f, del_h2, del_g) for term in terms: term.rect = SurroundingRectangle( term, buff=0.5 * SMALL_BUFF, stroke_width=0, fill_color=TEAL, fill_opacity=0.5 ) for derivative in derivatives: derivative.rect = SurroundingRectangle( derivative, color=TEAL ) del_h_sub_f = OldTex("f") del_h_sub_f.scale(0.5) del_h_sub_f.next_to(del_h1.get_corner(DR), RIGHT, buff=0) del_h_sub_f.set_color(self.f_color) lines = self.graph_edges top_lines = lines[::2].copy() bottom_lines = lines[1::2].copy() for group in top_lines, bottom_lines: group.set_stroke(YELLOW, 6) self.add_foreground_mobjects(cr_derivatives) rect = dx1.rect.copy() rect.save_state() rect.scale(3) rect.set_fill(opacity=0) self.play( rect.restore, FadeIn(derivatives[0].rect) ) self.wait() self.play(Transform(rect, df.rect)) self.wait() self.play( rect.replace, df_dx, {"stretch": True}, rect.scale, 1.1, ) self.wait() self.play( Transform(rect, del_f.rect), FadeOut(derivatives[0].rect), FadeIn(derivatives[2].rect), ) self.wait() self.play(Transform(rect, del_h1.rect)) self.wait() self.play(ReplacementTransform( del_f[1].copy(), del_h_sub_f, path_arc=PI, )) self.wait() self.play( del_h_sub_f.shift, UR, del_h_sub_f.fade, 1, rate_func=running_start, remover=True ) self.wait() self.play( Transform(rect, del_f.rect), ReplacementTransform(rect.copy(), df.rect), ) self.wait() for x in range(3): self.play(ShowCreationThenDestruction( top_lines, lag_ratio=1, )) self.wait() self.play( rect.replace, cr_derivatives[1::2], {"stretch": True}, rect.scale, 1.1, FadeOut(df.rect), FadeOut(derivatives[2].rect), FadeIn(derivatives[1].rect), FadeIn(derivatives[3].rect), ) self.wait() self.play( Transform(rect, dg.rect), FadeOut(derivatives[3].rect) ) self.wait() self.play(Transform(rect, dx2.rect)) self.wait() self.play( Transform(rect, del_h2.rect), FadeOut(derivatives[1].rect), FadeIn(derivatives[3].rect), ) self.wait() self.play(Transform(rect, del_g.rect)) self.wait() self.play( rect.replace, cr_derivatives, {"stretch": True}, rect.scale, 1.1, FadeOut(derivatives[3].rect) ) for x in range(3): self.play(*[ ShowCreationThenDestruction( group, lag_ratio=1, ) for group in (top_lines, bottom_lines) ]) self.wait() self.play(FadeOut(rect)) self.remove_foreground_mobject(cr_derivatives) def plug_in_expressions(self): lhs = VGroup( self.dh_dx_at_two[:3], self.chain_rule_rhs[::3], self.chain_rule_derivatives, ) lhs.generate_target() lhs.target.to_edge(LEFT) df_dx, dg_dx, dh_df, dh_dg = self.chain_rule_derivatives formulas = self.formulas x, f_formula, g_formula, h_formula = formulas full_derivative = OldTex( "=", "(", "2", "x", ")", "(", "2", "f", "g", ")", "+", "(", "-\\sin(", "\\pi", "x", ")", "\\pi", ")", "(", "f", "^2", ")" ) full_derivative.next_to(lhs.target, RIGHT) full_derivative.set_color_by_tex_to_color_map( self.tex_to_color_map ) self.play(MoveToTarget(lhs)) self.play(Write(full_derivative[0])) # df/dx self.play( f_formula.shift, UP, df_dx.shift, 0.5 * DOWN ) self.play( ReplacementTransform( f_formula[2:].copy(), full_derivative[2:4], ), FadeIn(full_derivative[1:5:3]) ) self.wait() self.play( f_formula.shift, DOWN, df_dx.shift, 0.5 * UP ) self.wait() # dg/dx self.play( g_formula.shift, 0.75 * UP, dg_dx.shift, 0.5 * DOWN ) self.play( ReplacementTransform( g_formula[2:].copy(), full_derivative[12:17], ), FadeIn(full_derivative[11:18:6]), Write(full_derivative[10]), ) self.wait() self.play( g_formula.shift, 0.75 * DOWN, dg_dx.shift, 0.5 * UP ) self.wait() # dh/df self.play( h_formula.shift, UP, dh_df.shift, 0.5 * DOWN ) self.wait() self.play( ReplacementTransform( h_formula[2:].copy(), full_derivative[6:9], ), FadeIn(full_derivative[5:10:4]) ) self.wait() self.play( dh_df.shift, 0.5 * UP ) # dh/dg self.play( dh_dg.shift, 0.5 * DOWN, ) self.wait() self.play( ReplacementTransform( h_formula[2:].copy(), full_derivative[19:21], ), FadeIn(full_derivative[18:22:3]) ) self.wait() self.play( h_formula.shift, DOWN, dh_dg.shift, 0.5 * UP ) self.wait() self.full_derivative = full_derivative def plug_in_values(self): full_derivative = self.full_derivative value_labels = self.value_labels rhs = OldTex( """ = (2 \\cdot 2) (2 \\cdot 4 \\cdot 1) + (-\\sin(\\pi 2)\\pi)(4^2) """, tex_to_color_map={ "2": self.x_color, "4": self.f_color, "1": self.g_color, "^2": WHITE, } ) rhs.next_to(full_derivative, DOWN, aligned_edge=LEFT) result = OldTex("=", "32", "+", "0") result.next_to(rhs, DOWN, aligned_edge=LEFT) self.play(LaggedStartMap(Write, value_labels)) self.wait() self.play(ReplacementTransform( full_derivative.copy(), rhs, lag_ratio=0.5, run_time=2 )) self.wait() self.play(Write(result)) self.wait() def discuss_meaning_of_result(self): x_dot = self.x_dot h_dot = self.h_dot for x in range(3): self.play( x_dot.shift, 0.25 * RIGHT, h_dot.shift, RIGHT, run_time=2, rate_func=lambda t: wiggle(t, 4) ) self.wait()
# -*- coding: utf-8 -*- from manim_imports_ext import * ###### Ben's stuff ######## RADIUS = 2 RADIUS_BUFF_HOR = 1.3 RADIUS_BUFF_VER = 0.5 RADIUS_COLOR = BLUE CIRCUM_COLOR = YELLOW DECIMAL_WIDTH = 0.5 HIGHLIGHT_COLOR = YELLOW # Warning, this file uses ContinualChangingDecimal, # which has since been been deprecated. Use a mobject # updater instead class ArcLengthChange(Animation): def __init__(self, mobject = None, new_angle = TAU/3, **kwargs): self.old_angle = mobject.angle self.start_angle = mobject.start_angle self.new_angle = new_angle Animation.__init__(self,mobject,**kwargs) def interpolate_mobject(self,alpha): angle = interpolate(self.old_angle, self.new_angle, alpha) self.mobject.angle = angle self.mobject.init_points() class LabelTracksLine(Animation): def __init__(self, mobject = None, line = None, buff = 0.2, **kwargs): self.line = line self.buff = buff Animation.__init__(self,mobject,**kwargs) def interpolate_mobject(self,alpha): line_center = self.line.get_center() line_end = self.line.get_points()[-1] v = line_end - line_center v = v/get_norm(v) w = np.array([-v[1],v[0],0]) self.mobject.move_to(line_center + self.buff * w) class CircleConstants(Scene): def radial_label_func(self,a,b,theta): theta2 = theta % TAU slope = (a-b)/(TAU/4) if theta2 < TAU/4: x = a - slope * theta2 elif theta < TAU/2: x = b + slope * (theta2 - TAU/4) elif theta < 3*TAU/4: x = a - slope * (theta2 - TAU/2) else: x = b + slope * (theta2 - 3*TAU/4) return x def construct(self): self.setup_circle() self.change_arc_length(0.004) self.pi_equals.next_to(self.decimal, LEFT) self.wait() self.change_arc_length(TAU/2) self.wait() self.change_arc_length(TAU) self.wait() self.change_arc_length(TAU/4) self.wait() self.change_arc_length(TAU/2) self.wait() def setup_circle(self): self.circle_arc = Arc(angle = 0.004, radius = RADIUS) self.radius = Line(ORIGIN, RADIUS * RIGHT) self.radius.set_color(RADIUS_COLOR) self.circle_arc.set_color(CIRCUM_COLOR) self.pi_equals = OldTex("\pi\\approx", color = CIRCUM_COLOR) self.decimal = DecimalNumber(0, color = CIRCUM_COLOR) self.decimal.next_to(self.pi_equals, RIGHT, buff = 0.25) self.circum_label = VGroup(self.pi_equals, self.decimal) self.circum_label.next_to(self.radius, RIGHT, buff = RADIUS_BUFF_HOR) self.one = OldTex("1", color = RADIUS_COLOR) self.one.next_to(self.radius, UP) self.play(ShowCreation(self.radius), FadeIn(self.one)) self.play( ShowCreation(self.circle_arc), Write(self.pi_equals), Write(self.decimal) ) def change_arc_length(self, new_angle): def decimal_position_update_func(decimal): angle = decimal.number max_radius = RADIUS + RADIUS_BUFF_HOR min_radius = RADIUS + RADIUS_BUFF_VER label_radius = self.radial_label_func(max_radius, min_radius, angle) label_center = label_radius * np.array([np.cos(angle), np.sin(angle),0]) label_center += 0.5 * RIGHT # label_center += pi_eq_stencil.get_width() * RIGHT # print "label_center = ", label_center decimal.move_to(label_center) self.play( Rotate(self.radius, new_angle - self.circle_arc.angle, about_point = ORIGIN), ArcLengthChange(self.circle_arc,new_angle), ChangeDecimalToValue( self.decimal, new_angle, position_update_func = decimal_position_update_func ), #MaintainPositionRelativeTo(self.one, self.radius), MaintainPositionRelativeTo(self.pi_equals, self.decimal), LabelTracksLine(self.one,self.radius, buff = 0.5), run_time = 3, ) self.wait(2) class AnalysisQuote(Scene): def construct(self): text = OldTexText('``We therefore set the radius of \\\\'\ 'the circle\dots to be = 1, and \dots\\\\'\ 'through approximations the \\\\'\ 'semicircumference of said circle \\\\'\ 'has been found to be $= 3.14159\dots$,\\\\'\ 'for which number, for the sake of \\\\'\ 'brevity, I will write $\pi$\dots"', alignment = '') for char in text.submobjects[12:24]: char.set_fill(HIGHLIGHT_COLOR) for char in text.submobjects[42:44]: char.set_fill(HIGHLIGHT_COLOR) for char in text.submobjects[75:92]: char.set_fill(HIGHLIGHT_COLOR) for char in text.submobjects[120:131]: char.set_fill(HIGHLIGHT_COLOR) text.submobjects[-5].set_fill(HIGHLIGHT_COLOR) text.to_edge(LEFT, buff = 1) self.play(LaggedStartMap(FadeIn,text), run_time = 5) self.wait() self.play(FadeOut(text)) self.wait() class BernoulliQuote(Scene): def construct(self): text = OldTexText('``Your most profound investigation of the series \\\\'\ '$1+{1\over 4}+{1\over 9}+{1\over 16} + $ etc., which I had found to be \\\\'\ 'one sixth of the square of $\pi$ itself\dots, not only\\\\'\ ' gave me the greatest pleasure, but also renown \\\\'\ 'among the whole Academy of St.\ Petersburg."') text.submobjects[88].set_fill(HIGHLIGHT_COLOR) for char in text.submobjects[41:60]: char.set_fill(HIGHLIGHT_COLOR) for char in text.submobjects[79:107]: char.set_fill(HIGHLIGHT_COLOR) for char in text.submobjects[127:143]: char.set_fill(HIGHLIGHT_COLOR) for char in text.submobjects[151:157]: char.set_fill(HIGHLIGHT_COLOR) self.play(LaggedStartMap(FadeIn,text), run_time = 5) self.wait() self.play(FadeOut(text)) self.wait class EulerSignature(Scene): def construct(self): sig = SVGMobject(file_name = "euler-signature") self.play( Write(sig, run_time = 5) ) ########################### RESOURCE_DIR = os.path.join(MEDIA_DIR, "3b1b_videos", "π Day 2018", "images") def get_image(name): return ImageMobject(os.path.join(RESOURCE_DIR, name)) def get_circle_drawing_terms(radius = 1, positioning_func = lambda m : m.center()): circle = Circle(color = YELLOW, radius = 1.25) positioning_func(circle) radius = Line(circle.get_center(), circle.get_points()[0]) radius.set_color(WHITE) one = OldTex("1") one.scale(0.75) one_update = UpdateFromFunc( one, lambda m : m.move_to( radius.get_center() + \ 0.25*rotate_vector(radius.get_vector(), TAU/4) ), ) decimal = DecimalNumber(0, num_decimal_places = 4, show_ellipsis = True) decimal.scale(0.75) def reposition_decimal(decimal): vect = radius.get_vector() unit_vect = vect/get_norm(vect) angle = radius.get_angle() alpha = (-np.cos(2*angle) + 1)/2 interp_length = interpolate(decimal.get_width(), decimal.get_height(), alpha) buff = interp_length/2 + MED_SMALL_BUFF decimal.move_to(radius.get_end() + buff*unit_vect) decimal.shift(UP*decimal.get_height()/2) return decimal kwargs = {"run_time" : 3, "rate_func" : bezier([0, 0, 1, 1])} changing_decimal = ChangingDecimal( decimal, lambda a : a*TAU, position_update_func = reposition_decimal, **kwargs ) terms = VGroup(circle, radius, one, decimal) generate_anims1 = lambda : [ShowCreation(radius), Write(one)] generate_anims2 = lambda : [ ShowCreation(circle, **kwargs), Rotating(radius, about_point = radius.get_start(), **kwargs), changing_decimal, one_update, ] return terms, generate_anims1, generate_anims2 ## class PiTauDebate(PiCreatureScene): def construct(self): pi, tau = self.pi, self.tau self.add(pi, tau) pi_value = OldTexText("3.1415...!") pi_value.set_color(BLUE) tau_value = OldTexText("6.2831...!") tau_value.set_color(GREEN) self.play(PiCreatureSays( pi, pi_value, target_mode = "angry", look_at = tau.eyes, # bubble_config = {"width" : 3} )) self.play(PiCreatureSays( tau, tau_value, target_mode = "angry", look_at = pi.eyes, bubble_config = {"width" : 3, "height" : 2}, )) self.wait() # Show tau terms, generate_anims1, generate_anims2 = get_circle_drawing_terms( radius = 1.25, positioning_func = lambda m : m.to_edge(RIGHT, buff = 2).to_edge(UP, buff = 1) ) circle, radius, one, decimal = terms self.play( RemovePiCreatureBubble(pi), RemovePiCreatureBubble(tau), *generate_anims1() ) self.play( tau.change, "hooray", pi.change, "sassy", *generate_anims2() ) self.wait() # Show pi circle = Circle(color = RED, radius = 1.25/2) circle.rotate(TAU/4) circle.move_to(pi) circle.to_edge(UP, buff = MED_LARGE_BUFF) diameter = Line(circle.get_left(), circle.get_right()) one = OldTex("1") one.scale(0.75) one.next_to(diameter, UP, SMALL_BUFF) circum_line = diameter.copy().scale(np.pi) circum_line.match_style(circle) circum_line.next_to(circle, DOWN, buff = MED_LARGE_BUFF) # circum_line.to_edge(LEFT) brace = Brace(circum_line, DOWN, buff = SMALL_BUFF) decimal = DecimalNumber(np.pi, num_decimal_places = 4, show_ellipsis = True) decimal.scale(0.75) decimal.next_to(brace, DOWN, SMALL_BUFF) self.play( FadeIn(VGroup(circle, diameter, one)), tau.change, "confused", pi.change, "hooray" ) self.add(circle.copy().fade(0.5)) self.play( ReplacementTransform(circle, circum_line, run_time = 2) ) self.play(GrowFromCenter(brace), Write(decimal)) self.wait(3) # self.play() def create_pi_creatures(self): pi = self.pi = Randolph() pi.to_edge(DOWN).shift(4*LEFT) tau = self.tau = TauCreature( # mode = "angry", file_name_prefix = "TauCreatures", color = GREEN_E ).flip() tau.to_edge(DOWN).shift(4*RIGHT) return VGroup(pi, tau) class HartlAndPalais(Scene): def construct(self): hartl_rect = ScreenRectangle( color = WHITE, stroke_width = 1, ) hartl_rect.set_width(FRAME_X_RADIUS - 1) hartl_rect.to_edge(LEFT) palais_rect = hartl_rect.copy() palais_rect.to_edge(RIGHT) tau_words = OldTexText("$\\tau$ ``tau''") tau_words.next_to(hartl_rect, UP) hartl_words = OldTexText("Michael Hartl's \\\\ ``Tau manifesto''") hartl_words.next_to(hartl_rect, DOWN) palais_words = OldTexText("Robert Palais' \\\\ ``Pi is Wrong!''") palais_words.next_to(palais_rect, DOWN) for words in hartl_words, palais_words: words.scale(0.7, about_edge = UP) three_legged_creature = ThreeLeggedPiCreature(height = 1.5) three_legged_creature.next_to(palais_rect, UP) # self.add(hartl_rect, palais_rect) self.add(hartl_words) self.play(Write(tau_words)) self.wait() self.play(FadeIn(palais_words)) self.play(FadeIn(three_legged_creature)) self.play(three_legged_creature.change_mode, "wave") self.play(Blink(three_legged_creature)) self.play(Homotopy( lambda x, y, z, t : (x + 0.1*np.sin(2*TAU*t)*np.exp(-10*(t-0.5 - 0.5*(y-1.85))**2), y, z), three_legged_creature, run_time = 2, )) self.wait() class ManyFormulas(Scene): def construct(self): formulas = VGroup( OldTex("\\sin(x + \\tau) = \\sin(x)"), OldTex("e^{\\tau i} = 1"), OldTex("n! \\approx \\sqrt{\\tau n} \\left(\\frac{n}{e} \\right)^n"), OldTex("c_n = \\frac{1}{\\tau} \\int_0^\\tau f(x) e^{inx}dx"), ) formulas.arrange(DOWN, buff = MED_LARGE_BUFF) formulas.to_edge(LEFT) self.play(LaggedStartMap(FadeIn, formulas, run_time = 3)) circle = Circle(color = YELLOW, radius = 2) circle.to_edge(RIGHT) radius = Line(circle.get_center(), circle.get_right()) radius.set_color(WHITE) angle_groups = VGroup() for denom in 5, 4, 3, 2: radius_copy = radius.copy() radius_copy.rotate(TAU/denom, about_point = circle.get_center()) arc = Arc( angle = TAU/denom, stroke_color = RED, stroke_width = 4, radius = circle.radius, ) arc.shift(circle.get_center()) mini_arc = arc.copy() mini_arc.set_stroke(WHITE, 2) mini_arc.scale(0.15, about_point = circle.get_center()) tau_tex = OldTex("\\tau/%d"%denom) point = mini_arc.point_from_proportion(0.5) tau_tex.next_to(point, direction = point - circle.get_center()) angle_group = VGroup(radius_copy, mini_arc, tau_tex, arc) angle_groups.add(angle_group) angle_group = angle_groups[0] self.play(*list(map(FadeIn, [circle, radius]))) self.play( circle.set_stroke, {"width" : 1,}, FadeIn(angle_group), ) self.wait() for group in angle_groups[1:]: self.play(Transform(angle_group, group, path_arc = TAU/8)) self.wait() class HistoryOfOurPeople(TeacherStudentsScene): def construct(self): self.teacher_says( "Today: The history \\\\ of our people.", bubble_config = {"width" : 4, "height" : 3} ) self.play_all_student_changes("hooray") self.wait() self.play(*[ ApplyMethod(pi.change, "happy", self.screen) for pi in self.pi_creatures ]) self.wait(4) class TauFalls(Scene): def construct(self): tau = TauCreature() bottom = np.min(tau.body.get_points()[:,1])*UP angle = -0.15*TAU tau.generate_target() tau.target.change("angry") tau.target.rotate(angle, about_point = bottom) self.play(Rotate(tau, angle, rate_func = rush_into, path_arc = angle, about_point = bottom)) # self.play(MoveToTarget(tau, rate_func = rush_into, path_arc = angle)) self.play(MoveToTarget(tau)) self.wait() class EulerWrites628(Scene): CONFIG = { "camera_config" : { "background_opacity" : 1, } } def construct(self): image = ImageMobject(os.path.join(RESOURCE_DIR, "dalembert_zoom")) image.set_width(FRAME_WIDTH - 1) image.to_edge(UP, buff = MED_SMALL_BUFF) image.fade(0.15) rect = Rectangle( width = 12, height = 0.5, stroke_width = 0, fill_opacity = 0.3, fill_color = GREEN, ) rect.insert_n_curves(20) rect.apply_function(lambda p : np.array([p[0], p[1] - 0.005*p[0]**2, p[2]])) rect.rotate(0.012*TAU) rect.move_to(image) rect.shift(0.15*DOWN) words = OldTexText( "``Let", "$\\pi$", "be the", "circumference", "of a circle whose", "radius = 1''", ) words.set_color_by_tex_to_color_map({ "circumference" : YELLOW, "radius" : GREEN, }) words.next_to(image, DOWN) pi = words.get_part_by_tex("\\pi").copy() terms, generate_anims1, generate_anims2 = get_circle_drawing_terms( radius = 1, positioning_func = lambda circ : circ.next_to(words, DOWN, buff = 1.25) ) circle, radius, one, decimal = terms unwrapped_perimeter = Line(ORIGIN, TAU*RIGHT) unwrapped_perimeter.match_style(circle) unwrapped_perimeter.next_to(circle, DOWN) brace = Brace(unwrapped_perimeter, UP, buff = SMALL_BUFF) perimeter = OldTex( "\\pi\\epsilon\\rho\\iota\\mu\\epsilon\\tau\\rho\\text{o}\\varsigma", "\\text{ (perimeter)}", "=" ) perimeter.next_to(brace, UP, submobject_to_align = perimeter[1], buff = SMALL_BUFF) perimeter[0][0].set_color(GREEN) self.play(FadeInFromDown(image)) self.play( Write(words), GrowFromPoint(rect, rect.point_from_proportion(0.9)) ) self.wait() self.play(*generate_anims1()) self.play(*generate_anims2()) self.play(terms.shift, UP) self.play( pi.scale, 2, pi.shift, DOWN, pi.set_color, GREEN ) self.wait() self.play( GrowFromCenter(brace), circle.set_stroke, YELLOW, 1, ReplacementTransform(circle.copy(), unwrapped_perimeter), decimal.scale, 1.25, decimal.next_to, perimeter[-1].get_right(), RIGHT, ReplacementTransform(pi, perimeter[0][0]), Write(perimeter), ) self.wait() class HeroAndVillain(Scene): CONFIG = { "camera_config" : { "background_opacity" : 1, } } def construct(self): good_euler = get_image("Leonhard_Euler_by_Handmann") bad_euler_pixelated = get_image("Leonard_Euler_pixelated") bad_euler = get_image("Leonard_Euler_revealed") pictures = good_euler, bad_euler_pixelated, bad_euler for mob in pictures: mob.set_height(5) good_euler.move_to(FRAME_X_RADIUS*LEFT/2) bad_euler.move_to(FRAME_X_RADIUS*RIGHT/2) bad_euler_pixelated.move_to(bad_euler) good_euler_label = OldTexText("Leonhard Euler") good_euler_label.next_to(good_euler, DOWN) tau_words = OldTexText("Used 6.2831...") tau_words.next_to(good_euler, UP) tau_words.set_color(GREEN) bad_euler_label = OldTexText("Also Euler...") bad_euler_label.next_to(bad_euler, DOWN) pi_words = OldTexText("Used 3.1415...") pi_words.set_color(RED) pi_words.next_to(bad_euler, UP) self.play( FadeInFromDown(good_euler), Write(good_euler_label) ) self.play(LaggedStartMap(FadeIn, tau_words)) self.wait() self.play(FadeInFromDown(bad_euler_pixelated)) self.play(LaggedStartMap(FadeIn, pi_words)) self.wait(2) self.play( FadeIn(bad_euler), Write(bad_euler_label), ) self.remove(bad_euler_pixelated) self.wait(2) class AnalysisQuote(Scene): def construct(self): analysis = get_image("Analysis_page_showing_pi") analysis.set_height(FRAME_HEIGHT) analysis.to_edge(LEFT, buff = 0) text = OldTexText( "``\\dots set the radius of", "the circle\\dots to be = 1, \\dots \\\\", "through approximations the", "semicircumference \\\\", "of said circle", "has been found to be", "$= 3.14159\\dots$,\\\\", "for which number, for the sake of", "brevity, \\\\ I will write", "$\pi$\\dots''", alignment = '' ) pi_formula = OldTex( "\\pi", "=", "{ \\text{semicircumference}", "\\over", "\\text{radius}}" ) text.set_width(FRAME_X_RADIUS) text.next_to(analysis, RIGHT, LARGE_BUFF) text.to_edge(UP) HIGHLIGHT_COLOR= GREEN for mob in text, pi_formula: mob.set_color_by_tex_to_color_map({ "semicircumference" : HIGHLIGHT_COLOR, "3.14" : HIGHLIGHT_COLOR, "\pi" : HIGHLIGHT_COLOR }) terms, generate_anims1, generate_anims2 = get_circle_drawing_terms( radius = 1, positioning_func = lambda circ : circ.next_to(text, DOWN, LARGE_BUFF) ) terms[0].set_color(HIGHLIGHT_COLOR) terms[-1].set_color(HIGHLIGHT_COLOR) pi_formula.next_to(terms, DOWN, buff = 0) pi_formula.align_to(text, alignment_vect = RIGHT) pi_formula[0].scale(2, about_edge = RIGHT) self.add(analysis) self.play(*generate_anims2(), rate_func = lambda t : 0.5*smooth(t)) self.play(LaggedStartMap(FadeIn,text), run_time = 5) self.play(FadeIn(pi_formula)) self.wait() class QuarterTurn(Scene): def construct(self): terms, generate_anims1, generate_anims2 = get_circle_drawing_terms( radius = 2, positioning_func = lambda circ : circ.move_to(4*RIGHT) ) circle, radius, one, decimal = terms circle_ghost = circle.copy().set_stroke(YELLOW_E, 1) radius_ghost = radius.copy().set_stroke(WHITE, 1) self.add(circle_ghost, radius_ghost) self.play( *generate_anims2(), rate_func = lambda t : 0.25*smooth(t) ) self.wait() pi_halves = OldTex("\\pi", "/2") pi_halves[0].set_color(RED) tau_fourths = OldTex("\\tau", "/4") tau_fourths[0].set_color(GREEN) for mob in pi_halves, tau_fourths: mob.next_to(decimal, UP) self.play(FadeInFromDown(pi_halves)) self.wait() self.play( pi_halves.shift, 0.75*UP, FadeInFromDown(tau_fourths) ) self.wait() class UsingTheta(Scene): def construct(self): plane = NumberPlane(x_unit_size = 3, y_unit_size = 3) # planes.fade(0.5) # plane.secondary_lines.fade(0.5) plane.fade(0.5) self.add(plane) circle = Circle(radius = 3) circle.set_stroke(YELLOW, 2) self.add(circle) radius = Line(ORIGIN, circle.get_right()) arc = Arc(radius = 0.5, angle = TAU, num_anchors = 200) arc.set_color(GREEN) start_arc = arc.copy() theta = OldTex("\\theta", "=") theta[0].match_color(arc) theta.add_background_rectangle() update_theta = Mobject.add_updater( theta, lambda m : m.shift( rotate_vector(0.9*RIGHT, radius.get_angle()/2) \ - m[1][0].get_center() ) ) angle = Integer(0, unit = "^\\circ") update_angle = ContinualChangingDecimal( angle, lambda a : radius.get_angle()*(360/TAU), position_update_func = lambda a : a.next_to(theta, RIGHT, SMALL_BUFF) ) self.add(update_theta, update_angle) last_frac = 0 for frac in 1./4, 1./12, 3./8, 1./6, 5./6: self.play( Rotate(radius, angle = (frac-last_frac)*TAU, about_point = ORIGIN), UpdateFromAlphaFunc( arc, lambda m, a : m.pointwise_become_partial( start_arc, 0, interpolate(last_frac, frac, a) ) ), run_time = 3 ) last_frac = frac self.wait() class ThingsNamedAfterEuler(Scene): def construct(self): group = VGroup(*list(map(TexText, [ "Euler's formula (Complex analysis)", "Euler's formula (Graph theory)", "Euler's formula (Mechanical engineering)", "Euler's formula (Analytical number theory)", "Euler's formula (Continued fractions)", "Euler-Lagrance equations (mechanics)", "Euler number (topology)", "Euler equations (fluid dynamics)", "Euler angles (rigid-body mechanics)", "Euler totient function (number theory)", ]))) group.arrange(DOWN, aligned_edge = LEFT) group.set_height(FRAME_HEIGHT - 1) self.play(LaggedStartMap(FadeIn, group, lag_ratio = 0.2, run_time = 12)) self.wait() class EulerThinking(Scene): def construct(self): image = get_image("Leonhard_Euler_by_Handmann") image.set_height(4) image.to_edge(DOWN) image.shift(4*LEFT) bubble = ThoughtBubble(height = 4.5) bubble.next_to(image, RIGHT) bubble.to_edge(UP, buff = SMALL_BUFF) bubble.shift(0.8*LEFT) bubble.set_fill(BLACK, 0.3) pi_vs_tau = OldTexText( "Should $\\pi$ represent \\\\", "3.1415...", "or", "6.2831...", "?" ) pi_vs_tau.set_color_by_tex_to_color_map({ "3.14" : GREEN, "6.28" : RED, }) pi_vs_tau.move_to(bubble.get_bubble_center()) question = OldTex( "\\frac{1}{1} + \\frac{1}{4} + \\frac{1}{9} + \\frac{1}{16} + \\cdots = ", "\\;???" ) question[0].set_color_by_gradient(BLUE_C, BLUE_B) question.move_to(bubble.get_bubble_center()) question.shift(2*SMALL_BUFF*UP) cross = Cross(pi_vs_tau) cross.set_stroke(RED, 8) self.add(image) self.play( ShowCreation(bubble), Write(pi_vs_tau) ) self.play(ShowCreation(cross)) self.wait() self.play( FadeOut(VGroup(pi_vs_tau, cross)), FadeIn(question), ) self.wait() class WhatIsRight(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs" : { "color" : BLUE_D, "filp_at_start" : False, }, "default_pi_creature_start_corner" : DOWN, } def construct(self): randy = self.pi_creature randy.scale(0.75, about_edge = DOWN) title = OldTexText("Which is ``right''?") title.scale(1.5) title.to_edge(UP) self.add(title) sum_over_N_converges = OldTex("1+2+3+\\cdots = -\\frac{1}{12}") sum_over_N_diverges = OldTex("1+2+3+\\cdots \\text{ Diverges}") literal_derivative = OldTex( "f'(x) = \\frac{f(x+dx) - f(x)}{dx}" ) limit_derivative = OldTex( "f'(x) = \\lim_{h \\to 0}\\frac{f(x+h) - f(x)}{h}" ) divide_by_zero_definable = OldTex( "\\frac{1}{0}", "\\text{ has meaning}" ) divide_by_zero_undefinable = OldTex( "\\frac{1}{0}", "\\text{ is undefined}" ) left_mobs = VGroup( sum_over_N_converges, literal_derivative, divide_by_zero_definable ) right_mobs = VGroup( sum_over_N_diverges, limit_derivative, divide_by_zero_undefinable ) for mob in left_mobs: mob.next_to(randy, UP) mob.shift(3.5*LEFT) for mob in right_mobs: mob.next_to(randy, UP) mob.shift(3.5*RIGHT) left_mobs.set_color_by_gradient(YELLOW_C, YELLOW_D) right_mobs.set_color_by_gradient(GREEN_C, GREEN_D) self.play(randy.change, "pondering", title) self.wait() self.play(randy.change, "sassy", title) self.wait() last_terms = VGroup() for left, right in zip(left_mobs, right_mobs)[:-1]: right.align_to(left) self.play( randy.change, "raise_right_hand", FadeInFromDown(left), last_terms.shift, 1.75*UP ) self.wait() self.play( randy.change, "raise_left_hand", FadeInFromDown(right) ) self.play(randy.change, "plain", right) last_terms.add(left, right, title) self.play( randy.change, "shruggie", FadeInFromDown(left_mobs[-1]), FadeInFromDown(right_mobs[-1]), last_terms.shift, 1.75*UP, ) self.wait(4) class AskPuzzle(TeacherStudentsScene): def construct(self): series = OldTex( "\\frac{1}{1} + \\frac{1}{4} + \\frac{1}{9} + \\cdots + " +\ "\\frac{1}{n^2} + \\cdots = ", "\\,???" ) series[0].set_color_by_gradient(BLUE_C, BLUE_B) series[1].set_color(YELLOW) question = OldTexText( "How should we think about\\\\", "$\\displaystyle \\sum_{n=1}^\\infty \\frac{1}{n^s}$", "for arbitrary $s$?" ) question[1].set_color(BLUE) question[0].shift(SMALL_BUFF*UP) response = OldTexText( "What do you mean by ", "$\\displaystyle \\sum_{n = 1}^{\\infty}$", "?" ) response[1].set_color(BLUE) self.teacher_says(series) self.play_all_student_changes("pondering", look_at = series) self.wait(3) self.play( FadeOut(self.teacher.bubble), self.teacher.change, "happy", series.scale, 0.5, series.to_corner, UP+LEFT, PiCreatureSays( self.students[0], question, target_mode = "raise_left_hand" ) ) self.play_student_changes( None, "confused", "confused", added_anims = [self.students[0].look_at, question] ) self.wait(2) self.students[0].bubble.content = VGroup() self.play( RemovePiCreatureBubble(self.students[0]), question.scale, 0.5, question.next_to, series, DOWN, MED_LARGE_BUFF, LEFT, PiCreatureSays(self.teacher, response) ) self.play_all_student_changes("erm") self.wait(3) class ChangeTopic(PiCreatureScene): def construct(self): pi, tau = self.pi_creatures title = OldTexText("Happy $\\pi$ day!") title.scale(1.5) title.to_edge(UP, buff = MED_SMALL_BUFF) self.add(title) question = OldTexText( "Have you ever seen why \\\\", "$\\displaystyle \\frac{2}{1} \\cdot \\frac{2}{3} \\cdots"+ \ "\\frac{4}{3} \\cdot \\frac{4}{5} \\cdot" + \ "\\frac{6}{5} \\cdot \\frac{6}{7} \\cdots = \\frac{\\pi}{2}$", "?" ) question[0].shift(MED_SMALL_BUFF*UP) question[1].set_color_by_gradient(YELLOW, GREEN) self.play( PiCreatureSays( tau, "We should \\emph{really} celebrate \\\\ on 6/28!", target_mode = "angry", ), pi.change, "guilty", ) self.wait(2) self.play( PiCreatureSays(pi, question), RemovePiCreatureBubble( tau, target_mode = "pondering", look_at = question, ) ) self.play(pi.change, "pondering", question) self.wait(4) def create_pi_creatures(self): tau = TauCreature(color = GREEN_E) pi = Randolph().flip() VGroup(pi, tau).scale(0.75) tau.to_edge(DOWN).shift(3*LEFT) pi.to_edge(DOWN).shift(3*RIGHT) return pi, tau class SpecialThanks(Scene): def construct(self): title = OldTexText("Special thanks to:") title.to_edge(UP, LARGE_BUFF) title.scale(1.5) title.set_color(BLUE) h_line = Line(LEFT, RIGHT).scale(4) h_line.next_to(title, DOWN) h_line.set_stroke(WHITE, 1) people = VGroup(*list(map(TexText, [ "Ben Hambrecht", "University Library Basel", "Martin Mattmüller", "Library of the Institut de France", ]))) people.arrange(DOWN, aligned_edge = LEFT, buff = MED_LARGE_BUFF) people.next_to(h_line, DOWN) self.add(title, h_line, people) class EndScene(PatreonEndScreen): CONFIG = { "camera_config" : { "background_opacity" : 1, } } def construct(self): self.add_title() title = self.title basel_screen = ScreenRectangle(height = 2.35) basel_screen.next_to(title, DOWN) watch_basel = OldTexText( "One such actual piece of math", "(quite pretty!)", ) watch_basel[0].set_color(YELLOW) watch_basel.next_to(basel_screen, DOWN, submobject_to_align = watch_basel[0]) self.add(watch_basel) # self.add(basel_screen) line = DashedLine(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT) line.next_to(watch_basel, DOWN) self.add(line) plushie_square = Square(side_length = 2) plushie_square.to_corner(DOWN+LEFT, buff = MED_LARGE_BUFF) plushie_square.shift(UP) plushie_words = OldTexText( "Plushie pi \\\\ creatures \\\\ now available.", alignment = "" ) plushie_words.next_to(plushie_square, RIGHT) self.add(plushie_words) # self.add(plushie_square) instagram_line = OldTexText( "randy\\_the\\_pi" ) instagram_logo = ImageMobject("instagram_logo") instagram_logo.match_height(instagram_line) instagram_logo.next_to(instagram_line, LEFT, SMALL_BUFF) instagram = Group(instagram_logo, instagram_line) instagram.next_to(line, DOWN) instagram.shift(FRAME_X_RADIUS*RIGHT/2) self.add(instagram) pictures = Group(*[ ImageMobject("randy/randy_%s"%name) for name in [ "science", "cooking", "in_a_can", "sandwhich", "lab", "fractal", "flowers", "group", "labcoat", "tennis", ] ]) for i, picture in enumerate(pictures): picture.set_height(2) picture.next_to(instagram, DOWN, aligned_edge = RIGHT) if i%3 != 0: picture.next_to(last_picture, LEFT, buff = 0) self.play(FadeIn(picture, run_time = 2)) last_picture = picture class Thumbnail(Scene): def construct(self): pi, eq, num = formula = OldTex( "\\pi", "=", "6.283185\\dots" ) formula.scale(2) pi.scale(1.5, about_edge = RIGHT) formula.set_stroke(BLUE, 1) formula.set_width(FRAME_WIDTH - 2) # formula.shift(0.5*RIGHT) self.add(formula) words = OldTexText("...according to Euler.") words.scale(1.5) words.next_to(formula, DOWN, MED_LARGE_BUFF) self.add(words)
# -*- coding: utf-8 -*- from manim_imports_ext import * def apply_function_to_center(point_func, mobject): mobject.apply_function_to_position(point_func) def apply_function_to_submobjects(point_func, mobject): mobject.apply_function_to_submobject_positions(point_func) def apply_function_to_points(point_func, mobject): mobject.apply_function(point_func) def get_nested_one_plus_one_over_x(n_terms, bottom_term="x"): tex = "1+ {1 \\over" * n_terms + bottom_term + "}" * n_terms return OldTex(tex, isolate=["1", "\\over", bottom_term]) def get_phi_continued_fraction(n_terms): return get_nested_one_plus_one_over_x(n_terms, bottom_term="1+\\cdots") def get_nested_f(n_terms, arg="x"): terms = ["f("] * n_terms + [arg] + [")"] * n_terms return OldTex(*terms) # Scene types class NumberlineTransformationScene(ZoomedScene): CONFIG = { "input_line_zero_point": 0.5 * UP + (FRAME_X_RADIUS - 1) * LEFT, "output_line_zero_point": 2 * DOWN + (FRAME_X_RADIUS - 1) * LEFT, "number_line_config": { "include_numbers": True, "x_min": -3.5, "x_max": 3.5, "unit_size": 2, }, # These would override number_line_config "input_line_config": { "color": BLUE, }, "output_line_config": {}, "num_inserted_number_line_curves": 20, "default_delta_x": 0.1, "default_sample_dot_radius": 0.07, "default_sample_dot_colors": [RED, YELLOW], "default_mapping_animation_config": { "run_time": 3, # "path_arc": 30 * DEGREES, }, "local_coordinate_num_decimal_places": 2, "zoom_factor": 0.1, "zoomed_display_height": 2.5, "zoomed_display_corner_buff": MED_SMALL_BUFF, "mini_line_scale_factor": 2, "default_coordinate_value_dx": 0.05, "zoomed_camera_background_rectangle_fill_opacity": 1.0, } def setup(self): ZoomedScene.setup(self) self.setup_number_lines() self.setup_titles() self.setup_zoomed_camera_background_rectangle() def setup_number_lines(self): number_lines = self.number_lines = VGroup() added_configs = (self.input_line_config, self.output_line_config) zero_opints = (self.input_line_zero_point, self.output_line_zero_point) for added_config, zero_point in zip(added_configs, zero_opints): full_config = dict(self.number_line_config) full_config.update(added_config) number_line = NumberLine(**full_config) number_line.insert_n_curves( self.num_inserted_number_line_curves ) number_line.shift(zero_point - number_line.number_to_point(0)) number_lines.add(number_line) self.input_line, self.output_line = number_lines self.add(number_lines) def setup_titles(self): input_title, output_title = self.titles = VGroup(*[ OldTexText(word) for word in ("Inputs", "Outputs") ]) vects = [UP, DOWN] for title, line, vect in zip(self.titles, self.number_lines, vects): title.next_to(line, vect, aligned_edge=LEFT) title.shift_onto_screen() self.add(self.titles) def setup_zoomed_camera_background_rectangle(self): frame = self.zoomed_camera.frame frame.next_to(self.camera.frame, UL) self.zoomed_camera_background_rectangle = BackgroundRectangle( frame, fill_opacity=self.zoomed_camera_background_rectangle_fill_opacity ) self.zoomed_camera_background_rectangle_anim = UpdateFromFunc( self.zoomed_camera_background_rectangle, lambda m: m.replace(frame, stretch=True) ) self.zoomed_camera_background_rectangle_group = VGroup( self.zoomed_camera_background_rectangle, ) def get_sample_input_points(self, x_min=None, x_max=None, delta_x=None): x_min = x_min or self.input_line.x_min x_max = x_max or self.input_line.x_max delta_x = delta_x or self.default_delta_x return [ self.get_input_point(x) for x in np.arange(x_min, x_max + delta_x, delta_x) ] def get_sample_dots(self, x_min=None, x_max=None, delta_x=None, dot_radius=None, colors=None): dot_radius = dot_radius or self.default_sample_dot_radius colors = colors or self.default_sample_dot_colors dots = VGroup(*[ Dot(point, radius=dot_radius) for point in self.get_sample_input_points(x_min, x_max, delta_x) ]) dots.set_color_by_gradient(*colors) return dots def get_local_sample_dots(self, x, sample_radius=None, **kwargs): zoom_factor = self.get_zoom_factor() delta_x = kwargs.get("delta_x", self.default_delta_x * zoom_factor) dot_radius = kwargs.get("dot_radius", self.default_sample_dot_radius * zoom_factor) if sample_radius is None: unrounded_radius = self.zoomed_camera.frame.get_width() / 2 sample_radius = int(unrounded_radius / delta_x) * delta_x config = { "x_min": x - sample_radius, "x_max": x + sample_radius, "delta_x": delta_x, "dot_radius": dot_radius, } config.update(kwargs) return self.get_sample_dots(**config) def add_sample_dot_ghosts(self, sample_dots, fade_factor=0.5): self.sample_dot_ghosts = sample_dots.copy() self.sample_dot_ghosts.fade(fade_factor) self.add(self.sample_dot_ghosts, sample_dots) def get_local_coordinate_values(self, x, dx=None, n_neighbors=1): dx = dx or self.default_coordinate_value_dx return [ x + n * dx for n in range(-n_neighbors, n_neighbors + 1) ] # Mapping animations def get_mapping_animation(self, func, mobject, how_to_apply_func=apply_function_to_center, **kwargs): anim_config = dict(self.default_mapping_animation_config) anim_config.update(kwargs) point_func = self.number_func_to_point_func(func) mobject.generate_target(use_deepcopy=True) how_to_apply_func(point_func, mobject.target) return MoveToTarget(mobject, **anim_config) def get_line_mapping_animation(self, func, **kwargs): input_line_copy = self.input_line.deepcopy() self.moving_input_line = input_line_copy input_line_copy.remove(input_line_copy.numbers) # input_line_copy.set_stroke(width=2) input_line_copy.insert_n_curves( self.num_inserted_number_line_curves ) return AnimationGroup( self.get_mapping_animation( func, input_line_copy, apply_function_to_points ), self.get_mapping_animation( func, input_line_copy.tick_marks, apply_function_to_submobjects ), ) def get_sample_dots_mapping_animation(self, func, dots, **kwargs): return self.get_mapping_animation( func, dots, how_to_apply_func=apply_function_to_submobjects ) def get_zoomed_camera_frame_mapping_animation(self, func, x=None, **kwargs): frame = self.zoomed_camera.frame if x is None: point = frame.get_center() else: point = self.get_input_point(x) point_mob = VectorizedPoint(point) return AnimationGroup( self.get_mapping_animation(func, point_mob), UpdateFromFunc(frame, lambda m: m.move_to(point_mob)), ) def apply_function(self, func, apply_function_to_number_line=True, sample_dots=None, local_sample_dots=None, target_coordinate_values=None, added_anims=None, **kwargs ): zcbr_group = self.zoomed_camera_background_rectangle_group zcbr_anim = self.zoomed_camera_background_rectangle_anim frame = self.zoomed_camera.frame anims = [] if apply_function_to_number_line: anims.append(self.get_line_mapping_animation(func)) if hasattr(self, "mini_line"): # Test for if mini_line is in self? anims.append(self.get_mapping_animation( func, self.mini_line, how_to_apply_func=apply_function_to_center )) if sample_dots: anims.append( self.get_sample_dots_mapping_animation(func, sample_dots) ) if self.zoom_activated: zoom_anim = self.get_zoomed_camera_frame_mapping_animation(func) anims.append(zoom_anim) anims.append(zcbr_anim) zoom_anim.update(1) target_mini_line = Line(frame.get_left(), frame.get_right()) target_mini_line.scale(self.mini_line_scale_factor) target_mini_line.match_style(self.output_line) zoom_anim.update(0) zcbr_group.submobjects.insert(1, target_mini_line) if target_coordinate_values: coordinates = self.get_local_coordinates( self.output_line, *target_coordinate_values ) anims.append(FadeIn(coordinates)) zcbr_group.add(coordinates) self.local_target_coordinates = coordinates if local_sample_dots: anims.append( self.get_sample_dots_mapping_animation(func, local_sample_dots) ) zcbr_group.add(local_sample_dots) if added_anims: anims += added_anims anims.append(Animation(zcbr_group)) self.play(*anims, **kwargs) # Zooming def zoom_in_on_input(self, x, local_sample_dots=None, local_coordinate_values=None, pop_out=True, first_added_anims=None, first_anim_kwargs=None, second_added_anims=None, second_anim_kwargs=None, zoom_factor=None, ): first_added_anims = first_added_anims or [] first_anim_kwargs = first_anim_kwargs or {} second_added_anims = second_added_anims or [] second_anim_kwargs = second_anim_kwargs or {} input_point = self.get_input_point(x) # Decide how to move camera frame into place frame = self.zoomed_camera.frame frame.generate_target() frame.target.move_to(input_point) if zoom_factor: frame.target.set_height( self.zoomed_display.get_height() * zoom_factor ) movement = MoveToTarget(frame) zcbr = self.zoomed_camera_background_rectangle zcbr_group = self.zoomed_camera_background_rectangle_group zcbr_anim = self.zoomed_camera_background_rectangle_anim anims = [] if self.zoom_activated: anims.append(movement) anims.append(zcbr_anim) else: movement.update(1) zcbr_anim.update(1) anims.append(self.get_zoom_in_animation()) anims.append(FadeIn(zcbr)) # Make sure frame is in final place for anim in anims: anim.update(1) # Add miniature number_line mini_line = self.mini_line = Line(frame.get_left(), frame.get_right()) mini_line.scale(self.mini_line_scale_factor) mini_line.insert_n_curves(self.num_inserted_number_line_curves) mini_line.match_style(self.input_line) mini_line_copy = mini_line.copy() zcbr_group.add(mini_line_copy, mini_line) anims += [FadeIn(mini_line), FadeIn(mini_line_copy)] # Add tiny coordinates if local_coordinate_values is None: local_coordinate_values = [x] local_coordinates = self.get_local_coordinates( self.input_line, *local_coordinate_values ) anims.append(FadeIn(local_coordinates)) zcbr_group.add(local_coordinates) self.local_coordinates = local_coordinates # Add tiny dots if local_sample_dots is not None: anims.append(LaggedStartMap(GrowFromCenter, local_sample_dots)) zcbr_group.add(local_sample_dots) if first_added_anims: anims += first_added_anims anims.append(Animation(zcbr_group)) if not pop_out: self.activate_zooming(animate=False) self.play(*anims, **first_anim_kwargs) if not self.zoom_activated and pop_out: self.activate_zooming(animate=False) added_anims = second_added_anims or [] self.play( self.get_zoomed_display_pop_out_animation(), *added_anims, **second_anim_kwargs ) def get_local_coordinates(self, line, *x_values, **kwargs): num_decimal_places = kwargs.get( "num_decimal_places", self.local_coordinate_num_decimal_places ) result = VGroup() result.tick_marks = VGroup() result.numbers = VGroup() result.add(result.tick_marks, result.numbers) for x in x_values: tick_mark = Line(UP, DOWN) tick_mark.set_height( 0.15 * self.zoomed_camera.frame.get_height() ) tick_mark.move_to(line.number_to_point(x)) result.tick_marks.add(tick_mark) number = DecimalNumber(x, num_decimal_places=num_decimal_places) number.scale(self.get_zoom_factor()) number.scale(0.5) # To make it seem small number.next_to(tick_mark, DOWN, buff=0.5 * number.get_height()) result.numbers.add(number) return result def get_mobjects_in_zoomed_camera(self, mobjects): frame = self.zoomed_camera.frame x_min = frame.get_left()[0] x_max = frame.get_right()[0] y_min = frame.get_bottom()[1] y_max = frame.get_top()[1] result = VGroup() for mob in mobjects: for point in mob.get_all_points(): if (x_min < point[0] < x_max) and (y_min < point[1] < y_max): result.add(mob) break return result # Helpers def get_input_point(self, x): return self.input_line.number_to_point(x) def get_output_point(self, fx): return self.output_line.number_to_point(fx) def number_func_to_point_func(self, number_func): input_line, output_line = self.number_lines def point_func(point): input_number = input_line.point_to_number(point) output_number = number_func(input_number) return output_line.number_to_point(output_number) return point_func class ExampleNumberlineTransformationScene(NumberlineTransformationScene): CONFIG = { "number_line_config": { "x_min": 0, "x_max": 5, "unit_size": 2.0 }, "output_line_config": { "x_max": 20, }, } def construct(self): func = lambda x: x**2 x = 3 dx = 0.05 sample_dots = self.get_sample_dots() local_sample_dots = self.get_local_sample_dots(x) self.play(LaggedStartMap(GrowFromCenter, sample_dots)) self.zoom_in_on_input( x, local_sample_dots=local_sample_dots, local_coordinate_values=[x - dx, x, x + dx], ) self.wait() self.apply_function( func, sample_dots=sample_dots, local_sample_dots=local_sample_dots, target_coordinate_values=[func(x) - dx, func(x), func(x) + dx], ) self.wait() # Scenes class WriteOpeningWords(Scene): def construct(self): raw_string1 = "Dear calculus student," raw_string2 = "You're about to go through your first course. Like " + \ "any new topic, it will take some hard work to understand," words1, words2 = [ OldTexText("\\Large", *rs.split(" ")) for rs in (raw_string1, raw_string2) ] words1.next_to(words2, UP, aligned_edge=LEFT, buff=LARGE_BUFF) words = VGroup(*it.chain(words1, words2)) words.set_width(FRAME_WIDTH - 2 * LARGE_BUFF) words.to_edge(UP) letter_wait = 0.05 word_wait = 2 * letter_wait comma_wait = 5 * letter_wait for word in words: self.play(LaggedStartMap( FadeIn, word, run_time=len(word) * letter_wait, lag_ratio=1.5 / len(word) )) self.wait(word_wait) if word.get_tex()[-1] == ",": self.wait(comma_wait) class StartingCalc101(PiCreatureScene): CONFIG = { "camera_config": {"background_opacity": 1}, "image_frame_width": 3.5, "image_frame_height": 2.5, } def construct(self): self.show_you() self.show_images() self.show_mystery_topic() def show_you(self): randy = self.pi_creature title = self.title = Title("Calculus 101") you = OldTexText("You") arrow = Vector(DL, color=WHITE) arrow.next_to(randy, UR) you.next_to(arrow.get_start(), UP) self.play( Write(you), GrowArrow(arrow), randy.change, "erm", title ) self.wait() self.play(Write(title, run_time=1)) self.play(FadeOut(VGroup(arrow, you))) def show_images(self): randy = self.pi_creature images = self.get_all_images() modes = [ "pondering", # hard_work_image "pondering", # neat_example_image "hesitant", # not_so_neat_example_image "hesitant", # physics_image "horrified", # piles_of_formulas_image "horrified", # getting_stuck_image "thinking", # aha_image "thinking", # graphical_intuition_image ] for i, image, mode in zip(it.count(), images, modes): anims = [] if hasattr(image, "fade_in_anim"): anims.append(image.fade_in_anim) anims.append(FadeIn(image.frame)) else: anims.append(FadeIn(image)) if i >= 3: image_to_fade_out = images[i - 3] if hasattr(image_to_fade_out, "fade_out_anim"): anims.append(image_to_fade_out.fade_out_anim) else: anims.append(FadeOut(image_to_fade_out)) if hasattr(image, "continual_animations"): self.add(*image.continual_animations) anims.append(ApplyMethod(randy.change, mode)) self.play(*anims) self.wait() if i >= 3: if hasattr(image_to_fade_out, "continual_animations"): self.remove(*image_to_fade_out.continual_animations) self.remove(image_to_fade_out.frame) self.wait(3) self.remaining_images = images[-3:] def show_mystery_topic(self): images = self.remaining_images randy = self.pi_creature mystery_box = Rectangle( width=self.image_frame_width, height=self.image_frame_height, stroke_color=YELLOW, fill_color=GREY_D, fill_opacity=0.5, ) mystery_box.scale(1.5) mystery_box.next_to(self.title, DOWN, MED_LARGE_BUFF) rects = images[-1].rects.copy() rects.center() rects.set_height(FRAME_HEIGHT - 1) # image = rects.get_image() open_cv_image = cv2.imread(get_full_raster_image_path("alt_calc_hidden_image")) blurry_iamge = cv2.blur(open_cv_image, (50, 50)) array = np.array(blurry_iamge)[:, :, ::-1] im_mob = ImageMobject(array) im_mob.replace(mystery_box, stretch=True) mystery_box.add(im_mob) q_marks = OldTex("???").scale(3) q_marks.space_out_submobjects(1.5) q_marks.set_stroke(BLACK, 1) q_marks.move_to(mystery_box) mystery_box.add(q_marks) for image in images: if hasattr(image, "continual_animations"): self.remove(*image.continual_animations) self.play( image.shift, DOWN, image.fade, 1, randy.change, "erm", run_time=1.5 ) self.remove(image) self.wait() self.play( FadeInFromDown(mystery_box), randy.change, "confused" ) self.wait(5) # Helpers def get_all_images(self): # Images matched to narration's introductory list images = VGroup( self.get_hard_work_image(), self.get_neat_example_image(), self.get_not_so_neat_example_image(), self.get_physics_image(), self.get_piles_of_formulas_image(), self.get_getting_stuck_image(), self.get_aha_image(), self.get_graphical_intuition_image(), ) colors = color_gradient([BLUE, YELLOW], len(images)) for i, image, color in zip(it.count(), images, colors): self.adjust_size(image) frame = Rectangle( width=self.image_frame_width, height=self.image_frame_height, color=color, stroke_width=2, ) frame.move_to(image) image.frame = frame image.add(frame) image.next_to(self.title, DOWN) alt_i = (i % 3) - 1 vect = (self.image_frame_width + LARGE_BUFF) * RIGHT image.shift(alt_i * vect) return images def adjust_size(self, group): group.set_width(min( group.get_width(), self.image_frame_width - 2 * MED_SMALL_BUFF )) group.set_height(min( group.get_height(), self.image_frame_height - 2 * MED_SMALL_BUFF )) return group def get_hard_work_image(self): new_randy = self.pi_creature.copy() new_randy.change_mode("telepath") bubble = new_randy.get_bubble(height=3.5, width=4) bubble.add_content(OldTex("\\frac{d}{dx}(\\sin(\\sqrt{x}))")) bubble.add(bubble.content) # Remove? return VGroup(new_randy, bubble) def get_neat_example_image(self): filled_circle = Circle( stroke_width=0, fill_color=BLUE_E, fill_opacity=1 ) area = OldTex("\\pi r^2") area.move_to(filled_circle) unfilled_circle = Circle( stroke_width=3, stroke_color=YELLOW, fill_opacity=0, ) unfilled_circle.next_to(filled_circle, RIGHT) circles = VGroup(filled_circle, unfilled_circle) circumference = OldTex("2\\pi r") circumference.move_to(unfilled_circle) equation = OldTex( "{d (\\pi r^2) \\over dr} = 2\\pi r", tex_to_color_map={ "\\pi r^2": BLUE_D, "2\\pi r": YELLOW, } ) equation.next_to(circles, UP) return VGroup( filled_circle, area, unfilled_circle, circumference, equation ) def get_not_so_neat_example_image(self): return OldTex("\\int x \\cos(x) \\, dx") def get_physics_image(self): t_max = 6.5 r = 0.2 spring = ParametricCurve( lambda t: op.add( r * (np.sin(TAU * t) * RIGHT + np.cos(TAU * t) * UP), t * DOWN, ), t_min=0, t_max=t_max, color=WHITE, stroke_width=2, ) spring.color_using_background_image("grey_gradient") weight = Square() weight.set_stroke(width=0) weight.set_fill(opacity=1) weight.color_using_background_image("grey_gradient") weight.set_height(0.4) t_tracker = ValueTracker(0) group = VGroup(spring, weight) group.continual_animations = [ t_tracker.add_udpater( lambda tracker, dt: tracker.set_value( tracker.get_value() + dt ) ), spring.add_updater( lambda s: s.stretch_to_fit_height( 1.5 + 0.5 * np.cos(3 * t_tracker.get_value()), about_edge=UP ) ), weight.add_updater( lambda w: w.move_to(spring.get_points()[-1]) ) ] def update_group_style(alpha): spring.set_stroke(width=2 * alpha) weight.set_fill(opacity=alpha) group.fade_in_anim = UpdateFromAlphaFunc( group, lambda g, a: update_group_style(a) ) group.fade_out_anim = UpdateFromAlphaFunc( group, lambda g, a: update_group_style(1 - a) ) return group def get_piles_of_formulas_image(self): return OldTex("(f/g)' = \\frac{gf' - fg'}{g^2}") def get_getting_stuck_image(self): creature = self.pi_creature.copy() creature.change_mode("angry") equation = OldTex("\\frac{d}{dx}(x^x)") equation.set_height(creature.get_height() / 2) equation.next_to(creature, RIGHT, aligned_edge=UP) creature.look_at(equation) return VGroup(creature, equation) def get_aha_image(self): creature = self.pi_creature.copy() creature.change_mode("hooray") from _2017.eoc.eoc.chapter3 import NudgeSideLengthOfCube scene = NudgeSideLengthOfCube( end_at_animation_number=7, skip_animations=True ) group = VGroup( scene.cube, scene.faces, scene.bars, scene.corner_cube, ) group.set_height(0.75 * creature.get_height()) group.next_to(creature, RIGHT) creature.look_at(group) return VGroup(creature, group) def get_graphical_intuition_image(self): gs = GraphScene() gs.setup_axes() graph = gs.get_graph( lambda x: 0.2 * (x - 3) * (x - 5) * (x - 6) + 4, x_min=2, x_max=8, ) rects = gs.get_riemann_rectangles( graph, x_min=2, x_max=8, stroke_width=0.5, dx=0.25 ) gs.add(graph, rects, gs.axes) group = VGroup(*gs.mobjects) self.adjust_size(group) group.next_to(self.title, DOWN, MED_LARGE_BUFF) group.rects = rects group.continual_animations = [ turn_animation_into_updater(Write(rects)), turn_animation_into_updater(ShowCreation(graph)), turn_animation_into_updater(FadeIn(gs.axes)), ] self.adjust_size(group) return group class GraphicalIntuitions(GraphScene): CONFIG = { "func": lambda x: 0.1 * (x - 2) * (x - 5) * (x - 7) + 4, "x_labeled_nums": list(range(1, 10)), } def construct(self): self.setup_axes() axes = self.axes graph = self.get_graph(self.func) ss_group = self.get_secant_slope_group( x=8, graph=graph, dx=0.01, secant_line_length=6, secant_line_color=RED, ) rects = self.get_riemann_rectangles( graph, x_min=2, x_max=8, dx=0.01, stroke_width=0 ) deriv_text = OldTexText( "Derivative $\\rightarrow$ slope", tex_to_color_map={"slope": ss_group.secant_line.get_color()} ) deriv_text.to_edge(UP) integral_text = OldTexText( "Integral $\\rightarrow$ area", tex_to_color_map={"area": rects[0].get_color()} ) integral_text.next_to(deriv_text, DOWN) self.play( Succession(Write(axes), ShowCreation(graph, run_time=2)), self.get_graph_words_anim(), ) self.animate_secant_slope_group_change( ss_group, target_x=2, rate_func=smooth, run_time=2.5, added_anims=[ Write(deriv_text), VFadeIn(ss_group, run_time=2), ] ) self.play(FadeIn(integral_text)) self.play( LaggedStartMap( GrowFromEdge, rects, lambda r: (r, DOWN) ), Animation(axes), Animation(graph), ) self.wait() def get_graph_words_anim(self): words = VGroup( OldTexText("Graphs,"), OldTexText("graphs,"), OldTexText("non-stop graphs"), OldTexText("all day"), OldTexText("every day"), OldTexText("as if to visualize is to graph"), ) for word in words: word.add_background_rectangle() words.arrange(DOWN) words.to_edge(UP) return LaggedStartMap( FadeIn, words, rate_func=there_and_back, run_time=len(words) - 1, lag_ratio=0.6, remover=True ) class Wrapper(Scene): CONFIG = { "title": "", "title_kwargs": {}, "screen_height": 6, "wait_time": 2, } def construct(self): rect = self.rect = ScreenRectangle(height=self.screen_height) title = self.title = OldTexText(self.title, **self.title_kwargs) title.to_edge(UP) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait(self.wait_time) class DomainColoringWrapper(Wrapper): CONFIG = { "title": "Complex $\\rightarrow$ Complex", } class R2ToR2Wrapper(Wrapper): CONFIG = {"title": "$\\mathds{R}^2 \\rightarrow \\mathds{R}^2$"} class ExampleMultivariableFunction(LinearTransformationScene): CONFIG = { "show_basis_vectors": False, "show_coordinates": True, } def construct(self): def example_function(point): x, y, z = point return np.array([ x + np.sin(y), y + np.sin(x), 0 ]) self.wait() self.apply_nonlinear_transformation(example_function, run_time=5) self.wait() class ChangingVectorFieldWrapper(Wrapper): CONFIG = {"title": "$(x, y, t) \\rightarrow (x', y')$"} class ChangingVectorField(Scene): CONFIG = { "wait_time": 30, } def construct(self): plane = self.plane = NumberPlane() plane.set_stroke(width=2) plane.add_coordinates() self.add(plane) # Obviously a silly thing to do, but I'm sweeping # through trying to make sure old scenes don't # completely break in spots which used to have # Continual animations time_tracker = self.time_tracker = ValueTracker(0) time_tracker.add_updater( lambda t: t.set_value(self.get_time()) ) vectors = self.get_vectors() vectors.add_updater(self.update_vectors) self.add(vectors) self.wait(self.wait_time) def get_vectors(self): vectors = VGroup() x_max = int(np.ceil(FRAME_WIDTH)) y_max = int(np.ceil(FRAME_HEIGHT)) step = 0.5 for x in np.arange(-x_max, x_max + 1, step): for y in np.arange(-y_max, y_max + 1, step): point = x * RIGHT + y * UP vectors.add(Vector(RIGHT).shift(point)) vectors.set_color_by_gradient(YELLOW, RED) return vectors def update_vectors(self, vectors): time = self.time_tracker.get_value() for vector in vectors: point = vector.get_start() out_point = self.func(point, time) norm = get_norm(out_point) if norm == 0: out_point = RIGHT # Fake it vector.set_fill(opacity=0) else: out_point *= 0.5 color = interpolate_color(BLUE, RED, norm / np.sqrt(8)) vector.set_fill(color, opacity=1) vector.set_stroke(BLACK, width=1) new_x, new_y = out_point[:2] vector.put_start_and_end_on( point, point + new_x * RIGHT + new_y * UP ) def func(self, point, time): x, y, z = point return np.array([ np.sin(time + 0.5 * x + y), np.cos(time + 0.2 * x * y + 0.7), 0 ]) class MoreTopics(Scene): def construct(self): calculus = OldTexText("Calculus") calculus.next_to(LEFT, LEFT) calculus.set_color(YELLOW) calculus.add_background_rectangle() others = VGroup( OldTexText("Multivariable calculus"), OldTexText("Complex analysis"), OldTexText("Differential geometry"), OldTexText("$\\vdots$") ) for word in others: word.add_background_rectangle() others.arrange( DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT, ) others.next_to(RIGHT, RIGHT) lines = VGroup(*[ Line(calculus.get_right(), word.get_left(), buff=MED_SMALL_BUFF) for word in others ]) rect = FullScreenFadeRectangle(fill_opacity=0.7) self.add(rect) self.add(calculus) self.play( LaggedStartMap(ShowCreation, lines), LaggedStartMap(Write, others), ) self.wait() self.calculus = calculus self.lines = lines self.full_screen_rect = rect self.other_topics = others class TransformationalViewWrapper(Wrapper): CONFIG = { "title": "Transformational view" } class SetTheStage(TeacherStudentsScene): def construct(self): ordinary = OldTexText("Ordinary visual") transformational = OldTexText("Transformational visual") for word in ordinary, transformational: word.move_to(self.hold_up_spot, DOWN) word.shift_onto_screen() self.screen.scale(1.25, about_edge=UL) self.add(self.screen) self.teacher_holds_up( ordinary, added_anims=[self.change_students(*3 * ["sassy"])] ) self.wait() self.play( ordinary.shift, UP, FadeInFromDown(transformational), self.teacher.change, "hooray", self.change_students(*3 * ["erm"]) ) self.wait(3) self.play_all_student_changes("pondering", look_at=self.screen) class StandardDerivativeVisual(GraphScene): CONFIG = { "y_max": 8, "y_axis_height": 5, } def construct(self): self.add_title() self.show_function_graph() self.show_slope_of_graph() self.encourage_not_to_think_of_slope_as_definition() self.show_sensitivity() def add_title(self): title = self.title = OldTexText("Standard derivative visual") title.to_edge(UP) h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_WIDTH - 2 * LARGE_BUFF) h_line.next_to(title, DOWN) self.add(title, h_line) def show_function_graph(self): self.setup_axes() def func(x): x -= 5 return 0.1 * (x + 3) * (x - 3) * x + 3 graph = self.get_graph(func) graph_label = self.get_graph_label(graph, x_val=9.5) input_tracker = ValueTracker(4) def get_x_value(): return input_tracker.get_value() def get_y_value(): return graph.underlying_function(get_x_value()) def get_x_point(): return self.coords_to_point(get_x_value(), 0) def get_y_point(): return self.coords_to_point(0, get_y_value()) def get_graph_point(): return self.coords_to_point(get_x_value(), get_y_value()) def get_v_line(): return DashedLine(get_x_point(), get_graph_point(), stroke_width=2) def get_h_line(): return DashedLine(get_graph_point(), get_y_point(), stroke_width=2) input_triangle = RegularPolygon(n=3, start_angle=TAU / 4) output_triangle = RegularPolygon(n=3, start_angle=0) for triangle in input_triangle, output_triangle: triangle.set_fill(WHITE, 1) triangle.set_stroke(width=0) triangle.scale(0.1) input_triangle_update = input_tracker.add_updater( lambda m: m.move_to(get_x_point(), UP) ) output_triangle_update = output_triangle.add_updater( lambda m: m.move_to(get_y_point(), RIGHT) ) x_label = OldTex("x") x_label_update = Mobject.add_updater( x_label, lambda m: m.next_to(input_triangle, DOWN, SMALL_BUFF) ) output_label = OldTex("f(x)") output_label_update = Mobject.add_updater( output_label, lambda m: m.next_to( output_triangle, LEFT, SMALL_BUFF) ) v_line = get_v_line() v_line_update = Mobject.add_updater( v_line, lambda vl: Transform(vl, get_v_line()).update(1) ) h_line = get_h_line() h_line_update = Mobject.add_updater( h_line, lambda hl: Transform(hl, get_h_line()).update(1) ) graph_dot = Dot(color=YELLOW) graph_dot_update = Mobject.add_updater( graph_dot, lambda m: m.move_to(get_graph_point()) ) self.play( ShowCreation(graph), Write(graph_label), ) self.play( DrawBorderThenFill(input_triangle, run_time=1), Write(x_label), ShowCreation(v_line), GrowFromCenter(graph_dot), ) self.add_foreground_mobject(graph_dot) self.play( ShowCreation(h_line), Write(output_label), DrawBorderThenFill(output_triangle, run_time=1) ) self.add( input_triangle_update, x_label_update, graph_dot_update, v_line_update, h_line_update, output_triangle_update, output_label_update, ) self.play( input_tracker.set_value, 8, run_time=6, rate_func=there_and_back ) self.input_tracker = input_tracker self.graph = graph def show_slope_of_graph(self): input_tracker = self.input_tracker deriv_input_tracker = ValueTracker(input_tracker.get_value()) # Slope line def get_slope_line(): return self.get_secant_slope_group( x=deriv_input_tracker.get_value(), graph=self.graph, dx=0.01, secant_line_length=4 ).secant_line slope_line = get_slope_line() slope_line_update = Mobject.add_updater( slope_line, lambda sg: Transform(sg, get_slope_line()).update(1) ) def position_deriv_label(deriv_label): deriv_label.next_to(slope_line, UP) return deriv_label deriv_label = OldTex( "\\frac{df}{dx}(x) =", "\\text{Slope}", "=" ) deriv_label.get_part_by_tex("Slope").match_color(slope_line) deriv_label_update = Mobject.add_updater( deriv_label, position_deriv_label ) slope_decimal = DecimalNumber(slope_line.get_slope()) slope_decimal.match_color(slope_line) slope_decimal.add_updater( lambda d: d.set_value(slope_line.get_slope()) ) slope_decimal.add_upater( lambda d: d.next_to( deriv_label, RIGHT, SMALL_BUFF ).shift(0.2 * SMALL_BUFF * DOWN) ) self.play( ShowCreation(slope_line), Write(deriv_label), Write(slope_decimal), run_time=1 ) self.wait() self.add( slope_line_update, # deriv_label_update, ) for x in 9, 2, 4: self.play( input_tracker.set_value, x, deriv_input_tracker.set_value, x, run_time=3 ) self.wait() self.deriv_input_tracker = deriv_input_tracker def encourage_not_to_think_of_slope_as_definition(self): morty = Mortimer(height=2) morty.to_corner(DR) self.play(FadeIn(morty)) self.play(PiCreatureSays( morty, "Don't think of \\\\ this as the definition", bubble_config={"height": 2, "width": 4} )) self.play(Blink(morty)) self.wait() self.play( RemovePiCreatureBubble(morty), UpdateFromAlphaFunc( morty, lambda m, a: m.set_fill(opacity=1 - a), remover=True ) ) def show_sensitivity(self): input_tracker = self.input_tracker deriv_input_tracker = self.deriv_input_tracker self.wiggle_input() for x in 9, 7, 2: self.play( input_tracker.set_value, x, deriv_input_tracker.set_value, x, run_time=3 ) self.wiggle_input() ### def wiggle_input(self, dx=0.5, run_time=3): input_tracker = self.input_tracker x = input_tracker.get_value() x_min = x - dx x_max = x + dx y, y_min, y_max = list(map( self.graph.underlying_function, [x, x_min, x_max] )) x_line = Line( self.coords_to_point(x_min, 0), self.coords_to_point(x_max, 0), ) y_line = Line( self.coords_to_point(0, y_min), self.coords_to_point(0, y_max), ) x_rect, y_rect = rects = VGroup(Rectangle(), Rectangle()) rects.set_stroke(width=0) rects.set_fill(YELLOW, 0.5) x_rect.match_width(x_line) x_rect.stretch_to_fit_height(0.25) x_rect.move_to(x_line) y_rect.match_height(y_line) y_rect.stretch_to_fit_width(0.25) y_rect.move_to(y_line) self.play( ApplyMethod( input_tracker.set_value, input_tracker.get_value() + dx, rate_func=lambda t: wiggle(t, 6) ), FadeIn( rects, rate_func=squish_rate_func(smooth, 0, 0.33), remover=True, ), run_time=run_time, ) self.play(FadeOut(rects)) class EoCWrapper(Scene): def construct(self): title = Title("Essence of calculus") self.play(Write(title)) self.wait() class IntroduceTransformationView(NumberlineTransformationScene): CONFIG = { "func": lambda x: 0.5 * np.sin(2 * x) + x, "number_line_config": { "x_min": 0, "x_max": 6, "unit_size": 2.0 }, } def construct(self): self.add_title() self.show_animation_preview() self.indicate_indicate_point_densities() self.show_zoomed_transformation() def add_title(self): title = self.title = OldTexText("$f(x)$ as a transformation") title.to_edge(UP) self.add(title) def show_animation_preview(self): input_points = self.get_sample_input_points() output_points = list(map( self.number_func_to_point_func(self.func), input_points )) sample_dots = self.get_sample_dots() sample_dot_ghosts = sample_dots.copy().fade(0.5) arrows = VGroup(*[ Arrow(ip, op, buff=MED_SMALL_BUFF) for ip, op in zip(input_points, output_points) ]) arrows = arrows[1::3] arrows.set_stroke(BLACK, 1) for sd in sample_dots: sd.save_state() sd.scale(2) sd.fade(1) self.play(LaggedStartMap( ApplyMethod, sample_dots, lambda sd: (sd.restore,), run_time=2 )) self.play(LaggedStartMap( GrowArrow, arrows, run_time=6, lag_ratio=0.3, )) self.add(sample_dot_ghosts) self.apply_function( self.func, sample_dots=sample_dots, run_time=3 ) self.wait() self.play(LaggedStartMap(FadeOut, arrows, run_time=1)) self.sample_dots = sample_dots self.sample_dot_ghosts = sample_dot_ghosts def indicate_indicate_point_densities(self): lower_brace = Brace(Line(LEFT, RIGHT), UP) upper_brace = lower_brace.copy() input_tracker = ValueTracker(0.5) dx = 0.5 def update_upper_brace(brace): x = input_tracker.get_value() line = Line( self.get_input_point(x), self.get_input_point(x + dx), ) brace.match_width(line, stretch=True) brace.next_to(line, UP, buff=SMALL_BUFF) return brace def update_lower_brace(brace): x = input_tracker.get_value() line = Line( self.get_output_point(self.func(x)), self.get_output_point(self.func(x + dx)), ) brace.match_width(line, stretch=True) brace.next_to(line, UP, buff=SMALL_BUFF) return brace lower_brace_anim = UpdateFromFunc(lower_brace, update_lower_brace) upper_brace_anim = UpdateFromFunc(upper_brace, update_upper_brace) new_title = OldTexText( "$\\frac{df}{dx}(x)$ measures stretch/squishing" ) new_title.move_to(self.title, UP) stretch_factor = DecimalNumber(0, color=YELLOW) stretch_factor_anim = ChangingDecimal( stretch_factor, lambda a: lower_brace.get_width() / upper_brace.get_width(), position_update_func=lambda m: m.next_to(lower_brace, UP, SMALL_BUFF) ) self.play( GrowFromCenter(upper_brace), FadeOut(self.title), # FadeIn(new_title) Write(new_title, run_time=2) ) self.title = new_title self.play( ReplacementTransform(upper_brace.copy(), lower_brace), GrowFromPoint(stretch_factor, upper_brace.get_center()) ) self.play( input_tracker.set_value, self.input_line.x_max - dx, lower_brace_anim, upper_brace_anim, stretch_factor_anim, run_time=8, rate_func=bezier([0, 0, 1, 1]) ) self.wait() new_sample_dots = self.get_sample_dots() self.play( FadeOut(VGroup( upper_brace, lower_brace, stretch_factor, self.sample_dots, self.moving_input_line, )), FadeIn(new_sample_dots), ) self.sample_dots = new_sample_dots def show_zoomed_transformation(self): x = 2.75 local_sample_dots = self.get_local_sample_dots(x) self.zoom_in_on_input( x, local_sample_dots=local_sample_dots, local_coordinate_values=self.get_local_coordinate_values(x), ) self.wait() self.apply_function( self.func, sample_dots=self.sample_dots, local_sample_dots=local_sample_dots, target_coordinate_values=self.get_local_coordinate_values(self.func(x)) ) self.wait() class ExamplePlease(TeacherStudentsScene): def construct(self): self.student_says("Example?", index=0) self.teacher_holds_up(OldTex("f(x) = x^2").scale(1.5)) self.wait(2) class TalkThroughXSquaredExample(IntroduceTransformationView): CONFIG = { "func": lambda x: x**2, "number_line_config": { "x_min": 0, "x_max": 5, "unit_size": 1.25, }, "output_line_config": { "x_max": 25, }, "default_delta_x": 0.2 } def construct(self): self.add_title() self.show_specific_points_mapping() def add_title(self): title = self.title = OldTexText("$f(x) = x^2$") title.to_edge(UP, buff=MED_SMALL_BUFF) self.add(title) def show_specific_points_mapping(self): # First, just show integers as examples int_dots = self.get_sample_dots(1, 6, 1) int_dot_ghosts = int_dots.copy().fade(0.5) int_arrows = VGroup(*[ Arrow( # num.get_bottom(), self.get_input_point(x), self.get_output_point(self.func(x)), buff=MED_SMALL_BUFF ) for x, num in zip(list(range(1, 6)), self.input_line.numbers[1:]) ]) point_func = self.number_func_to_point_func(self.func) numbers = self.input_line.numbers numbers.next_to(self.input_line, UP, SMALL_BUFF) self.titles[0].next_to(numbers, UP, MED_SMALL_BUFF, LEFT) # map(Tex.add_background_rectangle, numbers) # self.add_foreground_mobject(numbers) for dot, dot_ghost, arrow in zip(int_dots, int_dot_ghosts, int_arrows): arrow.match_color(dot) self.play(DrawBorderThenFill(dot, run_time=1)) self.add(dot_ghost) self.play( GrowArrow(arrow), dot.apply_function_to_position, point_func ) self.wait() # Show more sample_dots sample_dots = self.get_sample_dots() sample_dot_ghosts = sample_dots.copy().fade(0.5) self.play( LaggedStartMap(DrawBorderThenFill, sample_dots), LaggedStartMap(FadeOut, int_arrows), ) self.remove(int_dot_ghosts) self.add(sample_dot_ghosts) self.apply_function(self.func, sample_dots=sample_dots) self.remove(int_dots) self.wait() self.sample_dots = sample_dots self.sample_dot_ghosts = sample_dot_ghosts def get_stretch_words(self, factor, color=RED, less_than_one=False): factor_str = "$%s$" % str(factor) result = OldTexText( "Scale \\\\ by", factor_str, tex_to_color_map={factor_str: color} ) result.scale(0.7) la, ra = OldTex("\\leftarrow \\rightarrow") if less_than_one: la, ra = ra, la if factor < 0: kwargs = { "path_arc": np.pi, } la = Arrow(UP, DOWN, **kwargs) ra = Arrow(DOWN, UP, **kwargs) for arrow in la, ra: arrow.pointwise_become_partial(arrow, 0, 0.9) arrow.tip.scale(2) VGroup(la, ra).match_height(result) la.next_to(result, LEFT) ra.next_to(result, RIGHT) result.add(la, ra) result.next_to( self.zoomed_display.get_top(), DOWN, SMALL_BUFF ) return result def get_deriv_equation(self, x, rhs, color=RED): deriv_equation = self.deriv_equation = OldTex( "\\frac{df}{dx}(", str(x), ")", "=", str(rhs), tex_to_color_map={str(x): color, str(rhs): color} ) deriv_equation.next_to(self.title, DOWN, MED_LARGE_BUFF) return deriv_equation class ZoomInOnXSquaredNearOne(TalkThroughXSquaredExample): def setup(self): TalkThroughXSquaredExample.setup(self) self.force_skipping() self.add_title() self.show_specific_points_mapping() self.revert_to_original_skipping_status() def construct(self): zoom_words = OldTexText("Zoomed view \\\\ near 1") zoom_words.next_to(self.zoomed_display, DOWN) # zoom_words.shift_onto_screen() x = 1 local_sample_dots = self.get_local_sample_dots(x) local_coords = self.get_local_coordinate_values(x, dx=0.1) zcbr_anim = self.zoomed_camera_background_rectangle_anim zcbr_group = self.zoomed_camera_background_rectangle_group frame = self.zoomed_camera.frame sample_dot_ghost_copies = self.sample_dot_ghosts.copy() self.zoom_in_on_input(x, local_sample_dots, local_coords) self.play(FadeIn(zoom_words)) self.wait() local_sample_dots.save_state() frame.save_state() self.mini_line.save_state() self.apply_function( self.func, apply_function_to_number_line=False, sample_dots=sample_dot_ghost_copies, local_sample_dots=local_sample_dots, target_coordinate_values=local_coords ) self.remove(sample_dot_ghost_copies) self.wait() # Go back self.play( frame.restore, self.mini_line.restore, local_sample_dots.restore, zcbr_anim, Animation(zcbr_group) ) self.wait() # Zoom in even more extra_zoom_factor = 0.3 one_group = VGroup( self.local_coordinates.tick_marks[1], self.local_coordinates.numbers[1], ) all_other_coordinates = VGroup( self.local_coordinates.tick_marks[::2], self.local_coordinates.numbers[::2], self.local_target_coordinates, ) self.play(frame.scale, extra_zoom_factor) new_local_sample_dots = self.get_local_sample_dots(x, delta_x=0.005) new_coordinate_values = self.get_local_coordinate_values(x, dx=0.02) new_local_coordinates = self.get_local_coordinates( self.input_line, *new_coordinate_values ) self.play( Write(new_local_coordinates), Write(new_local_sample_dots), one_group.scale, extra_zoom_factor, {"about_point": self.get_input_point(1)}, FadeOut(all_other_coordinates), *[ ApplyMethod(dot.scale, extra_zoom_factor) for dot in local_sample_dots ] ) self.remove(one_group, local_sample_dots) zcbr_group.remove( self.local_coordinates, self.local_target_coordinates, local_sample_dots ) # Transform new zoomed view stretch_by_two_words = self.get_stretch_words(2) self.add_foreground_mobject(stretch_by_two_words) sample_dot_ghost_copies = self.sample_dot_ghosts.copy() self.apply_function( self.func, apply_function_to_number_line=False, sample_dots=sample_dot_ghost_copies, local_sample_dots=new_local_sample_dots, target_coordinate_values=new_coordinate_values, added_anims=[FadeIn(stretch_by_two_words)] ) self.remove(sample_dot_ghost_copies) self.wait() # Write derivative deriv_equation = self.get_deriv_equation(1, 2, color=RED) self.play(Write(deriv_equation)) self.wait() class ZoomInOnXSquaredNearThree(ZoomInOnXSquaredNearOne): CONFIG = { "zoomed_display_width": 4, } def construct(self): zoom_words = OldTexText("Zoomed view \\\\ near 3") zoom_words.next_to(self.zoomed_display, DOWN) x = 3 local_sample_dots = self.get_local_sample_dots(x) local_coordinate_values = self.get_local_coordinate_values(x, dx=0.1) target_coordinate_values = self.get_local_coordinate_values(self.func(x), dx=0.1) color = self.sample_dots[len(self.sample_dots) / 2].get_color() sample_dot_ghost_copies = self.sample_dot_ghosts.copy() stretch_words = self.get_stretch_words(2 * x, color) deriv_equation = self.get_deriv_equation(x, 2 * x, color) self.add(deriv_equation) self.zoom_in_on_input( x, pop_out=False, local_sample_dots=local_sample_dots, local_coordinate_values=local_coordinate_values ) self.play(Write(zoom_words, run_time=1)) self.wait() self.add_foreground_mobject(stretch_words) self.apply_function( self.func, apply_function_to_number_line=False, sample_dots=sample_dot_ghost_copies, local_sample_dots=local_sample_dots, target_coordinate_values=target_coordinate_values, added_anims=[Write(stretch_words)] ) self.wait(2) class ZoomInOnXSquaredNearOneFourth(ZoomInOnXSquaredNearOne): CONFIG = { "zoom_factor": 0.01, "local_coordinate_num_decimal_places": 4, "zoomed_display_width": 4, "default_delta_x": 0.25, } def construct(self): # Much copy-pasting from previous scenes. Not great, but # the fastest way to get the ease-of-tweaking I'd like. zoom_words = OldTexText("Zoomed view \\\\ near $1/4$") zoom_words.next_to(self.zoomed_display, DOWN) x = 0.25 local_sample_dots = self.get_local_sample_dots( x, sample_radius=2.5 * self.zoomed_camera.frame.get_width(), ) local_coordinate_values = self.get_local_coordinate_values( x, dx=0.01, ) target_coordinate_values = self.get_local_coordinate_values( self.func(x), dx=0.01, ) color = RED sample_dot_ghost_copies = self.sample_dot_ghosts.copy() stretch_words = self.get_stretch_words("1/2", color, less_than_one=True) deriv_equation = self.get_deriv_equation("1/4", "1/2", color) one_fourth_point = self.get_input_point(x) one_fourth_arrow = Vector(0.5 * UP, color=WHITE) one_fourth_arrow.stem.stretch(0.75, 0) one_fourth_arrow.tip.scale(0.75, about_edge=DOWN) one_fourth_arrow.next_to(one_fourth_point, DOWN, SMALL_BUFF) one_fourth_label = OldTex("0.25") one_fourth_label.match_height(self.input_line.numbers) one_fourth_label.next_to(one_fourth_arrow, DOWN, SMALL_BUFF) self.add(deriv_equation) self.zoom_in_on_input( x, local_sample_dots=local_sample_dots, local_coordinate_values=local_coordinate_values, pop_out=False, first_added_anims=[ FadeIn(one_fourth_label), GrowArrow(one_fourth_arrow), ] ) self.play(Write(zoom_words, run_time=1)) self.wait() self.add_foreground_mobject(stretch_words) self.apply_function( self.func, apply_function_to_number_line=False, sample_dots=sample_dot_ghost_copies, local_sample_dots=local_sample_dots, target_coordinate_values=target_coordinate_values, added_anims=[Write(stretch_words)] ) self.wait(2) class ZoomInOnXSquaredNearZero(ZoomInOnXSquaredNearOne): CONFIG = { "zoom_factor": 0.1, "zoomed_display_width": 4, "scale_by_term": "???", } def construct(self): zoom_words = OldTexText( "Zoomed %sx \\\\ near 0" % "{:,}".format(int(1.0 / self.zoom_factor)) ) zoom_words.next_to(self.zoomed_display, DOWN) x = 0 local_sample_dots = self.get_local_sample_dots( x, sample_radius=2 * self.zoomed_camera.frame.get_width() ) local_coordinate_values = self.get_local_coordinate_values( x, dx=self.zoom_factor ) # target_coordinate_values = self.get_local_coordinate_values( # self.func(x), dx=self.zoom_factor # ) color = self.sample_dots[len(self.sample_dots) / 2].get_color() sample_dot_ghost_copies = self.sample_dot_ghosts.copy() stretch_words = self.get_stretch_words( self.scale_by_term, color, less_than_one=True ) deriv_equation = self.get_deriv_equation(x, 2 * x, color) self.add(deriv_equation) self.zoom_in_on_input( x, pop_out=False, local_sample_dots=local_sample_dots, local_coordinate_values=local_coordinate_values ) self.play(Write(zoom_words, run_time=1)) self.wait() self.add_foreground_mobject(stretch_words) self.apply_function( self.func, apply_function_to_number_line=False, sample_dots=sample_dot_ghost_copies, local_sample_dots=local_sample_dots, # target_coordinate_values=target_coordinate_values, added_anims=[ Write(stretch_words), MaintainPositionRelativeTo( self.local_coordinates, self.zoomed_camera.frame ) ] ) self.wait(2) class ZoomInMoreAndMoreToZero(ZoomInOnXSquaredNearZero): def construct(self): x = 0 color = self.sample_dots[len(self.sample_dots) / 2].get_color() deriv_equation = self.get_deriv_equation(x, 2 * x, color) self.add(deriv_equation) frame = self.zoomed_camera.frame zoomed_display_height = self.zoomed_display.get_height() last_sample_dots = VGroup() last_coords = VGroup() last_zoom_words = None for factor in 0.1, 0.01, 0.001, 0.0001: frame.save_state() frame.set_height(factor * zoomed_display_height) self.local_coordinate_num_decimal_places = int(-np.log10(factor)) zoom_words = OldTexText( "Zoomed", "{:,}x \\\\".format(int(1.0 / factor)), "near 0", ) zoom_words.next_to(self.zoomed_display, DOWN) sample_dots = self.get_local_sample_dots(x) coords = self.get_local_coordinate_values(x, dx=factor) frame.restore() added_anims = [ ApplyMethod(last_sample_dots.fade, 1), ApplyMethod(last_coords.fade, 1), ] if last_zoom_words is not None: added_anims.append(ReplacementTransform( last_zoom_words, zoom_words )) else: added_anims.append(FadeIn(zoom_words)) self.zoom_in_on_input( x, local_sample_dots=sample_dots, local_coordinate_values=coords, pop_out=False, zoom_factor=factor, first_added_anims=added_anims ) self.wait() last_sample_dots = sample_dots last_coords = self.local_coordinates last_zoom_words = zoom_words class ZoomInOnXSquared100xZero(ZoomInOnXSquaredNearZero): CONFIG = { "zoom_factor": 0.01 } class ZoomInOnXSquared1000xZero(ZoomInOnXSquaredNearZero): CONFIG = { "zoom_factor": 0.001, "local_coordinate_num_decimal_places": 3, } class ZoomInOnXSquared10000xZero(ZoomInOnXSquaredNearZero): CONFIG = { "zoom_factor": 0.0001, "local_coordinate_num_decimal_places": 4, "scale_by_term": "0", } class XSquaredForNegativeInput(TalkThroughXSquaredExample): CONFIG = { "input_line_config": { "x_min": -4, "x_max": 4, }, "input_line_zero_point": 0.5 * UP + 0 * LEFT, "output_line_config": {}, "default_mapping_animation_config": { "path_arc": 30 * DEGREES }, "zoomed_display_width": 4, } def construct(self): self.add_title() self.show_full_transformation() self.zoom_in_on_example() def show_full_transformation(self): sample_dots = self.get_sample_dots( x_min=-4.005, delta_x=0.05, dot_radius=0.05 ) sample_dots.set_fill(opacity=0.8) self.play(LaggedStartMap(DrawBorderThenFill, sample_dots)) self.play(LaggedStartMap( ApplyFunction, sample_dots[len(sample_dots) / 2:0:-1], lambda mob: ( lambda m: m.scale(2).shift(SMALL_BUFF * UP).set_color(PINK), mob, ), rate_func=there_and_back, )) self.add_sample_dot_ghosts(sample_dots) self.apply_function(self.func, sample_dots=sample_dots) self.wait() def zoom_in_on_example(self): x = -2 local_sample_dots = self.get_local_sample_dots(x) local_coordinate_values = self.get_local_coordinate_values( x, dx=0.1 ) target_coordinate_values = self.get_local_coordinate_values( self.func(x), dx=0.1 ) deriv_equation = self.get_deriv_equation(x, 2 * x, color=BLUE) sample_dot_ghost_copies = self.sample_dot_ghosts.copy() scale_words = self.get_stretch_words(-4, color=BLUE) self.zoom_in_on_input( x, local_sample_dots=local_sample_dots, local_coordinate_values=local_coordinate_values, ) self.wait() self.play(Write(deriv_equation)) self.add_foreground_mobject(scale_words) self.play(Write(scale_words)) self.apply_function( self.func, sample_dots=sample_dot_ghost_copies, local_sample_dots=local_sample_dots, target_coordinate_values=target_coordinate_values ) self.wait() class FeelsALittleCramped(TeacherStudentsScene): def construct(self): self.student_says( "Kind of cramped,\\\\ isn't it?", target_mode="sassy" ) self.wait() self.teacher_says( "Sure, but think \\\\ locally" ) self.play_all_student_changes("pondering", look_at=self.screen) self.wait(3) class HowDoesThisSolveProblems(TeacherStudentsScene): def construct(self): self.student_says( "Is this...useful?", target_mode="confused" ) self.play_student_changes("maybe", "confused", "sassy") self.play(self.teacher.change, "happy") self.wait(3) class IntroduceContinuedFractionPuzzle(PiCreatureScene): CONFIG = { "remove_initial_rhs": True, } def construct(self): self.ask_question() self.set_equal_to_x() def create_pi_creatures(self): morty = Mortimer(height=2) morty.to_corner(DR) friend = PiCreature(color=GREEN, height=2) friend.to_edge(DOWN) friend.shift(LEFT) group = VGroup(morty, friend) group.shift(2 * LEFT) return morty, friend def ask_question(self): morty, friend = self.pi_creatures frac = get_phi_continued_fraction(9) frac.scale(0.8) rhs = DecimalNumber( (1 - np.sqrt(5)) / 2.0, num_decimal_places=5, show_ellipsis=True, ) rhs.set_color(YELLOW) equals = OldTex("=") equals.next_to(frac.get_part_by_tex("\\over"), RIGHT) rhs.next_to(equals, RIGHT) group = VGroup(frac, equals, rhs) group.scale(1.5) group.to_corner(UR) self.play( LaggedStartMap( Write, frac, run_time=15, lag_ratio=0.15, ), FadeInFromDown(equals), FadeInFromDown(rhs), PiCreatureSays( friend, "Would this be valid? \\\\ If not, why not?", target_mode="confused", look_at=frac, bubble_config={ "direction": RIGHT, "width": 4, "height": 3, } ), morty.change, "pondering", ) self.wait() anims = [ RemovePiCreatureBubble( friend, target_mode="pondering", look_at=frac ), ] if self.remove_initial_rhs: anims += [ Animation(frac), FadeOut(equals), rhs.scale, 0.5, rhs.to_corner, DL, ] self.play(*anims) self.neg_one_over_phi = rhs self.equals = equals self.frac = frac def set_equal_to_x(self): frac = self.frac morty, friend = self.get_pi_creatures() inner_frac = frac[4:] inner_frac_rect = SurroundingRectangle( inner_frac, stroke_width=2, buff=0.5 * SMALL_BUFF ) inner_frac_group = VGroup(inner_frac, inner_frac_rect) equals = OldTex("=") equals.next_to(frac[3], RIGHT) x, new_x = [Tex("x") for i in range(2)] xs = VGroup(x, new_x) xs.set_color(YELLOW) xs.scale(1.3) x.next_to(equals, RIGHT) new_x.next_to(frac[3], DOWN, 2 * SMALL_BUFF) fixed_point_words = VGroup( OldTexText("Fixed point of"), OldTex( "f(x) = 1 + \\frac{1}{x}", tex_to_color_map={"x": YELLOW} ) ) fixed_point_words.arrange(DOWN) self.play(Write(x), Write(equals)) self.wait() self.play(ShowCreation(inner_frac_rect)) self.wait() self.play( inner_frac_group.scale, 0.75, inner_frac_group.center, inner_frac_group.to_edge, LEFT, ReplacementTransform( x.copy(), new_x, path_arc=-90 * DEGREES ) ) self.wait() self.play( frac[3].stretch, 0.1, 0, {"about_edge": RIGHT}, MaintainPositionRelativeTo( VGroup(frac[2], new_x), frac[3] ), UpdateFromFunc( frac[:2], lambda m: m.next_to(frac[3], LEFT) ) ) self.wait() fixed_point_words.next_to(VGroup(frac[0], xs), DOWN, LARGE_BUFF) self.play( Write(fixed_point_words), morty.change, "hooray", friend.change, "happy" ) self.wait(3) class GraphOnePlusOneOverX(GraphScene): CONFIG = { "x_min": -6, "x_max": 6, "x_axis_width": 12, "y_min": -4, "y_max": 5, "y_axis_height": 8, "y_axis_label": None, "graph_origin": 0.5 * DOWN, "num_graph_anchor_points": 100, "func_graph_color": GREEN, "identity_graph_color": BLUE, } def construct(self): self.add_title() self.setup_axes() self.draw_graphs() self.show_solutions() def add_title(self): title = self.title = OldTex( "\\text{Solve: }", "1 + \\frac{1}{x}", "=", "x", ) title.set_color_by_tex("x", self.identity_graph_color, substring=False) title.set_color_by_tex("frac", self.func_graph_color) title.to_corner(UL) self.add(title) def setup_axes(self): GraphScene.setup_axes(self) step = 2 self.x_axis.add_numbers(*list(range(-6, 0, step)) + list(range(step, 7, step))) self.y_axis.label_direction = RIGHT self.y_axis.add_numbers(*list(range(-2, 0, step)) + list(range(step, 4, step))) def draw_graphs(self, animate=True): lower_func_graph, upper_func_graph = func_graph = VGroup(*[ self.get_graph( lambda x: 1.0 + 1.0 / x, x_min=x_min, x_max=x_max, color=self.func_graph_color, ) for x_min, x_max in [(-10, -0.1), (0.1, 10)] ]) func_graph.label = self.get_graph_label( upper_func_graph, "y = 1 + \\frac{1}{x}", x_val=6, direction=UP, ) identity_graph = self.get_graph( lambda x: x, color=self.identity_graph_color ) identity_graph.label = self.get_graph_label( identity_graph, "y = x", x_val=3, direction=UL, buff=SMALL_BUFF ) if animate: for graph in func_graph, identity_graph: self.play( ShowCreation(graph), Write(graph.label), run_time=2 ) self.wait() else: self.add( func_graph, func_graph.label, identity_graph, identity_graph.label, ) self.func_graph = func_graph self.identity_graph = identity_graph def show_solutions(self): phi = 0.5 * (1 + np.sqrt(5)) phi_bro = 0.5 * (1 - np.sqrt(5)) lines = VGroup() for num in phi, phi_bro: line = DashedLine( self.coords_to_point(num, 0), self.coords_to_point(num, num), color=WHITE ) line_copy = line.copy() line_copy.set_color(YELLOW) line.fade(0.5) line_anim = ShowCreationThenDestruction( line_copy, lag_ratio=0.5, run_time=2 ) cycle_animation(line_anim) lines.add(line) phi_line, phi_bro_line = lines decimal_kwargs = { "num_decimal_places": 3, "show_ellipsis": True, "color": YELLOW, } arrow_kwargs = { "buff": SMALL_BUFF, "color": WHITE, "tip_length": 0.15, "rectangular_stem_width": 0.025, } phi_decimal = DecimalNumber(phi, **decimal_kwargs) phi_decimal.next_to(phi_line, DOWN, LARGE_BUFF) phi_arrow = Arrow( phi_decimal[:4].get_top(), phi_line.get_bottom(), **arrow_kwargs ) phi_label = OldTex("=", "\\varphi") phi_label.next_to(phi_decimal, RIGHT) phi_label.set_color_by_tex("\\varphi", YELLOW) phi_bro_decimal = DecimalNumber(phi_bro, **decimal_kwargs) phi_bro_decimal.next_to(phi_bro_line, UP, LARGE_BUFF) phi_bro_decimal.shift(0.5 * LEFT) phi_bro_arrow = Arrow( phi_bro_decimal[:6].get_bottom(), phi_bro_line.get_top(), **arrow_kwargs ) brother_words = OldTexText( "$\\varphi$'s little brother", tex_to_color_map={"$\\varphi$": YELLOW}, arg_separator="" ) brother_words.next_to( phi_bro_decimal[-2], UP, buff=MED_SMALL_BUFF, aligned_edge=RIGHT ) self.add(phi_line.continual_anim) self.play(ShowCreation(phi_line)) self.play( Write(phi_decimal), GrowArrow(phi_arrow), ) self.play(Write(phi_label)) self.wait(3) self.add(phi_bro_line.continual_anim) self.play(ShowCreation(phi_bro_line)) self.play( Write(phi_bro_decimal), GrowArrow(phi_bro_arrow), ) self.wait(4) self.play(Write(brother_words)) self.wait(8) class ThinkAboutWithRepeatedApplication(IntroduceContinuedFractionPuzzle): CONFIG = { "remove_initial_rhs": False, } def construct(self): self.force_skipping() self.ask_question() self.revert_to_original_skipping_status() self.obviously_not() self.ask_about_fraction() self.plug_func_into_self() def obviously_not(self): morty, friend = self.get_pi_creatures() friend.change_mode("confused") randy = Randolph() randy.match_height(morty) randy.to_corner(DL) frac = self.frac rhs = self.neg_one_over_phi plusses = frac[1::4] plus_rects = VGroup(*[ SurroundingRectangle(plus, buff=0) for plus in plusses ]) plus_rects.set_color(PINK) self.play(FadeIn(randy)) self.play( PiCreatureSays( randy, "Obviously not!", bubble_config={"width": 3, "height": 2}, target_mode="angry", run_time=1, ), morty.change, "guilty", friend.change, "hesitant" ) self.wait() self.play( Animation(frac), RemovePiCreatureBubble(randy, target_mode="sassy"), morty.change, "confused", friend.change, "confused", ) self.play(LaggedStartMap( ShowCreationThenDestruction, plus_rects, run_time=2, lag_ratio=0.35, )) self.play(WiggleOutThenIn(rhs)) self.wait(2) self.play( frac.scale, 0.7, frac.to_corner, UL, FadeOut(self.equals), rhs.scale, 0.5, rhs.center, rhs.to_edge, LEFT, FadeOut(randy), morty.change, "pondering", friend.change, "pondering", ) def ask_about_fraction(self): frac = self.frac arrow = Vector(LEFT, color=RED) arrow.next_to(frac, RIGHT) question = OldTexText("What does this \\\\ actually mean?") question.set_color(RED) question.next_to(arrow, RIGHT) self.play( LaggedStartMap(FadeIn, question, run_time=1), GrowArrow(arrow), LaggedStartMap( ApplyMethod, frac, lambda m: (m.set_color, RED), rate_func=there_and_back, lag_ratio=0.2, run_time=2 ) ) self.wait() self.play(FadeOut(question), FadeOut(arrow)) def plug_func_into_self(self, value=1, value_str="1"): morty, friend = self.pi_creatures def func(x): return 1 + 1.0 / x lines = VGroup() value_labels = VGroup() for n_terms in range(5): lhs = get_nested_f(n_terms, arg="c") equals = OldTex("=") rhs = get_nested_one_plus_one_over_x(n_terms, bottom_term=value_str) equals.next_to(rhs[0], LEFT) lhs.next_to(equals, LEFT) lines.add(VGroup(lhs, equals, rhs)) value_label = OldTex("= %.3f\\dots" % value) value = func(value) value_labels.add(value_label) lines.arrange( DOWN, buff=MED_LARGE_BUFF, ) VGroup(lines, value_labels).scale(0.8) lines.to_corner(UR) buff = MED_LARGE_BUFF + MED_SMALL_BUFF + value_labels.get_width() lines.to_edge(RIGHT, buff=buff) for line, value_label in zip(lines, value_labels): value_label.move_to(line[1]).to_edge(RIGHT) top_line = lines[0] colors = [WHITE] + color_gradient([YELLOW, RED, PINK], len(lines) - 1) for n in range(1, len(lines)): color = colors[n] lines[n][0].set_color(color) lines[n][0][1:-1].match_style(lines[n - 1][0]) lines[n][2].set_color(color) lines[n][2][4:].match_style(lines[n - 1][2]) arrow = Vector(0.5 * DOWN, color=WHITE) arrow.next_to(value_labels[-1], DOWN) q_marks = OldTex("???") q_marks.next_to(arrow, DOWN) self.play( FadeInFromDown(top_line), FadeInFromDown(value_labels[0]) ) for n in range(1, len(lines)): new_line = lines[n] last_line = lines[n - 1] value_label = value_labels[n] mover, target = [ VGroup( line[0][0], line[0][-1], line[1], line[2][:4], ) for line in (lines[1], new_line) ] anims = [ReplacementTransform( mover.copy().fade(1), target, path_arc=30 * DEGREES )] if n == 4: morty.generate_target() morty.target.change("horrified") morty.target.shift(2.5 * DOWN) anims.append(MoveToTarget(morty, remover=True)) self.play(*anims) self.wait() self.play( ReplacementTransform( last_line[0].copy(), new_line[0][1:-1] ), ReplacementTransform( last_line[2].copy(), new_line[2][4:] ), ) self.play(FadeIn(value_label)) self.wait() self.play( GrowArrow(arrow), Write(q_marks), friend.change, "confused" ) self.wait(3) self.top_line = VGroup(lines[0], value_labels[0]) class RepeatedApplicationWithPhiBro(ThinkAboutWithRepeatedApplication): CONFIG = { "value": (1 - np.sqrt(5)) / 2, "value_str": "-1/\\varphi", } def construct(self): self.force_skipping() self.ask_question() self.obviously_not() self.revert_to_original_skipping_status() self.plug_func_into_self( value=self.value, value_str=self.value_str ) class RepeatedApplicationWithNegativeSeed(RepeatedApplicationWithPhiBro, MovingCameraScene): CONFIG = { "value": -0.65, "value_str": "-0.65" } def setup(self): MovingCameraScene.setup(self) RepeatedApplicationWithPhiBro.setup(self) def construct(self): RepeatedApplicationWithPhiBro.construct(self) rect = SurroundingRectangle(self.top_line) question = OldTexText("What about a negative seed?") question.match_color(rect) question.next_to(rect, UP) self.play(ShowCreation(rect)) self.play( Write(question), self.camera.frame.set_height, FRAME_HEIGHT + 1.5 ) self.wait() self.play( FadeOut(question), FadeOut(rect), self.camera.frame.set_height, FRAME_HEIGHT ) class ShowRepeatedApplication(Scene): CONFIG = { "title_color": YELLOW, } def construct(self): self.add_func_title() self.show_repeated_iteration() def add_func_title(self): title = self.title = VGroup( OldTex("f(", "x", ")"), OldTex("="), get_nested_one_plus_one_over_x(1) ) title.arrange(RIGHT) title.to_corner(UL) title.set_color(self.title_color) self.add(title) def show_repeated_iteration(self): line = VGroup() decimal_kwargs = { "num_decimal_places": 3, "show_ellipsis": True, } phi = (1 + np.sqrt(5)) / 2 def func(x): return 1.0 + 1.0 / x initial_term = DecimalNumber(2.71828, **decimal_kwargs) line.add(initial_term) last_term = initial_term def get_arrow(): arrow = OldTex("\\rightarrow") arrow.stretch(1.5, 0) arrow.next_to(line[-1], RIGHT) tex = OldTex("f(x)") tex.set_color(YELLOW) tex.match_width(arrow) tex.next_to(arrow, UP, SMALL_BUFF) return VGroup(arrow, tex) for x in range(2): arrow = get_arrow() line.add(arrow) new_term = DecimalNumber( func(last_term.number), **decimal_kwargs ) new_term.next_to(arrow[0], RIGHT) last_term = new_term line.add(new_term) line.add(get_arrow()) line.add(OldTex("\\dots\\dots").next_to(line[-1][0], RIGHT)) num_phi_mob = DecimalNumber(phi, **decimal_kwargs) line.add(num_phi_mob.next_to(line[-1], RIGHT)) line.move_to(DOWN) rects = VGroup(*[ SurroundingRectangle(mob) for mob in (line[0], line[1:-1], line[-1]) ]) rects.set_stroke(BLUE, 2) braces = VGroup(*[ Brace(rect, DOWN, buff=SMALL_BUFF) for rect in rects ]) braces.set_color_by_gradient(GREEN, YELLOW) brace_texts = VGroup(*[ brace.get_text(text).scale(0.75, about_edge=UP) for brace, text in zip(braces, [ "Arbitrary \\\\ starting \\\\ value", "Repeatedly apply $f(x)$", "$\\varphi$ \\\\ ``Golden ratio''" ]) ]) var_phi_mob = brace_texts[2][0] var_phi_mob.scale(2, about_edge=UP).set_color(YELLOW) brace_texts[2][1:].next_to(var_phi_mob, DOWN, MED_SMALL_BUFF) # Animations self.add(line[0]) self.play( GrowFromCenter(braces[0]), Write(brace_texts[0]) ) self.wait() self.play( GrowFromEdge(line[1], LEFT), FadeIn(braces[1]), FadeIn(brace_texts[1]), ) self.play(ReplacementTransform(line[0].copy(), line[2])) self.wait() self.play(GrowFromEdge(line[3], LEFT)) self.play(ReplacementTransform(line[2].copy(), line[4])) self.wait() self.play(GrowFromEdge(line[5], LEFT)) self.play(LaggedStartMap(GrowFromCenter, line[6])) self.wait() self.play(FadeIn(line[7])) self.play( GrowFromCenter(braces[2]), FadeIn(brace_texts[2]), ) self.wait() class NumericalPlayFromOne(ExternallyAnimatedScene): pass class NumericalPlayFromTau(ExternallyAnimatedScene): pass class NumericalPlayFromNegPhi(ExternallyAnimatedScene): pass class NumericalPlayOnNumberLineFromOne(Scene): CONFIG = { "starting_value": 1, "n_jumps": 10, "func": lambda x: 1 + 1.0 / x, "number_line_config": { "x_min": 0, "x_max": 2, "unit_size": 6, "tick_frequency": 0.25, "numbers_with_elongated_ticks": [0, 1, 2] } } def construct(self): self.add_number_line() self.add_phi_label() self.add_title() self.bounce_around() def add_number_line(self): number_line = NumberLine(**self.number_line_config) number_line.move_to(2 * DOWN) number_line.add_numbers() self.add(number_line) self.number_line = number_line def add_phi_label(self): number_line = self.number_line phi_point = number_line.number_to_point( (1 + np.sqrt(5)) / 2 ) phi_dot = Dot(phi_point, color=YELLOW) arrow = Vector(DL) arrow.next_to(phi_point, UR, SMALL_BUFF) phi_label = OldTex("\\varphi = 1.618\\dots") phi_label.set_color(YELLOW) phi_label.next_to(arrow.get_start(), UP, SMALL_BUFF) self.add(phi_dot, phi_label, arrow) def add_title(self): title = OldTex("x \\rightarrow 1 + \\frac{1}{x}") title.to_corner(UL) self.add(title) def bounce_around(self): number_line = self.number_line value = self.starting_value point = number_line.number_to_point(value) dot = Dot(point) dot.set_fill(RED, opacity=0.8) arrow = Vector(DR) arrow.next_to(point, UL, buff=SMALL_BUFF) arrow.match_color(dot) start_here = OldTexText("Start here") start_here.next_to(arrow.get_start(), UP, SMALL_BUFF) start_here.match_color(dot) self.play( FadeIn(start_here), GrowArrow(arrow), GrowFromPoint(dot, arrow.get_start()) ) self.play( FadeOut(start_here), FadeOut(arrow) ) self.wait() for x in range(self.n_jumps): new_value = self.func(value) new_point = number_line.number_to_point(new_value) if new_value - value > 0: path_arc = -120 * DEGREES else: path_arc = -120 * DEGREES arc = Line( point, new_point, path_arc=path_arc, buff=SMALL_BUFF ) self.play( ShowCreationThenDestruction(arc, run_time=1.5), ApplyMethod( dot.move_to, new_point, path_arc=path_arc ), ) self.wait(0.5) value = new_value point = new_point class NumericalPlayOnNumberLineFromTau(NumericalPlayOnNumberLineFromOne): CONFIG = { "starting_value": TAU, "number_line_config": { "x_min": 0, "x_max": 7, "unit_size": 2, } } class NumericalPlayOnNumberLineFromMinusPhi(NumericalPlayOnNumberLineFromOne): CONFIG = { "starting_value": -0.61803, "number_line_config": { "x_min": -3, "x_max": 3, "unit_size": 2, "tick_frequency": 0.25, }, "n_jumps": 25, } def add_phi_label(self): NumericalPlayOnNumberLineFromOne.add_phi_label(self) number_line = self.number_line new_point = number_line.number_to_point( (1 - np.sqrt(5)) / 2 ) arrow = Vector(DR) arrow.next_to(new_point, UL, SMALL_BUFF) arrow.set_color(RED) new_label = OldTex("-\\frac{1}{\\varphi} = -0.618\\dots") new_label.set_color(RED) new_label.next_to(arrow.get_start(), UP, SMALL_BUFF) new_label.shift(RIGHT) self.add(new_label, arrow) class RepeatedApplicationGraphically(GraphOnePlusOneOverX, PiCreatureScene): CONFIG = { "starting_value": 1, "n_jumps": 5, "n_times_to_show_identity_property": 2, } def setup(self): GraphOnePlusOneOverX.setup(self) PiCreatureScene.setup(self) def construct(self): self.setup_axes() self.draw_graphs(animate=False) self.draw_spider_web() def create_pi_creature(self): randy = Randolph(height=2) randy.flip() randy.to_corner(DR) return randy def get_new_randy_mode(self): randy = self.pi_creature if not hasattr(self, "n_mode_changes"): self.n_mode_changes = 0 else: self.n_mode_changes += 1 if self.n_mode_changes % 3 != 0: return randy.get_mode() return random.choice([ "confused", "erm", "maybe" ]) def draw_spider_web(self): randy = self.pi_creature func = self.func_graph[0].underlying_function x_val = self.starting_value curr_output = 0 dot = Dot(color=RED, fill_opacity=0.7) dot.move_to(self.coords_to_point(x_val, curr_output)) self.play(FadeIn(dot, 2 * UR)) self.wait() for n in range(self.n_jumps): new_output = func(x_val) func_graph_point = self.coords_to_point(x_val, new_output) id_graph_point = self.coords_to_point(new_output, new_output) v_line = DashedLine(dot.get_center(), func_graph_point) h_line = DashedLine(func_graph_point, id_graph_point) curr_output = new_output x_val = new_output for line in v_line, h_line: line_end = line.get_end() self.play( ShowCreation(line), dot.move_to, line_end, randy.change, self.get_new_randy_mode() ) self.wait() if n < self.n_times_to_show_identity_property: x_point = self.coords_to_point(new_output, 0) y_point = self.coords_to_point(0, new_output) lines = VGroup(*[ Line(dot.get_center(), point) for point in (x_point, y_point) ]) lines.set_color(YELLOW) self.play(ShowCreationThenDestruction( lines, run_time=2 )) self.wait(0.25) class RepeatedApplicationGraphicallyFromNegPhi(RepeatedApplicationGraphically): CONFIG = { "starting_value": -0.61, "n_jumps": 13, "n_times_to_show_identity_property": 0, } class LetsSwitchToTheTransformationalView(TeacherStudentsScene): def construct(self): self.teacher_says( "Lose the \\\\ graphs!", target_mode="hooray" ) self.play_student_changes("hooray", "erm", "surprised") self.wait(5) class AnalyzeFunctionWithTransformations(NumberlineTransformationScene): CONFIG = { "input_line_zero_point": 0.5 * UP, "output_line_zero_point": 2 * DOWN, "func": lambda x: 1 + 1.0 / x, "num_initial_applications": 10, "num_repeated_local_applications": 7, "zoomed_display_width": 3.5, "zoomed_display_height": 2, "default_mapping_animation_config": {}, } def construct(self): self.add_function_title() self.repeatedly_apply_function() self.show_phi_and_phi_bro() self.zoom_in_on_phi() self.zoom_in_on_phi_bro() def setup_number_lines(self): NumberlineTransformationScene.setup_number_lines(self) for line in self.input_line, self.output_line: VGroup(line, line.tick_marks).set_stroke(width=2) def add_function_title(self): title = OldTex("f(x)", "=", "1 +", "\\frac{1}{x}") title.to_edge(UP) self.add(title) self.title = title def repeatedly_apply_function(self): input_zero_point = self.input_line.number_to_point(0) output_zero_point = self.output_line.number_to_point(0) sample_dots = self.get_sample_dots( delta_x=0.05, dot_radius=0.05, x_min=-10, x_max=10, ) sample_dots.set_stroke(BLACK, 0.5) sample_points = list(map(Mobject.get_center, sample_dots)) self.play(LaggedStartMap( FadeInFrom, sample_dots, lambda m: (m, UP) )) self.show_arrows(sample_points) self.wait() for x in range(self.num_initial_applications): self.apply_function( self.func, apply_function_to_number_line=False, sample_dots=sample_dots ) self.wait() shift_vect = input_zero_point - output_zero_point shift_vect[0] = 0 lower_output_line = self.output_line.copy() upper_output_line = self.output_line.copy() lower_output_line.shift(-shift_vect) lower_output_line.fade(1) self.remove(self.output_line) self.play( ReplacementTransform(lower_output_line, self.output_line), upper_output_line.shift, shift_vect, upper_output_line.fade, 1, sample_dots.shift, shift_vect, ) self.remove(upper_output_line) self.wait() self.play(FadeOut(sample_dots)) def show_arrows(self, sample_points): input_zero_point = self.input_line.number_to_point(0) point_func = self.number_func_to_point_func(self.func) alt_point_func = self.number_func_to_point_func(lambda x: 1.0 / x) arrows, alt_arrows = [ VGroup(*[ Arrow( point, func(point), buff=SMALL_BUFF, tip_length=0.15 ) for point in sample_points if get_norm(point - input_zero_point) > 0.3 ]) for func in (point_func, alt_point_func) ] for group in arrows, alt_arrows: group.set_stroke(WHITE, 0.5) group.set_color_by_gradient(RED, YELLOW) for arrow in group: arrow.tip.set_stroke(BLACK, 0.5) one_plus = self.title.get_part_by_tex("1 +") one_plus_rect = BackgroundRectangle(one_plus) one_plus_rect.set_fill(BLACK, opacity=0.8) self.play(LaggedStartMap(GrowArrow, arrows)) self.wait() self.play(LaggedStartMap( ApplyMethod, arrows, lambda a: (a.scale, 0.7), rate_func=there_and_back, )) self.wait() self.play( Transform(arrows, alt_arrows), FadeIn(one_plus_rect, remover=True), rate_func=there_and_back_with_pause, run_time=4, ) self.wait() self.all_arrows = arrows def show_phi_and_phi_bro(self): phi = (1 + np.sqrt(5)) / 2 phi_bro = (1 - np.sqrt(5)) / 2 input_phi_point = self.input_line.number_to_point(phi) output_phi_point = self.output_line.number_to_point(phi) input_phi_bro_point = self.input_line.number_to_point(phi_bro) output_phi_bro_point = self.output_line.number_to_point(phi_bro) tick = Line(UP, DOWN) tick.set_stroke(YELLOW, 3) tick.match_height(self.input_line.tick_marks) phi_tick = tick.copy().move_to(input_phi_point, DOWN) phi_bro_tick = tick.copy().move_to(input_phi_bro_point, DOWN) VGroup(phi_tick, phi_bro_tick).shift(SMALL_BUFF * DOWN) phi_label = OldTex("1.618\\dots") phi_label.next_to(phi_tick, UP) phi_bro_label = OldTex("-0.618\\dots") phi_bro_label.next_to(phi_bro_tick, UP) VGroup(phi_label, phi_bro_label).set_color(YELLOW) arrow_kwargs = { "buff": SMALL_BUFF, "rectangular_stem_width": 0.035, "tip_length": 0.2, } phi_arrow = Arrow(phi_tick, output_phi_point, **arrow_kwargs) phi_bro_arrow = Arrow(phi_bro_tick, output_phi_bro_point, **arrow_kwargs) def fade_arrow(arrow): # arrow.set_stroke(GREY_D, 0.5) arrow.set_stroke(width=0.1) arrow.tip.set_fill(opacity=0) arrow.tip.set_stroke(width=0) return arrow self.play( LaggedStartMap( ApplyFunction, self.all_arrows, lambda a: (fade_arrow, a) ), FadeIn(phi_arrow), FadeIn(phi_bro_arrow), ) self.play( Write(phi_label), GrowFromCenter(phi_tick) ) self.play( Write(phi_bro_label), GrowFromCenter(phi_bro_tick) ) self.set_variables_as_attrs( input_phi_point, output_phi_point, input_phi_bro_point, output_phi_bro_point, phi_label, phi_tick, phi_bro_label, phi_bro_tick, phi_arrow, phi_bro_arrow ) def zoom_in_on_phi(self): phi = (1 + np.sqrt(5)) / 2 # phi_point = self.get_input_point(phi) local_sample_dots = self.get_local_sample_dots( phi, dot_radius=0.005, sample_radius=1 ) local_coordinate_values = [1.55, 1.6, 1.65, 1.7] # zcbr = self.zoomed_camera_background_rectangle zcbr_group = self.zoomed_camera_background_rectangle_group zcbr_group.add(self.phi_tick) title = self.title deriv_text = OldTex( "|", "\\frac{df}{dx}(\\varphi)", "|", "< 1", tex_to_color_map={"\\varphi": YELLOW} ) deriv_text.get_parts_by_tex("|").match_height( deriv_text, stretch=True ) deriv_text.move_to(title, UP) approx_value = OldTex("\\approx |%.2f|" % (-1 / phi**2)) approx_value.move_to(deriv_text) deriv_text_lhs = deriv_text[:-1] deriv_text_rhs = deriv_text[-1] self.zoom_in_on_input( phi, local_sample_dots=local_sample_dots, local_coordinate_values=local_coordinate_values ) self.wait() self.apply_function( self.func, apply_function_to_number_line=False, local_sample_dots=local_sample_dots, target_coordinate_values=local_coordinate_values, ) self.wait() self.play( FadeInFromDown(deriv_text_lhs), FadeInFromDown(deriv_text_rhs), title.to_corner, UL ) self.wait() self.play( deriv_text_lhs.next_to, approx_value, LEFT, deriv_text_rhs.next_to, approx_value, RIGHT, FadeIn(approx_value) ) self.wait() for n in range(self.num_repeated_local_applications): self.apply_function( self.func, apply_function_to_number_line=False, local_sample_dots=local_sample_dots, path_arc=60 * DEGREES, run_time=2 ) self.deriv_text = VGroup( deriv_text_lhs, deriv_text_rhs, approx_value ) def zoom_in_on_phi_bro(self): zcbr = self.zoomed_camera_background_rectangle # zcbr_group = self.zoomed_camera_background_rectangle_group zoomed_frame = self.zoomed_camera.frame phi_bro = (1 - np.sqrt(5)) / 2 # phi_bro_point = self.get_input_point(phi_bro) local_sample_dots = self.get_local_sample_dots(phi_bro) local_coordinate_values = [-0.65, -0.6, -0.55] deriv_text = OldTex( "\\left| \\frac{df}{dx}\\left(\\frac{-1}{\\varphi}\\right) \\right|", "\\approx |%.2f|" % (-1 / (phi_bro**2)), "> 1" ) deriv_text.move_to(self.deriv_text, UL) deriv_text[0][10:14].set_color(YELLOW) self.play( zoomed_frame.set_height, 4, zoomed_frame.center, self.deriv_text.fade, 1, run_time=2 ) self.wait() zcbr.set_fill(opacity=0) self.zoom_in_on_input( phi_bro, local_sample_dots=local_sample_dots, local_coordinate_values=local_coordinate_values, zoom_factor=self.zoom_factor, first_anim_kwargs={"run_time": 2}, ) self.wait() self.play(FadeInFromDown(deriv_text)) self.wait() zcbr.set_fill(opacity=1) self.apply_function( self.func, apply_function_to_number_line=False, local_sample_dots=local_sample_dots, target_coordinate_values=local_coordinate_values, ) self.wait() for n in range(self.num_repeated_local_applications): self.apply_function( self.func, apply_function_to_number_line=False, local_sample_dots=local_sample_dots, path_arc=20 * DEGREES, run_time=2, ) class StabilityAndInstability(AnalyzeFunctionWithTransformations): CONFIG = { "num_initial_applications": 0, } def construct(self): self.force_skipping() self.add_function_title() self.repeatedly_apply_function() self.show_phi_and_phi_bro() self.revert_to_original_skipping_status() self.label_stability() self.write_derivative_fact() def label_stability(self): self.title.to_corner(UL) stable_label = OldTexText("Stable fixed point") unstable_label = OldTexText("Unstable fixed point") labels = VGroup(stable_label, unstable_label) labels.scale(0.8) stable_label.next_to(self.phi_label, UP, aligned_edge=ORIGIN) unstable_label.next_to(self.phi_bro_label, UP, aligned_edge=ORIGIN) phi_point = self.input_phi_point phi_bro_point = self.input_phi_bro_point arrow_groups = VGroup() for point in phi_point, phi_bro_point: arrows = VGroup(*[a for a in self.all_arrows if get_norm(a.get_start() - point) < 0.75]).copy() arrows.set_fill(PINK, 1) arrows.set_stroke(PINK, 3) arrows.second_anim = LaggedStartMap( ApplyMethod, arrows, lambda m: (m.set_color, YELLOW), rate_func=there_and_back_with_pause, lag_ratio=0.7, run_time=2, ) arrows.anim = AnimationGroup(*list(map(GrowArrow, arrows))) arrow_groups.add(arrows) phi_arrows, phi_bro_arrows = arrow_groups self.add_foreground_mobjects(self.phi_arrow, self.phi_bro_arrow) self.play( Write(stable_label), phi_arrows.anim, ) self.play(phi_arrows.second_anim) self.play( Write(unstable_label), phi_bro_arrows.anim, ) self.play(phi_bro_arrows.second_anim) self.wait() self.stable_label = stable_label self.unstable_label = unstable_label self.phi_arrows = phi_arrows self.phi_bro_arrows = phi_bro_arrows def write_derivative_fact(self): stable_label = self.stable_label unstable_label = self.unstable_label labels = VGroup(stable_label, unstable_label) phi_arrows = self.phi_arrows phi_bro_arrows = self.phi_bro_arrows arrow_groups = VGroup(phi_arrows, phi_bro_arrows) deriv_labels = VGroup() for char, label in zip("<>", labels): deriv_label = OldTex( "\\big|", "\\frac{df}{dx}(", "x", ")", "\\big|", char, "1" ) deriv_label.get_parts_by_tex("\\big|").match_height( deriv_label, stretch=True ) deriv_label.set_color_by_tex("x", YELLOW, substring=False) deriv_label.next_to(label, UP) deriv_labels.add(deriv_label) dot_groups = VGroup() for arrow_group in arrow_groups: dot_group = VGroup() for arrow in arrow_group: start_point, end_point = [ line.number_to_point(line.point_to_number(p)) for line, p in [ (self.input_line, arrow.get_start()), (self.output_line, arrow.get_end()), ] ] dot = Dot(start_point, radius=0.05) dot.set_color(YELLOW) dot.generate_target() dot.target.move_to(end_point) dot_group.add(dot) dot_groups.add(dot_group) for deriv_label, dot_group in zip(deriv_labels, dot_groups): self.play(FadeInFromDown(deriv_label)) self.play(LaggedStartMap(GrowFromCenter, dot_group)) self.play(*list(map(MoveToTarget, dot_group)), run_time=2) self.wait() class StaticAlgebraicObject(Scene): def construct(self): frac = get_phi_continued_fraction(40) frac.set_width(FRAME_WIDTH - 1) # frac.shift(2 * DOWN) frac.to_edge(DOWN) frac.set_stroke(WHITE, width=0.5) title = OldTex( "\\infty \\ne \\lim", tex_to_color_map={"\\ne": RED} ) title.scale(1.5) title.to_edge(UP) polynomial = OldTex("x^2 - x - 1 = 0") polynomial.move_to(title) self.add(title) self.play(LaggedStartMap( GrowFromCenter, frac, lag_ratio=0.1, run_time=3 )) self.wait() factor = 1.1 self.play(frac.scale, factor, run_time=0.5) self.play( frac.scale, 1 / factor, frac.set_color, GREY_B, run_time=0.5, rate_func=lambda t: t**5, ) self.wait() self.play( FadeOut(title), FadeIn(polynomial) ) self.wait(2) class NotBetterThanGraphs(TeacherStudentsScene): def construct(self): self.student_says( "Um, yeah, I'll stick \\\\ with graphs thanks", target_mode="sassy", ) self.play( self.teacher.change, "guilty", self.change_students("sad", "sassy", "hesitant") ) self.wait(2) self.play( RemovePiCreatureBubble(self.students[1]), self.teacher.change, "raise_right_hand" ) self.play_all_student_changes( "confused", look_at=self.screen ) self.wait(3) self.teacher_says( "You must flex those \\\\ conceptual muscles", added_anims=[self.change_students( *3 * ["thinking"], look_at=self.teacher.eyes )] ) self.wait(3) class WhatComesAfterWrapper(Wrapper): CONFIG = {"title": "Beyond the first year"} def construct(self): Wrapper.construct(self) new_title = OldTexText("Next video") new_title.set_color(BLUE) new_title.move_to(self.title) self.play( FadeInFromDown(new_title), self.title.shift, UP, self.title.fade, 1, ) self.wait(3) class TopicsAfterSingleVariable(PiCreatureScene, MoreTopics): CONFIG = { "pi_creatures_start_on_screen": False, } def construct(self): MoreTopics.construct(self) self.show_horror() self.zero_in_on_complex_analysis() def create_pi_creatures(self): creatures = VGroup(*[ PiCreature(color=color) for color in [BLUE_E, BLUE_C, BLUE_D] ]) creatures.arrange(RIGHT, buff=LARGE_BUFF) creatures.scale(0.5) creatures.to_corner(DR) return creatures def show_horror(self): creatures = self.get_pi_creatures() modes = ["horrified", "tired", "horrified"] for creature, mode in zip(creatures, modes): creature.generate_target() creature.target.change(mode, self.other_topics) creatures.fade(1) self.play(LaggedStartMap(MoveToTarget, creatures)) self.wait(2) def zero_in_on_complex_analysis(self): creatures = self.get_pi_creatures() complex_analysis = self.other_topics[1] self.other_topics.remove(complex_analysis) self.play( complex_analysis.scale, 1.25, complex_analysis.center, complex_analysis.to_edge, UP, LaggedStartMap(FadeOut, self.other_topics), LaggedStartMap(FadeOut, self.lines), FadeOut(self.calculus), *[ ApplyMethod(creature.change, "pondering") for creature in creatures ] ) self.wait(4) class ShowJacobianZoomedIn(LinearTransformationScene, ZoomedScene): CONFIG = { "show_basis_vectors": False, "show_coordinates": True, "zoom_factor": 0.05, } def setup(self): LinearTransformationScene.setup(self) ZoomedScene.setup(self) def construct(self): def example_function(point): x, y, z = point return np.array([ x + np.sin(y), y + np.sin(x), 0 ]) zoomed_camera = self.zoomed_camera zoomed_display = self.zoomed_display frame = zoomed_camera.frame frame.move_to(3 * LEFT + 1 * UP) frame.set_color(YELLOW) zoomed_display.display_frame.set_color(YELLOW) zd_rect = BackgroundRectangle( zoomed_display, fill_opacity=1, buff=MED_SMALL_BUFF, ) self.add_foreground_mobject(zd_rect) zd_rect.anim = UpdateFromFunc( zd_rect, lambda rect: rect.replace(zoomed_display).scale(1.1) ) zd_rect.next_to(FRAME_HEIGHT * UP, UP) tiny_grid = NumberPlane( x_radius=2, y_radius=2, color=BLUE_E, secondary_color=GREY_D, ) tiny_grid.replace(frame) jacobian_words = OldTexText("Jacobian") jacobian_words.add_background_rectangle() jacobian_words.scale(1.5) jacobian_words.move_to(zoomed_display, UP) zoomed_display.next_to(jacobian_words, DOWN) self.play(self.get_zoom_in_animation()) self.activate_zooming() self.play( self.get_zoomed_display_pop_out_animation(), zd_rect.anim ) self.play( ShowCreation(tiny_grid), Write(jacobian_words), run_time=2 ) self.add_transformable_mobject(tiny_grid) self.add_foreground_mobject(jacobian_words) self.wait() self.apply_nonlinear_transformation( example_function, added_anims=[MaintainPositionRelativeTo( zoomed_camera.frame, tiny_grid, )], run_time=5 ) self.wait() class PrinciplesOverlay(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs": { "color": GREY_BROWN, "flip_at_start": True, }, "default_pi_creature_start_corner": DR, } def construct(self): morty = self.pi_creature q_marks = VGroup(*[Tex("?") for x in range(40)]) q_marks.arrange_in_grid(4, 10) q_marks.space_out_submobjects(1.4) for mark in q_marks: mark.shift( random.random() * RIGHT, random.random() * UP, ) mark.scale(1.5) mark.set_stroke(BLACK, 1) q_marks.next_to(morty, UP) q_marks.shift_onto_screen() q_marks.sort( lambda p: get_norm(p - morty.get_top()) ) self.play(morty.change, "pondering") self.wait(2) self.play(morty.change, "raise_right_hand") self.wait() self.play(morty.change, "thinking") self.wait(4) self.play(FadeInFromDown(q_marks[0])) self.wait(2) self.play(LaggedStartMap( FadeInFromDown, q_marks[1:], run_time=3 )) self.wait(3) class ManyInfiniteExpressions(Scene): def construct(self): frac = get_phi_continued_fraction(10) frac.set_height(2) frac.to_corner(UL) n = 9 radical_str_parts = [ "%d + \\sqrt{" % d for d in range(1, n + 1) ] radical_str_parts += ["\\cdots"] radical_str_parts += ["}"] * n radical = OldTex("".join(radical_str_parts)) radical.to_corner(UR) radical.to_edge(DOWN) radical.set_color_by_gradient(YELLOW, RED) n = 12 power_tower = OldTex( *["\\sqrt{2}^{"] * n + ["\\dots"] + ["}"] * n ) power_tower.to_corner(UR) power_tower.set_color_by_gradient(BLUE, GREEN) self.play(*[ LaggedStartMap( GrowFromCenter, group, lag_ratio=0.1, run_time=8, ) for group in (frac, radical, power_tower) ]) self.wait(2) class HoldUpPromo(PrinciplesOverlay): def construct(self): morty = self.pi_creature url = OldTexText("https://brilliant.org/3b1b/") url.to_corner(UL) rect = ScreenRectangle(height=5.5) rect.next_to(url, DOWN) rect.to_edge(LEFT) self.play( Write(url), self.pi_creature.change, "raise_right_hand" ) self.play(ShowCreation(rect)) self.wait(2) self.change_mode("thinking") self.wait() self.look_at(url) self.wait(10) self.change_mode("happy") self.wait(10) self.change_mode("raise_right_hand") self.wait(10) self.play(FadeOut(rect), FadeOut(url)) self.play(morty.change, "raise_right_hand") self.wait() self.play(morty.change, "hooray") self.wait(3) class EndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "Juan Benet", "Keith Smith", "Chloe Zhou", "Desmos", "Burt Humburg", "CrypticSwarm", "Andrew Sachs", "Ho\\`ang T\\`ung L\\^am", # "Hoàng Tùng Lâm", "Devin Scott", "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", "Fela", "Fred Ehrsam", "Britt Selvitelle", "Jonathan Wilson", "Ryan Atallah", "Joseph John Cox", "Luc Ritchie", "Matt Roveto", "Jamie Warner", "Marek Cirkos", "Magister Mugit", "Stevie Metke", "Cooper Jones", "James Hughes", "John V Wertheim", "Chris Giddings", "Song Gao", "Alexander Feldman", "Matt Langford", "Max Mitchell", "Richard Burgmann", "John Griffith", "Chris Connett", "Steven Tomlinson", "Jameel Syed", "Bong Choung", "Ignacio Freiberg", "Zhilong Yang", "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", "Isak Hietala", "1st ViewMaths", "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", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Sh\\`im\\'in Ku\\=ang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] } # class Thumbnail(GraphicalIntuitions): class Thumbnail(AnalyzeFunctionWithTransformations): CONFIG = { "x_axis_width": 12, "graph_origin": 1.5 * DOWN + 4 * LEFT, "num_initial_applications": 1, "input_line_zero_point": 2 * UP, } def construct(self): self.add_function_title() self.title.fade(1) self.titles.fade(1) self.repeatedly_apply_function() self.all_arrows.set_stroke(width=1) full_rect = FullScreenFadeRectangle() cross = Cross(full_rect) cross.set_stroke(width=40) # self.add(cross)
from fractions import Fraction from manim_imports_ext import * from functools import reduce class FractionMobject(VGroup): CONFIG = { "max_height": 1, } def __init__(self, fraction, **kwargs): VGroup.__init__(self, **kwargs) numerator = self.numerator = Integer(fraction.numerator) self.add(numerator) if fraction.denominator != 1: denominator = Integer(fraction.denominator) line = OldTex("/") numerator.next_to(line, LEFT, SMALL_BUFF) denominator.next_to(line, RIGHT, SMALL_BUFF) self.add(numerator, line, denominator) self.set_height(min(self.max_height, self.get_height())) self.value = fraction def add_plus_if_needed(self): if self.value > 0: plus = OldTex("+") plus.next_to(self, LEFT, SMALL_BUFF) plus.match_color(self) self.add_to_back(plus) class ShowRowReduction(Scene): CONFIG = { "matrices": [ [ [2, -1, -1], [0, 3, -4], [-3, 2, 1], ], [ [1, 0, 0], [0, 1, 0], [0, 0, 1], ], # [[1], [2], [3]], ], "h_spacing": 2, "extra_h_spacing": 0.5, "v_spacing": 1, "include_separation_lines": True, "changing_row_color": YELLOW, "reference_row_color": BLUE, } def construct(self): self.initialize_terms() self.apply_row_rescaling(0, Fraction(1, 2)) self.add_row_multiple_to_row(2, 0, 3) self.apply_row_rescaling(1, Fraction(1, 3)) self.add_row_multiple_to_row(2, 1, Fraction(-1, 2)) self.apply_row_rescaling(2, Fraction(6)) self.add_row_multiple_to_row(0, 1, Fraction(1, 2)) self.add_row_multiple_to_row(0, 2, Fraction(7, 6)) self.add_row_multiple_to_row(1, 2, Fraction(4, 3)) self.wait() def initialize_terms(self): full_matrix = reduce( lambda m, v: np.append(m, v, axis=1), self.matrices ) mobject_matrix = np.vectorize(FractionMobject)(full_matrix) rows = self.rows = VGroup(*it.starmap(VGroup, mobject_matrix)) for i, row in enumerate(rows): for j, term in enumerate(row): term.move_to( i * self.v_spacing * DOWN + j * self.h_spacing * RIGHT ) # Visually seaprate distinct parts separation_lines = self.separation_lines = VGroup() lengths = [len(m[0]) for m in self.matrices] for partial_sum in np.cumsum(lengths)[:-1]: VGroup(*mobject_matrix[:, partial_sum:].flatten()).shift( self.extra_h_spacing * RIGHT ) c1 = VGroup(*mobject_matrix[:, partial_sum - 1]) c2 = VGroup(*mobject_matrix[:, partial_sum]) line = DashedLine(c1.get_top(), c1.get_bottom()) line.move_to(VGroup(c1, c2)) separation_lines.add(line) if self.include_separation_lines: group = VGroup(rows, separation_lines) else: group = rows group.center().to_edge(DOWN, buff=2) self.add(group) def add_variables(self): # If it is meant to represent a system of equations pass def apply_row_rescaling(self, row_index, scale_factor): row = self.rows[row_index] new_row = VGroup() for element in row: target = FractionMobject(element.value * scale_factor) target.move_to(element) new_row.add(target) new_row.set_color(self.changing_row_color) label = VGroup( OldTex("r_%d" % (row_index + 1)), OldTex("\\rightarrow"), OldTex("("), FractionMobject(scale_factor), OldTex(")"), OldTex("r_%d" % (row_index + 1)), ) label.arrange(RIGHT, buff=SMALL_BUFF) label.to_edge(UP) VGroup(label[0], label[-1]).set_color(self.changing_row_color) scalar_mob = FractionMobject(scale_factor) scalar_mob.add_to_back( OldTex("\\times").next_to(scalar_mob, LEFT, SMALL_BUFF) ) scalar_mob.scale(0.5) scalar_mob.next_to(row[0], DR, SMALL_BUFF) # Do do, fancier illustrations here self.play( FadeIn(label), row.set_color, self.changing_row_color, ) self.play(FadeIn(scalar_mob)) for elem, new_elem in zip(row, new_row): self.play(scalar_mob.next_to, elem, DR, SMALL_BUFF) self.play(ReplacementTransform(elem, new_elem, path_arc=30 * DEGREES)) self.play(FadeOut(scalar_mob)) self.play(new_row.set_color, WHITE) self.play(FadeOut(label)) self.rows.submobjects[row_index] = new_row def add_row_multiple_to_row(self, row1_index, row2_index, scale_factor): row1 = self.rows[row1_index] row2 = self.rows[row2_index] new_row1 = VGroup() scaled_row2 = VGroup() for elem1, elem2 in zip(row1, row2): target = FractionMobject(elem1.value + scale_factor * elem2.value) target.move_to(elem1) new_row1.add(target) scaled_term = FractionMobject(scale_factor * elem2.value) scaled_term.move_to(elem2) scaled_row2.add(scaled_term) new_row1.set_color(self.changing_row_color) scaled_row2.set_color(self.reference_row_color) for elem1, elem2 in zip(row1, scaled_row2): elem2.add_plus_if_needed() elem2.scale(0.5) elem2.next_to(elem1, UL, buff=SMALL_BUFF) label = VGroup( OldTex("r_%d" % (row1_index + 1)), OldTex("\\rightarrow"), OldTex("r_%d" % (row1_index + 1)), OldTex("+"), OldTex("("), FractionMobject(scale_factor), OldTex(")"), OldTex("r_%d" % (row2_index + 1)), ) label.arrange(RIGHT, buff=SMALL_BUFF) label.to_edge(UP) VGroup(label[0], label[2]).set_color(self.changing_row_color) label[-1].set_color(self.reference_row_color) self.play( FadeIn(label), row1.set_color, self.changing_row_color, row2.set_color, self.reference_row_color, ) row1.target.next_to(self.rows, UP, buff=2) row1.target.align_to(row1, LEFT) row2.target.next_to(row1.target, DOWN, buff=MED_LARGE_BUFF) lp, rp = row2_parens = OldTex("()") row2_parens.set_height(row2.get_height() + 2 * SMALL_BUFF) lp.next_to(row2, LEFT, SMALL_BUFF) rp.next_to(row2, RIGHT, SMALL_BUFF) scalar = FractionMobject(scale_factor) scalar.next_to(lp, LEFT, SMALL_BUFF) scalar.add_plus_if_needed() self.play( FadeIn(row2_parens), Write(scalar), ) self.play(ReplacementTransform(row2.copy(), scaled_row2)) self.wait() for elem, new_elem, s_elem in zip(row1, new_row1, scaled_row2): self.play( FadeOut(elem), FadeIn(new_elem), Transform(s_elem, new_elem.copy().fade(1), remover=True) ) self.wait() self.play( FadeOut(label), FadeOut(row2_parens), FadeOut(scalar), new_row1.set_color, WHITE, row2.set_color, WHITE, ) self.rows.submobjects[row1_index] = new_row1
from manim_imports_ext import * from _2018.sphere_area import * class MadAtMathologer(PiCreatureScene): def create_pi_creature(self): return Mortimer().to_corner(DR) def construct(self): morty = self.pi_creature self.play(morty.change, "angry") self.wait(3) self.play(morty.change, "heistant") self.wait(2) self.play(morty.change, "shruggie") self.wait(3) class JustTheIntegral(Scene): def construct(self): tex = OldTex("\\int_0^{\\pi / 2} \\cos(\\theta)d\\theta") tex.scale(2) self.add(tex) class SphereVideoWrapper(Scene): def construct(self): title = OldTexText("Surface area of a sphere") 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 SphereRings(SecondProof): CONFIG = { "sphere_config": { "resolution": (60, 60), }, } def construct(self): self.setup_shapes() self.grow_rings() self.show_one_ring() self.show_radial_line() self.show_thickness() self.flash_through_rings() def grow_rings(self): sphere = self.sphere rings = self.rings north_rings = rings[:len(rings) // 2] sphere.set_fill(opacity=0) sphere.set_stroke(WHITE, 0.5, opacity=0.5) southern_mesh = VGroup(*[ face.copy() for face in sphere if face.get_center()[2] < 0 ]) southern_mesh.set_stroke(WHITE, 0.1, 0.5) self.play(Write(sphere)) self.wait() self.play( FadeOut(sphere), FadeIn(southern_mesh), FadeIn(north_rings), ) self.wait(4) self.north_rings = north_rings self.southern_mesh = southern_mesh def show_one_ring(self): north_rings = self.north_rings index = len(north_rings) // 2 ring = north_rings[index] to_fade = VGroup(*[ nr for nr in north_rings if nr is not ring ]) north_rings.save_state() circle = Circle() circle.set_stroke(PINK, 5) circle.set_width(ring.get_width()) circle.move_to(ring, IN) thickness = ring.get_depth() * np.sqrt(2) brace = Brace(Line(ORIGIN, 0.2 * RIGHT), UP) brace.set_width(thickness) brace.rotate(90 * DEGREES, RIGHT) brace.rotate(45 * DEGREES, UP) brace.move_to(1.5 * (RIGHT + OUT)) brace.set_stroke(WHITE, 1) word = OldTexText("Thickness") word.rotate(90 * DEGREES, RIGHT) word.next_to(brace, RIGHT + OUT, buff=0) self.play( to_fade.set_fill, {"opacity": 0.2}, to_fade.set_stroke, {"opacity": 0.0}, ) self.move_camera( phi=0, theta=-90 * DEGREES, run_time=2, ) self.stop_ambient_camera_rotation() self.play(ShowCreation(circle)) self.play(FadeOut(circle)) self.move_camera( phi=70 * DEGREES, theta=-100 * DEGREES, run_time=2, ) self.begin_ambient_camera_rotation(0.02) self.play( GrowFromCenter(brace), Write(word), ) self.wait(2) self.play(FadeOut(VGroup(brace, word))) self.circum_circle = circle self.thickness_label = VGroup(brace, word) self.ring = ring def show_radial_line(self): ring = self.ring point = ring.get_corner(RIGHT + IN) R_line = Line(ORIGIN, point) xy_line = Line(ORIGIN, self.sphere.get_right()) theta = np.arccos(np.dot( normalize(R_line.get_vector()), normalize(xy_line.get_vector()) )) arc = Arc(angle=theta, radius=0.5) arc.rotate(90 * DEGREES, RIGHT, about_point=ORIGIN) theta = OldTex("\\theta") theta.rotate(90 * DEGREES, RIGHT) theta.next_to(arc, RIGHT) theta.shift(SMALL_BUFF * (LEFT + OUT)) R_label = OldTex("R") R_label.rotate(90 * DEGREES, RIGHT) R_label.next_to( R_line.get_center(), OUT + LEFT, buff=SMALL_BUFF ) VGroup(R_label, R_line).set_color(YELLOW) z_axis_point = np.array(point) z_axis_point[:2] = 0 r_line = DashedLine(z_axis_point, point) r_line.set_color(RED) r_label = OldTex("R\\cos(\\theta)") r_label.rotate(90 * DEGREES, RIGHT) r_label.scale(0.7) r_label.match_color(r_line) r_label.set_stroke(width=0, background=True) r_label.next_to(r_line, OUT, 0.5 * SMALL_BUFF) VGroup( R_label, xy_line, arc, R_label, r_line, r_label, ).set_shade_in_3d(True) # self.stop_ambient_camera_rotation() self.move_camera( phi=85 * DEGREES, theta=-100 * DEGREES, added_anims=[ ring.set_fill, {"opacity": 0.5}, ring.set_stroke, {"opacity": 0.1}, ShowCreation(R_line), FadeIn(R_label, IN), ] ) self.wait() self.play( FadeIn(xy_line), ShowCreation(arc), Write(theta), ) self.wait() self.play( ShowCreation(r_line), FadeIn(r_label, IN), ) self.wait() self.move_camera( phi=70 * DEGREES, theta=-110 * DEGREES, run_time=3 ) self.wait(2) def show_thickness(self): brace, word = self.thickness_label R_dtheta = OldTex("R \\, d\\theta") R_dtheta.rotate(90 * DEGREES, RIGHT) R_dtheta.move_to(word, LEFT) self.play( GrowFromCenter(brace), Write(R_dtheta) ) self.wait(3) def flash_through_rings(self): rings = self.north_rings.copy() rings.fade(1) rings.sort(lambda p: p[2]) for x in range(8): self.play(LaggedStartMap( ApplyMethod, rings, lambda m: (m.set_fill, PINK, 0.5), rate_func=there_and_back, lag_ratio=0.1, run_time=2, )) class IntegralSymbols(Scene): def construct(self): int_sign = OldTex("\\displaystyle \\int") int_sign.set_height(1.5) int_sign.move_to(5 * LEFT) circumference, times, thickness = ctt = OldTexText( "circumference", "$\\times$", "thickness" ) circumference.set_color(MAROON_B) ctt.next_to(int_sign, RIGHT, SMALL_BUFF) area_brace = Brace(ctt, DOWN) area_text = area_brace.get_text("Area of a ring") all_rings = OldTexText("All rings") all_rings.scale(0.5) all_rings.next_to(int_sign, DOWN, SMALL_BUFF) all_rings.shift(SMALL_BUFF * LEFT) circum_formula = OldTex( "2\\pi", "R\\cos(\\theta)", ) circum_formula[1].set_color(RED) circum_formula.move_to(circumference) circum_brace = Brace(circum_formula, UP) R_dtheta = OldTex("R \\, d\\theta") R_dtheta.move_to(thickness, LEFT) R_dtheta_brace = Brace(R_dtheta, UP) zero, pi_halves = bounds = OldTex("0", "\\pi / 2") bounds.scale(0.5) zero.move_to(all_rings) pi_halves.next_to(int_sign, UP, SMALL_BUFF) pi_halves.shift(SMALL_BUFF * RIGHT) self.add(int_sign) self.play( GrowFromCenter(area_brace), FadeIn(area_text, UP), ) self.wait() self.play(FadeInFromDown(circumference)) self.play( FadeInFromDown(thickness), Write(times) ) self.play(Write(all_rings)) self.wait() self.play( circumference.next_to, circum_brace, UP, MED_SMALL_BUFF, circumference.shift, SMALL_BUFF * UR, GrowFromCenter(circum_brace), ) self.play(FadeIn(circum_formula, UP)) self.wait() self.play( thickness.next_to, circumference, RIGHT, MED_SMALL_BUFF, GrowFromCenter(R_dtheta_brace), area_brace.stretch, 0.84, 0, {"about_edge": LEFT}, MaintainPositionRelativeTo(area_text, area_brace), ) self.play(FadeIn(R_dtheta, UP)) self.wait() self.play(ReplacementTransform(all_rings, bounds)) self.wait() # RHS rhs = OldTex( "\\displaystyle =", "2\\pi R^2", "\\int_0^{\\pi / 2}", "\\cos(\\theta)", "d\\theta", ) rhs.set_color_by_tex("cos", RED) rhs.next_to(R_dtheta, RIGHT) int_brace = Brace(rhs[2:], DOWN) q_marks = int_brace.get_text("???") one = OldTex("1") one.move_to(q_marks) self.play(FadeIn(rhs, 4 * LEFT)) self.wait() self.play(ShowCreationThenFadeAround(rhs[1])) self.wait() self.play(ShowCreationThenFadeAround(rhs[2:])) self.wait() self.play( GrowFromCenter(int_brace), LaggedStartMap( FadeInFrom, q_marks, lambda m: (m, UP), ) ) self.wait() self.play(ReplacementTransform(q_marks, one)) self.wait() class ShamelessPlug(TeacherStudentsScene): def construct(self): self.student_says( "But why $4\\pi R^2$?", target_mode="maybe" ) self.play_student_changes( "erm", "maybe", "happy", added_anims=[self.teacher.change, "happy"] ) self.wait(3)
from manim_imports_ext import * class WorkOutNumerically(Scene): CONFIG = { "M1_COLOR": TEAL, "M2_COLOR": PINK, } def construct(self): self.add_question() self.add_example() self.compute_rhs() self.compute_lhs() def add_question(self): equation = self.original_equation = OldTex( "\\det(", "M_1", "M_2", ")", "=", "\\det(", "M_1", ")", "\\det(", "M_2", ")", ) equation.set_color_by_tex_to_color_map({ "M_1": self.M1_COLOR, "M_2": self.M2_COLOR, }) challenge = OldTexText("Explain in one sentence") challenge.set_color(YELLOW) group = VGroup(challenge, equation) group.arrange(DOWN) group.to_edge(UP) self.add(equation) self.play(Write(challenge)) self.wait() def add_example(self): M1 = self.M1 = Matrix([[2, -1], [1, 1]]) M1.set_color(self.M1_COLOR) self.M1_copy = M1.copy() M2 = self.M2 = Matrix([[-1, 4], [1, 1]]) M2.set_color(self.M2_COLOR) self.M2_copy = M2.copy() eq_parts = OldTex( "\\det", "\\big(", "\\big)", "=", "\\det", "\\big(", "\\big)", "\\det", "\\big(", "\\big)", ) for part in eq_parts.get_parts_by_tex("\\big"): part.scale(2) part.stretch(1.5, 1) i1, i2, i3 = [ eq_parts.index_of_part(part) + 1 for part in eq_parts.get_parts_by_tex("\\big(") ] equation = self.equation_with_numbers = VGroup(*it.chain( eq_parts[:i1], [M1, M2], eq_parts[i1:i2], [self.M1_copy], eq_parts[i2:i3], [self.M2_copy], eq_parts[i3:], )) equation.arrange(RIGHT, buff=SMALL_BUFF) eq_parts.get_part_by_tex("=").shift(0.2 * SMALL_BUFF * DOWN) equation.set_width(FRAME_WIDTH - 2 * LARGE_BUFF) equation.next_to(self.original_equation, DOWN, MED_LARGE_BUFF) self.play(LaggedStartMap(FadeIn, equation)) def compute_rhs(self): M1, M2 = self.M1_copy, self.M2_copy line1 = VGroup( OldTex( "\\big(", "2", "\\cdot", "2", "-", "(-1)", "\\cdot", "1", "\\big)" ), OldTex( "\\big(", "-1", "\\cdot", "1", "-", "4", "\\cdot", "1", "\\big)" ), ) line1.arrange(RIGHT, buff=SMALL_BUFF) line1[0].set_color(self.M1_COLOR) line1[1].set_color(self.M2_COLOR) indices = [1, 3, 5, 7] line2 = OldTex("(3)", "(-5)") line2.match_style(line1) line3 = OldTex("-15") arrows = [Tex("\\downarrow") for x in range(2)] lines = VGroup(line1, arrows[0], line2, arrows[1], line3) lines.arrange(DOWN, buff=MED_SMALL_BUFF) lines.next_to(self.equation_with_numbers, DOWN, buff=MED_LARGE_BUFF) lines.to_edge(RIGHT) for matrix, det in zip([M1, M2], line1): numbers = VGroup(*[det[i] for i in indices]) numbers_iter = iter(numbers) non_numbers = VGroup(*[m for m in det if m not in numbers]) matrix_numbers = VGroup(*[ matrix.mob_matrix[i][j].copy() for i, j in ((0, 0), (1, 1), (0, 1), (1, 0)) ]) self.play( LaggedStartMap(FadeIn, non_numbers, run_time=1), LaggedStartMap( ReplacementTransform, matrix_numbers, lambda m: (m, next(numbers_iter)), path_arc=TAU / 6 ), ) self.play(LaggedStartMap(FadeIn, lines[1:], run_time=3)) def compute_lhs(self): matrix = Matrix([[-3, 7], [0, 5]]) matrix.set_color(BLUE) matrix.scale(0.8) empty_det_tex = OldTex("\\det", "\\big(", "\\big)") empty_det_tex[1:].scale(1.5) empty_det_tex[1:].match_height(matrix, stretch=True) det_tex = VGroup(empty_det_tex[:2], matrix, *empty_det_tex[2:]) det_tex.arrange(RIGHT, buff=SMALL_BUFF) group = VGroup( det_tex, OldTex("\\downarrow"), OldTex("(-3)(5) - (7)(0)").scale(0.8), OldTex("\\downarrow"), OldTex("-15"), ) group.arrange(DOWN, buff=2 * SMALL_BUFF) # group.set_height(0.4*FRAME_HEIGHT) group.next_to(self.equation_with_numbers, DOWN) group.shift(FRAME_WIDTH * LEFT / 4) self.play(FadeIn(empty_det_tex)) self.play(*[ ReplacementTransform(M.copy(), matrix) for M in (self.M1, self.M2) ]) self.play(LaggedStartMap(FadeIn, group[1:])) self.wait() class LetsGoInOneSentence(TeacherStudentsScene): def construct(self): self.teacher_says( "Here we go, \\\\", "one sentence!" ) self.play_all_student_changes("hooray") self.teacher_says( "Or three...", "", target_mode="guilty" ) self.play_all_student_changes("sassy") self.wait(4) class SuccessiveLinearTransformations(LinearTransformationScene): CONFIG = { "matrix_2": [[3, -1], [0, 1]], "matrix_1": [[2, 3], [-1. / 3, 2]], } def construct(self): self.create_product_and_inverse() self.scale_area_successively() self.apply_transformations_successively() self.scale_area_successively( "\\det(M_2)", "\\det(M_1)", "\\det(M_1 M_2)", reset=False ) # self.show_det_as_scaling_factor() def create_product_and_inverse(self): self.matrix_product = np.dot(self.matrix_1, self.matrix_2) self.matrix_product_inverse = np.linalg.inv(self.matrix_product) def scale_area_successively(self, tex2="3", tex1="5", tex_prod="15", reset=True): self.add_unit_square() t1 = "$%s \\, \\cdot $" % tex1 t2 = "$%s \\, \\cdot $" % tex2 t3 = "Area" areas = VGroup( OldTexText("", "", t3), OldTexText("", t2, t3), OldTexText(t1, t2, t3), ) areas.scale(0.8) areas.move_to(self.square) area = areas[0] self.add_moving_mobject(area, areas[1]) self.play( FadeIn(self.square), Write(area), Animation(self.basis_vectors) ) self.apply_matrix(self.matrix_2) self.wait() self.add_moving_mobject(area, areas[2]) self.apply_matrix(self.matrix_1) self.wait() product = VGroup(area[:2]) brace = Brace(product, DOWN, buff=SMALL_BUFF) brace_tex = brace.get_tex(tex_prod, buff=SMALL_BUFF) brace_tex.scale(0.8, about_edge=UP) self.play( GrowFromCenter(brace), Write(brace_tex) ) self.wait() if reset: self.play( FadeOut(VGroup(self.square, area, brace, brace_tex)), Animation(self.plane), Animation(self.basis_vectors) ) self.transformable_mobjects.remove(self.square) self.moving_mobjects = [] self.reset_plane() self.wait() def apply_transformations_successively(self): M1, M2, all_space = expression = OldTex( "M_1", "M_2", "\\text{(All 2d space)}" ) expression.set_color_by_tex_to_color_map({ "M_1": TEAL, "M_2": PINK, }) expression.shift(FRAME_WIDTH * LEFT / 4) expression.to_edge(UP) for part in expression: part.add_background_rectangle() part.background_rectangle.stretch(1.05, 0) M1.save_state() M1.move_to(ORIGIN) M1.fade(1) # Apply one after the other self.play( FocusOn(M2, run_time=1), FadeIn(VGroup(M2, all_space)) ) self.add_foreground_mobjects(M2, all_space) self.apply_matrix(self.matrix_2) self.wait() self.play(M1.restore) self.add_foreground_mobjects(M1) self.apply_matrix(self.matrix_1) self.wait() # Show full composition rp, lp = parens = OldTex("()") matrices = VGroup(M1, M2) matrices.generate_target() parens.match_height(matrices) lp.move_to(matrices, RIGHT) matrices.target.next_to(lp, LEFT, SMALL_BUFF) rp.next_to(matrices.target, LEFT, SMALL_BUFF) self.reset_plane() self.play( MoveToTarget(matrices), *list(map(GrowFromCenter, parens)) ) self.apply_matrix(self.matrix_product) self.wait() self.reset_plane() def show_det_as_scaling_factor(self): pass ### def reset_plane(self): plane_and_bases = VGroup(self.plane, self.basis_vectors) self.play(FadeOut(plane_and_bases)) self.apply_matrix(self.matrix_product_inverse, run_time=0) self.play(FadeIn(plane_and_bases))
from manim_imports_ext import * # Quick note to anyone coming to this file with the # intent of recreating animations from the video. Some # of these, especially those involving AnimatedStreamLines, # can take an extremely long time to run, but much of the # computational cost is just for giving subtle little effects # which don't matter too much. Switching the line_anim_class # to ShowPassingFlash will give significant speedups, as will # increasing the values of delta_x and delta_y in sampling for # the stream lines. Certainly while developing, things were not # run at production quality. FOX_COLOR = "#DF7F20" RABBIT_COLOR = "#C6D6EF" # Warning, this file uses ContinualChangingDecimal, # which has since been been deprecated. Use a mobject # updater instead # Helper functions def joukowsky_map(z): if z == 0: return 0 return z + fdiv(1, z) def inverse_joukowsky_map(w): u = 1 if w.real >= 0 else -1 return (w + u * np.sqrt(w**2 - 4)) / 2 def derivative(func, dt=1e-7): return lambda z: (func(z + dt) - func(z)) / dt def negative_gradient(potential_func, dt=1e-7): def result(p): output = potential_func(p) dx = dt * RIGHT dy = dt * UP dz = dt * OUT return -np.array([ (potential_func(p + dx) - output) / dt, (potential_func(p + dy) - output) / dt, (potential_func(p + dz) - output) / dt, ]) return result def divergence(vector_func, dt=1e-7): def result(point): value = vector_func(point) return sum([ (vector_func(point + dt * RIGHT) - value)[i] / dt for i, vect in enumerate([RIGHT, UP, OUT]) ]) return result def two_d_curl(vector_func, dt=1e-7): def result(point): value = vector_func(point) return op.add( (vector_func(point + dt * RIGHT) - value)[1] / dt, -(vector_func(point + dt * UP) - value)[0] / dt, ) return result def cylinder_flow_vector_field(point, R=1, U=1): z = R3_to_complex(point) # return complex_to_R3(1.0 / derivative(joukowsky_map)(z)) return complex_to_R3(derivative(joukowsky_map)(z).conjugate()) def cylinder_flow_magnitude_field(point): return get_norm(cylinder_flow_vector_field(point)) def vec_tex(s): return "\\vec{\\textbf{%s}}" % s def four_swirls_function(point): x, y = point[:2] result = (y**3 - 4 * y) * RIGHT + (x**3 - 16 * x) * UP result *= 0.05 norm = get_norm(result) if norm == 0: return result # result *= 2 * sigmoid(norm) / norm return result def get_force_field_func(*point_strength_pairs, **kwargs): radius = kwargs.get("radius", 0.5) def func(point): result = np.array(ORIGIN) for center, strength in point_strength_pairs: to_center = center - point norm = get_norm(to_center) if norm == 0: continue elif norm < radius: to_center /= radius**3 elif norm >= radius: to_center /= norm**3 to_center *= -strength result += to_center return result return func def get_charged_particles(color, sign, radius=0.1): result = Circle( stroke_color=WHITE, stroke_width=0.5, fill_color=color, fill_opacity=0.8, radius=radius ) sign = OldTex(sign) sign.set_stroke(WHITE, 1) sign.set_width(0.5 * result.get_width()) sign.move_to(result) result.add(sign) return result def get_proton(radius=0.1): return get_charged_particles(RED, "+", radius) def get_electron(radius=0.05): return get_charged_particles(BLUE, "-", radius) def preditor_prey_vector_field(point): alpha = 30.0 beta = 1.0 gamma = 30.0 delta = 1.0 x, y = point[:2] result = 0.05 * np.array([ alpha * x - beta * x * y, delta * x * y - gamma * y, 0, ]) return rotate(result, 1 * DEGREES) # Mobjects # TODO, this is untested after turning it from a # ContinualAnimation into a VGroup class JigglingSubmobjects(VGroup): CONFIG = { "amplitude": 0.05, "jiggles_per_second": 1, } def __init__(self, group, **kwargs): VGroup.__init__(self, **kwargs) for submob in group.submobjects: submob.jiggling_direction = rotate_vector( RIGHT, np.random.random() * TAU, ) submob.jiggling_phase = np.random.random() * TAU self.add(submob) self.add_updater(lambda m, dt: m.update(dt)) def update(self, dt): for submob in self.submobjects: submob.jiggling_phase += dt * self.jiggles_per_second * TAU submob.shift( self.amplitude * submob.jiggling_direction * np.sin(submob.jiggling_phase) * dt ) # Scenes class Introduction(MovingCameraScene): CONFIG = { "stream_lines_config": { "start_points_generator_config": { "delta_x": 1.0 / 8, "delta_y": 1.0 / 8, "y_min": -8.5, "y_max": 8.5, } }, "vector_field_config": {}, "virtual_time": 3, } def construct(self): # Divergence def div_func(p): return p / 3 div_vector_field = VectorField( div_func, **self.vector_field_config ) stream_lines = StreamLines( div_func, **self.stream_lines_config ) stream_lines.shuffle() div_title = self.get_title("Divergence") self.add(div_vector_field) self.play( LaggedStartMap(ShowPassingFlash, stream_lines), FadeIn(div_title[0]), *list(map(GrowFromCenter, div_title[1])) ) # Curl def curl_func(p): return rotate_vector(p / 3, 90 * DEGREES) curl_vector_field = VectorField( curl_func, **self.vector_field_config ) stream_lines = StreamLines( curl_func, **self.stream_lines_config ) stream_lines.shuffle() curl_title = self.get_title("Curl") self.play( ReplacementTransform(div_vector_field, curl_vector_field), ReplacementTransform( div_title, curl_title, path_arc=90 * DEGREES ), ) self.play(ShowPassingFlash(stream_lines, run_time=3)) self.wait() def get_title(self, word): title = OldTexText(word) title.scale(2) title.to_edge(UP) title.add_background_rectangle() return title class ShowWritingTrajectory(TeacherStudentsScene): def construct(self): self.add_screen() self.show_meandering_path() self.show_previous_video() def add_screen(self): self.screen.scale(1.4, about_edge=UL) self.add(self.screen) def show_meandering_path(self): solid_path = VMobject().set_points_smoothly([ 3 * UP + 2 * RIGHT, 2 * UP + 4 * RIGHT, 3.5 * UP + 3.5 * RIGHT, 2 * UP + 3 * RIGHT, 3 * UP + 7 * RIGHT, 3 * UP + 5 * RIGHT, UP + 6 * RIGHT, 2 * RIGHT, 2 * UP + 2 * RIGHT, self.screen.get_right() ]) step = 1.0 / 80 dashed_path = VGroup(*[ VMobject().pointwise_become_partial( solid_path, x, x + step / 2 ) for x in np.arange(0, 1 + step, step) ]) arrow = Arrow( solid_path.get_points()[-2], solid_path.get_points()[-1], buff=0 ) dashed_path.add(arrow.tip) dashed_path.set_color_by_gradient(BLUE, YELLOW) self.play( ShowCreation( dashed_path, rate_func=bezier([0, 0, 1, 1]), run_time=5, ), self.teacher.change, "raise_right_hand", self.change_students(*["sassy"] * 3) ) self.play( LaggedStartMap( ApplyMethod, dashed_path, lambda m: (m.scale, 0), remover=True ), self.teacher.change, "tease", self.change_students( *["pondering"] * 3, look_at=self.screen ) ) def show_previous_video(self): screen = self.screen arrow = Vector(LEFT, color=WHITE) arrow.next_to(screen, RIGHT) prev_words = OldTexText("Previous video") prev_words.next_to(arrow, RIGHT) screen.generate_target() screen.target.set_height(3.75) screen.target.to_corner(UR) complex_words = OldTexText("Complex derivatives") complex_words.next_to( screen.target, LEFT, buff=2 * SMALL_BUFF + arrow.get_length() ) self.play( GrowArrow(arrow), Write(prev_words) ) self.wait(3) self.play( arrow.flip, arrow.next_to, screen.target, LEFT, SMALL_BUFF, MoveToTarget(screen), FadeOut(prev_words), Write(complex_words), self.teacher.change, "raise_right_hand", path_arc=30 * DEGREES ) self.play_student_changes("erm", "sassy", "confused") self.look_at(screen) self.wait(2) self.play_student_changes("pondering", "confused", "sassy") self.wait(2) bubble = self.teacher.get_bubble( bubble_type=SpeechBubble, height=3, width=5 ) complex_words.generate_target() complex_words.target.move_to(bubble.get_bubble_center()) # self.play( # FadeOut(screen), # FadeOut(arrow), # ShowCreation(bubble), # self.teacher.change, "hooray", # MoveToTarget(complex_words), # ) s0 = self.students[0] s0.target_center = s0.get_center() def update_s0(s0, dt): s0.target_center += dt * LEFT * 0.5 s0.move_to(s0.target_center) self.add(Mobject.add_updater(s0, update_s0)) self.play_student_changes("tired", "horrified", "sad") self.play(s0.look, LEFT) self.wait(4) class TestVectorField(Scene): CONFIG = { "func": cylinder_flow_vector_field, "flow_time": 15, } def construct(self): lines = StreamLines( four_swirls_function, virtual_time=3, min_magnitude=0, max_magnitude=2, ) self.add(AnimatedStreamLines( lines, line_anim_class=ShowPassingFlash )) self.wait(10) class CylinderModel(Scene): CONFIG = { "production_quality_flow": True, "vector_field_func": cylinder_flow_vector_field, } def construct(self): self.add_plane() self.add_title() self.show_numbers() self.show_contour_lines() self.show_flow() self.apply_joukowsky_map() def add_plane(self): self.plane = ComplexPlane() self.plane.add_coordinates() self.plane.coordinate_labels.submobjects.pop(-1) self.add(self.plane) def add_title(self): title = OldTexText("Complex Plane") title.to_edge(UP, buff=MED_SMALL_BUFF) title.add_background_rectangle() self.title = title self.add(title) def show_numbers(self): run_time = 5 unit_circle = self.unit_circle = Circle( radius=self.plane.unit_size, fill_color=BLACK, fill_opacity=0, stroke_color=YELLOW ) dot = Dot() dot_update = UpdateFromFunc( dot, lambda d: d.move_to(unit_circle.point_from_proportion(1)) ) exp_tex = OldTex("e^{", "0.00", "i}") zero = exp_tex.get_part_by_tex("0.00") zero.fade(1) exp_tex_update = UpdateFromFunc( exp_tex, lambda et: et.next_to(dot, UR, SMALL_BUFF) ) exp_decimal = DecimalNumber( 0, num_decimal_places=2, include_background_rectangle=True, color=YELLOW ) exp_decimal.replace(zero) exp_decimal_update = ChangeDecimalToValue( exp_decimal, TAU, position_update_func=lambda mob: mob.move_to(zero), run_time=run_time, ) sample_numbers = [ complex(-5, 2), complex(2, 2), complex(3, 1), complex(-5, -2), complex(-4, 1), ] sample_labels = VGroup() for z in sample_numbers: sample_dot = Dot(self.plane.number_to_point(z)) sample_label = DecimalNumber( z, num_decimal_places=0, include_background_rectangle=True, ) sample_label.next_to(sample_dot, UR, SMALL_BUFF) sample_labels.add(VGroup(sample_dot, sample_label)) self.play( ShowCreation(unit_circle, run_time=run_time), VFadeIn(exp_tex), UpdateFromAlphaFunc( exp_decimal, lambda ed, a: ed.set_fill(opacity=a) ), dot_update, exp_tex_update, exp_decimal_update, LaggedStartMap( FadeIn, sample_labels, remover=True, rate_func=there_and_back, run_time=run_time, ) ) self.play( FadeOut(exp_tex), FadeOut(exp_decimal), FadeOut(dot), unit_circle.set_fill, BLACK, {"opacity": 1}, ) self.wait() def show_contour_lines(self): warped_grid = self.warped_grid = self.get_warpable_grid() h_line = Line(3 * LEFT, 3 * RIGHT, color=WHITE) # Hack func_label = self.get_func_label() self.remove(self.plane) self.add_foreground_mobjects(self.unit_circle, self.title) self.play( warped_grid.apply_complex_function, inverse_joukowsky_map, Animation(h_line, remover=True) ) self.play(Write(func_label)) self.add_foreground_mobjects(func_label) self.wait() def show_flow(self): stream_lines = self.get_stream_lines() stream_lines_copy = stream_lines.copy() stream_lines_copy.set_stroke(YELLOW, 1) stream_lines_animation = self.get_stream_lines_animation( stream_lines ) tiny_buff = 0.0001 v_lines = VGroup(*[ Line( UP, ORIGIN, path_arc=0, n_arc_anchors=20, ).shift(x * RIGHT) for x in np.linspace(0, 1, 5) ]) v_lines.match_background_image_file(stream_lines) fast_lines, slow_lines = [ VGroup(*[ v_lines.copy().next_to(point, vect, tiny_buff) for point, vect in it.product(h_points, [UP, DOWN]) ]) for h_points in [ [0.5 * LEFT, 0.5 * RIGHT], [2 * LEFT, 2 * RIGHT], ] ] for lines in fast_lines, slow_lines: lines.apply_complex_function(inverse_joukowsky_map) self.add(stream_lines_animation) self.wait(7) self.play( ShowCreationThenDestruction( stream_lines_copy, lag_ratio=0, run_time=3, ) ) self.wait() self.play(ShowCreation(fast_lines)) self.wait(2) self.play(ReplacementTransform(fast_lines, slow_lines)) self.wait(3) self.play( FadeOut(slow_lines), VFadeOut(stream_lines_animation.mobject) ) self.remove(stream_lines_animation) def apply_joukowsky_map(self): shift_val = 0.1 * LEFT + 0.2 * UP scale_factor = get_norm(RIGHT - shift_val) movers = VGroup(self.warped_grid, self.unit_circle) self.unit_circle.insert_n_curves(50) stream_lines = self.get_stream_lines() stream_lines.scale(scale_factor) stream_lines.shift(shift_val) stream_lines.apply_complex_function(joukowsky_map) self.play( movers.scale, scale_factor, movers.shift, shift_val, ) self.wait() self.play( movers.apply_complex_function, joukowsky_map, ShowCreationThenFadeAround(self.func_label), run_time=2 ) self.add(self.get_stream_lines_animation(stream_lines)) self.wait(20) # Helpers def get_func_label(self): func_label = self.func_label = OldTex("f(z) = z + 1 / z") func_label.add_background_rectangle() func_label.next_to(self.title, DOWN, MED_SMALL_BUFF) return func_label def get_warpable_grid(self): top_grid = NumberPlane() top_grid.prepare_for_nonlinear_transform() bottom_grid = top_grid.copy() tiny_buff = 0.0001 top_grid.next_to(ORIGIN, UP, buff=tiny_buff) bottom_grid.next_to(ORIGIN, DOWN, buff=tiny_buff) result = VGroup(top_grid, bottom_grid) result.add(*[ Line( ORIGIN, FRAME_WIDTH * RIGHT / 2, color=WHITE, path_arc=0, n_arc_anchors=100, ).next_to(ORIGIN, vect, buff=2) for vect in (LEFT, RIGHT) ]) # This line is a bit of a hack h_line = Line(LEFT, RIGHT, color=WHITE) h_line.set_points([LEFT, LEFT, RIGHT, RIGHT]) h_line.scale(2) result.add(h_line) return result def get_stream_lines(self): func = self.vector_field_func if self.production_quality_flow: delta_x = 0.5 delta_y = 0.1 else: delta_x = 1 # delta_y = 1 delta_y = 0.1 return StreamLines( func, start_points_generator_config={ "x_min": -8, "x_max": -7, "y_min": -4, "y_max": 4, "delta_x": delta_x, "delta_y": delta_y, "n_repeats": 1, "noise_factor": 0.1, }, stroke_width=2, virtual_time=15, ) def get_stream_lines_animation(self, stream_lines): if self.production_quality_flow: line_anim_class = ShowPassingFlashWithThinningStrokeWidth else: line_anim_class = ShowPassingFlash return AnimatedStreamLines( stream_lines, line_anim_class=line_anim_class, ) class OkayNotToUnderstand(Scene): def construct(self): words = OldTexText( "It's okay not to \\\\ understand this just yet." ) morty = Mortimer() morty.change("confused") words.next_to(morty, UP) self.add(morty, words) class ThatsKindOfInteresting(TeacherStudentsScene): def construct(self): self.student_says( "Cool!", target_mode="hooray", index=2, added_anims=[self.teacher.change, "happy"] ) self.play_student_changes("happy", "happy") self.wait(2) class ElectricField(CylinderModel, MovingCameraScene): def construct(self): self.add_plane() self.add_title() self.setup_warped_grid() self.show_uniform_field() self.show_moving_charges() self.show_field_lines() def setup_warped_grid(self): warped_grid = self.warped_grid = self.get_warpable_grid() warped_grid.save_state() func_label = self.get_func_label() unit_circle = self.unit_circle = Circle( radius=self.plane.unit_size, stroke_color=YELLOW, fill_color=BLACK, fill_opacity=1 ) self.add_foreground_mobjects(self.title, func_label, unit_circle) self.remove(self.plane) self.play( warped_grid.apply_complex_function, inverse_joukowsky_map, ) self.wait() def show_uniform_field(self): vector_field = self.vector_field = VectorField( lambda p: UP, colors=[BLUE_E, WHITE, RED] ) protons, electrons = groups = [ VGroup(*[method(radius=0.2) for x in range(20)]) for method in (get_proton, get_electron) ] for group in groups: group.arrange(RIGHT, buff=MED_SMALL_BUFF) random.shuffle(group.submobjects) protons.next_to(FRAME_HEIGHT * DOWN / 2, DOWN) electrons.next_to(FRAME_HEIGHT * UP / 2, UP) self.play( self.warped_grid.restore, FadeOut(self.unit_circle), FadeOut(self.title), FadeOut(self.func_label), LaggedStartMap(GrowArrow, vector_field) ) self.remove_foreground_mobjects(self.title, self.func_label) self.wait() for group, vect in (protons, UP), (electrons, DOWN): self.play(LaggedStartMap( ApplyMethod, group, lambda m: (m.shift, (FRAME_HEIGHT + 1) * vect), run_time=3, rate_func=rush_into )) def show_moving_charges(self): unit_circle = self.unit_circle protons = VGroup(*[ get_proton().move_to( rotate_vector(0.275 * n * RIGHT, angle) ) for n in range(4) for angle in np.arange( 0, TAU, TAU / (6 * n) if n > 0 else TAU ) ]) jiggling_protons = JigglingSubmobjects(protons) electrons = VGroup(*[ get_electron().move_to( proton.get_center() + proton.radius * rotate_vector(RIGHT, angle) ) for proton in protons for angle in [np.random.random() * TAU] ]) jiggling_electrons = JigglingSubmobjects(electrons) electrons.generate_target() for electron in electrons.target: y_part = electron.get_center()[1] if y_part > 0: electron.shift(2 * y_part * DOWN) # New vector field def new_electric_field(point): if get_norm(point) < 1: return ORIGIN vect = cylinder_flow_vector_field(point) return rotate_vector(vect, 90 * DEGREES) new_vector_field = VectorField( new_electric_field, colors=self.vector_field.colors ) warped_grid = self.warped_grid self.play(GrowFromCenter(unit_circle)) self.add(jiggling_protons, jiggling_electrons) self.add_foreground_mobjects( self.vector_field, unit_circle, protons, electrons ) self.play( LaggedStartMap(VFadeIn, protons), LaggedStartMap(VFadeIn, electrons), ) self.play( self.camera.frame.scale, 0.7, run_time=3 ) self.play( MoveToTarget(electrons), # More indication? warped_grid.apply_complex_function, inverse_joukowsky_map, Transform( self.vector_field, new_vector_field ), run_time=3 ) self.wait(5) def show_field_lines(self): h_lines = VGroup(*[ Line( 5 * LEFT, 5 * RIGHT, path_arc=0, n_arc_anchors=50, stroke_color=GREY_B, stroke_width=2, ).shift(y * UP) for y in np.arange(-3, 3.25, 0.25) if y != 0 ]) h_lines.apply_complex_function(inverse_joukowsky_map) for h_line in h_lines: h_line.save_state() voltage = DecimalNumber( 10, num_decimal_places=1, unit="\\, V", color=YELLOW, include_background_rectangle=True, ) vp_prop = 0.1 voltage_point = VectorizedPoint( h_lines[4].point_from_proportion(vp_prop) ) def get_voltage(dummy_arg): y = voltage_point.get_center()[1] return 10 - y voltage_update = voltage.add_updater( lambda d: d.set_value(get_voltage), ) voltage.add_updater( lambda d: d.next_to( voltage_point, UP, SMALL_BUFF ) ) self.play(ShowCreation( h_lines, run_time=2, lag_ratio=0 )) self.add(voltage_update) self.add_foreground_mobjects(voltage) self.play( UpdateFromAlphaFunc( voltage, lambda m, a: m.set_fill(opacity=a) ), h_lines[4].set_stroke, YELLOW, 4, ) for hl1, hl2 in zip(h_lines[4:], h_lines[5:]): self.play( voltage_point.move_to, hl2.point_from_proportion(vp_prop), hl1.restore, hl2.set_stroke, YELLOW, 3, run_time=0.5 ) self.wait(0.5) class AskQuestions(TeacherStudentsScene): def construct(self): div_tex = OldTex("\\nabla \\cdot", vec_tex("v")) curl_tex = OldTex("\\nabla \\times", vec_tex("v")) div_name = OldTexText("Divergence") curl_name = OldTexText("Curl") div = VGroup(div_name, div_tex) curl = VGroup(curl_name, curl_tex) for group in div, curl: group[1].set_color_by_tex(vec_tex("v"), YELLOW) group.arrange(DOWN) topics = VGroup(div, curl) topics.arrange(DOWN, buff=LARGE_BUFF) topics.move_to(self.hold_up_spot, DOWN) div.save_state() div.move_to(self.hold_up_spot, DOWN) screen = self.screen self.student_says( "What does fluid flow have \\\\ to do with electricity?", added_anims=[self.teacher.change, "happy"] ) self.wait() self.student_says( "And you mentioned \\\\ complex numbers?", index=0, ) self.wait(3) self.play( FadeInFromDown(div), self.teacher.change, "raise_right_hand", FadeOut(self.students[0].bubble), FadeOut(self.students[0].bubble.content), self.change_students(*["pondering"] * 3) ) self.play( FadeInFromDown(curl), div.restore ) self.wait() self.look_at(self.screen) self.wait() self.play_all_student_changes("hooray", look_at=screen) self.wait(3) topics.generate_target() topics.target.to_edge(LEFT, buff=LARGE_BUFF) arrow = OldTex("\\leftrightarrow") arrow.scale(2) arrow.next_to(topics.target, RIGHT, buff=LARGE_BUFF) screen.next_to(arrow, RIGHT, LARGE_BUFF) complex_analysis = OldTexText("Complex analysis") complex_analysis.next_to(screen, UP) self.play( MoveToTarget(topics), self.change_students( "confused", "sassy", "erm", look_at=topics.target ), self.teacher.change, "pondering", screen ) self.play( Write(arrow), FadeInFromDown(complex_analysis) ) self.look_at(screen) self.wait(6) class ScopeMeiosis(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs": { "flip_at_start": True, "color": GREY_BROWN, }, "default_pi_creature_start_corner": DR, } def construct(self): morty = self.pi_creature section_titles = VGroup(*list(map(TexText, [ "Background on div/curl", "Conformal maps", "Conformal map $\\Rightarrow" + "\\text{div}\\textbf{F} = " + "\\text{curl}\\textbf{F} = 0$", "Complex derivatives", ]))) sections = VGroup(*[ VGroup(title, self.get_lines(title, 3)) for title in section_titles ]) sections.arrange( DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT ) sections.to_edge(UP) top_title = section_titles[0] lower_sections = sections[1:] self.add(sections) modes = [ "pondering", "pondering", "bump", "bump", "concerned_musician", "concerned_musician", ] for n, mode in zip(list(range(6)), modes): if n % 2 == 1: top_title = lines lines = self.get_lines(top_title, 4) else: lines = self.get_lines(top_title, 6) lower_sections.generate_target() lower_sections.target.next_to( lines, DOWN, MED_LARGE_BUFF, LEFT, ) self.play( ShowCreation(lines), MoveToTarget(lower_sections), morty.change, mode, lines, ) def get_lines(self, title, n_lines): lines = VGroup(*[ Line(3 * LEFT, 3 * RIGHT, color=GREY_B) for x in range(n_lines) ]) lines.arrange(DOWN, buff=MED_SMALL_BUFF) lines.next_to( title, DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT ) lines[-1].pointwise_become_partial( lines[-1], 0, random.random() ) return lines class WhyAreYouTellingUsThis(TeacherStudentsScene): def construct(self): self.student_says( "Cool story bro...\\\\ how about the actual math?", target_mode="sassy", added_anims=[self.teacher.change, "guilty"] ) self.play_student_changes("angry", "sassy", "angry") self.wait(2) class TopicsAndConnections(Scene): CONFIG = { "random_seed": 1, } def construct(self): dots = VGroup(*[ Dot(8 * np.array([ random.random(), random.random(), 0 ])) for n in range(5) ]) topics = VGroup(*[ OldTexText(word).next_to( dot, RIGHT, SMALL_BUFF ) for dot, word in zip(dots, [ "Divergence/curl", "Fluid flow", "Electricity and magnetism", "Conformal maps", "Complex numbers" ]) ]) for topic in topics: topic.add_to_back( topic.copy().set_stroke(BLACK, 2) ) VGroup(dots, topics).center() for dot in dots: dot.save_state() dot.scale(3) dot.set_fill(opacity=0) connections = VGroup(*[ DashedLine(d1.get_center(), d2.get_center()) for d1, d2 in it.combinations(dots, 2) ]) connections.set_stroke(YELLOW, 2) full_rect = FullScreenFadeRectangle() self.play( LaggedStartMap( ApplyMethod, dots, lambda d: (d.restore,) ), LaggedStartMap(Write, topics), ) self.wait() self.play( LaggedStartMap(ShowCreation, connections), Animation(topics), Animation(dots), ) self.wait() self.play( FadeIn(full_rect), Animation(topics[0]), Animation(dots[0]), ) self.wait() class OnToTheLesson(Scene): def construct(self): words = OldTexText("On to the lesson!") words.scale(1.5) self.add(words) self.play(FadeInFromDown(words)) self.wait() class IntroduceVectorField(Scene): CONFIG = { "vector_field_config": { # "delta_x": 2, # "delta_y": 2, "delta_x": 0.5, "delta_y": 0.5, }, "stream_line_config": { "start_points_generator_config": { # "delta_x": 1, # "delta_y": 1, "delta_x": 0.25, "delta_y": 0.25, }, "virtual_time": 3, }, "stream_line_animation_config": { # "line_anim_class": ShowPassingFlash, "line_anim_class": ShowPassingFlashWithThinningStrokeWidth, } } def construct(self): self.add_plane() self.add_title() self.points_to_vectors() self.show_fluid_flow() self.show_gravitational_force() self.show_magnetic_force() self.show_fluid_flow() def add_plane(self): plane = self.plane = NumberPlane() plane.add_coordinates() plane.remove(plane.coordinate_labels[-1]) self.add(plane) def add_title(self): title = OldTexText("Vector field") title.scale(1.5) title.to_edge(UP, buff=MED_SMALL_BUFF) title.add_background_rectangle(opacity=1, buff=SMALL_BUFF) self.add_foreground_mobjects(title) def points_to_vectors(self): vector_field = self.vector_field = VectorField( four_swirls_function, **self.vector_field_config ) dots = VGroup() for vector in vector_field: dot = Dot(radius=0.05) dot.move_to(vector.get_start()) dot.target = vector dots.add(dot) self.play(LaggedStartMap(GrowFromCenter, dots)) self.wait() self.play(LaggedStartMap(MoveToTarget, dots, remover=True)) self.add(vector_field) self.wait() def show_fluid_flow(self): vector_field = self.vector_field stream_lines = StreamLines( vector_field.func, **self.stream_line_config ) stream_line_animation = AnimatedStreamLines( stream_lines, **self.stream_line_animation_config ) self.add(stream_line_animation) self.play( vector_field.set_fill, {"opacity": 0.5} ) self.wait(7) self.play( vector_field.set_fill, {"opacity": 1}, VFadeOut(stream_line_animation.mobject), ) self.remove(stream_line_animation) def show_gravitational_force(self): earth = self.earth = ImageMobject("earth") moon = self.moon = ImageMobject("moon", height=1) earth_center = 3 * RIGHT + 2 * UP moon_center = 3 * LEFT + DOWN earth.move_to(earth_center) moon.move_to(moon_center) gravity_func = get_force_field_func((earth_center, -6), (moon_center, -1)) gravity_field = VectorField( gravity_func, **self.vector_field_config ) self.add_foreground_mobjects(earth, moon) self.play( GrowFromCenter(earth), GrowFromCenter(moon), Transform(self.vector_field, gravity_field), run_time=2 ) self.vector_field.func = gravity_field.func self.wait() def show_magnetic_force(self): magnetic_func = get_force_field_func( (3 * LEFT, -1), (3 * RIGHT, +1) ) magnetic_field = VectorField( magnetic_func, **self.vector_field_config ) magnet = VGroup(*[ Rectangle( width=3.5, height=1, stroke_width=0, fill_opacity=1, fill_color=color ) for color in (BLUE, RED) ]) magnet.arrange(RIGHT, buff=0) for char, vect in ("S", LEFT), ("N", RIGHT): letter = OldTexText(char) edge = magnet.get_edge_center(vect) letter.next_to(edge, -vect, buff=MED_LARGE_BUFF) magnet.add(letter) self.add_foreground_mobjects(magnet) self.play( self.earth.scale, 0, self.moon.scale, 0, DrawBorderThenFill(magnet), Transform(self.vector_field, magnetic_field), run_time=2 ) self.vector_field.func = magnetic_field.func self.remove_foreground_mobjects(self.earth, self.moon) class QuickNoteOnDrawingThese(TeacherStudentsScene): def construct(self): self.teacher_says( "Quick note on \\\\ drawing vector fields", bubble_config={"width": 5, "height": 3}, added_anims=[self.change_students( "confused", "erm", "sassy" )] ) self.look_at(self.screen) self.wait(3) class ShorteningLongVectors(IntroduceVectorField): def construct(self): self.add_plane() self.add_title() self.contrast_adjusted_and_non_adjusted() def contrast_adjusted_and_non_adjusted(self): func = four_swirls_function unadjusted = VectorField( func, length_func=lambda n: n, colors=[WHITE], ) adjusted = VectorField(func) for v1, v2 in zip(adjusted, unadjusted): v1.save_state() v1.target = v2 self.add(adjusted) self.wait() self.play(LaggedStartMap( MoveToTarget, adjusted, run_time=3 )) self.wait() self.play(LaggedStartMap( ApplyMethod, adjusted, lambda m: (m.restore,), run_time=3 )) self.wait() class TimeDependentVectorField(ExternallyAnimatedScene): pass class ChangingElectricField(Scene): CONFIG = { "vector_field_config": {} } def construct(self): particles = self.get_particles() vector_field = self.get_vector_field() def update_vector_field(vector_field): new_field = self.get_vector_field() Transform(vector_field, new_field).update(1) vector_field.func = new_field.func def update_particles(particles, dt): func = vector_field.func for particle in particles: force = func(particle.get_center()) particle.velocity += force * dt particle.shift(particle.velocity * dt) self.add( Mobject.add_updater(vector_field, update_vector_field), Mobject.add_updater(particles, update_particles), ) self.wait(20) def get_particles(self): particles = self.particles = VGroup() for n in range(9): if n % 2 == 0: particle = get_proton(radius=0.2) particle.charge = +1 else: particle = get_electron(radius=0.2) particle.charge = -1 particle.velocity = np.random.normal(0, 0.1, 3) particles.add(particle) particle.shift(np.random.normal(0, 0.2, 3)) particles.arrange_in_grid(buff=LARGE_BUFF) return particles def get_vector_field(self): func = get_force_field_func(*list(zip( list(map(Mobject.get_center, self.particles)), [p.charge for p in self.particles] ))) self.vector_field = VectorField(func, **self.vector_field_config) return self.vector_field class InsertAirfoildTODO(TODOStub): CONFIG = {"message": "Insert airfoil flow animation"} class ThreeDVectorField(ExternallyAnimatedScene): pass class ThreeDVectorFieldEquation(Scene): def construct(self): vector = Matrix([ "yz", "xz", "xy", ]) vector.set_height(FRAME_HEIGHT - 1) self.add(vector) class GravityFluidFlow(IntroduceVectorField): def construct(self): self.vector_field = VectorField( lambda p: np.array(ORIGIN), **self.vector_field_config ) self.show_gravitational_force() self.show_fluid_flow() class TotallyToScale(Scene): def construct(self): words = OldTexText( "Totally drawn to scale. \\\\ Don't even worry about it." ) words.set_width(FRAME_WIDTH - 1) words.add_background_rectangle() self.add(words) self.wait() # TODO: Revisit this class FluidFlowAsHillGradient(CylinderModel, ThreeDScene): CONFIG = { "production_quality_flow": False, } def construct(self): def potential(point): x, y = point[:2] result = 2 - 0.01 * op.mul( ((x - 4)**2 + y**2), ((x + 4)**2 + y**2) ) return max(-10, result) vector_field_func = negative_gradient(potential) stream_lines = StreamLines( vector_field_func, virtual_time=3, color_lines_by_magnitude=False, start_points_generator_config={ "delta_x": 0.2, "delta_y": 0.2, } ) for line in stream_lines: line.get_points()[:, 2] = np.apply_along_axis( potential, 1, line.get_points() ) stream_lines_animation = self.get_stream_lines_animation( stream_lines ) plane = NumberPlane() self.add(plane) self.add(stream_lines_animation) self.wait(3) self.begin_ambient_camera_rotation(rate=0.1) self.move_camera( phi=70 * DEGREES, run_time=2 ) self.wait(5) class DefineDivergence(ChangingElectricField): CONFIG = { "vector_field_config": { "length_func": lambda norm: 0.3, "min_magnitude": 0, "max_magnitude": 1, }, "stream_line_config": { "start_points_generator_config": { "delta_x": 0.125, "delta_y": 0.125, }, "virtual_time": 5, "n_anchors_per_line": 10, "min_magnitude": 0, "max_magnitude": 1, "stroke_width": 2, }, "stream_line_animation_config": { "line_anim_class": ShowPassingFlash, }, "flow_time": 10, "random_seed": 7, } def construct(self): self.draw_vector_field() self.show_flow() self.point_out_sources_and_sinks() self.show_divergence_values() def draw_vector_field(self): particles = self.get_particles() random.shuffle(particles.submobjects) particles.remove(particles[0]) particles.arrange_in_grid( n_cols=4, buff=3 ) for particle in particles: particle.shift( np.random.normal(0, 0.75) * RIGHT, np.random.normal(0, 0.5) * UP, ) particle.shift_onto_screen(buff=2 * LARGE_BUFF) particle.charge *= 0.125 vector_field = self.get_vector_field() self.play( LaggedStartMap(GrowArrow, vector_field), LaggedStartMap(GrowFromCenter, particles), run_time=4 ) self.wait() self.play(LaggedStartMap(FadeOut, particles)) def show_flow(self): stream_lines = StreamLines( self.vector_field.func, **self.stream_line_config ) stream_line_animation = AnimatedStreamLines( stream_lines, **self.stream_line_animation_config ) self.add(stream_line_animation) self.wait(self.flow_time) def point_out_sources_and_sinks(self): particles = self.particles self.positive_points, self.negative_points = [ [ particle.get_center() for particle in particles if u * particle.charge > 0 ] for u in (+1, -1) ] pair_of_vector_circle_groups = VGroup() for point_set in self.positive_points, self.negative_points: vector_circle_groups = VGroup() for point in point_set: vector_circle_group = VGroup() for angle in np.linspace(0, TAU, 12, endpoint=False): step = 0.5 * rotate_vector(RIGHT, angle) vect = self.vector_field.get_vector(point + step) vect.set_color(WHITE) vect.set_stroke(width=2) vector_circle_group.add(vect) vector_circle_groups.add(vector_circle_group) pair_of_vector_circle_groups.add(vector_circle_groups) self.play( self.vector_field.set_fill, {"opacity": 0.5}, LaggedStartMap( LaggedStartMap, vector_circle_groups, lambda vcg: (GrowArrow, vcg), ), ) self.wait(4) self.play(FadeOut(vector_circle_groups)) self.play(self.vector_field.set_fill, {"opacity": 1}) self.positive_vector_circle_groups = pair_of_vector_circle_groups[0] self.negative_vector_circle_groups = pair_of_vector_circle_groups[1] self.wait() def show_divergence_values(self): positive_points = self.positive_points negative_points = self.negative_points div_func = divergence(self.vector_field.func) circle = Circle(color=WHITE, radius=0.2) circle.add(Dot(circle.get_center(), radius=0.02)) circle.move_to(positive_points[0]) div_tex = OldTex( "\\text{div} \\, \\textbf{F}(x, y) = " ) div_tex.add_background_rectangle() div_tex_update = Mobject.add_updater( div_tex, lambda m: m.next_to(circle, UP, SMALL_BUFF) ) div_value = DecimalNumber( 0, num_decimal_places=1, include_background_rectangle=True, include_sign=True, ) div_value_update = ContinualChangingDecimal( div_value, lambda a: np.round(div_func(circle.get_center()), 1), position_update_func=lambda m: m.next_to(div_tex, RIGHT, SMALL_BUFF), include_sign=True, ) self.play( ShowCreation(circle), FadeIn(div_tex), FadeIn(div_value), ) self.add(div_tex_update) self.add(div_value_update) self.wait() for point in positive_points[1:-1]: self.play(circle.move_to, point) self.wait(1.5) for point in negative_points: self.play(circle.move_to, point) self.wait(2) self.wait(4) # self.remove(div_tex_update) # self.remove(div_value_update) # self.play( # ApplyMethod(circle.scale, 0, remover=True), # FadeOut(div_tex), # FadeOut(div_value), # ) class DefineDivergenceJustFlow(DefineDivergence): CONFIG = { "flow_time": 10, } def construct(self): self.force_skipping() self.draw_vector_field() self.revert_to_original_skipping_status() self.clear() self.show_flow() class DefineDivergenceSymbols(Scene): def construct(self): tex_mob = OldTex( "\\text{div}", "\\textbf{F}", "(x, y)", "=", ) div, F, xy, eq = tex_mob output = DecimalNumber(0, include_sign=True) output.next_to(tex_mob, RIGHT) time_tracker = ValueTracker() always_shift(time_tracker, rate=1) self.add(time_tracker) output_animation = ContinualChangingDecimal( output, lambda a: 3 * np.cos(int(time_tracker.get_value())), ) F.set_color(BLUE) xy.set_color(YELLOW) F_brace = Brace(F, UP, buff=SMALL_BUFF) F_label = F_brace.get_text( "Vector field function", ) F_label.match_color(F) xy_brace = Brace(xy, DOWN, buff=SMALL_BUFF) xy_label = xy_brace.get_text("Some point") xy_label.match_color(xy) output_brace = Brace(output, UP, buff=SMALL_BUFF) output_label = output_brace.get_text( "Measure of how much \\\\ " "$(x, y)$ ``generates'' fluid" ) brace_label_pairs = [ (F_brace, F_label), (xy_brace, xy_label), (output_brace, output_label), ] self.add(tex_mob, output_animation) fade_anims = [] for brace, label in brace_label_pairs: self.play( GrowFromCenter(brace), FadeInFromDown(label), *fade_anims ) self.wait(2) fade_anims = list(map(FadeOut, [brace, label])) self.wait() class DivergenceAtSlowFastPoint(Scene): CONFIG = { "vector_field_config": { "length_func": lambda norm: 0.1 + 0.4 * norm / 4.0, "min_magnitude": 0, "max_magnitude": 3, }, "stream_lines_config": { "start_points_generator_config": { "delta_x": 0.125, "delta_y": 0.125, }, "virtual_time": 1, "min_magnitude": 0, "max_magnitude": 3, }, } def construct(self): def func(point): return 3 * sigmoid(point[0]) * RIGHT vector_field = self.vector_field = VectorField( func, **self.vector_field_config ) circle = Circle(color=WHITE) slow_words = OldTexText("Slow flow in") fast_words = OldTexText("Fast flow out") words = VGroup(slow_words, fast_words) for word, vect in zip(words, [LEFT, RIGHT]): word.add_background_rectangle() word.next_to(circle, vect) div_tex = OldTex( "\\text{div}\\,\\textbf{F}(x, y) > 0" ) div_tex.add_background_rectangle() div_tex.next_to(circle, UP) self.add(vector_field) self.add_foreground_mobjects(circle, div_tex) self.begin_flow() self.wait(2) for word in words: self.add_foreground_mobjects(word) self.play(Write(word)) self.wait(8) def begin_flow(self): stream_lines = StreamLines( self.vector_field.func, **self.stream_lines_config ) stream_line_animation = AnimatedStreamLines(stream_lines) stream_line_animation.update(3) self.add(stream_line_animation) class DivergenceAsNewFunction(Scene): def construct(self): self.add_plane() self.show_vector_field_function() self.show_divergence_function() def add_plane(self): plane = self.plane = NumberPlane() plane.add_coordinates() self.add(plane) def show_vector_field_function(self): func = self.func unscaled_vector_field = VectorField( func, length_func=lambda norm: norm, colors=[BLUE_C, YELLOW, RED], delta_x=np.inf, delta_y=np.inf, ) in_dot = Dot(color=PINK) in_dot.move_to(3.75 * LEFT + 1.25 * UP) def get_input(): return in_dot.get_center() def get_out_vect(): return unscaled_vector_field.get_vector(get_input()) # Tex func_tex = OldTex( "\\textbf{F}(", "+0.00", ",", "+0.00", ")", "=", ) dummy_in_x, dummy_in_y = func_tex.get_parts_by_tex("+0.00") func_tex.add_background_rectangle() rhs = DecimalMatrix( [[0], [0]], element_to_mobject_config={ "num_decimal_places": 2, "include_sign": True, }, include_background_rectangle=True ) rhs.next_to(func_tex, RIGHT) dummy_out_x, dummy_out_y = rhs.get_mob_matrix().flatten() VGroup(func_tex, rhs).to_corner(UL, buff=MED_SMALL_BUFF) VGroup( dummy_in_x, dummy_in_y, dummy_out_x, dummy_out_y, ).set_fill(BLACK, opacity=0) # Changing decimals in_x, in_y, out_x, out_y = [ DecimalNumber(0, include_sign=True) for x in range(4) ] VGroup(in_x, in_y).set_color(in_dot.get_color()) VGroup(out_x, out_y).set_color(get_out_vect().get_fill_color()) in_x_update = ContinualChangingDecimal( in_x, lambda a: get_input()[0], position_update_func=lambda m: m.move_to(dummy_in_x) ) in_y_update = ContinualChangingDecimal( in_y, lambda a: get_input()[1], position_update_func=lambda m: m.move_to(dummy_in_y) ) out_x_update = ContinualChangingDecimal( out_x, lambda a: func(get_input())[0], position_update_func=lambda m: m.move_to(dummy_out_x) ) out_y_update = ContinualChangingDecimal( out_y, lambda a: func(get_input())[1], position_update_func=lambda m: m.move_to(dummy_out_y) ) self.add(func_tex, rhs) # self.add(Mobject.add_updater( # rhs, lambda m: m.next_to(func_tex, RIGHT) # )) # Where those decimals actually change self.add(in_x_update, in_y_update) in_dot.save_state() in_dot.move_to(ORIGIN) self.play(in_dot.restore) self.wait() self.play(*[ ReplacementTransform( VGroup(mob.copy().fade(1)), VGroup(out_x, out_y), ) for mob in (in_x, in_y) ]) out_vect = get_out_vect() VGroup(out_x, out_y).match_style(out_vect) out_vect.save_state() out_vect.move_to(rhs) out_vect.set_fill(opacity=0) self.play(out_vect.restore) self.out_vect_update = Mobject.add_updater( out_vect, lambda ov: Transform(ov, get_out_vect()).update(1) ) self.add(self.out_vect_update) self.add(out_x_update, out_y_update) self.add(Mobject.add_updater( VGroup(out_x, out_y), lambda m: m.match_style(out_vect) )) self.wait() for vect in DOWN, 2 * RIGHT, UP: self.play( in_dot.shift, 3 * vect, run_time=3 ) self.wait() self.in_dot = in_dot self.out_vect = out_vect self.func_equation = VGroup(func_tex, rhs) self.out_x, self.out_y = out_x, out_y self.in_x, self.in_y = out_x, out_y self.in_x_update = in_x_update self.in_y_update = in_y_update self.out_x_update = out_x_update self.out_y_update = out_y_update def show_divergence_function(self): vector_field = VectorField(self.func) vector_field.remove(*[ v for v in vector_field if v.get_start()[0] < 0 and v.get_start()[1] > 2 ]) vector_field.set_fill(opacity=0.5) in_dot = self.in_dot def get_neighboring_points(step_sizes=[0.3], n_angles=12): point = in_dot.get_center() return list(it.chain(*[ [ point + step_size * step for step in compass_directions(n_angles) ] for step_size in step_sizes ])) def get_vector_ring(): return VGroup(*[ vector_field.get_vector(point) for point in get_neighboring_points() ]) def get_stream_lines(): return StreamLines( self.func, start_points_generator=get_neighboring_points, start_points_generator_config={ "step_sizes": np.arange(0.1, 0.5, 0.1) }, virtual_time=1, stroke_width=3, ) def show_flow(): stream_lines = get_stream_lines() random.shuffle(stream_lines.submobjects) self.play(LaggedStartMap( ShowCreationThenDestruction, stream_lines, remover=True )) vector_ring = get_vector_ring() vector_ring_update = Mobject.add_updater( vector_ring, lambda vr: Transform(vr, get_vector_ring()).update(1) ) func_tex, rhs = self.func_equation out_x, out_y = self.out_x, self.out_y out_x_update = self.out_x_update out_y_update = self.out_y_update div_tex = OldTex("\\text{div}") div_tex.add_background_rectangle() div_tex.move_to(func_tex, LEFT) div_tex.shift(2 * SMALL_BUFF * RIGHT) self.remove(out_x_update, out_y_update) self.remove(self.out_vect_update) self.add(self.in_x_update, self.in_y_update) self.play( func_tex.next_to, div_tex, RIGHT, SMALL_BUFF, {"submobject_to_align": func_tex[1][0]}, Write(div_tex), FadeOut(self.out_vect), FadeOut(out_x), FadeOut(out_y), FadeOut(rhs), ) # This line is a dumb hack around a Scene bug self.add(*[ Mobject.add_updater( mob, lambda m: m.set_fill(None, 0) ) for mob in (out_x, out_y) ]) self.add_foreground_mobjects(div_tex) self.play( LaggedStartMap(GrowArrow, vector_field), LaggedStartMap(GrowArrow, vector_ring), ) self.add(vector_ring_update) self.wait() div_func = divergence(self.func) div_rhs = DecimalNumber( 0, include_sign=True, include_background_rectangle=True ) div_rhs_update = ContinualChangingDecimal( div_rhs, lambda a: div_func(in_dot.get_center()), position_update_func=lambda d: d.next_to(func_tex, RIGHT, SMALL_BUFF) ) self.play(FadeIn(div_rhs)) self.add(div_rhs_update) show_flow() for vect in 2 * RIGHT, 3 * DOWN, 2 * LEFT, 2 * LEFT: self.play(in_dot.shift, vect, run_time=3) show_flow() self.wait() def func(self, point): x, y = point[:2] return np.sin(x + y) * RIGHT + np.sin(y * x / 3) * UP class DivergenceZeroCondition(Scene): def construct(self): title = OldTexText( "For actual (incompressible) fluid flow:" ) title.to_edge(UP) equation = OldTex( "\\text{div} \\, \\textbf{F} = 0 \\quad \\text{everywhere}" ) equation.next_to(title, DOWN) for mob in title, equation: mob.add_background_rectangle(buff=MED_SMALL_BUFF / 2) self.add_foreground_mobjects(mob) self.wait(1) class PureCylinderFlow(Scene): def construct(self): self.add_vector_field() self.begin_flow() self.add_circle() self.wait(5) def add_vector_field(self): vector_field = VectorField( cylinder_flow_vector_field, ) for vector in vector_field: if get_norm(vector.get_start()) < 1: vector_field.remove(vector) vector_field.set_fill(opacity=0.75) self.modify_vector_field(vector_field) self.add_foreground_mobjects(vector_field) def begin_flow(self): stream_lines = StreamLines( cylinder_flow_vector_field, colors=[BLUE_E, BLUE_D, BLUE_C], start_points_generator_config={ "delta_x": 0.125, "delta_y": 0.125, }, virtual_time=5, ) self.add(stream_lines) for stream_line in stream_lines: if get_norm(stream_line.get_points()[0]) < 1: stream_lines.remove(stream_line) self.modify_flow(stream_lines) stream_line_animation = AnimatedStreamLines(stream_lines) stream_line_animation.update(3) self.add(stream_line_animation) def add_circle(self): circle = Circle( radius=1, stroke_color=YELLOW, fill_color=BLACK, fill_opacity=1, ) self.modify_flow(circle) self.add_foreground_mobjects(circle) def modify_flow(self, mobject): pass def modify_vector_field(self, vector_field): pass class PureAirfoilFlow(PureCylinderFlow): def modify_flow(self, mobject): vect = 0.1 * LEFT + 0.2 * UP mobject.scale(get_norm(vect - RIGHT)) mobject.shift(vect) mobject.apply_complex_function(joukowsky_map) return mobject def modify_vector_field(self, vector_field): def func(z): w = complex(-0.1, 0.2) n = abs(w - 1) return joukowsky_map(inverse_joukowsky_map(z) - w / n) def new_vector_field_func(point): z = R3_to_complex(point) return complex_to_R3(derivative(func)(z).conjugate()) vf = VectorField(new_vector_field_func, delta_y=0.33) Transform(vector_field, vf).update(1) vf.set_fill(opacity=0.5) class IntroduceCurl(IntroduceVectorField): CONFIG = { "stream_line_animation_config": { "line_anim_class": ShowPassingFlash, }, "stream_line_config": { "start_points_generator_config": { "delta_x": 0.125, "delta_y": 0.125, }, "virtual_time": 1, } } def construct(self): self.add_title() self.show_vector_field() self.begin_flow() self.show_rotation() def add_title(self): title = self.title = Title( "Curl", match_underline_width_to_text=True, scale_factor=1.5, ) title.add_background_rectangle() title.to_edge(UP, buff=MED_SMALL_BUFF) self.add_foreground_mobjects(title) def show_vector_field(self): vector_field = self.vector_field = VectorField( four_swirls_function, **self.vector_field_config ) vector_field.submobjects.sort( key=lambda v: v.get_length() ) self.play(LaggedStartMap(GrowArrow, vector_field)) self.wait() def begin_flow(self): stream_lines = StreamLines( self.vector_field.func, **self.stream_line_config ) stream_line_animation = AnimatedStreamLines( stream_lines, **self.stream_line_animation_config ) self.add(stream_line_animation) self.wait(3) def show_rotation(self): clockwise_arrows, counterclockwise_arrows = [ VGroup(*[ self.get_rotation_arrows(clockwise=cw).move_to(point) for point in points ]) for cw, points in [ (True, [2 * UP, 2 * DOWN]), (False, [4 * LEFT, 4 * RIGHT]), ] ] for group, u in (counterclockwise_arrows, +1), (clockwise_arrows, -1): for arrows in group: label = OldTex( "\\text{curl} \\, \\textbf{F}", ">" if u > 0 else "<", "0" ) label.add_background_rectangle() label.next_to(arrows, DOWN) self.add_foreground_mobjects(label) always_rotate(arrows, rate=u * 30 * DEGREES) self.play( FadeIn(arrows), FadeIn(label) ) self.wait(2) for group in counterclockwise_arrows, clockwise_arrows: self.play(FocusOn(group[0])) self.play( UpdateFromAlphaFunc( group, lambda mob, alpha: mob.set_color( interpolate_color(WHITE, PINK, alpha) ).set_stroke( width=interpolate(5, 10, alpha) ), rate_func=there_and_back, run_time=2 ) ) self.wait() self.wait(6) # Helpers def get_rotation_arrows(self, clockwise=True, width=1): result = VGroup(*[ Arrow( *points, buff=2 * SMALL_BUFF, path_arc=90 * DEGREES ).set_stroke(width=5) for points in adjacent_pairs(compass_directions(4, RIGHT)) ]) if clockwise: result.flip() result.set_width(width) return result class ShearCurl(IntroduceCurl): def construct(self): self.show_vector_field() self.begin_flow() self.wait(2) self.comment_on_relevant_region() def show_vector_field(self): vector_field = self.vector_field = VectorField( self.func, **self.vector_field_config ) vector_field.submobjects.key=sort( key=lambda a: a.get_length() ) self.play(LaggedStartMap(GrowArrow, vector_field)) def comment_on_relevant_region(self): circle = Circle(color=WHITE, radius=0.75) circle.next_to(ORIGIN, UP, LARGE_BUFF) self.play(ShowCreation(circle)) slow_words, fast_words = words = [ OldTexText("Slow flow below"), OldTexText("Fast flow above") ] for word, vect in zip(words, [DOWN, UP]): word.add_background_rectangle(buff=SMALL_BUFF) word.next_to(circle, vect) self.add_foreground_mobjects(word) self.play(Write(word)) self.wait() twig = Rectangle( height=0.8 * 2 * circle.radius, width=SMALL_BUFF, stroke_width=0, fill_color=GREY_BROWN, fill_opacity=1, ) twig.add(Dot(twig.get_center())) twig.move_to(circle) always_rotate( twig, rate=-90 * DEGREES, ) self.play(FadeIn(twig, UP)) self.add(twig_rotation) self.wait(16) # Helpers def func(self, point): return 0.5 * point[1] * RIGHT class FromKAWrapper(TeacherStudentsScene): def construct(self): screen = self.screen self.play( self.teacher.change, "raise_right_hand", self.change_students( "pondering", "confused", "hooray", ) ) self.look_at(screen) self.wait(2) self.play_student_changes("erm", "happy", "confused") self.wait(3) self.teacher_says( "Our focus is \\\\ the 2d version", bubble_config={"width": 4, "height": 3}, added_anims=[self.change_students( "happy", "hooray", "happy" )] ) self.wait() class ShowCurlAtVariousPoints(IntroduceCurl): CONFIG = { "func": four_swirls_function, "sample_points": [ 4 * RIGHT, 2 * UP, 4 * LEFT, 2 * DOWN, ORIGIN, 3 * RIGHT + 2 * UP, 3 * LEFT + 2 * UP, ], "vector_field_config": { "fill_opacity": 0.75 }, "stream_line_config": { "virtual_time": 5, "start_points_generator_config": { "delta_x": 0.25, "delta_y": 0.25, } } } def construct(self): self.add_plane() self.show_vector_field() self.begin_flow() self.show_curl_at_points() def add_plane(self): plane = NumberPlane() plane.add_coordinates() self.add(plane) self.plane = plane def show_curl_at_points(self): dot = Dot() circle = Circle(radius=0.25, color=WHITE) circle.move_to(dot) circle_update = Mobject.add_updater( circle, lambda m: m.move_to(dot) ) curl_tex = OldTex( "\\text{curl} \\, \\textbf{F}(x, y) = " ) curl_tex.add_background_rectangle(buff=0.025) curl_tex_update = Mobject.add_updater( curl_tex, lambda m: m.next_to(circle, UP, SMALL_BUFF) ) curl_func = two_d_curl(self.func) curl_value = DecimalNumber( 0, include_sign=True, include_background_rectangle=True, ) curl_value_update = ContinualChangingDecimal( curl_value, lambda a: curl_func(dot.get_center()), position_update_func=lambda m: m.next_to( curl_tex, RIGHT, buff=0 ), include_background_rectangle=True, include_sign=True, ) points = self.sample_points self.add(dot, circle_update) self.play( dot.move_to, points[0], VFadeIn(dot), VFadeIn(circle), ) curl_tex_update.update(0) curl_value_update.update(0) self.play(Write(curl_tex), FadeIn(curl_value)) self.add(curl_tex_update, curl_value_update) self.wait() for point in points[1:]: self.play(dot.move_to, point, run_time=3) self.wait(2) self.wait(2) class IllustrationUseVennDiagram(Scene): def construct(self): title = Title("Divergence \\& Curl") title.to_edge(UP, buff=MED_SMALL_BUFF) useful_for = OldTexText("Useful for") useful_for.next_to(title, DOWN) useful_for.set_color(BLUE) fluid_flow = OldTexText("Fluid \\\\ flow") fluid_flow.next_to(ORIGIN, UL) ff_circle = Circle(color=YELLOW) ff_circle.surround(fluid_flow, stretch=True) fluid_flow.match_color(ff_circle) big_circle = Circle( fill_color=BLUE, fill_opacity=0.2, stroke_color=BLUE, ) big_circle.stretch_to_fit_width(9) big_circle.stretch_to_fit_height(6) big_circle.next_to(useful_for, DOWN, SMALL_BUFF) illustrated_by = OldTexText("Illustrated by") illustrated_by.next_to( big_circle.point_from_proportion(3. / 8), UL ) illustrated_by.match_color(ff_circle) illustrated_by_arrow = Arrow( illustrated_by.get_bottom(), ff_circle.get_left(), path_arc=90 * DEGREES, color=YELLOW, ) illustrated_by_arrow.pointwise_become_partial( illustrated_by_arrow, 0, 0.95 ) examples = VGroup( OldTexText("Electricity"), OldTexText("Magnetism"), OldTexText("Phase flow"), OldTexText("Stokes' theorem"), ) points = [ 2 * RIGHT + 0.5 * UP, 2 * RIGHT + 0.5 * DOWN, 2 * DOWN, 2 * LEFT + DOWN, ] for example, point in zip(examples, points): example.move_to(point) self.play(Write(title), run_time=1) self.play( Write(illustrated_by), ShowCreation(illustrated_by_arrow), run_time=1, ) self.play( ShowCreation(ff_circle), FadeIn(fluid_flow), ) self.wait() self.play( Write(useful_for), DrawBorderThenFill(big_circle), Animation(fluid_flow), Animation(ff_circle), ) self.play(LaggedStartMap( FadeIn, examples, run_time=3, )) self.wait() class MaxwellsEquations(Scene): CONFIG = { "faded_opacity": 0.3, } def construct(self): self.add_equations() self.circle_gauss_law() self.circle_magnetic_divergence() self.circle_curl_equations() def add_equations(self): title = Title("Maxwell's equations") title.to_edge(UP, buff=MED_SMALL_BUFF) tex_to_color_map = { "\\textbf{E}": BLUE, "\\textbf{B}": YELLOW, "\\rho": WHITE, } equations = self.equations = VGroup(*[ OldTex( tex, tex_to_color_map=tex_to_color_map ) for tex in [ """ \\text{div} \\, \\textbf{E} = {\\rho \\over \\varepsilon_0} """, """\\text{div} \\, \\textbf{B} = 0""", """ \\text{curl} \\, \\textbf{E} = -{\\partial \\textbf{B} \\over \\partial t} """, """ \\text{curl} \\, \\textbf{B} = \\mu_0 \\left( \\textbf{J} + \\varepsilon_0 {\\partial \\textbf{E} \\over \\partial t} \\right) """, ] ]) equations.arrange( DOWN, aligned_edge=LEFT, buff=MED_LARGE_BUFF ) field_definitions = VGroup(*[ OldTex(text, tex_to_color_map=tex_to_color_map) for text in [ "\\text{Electric field: } \\textbf{E}", "\\text{Magnetic field: } \\textbf{B}", ] ]) field_definitions.arrange( RIGHT, buff=MED_LARGE_BUFF ) field_definitions.next_to(title, DOWN, MED_LARGE_BUFF) equations.next_to(field_definitions, DOWN, MED_LARGE_BUFF) field_definitions.shift(MED_SMALL_BUFF * UP) self.add(title) self.add(field_definitions) self.play(LaggedStartMap( FadeIn, equations, run_time=3, lag_range=0.4 )) self.wait() def circle_gauss_law(self): equation = self.equations[0] rect = SurroundingRectangle(equation) rect.set_color(RED) rho = equation.get_part_by_tex("\\rho") sub_rect = SurroundingRectangle(rho) sub_rect.match_color(rect) rho_label = OldTexText("Charge density") rho_label.next_to(sub_rect, RIGHT) rho_label.match_color(sub_rect) gauss_law = OldTexText("Gauss's law") gauss_law.next_to(rect, RIGHT) self.play( ShowCreation(rect), Write(gauss_law, run_time=1), self.equations[1:].set_fill, {"opacity": self.faded_opacity} ) self.wait(2) self.play( ReplacementTransform(rect, sub_rect), FadeOut(gauss_law), FadeIn(rho_label), rho.match_color, sub_rect, ) self.wait() self.play( self.equations.to_edge, LEFT, MaintainPositionRelativeTo(rho_label, equation), MaintainPositionRelativeTo(sub_rect, equation), VFadeOut(rho_label), VFadeOut(sub_rect), ) self.wait() def circle_magnetic_divergence(self): equations = self.equations rect = SurroundingRectangle(equations[1]) self.play( equations[0].set_fill, {"opacity": self.faded_opacity}, equations[1].set_fill, {"opacity": 1.0}, ) self.play(ShowCreation(rect)) self.wait(3) self.play(FadeOut(rect)) def circle_curl_equations(self): equations = self.equations rect = SurroundingRectangle(equations[2:]) randy = Randolph(height=2) randy.flip() randy.next_to(rect, RIGHT, aligned_edge=DOWN) randy.look_at(rect) self.play( equations[1].set_fill, {"opacity": self.faded_opacity}, equations[2:].set_fill, {"opacity": 1.0}, ) self.play(ShowCreation(rect)) self.play( randy.change, "confused", VFadeIn(randy), ) self.play(Blink(randy)) self.play(randy.look_at, 2 * RIGHT) self.wait(3) self.play( FadeOut(rect), randy.change, "pondering", randy.look_at, rect, ) self.wait() self.play(Blink(randy)) self.wait() class ThatWeKnowOf(Scene): def construct(self): words = OldTexText("*That we know of!") self.add(words) class IllustrateGaussLaw(DefineDivergence, MovingCameraScene): CONFIG = { "flow_time": 10, "stream_line_config": { "start_points_generator_config": { "delta_x": 1.0 / 16, "delta_y": 1.0 / 16, "x_min": -2, "x_max": 2, "y_min": -1.5, "y_max": 1.5, }, "color_lines_by_magnitude": True, "colors": [BLUE_E, BLUE_D, BLUE_C], "stroke_width": 3, }, "stream_line_animation_config": { "line_anim_class": ShowPassingFlashWithThinningStrokeWidth, "line_anim_config": { "n_segments": 5, } }, "final_frame_width": 4, } def construct(self): particles = self.get_particles() vector_field = self.get_vector_field() self.add_foreground_mobjects(vector_field) self.add_foreground_mobjects(particles) self.zoom_in() self.show_flow() def get_particles(self): particles = VGroup( get_proton(radius=0.1), get_electron(radius=0.1), ) particles.arrange(RIGHT, buff=2.25) particles.shift(0.25 * UP) for particle, sign in zip(particles, [+1, -1]): particle.charge = sign self.particles = particles return particles def zoom_in(self): self.play( self.camera_frame.set_width, self.final_frame_width, run_time=2 ) class IllustrateGaussMagnetic(IllustrateGaussLaw): CONFIG = { "final_frame_width": 7, "stream_line_config": { "start_points_generator_config": { "delta_x": 1.0 / 16, "delta_y": 1.0 / 16, "x_min": -3.5, "x_max": 3.5, "y_min": -2, "y_max": 2, }, "color_lines_by_magnitude": True, "colors": [BLUE_E, BLUE_D, BLUE_C], "stroke_width": 3, }, "stream_line_animation_config": { "start_up_time": 0, }, "flow_time": 10, } def construct(self): self.add_wires() self.show_vector_field() self.zoom_in() self.show_flow() def add_wires(self): top, bottom = [ Circle( radius=0.275, stroke_color=WHITE, fill_color=BLACK, fill_opacity=1 ) for x in range(2) ] top.add(OldTex("\\times").scale(0.5)) bottom.add(Dot().scale(0.5)) top.move_to(1 * UP) bottom.move_to(1 * DOWN) self.add_foreground_mobjects(top, bottom) def show_vector_field(self): vector_field = self.vector_field = VectorField( self.func, **self.vector_field_config ) vector_field.submobjects.sort( key=lambda a: -a1.get_length() ) self.play(LaggedStartMap(GrowArrow, vector_field)) self.add_foreground_mobjects( vector_field, *self.foreground_mobjects ) def func(self, point): x, y = point[:2] top_part = np.array([(y - 1.0), -x, 0]) bottom_part = np.array([-(y + 1.0), x, 0]) norm = get_norm return 1 * op.add( top_part / (norm(top_part) * norm(point - UP) + 0.1), bottom_part / (norm(bottom_part) * norm(point - DOWN) + 0.1), # top_part / (norm(top_part)**2 + 1), # bottom_part / (norm(bottom_part)**2 + 1), ) class IllustrateEMCurlEquations(ExternallyAnimatedScene): pass class RelevantInNonSpatialCircumstances(TeacherStudentsScene): def construct(self): self.teacher_says( """ $\\textbf{div}$ and $\\textbf{curl}$ are \\\\ even useful in some \\\\ non-spatial problems """, target_mode="hooray" ) self.play_student_changes( "sassy", "confused", "hesitant" ) self.wait(3) class ShowTwoPopulations(Scene): CONFIG = { "total_num_animals": 80, "start_num_foxes": 40, "start_num_rabbits": 20, "animal_height": 0.5, "final_wait_time": 30, "count_word_scale_val": 1, } def construct(self): self.introduce_animals() self.evolve_system() def introduce_animals(self): foxes = self.foxes = VGroup(*[ self.get_fox() for n in range(self.total_num_animals) ]) rabbits = self.rabbits = VGroup(*[ self.get_rabbit() for n in range(self.total_num_animals) ]) foxes[self.start_num_foxes:].set_fill(opacity=0) rabbits[self.start_num_rabbits:].set_fill(opacity=0) fox, rabbit = examples = VGroup(foxes[0], rabbits[0]) for mob in examples: mob.save_state() mob.set_height(3) examples.arrange(LEFT, buff=2) preditor, prey = words = VGroup( OldTexText("Predator"), OldTexText("Prey") ) for mob, word in zip(examples, words): word.scale(1.5) word.next_to(mob, UP) self.play( FadeInFromDown(mob), Write(word, run_time=1), ) self.play( LaggedStartMap( ApplyMethod, examples, lambda m: (m.restore,) ), LaggedStartMap(FadeOut, words), *[ LaggedStartMap( FadeIn, group[1:], run_time=4, lag_ratio=0.1, rate_func=lambda t: np.clip(smooth(2 * t), 0, 1) ) for group in [foxes, rabbits] ] ) def evolve_system(self): foxes = self.foxes rabbits = self.rabbits phase_point = VectorizedPoint( self.start_num_rabbits * RIGHT + self.start_num_foxes * UP ) self.add(move_along_vector_field( phase_point, preditor_prey_vector_field, )) def get_num_rabbits(): return phase_point.get_center()[0] def get_num_foxes(): return phase_point.get_center()[1] def get_updater(pop_size_getter): def update(animals): target_num = pop_size_getter() for n, animal in enumerate(animals): animal.set_fill( opacity=np.clip(target_num - n, 0, 1) ) target_int = int(np.ceil(target_num)) tail = animals.submobjects[target_int:] random.shuffle(tail) animals.submobjects[target_int:] = tail return update self.add(Mobject.add_updater( foxes, get_updater(get_num_foxes) )) self.add(Mobject.add_updater( rabbits, get_updater(get_num_rabbits) )) # Add counts for foxes and rabbits labels = self.get_pop_labels() num_foxes = Integer(10) num_foxes.scale(self.count_word_scale_val) num_foxes.next_to(labels[0], RIGHT) num_foxes.align_to(labels[0][0][1], DOWN) num_rabbits = Integer(10) num_rabbits.scale(self.count_word_scale_val) num_rabbits.next_to(labels[1], RIGHT) num_rabbits.align_to(labels[1][0][1], DOWN) num_foxes.add_updater(lambda d: d.set_value(get_num_foxes())) num_rabbits.add_updater(lambda d: d.set_value(get_num_rabbits())) self.add(num_foxes, num_rabbits) for count in num_foxes, num_rabbits: self.add(Mobject.add_updater( count, self.update_count_color, )) self.play( FadeIn(labels), *[ UpdateFromAlphaFunc(count, lambda m, a: m.set_fill(opacity=a)) for count in (num_foxes, num_rabbits) ] ) self.wait(self.final_wait_time) # Helpers def get_animal(self, name, color): result = SVGMobject( file_name=name, height=self.animal_height, fill_color=color, ) # for submob in result.family_members_with_points(): # if submob.is_subpath: # submob.is_subpath = False # submob.set_fill( # interpolate_color(color, BLACK, 0.8), # opacity=1 # ) x_shift, y_shift = [ (2 * random.random() - 1) * max_val for max_val in [ FRAME_WIDTH / 2 - 2, FRAME_HEIGHT / 2 - 2 ] ] result.shift(x_shift * RIGHT + y_shift * UP) return result def get_fox(self): return self.get_animal("fox", FOX_COLOR) def get_rabbit(self): # return self.get_animal("rabbit", WHITE) return self.get_animal("bunny", RABBIT_COLOR) def get_pop_labels(self): labels = VGroup( OldTexText("\\# Foxes: "), OldTexText("\\# Rabbits: "), ) for label in labels: label.scale(self.count_word_scale_val) labels.arrange(RIGHT, buff=2) labels.to_edge(UP) return labels def update_count_color(self, count): count.set_fill(interpolate_color( BLUE, RED, (count.number - 20) / 30.0 )) return count class PhaseSpaceOfPopulationModel(ShowTwoPopulations, PiCreatureScene, MovingCameraScene): CONFIG = { "origin": 5 * LEFT + 2.5 * DOWN, "vector_field_config": { "max_magnitude": 50, }, "pi_creatures_start_on_screen": False, "default_pi_creature_kwargs": { "height": 1.8 }, "flow_time": 10, } def setup(self): MovingCameraScene.setup(self) PiCreatureScene.setup(self) def construct(self): self.add_axes() self.add_example_point() self.write_differential_equations() self.add_vectors() self.show_phase_flow() def add_axes(self): axes = self.axes = Axes( x_min=0, x_max=55, x_axis_config={"unit_size": 0.15}, y_min=0, y_max=55, y_axis_config={"unit_size": 0.09}, axis_config={ "tick_frequency": 10, }, ) axes.shift(self.origin) for axis in axes.x_axis, axes.y_axis: axis.add_numbers(*list(range(10, 60, 10))) axes_labels = self.axes_labels = VGroup(*[ VGroup( method().set_height(0.75), OldTexText("Population"), ).arrange(RIGHT, buff=MED_SMALL_BUFF) for method in (self.get_rabbit, self.get_fox) ]) for axis, label, vect in zip(axes, axes_labels, [RIGHT, UP]): label.next_to( axis, vect, submobject_to_align=label[0] ) self.add(axes, axes_labels) def add_example_point(self): axes = self.axes origin = self.origin x = self.start_num_rabbits y = self.start_num_foxes point = axes.coords_to_point(x, y) x_point = axes.coords_to_point(x, 0) y_point = axes.coords_to_point(0, y) v_line = DashedLine(x_point, point) h_line = DashedLine(y_point, point) v_line.set_color(FOX_COLOR) h_line.set_color(GREY_B) dot = Dot(point) coord_pair = OldTex( "(10, 10)", isolate=["10"] ) pop_sizes = VGroup(Integer(10), Integer(10)) pop_sizes[0].set_color(GREY_B) pop_sizes[1].set_color(FOX_COLOR) tens = coord_pair.get_parts_by_tex("10") tens.fade(1) def get_pop_size_update(i): return ContinualChangingDecimal( pop_sizes[i], lambda a: int(np.round( axes.point_to_coords(dot.get_center())[i] )), position_update_func=lambda m: m.move_to(tens[i]) ) coord_pair.add_background_rectangle() coord_pair_update = Mobject.add_updater( coord_pair, lambda m: m.next_to(dot, UR, SMALL_BUFF) ) pop_sizes_updates = [get_pop_size_update(i) for i in (0, 1)] phase_space = OldTexText("``Phase space''") phase_space.set_color(YELLOW) phase_space.scale(1.5) phase_space.to_edge(UP) phase_space.shift(2 * RIGHT) self.play(ShowCreation(v_line)) self.play(ShowCreation(h_line)) dot.save_state() dot.move_to(origin) self.add(coord_pair_update) self.add(*pop_sizes_updates) self.play( dot.restore, VFadeIn(coord_pair), UpdateFromAlphaFunc(pop_sizes, lambda m, a: m.set_fill(opacity=a)), ) self.wait() self.play(Write(phase_space)) self.wait(2) self.play(FadeOut(VGroup(h_line, v_line, phase_space))) self.play(Rotating( dot, about_point=axes.coords_to_point(30, 30), rate_func=smooth, )) self.dot = dot self.coord_pair = coord_pair self.coord_pair_update = coord_pair_update self.pop_sizes = pop_sizes self.pop_sizes_updates = pop_sizes_updates def write_differential_equations(self): equations = self.get_equations() equations.shift(2 * DOWN) rect = SurroundingRectangle(equations, color=YELLOW) rect.set_fill(BLACK, 0.8) title = OldTexText("Differential equations") title.next_to(rect, UP) title.set_color(rect.get_stroke_color()) self.differential_equation_group = VGroup( rect, equations, title ) self.differential_equation_group.to_corner(UR) randy = self.pi_creature randy.next_to(rect, DL) self.play( Write(title, run_time=1), ShowCreation(rect) ) self.play( LaggedStartMap(FadeIn, equations), randy.change, "confused", equations, VFadeIn(randy), ) self.wait(3) def add_vectors(self): origin = self.axes.coords_to_point(0, 0) dot = self.dot randy = self.pi_creature def rescaled_field(point): x, y = self.axes.point_to_coords(point) result = preditor_prey_vector_field(np.array([x, y, 0])) return self.axes.coords_to_point(*result[:2]) - origin self.vector_field_config.update({ "x_min": origin[0] + 0.5, "x_max": self.axes.get_right()[0] + 1, "y_min": origin[1] + 0.5, "y_max": self.axes.get_top()[1], }) vector_field = VectorField( rescaled_field, **self.vector_field_config ) def get_dot_vector(): vector = vector_field.get_vector(dot.get_center()) vector.scale(1, about_point=vector.get_start()) return vector dot_vector = get_dot_vector() self.play( LaggedStartMap(GrowArrow, vector_field), randy.change, "thinking", dot, Animation(self.differential_equation_group) ) self.wait(3) self.play( Animation(dot), vector_field.set_fill, {"opacity": 0.2}, Animation(self.differential_equation_group), GrowArrow(dot_vector), randy.change, "pondering", ) self.wait() self.play( dot.move_to, dot_vector.get_end(), dot.align_to, dot, RIGHT, run_time=3, ) self.wait(2) self.play( dot.move_to, dot_vector.get_end(), run_time=3, ) self.wait(2) for x in range(6): new_dot_vector = get_dot_vector() fade_anims = [ FadeOut(dot_vector), FadeIn(new_dot_vector), Animation(dot), ] if x == 4: fade_anims += [ vector_field.set_fill, {"opacity": 0.5}, FadeOut(randy), FadeOut(self.differential_equation_group), ] self.play(*fade_anims) dot_vector = new_dot_vector self.play(dot.move_to, dot_vector.get_end()) dot_movement = move_along_vector_field( dot, lambda p: 0.3 * vector_field.func(p) ) self.add(dot_movement) self.play(FadeOut(dot_vector)) self.wait(10) self.play( vector_field.set_fill, {"opacity": 1.0}, VFadeOut(dot), VFadeOut(self.coord_pair), UpdateFromAlphaFunc(self.pop_sizes, lambda m, a: m.set_fill(opacity=1 - a)), ) self.remove( dot_movement, self.coord_pair_update, *self.pop_sizes_updates ) self.wait() self.vector_field = vector_field def show_phase_flow(self): vector_field = self.vector_field stream_lines = StreamLines( vector_field.func, start_points_generator_config={ "x_min": vector_field.x_min, "x_max": vector_field.x_max, "y_min": vector_field.y_min, "y_max": vector_field.y_max, "delta_x": 0.25, "delta_y": 0.25, }, min_magnitude=vector_field.min_magnitude, max_magnitude=vector_field.max_magnitude, virtual_time=4, ) stream_line_animation = AnimatedStreamLines( stream_lines, ) self.add(stream_line_animation) self.add_foreground_mobjects(vector_field) self.wait(self.flow_time) self.play( self.camera_frame.scale, 1.5, {"about_point": self.origin}, run_time=self.flow_time, ) self.wait(self.flow_time) # def get_equations(self): variables = ["X", "YY"] equations = OldTex( """ {dX \\over dt} = X \\cdot (\\alpha - \\beta YY \\,) \\\\ \\quad \\\\ {dYY \\over dt} = YY \\cdot (\\delta X - \\gamma) """, isolate=variables ) animals = [self.get_rabbit(), self.get_fox().flip()] for char, animal in zip(variables, animals): for part in equations.get_parts_by_tex(char): animal_copy = animal.copy() animal_copy.set_height(0.5) animal_copy.move_to(part, DL) part.become(animal_copy) return equations class PhaseFlowWords(Scene): def construct(self): words = OldTexText("``Phase flow''") words.scale(2) self.play(Write(words)) self.wait() class PhaseFlowQuestions(Scene): def construct(self): questions = VGroup( OldTexText( "Which points does the flow \\\\" + "converge to? Diverge away from?", ), OldTexText("Where are there cycles?"), ) questions.arrange(DOWN, buff=LARGE_BUFF) questions.to_corner(UR) for question in questions: self.play(FadeInFromDown(question)) self.wait(2) class ToolsBeyondDivAndCurlForODEs(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs": { "color": GREY_BROWN, }, "default_pi_creature_start_corner": DOWN, } def construct(self): morty = self.pi_creature div_curl = OldTexText("div \\\\", "curl") div_curl.set_color_by_tex("div", BLUE) div_curl.set_color_by_tex("curl", YELLOW) div_curl.next_to(morty.get_corner(UL), UP, MED_LARGE_BUFF) jacobian = OldTexText("Analyze the \\\\ Jacobian") jacobian.set_color(GREEN) jacobian.next_to(morty.get_corner(UR), UP, MED_LARGE_BUFF) flow_intuitions = OldTexText("Flow-based intuitions") flow_intuitions.next_to( VGroup(div_curl, jacobian), UP, buff=1.5 ) arrow1 = Arrow(div_curl.get_top(), flow_intuitions.get_bottom()) arrow2 = Arrow(flow_intuitions.get_bottom(), jacobian.get_top()) self.play( FadeInFromDown(div_curl), morty.change, "raise_left_hand", ) self.wait() self.play( FadeInFromDown(jacobian), morty.change, "raise_right_hand" ) self.wait() self.play( ReplacementTransform( flow_intuitions.copy().fade(1).move_to(div_curl), flow_intuitions, ), GrowArrow(arrow1), morty.change, "pondering" ) self.wait(0.5) self.play(GrowArrow(arrow2)) self.wait() class AskAboutComputation(TeacherStudentsScene): def construct(self): self.student_says( "Sure, but how do you \\\\" + "\\emph{compute} $\\textbf{div}$ and $\\textbf{curl}$?", target_mode="sassy", ) self.play_student_changes( "confused", "sassy", "angry", added_anims=[self.teacher.change, "guilty"] ) self.wait() self.teacher_says( "Are you familiar \\\\" + "with my work \\\\" + "at Khan Academy?", target_mode="speaking", bubble_config={"width": 4, "height": 3} ) self.play_student_changes( * 3 * ["pondering"], look_at=self.screen ) self.wait(5) class QuickWordsOnNotation(Scene): def construct(self): words = OldTexText("Quick words on notation:") words.scale(1.5) self.play(FadeInFromDown(words)) self.wait() class NablaNotation(PiCreatureScene, MovingCameraScene): CONFIG = { "default_pi_creature_kwargs": { "color": GREY_BROWN, }, "default_pi_creature_start_corner": DL, } def setup(self): MovingCameraScene.setup(self) PiCreatureScene.setup(self) def construct(self): self.show_notation() self.show_expansion() self.zoom_out() def show_notation(self): morty = self.pi_creature tex_to_color_map = { "\\text{div}": BLUE, "\\nabla \\cdot": BLUE, "\\text{curl}": YELLOW, "\\nabla \\times": YELLOW, } div_equation = OldTex( "\\text{div} \\, \\textbf{F} = \\nabla \\cdot \\textbf{F}", tex_to_color_map=tex_to_color_map ) div_nabla = div_equation.get_part_by_tex("\\nabla") curl_equation = OldTex( "\\text{curl} \\, \\textbf{F} = \\nabla \\times \\textbf{F}", tex_to_color_map=tex_to_color_map ) curl_nabla = curl_equation.get_part_by_tex("\\nabla") equations = VGroup(div_equation, curl_equation) equations.arrange(DOWN, buff=LARGE_BUFF) equations.next_to(morty, UP, 2) equations.to_edge(LEFT) self.play( FadeInFromDown(div_equation), morty.change, "raise_right_hand" ) self.wait() self.play(WiggleOutThenIn(div_nabla, scale_value=1.5)) self.wait() self.play( FadeInFromDown(curl_equation), morty.change, "raise_left_hand" ) self.wait() self.play(WiggleOutThenIn(curl_nabla, scale_value=1.5)) self.wait() self.equations = equations def show_expansion(self): equations = self.equations morty = self.pi_creature nabla_vector = Matrix([ ["\\partial \\over \\partial x"], ["\\partial \\over \\partial y"], ], v_buff=1.5) F_vector = Matrix([ ["\\textbf{F}_x"], ["\\textbf{F}_y"], ], v_buff=1.2) nabla_vector.match_height(F_vector) div_lhs, curl_lhs = lhs_groups = VGroup(*[ VGroup( nabla_vector.deepcopy(), OldTex(tex).scale(1.5), F_vector.copy(), OldTex("=") ) for tex in ("\\cdot", "\\times") ]) colors = [BLUE, YELLOW] for lhs, color in zip(lhs_groups, colors): lhs.arrange(RIGHT, buff=MED_SMALL_BUFF) VGroup(lhs[0].brackets, lhs[1]).set_color(color) div_lhs.to_edge(UP) curl_lhs.next_to(div_lhs, DOWN, buff=LARGE_BUFF) div_rhs = OldTex( "{\\partial F_x \\over \\partial x} + " + "{\\partial F_y \\over \\partial y}" ) curl_rhs = OldTex( "{\\partial F_y \\over \\partial x} - " + "{\\partial F_x \\over \\partial y}" ) rhs_groups = VGroup(div_rhs, curl_rhs) for rhs, lhs in zip(rhs_groups, lhs_groups): rhs.next_to(lhs, RIGHT) for rhs, tex, color in zip(rhs_groups, ["div", "curl"], colors): rhs.rect = SurroundingRectangle(rhs, color=color) rhs.label = OldTex( "\\text{%s}" % tex, "\\, \\textbf{F}" ) rhs.label.set_color(color) rhs.label.next_to(rhs.rect, UP) for i in 0, 1: self.play( ReplacementTransform( equations[i][2].copy(), lhs_groups[i][0].brackets ), ReplacementTransform( equations[i][3].copy(), lhs_groups[i][2], ), morty.change, "pondering", *[ GrowFromPoint(mob, equations[i].get_right()) for mob in [ lhs_groups[i][0].get_entries(), lhs_groups[i][1], lhs_groups[i][3] ] ], run_time=2 ) self.wait() self.wait() for rhs in rhs_groups: self.play( Write(rhs), morty.change, 'confused' ) self.play( ShowCreation(rhs.rect), FadeInFromDown(rhs.label), ) self.wait() self.play(morty.change, "erm") self.wait(3) def zoom_out(self): screen_rect = self.camera_frame.copy() screen_rect.set_stroke(WHITE, 3) screen_rect.scale(1.01) words = OldTexText("Something deeper at play...") words.scale(1.3) words.next_to(screen_rect, UP) self.add(screen_rect) self.play( self.camera_frame.set_height, FRAME_HEIGHT + 3, Write(words, rate_func=squish_rate_func(smooth, 0.3, 1)), run_time=2, ) self.wait() class DivCurlDotCross(Scene): def construct(self): rects = VGroup(*[ ScreenRectangle(height=2.5) for n in range(4) ]) rects.arrange_in_grid(n_rows=2, buff=LARGE_BUFF) rects[2:].shift(MED_LARGE_BUFF * DOWN) titles = VGroup(*list(map(TexText, [ "Divergence", "Curl", "Dot product", "Cross product" ]))) for title, rect in zip(titles, rects): title.next_to(rect, UP) self.add(rects, titles) class ShowDotProduct(MovingCameraScene): CONFIG = { "prod_tex": "\\cdot" } def construct(self): plane = NumberPlane() v1 = Vector(RIGHT, color=BLUE) v2 = Vector(UP, color=YELLOW) dot_product = OldTex( "\\vec{\\textbf{v}}", self.prod_tex, "\\vec{\\textbf{w}}", "=" ) dot_product.set_color_by_tex_to_color_map({ "textbf{v}": BLUE, "textbf{w}": YELLOW, }) dot_product.add_background_rectangle() dot_product.next_to(2.25 * UP, RIGHT) dot_product_value = DecimalNumber( 1.0, include_background_rectangle=True, ) dot_product_value.next_to(dot_product) dot_product_value_update = ContinualChangingDecimal( dot_product_value, lambda a: self.get_product(v1, v2), include_background_rectangle=True, ) self.camera_frame.set_height(4) self.camera_frame.move_to(DL, DL) self.add(plane) self.add(dot_product, dot_product_value_update) self.add_additional_continual_animations(v1, v2) self.add_foreground_mobjects(v1, v2) for n in range(5): self.play( Rotate(v1, 45 * DEGREES, about_point=ORIGIN), Rotate(v2, -45 * DEGREES, about_point=ORIGIN), run_time=3, rate_func=there_and_back ) self.wait(0.5) def get_product(self, v1, v2): return np.dot(v1.get_vector(), v2.get_vector()) def add_additional_continual_animations(self, v1, v2): pass class ShowCrossProduct(ShowDotProduct): CONFIG = { "prod_tex": "\\times" } def get_product(self, v1, v2): return get_norm( np.cross(v1.get_vector(), v2.get_vector()) ) def add_additional_continual_animations(self, v1, v2): square = Square( stroke_color=YELLOW, stroke_width=3, fill_color=YELLOW, fill_opacity=0.2, ) self.add(Mobject.add_updater( square, lambda s: s.set_points_as_corners([ ORIGIN, v1.get_end(), v1.get_end() + v2.get_end(), v2.get_end(), ]) )) class DivergenceTinyNudgesView(MovingCameraScene): CONFIG = { "scale_factor": 0.25, "point": ORIGIN, } def construct(self): self.add_vector_field() self.zoom_in() self.take_tiny_step() self.show_dot_product() self.show_circle_of_values() self.switch_to_curl_words() self.rotate_difference_vectors() def add_vector_field(self): plane = self.plane = NumberPlane() def func(p): x, y = p[:2] result = np.array([ np.sin(x + 0.1), np.cos(2 * y), 0 ]) result /= (get_norm(result)**0.5 + 1) return result vector_field = self.vector_field = VectorField( func, length_func=lambda n: 0.5 * sigmoid(n), # max_magnitude=1.0, ) self.add(plane) self.add(vector_field) def zoom_in(self): point = self.point vector_field = self.vector_field sf = self.scale_factor vector_field.vector_config.update({ "rectangular_stem_width": 0.02, "tip_length": 0.1, }) vector_field.length_func = lambda n: n vector = vector_field.get_vector(point) input_dot = Dot(point).scale(sf) input_words = OldTexText("$(x_0, y_0)$").scale(sf) input_words.next_to(input_dot, DL, SMALL_BUFF * sf) output_words = OldTexText("Output").scale(sf) output_words.add_background_rectangle() output_words.next_to(vector.get_top(), UP, sf * SMALL_BUFF) output_words.match_color(vector) self.play( self.camera_frame.scale, sf, self.camera_frame.move_to, point, FadeOut(vector_field), FadeIn(vector), run_time=2 ) self.add_foreground_mobjects(input_dot) self.play( FadeIn(input_dot, SMALL_BUFF * DL), Write(input_words), ) self.play( Indicate(vector), Write(output_words), ) self.wait() self.set_variables_as_attrs( point, vector, input_dot, input_words, output_words, ) def take_tiny_step(self): sf = self.scale_factor vector_field = self.vector_field point = self.point vector = self.vector output_words = self.output_words input_dot = self.input_dot nudge = 0.5 * RIGHT nudged_point = point + nudge new_vector = vector_field.get_vector(nudged_point) new_vector.set_color(YELLOW) new_dot = Dot(nudged_point).scale(sf) step_vector = Arrow( point, nudged_point, buff=0, color=TEAL, **vector_field.vector_config ) step_vector.set_stroke(BLACK, 0.5) new_output_words = OldTexText("New output").scale(sf) new_output_words.add_background_rectangle() new_output_words.next_to(new_vector.get_end(), UP, sf * SMALL_BUFF) new_output_words.match_color(new_vector) step_words = OldTexText("Step").scale(sf) step_words.next_to(step_vector, UP, buff=0) step_words.set_color(step_vector.get_fill_color()) step_words.add_background_rectangle() small_step_words = OldTexText("(think tiny step)").scale(sf) small_step_words.next_to( step_words, RIGHT, buff=sf * MED_SMALL_BUFF, ) small_step_words.add_background_rectangle() small_step_words.match_style(step_words) shifted_vector = vector.copy().shift(nudge) diff_vector = Arrow( shifted_vector.get_end(), new_vector.get_end(), buff=0, color=RED, **vector_field.vector_config ) diff_words = OldTexText("Difference").scale(sf) diff_words.add_background_rectangle() diff_words.next_to(diff_vector.get_start(), UR, buff=2 * sf * SMALL_BUFF) diff_words.match_color(diff_vector) diff_words.rotate( diff_vector.get_angle(), about_point=diff_vector.get_start() ) self.play( GrowArrow(step_vector), Write(step_words), ReplacementTransform(input_dot.copy(), new_dot) ) self.add_foreground_mobjects(new_dot) self.play(FadeIn(small_step_words)) self.play(FadeOut(small_step_words)) self.play( ReplacementTransform(vector.copy(), new_vector), ReplacementTransform(output_words.copy(), new_output_words), ) self.wait() self.play(ReplacementTransform( vector.copy(), shifted_vector, path_arc=-TAU / 4 )) self.wait() self.play( FadeOut(output_words), FadeOut(new_output_words), GrowArrow(diff_vector), Write(diff_words) ) self.wait() self.play( vector.scale, 0, {"about_point": vector.get_start()}, shifted_vector.scale, 0, {"about_point": shifted_vector.get_start()}, ReplacementTransform( new_vector, diff_vector.copy().shift(-vector.get_vector()), remover=True ), diff_vector.shift, -vector.get_vector(), MaintainPositionRelativeTo(diff_words, diff_vector), run_time=2 ) self.wait() self.set_variables_as_attrs( step_vector, step_words, diff_vector, diff_words, ) def show_dot_product(self): sf = self.scale_factor point = self.point step_vector = self.step_vector step_words = self.step_words diff_vector = self.diff_vector diff_words = self.diff_words vects = VGroup(step_vector, diff_vector) moving_step_vector = step_vector.copy() moving_diff_vector = diff_vector.copy() def update_moving_diff_vector(dv): step = moving_step_vector.get_vector() o1 = self.vector_field.get_vector(point).get_vector() o2 = self.vector_field.get_vector(point + step).get_vector() diff = o2 - o1 dv.put_start_and_end_on( moving_step_vector.get_end(), moving_step_vector.get_end() + diff, ) self.moving_diff_vector_update = Mobject.add_updater( moving_diff_vector, update_moving_diff_vector ) self.add(self.moving_diff_vector_update) div_text = self.get_operator_text("div") step_words_copy = step_words.copy() diff_words_copy = diff_words.copy() copies = VGroup(step_words_copy, diff_words_copy) substrings = ["Step", "Difference"] dot_product = OldTexText( "(Step) $\\cdot$ (Difference)", isolate=substrings, arg_separator="", ).scale(sf) group = VGroup(div_text, dot_product) group.arrange(RIGHT, buff=sf * MED_SMALL_BUFF) group.next_to( self.camera_frame.get_top(), DOWN, buff=sf * MED_SMALL_BUFF ) for substring, mob, vect in zip(substrings, copies, vects): part = dot_product.get_part_by_tex(substring) mob.generate_target() mob.target.rotate(-vect.get_angle()) mob.target.replace(part) # part.set_fill(opacity=0) part.match_color(mob) dot_product.add_background_rectangle() brace = Brace( dot_product.copy().scale(1 / sf, about_point=ORIGIN), DOWN, buff=SMALL_BUFF ).scale(sf, about_point=ORIGIN) dp_kwargs = { "include_sign": True, } dot_product_value = DecimalNumber(1.0, **dp_kwargs) dot_product_value.scale(sf) dot_product_value.next_to(brace, DOWN, sf * SMALL_BUFF) dot_product_value_update = ContinualChangingDecimal( dot_product_value, lambda a: np.dot( moving_step_vector.get_vector(), moving_diff_vector.get_vector(), ), **dp_kwargs ) self.play( Write(dot_product), LaggedStartMap(MoveToTarget, copies) ) self.remove(copies) self.play(FadeIn(div_text)) self.play(ShowPassingFlashAround( div_text[1:3], surrounding_rectangle_config={"buff": sf * SMALL_BUFF} )) self.add(BackgroundRectangle(dot_product_value)) self.play( GrowFromCenter(brace), Write(dot_product_value), ) self.add(dot_product_value_update) self.wait() self.set_variables_as_attrs( div_text, dot_product, moving_step_vector, moving_diff_vector, dot_product_value, dot_product_value_update, brace, ) def show_circle_of_values(self): point = self.point moving_step_vector = self.moving_step_vector moving_diff_vector = self.moving_diff_vector all_diff_vectors = VGroup() all_step_vectors = VGroup() # Loop around n_samples = 12 angle = TAU / n_samples self.add_foreground_mobjects(self.step_words) for n in range(n_samples): self.play( Rotating( moving_step_vector, radians=angle, about_point=point, run_time=15.0 / n_samples, rate_func=linear, ) ) step_vector_copy = moving_step_vector.copy() diff_vector_copy = moving_diff_vector.copy() diff_vector_copy.set_stroke(BLACK, 0.5) self.add(step_vector_copy, diff_vector_copy) all_step_vectors.add(step_vector_copy) all_diff_vectors.add(diff_vector_copy) self.remove( self.step_vector, self.diff_vector, self.moving_step_vector, self.moving_diff_vector, self.moving_diff_vector_update, self.dot_product_value_update ) self.remove_foreground_mobjects(self.step_words) self.play( FadeOut(self.brace), FadeOut(self.dot_product_value), FadeOut(self.step_words), FadeOut(self.diff_words), ) self.wait() for s in 0.6, -0.6: for step, diff in zip(all_step_vectors, all_diff_vectors): diff.generate_target() diff.target.put_start_and_end_on( step.get_end(), step.get_end() + s * step.get_vector() ) self.play( all_step_vectors.set_fill, {"opacity": 0.5}, LaggedStartMap( MoveToTarget, all_diff_vectors, run_time=3 ), ) self.wait() self.show_stream_lines(lambda p: s * (p - point)) self.wait() self.set_variables_as_attrs( all_step_vectors, all_diff_vectors, ) def switch_to_curl_words(self): sf = self.scale_factor div_text = self.div_text dot_product = self.dot_product curl_text = self.get_operator_text("curl") cross_product = OldTexText( "(Step) $\\times$ (Difference)", tex_to_color_map={ "Step": TEAL, "Difference": RED }, arg_separator="", ).scale(sf) cross_product.add_background_rectangle(opacity=1) group = VGroup(curl_text, cross_product) group.arrange(RIGHT, buff=sf * MED_SMALL_BUFF) group.next_to(self.camera_frame.get_top(), sf * DOWN) self.play( dot_product.shift, sf * DOWN, dot_product.fade, 1, remover=True ) self.play(FadeIn(cross_product, sf * DOWN)) self.play( div_text.shift, sf * DOWN, div_text.fade, 1, remover=True ) self.play(FadeIn(curl_text, sf * DOWN)) self.wait() def rotate_difference_vectors(self): point = self.point all_step_vectors = self.all_step_vectors all_diff_vectors = self.all_diff_vectors for s in 0.6, -0.6: for step, diff in zip(all_step_vectors, all_diff_vectors): diff.generate_target() diff.target.put_start_and_end_on( step.get_end(), step.get_end() + s * rotate_vector( step.get_vector(), 90 * DEGREES ) ) self.play( LaggedStartMap( MoveToTarget, all_diff_vectors, run_time=2 ), ) self.wait() self.show_stream_lines( lambda p: s * rotate_vector((p - point), 90 * DEGREES) ) self.wait() self.set_variables_as_attrs( all_step_vectors, all_diff_vectors, ) # Helpers def get_operator_text(self, operator): text = OldTexText( operator + "\\,", "$\\textbf{F}(x_0, y_0)\\,$", "corresponds to average of", arg_separator="" ).scale(self.scale_factor) text.set_color_by_tex(operator, YELLOW) text.add_background_rectangle() return text def show_stream_lines(self, func): point = self.point stream_lines = StreamLines( func, start_points_generator_config={ "x_min": point[0] - 2, "x_max": point[0] + 2, "y_min": point[1] - 1, "y_max": point[1] + 1, "delta_x": 0.025, "delta_y": 0.025, }, virtual_time=1, ) random.shuffle(stream_lines.submobjects) self.play(LaggedStartMap( ShowPassingFlash, stream_lines, run_time=4, )) class ZToHalfFlowNearWall(ComplexTransformationScene, MovingCameraScene): CONFIG = { "num_anchors_to_add_per_line": 200, "plane_config": {"y_radius": 8} } def setup(self): MovingCameraScene.setup(self) ComplexTransformationScene.setup(self) def construct(self): # self.camera.frame.shift(2 * UP) self.camera.frame.scale(0.5, about_point=ORIGIN) plane = NumberPlane( x_radius=15, y_radius=25, y_unit_size=0.5, secondary_line_ratio=0, ) plane.next_to(ORIGIN, UP, buff=0.001) horizontal_lines = VGroup(*[l for l in list(planes) + [plane.axes[0]] if np.abs(l.get_center()[0]) < 0.1]) plane.set_stroke(MAROON_B, width=2) horizontal_lines.set_stroke(BLUE, width=2) self.prepare_for_transformation(plane) self.add_transformable_mobjects(plane) self.background.set_stroke(width=2) for label in self.background.coordinate_labels: label.set_stroke(width=0) label.scale(0.75, about_edge=UR) words = OldTexText("(Idealized) Flow \\\\", "near a wall") words.scale(0.75) words.add_background_rectangle_to_submobjects() words.next_to(0.75 * UP, LEFT, MED_LARGE_BUFF) equation = OldTex("z \\rightarrow z^{1/2}") equation.scale(0.75) equation.add_background_rectangle() equation.next_to(words, UP) self.apply_complex_function( lambda x: x**(1. / 2), added_anims=[Write(equation)] ) self.play(Write(words, run_time=1)) def func(point): z = R3_to_complex(point) d_half = derivative(lambda z: z**2) return complex_to_R3(d_half(z).conjugate()) stream_lines = StreamLines( func, start_points_generator_config={ "x_min": 0.01, "y_min": 0.01, "delta_x": 0.125, "delta_y": 0.125, }, virtual_time=3, stroke_width=2, max_magnitude=10, ) stream_line_animation = AnimatedStreamLines(stream_lines) self.add(stream_line_animation) self.wait(7) class IncmpressibleAndIrrotational(Scene): def construct(self): div_0 = OldTexText("div$\\textbf{F} = 0$") curl_0 = OldTexText("curl$\\textbf{F}$ = 0") incompressible = OldTexText("Incompressible") irrotational = OldTexText("Irrotational") for text in [div_0, curl_0, incompressible, irrotational]: self.stylize_word_for_background(text) div_0.to_edge(UP) curl_0.next_to(div_0, DOWN, MED_LARGE_BUFF) for op, word in (div_0, incompressible), (curl_0, irrotational): op.generate_target() group = VGroup(op.target, word) group.arrange(RIGHT, buff=MED_LARGE_BUFF) group.move_to(op) self.play(FadeInFromDown(div_0)) self.play(FadeInFromDown(curl_0)) self.wait() self.play( MoveToTarget(div_0), FadeInFromDown(incompressible), ) self.wait() self.play( MoveToTarget(curl_0), FadeInFromDown(irrotational), ) self.wait() rect = SurroundingRectangle(VGroup(curl_0, irrotational)) question = OldTexText("Does this actually happen?") question.next_to(rect, DOWN) question.match_color(rect) self.stylize_word_for_background(question) self.play(ShowCreation(rect)) self.play(Write(question)) self.wait() def stylize_word_for_background(self, word): word.add_background_rectangle() class NoChargesOverlay(Scene): def construct(self): rect = FullScreenFadeRectangle() rect.set_fill(BLUE_D, 0.75) circle = Circle(radius=1.5, num_anchors=5000) circle.rotate(135 * DEGREES) rect.add_subpath(circle.get_points()) words = OldTexText("No charges outside wire") words.scale(1.5) words.to_edge(UP) self.add(rect, words) # End message class BroughtToYouBy(PiCreatureScene): CONFIG = { "pi_creatures_start_on_screen": False, } def construct(self): self.brought_to_you_by() self.just_you_and_me() def brought_to_you_by(self): so_words = OldTexText("So", "...", arg_separator="") so_words.scale(2) btyb = OldTexText("Brought to you", "by") btyb.scale(1.5) btyb_line = Line(LEFT, RIGHT) btyb_line.next_to(btyb, RIGHT, SMALL_BUFF) btyb_line.align_to(btyb[0], DOWN) btyb_group = VGroup(btyb, btyb_line) btyb_group.center() you_word = OldTexText("\\emph{you}") you_word.set_color(YELLOW) you_word.scale(1.75) you_word.move_to(btyb_line) you_word.align_to(btyb, DOWN) only_word = OldTexText("(only)") only_word.scale(1.25) only_brace = Brace(only_word, DOWN, buff=SMALL_BUFF) only_group = VGroup(only_word, only_brace) only_group.next_to( VGroup(btyb[0][-1], btyb[1][0]), UP, SMALL_BUFF ) only_group.set_color(RED) full_group = VGroup(btyb_group, only_group, you_word) full_group.generate_target() full_group.target.scale(0.4) full_group.target.to_corner(UL) patreon_logo = PatreonLogo() patreon_logo.scale(0.4) patreon_logo.next_to(full_group.target, DOWN) self.play( Write(so_words[0]), LaggedStartMap( DrawBorderThenFill, so_words[1], run_time=5 ), ) self.play( so_words.shift, DOWN, so_words.fade, 1, remover=True ) self.play(FadeInFromDown(btyb_group)) self.wait() self.play(Write(you_word)) self.play( GrowFromCenter(only_brace), Write(only_word) ) self.wait() self.play(MoveToTarget( full_group, rate_func=running_start, )) self.play(LaggedStartMap( DrawBorderThenFill, patreon_logo )) self.wait() def just_you_and_me(self): randy, morty = self.pi_creatures for pi in self.pi_creatures: pi.change("pondering") math = OldTex("\\sum_{n=1}^\\infty \\frac{1}{n^s}") math.scale(2) math.move_to(self.pi_creatures) spiral = Line(0.5 * RIGHT, 0.5 * RIGHT + 70 * UP) spiral.insert_n_curves(1000) from _2017.eoc.zeta import zeta spiral.apply_complex_function(zeta) step = 0.1 spiral = VGroup(*[ VMobject().pointwise_become_partial( spiral, a, a + step ) for a in np.arange(0, 1, step) ]) spiral.set_color_by_gradient(BLUE, YELLOW, RED) spiral.scale(0.5) spiral.move_to(math) self.play(FadeInFromDown(randy)) self.play(FadeInFromDown(morty)) self.play( Write(math), randy.change, "hooray", morty.change, "hooray", ) self.look_at(math) self.play( ShowCreation(spiral, run_time=6, rate_func=linear), math.scale, 0.5, math.shift, 3 * UP, randy.change, "thinking", morty.change, "thinking", ) self.play(LaggedStartMap(FadeOut, spiral, run_time=3)) self.wait(3) # Helpers def create_pi_creatures(self): randy = Randolph(color=BLUE_C) randy.to_edge(DOWN).shift(4 * LEFT) morty = Mortimer() morty.to_edge(DOWN).shift(4 * RIGHT) return VGroup(randy, morty) class ThoughtsOnAds(Scene): def construct(self): title = Title( "Internet advertising", match_underline_width_to_text=True, underline_buff=SMALL_BUFF, ) line = NumberLine( color=GREY_B, x_min=0, x_max=12, numbers_with_elongated_ticks=[] ) line.move_to(DOWN) arrows = VGroup(Vector(2 * LEFT), Vector(2 * RIGHT)) arrows.arrange(RIGHT, buff=2) arrows.next_to(line, DOWN) misaligned = OldTexText("Misaligned") misaligned.next_to(arrows[0], DOWN) aligned = OldTexText("Well-aligned") aligned.next_to(arrows[1], DOWN) VGroup(arrows[0], misaligned).set_color(RED) VGroup(arrows[1], aligned).set_color(BLUE) left_text = OldTexText( "Any website presented \\\\", "as a click-maximizing \\\\ slideshow" ) left_text.scale(0.8) left_text.next_to(line, UP, buff=MED_LARGE_BUFF) left_text.to_edge(LEFT) viewer, brand, creator = vcb = VGroup( *list(map(TexText, ["viewer", "brand", "creator"])) ) brand.next_to(creator, LEFT, LARGE_BUFF) viewer.next_to(vcb[1:], UP, LARGE_BUFF) arrow_config = { "path_arc": 60 * DEGREES, "tip_length": 0.15, } vcb_arrows = VGroup(*[ VGroup( Arrow(p1, p2, **arrow_config), Arrow(p2, p1, **arrow_config), ) for p1, p2 in [ (creator.get_left(), brand.get_right()), (brand.get_top(), viewer.get_bottom()), (viewer.get_bottom(), creator.get_top()), ] ]) vcb_arrows.set_stroke(width=2) vcb_arrows.set_color(BLUE) vcb_group = VGroup(vcb, vcb_arrows) vcb_group.next_to(line, UP, buff=MED_LARGE_BUFF) vcb_group.to_edge(RIGHT) knob = RegularPolygon(n=3, start_angle=-90 * DEGREES) knob.set_height(0.25) knob.set_stroke(width=0) knob.set_fill(YELLOW, 1) knob.move_to(line.get_left(), DOWN) right_rect = Rectangle( width=3, height=0.25, stroke_color=WHITE, stroke_width=2, fill_color=BLUE, fill_opacity=0.5 ) right_rect.move_to(line, RIGHT) right_rect_label = Group( ImageMobject("3b1b_logo", height=1), OldTexText("(hopefully)").scale(0.8) ) right_rect_label.arrange(DOWN, buff=SMALL_BUFF) # OldTexText( # "Where I hope \\\\ I've been" # ) right_rect_label.next_to( right_rect, UP, SMALL_BUFF ) # right_rect_label.set_color(BLUE) self.add(title) self.play(ShowCreation(line)) self.play( Write(misaligned), Write(aligned), *list(map(GrowArrow, arrows)), run_time=1 ) self.play( FadeIn(left_text), FadeIn(knob, 2 * RIGHT) ) self.wait() self.play( LaggedStartMap(FadeInFromDown, vcb), LaggedStartMap(ShowCreation, vcb_arrows), ApplyMethod( knob.move_to, line.get_right(), DOWN, run_time=2 ) ) self.wait(2) self.play(vcb_group.shift, 2 * UP) self.play( DrawBorderThenFill(right_rect), FadeIn(right_rect_label), ) self.wait() class HoldUpPreviousPromo(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs": { "color": GREY_BROWN, "flip_at_start": True, }, "default_pi_creature_start_corner": DR, } def construct(self): morty = self.pi_creature screen_rect = ScreenRectangle(height=5) screen_rect.to_corner(UL) self.play( FadeInFromDown(screen_rect), morty.change, "raise_right_hand", ) self.wait(5) class GoalWrapper(Scene): def construct(self): goal = OldTexText( "Goal: Teach/remind people \\\\ that they love math" ) goal.to_edge(UP) self.add(goal) screen_rect = ScreenRectangle(height=6) screen_rect.next_to(goal, DOWN) self.play(ShowCreation(screen_rect)) self.wait() class PeopleValueGraph(GraphScene): CONFIG = { "x_axis_label": "People reached", "y_axis_label": "Value per person", "x_min": 0, "x_max": 12, "x_axis_width": 11, "y_max": 8, "y_axis_height": 5, "graph_origin": 2 * DOWN + 5 * LEFT, "riemann_rectangles_config": { "dx": 0.01, "stroke_width": 0, "start_color": GREEN, "end_color": BLUE, } } def construct(self): self.setup_axes() self.tweak_labels() self.add_curve() self.comment_on_incentives() self.change_curve() def tweak_labels(self): self.add_foreground_mobjects(self.x_axis_label_mob) self.y_axis_label_mob.to_edge(LEFT) def add_curve(self): graph = self.graph = self.get_graph( lambda x: 7 * np.exp(-0.5 * x), ) self.play( ShowCreation(graph), rate_func=bezier([0, 0, 1, 1]), run_time=3 ) def comment_on_incentives(self): reach_arrow = Vector(5 * RIGHT) reach_arrow.next_to( self.x_axis, DOWN, buff=SMALL_BUFF, aligned_edge=RIGHT ) reach_words = OldTexText("Maximize reach?") reach_words.next_to(reach_arrow, DOWN, buff=SMALL_BUFF) reach_words.match_color(reach_arrow) area = self.area = self.get_riemann_rectangles( self.graph, **self.riemann_rectangles_config ) area_words = OldTexText("Maximize this area") area_words.set_color(BLUE) area_words.move_to(self.coords_to_point(4, 5)) area_arrow = Arrow( area_words.get_bottom(), self.coords_to_point(1.5, 2) ) self.play(GrowArrow(reach_arrow)) self.play(Write(reach_words)) self.wait() self.play( LaggedStartMap(DrawBorderThenFill, area), Animation(self.graph), Animation(self.axes), Write(area_words), GrowArrow(area_arrow), ) self.wait() self.area_label_group = VGroup(area_words, area_arrow) def change_curve(self): new_graph = self.get_graph( lambda x: interpolate( 7 * np.exp(-0.01 * x), 7 * np.exp(-3 * x), smooth(np.clip(x / 5, 0, 1)) ) ) new_area = self.get_riemann_rectangles( new_graph, **self.riemann_rectangles_config ) self.play( Transform(self.area, new_area), Transform(self.graph, new_graph), self.area_label_group[0].shift, RIGHT, Animation(self.area_label_group), Animation(self.axes), run_time=4, ) self.wait() class DivCurlEndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "Juan Benet", "Keith Smith", "Chloe Zhou", "Desmos ", "Burt Humburg", "CrypticSwarm", "Andrew Sachs", "Devin Scott", "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", "Fela ", "Fred Ehrsam", "Randy C. Will", "Britt Selvitelle", "Jonathan Wilson", "Ryan Atallah", "Joseph John Cox", "Luc Ritchie", "Omar Zrien", "Sindre Reino Trosterud", "Jeff Straathof", "Matt Langford", "Matt Roveto", "Marek Cirkos", "Magister Mugit", "Stevie Metke", "Cooper Jones", "James Hughes", "John V Wertheim", "Chris Giddings", "Song Gao", "Alexander Feldman", "Richard Burgmann", "John Griffith", "Chris Connett", "Steven Tomlinson", "Jameel Syed", "Bong Choung", "Ignacio Freiberg", "Zhilong Yang", "Giovanni Filippi", "Eric Younge", "Prasant Jagannath", "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", "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", "Robert Teed", "Jason Hise", "Bernd Sing", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Sh\\`im\\'in Ku\\=ang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], }
from manim_imports_ext import * class ComplexAnalysisOverlay(Scene): def construct(self): words = OldTexText("Complex analysis") words.scale(1.25) words.to_edge(UP) words.add_background_rectangle() self.add(words) self.wait() class AnalyzeZSquared(ComplexTransformationScene, ZoomedScene): CONFIG = { "plane_config": { "line_frequency": 0.1, }, "num_anchors_to_add_per_line": 20, "complex_homotopy": lambda z, t: z**(1.0 + t), "zoom_factor": 0.05, } def setup(self): ComplexTransformationScene.setup(self) ZoomedScene.setup(self) def construct(self): self.edit_background_plane() self.add_title() # self.add_transforming_planes() # self.preview_some_numbers() self.zoom_in_to_one_plus_half_i() self.write_derivative() def add_title(self): title = OldTex("z \\rightarrow z^2") title.add_background_rectangle() title.scale(1.5) title.to_corner(UL, buff=MED_SMALL_BUFF) self.add_foreground_mobject(title) def edit_background_plane(self): self.backgrounds.set_stroke(GREY, 2) self.background.secondary_lines.set_stroke(GREY_D, 1) self.add_foreground_mobject(self.background.coordinate_labels) def add_transforming_planes(self): self.plane = self.get_plane() self.add_transformable_mobjects(self.plane) def preview_some_numbers(self): dots = VGroup(*[ Dot().move_to(self.background.number_to_point(z)) for z in [ 1, 2, complex(0, 1), -1, complex(2, 0.5), complex(-1, -1), complex(3, 0.5), ] ]) dots.set_color_by_gradient(RED, YELLOW) d_angle = 30 * DEGREES dot_groups = VGroup() for dot in dots: point = dot.get_center() z = self.background.point_to_number(point) z_out = self.complex_homotopy(z, 1) out_point = self.background.number_to_point(z_out) path_arc = angle_of_vector(point) if abs(z - 1) < 0.01: # One is special arrow = Arc( start_angle=(-90 * DEGREES + d_angle), angle=(360 * DEGREES - 2 * d_angle), radius=0.25 ) arrow.add_tip(tip_length=0.15) arrow.pointwise_become_partial(arrow, 0, 0.9) arrow.next_to(dot, UP, buff=0) else: arrow = Arrow( point, out_point, path_arc=path_arc, buff=SMALL_BUFF, ) arrow.match_color(dot) out_dot = dot.copy() # out_dot.set_fill(opacity=0.5) out_dot.set_stroke(BLUE, 1) out_dot.move_to(out_point) dot.path_arc = path_arc dot.out_dot = out_dot dot_group = VGroup(dot, arrow, out_dot) dot_groups.add(dot_group) dot_copy = dot.copy() dot.save_state() dot.scale(3) dot.fade(1) dot_group.anim = Succession( ApplyMethod(dot.restore), AnimationGroup( ShowCreation(arrow), ReplacementTransform( dot_copy, out_dot, path_arc=path_arc ) ) ) for dot_group in dot_groups[:3]: self.play(dot_group.anim) self.wait() self.play(*[dg.anim for dg in dot_groups[3:]]) self.apply_complex_homotopy( self.complex_homotopy, added_anims=[Animation(dot_groups)] ) self.wait() self.play(FadeOut(dot_groups)) self.wait() self.play(FadeOut(self.plane)) self.transformable_mobjects.remove(self.plane) def zoom_in_to_one_plus_half_i(self): z = complex(1, 0.5) point = self.background.number_to_point(z) point_mob = VectorizedPoint(point) frame = self.zoomed_camera.frame frame.move_to(point) tiny_plane = NumberPlane( x_radius=2, y_radius=2, color=GREEN, secondary_color=GREEN_E ) tiny_plane.replace(frame) plane = self.get_plane() words = OldTexText("What does this look like") words.add_background_rectangle() words.next_to(self.zoomed_display, LEFT, aligned_edge=UP) arrow = Arrow(words.get_bottom(), self.zoomed_display.get_left()) VGroup(words, arrow).set_color(YELLOW) self.play(FadeIn(plane)) self.activate_zooming(animate=True) self.play(ShowCreation(tiny_plane)) self.wait() self.add_transformable_mobjects(plane, tiny_plane, point_mob) self.add_foreground_mobjects(words, arrow) self.apply_complex_homotopy( self.complex_homotopy, added_anims=[ Write(words), GrowArrow(arrow), MaintainPositionRelativeTo(frame, point_mob) ] ) self.wait(2) def write_derivative(self): pass # Helpers def get_plane(self): top_plane = NumberPlane( y_radius=FRAME_HEIGHT / 2, x_line_frequency=0.1, y_line_frequency=0.1, ) self.prepare_for_transformation(top_plane) bottom_plane = top_plane.copy() tiny_tiny_buff = 0.001 top_plane.next_to(ORIGIN, UP, buff=tiny_tiny_buff) bottom_plane.next_to(ORIGIN, DOWN, buff=tiny_tiny_buff) return VGroup(top_plane, bottom_plane)
from manim_imports_ext import * import warnings warnings.warn(""" Warning: This file makes use of ContinualAnimation, which has since been deprecated """) import time import mpmath mpmath.mp.dps = 7 # Warning, this file uses ContinualChangingDecimal, # which has since been been deprecated. Use a mobject # updater instead # Useful constants to play around with UL = UP + LEFT UR = UP + RIGHT DL = DOWN + LEFT DR = DOWN + RIGHT standard_rect = np.array([UL, UR, DR, DL]) # Used in EquationSolver2d, and a few other places border_stroke_width = 10 # Used for clockwise circling in some scenes cw_circle = Circle(color = WHITE).stretch(-1, 0) # Used when walker animations are on black backgrounds, in EquationSolver2d and PiWalker WALKER_LIGHT_COLOR = GREY_D ODOMETER_RADIUS = 1.5 ODOMETER_STROKE_WIDTH = 20 # TODO/WARNING: There's a lot of refactoring and cleanup to be done in this code, # (and it will be done, but first I'll figure out what I'm doing with all this...) # -SR # This turns counterclockwise revs into their color. Beware, we use CCW angles # in all display code, but generally think in this video's script in terms of # CW angles def rev_to_rgba(alpha): alpha = (0.5 - alpha) % 1 # For convenience, to go CW from red on left instead of CCW from right # 0 is red, 1/6 is yellow, 1/3 is green, 2/3 is blue hue_list = [0, 0.5/6.0, 1/6.0, 1.1/6.0, 2/6.0, 3/6.0, 4/6.0, 5/6.0] num_hues = len(hue_list) start_index = int(np.floor(num_hues * alpha)) % num_hues end_index = (start_index + 1) % num_hues beta = (alpha % (1.0/num_hues)) * num_hues start_hue = hue_list[start_index] end_hue = hue_list[end_index] if end_hue < start_hue: end_hue = end_hue + 1 hue = interpolate(start_hue, end_hue, beta) return color_to_rgba(Color(hue = hue, saturation = 1, luminance = 0.5)) # alpha = alpha % 1 # colors = colorslist # num_colors = len(colors) # beta = (alpha % (1.0/num_colors)) * num_colors # start_index = int(np.floor(num_colors * alpha)) % num_colors # end_index = (start_index + 1) % num_colors # return interpolate(colors[start_index], colors[end_index], beta) def rev_to_color(alpha): return rgba_to_color(rev_to_rgba(alpha)) def point_to_rev(xxx_todo_changeme6, allow_origin = False): # Warning: np.arctan2 would happily discontinuously returns the value 0 for (0, 0), due to # design choices in the underlying atan2 library call, but for our purposes, this is # illegitimate, and all winding number calculations must be set up to avoid this (x, y) = xxx_todo_changeme6 if not(allow_origin) and (x, y) == (0, 0): print("Error! Angle of (0, 0) computed!") return return fdiv(np.arctan2(y, x), TAU) def point_to_size(xxx_todo_changeme7): (x, y) = xxx_todo_changeme7 return np.sqrt(x**2 + y**2) # rescaled_size goes from 0 to 1 as size goes from 0 to infinity # The exact method is arbitrarily chosen to make pleasing color map # brightness levels def point_to_rescaled_size(p): base_size = point_to_size(p) return np.sqrt(fdiv(base_size, base_size + 1)) def point_to_rgba(point): rev = point_to_rev(point, allow_origin = True) rgba = rev_to_rgba(rev) rescaled_size = point_to_rescaled_size(point) return rgba * [rescaled_size, rescaled_size, rescaled_size, 1] # Preserve alpha positive_color = rev_to_color(0) negative_color = rev_to_color(0.5) neutral_color = rev_to_color(0.25) class EquationSolver1d(GraphScene, ZoomedScene): CONFIG = { "camera_config" : { "use_z_coordinate_for_display_order": True, }, "func" : lambda x : x, "targetX" : 0, "targetY" : 0, "initial_lower_x" : 0, "initial_upper_x" : 10, "num_iterations" : 10, "iteration_at_which_to_start_zoom" : None, "graph_label" : None, "show_target_line" : True, "base_line_y" : 0, # The y coordinate at which to draw our x guesses "show_y_as_deviation" : False, # Displays y-values as deviations from target, } def drawGraph(self): self.setup_axes() self.graph = self.get_graph(self.func) self.add(self.graph) if self.graph_label != None: curve_label = self.get_graph_label(self.graph, self.graph_label, x_val = 4, direction = LEFT) curve_label.shift(LEFT) self.add(curve_label) if self.show_target_line: target_line_object = DashedLine( self.coords_to_point(self.x_min, self.targetY), self.coords_to_point(self.x_max, self.targetY), dash_length = 0.1) self.add(target_line_object) target_label_num = 0 if self.show_y_as_deviation else self.targetY target_line_label = OldTex("y = " + str(target_label_num)) target_line_label.next_to(target_line_object.get_left(), UP + RIGHT) self.add(target_line_label) self.wait() # Give us time to appreciate the graph if self.show_target_line: self.play(FadeOut(target_line_label)) # Reduce clutter print("For reference, graphOrigin: ", self.coords_to_point(0, 0)) print("targetYPoint: ", self.coords_to_point(0, self.targetY)) # This is a mess right now (first major animation coded), # but it works; can be refactored later or never def solveEquation(self): # Under special conditions, used in GuaranteedZeroScene, we let the # "lower" guesses actually be too high, or vice versa, and color # everything accordingly def color_by_comparison(val, ref): if val > ref: return positive_color elif val < ref: return negative_color else: return neutral_color lower_color = color_by_comparison(self.func(self.initial_lower_x), self.targetY) upper_color = color_by_comparison(self.func(self.initial_upper_x), self.targetY) if self.show_y_as_deviation: y_bias = -self.targetY else: y_bias = 0 startBrace = OldTex("|", stroke_width = 10) #Tex("[") # Not using [ and ] because they end up crossing over startBrace.set_color(lower_color) endBrace = startBrace.copy().stretch(-1, 0) endBrace.set_color(upper_color) genericBraces = Group(startBrace, endBrace) #genericBraces.scale(1.5) leftBrace = startBrace.copy() rightBrace = endBrace.copy() xBraces = Group(leftBrace, rightBrace) downBrace = startBrace.copy() upBrace = endBrace.copy() yBraces = Group(downBrace, upBrace) yBraces.rotate(TAU/4) lowerX = self.initial_lower_x lowerY = self.func(lowerX) upperX = self.initial_upper_x upperY = self.func(upperX) leftBrace.move_to(self.coords_to_point(lowerX, self.base_line_y)) #, aligned_edge = RIGHT) leftBraceLabel = DecimalNumber(lowerX) leftBraceLabel.next_to(leftBrace, DOWN + LEFT, buff = SMALL_BUFF) leftBraceLabelAnimation = ContinualChangingDecimal(leftBraceLabel, lambda alpha : self.point_to_coords(leftBrace.get_center())[0], tracked_mobject = leftBrace) rightBrace.move_to(self.coords_to_point(upperX, self.base_line_y)) #, aligned_edge = LEFT) rightBraceLabel = DecimalNumber(upperX) rightBraceLabel.next_to(rightBrace, DOWN + RIGHT, buff = SMALL_BUFF) rightBraceLabelAnimation = ContinualChangingDecimal(rightBraceLabel, lambda alpha : self.point_to_coords(rightBrace.get_center())[0], tracked_mobject = rightBrace) downBrace.move_to(self.coords_to_point(0, lowerY)) #, aligned_edge = UP) downBraceLabel = DecimalNumber(lowerY) downBraceLabel.next_to(downBrace, LEFT + DOWN, buff = SMALL_BUFF) downBraceLabelAnimation = ContinualChangingDecimal(downBraceLabel, lambda alpha : self.point_to_coords(downBrace.get_center())[1] + y_bias, tracked_mobject = downBrace) upBrace.move_to(self.coords_to_point(0, upperY)) #, aligned_edge = DOWN) upBraceLabel = DecimalNumber(upperY) upBraceLabel.next_to(upBrace, LEFT + UP, buff = SMALL_BUFF) upBraceLabelAnimation = ContinualChangingDecimal(upBraceLabel, lambda alpha : self.point_to_coords(upBrace.get_center())[1] + y_bias, tracked_mobject = upBrace) lowerDotPoint = self.input_to_graph_point(lowerX, self.graph) lowerDotXPoint = self.coords_to_point(lowerX, self.base_line_y) lowerDotYPoint = self.coords_to_point(0, self.func(lowerX)) lowerDot = Dot(lowerDotPoint + OUT, color = lower_color) upperDotPoint = self.input_to_graph_point(upperX, self.graph) upperDot = Dot(upperDotPoint + OUT, color = upper_color) upperDotXPoint = self.coords_to_point(upperX, self.base_line_y) upperDotYPoint = self.coords_to_point(0, self.func(upperX)) lowerXLine = Line(lowerDotXPoint, lowerDotPoint, color = lower_color) upperXLine = Line(upperDotXPoint, upperDotPoint, color = upper_color) lowerYLine = Line(lowerDotPoint, lowerDotYPoint, color = lower_color) upperYLine = Line(upperDotPoint, upperDotYPoint, color = upper_color) x_guess_line = Line(lowerDotXPoint, upperDotXPoint, color = WHITE, stroke_width = 10) lowerGroup = Group( lowerDot, leftBrace, downBrace, lowerXLine, lowerYLine, x_guess_line ) upperGroup = Group( upperDot, rightBrace, upBrace, upperXLine, upperYLine, x_guess_line ) initialLowerXDot = Dot(lowerDotXPoint + OUT, color = lower_color) initialUpperXDot = Dot(upperDotXPoint + OUT, color = upper_color) initialLowerYDot = Dot(lowerDotYPoint + OUT, color = lower_color) initialUpperYDot = Dot(upperDotYPoint + OUT, color = upper_color) # All the initial adds and ShowCreations are here now: self.play(FadeIn(initialLowerXDot), FadeIn(leftBrace), FadeIn(leftBraceLabel)) self.add_foreground_mobjects(initialLowerXDot, leftBrace) self.add(leftBraceLabelAnimation) self.play(ShowCreation(lowerXLine)) self.add_foreground_mobject(lowerDot) self.play(ShowCreation(lowerYLine)) self.play(FadeIn(initialLowerYDot), FadeIn(downBrace), FadeIn(downBraceLabel)) self.add_foreground_mobjects(initialLowerYDot, downBrace) self.add(downBraceLabelAnimation) self.wait() self.play(FadeIn(initialUpperXDot), FadeIn(rightBrace), FadeIn(rightBraceLabel)) self.add_foreground_mobjects(initialUpperXDot, rightBrace) self.add(rightBraceLabelAnimation) self.play(ShowCreation(upperXLine)) self.add_foreground_mobject(upperDot) self.play(ShowCreation(upperYLine)) self.play(FadeIn(initialUpperYDot), FadeIn(upBrace), FadeIn(upBraceLabel)) self.add_foreground_mobjects(initialUpperYDot, upBrace) self.add(upBraceLabelAnimation) self.wait() self.play(FadeIn(x_guess_line)) self.wait() for i in range(self.num_iterations): if i == self.iteration_at_which_to_start_zoom: self.activate_zooming() self.little_rectangle.move_to( self.coords_to_point(self.targetX, self.targetY)) inverseZoomFactor = 1/float(self.zoom_factor) self.play( lowerDot.scale, inverseZoomFactor, upperDot.scale, inverseZoomFactor) def makeUpdater(xAtStart, fixed_guess_x): def updater(group, alpha): dot, xBrace, yBrace, xLine, yLine, guess_line = group newX = interpolate(xAtStart, midX, alpha) newY = self.func(newX) graphPoint = self.input_to_graph_point(newX, self.graph) dot.move_to(graphPoint) xAxisPoint = self.coords_to_point(newX, self.base_line_y) xBrace.move_to(xAxisPoint) yAxisPoint = self.coords_to_point(0, newY) yBrace.move_to(yAxisPoint) xLine.put_start_and_end_on(xAxisPoint, graphPoint) yLine.put_start_and_end_on(yAxisPoint, graphPoint) fixed_guess_point = self.coords_to_point(fixed_guess_x, self.base_line_y) guess_line.put_start_and_end_on(xAxisPoint, fixed_guess_point) return group return updater midX = (lowerX + upperX)/float(2) midY = self.func(midX) # If we run with an interval whose endpoints start off with same sign, # then nothing after this branching can be trusted to do anything reasonable # in terms of picking branches or assigning colors in_negative_branch = midY < self.targetY sign_color = negative_color if in_negative_branch else positive_color midCoords = self.coords_to_point(midX, midY) midColor = neutral_color # Hm... even the z buffer isn't helping keep this above x_guess_line midXBrace = startBrace.copy() # Had start and endBrace been asymmetric, we'd do something different here midXBrace.set_color(midColor) midXBrace.move_to(self.coords_to_point(midX, self.base_line_y) + OUT) # We only actually add this much later midXPoint = Dot(self.coords_to_point(midX, self.base_line_y) + OUT, color = sign_color) x_guess_label_caption = OldTexText("New guess: x = ", fill_color = midColor) x_guess_label_num = DecimalNumber(midX, fill_color = midColor) x_guess_label_num.move_to(0.9 * FRAME_Y_RADIUS * DOWN) x_guess_label_caption.next_to(x_guess_label_num, LEFT) x_guess_label = Group(x_guess_label_caption, x_guess_label_num) y_guess_label_caption = OldTexText(", y = ", fill_color = midColor) y_guess_label_num = DecimalNumber(midY, fill_color = sign_color) y_guess_label_caption.next_to(x_guess_label_num, RIGHT) y_guess_label_num.next_to(y_guess_label_caption, RIGHT) y_guess_label = Group(y_guess_label_caption, y_guess_label_num) guess_labels = Group(x_guess_label, y_guess_label) self.play( ReplacementTransform(leftBrace.copy(), midXBrace), ReplacementTransform(rightBrace.copy(), midXBrace), FadeIn(x_guess_label)) self.add_foreground_mobject(midXBrace) midXLine = DashedLine( self.coords_to_point(midX, self.base_line_y), midCoords, color = midColor ) self.play(ShowCreation(midXLine)) midDot = Dot(midCoords, color = sign_color) if(self.iteration_at_which_to_start_zoom != None and i >= self.iteration_at_which_to_start_zoom): midDot.scale(inverseZoomFactor) self.add(midDot) midYLine = DashedLine(midCoords, self.coords_to_point(0, midY), color = sign_color) self.play( ShowCreation(midYLine), FadeIn(y_guess_label), ApplyMethod(midXBrace.set_color, sign_color), ApplyMethod(midXLine.set_color, sign_color), run_time = 0.25 ) midYPoint = Dot(self.coords_to_point(0, midY), color = sign_color) self.add(midXPoint, midYPoint) if in_negative_branch: self.play( UpdateFromAlphaFunc(lowerGroup, makeUpdater(lowerX, fixed_guess_x = upperX ) ), FadeOut(guess_labels), ) lowerX = midX lowerY = midY else: self.play( UpdateFromAlphaFunc(upperGroup, makeUpdater(upperX, fixed_guess_x = lowerX ) ), FadeOut(guess_labels), ) upperX = midX upperY = midY #mid_group = Group(midXLine, midDot, midYLine) Removing groups doesn't flatten as expected? self.remove(midXLine, midDot, midYLine, midXBrace) self.wait() def construct(self): self.drawGraph() self.solveEquation() # Returns the value with the same fractional component as x, closest to m def resit_near(x, m): frac_diff = (x - m) % 1 if frac_diff > 0.5: frac_diff -= 1 return m + frac_diff # TODO?: Perhaps use modulus of (uniform) continuity instead of num_checkpoints, calculating # latter as needed from former? # # "cheap" argument only used for diagnostic testing right now def make_alpha_winder(func, start, end, num_checkpoints, cheap = False): check_points = [None for i in range(num_checkpoints)] check_points[0] = func(start) step_size = fdiv(end - start, num_checkpoints) for i in range(num_checkpoints - 1): check_points[i + 1] = \ resit_near( func(start + (i + 1) * step_size), check_points[i]) def return_func(alpha): if cheap: return alpha # A test to see if this func is responsible for slowdown index = np.clip(0, num_checkpoints - 1, int(alpha * num_checkpoints)) x = interpolate(start, end, alpha) if cheap: return check_points[index] # A more principled test that at least returns a reasonable answer else: return resit_near(func(x), check_points[index]) return return_func # The various inconsistent choices of what datatype to use where are a bit of a mess, # but I'm more keen to rush this video out now than to sort this out. def complex_to_pair(c): return np.array((c.real, c.imag)) def plane_func_from_complex_func(f): return lambda x_y4 : complex_to_pair(f(complex(x_y4[0],x_y4[1]))) def point3d_func_from_plane_func(f): def g(xxx_todo_changeme): (x, y, z) = xxx_todo_changeme f_val = f((x, y)) return np.array((f_val[0], f_val[1], 0)) return g def point3d_func_from_complex_func(f): return point3d_func_from_plane_func(plane_func_from_complex_func(f)) def plane_zeta(xxx_todo_changeme8): (x, y) = xxx_todo_changeme8 CLAMP_SIZE = 1000 z = complex(x, y) try: answer = mpmath.zeta(z) except ValueError: return (CLAMP_SIZE, 0) if abs(answer) > CLAMP_SIZE: answer = answer/abs(answer) * CLAMP_SIZE return (float(answer.real), float(answer.imag)) def rescaled_plane_zeta(xxx_todo_changeme9): (x, y) = xxx_todo_changeme9 return plane_zeta((x/FRAME_X_RADIUS, 8*y)) # Returns a function from 2-ples to 2-ples # This function is specified by a list of (x, y, z) tuples, # and has winding number z (or total of all specified z) around each (x, y) # # Can also pass in (x, y) tuples, interpreted as (x, y, 1) def plane_func_by_wind_spec(*specs): def embiggen(p): if len(p) == 3: return p elif len(p) == 2: return (p[0], p[1], 1) else: print("Error in plane_func_by_wind_spec embiggen!") specs = list(map(embiggen, specs)) pos_specs = [x_y_z for x_y_z in specs if x_y_z[2] > 0] neg_specs = [x_y_z1 for x_y_z1 in specs if x_y_z1[2] < 0] neg_specs_made_pos = [(x_y_z2[0], x_y_z2[1], -x_y_z2[2]) for x_y_z2 in neg_specs] def poly(c, root_specs): return np.prod([(c - complex(x, y))**z for (x, y, z) in root_specs]) def complex_func(c): return poly(c, pos_specs) * np.conjugate(poly(c, neg_specs_made_pos)) return plane_func_from_complex_func(complex_func) def scale_func(func, scale_factor): return lambda x : func(x) * scale_factor # Used in Initial2dFunc scenes, VectorField scene, and ExamplePlaneFunc example_plane_func_spec = [(-3, -1.3, 2), (0.1, 0.2, 1), (2.8, -2, -1)] example_plane_func = plane_func_by_wind_spec(*example_plane_func_spec) empty_animation = EmptyAnimation() class WalkerAnimation(Animation): CONFIG = { "walk_func" : None, # Must be initialized to use "remover" : True, "rate_func" : None, "coords_to_point" : None } def __init__(self, walk_func, val_func, coords_to_point, show_arrows = True, scale_arrows = False, **kwargs): self.walk_func = walk_func self.val_func = val_func self.coords_to_point = coords_to_point self.compound_walker = VGroup() self.show_arrows = show_arrows self.scale_arrows = scale_arrows if "walker_stroke_color" in kwargs: walker_stroke_color = kwargs["walker_stroke_color"] else: walker_stroke_color = BLACK base_walker = Dot().scale(5 * 0.35).set_stroke(walker_stroke_color, 2) # PiCreature().scale(0.8 * 0.35) self.compound_walker.walker = base_walker if show_arrows: self.compound_walker.arrow = Arrow(ORIGIN, 0.5 * RIGHT, buff = 0) self.compound_walker.arrow.match_style(self.compound_walker.walker) self.compound_walker.digest_mobject_attrs() Animation.__init__(self, self.compound_walker, **kwargs) # Perhaps abstract this out into an "Animation updating from original object" class def interpolate_submobject(self, submobject, starting_submobject, alpha): submobject.set_points(starting_submobject.get_points()) def interpolate_mobject(self, alpha): Animation.interpolate_mobject(self, alpha) cur_x, cur_y = cur_coords = self.walk_func(alpha) cur_point = self.coords_to_point(cur_x, cur_y) self.mobject.shift(cur_point - self.mobject.walker.get_center()) val = self.val_func(cur_coords) rev = point_to_rev(val) self.mobject.walker.set_fill(rev_to_color(rev)) if self.show_arrows: self.mobject.arrow.set_fill(rev_to_color(rev)) self.mobject.arrow.rotate( rev * TAU, about_point = self.mobject.arrow.get_start() ) if self.scale_arrows: size = point_to_rescaled_size(val) self.mobject.arrow.scale( size * 0.3, # Hack constant; we barely use this feature right now about_point = self.mobject.arrow.get_start() ) def walker_animation_with_display( walk_func, val_func, coords_to_point, number_update_func = None, show_arrows = True, scale_arrows = False, num_decimal_places = 1, include_background_rectangle = True, **kwargs ): walker_anim = WalkerAnimation( walk_func = walk_func, val_func = val_func, coords_to_point = coords_to_point, show_arrows = show_arrows, scale_arrows = scale_arrows, **kwargs) walker = walker_anim.compound_walker.walker if number_update_func != None: display = DecimalNumber(0, num_decimal_places = num_decimal_places, fill_color = WHITE if include_background_rectangle else BLACK, include_background_rectangle = include_background_rectangle) if include_background_rectangle: display.background_rectangle.fill_opacity = 0.5 display.background_rectangle.fill_color = GREY display.background_rectangle.scale(1.2) displaycement = 0.5 * DOWN # How about that pun, eh? # display.move_to(walker.get_center() + displaycement) display.next_to(walker, DOWN+RIGHT, SMALL_BUFF) display_anim = ChangingDecimal(display, number_update_func, tracked_mobject = walker_anim.compound_walker.walker, **kwargs) anim_group = AnimationGroup(walker_anim, display_anim, rate_func=linear) return anim_group else: return walker_anim def LinearWalker( start_coords, end_coords, coords_to_point, val_func, number_update_func = None, show_arrows = True, scale_arrows = False, include_background_rectangle = True, **kwargs ): walk_func = lambda alpha : interpolate(start_coords, end_coords, alpha) return walker_animation_with_display( walk_func = walk_func, coords_to_point = coords_to_point, val_func = val_func, number_update_func = number_update_func, show_arrows = show_arrows, scale_arrows = scale_arrows, include_background_rectangle = include_background_rectangle, **kwargs) class ColorMappedByFuncScene(Scene): CONFIG = { "func" : lambda p : p, "num_plane" : NumberPlane(), "show_num_plane" : True, "show_output" : False, "hide_background" : False #Background used for color mapped objects, not as background } def short_path_to_long_path(self, filename_with_ext): return self.get_image_file_path(filename_with_ext) def setup(self): # The composition of input_to_pos and pos_to_color # is to be equal to func (which turns inputs into colors) # However, depending on whether we are showing input or output (via a MappingCamera), # we color the background using either func or the identity map if self.show_output: self.input_to_pos_func = self.func self.pos_to_color_func = lambda p : p else: self.input_to_pos_func = lambda p : p self.pos_to_color_func = self.func self.pixel_pos_to_color_func = lambda x_y3 : self.pos_to_color_func( self.num_plane.point_to_coords_cheap(np.array([x_y3[0], x_y3[1], 0])) ) jitter_val = 0.1 line_coords = np.linspace(-10, 10) + jitter_val func_hash_points = it.product(line_coords, line_coords) def mini_hasher(p): rgba = point_to_rgba(self.pixel_pos_to_color_func(p)) if rgba[3] != 1.0: print("Warning! point_to_rgba assigns fractional alpha", rgba[3]) return tuple(rgba) to_hash = tuple(mini_hasher(p) for p in func_hash_points) func_hash = hash(to_hash) # We hash just based on output image # Thus, multiple scenes with same output image can re-use it # without recomputation full_hash = hash((func_hash, self.camera.get_pixel_width())) self.background_image_file = self.short_path_to_long_path( "color_mapped_bg_hash_" + str(full_hash) + ".png" ) self.in_background_pass = not os.path.exists(self.background_image_file) print("Background file: " + self.background_image_file) if self.in_background_pass: print("The background file does not exist yet; this will be a background creation + video pass") else: print("The background file already exists; this will only be a video pass") def construct(self): if self.in_background_pass: self.camera.set_background_from_func( lambda x_y: point_to_rgba( self.pixel_pos_to_color_func( (x_y[0], x_y[1]) ) ) ) self.save_image(self.background_image_file, mode="RGBA") if self.hide_background: # Clearing background self.camera.background_image = None else: # Even if we just computed the background, we switch to the file now self.camera.background_image = self.background_image_file self.camera.init_background() if self.show_num_plane: self.num_plane.fade() self.add(self.num_plane) class PureColorMap(ColorMappedByFuncScene): CONFIG = { "show_num_plane" : False } def construct(self): ColorMappedByFuncScene.construct(self) self.wait() # This sets self.background_image_file, but does not display it as the background class ColorMappedObjectsScene(ColorMappedByFuncScene): CONFIG = { "show_num_plane" : False, "hide_background" : True, } class PiWalker(ColorMappedByFuncScene): CONFIG = { "walk_coords" : [], "step_run_time" : 1, "scale_arrows" : False, "display_wind" : True, "wind_reset_indices" : [], "display_size" : False, "display_odometer" : False, "color_foreground_not_background" : False, "show_num_plane" : False, "draw_lines" : True, "num_checkpoints" : 10, "num_decimal_places" : 1, "include_background_rectangle" : False, } def construct(self): ColorMappedByFuncScene.construct(self) if self.color_foreground_not_background or self.display_odometer: # Clear background self.camera.background_image = None self.camera.init_background() num_plane = self.num_plane walk_coords = self.walk_coords points = [num_plane.coords_to_point(x, y) for x, y in walk_coords] polygon = Polygon(*points, color = WHITE) if self.color_foreground_not_background: polygon.stroke_width = border_stroke_width polygon.color_using_background_image(self.background_image_file) total_run_time = len(points) * self.step_run_time polygon_anim = ShowCreation(polygon, run_time = total_run_time, rate_func=linear) walker_anim = empty_animation start_wind = 0 for i in range(len(walk_coords)): start_coords = walk_coords[i] end_coords = walk_coords[(i + 1) % len(walk_coords)] # We need to do this roundabout default argument thing to get the closure we want, # so the next iteration changing start_coords, end_coords doesn't change this closure val_alpha_func = lambda a, start_coords = start_coords, end_coords = end_coords : self.func(interpolate(start_coords, end_coords, a)) if self.display_wind: clockwise_val_func = lambda p : -point_to_rev(self.func(p)) alpha_winder = make_alpha_winder(clockwise_val_func, start_coords, end_coords, self.num_checkpoints) number_update_func = lambda alpha, alpha_winder = alpha_winder, start_wind = start_wind: alpha_winder(alpha) - alpha_winder(0) + start_wind start_wind = 0 if i + 1 in self.wind_reset_indices else number_update_func(1) elif self.display_size: # We need to do this roundabout default argument thing to get the closure we want, # so the next iteration changing val_alpha_func doesn't change this closure number_update_func = lambda a, val_alpha_func = val_alpha_func : point_to_rescaled_size(val_alpha_func(a)) # We only use this for diagnostics else: number_update_func = None new_anim = LinearWalker( start_coords = start_coords, end_coords = end_coords, coords_to_point = num_plane.coords_to_point, val_func = self.func, remover = (i < len(walk_coords) - 1), show_arrows = not self.show_output, scale_arrows = self.scale_arrows, number_update_func = number_update_func, run_time = self.step_run_time, walker_stroke_color = WALKER_LIGHT_COLOR if self.color_foreground_not_background else BLACK, num_decimal_places = self.num_decimal_places, include_background_rectangle = self.include_background_rectangle, ) if self.display_odometer: # Discard above animation and show an odometer instead # We need to do this roundabout default argument thing to get the closure we want, # so the next iteration changing val_alpha_func doesn't change this closure rev_func = lambda a, val_alpha_func = val_alpha_func : point_to_rev(val_alpha_func(a)) base_arrow = Arrow(ORIGIN, RIGHT, buff = 0) new_anim = FuncRotater(base_arrow, rev_func = rev_func, run_time = self.step_run_time, rate_func=linear, remover = i < len(walk_coords) - 1, ) walker_anim = Succession(walker_anim, new_anim) # TODO: Allow smooth paths instead of breaking them up into lines, and # use point_from_proportion to get points along the way if self.display_odometer: color_wheel = Circle(radius = ODOMETER_RADIUS) color_wheel.stroke_width = ODOMETER_STROKE_WIDTH color_wheel.color_using_background_image(self.short_path_to_long_path("pure_color_map.png")) # Manually inserted here; this is unclean self.add(color_wheel) self.play(walker_anim) else: if self.draw_lines: self.play(polygon_anim, walker_anim) else: # (Note: Turns out, play is unhappy playing empty_animation, as had been # previous approach to this toggle; should fix that) self.play(walker_anim) self.wait() class PiWalkerRect(PiWalker): CONFIG = { "start_x" : -1, "start_y" : 1, "walk_width" : 2, "walk_height" : 2, "func" : plane_func_from_complex_func(lambda c: c**2), "double_up" : False, # New default for the scenes using this: "display_wind" : True } def setup(self): TL = np.array((self.start_x, self.start_y)) TR = TL + (self.walk_width, 0) BR = TR + (0, -self.walk_height) BL = BR + (-self.walk_width, 0) self.walk_coords = [TL, TR, BR, BL] if self.double_up: self.walk_coords = self.walk_coords + self.walk_coords PiWalker.setup(self) class PiWalkerCircle(PiWalker): CONFIG = { "radius" : 1, "num_steps" : 100, "step_run_time" : 0.01 } def setup(self): r = self.radius N = self.num_steps self.walk_coords = [r * np.array((np.cos(i * TAU/N), np.sin(i * TAU/N))) for i in range(N)] PiWalker.setup(self) def split_interval(xxx_todo_changeme10): (a, b) = xxx_todo_changeme10 mid = (a + b)/2.0 return ((a, mid), (mid, b)) # I am surely reinventing some wheel here, but what's done is done... class RectangleData(): def __init__(self, x_interval, y_interval): self.rect = (x_interval, y_interval) def get_top_left(self): return np.array((self.rect[0][0], self.rect[1][1])) def get_top_right(self): return np.array((self.rect[0][1], self.rect[1][1])) def get_bottom_right(self): return np.array((self.rect[0][1], self.rect[1][0])) def get_bottom_left(self): return np.array((self.rect[0][0], self.rect[1][0])) def get_top(self): return (self.get_top_left(), self.get_top_right()) def get_right(self): return (self.get_top_right(), self.get_bottom_right()) def get_bottom(self): return (self.get_bottom_right(), self.get_bottom_left()) def get_left(self): return (self.get_bottom_left(), self.get_top_left()) def get_center(self): return interpolate(self.get_top_left(), self.get_bottom_right(), 0.5) def get_width(self): return self.rect[0][1] - self.rect[0][0] def get_height(self): return self.rect[1][1] - self.rect[1][0] def splits_on_dim(self, dim): x_interval = self.rect[0] y_interval = self.rect[1] # TODO: Can refactor the following; will do later if dim == 0: return_data = [RectangleData(new_interval, y_interval) for new_interval in split_interval(x_interval)] elif dim == 1: return_data = [RectangleData(x_interval, new_interval) for new_interval in split_interval(y_interval)[::-1]] else: print("RectangleData.splits_on_dim passed illegitimate dimension!") return tuple(return_data) def split_line_on_dim(self, dim): x_interval = self.rect[0] y_interval = self.rect[1] if dim == 0: sides = (self.get_top(), self.get_bottom()) elif dim == 1: sides = (self.get_left(), self.get_right()) else: print("RectangleData.split_line_on_dim passed illegitimate dimension!") return tuple([mid(x, y) for (x, y) in sides]) class EquationSolver2dNode(object): def __init__(self, first_anim, children = []): self.first_anim = first_anim self.children = children def depth(self): if len(self.children) == 0: return 0 return 1 + max([n.depth() for n in self.children]) def nodes_at_depth(self, n): if n == 0: return [self] # Not the efficient way to flatten lists, because Python + is linear in list size, # but we have at most two children, so no big deal here return sum([c.nodes_at_depth(n - 1) for c in self.children], []) # This is definitely NOT the efficient way to do BFS, but I'm just trying to write something # quick without thinking that gets the job done on small instances for now def hacky_bfs(self): depth = self.depth() # Not the efficient way to flatten lists, because Python + is linear in list size, # but this IS hacky_bfs... return sum([self.nodes_at_depth(i) for i in range(depth + 1)], []) def display_in_series(self): return Succession(self.first_anim, *[n.display_in_series() for n in self.children]) def display_in_parallel(self): return Succession(self.first_anim, AnimationGroup(*[n.display_in_parallel() for n in self.children])) def display_in_bfs(self): bfs_nodes = self.hacky_bfs() return Succession(*[n.first_anim for n in bfs_nodes]) def play_in_bfs(self, scene, border_anim): bfs_nodes = self.hacky_bfs() print("Number of nodes: ", len(bfs_nodes)) if len(bfs_nodes) < 1: print("Less than 1 node! Aborting!") return scene.play(bfs_nodes[0].first_anim, border_anim) for node in bfs_nodes[1:]: scene.play(node.first_anim) class EquationSolver2d(ColorMappedObjectsScene): CONFIG = { "camera_config" : {"use_z_coordinate_for_display_order": True}, "initial_lower_x" : -5, "initial_upper_x" : 5, "initial_lower_y" : -3, "initial_upper_y" : 3, "num_iterations" : 0, "num_checkpoints" : 10, # Should really merge this into one enum-style variable "display_in_parallel" : False, "display_in_bfs" : False, "use_fancy_lines" : True, "line_color" : WHITE, # Only used for non-fancy lines # TODO: Consider adding a "find_all_roots" flag, which could be turned off # to only explore one of the two candidate subrectangles when both are viable # Walker settings "show_arrows" : True, "scale_arrows" : False, # Special case settings # These are used to hack UhOhScene, where we display different colors than # are actually, secretly, guiding the evolution of the EquationSolver2d # # replacement_background_image_file has to be manually configured "show_winding_numbers" : True, # Used for UhOhScene; "manual_wind_override" : None, "show_cursor" : True, "linger_parameter" : 0.5, "use_separate_plays" : False, "use_cheap_winding_numbers" : False, # To use this, make num_checkpoints large } def construct(self): if self.num_iterations == 0: print("You forgot to set num_iterations (maybe you meant to subclass something other than EquationSolver2d directly?)") return ColorMappedObjectsScene.construct(self) num_plane = self.num_plane clockwise_val_func = lambda p : -point_to_rev(self.func(p)) base_line = Line(UP, RIGHT, stroke_width = border_stroke_width, color = self.line_color) if self.use_fancy_lines: base_line.color_using_background_image(self.background_image_file) def match_style_with_bg(obj1, obj2): obj1.match_style(obj2) bg = obj2.get_background_image_file() if bg != None: obj1.color_using_background_image(bg) run_time_base = 1 run_time_with_lingering = run_time_base + self.linger_parameter base_rate = lambda t : t linger_rate = squish_rate_func(lambda t : t, 0, fdiv(run_time_base, run_time_with_lingering)) cursor_base = OldTexText("?") cursor_base.scale(2) # Helper functions for manual_wind_override def head(m): if m == None: return None return m[0] def child(m, i): if m == None or m == 0: return None return m[i + 1] def Animate2dSolver(cur_depth, rect, dim_to_split, sides_to_draw = [0, 1, 2, 3], manual_wind_override = None): print("Solver at depth: " + str(cur_depth)) if cur_depth >= self.num_iterations: return EquationSolver2dNode(empty_animation) def draw_line_return_wind(start, end, start_wind, should_linger = False, draw_line = True): alpha_winder = make_alpha_winder(clockwise_val_func, start, end, self.num_checkpoints, cheap = self.use_cheap_winding_numbers) a0 = alpha_winder(0) rebased_winder = lambda alpha: alpha_winder(alpha) - a0 + start_wind colored_line = Line(num_plane.coords_to_point(*start) + IN, num_plane.coords_to_point(*end) + IN) match_style_with_bg(colored_line, base_line) walker_anim = LinearWalker( start_coords = start, end_coords = end, coords_to_point = num_plane.coords_to_point, val_func = self.func, # Note: This is the image func, and not logic_func number_update_func = rebased_winder if self.show_winding_numbers else None, remover = True, walker_stroke_color = WALKER_LIGHT_COLOR, show_arrows = self.show_arrows, scale_arrows = self.scale_arrows, ) if should_linger: # Do we need an "and not self.display_in_parallel" here? run_time = run_time_with_lingering rate_func = linger_rate else: run_time = run_time_base rate_func = base_rate opt_line_anim = ShowCreation(colored_line) if draw_line else empty_animation line_draw_anim = AnimationGroup( opt_line_anim, walker_anim, run_time = run_time, rate_func = rate_func) return (line_draw_anim, rebased_winder(1)) wind_so_far = 0 anim = empty_animation sides = [ rect.get_top(), rect.get_right(), rect.get_bottom(), rect.get_left() ] for (i, (start, end)) in enumerate(sides): (next_anim, wind_so_far) = draw_line_return_wind(start, end, wind_so_far, should_linger = i == len(sides) - 1, draw_line = i in sides_to_draw) anim = Succession(anim, next_anim) if self.show_cursor: cursor = cursor_base.copy() center_x, center_y = rect.get_center() width = rect.get_width() height = rect.get_height() cursor.move_to(num_plane.coords_to_point(center_x, center_y) + 10 * IN) cursor.scale(min(width, height)) # Do a quick FadeIn, wait, and quick FadeOut on the cursor, matching rectangle-drawing time cursor_anim = Succession( FadeIn(cursor, run_time = 0.1), Animation(cursor, run_time = 3.8), FadeOut(cursor, run_time = 0.1) ) anim = AnimationGroup(anim, cursor_anim) override_wind = head(manual_wind_override) if override_wind != None: total_wind = override_wind else: total_wind = round(wind_so_far) if total_wind == 0: coords = [ rect.get_top_left(), rect.get_top_right(), rect.get_bottom_right(), rect.get_bottom_left() ] points = np.array([num_plane.coords_to_point(x, y) for (x, y) in coords]) + 3 * IN # TODO: Maybe use diagonal lines or something to fill in rectangles indicating # their "Nothing here" status? # Or draw a large X or something fill_rect = polygonObject = Polygon(*points, fill_opacity = 0.8, color = GREY_D) return EquationSolver2dNode(Succession(anim, FadeIn(fill_rect))) else: (sub_rect1, sub_rect2) = rect.splits_on_dim(dim_to_split) if dim_to_split == 0: sub_rect_and_sides = [(sub_rect1, 1), (sub_rect2, 3)] else: sub_rect_and_sides = [(sub_rect1, 2), (sub_rect2, 0)] children = [ Animate2dSolver( cur_depth = cur_depth + 1, rect = sub_rect, dim_to_split = 1 - dim_to_split, sides_to_draw = [side_to_draw], manual_wind_override = child(manual_wind_override, index) ) for (index, (sub_rect, side_to_draw)) in enumerate(sub_rect_and_sides) ] mid_line_coords = rect.split_line_on_dim(dim_to_split) mid_line_points = [num_plane.coords_to_point(x, y) + 2 * IN for (x, y) in mid_line_coords] mid_line = DashedLine(*mid_line_points) return EquationSolver2dNode(Succession(anim, ShowCreation(mid_line)), children) lower_x = self.initial_lower_x upper_x = self.initial_upper_x lower_y = self.initial_lower_y upper_y = self.initial_upper_y x_interval = (lower_x, upper_x) y_interval = (lower_y, upper_y) rect = RectangleData(x_interval, y_interval) print("Starting to compute anim") node = Animate2dSolver( cur_depth = 0, rect = rect, dim_to_split = 0, sides_to_draw = [], manual_wind_override = self.manual_wind_override ) print("Done computing anim") if self.display_in_parallel: anim = node.display_in_parallel() elif self.display_in_bfs: anim = node.display_in_bfs() else: anim = node.display_in_series() # Keep timing details here in sync with details above rect_points = [ rect.get_top_left(), rect.get_top_right(), rect.get_bottom_right(), rect.get_bottom_left(), ] border = Polygon(*[num_plane.coords_to_point(*x) + IN for x in rect_points]) match_style_with_bg(border, base_line) rect_time_without_linger = 4 * run_time_base rect_time_with_linger = 3 * run_time_base + run_time_with_lingering def rect_rate(alpha): time_in = alpha * rect_time_with_linger if time_in < 3 * run_time_base: return fdiv(time_in, 4 * run_time_base) else: time_in_last_leg = time_in - 3 * run_time_base alpha_in_last_leg = fdiv(time_in_last_leg, run_time_with_lingering) return interpolate(0.75, 1, linger_rate(alpha_in_last_leg)) border_anim = ShowCreation( border, run_time = rect_time_with_linger, rate_func = rect_rate ) print("About to do the big Play; for reference, the current time is ", time.strftime("%H:%M:%S")) if self.use_separate_plays: node.play_in_bfs(self, border_anim) else: self.play(anim, border_anim) print("All done; for reference, the current time is ", time.strftime("%H:%M:%S")) self.wait() # TODO: Perhaps have option for bullets (pulses) to fade out and in at ends of line, instead of # jarringly popping out and in? # # TODO: Perhaps have bullets change color corresponding to a function of their coordinates? # This could involve some merging of functoinality with PiWalker class LinePulser(ContinualAnimation): def __init__(self, line, bullet_template, num_bullets, pulse_time, output_func = None, **kwargs): self.line = line self.num_bullets = num_bullets self.pulse_time = pulse_time self.bullets = [bullet_template.copy() for i in range(num_bullets)] self.output_func = output_func ContinualAnimation.__init__(self, VGroup(*self.bullets), **kwargs) def update_mobject(self, dt): alpha = self.external_time % self.pulse_time start = self.line.get_start() end = self.line.get_end() for i in range(self.num_bullets): position = interpolate(start, end, fdiv((i + alpha),(self.num_bullets))) self.bullets[i].move_to(position) if self.output_func: position_2d = (position[0], position[1]) rev = point_to_rev(self.output_func(position_2d)) color = rev_to_color(rev) self.bullets[i].set_color(color) class ArrowCircleTest(Scene): def construct(self): circle_radius = 3 circle = Circle(radius = circle_radius, color = WHITE) self.add(circle) base_arrow = Arrow(circle_radius * 0.7 * RIGHT, circle_radius * 1.3 * RIGHT) def rev_rotate(x, revs): x.rotate(revs * TAU, about_point = ORIGIN) x.set_color(rev_to_color(revs)) return x num_arrows = 8 * 3 # 0.5 - fdiv below so as to get a clockwise rotation from left arrows = [rev_rotate(base_arrow.copy(), 0.5 - (fdiv(i, num_arrows))) for i in range(num_arrows)] arrows_vgroup = VGroup(*arrows) self.play(ShowCreation(arrows_vgroup), run_time = 2.5, rate_func=linear) self.wait() class FuncRotater(Animation): CONFIG = { "rev_func" : lambda x : x, # Func from alpha to CCW revolutions, } # Perhaps abstract this out into an "Animation updating from original object" class def interpolate_submobject(self, submobject, starting_submobject, alpha): submobject.set_points(starting_submobject.get_points()) def interpolate_mobject(self, alpha): Animation.interpolate_mobject(self, alpha) angle_revs = self.rev_func(alpha) self.mobject.rotate( angle_revs * TAU, about_point = ORIGIN ) self.mobject.set_color(rev_to_color(angle_revs)) class TestRotater(Scene): def construct(self): test_line = Line(ORIGIN, RIGHT) self.play(FuncRotater( test_line, rev_func = lambda x : x % 0.25, run_time = 10)) # TODO: Be careful about clockwise vs. counterclockwise convention throughout! # Make sure this is correct everywhere in resulting video. class OdometerScene(ColorMappedObjectsScene): CONFIG = { # "func" : lambda p : 100 * p # Full coloring, essentially "rotate_func" : lambda x : 2 * np.sin(2 * x * TAU), # This is given in terms of CW revs "run_time" : 40, "dashed_line_angle" : None, "biased_display_start" : None, "pure_odometer_background" : False } def construct(self): ColorMappedObjectsScene.construct(self) radius = ODOMETER_RADIUS circle = Circle(center = ORIGIN, radius = radius) circle.stroke_width = ODOMETER_STROKE_WIDTH circle.color_using_background_image(self.background_image_file) self.add(circle) if self.pure_odometer_background: # Just display this background circle, for compositing in Premiere with PiWalker odometers self.wait() return if self.dashed_line_angle: dashed_line = DashedLine(ORIGIN, radius * RIGHT) # Clockwise rotation dashed_line.rotate(-self.dashed_line_angle * TAU, about_point = ORIGIN) self.add(dashed_line) num_display = DecimalNumber(0, include_background_rectangle = False) num_display.move_to(2 * DOWN) caption = OldTexText("turns clockwise") caption.next_to(num_display, DOWN) self.add(caption) display_val_bias = 0 if self.biased_display_start != None: display_val_bias = self.biased_display_start - self.rotate_func(0) display_func = lambda alpha : self.rotate_func(alpha) + display_val_bias base_arrow = Arrow(ORIGIN, RIGHT, buff = 0) self.play( FuncRotater(base_arrow, rev_func = lambda x : -self.rotate_func(x)), ChangingDecimal(num_display, display_func), run_time = self.run_time, rate_func=linear) ############# # Above are mostly general tools; here, we list, in order, finished or near-finished scenes class FirstSqrtScene(EquationSolver1d): CONFIG = { "x_min" : 0, "x_max" : 2.5, "y_min" : 0, "y_max" : 2.5**2, "graph_origin" : 2.5*DOWN + 5.5*LEFT, "x_axis_width" : 12, "zoom_factor" : 3, "zoomed_canvas_center" : 2.25 * UP + 1.75 * LEFT, "func" : lambda x : x**2, "targetX" : np.sqrt(2), "targetY" : 2, "initial_lower_x" : 1, "initial_upper_x" : 2, "num_iterations" : 5, "iteration_at_which_to_start_zoom" : 3, "graph_label" : "y = x^2", "show_target_line" : True, "x_tick_frequency" : 0.25 } class TestFirstSqrtScene(FirstSqrtScene): CONFIG = { "num_iterations" : 1, } FirstSqrtSceneConfig = FirstSqrtScene.CONFIG shiftVal = FirstSqrtSceneConfig["targetY"] class SecondSqrtScene(FirstSqrtScene): CONFIG = { "graph_label" : FirstSqrtSceneConfig["graph_label"] + " - " + str(shiftVal), "show_y_as_deviation" : True, } class TestSecondSqrtScene(SecondSqrtScene): CONFIG = { "num_iterations" : 1 } class GuaranteedZeroScene(SecondSqrtScene): CONFIG = { # Manual config values, not automatically synced to anything above "initial_lower_x" : 1.75, "initial_upper_x" : 2 } class TestGuaranteedZeroScene(GuaranteedZeroScene): CONFIG = { "num_iterations" : 1 } # TODO: Pi creatures intrigued class RewriteEquation(Scene): def construct(self): # Can maybe use get_center() to perfectly center Groups before and after transform f_old = OldTex("f(x)") f_new = f_old.copy() equals_old = OldTex("=") equals_old_2 = equals_old.copy() equals_new = equals_old.copy() g_old = OldTex("g(x)") g_new = g_old.copy() minus_new = OldTex("-") zero_new = OldTex("0") f_old.next_to(equals_old, LEFT) g_old.next_to(equals_old, RIGHT) minus_new.next_to(g_new, LEFT) f_new.next_to(minus_new, LEFT) equals_new.next_to(g_new, RIGHT) zero_new.next_to(equals_new, RIGHT) # where_old = OldTexText("Where does ") # where_old.next_to(f_old, LEFT) # where_new = where_old.copy() # where_new.next_to(f_new, LEFT) # qmark_old = OldTexText("?") # qmark_old.next_to(g_old, RIGHT) # qmark_new = qmark_old.copy() # qmark_new.next_to(zero_new, RIGHT) self.add(f_old, equals_old, equals_old_2, g_old) #, where_old, qmark_old) self.wait() self.play( ReplacementTransform(f_old, f_new), ReplacementTransform(equals_old, equals_new), ReplacementTransform(g_old, g_new), ReplacementTransform(equals_old_2, minus_new), ShowCreation(zero_new), # ReplacementTransform(where_old, where_new), # ReplacementTransform(qmark_old, qmark_new), ) self.wait() class SignsExplanation(Scene): def construct(self): num_line = NumberLine() largest_num = 10 num_line.add_numbers(*list(range(-largest_num, largest_num + 1))) self.add(num_line) self.wait() pos_num = 3 neg_num = -pos_num pos_arrow = Arrow( num_line.number_to_point(0), num_line.number_to_point(pos_num), buff = 0, color = positive_color) neg_arrow = Arrow( num_line.number_to_point(0), num_line.number_to_point(neg_num), buff = 0, color = negative_color) plus_sign = OldTex("+", fill_color = positive_color) minus_sign = OldTex("-", fill_color = negative_color) plus_sign.next_to(pos_arrow, UP) minus_sign.next_to(neg_arrow, UP) #num_line.add_numbers(pos_num) self.play(ShowCreation(pos_arrow), FadeIn(plus_sign)) #num_line.add_numbers(neg_num) self.play(ShowCreation(neg_arrow), FadeIn(minus_sign)) class VectorField(Scene): CONFIG = { "func" : example_plane_func, "granularity" : 10, "arrow_scale_factor" : 0.1, "normalized_arrow_scale_factor" : 5 } def construct(self): num_plane = NumberPlane() self.add(num_plane) x_min, y_min = num_plane.point_to_coords(FRAME_X_RADIUS * LEFT + FRAME_Y_RADIUS * UP) x_max, y_max = num_plane.point_to_coords(FRAME_X_RADIUS * RIGHT + FRAME_Y_RADIUS * DOWN) x_points = np.linspace(x_min, x_max, self.granularity) y_points = np.linspace(y_min, y_max, self.granularity) points = it.product(x_points, y_points) sized_arrows = Group() unsized_arrows = Group() for (x, y) in points: output = self.func((x, y)) output_size = np.sqrt(sum(output**2)) normalized_output = output * fdiv(self.normalized_arrow_scale_factor, output_size) # Assume output has nonzero size here arrow = Vector(output * self.arrow_scale_factor) normalized_arrow = Vector(normalized_output * self.arrow_scale_factor) arrow.move_to(num_plane.coords_to_point(x, y)) normalized_arrow.move_to(arrow) sized_arrows.add(arrow) unsized_arrows.add(normalized_arrow) self.add(sized_arrows) self.wait() self.play(ReplacementTransform(sized_arrows, unsized_arrows)) self.wait() class HasItsLimitations(Scene): CONFIG = { "camera_config" : {"use_z_coordinate_for_display_order": True}, } def construct(self): num_line = NumberLine() num_line.add_numbers() self.add(num_line) self.wait() # We arrange to go from 2 to 4, a la the squaring in FirstSqrtScene base_point = num_line.number_to_point(2) + OUT dot_color = ORANGE DOT_Z = OUT # Note: This z-buffer value is needed for our static scenes, but is # not sufficient for everything, in that we still need to use # the foreground_mobjects trick during animations. # At some point, we should figure out how to have animations # play well with z coordinates. input_dot = Dot(base_point + DOT_Z, color = dot_color) input_label = OldTexText("Input", fill_color = dot_color) input_label.next_to(input_dot, UP + LEFT) input_label.add_background_rectangle() self.add_foreground_mobject(input_dot) self.add(input_label) curved_arrow = Arc(0, color = MAROON_E) curved_arrow.set_bound_angles(np.pi, 0) curved_arrow.init_points() curved_arrow.add_tip() curved_arrow.move_arc_center_to(base_point + RIGHT) # Could do something smoother, with arrowhead moving along partial arc? self.play(ShowCreation(curved_arrow)) output_dot = Dot(base_point + 2 * RIGHT + DOT_Z, color = dot_color) output_label = OldTexText("Output", fill_color = dot_color) output_label.next_to(output_dot, UP + RIGHT) output_label.add_background_rectangle() self.add_foreground_mobject(output_dot) self.add(output_label) self.wait() num_plane = NumberPlane() num_plane.add_coordinates() new_base_point = base_point + 2 * UP new_input_dot = input_dot.copy().move_to(new_base_point) new_input_label = input_label.copy().next_to(new_input_dot, UP + LEFT) new_curved_arrow = Arc(0).match_style(curved_arrow) new_curved_arrow.set_bound_angles(np.pi * 3/4, 0) new_curved_arrow.init_points() new_curved_arrow.add_tip() input_diff = input_dot.get_center() - curved_arrow.get_points()[0] output_diff = output_dot.get_center() - curved_arrow.get_points()[-1] new_curved_arrow.shift((new_input_dot.get_center() - new_curved_arrow.get_points()[0]) - input_diff) new_output_dot = output_dot.copy().move_to(new_curved_arrow.get_points()[-1] + output_diff) new_output_label = output_label.copy().next_to(new_output_dot, UP + RIGHT) dot_objects = Group(input_dot, input_label, output_dot, output_label, curved_arrow) new_dot_objects = Group(new_input_dot, new_input_label, new_output_dot, new_output_label, new_curved_arrow) self.play( FadeOut(num_line), FadeIn(num_plane), ReplacementTransform(dot_objects, new_dot_objects), ) self.wait() self.add_foreground_mobject(new_dot_objects) complex_plane = ComplexPlane() complex_plane.add_coordinates() # This looks a little wonky and we may wish to do a crossfade in Premiere instead self.play(FadeOut(num_plane), FadeIn(complex_plane)) self.wait() class ComplexPlaneIs2d(Scene): def construct(self): com_plane = ComplexPlane() self.add(com_plane) # TODO: Add labels to axes, specific complex points self.wait() class NumberLineScene(Scene): def construct(self): num_line = NumberLine() self.add(num_line) # TODO: Add labels, arrows, specific points self.wait() border_color = PURPLE_E inner_color = RED stroke_width = 10 left_point = num_line.number_to_point(-1) right_point = num_line.number_to_point(1) # TODO: Make this line a thin rectangle interval_1d = Line(left_point, right_point, stroke_color = inner_color, stroke_width = stroke_width) rect_1d = Rectangle(stroke_width = 0, fill_opacity = 1, fill_color = inner_color) rect_1d.replace(interval_1d) rect_1d.stretch_to_fit_height(SMALL_BUFF) left_dot = Dot(left_point, stroke_width = stroke_width, color = border_color) right_dot = Dot(right_point, stroke_width = stroke_width, color = border_color) endpoints_1d = VGroup(left_dot, right_dot) full_1d = VGroup(rect_1d, endpoints_1d) self.play(ShowCreation(full_1d)) self.wait() # TODO: Can polish the morphing above; have dots become left and right sides, and # only then fill in the top and bottom num_plane = NumberPlane() random_points = [UP + LEFT, UP + RIGHT, DOWN + RIGHT, DOWN + LEFT] border_2d = Polygon( *random_points, stroke_color = border_color, stroke_width = stroke_width) filling_2d = Polygon( *random_points, fill_color = inner_color, fill_opacity = 0.8, stroke_width = stroke_width) full_2d = VGroup(filling_2d, border_2d) self.play( FadeOut(num_line), FadeIn(num_plane), ReplacementTransform(full_1d, full_2d)) self.wait() class Initial2dFuncSceneBase(Scene): CONFIG = { "func" : point3d_func_from_complex_func(lambda c : c**2 - c**3/5 + 1) # We don't use example_plane_func because, unfortunately, the sort of examples # which are good for demonstrating our color mapping haven't turned out to be # good for visualizing in this manner; the gridlines run over themselves multiple # times in too confusing a fashion } def show_planes(self): print("Error! Unimplemented (pure virtual) show_planes") def shared_construct(self): points = [LEFT + DOWN, RIGHT + DOWN, LEFT + UP, RIGHT + UP] for i in range(len(points) - 1): line = Line(points[i], points[i + 1], color = RED) self.obj_draw(line) def wiggle_around(point): radius = 0.2 small_circle = cw_circle.copy() small_circle.scale(radius) small_circle.move_to(point + radius * RIGHT) small_circle.set_color(RED) self.obj_draw(small_circle) wiggle_around(points[-1]) def obj_draw(self, input_object): self.play(ShowCreation(input_object)) def construct(self): self.show_planes() self.shared_construct() # Alternative to the below, using MappingCameras, but no morphing animation class Initial2dFuncSceneWithoutMorphing(Initial2dFuncSceneBase): def setup(self): left_camera = Camera(**self.camera_config) right_camera = MappingCamera( mapping_func = self.func, **self.camera_config) split_screen_camera = SplitScreenCamera(left_camera, right_camera, **self.camera_config) self.camera = split_screen_camera def show_planes(self): self.num_plane = NumberPlane() self.num_plane.prepare_for_nonlinear_transform() #num_plane.fade() self.add(self.num_plane) # Alternative to the above, manually implementing split screen with a morphing animation class Initial2dFuncSceneMorphing(Initial2dFuncSceneBase): CONFIG = { "num_needed_anchor_curves" : 10, } def setup(self): split_line = DashedLine(FRAME_Y_RADIUS * UP, FRAME_Y_RADIUS * DOWN) self.num_plane = NumberPlane(x_radius = FRAME_X_RADIUS/2) self.num_plane.to_edge(LEFT, buff = 0) self.num_plane.prepare_for_nonlinear_transform() self.add(self.num_plane, split_line) def squash_onto_left(self, object): object.shift(FRAME_X_RADIUS/2 * LEFT) def squash_onto_right(self, object): object.shift(FRAME_X_RADIUS/2 * RIGHT) def obj_draw(self, input_object): output_object = input_object.copy() if input_object.get_num_curves() < self.num_needed_anchor_curves: input_object.insert_n_curves(self.num_needed_anchor_curves) output_object.apply_function(self.func) self.squash_onto_left(input_object) self.squash_onto_right(output_object) self.play( ShowCreation(input_object), ShowCreation(output_object) ) def show_planes(self): right_plane = self.num_plane.copy() right_plane.center() right_plane.prepare_for_nonlinear_transform() right_plane.apply_function(self.func) right_plane.shift(FRAME_X_RADIUS/2 * RIGHT) self.right_plane = right_plane crappy_cropper = FullScreenFadeRectangle(fill_opacity = 1) crappy_cropper.stretch_to_fit_width(FRAME_X_RADIUS) crappy_cropper.to_edge(LEFT, buff = 0) self.play( ReplacementTransform(self.num_plane.copy(), right_plane), FadeIn(crappy_cropper), Animation(self.num_plane), run_time = 3 ) class DemonstrateColorMapping(ColorMappedObjectsScene): CONFIG = { "show_num_plane" : False, "show_full_color_map" : True } def construct(self): ColorMappedObjectsScene.construct(self) # Doing this in Premiere now instead # output_plane_label = OldTexText("Output Plane", color = WHITE) # output_plane_label.move_to(3 * UP) # self.add_foreground_mobject(output_plane_label) if self.show_full_color_map: bright_background = Rectangle(width = 2 * FRAME_X_RADIUS + 1, height = 2 * FRAME_Y_RADIUS + 1, fill_opacity = 1) bright_background.color_using_background_image(self.background_image_file) dim_background = bright_background.copy() dim_background.fill_opacity = 0.3 background = bright_background.copy() self.add(background) self.wait() self.play(ReplacementTransform(background, dim_background)) self.wait() ray = Line(ORIGIN, 10 * LEFT) circle = cw_circle.copy() circle.color_using_background_image(self.background_image_file) self.play(ShowCreation(circle)) self.wait() scale_up_factor = 5 scale_down_factor = 20 self.play(ApplyMethod(circle.scale, fdiv(1, scale_down_factor))) self.play(ApplyMethod(circle.scale, scale_up_factor * scale_down_factor)) self.play(ApplyMethod(circle.scale, fdiv(1, scale_up_factor))) self.wait() self.remove(circle) ray = Line(ORIGIN, 10 * LEFT) ray.color_using_background_image(self.background_image_file) self.play(ShowCreation(ray)) self.wait() self.play(Rotating(ray, about_point = ORIGIN, radians = -TAU/2)) self.wait() self.play(Rotating(ray, about_point = ORIGIN, radians = -TAU/2)) self.wait() if self.show_full_color_map: self.play(ReplacementTransform(background, bright_background)) self.wait() # Everything in this is manually kept in sync with WindingNumber_G/TransitionFromPathsToBoundaries class LoopSplitScene(ColorMappedObjectsScene): CONFIG = { "func" : plane_func_by_wind_spec( (-2, 0, 2), (2, 0, 1) ), "use_fancy_lines" : True, } def PulsedLine(self, start, end, bullet_template, num_bullets = 4, pulse_time = 1, **kwargs): line = Line(start, end, color = WHITE, stroke_width = 4, **kwargs) if self.use_fancy_lines: line.color_using_background_image(self.background_image_file) anim = LinePulser( line = line, bullet_template = bullet_template, num_bullets = num_bullets, pulse_time = pulse_time, output_func = self.func, **kwargs) return (line, VMobject(*anim.bullets), anim) def construct(self): ColorMappedObjectsScene.construct(self) scale_factor = 2 shift_term = 0 # TODO: Change all this to use a wider than tall loop, made of two squares # Original loop tl = (UP + 2 * LEFT) * scale_factor tm = UP * scale_factor tr = (UP + 2 * RIGHT) * scale_factor bl = (DOWN + 2 * LEFT) * scale_factor bm = DOWN * scale_factor br = (DOWN + 2 * RIGHT) * scale_factor top_line = Line(tl, tr) # Invisible; only used for surrounding circle bottom_line = Line(br, bl) # Invisible; only used for surrounding circle stroke_width = top_line.stroke_width default_bullet = PiCreature() default_bullet.scale(0.15) def pl(a, b): return self.PulsedLine(a, b, default_bullet) def indicate_circle(x, double_horizontal_stretch = False): circle = Circle(color = WHITE, radius = 2 * np.sqrt(2)) circle.move_to(x.get_center()) if x.get_slope() == 0: circle.stretch(0.2, 1) if double_horizontal_stretch: circle.stretch(2, 0) else: circle.stretch(0.2, 0) return circle tl_line_trip = pl(tl, tm) midline_left_trip = pl(tm, bm) bl_line_trip = pl(bm, bl) left_line_trip = pl(bl, tl) left_square_trips = [tl_line_trip, midline_left_trip, bl_line_trip, left_line_trip] left_square_lines = [x[0] for x in left_square_trips] left_square_lines_vmobject = VMobject(*left_square_lines) left_square_bullets = [x[1] for x in left_square_trips] left_square_anims = [x[2] for x in left_square_trips] tr_line_trip = pl(tm, tr) right_line_trip = pl(tr, br) br_line_trip = pl(br, bm) midline_right_trip = pl(bm, tm) right_square_trips = [tr_line_trip, right_line_trip, br_line_trip, midline_right_trip] right_square_lines = [x[0] for x in right_square_trips] right_square_lines_vmobject = VMobject(*right_square_lines) right_square_bullets = [x[1] for x in right_square_trips] right_square_anims = [x[2] for x in right_square_trips] midline_trips = [midline_left_trip, midline_right_trip] midline_lines = [x[0] for x in midline_trips] midline_lines_vmobject = VMobject(*midline_lines) midline_bullets = [x[1] for x in midline_trips] midline_anims = [x[1] for x in midline_trips] left_line = left_line_trip[0] right_line = right_line_trip[0] for b in left_square_bullets + right_square_bullets: b.set_fill(opacity = 0) faded = 0.3 # Workaround for FadeOut/FadeIn not playing well with ContinualAnimations due to # Transforms making copies no longer identified with the ContinualAnimation's tracked mobject def bullet_fade(start, end, mob): return UpdateFromAlphaFunc(mob, lambda m, a : m.set_fill(opacity = interpolate(start, end, a))) def bullet_list_fade(start, end, bullet_list): return [bullet_fade(start, end, b) for b in bullet_list] def line_fade(start, end, mob): return UpdateFromAlphaFunc(mob, lambda m, a : m.set_stroke(width = interpolate(start, end, a) * stroke_width)) def play_combined_fade(start, end, lines_vmobject, bullets): self.play( line_fade(start, end, lines_vmobject), *bullet_list_fade(start, end, bullets) ) def play_fade_left(start, end): play_combined_fade(start, end, left_square_lines_vmobject, left_square_bullets) def play_fade_right(start, end): play_combined_fade(start, end, right_square_lines_vmobject, right_square_bullets) def play_fade_mid(start, end): play_combined_fade(start, end, midline_lines_vmobject, midline_bullets) def flash_circles(circles): self.play(LaggedStartMap(FadeIn, VGroup(circles))) self.wait() self.play(FadeOut(VGroup(circles))) self.wait() self.add(left_square_lines_vmobject, right_square_lines_vmobject) self.remove(*midline_lines) self.wait() self.play(ShowCreation(midline_lines[0])) self.add(midline_lines_vmobject) self.wait() self.add(*left_square_anims) self.play(line_fade(1, faded, right_square_lines_vmobject), *bullet_list_fade(0, 1, left_square_bullets)) self.wait() flash_circles([indicate_circle(l) for l in left_square_lines]) self.play(line_fade(faded, 1, right_square_lines_vmobject), *bullet_list_fade(1, 0, left_square_bullets)) self.wait() self.add(*right_square_anims) self.play(line_fade(1, faded, left_square_lines_vmobject), *bullet_list_fade(0, 1, right_square_bullets)) self.wait() flash_circles([indicate_circle(l) for l in right_square_lines]) self.play(line_fade(faded, 1, left_square_lines_vmobject), *bullet_list_fade(1, 0, right_square_bullets)) self.wait() self.play(*bullet_list_fade(0, 1, left_square_bullets + right_square_bullets)) self.wait() outside_circlers = [ indicate_circle(left_line), indicate_circle(right_line), indicate_circle(top_line, double_horizontal_stretch = True), indicate_circle(bottom_line, double_horizontal_stretch = True) ] flash_circles(outside_circlers) inner_circle = indicate_circle(midline_lines[0]) self.play(FadeIn(inner_circle)) self.wait() self.play(FadeOut(inner_circle), line_fade(1, 0, midline_lines_vmobject), *bullet_list_fade(1, 0, midline_bullets)) self.wait() # Repeat for effect, goes well with narration self.play(FadeIn(inner_circle), line_fade(0, 1, midline_lines_vmobject), *bullet_list_fade(0, 1, midline_bullets)) self.wait() self.play(FadeOut(inner_circle), line_fade(1, 0, midline_lines_vmobject), *bullet_list_fade(1, 0, midline_bullets)) self.wait() # TODO: Perhaps do extra illustration of zooming out and winding around a large circle, # to illustrate relation between degree and large-scale winding number class FundThmAlg(EquationSolver2d): CONFIG = { "func" : plane_func_by_wind_spec((1, 2), (-1, 1.5), (-1, 1.5)), "num_iterations" : 2, } class SolveX5MinusXMinus1(EquationSolver2d): CONFIG = { "func" : plane_func_from_complex_func(lambda c : c**5 - c - 1), "num_iterations" : 10, "show_cursor" : True, "display_in_bfs" : True, } class PureColorMapOfX5Thing(PureColorMap): CONFIG = { "func" : plane_func_from_complex_func(lambda c : c**5 - c - 1), } class X5ThingWithRightHalfGreyed(SolveX5MinusXMinus1): CONFIG = { "num_iterations" : 3, "manual_wind_override" : (1, None, (1, (0, None, None), (0, None, None))) } class SolveX5MinusXMinus1_5Iterations(EquationSolver2d): CONFIG = { "func" : plane_func_from_complex_func(lambda c : c**5 - c - 1), "num_iterations" : 5, "show_cursor" : True, "display_in_bfs" : True, "manual_wind_override" : (None, None, (None, (0, None, None), (0, None, None))) } class X5_Monster_Red_Lines(SolveX5MinusXMinus1_5Iterations): CONFIG = { "use_separate_plays" : True, "use_fancy_lines" : False, "line_color" : RED, } class X5_Monster_Green_Lines(X5_Monster_Red_Lines): CONFIG = { "line_color" : GREEN, } class X5_Monster_Red_Lines_Long(X5_Monster_Red_Lines): CONFIG = { "num_iterations" : 6 } class X5_Monster_Green_Lines_Long(X5_Monster_Green_Lines): CONFIG = { "num_iterations" : 6 } class X5_Monster_Red_Lines_Little_More(X5_Monster_Red_Lines_Long): CONFIG = { "num_iterations" : 7 } class X5_Monster_Green_Lines_Little_More(X5_Monster_Green_Lines_Long): CONFIG = { "num_iterations" : 7 } class X5_Monster_Red_Lines_No_Numbers(X5_Monster_Red_Lines): CONFIG = { "num_iterations" : 3, "show_winding_numbers" : False, } class X5_Monster_Green_Lines_No_Numbers(X5_Monster_Green_Lines): CONFIG = { "num_iterations" : 3, "show_winding_numbers" : False, } class SolveX5MinusXMinus1_3Iterations(EquationSolver2d): CONFIG = { "func" : plane_func_from_complex_func(lambda c : c**5 - c - 1), "num_iterations" : 3, "show_cursor" : True, "display_in_bfs" : True, } class Diagnostic(SolveX5MinusXMinus1_3Iterations): CONFIG = { # I think the combination of these two makes things slow "use_separate_plays" : not False, # This one isn't important to set any particular way, so let's leave it like this "use_fancy_lines" : True, # This causes a small slowdown (before rendering, in particular), but not the big one, I think "show_winding_numbers" : True, # This doesn't significantly matter for rendering time, I think "camera_config" : {"use_z_coordinate_for_display_order" : True} } # All above flags False (meaning not db = False): just under 30 it/s # not db = True: 30 # use_fancy_lines = True: 30 at first (if scene.play(bfs_nodes[0].first_anim, border_anim is off), but then drops to 3 (or drops right away if that simultaneous play is on) # use_z_coordinate = True: 30 # show_winding_numbers = True: 10 # winding AND use_fancy_lines: 10 # not db AND fancy_lines AND z_coords = true, winding = false: 3. Not 30, but 3. Slow. # db AND use_fancy: 3. Slow. # fancy AND z_coords: 30. Fast. [Hm, this may have been a mistake; fancy and z_coords is now slow?] # fancy, winding, AND z_coords, but not (not db): 10 # not db, winding, AND z_coords, but not fancy: 10 # class DiagnosticB(Diagnostic): # CONFIG = { # "num_iterations" : 3, # #"num_checkpoints" : 100, # #"show_winding_numbers" : False, # #"use_cheap_winding_numbers" : True, # } class SolveX5MinusXMinus1Parallel(SolveX5MinusXMinus1): CONFIG = { "display_in_parallel" : True } class SolveX5MinusXMinus1BFS(SolveX5MinusXMinus1): CONFIG = { "display_in_bfs" : True } class PreviewClip(EquationSolver2d): CONFIG = { "func" : example_plane_func, "num_iterations" : 5, "display_in_parallel" : True, "use_fancy_lines" : True, } class ParallelClip(EquationSolver2d): CONFIG = { "func" : plane_func_by_wind_spec( (-3, -1.3, 2), (0.1, 0.2, 1), (2.8, -2, 1) ), "num_iterations" : 5, "display_in_parallel" : True, } class EquationSolver2dMatchBreakdown(EquationSolver2d): CONFIG = { "func" : plane_func_by_wind_spec( (-2, 0.3, 2), (2, -0.2, 1) # Not an exact match, because our breakdown function has a zero along midlines... ), "num_iterations" : 5, "display_in_parallel" : True, "show_cursor" : True } class EquationSolver2dMatchBreakdown_parallel(EquationSolver2dMatchBreakdown): CONFIG = { "display_in_parallel" : True, "display_in_bfs" : False, } class EquationSolver2dMatchBreakdown_bfs(EquationSolver2dMatchBreakdown): CONFIG = { "display_in_parallel" : False, "display_in_bfs" : True, } class QuickPreview(PreviewClip): CONFIG = { "num_iterations" : 3, "display_in_parallel" : False, "display_in_bfs" : True, "show_cursor" : True } class LongEquationSolver(EquationSolver2d): CONFIG = { "func" : example_plane_func, "num_iterations" : 10, "display_in_bfs" : True, "linger_parameter" : 0.4, "show_cursor" : True, } class QuickPreviewUnfancy(LongEquationSolver): CONFIG = { # "use_fancy_lines" : False, } # TODO: Borsuk-Ulam visuals # Note: May want to do an ordinary square scene, then MappingCamera it into a circle # class BorsukUlamScene(PiWalker): # 3-way scene of "Good enough"-illustrating odometers; to be composed in Premiere left_func = lambda x : x**2 - x + 1 diff_func = lambda x : np.cos(1.4 * (x - 0.1) * (np.log(x + 0.1) - 0.3) * TAU)/2.1 class LeftOdometer(OdometerScene): CONFIG = { "rotate_func" : left_func, "biased_display_start" : 0 } class RightOdometer(OdometerScene): CONFIG = { "rotate_func" : lambda x : left_func(x) + diff_func(x), "biased_display_start" : 0 } class DiffOdometer(OdometerScene): CONFIG = { "rotate_func" : diff_func, "dashed_line_angle" : 0.5, "biased_display_start" : 0 } class CombineInterval(Scene): def construct(self): plus_sign = OldTex("+", fill_color = positive_color) minus_sign = OldTex("-", fill_color = negative_color) left_point = Dot(LEFT, color = positive_color) right_point = Dot(RIGHT, color = negative_color) line1 = Line(LEFT, RIGHT) interval1 = Group(line1, left_point, right_point) plus_sign.next_to(left_point, UP) minus_sign.next_to(right_point, UP) self.add(interval1, plus_sign, minus_sign) self.wait() self.play( CircleIndicate(plus_sign), CircleIndicate(minus_sign), ) self.wait() mid_point = Dot(ORIGIN, color = GREY) question_mark = OldTex("?", fill_color = GREY) plus_sign_copy = plus_sign.copy() minus_sign_copy = minus_sign.copy() new_signs = Group(question_mark, plus_sign_copy, minus_sign_copy) for sign in new_signs: sign.next_to(mid_point, UP) self.play(FadeIn(mid_point), FadeIn(question_mark)) self.wait() self.play( ApplyMethod(mid_point.set_color, positive_color), ReplacementTransform(question_mark, plus_sign_copy), ) self.play( CircleIndicate(plus_sign_copy), CircleIndicate(minus_sign), ) self.wait() self.play( ApplyMethod(mid_point.set_color, negative_color), ReplacementTransform(plus_sign_copy, minus_sign_copy), ) self.play( CircleIndicate(minus_sign_copy), CircleIndicate(plus_sign), ) self.wait() class CombineInterval2(Scene): def construct(self): plus_sign = OldTex("+", fill_color = positive_color) def make_interval(a, b): line = Line(a, b) start_dot = Dot(a, color = positive_color) end_dot = Dot(b, color = positive_color) start_sign = plus_sign.copy().next_to(start_dot, UP) end_sign = plus_sign.copy().next_to(end_dot, UP) return Group(start_sign, end_sign, line, start_dot, end_dot) def pair_indicate(a, b): self.play( CircleIndicate(a), CircleIndicate(b) ) left_interval = make_interval(2 * LEFT, LEFT) right_interval = make_interval(RIGHT, 2 * RIGHT) self.play(FadeIn(left_interval), FadeIn(right_interval)) pair_indicate(left_interval[0], left_interval[1]) pair_indicate(right_interval[0], right_interval[1]) self.play( ApplyMethod(left_interval.shift, RIGHT), ApplyMethod(right_interval.shift, LEFT), ) pair_indicate(left_interval[0], right_interval[1]) self.wait() tiny_loop_func = scale_func(plane_func_by_wind_spec((-1, -2), (1, 1), (1, 1)), 0.3) class TinyLoopScene(ColorMappedByFuncScene): CONFIG = { "func" : tiny_loop_func, "show_num_plane" : False, "loop_point" : ORIGIN, "circle_scale" : 0.7 } def construct(self): ColorMappedByFuncScene.construct(self) circle = cw_circle.copy() circle.scale(self.circle_scale) circle.move_to(self.loop_point) self.play(ShowCreation(circle)) self.wait() class TinyLoopInInputPlaneAroundNonZero(TinyLoopScene): CONFIG = { "loop_point" : 0.5 * RIGHT } class TinyLoopInInputPlaneAroundZero(TinyLoopScene): CONFIG = { "loop_point" : UP + RIGHT } class TinyLoopInOutputPlaneAroundNonZero(TinyLoopInInputPlaneAroundNonZero): CONFIG = { "camera_class" : MappingCamera, "camera_config" : {"mapping_func" : point3d_func_from_plane_func(tiny_loop_func)}, "show_output" : True, "show_num_plane" : False, } class TinyLoopInOutputPlaneAroundZero(TinyLoopInInputPlaneAroundZero): CONFIG = { "camera_class" : MappingCamera, "camera_config" : {"mapping_func" : point3d_func_from_plane_func(tiny_loop_func)}, "show_output" : True, "show_num_plane" : False, } class BorderOf2dRegionScene(Scene): def construct(self): num_plane = NumberPlane() self.add(num_plane) points = standard_rect + 1.5 * UP + 2 * RIGHT interior = Polygon(*points, fill_color = neutral_color, fill_opacity = 1, stroke_width = 0) self.play(FadeIn(interior)) border = Polygon(*points, color = negative_color, stroke_width = border_stroke_width) self.play(ShowCreation(border)) big_loop_no_zeros_func = lambda x_y5 : complex_to_pair(np.exp(complex(10, x_y5[1] * np.pi))) class BigLoopNoZeros(ColorMappedObjectsScene): CONFIG = { "func" : big_loop_no_zeros_func } def construct(self): ColorMappedObjectsScene.construct(self) points = 3 * np.array([UL, UR, DR, DL]) polygon = Polygon(*points) polygon.color_using_background_image(self.background_image_file) self.play(ShowCreation(polygon)) self.wait() polygon2 = polygon.copy() polygon2.fill_opacity = 1 self.play(FadeIn(polygon2)) self.wait() class ExamplePlaneFunc(ColorMappedByFuncScene): CONFIG = { "show_num_plane" : False, "func" : example_plane_func } def construct(self): ColorMappedByFuncScene.construct(self) radius = 0.5 def circle_point(point): circle = cw_circle.copy().scale(radius).move_to(point) self.play(ShowCreation(circle)) return circle def circle_spec(spec): point = spec[0] * RIGHT + spec[1] * UP return circle_point(point) nonzero_point = ORIGIN # Manually chosen, not auto-synced with example_plane_func nonzero_point_circle = circle_point(nonzero_point) self.wait() self.play(FadeOut(nonzero_point_circle)) self.wait() zero_circles = Group() for spec in example_plane_func_spec: zero_circles.add(circle_spec(spec)) self.wait() # TODO: Fix the code in Fade to automatically propagate correctly # to subobjects, even with special vectorized object handler. # Also, remove the special handling from FadeOut, have it implemented # solely through Fade. # # But for now, I'll just take care of this stuff myself here. # self.play(*[FadeOut(zero_circle) for zero_circle in zero_circles]) self.play(FadeOut(zero_circles)) self.wait() # We can reuse our nonzero point from before for "Output doesn't go through ever color" # Do re-use in Premiere # We can also re-use the first of our zero-circles for "Output does go through every color", # but just in case it would be useful, here's another one, all on its own specific_spec_index = 0 temp_circle = circle_spec(example_plane_func_spec[specific_spec_index]) self.play(FadeOut(temp_circle)) self.wait() class PiWalkerExamplePlaneFunc(PiWalkerRect): CONFIG = { "show_num_plane" : False, "func" : example_plane_func, # These are just manually entered, not # automatically kept in sync with example_plane_func: "start_x" : -4, "start_y" : 3, "walk_width" : 8, "walk_height" : 6, } class NoticeHowOnThisLoop(PiWalkerRect): CONFIG = { "show_num_plane" : False, "func" : example_plane_func, # These are just manually entered, not # automatically kept in sync with example_plane_func: "start_x" : 0.5, "start_y" : -0.5, "walk_width" : -1, # We trace from bottom-right clockwise on this one, to start at a red point "walk_height" : -1, } class ButOnThisLoopOverHere(NoticeHowOnThisLoop): CONFIG = { # These are just manually entered, not # automatically kept in sync with example_plane_func: "start_x" : -1, "start_y" : 0, "walk_width" : 1, "walk_height" : 1, } class PiWalkerExamplePlaneFuncWithScaling(PiWalkerExamplePlaneFunc): CONFIG = { "scale_arrows" : True, "display_size" : True, } class TinyLoopOfBasicallySameColor(PureColorMap): def construct(self): PureColorMap.construct(self) radius = 0.5 circle = cw_circle.copy().scale(radius).move_to(UP + RIGHT) self.play(ShowCreation(circle)) self.wait() def uhOhFunc(xxx_todo_changeme11): (x, y) = xxx_todo_changeme11 x = -np.clip(x, -5, 5)/5 y = -np.clip(y, -3, 3)/3 alpha = 0.5 # Most things will return green # These next three things should really be abstracted into some "Interpolated triangle" function if x >= 0 and y >= x and y <= 1: alpha = interpolate(0.5, 1, y - x) if x < 0 and y >= -2 * x and y <= 1: alpha = interpolate(0.5, 1, y + 2 * x) if x >= -1 and y >= 2 * (x + 1) and y <= 1: alpha = interpolate(0.5, 0, y - 2 * (x + 1)) return complex_to_pair(100 * np.exp(complex(0, TAU * (0.5 - alpha)))) class UhOhFuncTest(PureColorMap): CONFIG = { "func" : uhOhFunc } class UhOhScene(EquationSolver2d): CONFIG = { "func" : uhOhFunc, "manual_wind_override" : (1, None, (1, None, (1, None, None))), # Tailored to UhOhFunc above "show_winding_numbers" : False, "num_iterations" : 5, } class UhOhSceneWithWindingNumbers(UhOhScene): CONFIG = { "show_winding_numbers" : True, } class UhOhSceneWithWindingNumbersNoOverride(UhOhSceneWithWindingNumbers): CONFIG = { "manual_wind_override" : None, "num_iterations" : 2 } class UhOhSalientStill(ColorMappedObjectsScene): CONFIG = { "func" : uhOhFunc } def construct(self): ColorMappedObjectsScene.construct(self) new_up = 3 * UP new_left = 5 * LEFT thin_line = Line(UP, RIGHT, color = WHITE) main_points = [new_left + new_up, new_up, ORIGIN, new_left] polygon = Polygon(*main_points, stroke_width = border_stroke_width) thin_polygon = polygon.copy().match_style(thin_line) polygon.color_using_background_image(self.background_image_file) midline = Line(new_up + 0.5 * new_left, 0.5 * new_left, stroke_width = border_stroke_width) thin_midline = midline.copy().match_style(thin_line) midline.color_using_background_image(self.background_image_file) self.add(polygon, midline) self.wait() everything_filler = FullScreenFadeRectangle(fill_opacity = 1) everything_filler.color_using_background_image(self.background_image_file) thin_white_copy = Group(thin_polygon, thin_midline) self.play(FadeIn(everything_filler), FadeIn(thin_white_copy)) self.wait() # TODO: Brouwer's fixed point theorem visuals # class BFTScene(Scene): # TODO: Pi creatures wide-eyed in amazement ################# # TODOs, from easiest to hardest: # Minor fiddling with little things in each animation; placements, colors, timing, text # Initial odometer scene (simple once previous Pi walker scene is decided upon) # Writing new Pi walker scenes by parametrizing general template # (All the above are basically trivial tinkering at this point) # ---- # Pi creature emotion stuff # BFT visuals # Borsuk-Ulam visuals #################### # Random test scenes and test functions go here: def rect_to_circle(xxx_todo_changeme12): (x, y, z) = xxx_todo_changeme12 size = np.sqrt(x**2 + y**2) max_abs_size = max(abs(x), abs(y)) return fdiv(np.array((x, y, z)) * max_abs_size, size) class MapPiWalkerRect(PiWalkerRect): CONFIG = { "camera_class" : MappingCamera, "camera_config" : {"mapping_func" : rect_to_circle}, "show_output" : True } class ShowBack(PiWalkerRect): CONFIG = { "func" : plane_func_by_wind_spec((1, 2), (-1, 1.5), (-1, 1.5)) } class PiWalkerOdometerTest(PiWalkerExamplePlaneFunc): CONFIG = { "display_odometer" : True } class PiWalkerFancyLineTest(PiWalkerExamplePlaneFunc): CONFIG = { "color_foreground_not_background" : True } class NotFoundScene(Scene): def construct(self): self.add(OldTexText("SCENE NOT FOUND!")) self.wait() criticalStripYScale = 100 criticalStrip = Axes(x_min = -0.5, x_max = 1.5, x_axis_config = {"unit_size" : FRAME_X_RADIUS, "number_at_center" : 0.5}, y_min = -criticalStripYScale, y_max = criticalStripYScale, y_axis_config = {"unit_size" : fdiv(FRAME_Y_RADIUS, criticalStripYScale)}) class ZetaViz(PureColorMap): CONFIG = { "func" : plane_zeta, #"num_plane" : criticalStrip, "show_num_plane" : True } class TopLabel(Scene): CONFIG = { "text" : "Text" } def construct(self): label = OldTexText(self.text) label.move_to(3 * UP) self.add(label) self.wait() # This is a giant hack that doesn't handle rev wrap-around correctly; should use # make_alpha_winder instead class SpecifiedWinder(PiWalker): CONFIG = { "start_x" : 0, "start_y" : 0, "x_wind" : 1, # Assumed positive "y_wind" : 1, # Assumed positive "step_size" : 0.1 } def setup(self): rev_func = lambda p : point_to_rev(self.func(p)) start_pos = np.array((self.start_x, self.start_y)) cur_pos = start_pos.copy() start_rev = rev_func(start_pos) mid_rev = start_rev while (abs(mid_rev - start_rev) < self.x_wind): cur_pos += (self.step_size, 0) mid_rev = rev_func(cur_pos) print("Reached ", cur_pos, ", with rev ", mid_rev - start_rev) mid_pos = cur_pos.copy() end_rev = mid_rev while (abs(end_rev - mid_rev) < self.y_wind): cur_pos -= (0, self.step_size) end_rev = rev_func(cur_pos) end_pos = cur_pos.copy() print("Reached ", cur_pos, ", with rev ", end_rev - mid_rev) self.walk_coords = [start_pos, mid_pos, end_pos] print("Walk coords: ", self.walk_coords) PiWalker.setup(self) class OneFifthTwoFifthWinder(SpecifiedWinder): CONFIG = { "func" : example_plane_func, "start_x" : -2.0, "start_y" : 1.0, "x_wind" : 0.2, "y_wind" : 0.2, "step_size" : 0.01, "show_num_plane" : False, "step_run_time" : 6, "num_decimal_places" : 2, } class OneFifthOneFifthWinderWithReset(OneFifthTwoFifthWinder): CONFIG = { "wind_reset_indices" : [1] } class OneFifthTwoFifthWinderOdometer(OneFifthTwoFifthWinder): CONFIG = { "display_odometer" : True, } class ForwardBackWalker(PiWalker): CONFIG = { "func" : example_plane_func, "walk_coords" : [np.array((-2, 1)), np.array((1, 1))], "step_run_time" : 3, } class ForwardBackWalkerOdometer(ForwardBackWalker): CONFIG = { "display_odometer" : True, } class PureOdometerBackground(OdometerScene): CONFIG = { "pure_odometer_background" : True } class CWColorWalk(PiWalkerRect): CONFIG = { "func" : example_plane_func, "start_x" : example_plane_func_spec[0][0] - 1, "start_y" : example_plane_func_spec[0][1] + 1, "walk_width" : 2, "walk_height" : 2, "draw_lines" : False, "display_wind" : False, "step_run_time" : 2 } class CWColorWalkOdometer(CWColorWalk): CONFIG = { "display_odometer" : True, } class CCWColorWalk(CWColorWalk): CONFIG = { "start_x" : example_plane_func_spec[2][0] - 1, "start_y" : example_plane_func_spec[2][1] + 1, } class CCWColorWalkOdometer(CCWColorWalk): CONFIG = { "display_odometer" : True, } class ThreeTurnWalker(PiWalkerRect): CONFIG = { "func" : plane_func_from_complex_func(lambda c: c**3 * complex(1, 1)**3), "double_up" : True, "wind_reset_indices" : [4] } class ThreeTurnWalkerOdometer(ThreeTurnWalker): CONFIG = { "display_odometer" : True, } class FourTurnWalker(PiWalkerRect): CONFIG = { "func" : plane_func_by_wind_spec((0, 0, 4)) } class FourTurnWalkerOdometer(FourTurnWalker): CONFIG = { "display_odometer" : True, } class OneTurnWalker(PiWalkerRect): CONFIG = { "func" : plane_func_from_complex_func(lambda c : np.exp(c) + c) } class OneTurnWalkerOdometer(OneTurnWalker): CONFIG = { "display_odometer" : True, } class ZeroTurnWalker(PiWalkerRect): CONFIG = { "func" : plane_func_by_wind_spec((2, 2, 1), (-1, 2, -1)) } class ZeroTurnWalkerOdometer(ZeroTurnWalker): CONFIG = { "display_odometer" : True, } class NegOneTurnWalker(PiWalkerRect): CONFIG = { "step_run_time" : 2, "func" : plane_func_by_wind_spec((0, 0, -1)) } class NegOneTurnWalkerOdometer(NegOneTurnWalker): CONFIG = { "display_odometer" : True, } # FIN
# -*- coding: utf-8 -*- import scipy from manim_imports_ext import * from _2018.fourier import * import warnings warnings.warn(""" Warning: This file makes use of ContinualAnimation, which has since been deprecated """) FREQUENCY_COLOR = RED USE_ALMOST_FOURIER_BY_DEFAULT = False class GaussianDistributionWrapper(Line): """ This is meant to encode a 2d normal distribution as a mobject (so as to be able to have it be interpolated during animations). It is a line whose center is the mean mu of a distribution, and whose radial vector (center to end) is the distribution's standard deviation """ CONFIG = { "stroke_width" : 0, "mu" : ORIGIN, "sigma" : RIGHT, } def __init__(self, **kwargs): Line.__init__(self, ORIGIN, RIGHT, **kwargs) self.change_parameters(self.mu, self.sigma) def change_parameters(self, mu = None, sigma = None): curr_mu, curr_sigma = self.get_parameters() mu = mu if mu is not None else curr_mu sigma = sigma if sigma is not None else curr_sigma self.put_start_and_end_on(mu - sigma, mu + sigma) return self def get_parameters(self): """ Return mu_x, mu_y, sigma_x, sigma_y""" center, end = self.get_center(), self.get_end() return center, end-center def get_random_points(self, size = 1): mu, sigma = self.get_parameters() return np.array([ np.array([ np.random.normal(mu_coord, sigma_coord) for mu_coord, sigma_coord in zip(mu, sigma) ]) for x in range(size) ]) class ProbabalisticMobjectCloud(ContinualAnimation): CONFIG = { "fill_opacity" : 0.25, "n_copies" : 100, "gaussian_distribution_wrapper_config" : {}, "time_per_change" : 1./60, "start_up_time" : 0, } def __init__(self, prototype, **kwargs): digest_config(self, kwargs) fill_opacity = self.fill_opacity or prototype.get_fill_opacity() if "mu" not in self.gaussian_distribution_wrapper_config: self.gaussian_distribution_wrapper_config["mu"] = prototype.get_center() self.gaussian_distribution_wrapper = GaussianDistributionWrapper( **self.gaussian_distribution_wrapper_config ) self.time_since_last_change = np.inf group = VGroup(*[ prototype.copy().set_fill(opacity = fill_opacity) for x in range(self.n_copies) ]) ContinualAnimation.__init__(self, group, **kwargs) self.update_mobject(0) def update_mobject(self, dt): self.time_since_last_change += dt if self.time_since_last_change < self.time_per_change: return self.time_since_last_change = 0 group = self.mobject points = self.gaussian_distribution_wrapper.get_random_points(len(group)) for mob, point in zip(group, points): self.update_mobject_by_point(mob, point) return self def update_mobject_by_point(self, mobject, point): mobject.move_to(point) return self class ProbabalisticDotCloud(ProbabalisticMobjectCloud): CONFIG = { "color" : BLUE, } def __init__(self, **kwargs): digest_config(self, kwargs) dot = Dot(color = self.color) ProbabalisticMobjectCloud.__init__(self, dot) class ProbabalisticVectorCloud(ProbabalisticMobjectCloud): CONFIG = { "color" : RED, "n_copies" : 20, "fill_opacity" : 0.5, "center_func" : lambda : ORIGIN, } def __init__(self, **kwargs): digest_config(self, kwargs) vector = Vector( RIGHT, color = self.color, max_tip_length_to_length_ratio = 1, ) ProbabalisticMobjectCloud.__init__(self, vector) def update_mobject_by_point(self, vector, point): vector.put_start_and_end_on( self.center_func(), point ) class RadarDish(SVGMobject): CONFIG = { "file_name" : "radar_dish", "fill_color" : GREY_B, "stroke_color" : WHITE, "stroke_width" : 1, "height" : 1, } class Plane(SVGMobject): CONFIG = { "file_name" : "plane", "color" : GREY_B, "height" : 1, } def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) self.rotate(-TAU/4) class FalconHeavy(SVGMobject): CONFIG = { "file_name" : "falcon_heavy", "color" : WHITE, "logo_color" : BLUE_E, "height" : 1.5, } def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) self.logo = self[-9:] self.logo.set_color(self.logo_color) class RadarPulseSingleton(ContinualAnimation): CONFIG = { "speed" : 3.0, "direction" : RIGHT, "start_up_time" : 0, "fade_in_time" : 0.5, "color" : WHITE, "stroke_width" : 3, } def __init__(self, radar_dish, target, **kwargs): digest_config(self, kwargs) self.direction = self.direction/get_norm(self.direction) self.radar_dish = radar_dish self.target = target self.reflection_distance = None self.arc = Arc( start_angle = -30*DEGREES, angle = 60*DEGREES, ) self.arc.set_height(0.75*radar_dish.get_height()) self.arc.move_to(radar_dish, UP+RIGHT) self.start_points = np.array(self.arc.get_points()) self.start_center = self.arc.get_center() self.finished = False ContinualAnimation.__init__(self, self.arc, **kwargs) def update_mobject(self, dt): arc = self.arc total_distance = self.speed*self.internal_time arc.set_points(self.start_points) arc.shift(total_distance*self.direction) if self.internal_time < self.fade_in_time: alpha = np.clip(self.internal_time/self.fade_in_time, 0, 1) arc.set_stroke(self.color, alpha*self.stroke_width) if self.reflection_distance is None: #Check if reflection is happening arc_point = arc.get_edge_center(self.direction) target_point = self.target.get_edge_center(-self.direction) arc_distance = np.dot(arc_point, self.direction) target_distance = np.dot(target_point, self.direction) if arc_distance > target_distance: self.reflection_distance = target_distance #Don't use elif in case the above code creates reflection_distance if self.reflection_distance is not None: delta_distance = total_distance - self.reflection_distance point_distances = np.dot(self.direction, arc.get_points().T) diffs = point_distances - self.reflection_distance shift_vals = np.outer(-2*np.maximum(diffs, 0), self.direction) arc.set_points(arc.get_points() + shift_vals) #Check if done arc_point = arc.get_edge_center(-self.direction) if np.dot(arc_point, self.direction) < np.dot(self.start_center, self.direction): self.finished = True self.arc.fade(1) def is_finished(self): return self.finished class RadarPulse(ContinualAnimation): CONFIG = { "n_pulse_singletons" : 8, "frequency" : 0.05, "colors" : [BLUE, YELLOW] } def __init__(self, *args, **kwargs): digest_config(self, kwargs) colors = color_gradient(self.colors, self.n_pulse_singletons) self.pulse_singletons = [ RadarPulseSingleton(*args, color = color, **kwargs) for color in colors ] pluse_mobjects = VGroup(*[ps.mobject for ps in self.pulse_singletons]) ContinualAnimation.__init__(self, pluse_mobjects, **kwargs) def update_mobject(self, dt): for i, ps in enumerate(self.pulse_singletons): ps.internal_time = self.internal_time - i*self.frequency ps.update_mobject(dt) def is_finished(self): return all([ps.is_finished() for ps in self.pulse_singletons]) class MultipleFlashes(Succession): CONFIG = { "run_time_per_flash" : 1.0, "num_flashes" : 3, } def __init__(self, *args, **kwargs): digest_config(self, kwargs) kwargs["run_time"] = self.run_time_per_flash Succession.__init__(self, *[ Flash(*args, **kwargs) for x in range(self.num_flashes) ]) class TrafficLight(SVGMobject): CONFIG = { "file_name" : "traffic_light", "height" : 0.7, "post_height" : 2, "post_width" : 0.05, } def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) post = Rectangle( height = self.post_height, width = self.post_width, stroke_width = 0, fill_color = WHITE, fill_opacity = 1, ) self.move_to(post.get_top(), DOWN) self.add_to_back(post) ################### class MentionUncertaintyPrinciple(TeacherStudentsScene): def construct(self): title = OldTexText("Heisenberg Uncertainty Principle") title.to_edge(UP) dot_cloud = ProbabalisticDotCloud() vector_cloud = ProbabalisticVectorCloud( gaussian_distribution_wrapper_config = {"sigma_x" : 0.2}, center_func = lambda : dot_cloud.gaussian_distribution_wrapper.get_parameters()[0], ) for cloud in dot_cloud, vector_cloud: cloud.gaussian_distribution_wrapper.next_to( title, DOWN, 2*LARGE_BUFF ) vector_cloud.gaussian_distribution_wrapper.shift(3*RIGHT) def get_brace_text_group_update(gdw, vect, text, color): brace = Brace(gdw, vect) text = brace.get_tex("2\\sigma_{\\text{%s}}"%text, buff = SMALL_BUFF) group = VGroup(brace, text) def update_group(group): brace, text = group brace.match_width(gdw, stretch = True) brace.next_to(gdw, vect) text.next_to(brace, vect, buff = SMALL_BUFF) group.set_color(color) return Mobject.add_updater(group, update_group) dot_brace_anim = get_brace_text_group_update( dot_cloud.gaussian_distribution_wrapper, DOWN, "position", dot_cloud.color ) vector_brace_anim = get_brace_text_group_update( vector_cloud.gaussian_distribution_wrapper, UP, "momentum", vector_cloud.color ) self.add(title) self.add(dot_cloud) self.play( Write(title), self.teacher.change, "raise_right_hand", self.change_students(*["pondering"]*3) ) self.play( Write(dot_brace_anim.mobject, run_time = 1) ) self.add(dot_brace_anim) self.wait() # self.wait(2) self.play( dot_cloud.gaussian_distribution_wrapper.change_parameters, {"sigma" : 0.1*RIGHT}, run_time = 2, ) self.wait() self.add(vector_cloud) self.play( FadeIn(vector_brace_anim.mobject) ) self.add(vector_brace_anim) self.play( vector_cloud.gaussian_distribution_wrapper.change_parameters, {"sigma" : RIGHT}, self.change_students(*3*["confused"]), run_time = 3, ) #Back and forth for x in range(2): self.play( dot_cloud.gaussian_distribution_wrapper.change_parameters, {"sigma" : 2*RIGHT}, vector_cloud.gaussian_distribution_wrapper.change_parameters, {"sigma" : 0.1*RIGHT}, run_time = 3, ) self.play_student_changes("thinking", "erm", "sassy") self.play( dot_cloud.gaussian_distribution_wrapper.change_parameters, {"sigma" : 0.1*RIGHT}, vector_cloud.gaussian_distribution_wrapper.change_parameters, {"sigma" : 1*RIGHT}, run_time = 3, ) self.wait() class FourierTradeoff(Scene): CONFIG = { "show_text" : True, "complex_to_real_func" : lambda z : z.real, "widths" : [6, 0.02, 1], } def construct(self): #Setup axes time_mean = 4 time_axes = Axes( x_min = 0, x_max = 2*time_mean, x_axis_config = {"unit_size" : 1.5}, y_min = -2, y_max = 2, y_axis_config = {"unit_size" : 0.5} ) time_label = OldTexText("Time") time_label.scale(1.5) time_label.next_to( time_axes.x_axis.get_right(), UP+LEFT, buff = MED_SMALL_BUFF, ) time_axes.add(time_label) time_axes.center().to_edge(UP) time_axes.x_axis.add_numbers(*list(range(1, 2*time_mean))) frequency_axes = Axes( x_min = 0, x_max = 8, x_axis_config = {"unit_size" : 1.5}, y_min = -0.025, y_max = 0.075, y_axis_config = { "unit_size" : 30, "tick_frequency" : 0.025, }, color = TEAL, ) frequency_label = OldTexText("Frequency") frequency_label.scale(1.5) frequency_label.next_to( frequency_axes.x_axis.get_right(), UP+LEFT, buff = MED_SMALL_BUFF, ) frequency_label.set_color(FREQUENCY_COLOR) frequency_axes.add(frequency_label) frequency_axes.move_to(time_axes, LEFT) frequency_axes.to_edge(DOWN, buff = LARGE_BUFF) frequency_axes.x_axis.add_numbers() # Graph information #x-coordinate of this point determines width of wave_packet graph width_tracker = ExponentialValueTracker(0.5) get_width = width_tracker.get_value def get_wave_packet_function(): factor = 1./get_width() return lambda t : (factor**0.25)*np.cos(4*TAU*t)*np.exp(-factor*(t-time_mean)**2) def get_wave_packet(): graph = time_axes.get_graph( get_wave_packet_function(), num_graph_points = 200, ) graph.set_color(YELLOW) return graph time_radius = 10 def get_wave_packet_fourier_transform(): return get_fourier_graph( frequency_axes, get_wave_packet_function(), t_min = time_mean - time_radius, t_max = time_mean + time_radius, n_samples = 2*time_radius*17, complex_to_real_func = self.complex_to_real_func, color = FREQUENCY_COLOR, ) wave_packet = get_wave_packet() wave_packet_update = UpdateFromFunc( wave_packet, lambda g : Transform(g, get_wave_packet()).update(1) ) fourier_graph = get_wave_packet_fourier_transform() fourier_graph_update = UpdateFromFunc( fourier_graph, lambda g : Transform(g, get_wave_packet_fourier_transform()).update(1) ) arrow = Arrow( wave_packet, frequency_axes.coords_to_point( 4, frequency_axes.y_max/2, ), color = FREQUENCY_COLOR, ) fourier_words = OldTexText("Fourier Transform") fourier_words.next_to(arrow, LEFT, buff = MED_LARGE_BUFF) sub_words = OldTexText("(To be explained shortly)") sub_words.set_color(BLUE) sub_words.scale(0.75) sub_words.next_to(fourier_words, DOWN) #Draw items self.add(time_axes, frequency_axes) self.play(ShowCreation(wave_packet, rate_func = double_smooth)) anims = [ReplacementTransform( wave_packet.copy(), fourier_graph )] if self.show_text: anims += [ GrowArrow(arrow), Write(fourier_words, run_time = 1) ] self.play(*anims) # self.play(FadeOut(arrow)) self.wait() for width in self.widths: self.play( width_tracker.set_value, width, wave_packet_update, fourier_graph_update, run_time = 3 ) if sub_words not in self.mobjects and self.show_text: self.play(FadeIn(sub_words)) else: self.wait() self.wait() class ShowPlan(PiCreatureScene): def construct(self): self.add_title() words = self.get_words() self.play_sound_anims(words[0]) self.play_doppler_anims(words[1]) self.play_quantum_anims(words[2]) def add_title(self): title = OldTexText("The plan") title.scale(1.5) title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) self.add(title, h_line) def get_words(self): trips = [ ("sound waves", "(time vs. frequency)", YELLOW), ("Doppler radar", "(distance vs. velocity)", GREEN), ("quantum particles", "(position vs. momentum)", BLUE), ] words = VGroup() for topic, tradeoff, color in trips: word = OldTexText("Uncertainty for", topic, tradeoff) word[1:].set_color(color) word[2].scale(0.75) word[2].next_to(word[1], DOWN, buff = 1.5*SMALL_BUFF) words.add(word) words.arrange(DOWN, aligned_edge = LEFT, buff = MED_LARGE_BUFF) words.to_edge(LEFT) return words def play_sound_anims(self, word): morty = self.pi_creature wave = FunctionGraph( lambda x : 0.3*np.sin(15*x)*np.sin(0.5*x), x_min = 0, x_max = 30, step_size = 0.001, ) wave.next_to(word, RIGHT) rect = BackgroundRectangle(wave, fill_opacity = 1) rect.stretch(2, 1) rect.next_to(wave, LEFT, buff = 0) always_shift(wave, direction=LEFT, rate=5) wave_fader = UpdateFromAlphaFunc( wave, lambda w, a : w.set_stroke(width = 3*a) ) checkmark = self.get_checkmark(word) self.add(wave) self.add_foreground_mobjects(rect, word) self.play( Animation(word), wave_fader, morty.change, "raise_right_hand", word ) self.wait(2) wave_fader.rate_func = lambda a : 1-smooth(a) self.add_foreground_mobjects(checkmark) self.play( Write(checkmark), morty.change, "happy", wave_fader, ) self.remove_foreground_mobjects(rect, word) self.add(word) self.wait() def play_doppler_anims(self, word): morty = self.pi_creature radar_dish = RadarDish() radar_dish.next_to(word, DOWN, aligned_edge = LEFT) target = Plane() # target.match_height(radar_dish) target.next_to(radar_dish, RIGHT, buff = LARGE_BUFF) always_shift(target, direction = RIGHT, rate = 1.25) pulse = RadarPulse(radar_dish, target) checkmark = self.get_checkmark(word) self.add(target) self.play( Write(word), DrawBorderThenFill(radar_dish), UpdateFromAlphaFunc( target, lambda m, a : m.set_fill(opacity = a) ), morty.change, "pondering", run_time = 1 ) self.add(pulse) count = it.count() #TODO, this is not a great hack... while not pulse.is_finished() and next(count) < 15: self.play( morty.look_at, pulse.mobject, run_time = 0.5 ) self.play( Write(checkmark), UpdateFromAlphaFunc( target, lambda m, a : m.set_fill(opacity = 1-a) ), FadeOut(radar_dish), morty.change, "happy" ) self.wait() def play_quantum_anims(self, word): morty = self.pi_creature dot_cloud = ProbabalisticDotCloud() gdw = dot_cloud.gaussian_distribution_wrapper gdw.next_to(word, DOWN, MED_LARGE_BUFF) gdw.rotate(5*DEGREES) gdw.save_state() gdw.scale(0) checkmark = self.get_checkmark(word) ish = OldTexText("$\\dots$ish") ish.next_to(checkmark, RIGHT, -SMALL_BUFF, DOWN) self.add(dot_cloud) self.play( Write(word), FadeIn(dot_cloud.mobject), morty.change, "confused", ) self.play(gdw.restore, run_time = 2) self.play(Write(checkmark)) self.wait() self.play( Write(ish), morty.change, 'maybe' ) self.wait(6) ## def get_checkmark(self, word): checkmark = OldTex("\\checkmark") checkmark.set_color(GREEN) checkmark.scale(1.25) checkmark.next_to(word[1], UP+RIGHT, buff = 0) return checkmark class StartWithIntuition(TeacherStudentsScene): def construct(self): self.teacher_says( "You already \\\\ have this \\\\ intuition", bubble_config = { "height" : 3.5, "width" : 3, }, ) self.play_student_changes("pondering", "erm", "maybe") self.look_at(VectorizedPoint(4*LEFT + 2*UP)) self.wait(5) class TwoCarsAtRedLight(Scene): CONFIG = { "text_scale_val" : 0.75, } def construct(self): self.pull_up_behind() self.flash_in_sync_short_time() self.show_low_confidence() self.flash_in_sync_long_time() self.show_high_confidence() def pull_up_behind(self): #Setup Traffic light traffic_light = TrafficLight() traffic_light.move_to(6*RIGHT + 2.5*DOWN, DOWN) source_point = VectorizedPoint( traffic_light[2].get_right() ) screen = Line(ORIGIN, UP) screen.next_to(source_point, RIGHT, LARGE_BUFF) red_light = Spotlight( color = RED, source_point = source_point, radius = 0.5, screen = screen, num_levels = 20, opacity_function = lambda r : 1/(10*r**2+1) ) red_light.fade(0.5) red_light.rotate(TAU/2, about_edge = LEFT) self.add(red_light, traffic_light) #Setup cars car1, car2 = cars = self.cars = VGroup(*[ Car() for x in range(2) ]) cars.arrange(RIGHT, buff = LARGE_BUFF) cars.next_to( traffic_light, LEFT, buff = LARGE_BUFF, aligned_edge = DOWN ) car2.pi_creature.set_color(GREY_BROWN) car1.start_point = car1.get_corner(DOWN+RIGHT) car1.shift(FRAME_X_RADIUS*LEFT) #Pull up car self.add(cars) self.play( SwitchOn( red_light, rate_func = squish_rate_func(smooth, 0, 0.3), ), Animation(traffic_light), self.get_flashes(car2, num_flashes = 3), MoveCar( car1, car1.start_point, run_time = 3, rate_func = rush_from, ) ) def flash_in_sync_short_time(self): car1, car2 = cars = self.cars #Setup axes axes = Axes( x_min = 0, x_max = 5, y_min = 0, y_max = 2, y_axis_config = { "tick_frequency" : 0.5, }, ) axes.x_axis.add_numbers(1, 2, 3) time_label = OldTexText("Time") time_label.scale(self.text_scale_val) time_label.next_to(axes.x_axis.get_right(), DOWN) y_title = OldTexText("Signal") y_title.scale(self.text_scale_val) y_title.next_to(axes.y_axis, UP, SMALL_BUFF) axes.add(time_label, y_title) axes.to_corner(UP+LEFT, buff = MED_SMALL_BUFF) graph = axes.get_graph( self.get_multispike_function(list(range(1, 4))), x_min = 0.8, x_max = 3.8, ) graph.set_color(YELLOW) #Label short duration brace = Brace(Line( axes.input_to_graph_point(1, graph), axes.input_to_graph_point(3, graph), ), UP) text = OldTexText("Short duration observation") text.scale(self.text_scale_val) text.next_to(brace, UP, SMALL_BUFF) text.align_to( axes.coords_to_point(0.25, 0), LEFT ) self.play( self.get_flashes(car1, num_flashes = 2), self.get_flashes(car2, num_flashes = 2), LaggedStartMap(FadeIn, VGroup( axes, time_label, y_title, )) ) self.play( self.get_flashes(car1, num_flashes = 3), self.get_flashes(car2, num_flashes = 3), ShowCreation(graph, rate_func=linear, run_time = 3) ) self.play( self.get_flashes(car1, num_flashes = 10), self.get_flashes(car2, num_flashes = 10, run_time_per_flash = 0.98), GrowFromCenter(brace), Write(text), ) self.time_axes = axes self.time_graph = graph self.time_graph_label = VGroup( brace, text ) def show_low_confidence(self): car1, car2 = cars = self.cars time_axes = self.time_axes #Setup axes frequency_axes = Axes( x_min = 0, x_max = 3, y_min = 0, y_max = 1.5, y_axis_config = { "tick_frequency" : 0.5, } ) frequency_axes.next_to(time_axes, DOWN, LARGE_BUFF) frequency_axes.set_color(GREY_B) frequency_label = OldTexText("Frequency") frequency_label.scale(self.text_scale_val) frequency_label.next_to(frequency_axes.x_axis.get_right(), DOWN) frequency_axes.add( frequency_label, VectorizedPoint(frequency_axes.y_axis.get_top()) ) frequency_axes.x_axis.add_numbers(1, 2) frequency_graph = frequency_axes.get_graph( lambda x : np.exp(-4*(x-1)**2), x_min = 0, x_max = 2, ) frequency_graph.set_color(RED) peak_point = frequency_axes.input_to_graph_point( 1, frequency_graph ) #Setup label label = OldTexText("Low confidence") label.scale(self.text_scale_val) label.move_to(peak_point + UP+RIGHT, DOWN) label.match_color(frequency_graph) arrow = Arrow(label.get_bottom(), peak_point, buff = 2*SMALL_BUFF) arrow.match_color(frequency_graph) self.play( ReplacementTransform( self.time_axes.copy(), frequency_axes ), ReplacementTransform( self.time_graph.copy(), frequency_graph ), ) self.play( Write(label), GrowArrow(arrow) ) self.wait() self.frequency_axes = frequency_axes self.frequency_graph = frequency_graph self.frequency_graph_label = VGroup( label, arrow ) def flash_in_sync_long_time(self): time_graph = self.time_graph time_axes = self.time_axes frequency_graph = self.frequency_graph frequency_axes = self.frequency_axes n_spikes = 12 new_time_graph = time_axes.get_graph( self.get_multispike_function(list(range(1, n_spikes+1))), x_min = 0.8, x_max = n_spikes + 0.8, ) new_time_graph.match_color(time_graph) new_frequency_graph = frequency_axes.get_graph( lambda x : np.exp(-500*(x-1)**2), x_min = 0, x_max = 2, num_anchors = 500, ) new_frequency_graph.match_color(self.frequency_graph) def pin_freq_graph_end_points(freq_graph): freq_graph.get_points()[0] = frequency_axes.coords_to_point(0, 0) freq_graph.get_points()[-1] = frequency_axes.coords_to_point(2, 0) self.play(LaggedStartMap( FadeOut, VGroup( self.time_graph_label, self.frequency_graph_label, self.time_graph, ) )) self.play( ApplyMethod( self.time_axes.x_axis.stretch, 2.5, 0, {"about_edge" : LEFT}, run_time = 4, rate_func = squish_rate_func(smooth, 0.3, 0.6), ), UpdateFromFunc( self.time_axes.x_axis.tip, lambda m : m.move_to( self.time_axes.x_axis.get_right(), LEFT ) ), ShowCreation( new_time_graph, run_time = n_spikes, rate_func=linear, ), ApplyMethod( frequency_graph.stretch, 0.1, 0, run_time = n_spikes, ), UpdateFromFunc(frequency_graph, pin_freq_graph_end_points), *[ self.get_flashes(car, num_flashes = n_spikes) for car in self.cars ] ) self.new_time_graph = new_time_graph self.new_frequency_graph = new_frequency_graph def show_high_confidence(self): #Frequency stuff arrow = self.frequency_graph_label[1] label = OldTexText("High confidence") label.scale(self.text_scale_val) label.next_to(arrow.get_start(), UP, SMALL_BUFF) label.match_color(arrow) frequency_axes = self.frequency_axes #Time stuff new_time_graph = self.new_time_graph brace = Brace(new_time_graph, UP, buff = SMALL_BUFF) text = OldTexText("Long duration observation") text.scale(self.text_scale_val) text.next_to(brace, UP, buff = SMALL_BUFF) self.play( FadeIn(label), GrowArrow(arrow), *list(map(self.get_flashes, self.cars)) ) self.play( GrowFromCenter(brace), Write(text, run_time = 1), *list(map(self.get_flashes, self.cars)) ) self.play(*[ self.get_flashes(car, num_flashes = 10) for car in self.cars ]) ### def get_flashes(self, car, colors = [YELLOW, RED], num_flashes = 1, **kwargs): return AnimationGroup(*[ MultipleFlashes(light, color, num_flashes = num_flashes, **kwargs) for light, color in zip(car.get_lights(), colors) ]) def get_multispike_function(self, spike_times): return lambda x : sum([ 1.25*np.exp(-100*(x-m)**2) for m in spike_times ]) class VariousMusicalNotes(Scene): def construct(self): freq = 20 # x-coordinate of this point represents log(a) # where the bell curve component of the signal # is exp(-a*(x**2)) graph_width_tracker = ExponentialValueTracker(1) def get_graph(): a = graph_width_tracker.get_value() return FunctionGraph( lambda x : np.exp(-a*x**2)*np.sin(freq*x)-0.5, step_size = 0.001, ) graph = get_graph() def graph_update(graph): graph.set_points(get_graph().get_points()) graph_update_anim = UpdateFromFunc(graph, graph_update) def change_width_anim(width, **kwargs): a = 2.0/(width**2) return AnimationGroup( ApplyMethod(graph_width_tracker.set_value, a), graph_update_anim, **kwargs ) change_width_anim(FRAME_X_RADIUS).update(1) graph_update_anim.update(0) phrases = [ OldTexText(*words.split(" ")) for words in [ "Very clear frequency", "Less clear frequency", "Extremely unclear frequency", ] ] #Show graphs and phrases widths = [FRAME_X_RADIUS, 1, 0.2] for width, phrase in zip(widths, phrases): brace = Brace(Line(LEFT, RIGHT), UP) brace.stretch(width, 0) brace.next_to(graph.get_center(), UP, buff = 1.2) phrase.next_to(brace, UP) if width is widths[0]: self.play(ShowCreation(graph, rate_func=linear)), self.play( GrowFromCenter(brace), Write(phrase, run_time = 1) ) else: self.play( change_width_anim(width), ReplacementTransform( VGroup(last_phrase, last_brace), VGroup(phrase, brace), rate_func = squish_rate_func(smooth, 0.5, 1), ), run_time = 2 ) self.wait() # self.play(*map(FadeOut, [graph, brace, phrase])) last_phrase = phrase last_brace = brace #Talk about correlations short_signal_words = OldTexText( "Short", "signal", "correlates", "with", "wide range", "of frequencies" ) long_signal_words = OldTexText( "Only", "wide", "signals", "correlate", "with a", "short range", "of frequencies" ) phrases = VGroup(short_signal_words, long_signal_words) for phrase in phrases: phrase.scale(0.8) phrase.set_color_by_tex_to_color_map({ "short" : RED, "long" : GREEN, "wide" : GREEN, }, case_sensitive = False) phrases.arrange(DOWN) phrases.to_edge(UP) long_graph = FunctionGraph( lambda x : 0.5*np.sin(freq*x), x_min = -FRAME_WIDTH, x_max = FRAME_WIDTH, n_components = 0.001 ) long_graph.set_color(BLUE) long_graph.next_to(graph, UP, MED_LARGE_BUFF) self.play( ShowCreation(long_graph), *list(map(FadeOut, [last_brace, last_phrase])) ) self.play( Write(short_signal_words), change_width_anim(widths[2]) ) self.play( long_graph.stretch, 0.35, 0, long_graph.set_color, GREEN, run_time = 5, rate_func = wiggle ) self.wait() self.play( Write(long_signal_words), change_width_anim(widths[0]), ) self.play( long_graph.stretch, 0.95, 0, long_graph.set_color, average_color(GREEN, BLUE), run_time = 4, rate_func = wiggle ) self.wait() class CrossOutDefinitenessAndCertainty(TeacherStudentsScene): def construct(self): words = VGroup( OldTexText("Definiteness"), OldTexText("Certainty"), ) words.arrange(DOWN) words.next_to(self.teacher, UP+LEFT) crosses = VGroup(*list(map(Cross, words))) self.add(words) self.play( self.teacher.change, "sassy", ShowCreation(crosses[0]) ) self.play( self.change_students(*3*["erm"]), ShowCreation(crosses[1]) ) self.wait(2) class BringInFourierTranform(TeacherStudentsScene): def construct(self): fourier = OldTexText("Fourier") fourier.scale(1.5) fourier.next_to(self.teacher.get_corner(UP+LEFT), UP, LARGE_BUFF) fourier.save_state() fourier.shift(DOWN) fourier.fade(1) self.play( self.teacher.change, "raise_right_hand", fourier.restore ) self.play_student_changes("happy", "erm", "confused") self.look_at(3*LEFT + 2*UP) self.wait(3) class LastVideoWrapper(Scene): def construct(self): title = OldTexText("Visualizing the Fourier Transform") title.to_edge(UP) screen_rect = ScreenRectangle(height = 6) screen_rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(screen_rect)) self.wait() class FourierRecapScene(DrawFrequencyPlot): CONFIG = { "frequency_axes_config" : { "x_max" : 10.0, "x_axis_config" : { "unit_size" : 0.7, "numbers_to_show" : list(range(1, 10, 1)), } }, "initial_winding_frequency" : 0.1, } def construct(self): self.setup_axes() self.preview_fourier_plot() self.wrap_signal_around_circle() self.match_winding_to_beat_frequency() self.follow_center_of_mass() self.draw_fourier_plot() self.set_color_spike() def setup_axes(self): self.remove(self.pi_creature) time_axes = self.get_time_axes() time_axes.to_edge(UP, buff = MED_SMALL_BUFF) time_axes.scale(0.9, about_edge = UP) frequency_axes = self.get_frequency_axes() circle_plane = self.get_circle_plane() self.add(time_axes) self.set_variables_as_attrs( time_axes, frequency_axes, circle_plane ) def preview_fourier_plot(self): time_graph = self.graph = self.get_time_graph( width = 2, num_graph_points = 200, ) fourier_graph = self.get_fourier_transform_graph( time_graph ) fourier_graph.pointwise_become_partial(fourier_graph, 0.1, 1) #labels signal_label = OldTexText("Signal") fourier_label = OldTexText("Fourier transform") signal_label.next_to(time_graph, UP, buff = SMALL_BUFF) fourier_label.next_to(fourier_graph, UP) fourier_label.match_color(fourier_graph) self.play( ShowCreation(time_graph, run_time = 2), Write(signal_label), ) self.wait() self.play( LaggedStartMap(FadeIn, self.frequency_axes), ReplacementTransform( time_graph.copy(), fourier_graph, run_time = 2 ), ReplacementTransform( signal_label.copy(), fourier_label, run_time = 2, rate_func = squish_rate_func(smooth, 0.5, 1) ), ) self.wait() self.play(LaggedStartMap( Indicate, self.frequency_axes.x_axis.numbers, run_time = 4, rate_func = wiggle, )) self.wait() self.play(*list(map(FadeOut, [ self.frequency_axes, fourier_graph, signal_label, fourier_label, ]))) self.time_graph = time_graph self.set_variables_as_attrs(time_graph, fourier_label) def wrap_signal_around_circle(self): time_graph = self.time_graph circle_plane = self.circle_plane freq = self.initial_winding_frequency pol_graph = self.get_polarized_mobject(time_graph, freq) winding_freq_label = self.get_winding_frequency_label() winding_freq_label.add_to_back(BackgroundRectangle(winding_freq_label)) winding_freq_label.move_to(circle_plane.get_top(), DOWN) self.add_foreground_mobjects(winding_freq_label) self.play( Write(circle_plane, run_time = 1), ReplacementTransform( time_graph.copy(), pol_graph, path_arc = -TAU/4, run_time_per_flash = 2, run_time = 2, ), FadeIn(winding_freq_label), ) freq = 0.3 self.change_frequency(freq, run_time = 2) ghost_pol_graph = pol_graph.copy() self.remove(pol_graph) self.play(ghost_pol_graph.set_stroke, {"width" : 0.5}) self.play( *self.get_vector_animations(time_graph), run_time = 15 ) self.remove(ghost_pol_graph) self.wait() def match_winding_to_beat_frequency(self): self.v_lines_indicating_periods = self.get_v_lines_indicating_periods(0.3) self.add(self.v_lines_indicating_periods) for freq in range(1, 6): self.change_frequency(freq, run_time = 5) self.play( *self.get_vector_animations( self.time_graph, draw_polarized_graph = False ), run_time = 10 ) self.wait() def follow_center_of_mass(self): com_dot = self.get_center_of_mass_dot() self.generate_center_of_mass_dot_update_anim() com_arrow = Arrow(UP+3*RIGHT, ORIGIN) com_arrow.shift(com_dot.get_center()) com_arrow.match_color(com_dot) com_words = OldTexText("Center of mass") com_words.next_to(com_arrow.get_start(), UP) com_words.match_color(com_arrow) com_words.add_background_rectangle() com_dot.save_state() com_dot.move_to(com_arrow.get_start()) com_dot.fade(1) self.play( com_dot.restore, GrowArrow(com_arrow, rate_func = squish_rate_func(smooth, 0.2, 1)), Write(com_words), ) self.wait() squished_func = squish_rate_func(smooth, 0, 0.2) self.change_frequency( 4, added_anims = [ FadeOut(com_arrow, rate_func = squished_func), FadeOut(com_words, rate_func = squished_func), ], run_time = 5 ) def draw_fourier_plot(self): frequency_axes = self.frequency_axes fourier_label = self.fourier_label self.change_frequency(0, run_time = 2) self.play( FadeIn(frequency_axes), FadeIn(fourier_label), ) fourier_graph = self.get_fourier_transform_graph(self.time_graph) self.get_fourier_graph_drawing_update_anim(fourier_graph) self.generate_fourier_dot_transform(fourier_graph) self.change_frequency(5, run_time = 20) self.wait() self.change_frequency(7.5, run_time = 10) self.fourier_graph_drawing_update_anim = Animation(Mobject()) self.fourier_graph = fourier_graph def set_color_spike(self): spike_point = self.frequency_axes.input_to_graph_point( 5, self.fourier_graph ) circle = Circle(color = YELLOW, radius = 0.25) circle.move_to(spike_point) circle.save_state() circle.scale(5) circle.fade(1) self.change_frequency(5) self.play(circle.restore) self.play(FadeOut(circle)) self.wait() for x in range(2): self.change_frequency(5.2, run_time = 3) self.change_frequency(4.8, run_time = 3) self.change_frequency(5, run_time = 1.5) self.wait() ######### def get_time_graph(self, frequency = 5, width = 2, **kwargs): # low_x = center-width/2 # high_x = center+width/2 # new_smooth = lambda x : np.clip(smooth((x+0.5)), 0, 1) # def func(x): # pure_signal = 0.9*np.cos(TAU*frequency*x) # factor = new_smooth(x - low_x) - new_smooth(x-high_x) # return 1 + factor*pure_signal graph = self.time_axes.get_graph( lambda x : 1+0.9*np.cos(TAU*frequency*x), x_min = 0, x_max = width, **kwargs ) graph.set_color(YELLOW) return graph class RealPartOfInsert(Scene): def construct(self): words = OldTexText("(Real part of the)") words.set_color(RED) self.add(words) self.play(Write(words)) self.wait(5) class CenterOfMassDescription(FourierRecapScene): def construct(self): self.remove(self.pi_creature) circle_plane = self.get_circle_plane() circle_plane.save_state() circle_plane.generate_target() circle_plane.target.set_height(FRAME_HEIGHT) circle_plane.target.center() circle_plane.target.axes.set_stroke(width = 2) circle_plane.targets.set_stroke(width = 2) circle_plane.target.secondary_lines.set_stroke(width = 1) start_coords = (0.5, 0.5) alt_coords = (0.8, 0.8) com_dot = Dot(color = self.center_of_mass_color) com_dot.move_to(circle_plane.coords_to_point(*start_coords)) self.add(circle_plane, com_dot) self.wait() self.play( MoveToTarget(circle_plane), com_dot.move_to, circle_plane.target.coords_to_point(*start_coords) ) self.wait() alt_com_dot = com_dot.copy().move_to( circle_plane.coords_to_point(*alt_coords) ) for dot in com_dot, alt_com_dot: line = Line(ORIGIN, dot.get_center()) line.match_color(com_dot) angle = line.get_angle() line.rotate(-angle, about_point = ORIGIN) brace = Brace(line, UP) words = brace.get_text("Strength of frequency") words.add_background_rectangle() dot.length_label_group = VGroup(line, brace, words) dot.length_label_group.rotate(angle, about_point = ORIGIN) line, brace, words = com_dot.length_label_group self.play( GrowFromCenter(line), GrowFromCenter(brace), FadeIn(words), ) self.wait() self.play( Transform( com_dot.length_label_group, alt_com_dot.length_label_group, ), Transform(com_dot, alt_com_dot), rate_func = there_and_back, run_time = 4, ) #Do rotation line = com_dot.length_label_group[0] com_dot.length_label_group.remove(line) angle = line.get_angle() arc, alt_arc = [ Arc( start_angle = 0, angle = factor*angle, radius = 0.5, ) for factor in (1, 2) ] theta = OldTex("\\theta") theta.shift(1.5*arc.point_from_proportion(0.5)) self.play( FadeOut(com_dot.length_label_group), Animation(line), ShowCreation(arc), Write(theta) ) self.play( Rotate( VGroup(line, com_dot), angle, about_point = ORIGIN ), Transform(arc, alt_arc), theta.move_to, 1.5*alt_arc.point_from_proportion(0.5), rate_func = there_and_back, run_time = 4 ) self.wait() class AskAboutLongVsShort(TeacherStudentsScene): def construct(self): self.student_says( "What happens if we \\\\ change the length of \\\\ the signal?", index = 2, ) self.play( self.teacher.change, "happy", self.change_students("pondering", "confused", "raise_right_hand") ) self.wait(5) class LongAndShortSignalsInWindingMachine(FourierRecapScene): CONFIG = { "num_fourier_graph_points" : 1000, } def construct(self): self.setup_axes() self.extend_for_long_time() self.note_sharp_fourier_peak() self.very_short_signal() self.note_wide_fourier_peak() def setup_axes(self): FourierRecapScene.setup_axes(self) self.add(self.circle_plane) self.add(self.frequency_axes) self.time_graph = self.graph = self.get_time_graph(width = 2) self.add(self.time_graph) self.force_skipping() self.wrap_signal_around_circle() fourier_graph = self.get_fourier_transform_graph(self.time_graph) self.fourier_graph = fourier_graph self.add(fourier_graph) self.change_frequency(5) self.revert_to_original_skipping_status() def extend_for_long_time(self): short_time_graph = self.time_graph long_time_graph = self.get_time_graph( width = 10, num_graph_points = 500, ) long_time_graph.set_stroke(width = 2) new_freq = 5.1 long_pol_graph = self.get_polarized_mobject( long_time_graph, freq = new_freq ) fourier_graph = self.fourier_graph self.change_frequency(new_freq) self.play( FadeOut(self.graph), FadeOut(self.graph.polarized_mobject), FadeOut(fourier_graph) ) self.play( ShowCreation(long_time_graph, rate_func=linear), ShowCreation(long_pol_graph, rate_func=linear), run_time = 5 ) self.wait() self.time_graph = self.graph = long_time_graph def note_sharp_fourier_peak(self): fourier_graph = self.get_fourier_transform_graph( self.time_graph, num_graph_points = self.num_fourier_graph_points ) self.fourier_graph = fourier_graph self.note_fourier_peak(fourier_graph, 5, 5.1) def very_short_signal(self): time_graph = self.time_graph fourier_graph = self.fourier_graph short_time_graph = self.get_time_graph(width = 0.6) new_freq = 5.1 short_pol_graph = self.get_polarized_mobject( short_time_graph, freq = new_freq ) self.play( FadeOut(fourier_graph), FadeOut(time_graph), FadeOut(time_graph.polarized_mobject), ) self.play( ShowCreation(short_time_graph), ShowCreation(short_time_graph.polarized_mobject), ) self.graph = self.time_graph = short_time_graph self.change_frequency(6.66, run_time = 5) def note_wide_fourier_peak(self): fourier_graph = self.get_fourier_transform_graph( self.graph, num_graph_points = self.num_fourier_graph_points ) self.fourier_graph = fourier_graph self.note_fourier_peak(fourier_graph, 5, 6.66) ### def note_fourier_peak(self, fourier_graph, freq1, freq2): fourier_graph = self.fourier_graph dots = self.get_fourier_graph_dots(fourier_graph, freq1, freq2) self.get_center_of_mass_dot() self.generate_center_of_mass_dot_update_anim() self.generate_fourier_dot_transform(fourier_graph) dot = self.fourier_graph_dot arrow = Arrow(UP, ORIGIN, buff = SMALL_BUFF) arrow.next_to(dot, UP, buff = SMALL_BUFF) self.play(ShowCreation(fourier_graph)) self.change_frequency(freq1, added_anims = [ MaintainPositionRelativeTo(arrow, dot), UpdateFromAlphaFunc( arrow, lambda m, a : m.set_fill(opacity = a) ), ], run_time = 3, ) self.wait() self.change_frequency(freq2, added_anims = [ MaintainPositionRelativeTo(arrow, dot) ], run_time = 3 ) self.wait() self.play(*list(map(FadeOut, [ dot, arrow, self.center_of_mass_dot ]))) #This is not great... for attr in "center_of_mass_dot", "fourier_graph_dot": self.__dict__.pop(attr) def get_fourier_graph_dots(self, fourier_graph, *freqs): axis_point = self.frequency_axes.coords_to_point(4.5, -0.25) dots = VGroup() for freq in freqs: point = self.frequency_axes.input_to_graph_point(freq, fourier_graph) dot = Dot(point) dot.scale(0.5) dots.add(dot) vect = point - axis_point vect *= 1.3/get_norm(vect) arrow = Arrow(vect, ORIGIN, buff = SMALL_BUFF) arrow.set_color(YELLOW) arrow.shift(point) dot.arrow = arrow return dots class FocusRectangleInsert(FourierRecapScene): CONFIG = { "target_width" : 0.5 } def construct(self): self.setup_axes() self.clear() point = self.frequency_axes.coords_to_point(5, 0.25) rect = ScreenRectangle(height = 2.1*FRAME_Y_RADIUS) rect.set_stroke(YELLOW, 2) self.add(rect) self.wait() self.play( rect.stretch_to_fit_width, self.target_width, rect.stretch_to_fit_height, 1.5, rect.move_to, point, run_time = 2 ) self.wait(3) class BroadPeakFocusRectangleInsert(FocusRectangleInsert): CONFIG = { "target_width" : 1.5, } class CleanerFourierTradeoff(FourierTradeoff): CONFIG = { "show_text" : False, "complex_to_real_func" : lambda z : z.real, "widths" : [0.02, 6, 1], } class MentionDopplerRadar(TeacherStudentsScene): def construct(self): words = OldTexText("Doppler Radar") words.next_to(self.teacher, UP) words.save_state() words.shift(DOWN).fade(1) dish = RadarDish() dish.next_to(self.students, UP, buff = 2, aligned_edge = LEFT) plane = Plane() plane.to_edge(RIGHT) plane.align_to(dish) always_shift(plane, LEFT, 1) plane.flip() pulse = RadarPulse(dish, plane) look_at_anims = [ Mobject.add_updater( pi, lambda pi : pi.look_at(pulse.mobject) ) for pi in self.get_pi_creatures() ] self.add(dish, plane, pulse, *look_at_anims) self.play( self.teacher.change, "hooray", words.restore ) self.play_student_changes("pondering", "erm", "sassy") self.wait(2) self.play( self.teacher.change, "happy", self.change_students(*["thinking"]*3) ) self.wait() dish.set_stroke(width = 0) self.play(UpdateFromAlphaFunc( VGroup(plane, dish), lambda m, a : m.set_fill(opacity = 1 - a) )) class IntroduceDopplerRadar(Scene): CONFIG = { "frequency_spread_factor" : 100, } def construct(self): self.setup_axes() self.measure_distance_with_time() self.show_frequency_shift() self.show_frequency_shift_in_fourier() def setup_axes(self): self.dish = RadarDish() self.dish.to_corner(UP+LEFT) axes = Axes( x_min = 0, x_max = 10, y_min = -1.5, y_max = 1.5 ) axes.move_to(DOWN) time_label = OldTexText("Time") time_label.next_to(axes.x_axis.get_right(), UP) axes.time_label = time_label axes.add(time_label) self.axes = axes self.add(self.dish) self.add(axes) def measure_distance_with_time(self): dish = self.dish axes = self.axes distance = 5 time_diff = 5 speed = (2*distance)/time_diff randy = Randolph().flip() randy.match_height(dish) randy.move_to(dish.get_right(), LEFT) randy.shift(distance*RIGHT) pulse_graph, echo_graph, sum_graph = \ self.get_pulse_and_echo_graphs( self.get_single_pulse_graph, (1,), (1+time_diff,) ) words = ["Original signal", "Echo"] for graph, word in zip([pulse_graph, echo_graph], words): arrow = Vector(DOWN) arrow.next_to(graph.peak_point, UP, SMALL_BUFF) arrow.match_color(graph) graph.arrow = arrow label = OldTexText(word) label.next_to(arrow.get_start(), UP, SMALL_BUFF) label.match_color(graph) graph.label = label double_arrow = DoubleArrow( pulse_graph.peak_point, echo_graph.peak_point, color = WHITE ) distance_text = OldTexText("$2 \\times$ distance/(signal speed)") distance_text.set_width(0.9*double_arrow.get_width()) distance_text.next_to(double_arrow, UP, SMALL_BUFF) #v_line anim? pulse = RadarPulseSingleton( dish, randy, speed = 0.97*speed, #Just needs slightly better alignment ) graph_draw = turn_animation_into_updater( ShowCreation( sum_graph, rate_func=linear, run_time = 0.97*axes.x_max ) ) randy_look_at = Mobject.add_updater( randy, lambda pi : pi.look_at(pulse.mobject) ) axes_anim = ContinualAnimation(axes) self.add(randy_look_at, axes_anim, graph_draw) self.wait(0.5) self.add(pulse) self.play( Write(pulse_graph.label), GrowArrow(pulse_graph.arrow), run_time = 1, ) self.play(randy.change, "pondering") self.wait(time_diff - 2) self.play( Write(echo_graph.label), GrowArrow(echo_graph.arrow), run_time = 1 ) self.wait() self.play( GrowFromCenter(double_arrow), FadeIn(distance_text) ) self.wait() self.remove(graph_draw, pulse, randy_look_at, axes_anim) self.add(axes) self.play(LaggedStartMap(FadeOut, VGroup( sum_graph, randy, pulse_graph.arrow, pulse_graph.label, echo_graph.arrow, echo_graph.label, double_arrow, distance_text ))) def show_frequency_shift(self): axes = self.axes dish = self.dish plane = Plane() plane.flip() plane.move_to(dish) plane.to_edge(RIGHT) time_diff = 6 pulse_graph, echo_graph, sum_graph = graphs = \ self.get_pulse_and_echo_graphs( self.get_frequency_pulse_graph, (1,25), (1+time_diff,50) ) for graph in graphs: graph.set_stroke(width = 3) signal_graph = self.get_frequency_pulse_graph(1) pulse_brace = Brace(Line(ORIGIN, RIGHT), UP) pulse_brace.move_to(axes.coords_to_point(1, 1.2)) echo_brace = pulse_brace.copy() echo_brace.stretch(0.6, 0) echo_brace.move_to(axes.coords_to_point(7, 1.2)) pulse_text = pulse_brace.get_text("Original signal") pulse_text.add_background_rectangle() echo_text = echo_brace.get_text("Echo") echo_subtext = OldTexText("(Higher frequency)") echo_subtext.next_to(echo_text, RIGHT) echo_subtext.match_color(echo_graph) graph_draw = turn_animation_into_updater( ShowCreation(sum_graph, run_time = 8, rate_func=linear) ) pulse = RadarPulse(dish, plane, n_pulse_singletons = 12) always_shift(plane, LEFT, 1.5) self.add(graph_draw, pulse, plane) self.play(UpdateFromAlphaFunc( plane, lambda m, a : m.set_fill(opacity = a) )) self.play( GrowFromCenter(pulse_brace), FadeIn(pulse_text), ) self.wait(3) self.play( GrowFromCenter(echo_brace), GrowFromCenter(echo_text), ) self.play(UpdateFromAlphaFunc( plane, lambda m, a : m.set_fill(opacity = 1-a) )) #Only for when -s is run graph_draw.update(10) self.wait(0.1) self.play(Write(echo_subtext, run_time = 1)) self.wait() self.remove(graph_draw, pulse, plane) pulse_graph.set_stroke(width = 0) echo_graph.set_stroke(width = 0) self.time_graph_group = VGroup( axes, pulse_brace, pulse_text, echo_brace, echo_text, echo_subtext, pulse_graph, echo_graph, sum_graph, ) self.set_variables_as_attrs(*self.time_graph_group) def show_frequency_shift_in_fourier(self): sum_graph = self.sum_graph pulse_graph = self.pulse_graph pulse_label = VGroup(self.pulse_brace, self.pulse_text) echo_graph = self.echo_graph echo_label = VGroup( self.echo_brace, self.echo_text, self.echo_subtext ) #Setup all fourier graph stuff f_max = 0.02 frequency_axes = Axes( x_min = 0, x_max = 20, x_axis_config = {"unit_size" : 0.5}, y_min = -f_max, y_max = f_max, y_axis_config = { "unit_size" : 50, "tick_frequency" : 0.01, }, ) frequency_axes.move_to(self.axes, LEFT) frequency_axes.to_edge(DOWN) frequency_label = OldTexText("Frequency") frequency_label.next_to( frequency_axes.x_axis.get_right(), UP, ) frequency_label.to_edge(RIGHT) frequency_axes.add(frequency_label) for graph in pulse_graph, echo_graph, sum_graph: graph.fourier_transform = get_fourier_graph( frequency_axes, graph.underlying_function, frequency_axes.x_min, 25, complex_to_real_func = abs, ) #Braces labeling F.T. original_fourier_brace = Brace( Line( frequency_axes.coords_to_point(7, 0.9*f_max), frequency_axes.coords_to_point(9, 0.9*f_max), ), UP, ).set_color(BLUE) echo_fourier_brace = Brace( Line( frequency_axes.coords_to_point(14, 0.4*f_max), frequency_axes.coords_to_point(18, 0.4*f_max), ), UP, ).set_color(YELLOW) # braces = [original_fourier_brace, echo_fourier_brace] # words = ["original signal", "echo"] # for brace, word in zip(braces, words): # brace.add(brace.get_text("F.T. of \\\\ %s"%word)) fourier_label = OldTex("||\\text{Fourier transform}||") # fourier_label.next_to(sum_graph.fourier_transform, UP, MED_LARGE_BUFF) fourier_label.next_to(frequency_axes.y_axis, UP, buff = SMALL_BUFF) fourier_label.shift_onto_screen() fourier_label.set_color(RED) #v_lines v_line = DashedLine( frequency_axes.coords_to_point(8, 0), frequency_axes.coords_to_point(8, 1.2*f_max), color = YELLOW, dash_length = 0.025, ) v_line_pair = VGroup(*[ v_line.copy().shift(u*0.6*RIGHT) for u in (-1, 1) ]) v_line = VGroup(v_line) double_arrow = DoubleArrow( frequency_axes.coords_to_point(8, 0.007), frequency_axes.coords_to_point(16, 0.007), buff = 0, color = WHITE ) self.play( self.time_graph_group.to_edge, UP, ApplyMethod( self.dish.shift, 2*UP, remover = True ), FadeIn(frequency_axes) ) self.wait() self.play( FadeOut(sum_graph), FadeOut(echo_label), pulse_graph.set_stroke, {"width" : 3}, ) self.play( ReplacementTransform( pulse_label[0].copy(), original_fourier_brace ), ShowCreation(pulse_graph.fourier_transform) ) self.play(Write(fourier_label)) self.wait() self.play(ShowCreation(v_line)) self.wait() self.play(ReplacementTransform(v_line, v_line_pair)) self.wait() self.play(FadeOut(v_line_pair)) self.wait() self.play( FadeOut(pulse_graph), FadeIn(sum_graph), ReplacementTransform( pulse_graph.fourier_transform, sum_graph.fourier_transform ) ) self.play(FadeIn(echo_label)) self.play(ReplacementTransform( echo_label[0].copy(), echo_fourier_brace, )) self.wait(2) self.play(GrowFromCenter(double_arrow)) self.wait() ### def get_graph(self, func, **kwargs): graph = self.axes.get_graph(func, **kwargs) graph.peak_point = self.get_peak_point(graph) return graph def get_single_pulse_graph(self, x, **kwargs): return self.get_graph(self.get_single_pulse_function(x), **kwargs) def get_single_pulse_function(self, x): return lambda t : -2*np.sin(10*(t-x))*np.exp(-100*(t-x)**2) def get_frequency_pulse_graph(self, x, freq = 50, **kwargs): return self.get_graph( self.get_frequency_pulse_function(x, freq), num_graph_points = 700, **kwargs ) def get_frequency_pulse_function(self, x, freq): factor = self.frequency_spread_factor return lambda t : op.mul( 2*np.cos(2*freq*(t-x)), min(np.exp(-(freq**2/factor)*(t-x)**2), 0.5) ) def get_peak_point(self, graph): anchors = graph.get_anchors() return anchors[np.argmax([p[1] for p in anchors])] def get_pulse_and_echo_graphs(self, func, args1, args2): pulse_graph = func(*args1, color = BLUE) echo_graph = func(*args2, color = YELLOW) sum_graph = self.axes.get_graph( lambda x : sum([ pulse_graph.underlying_function(x), echo_graph.underlying_function(x), ]), num_graph_points = echo_graph.get_num_curves(), color = WHITE ) sum_graph.background_image_file = "blue_yellow_gradient" return pulse_graph, echo_graph, sum_graph class DopplerFormulaInsert(Scene): def construct(self): formula = OldTex( "f_{\\text{echo}", "=", "\\left(1 + \\frac{v}{c}\\right)", "f_{\\text{pulse}}" ) formula[0].set_color(BLUE) formula[3].set_color(YELLOW) randy = Randolph(color = BLUE_C) formula.scale(1.5) formula.next_to(randy, UP+LEFT) formula.shift_onto_screen() self.add(randy) self.play( LaggedStartMap(FadeIn, formula), randy.change, "pondering", randy.get_bottom(), ) self.play(Blink(randy)) self.wait(2) self.play(Blink(randy)) self.wait() class MentionPRFNuance(TeacherStudentsScene): def construct(self): title = OldTexText( "Speed of light", "$\\gg$", "Speed of a plane" ) title.to_edge(UP) self.add(title) axes = self.axes = Axes( x_min = 0, x_max = 10, y_min = 0, y_max = 2, ) axes.next_to(title, DOWN, buff = MED_LARGE_BUFF) frequency_label = OldTexText("Frequency") frequency_label.scale(0.7) frequency_label.next_to(axes.x_axis.get_right(), UP) axes.add(frequency_label) self.add(axes) pulse_x, shift_x = 4, 6 pulse_graph = self.get_spike_graph(pulse_x) shift_graph = self.get_spike_graph(shift_x) shift_graph.set_stroke(YELLOW, 2) peak_points = VGroup(pulse_graph.peak_point, shift_graph.peak_point) self.add(pulse_graph) brace = Brace(peak_points, UP, buff = SMALL_BUFF) displayed_doppler_shift = OldTexText("How I'm showing the \\\\", "Doppler shift") actual_doppler_shift = OldTexText("Actual\\\\", "Doppler shift") doppler_shift_words = VGroup(displayed_doppler_shift, actual_doppler_shift) doppler_shift_words.set_color(YELLOW) doppler_shift_words.scale(0.75) displayed_doppler_shift.next_to(brace, UP, buff = SMALL_BUFF) actual_doppler_shift.move_to(pulse_graph.peak_point) actual_doppler_shift.align_to(displayed_doppler_shift) self.play( Animation(pulse_graph), self.teacher.change, "raise_right_hand", run_time = 1 ) self.play( ShowCreation(shift_graph), FadeIn(brace), Write(displayed_doppler_shift, run_time = 1), self.change_students(*3*["sassy"]), ) self.play( UpdateFromAlphaFunc( shift_graph, lambda g, a : Transform( g, self.get_spike_graph( interpolate(shift_x, pulse_x+0.01, a), ).match_style(shift_graph) ).update(1), ), UpdateFromFunc( brace, lambda b : b.match_width( peak_points, stretch = True ).next_to(peak_points, UP, SMALL_BUFF) ), Transform( displayed_doppler_shift, actual_doppler_shift, rate_func = squish_rate_func(smooth, 0.3, 0.6) ), run_time = 3 ) self.wait(2) everything = VGroup( title, axes, pulse_graph, shift_graph, brace, displayed_doppler_shift ) rect = SurroundingRectangle(everything, color = WHITE) everything.add(rect) self.teacher_says( "I'll ignore certain \\\\ nuances for now.", target_mode = "shruggie", added_anims = [ everything.scale, 0.4, everything.to_corner, UP+LEFT, UpdateFromAlphaFunc( rect, lambda m, a : m.set_stroke(width = 2*a) ) ], ) self.play_student_changes(*3*["hesitant"]) self.wait(2) def get_spike_graph(self, x, color = RED, **kwargs): graph = self.axes.get_graph( lambda t : np.exp(-10*(t-x)**2)*np.cos(10*(t-x)), color = color, **kwargs ) graph.peak_point = VectorizedPoint(self.axes.input_to_graph_point(x, graph)) graph.add(graph.peak_point) return graph class TimeAndFrequencyGivePositionAndVelocity(IntroduceDopplerRadar): def construct(self): x = 7 freq = 25 axes = self.axes = Axes( x_min = 0, x_max = 10, y_min = -2, y_max = 2, ) axes.center() title = OldTexText("Echo signal") title.next_to(axes.y_axis, UP) axes.add(title) axes.to_edge(UP) graph = self.get_frequency_pulse_graph(x = x, freq = freq) graph.background_image_file = "blue_yellow_gradient" arrow = Arrow( axes.coords_to_point(0, -1.5), axes.coords_to_point(x, -1.5), color = WHITE, buff = SMALL_BUFF, ) time = OldTexText("Time") time.next_to(arrow, DOWN, SMALL_BUFF) delta_x = 0.7 brace = Brace( Line( axes.coords_to_point(x-delta_x, 1), axes.coords_to_point(x+delta_x, 1) ), UP ) frequency = OldTexText("Frequency") frequency.set_color(YELLOW) frequency.next_to(brace, UP, SMALL_BUFF) time_updown_arrow = OldTex("\\Updownarrow") time_updown_arrow.next_to(time, DOWN, SMALL_BUFF) freq_updown_arrow = time_updown_arrow.copy() freq_updown_arrow.next_to(frequency, UP, SMALL_BUFF) distance = OldTexText("Distance") distance.next_to(time_updown_arrow, DOWN, SMALL_BUFF) velocity = OldTexText("Velocity") velocity.next_to(freq_updown_arrow, UP, SMALL_BUFF) VGroup(freq_updown_arrow, velocity).match_style(frequency) self.add(axes) self.play(ShowCreation(graph)) self.play( GrowArrow(arrow), LaggedStartMap(FadeIn, time, run_time = 1) ) self.play( GrowFromCenter(brace), LaggedStartMap(FadeIn, frequency, run_time = 1) ) self.wait() self.play( GrowFromPoint(time_updown_arrow, time_updown_arrow.get_top()), ReplacementTransform( time.copy().fade(1), distance ) ) self.play( GrowFromPoint(freq_updown_arrow, freq_updown_arrow.get_top()), ReplacementTransform( frequency.copy().fade(1), velocity ) ) self.wait() class RadarOperatorUncertainty(Scene): def construct(self): dish = RadarDish() dish.scale(3) dish.move_to(4*RIGHT + 2*DOWN) dish_words = OldTexText("3b1b industrial \\\\ enterprises") dish_words.scale(0.25) dish_words.set_stroke(BLACK, 0.5) dish_words.set_color(BLACK) dish_words.move_to(dish, DOWN) dish_words.shift(SMALL_BUFF*(UP+2*LEFT)) dish.add(dish_words) randy = Randolph() randy.next_to(dish, LEFT, aligned_edge = DOWN) bubble = randy.get_bubble( width = 7, height = 4, ) echo_object = Square() echo_object.move_to(dish) echo_object.shift(FRAME_X_RADIUS*RIGHT) pulse = RadarPulse(dish, echo_object, speed = 6) plane = Plane().scale(0.5) plane.move_to(bubble.get_bubble_center()+LEFT) plane_cloud = ProbabalisticMobjectCloud( plane, fill_opacity = 0.3, n_copies = 10, ) plane_gdw = plane_cloud.gaussian_distribution_wrapper vector_cloud = ProbabalisticVectorCloud( center_func = plane_gdw.get_center, ) vector_gdw = vector_cloud.gaussian_distribution_wrapper vector_gdw.scale(0.05) vector_gdw.move_to(plane_gdw) vector_gdw.shift(2*RIGHT) self.add(randy, dish, bubble, plane_cloud, pulse) self.play(randy.change, "confused") self.wait(3) self.add(vector_cloud) for i in range(3): for plane_factor, vector_factor, freq in (0.05, 10, 0.01), (20, 0.1, 0.1): pulse.internal_time = 0 pulse.frequency = freq self.play( randy.change, "pondering", plane, plane_gdw.scale, plane_factor, vector_gdw.scale, vector_factor, ) self.wait(2) class AmbiguityInLongEchos(IntroduceDopplerRadar, PiCreatureScene): CONFIG = { "object_x_coords" : [7, 4, 6, 9, 8], "frequency_spread_factor" : 200, "n_pulse_singletons" : 16, "pulse_frequency" : 0.025, } def construct(self): self.setup_axes() self.setup_objects() self.send_long_pulse_single_echo() self.introduce_multiple_objects() self.use_short_pulse() self.fourier_transform_of_one_pulse() self.show_echos_of_moving_objects() self.overlapping_frequenies_of_various_objects() self.echos_of_long_pure_signal_in_frequency_space() self.concentrated_fourier_requires_long_time() def setup_axes(self): axes = self.axes = Axes( x_min = 0, x_max = 10, y_min = -1.5, y_max = 1.5, ) time_label = OldTexText("Time") time_label.next_to(axes.x_axis.get_right(), UP) axes.add(time_label) axes.center() axes.shift(DOWN) self.add(axes) dish = self.dish = RadarDish() dish.move_to(axes, LEFT) dish.to_edge(UP, buff = LARGE_BUFF) self.add(dish) def setup_objects(self): objects = self.objects = VGroup( Plane().flip(), SVGMobject( file_name = "blimp", color = BLUE_C, height = 0.5, ), SVGMobject( file_name = "biplane", color = RED_D, height = 0.5, ), SVGMobject( file_name = "helicopter", color = GREY_B, height = 0.5, ).rotate(-TAU/24), FalconHeavy(), ) y_shifts = [0.25, 0, 0.5, 0.25, -0.5] for x, y, obj in zip(self.object_x_coords, y_shifts, objects): obj.move_to(self.axes.coords_to_point(x, 0)) obj.align_to(self.dish) obj.shift(y*UP) self.object_velocities = [ 0.7*LEFT, 0.1*RIGHT, 0.4*LEFT, 0.4*RIGHT, 0.5*UP, ] def send_long_pulse_single_echo(self): x = self.object_x_coords[0] plane = self.objects[0] self.add(plane) randy = self.pi_creature self.remove(randy) pulse_graph = self.get_frequency_pulse_graph(x) pulse_graph.background_image_file = "blue_yellow_gradient" pulse = self.get_pulse(self.dish, plane) brace = Brace( Line( self.axes.coords_to_point(x-1, 1), self.axes.coords_to_point(x+1, 1), ), UP ) words = brace.get_text("Spread over time") self.add(pulse) self.wait() squished_rate_func = squish_rate_func(smooth, 0.6, 0.9) self.play( ShowCreation(pulse_graph, rate_func=linear), GrowFromCenter(brace, rate_func = squished_rate_func), Write(words, rate_func = squished_rate_func), run_time = 3, ) self.remove(pulse) self.play(FadeIn(randy)) self.play(PiCreatureBubbleIntroduction( randy, "Who cares?", bubble_type = ThoughtBubble, bubble_config = { "direction" : LEFT, "width" : 2, "height": 1.5, }, target_mode = "maybe", look_at = brace, )) self.play(Blink(randy)) self.play(LaggedStartMap( FadeOut, VGroup( randy.bubble, randy.bubble.content, brace, words, ) )) self.curr_graph = pulse_graph def introduce_multiple_objects(self): objects = self.objects x_coords = self.object_x_coords curr_graph = self.curr_graph randy = self.pi_creature graphs = VGroup(*[ self.get_frequency_pulse_graph(x) for x in x_coords ]) graphs.set_color_by_gradient(BLUE, YELLOW) sum_graph = self.axes.get_graph( lambda t : sum([ graph.underlying_function(t) for graph in graphs ]), num_graph_points = 1000 ) noise_function = lambda t : np.sum([ 0.5*np.sin(f*t)/f for f in (2, 3, 5, 7, 11, 13) ]) noisy_graph = self.axes.get_graph( lambda t : sum_graph.underlying_function(t)*(1+noise_function(t)), num_graph_points = 1000 ) for graph in sum_graph, noisy_graph: graph.background_image_file = "blue_yellow_gradient" pulses = self.get_pulses() self.play( LaggedStartMap(GrowFromCenter, objects[1:]), FadeOut(curr_graph), randy.change, "pondering" ) self.add(*pulses) self.wait(0.5) self.play( ShowCreation( sum_graph, rate_func=linear, run_time = 3.5, ), randy.change, "confused" ) self.remove(*pulses) self.play(randy.change, "pondering") self.play(Transform( sum_graph, noisy_graph, rate_func = lambda t : wiggle(t, 4), run_time = 3 )) self.wait(2) self.curr_graph = sum_graph def use_short_pulse(self): curr_graph = self.curr_graph objects = self.objects x_coords = self.object_x_coords randy = self.pi_creature self.frequency_spread_factor = 10 self.n_pulse_singletons = 4 self.pulse_frequency = 0.015 graphs = VGroup(*[ self.get_frequency_pulse_graph(x) for x in x_coords ]) sum_graph = self.axes.get_graph( lambda t : sum([ graph.underlying_function(t) for graph in graphs ]), num_graph_points = 1000 ) sum_graph.background_image_file = "blue_yellow_gradient" pulses = self.get_pulses() self.play(FadeOut(curr_graph)) self.add(*pulses) self.wait(0.5) self.play( ShowCreation( sum_graph, rate_func=linear, run_time = 3.5, ), randy.change, "happy" ) self.wait() self.curr_graph = sum_graph self.first_echo_graph = graphs[0] self.first_echo_graph.set_color(YELLOW) def fourier_transform_of_one_pulse(self): frequency_axes = Axes( x_min = 0, x_max = 20, x_axis_config = { "unit_size" : 0.5, "tick_frequency" : 2, }, y_min = -.01, y_max = .01, y_axis_config = { "unit_size" : 110, "tick_frequency" : 0.006 } ) frequency_label = OldTexText("Frequency") frequency_label.next_to(frequency_axes.x_axis.get_right(), UP) frequency_axes.add(frequency_label) first_echo_graph = self.first_echo_graph self.play( ApplyMethod( VGroup(self.axes, first_echo_graph).to_edge, UP, {"buff" : SMALL_BUFF}, rate_func = squish_rate_func(smooth, 0.5, 1) ), LaggedStartMap(FadeOut, self.objects), LaggedStartMap(FadeOut, VGroup( self.curr_graph, self.dish, self.pi_creature )), run_time = 2 ) # frequency_axes.next_to(self.axes, DOWN, LARGE_BUFF, LEFT) fourier_graph = get_fourier_graph( frequency_axes, first_echo_graph.underlying_function, t_min = 0, t_max = 25, complex_to_real_func = np.abs, ) fourier_graph.save_state() fourier_graph.move_to(first_echo_graph) h_vect = 4*RIGHT fourier_graph.shift(h_vect) fourier_graph.fade(1) f = 8 v_line = DashedLine( frequency_axes.coords_to_point(f, 0), frequency_axes.coords_to_point(f, frequency_axes.y_max), ) v_lines = VGroup( v_line.copy().shift(2*LEFT), v_line.copy().shift(2*RIGHT), ) rect = Rectangle(stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.25) rect.replace(v_lines, stretch = True) rect.save_state() rect.stretch(0, 0) self.play(Write(frequency_axes, run_time = 1)) self.play( ApplyFunction( lambda m : m.move_to(fourier_graph.saved_state).shift(-h_vect).fade(1), first_echo_graph.copy(), remover = True, ), fourier_graph.restore ) self.wait() self.play(ShowCreation(v_line)) self.play( ReplacementTransform(VGroup(v_line), v_lines), rect.restore ) self.wait() self.play(FadeOut(v_lines), FadeOut(rect)) self.frequency_axes = frequency_axes self.fourier_graph = fourier_graph def show_echos_of_moving_objects(self): objects = self.objects objects.save_state() object_velocities = self.object_velocities movements = self.object_movements = [ always_shift( obj, direction = v/get_norm(v), rate = get_norm(v) ) for v, obj in zip(object_velocities, objects) ] pulses = self.get_pulses() continual_anims = pulses+movements self.play( FadeOut(self.axes), FadeOut(self.first_echo_graph), LaggedStartMap(FadeIn, objects), FadeIn(self.dish) ) self.add(*continual_anims) self.wait(4) self.play(*[ UpdateFromAlphaFunc( obj, lambda m, a : m.set_fill(opacity = 1-a), ) for obj in objects ]) self.remove(*continual_anims) self.wait() def overlapping_frequenies_of_various_objects(self): frequency_axes = self.frequency_axes fourier_graph = self.fourier_graph shifted_graphs = self.get_shifted_frequency_graphs(fourier_graph) color = fourier_graph.get_color() shifted_graphs.set_color_by_gradient( average_color(color, WHITE), color, average_color(color, BLACK), ) sum_graph = self.get_sum_graph(frequency_axes, shifted_graphs) sum_graph.match_style(fourier_graph) shifted_graphs.save_state() self.play(ReplacementTransform( VGroup(fourier_graph), shifted_graphs, lag_ratio = 0.5, run_time = 2 )) self.wait() self.play( shifted_graphs.arrange, DOWN, shifted_graphs.move_to, fourier_graph, DOWN, ) self.wait() self.play(shifted_graphs.restore), self.play(ReplacementTransform( shifted_graphs, VGroup(sum_graph), )) self.wait() self.curr_fourier_graph = sum_graph def echos_of_long_pure_signal_in_frequency_space(self): curr_fourier_graph = self.curr_fourier_graph f_max = self.frequency_axes.y_max new_fourier_graph = self.frequency_axes.get_graph( lambda x : f_max * np.exp(-100*(x-8)**2), num_graph_points = 1000, ) new_fourier_graph.set_color(PINK) self.play( FadeOut(curr_fourier_graph), FadeIn(new_fourier_graph), ) self.fourier_graph = new_fourier_graph self.overlapping_frequenies_of_various_objects() def concentrated_fourier_requires_long_time(self): objects = self.objects objects.restore() object_movements = self.object_movements self.n_pulse_singletons = 32 pulses = self.get_pulses() randy = self.pi_creature continual_anims = object_movements+pulses self.play(FadeIn(randy)) self.add(*continual_anims) self.play(randy.change, "angry", *[ UpdateFromAlphaFunc(obj, lambda m, a : m.set_fill(opacity = a)) for obj in objects ]) self.play(Blink(randy)) self.wait(2) self.play(Blink(randy)) self.wait() self.play(randy.change, "plain", *[ UpdateFromAlphaFunc(obj, lambda m, a : m.set_fill(opacity = 1-a)) for obj in objects ]) self.wait() ### def get_frequency_pulse_graph(self, x, freq = 25, **kwargs): graph = IntroduceDopplerRadar.get_frequency_pulse_graph( self, x, freq, **kwargs ) return graph def get_pulse(self, dish, echo_object): return RadarPulse( dish, echo_object, n_pulse_singletons = self.n_pulse_singletons, frequency = 0.025, speed = 5.0, ) def get_pulses(self): return [ self.get_pulse( self.dish.copy().shift(0.01*obj.get_center()[0]), obj ) for obj in self.objects ] def create_pi_creature(self): randy = Randolph() randy.scale(0.5).flip() randy.to_edge(RIGHT, buff = 1.7).shift(0.5*UP) return randy def get_shifted_frequency_graphs(self, fourier_graph): frequency_axes = self.frequency_axes def get_func(v): return lambda f : fourier_graph.underlying_function(np.clip( f-5*v[0], frequency_axes.x_min, frequency_axes.x_max, )) def get_graph(func): return frequency_axes.get_graph(func) shifted_graphs = VGroup(*list(map( get_graph, list(map(get_func, self.object_velocities)) ))) shifted_graphs.match_style(fourier_graph) return shifted_graphs def get_sum_graph(self, axes, graphs): def get_func(graph): return graph.underlying_function funcs = list(map(get_func, graphs)) return axes.get_graph( lambda t : sum([func(t) for func in funcs]), ) class SummarizeFourierTradeoffForDoppler(Scene): def construct(self): time_axes = Axes( x_min = 0, x_max = 12, y_min = -0.5, y_max = 1, ) time_axes.center().to_edge(UP, buff = LARGE_BUFF) frequency_axes = time_axes.copy() frequency_axes.next_to(time_axes, DOWN, buff = 2) time_label = OldTexText("Time") frequency_label = OldTexText("Frequency") for label, axes in (time_label, time_axes), (frequency_label, frequency_axes): label.next_to(axes.get_right(), UP, SMALL_BUFF) axes.add(label) frequency_label.shift_onto_screen() title = OldTexText("Fourier Trade-off") title.next_to(time_axes, DOWN) self.add(title) #Position determines log of scale value for exponentials a_mob = VectorizedPoint() x_values = [3, 5, 6, 7, 8] v_values = [5, 5.5, 5.75, 6.5, 7] def get_top_graphs(): a = np.exp(a_mob.get_center()[0]) graphs = VGroup(*[ time_axes.get_graph(lambda t : np.exp(-5*a*(t-x)**2)) for x in x_values ]) graphs.set_color(WHITE) graphs.color_using_background_image("blue_yellow_gradient") return graphs def get_bottom_graphs(): a = np.exp(a_mob.get_center()[0]) graphs = VGroup(*[ frequency_axes.get_graph(lambda t : np.exp(-(5./a)*(t-v)**2)) for v in v_values ]) graphs.set_color(RED) return graphs top_graphs = get_top_graphs() bottom_graphs = get_bottom_graphs() update_top_graphs = Mobject.add_updater( top_graphs, lambda g : Transform(g, get_top_graphs()).update(1) ) update_bottom_graphs = Mobject.add_updater( bottom_graphs, lambda g : Transform(g, get_bottom_graphs()).update(1) ) self.add(time_axes, frequency_axes) self.add(update_top_graphs, update_bottom_graphs) shift_vect = 2*RIGHT for s in 1, -2, 1: self.play(a_mob.shift, s*shift_vect, run_time = 3) class MentionUncertaintyPrincipleCopy(MentionUncertaintyPrinciple): pass class IntroduceDeBroglie(Scene): CONFIG = { "default_wave_frequency" : 1, "wave_colors" : [BLUE_D, YELLOW], "dispersion_factor" : 1, "amplitude" : 1, } def construct(self): text_scale_val = 0.8, #Overlay real tower in video editor eiffel_tower = Line(3*DOWN, 3*UP, stroke_width = 0) picture = ImageMobject("de_Broglie") picture.set_height(4) picture.to_corner(UP+LEFT) name = OldTexText("Louis de Broglie") name.next_to(picture, DOWN) picture.save_state() picture.scale(0) picture.move_to(eiffel_tower.get_top()) broadcasts = [ Broadcast( eiffel_tower.get_top(), big_radius = 10, n_circles = 10, lag_ratio = 0.9, run_time = 7, rate_func = squish_rate_func(smooth, a, a+0.3), color = WHITE, ) for a in np.linspace(0, 0.7, 3) ] self.play(*broadcasts) self.play(picture.restore) self.play(Write(name)) self.wait() #Time line time_line = NumberLine( x_min = 1900, x_max = 1935, tick_frequency = 1, numbers_with_elongated_ticks = list(range(1900, 1941, 10)), color = BLUE_D ) time_line.stretch_to_fit_width(FRAME_WIDTH - picture.get_width() - 2) time_line.add_numbers(*time_line.numbers_with_elongated_ticks) time_line.next_to(picture, RIGHT, MED_LARGE_BUFF, DOWN) year_to_words = { 1914 : "Wold War I begins", 1915 : "Einstein field equations", 1916 : "Lewis dot formulas", 1917 : "Not a lot of physics...because war", 1918 : "S'more Rutherford badassery", 1919 : "Eddington confirms general relativity predictions", 1920 : "World is generally stoked on general relativity", 1921 : "Einstein gets long overdue Nobel prize", 1922 : "Stern-Gerlach Experiment", 1923 : "Compton scattering observed", 1924 : "de Broglie's thesis" } arrow = Vector(DOWN, color = WHITE) arrow.next_to(time_line.number_to_point(1914), UP) words = OldTexText(year_to_words[1914]) words.scale(text_scale_val) date = Integer(1914) date.next_to(arrow, UP, LARGE_BUFF) def get_year(alpha = 0): return int(time_line.point_to_number(arrow.get_end())) def update_words(words): text = year_to_words.get(get_year(), "Hi there") if text not in words.get_tex(): words.__init__(text) words.scale(text_scale_val) words.move_to(interpolate( arrow.get_top(), date.get_bottom(), 0.5 )) update_words(words) self.play( FadeIn(time_line), GrowArrow(arrow), Write(words), Write(date), run_time = 1 ) self.wait() self.play( arrow.next_to, time_line.number_to_point(1924), UP, ChangingDecimal( date, get_year, position_update_func = lambda m : m.next_to(arrow, UP, LARGE_BUFF) ), UpdateFromFunc(words, update_words), run_time = 3, ) self.wait() #Transform time_line line = time_line self.play( FadeOut(time_line.numbers), VGroup(arrow, words, date).shift, MED_LARGE_BUFF*UP, *[ ApplyFunction( lambda m : m.rotate(TAU/4).set_stroke(width = 0), mob, remover = True ) for mob in time_line.tick_marks ] ) #Wave function particle = VectorizedPoint() axes = Axes(x_min = -1, x_max = 10) axes.match_width(line) axes.shift(line.get_center() - axes.x_axis.get_center()) im_line = line.copy() im_line.set_color(YELLOW) wave_update_animation = self.get_wave_update_animation( axes, particle, line, im_line ) for x in range(3): particle.move_to(axes.coords_to_point(-10, 0)) self.play( ApplyMethod( particle.move_to, axes.coords_to_point(22, 0), rate_func=linear ), wave_update_animation, run_time = 3 ) self.wait() ### def get_wave_update_animation(self, axes, particle, re_line = None, im_line = None): line = Line( axes.x_axis.get_left(), axes.x_axis.get_right(), ) if re_line is None: re_line = line.copy() re_line.set_color(self.wave_colors[0]) if im_line is None: im_line = line.copy() im_line.set_color(self.wave_colors[1]) lines = VGroup(im_line, re_line) def update_lines(lines): waves = self.get_wave_pair(axes, particle) for line, wave in zip(lines, waves): wave.match_style(line) Transform(line, wave).update(1) return UpdateFromFunc(lines, update_lines) def get_wave( self, axes, particle, complex_to_real_func = lambda z : z.real, freq = None, **kwargs): freq = freq or self.default_wave_frequency k0 = 1./freq t0 = axes.x_axis.point_to_number(particle.get_center()) def func(x): dispersion = fdiv(1., self.dispersion_factor)*(np.sqrt(1./(1+t0**2))) wave_part = complex_to_real_func(np.exp( complex(0, TAU*freq*(x-dispersion)) )) bell_part = np.exp(-dispersion*(x-t0)**2) amplitude = self.amplitude return amplitude*wave_part*bell_part graph = axes.get_graph(func) return graph def get_wave_pair(self, axes, particle, colors = None, **kwargs): if colors is None and "color" not in kwargs: colors = self.wave_colors return VGroup(*[ self.get_wave( axes, particle, C_to_R, color = color, **kwargs ) for C_to_R, color in zip( [lambda z : z.imag, lambda z : z.real], colors ) ]) class ShowMomentumFormula(IntroduceDeBroglie, TeacherStudentsScene): CONFIG = { "default_wave_frequency" : 2, "dispersion_factor" : 0.25, "p_color" : BLUE, "xi_color" : YELLOW, "amplitude" : 0.5, } def construct(self): self.introduce_formula() self.react_to_claim() def introduce_formula(self): formula = p, eq, h, xi = OldTex("p", "=", "h", "\\xi") formula.move_to(ORIGIN) formula.scale(1.5) word_shift_val = 1.75 p_words = OldTexText("Momentum") p_words.next_to(p, UP, LARGE_BUFF).shift(word_shift_val*LEFT) p_arrow = Arrow( p_words.get_bottom(), p.get_corner(UP+LEFT), buff = SMALL_BUFF ) added_p_words = OldTexText("(Classically $m \\times v$)") added_p_words.move_to(p_words, DOWN) VGroup(p, p_words, added_p_words, p_arrow).set_color(self.p_color) xi_words = OldTexText("Spatial frequency") added_xi_words = OldTexText("(cycles per unit \\emph{distance})") xi_words.next_to(xi, UP, LARGE_BUFF).shift(word_shift_val*RIGHT) xi_words.align_to(p_words) xi_arrow = Arrow( xi_words.get_bottom(), xi.get_corner(UP+RIGHT), buff = SMALL_BUFF ) added_xi_words.move_to(xi_words, DOWN) added_xi_words.align_to(added_p_words, DOWN) VGroup(xi, xi_words, added_xi_words, xi_arrow).set_color(self.xi_color) axes = Axes( x_min = 0, x_max = FRAME_WIDTH, y_min = -1, y_max = 1, ) axes.center().to_edge(UP, buff = -0.5) # axes.next_to(formula, RIGHT) particle = VectorizedPoint() wave_update_animation = self.get_wave_update_animation(axes, particle) wave = wave_update_animation.mobject wave[0].set_stroke(width = 0) particle.next_to(wave, LEFT, buff = 2) wave_propagation = AnimationGroup( ApplyMethod(particle.move_to, axes.coords_to_point(30, 0)), wave_update_animation, run_time = 4, rate_func=linear, ) stopped_wave_propagation = AnimationGroup( ApplyMethod(particle.move_to, xi_words), wave_update_animation, run_time = 3, rate_func=linear, ) n_v_lines = 10 v_lines = VGroup(*[ DashedLine(UP, DOWN) for x in range(n_v_lines) ]) v_lines.match_color(xi) v_lines.arrange( RIGHT, buff = float(axes.x_axis.unit_size)/self.default_wave_frequency ) v_lines.move_to(stopped_wave_propagation.sub_anims[0].target_mobject) v_lines.align_to(wave) v_lines.shift(0.125*RIGHT) self.add(formula, wave) self.play( self.teacher.change, "raise_right_hand", GrowArrow(p_arrow), Succession( Write, p_words, ApplyMethod, p_words.next_to, added_p_words, UP, ), FadeIn( added_p_words, rate_func = squish_rate_func(smooth, 0.5, 1), run_time = 2, ), wave_propagation ) self.play( Write(xi_words), GrowArrow(xi_arrow), self.change_students("confused", "erm", "sassy"), stopped_wave_propagation ) self.play( FadeIn(added_xi_words), xi_words.next_to, added_xi_words, UP, ) self.play( LaggedStartMap(ShowCreation, v_lines), self.change_students(*["pondering"]*3) ) self.play(LaggedStartMap(FadeOut, v_lines)) self.wait() self.formula_labels = VGroup( p_words, p_arrow, added_p_words, xi_words, xi_arrow, added_xi_words, ) self.set_variables_as_attrs(wave, wave_propagation, formula) def react_to_claim(self): formula_labels = self.formula_labels full_formula = VGroup(self.formula, formula_labels) full_formula.save_state() wave_propagation = self.wave_propagation student = self.students[2] self.student_says( "Hang on...", bubble_config = {"height" : 2, "width" : 2, "direction" : LEFT}, target_mode = "sassy", index = 2, added_anims = [self.teacher.change, "plain"] ) student.bubble.add(student.bubble.content) self.wait() kwargs = { "path_arc" : TAU/4, "lag_ratio" : 0.5, "lag_ratio" : 0.7, "run_time" : 1.5, } self.play( full_formula.scale, 0, full_formula.move_to, student.eyes.get_bottom()+SMALL_BUFF*DOWN, Animation(student.bubble), **kwargs ) self.play(full_formula.restore, Animation(student.bubble), **kwargs) wave_propagation.update_config( rate_func = lambda a : interpolate(0.35, 1, a) ) self.play( wave_propagation, RemovePiCreatureBubble(student, target_mode = "confused"), ) wave_propagation.update_config(rate_func = lambda t : t) self.student_says( "Physics is \\\\ just weird", bubble_config = {"height" : 2.5, "width" : 3}, target_mode = "shruggie", index = 0, added_anims = [ApplyMethod(full_formula.shift, UP)] ) self.wait() self.play( wave_propagation, ApplyMethod(full_formula.shift, DOWN), FadeOut(self.students[0].bubble), FadeOut(self.students[0].bubble.content), self.change_students(*3*["pondering"]), self.teacher.change, "pondering", ) self.play(wave_propagation) class AskPhysicists(PiCreatureScene): def construct(self): morty, physy1, physy2, physy3 = self.pi_creatures formula = OldTex("p", "=", "h", "\\xi") formula.set_color_by_tex_to_color_map({ "p" : BLUE, "\\xi" : YELLOW, }) formula.scale(1.5) formula.to_edge(UP) formula.save_state() formula.shift(DOWN) formula.fade(1) self.play(formula.restore) self.pi_creature_says( morty, "So...why?", target_mode = "maybe" ) self.wait(2) self.play( RemovePiCreatureBubble(morty), PiCreatureSays( physy2, "Take the Schrödinger equation \\\\ with $H = \\frac{p^2}{2m}+V(x)$", bubble_config = {"fill_opacity" : 0.9}, ), ) self.play( PiCreatureSays( physy1, "Even classically position and \\\\ momentum are conjugate", target_mode = "surprised", bubble_config = {"fill_opacity" : 0.9}, ), ) self.play( PiCreatureSays( physy3, "Consider special relativity \\\\ together with $E = hf$", target_mode = "hooray", bubble_config = {"fill_opacity" : 0.9}, ), morty.change, "guilty" ) self.wait(2) ### def create_pi_creatures(self): scale_factor = 0.85 morty = Mortimer().flip() morty.scale(scale_factor) morty.to_corner(DOWN+LEFT) physies = VGroup(*[ PiCreature(color = c).flip() for c in (GREY, GREY_B, GREY_D) ]) physies.arrange(RIGHT, buff = MED_SMALL_BUFF) physies.scale(scale_factor) physies.to_corner(DOWN+RIGHT) self.add(physies) return VGroup(morty, *physies) class SortOfDopplerEffect(PiCreatureScene): CONFIG = { "omega" : np.pi, "arrow_spacing" : 0.25, } def setup(self): PiCreatureScene.setup(self) rect = self.screen_rect = ScreenRectangle(height = FRAME_HEIGHT) rect.set_stroke(width = 0) self.camera = MovingCamera( rect, **self.camera_config ) def construct(self): screen_rect = self.screen_rect #x-coordinate gives time t_tracker = VectorizedPoint() #x-coordinate gives wave number k_tracker = VectorizedPoint(2*RIGHT) always_shift(t_tracker, RIGHT, 1) def get_wave(): t = t_tracker.get_center()[0] k = k_tracker.get_center()[0] omega = self.omega color = interpolate_color( BLUE, RED, (k-2)/2.0 ) func = lambda x : 0.5*np.cos(omega*t - k*x) graph = FunctionGraph( func, x_min = -5*FRAME_X_RADIUS, x_max = FRAME_X_RADIUS, color = color, ) return VGroup(graph, *[ Arrow( x*RIGHT, x*RIGHT + func(x)*UP, color = color ) for x in np.arange( -4*FRAME_X_RADIUS, FRAME_X_RADIUS, self.arrow_spacing ) ]) return wave = get_wave() wave_update = Mobject.add_updater( wave, lambda w : Transform(w, get_wave()).update(1) ) rect = ScreenRectangle(height = 2) rect.to_edge(RIGHT) always_shift(rect, LEFT, 1) rect_movement = rect randy = self.pi_creature randy_look_at = Mobject.add_updater( randy, lambda r : r.look_at(rect) ) ref_frame1 = OldTexText("Reference frame 1") # ref_frame1.next_to(randy, UP, aligned_edge = LEFT) ref_frame1.to_edge(UP) ref_frame2 = OldTexText("Reference frame 2") ref_frame2.next_to(rect, UP) # ref_frame2.set_fill(opacity = 0) ref_frame2_follow = Mobject.add_updater( ref_frame2, lambda m : m.next_to(rect, UP) ) ref_frame_1_continual_anim = ContinualAnimation(ref_frame1) self.add( t_tracker, wave_update, rect_movement, randy_look_at, ref_frame2_follow, ref_frame_1_continual_anim ) self.add(ref_frame1) self.play(randy.change, "pondering") self.wait(4) start_height = screen_rect.get_height() start_center = screen_rect.get_center() self.play( UpdateFromAlphaFunc( screen_rect, lambda m, a : m.move_to( interpolate(start_center, rect.get_center(), a) ) ), k_tracker.shift, 2*RIGHT, ) self.play( MaintainPositionRelativeTo( screen_rect, rect, run_time = 4 ), ) self.play( screen_rect.move_to, rect.get_right()+FRAME_X_RADIUS*LEFT, k_tracker.shift, 2*LEFT, ) #Frequency words temporal_frequency = OldTexText("Temporal", "frequency") spatial_frequency = OldTexText("Spatial", "frequency") temporal_frequency.move_to(screen_rect).to_edge(UP) spatial_frequency.next_to(temporal_frequency, DOWN) cross = Cross(temporal_frequency[0]) time = OldTexText("Time") space = OldTexText("Space") time.next_to(temporal_frequency, RIGHT, buff = 2) space.next_to(time, DOWN) space.align_to(spatial_frequency) self.play(FadeIn(temporal_frequency)) self.play(ShowCreation(cross)) self.play(Write(spatial_frequency)) self.wait() self.play(FadeIn(time), FadeIn(space)) self.play( Transform(time, space), Transform(space, time), lag_ratio = 0.5, run_time = 1, ) self.play(FadeOut(time), FadeOut(space)) self.wait(3) ### def create_pi_creature(self): return Randolph().scale(0.5).to_corner(DOWN+LEFT) class HangingWeightsScene(MovingCameraScene): CONFIG = { "frequency" : 0.5, "ceiling_radius" : 3*FRAME_X_RADIUS, "n_springs" : 72, "amplitude" : 0.6, "spring_radius" : 0.15, } def construct(self): self.setup_springs() self.setup_weights() self.introduce() self.show_analogy_with_electron() self.metaphor_for_something() self.moving_reference_frame() def setup_springs(self): ceiling = self.ceiling = Line(LEFT, RIGHT) ceiling.scale(self.ceiling_radius) ceiling.to_edge(UP, buff = LARGE_BUFF) self.add(ceiling) def get_spring(alpha, height = 2): t_max = 6.5 r = self.spring_radius s = (height - r)/(t_max**2) spring = ParametricCurve( lambda t : op.add( r*(np.sin(TAU*t)*RIGHT+np.cos(TAU*t)*UP), s*((t_max - t)**2)*DOWN, ), t_min = 0, t_max = t_max, color = WHITE, stroke_width = 2, ) spring.alpha = alpha spring.move_to(ceiling.point_from_proportion(alpha), UP) spring.color_using_background_image("grey_gradient") return spring alphas = np.linspace(0, 1, self.n_springs) bezier([0, 1, 0, 1]) springs = self.springs = VGroup(*list(map(get_spring, alphas))) k_tracker = self.k_tracker = VectorizedPoint() t_tracker = self.t_tracker = VectorizedPoint() always_shift(t_tracker, RIGHT, 1) self.t_tracker_walk = t_tracker equilibrium_height = springs.get_height() def update_springs(springs): for spring in springs: k = k_tracker.get_center()[0] t = t_tracker.get_center()[0] f = self.frequency x = spring.get_top()[0] A = self.amplitude d_height = A*np.cos(TAU*f*t - k*x) new_spring = get_spring(spring.alpha, 2+d_height) Transform(spring, new_spring).update(1) spring_update_anim = Mobject.add_updater(springs, update_springs) self.spring_update_anim = spring_update_anim spring_update_anim.update(0) self.play( ShowCreation(ceiling), LaggedStartMap(ShowCreation, springs) ) def setup_weights(self): weights = self.weights = VGroup() weight_anims = weight_anims = [] for spring in self.springs: x = spring.get_top()[0] mass = np.exp(-0.1*x**2) weight = Circle(radius = 0.15) weight.start_radius = 0.15 weight.target_radius = 0.25*mass #For future update weight.spring = spring weight_anim = Mobject.add_updater( weight, lambda w : w.move_to(w.spring.get_bottom()) ) weight_anim.update(0) weight_anims.append(weight_anim) weights.add(weight) weights.set_fill(opacity = 1) weights.set_color_by_gradient(BLUE_D, BLUE_E, BLUE_D) weights.set_stroke(WHITE, 1) self.play(LaggedStartMap(GrowFromCenter, weights)) self.add(self.t_tracker_walk) self.add(self.spring_update_anim) self.add(*weight_anims) def introduce(self): arrow = Arrow(4*LEFT, LEFT) arrows = VGroup(arrow, arrow.copy().flip(about_point = ORIGIN)) arrows.set_color(WHITE) self.wait(3) self.play(*list(map(GrowArrow, arrows))) self.play(*[ UpdateFromAlphaFunc( weight, lambda w, a : w.set_width( 2*interpolate(w.start_radius, w.target_radius, a) ), run_time = 2 ) for weight in self.weights ]) self.play(FadeOut(arrows)) self.wait(3) def show_analogy_with_electron(self): words = OldTexText( "Analogous to the energy of a particle \\\\", "(in the sense of $E=mc^2$)" ) words.move_to(DOWN) self.play(Write(words)) self.wait(3) self.play(FadeOut(words)) def metaphor_for_something(self): de_broglie = ImageMobject("de_Broglie") de_broglie.set_height(3.5) de_broglie.to_corner(DOWN+RIGHT) words = OldTexText(""" If a photon's energy is carried as a wave \\\\ is this true for any particle? """) words.next_to(de_broglie, LEFT) einstein = ImageMobject("Einstein") einstein.match_height(de_broglie) einstein.to_corner(DOWN+LEFT) for picture in de_broglie, einstein: picture.backdrop = Rectangle() picture.backdrop.replace(picture, stretch = True) picture.backdrop.set_fill(BLACK, 1) picture.backdrop.set_stroke(BLACK, 0) self.play( Animation(de_broglie.backdrop, remover = True), FadeIn(de_broglie) ) self.play(Write(words)) self.wait(7) self.play( FadeOut(words), Animation(einstein.backdrop, remover = True), FadeIn(einstein) ) self.wait(2) self.de_broglie = de_broglie self.einstein = einstein def moving_reference_frame(self): rect = ScreenRectangle(height = 2.1*FRAME_Y_RADIUS) rect_movement = always_shift(rect, direction = LEFT, rate = 2) camera_frame = self.camera_frame self.add(rect) self.play( Animation(self.de_broglie.backdrop, remover = True), FadeOut(self.de_broglie), Animation(self.einstein.backdrop, remover = True), FadeOut(self.einstein), ) self.play(camera_frame.scale, 3, {"about_point" : 2*UP}) self.play(rect.shift, FRAME_WIDTH*RIGHT, path_arc = -TAU/2) self.add(rect_movement) self.wait(3) def zoom_into_reference_frame(): original_height = camera_frame.get_height() original_center = camera_frame.get_center() self.play( UpdateFromAlphaFunc( camera_frame, lambda c, a : c.set_height( interpolate(original_height, 0.95*rect.get_height(), a) ).move_to( interpolate(original_center, rect.get_center(), a) ) ), ApplyMethod(self.k_tracker.shift, RIGHT) ) self.play(MaintainPositionRelativeTo( camera_frame, rect, run_time = 6 )) self.play( camera_frame.set_height, original_height, camera_frame.move_to, original_center, ApplyMethod(self.k_tracker.shift, LEFT) ) zoom_into_reference_frame() self.wait() self.play( UpdateFromAlphaFunc(rect, lambda m, a : m.set_stroke(width = 2*(1-a))) ) index = int(0.5*len(self.springs)) weights = VGroup(self.weights[index], self.weights[index+4]) flashes = list(map(self.get_peak_flash_anim, weights)) weights.save_state() weights.set_fill(RED) self.add(*flashes) self.wait(5) rect.align_to(camera_frame, RIGHT) self.play(UpdateFromAlphaFunc(rect, lambda m, a : m.set_stroke(width = 2*a))) randy = Randolph(mode = "pondering") randy.look(UP+RIGHT) de_broglie = ImageMobject("de_Broglie") de_broglie.set_height(6) de_broglie.next_to(4*DOWN, DOWN) self.add( Mobject.add_updater( randy, lambda m : m.next_to( rect.get_corner(DOWN+LEFT), UP+RIGHT, MED_LARGE_BUFF, ).look_at(weights) ), de_broglie ) self.wait(2) zoom_into_reference_frame() self.wait(8) ### def get_peak_flash_anim(self, weight): mobject = Mobject() #Dummy mobject.last_y = 0 mobject.last_dy = 0 mobject.curr_anim = None mobject.curr_anim_time = 0 mobject.time_since_last_flash = 0 def update(mob, dt): mob.time_since_last_flash += dt point = weight.get_center() y = point[1] mob.dy = y - mob.last_y different_dy = np.sign(mob.dy) != np.sign(mob.last_dy) if different_dy and mob.time_since_last_flash > 0.5: mob.curr_anim = Flash( VectorizedPoint(point), flash_radius = 0.5, line_length = 0.3, run_time = 0.2, ) mob.submobjects = [mob.curr_anim.mobject] mob.time_since_last_flash = 0 mob.last_y = float(y) mob.last_dy = float(mob.dy) ## if mob.curr_anim: mob.curr_anim_time += dt if mob.curr_anim_time > mob.curr_anim.run_time: mob.curr_anim = None mob.submobjects = [] mob.curr_anim_time = 0 return mob.curr_anim.update(mob.curr_anim_time/mob.curr_anim.run_time) return Mobject.add_updater(mobject, update) class MinutPhysicsWrapper(Scene): def construct(self): logo = ImageMobject("minute_physics_logo", invert = True) logo.to_corner(UP+LEFT) self.add(logo) title = OldTexText("Minute Physics on special relativity") title.to_edge(UP).shift(MED_LARGE_BUFF*RIGHT) screen_rect = ScreenRectangle() screen_rect.set_width(title.get_width() + LARGE_BUFF) screen_rect.next_to(title, DOWN) self.play(ShowCreation(screen_rect)) self.play(Write(title)) self.wait(2) class WhatDoesTheFourierTradeoffTellUs(TeacherStudentsScene): def construct(self): self.teacher_says( "So! What does \\\\ the Fourier trade-off \\\\ tell us?", target_mode = "surprised", bubble_config = {"width" : 4, "height" : 3} ) self.play_student_changes(*["thinking"]*3) self.wait(4) class FourierTransformOfWaveFunction(Scene): CONFIG = { "wave_stroke_width" : 3, "wave_color" : BLUE, } def construct(self): self.show_wave_packet() self.take_fourier_transform() self.show_correlations_with_pure_frequencies() self.this_is_momentum() self.show_tradeoff() def setup(self): self.x0_tracker = ValueTracker(-3) self.k_tracker = ValueTracker(1) self.a_tracker = ExponentialValueTracker(0.5) def show_wave_packet(self): axes = Axes( x_min = 0, x_max = 12, y_min = -1, y_max = 1, y_axis_config = { "tick_frequency" : 0.5 } ) position_label = OldTexText("Position") position_label.next_to(axes.x_axis.get_right(), UP) axes.add(position_label) axes.center().to_edge(UP, buff = LARGE_BUFF) wave = self.get_wave(axes) wave_update_animation = UpdateFromFunc( wave, lambda w : Transform(w, self.get_wave(axes)).update(1) ) self.add(axes, wave) self.play( self.x0_tracker.set_value, 5, wave_update_animation, run_time = 3, ) self.wait() self.wave_function = wave.underlying_function self.wave_update_animation = wave_update_animation self.wave = wave self.axes = axes def take_fourier_transform(self): wave = self.wave wave_update_animation = self.wave_update_animation frequency_axes = Axes( x_min = 0, x_max = 3, x_axis_config = { "unit_size" : 4, "tick_frequency" : 0.25, "numbers_with_elongated_ticks" : [1, 2] }, y_min = -0.15, y_max = 0.15, y_axis_config = { "unit_size" : 7.5, "tick_frequency" : 0.05, } ) label = self.frequency_x_axis_label = OldTexText("Spatial frequency") label.next_to(frequency_axes.x_axis.get_right(), UP) frequency_axes.add(label) frequency_axes.move_to(self.axes, LEFT) frequency_axes.to_edge(DOWN, buff = LARGE_BUFF) label.shift_onto_screen() def get_wave_function_fourier_graph(): return get_fourier_graph( frequency_axes, self.get_wave_func(), t_min = 0, t_max = 15, ) fourier_graph = get_wave_function_fourier_graph() self.fourier_graph_update_animation = UpdateFromFunc( fourier_graph, lambda m : Transform( m, get_wave_function_fourier_graph() ).update(1) ) wave_copy = wave.copy() wave_copy.generate_target() wave_copy.target.move_to(fourier_graph, LEFT) wave_copy.target.fade(1) fourier_graph.save_state() fourier_graph.move_to(wave, LEFT) fourier_graph.fade(1) arrow = Arrow( self.axes.coords_to_point(5, -1), frequency_axes.coords_to_point(1, 0.1), color = YELLOW, ) fourier_label = OldTexText("Fourier Transform") fourier_label.next_to(arrow.get_center(), RIGHT) self.play(ReplacementTransform( self.axes.copy(), frequency_axes )) self.play( MoveToTarget(wave_copy, remover = True), fourier_graph.restore, GrowArrow(arrow), Write(fourier_label, run_time = 1), ) self.wait() self.frequency_axes = frequency_axes self.fourier_graph = fourier_graph self.fourier_label = VGroup(arrow, fourier_label) def show_correlations_with_pure_frequencies(self): frequency_axes = self.frequency_axes axes = self.axes sinusoid = axes.get_graph( lambda x : 0.5*np.cos(TAU*x), x_min = -FRAME_X_RADIUS, x_max = 3*FRAME_X_RADIUS, ) sinusoid.to_edge(UP, buff = SMALL_BUFF) v_line = DashedLine(1.5*UP, ORIGIN, color = YELLOW) v_line.move_to(frequency_axes.coords_to_point(1, 0), DOWN) f_equals = OldTex("f = ") freq_decimal = DecimalNumber(1) freq_decimal.next_to(f_equals, RIGHT, buff = SMALL_BUFF) freq_label = VGroup(f_equals, freq_decimal) freq_label.next_to( v_line, UP, SMALL_BUFF, submobject_to_align = f_equals[0] ) self.play( ShowCreation(sinusoid), ShowCreation(v_line), Write(freq_label, run_time = 1), FadeOut(self.fourier_label) ) last_f = 1 for f in 1.4, 0.7, 1: self.play( sinusoid.stretch,f/last_f, 0, {"about_point" : axes.coords_to_point(0, 0)}, v_line.move_to, frequency_axes.coords_to_point(f, 0), DOWN, MaintainPositionRelativeTo(freq_label, v_line), ChangeDecimalToValue(freq_decimal, f), run_time = 3, ) last_f = f self.play(*list(map(FadeOut, [ sinusoid, v_line, freq_label ]))) def this_is_momentum(self): formula = OldTex("p", "=", "h", "\\xi") formula.set_color_by_tex_to_color_map({ "p" : BLUE, "xi" : YELLOW, }) formula.next_to( self.frequency_x_axis_label, UP ) f_max = 0.12 brace = Brace(Line(2*LEFT, 2*RIGHT), UP) brace.move_to(self.frequency_axes.coords_to_point(1, f_max), DOWN) words = OldTexText("This wave \\\\ describes momentum") words.next_to(brace, UP) self.play(Write(formula)) self.wait() self.play( GrowFromCenter(brace), Write(words) ) brace.add(words) for k in 2, 0.5, 1: self.play( self.k_tracker.set_value, k, self.wave_update_animation, self.fourier_graph_update_animation, UpdateFromFunc( brace, lambda b : b.move_to( self.frequency_axes.coords_to_point( self.k_tracker.get_value(), f_max, ), DOWN ) ), run_time = 2 ) self.wait() self.play(*list(map(FadeOut, [brace, words, formula]))) def show_tradeoff(self): for a in 5, 0.1, 0.01, 10, 0.5: self.play( ApplyMethod( self.a_tracker.set_value, a, run_time = 2 ), self.wave_update_animation, self.fourier_graph_update_animation ) self.wait() ## def get_wave_func(self): x0 = self.x0_tracker.get_value() k = self.k_tracker.get_value() a = self.a_tracker.get_value() A = a**(0.25) return lambda x : A*np.cos(TAU*k*x)*np.exp(-a*(x - x0)**2) def get_wave(self, axes): return axes.get_graph( self.get_wave_func(), color = self.wave_color, stroke_width = self.wave_stroke_width ) class DopplerComparisonTodos(TODOStub): CONFIG = { "message" : """ Insert some Doppler footage, insert some hanging spring scene, insert position-momentum Fourier trade-off """ } class MusicalNote(AddingPureFrequencies): def construct(self): speaker = self.speaker = SVGMobject(file_name = "speaker") speaker.move_to(2*DOWN) randy = self.pi_creature axes = Axes( x_min = 0, x_max = 10, y_min = -1.5, y_max = 1.5 ) axes.center().to_edge(UP) time_label = OldTexText("Time") time_label.next_to(axes.x_axis.get_right(), UP) axes.add(time_label) graph = axes.get_graph( lambda x : op.mul( np.exp(-0.2*(x-4)**2), 0.3*(np.cos(2*TAU*x) + np.cos(3*TAU*x) + np.cos(5*TAU*x)), ), ) graph.set_color(BLUE) v_line = DashedLine(ORIGIN, 0.5*UP) v_line_update = UpdateFromFunc( v_line, lambda l : l.put_start_and_end_on_with_projection( graph.get_points()[-1], axes.x_axis.number_to_point( axes.x_axis.point_to_number(graph.get_points()[-1]) ) ) ) self.add(speaker, axes) self.play( randy.change, "pondering", self.get_broadcast_animation(n_circles = 6, run_time = 5), self.get_broadcast_animation(n_circles = 12, run_time = 5), ShowCreation(graph, run_time = 5, rate_func=linear), v_line_update ) self.wait(2) class AskAboutUncertainty(TeacherStudentsScene): def construct(self): self.student_says( "What does this have \\\\ to do with ``certainty''", bubble_config = {"direction" : LEFT}, index = 2 ) self.play(PiCreatureSays( self.students[0], "What even are \\\\ these waves?", target_mode = "confused" )) self.wait(2) class ProbabalisticDetection(FourierTransformOfWaveFunction): CONFIG = { "wave_stroke_width" : 2, } def construct(self): self.setup_wave() self.detect_only_single_points() self.show_probability_distribution() self.show_concentration_of_the_wave() def setup_wave(self): axes = Axes( x_min = 0, x_max = 10, y_min = -0.5, y_max = 1.5, y_axis_config = { "unit_size" : 1.5, "tick_frequency" : 0.25, } ) axes.set_stroke(width = 2) axes.center() self.x0_tracker.set_value(5) self.k_tracker.set_value(1) self.a_tracker.set_value(0.2) wave = self.get_wave(axes) self.wave_update_animation = UpdateFromFunc( wave, lambda w : Transform(w, self.get_wave(axes)).update(1) ) self.k_tracker.save_state() self.k_tracker.set_value(0) bell_curve = self.get_wave(axes) self.k_tracker.restore() bell_curve.set_stroke(width = 0) bell_curve.set_fill(BLUE, opacity = 0.5) squared_bell_curve = axes.get_graph( lambda x : bell_curve.underlying_function(x)**2 ).match_style(bell_curve) self.set_variables_as_attrs( axes, wave, bell_curve, squared_bell_curve ) def detect_only_single_points(self): particle = ProbabalisticDotCloud( n_copies = 100, fill_opacity = 0.05, time_per_change = 0.05, ) particle.mobject[0].set_fill(BLUE, opacity = 1) gdw = particle.gaussian_distribution_wrapper rect = Rectangle( stroke_width = 0, height = 0.5, width = 2, ) rect.set_fill(YELLOW, 0.3) rect.move_to(self.axes.coords_to_point(self.x0_tracker.get_value(), 0)) brace = Brace(rect, UP, buff = 0) question = OldTexText("Do we detect the particle \\\\ in this region?") question.next_to(brace, UP) question.add_background_rectangle() rect.save_state() rect.stretch(0, 0) gdw_anim = Mobject.add_updater( gdw, lambda m : m.set_width( 2.0/(self.a_tracker.get_value()**(0.5)) ).move_to(rect) ) self.add(rect, brace, question) yes = OldTexText("Yes").set_color(GREEN) no = OldTexText("No").set_color(RED) for word in yes, no: word.next_to(rect, DOWN) # word.add_background_rectangle() answer = VGroup() def update_answer(answer): px = particle.mobject[0].get_center()[0] lx = rect.get_left()[0] rx = rect.get_right()[0] if lx < px < rx: answer.submobjects = [yes] else: answer.submobjects = [no] answer_anim = Mobject.add_updater(answer, update_answer) self.add(gdw_anim, particle) self.play( GrowFromCenter(brace), rect.restore, Write(question) ) self.wait() self.add(answer_anim) self.wait(4) self.add_foreground_mobjects(answer, particle.mobject) self.question_group = VGroup(question, brace) self.particle = particle self.rect = rect def show_probability_distribution(self): axes = self.axes wave = self.wave bell_curve = self.bell_curve question_group = self.question_group gdw = self.particle.gaussian_distribution_wrapper rect = self.rect v_lines = VGroup(*[ DashedLine(ORIGIN, 3*UP).move_to(point, DOWN) for point in (rect.get_left(), rect.get_right()) ]) self.play( FadeIn(VGroup(axes, wave)), question_group.next_to, v_lines, UP, {"buff" : 0}, *list(map(ShowCreation, v_lines)) ) self.wait(10) def show_concentration_of_the_wave(self): self.play( self.a_tracker.set_value, 5, self.wave_update_animation, ) self.wait(10) class HeisenbergCommentTodos(TODOStub): CONFIG = { "message" : "Insert position-momentum trade-off" } class HeisenbergPetPeeve(PiCreatureScene): def construct(self): morty, other = self.pi_creatures particle = ProbabalisticDotCloud() gdw = particle.gaussian_distribution_wrapper gdw.to_edge(UP, buff = LARGE_BUFF) gdw.stretch_to_fit_width(3) gdw.rotate(3*DEGREES) self.add(particle) self.wait() self.play(PiCreatureSays( other, """ According to the H.U.P., the \\\\ universe is unknowable! """, target_mode = "speaking" )) self.play(morty.change, "angry") self.wait(3) self.play( PiCreatureSays( morty, "Well, yes and no", target_mode = "sassy", ), RemovePiCreatureBubble( other, target_mode = "erm" ) ) self.wait(4) ### def create_pi_creatures(self): morty = Mortimer() morty.to_corner(DOWN+RIGHT) other = PiCreature(color = MAROON_E) other.to_edge(DOWN).shift(3*LEFT) return VGroup(morty, other) class OneLevelDeeper(Scene): def construct(self): heisenberg = ImageMobject("Heisenberg") heisenberg.to_corner(UP+LEFT) self.add(heisenberg) hup_words = OldTexText("Heisenberg's uncertainty principle") wave_words = OldTexText("Interpretation of the wave function") arrow = Vector(UP) group = VGroup(hup_words, arrow, wave_words) group.arrange(DOWN) randomness = ProbabalisticMobjectCloud( OldTexText("Randomness"), n_copies = 5, time_per_change = 0.05 ) gdw = randomness.gaussian_distribution_wrapper gdw.rotate(TAU/4) gdw.set_height(1) # gdw.set_width(4) gdw.next_to(hup_words, UP, MED_LARGE_BUFF) self.add(hup_words, randomness) self.wait(4) self.play( FadeIn(wave_words), GrowArrow(arrow), ApplyMethod( gdw.next_to, wave_words, DOWN, MED_LARGE_BUFF, path_arc = TAU/2, ) ) self.wait(6) class BetterTranslation(TeacherStudentsScene): def construct(self): english_term = OldTexText("Uncertainty principle") german_word = OldTexText("Unschärferelation") translation = OldTexText("Unsharpness relation") to_german_words = OldTexText("In German") to_german_words.scale(0.5) to_german_arrow = Vector(DOWN, color = WHITE, buff = SMALL_BUFF) to_german_words.next_to(to_german_arrow, RIGHT, SMALL_BUFF) to_german_words.set_color(YELLOW) to_german_group = VGroup(to_german_arrow, to_german_words) translation_words = OldTexText("Literal translation") translation_words.scale(0.5) translation_arrow = Vector(DOWN, color = WHITE, buff = SMALL_BUFF) translation_words.next_to(translation_arrow, LEFT, SMALL_BUFF) translation_words.set_color(YELLOW) translation_group = VGroup(translation_arrow, translation_words) english_term.next_to(self.teacher, UP+LEFT) english_term.save_state() english_term.shift(DOWN) english_term.fade(1) self.play( english_term.restore, self.change_students(*["pondering"]*3) ) self.wait() german_word.move_to(english_term) to_german_group.next_to( german_word, UP, submobject_to_align = to_german_arrow ) self.play( self.teacher.change, "raise_right_hand", english_term.next_to, to_german_arrow, UP ) self.play( GrowArrow(to_german_arrow), FadeIn(to_german_words), ReplacementTransform( english_term.copy().fade(1), german_word ) ) self.wait(2) group = VGroup(english_term, to_german_group, german_word) translation.move_to(german_word) translation_group.next_to( german_word, UP, submobject_to_align = translation_arrow ) self.play( group.next_to, translation_arrow, UP, ) self.play( GrowArrow(translation_arrow), FadeIn(translation_words), ReplacementTransform( german_word.copy().fade(1), translation ) ) self.play_student_changes(*["happy"]*3) self.wait(2) class ThinkOfHeisenbergUncertainty(PiCreatureScene): def construct(self): morty = self.pi_creature morty.center().to_edge(DOWN).shift(LEFT) dot_cloud = ProbabalisticDotCloud() dot_gdw = dot_cloud.gaussian_distribution_wrapper dot_gdw.set_width(1) dot_gdw.rotate(TAU/8) dot_gdw.move_to(FRAME_X_RADIUS*RIGHT/2), vector_cloud = ProbabalisticVectorCloud( center_func = dot_gdw.get_center ) vector_gdw = vector_cloud.gaussian_distribution_wrapper vector_gdw.set_width(0.1) vector_gdw.rotate(TAU/8) vector_gdw.next_to(dot_gdw, UP+LEFT, LARGE_BUFF) time_tracker = ValueTracker(0) self.add() freq = 1 continual_anims = [ always_shift(time_tracker, direction = RIGHT, rate = 1), Mobject.add_updater( dot_gdw, lambda d : d.set_width( (np.cos(freq*time_tracker.get_value()) + 1.1)/2 ) ), Mobject.add_updater( vector_gdw, lambda d : d.set_width( (-np.cos(freq*time_tracker.get_value()) + 1.1)/2 ) ), dot_cloud, vector_cloud ] self.add(*continual_anims) position, momentum, time, frequency = list(map(TexText, [ "Position", "Momentum", "Time", "Frequency" ])) VGroup(position, time).set_color(BLUE) VGroup(momentum, frequency).set_color(YELLOW) groups = VGroup() for m1, m2 in (position, momentum), (time, frequency): arrow = OldTex("\\updownarrow").scale(1.5) group = VGroup(m1, arrow, m2) group.arrange(DOWN) lp, rp = parens = OldTex("\\big(\\big)") parens.stretch(1.5, 1) parens.match_height(group) lp.next_to(group, LEFT, buff = SMALL_BUFF) rp.next_to(group, RIGHT, buff = SMALL_BUFF) group.add(parens) groups.add(group) arrow = OldTex("\\Leftrightarrow").scale(2) groups.submobjects.insert(1, arrow) groups.arrange(RIGHT) groups.next_to(morty, UP+RIGHT, LARGE_BUFF) groups.shift_onto_screen() self.play(PiCreatureBubbleIntroduction( morty, "Heisenberg \\\\ uncertainty \\\\ principle", bubble_type = ThoughtBubble, bubble_config = {"height" : 4, "width" : 4, "direction" : RIGHT}, target_mode = "pondering" )) self.wait() self.play(morty.change, "confused", dot_gdw) self.wait(10) self.play( ApplyMethod( VGroup(dot_gdw, vector_gdw ).shift, FRAME_X_RADIUS*RIGHT, rate_func = running_start ) ) self.remove(*continual_anims) self.play( morty.change, "raise_left_hand", groups, FadeIn( groups, lag_ratio = 0.5, run_time = 3, ) ) self.wait(2) # End things class PatreonMention(PatreonThanks): def construct(self): morty = Mortimer() morty.next_to(ORIGIN, DOWN) patreon_logo = PatreonLogo() patreon_logo.to_edge(UP) thank_you = OldTexText("Thank you.") thank_you.next_to(patreon_logo, DOWN) self.play( DrawBorderThenFill(patreon_logo), morty.change, "gracious" ) self.play(Write(thank_you)) self.wait(3) class Promotion(PiCreatureScene): CONFIG = { "camera_class" : ThreeDCamera, "seconds_to_blink" : 5, } def construct(self): aops_logo = AoPSLogo() aops_logo.next_to(self.pi_creature, UP+LEFT) url = OldTexText( "AoPS.com/", "3b1b", arg_separator = "" ) url.to_corner(UP+LEFT) url_rect = Rectangle(color = BLUE) url_rect.replace( url.get_part_by_tex("3b1b"), stretch = True ) url_rect.stretch_in_place(1.1, dim = 1) rect = Rectangle(height = 9, width = 16) rect.set_height(4.5) rect.next_to(url, DOWN) rect.to_edge(LEFT) rect.set_stroke(width = 0) mathy = Mathematician() mathy.flip() mathy.to_corner(DOWN+RIGHT) morty = self.pi_creature morty.save_state() book = ImageMobject("AoPS_volume_2") book.set_height(2) book.next_to(mathy, UP+LEFT).shift(MED_LARGE_BUFF*LEFT) mathy.get_center = mathy.get_top words = OldTexText(""" Interested in working for \\\\ one of my favorite math\\\\ education companies? """, alignment = "") words.to_edge(UP) arrow = Arrow( aops_logo.get_top(), morty.get_top(), path_arc = -0.4*TAU, stroke_width = 5, tip_length = 0.5, ) arrow.tip.shift(SMALL_BUFF*DOWN) self.add(words) self.play( self.pi_creature.change_mode, "raise_right_hand", *[ DrawBorderThenFill( submob, run_time = 2, rate_func = squish_rate_func(double_smooth, a, a+0.5) ) for submob, a in zip(aops_logo, np.linspace(0, 0.5, len(aops_logo))) ] ) self.play( words.scale, 0.75, words.next_to, url, DOWN, LARGE_BUFF, words.shift_onto_screen, Write(url), ) self.wait(2) self.play( LaggedStartMap( ApplyFunction, aops_logo, lambda mob : (lambda m : m.shift(0.2*UP).set_color(YELLOW), mob), rate_func = there_and_back, run_time = 1, ), morty.change, "thinking" ) self.wait() self.play(ShowCreation(arrow)) self.play(FadeOut(arrow)) self.wait() # To teacher self.play( morty.change_mode, "plain", morty.flip, morty.scale, 0.7, morty.next_to, mathy, LEFT, LARGE_BUFF, morty.to_edge, DOWN, FadeIn(mathy), ) self.play( PiCreatureSays( mathy, "", bubble_config = {"width" : 5}, look_at = morty.eyes, ), morty.change, "happy", aops_logo.shift, 1.5*UP + 0.5*RIGHT ) self.play(Blink(mathy)) self.wait() self.play( RemovePiCreatureBubble( mathy, target_mode = "raise_right_hand" ), aops_logo.to_corner, UP+RIGHT, aops_logo.shift, MED_SMALL_BUFF*DOWN, GrowFromPoint(book, mathy.get_corner(UP+LEFT)), ) self.play(morty.change, "pondering", book) self.wait(3) self.play(Blink(mathy)) self.wait() self.play( Animation( BackgroundRectangle(book, fill_opacity = 1), remover = True ), FadeOut(book), ) print(self.num_plays) self.play( FadeOut(words), ShowCreation(rect), morty.restore, morty.change, "happy", rect, FadeOut(mathy), ) self.wait(10) self.play(ShowCreation(url_rect)) self.play( FadeOut(url_rect), url.get_part_by_tex("3b1b").set_color, BLUE, ) self.wait(15) class PuzzleStatement(Scene): def construct(self): aops_logo = AoPSLogo() url = OldTexText("AoPS.com/3b1b") url.next_to(aops_logo, UP) group = VGroup(aops_logo, url) group.to_edge(UP) self.add(group) words = OldTexText(""" AoPS must choose one of 20 people to send to a tug-of-war tournament. We don't care who we send, as long as we don't send our weakest person. \\\\ \\\\ Each person has a different strength, but we don't know those strengths. We get 10 intramural 10-on-10 matches to determine who we send. Can we make sure we don't send the weakest person? """, alignment = "") words.set_width(FRAME_WIDTH - 2) words.next_to(group, DOWN, LARGE_BUFF) self.play(LaggedStartMap(FadeIn, words, run_time = 5, lag_ratio = 0.2)) self.wait(2) class UncertaintyEndScreen(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", "Samantha D. Suplee", "Mark Govea", "John Haley", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Desmos ", "Boris Veselinovich", "Ryan Dahl", "Ripta Pasay", "Eric Lavault", "Randall Hunt", "Andrew Busey", "Mads Elvheim", "Tianyu Ge", "Awoo", "Dr. David G. Stork", "Linh Tran", "Jason Hise", "Bernd Sing", "James H. Park", "Ankalagon ", "Mathias Jansson", "David Clark", "Ted Suzman", "Eric Chow", "Michael Gardner", "David Kedmey", "Jonathan Eppele", "Clark Gaebel", "Jordan Scales", "Ryan Atallah", "supershabam ", "1stViewMaths", "Jacob Magnuson", "Chloe Zhou", "Ross Garber", "Thomas Tarler", "Isak Hietala", "Egor Gumenuk", "Waleed Hamied", "Oliver Steele", "Yaw Etse", "David B", "Delton Ding", "James Thornton", "Felix Tripier", "Arthur Zey", "George Chiesa", "Norton Wang", "Kevin Le", "Alexander Feldman", "David MacCumber", "Jacob Kohl", "Frank Secilia", "George John", "Akash Kumar", "Britt Selvitelle", "Jonathan Wilson", "Michael Kunze", "Giovanni Filippi", "Eric Younge", "Prasant Jagannath", "Andrejs olins", "Cody Brocious", ], } class Thumbnail(Scene): def construct(self): uncertainty_principle = OldTexText("Uncertainty \\\\", "principle") uncertainty_principle[1].shift(SMALL_BUFF*UP) quantum = OldTexText("Quantum") VGroup(uncertainty_principle, quantum).scale(2.5) uncertainty_principle.to_edge(UP, MED_LARGE_BUFF) quantum.to_edge(DOWN, MED_LARGE_BUFF) arrow = OldTex("\\Downarrow") arrow.scale(4) arrow.move_to(Line( uncertainty_principle.get_bottom(), quantum.get_top(), )) cross = Cross(arrow) cross.set_stroke(RED, 20) is_word, not_word = is_not = OldTexText("is", "\\emph{NOT}") is_not.scale(3) is_word.move_to(arrow) # is_word.shift(0.6*UP) not_word.set_color(RED) not_word.set_stroke(RED, 3) not_word.rotate(10*DEGREES, about_edge = DOWN+LEFT) not_word.next_to(is_word, DOWN, 0.1*SMALL_BUFF) dot_cloud = ProbabalisticDotCloud( n_copies = 1000, ) dot_gdw = dot_cloud.gaussian_distribution_wrapper # dot_gdw.rotate(3*DEGREES) dot_gdw.rotate(25*DEGREES) # dot_gdw.scale(2) dot_gdw.scale(2) # dot_gdw.move_to(quantum.get_bottom()+SMALL_BUFF*DOWN) dot_gdw.move_to(quantum) def get_func(a): return lambda t : 0.5*np.exp(-a*t**2)*np.cos(TAU*t) axes = Axes( x_min = -6, x_max = 6, x_axis_config = {"unit_size" : 0.25} ) graphs = VGroup(*[ axes.get_graph(get_func(a)) for a in (10, 3, 1, 0.3, 0.1,) ]) graphs.arrange(DOWN, buff = 0.6) graphs.to_corner(UP+LEFT) graphs.set_color_by_gradient(BLUE_B, BLUE_D) frequency_axes = Axes( x_min = 0, x_max = 2, x_axis_config = {"unit_size" : 1} ) fourier_graphs = VGroup(*[ get_fourier_graph( frequency_axes, graph.underlying_function, t_min = -10, t_max = 10, ) for graph in graphs ]) for graph, fourier_graph in zip(graphs, fourier_graphs): fourier_graph.pointwise_become_partial(fourier_graph, 0.02, 0.06) fourier_graph.scale(3) fourier_graph.stretch(3, 1) fourier_graph.move_to(graph) fourier_graph.to_edge(RIGHT) self.add(graphs, fourier_graphs) self.add(dot_cloud) self.add( uncertainty_principle, quantum, ) self.add(arrow, cross) # self.add(is_word) # self.add(is_not)
#!/usr/bin/env python # -*- coding: utf-8 -*- from manim_imports_ext import * import warnings warnings.warn(""" Warning: This file makes use of ContinualAnimation, which has since been deprecated """) import types import functools LIGHT_COLOR = YELLOW INDICATOR_RADIUS = 0.7 INDICATOR_STROKE_WIDTH = 1 INDICATOR_STROKE_COLOR = WHITE INDICATOR_TEXT_COLOR = WHITE INDICATOR_UPDATE_TIME = 0.2 FAST_INDICATOR_UPDATE_TIME = 0.1 OPACITY_FOR_UNIT_INTENSITY = 0.2 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.5 AMBIENT_DIMMED = 0.2 SPOTLIGHT_FULL = 0.9 SPOTLIGHT_DIMMED = 0.2 LIGHT_COLOR = YELLOW DEGREES = TAU/360 inverse_power_law = lambda maxint,scale,cutoff,exponent: \ (lambda r: maxint * (cutoff/(r/scale+cutoff))**exponent) inverse_quadratic = lambda maxint, scale, cutoff: inverse_power_law(maxint,scale,cutoff,2) # A = np.array([5.,-3.,0.]) # B = np.array([-5.,3.,0.]) # C = np.array([-5.,-3.,0.]) # xA = A[0] # yA = A[1] # xB = B[0] # yB = B[1] # xC = C[0] # yC = C[1] # find the coords of the altitude point H # as the solution of a certain LSE # prelim_matrix = np.array([[yA - yB, xB - xA], [xA - xB, yA - yB]]) # sic # prelim_vector = np.array([xB * yA - xA * yB, xC * (xA - xB) + yC * (yA - yB)]) # H2 = np.linalg.solve(prelim_matrix,prelim_vector) # H = np.append(H2, 0.) class AngleUpdater(ContinualAnimation): def __init__(self, angle_arc, spotlight, **kwargs): self.angle_arc = angle_arc self.spotlight = spotlight ContinualAnimation.__init__(self, self.angle_arc, **kwargs) def update_mobject(self, dt): new_arc = self.angle_arc.copy().set_bound_angles( start = self.spotlight.start_angle(), stop = self.spotlight.stop_angle() ) new_arc.init_points() new_arc.move_arc_center_to(self.spotlight.get_source_point()) self.angle_arc.set_points(new_arc.get_points()) self.angle_arc.add_tip( tip_length = ARC_TIP_LENGTH, at_start = True, at_end = True ) class LightIndicator(Mobject): CONFIG = { "radius": 0.5, "reading_height" : 0.25, "intensity": 0, "opacity_for_unit_intensity": 1, "fill_color" : YELLOW, "precision": 3, "show_reading": True, "measurement_point": ORIGIN, "light_source": None } def init_points(self): self.background = Circle(color=BLACK, radius = self.radius) self.background.set_fill(opacity = 1.0) self.foreground = Circle(color=self.color, radius = self.radius) self.foreground.set_stroke( color=INDICATOR_STROKE_COLOR, width=INDICATOR_STROKE_WIDTH ) self.foreground.set_fill(color = self.fill_color) self.add(self.background, self.foreground) self.reading = DecimalNumber(self.intensity,num_decimal_places = self.precision) self.reading.set_fill(color=INDICATOR_TEXT_COLOR) self.reading.set_height(self.reading_height) self.reading.move_to(self.get_center()) if self.show_reading: self.add(self.reading) def set_intensity(self, new_int): self.intensity = new_int new_opacity = min(1, new_int * self.opacity_for_unit_intensity) self.foreground.set_fill(opacity=new_opacity) ChangeDecimalToValue(self.reading, new_int).update(1) if new_int > 1.1: self.reading.set_fill(color = BLACK) else: self.reading.set_fill(color = WHITE) return self def get_measurement_point(self): if self.measurement_point is not None: return self.measurement_point else: return self.get_center() def measured_intensity(self): distance = get_norm( self.get_measurement_point() - self.light_source.get_source_point() ) intensity = self.light_source.opacity_function(distance) / self.opacity_for_unit_intensity return intensity def update_mobjects(self): if self.light_source == None: print("Indicator cannot update, reason: no light source found") self.set_intensity(self.measured_intensity()) class UpdateLightIndicator(AnimationGroup): def __init__(self, indicator, intensity, **kwargs): if not isinstance(indicator,LightIndicator): raise Exception("This transform applies only to LightIndicator") target_foreground = indicator.copy().set_intensity(intensity).foreground change_opacity = Transform( indicator.foreground, target_foreground ) changing_decimal = ChangeDecimalToValue(indicator.reading, intensity) AnimationGroup.__init__(self, changing_decimal, change_opacity, **kwargs) self.mobject = indicator class ContinualLightIndicatorUpdate(ContinualAnimation): def update_mobject(self,dt): self.mobject.update_mobjects() def copy_func(f): """Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)""" g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__) g = functools.update_wrapper(g, f) return g class ScaleLightSources(Transform): def __init__(self, light_sources_mob, factor, about_point = None, **kwargs): if about_point == None: about_point = light_sources_mob.get_center() ls_target = light_sources_mob.copy() for submob in ls_target: if type(submob) == LightSource: new_sp = submob.source_point.copy() # a mob new_sp.scale(factor,about_point = about_point) submob.move_source_to(new_sp.get_location()) #ambient_of = copy_func(submob.ambient_light.opacity_function) #new_of = lambda r: ambient_of(r/factor) #submob.ambient_light.opacity_function = new_of #spotlight_of = copy_func(submob.ambient_light.opacity_function) #new_of = lambda r: spotlight_of(r/factor) #submob.spotlight.change_opacity_function(new_of) new_r = factor * submob.radius submob.set_radius(new_r) new_r = factor * submob.ambient_light.radius submob.ambient_light.radius = new_r new_r = factor * submob.spotlight.radius submob.spotlight.radius = new_r submob.ambient_light.scale_about_point(factor, new_sp.get_center()) submob.spotlight.scale_about_point(factor, new_sp.get_center()) Transform.__init__(self,light_sources_mob,ls_target,**kwargs) class ThreeDSpotlight(VGroup): CONFIG = { "fill_color" : YELLOW, } def __init__(self, screen, ambient_light, source_point_func, **kwargs): self.screen = screen self.ambient_light = ambient_light self.source_point_func = source_point_func self.dr = ambient_light.radius/ambient_light.num_levels VGroup.__init__(self, **kwargs) def update(self): screen = self.screen source_point = self.source_point_func() dr = self.dr corners = screen.get_anchors() self.submobjects = [VGroup() for a in screen.get_anchors()] distance = get_norm( screen.get_center() - source_point ) n_parts = np.ceil(distance/dr) alphas = np.linspace(0, 1, n_parts+1) for face, (c1, c2) in zip(self, adjacent_pairs(corners)): face.submobjects = [] for a1, a2 in zip(alphas, alphas[1:]): face.add(Polygon( interpolate(source_point, c1, a1), interpolate(source_point, c1, a2), interpolate(source_point, c2, a2), interpolate(source_point, c2, a1), fill_color = self.fill_color, fill_opacity = self.ambient_light.opacity_function(a1*distance), stroke_width = 0 )) class ContinualThreeDLightConeUpdate(ContinualAnimation): def update(self, dt): self.mobject.update() ### class ThinkAboutPondScene(PiCreatureScene): CONFIG = { "default_pi_creature_class" : Randolph, } def construct(self): randy = self.pi_creature randy.to_corner(DOWN+LEFT) bubble = ThoughtBubble( width = 11, height = 8, ) circles = bubble[:3] angle = -15*DEGREES circles.rotate(angle, about_point = bubble.get_bubble_center()) circles.shift(LARGE_BUFF*LEFT) for circle in circles: circle.rotate(-angle) bubble.pin_to(randy) bubble.shift(DOWN) bubble[:3].rotate(np.pi, axis = UP+2*RIGHT, about_edge = UP+LEFT) bubble[:3].scale(0.7, about_edge = DOWN+RIGHT) bubble[:3].shift(1.5*DOWN) for oval in bubble[:3]: oval.rotate(TAU/3) self.play( randy.change, "thinking", ShowCreation(bubble) ) self.wait(2) self.play(randy.change, "happy", bubble) self.wait(4) self.play(randy.change, "hooray", bubble) self.wait(2) class IntroScene(PiCreatureScene): CONFIG = { "rect_height" : 0.075, "duration" : 1.0, "eq_spacing" : 3 * MED_LARGE_BUFF, "n_rects_to_show" : 30, } def construct(self): randy = self.get_primary_pi_creature() randy.scale(0.7).to_corner(DOWN+RIGHT) self.build_up_euler_sum() self.show_history() # self.other_pi_formulas() # self.refocus_on_euler_sum() def build_up_euler_sum(self): morty = self.pi_creature euler_sum = self.euler_sum = OldTex( "1", "+", "{1 \\over 4}", "+", "{1 \\over 9}", "+", "{1 \\over 16}", "+", "{1 \\over 25}", "+", "\\cdots", "=", arg_separator = " \\, " ) equals_sign = euler_sum.get_part_by_tex("=") plusses = euler_sum.get_parts_by_tex("+") term_mobjects = euler_sum.get_parts_by_tex("1") self.euler_sum.to_edge(UP) self.euler_sum.shift(2*LEFT) max_n = self.n_rects_to_show terms = [1./(n**2) for n in range(1, max_n + 1)] series_terms = list(np.cumsum(terms)) series_terms.append(np.pi**2/6) ##Just force this up there partial_sum_decimal = self.partial_sum_decimal = DecimalNumber( series_terms[1], num_decimal_places = 2 ) partial_sum_decimal.next_to(equals_sign, RIGHT) ## Number line number_line = self.number_line = NumberLine( x_min = 0, color = WHITE, number_at_center = 1, stroke_width = 1, numbers_with_elongated_ticks = [0,1,2,3], numbers_to_show = np.arange(0,5), unit_size = 5, tick_frequency = 0.2, line_to_number_buff = MED_LARGE_BUFF ) number_line.add_numbers() number_line.to_edge(LEFT) number_line.shift(MED_LARGE_BUFF*UP) # create slabs for series terms lines = VGroup() rects = self.rects = VGroup() rect_labels = VGroup() slab_colors = it.cycle([YELLOW, BLUE]) rect_anims = [] rect_label_anims = [] for i, t1, t2 in zip(it.count(1), [0]+series_terms, series_terms): color = next(slab_colors) line = Line(*list(map(number_line.number_to_point, [t1, t2]))) rect = Rectangle( stroke_width = 0, fill_opacity = 1, fill_color = color ) rect.match_width(line) rect.stretch_to_fit_height(self.rect_height) rect.move_to(line) if i <= 5: if i == 1: rect_label = OldTex("1") else: rect_label = OldTex("\\frac{1}{%d}"%(i**2)) rect_label.scale(0.75) max_width = 0.7*rect.get_width() if rect_label.get_width() > max_width: rect_label.set_width(max_width) rect_label.next_to(rect, UP, buff = MED_LARGE_BUFF/(i+1)) term_mobject = term_mobjects[i-1] rect_anim = GrowFromPoint(rect, term_mobject.get_center()) rect_label_anim = ReplacementTransform( term_mobject.copy(), rect_label ) else: rect_label = VectorizedPoint() rect_anim = GrowFromPoint(rect, rect.get_left()) rect_label_anim = FadeIn(rect_label) rects.add(rect) rect_labels.add(rect_label) rect_anims.append(rect_anim) rect_label_anims.append(rect_label_anim) lines.add(line) dots = OldTex("\\dots").scale(0.5) last_rect = rect_anims[-1].target_mobject dots.set_width(0.9*last_rect.get_width()) dots.move_to(last_rect, UP+RIGHT) rects.submobjects[-1] = dots rect_anims[-1] = FadeIn(dots) self.add(number_line) self.play(FadeIn(euler_sum[0])) self.play( rect_anims[0], rect_label_anims[0] ) for i in range(4): self.play( FadeIn(term_mobjects[i+1]), FadeIn(plusses[i]), ) anims = [ rect_anims[i+1], rect_label_anims[i+1], ] if i == 0: anims += [ FadeIn(equals_sign), FadeIn(partial_sum_decimal) ] elif i <= 5: anims += [ ChangeDecimalToValue( partial_sum_decimal, series_terms[i+1], run_time = 1, num_decimal_places = 6, position_update_func = lambda m: m.next_to(equals_sign, RIGHT) ) ] self.play(*anims) for i in range(4, len(series_terms)-2): anims = [ rect_anims[i+1], ChangeDecimalToValue( partial_sum_decimal, series_terms[i+1], num_decimal_places = 6, ), ] if i == 5: anims += [ FadeIn(euler_sum[-3]), # + FadeIn(euler_sum[-2]), # ... ] self.play(*anims, run_time = 2./i) brace = self.brace = Brace(partial_sum_decimal, DOWN) q_marks = self.q_marks = OldTexText("???") q_marks.next_to(brace, DOWN) q_marks.set_color(LIGHT_COLOR) self.play( GrowFromCenter(brace), Write(q_marks), ChangeDecimalToValue( partial_sum_decimal, series_terms[-1], num_decimal_places = 6, ), morty.change, "confused", ) self.wait() self.number_line_group = VGroup( number_line, rects, rect_labels ) def show_history(self): # Pietro Mengoli in 1644 morty = self.pi_creature pietro = ImageMobject("Pietro_Mengoli") euler = ImageMobject("Euler") pietro_words = OldTexText("Challenge posed by \\\\ Pietro Mengoli in 1644") pietro_words.scale(0.75) pietro_words.next_to(pietro, DOWN) pietro.add(pietro_words) euler_words = OldTexText("Solved by Leonard \\\\ Euler in 1735") euler_words.scale(0.75) euler_words.next_to(euler, DOWN) euler.add(euler_words) pietro.next_to(FRAME_X_RADIUS*LEFT, LEFT) euler.next_to(FRAME_X_RADIUS*RIGHT, RIGHT) pi_answer = self.pi_answer = OldTex("{\\pi^2 \\over 6}") pi_answer.set_color(YELLOW) pi_answer.move_to(self.partial_sum_decimal, LEFT) equals_sign = OldTex("=") equals_sign.next_to(pi_answer, RIGHT) pi_answer.shift(SMALL_BUFF*UP) self.partial_sum_decimal.generate_target() self.partial_sum_decimal.target.next_to(equals_sign, RIGHT) pi = pi_answer[0] pi_rect = SurroundingRectangle(pi, color = RED) pi_rect.save_state() pi_rect.set_height(FRAME_Y_RADIUS) pi_rect.center() pi_rect.set_stroke(width = 0) squared = pi_answer[1] squared_rect = SurroundingRectangle(squared, color = BLUE) brace = Brace( VGroup(self.euler_sum, self.partial_sum_decimal.target), DOWN, buff = SMALL_BUFF ) basel_text = brace.get_text("Basel problem", buff = SMALL_BUFF) self.number_line_group.save_state() self.play( pietro.next_to, ORIGIN, LEFT, LARGE_BUFF, self.number_line_group.next_to, FRAME_Y_RADIUS*DOWN, DOWN, morty.change, "pondering", ) self.wait(2) self.play(euler.next_to, ORIGIN, RIGHT, LARGE_BUFF) self.wait(2) self.play( ReplacementTransform(self.q_marks, pi_answer), FadeIn(equals_sign), FadeOut(self.brace), MoveToTarget(self.partial_sum_decimal) ) self.wait() self.play(morty.change, "surprised") self.play(pi_rect.restore) self.wait() self.play(Transform(pi_rect, squared_rect)) self.play(FadeOut(pi_rect)) self.play(morty.change, "hesitant") self.wait(2) self.play( GrowFromCenter(brace), euler.to_edge, DOWN, pietro.to_edge, DOWN, self.number_line_group.restore, self.number_line_group.shift, LARGE_BUFF*RIGHT, ) self.play(Write(basel_text)) self.play(morty.change, "happy") self.wait(4) def other_pi_formulas(self): self.play( FadeOut(self.rects), FadeOut(self.number_line) ) self.leibniz_sum = OldTex( "1-{1\\over 3}+{1\\over 5}-{1\\over 7}+{1\\over 9}-\\cdots", "=", "{\\pi \\over 4}") self.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} \\cdots", "=", "{\\pi \\over 2}") self.leibniz_sum.next_to(self.euler_sum.get_part_by_tex("="), DOWN, buff = self.eq_spacing, submobject_to_align = self.leibniz_sum.get_part_by_tex("=") ) self.wallis_product.next_to(self.leibniz_sum.get_part_by_tex("="), DOWN, buff = self.eq_spacing, submobject_to_align = self.wallis_product.get_part_by_tex("=") ) self.play( Write(self.leibniz_sum) ) self.play( Write(self.wallis_product) ) def refocus_on_euler_sum(self): self.euler_sum.add(self.pi_answer) self.play( FadeOut(self.leibniz_sum), FadeOut(self.wallis_product), ApplyMethod(self.euler_sum.shift, ORIGIN + 2*UP - self.euler_sum.get_center()) ) # focus on pi squared pi_squared = self.euler_sum.get_part_by_tex("\\pi")[-3] self.play( ScaleInPlace(pi_squared,2,rate_func = wiggle) ) # Morty thinks of a circle q_circle = Circle( stroke_color = YELLOW, fill_color = YELLOW, fill_opacity = 0.5, radius = 0.4, stroke_width = 10.0 ) q_mark = OldTex("?") q_mark.next_to(q_circle) thought = Group(q_circle, q_mark) q_mark.set_height(0.8 * q_circle.get_height()) self.pi_creature_thinks(thought,target_mode = "confused", bubble_config = { "height" : 2, "width" : 3 }) self.wait() class PiHidingWrapper(Scene): def construct(self): title = OldTexText("Pi hiding in prime regularities") title.to_edge(UP) screen = ScreenRectangle(height = 6) screen.next_to(title, DOWN) self.add(title) self.play(ShowCreation(screen)) self.wait(2) class MathematicalWebOfConnections(PiCreatureScene): def construct(self): self.complain_that_pi_is_not_about_circles() self.show_other_pi_formulas() self.question_fundamental() self.draw_circle() self.remove_all_but_basel_sum() self.show_web_of_connections() self.show_light() def complain_that_pi_is_not_about_circles(self): jerk, randy = self.pi_creatures words = self.words = OldTexText( "I am not", "fundamentally \\\\", "about circles" ) words.set_color_by_tex("fundamentally", YELLOW) self.play(PiCreatureSays( jerk, words, target_mode = "angry" )) self.play(randy.change, "guilty") self.wait(2) def show_other_pi_formulas(self): jerk, randy = self.pi_creatures words = self.words basel_sum = OldTex( "1 + {1 \\over 4} + {1 \\over 9} + {1 \\over 16} + \\cdots", "=", "{\\pi^2 \\over 6}" ) leibniz_sum = OldTex( "1-{1\\over 3}+{1\\over 5}-{1\\over 7}+{1\\over 9}-\\cdots", "=", "{\\pi \\over 4}") 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} \\cdots", "=", "{\\pi \\over 2}") basel_sum.move_to(randy) basel_sum.to_edge(UP) basel_equals = basel_sum.get_part_by_tex("=") formulas = VGroup(basel_sum, leibniz_sum, wallis_product) formulas.scale(0.75) formulas.arrange(DOWN, buff = MED_LARGE_BUFF) for formula in formulas: basel_equals_x = basel_equals.get_center()[0] formula_equals_x = formula.get_part_by_tex("=").get_center()[0] formula.shift((basel_equals_x - formula_equals_x)*RIGHT) formulas.to_corner(UP+RIGHT) formulas.shift(2*LEFT) self.formulas = formulas self.play( jerk.change, "sassy", randy.change, "raise_right_hand", FadeOut(jerk.bubble), words.next_to, jerk, UP, FadeIn(basel_sum, lag_ratio = 0.5, run_time = 3) ) for formula in formulas[1:]: self.play( FadeIn( formula, lag_ratio = 0.5, run_time = 3 ), ) self.wait() def question_fundamental(self): jerk, randy = self.pi_creatures words = self.words fundamentally = words.get_part_by_tex("fundamentally") words.remove(fundamentally) self.play( fundamentally.move_to, self.pi_creatures, fundamentally.shift, UP, FadeOut(words), jerk.change, "pondering", randy.change, "pondering", ) self.wait() question = OldTexText("Does this mean \\\\ anything?") question.scale(0.8) question.set_stroke(WHITE, 0.5) question.next_to(fundamentally, DOWN, LARGE_BUFF) arrow = Arrow(question, fundamentally) arrow.set_color(WHITE) self.play( FadeIn(question), GrowArrow(arrow) ) self.wait() fundamentally.add(question, arrow) self.fundamentally = fundamentally def draw_circle(self): semi_circle = Arc(angle = np.pi, radius = 2) radius = Line(ORIGIN, semi_circle.get_points()[0]) radius.set_color(BLUE) semi_circle.set_color(YELLOW) VGroup(radius, semi_circle).move_to( FRAME_X_RADIUS*LEFT/2 + FRAME_Y_RADIUS*UP/2, ) decimal = DecimalNumber(0) def decimal_position_update_func(decimal): decimal.move_to(semi_circle.get_points()[-1]) decimal.shift(0.3*radius.get_vector()) one = OldTex("1") one.next_to(radius, UP) self.play(ShowCreation(radius), FadeIn(one)) self.play( Rotate(radius, np.pi, about_point = radius.get_start()), ShowCreation(semi_circle), ChangeDecimalToValue( decimal, np.pi, position_update_func = decimal_position_update_func ), MaintainPositionRelativeTo(one, radius), run_time = 3, ) self.wait(2) self.circle_group = VGroup(semi_circle, radius, one, decimal) def remove_all_but_basel_sum(self): to_shift_down = VGroup( self.circle_group, self.pi_creatures, self.fundamentally, self.formulas[1:], ) to_shift_down.generate_target() for part in to_shift_down.target: part.move_to(FRAME_HEIGHT*DOWN) basel_sum = self.formulas[0] self.play( MoveToTarget(to_shift_down), basel_sum.scale, 1.5, basel_sum.move_to, 1.5*DOWN, ) self.basel_sum = basel_sum def show_web_of_connections(self): self.remove(self.pi_creatures) title = OldTexText("Interconnected web of mathematics") title.to_edge(UP) basel_sum = self.basel_sum dots = VGroup(*[ Dot(radius = 0.1).move_to( (j - 0.5*(i%2))*RIGHT + \ (np.sqrt(3)/2.0)* i*DOWN + \ 0.5*(random.random()*RIGHT + random.random()*UP), ) for i in range(4) for j in range(7+(i%2)) ]) dots.set_height(3) dots.next_to(title, DOWN, MED_LARGE_BUFF) edges = VGroup() for x in range(100): d1, d2 = random.sample(dots, 2) edge = Line(d1.get_center(), d2.get_center()) edge.set_stroke(YELLOW, 0.5) edges.add(edge) ## Choose special path path_dots = VGroup( dots[-7], dots[-14], dots[9], dots[19], dots[14], ) path_edges = VGroup(*[ Line( d1.get_center(), d2.get_center(), color = RED ) for d1, d2 in zip(path_dots, path_dots[1:]) ]) circle = Circle(color = YELLOW, radius = 1) radius = Line(circle.get_center(), circle.get_right()) radius.set_color(BLUE) VGroup(circle, radius).next_to(path_dots[-1], RIGHT) self.play( Write(title), LaggedStartMap(ShowCreation, edges, run_time = 3), LaggedStartMap(GrowFromCenter, dots, run_time = 3) ) self.play(path_dots[0].set_color, RED) for dot, edge in zip(path_dots[1:], path_edges): self.play( ShowCreation(edge), dot.set_color, RED ) self.play(ShowCreation(radius)) radius.set_points_as_corners(radius.get_anchors()) self.play( ShowCreation(circle), Rotate(radius, angle = 0.999*TAU, about_point = radius.get_start()), run_time = 2 ) self.wait() graph = VGroup(dots, edges, path_edges, title) circle.add(radius) basel_sum.generate_target() basel_sum.target.to_edge(UP) arrow = Arrow( UP, DOWN, rectangular_stem_width = 0.1, tip_length = 0.45, color = RED, ) arrow.next_to(basel_sum.target, DOWN, buff = MED_LARGE_BUFF) self.play( MoveToTarget(basel_sum), graph.next_to, basel_sum.target, UP, LARGE_BUFF, circle.next_to, arrow, DOWN, MED_LARGE_BUFF, ) self.play(GrowArrow(arrow)) self.wait() self.arrow = arrow self.circle = circle def show_light(self): light = AmbientLight( num_levels = 500, radius = 13, opacity_function = lambda r : 1.0/(r+1), ) pi = self.basel_sum[-1][0] pi.set_stroke(BLACK, 0.5) light.move_to(pi) self.play( SwitchOn(light, run_time = 3), Animation(self.arrow), Animation(self.circle), Animation(self.basel_sum), ) self.wait() ### def create_pi_creatures(self): jerk = PiCreature(color = GREEN_D) randy = Randolph().flip() jerk.move_to(0.5*FRAME_X_RADIUS*LEFT).to_edge(DOWN) randy.move_to(0.5*FRAME_X_RADIUS*RIGHT).to_edge(DOWN) return VGroup(jerk, randy) class FirstLighthouseScene(PiCreatureScene): CONFIG = { "num_levels" : 100, "opacity_function" : inverse_quadratic(1,2,1), } def construct(self): self.remove(self.pi_creature) self.show_lighthouses_on_number_line() self.describe_brightness_of_each() self.ask_about_rearrangements() def show_lighthouses_on_number_line(self): number_line = self.number_line = NumberLine( x_min = 0, color = WHITE, number_at_center = 1.6, stroke_width = 1, numbers_with_elongated_ticks = list(range(1,6)), numbers_to_show = list(range(1,6)), unit_size = 2, tick_frequency = 0.2, line_to_number_buff = LARGE_BUFF, label_direction = DOWN, ) number_line.add_numbers() self.add(number_line) origin_point = number_line.number_to_point(0) morty = self.pi_creature morty.scale(0.75) morty.flip() right_pupil = morty.eyes[1] morty.next_to(origin_point, LEFT, buff = 0, submobject_to_align = right_pupil) light_sources = VGroup() for i in range(1,NUM_CONES+1): light_source = LightSource( opacity_function = self.opacity_function, num_levels = self.num_levels, radius = 12.0, ) point = number_line.number_to_point(i) light_source.move_source_to(point) light_sources.add(light_source) lighthouses = self.lighthouses = VGroup(*[ ls.lighthouse for ls in light_sources[:NUM_VISIBLE_CONES+1] ]) morty.save_state() morty.scale(3) morty.fade(1) morty.center() self.play(morty.restore) self.play( morty.change, "pondering", LaggedStartMap( FadeIn, lighthouses, run_time = 1 ) ) self.play(LaggedStartMap( SwitchOn, VGroup(*[ ls.ambient_light for ls in light_sources ]), run_time = 5, lag_ratio = 0.1, rate_func = rush_into, ), Animation(lighthouses)) self.wait() self.light_sources = light_sources def describe_brightness_of_each(self): number_line = self.number_line morty = self.pi_creature light_sources = self.light_sources lighthouses = self.lighthouses light_indicator = LightIndicator( radius = INDICATOR_RADIUS, opacity_for_unit_intensity = OPACITY_FOR_UNIT_INTENSITY, color = LIGHT_COLOR ) light_indicator.reading.scale(0.8) light_indicator.set_intensity(0) intensities = np.cumsum(np.array([1./n**2 for n in range(1,NUM_CONES+1)])) opacities = intensities * light_indicator.opacity_for_unit_intensity bubble = ThoughtBubble( direction = RIGHT, width = 2.5, height = 3.5 ) bubble.pin_to(morty) bubble.add_content(light_indicator) euler_sum_above = OldTex( "1", "+", "{1\over 4}", "+", "{1\over 9}", "+", "{1\over 16}", "+", "{1\over 25}", "+", "{1\over 36}" ) euler_sum_terms = euler_sum_above[::2] plusses = euler_sum_above[1::2] for i, term in enumerate(euler_sum_above): #horizontal alignment with tick marks term.next_to(number_line.number_to_point(0.5*i+1), UP , buff = 2) # vertical alignment with light indicator old_y = term.get_center()[1] new_y = light_indicator.get_center()[1] term.shift([0,new_y - old_y,0]) # show limit value in light indicator and an equals sign limit_reading = OldTex("{\pi^2 \over 6}") limit_reading.move_to(light_indicator.reading) equals_sign = OldTex("=") equals_sign.next_to(morty, UP) old_y = equals_sign.get_center()[1] new_y = euler_sum_above.get_center()[1] equals_sign.shift([0,new_y - old_y,0]) #Triangle of light to morty's eye ls0 = light_sources[0] ls0.save_state() eye = morty.eyes[1] triangle = Polygon( number_line.number_to_point(1), eye.get_top(), eye.get_bottom(), stroke_width = 0, fill_color = YELLOW, fill_opacity = 1, ) triangle_anim = GrowFromPoint( triangle, triangle.get_right(), point_color = YELLOW ) # First lighthouse has apparent reading self.play(LaggedStartMap(FadeOut, light_sources[1:])) self.wait() self.play( triangle_anim, # Animation(eye) ) for x in range(4): triangle_copy = triangle.copy() self.play( FadeOut(triangle.copy()), triangle_anim, ) self.play( FadeOut(triangle), ShowCreation(bubble), FadeIn(light_indicator), ) self.play( UpdateLightIndicator(light_indicator, 1), FadeIn(euler_sum_terms[0]) ) self.wait(2) # Second lighthouse is 1/4, third is 1/9, etc. for i in range(1, 5): self.play( ApplyMethod( ls0.move_to, light_sources[i], run_time = 3 ), UpdateLightIndicator(light_indicator, 1./(i+1)**2, run_time = 3), FadeIn( euler_sum_terms[i], run_time = 3, rate_func = squish_rate_func(smooth, 0.5, 1) ), ) self.wait() self.play( ApplyMethod(ls0.restore), UpdateLightIndicator(light_indicator, 1) ) #Switch them all on self.play( LaggedStartMap(FadeIn, lighthouses[1:]), morty.change, "hooray", ) self.play( LaggedStartMap( SwitchOn, VGroup(*[ ls.ambient_light for ls in light_sources[1:] ]), run_time = 5, rate_func = rush_into, ), Animation(lighthouses), Animation(euler_sum_above), Write(plusses), UpdateLightIndicator(light_indicator, np.pi**2/6, run_time = 5), morty.change, "happy", ) self.wait() self.play( FadeOut(light_indicator.reading), FadeIn(limit_reading), morty.change, "confused", ) self.play(Write(equals_sign)) self.wait() def ask_about_rearrangements(self): light_sources = self.light_sources origin = self.number_line.number_to_point(0) morty = self.pi_creature self.play( LaggedStartMap( Rotate, light_sources, lambda m : (m, (2*random.random()-1)*90*DEGREES), about_point = origin, rate_func = lambda t : wiggle(t, 4), run_time = 10, lag_ratio = 0.9, ), morty.change, "pondering", ) class RearrangeWords(Scene): def construct(self): words = OldTexText("Rearrange without changing \\\\ the apparent brightness") self.play(Write(words)) self.wait(5) class ThatJustSeemsUseless(TeacherStudentsScene): def construct(self): self.student_says( "How would \\\\ that help?", target_mode = "sassy", index = 2, bubble_config = {"direction" : LEFT}, ) self.play( self.teacher.change, "guilty", self.change_students(*3*['sassy']) ) self.wait() class AskAboutBrightness(TeacherStudentsScene): CONFIG = { "num_levels" : 200, "radius" : 10, } def construct(self): light_source = LightSource( num_levels = self.num_levels, radius = self.radius, opacity_function = inverse_quadratic(1,2,1), ) light_source.lighthouse.scale(0.5, about_edge = UP) light_source.move_source_to(5*LEFT + 2*UP) self.add_foreground_mobjects(self.pi_creatures) self.student_says( "What do you mean \\\\ by ``brightness''?", added_anims = [ SwitchOn(light_source.ambient_light), Animation(light_source.lighthouse) ] ) self.play(self.teacher.change, "happy") self.wait(4) class IntroduceScreen(Scene): CONFIG = { "num_levels" : 100, "radius" : 10, "num_rays" : 250, "min_ray_angle" : 0, "max_ray_angle" : TAU, "source_point" : 2.5*LEFT, "observer_point" : 3.5*RIGHT, "screen_height" : 2, } def construct(self): self.setup_elements() self.setup_angle() # spotlight and angle msmt change when screen rotates self.rotate_screen() # self.morph_lighthouse_into_sun() def setup_elements(self): SCREEN_SIZE = 3.0 source_point = self.source_point observer_point = self.observer_point, # Light source light_source = self.light_source = self.get_light_source() # Screen screen = self.screen = Rectangle( width = 0.05, height = self.screen_height, mark_paths_closed = True, fill_color = WHITE, fill_opacity = 1.0, stroke_width = 0.0 ) screen.next_to(observer_point, LEFT) screen_label = OldTexText("Screen") screen_label.next_to(screen, UP+LEFT) screen_arrow = Arrow( screen_label.get_bottom(), screen.get_center(), ) # Pi creature morty = Mortimer() morty.shift(screen.get_center() - morty.eyes.get_left()) morty.look_at(source_point) # Camera camera = SVGMobject(file_name = "camera") camera.rotate(TAU/4) camera.set_height(1.5) camera.move_to(morty.eyes, LEFT) # Animations light_source.set_max_opacity_spotlight(0.001) screen_tracker = self.screen_tracker = ScreenTracker(light_source) self.add(light_source.lighthouse) self.play(SwitchOn(light_source.ambient_light)) self.play( Write(screen_label), GrowArrow(screen_arrow), FadeIn(screen) ) self.wait() self.play(*list(map(FadeOut, [screen_label, screen_arrow]))) screen.save_state() self.play( FadeIn(morty), screen.match_height, morty.eyes, screen.next_to, morty.eyes, LEFT, SMALL_BUFF ) self.play(Blink(morty)) self.play( FadeOut(morty), FadeIn(camera), screen.scale, 2, {"about_edge" : UP}, ) self.wait() self.play( FadeOut(camera), screen.restore, ) light_source.set_screen(screen) light_source.spotlight.opacity_function = lambda r : 0.2/(r+1) screen_tracker.update(0) ## Ask about proportion self.add_foreground_mobjects(light_source.shadow, screen) self.shoot_rays() ## self.play(SwitchOn(light_source.spotlight)) def setup_angle(self): self.wait() # angle msmt (arc) arc_angle = self.light_source.spotlight.opening_angle() # draw arc arrows to show the opening angle self.angle_arc = Arc( radius = 3, start_angle = self.light_source.spotlight.start_angle(), angle = self.light_source.spotlight.opening_angle(), tip_length = ARC_TIP_LENGTH ) #angle_arc.add_tip(at_start = True, at_end = True) self.angle_arc.move_arc_center_to(self.light_source.get_source_point()) # angle msmt (decimal number) self.angle_indicator = DecimalNumber( arc_angle / DEGREES, num_decimal_places = 0, unit = "^\\circ" ) self.angle_indicator.next_to(self.angle_arc, RIGHT) angle_update_func = lambda x: self.light_source.spotlight.opening_angle() / DEGREES self.angle_indicator.add_updater( lambda d: d.set_value(angle_update_func()) ) self.add(self.angle_indicator) arc_tracker = AngleUpdater( self.angle_arc, self.light_source.spotlight ) self.add(arc_tracker) self.play( ShowCreation(self.angle_arc), ShowCreation(self.angle_indicator) ) self.wait() def rotate_screen(self): self.add( Mobject.add_updater( self.light_source, lambda m : m.update() ), ) self.add( Mobject.add_updater( self.angle_indicator, lambda m : m.set_stroke(width = 0).set_fill(opacity = 1) ) ) self.remove(self.light_source.ambient_light) def rotate_screen(angle): self.play( Rotate(self.light_source.spotlight.screen, angle), Animation(self.angle_arc), run_time = 2, ) for angle in TAU/8, -TAU/4, TAU/8, -TAU/6: rotate_screen(angle) self.wait() self.shoot_rays() rotate_screen(TAU/6) ## def get_light_source(self): light_source = LightSource( opacity_function = inverse_quadratic(1,2,1), num_levels = self.num_levels, radius = self.radius, max_opacity_ambient = AMBIENT_FULL, ) light_source.move_source_to(self.source_point) return light_source def shoot_rays(self, show_creation_kwargs = None): if show_creation_kwargs is None: show_creation_kwargs = {} source_point = self.source_point screen = self.screen # Rays step_size = (self.max_ray_angle - self.min_ray_angle)/self.num_rays rays = VGroup(*[ Line(ORIGIN, self.radius*rotate_vector(RIGHT, angle)) for angle in np.arange( self.min_ray_angle, self.max_ray_angle, step_size ) ]) rays.shift(source_point) rays.set_stroke(YELLOW, 1) max_angle = np.max([ angle_of_vector(point - source_point) for point in screen.get_points() ]) min_angle = np.min([ angle_of_vector(point - source_point) for point in screen.get_points() ]) for ray in rays: if min_angle <= ray.get_angle() <= max_angle: ray.target_color = GREEN else: ray.target_color = RED self.play(*[ ShowCreation(ray, run_time = 3, **show_creation_kwargs) for ray in rays ]) self.play(*[ ApplyMethod(ray.set_color, ray.target_color) for ray in rays ]) self.wait() self.play(FadeOut(rays)) class EarthScene(IntroduceScreen): CONFIG = { "screen_height" : 0.5, "screen_thickness" : 0, "radius" : 100 + FRAME_X_RADIUS, "source_point" : 100*LEFT, "min_ray_angle" : -1.65*DEGREES, "max_ray_angle" : 1.65*DEGREES, "num_rays" : 100, } def construct(self): # Earth earth_radius = 3 earth = ImageMobject("earth") earth_circle = Circle(radius = earth_radius) earth_circle.to_edge(RIGHT) earth.replace(earth_circle) black_rect = Rectangle( height = FRAME_HEIGHT, width = earth_radius + LARGE_BUFF, stroke_width = 0, fill_color = BLACK, fill_opacity = 1 ) black_rect.move_to(earth.get_center(), LEFT) self.add_foreground_mobjects(black_rect, earth) # screen screen = self.screen = Line( self.screen_height*UP, ORIGIN, stroke_color = WHITE, stroke_width = self.screen_thickness, ) screen.move_to(earth.get_left()) screen.generate_target() screen.target.rotate( -60*DEGREES, about_point = earth_circle.get_center() ) equator_arrow = Vector( DOWN+2*RIGHT, color = WHITE, ) equator_arrow.next_to(screen.get_center(), UP+LEFT, SMALL_BUFF) pole_arrow = Vector( UP+3*RIGHT, color = WHITE, path_arc = -60*DEGREES, ) pole_arrow.shift( screen.target.get_center()+SMALL_BUFF*LEFT - \ pole_arrow.get_end() ) for arrow in equator_arrow, pole_arrow: arrow.pointwise_become_partial(arrow, 0, 0.95) equator_words = OldTexText("Some", "unit of area") pole_words = OldTexText("The same\\\\", "unit of area") pole_words.next_to(pole_arrow.get_start(), DOWN) equator_words.next_to(equator_arrow.get_start(), UP) # Light source (far-away Sun) sun = sun = LightSource( opacity_function = lambda r : 0.5, max_opacity_ambient = 0, max_opacity_spotlight = 0.5, num_levels = 5, radius = self.radius, screen = screen ) sun.move_source_to(self.source_point) sunlight = sun.spotlight sunlight.opacity_function = lambda r : 5./(r+1) screen_tracker = ScreenTracker(sun) # Add elements to scene self.add(screen) self.play(SwitchOn( sunlight, rate_func = squish_rate_func(smooth, 0.7, 0.8), )) self.add(screen_tracker) self.play( Write(equator_words), GrowArrow(equator_arrow) ) self.add_foreground_mobjects(equator_words, equator_arrow) self.shoot_rays(show_creation_kwargs = { "rate_func" : lambda t : interpolate(0.98, 1, smooth(t)) }) self.wait() # Point to patch self.play( MoveToTarget(screen), Transform(equator_arrow, pole_arrow), Transform( equator_words, pole_words, rate_func = squish_rate_func(smooth, 0.6, 1), ), Animation(sunlight), run_time = 3, ) self.shoot_rays(show_creation_kwargs = { "rate_func" : lambda t : interpolate(0.98, 1, smooth(t)) }) self.wait() class ShowLightInThreeDimensions(IntroduceScreen, ThreeDScene): CONFIG = { "num_levels" : 200, } def construct(self): light_source = self.get_light_source() screens = VGroup( Square(), RegularPolygon(8), Circle().insert_n_curves(25), ) for screen in screens: screen.set_height(self.screen_height) screens.rotate(TAU/4, UP) screens.next_to(self.observer_point, LEFT) screens.set_stroke(WHITE, 2) screens.set_fill(WHITE, 0.5) screen = screens[0] cone = ThreeDSpotlight( screen, light_source.ambient_light, light_source.get_source_point ) cone_update_anim = ContinualThreeDLightConeUpdate(cone) self.add(light_source, screen, cone) self.add(cone_update_anim) self.move_camera( phi = 60*DEGREES, theta = -155*DEGREES, run_time = 3, ) self.begin_ambient_camera_rotation() kwargs = {"run_time" : 2} self.play(screen.stretch, 0.5, 1, **kwargs) self.play(screen.stretch, 2, 2, **kwargs) self.play(Rotate( screen, TAU/4, axis = UP+OUT, rate_func = there_and_back, run_time = 3, )) self.play(Transform(screen, screens[1], **kwargs)) self.play(screen.stretch, 0.5, 2, **kwargs) self.play(Transform(screen, screens[2], **kwargs)) self.wait(2) self.play( screen.stretch, 0.5, 1, screen.stretch, 2, 2, **kwargs ) self.play( screen.stretch, 3, 1, screen.stretch, 0.7, 2, **kwargs ) self.wait(2) class LightInThreeDimensionsOverlay(Scene): def construct(self): words = OldTexText(""" ``Solid angle'' \\\\ (measured in ``steradians'') """) self.play(Write(words)) self.wait() class InverseSquareLaw(ThreeDScene): CONFIG = { "screen_height" : 1.0, "source_point" : 5*LEFT, "unit_distance" : 4, "num_levels" : 100, } def construct(self): self.move_screen_farther_away() self.morph_into_3d() def move_screen_farther_away(self): source_point = self.source_point unit_distance = self.unit_distance # screen screen = self.screen = Line(self.screen_height*UP, ORIGIN) screen.get_reference_point = screen.get_center screen.shift( source_point + unit_distance*RIGHT -\ screen.get_reference_point() ) # light source light_source = self.light_source = LightSource( # opacity_function = inverse_quadratic(1,5,1), opacity_function = lambda r : 1./(r+1), num_levels = self.num_levels, radius = 10, max_opacity = 0.2 ) light_source.set_max_opacity_spotlight(0.2) light_source.set_screen(screen) light_source.move_source_to(source_point) # abbreviations ambient_light = light_source.ambient_light spotlight = light_source.spotlight lighthouse = light_source.lighthouse shadow = light_source.shadow # Morty morty = self.morty = Mortimer().scale(0.3) morty.next_to(screen, RIGHT, buff = MED_LARGE_BUFF) #Screen tracker def update_spotlight(spotlight): spotlight.update_sectors() spotlight_update = Mobject.add_updater(spotlight, update_spotlight) shadow_update = Mobject.add_updater( shadow, lambda m : light_source.update_shadow() ) # Light indicator light_indicator = self.light_indicator = LightIndicator( opacity_for_unit_intensity = 0.5, ) def update_light_indicator(light_indicator): distance = get_norm(screen.get_reference_point() - source_point) light_indicator.set_intensity(1.0/(distance/unit_distance)**2) light_indicator.next_to(morty, UP, MED_LARGE_BUFF) light_indicator_update = Mobject.add_updater( light_indicator, update_light_indicator ) light_indicator_update.update(0) continual_updates = self.continual_updates = [ spotlight_update, light_indicator_update, shadow_update ] # Distance indicators one_arrow = DoubleArrow(ORIGIN, unit_distance*RIGHT, buff = 0) two_arrow = DoubleArrow(ORIGIN, 2*unit_distance*RIGHT, buff = 0) arrows = VGroup(one_arrow, two_arrow) arrows.set_color(WHITE) one_arrow.move_to(source_point + DOWN, LEFT) two_arrow.move_to(source_point + 1.75*DOWN, LEFT) one = Integer(1).next_to(one_arrow, UP, SMALL_BUFF) two = Integer(2).next_to(two_arrow, DOWN, SMALL_BUFF) arrow_group = VGroup(one_arrow, one, two_arrow, two) # Animations self.add_foreground_mobjects(lighthouse, screen, morty) self.add(shadow_update) self.play( SwitchOn(ambient_light), morty.change, "pondering" ) self.play( SwitchOn(spotlight), FadeIn(light_indicator) ) # self.remove(spotlight) self.add(*continual_updates) self.wait() for distance in -0.5, 0.5: self.shift_by_distance(distance) self.wait() self.add_foreground_mobjects(one_arrow, one) self.play(GrowFromCenter(one_arrow), Write(one)) self.wait() self.add_foreground_mobjects(two_arrow, two) self.shift_by_distance(1, GrowFromPoint(two_arrow, two_arrow.get_left()), Write(two, rate_func = squish_rate_func(smooth, 0.5, 1)) ) self.wait() q_marks = OldTexText("???") q_marks.next_to(light_indicator, UP) self.play( Write(q_marks), morty.change, "confused", q_marks ) self.play(Blink(morty)) self.play(FadeOut(q_marks), morty.change, "pondering") self.wait() self.shift_by_distance(-1, arrow_group.shift, DOWN) self.set_variables_as_attrs( ambient_light, spotlight, shadow, lighthouse, morty, arrow_group, *continual_updates ) def morph_into_3d(self): # axes = ThreeDAxes() old_screen = self.screen spotlight = self.spotlight source_point = self.source_point ambient_light = self.ambient_light unit_distance = self.unit_distance light_indicator = self.light_indicator morty = self.morty new_screen = Square( side_length = self.screen_height, stroke_color = WHITE, stroke_width = 1, fill_color = WHITE, fill_opacity = 0.5 ) new_screen.rotate(TAU/4, UP) new_screen.move_to(old_screen, IN) old_screen.fade(1) cone = ThreeDSpotlight( new_screen, ambient_light, source_point_func = lambda : source_point ) cone_update_anim = ContinualThreeDLightConeUpdate(cone) self.remove(self.spotlight_update, self.light_indicator_update) self.add( ContinualAnimation(new_screen), cone_update_anim ) self.remove(spotlight) self.move_camera( phi = 60*DEGREES, theta = -145*DEGREES, added_anims = [ # ApplyMethod( # old_screen.scale, 1.8, {"about_edge" : DOWN}, # run_time = 2, # ), ApplyFunction( lambda m : m.fade(1).shift(1.5*DOWN), light_indicator, remover = True ), FadeOut(morty) ], run_time = 2, ) self.wait() ## Create screen copies def get_screen_copy_group(distance): n = int(distance)**2 copies = VGroup(*[new_screen.copy() for x in range(n)]) copies.rotate(-TAU/4, axis = UP) copies.arrange_in_grid(buff = 0) copies.rotate(TAU/4, axis = UP) copies.move_to(source_point, IN) copies.shift(distance*RIGHT*unit_distance) return copies screen_copy_groups = list(map(get_screen_copy_group, list(range(1, 8)))) def get_screen_copy_group_anim(n): group = screen_copy_groups[n] prev_group = screen_copy_groups[n-1] group.save_state() group.fade(1) group.replace(prev_group, dim_to_match = 1) return ApplyMethod(group.restore) # corner_directions = [UP+OUT, DOWN+OUT, DOWN+IN, UP+IN] # edge_directions = [ # UP, UP+OUT, OUT, DOWN+OUT, DOWN, DOWN+IN, IN, UP+IN, ORIGIN # ] # four_copies = VGroup(*[new_screen.copy() for x in range(4)]) # nine_copies = VGroup(*[new_screen.copy() for x in range(9)]) # def update_four_copies(four_copies): # for mob, corner_direction in zip(four_copies, corner_directions): # mob.move_to(new_screen, corner_direction) # four_copies_update_anim = UpdateFromFunc(four_copies, update_four_copies) # def update_nine_copies(nine_copies): # for mob, corner_direction in zip(nine_copies, edge_directions): # mob.move_to(new_screen, corner_direction) # nine_copies_update_anim = UpdateFromFunc(nine_copies, update_nine_copies) three_arrow = DoubleArrow( source_point + 4*DOWN, source_point + 4*DOWN + 3*unit_distance*RIGHT, buff = 0, color = WHITE ) three = Integer(3) three.next_to(three_arrow, DOWN) new_screen.fade(1) # self.add( # ContinualAnimation(screen_copy), # ContinualAnimation(four_copies), # ) self.add(ContinualAnimation(screen_copy_groups[0])) self.add(ContinualAnimation(screen_copy_groups[1])) self.play( new_screen.scale, 2, {"about_edge" : IN}, new_screen.shift, unit_distance*RIGHT, get_screen_copy_group_anim(1), run_time = 2, ) self.wait() self.move_camera( phi = 75*DEGREES, theta = -155*DEGREES, distance = 7, run_time = 10, ) self.begin_ambient_camera_rotation(rate = -0.01) self.add(ContinualAnimation(screen_copy_groups[2])) self.play( new_screen.scale, 3./2, {"about_edge" : IN}, new_screen.shift, unit_distance*RIGHT, get_screen_copy_group_anim(2), GrowFromPoint(three_arrow, three_arrow.get_left()), Write(three, rate_func = squish_rate_func(smooth, 0.5, 1)), run_time = 2, ) self.begin_ambient_camera_rotation(rate = -0.01) self.play(LaggedStartMap( ApplyMethod, screen_copy_groups[2], lambda m : (m.set_color, RED), run_time = 5, rate_func = there_and_back, )) self.wait(2) self.move_camera(distance = 18) self.play(*[ ApplyMethod(mob.fade, 1) for mob in screen_copy_groups[:2] ]) last_group = screen_copy_groups[2] for n in range(4, len(screen_copy_groups)+1): group = screen_copy_groups[n-1] self.add(ContinualAnimation(group)) self.play( new_screen.scale, float(n)/(n-1), {"about_edge" : IN}, new_screen.shift, unit_distance*RIGHT, get_screen_copy_group_anim(n-1), last_group.fade, 1, ) last_group = group self.wait() ### def shift_by_distance(self, distance, *added_anims): anims = [ self.screen.shift, self.unit_distance*distance*RIGHT, ] if self.morty in self.mobjects: anims.append(MaintainPositionRelativeTo(self.morty, self.screen)) anims += added_anims self.play(*anims, run_time = 2) class OtherInstanceOfInverseSquareLaw(Scene): def construct(self): title = OldTexText("Where the inverse square law shows up") title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) self.add(title, h_line) items = VGroup(*[ OldTexText("- %s"%s).scale(1) for s in [ "Heat", "Sound", "Radio waves", "Electric fields", ] ]) items.arrange(DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT) items.next_to(h_line, DOWN, LARGE_BUFF) items.to_edge(LEFT) dot = Dot() dot.move_to(4*RIGHT) self.add(dot) def get_broadcast(): return Broadcast(dot, big_radius = 5, run_time = 5) self.play( LaggedStartMap(FadeIn, items, run_time = 4, lag_ratio = 0.7), Succession(*[ get_broadcast() for x in range(2) ]) ) self.play(get_broadcast()) self.wait() class ScreensIntroWrapper(TeacherStudentsScene): def construct(self): point = VectorizedPoint(FRAME_X_RADIUS*LEFT/2 + FRAME_Y_RADIUS*UP/2) self.play(self.teacher.change, "raise_right_hand") self.play_student_changes( "pondering", "erm", "confused", look_at = point, ) self.play(self.teacher.look_at, point) self.wait(5) class ManipulateLightsourceSetups(PiCreatureScene): CONFIG = { "num_levels" : 100, "radius" : 10, "pi_creature_point" : 2*LEFT + 2*DOWN, } def construct(self): unit_distance = 3 # Morty morty = self.pi_creature observer_point = morty.eyes[1].get_center() bubble = ThoughtBubble(height = 3, width = 4, direction = RIGHT) bubble.set_fill(BLACK, 1) bubble.pin_to(morty) # Indicator light_indicator = LightIndicator( opacity_for_unit_intensity = 0.5, fill_color = YELLOW, radius = 0.4, reading_height = 0.2, ) light_indicator.move_to(bubble.get_bubble_center()) def update_light_indicator(light_indicator): distance = get_norm(light_source.get_source_point()-observer_point) light_indicator.set_intensity((unit_distance/distance)**2) #Light source light_source = LightSource( opacity_function = inverse_quadratic(1,2,1), num_levels = self.num_levels, radius = self.radius, max_opacity_ambient = AMBIENT_FULL, ) light_source.move_to(observer_point + unit_distance*RIGHT) #Light source copies light_source_copies = VGroup(*[light_source.copy() for x in range(2)]) for lsc, vect in zip(light_source_copies, [RIGHT, UP]): lsc.move_to(observer_point + np.sqrt(2)*unit_distance*vect) self.add(light_source) self.add_foreground_mobjects(morty, bubble, light_indicator) self.add(Mobject.add_updater(light_indicator, update_light_indicator)) self.play( ApplyMethod( light_source.shift, 0.66*unit_distance*LEFT, rate_func = wiggle, run_time = 5, ), morty.change, "erm", ) self.play( UpdateFromAlphaFunc( light_source, lambda ls, a : ls.move_to( observer_point + rotate_vector( unit_distance*RIGHT, (1+1./8)*a*TAU ) ), run_time = 6, rate_func = bezier([0, 0, 1, 1]) ), morty.change, "pondering", UpdateFromFunc(morty, lambda m : m.look_at(light_source)) ) self.wait() plus = OldTex("+") point = light_indicator.get_center() plus.move_to(point) light_indicator_copy = light_indicator.copy() self.add_foreground_mobjects(plus, light_indicator_copy) self.play( ReplacementTransform( light_source, light_source_copies[0] ), ReplacementTransform( light_source.copy().fade(1), light_source_copies[1] ), FadeIn(plus), UpdateFromFunc( light_indicator_copy, lambda li : update_light_indicator(li), ), UpdateFromAlphaFunc( light_indicator, lambda m, a : m.move_to( point + a*0.75*RIGHT, ) ), UpdateFromAlphaFunc( light_indicator_copy, lambda m, a : m.move_to( point + a*0.75*LEFT, ) ), run_time = 2 ) self.play(morty.change, "hooray") self.wait(2) ## def create_pi_creature(self): morty = Mortimer() morty.flip() morty.scale(0.5) morty.move_to(self.pi_creature_point) return morty class TwoLightSourcesScene(ManipulateLightsourceSetups): CONFIG = { "num_levels" : 200, "radius" : 15, "a" : 9, "b" : 5, "origin_point" : 5*LEFT + 2.5*DOWN } def construct(self): MAX_OPACITY = 0.4 INDICATOR_RADIUS = 0.6 OPACITY_FOR_UNIT_INTENSITY = 0.5 origin_point = self.origin_point #Morty morty = self.pi_creature morty.change("hooray") # From last scen morty.generate_target() morty.target.change("plain") morty.target.scale(0.6) morty.target.next_to( origin_point, LEFT, buff = 0, submobject_to_align = morty.target.eyes[1] ) #Axes axes = Axes( x_min = -1, x_max = 10.5, y_min = -1, y_max = 6.5, ) axes.shift(origin_point) #Important reference points A = axes.coords_to_point(self.a, 0) B = axes.coords_to_point(0, self.b) C = axes.coords_to_point(0, 0) xA = A[0] yA = A[1] xB = B[0] yB = B[1] xC = C[0] yC = C[1] # find the coords of the altitude point H # as the solution of a certain LSE prelim_matrix = np.array([ [yA - yB, xB - xA], [xA - xB, yA - yB] ]) # sic prelim_vector = np.array( [xB * yA - xA * yB, xC * (xA - xB) + yC * (yA - yB)] ) H2 = np.linalg.solve(prelim_matrix, prelim_vector) H = np.append(H2, 0.) #Lightsources lsA = LightSource( radius = self.radius, num_levels = self.num_levels, opacity_function = inverse_power_law(2, 1, 1, 1.5), ) lsB = lsA.deepcopy() lsA.move_source_to(A) lsB.move_source_to(B) lsC = lsA.deepcopy() lsC.move_source_to(H) #Lighthouse labels A_label = OldTexText("A") A_label.next_to(lsA.lighthouse, RIGHT) B_label = OldTexText("B") B_label.next_to(lsB.lighthouse, LEFT) #Identical lighthouse labels identical_lighthouses_words = OldTexText("All identical \\\\ lighthouses") identical_lighthouses_words.to_corner(UP+RIGHT) identical_lighthouses_words.shift(LEFT) identical_lighthouses_arrows = VGroup(*[ Arrow( identical_lighthouses_words.get_corner(DOWN+LEFT), ls.get_source_point(), buff = SMALL_BUFF, color = WHITE, ) for ls in (lsA, lsB, lsC) ]) #Lines line_a = Line(C, A) line_a.set_color(BLUE) line_b = Line(C, B) line_b.set_color(RED) line_c = Line(A, B) line_h = Line(H, C) line_h.set_color(GREEN) label_a = OldTex("a") label_a.match_color(line_a) label_a.next_to(line_a, DOWN, buff = SMALL_BUFF) label_b = OldTex("b") label_b.match_color(line_b) label_b.next_to(line_b, LEFT, buff = SMALL_BUFF) label_h = OldTex("h") label_h.match_color(line_h) label_h.next_to(line_h.get_center(), RIGHT, buff = SMALL_BUFF) perp_mark = VMobject().set_points_as_corners([ RIGHT, RIGHT+DOWN, DOWN ]) perp_mark.scale(0.25, about_point = ORIGIN) perp_mark.rotate(line_c.get_angle() + TAU/4, about_point = ORIGIN) perp_mark.shift(H) # perp_mark.set_color(BLACK) #Indicators indicator = LightIndicator( color = LIGHT_COLOR, radius = INDICATOR_RADIUS, opacity_for_unit_intensity = OPACITY_FOR_UNIT_INTENSITY, show_reading = True, precision = 2, ) indicator.next_to(origin_point, UP+LEFT) def update_indicator(indicator): intensity = 0 for ls in lsA, lsB, lsC: if ls in self.mobjects: distance = get_norm(ls.get_source_point() - origin_point) d_indensity = fdiv( 3./(distance**2), indicator.opacity_for_unit_intensity ) d_indensity *= ls.ambient_light.submobjects[1].get_fill_opacity() intensity += d_indensity indicator.set_intensity(intensity) indicator_update_anim = Mobject.add_updater(indicator, update_indicator) new_indicator = indicator.copy() new_indicator.light_source = lsC new_indicator.measurement_point = C #Note sure what this is... distance1 = get_norm(origin_point - lsA.get_source_point()) intensity = lsA.ambient_light.opacity_function(distance1) / indicator.opacity_for_unit_intensity distance2 = get_norm(origin_point - lsB.get_source_point()) intensity += lsB.ambient_light.opacity_function(distance2) / indicator.opacity_for_unit_intensity # IPT Theorem theorem = OldTex( "{1 \over ", "a^2}", "+", "{1 \over", "b^2}", "=", "{1 \over","h^2}" ) theorem.set_color_by_tex_to_color_map({ "a" : line_a.get_color(), "b" : line_b.get_color(), "h" : line_h.get_color(), }) theorem_name = OldTexText("Inverse Pythagorean Theorem") theorem_name.to_corner(UP+RIGHT) theorem.next_to(theorem_name, DOWN, buff = MED_LARGE_BUFF) theorem_box = SurroundingRectangle(theorem, color = WHITE) #Transition from last_scene self.play( ShowCreation(axes, run_time = 2), MoveToTarget(morty), FadeIn(indicator), ) #Move lsC around self.add(lsC) indicator_update_anim.update(0) intensity = indicator.reading.number self.play( SwitchOn(lsC.ambient_light), FadeIn(lsC.lighthouse), UpdateFromAlphaFunc( indicator, lambda i, a : i.set_intensity(a*intensity) ) ) self.add(indicator_update_anim) self.play(Animation(lsC), run_time = 0) #Why is this needed? for point in axes.coords_to_point(5, 2), H: self.play( lsC.move_source_to, point, path_arc = TAU/4, run_time = 1.5, ) self.wait() # Draw line self.play( ShowCreation(line_h), morty.change, "pondering" ) self.wait() self.play( ShowCreation(line_c), ShowCreation(perp_mark) ) self.wait() self.add_foreground_mobjects(line_c, line_h) #Add alternate light_sources for ls in lsA, lsB: ls.save_state() ls.move_to(lsC) ls.fade(1) self.add(ls) self.play( ls.restore, run_time = 2 ) self.wait() A_label.save_state() A_label.center().fade(1) self.play(A_label.restore) self.wait() self.play(ReplacementTransform( A_label.copy().fade(1), B_label )) self.wait(2) #Compare combined of laA + lsB with lsC rect = SurroundingRectangle(indicator, color = RED) self.play( FadeOut(lsA), FadeOut(lsB), ) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.play(FadeOut(lsC)) self.add(lsA, lsB) self.play( FadeIn(lsA), FadeIn(lsB), ) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.wait(2) # All standard lighthouses self.add(lsC) self.play(FadeIn(lsC)) self.play( Write(identical_lighthouses_words), LaggedStartMap(GrowArrow, identical_lighthouses_arrows) ) self.wait() self.play(*list(map(FadeOut, [ identical_lighthouses_words, identical_lighthouses_arrows, ]))) #Show labels of lengths self.play(ShowCreation(line_a), Write(label_a)) self.wait() self.play(ShowCreation(line_b), Write(label_b)) self.wait() self.play(Write(label_h)) self.wait() #Write IPT a_part = theorem[:2] b_part = theorem[2:5] h_part = theorem[5:] for part in a_part, b_part, h_part: part.save_state() part.scale(3) part.fade(1) a_part.move_to(lsA) b_part.move_to(lsB) h_part.move_to(lsC) self.play(*list(map(FadeOut, [lsA, lsB, lsC, indicator]))) for ls, part in (lsA, a_part), (lsB, b_part), (lsC, h_part): self.add(ls) self.play( SwitchOn(ls.ambient_light, run_time = 2), FadeIn(ls.lighthouse), part.restore ) self.wait() self.play( Write(theorem_name), ShowCreation(theorem_box) ) self.play(morty.change, "confused") self.wait(2) class MathologerVideoWrapper(Scene): def construct(self): title = OldTexText(""" Mathologer's excellent video on \\\\ the many Pythagorean theorem cousins """) # title.scale(0.7) title.to_edge(UP) logo = ImageMobject("mathologer_logo") logo.set_height(1) logo.to_corner(UP+LEFT) logo.shift(FRAME_WIDTH*RIGHT) screen = ScreenRectangle(height = 5.5) screen.next_to(title, DOWN) self.play( logo.shift, FRAME_WIDTH*LEFT, LaggedStartMap(FadeIn, title), run_time = 2 ) self.play(ShowCreation(screen)) self.wait(5) class SimpleIPTProof(Scene): def construct(self): A = 5*RIGHT B = 3*UP C = ORIGIN #Dumb and inefficient alphas = np.linspace(0, 1, 500) i = np.argmin([get_norm(interpolate(A, B, a)) for a in alphas]) H = interpolate(A, B, alphas[i]) triangle = VGroup( Line(C, A, color = BLUE), Line(C, B, color = RED), Line(A, B, color = WHITE), Line(C, H, color = GREEN) ) for line, char in zip(triangle, ["a", "b", "c", "h"]): label = OldTex(char) label.match_color(line) vect = line.get_center() - triangle.get_center() vect /= get_norm(vect) label.next_to(line.get_center(), vect) triangle.add(label) if char == "h": label.next_to(line.get_center(), UP+LEFT, SMALL_BUFF) triangle.to_corner(UP+LEFT) self.add(triangle) argument_lines = VGroup( OldTex( "\\text{Area} = ", "{1 \\over 2}", "a", "b", "=", "{1 \\over 2}", "c", "h" ), OldTex("\\Downarrow"), OldTex("a^2", "b^2", "=", "c^2", "h^2"), OldTex("\\Downarrow"), OldTex( "a^2", "b^2", "=", "(", "a^2", "+", "b^2", ")", "h^2" ), OldTex("\\Downarrow"), OldTex( "{1 \\over ", "h^2}", "=", "{1 \\over ", "b^2}", "+", "{1 \\over ", "a^2}", ), ) argument_lines.arrange(DOWN) for line in argument_lines: line.set_color_by_tex_to_color_map({ "a" : BLUE, "b" : RED, "h" : GREEN, "Area" : WHITE, "Downarrow" : WHITE, }) all_equals = line.get_parts_by_tex("=") if all_equals: line.alignment_mob = all_equals[-1] else: line.alignment_mob = line[0] line.shift(-line.alignment_mob.get_center()[0]*RIGHT) argument_lines.next_to(triangle, RIGHT) argument_lines.to_edge(UP) prev_line = argument_lines[0] self.play(FadeIn(prev_line)) for arrow, line in zip(argument_lines[1::2], argument_lines[2::2]): line.save_state() line.shift( prev_line.alignment_mob.get_center() - \ line.alignment_mob.get_center() ) line.fade(1) self.play( line.restore, GrowFromPoint(arrow, arrow.get_top()) ) self.wait() prev_line = line class WeCanHaveMoreFunThanThat(TeacherStudentsScene): def construct(self): point = VectorizedPoint(FRAME_X_RADIUS*LEFT/2 + FRAME_Y_RADIUS*UP/2) self.teacher_says( "We can have \\\\ more fun than that!", target_mode = "hooray" ) self.play_student_changes(*3*["erm"], look_at = point) self.wait() self.play( RemovePiCreatureBubble( self.teacher, target_mode = "raise_right_hand", look_at = point, ), self.change_students(*3*["pondering"], look_at = point) ) self.wait(3) class IPTScene(TwoLightSourcesScene, ZoomedScene): CONFIG = { "max_opacity_ambient" : 0.2, "num_levels" : 200, } def construct(self): #Copy pasting from TwoLightSourcesScene....Very bad... origin_point = self.origin_point self.remove(self.pi_creature) #Axes axes = Axes( x_min = -1, x_max = 10.5, y_min = -1, y_max = 6.5, ) axes.shift(origin_point) #Important reference points A = axes.coords_to_point(self.a, 0) B = axes.coords_to_point(0, self.b) C = axes.coords_to_point(0, 0) xA = A[0] yA = A[1] xB = B[0] yB = B[1] xC = C[0] yC = C[1] # find the coords of the altitude point H # as the solution of a certain LSE prelim_matrix = np.array([ [yA - yB, xB - xA], [xA - xB, yA - yB] ]) # sic prelim_vector = np.array( [xB * yA - xA * yB, xC * (xA - xB) + yC * (yA - yB)] ) H2 = np.linalg.solve(prelim_matrix, prelim_vector) H = np.append(H2, 0.) #Lightsources lsA = LightSource( radius = self.radius, num_levels = self.num_levels, opacity_function = inverse_power_law(2, 1, 1, 1.5), max_opacity_ambient = self.max_opacity_ambient, ) lsA.lighthouse.scale(0.5, about_edge = UP) lsB = lsA.deepcopy() lsA.move_source_to(A) lsB.move_source_to(B) lsC = lsA.deepcopy() lsC.move_source_to(H) #Lighthouse labels A_label = OldTexText("A") A_label.next_to(lsA.lighthouse, RIGHT) B_label = OldTexText("B") B_label.next_to(lsB.lighthouse, LEFT) #Lines line_a = Line(C, A) line_a.set_color(BLUE) line_b = Line(C, B) line_b.set_color(RED) line_c = Line(A, B) line_h = Line(H, C) line_h.set_color(GREEN) label_a = OldTex("a") label_a.match_color(line_a) label_a.next_to(line_a, DOWN, buff = SMALL_BUFF) label_b = OldTex("b") label_b.match_color(line_b) label_b.next_to(line_b, LEFT, buff = SMALL_BUFF) label_h = OldTex("h") label_h.match_color(line_h) label_h.next_to(line_h.get_center(), RIGHT, buff = SMALL_BUFF) perp_mark = VMobject().set_points_as_corners([ RIGHT, RIGHT+DOWN, DOWN ]) perp_mark.scale(0.25, about_point = ORIGIN) perp_mark.rotate(line_c.get_angle() + TAU/4, about_point = ORIGIN) perp_mark.shift(H) # Mini triangle m_hyp_a = Line(H, A) m_a = line_a.copy() m_hyp_b = Line(H, B) m_b = line_b.copy() mini_triangle = VGroup(m_a, m_hyp_a, m_b, m_hyp_b) mini_triangle.set_stroke(width = 5) mini_triangle.generate_target() mini_triangle.target.scale(0.1, about_point = origin_point) for part, part_target in zip(mini_triangle, mini_triangle.target): part.target = part_target # Screen label screen_word = OldTexText("Screen") screen_word.next_to(mini_triangle.target, UP+RIGHT, LARGE_BUFF) screen_arrow = Arrow( screen_word.get_bottom(), mini_triangle.target.get_center(), color = WHITE, ) # IPT Theorem theorem = OldTex( "{1 \over ", "a^2}", "+", "{1 \over", "b^2}", "=", "{1 \over","h^2}" ) theorem.set_color_by_tex_to_color_map({ "a" : line_a.get_color(), "b" : line_b.get_color(), "h" : line_h.get_color(), }) theorem_name = OldTexText("Inverse Pythagorean Theorem") theorem_name.to_corner(UP+RIGHT) theorem.next_to(theorem_name, DOWN, buff = MED_LARGE_BUFF) theorem_box = SurroundingRectangle(theorem, color = WHITE) # Setup spotlights spotlight_a = VGroup() spotlight_a.screen = m_hyp_a spotlight_b = VGroup() spotlight_b.screen = m_hyp_b for spotlight in spotlight_a, spotlight_b: spotlight.get_source_point = lsC.get_source_point dr = lsC.ambient_light.radius/lsC.ambient_light.num_levels def update_spotlight(spotlight): spotlight.submobjects = [] source_point = spotlight.get_source_point() c1, c2 = spotlight.screen.get_start(), spotlight.screen.get_end() distance = max( get_norm(c1 - source_point), get_norm(c2 - source_point), ) n_parts = np.ceil(distance/dr) alphas = np.linspace(0, 1, n_parts+1) for a1, a2 in zip(alphas, alphas[1:]): spotlight.add(Polygon( interpolate(source_point, c1, a1), interpolate(source_point, c1, a2), interpolate(source_point, c2, a2), interpolate(source_point, c2, a1), fill_color = YELLOW, fill_opacity = 2*lsC.ambient_light.opacity_function(a1*distance), stroke_width = 0 )) def update_spotlights(spotlights): for spotlight in spotlights: update_spotlight(spotlight) def get_spotlight_triangle(spotlight): sp = spotlight.get_source_point() c1 = spotlight.screen.get_start() c2 = spotlight.screen.get_end() return Polygon( sp, c1, c2, stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.5, ) spotlights = VGroup(spotlight_a, spotlight_b) spotlights_update_anim = Mobject.add_updater( spotlights, update_spotlights ) # Add components self.add( axes, lsA.ambient_light, lsB.ambient_light, lsC.ambient_light, line_c, ) self.add_foreground_mobjects( lsA.lighthouse, A_label, lsB.lighthouse, B_label, lsC.lighthouse, line_h, theorem, theorem_name, theorem_box, ) # Show miniature triangle self.play(ShowCreation(mini_triangle, lag_ratio = 0)) self.play( MoveToTarget(mini_triangle), run_time = 2, ) self.add_foreground_mobject(mini_triangle) # Show beams of light self.play( Write(screen_word), GrowArrow(screen_arrow), ) self.wait() spotlights_update_anim.update(0) self.play( LaggedStartMap(FadeIn, spotlight_a), LaggedStartMap(FadeIn, spotlight_b), Animation(screen_arrow), ) self.add(spotlights_update_anim) self.play(*list(map(FadeOut, [screen_word, screen_arrow]))) self.wait() # Reshape screen m_hyps = [m_hyp_a, m_hyp_b] for hyp, line in (m_hyp_a, m_a), (m_hyp_b, m_b): hyp.save_state() hyp.alt_version = line.copy() hyp.alt_version.set_color(WHITE) for x in range(2): self.play(*[ Transform(m, m.alt_version) for m in m_hyps ]) self.wait() self.play(*[m.restore for m in m_hyps]) self.wait() # Show spotlight a key point def show_beaming_light(spotlight): triangle = get_spotlight_triangle(spotlight) for x in range(3): anims = [] if x > 0: anims.append(FadeOut(triangle.copy())) anims.append(GrowFromPoint(triangle, triangle.get_points()[0])) self.play(*anims) self.play(FadeOut(triangle)) pass def show_key_point(spotlight, new_point): screen = spotlight.screen update_spotlight_anim = UpdateFromFunc(spotlight, update_spotlight) self.play( Transform(screen, screen.alt_version), update_spotlight_anim, ) show_beaming_light(spotlight) self.play(screen.restore, update_spotlight_anim) self.wait() self.play( lsC.move_source_to, new_point, Transform(screen, screen.alt_version), update_spotlight_anim, run_time = 2 ) show_beaming_light(spotlight) self.wait() self.play( lsC.move_source_to, H, screen.restore, update_spotlight_anim, run_time = 2 ) self.wait() self.remove(spotlights_update_anim) self.add(spotlight_b) self.play(*list(map(FadeOut, [ spotlight_a, lsA.ambient_light, lsB.ambient_light ]))) show_key_point(spotlight_b, A) self.play( FadeOut(spotlight_b), FadeIn(spotlight_a), ) show_key_point(spotlight_a, B) self.wait() class HomeworkWrapper(Scene): def construct(self): title = OldTexText("Homework") title.to_edge(UP) screen = ScreenRectangle(height = 6) screen.center() self.add(title) self.play(ShowCreation(screen)) self.wait(5) class HeresWhereThingsGetGood(TeacherStudentsScene): def construct(self): self.teacher_says("Now for the \\\\ good part!") self.play_student_changes(*["hooray"]*3) self.play_student_changes(*["happy"]*3) self.wait() class DiameterTheorem(TeacherStudentsScene): def construct(self): circle = Circle(radius = 2, color = WHITE) circle.next_to(self.students[2], UP) self.add(circle) center = Dot(circle.get_center(), color = WHITE) self.add_foreground_mobject(center) diameter_word = OldTexText("Diameter") diameter_word.next_to(center, DOWN, SMALL_BUFF) point = VectorizedPoint(circle.get_top()) triangle = Polygon(LEFT, RIGHT, UP) triangle.set_stroke(BLUE) triangle.set_fill(WHITE, 0.5) def update_triangle(triangle): triangle.set_points_as_corners([ circle.get_left(), circle.get_right(), point.get_center(), circle.get_left(), ]) triangle_update_anim = Mobject.add_updater( triangle, update_triangle ) triangle_update_anim.update(0) perp_mark = VMobject() perp_mark.set_points_as_corners([LEFT, DOWN, RIGHT]) perp_mark.shift(DOWN) perp_mark.scale(0.15, about_point = ORIGIN) perp_mark.shift(point.get_center()) perp_mark.add(point.copy()) self.play( self.teacher.change, "raise_right_hand", DrawBorderThenFill(triangle), Write(diameter_word), ) self.play( ShowCreation(perp_mark), self.change_students(*["pondering"]*3) ) self.add_foreground_mobjects(perp_mark) self.add(triangle_update_anim) for angle in 0.2*TAU, -0.4*TAU, 0.3*TAU: point.generate_target() point.target.rotate(angle, about_point = circle.get_center()) perp_mark.generate_target() perp_mark.target.rotate(angle/2) perp_mark.target.shift( point.target.get_center() - \ perp_mark.target[1].get_center() ) self.play( MoveToTarget(point), MoveToTarget(perp_mark), path_arc = angle, run_time = 3, ) class InscribedeAngleThreorem(TeacherStudentsScene): def construct(self): circle = Circle(radius = 2, color = WHITE) circle.next_to(self.students[2], UP) self.add(circle) title = OldTexText("Inscribed angle \\\\ theorem") title.to_corner(UP+LEFT) self.add(title) center = Dot(circle.get_center(), color = WHITE) self.add_foreground_mobject(center) point = VectorizedPoint(circle.get_left()) shape = Polygon(UP+LEFT, ORIGIN, DOWN+LEFT, RIGHT) shape.set_stroke(BLUE) def update_shape(shape): shape.set_points_as_corners([ point.get_center(), circle.point_from_proportion(7./8), circle.get_center(), circle.point_from_proportion(1./8), point.get_center(), ]) shape_update_anim = Mobject.add_updater( shape, update_shape ) shape_update_anim.update(0) angle_mark = Arc(start_angle = -TAU/8, angle = TAU/4) angle_mark.scale(0.3, about_point = ORIGIN) angle_mark.shift(circle.get_center()) theta = OldTex("\\theta").set_color(RED) theta.next_to(angle_mark, RIGHT, MED_SMALL_BUFF) angle_mark.match_color(theta) half_angle_mark = Arc(start_angle = -TAU/16, angle = TAU/8) half_angle_mark.scale(0.3, about_point = ORIGIN) half_angle_mark.shift(point.get_center()) half_angle_mark.add(point.copy()) theta_halves = OldTex("\\theta/2").set_color(GREEN) theta_halves.scale(0.7) half_angle_mark.match_color(theta_halves) theta_halves_update = UpdateFromFunc( theta_halves, lambda m : m.move_to(interpolate( point.get_center(), half_angle_mark.point_from_proportion(0.5), 2.5, )) ) theta_halves_update.update(0) self.play( self.teacher.change, "raise_right_hand", ShowCreation(shape, rate_func=linear), ) self.play(*list(map(FadeIn, [angle_mark, theta]))) self.play( ShowCreation(half_angle_mark), Write(theta_halves), self.change_students(*["pondering"]*3) ) self.add_foreground_mobjects(half_angle_mark, theta_halves) self.add(shape_update_anim) for angle in 0.25*TAU, -0.4*TAU, 0.3*TAU, -0.35*TAU: point.generate_target() point.target.rotate(angle, about_point = circle.get_center()) half_angle_mark.generate_target() half_angle_mark.target.rotate(angle/2) half_angle_mark.target.shift( point.target.get_center() - \ half_angle_mark.target[1].get_center() ) self.play( MoveToTarget(point), MoveToTarget(half_angle_mark), theta_halves_update, path_arc = angle, run_time = 3, ) class PondScene(ThreeDScene): def construct(self): BASELINE_YPOS = -2.5 OBSERVER_POINT = np.array([0,BASELINE_YPOS,0]) LAKE0_RADIUS = 1.5 INDICATOR_RADIUS = 0.6 TICK_SIZE = 0.5 LIGHTHOUSE_HEIGHT = 0.5 LAKE_COLOR = BLUE LAKE_OPACITY = 0.15 LAKE_STROKE_WIDTH = 5.0 LAKE_STROKE_COLOR = BLUE TEX_SCALE = 0.8 DOT_COLOR = BLUE LIGHT_MAX_INT = 1 LIGHT_SCALE = 2.5 LIGHT_CUTOFF = 1 RIGHT_ANGLE_SIZE = 0.3 self.cumulated_zoom_factor = 1 def right_angle(pointA, pointB, pointC, size = 1): v1 = pointA - pointB v1 = size * v1/get_norm(v1) v2 = pointC - pointB v2 = size * v2/get_norm(v2) P = pointB Q = pointB + v1 R = Q + v2 S = R - v1 angle_sign = VMobject() angle_sign.set_points_as_corners([P,Q,R,S,P]) angle_sign.mark_paths_closed = True angle_sign.set_fill(color = WHITE, opacity = 1) angle_sign.set_stroke(width = 0) return angle_sign def triangle(pointA, pointB, pointC): mob = VMobject() mob.set_points_as_corners([pointA, pointB, pointC, pointA]) mob.mark_paths_closed = True mob.set_fill(color = WHITE, opacity = 0.5) mob.set_stroke(width = 0) return mob def zoom_out_scene(factor): self.remove_foreground_mobject(self.ls0_dot) self.remove(self.ls0_dot) phi0 = self.camera.get_phi() # default is 0 degs theta0 = self.camera.get_theta() # default is -90 degs distance0 = self.camera.get_distance() distance1 = 2 * distance0 camera_target_point = self.camera.get_spherical_coords(phi0, theta0, distance1) self.play( ApplyMethod(self.camera.rotation_mobject.move_to, camera_target_point), self.zoomable_mobs.shift, self.obs_dot.get_center(), self.unzoomable_mobs.scale,2,{"about_point" : ORIGIN}, ) self.cumulated_zoom_factor *= factor # place ls0_dot by hand #old_radius = self.ls0_dot.radius #self.ls0_dot.radius = 2 * old_radius #v = self.ls0_dot.get_center() - self.obs_dot.get_center() #self.ls0_dot.shift(v) #self.ls0_dot.move_to(self.outer_lake.get_center()) self.ls0_dot.scale(2, about_point = ORIGIN) #self.add_foreground_mobject(self.ls0_dot) def shift_scene(v): self.play( self.zoomable_mobs.shift,v, self.unzoomable_mobs.shift,v ) self.zoomable_mobs = VMobject() self.unzoomable_mobs = VMobject() baseline = VMobject() baseline.set_points_as_corners([[-8,BASELINE_YPOS,0],[8,BASELINE_YPOS,0]]) baseline.set_stroke(width = 0) # in case it gets accidentally added to the scene self.zoomable_mobs.add(baseline) # prob not necessary obs_dot = self.obs_dot = Dot(OBSERVER_POINT, fill_color = DOT_COLOR) ls0_dot = self.ls0_dot = Dot(OBSERVER_POINT + 2 * LAKE0_RADIUS * UP, fill_color = WHITE) self.unzoomable_mobs.add(self.obs_dot)#, self.ls0_dot) # lake lake0 = Circle(radius = LAKE0_RADIUS, stroke_width = 0, fill_color = LAKE_COLOR, fill_opacity = LAKE_OPACITY ) lake0.move_to(OBSERVER_POINT + LAKE0_RADIUS * UP) self.zoomable_mobs.add(lake0) # Morty and indicator morty = Mortimer().flip().scale(0.3) morty.next_to(OBSERVER_POINT,DOWN) indicator = LightIndicator(precision = 2, radius = INDICATOR_RADIUS, show_reading = False, color = LIGHT_COLOR ) indicator.next_to(morty,LEFT) self.unzoomable_mobs.add(morty, indicator) # first lighthouse original_op_func = inverse_quadratic(LIGHT_MAX_INT,LIGHT_SCALE,LIGHT_CUTOFF) ls0 = LightSource(opacity_function = original_op_func, radius = 15.0, num_levels = 150) ls0.lighthouse.set_height(LIGHTHOUSE_HEIGHT) ls0.lighthouse.height = LIGHTHOUSE_HEIGHT ls0.move_source_to(OBSERVER_POINT + LAKE0_RADIUS * 2 * UP) self.zoomable_mobs.add(ls0, ls0.lighthouse, ls0.ambient_light) # self.add(lake0, morty, obs_dot, ls0_dot, ls0.lighthouse) # shore arcs arc_left = Arc(-TAU/2, radius = LAKE0_RADIUS, start_angle = -TAU/4, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR ) arc_left.move_arc_center_to(OBSERVER_POINT + LAKE0_RADIUS * UP) one_left = OldTex("1", color = LAKE_COLOR).scale(TEX_SCALE) one_left.next_to(arc_left,LEFT) arc_right = Arc(TAU/2, radius = LAKE0_RADIUS, start_angle = -TAU/4, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR ) arc_right.move_arc_center_to(OBSERVER_POINT + LAKE0_RADIUS * UP) one_right = OldTex("1", color = LAKE_COLOR).scale(TEX_SCALE) one_right.next_to(arc_right,RIGHT) # New introduction lake0.save_state() morty.save_state() lake0.set_height(6) morty.to_corner(UP+LEFT) morty.fade(1) lake0.center() lake_word = OldTexText("Lake") lake_word.scale(2) lake_word.move_to(lake0) self.play( DrawBorderThenFill(lake0, stroke_width = 1), Write(lake_word) ) self.play( lake0.restore, lake_word.scale, 0.5, {"about_point" : lake0.get_bottom()}, lake_word.fade, 1 ) self.remove(lake_word) self.play(morty.restore) self.play( GrowFromCenter(obs_dot), GrowFromCenter(ls0_dot), FadeIn(ls0.lighthouse) ) self.add_foreground_mobjects(ls0.lighthouse, obs_dot, ls0_dot) self.play( SwitchOn(ls0.ambient_light), Animation(ls0.lighthouse), ) self.wait() self.play( morty.move_to, ls0.lighthouse, run_time = 3, path_arc = TAU/2, rate_func = there_and_back ) self.play( ShowCreation(arc_right), Write(one_right), ) self.play( ShowCreation(arc_left), Write(one_left), ) self.play( lake0.set_stroke, { "color": LAKE_STROKE_COLOR, "width" : LAKE_STROKE_WIDTH }, ) self.wait() self.add_foreground_mobjects(morty) # Show indicator self.play(FadeIn(indicator)) self.play(indicator.set_intensity, 0.5) diameter_start = interpolate(OBSERVER_POINT,ls0.get_source_point(),0.02) diameter_stop = interpolate(OBSERVER_POINT,ls0.get_source_point(),0.98) # diameter diameter = DoubleArrow(diameter_start, diameter_stop, buff = 0, color = WHITE, ) diameter_text = OldTex("d").scale(TEX_SCALE) diameter_text.next_to(diameter,RIGHT) self.play( GrowFromCenter(diameter), Write(diameter_text), #FadeOut(self.obs_dot), FadeOut(ls0_dot) ) self.wait() indicator_reading = OldTex("{1 \over d^2}").scale(TEX_SCALE) indicator_reading.move_to(indicator) self.unzoomable_mobs.add(indicator_reading) self.play( ReplacementTransform( diameter_text[0].copy(), indicator_reading[2], ), FadeIn(indicator_reading) ) self.wait() # replace d with its value new_diameter_text = OldTex("{2 \over \pi}").scale(TEX_SCALE) new_diameter_text.color = LAKE_COLOR new_diameter_text.move_to(diameter_text) self.play(FadeOut(diameter_text)) self.play(FadeIn(new_diameter_text)) self.wait(2) # insert into indicator reading new_reading = OldTex("{\pi^2 \over 4}").scale(TEX_SCALE) new_reading.move_to(indicator) new_diameter_text_copy = new_diameter_text.copy() new_diameter_text_copy.submobjects.reverse() self.play( FadeOut(indicator_reading), ReplacementTransform( new_diameter_text_copy, new_reading, parth_arc = 30*DEGREES ) ) indicator_reading = new_reading self.wait(2) self.play( FadeOut(one_left), FadeOut(one_right), FadeOut(new_diameter_text), FadeOut(arc_left), FadeOut(arc_right) ) self.add_foreground_mobjects(indicator, indicator_reading) self.unzoomable_mobs.add(indicator_reading) def indicator_wiggle(): INDICATOR_WIGGLE_FACTOR = 1.3 self.play( ScaleInPlace(indicator, INDICATOR_WIGGLE_FACTOR, rate_func = wiggle), ScaleInPlace(indicator_reading, INDICATOR_WIGGLE_FACTOR, rate_func = wiggle) ) def angle_for_index(i,step): return -TAU/4 + TAU/2**step * (i + 0.5) def position_for_index(i, step, scaled_down = False): theta = angle_for_index(i,step) radial_vector = np.array([np.cos(theta),np.sin(theta),0]) position = self.lake_center + self.lake_radius * radial_vector if scaled_down: return position.scale_about_point(self.obs_dot.get_center(),0.5) else: return position def split_light_source(i, step, show_steps = True, animate = True, run_time = 1): ls_new_loc1 = position_for_index(i,step + 1) ls_new_loc2 = position_for_index(i + 2**step,step + 1) hyp = VMobject() hyp1 = Line(self.lake_center,ls_new_loc1) hyp2 = Line(self.lake_center,ls_new_loc2) hyp.add(hyp2,hyp1) self.new_hypotenuses.append(hyp) if show_steps == True: self.play( ShowCreation(hyp, run_time = run_time) ) leg1 = Line(self.obs_dot.get_center(),ls_new_loc1) leg2 = Line(self.obs_dot.get_center(),ls_new_loc2) self.new_legs_1.append(leg1) self.new_legs_2.append(leg2) if show_steps == True: self.play( ShowCreation(leg1, run_time = run_time), ShowCreation(leg2, run_time = run_time), ) ls1 = self.light_sources_array[i] ls2 = ls1.copy() if animate == True: self.add(ls2) self.additional_light_sources.append(ls2) # check if the light sources are on screen ls_old_loc = np.array(ls1.get_source_point()) onscreen_old = np.any(np.abs(ls_old_loc) < 10) onscreen_1 = np.any(np.abs(ls_new_loc1) < 10) onscreen_2 = np.any(np.abs(ls_new_loc2) < 10) show_animation = (onscreen_old or onscreen_1 or onscreen_2) if show_animation or animate: ls1.generate_target() ls2.generate_target() ls1.target.move_source_to(ls_new_loc1) ls2.target.move_source_to(ls_new_loc2) ls1.fade(1) self.play( MoveToTarget(ls1), MoveToTarget(ls2), run_time = run_time ) else: ls1.move_source_to(ls_new_loc1) ls2.move_source_to(ls_new_loc1) def construction_step(n, show_steps = True, run_time = 1, simultaneous_splitting = False): # we assume that the scene contains: # an inner lake, self.inner_lake # an outer lake, self.outer_lake # light sources, self.light_sources # legs from the observer point to each light source # self.legs # altitudes from the observer point to the # locations of the light sources in the previous step # self.altitudes # hypotenuses connecting antipodal light sources # self.hypotenuses # these are mobjects! # first, fade out all of the hypotenuses and altitudes if show_steps == True: self.zoomable_mobs.remove(self.hypotenuses, self.altitudes, self.inner_lake) self.play( FadeOut(self.hypotenuses), FadeOut(self.altitudes), FadeOut(self.inner_lake) ) else: self.zoomable_mobs.remove(self.inner_lake) self.play( FadeOut(self.inner_lake) ) # create a new, outer lake self.lake_center = self.obs_dot.get_center() + self.lake_radius * UP new_outer_lake = Circle(radius = self.lake_radius, stroke_width = LAKE_STROKE_WIDTH, fill_color = LAKE_COLOR, fill_opacity = LAKE_OPACITY, stroke_color = LAKE_STROKE_COLOR ) new_outer_lake.move_to(self.lake_center) if show_steps == True: self.play( FadeIn(new_outer_lake, run_time = run_time), FadeIn(self.ls0_dot) ) else: self.play( FadeIn(new_outer_lake, run_time = run_time), ) self.wait() self.inner_lake = self.outer_lake self.outer_lake = new_outer_lake self.altitudes = self.legs #self.lake_center = self.outer_lake.get_center() self.additional_light_sources = [] self.new_legs_1 = [] self.new_legs_2 = [] self.new_hypotenuses = [] if simultaneous_splitting == False: for i in range(2**n): split_light_source(i, step = n, show_steps = show_steps, run_time = run_time ) if n == 1 and i == 0: # show again where the right angles are A = self.light_sources[0].get_center() B = self.additional_light_sources[0].get_center() C = self.obs_dot.get_center() triangle1 = triangle( A, C, B ) right_angle1 = right_angle( A, C, B, size = 2 * RIGHT_ANGLE_SIZE ) self.play( FadeIn(triangle1), FadeIn(right_angle1) ) self.wait() self.play( FadeOut(triangle1), FadeOut(right_angle1) ) self.wait() H = self.inner_lake.get_center() + self.lake_radius/2 * RIGHT L = self.outer_lake.get_center() triangle2 = triangle( L, H, C ) right_angle2 = right_angle( L, H, C, size = 2 * RIGHT_ANGLE_SIZE ) self.play( FadeIn(triangle2), FadeIn(right_angle2) ) self.wait() self.play( FadeOut(triangle2), FadeOut(right_angle2) ) self.wait() else: # simultaneous splitting old_lake = self.outer_lake.copy() old_ls = self.light_sources.copy() old_ls2 = old_ls.copy() for submob in old_ls2.submobjects: old_ls.add(submob) self.remove(self.outer_lake, self.light_sources) self.add(old_lake, old_ls) for i in range(2**n): split_light_source(i, step = n, show_steps = show_steps, run_time = run_time, animate = False ) self.play( ReplacementTransform(old_ls, self.light_sources, run_time = run_time), ReplacementTransform(old_lake, self.outer_lake, run_time = run_time), ) # collect the newly created mobs (in arrays) # into the appropriate Mobject containers self.legs = VMobject() for leg in self.new_legs_1: self.legs.add(leg) self.zoomable_mobs.add(leg) for leg in self.new_legs_2: self.legs.add(leg) self.zoomable_mobs.add(leg) for hyp in self.hypotenuses.submobjects: self.zoomable_mobs.remove(hyp) self.hypotenuses = VMobject() for hyp in self.new_hypotenuses: self.hypotenuses.add(hyp) self.zoomable_mobs.add(hyp) for ls in self.additional_light_sources: self.light_sources.add(ls) self.light_sources_array.append(ls) self.zoomable_mobs.add(ls) # update scene self.add( self.light_sources, self.inner_lake, self.outer_lake, ) self.zoomable_mobs.add(self.light_sources, self.inner_lake, self.outer_lake) if show_steps == True: self.add( self.legs, self.hypotenuses, self.altitudes, ) self.zoomable_mobs.add(self.legs, self.hypotenuses, self.altitudes) self.wait() if show_steps == True: self.play(FadeOut(self.ls0_dot)) #self.lake_center = ls0_loc = self.obs_dot.get_center() + self.lake_radius * UP self.lake_radius *= 2 self.lake_center = ls0_loc = ls0.get_source_point() self.inner_lake = VMobject() self.outer_lake = lake0 self.legs = VMobject() self.legs.add(Line(OBSERVER_POINT,self.lake_center)) self.altitudes = VMobject() self.hypotenuses = VMobject() self.light_sources_array = [ls0] self.light_sources = VMobject() self.light_sources.add(ls0) self.lake_radius = 2 * LAKE0_RADIUS # don't ask... self.zoomable_mobs.add(self.inner_lake, self.outer_lake, self.altitudes, self.light_sources) self.add( self.inner_lake, self.outer_lake, self.legs, self.altitudes, self.hypotenuses ) self.play(FadeOut(diameter)) self.additional_light_sources = [] self.new_legs_1 = [] self.new_legs_2 = [] self.new_hypotenuses = [] construction_step(0) my_triangle = triangle( self.light_sources[0].get_source_point(), OBSERVER_POINT, self.light_sources[1].get_source_point() ) angle_sign1 = right_angle( self.light_sources[0].get_source_point(), OBSERVER_POINT, self.light_sources[1].get_source_point(), size = RIGHT_ANGLE_SIZE ) self.play( FadeIn(angle_sign1), FadeIn(my_triangle) ) angle_sign2 = right_angle( self.light_sources[1].get_source_point(), self.lake_center, OBSERVER_POINT, size = RIGHT_ANGLE_SIZE ) self.play( FadeIn(angle_sign2) ) self.wait() self.play( FadeOut(angle_sign1), FadeOut(angle_sign2), FadeOut(my_triangle) ) indicator_wiggle() self.remove(self.ls0_dot) zoom_out_scene(2) construction_step(1) indicator_wiggle() #self.play(FadeOut(self.ls0_dot)) zoom_out_scene(2) construction_step(2) indicator_wiggle() self.play(FadeOut(self.ls0_dot)) self.play( FadeOut(self.altitudes), FadeOut(self.hypotenuses), FadeOut(self.legs) ) max_it = 6 scale = 2**(max_it - 4) TEX_SCALE *= scale # for i in range(3,max_it + 1): # construction_step(i, show_steps = False, run_time = 4.0/2**i, # simultaneous_splitting = True) # simultaneous expansion of light sources from now on self.play(FadeOut(self.inner_lake)) for n in range(3,max_it + 1): new_lake = self.outer_lake.copy().scale(2,about_point = self.obs_dot.get_center()) for ls in self.light_sources_array: lsp = ls.copy() self.light_sources.add(lsp) self.add(lsp) self.light_sources_array.append(lsp) new_lake_center = new_lake.get_center() new_lake_radius = 0.5 * new_lake.get_width() shift_list = (Transform(self.outer_lake,new_lake),) for i in range(2**n): theta = -TAU/4 + (i + 0.5) * TAU / 2**n v = np.array([np.cos(theta), np.sin(theta),0]) pos1 = new_lake_center + new_lake_radius * v pos2 = new_lake_center - new_lake_radius * v shift_list += (self.light_sources.submobjects[i].move_source_to,pos1) shift_list += (self.light_sources.submobjects[i+2**n].move_source_to,pos2) self.play(*shift_list) #self.revert_to_original_skipping_status() # Now create a straight number line and transform into it MAX_N = 17 origin_point = self.obs_dot.get_center() self.number_line = NumberLine( x_min = -MAX_N, x_max = MAX_N + 1, color = WHITE, number_at_center = 0, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR, #numbers_with_elongated_ticks = range(-MAX_N,MAX_N + 1), numbers_to_show = list(range(-MAX_N,MAX_N + 1,2)), unit_size = LAKE0_RADIUS * TAU/4 / 2 * scale, tick_frequency = 1, line_to_number_buff = LARGE_BUFF, label_direction = UP, ).shift(scale * 2.5 * DOWN) self.number_line.label_direction = DOWN self.number_line_labels = self.number_line.get_number_mobjects() self.wait() origin_point = self.number_line.number_to_point(0) nl_sources = VMobject() pond_sources = VMobject() for i in range(-MAX_N,MAX_N+1): anchor = self.number_line.number_to_point(2*i + 1) ls = self.light_sources_array[i].copy() ls.move_source_to(anchor) nl_sources.add(ls) pond_sources.add(self.light_sources_array[i].copy()) self.add(pond_sources) self.remove(self.light_sources) self.outer_lake.rotate(TAU/8) # open sea open_sea = Rectangle( width = 20 * scale, height = 10 * scale, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR, fill_color = LAKE_COLOR, fill_opacity = LAKE_OPACITY, ).flip().next_to(origin_point,UP,buff = 0) self.play( ReplacementTransform(pond_sources,nl_sources), ReplacementTransform(self.outer_lake,open_sea), FadeOut(self.inner_lake) ) self.play(FadeIn(self.number_line)) self.wait() v = 4 * scale * UP self.play( nl_sources.shift,v, morty.shift,v, self.number_line.shift,v, indicator.shift,v, indicator_reading.shift,v, open_sea.shift,v, self.obs_dot.shift,v, ) self.number_line_labels.shift(v) origin_point = self.number_line.number_to_point(0) #self.remove(self.obs_dot) self.play( indicator.move_to, origin_point + scale * UP, indicator_reading.move_to, origin_point + scale * UP, FadeOut(open_sea), FadeOut(morty), FadeIn(self.number_line_labels) ) two_sided_sum = OldTex("\dots", "+", "{1\over (-11)^2}",\ "+", "{1\over (-9)^2}", " + ", "{1\over (-7)^2}", " + ", "{1\over (-5)^2}", " + ", \ "{1\over (-3)^2}", " + ", "{1\over (-1)^2}", " + ", "{1\over 1^2}", " + ", \ "{1\over 3^2}", " + ", "{1\over 5^2}", " + ", "{1\over 7^2}", " + ", \ "{1\over 9^2}", " + ", "{1\over 11^2}", " + ", "\dots") nb_symbols = len(two_sided_sum.submobjects) two_sided_sum.scale(TEX_SCALE) for (i,submob) in zip(list(range(nb_symbols)),two_sided_sum.submobjects): submob.next_to(self.number_line.number_to_point(i - 13),DOWN, buff = 2*scale) if (i == 0 or i % 2 == 1 or i == nb_symbols - 1): # non-fractions submob.shift(0.3 * scale * DOWN) self.play(Write(two_sided_sum)) for i in range(MAX_N - 5, MAX_N): self.remove(nl_sources.submobjects[i].ambient_light) for i in range(MAX_N, MAX_N + 5): self.add_foreground_mobject(nl_sources.submobjects[i].ambient_light) self.wait() covering_rectangle = Rectangle( width = FRAME_X_RADIUS * scale, height = 2 * FRAME_Y_RADIUS * scale, stroke_width = 0, fill_color = BLACK, fill_opacity = 1, ) covering_rectangle.next_to(ORIGIN,LEFT,buff = 0) for i in range(10): self.add_foreground_mobject(nl_sources.submobjects[i]) self.add_foreground_mobject(indicator) self.add_foreground_mobject(indicator_reading) half_indicator_reading = OldTex("{\pi^2 \over 8}").scale(TEX_SCALE) half_indicator_reading.move_to(indicator) central_plus_sign = two_sided_sum[13] self.play( FadeIn(covering_rectangle), Transform(indicator_reading, half_indicator_reading), FadeOut(central_plus_sign) ) equals_sign = OldTex("=").scale(TEX_SCALE) equals_sign.move_to(central_plus_sign) p = 2 * scale * LEFT + central_plus_sign.get_center()[1] * UP self.play( indicator.move_to,p, indicator_reading.move_to,p, FadeIn(equals_sign), ) self.revert_to_original_skipping_status() # show Randy admiring the result randy = Randolph(color = MAROON_E).scale(scale).move_to(2*scale*DOWN+5*scale*LEFT) self.play(FadeIn(randy)) self.play(randy.change,"happy") self.play(randy.change,"hooray") class CircumferenceText(Scene): CONFIG = {"n" : 16} def construct(self): words = OldTexText("Circumference %d"%self.n) words.scale(1.25) words.to_corner(UP+LEFT) self.add(words) class CenterOfLargerCircleOverlayText(Scene): def construct(self): words = OldTexText("Center of \\\\ larger circle") arrow = Vector(DOWN+LEFT, color = WHITE) arrow.shift(words.get_bottom() + SMALL_BUFF*DOWN - arrow.get_start()) group = VGroup(words, arrow) group.set_height(FRAME_HEIGHT - 1) group.to_edge(UP) self.add(group) class DiameterWordOverlay(Scene): def construct(self): word = OldTexText("Diameter") word.set_width(FRAME_X_RADIUS) word.rotate(-45*DEGREES) self.play(Write(word)) self.wait() class YayIPTApplies(TeacherStudentsScene): def construct(self): self.teacher_says( "Heyo! The Inverse \\\\ Pythagorean Theorem \\\\ applies!", bubble_config = {"width" : 5}, target_mode = "surprised" ) self.play_student_changes(*3*["hooray"]) self.wait(2) class WalkThroughOneMoreStep(TeacherStudentsScene): def construct(self): self.student_says(""" Wait...can you walk \\\\ through one more step? """) self.play(self.teacher.change, "happy") self.wait(4) class ThinkBackToHowAmazingThisIs(ThreeDScene): CONFIG = { "x_radius" : 100, "max_shown_n" : 20, } def construct(self): self.show_sum() self.show_giant_circle() def show_sum(self): number_line = NumberLine( x_min = -self.x_radius, x_max = self.x_radius, numbers_to_show = list(range(-self.max_shown_n, self.max_shown_n)), ) number_line.add_numbers() number_line.shift(2*DOWN) positive_dots, negative_dots = [ VGroup(*[ Dot(number_line.number_to_point(u*x)) for x in range(1, int(self.x_radius), 2) ]) for u in (1, -1) ] dot_pairs = it.starmap(VGroup, list(zip(positive_dots, negative_dots))) # Decimal decimal = DecimalNumber(0, num_decimal_places = 6) decimal.to_edge(UP) terms = [2./(n**2) for n in range(1, 100, 2)] partial_sums = np.cumsum(terms) # pi^2/4 label brace = Brace(decimal, DOWN) pi_term = OldTex("\pi^2 \over 4") pi_term.next_to(brace, DOWN) term_mobjects = VGroup() for n in range(1, self.max_shown_n, 2): p_term = OldTex("\\left(\\frac{1}{%d}\\right)^2"%n) n_term = OldTex("\\left(\\frac{-1}{%d}\\right)^2"%n) group = VGroup(p_term, n_term) group.scale(0.7) p_term.next_to(number_line.number_to_point(n), UP, LARGE_BUFF) n_term.next_to(number_line.number_to_point(-n), UP, LARGE_BUFF) term_mobjects.add(group) term_mobjects.set_color_by_gradient(BLUE, YELLOW) plusses = VGroup(*[ VGroup(*[ OldTex("+").next_to( number_line.number_to_point(u*n), UP, buff = 1.25, ) for u in (-1, 1) ]) for n in range(0, self.max_shown_n, 2) ]) zoom_out = always_shift( self.camera.rotation_mobject, direction = OUT, rate = 0.4 ) def update_decimal(decimal): z = self.camera.rotation_mobject.get_center()[2] decimal.set_height(0.07*z) decimal.move_to(0.7*z*UP) scale_decimal = Mobject.add_updater(decimal, update_decimal) self.add(number_line, *dot_pairs) self.add(zoom_out, scale_decimal) tuples = list(zip(term_mobjects, plusses, partial_sums)) run_time = 1 for term_mobs, plus_pair, partial_sum in tuples: self.play( FadeIn(term_mobs), Write(plus_pair, run_time = 1), ChangeDecimalToValue(decimal, partial_sum), run_time = run_time ) self.wait(run_time) run_time *= 0.9 self.play(ChangeDecimalToValue(decimal, np.pi**2/4, run_time = 5)) zoom_out.begin_wind_down() self.wait() self.remove(zoom_out, scale_decimal) self.play(*list(map(FadeOut, it.chain( term_mobjects, plusses, number_line.numbers, [decimal] )))) self.number_line = number_line def show_giant_circle(self): self.number_line.insert_n_curves(10000) everything = VGroup(*self.mobjects) circle = everything.copy() circle.move_to(ORIGIN) circle.apply_function( lambda x_y_z : complex_to_R3(7*np.exp(complex(0, 0.0315*x_y_z[0]))) ) circle.rotate(-TAU/4, about_point = ORIGIN) circle.center() self.play(Transform(everything, circle, run_time = 6)) class ButWait(TeacherStudentsScene): def construct(self): self.student_says( "But wait!", target_mode = "angry", run_time = 1, ) self.play_student_changes( "sassy", "angry", "sassy", added_anims = [self.teacher.change, "guilty"], run_time = 1 ) self.student_says( """ You promised us \\\\ $1+{1 \\over 4} + {1 \\over 9} + {1 \\over 16} + \\cdots$ """, target_mode = "sassy", ) self.wait(3) self.teacher_says("Yes, but that's \\\\ very close.") self.play_student_changes(*["plain"]*3) self.wait(2) class FinalSumManipulationScene(PiCreatureScene): def construct(self): LAKE_COLOR = BLUE LAKE_OPACITY = 0.15 LAKE_STROKE_WIDTH = 5.0 LAKE_STROKE_COLOR = BLUE TEX_SCALE = 0.8 LIGHT_COLOR2 = RED LIGHT_COLOR3 = BLUE unit_length = 1.5 vertical_spacing = 2.5 * DOWN switch_on_time = 0.2 sum_vertical_spacing = 1.5 randy = self.get_primary_pi_creature() randy.set_color(MAROON_D) randy.color = MAROON_D randy.scale(0.7).flip().to_edge(DOWN + LEFT) self.wait() ls_template = LightSource( radius = 1, num_levels = 10, max_opacity_ambient = 0.5, opacity_function = inverse_quadratic(1,0.75,1) ) odd_range = np.arange(1,9,2) even_range = np.arange(2,16,2) full_range = np.arange(1,8,1) self.number_line1 = NumberLine( x_min = 0, x_max = 11, color = LAKE_STROKE_COLOR, number_at_center = 0, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR, #numbers_to_show = full_range, number_scale_val = 0.5, numbers_with_elongated_ticks = [], unit_size = unit_length, tick_frequency = 1, line_to_number_buff = MED_SMALL_BUFF, include_tip = True, label_direction = UP, ) self.number_line1.next_to(2.5 * UP + 3 * LEFT, RIGHT, buff = 0.3) self.number_line1.add_numbers() odd_lights = VMobject() for i in odd_range: pos = self.number_line1.number_to_point(i) ls = ls_template.copy() ls.move_source_to(pos) odd_lights.add(ls) self.play( ShowCreation(self.number_line1, run_time = 5), ) self.wait() odd_terms = VMobject() for i in odd_range: if i == 1: term = OldTex("\phantom{+\,\,\,}{1\over " + str(i) + "^2}", fill_color = LIGHT_COLOR, stroke_color = LIGHT_COLOR) else: term = OldTex("+\,\,\, {1\over " + str(i) + "^2}", fill_color = LIGHT_COLOR, stroke_color = LIGHT_COLOR) term.next_to(self.number_line1.number_to_point(i), DOWN, buff = 1.5) odd_terms.add(term) for (ls, term) in zip(odd_lights.submobjects, odd_terms.submobjects): self.play( FadeIn(ls.lighthouse, run_time = switch_on_time), SwitchOn(ls.ambient_light, run_time = switch_on_time), Write(term, run_time = switch_on_time) ) result1 = OldTex("{\pi^2\over 8} =", fill_color = LIGHT_COLOR, stroke_color = LIGHT_COLOR) result1.next_to(self.number_line1, LEFT, buff = 0.5) result1.shift(0.87 * vertical_spacing) self.play(Write(result1)) self.number_line2 = self.number_line1.copy() self.number_line2.numbers_to_show = full_range self.number_line2.shift(2 * vertical_spacing) self.number_line2.add_numbers() full_lights = VMobject() for i in full_range: pos = self.number_line2.number_to_point(i) ls = ls_template.copy() ls.color = LIGHT_COLOR3 ls.move_source_to(pos) full_lights.add(ls) self.play( ShowCreation(self.number_line2, run_time = 5), ) self.wait() full_lighthouses = VMobject() full_ambient_lights = VMobject() for ls in full_lights: full_lighthouses.add(ls.lighthouse) full_ambient_lights.add(ls.ambient_light) self.play( LaggedStartMap(FadeIn, full_lighthouses, lag_ratio = 0.2, run_time = 3), ) self.play( LaggedStartMap(SwitchOn, full_ambient_lights, lag_ratio = 0.2, run_time = 3) ) # for ls in full_lights.submobjects: # self.play( # FadeIn(ls.lighthouse, run_time = 0.1),#5 * switch_on_time), # SwitchOn(ls.ambient_light, run_time = 0.1)#5 * switch_on_time), # ) even_terms = VMobject() for i in even_range: term = OldTex("+\,\,\, {1\over " + str(i) + "^2}", fill_color = LIGHT_COLOR2, stroke_color = LIGHT_COLOR) term.next_to(self.number_line1.number_to_point(i), DOWN, buff = sum_vertical_spacing) even_terms.add(term) even_lights = VMobject() for i in even_range: pos = self.number_line1.number_to_point(i) ls = ls_template.copy() ls.color = LIGHT_COLOR2 ls.move_source_to(pos) even_lights.add(ls) for (ls, term) in zip(even_lights.submobjects, even_terms.submobjects): self.play( SwitchOn(ls.ambient_light, run_time = switch_on_time), Write(term) ) self.wait() # now morph the even lights into the full lights full_lights_copy = full_lights.copy() even_lights_copy = even_lights.copy() self.play( Transform(even_lights,full_lights, run_time = 2) ) self.wait() for i in range(6): self.play( Transform(even_lights[i], even_lights_copy[i]) ) self.wait() # draw arrows P1 = self.number_line2.number_to_point(1) P2 = even_terms.submobjects[0].get_center() Q1 = interpolate(P1, P2, 0.2) Q2 = interpolate(P1, P2, 0.8) quarter_arrow = Arrow(Q1, Q2, color = LIGHT_COLOR2) quarter_label = OldTex("\\times {1\over 4}", fill_color = LIGHT_COLOR2, stroke_color = LIGHT_COLOR2) quarter_label.scale(0.7) quarter_label.next_to(quarter_arrow.get_center(), RIGHT) self.play( ShowCreation(quarter_arrow), Write(quarter_label), ) self.wait() P3 = odd_terms.submobjects[0].get_center() R1 = interpolate(P1, P3, 0.2) R2 = interpolate(P1, P3, 0.8) three_quarters_arrow = Arrow(R1, R2, color = LIGHT_COLOR) three_quarters_label = OldTex("\\times {3\over 4}", fill_color = LIGHT_COLOR, stroke_color = LIGHT_COLOR) three_quarters_label.scale(0.7) three_quarters_label.next_to(three_quarters_arrow.get_center(), LEFT) self.play( ShowCreation(three_quarters_arrow), Write(three_quarters_label) ) self.wait() four_thirds_arrow = Arrow(R2, R1, color = LIGHT_COLOR) four_thirds_label = OldTex("\\times {4\over 3}", fill_color = LIGHT_COLOR, stroke_color = LIGHT_COLOR) four_thirds_label.scale(0.7) four_thirds_label.next_to(four_thirds_arrow.get_center(), LEFT) self.play( FadeOut(quarter_label), FadeOut(quarter_arrow), FadeOut(even_lights), FadeOut(even_terms) ) self.wait() self.play( ReplacementTransform(three_quarters_arrow, four_thirds_arrow), ReplacementTransform(three_quarters_label, four_thirds_label) ) self.wait() full_terms = VMobject() for i in range(1,8): #full_range: if i == 1: term = OldTex("\phantom{+\,\,\,}{1\over " + str(i) + "^2}", fill_color = LIGHT_COLOR3, stroke_color = LIGHT_COLOR3) elif i == 7: term = OldTex("+\,\,\,\dots", fill_color = LIGHT_COLOR3, stroke_color = LIGHT_COLOR3) else: term = OldTex("+\,\,\, {1\over " + str(i) + "^2}", fill_color = LIGHT_COLOR3, stroke_color = LIGHT_COLOR3) term.move_to(self.number_line2.number_to_point(i)) full_terms.add(term) #return self.play( FadeOut(self.number_line1), FadeOut(odd_lights), FadeOut(self.number_line2), FadeOut(full_lights), FadeIn(full_terms) ) self.wait() v = (sum_vertical_spacing + 0.5) * UP self.play( odd_terms.shift, v, result1.shift, v, four_thirds_arrow.shift, v, four_thirds_label.shift, v, odd_terms.shift, v, full_terms.shift, v ) arrow_copy = four_thirds_arrow.copy() label_copy = four_thirds_label.copy() arrow_copy.shift(2.5 * LEFT) label_copy.shift(2.5 * LEFT) self.play( FadeIn(arrow_copy), FadeIn(label_copy) ) self.wait() final_result = OldTex("{\pi^2 \over 6}=", fill_color = LIGHT_COLOR3, stroke_color = LIGHT_COLOR3) final_result.next_to(arrow_copy, DOWN) self.play( Write(final_result), randy.change_mode,"hooray" ) self.wait() equation = VMobject() equation.add(final_result) equation.add(full_terms) self.play( FadeOut(result1), FadeOut(odd_terms), FadeOut(arrow_copy), FadeOut(label_copy), FadeOut(four_thirds_arrow), FadeOut(four_thirds_label), full_terms.shift,LEFT, ) self.wait() self.play(equation.shift, -equation.get_center()[1] * UP + UP + 1.5 * LEFT) result_box = Rectangle(width = 1.1 * equation.get_width(), height = 2 * equation.get_height(), color = LIGHT_COLOR3) result_box.move_to(equation) self.play( ShowCreation(result_box) ) self.wait() class LabeledArc(Arc): CONFIG = { "length" : 1 } def __init__(self, angle, **kwargs): BUFFER = 0.8 Arc.__init__(self,angle,**kwargs) label = DecimalNumber(self.length, num_decimal_places = 0) r = BUFFER * self.radius theta = self.start_angle + self.angle/2 label_pos = r * np.array([np.cos(theta), np.sin(theta), 0]) label.move_to(label_pos) self.add(label) class ArcHighlightOverlaySceneCircumferenceEight(Scene): CONFIG = { "n" : 2, } def construct(self): BASELINE_YPOS = -2.5 OBSERVER_POINT = [0,BASELINE_YPOS,0] LAKE0_RADIUS = 2.5 INDICATOR_RADIUS = 0.6 TICK_SIZE = 0.5 LIGHTHOUSE_HEIGHT = 0.2 LAKE_COLOR = BLUE LAKE_OPACITY = 0.15 LAKE_STROKE_WIDTH = 5.0 LAKE_STROKE_COLOR = BLUE TEX_SCALE = 0.8 DOT_COLOR = BLUE FLASH_TIME = 1 def flash_arcs(n): angle = TAU/2**n arcs = [] arcs.append(LabeledArc(angle/2, start_angle = -TAU/4, radius = LAKE0_RADIUS, length = 1)) for i in range(1,2**n): arcs.append(LabeledArc(angle, start_angle = -TAU/4 + (i-0.5)*angle, radius = LAKE0_RADIUS, length = 2)) arcs.append(LabeledArc(angle/2, start_angle = -TAU/4 - angle/2, radius = LAKE0_RADIUS, length = 1)) self.play( FadeIn(arcs[0], run_time = FLASH_TIME) ) for i in range(1,2**n + 1): self.play( FadeOut(arcs[i-1], run_time = FLASH_TIME), FadeIn(arcs[i], run_time = FLASH_TIME) ) self.play( FadeOut(arcs[2**n], run_time = FLASH_TIME), ) flash_arcs(self.n) class ArcHighlightOverlaySceneCircumferenceSixteen(ArcHighlightOverlaySceneCircumferenceEight): CONFIG = { "n" : 3, } class InfiniteCircleScene(PiCreatureScene): def construct(self): morty = self.get_primary_pi_creature() morty.set_color(MAROON_D).flip() morty.color = MAROON_D morty.scale(0.5).move_to(ORIGIN) arrow = Arrow(ORIGIN, 2.4 * RIGHT) dot = Dot(color = BLUE).next_to(arrow) ellipsis = OldTex("\dots") infsum = VGroup() infsum.add(ellipsis.copy()) for i in range(3): infsum.add(arrow.copy().next_to(infsum.submobjects[-1])) infsum.add(dot.copy().next_to(infsum.submobjects[-1])) infsum.add(arrow.copy().next_to(infsum.submobjects[-1])) infsum.add(ellipsis.copy().next_to(infsum.submobjects[-1])) infsum.next_to(morty,DOWN, buff = 1) self.wait() self.play( LaggedStartMap(FadeIn,infsum,lag_ratio = 0.2) ) self.wait() A = infsum.submobjects[-1].get_center() + 0.5 * RIGHT B = A + RIGHT + 1.3 * UP + 0.025 * LEFT right_arc = DashedLine(TAU/4*UP, ORIGIN, stroke_color = YELLOW, stroke_width = 8).apply_complex_function(np.exp) right_arc.rotate(-TAU/4).next_to(infsum, RIGHT).shift(0.5 * UP) right_tip_line = Arrow(B - UP, B, color = WHITE) right_tip_line.add_tip() right_tip = right_tip_line.get_tip() right_tip.set_fill(color = YELLOW) right_arc.add(right_tip) C = B + 3.2 * UP right_line = DashedLine(B + 0.2 * DOWN,C + 0.2 * UP, stroke_color = YELLOW, stroke_width = 8) ru_arc = right_arc.copy().rotate(angle = TAU/4) ru_arc.remove(ru_arc.submobjects[-1]) ru_arc.to_edge(UP+RIGHT, buff = 0.15) D = np.array([5.85, 3.85,0]) E = np.array([-D[0],D[1],0]) up_line = DashedLine(D, E, stroke_color = YELLOW, stroke_width = 8) lu_arc = ru_arc.copy().flip().to_edge(LEFT + UP, buff = 0.15) left_line = right_line.copy().flip(axis = RIGHT).to_edge(LEFT, buff = 0.15) left_arc = right_arc.copy().rotate(-TAU/4) left_arc.next_to(infsum, LEFT).shift(0.5 * UP + 0.1 * LEFT) right_arc.shift(0.2 * RIGHT) right_line.shift(0.2 * RIGHT) self.play(FadeIn(right_arc)) self.play(ShowCreation(right_line)) self.play(FadeIn(ru_arc)) self.play(ShowCreation(up_line)) self.play(FadeIn(lu_arc)) self.play(ShowCreation(left_line)) self.play(FadeIn(left_arc)) self.wait() class Credits(Scene): def construct(self): credits = VGroup(*[ VGroup(*list(map(TexText, pair))) for pair in [ ("Primary writer and animator:", "Ben Hambrecht"), ("Editing, advising, narrating:", "Grant Sanderson"), ("Based on a paper originally by:", "Johan Wästlund"), ] ]) for credit, color in zip(credits, [MAROON_D, BLUE_D, WHITE]): credit[1].set_color(color) credit.arrange(DOWN, buff = SMALL_BUFF) credits.arrange(DOWN, buff = LARGE_BUFF) credits.center() patreon_logo = PatreonLogo() patreon_logo.to_edge(UP) for credit in credits: self.play(LaggedStartMap(FadeIn, credit[0])) self.play(FadeIn(credit[1])) self.wait() self.play( credits.next_to, patreon_logo.get_bottom(), DOWN, MED_LARGE_BUFF, DrawBorderThenFill(patreon_logo) ) self.wait() class Promotion(PiCreatureScene): CONFIG = { "seconds_to_blink" : 5, } def construct(self): url = OldTexText("https://brilliant.org/3b1b/") url.to_corner(UP+LEFT) rect = Rectangle(height = 9, width = 16) rect.set_height(5.5) rect.next_to(url, DOWN) rect.to_edge(LEFT) self.play( Write(url), self.pi_creature.change, "raise_right_hand" ) self.play(ShowCreation(rect)) self.wait(2) self.change_mode("thinking") self.wait() self.look_at(url) self.wait(10) self.change_mode("happy") self.wait(10) self.change_mode("raise_right_hand") self.wait(10) self.remove(rect) self.play( url.next_to, self.pi_creature, UP+LEFT ) url_rect = SurroundingRectangle(url) self.play(ShowCreation(url_rect)) self.play(FadeOut(url_rect)) self.wait(3) class BaselPatreonThanks(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 Ku$\\overline{\\text{a}}$ng", "Mathew Bramson", "Jerry Ling", "Mustafa Mahdi", "Meshal Alshammari", "Mayank M. Mehrotra", "Lukas Biewald", "Robert Teed", "Samantha D. Suplee", "Mark Govea", "John Haley", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Desmos ", "Boris Veselinovich", "Ryan Dahl", "Ripta Pasay", "Eric Lavault", "Randall Hunt", "Andrew Busey", "Mads Elvheim", "Tianyu Ge", "Awoo", "Dr. David G. Stork", "Linh Tran", "Jason Hise", "Bernd Sing", "James H. Park", "Ankalagon ", "Devin Scott", "Mathias Jansson", "David Clark", "Ted Suzman", "Eric Chow", "Michael Gardner", "David Kedmey", "Jonathan Eppele", "Clark Gaebel", "Jordan Scales", "Ryan Atallah", "supershabam ", "1stViewMaths ", "Jacob Magnuson", "Chloe Zhou", "Ross Garber", "Thomas Tarler", "Isak Hietala", "Egor Gumenuk", "Waleed Hamied", "Oliver Steele", "Yaw Etse", "David B", "Delton Ding", "James Thornton", "Felix Tripier", "Arthur Zey", "George Chiesa", "Norton Wang", "Kevin Le", "Alexander Feldman", "David MacCumber", "Jacob Kohl", "Sergei ", "Frank Secilia", "Patrick Mézard", "George John", "Akash Kumar", "Britt Selvitelle", "Jonathan Wilson", "Ignacio Freiberg", "Zhilong Yang", "Karl Niu", "Dan Esposito", "Michael Kunze", "Giovanni Filippi", "Eric Younge", "Prasant Jagannath", "Andrejs Olins", "Cody Brocious", ], } def construct(self): next_video = OldTexText("$\\uparrow$ Next video $\\uparrow$") next_video.to_edge(RIGHT, buff = 1.5) next_video.shift(MED_SMALL_BUFF*UP) next_video.set_color(YELLOW) self.add_foreground_mobject(next_video) PatreonEndScreen.construct(self) class Thumbnail(Scene): CONFIG = { "light_source_config" : { "num_levels" : 250, "radius" : 10.0, "max_opacity_ambient" : 1.0, "opacity_function" : inverse_quadratic(1,0.25,1) } } def construct(self): equation = OldTex( "1", "+", "{1\over 4}", "+", "{1\over 9}","+", "{1\over 16}","+", "{1\over 25}", "+", "\cdots" ) equation.scale(1.8) equation.move_to(2*UP) equation.set_stroke(RED, 1) answer = OldTex("= \\frac{\\pi^2}{6}", color = LIGHT_COLOR) answer.scale(3) answer.set_stroke(RED, 1) # answer.next_to(equation, DOWN, buff = 1) answer.move_to(1.25*DOWN) #equation.move_to(2 * UP) #answer = OldTex("={\pi^2\over 6}", color = LIGHT_COLOR).scale(3) #answer.next_to(equation, DOWN, buff = 1) lake_radius = 6 lake_center = ORIGIN lake = Circle( fill_color = BLUE, fill_opacity = 0.15, radius = lake_radius, stroke_color = BLUE_D, stroke_width = 3, ) lake.move_to(lake_center) for i in range(16): theta = -TAU/4 + (i + 0.5) * TAU/16 pos = lake_center + lake_radius * np.array([np.cos(theta), np.sin(theta), 0]) ls = LightSource(**self.light_source_config) ls.move_source_to(pos) lake.add(ls.ambient_light) lake.add(ls.lighthouse) self.add(lake) self.add(equation, answer) self.wait()
#!/usr/bin/env python from manim_imports_ext import * from once_useful_constructs.light import * import warnings warnings.warn(""" Warning: This file makes use of ContinualAnimation, which has since been deprecated """) import types import functools LIGHT_COLOR = YELLOW INDICATOR_RADIUS = 0.7 INDICATOR_STROKE_WIDTH = 1 INDICATOR_STROKE_COLOR = WHITE INDICATOR_TEXT_COLOR = WHITE INDICATOR_UPDATE_TIME = 0.2 FAST_INDICATOR_UPDATE_TIME = 0.1 OPACITY_FOR_UNIT_INTENSITY = 0.2 SWITCH_ON_RUN_TIME = 1.5 FAST_SWITCH_ON_RUN_TIME = 0.1 NUM_CONES = 7 # in first lighthouse scene NUM_VISIBLE_CONES = 5 # ibidem ARC_TIP_LENGTH = 0.2 NUM_LEVELS = 15 AMBIENT_FULL = 0.8 AMBIENT_DIMMED = 0.5 AMBIENT_SCALE = 2.0 AMBIENT_RADIUS = 20.0 SPOTLIGHT_FULL = 0.8 SPOTLIGHT_DIMMED = 0.2 SPOTLIGHT_SCALE = 1.0 SPOTLIGHT_RADIUS = 20.0 LIGHT_COLOR = YELLOW DEGREES = TAU/360 BASELINE_YPOS = -2.5 OBSERVER_POINT = np.array([0,BASELINE_YPOS,0]) LAKE0_RADIUS = 1.5 INDICATOR_RADIUS = 0.6 TICK_SIZE = 0.5 LIGHTHOUSE_HEIGHT = 0.5 LAKE_COLOR = BLUE LAKE_OPACITY = 0.15 LAKE_STROKE_WIDTH = 5.0 LAKE_STROKE_COLOR = BLUE TEX_SCALE = 0.8 DOT_COLOR = BLUE LIGHT_MAX_INT = 1 LIGHT_SCALE = 2.5 LIGHT_CUTOFF = 1 RIGHT_ANGLE_SIZE = 0.3 inverse_power_law = lambda maxint,scale,cutoff,exponent: \ (lambda r: maxint * (cutoff/(r/scale+cutoff))**exponent) inverse_quadratic = lambda maxint,scale,cutoff: inverse_power_law(maxint,scale,cutoff,2) A = np.array([5.,-3.,0.]) B = np.array([-5.,3.,0.]) C = np.array([-5.,-3.,0.]) xA = A[0] yA = A[1] xB = B[0] yB = B[1] xC = C[0] yC = C[1] # find the coords of the altitude point H # as the solution of a certain LSE prelim_matrix = np.array([[yA - yB, xB - xA], [xA - xB, yA - yB]]) # sic prelim_vector = np.array([xB * yA - xA * yB, xC * (xA - xB) + yC * (yA - yB)]) H2 = np.linalg.solve(prelim_matrix,prelim_vector) H = np.append(H2, 0.) class AngleUpdater(ContinualAnimation): def __init__(self, angle_arc, spotlight, **kwargs): self.angle_arc = angle_arc self.spotlight = spotlight ContinualAnimation.__init__(self, self.angle_arc, **kwargs) def update_mobject(self, dt): new_arc = self.angle_arc.copy().set_bound_angles( start = self.spotlight.start_angle(), stop = self.spotlight.stop_angle() ) new_arc.init_points() new_arc.move_arc_center_to(self.spotlight.get_source_point()) self.angle_arc.set_points(new_arc.get_points()) self.angle_arc.add_tip(tip_length = ARC_TIP_LENGTH, at_start = True, at_end = True) class LightIndicator(VMobject): CONFIG = { "radius": 0.5, "intensity": 0, "opacity_for_unit_intensity": 1, "precision": 3, "show_reading": True, "measurement_point": ORIGIN, "light_source": None } def init_points(self): self.background = Circle(color=BLACK, radius = self.radius) self.background.set_fill(opacity=1.0) self.foreground = Circle(color=self.color, radius = self.radius) self.foreground.set_stroke(color=INDICATOR_STROKE_COLOR,width=INDICATOR_STROKE_WIDTH) self.add(self.background, self.foreground) self.reading = DecimalNumber(self.intensity,num_decimal_places = self.precision) self.reading.set_fill(color=INDICATOR_TEXT_COLOR) self.reading.move_to(self.get_center()) if self.show_reading: self.add(self.reading) def set_intensity(self, new_int): self.intensity = new_int new_opacity = min(1, new_int * self.opacity_for_unit_intensity) self.foreground.set_fill(opacity=new_opacity) ChangeDecimalToValue(self.reading, new_int).update(1) return self def get_measurement_point(self): if self.measurement_point != None: return self.measurement_point else: return self.get_center() def measured_intensity(self): distance = get_norm(self.get_measurement_point() - self.light_source.get_source_point()) intensity = self.light_source.opacity_function(distance) / self.opacity_for_unit_intensity return intensity def update_mobjects(self): if self.light_source == None: print("Indicator cannot update, reason: no light source found") self.set_intensity(self.measured_intensity()) class UpdateLightIndicator(AnimationGroup): def __init__(self, indicator, intensity, **kwargs): if not isinstance(indicator,LightIndicator): raise Exception("This transform applies only to LightIndicator") target_foreground = indicator.copy().set_intensity(intensity).foreground change_opacity = Transform( indicator.foreground, target_foreground ) changing_decimal = ChangeDecimalToValue(indicator.reading, intensity) AnimationGroup.__init__(self, changing_decimal, change_opacity, **kwargs) self.mobject = indicator class ContinualLightIndicatorUpdate(ContinualAnimation): def update_mobject(self,dt): self.mobject.update_mobjects() def copy_func(f): """Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)""" g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__) g = functools.update_wrapper(g, f) return g class ScaleLightSources(Transform): def __init__(self, light_sources_mob, factor, about_point = None, **kwargs): if about_point == None: about_point = light_sources_mob.get_center() ls_target = light_sources_mob.copy() for submob in ls_target: if type(submob) == LightSource: new_sp = submob.source_point.copy() # a mob new_sp.scale(factor,about_point = about_point) submob.move_source_to(new_sp.get_location()) # ambient_of = copy_func(submob.ambient_light.opacity_function) # new_of = lambda r: ambient_of(r / factor) # submob.ambient_light.change_opacity_function(new_of) # spotlight_of = copy_func(submob.ambient_light.opacity_function) # new_of = lambda r: spotlight_of(r / factor) # submob.spotlight.change_opacity_function(new_of) new_r = factor * submob.radius submob.set_radius(new_r) new_r = factor * submob.ambient_light.radius submob.ambient_light.radius = new_r new_r = factor * submob.spotlight.radius submob.spotlight.radius = new_r submob.ambient_light.scale_about_point(factor, new_sp.get_center()) submob.spotlight.scale_about_point(factor, new_sp.get_center()) Transform.__init__(self,light_sources_mob,ls_target,**kwargs) class IntroScene(PiCreatureScene): CONFIG = { "rect_height" : 0.2, "duration" : 0.5, "eq_spacing" : 6 * MED_LARGE_BUFF } def construct(self): randy = self.get_primary_pi_creature() randy.scale(0.7).to_corner(DOWN+RIGHT) self.build_up_euler_sum() self.build_up_sum_on_number_line() self.show_pi_answer() self.other_pi_formulas() self.refocus_on_euler_sum() def build_up_euler_sum(self): self.euler_sum = OldTex( "1", "+", "{1 \\over 4}", "+", "{1 \\over 9}", "+", "{1 \\over 16}", "+", "{1 \\over 25}", "+", "\\cdots", "=", arg_separator = " \\, " ) self.euler_sum.to_edge(UP) self.euler_sum.shift(2*LEFT) terms = [1./n**2 for n in range(1,6)] partial_results_values = np.cumsum(terms) self.play( FadeIn(self.euler_sum[0], run_time = self.duration) ) equals_sign = self.euler_sum.get_part_by_tex("=") self.partial_sum_decimal = DecimalNumber(partial_results_values[1], num_decimal_places = 2) self.partial_sum_decimal.next_to(equals_sign, RIGHT) for i in range(4): FadeIn(self.partial_sum_decimal, run_time = self.duration) if i == 0: self.play( FadeIn(self.euler_sum[1], run_time = self.duration), FadeIn(self.euler_sum[2], run_time = self.duration), FadeIn(equals_sign, run_time = self.duration), FadeIn(self.partial_sum_decimal, run_time = self.duration) ) else: self.play( FadeIn(self.euler_sum[2*i+1], run_time = self.duration), FadeIn(self.euler_sum[2*i+2], run_time = self.duration), ChangeDecimalToValue( self.partial_sum_decimal, partial_results_values[i+1], run_time = self.duration, num_decimal_places = 6, show_ellipsis = True, position_update_func = lambda m: m.next_to(equals_sign, RIGHT) ) ) self.wait() self.q_marks = OldTexText("???").set_color(LIGHT_COLOR) self.q_marks.move_to(self.partial_sum_decimal) self.play( FadeIn(self.euler_sum[-3], run_time = self.duration), # + FadeIn(self.euler_sum[-2], run_time = self.duration), # ... ReplacementTransform(self.partial_sum_decimal, self.q_marks) ) self.wait() def build_up_sum_on_number_line(self): self.number_line = NumberLine( x_min = 0, color = WHITE, number_at_center = 1, stroke_width = 1, numbers_with_elongated_ticks = [0,1,2,3], numbers_to_show = np.arange(0,5), unit_size = 5, tick_frequency = 0.2, line_to_number_buff = MED_LARGE_BUFF ).shift(LEFT) self.number_line_labels = self.number_line.get_number_mobjects() self.play( FadeIn(self.number_line), FadeIn(self.number_line_labels) ) self.wait() # create slabs for series terms max_n1 = 10 max_n2 = 100 terms = [0] + [1./(n**2) for n in range(1, max_n2 + 1)] series_terms = np.cumsum(terms) lines = VGroup() self.rects = VGroup() slab_colors = [YELLOW, BLUE] * (max_n2 / 2) for t1, t2, color in zip(series_terms, series_terms[1:], slab_colors): line = Line(*list(map(self.number_line.number_to_point, [t1, t2]))) rect = Rectangle() rect.stroke_width = 0 rect.fill_opacity = 1 rect.set_color(color) rect.stretch_to_fit_height( self.rect_height, ) rect.stretch_to_fit_width(0.5 * line.get_width()) rect.move_to(line) self.rects.add(rect) lines.add(line) #self.rects.set_colors_by_radial_gradient(ORIGIN, 5, YELLOW, BLUE) self.little_euler_terms = VGroup() for i in range(1,7): if i == 1: term = OldTex("1", fill_color = slab_colors[i-1]) else: term = OldTex("{1\over " + str(i**2) + "}", fill_color = slab_colors[i-1]) term.scale(0.4) self.little_euler_terms.add(term) for i in range(5): self.play( GrowFromPoint(self.rects[i], self.euler_sum[2*i].get_center(), run_time = 1) ) term = self.little_euler_terms.submobjects[i] term.next_to(self.rects[i], UP) self.play(FadeIn(term)) self.ellipsis = OldTex("\cdots") self.ellipsis.scale(0.4) for i in range(5, max_n1): if i == 5: self.ellipsis.next_to(self.rects[i+3], UP) self.play( FadeIn(self.ellipsis), GrowFromPoint(self.rects[i], self.euler_sum[10].get_center(), run_time = 0.5) ) else: self.play( GrowFromPoint(self.rects[i], self.euler_sum[10].get_center(), run_time = 0.5) ) for i in range(max_n1, max_n2): self.play( GrowFromPoint(self.rects[i], self.euler_sum[10].get_center(), run_time = 0.01) ) self.wait() PI = TAU/2 P = self.q_marks.get_center() + 0.5 * DOWN + 0.5 * LEFT Q = self.rects[-1].get_center() + 0.2 * UP self.arrow = CurvedArrow(P, Q, angle = TAU/12, color = YELLOW ) self.play(FadeIn(self.arrow)) self.wait() def show_pi_answer(self): self.pi_answer = OldTex("{\\pi^2 \\over 6}").set_color(YELLOW) self.pi_answer.move_to(self.partial_sum_decimal) self.pi_answer.next_to(self.euler_sum[-1], RIGHT, buff = 1, submobject_to_align = self.pi_answer[-2]) self.play(ReplacementTransform(self.q_marks, self.pi_answer)) self.wait() def other_pi_formulas(self): self.play( FadeOut(self.rects), FadeOut(self.number_line_labels), FadeOut(self.number_line), FadeOut(self.little_euler_terms), FadeOut(self.ellipsis), FadeOut(self.arrow) ) self.leibniz_sum = OldTex( "1-{1\\over 3}+{1\\over 5}-{1\\over 7}+{1\\over 9}-\\cdots", "=", "\quad\,\,{\\pi \\over 4}", arg_separator = " \\, ") self.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} \\cdots", "=", "\quad\,\, {\\pi \\over 2}", arg_separator = " \\, ") self.leibniz_sum.next_to(self.euler_sum.get_part_by_tex("="), DOWN, buff = 2, submobject_to_align = self.leibniz_sum.get_part_by_tex("=") ) self.wallis_product.next_to(self.leibniz_sum.get_part_by_tex("="), DOWN, buff = 2, submobject_to_align = self.wallis_product.get_part_by_tex("=") ) self.play( Write(self.leibniz_sum) ) self.play( Write(self.wallis_product) ) def refocus_on_euler_sum(self): self.euler_sum.add(self.pi_answer) self.play( FadeOut(self.leibniz_sum), FadeOut(self.wallis_product), ApplyMethod(self.euler_sum.shift, ORIGIN + 2*UP - self.euler_sum.get_center()) ) # focus on pi squared pi_squared = self.euler_sum.get_part_by_tex("\\pi")[-3] self.play( WiggleOutThenIn(pi_squared, scale_value = 4, angle = 0.003 * TAU, run_time = 2 ) ) # Morty thinks of a circle q_circle = Circle( stroke_color = YELLOW, fill_color = YELLOW, fill_opacity = 0.25, radius = 0.5, stroke_width = 3.0 ) q_mark = OldTex("?") q_mark.next_to(q_circle) thought = Group(q_circle, q_mark) q_mark.set_height(0.6 * q_circle.get_height()) self.look_at(pi_squared) self.pi_creature_thinks(thought,target_mode = "confused", bubble_config = { "height" : 2.5, "width" : 5 }) self.look_at(pi_squared) self.wait() class FirstLighthouseScene(PiCreatureScene): def construct(self): self.remove(self.get_primary_pi_creature()) self.show_lighthouses_on_number_line() def show_lighthouses_on_number_line(self): self.number_line = NumberLine( x_min = 0, color = WHITE, number_at_center = 1.6, stroke_width = 1, numbers_with_elongated_ticks = list(range(1,5)), numbers_to_show = list(range(1,5)), unit_size = 2, tick_frequency = 0.2, line_to_number_buff = LARGE_BUFF, label_direction = UP, ) self.number_line.label_direction = DOWN self.number_line_labels = self.number_line.get_number_mobjects() self.add(self.number_line,self.number_line_labels) self.wait() origin_point = self.number_line.number_to_point(0) self.default_pi_creature_class = Randolph randy = self.get_primary_pi_creature() randy.scale(0.5) randy.flip() right_pupil = randy.pupils[1] randy.next_to(origin_point, LEFT, buff = 0, submobject_to_align = right_pupil) light_indicator = LightIndicator(radius = INDICATOR_RADIUS, opacity_for_unit_intensity = OPACITY_FOR_UNIT_INTENSITY, color = LIGHT_COLOR) light_indicator.reading.scale(0.8) bubble = ThoughtBubble(direction = RIGHT, width = 2.5, height = 3.5) bubble.next_to(randy,LEFT+UP) bubble.add_content(light_indicator) self.wait() self.play( randy.change, "wave_2", ShowCreation(bubble), FadeIn(light_indicator) ) light_sources = [] euler_sum_above = OldTex("1", "+", "{1\over 4}", "+", "{1\over 9}", "+", "{1\over 16}", "+", "{1\over 25}", "+", "{1\over 36}") for (i,term) in zip(list(range(len(euler_sum_above))),euler_sum_above): #horizontal alignment with tick marks term.next_to(self.number_line.number_to_point(0.5*i+1),UP,buff = 2) # vertical alignment with light indicator old_y = term.get_center()[1] new_y = light_indicator.get_center()[1] term.shift([0,new_y - old_y,0]) for i in range(1,NUM_CONES+1): light_source = LightSource( opacity_function = inverse_quadratic(1,AMBIENT_SCALE,1), num_levels = NUM_LEVELS, radius = AMBIENT_RADIUS, ) point = self.number_line.number_to_point(i) light_source.move_source_to(point) light_sources.append(light_source) self.wait() for ls in light_sources: self.add_foreground_mobject(ls.lighthouse) light_indicator.set_intensity(0) intensities = np.cumsum(np.array([1./n**2 for n in range(1,NUM_CONES+1)])) opacities = intensities * light_indicator.opacity_for_unit_intensity self.remove_foreground_mobjects(light_indicator) # slowly switch on visible light cones and increment indicator for (i,light_source) in zip(list(range(NUM_VISIBLE_CONES)),light_sources[:NUM_VISIBLE_CONES]): indicator_start_time = 1.0 * (i+1) * SWITCH_ON_RUN_TIME/light_source.radius * self.number_line.unit_size indicator_stop_time = indicator_start_time + INDICATOR_UPDATE_TIME indicator_rate_func = squish_rate_func( smooth,indicator_start_time,indicator_stop_time) self.play( SwitchOn(light_source.ambient_light), FadeIn(euler_sum_above[2*i], run_time = SWITCH_ON_RUN_TIME, rate_func = indicator_rate_func), FadeIn(euler_sum_above[2*i - 1], run_time = SWITCH_ON_RUN_TIME, rate_func = indicator_rate_func), # this last line *technically* fades in the last term, but it is off-screen ChangeDecimalToValue(light_indicator.reading,intensities[i], rate_func = indicator_rate_func, run_time = SWITCH_ON_RUN_TIME), ApplyMethod(light_indicator.foreground.set_fill,None,opacities[i], rate_func = indicator_rate_func, run_time = SWITCH_ON_RUN_TIME) ) if i == 0: self.wait() # move a copy out of the thought bubble for comparison light_indicator_copy = light_indicator.copy() old_y = light_indicator_copy.get_center()[1] new_y = self.number_line.get_center()[1] self.play( light_indicator_copy.shift,[0, new_y - old_y,0] ) self.wait() self.wait() # quickly switch on off-screen light cones and increment indicator for (i,light_source) in zip(list(range(NUM_VISIBLE_CONES,NUM_CONES)),light_sources[NUM_VISIBLE_CONES:NUM_CONES]): indicator_start_time = 0.5 * (i+1) * FAST_SWITCH_ON_RUN_TIME/light_source.radius * self.number_line.unit_size indicator_stop_time = indicator_start_time + FAST_INDICATOR_UPDATE_TIME indicator_rate_func = squish_rate_func(#smooth, 0.8, 0.9) smooth,indicator_start_time,indicator_stop_time) self.play( SwitchOn(light_source.ambient_light, run_time = FAST_SWITCH_ON_RUN_TIME), ChangeDecimalToValue(light_indicator.reading,intensities[i-1], rate_func = indicator_rate_func, run_time = FAST_SWITCH_ON_RUN_TIME), ApplyMethod(light_indicator.foreground.set_fill,None,opacities[i-1]) ) # show limit value in light indicator and an equals sign limit_reading = OldTex("{\pi^2 \over 6}") limit_reading.move_to(light_indicator.reading) equals_sign = OldTex("=") equals_sign.next_to(randy, UP) old_y = equals_sign.get_center()[1] new_y = euler_sum_above.get_center()[1] equals_sign.shift([0,new_y - old_y,0]) self.play( FadeOut(light_indicator.reading), FadeIn(limit_reading), FadeIn(equals_sign), ) self.wait() class SingleLighthouseScene(PiCreatureScene): def construct(self): self.setup_elements() self.setup_angle() # spotlight and angle msmt change when screen rotates self.rotate_screen() #self.morph_lighthouse_into_sun() def setup_elements(self): self.remove(self.get_primary_pi_creature()) SCREEN_SIZE = 3.0 DISTANCE_FROM_LIGHTHOUSE = 10.0 source_point = [-DISTANCE_FROM_LIGHTHOUSE/2,0,0] observer_point = [DISTANCE_FROM_LIGHTHOUSE/2,0,0] # Light source self.light_source = LightSource( opacity_function = inverse_quadratic(1,SPOTLIGHT_SCALE,1), num_levels = NUM_LEVELS, radius = 10, max_opacity_ambient = AMBIENT_FULL, max_opacity_spotlight = SPOTLIGHT_FULL, ) self.light_source.move_source_to(source_point) # Pi Creature morty = self.get_primary_pi_creature() morty.scale(0.5) morty.move_to(observer_point) morty.shift(2*OUT) self.add_foreground_mobject(morty) self.add(self.light_source.lighthouse) self.play( SwitchOn(self.light_source.ambient_light) ) # Screen self.screen = Rectangle( width = 0.06, height = 2, mark_paths_closed = True, fill_color = WHITE, fill_opacity = 1.0, stroke_width = 0.0 ) self.screen.rotate(-TAU/6) self.screen.next_to(morty,LEFT) self.light_source.set_screen(self.screen) # Animations self.play(FadeIn(self.screen)) #self.light_source.set_max_opacity_spotlight(0.001) #self.play(SwitchOn(self.light_source.spotlight)) self.wait() # just calling .dim_ambient via ApplyMethod does not work, why? dimmed_ambient_light = self.light_source.ambient_light.deepcopy() dimmed_ambient_light.dimming(AMBIENT_DIMMED) self.light_source.update_shadow() self.play( FadeIn(self.light_source.shadow), ) self.add_foreground_mobject(self.light_source.shadow) self.add_foreground_mobject(morty) self.play( self.light_source.dim_ambient, #Transform(self.light_source.ambient_light,dimmed_ambient_light), #self.light_source.set_max_opacity_spotlight,1.0, ) self.play( FadeIn(self.light_source.spotlight) ) self.screen_tracker = ScreenTracker(self.light_source) self.add(self.screen_tracker) self.wait() def setup_angle(self): self.wait() pointing_screen_at_source = Rotate(self.screen,TAU/6) self.play(pointing_screen_at_source) # angle msmt (arc) arc_angle = self.light_source.spotlight.opening_angle() # draw arc arrows to show the opening angle self.angle_arc = Arc(radius = 5, start_angle = self.light_source.spotlight.start_angle(), angle = self.light_source.spotlight.opening_angle(), tip_length = ARC_TIP_LENGTH) #angle_arc.add_tip(at_start = True, at_end = True) self.angle_arc.move_arc_center_to(self.light_source.get_source_point()) # angle msmt (decimal number) self.angle_indicator = DecimalNumber(arc_angle / DEGREES, num_decimal_places = 0, unit = "^\\circ", fill_opacity = 1.0, fill_color = WHITE) self.angle_indicator.next_to(self.angle_arc,RIGHT) angle_update_func = lambda x: self.light_source.spotlight.opening_angle() / DEGREES self.angle_indicator.add_updater( lambda d: d.set_value(angle_update_func()) ) self.add(self.angle_indicator) ca2 = AngleUpdater(self.angle_arc, self.light_source.spotlight) self.add(ca2) self.play( ShowCreation(self.angle_arc), ShowCreation(self.angle_indicator) ) self.wait() def rotate_screen(self): self.play(Rotate(self.light_source.spotlight.screen, TAU/8)) self.play(Rotate(self.light_source.spotlight.screen, -TAU/4)) self.play(Rotate(self.light_source.spotlight.screen, TAU/8)) self.wait() self.play(Rotate(self.light_source.spotlight.screen, -TAU/4)) self.wait() self.play(Rotate(self.light_source.spotlight.screen, TAU/4)) ### The following is supposed to morph the scene into the Earth scene, ### but it doesn't work class MorphIntoSunScene(PiCreatureScene): def construct(self): self.setup_elements() self.morph_lighthouse_into_sun() def setup_elements(self): self.remove(self.get_primary_pi_creature()) SCREEN_SIZE = 3.0 DISTANCE_FROM_LIGHTHOUSE = 10.0 source_point = [-DISTANCE_FROM_LIGHTHOUSE/2,0,0] observer_point = [DISTANCE_FROM_LIGHTHOUSE/2,0,0] # Light source self.light_source = LightSource( opacity_function = inverse_quadratic(1,SPOTLIGHT_SCALE,1), num_levels = NUM_LEVELS, radius = 10, max_opacity_ambient = AMBIENT_FULL, max_opacity_spotlight = SPOTLIGHT_FULL, ) self.light_source.move_source_to(source_point) # Pi Creature morty = self.get_primary_pi_creature() morty.scale(0.5) morty.move_to(observer_point) morty.shift(2*OUT) self.add_foreground_mobject(morty) self.add(self.light_source.lighthouse,self.light_source.ambient_light) # Screen self.screen = Rectangle( width = 0.06, height = 2, mark_paths_closed = True, fill_color = WHITE, fill_opacity = 1.0, stroke_width = 0.0 ) self.screen.next_to(morty,LEFT) self.light_source.set_screen(self.screen) self.add(self.screen,self.light_source.shadow) self.add_foreground_mobject(self.light_source.shadow) self.add_foreground_mobject(morty) self.light_source.dim_ambient self.add(self.light_source.spotlight) self.screen_tracker = ScreenTracker(self.light_source) self.add(self.screen_tracker) self.wait() def morph_lighthouse_into_sun(self): sun_position = np.array([-100,0,0]) # Why does none of this change the opacity function??? self.sun = self.light_source.copy() self.sun.change_spotlight_opacity_function(lambda r: 0.1) # self.sun.spotlight.opacity_function = lambda r: 0.1 # for submob in self.sun.spotlight.submobjects: # submob.set_fill(opacity = 0.1) #self.sun.move_source_to(sun_position) #self.sun.set_radius(120) self.sun.spotlight.init_points() self.wait() self.play( Transform(self.light_source,self.sun) ) self.wait() class EarthScene(Scene): def construct(self): SCREEN_THICKNESS = 10 self.screen_height = 2.0 self.brightness_rect_height = 1.0 # screen self.screen = VMobject(stroke_color = WHITE, stroke_width = SCREEN_THICKNESS) self.screen.set_points_as_corners([ [0,-self.screen_height/2,0], [0,self.screen_height/2,0] ]) # Earth earth_center_x = 2 earth_center = [earth_center_x,0,0] earth_radius = 3 earth = Circle(radius = earth_radius) earth.add(self.screen) earth.move_to(earth_center) #self.remove(self.screen_tracker) theta0 = 70 * DEGREES dtheta = 10 * DEGREES theta1 = theta0 + dtheta theta = (theta0 + theta1)/2 self.add_foreground_mobject(self.screen) # background Earth background_earth = SVGMobject( file_name = "earth", width = 2 * earth_radius, fill_color = BLUE, ) background_earth.move_to(earth_center) # Morty morty = Mortimer().scale(0.5).next_to(self.screen, RIGHT, buff = 1.5) self.add_foreground_mobject(morty) # Light source (far-away Sun) sun_position = [-100,0,0] self.sun = LightSource( opacity_function = lambda r : 0.5, max_opacity_ambient = 0, max_opacity_spotlight = 0.5, num_levels = NUM_LEVELS, radius = 150, screen = self.screen ) self.sun.move_source_to(sun_position) # Add elements to scene self.add(self.sun,self.screen) self.bring_to_back(self.sun.shadow) screen_tracker = ScreenTracker(self.sun) self.add(screen_tracker) self.wait() self.play( FadeIn(earth), FadeIn(background_earth) ) self.add_foreground_mobject(earth) self.add_foreground_mobject(self.screen) # move screen onto Earth screen_on_earth = self.screen.deepcopy() screen_on_earth.rotate(-theta) screen_on_earth.scale(0.3) screen_on_earth.move_to(np.array([ earth_center_x - earth_radius * np.cos(theta), earth_radius * np.sin(theta), 0])) polar_morty = morty.copy().scale(0.5).next_to(screen_on_earth,DOWN,buff = 0.5) polar_morty.set_color(BLUE_C) self.play( Transform(self.screen, screen_on_earth), Transform(morty,polar_morty) ) self.wait() tropical_morty = polar_morty.copy() tropical_morty.move_to(np.array([0,0,0])) tropical_morty.set_color(RED) morty.target = tropical_morty # move screen to equator self.play( Rotate(earth, theta0 + dtheta/2,run_time = 3), MoveToTarget(morty, path_arc = 70*DEGREES, run_time = 3), ) class ScreenShapingScene(ThreeDScene): # TODO: Morph from Earth Scene into this scene def construct(self): #self.force_skipping() self.setup_elements() self.deform_screen() self.create_brightness_rect() self.slant_screen() self.unslant_screen() self.left_shift_screen_while_showing_light_indicator() self.add_distance_arrow() self.right_shift_screen_while_showing_light_indicator_and_distance_arrow() self.left_shift_again() #self.revert_to_original_skipping_status() self.morph_into_3d() self.prove_inverse_square_law() def setup_elements(self): SCREEN_THICKNESS = 10 self.screen_height = 1.0 self.brightness_rect_height = 1.0 # screen self.screen = Line([3,-self.screen_height/2,0],[3,self.screen_height/2,0], path_arc = 0, num_arc_anchors = 10) # light source self.light_source = LightSource( opacity_function = inverse_quadratic(1,5,1), num_levels = NUM_LEVELS, radius = 10, max_opacity = 0.2 #screen = self.screen ) self.light_source.set_max_opacity_spotlight(0.2) self.light_source.set_screen(self.screen) self.light_source.move_source_to([-5,0,0]) # abbreviations self.ambient_light = self.light_source.ambient_light self.spotlight = self.light_source.spotlight self.lighthouse = self.light_source.lighthouse #self.add_foreground_mobject(self.light_source.shadow) # Morty self.morty = Mortimer().scale(0.3).next_to(self.screen, RIGHT, buff = 0.5) # Add everything to the scene self.add(self.lighthouse) self.wait() self.play(FadeIn(self.screen)) self.wait() self.add_foreground_mobject(self.screen) self.add_foreground_mobject(self.morty) self.play(SwitchOn(self.ambient_light)) self.play( SwitchOn(self.spotlight), self.light_source.dim_ambient ) screen_tracker = ScreenTracker(self.light_source) self.add(screen_tracker) self.wait() def deform_screen(self): self.wait() self.play(ApplyMethod(self.screen.set_path_arc, 45 * DEGREES)) self.play(ApplyMethod(self.screen.set_path_arc, -90 * DEGREES)) self.play(ApplyMethod(self.screen.set_path_arc, 0)) def create_brightness_rect(self): # in preparation for the slanting, create a rectangle that shows the brightness # a rect a zero width overlaying the screen # so we can morph it into the brightness rect above brightness_rect0 = Rectangle(width = 0, height = self.screen_height).move_to(self.screen.get_center()) self.add_foreground_mobject(brightness_rect0) self.brightness_rect = Rectangle(width = self.brightness_rect_height, height = self.brightness_rect_height, fill_color = YELLOW, fill_opacity = 0.5) self.brightness_rect.next_to(self.screen, UP, buff = 1) self.play( ReplacementTransform(brightness_rect0,self.brightness_rect) ) self.unslanted_screen = self.screen.deepcopy() self.unslanted_brightness_rect = self.brightness_rect.copy() # for unslanting the screen later def slant_screen(self): SLANTING_AMOUNT = 0.1 lower_screen_point, upper_screen_point = self.screen.get_start_and_end() lower_slanted_screen_point = interpolate( lower_screen_point, self.spotlight.get_source_point(), SLANTING_AMOUNT ) upper_slanted_screen_point = interpolate( upper_screen_point, self.spotlight.get_source_point(), -SLANTING_AMOUNT ) self.slanted_brightness_rect = self.brightness_rect.copy() self.slanted_brightness_rect.width *= 2 self.slanted_brightness_rect.init_points() self.slanted_brightness_rect.set_fill(opacity = 0.25) self.slanted_screen = Line(lower_slanted_screen_point,upper_slanted_screen_point, path_arc = 0, num_arc_anchors = 10) self.slanted_brightness_rect.move_to(self.brightness_rect.get_center()) self.play( Transform(self.screen,self.slanted_screen), Transform(self.brightness_rect,self.slanted_brightness_rect), ) def unslant_screen(self): self.wait() self.play( Transform(self.screen,self.unslanted_screen), Transform(self.brightness_rect,self.unslanted_brightness_rect), ) def left_shift_screen_while_showing_light_indicator(self): # Scene 5: constant screen size, changing opening angle OPACITY_FOR_UNIT_INTENSITY = 1 # let's use an actual light indicator instead of just rects self.indicator_intensity = 0.25 indicator_height = 1.25 * self.screen_height self.indicator = LightIndicator(radius = indicator_height/2, opacity_for_unit_intensity = OPACITY_FOR_UNIT_INTENSITY, color = LIGHT_COLOR, precision = 2) self.indicator.set_intensity(self.indicator_intensity) self.indicator.move_to(self.brightness_rect.get_center()) self.play( FadeOut(self.brightness_rect), FadeIn(self.indicator) ) # Here some digits of the indicator disappear... self.add_foreground_mobject(self.indicator.reading) self.unit_indicator_intensity = 1.0 # intensity at distance 1 # (where we are about to move to) self.left_shift = (self.screen.get_center()[0] - self.spotlight.get_source_point()[0])/2 self.play( self.screen.shift,[-self.left_shift,0,0], self.morty.shift,[-self.left_shift,0,0], self.indicator.shift,[-self.left_shift,0,0], self.indicator.set_intensity,self.unit_indicator_intensity, ) def add_distance_arrow(self): # distance arrow (length 1) left_x = self.spotlight.get_source_point()[0] right_x = self.screen.get_center()[0] arrow_y = -2 arrow1 = Arrow([left_x,arrow_y,0],[right_x,arrow_y,0]) arrow2 = Arrow([right_x,arrow_y,0],[left_x,arrow_y,0]) arrow1.set_fill(color = WHITE) arrow2.set_fill(color = WHITE) distance_decimal = Integer(1).next_to(arrow1,DOWN) self.arrow = VGroup(arrow1, arrow2,distance_decimal) self.add(self.arrow) # distance arrow (length 2) # will be morphed into self.distance_to_source = right_x - left_x new_right_x = left_x + 2 * self.distance_to_source new_arrow1 = Arrow([left_x,arrow_y,0],[new_right_x,arrow_y,0]) new_arrow2 = Arrow([new_right_x,arrow_y,0],[left_x,arrow_y,0]) new_arrow1.set_fill(color = WHITE) new_arrow2.set_fill(color = WHITE) new_distance_decimal = Integer(2).next_to(new_arrow1,DOWN) self.new_arrow = VGroup(new_arrow1, new_arrow2, new_distance_decimal) # don't add it yet def right_shift_screen_while_showing_light_indicator_and_distance_arrow(self): self.wait() self.play( ReplacementTransform(self.arrow,self.new_arrow), ApplyMethod(self.screen.shift,[self.distance_to_source,0,0]), ApplyMethod(self.indicator.shift,[self.left_shift,0,0]), ApplyMethod(self.indicator.set_intensity,self.indicator_intensity), # this should trigger ChangingDecimal, but it doesn't # maybe bc it's an anim within an anim? ApplyMethod(self.morty.shift,[self.distance_to_source,0,0]), ) def left_shift_again(self): self.wait() self.play( ReplacementTransform(self.new_arrow,self.arrow), ApplyMethod(self.screen.shift,[-self.distance_to_source,0,0]), #ApplyMethod(self.indicator.shift,[-self.left_shift,0,0]), ApplyMethod(self.indicator.set_intensity,self.unit_indicator_intensity), ApplyMethod(self.morty.shift,[-self.distance_to_source,0,0]), ) def morph_into_3d(self): self.play(FadeOut(self.morty)) axes = ThreeDAxes() self.add(axes) phi0 = self.camera.get_phi() # default is 0 degs theta0 = self.camera.get_theta() # default is -90 degs distance0 = self.camera.get_distance() phi1 = 60 * DEGREES # angle from zenith (0 to 180) theta1 = -135 * DEGREES # azimuth (0 to 360) distance1 = distance0 target_point = self.camera.get_spherical_coords(phi1, theta1, distance1) dphi = phi1 - phi0 dtheta = theta1 - theta0 camera_target_point = target_point # self.camera.get_spherical_coords(45 * DEGREES, -60 * DEGREES) projection_direction = self.camera.spherical_coords_to_point(phi1,theta1, 1) new_screen0 = Rectangle(height = self.screen_height, width = 0.1, stroke_color = RED, fill_color = RED, fill_opacity = 1) new_screen0.rotate(TAU/4,axis = DOWN) new_screen0.move_to(self.screen.get_center()) self.add(new_screen0) self.remove(self.screen) self.light_source.set_screen(new_screen0) self.light_source.set_camera(self.camera) new_screen = Rectangle(height = self.screen_height, width = self.screen_height, stroke_color = RED, fill_color = RED, fill_opacity = 1) new_screen.rotate(TAU/4,axis = DOWN) new_screen.move_to(self.screen.get_center()) self.add_foreground_mobject(self.ambient_light) self.add_foreground_mobject(self.spotlight) self.add_foreground_mobject(self.light_source.shadow) self.play( ApplyMethod(self.camera.rotation_mobject.move_to, camera_target_point), ) self.remove(self.spotlight) self.play(Transform(new_screen0,new_screen)) self.wait() self.unit_screen = new_screen0 # better name def prove_inverse_square_law(self): def orientate(mob): mob.move_to(self.unit_screen) mob.rotate(TAU/4, axis = LEFT) mob.rotate(TAU/4, axis = OUT) mob.rotate(TAU/2, axis = LEFT) return mob unit_screen_copy = self.unit_screen.copy() fourfold_screen = self.unit_screen.copy() fourfold_screen.scale(2,about_point = self.light_source.get_source_point()) self.remove(self.spotlight) reading1 = OldTex("1") orientate(reading1) self.play(FadeIn(reading1)) self.wait() self.play(FadeOut(reading1)) self.play( Transform(self.unit_screen, fourfold_screen) ) reading21 = OldTex("{1\over 4}").scale(0.8) orientate(reading21) reading22 = reading21.deepcopy() reading23 = reading21.deepcopy() reading24 = reading21.deepcopy() reading21.shift(0.5*OUT + 0.5*UP) reading22.shift(0.5*OUT + 0.5*DOWN) reading23.shift(0.5*IN + 0.5*UP) reading24.shift(0.5*IN + 0.5*DOWN) corners = fourfold_screen.get_anchors() midpoint1 = (corners[0] + corners[1])/2 midpoint2 = (corners[1] + corners[2])/2 midpoint3 = (corners[2] + corners[3])/2 midpoint4 = (corners[3] + corners[0])/2 midline1 = Line(midpoint1, midpoint3) midline2 = Line(midpoint2, midpoint4) self.play( ShowCreation(midline1), ShowCreation(midline2) ) self.play( FadeIn(reading21), FadeIn(reading22), FadeIn(reading23), FadeIn(reading24), ) self.wait() self.play( FadeOut(reading21), FadeOut(reading22), FadeOut(reading23), FadeOut(reading24), FadeOut(midline1), FadeOut(midline2) ) ninefold_screen = unit_screen_copy.copy() ninefold_screen.scale(3,about_point = self.light_source.get_source_point()) self.play( Transform(self.unit_screen, ninefold_screen) ) reading31 = OldTex("{1\over 9}").scale(0.8) orientate(reading31) reading32 = reading31.deepcopy() reading33 = reading31.deepcopy() reading34 = reading31.deepcopy() reading35 = reading31.deepcopy() reading36 = reading31.deepcopy() reading37 = reading31.deepcopy() reading38 = reading31.deepcopy() reading39 = reading31.deepcopy() reading31.shift(IN + UP) reading32.shift(IN) reading33.shift(IN + DOWN) reading34.shift(UP) reading35.shift(ORIGIN) reading36.shift(DOWN) reading37.shift(OUT + UP) reading38.shift(OUT) reading39.shift(OUT + DOWN) corners = ninefold_screen.get_anchors() midpoint11 = (2*corners[0] + corners[1])/3 midpoint12 = (corners[0] + 2*corners[1])/3 midpoint21 = (2*corners[1] + corners[2])/3 midpoint22 = (corners[1] + 2*corners[2])/3 midpoint31 = (2*corners[2] + corners[3])/3 midpoint32 = (corners[2] + 2*corners[3])/3 midpoint41 = (2*corners[3] + corners[0])/3 midpoint42 = (corners[3] + 2*corners[0])/3 midline11 = Line(midpoint11, midpoint32) midline12 = Line(midpoint12, midpoint31) midline21 = Line(midpoint21, midpoint42) midline22 = Line(midpoint22, midpoint41) self.play( ShowCreation(midline11), ShowCreation(midline12), ShowCreation(midline21), ShowCreation(midline22), ) self.play( FadeIn(reading31), FadeIn(reading32), FadeIn(reading33), FadeIn(reading34), FadeIn(reading35), FadeIn(reading36), FadeIn(reading37), FadeIn(reading38), FadeIn(reading39), ) class IndicatorScalingScene(Scene): def construct(self): unit_intensity = 0.6 indicator1 = LightIndicator(show_reading = False, color = LIGHT_COLOR) indicator1.set_intensity(unit_intensity) reading1 = OldTex("1") reading1.move_to(indicator1) indicator2 = LightIndicator(show_reading = False, color = LIGHT_COLOR) indicator2.shift(2*RIGHT) indicator2.set_intensity(unit_intensity/4) reading2 = OldTex("{1\over 4}").scale(0.8) reading2.move_to(indicator2) indicator3 = LightIndicator(show_reading = False, color = LIGHT_COLOR) indicator3.shift(4*RIGHT) indicator3.set_intensity(unit_intensity/9) reading3 = OldTex("{1\over 9}").scale(0.8) reading3.move_to(indicator3) self.play(FadeIn(indicator1)) self.play(FadeIn(reading1)) self.wait() self.play(FadeOut(reading1)) self.play(Transform(indicator1, indicator2)) self.play(FadeIn(reading2)) self.wait() self.play(FadeOut(reading2)) self.play(Transform(indicator1, indicator3)) self.play(FadeIn(reading3)) self.wait() class BackToEulerSumScene(PiCreatureScene): def construct(self): self.remove(self.get_primary_pi_creature()) NUM_CONES = 7 NUM_VISIBLE_CONES = 6 INDICATOR_RADIUS = 0.5 OPACITY_FOR_UNIT_INTENSITY = 1.0 self.number_line = NumberLine( x_min = 0, color = WHITE, number_at_center = 1.6, stroke_width = 1, numbers_with_elongated_ticks = list(range(1,5)), numbers_to_show = list(range(1,5)), unit_size = 2, tick_frequency = 0.2, line_to_number_buff = LARGE_BUFF, label_direction = UP, ) self.number_line.label_direction = DOWN #self.number_line.shift(3*UP) self.number_line_labels = self.number_line.get_number_mobjects() self.add(self.number_line,self.number_line_labels) self.wait() origin_point = self.number_line.number_to_point(0) self.default_pi_creature_class = Randolph randy = self.get_primary_pi_creature() randy.scale(0.5) randy.flip() right_pupil = randy.pupils[1] randy.next_to(origin_point, LEFT, buff = 0, submobject_to_align = right_pupil) randy_copy = randy.copy() randy_copy.target = randy.copy().shift(DOWN) bubble = ThoughtBubble(direction = RIGHT, width = 4, height = 3, file_name = "Bubbles_thought.svg") bubble.next_to(randy,LEFT+UP) bubble.set_fill(color = BLACK, opacity = 1) self.play( randy.change, "wave_2", ShowCreation(bubble), ) euler_sum = OldTex("1", "+", "{1\over 4}", "+", "{1\over 9}", "+", "{1\over 16}", "+", "{1\over 25}", "+", "\cdots", " ") # the last entry is a dummy element which makes looping easier # used just for putting the fractions into the light indicators intensities = np.array([1./(n+1)**2 for n in range(NUM_CONES)]) opacities = intensities * OPACITY_FOR_UNIT_INTENSITY # repeat: # fade in lighthouse # switch on / fade in ambient light # show creation / write light indicator # move indicator onto origin # while morphing and dimming # move indicator into thought bubble # while indicators already inside shift to the back # and while term appears in the series below point = self.number_line.number_to_point(1) v = point - self.number_line.number_to_point(0) light_source = LightSource() light_source.move_source_to(point) #light_source.ambient_light.move_source_to(point) #light_source.lighthouse.move_to(point) self.play(FadeIn(light_source.lighthouse)) self.play(SwitchOn(light_source.ambient_light)) # create an indicator that will move along the number line indicator = LightIndicator(color = LIGHT_COLOR, radius = INDICATOR_RADIUS, opacity_for_unit_intensity = OPACITY_FOR_UNIT_INTENSITY, show_reading = False ) indicator_reading = euler_sum[0] indicator_reading.set_height(0.5 * indicator.get_height()) indicator_reading.move_to(indicator.get_center()) indicator.add(indicator_reading) indicator.tex_reading = indicator_reading # the TeX reading is too bright at full intensity indicator.tex_reading.set_fill(color = BLACK) indicator.foreground.set_fill(None,opacities[0]) indicator.move_to(point) indicator.set_intensity(intensities[0]) self.play(FadeIn(indicator)) self.add_foreground_mobject(indicator) collection_point = np.array([-6.,2.,0.]) left_shift = 0.2*LEFT collected_indicators = Mobject() for i in range(2, NUM_VISIBLE_CONES + 1): previous_point = self.number_line.number_to_point(i - 1) point = self.number_line.number_to_point(i) v = point - previous_point #print v # Create and position the target indicator (next on number line). indicator_target = indicator.deepcopy() indicator_target.shift(v) # Here we make a copy that will move into the thought bubble. bubble_indicator = indicator.deepcopy() # And its target bubble_indicator_target = bubble_indicator.deepcopy() bubble_indicator_target.set_intensity(intensities[i - 2]) # give the target the appropriate reading euler_sum[2*i-4].move_to(bubble_indicator_target) bubble_indicator_target.remove(bubble_indicator_target.tex_reading) bubble_indicator_target.tex_reading = euler_sum[2*i-4].copy() bubble_indicator_target.add(bubble_indicator_target.tex_reading) # center it in the indicator if bubble_indicator_target.tex_reading.get_tex() != "1": bubble_indicator_target.tex_reading.set_height(0.8*indicator.get_height()) # the target is less bright, possibly switch to a white text color if bubble_indicator_target.intensity < 0.7: bubble_indicator.tex_reading.set_fill(color = WHITE) # position the target in the thought bubble bubble_indicator_target.move_to(collection_point) self.add_foreground_mobject(bubble_indicator) self.wait() self.play( Transform(bubble_indicator,bubble_indicator_target), collected_indicators.shift,left_shift, ) collected_indicators.add(bubble_indicator) new_light = light_source.deepcopy() w = new_light.get_source_point() new_light.move_source_to(w + (i-2)*v) w2 = new_light.get_source_point() self.add(new_light.lighthouse) self.play( Transform(indicator,indicator_target), new_light.lighthouse.shift,v, ) new_light.move_source_to(w + (i-1)*v) new_light.lighthouse.move_to(w + (i-1)*v) self.play(SwitchOn(new_light.ambient_light), ) # quickly switch on off-screen light cones for i in range(NUM_VISIBLE_CONES,NUM_CONES): indicator_start_time = 0.5 * (i+1) * FAST_SWITCH_ON_RUN_TIME/light_source.ambient_light.radius * self.number_line.unit_size indicator_stop_time = indicator_start_time + FAST_INDICATOR_UPDATE_TIME indicator_rate_func = squish_rate_func(#smooth, 0.8, 0.9) smooth,indicator_start_time,indicator_stop_time) ls = LightSource() point = point = self.number_line.number_to_point(i) ls.move_source_to(point) self.play( SwitchOn(ls.ambient_light, run_time = FAST_SWITCH_ON_RUN_TIME), ) # and morph indicator stack into limit value sum_indicator = LightIndicator(color = LIGHT_COLOR, radius = INDICATOR_RADIUS, opacity_for_unit_intensity = OPACITY_FOR_UNIT_INTENSITY, show_reading = False ) sum_indicator.set_intensity(intensities[0] * np.pi**2/6) sum_indicator_reading = OldTex("{\pi^2 \over 6}") sum_indicator_reading.set_fill(color = BLACK) sum_indicator_reading.set_height(0.8 * sum_indicator.get_height()) sum_indicator.add(sum_indicator_reading) sum_indicator.move_to(collection_point) self.play( FadeOut(collected_indicators), FadeIn(sum_indicator) ) self.wait() class TwoLightSourcesScene(PiCreatureScene): def construct(self): MAX_OPACITY = 0.4 INDICATOR_RADIUS = 0.6 OPACITY_FOR_UNIT_INTENSITY = 0.5 morty = self.get_primary_pi_creature() morty.scale(0.3).flip() right_pupil = morty.pupils[1] morty.next_to(C, LEFT, buff = 0, submobject_to_align = right_pupil) horizontal = VMobject(stroke_width = 1) horizontal.set_points_as_corners([C,A]) vertical = VMobject(stroke_width = 1) vertical.set_points_as_corners([C,B]) self.play( ShowCreation(horizontal), ShowCreation(vertical) ) indicator = LightIndicator(color = LIGHT_COLOR, radius = INDICATOR_RADIUS, opacity_for_unit_intensity = OPACITY_FOR_UNIT_INTENSITY, show_reading = True, precision = 2 ) indicator.next_to(morty,LEFT) self.play( Write(indicator) ) ls1 = LightSource(radius = 20, num_levels = 50) ls2 = ls1.deepcopy() ls1.move_source_to(A) ls2.move_source_to(B) self.play( FadeIn(ls1.lighthouse), FadeIn(ls2.lighthouse), SwitchOn(ls1.ambient_light), SwitchOn(ls2.ambient_light) ) distance1 = get_norm(C - ls1.get_source_point()) intensity = ls1.ambient_light.opacity_function(distance1) / indicator.opacity_for_unit_intensity distance2 = get_norm(C - ls2.get_source_point()) intensity += ls2.ambient_light.opacity_function(distance2) / indicator.opacity_for_unit_intensity self.play( UpdateLightIndicator(indicator,intensity) ) self.wait() ls3 = ls1.deepcopy() ls3.move_to(np.array([6,3.5,0])) new_indicator = indicator.copy() new_indicator.light_source = ls3 new_indicator.measurement_point = C self.add(new_indicator) self.play( indicator.shift, 2 * UP ) #intensity = intensity_for_light_source(ls3) self.play( SwitchOff(ls1.ambient_light), #FadeOut(ls1.lighthouse), SwitchOff(ls2.ambient_light), #FadeOut(ls2.lighthouse), UpdateLightIndicator(new_indicator,0.0) ) # create a *continual* animation for the replacement source updater = ContinualLightIndicatorUpdate(new_indicator) self.add(updater) self.play( SwitchOn(ls3.ambient_light), FadeIn(ls3.lighthouse), ) self.wait() # move the light source around # TODO: moving along a path arc location = np.array([-3,-2.,0.]) self.play(ls3.move_source_to,location) location = np.array([6.,1.,0.]) self.play(ls3.move_source_to,location) location = np.array([5.,2.,0.]) self.play(ls3.move_source_to,location) closer_location = interpolate(location, C, 0.5) self.play(ls3.move_source_to,closer_location) self.play(ls3.move_source_to,location) # maybe move in a circle around C using a loop? self.play(ls3.move_source_to,H) # draw lines to complete the geometric picture # and label the lengths line_a = VMobject() line_a.set_points_as_corners([B,C]) line_b = VMobject() line_b.set_points_as_corners([A,C]) line_c = VMobject() line_c.set_points_as_corners([A,B]) line_h = VMobject() line_h.set_points_as_corners([H,C]) label_a = OldTex("a") label_a.next_to(line_a, LEFT, buff = 0.5) label_b = OldTex("b") label_b.next_to(line_b, DOWN, buff = 0.5) label_h = OldTex("h") label_h.next_to(line_h.get_center(), RIGHT, buff = 0.5) self.play( ShowCreation(line_a), Write(label_a) ) self.play( ShowCreation(line_b), Write(label_b) ) self.play( ShowCreation(line_c), ) self.play( ShowCreation(line_h), Write(label_h) ) # state the IPT theorem_location = np.array([3.,2.,0.]) theorem = OldTex("{1\over a^2} + {1\over b^2} = {1\over h^2}") theorem_name = OldTexText("Inverse Pythagorean Theorem") buffer = 1.2 theorem_box = Rectangle(width = buffer*theorem.get_width(), height = buffer*theorem.get_height()) theorem.move_to(theorem_location) theorem_box.move_to(theorem_location) theorem_name.next_to(theorem_box,UP) self.play( Write(theorem), ) self.play( ShowCreation(theorem_box), Write(theorem_name), ) class IPTScene1(PiCreatureScene): def construct(self): show_detail = True SCREEN_SCALE = 0.1 SCREEN_THICKNESS = 0.2 # use the following for the zoomed inset if show_detail: self.camera.frame_shape = (0.02 * FRAME_HEIGHT, 0.02 * FRAME_WIDTH) self.camera.frame_center = C SCREEN_SCALE = 0.01 SCREEN_THICKNESS = 0.02 morty = self.get_primary_pi_creature() self.remove(morty) morty.scale(0.3).flip() right_pupil = morty.pupils[1] morty.next_to(C, LEFT, buff = 0, submobject_to_align = right_pupil) if not show_detail: self.add_foreground_mobject(morty) stroke_width = 6 line_a = Line(B,C,stroke_width = stroke_width) line_b = Line(A,C,stroke_width = stroke_width) line_c = Line(A,B,stroke_width = stroke_width) line_h = Line(C,H,stroke_width = stroke_width) length_a = line_a.get_length() length_b = line_b.get_length() length_c = line_c.get_length() length_h = line_h.get_length() label_a = OldTex("a") label_a.next_to(line_a, LEFT, buff = 0.5) label_b = OldTex("b") label_b.next_to(line_b, DOWN, buff = 0.5) label_h = OldTex("h") label_h.next_to(line_h.get_center(), RIGHT, buff = 0.5) self.add_foreground_mobject(line_a) self.add_foreground_mobject(line_b) self.add_foreground_mobject(line_c) self.add_foreground_mobject(line_h) self.add_foreground_mobject(label_a) self.add_foreground_mobject(label_b) self.add_foreground_mobject(label_h) if not show_detail: self.add_foreground_mobject(morty) ls1 = LightSource(radius = 10) ls1.move_source_to(B) self.add(ls1.lighthouse) if not show_detail: self.play( SwitchOn(ls1.ambient_light) ) self.wait() # adding the first screen screen_width_a = SCREEN_SCALE * length_a screen_width_b = SCREEN_SCALE * length_b screen_width_ap = screen_width_a * length_a / length_c screen_width_bp = screen_width_b * length_b / length_c screen_width_c = SCREEN_SCALE * length_c screen_thickness_a = SCREEN_THICKNESS screen_thickness_b = SCREEN_THICKNESS screen1 = Rectangle(width = screen_width_b, height = screen_thickness_b, stroke_width = 0, fill_opacity = 1.0) screen1.move_to(C + screen_width_b/2 * RIGHT + screen_thickness_b/2 * DOWN) if not show_detail: self.add_foreground_mobject(morty) self.play( FadeIn(screen1) ) self.add_foreground_mobject(screen1) ls1.set_screen(screen1) screen_tracker = ScreenTracker(ls1) self.add(screen_tracker) #self.add(ls1.shadow) if not show_detail: self.play( SwitchOn(ls1.ambient_light) ) self.play( SwitchOn(ls1.spotlight), SwitchOff(ls1.ambient_light) ) # now move the light source to the height point # while shifting scaling the screen screen1p = screen1.deepcopy() screen1pp = screen1.deepcopy() #self.add(screen1p) angle = np.arccos(length_b / length_c) screen1p.stretch_to_fit_width(screen_width_bp) screen1p.move_to(C + (screen_width_b - screen_width_bp/2) * RIGHT + SCREEN_THICKNESS/2 * DOWN) screen1p.rotate(-angle, about_point = C + screen_width_b * RIGHT) self.play( ls1.move_source_to,H, Transform(screen1,screen1p) ) # add and move the second light source and screen ls2 = ls1.deepcopy() ls2.move_source_to(A) screen2 = Rectangle(width = screen_width_a, height = screen_thickness_a, stroke_width = 0, fill_opacity = 1.0) screen2.rotate(-TAU/4) screen2.move_to(C + screen_width_a/2 * UP + screen_thickness_a/2 * LEFT) self.play( FadeIn(screen2) ) self.add_foreground_mobject(screen2) if not show_detail: self.add_foreground_mobject(morty) # the same scene adding sequence as before ls2.set_screen(screen2) screen_tracker2 = ScreenTracker(ls2) self.add(screen_tracker2) if not show_detail: self.play( SwitchOn(ls2.ambient_light) ) self.wait() self.play( SwitchOn(ls2.spotlight), SwitchOff(ls2.ambient_light) ) # now move the light source to the height point # while shifting scaling the screen screen2p = screen2.deepcopy() screen2pp = screen2.deepcopy() angle = np.arccos(length_a / length_c) screen2p.stretch_to_fit_height(screen_width_ap) screen2p.move_to(C + (screen_width_a - screen_width_ap/2) * UP + screen_thickness_a/2 * LEFT) screen2p.rotate(angle, about_point = C + screen_width_a * UP) # we can reuse the translation vector # screen2p.shift(vector) self.play( ls2.move_source_to,H, SwitchOff(ls1.ambient_light), Transform(screen2,screen2p) ) # now transform both screens back self.play( Transform(screen1, screen1pp), Transform(screen2, screen2pp), ) class IPTScene2(Scene): def construct(self): intensity1 = 0.3 intensity2 = 0.2 formula_scale = 01.2 indy_radius = 1 indy1 = LightIndicator(color = LIGHT_COLOR, show_reading = False, radius = indy_radius) indy1.set_intensity(intensity1) reading1 = OldTex("{1\over a^2}").scale(formula_scale).move_to(indy1) indy1.add(reading1) indy2 = LightIndicator(color = LIGHT_COLOR, show_reading = False, radius = indy_radius) indy2.set_intensity(intensity2) reading2 = OldTex("{1\over b^2}").scale(formula_scale).move_to(indy2) indy2.add(reading2) indy3 = LightIndicator(color = LIGHT_COLOR, show_reading = False, radius = indy_radius) indy3.set_intensity(intensity1 + intensity2) reading3 = OldTex("{1\over h^2}").scale(formula_scale).move_to(indy3) indy3.add(reading3) plus_sign = OldTex("+").scale(formula_scale) equals_sign = OldTex("=").scale(formula_scale) plus_sign.next_to(indy1, RIGHT) indy2.next_to(plus_sign, RIGHT) equals_sign.next_to(indy2, RIGHT) indy3.next_to(equals_sign, RIGHT) formula = VGroup( indy1, plus_sign, indy2, equals_sign, indy3 ) formula.move_to(ORIGIN) self.play(FadeIn(indy1)) self.play(FadeIn(plus_sign), FadeIn(indy2)) self.play(FadeIn(equals_sign), FadeIn(indy3)) buffer = 1.5 box = Rectangle(width = formula.get_width() * buffer, height = formula.get_height() * buffer) box.move_to(formula) text = OldTexText("Inverse Pythagorean Theorem").scale(formula_scale) text.next_to(box,UP) self.play(ShowCreation(box),Write(text)) class InscribedAngleScene(ThreeDScene): def construct(self): BASELINE_YPOS = -2.5 OBSERVER_POINT = [0,BASELINE_YPOS,0] LAKE0_RADIUS = 1.5 INDICATOR_RADIUS = 0.6 TICK_SIZE = 0.5 LIGHTHOUSE_HEIGHT = 0.3 LAKE_COLOR = BLUE LAKE_OPACITY = 0.15 LAKE_STROKE_WIDTH = 5.0 LAKE_STROKE_COLOR = BLUE TEX_SCALE = 0.8 DOT_COLOR = BLUE LIGHT_MAX_INT = 1 LIGHT_SCALE = 5 LIGHT_CUTOFF = 1 self.cumulated_zoom_factor = 1 def zoom_out_scene(factor): phi0 = self.camera.get_phi() # default is 0 degs theta0 = self.camera.get_theta() # default is -90 degs distance0 = self.camera.get_distance() distance1 = 2 * distance0 camera_target_point = self.camera.get_spherical_coords(phi0, theta0, distance1) self.play( ApplyMethod(self.camera.rotation_mobject.move_to, camera_target_point), self.zoomable_mobs.shift, self.obs_dot.get_center(), self.unzoomable_mobs.scale,2,{"about_point" : ORIGIN}, ) self.cumulated_zoom_factor *= factor def shift_scene(v): self.play( self.zoomable_mobs.shift,v, self.unzoomable_mobs.shift,v ) self.force_skipping() self.zoomable_mobs = VMobject() self.unzoomable_mobs = VMobject() baseline = VMobject() baseline.set_points_as_corners([[-8,BASELINE_YPOS,0],[8,BASELINE_YPOS,0]]) baseline.set_stroke(width = 0) # in case it gets accidentally added to the scene self.zoomable_mobs.add(baseline) # prob not necessary self.obs_dot = Dot(OBSERVER_POINT, fill_color = DOT_COLOR) self.ls0_dot = Dot(OBSERVER_POINT + 2 * LAKE0_RADIUS * UP, fill_color = WHITE) self.unzoomable_mobs.add(self.obs_dot) #, self.ls0_dot) # lake lake0 = Circle(radius = LAKE0_RADIUS, stroke_width = 0, fill_color = LAKE_COLOR, fill_opacity = LAKE_OPACITY ) lake0.move_to(OBSERVER_POINT + LAKE0_RADIUS * UP) self.zoomable_mobs.add(lake0) # Morty and indicator morty = Mortimer().scale(0.3) morty.next_to(OBSERVER_POINT,DOWN) indicator = LightIndicator(precision = 2, radius = INDICATOR_RADIUS, show_reading = False, color = LIGHT_COLOR ) indicator.next_to(morty,LEFT) self.unzoomable_mobs.add(morty, indicator) # first lighthouse original_op_func = inverse_quadratic(LIGHT_MAX_INT,AMBIENT_SCALE,LIGHT_CUTOFF) ls0 = LightSource(opacity_function = original_op_func, num_levels = NUM_LEVELS) ls0.move_source_to(OBSERVER_POINT + LAKE0_RADIUS * 2 * UP) self.zoomable_mobs.add(ls0, ls0.lighthouse, ls0.ambient_light) self.add(lake0,morty,self.obs_dot,self.ls0_dot, ls0.lighthouse) self.wait() # shore arcs arc_left = Arc(-TAU/2, radius = LAKE0_RADIUS, start_angle = -TAU/4, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR ) arc_left.move_arc_center_to(OBSERVER_POINT + LAKE0_RADIUS * UP) one_left = OldTex("1", color = LAKE_COLOR).scale(TEX_SCALE) one_left.next_to(arc_left,LEFT) arc_right = Arc(TAU/2, radius = LAKE0_RADIUS, start_angle = -TAU/4, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR ) arc_right.move_arc_center_to(OBSERVER_POINT + LAKE0_RADIUS * UP) one_right = OldTex("1", color = LAKE_COLOR).scale(TEX_SCALE) one_right.next_to(arc_right,RIGHT) self.play( ShowCreation(arc_left), Write(one_left), ShowCreation(arc_right), Write(one_right), ) self.play( SwitchOn(ls0.ambient_light), lake0.set_stroke,{"color": LAKE_STROKE_COLOR, "width" : LAKE_STROKE_WIDTH}, ) self.play(FadeIn(indicator)) self.play( indicator.set_intensity,0.5 ) # diameter diameter = DoubleArrow(OBSERVER_POINT, ls0.get_source_point(), buff = 0, color = WHITE, ) diameter_text = OldTex("d").scale(TEX_SCALE) diameter_text.next_to(diameter,RIGHT) self.play( ShowCreation(diameter), Write(diameter_text), #FadeOut(self.obs_dot), FadeOut(self.ls0_dot) ) indicator_reading = OldTex("{1\over d^2}").scale(TEX_SCALE) indicator_reading.move_to(indicator) self.unzoomable_mobs.add(indicator_reading) self.play( FadeIn(indicator_reading) ) # replace d with its value new_diameter_text = OldTex("{2\over \pi}").scale(TEX_SCALE) new_diameter_text.color = LAKE_COLOR new_diameter_text.move_to(diameter_text) self.play( Transform(diameter_text,new_diameter_text) ) # insert into indicator reading new_reading = OldTex("{\pi^2 \over 4}").scale(TEX_SCALE) new_reading.move_to(indicator) self.play( Transform(indicator_reading,new_reading) ) self.play( FadeOut(one_left), FadeOut(one_right), FadeOut(diameter_text), FadeOut(arc_left), FadeOut(arc_right) ) def indicator_wiggle(): INDICATOR_WIGGLE_FACTOR = 1.3 self.play( ScaleInPlace(indicator, INDICATOR_WIGGLE_FACTOR, rate_func = wiggle), ScaleInPlace(indicator_reading, INDICATOR_WIGGLE_FACTOR, rate_func = wiggle) ) def angle_for_index(i,step): return -TAU/4 + TAU/2**step * (i + 0.5) def position_for_index(i, step, scaled_down = False): theta = angle_for_index(i,step) radial_vector = np.array([np.cos(theta),np.sin(theta),0]) position = self.lake_center + self.lake_radius * radial_vector if scaled_down: return position.scale_about_point(self.obs_dot.get_center(),0.5) else: return position def split_light_source(i, step, show_steps = True, run_time = 1): ls_new_loc1 = position_for_index(i,step + 1) ls_new_loc2 = position_for_index(i + 2**step,step + 1) hyp = VMobject() hyp1 = Line(self.lake_center,ls_new_loc1) hyp2 = Line(self.lake_center,ls_new_loc2) hyp.add(hyp2,hyp1) self.new_hypotenuses.append(hyp) if show_steps == True: self.play( ShowCreation(hyp, run_time = run_time) ) leg1 = Line(self.obs_dot.get_center(),ls_new_loc1) leg2 = Line(self.obs_dot.get_center(),ls_new_loc2) self.new_legs_1.append(leg1) self.new_legs_2.append(leg2) if show_steps == True: self.play( ShowCreation(leg1, run_time = run_time), ShowCreation(leg2, run_time = run_time), ) ls1 = self.light_sources_array[i] ls2 = ls1.copy() self.add(ls2) self.additional_light_sources.append(ls2) # check if the light sources are on screen ls_old_loc = np.array(ls1.get_source_point()) onscreen_old = np.all(np.abs(ls_old_loc[:2]) < 10 ** 2**step) onscreen_1 = np.all(np.abs(ls_new_loc1[:2][:2]) < 10 ** 2**step) onscreen_2 = np.all(np.abs(ls_new_loc2[:2]) < 10 ** 2**step) show_animation = (onscreen_old or onscreen_1 or onscreen_2) if show_animation: print("animating (", i, ",", step, ")") self.play( ApplyMethod(ls1.move_source_to,ls_new_loc1, run_time = run_time), ApplyMethod(ls2.move_source_to,ls_new_loc2, run_time = run_time), ) else: ls1.move_source_to(ls_new_loc1) ls2.move_source_to(ls_new_loc1) def construction_step(n, show_steps = True, run_time = 1, simultaneous_splitting = False): # we assume that the scene contains: # an inner lake, self.inner_lake # an outer lake, self.outer_lake # light sources, self.light_sources # legs from the observer point to each light source # self.legs # altitudes from the observer point to the # locations of the light sources in the previous step # self.altitudes # hypotenuses connecting antipodal light sources # self.hypotenuses # these are mobjects! # first, fade out all of the hypotenuses and altitudes if show_steps == True: self.zoomable_mobs.remove(self.hypotenuses, self.altitudes, self.inner_lake) self.play( FadeOut(self.hypotenuses), FadeOut(self.altitudes), FadeOut(self.inner_lake) ) else: self.zoomable_mobs.remove(self.inner_lake) self.play( FadeOut(self.inner_lake) ) # create a new, outer lake self.lake_center = self.obs_dot.get_center() + self.lake_radius * UP new_outer_lake = Circle(radius = self.lake_radius, stroke_width = LAKE_STROKE_WIDTH, fill_color = LAKE_COLOR, fill_opacity = LAKE_OPACITY, stroke_color = LAKE_STROKE_COLOR ) new_outer_lake.move_to(self.lake_center) if show_steps == True: self.play( FadeIn(new_outer_lake, run_time = run_time), FadeIn(self.ls0_dot) ) else: self.play( FadeIn(new_outer_lake, run_time = run_time), ) self.wait() self.inner_lake = self.outer_lake self.outer_lake = new_outer_lake self.altitudes = self.legs #self.lake_center = self.outer_lake.get_center() self.additional_light_sources = [] self.new_legs_1 = [] self.new_legs_2 = [] self.new_hypotenuses = [] for i in range(2**n): split_light_source(i, step = n, show_steps = show_steps, run_time = run_time ) # collect the newly created mobs (in arrays) # into the appropriate Mobject containers self.legs = VMobject() for leg in self.new_legs_1: self.legs.add(leg) self.zoomable_mobs.add(leg) for leg in self.new_legs_2: self.legs.add(leg) self.zoomable_mobs.add(leg) for hyp in self.hypotenuses.submobjects: self.zoomable_mobs.remove(hyp) self.hypotenuses = VMobject() for hyp in self.new_hypotenuses: self.hypotenuses.add(hyp) self.zoomable_mobs.add(hyp) for ls in self.additional_light_sources: self.light_sources.add(ls) self.light_sources_array.append(ls) self.zoomable_mobs.add(ls) # update scene self.add( self.light_sources, self.inner_lake, self.outer_lake, ) self.zoomable_mobs.add(self.light_sources, self.inner_lake, self.outer_lake) if show_steps == True: self.add( self.legs, self.hypotenuses, self.altitudes, ) self.zoomable_mobs.add(self.legs, self.hypotenuses, self.altitudes) self.wait() if show_steps == True: self.play(FadeOut(self.ls0_dot)) #self.lake_center = ls0_loc = self.obs_dot.get_center() + self.lake_radius * UP self.lake_radius *= 2 self.lake_center = ls0_loc = ls0.get_source_point() self.inner_lake = VMobject() self.outer_lake = lake0 self.legs = VMobject() self.legs.add(Line(OBSERVER_POINT,self.lake_center)) self.altitudes = VMobject() self.hypotenuses = VMobject() self.light_sources_array = [ls0] self.light_sources = VMobject() self.light_sources.add(ls0) self.lake_radius = 2 * LAKE0_RADIUS # don't ask... self.zoomable_mobs.add(self.inner_lake, self.outer_lake, self.altitudes, self.light_sources) self.add(self.inner_lake, self.outer_lake, self.legs, self.altitudes, self.hypotenuses ) self.play(FadeOut(diameter)) self.additional_light_sources = [] self.new_legs_1 = [] self.new_legs_2 = [] self.new_hypotenuses = [] self.revert_to_original_skipping_status() construction_step(0) indicator_wiggle() self.play(FadeOut(self.ls0_dot)) zoom_out_scene(2) return construction_step(1) indicator_wiggle() self.play(FadeOut(self.ls0_dot)) zoom_out_scene(2) construction_step(2) indicator_wiggle() self.play(FadeOut(self.ls0_dot)) self.revert_to_original_skipping_status() ANGLE_COLOR1 = BLUE_C ANGLE_COLOR2 = GREEN_D for mob in self.mobjects: mob.fade(1.0) for hyp in self.hypotenuses: hyp.set_stroke(width = 0) for alt in self.altitudes: alt.set_stroke(width = 0) for leg in self.legs: leg.set_stroke(width = 0) self.inner_lake.set_stroke(width = 0) self.outer_lake.set_stroke(width = 0) self.wait() inner_lake_center = self.inner_lake.get_center() inner_lake_radius = self.lake_radius * 0.25 inner_ls = VGroup() for i in range(4): theta = -TAU/4 + (i+0.5) * TAU/4 point = inner_lake_center + inner_lake_radius * np.array([np.cos(theta), np.sin(theta),0]) dot = Dot(point, color = LAKE_STROKE_COLOR, radius = 0.3) inner_ls.add(dot) self.add(inner_ls) inner_ls1 = inner_ls.submobjects[0] inner_ls2 = inner_ls.submobjects[1] inner_ls1_center = inner_ls1.get_center() inner_ls2_center = inner_ls2.get_center() outer_lake_center = self.outer_lake.get_center() outer_lake_radius = self.lake_radius * 0.5 outer_ls = VGroup() for i in range(8): theta = -TAU/4 + (i+0.5) * TAU/8 point = outer_lake_center + outer_lake_radius * np.array([np.cos(theta), np.sin(theta),0]) dot = Dot(point, color = LAKE_STROKE_COLOR, radius = 0.3) outer_ls.add(dot) self.add(outer_ls) outer_ls1 = outer_ls.submobjects[0] outer_ls2 = outer_ls.submobjects[1] outer_ls1_center = outer_ls1.get_center() outer_ls2_center = outer_ls2.get_center() self.wait() arc_radius = 2.0 line1 = Line(inner_lake_center, inner_ls1_center, color = WHITE) line2 = Line(inner_lake_center, inner_ls2_center, color = WHITE) #arc_point1 = interpolate(inner_lake_center, inner_ls1_center, 0.2) #arc_point2 = interpolate(inner_lake_center, inner_ls2_center, 0.2) #inner_angle_arc = ArcBetweenPoints(arc_point1, arc_point2, angle = TAU/4) inner_angle_arc = Arc(angle = TAU/4, start_angle = -TAU/8, radius = arc_radius, stroke_color = ANGLE_COLOR1) inner_angle_arc.move_arc_center_to(inner_lake_center) inner_label = OldTex("\\theta", fill_color = ANGLE_COLOR1).scale(3).next_to(inner_angle_arc, LEFT, buff = -0.1) self.play( ShowCreation(line1), ShowCreation(line2), ) self.play( ShowCreation(inner_angle_arc), FadeIn(inner_label) ) self.wait() line3 = Line(outer_lake_center, inner_ls1_center, color = WHITE) line4 = Line(outer_lake_center, inner_ls2_center, color = WHITE) outer_angle_arc = Arc(angle = TAU/8, start_angle = -3*TAU/16, radius = arc_radius, stroke_color = ANGLE_COLOR2) outer_angle_arc.move_arc_center_to(outer_lake_center) outer_label = OldTex("{\\theta \over 2}", color = ANGLE_COLOR2).scale(2.5).move_to(outer_angle_arc) outer_label.shift([-2,-1,0]) self.play( ShowCreation(line3), ShowCreation(line4), ) self.play( ShowCreation(outer_angle_arc), FadeIn(outer_label) ) self.wait() line5 = Line(outer_lake_center, outer_ls1_center, color = WHITE) line6 = Line(outer_lake_center, outer_ls2_center, color = WHITE) self.play( ShowCreation(line5), ShowCreation(line6) ) self.wait() self.play( FadeOut(line1), FadeOut(line2), FadeOut(line3), FadeOut(line4), FadeOut(line5), FadeOut(line6), FadeOut(inner_angle_arc), FadeOut(outer_angle_arc), FadeOut(inner_label), FadeOut(outer_label), ) self.wait() inner_lines = VGroup() inner_arcs = VGroup() for i in range(-2,2): theta = -TAU/4 + (i+0.5)*TAU/4 ls_point = inner_lake_center + inner_lake_radius * np.array([ np.cos(theta), np.sin(theta),0]) line = Line(inner_lake_center, ls_point, color = WHITE) inner_lines.add(line) arc = Arc(angle = TAU/4, start_angle = theta, radius = arc_radius, stroke_color = ANGLE_COLOR1) arc.move_arc_center_to(inner_lake_center) inner_arcs.add(arc) if i == 1: arc.set_stroke(width = 0) for line in inner_lines.submobjects: self.play( ShowCreation(line), ) self.add_foreground_mobject(inner_lines) for arc in inner_arcs.submobjects: self.play( ShowCreation(arc) ) self.wait() outer_lines = VGroup() outer_arcs = VGroup() for i in range(-2,2): theta = -TAU/4 + (i+0.5)*TAU/4 ls_point = inner_lake_center + inner_lake_radius * np.array([ np.cos(theta), np.sin(theta),0]) line = Line(outer_lake_center, ls_point, color = WHITE) outer_lines.add(line) theta = -TAU/4 + (i+0.5)*TAU/8 arc = Arc(angle = TAU/8, start_angle = theta, radius = arc_radius, stroke_color = ANGLE_COLOR2) arc.move_arc_center_to(outer_lake_center) outer_arcs.add(arc) if i == 1: arc.set_stroke(width = 0) for line in outer_lines.submobjects: self.play( ShowCreation(line), ) self.add_foreground_mobject(outer_lines) for arc in outer_arcs.submobjects: self.play( ShowCreation(arc) ) self.wait() self.play( FadeOut(inner_lines), FadeOut(inner_arcs) ) outer_lines2 = VGroup() for i in range(-2,2): theta = -TAU/4 + (i+0.5)*TAU/8 ls_point = outer_lake_center + outer_lake_radius * np.array([ np.cos(theta), np.sin(theta),0]) line = Line(outer_lake_center, ls_point, color = WHITE) outer_lines2.add(line) self.play( ShowCreation(outer_lines2), ) self.wait() outer_lines3 = outer_lines2.copy().rotate(TAU/2, about_point = outer_lake_center) outer_arcs3 = outer_arcs.copy().rotate(TAU/2, about_point = outer_lake_center) self.play( ShowCreation(outer_lines3), ) self.add_foreground_mobject(outer_lines3) for arc in outer_arcs3.submobjects: self.play( ShowCreation(arc) ) last_arc = outer_arcs3.submobjects[0].copy() last_arc.rotate(-TAU/8, about_point = outer_lake_center) last_arc2 = last_arc.copy() last_arc2.rotate(TAU/2, about_point = outer_lake_center) self.play( ShowCreation(last_arc), ShowCreation(last_arc2), ) self.wait() self.play( FadeOut(outer_lines2), FadeOut(outer_lines3), FadeOut(outer_arcs), FadeOut(outer_arcs3), FadeOut(last_arc), FadeOut(last_arc2), ) self.play( FadeOut(inner_ls), FadeOut(outer_ls), ) self.wait() class PondScene(ThreeDScene): def construct(self): BASELINE_YPOS = -2.5 OBSERVER_POINT = np.array([0,BASELINE_YPOS,0]) LAKE0_RADIUS = 1.5 INDICATOR_RADIUS = 0.6 TICK_SIZE = 0.5 LIGHTHOUSE_HEIGHT = 0.5 LAKE_COLOR = BLUE LAKE_OPACITY = 0.15 LAKE_STROKE_WIDTH = 5.0 LAKE_STROKE_COLOR = BLUE TEX_SCALE = 0.8 DOT_COLOR = BLUE LIGHT_MAX_INT = 1 LIGHT_SCALE = 2.5 LIGHT_CUTOFF = 1 RIGHT_ANGLE_SIZE = 0.3 self.cumulated_zoom_factor = 1 STEP_RUN_TIME = 0.5 #self.force_skipping() def right_angle(pointA, pointB, pointC, size = 1): v1 = pointA - pointB v1 = size * v1/get_norm(v1) v2 = pointC - pointB v2 = size * v2/get_norm(v2) P = pointB Q = pointB + v1 R = Q + v2 S = R - v1 angle_sign = VMobject() angle_sign.set_points_as_corners([P,Q,R,S,P]) angle_sign.mark_paths_closed = True angle_sign.set_fill(color = WHITE, opacity = 1) angle_sign.set_stroke(width = 0) return angle_sign def triangle(pointA, pointB, pointC): mob = VMobject() mob.set_points_as_corners([pointA, pointB, pointC, pointA]) mob.mark_paths_closed = True mob.set_fill(color = WHITE, opacity = 0.5) mob.set_stroke(width = 0) return mob def zoom_out_scene(factor): self.remove_foreground_mobject(self.ls0_dot) self.remove(self.ls0_dot) phi0 = self.camera.get_phi() # default is 0 degs theta0 = self.camera.get_theta() # default is -90 degs distance0 = self.camera.get_distance() distance1 = 2 * distance0 camera_target_point = self.camera.get_spherical_coords(phi0, theta0, distance1) self.play( ApplyMethod(self.camera.rotation_mobject.move_to, camera_target_point), self.zoomable_mobs.shift, self.obs_dot.get_center(), self.unzoomable_mobs.scale,2,{"about_point" : ORIGIN}, ) self.cumulated_zoom_factor *= factor # place ls0_dot by hand #old_radius = self.ls0_dot.radius #self.ls0_dot.radius = 2 * old_radius #v = self.ls0_dot.get_center() - self.obs_dot.get_center() #self.ls0_dot.shift(v) #self.ls0_dot.move_to(self.outer_lake.get_center()) self.ls0_dot.scale(2, about_point = ORIGIN) #self.add_foreground_mobject(self.ls0_dot) def shift_scene(v): self.play( self.zoomable_mobs.shift,v, self.unzoomable_mobs.shift,v ) self.zoomable_mobs = VMobject() self.unzoomable_mobs = VMobject() baseline = VMobject() baseline.set_points_as_corners([[-8,BASELINE_YPOS,0],[8,BASELINE_YPOS,0]]) baseline.set_stroke(width = 0) # in case it gets accidentally added to the scene self.zoomable_mobs.add(baseline) # prob not necessary self.obs_dot = Dot(OBSERVER_POINT, fill_color = DOT_COLOR) self.ls0_dot = Dot(OBSERVER_POINT + 2 * LAKE0_RADIUS * UP, fill_color = WHITE) self.unzoomable_mobs.add(self.obs_dot)#, self.ls0_dot) # lake lake0 = Circle(radius = LAKE0_RADIUS, stroke_width = 0, fill_color = LAKE_COLOR, fill_opacity = LAKE_OPACITY ) lake0.move_to(OBSERVER_POINT + LAKE0_RADIUS * UP) self.zoomable_mobs.add(lake0) # Morty and indicator morty = Randolph(color = MAROON_D).scale(0.3) morty.next_to(OBSERVER_POINT,DOWN) indicator = LightIndicator(precision = 2, radius = INDICATOR_RADIUS, show_reading = False, color = LIGHT_COLOR ) indicator.next_to(morty,LEFT) self.unzoomable_mobs.add(morty, indicator) # first lighthouse original_op_func = inverse_quadratic(LIGHT_MAX_INT,LIGHT_SCALE,LIGHT_CUTOFF) ls0 = LightSource(opacity_function = original_op_func, radius = 15.0, num_levels = 15) ls0.lighthouse.set_height(LIGHTHOUSE_HEIGHT) ls0.lighthouse.height = LIGHTHOUSE_HEIGHT ls0.move_source_to(OBSERVER_POINT + LAKE0_RADIUS * 2 * UP) self.zoomable_mobs.add(ls0, ls0.lighthouse, ls0.ambient_light) self.add(lake0,morty,self.obs_dot,self.ls0_dot, ls0.lighthouse) self.add_foreground_mobject(morty) self.add_foreground_mobject(self.obs_dot) self.add_foreground_mobject(self.ls0_dot) self.wait() # shore arcs arc_left = Arc(-TAU/2, radius = LAKE0_RADIUS, start_angle = -TAU/4, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR ) arc_left.move_arc_center_to(OBSERVER_POINT + LAKE0_RADIUS * UP) one_left = OldTex("1", color = LAKE_COLOR).scale(TEX_SCALE) one_left.next_to(arc_left,LEFT) arc_right = Arc(TAU/2, radius = LAKE0_RADIUS, start_angle = -TAU/4, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR ) arc_right.move_arc_center_to(OBSERVER_POINT + LAKE0_RADIUS * UP) one_right = OldTex("1", color = LAKE_COLOR).scale(TEX_SCALE) one_right.next_to(arc_right,RIGHT) self.play( ShowCreation(arc_left), Write(one_left), ShowCreation(arc_right), Write(one_right), ) self.play( SwitchOn(ls0.ambient_light), lake0.set_stroke,{"color": LAKE_STROKE_COLOR, "width" : LAKE_STROKE_WIDTH}, ) self.play(FadeIn(indicator)) self.add_foreground_mobject(indicator) self.play( indicator.set_intensity,0.5 ) diameter_start = interpolate(OBSERVER_POINT,ls0.get_source_point(),0.02) diameter_stop = interpolate(OBSERVER_POINT,ls0.get_source_point(),0.98) # diameter diameter = DoubleArrow(diameter_start, diameter_stop, buff = 0, color = WHITE, ) diameter_text = OldTex("d").scale(TEX_SCALE) diameter_text.next_to(diameter,RIGHT) self.play( ShowCreation(diameter), Write(diameter_text), #FadeOut(self.obs_dot), FadeOut(self.ls0_dot) ) indicator_reading = OldTex("{1\over d^2}").scale(TEX_SCALE) indicator_reading.move_to(indicator) self.unzoomable_mobs.add(indicator_reading) self.play( FadeIn(indicator_reading) ) self.add_foreground_mobject(indicator_reading) # replace d with its value new_diameter_text = OldTex("{2\over \pi}").scale(TEX_SCALE) new_diameter_text.color = LAKE_COLOR new_diameter_text.move_to(diameter_text) self.play( Transform(diameter_text,new_diameter_text) ) # insert into indicator reading new_reading = OldTex("{\pi^2 \over 4}").scale(TEX_SCALE) new_reading.move_to(indicator) self.play( Transform(indicator_reading,new_reading) ) self.wait() self.play( FadeOut(one_left), FadeOut(one_right), FadeOut(diameter_text), FadeOut(arc_left), FadeOut(arc_right) ) def indicator_wiggle(): INDICATOR_WIGGLE_FACTOR = 1.3 self.play( ScaleInPlace(indicator, INDICATOR_WIGGLE_FACTOR, rate_func = wiggle), ScaleInPlace(indicator_reading, INDICATOR_WIGGLE_FACTOR, rate_func = wiggle) ) def angle_for_index(i,step): return -TAU/4 + TAU/2**step * (i + 0.5) def position_for_index(i, step, scaled_down = False): theta = angle_for_index(i,step) radial_vector = np.array([np.cos(theta),np.sin(theta),0]) position = self.lake_center + self.lake_radius * radial_vector if scaled_down: return position.scale_about_point(self.obs_dot.get_center(),0.5) else: return position def split_light_source(i, step, show_steps = True, animate = True, run_time = 1): ls_new_loc1 = position_for_index(i,step + 1) ls_new_loc2 = position_for_index(i + 2**step,step + 1) hyp = VMobject() hyp1 = Line(self.lake_center,ls_new_loc1) hyp2 = Line(self.lake_center,ls_new_loc2) hyp.add(hyp2,hyp1) self.new_hypotenuses.append(hyp) if show_steps == True: self.play( ShowCreation(hyp, run_time = run_time) ) leg1 = Line(self.obs_dot.get_center(),ls_new_loc1) leg2 = Line(self.obs_dot.get_center(),ls_new_loc2) self.new_legs_1.append(leg1) self.new_legs_2.append(leg2) if show_steps == True: self.play( ShowCreation(leg1, run_time = run_time), ShowCreation(leg2, run_time = run_time), ) ls1 = self.light_sources_array[i] ls2 = ls1.copy() if animate == True: self.add(ls2) self.additional_light_sources.append(ls2) # check if the light sources are on screen ls_old_loc = np.array(ls1.get_source_point()) onscreen_old = np.all(np.abs(ls_old_loc[:2]) < 10 * 2**3) onscreen_1 = np.all(np.abs(ls_new_loc1[:2]) < 10 * 2**3) onscreen_2 = np.all(np.abs(ls_new_loc2[:2]) < 10 * 2**3) show_animation = (onscreen_old or onscreen_1 or onscreen_2) if show_animation or animate: print("animating (", i, ",", step, ")") self.play( ApplyMethod(ls1.move_source_to,ls_new_loc1, run_time = run_time), ApplyMethod(ls2.move_source_to,ls_new_loc2, run_time = run_time), ) else: ls1.move_source_to(ls_new_loc1) ls2.move_source_to(ls_new_loc1) def construction_step(n, show_steps = True, run_time = 1, simultaneous_splitting = False): # we assume that the scene contains: # an inner lake, self.inner_lake # an outer lake, self.outer_lake # light sources, self.light_sources # legs from the observer point to each light source # self.legs # altitudes from the observer point to the # locations of the light sources in the previous step # self.altitudes # hypotenuses connecting antipodal light sources # self.hypotenuses # these are mobjects! # first, fade out all of the hypotenuses and altitudes if show_steps == True: self.zoomable_mobs.remove(self.hypotenuses, self.altitudes, self.inner_lake) self.play( FadeOut(self.hypotenuses), FadeOut(self.altitudes), FadeOut(self.inner_lake) ) else: self.zoomable_mobs.remove(self.inner_lake) self.play( FadeOut(self.inner_lake) ) # create a new, outer lake self.lake_center = self.obs_dot.get_center() + self.lake_radius * UP new_outer_lake = Circle(radius = self.lake_radius, stroke_width = LAKE_STROKE_WIDTH, fill_color = LAKE_COLOR, fill_opacity = LAKE_OPACITY, stroke_color = LAKE_STROKE_COLOR ) new_outer_lake.move_to(self.lake_center) if show_steps == True: self.play( FadeIn(new_outer_lake, run_time = run_time), FadeIn(self.ls0_dot) ) else: self.play( FadeIn(new_outer_lake, run_time = run_time), ) self.wait() self.inner_lake = self.outer_lake self.outer_lake = new_outer_lake self.altitudes = self.legs #self.lake_center = self.outer_lake.get_center() self.additional_light_sources = [] self.new_legs_1 = [] self.new_legs_2 = [] self.new_hypotenuses = [] # WE ALWAYS USE THIS CASE BRANCH if simultaneous_splitting == False: for i in range(2**n): split_light_source(i, step = n, show_steps = show_steps, run_time = run_time ) if n == 1 and i == 0: # show again where the right angles are A = self.light_sources[0].get_center() B = self.additional_light_sources[0].get_center() C = self.obs_dot.get_center() triangle1 = triangle( A, C, B ) right_angle1 = right_angle( A, C, B, size = 2 * RIGHT_ANGLE_SIZE ) self.play( FadeIn(triangle1), FadeIn(right_angle1) ) self.wait() self.play( FadeOut(triangle1), FadeOut(right_angle1) ) self.wait() H = self.inner_lake.get_center() + self.lake_radius/2 * RIGHT L = self.outer_lake.get_center() triangle2 = triangle( L, H, C ) right_angle2 = right_angle( L, H, C, size = 2 * RIGHT_ANGLE_SIZE ) self.play( FadeIn(triangle2), FadeIn(right_angle2) ) self.wait() self.play( FadeOut(triangle2), FadeOut(right_angle2) ) self.wait() # WE DON'T USE THIS CASE BRANCH ANYMORE else: # simultaneous splitting old_lake = self.outer_lake.copy() old_ls = self.light_sources.copy() old_ls2 = old_ls.copy() for submob in old_ls2.submobjects: old_ls.add(submob) self.remove(self.outer_lake, self.light_sources) self.add(old_lake, old_ls) for i in range(2**n): split_light_source(i, step = n, show_steps = show_steps, run_time = run_time, animate = False ) self.play( ReplacementTransform(old_ls, self.light_sources, run_time = run_time), ReplacementTransform(old_lake, self.outer_lake, run_time = run_time), ) # collect the newly created mobs (in arrays) # into the appropriate Mobject containers self.legs = VMobject() for leg in self.new_legs_1: self.legs.add(leg) self.zoomable_mobs.add(leg) for leg in self.new_legs_2: self.legs.add(leg) self.zoomable_mobs.add(leg) for hyp in self.hypotenuses.submobjects: self.zoomable_mobs.remove(hyp) self.hypotenuses = VMobject() for hyp in self.new_hypotenuses: self.hypotenuses.add(hyp) self.zoomable_mobs.add(hyp) for ls in self.additional_light_sources: self.light_sources.add(ls) self.light_sources_array.append(ls) self.zoomable_mobs.add(ls) # update scene self.add( self.light_sources, self.inner_lake, self.outer_lake, ) self.zoomable_mobs.add(self.light_sources, self.inner_lake, self.outer_lake) if show_steps == True: self.add( self.legs, self.hypotenuses, self.altitudes, ) self.zoomable_mobs.add(self.legs, self.hypotenuses, self.altitudes) self.wait() if show_steps == True: self.play(FadeOut(self.ls0_dot)) #self.lake_center = ls0_loc = self.obs_dot.get_center() + self.lake_radius * UP self.lake_radius *= 2 self.lake_center = ls0_loc = ls0.get_source_point() self.inner_lake = VMobject() self.outer_lake = lake0 self.legs = VMobject() self.legs.add(Line(OBSERVER_POINT,self.lake_center)) self.altitudes = VMobject() self.hypotenuses = VMobject() self.light_sources_array = [ls0] self.light_sources = VMobject() self.light_sources.add(ls0) self.lake_radius = 2 * LAKE0_RADIUS # don't ask... self.zoomable_mobs.add(self.inner_lake, self.outer_lake, self.altitudes, self.light_sources) self.add(self.inner_lake, self.outer_lake, self.legs, self.altitudes, self.hypotenuses ) self.play(FadeOut(diameter)) self.additional_light_sources = [] self.new_legs_1 = [] self.new_legs_2 = [] self.new_hypotenuses = [] construction_step(0, run_time = STEP_RUN_TIME) my_triangle = triangle( self.light_sources[0].get_source_point(), OBSERVER_POINT, self.light_sources[1].get_source_point() ) angle_sign1 = right_angle( self.light_sources[0].get_source_point(), OBSERVER_POINT, self.light_sources[1].get_source_point(), size = RIGHT_ANGLE_SIZE ) self.play( FadeIn(angle_sign1), FadeIn(my_triangle) ) angle_sign2 = right_angle( self.light_sources[1].get_source_point(), self.lake_center, OBSERVER_POINT, size = RIGHT_ANGLE_SIZE ) self.play( FadeIn(angle_sign2) ) self.wait() self.play( FadeOut(angle_sign1), FadeOut(angle_sign2), FadeOut(my_triangle) ) indicator_wiggle() self.remove(self.ls0_dot) zoom_out_scene(2) construction_step(1, run_time = STEP_RUN_TIME) indicator_wiggle() #self.play(FadeOut(self.ls0_dot)) zoom_out_scene(2) construction_step(2, run_time = STEP_RUN_TIME) indicator_wiggle() self.play(FadeOut(self.ls0_dot)) self.play( FadeOut(self.altitudes), FadeOut(self.hypotenuses), FadeOut(self.legs) ) max_it = 10 scale = 2**(max_it - 5) TEX_SCALE *= scale # for i in range(3,max_it + 1): # construction_step(i, show_steps = False, run_time = 4.0/2**i, # simultaneous_splitting = True) #print "starting simultaneous expansion" # simultaneous expansion of light sources from now on self.play(FadeOut(self.inner_lake)) for n in range(3,max_it + 1): print("working on n = ", n, "...") new_lake = self.outer_lake.copy().scale(2,about_point = self.obs_dot.get_center()) for (i,ls) in enumerate(self.light_sources_array[:2**n]): #print i lsp = ls.copy() self.light_sources.add(lsp) self.add(lsp) self.light_sources_array.append(lsp) new_lake_center = new_lake.get_center() new_lake_radius = 0.5 * new_lake.get_width() self.play(Transform(self.outer_lake,new_lake)) shift_list = [] for i in range(2**n): #print "===========" #print i theta = -TAU/4 + (i + 0.5) * TAU / 2**(n+1) v = np.array([np.cos(theta), np.sin(theta),0]) pos1 = new_lake_center + new_lake_radius * v pos2 = new_lake_center - new_lake_radius * v ls1 = self.light_sources.submobjects[i] ls2 = self.light_sources.submobjects[i+2**n] ls_old_loc = np.array(ls1.get_source_point()) onscreen_old = np.all(np.abs(ls_old_loc[:2]) < 10 * 2**2) onscreen_1 = np.all(np.abs(pos1[:2]) < 10 * 2**2) onscreen_2 = np.all(np.abs(pos2[:2]) < 10 * 2**2) if onscreen_old or onscreen_1: print("anim1 for step", n, "part", i) print("------------------ moving from", ls_old_loc[:2], "to", pos1[:2]) shift_list.append(ApplyMethod(ls1.move_source_to, pos1, run_time = STEP_RUN_TIME)) else: ls1.move_source_to(pos1) if onscreen_old or onscreen_2: print("anim2 for step", n, "part", i) print("------------------ moving from", ls_old_loc[:2], "to", pos2[:2]) shift_list.append(ApplyMethod(ls2.move_source_to, pos2, run_time = STEP_RUN_TIME)) else: ls2.move_source_to(pos2) #print shift_list self.play(*shift_list) print("...done") #self.revert_to_original_skipping_status() # Now create a straight number line and transform into it MAX_N = 7 origin_point = self.obs_dot.get_center() self.number_line = NumberLine( x_min = -MAX_N, x_max = MAX_N + 1, color = WHITE, number_at_center = 0, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR, numbers_with_elongated_ticks = [], numbers_to_show = list(range(-MAX_N,MAX_N + 1)),#,2), unit_size = LAKE0_RADIUS * TAU/4 / 2 * scale, tick_frequency = 1, tick_size = LAKE_STROKE_WIDTH, number_scale_val = 3, line_to_number_buff = LARGE_BUFF, label_direction = UP, ).shift(origin_point - self.number_line.number_to_point(0)) # .shift(scale * 2.5 * DOWN) print("scale ", scale) print("number line at", self.number_line.get_center()) print("should be at", origin_point, "or", OBSERVER_POINT) self.number_line.tick_marks.fade(1) self.number_line_labels = self.number_line.get_number_mobjects() self.wait() origin_point = self.number_line.number_to_point(0) nl_sources = VMobject() pond_sources = VMobject() for i in range(-MAX_N,MAX_N+1): anchor = self.number_line.number_to_point(2*i + 1) ls = self.light_sources_array[i].copy() ls.move_source_to(anchor) nl_sources.add(ls) pond_sources.add(self.light_sources_array[i].copy()) self.add(pond_sources) self.remove(self.light_sources) for ls in self.light_sources_array: self.remove(ls) self.outer_lake.rotate(TAU/8) # open sea open_sea = Rectangle( width = 200 * scale, height = 100 * scale, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR, fill_color = LAKE_COLOR, fill_opacity = LAKE_OPACITY, ).flip().next_to(self.obs_dot.get_center(),UP,buff = 0) self.revert_to_original_skipping_status() self.play( ReplacementTransform(pond_sources,nl_sources), #FadeOut(pond_sources), #FadeIn(nl_sources), ReplacementTransform(self.outer_lake,open_sea), #FadeOut(self.inner_lake) ) self.play(FadeIn(self.number_line)) self.wait() v = 4 * scale * UP self.play( nl_sources.shift,v, morty.shift,v, self.number_line.shift,v, indicator.shift,v, indicator_reading.shift,v, open_sea.shift,v, self.obs_dot.shift,v, ) self.number_line_labels.shift(v) origin_point = self.number_line.number_to_point(0) #self.remove(self.obs_dot) self.play( indicator.move_to, origin_point + scale * UP + 2 * UP, indicator_reading.move_to, origin_point + scale * UP + 2 * UP, FadeOut(open_sea), FadeOut(morty), FadeIn(self.number_line_labels), FadeIn(self.number_line.tick_marks), ) two_sided_sum = OldTex("\dots", "+", "{1\over (-11)^2}",\ "+", "{1\over (-9)^2}", " + ", "{1\over (-7)^2}", " + ", "{1\over (-5)^2}", " + ", \ "{1\over (-3)^2}", " + ", "{1\over (-1)^2}", " + ", "{1\over 1^2}", " + ", \ "{1\over 3^2}", " + ", "{1\over 5^2}", " + ", "{1\over 7^2}", " + ", \ "{1\over 9^2}", " + ", "{1\over 11^2}", " + ", "\dots") nb_symbols = len(two_sided_sum.submobjects) two_sided_sum.scale(TEX_SCALE) for (i,submob) in zip(list(range(nb_symbols)),two_sided_sum.submobjects): submob.next_to(self.number_line.number_to_point(i - 13),DOWN, buff = 2*scale) if (i == 0 or i % 2 == 1 or i == nb_symbols - 1): # non-fractions submob.shift(0.3 * scale * DOWN) self.play(Write(two_sided_sum)) self.wait() for ls in nl_sources.submobjects: if ls.get_source_point()[0] < 0: self.remove_foreground_mobject(ls.ambient_light) self.remove(ls.ambient_light) else: self.add_foreground_mobject(ls.ambient_light) for label in self.number_line_labels.submobjects: if label.get_center()[0] <= 0: self.remove(label) covering_rectangle = Rectangle( width = FRAME_X_RADIUS * scale, height = 2 * FRAME_Y_RADIUS * scale, stroke_width = 0, fill_color = BLACK, fill_opacity = 1, ) covering_rectangle.next_to(ORIGIN, LEFT, buff = 0) #for i in range(10): # self.add_foreground_mobject(nl_sources.submobjects[i]) self.add_foreground_mobject(indicator) self.add_foreground_mobject(indicator_reading) half_indicator_reading = OldTex("{\pi^2 \over 8}").scale(TEX_SCALE) half_indicator_reading.move_to(indicator) central_plus_sign = two_sided_sum[13] self.play( FadeIn(covering_rectangle), Transform(indicator_reading, half_indicator_reading), FadeOut(central_plus_sign) ) equals_sign = OldTex("=").scale(TEX_SCALE) equals_sign.move_to(central_plus_sign) p = 2 * scale * LEFT + central_plus_sign.get_center()[1] * UP self.play( indicator.move_to,p, indicator_reading.move_to,p, FadeIn(equals_sign), ) self.revert_to_original_skipping_status() # show Randy admiring the result randy = Randolph(color = MAROON_D).scale(scale).move_to(2*scale*DOWN+5*scale*LEFT) self.play(FadeIn(randy)) self.play(randy.change,"happy") self.play(randy.change,"hooray") class WaitScene(TeacherStudentsScene): def construct(self): self.teacher_says(OldTex("{1\over 1^2}+{1\over 3^2}+{1\over 5^2}+{1\over 7^2}+\dots = {\pi^2 \over 8}!")) student_q = OldTexText("What about") full_sum = OldTex("{1\over 1^2}+{1\over 2^2}+{1\over 3^2}+{1\over 4^2}+\dots?") full_sum.next_to(student_q,RIGHT) student_q.add(full_sum) self.student_says(student_q, target_mode = "angry") class FinalSumManipulationScene(PiCreatureScene): def construct(self): LAKE_COLOR = BLUE LAKE_OPACITY = 0.15 LAKE_STROKE_WIDTH = 5.0 LAKE_STROKE_COLOR = BLUE TEX_SCALE = 0.8 LIGHT_COLOR2 = RED LIGHT_COLOR3 = BLUE unit_length = 1.5 vertical_spacing = 2.5 * DOWN switch_on_time = 0.2 sum_vertical_spacing = 1.5 randy = self.get_primary_pi_creature() randy.set_color(MAROON_D) randy.color = MAROON_D randy.scale(0.7).flip().to_edge(DOWN + LEFT) self.wait() ls_template = LightSource( radius = 1, num_levels = 10, max_opacity_ambient = 0.5, opacity_function = inverse_quadratic(1,0.75,1) ) odd_range = np.arange(1,9,2) even_range = np.arange(2,16,2) full_range = np.arange(1,8,1) self.number_line1 = NumberLine( x_min = 0, x_max = 11, color = LAKE_STROKE_COLOR, number_at_center = 0, stroke_width = LAKE_STROKE_WIDTH, stroke_color = LAKE_STROKE_COLOR, #numbers_to_show = full_range, number_scale_val = 0.5, numbers_with_elongated_ticks = [], unit_size = unit_length, tick_frequency = 1, line_to_number_buff = MED_SMALL_BUFF, include_tip = True, label_direction = UP, ) self.number_line1.next_to(2.5 * UP + 3 * LEFT, RIGHT, buff = 0.3) self.number_line1.add_numbers() odd_lights = VMobject() for i in odd_range: pos = self.number_line1.number_to_point(i) ls = ls_template.copy() ls.move_source_to(pos) odd_lights.add(ls) self.play( ShowCreation(self.number_line1, run_time = 5), ) self.wait() odd_terms = VMobject() for i in odd_range: if i == 1: term = OldTex("\phantom{+\,\,\,}{1\over " + str(i) + "^2}", fill_color = LIGHT_COLOR, stroke_color = LIGHT_COLOR) else: term = OldTex("+\,\,\, {1\over " + str(i) + "^2}", fill_color = LIGHT_COLOR, stroke_color = LIGHT_COLOR) term.next_to(self.number_line1.number_to_point(i), DOWN, buff = 1.5) odd_terms.add(term) for (ls, term) in zip(odd_lights.submobjects, odd_terms.submobjects): self.play( FadeIn(ls.lighthouse, run_time = switch_on_time), SwitchOn(ls.ambient_light, run_time = switch_on_time), Write(term, run_time = switch_on_time) ) result1 = OldTex("{\pi^2\over 8} =", fill_color = LIGHT_COLOR, stroke_color = LIGHT_COLOR) result1.next_to(self.number_line1, LEFT, buff = 0.5) result1.shift(0.87 * vertical_spacing) self.play(Write(result1)) self.number_line2 = self.number_line1.copy() self.number_line2.numbers_to_show = full_range self.number_line2.shift(2 * vertical_spacing) self.number_line2.add_numbers() full_lights = VMobject() for i in full_range: pos = self.number_line2.number_to_point(i) ls = ls_template.copy() ls.color = LIGHT_COLOR3 ls.move_source_to(pos) full_lights.add(ls) self.play( ShowCreation(self.number_line2, run_time = 5), ) self.wait() full_lighthouses = VMobject() full_ambient_lights = VMobject() for ls in full_lights: full_lighthouses.add(ls.lighthouse) full_ambient_lights.add(ls.ambient_light) self.play( LaggedStartMap(FadeIn, full_lighthouses, lag_ratio = 0.2, run_time = 3), ) self.play( LaggedStartMap(SwitchOn, full_ambient_lights, lag_ratio = 0.2, run_time = 3) ) # for ls in full_lights.submobjects: # self.play( # FadeIn(ls.lighthouse, run_time = 0.1),#5 * switch_on_time), # SwitchOn(ls.ambient_light, run_time = 0.1)#5 * switch_on_time), # ) even_terms = VMobject() for i in even_range: term = OldTex("+\,\,\, {1\over " + str(i) + "^2}", fill_color = LIGHT_COLOR2, stroke_color = LIGHT_COLOR) term.next_to(self.number_line1.number_to_point(i), DOWN, buff = sum_vertical_spacing) even_terms.add(term) even_lights = VMobject() for i in even_range: pos = self.number_line1.number_to_point(i) ls = ls_template.copy() ls.color = LIGHT_COLOR2 ls.move_source_to(pos) even_lights.add(ls) for (ls, term) in zip(even_lights.submobjects, even_terms.submobjects): self.play( SwitchOn(ls.ambient_light, run_time = switch_on_time), Write(term) ) self.wait() # now morph the even lights into the full lights full_lights_copy = full_lights.copy() even_lights_copy = even_lights.copy() self.play( Transform(even_lights,full_lights, run_time = 2) ) self.wait() for i in range(6): self.play( Transform(even_lights[i], even_lights_copy[i]) ) self.wait() # draw arrows P1 = self.number_line2.number_to_point(1) P2 = even_terms.submobjects[0].get_center() Q1 = interpolate(P1, P2, 0.2) Q2 = interpolate(P1, P2, 0.8) quarter_arrow = Arrow(Q1, Q2, color = LIGHT_COLOR2) quarter_label = OldTex("\\times {1\over 4}", fill_color = LIGHT_COLOR2, stroke_color = LIGHT_COLOR2) quarter_label.scale(0.7) quarter_label.next_to(quarter_arrow.get_center(), RIGHT) self.play( ShowCreation(quarter_arrow), Write(quarter_label), ) self.wait() P3 = odd_terms.submobjects[0].get_center() R1 = interpolate(P1, P3, 0.2) R2 = interpolate(P1, P3, 0.8) three_quarters_arrow = Arrow(R1, R2, color = LIGHT_COLOR) three_quarters_label = OldTex("\\times {3\over 4}", fill_color = LIGHT_COLOR, stroke_color = LIGHT_COLOR) three_quarters_label.scale(0.7) three_quarters_label.next_to(three_quarters_arrow.get_center(), LEFT) self.play( ShowCreation(three_quarters_arrow), Write(three_quarters_label) ) self.wait() four_thirds_arrow = Arrow(R2, R1, color = LIGHT_COLOR) four_thirds_label = OldTex("\\times {4\over 3}", fill_color = LIGHT_COLOR, stroke_color = LIGHT_COLOR) four_thirds_label.scale(0.7) four_thirds_label.next_to(four_thirds_arrow.get_center(), LEFT) self.play( FadeOut(quarter_label), FadeOut(quarter_arrow), FadeOut(even_lights), FadeOut(even_terms) ) self.wait() self.play( ReplacementTransform(three_quarters_arrow, four_thirds_arrow), ReplacementTransform(three_quarters_label, four_thirds_label) ) self.wait() full_terms = VMobject() for i in range(1,8): #full_range: if i == 1: term = OldTex("\phantom{+\,\,\,}{1\over " + str(i) + "^2}", fill_color = LIGHT_COLOR3, stroke_color = LIGHT_COLOR3) elif i == 7: term = OldTex("+\,\,\,\dots", fill_color = LIGHT_COLOR3, stroke_color = LIGHT_COLOR3) else: term = OldTex("+\,\,\, {1\over " + str(i) + "^2}", fill_color = LIGHT_COLOR3, stroke_color = LIGHT_COLOR3) term.move_to(self.number_line2.number_to_point(i)) full_terms.add(term) #return self.play( FadeOut(self.number_line1), FadeOut(odd_lights), FadeOut(self.number_line2), FadeOut(full_lights), FadeIn(full_terms) ) self.wait() v = (sum_vertical_spacing + 0.5) * UP self.play( odd_terms.shift, v, result1.shift, v, four_thirds_arrow.shift, v, four_thirds_label.shift, v, odd_terms.shift, v, full_terms.shift, v ) arrow_copy = four_thirds_arrow.copy() label_copy = four_thirds_label.copy() arrow_copy.shift(2.5 * LEFT) label_copy.shift(2.5 * LEFT) self.play( FadeIn(arrow_copy), FadeIn(label_copy) ) self.wait() final_result = OldTex("{\pi^2 \over 6}=", fill_color = LIGHT_COLOR3, stroke_color = LIGHT_COLOR3) final_result.next_to(arrow_copy, DOWN) self.play( Write(final_result), randy.change_mode,"hooray" ) self.wait() equation = VMobject() equation.add(final_result) equation.add(full_terms) self.play( FadeOut(result1), FadeOut(odd_terms), FadeOut(arrow_copy), FadeOut(label_copy), FadeOut(four_thirds_arrow), FadeOut(four_thirds_label), full_terms.shift,LEFT, ) self.wait() self.play(equation.shift, -equation.get_center()[1] * UP + UP + 1.5 * LEFT) result_box = Rectangle(width = 1.1 * equation.get_width(), height = 2 * equation.get_height(), color = LIGHT_COLOR3) result_box.move_to(equation) self.play( ShowCreation(result_box) ) self.wait() class LabeledArc(Arc): CONFIG = { "length" : 1 } def __init__(self, angle, **kwargs): BUFFER = 1.3 Arc.__init__(self,angle,**kwargs) label = DecimalNumber(self.length, num_decimal_places = 0) r = BUFFER * self.radius theta = self.start_angle + self.angle/2 label_pos = r * np.array([np.cos(theta), np.sin(theta), 0]) label.move_to(label_pos) self.add(label) class ArcHighlightOverlayScene(Scene): def construct(self): BASELINE_YPOS = -2.5 OBSERVER_POINT = [0,BASELINE_YPOS,0] LAKE0_RADIUS = 1.5 INDICATOR_RADIUS = 0.6 TICK_SIZE = 0.5 LIGHTHOUSE_HEIGHT = 0.2 LAKE_COLOR = BLUE LAKE_OPACITY = 0.15 LAKE_STROKE_WIDTH = 5.0 LAKE_STROKE_COLOR = BLUE TEX_SCALE = 0.8 DOT_COLOR = BLUE FLASH_TIME = 0.25 def flash_arcs(n): angle = TAU/2**n arcs = [] arcs.append(LabeledArc(angle/2, start_angle = -TAU/4, radius = LAKE0_RADIUS, length = 1)) for i in range(1,2**n): arcs.append(LabeledArc(angle, start_angle = -TAU/4 + (i-0.5)*angle, radius = LAKE0_RADIUS, length = 2)) arcs.append(LabeledArc(angle/2, start_angle = -TAU/4 - angle/2, radius = LAKE0_RADIUS, length = 1)) self.play( FadeIn(arcs[0], run_time = FLASH_TIME) ) for i in range(1,2**n + 1): self.play( FadeOut(arcs[i-1], run_time = FLASH_TIME), FadeIn(arcs[i], run_time = FLASH_TIME) ) self.play( FadeOut(arcs[2**n], run_time = FLASH_TIME), ) class ThumbnailScene(Scene): def construct(self): equation = OldTex("1+{1\over 4}+{1\over 9}+{1\over 16}+{1\over 25}+\dots") equation.scale(1.5) equation.move_to(1.5 * UP) q_mark = OldTex("=?", color = LIGHT_COLOR).scale(5) q_mark.next_to(equation, DOWN, buff = 1.5) #equation.move_to(2 * UP) #q_mark = OldTex("={\pi^2\over 6}", color = LIGHT_COLOR).scale(3) #q_mark.next_to(equation, DOWN, buff = 1) lake_radius = 6 lake_center = ORIGIN op_scale = 0.4 lake = Circle( fill_color = LAKE_COLOR, fill_opacity = LAKE_OPACITY, radius = lake_radius, stroke_color = LAKE_STROKE_COLOR, stroke_width = LAKE_STROKE_WIDTH, ) lake.move_to(lake_center) for i in range(16): theta = -TAU/4 + (i + 0.5) * TAU/16 pos = lake_center + lake_radius * np.array([np.cos(theta), np.sin(theta), 0]) ls = LightSource( radius = 15.0, num_levels = 150, max_opacity_ambient = 1.0, opacity_function = inverse_quadratic(1,op_scale,1) ) ls.move_source_to(pos) lake.add(ls.ambient_light, ls.lighthouse) self.add(lake) self.add(equation, q_mark) self.wait() class InfiniteCircleScene(PiCreatureScene): def construct(self): morty = self.get_primary_pi_creature() morty.set_color(MAROON_D).flip() morty.color = MAROON_D morty.scale(0.5).move_to(ORIGIN) arrow = Arrow(ORIGIN, 2.4 * RIGHT) dot = Dot(color = BLUE).next_to(arrow) ellipsis = OldTex("\dots") infsum = VGroup() infsum.add(ellipsis.copy()) for i in range(3): infsum.add(arrow.copy().next_to(infsum.submobjects[-1])) infsum.add(dot.copy().next_to(infsum.submobjects[-1])) infsum.add(arrow.copy().next_to(infsum.submobjects[-1])) infsum.add(ellipsis.copy().next_to(infsum.submobjects[-1])) infsum.next_to(morty,DOWN, buff = 1) self.wait() self.play( LaggedStartMap(FadeIn,infsum,lag_ratio = 0.2) ) self.wait() A = infsum.submobjects[-1].get_center() + 0.5 * RIGHT B = A + RIGHT + 1.3 * UP + 0.025 * LEFT right_arc = DashedLine(TAU/4*UP, ORIGIN, stroke_color = YELLOW, stroke_width = 8).apply_complex_function(np.exp) right_arc.rotate(-TAU/4).next_to(infsum, RIGHT).shift(0.5 * UP) right_tip_line = Arrow(B - UP, B, color = WHITE) right_tip_line.add_tip() right_tip = right_tip_line.get_tip() right_tip.set_fill(color = YELLOW) right_arc.add(right_tip) C = B + 3.2 * UP right_line = DashedLine(B + 0.2 * DOWN,C + 0.2 * UP, stroke_color = YELLOW, stroke_width = 8) ru_arc = right_arc.copy().rotate(angle = TAU/4) ru_arc.remove(ru_arc.submobjects[-1]) ru_arc.to_edge(UP+RIGHT, buff = 0.15) D = np.array([5.85, 3.85,0]) E = np.array([-D[0],D[1],0]) up_line = DashedLine(D, E, stroke_color = YELLOW, stroke_width = 8) lu_arc = ru_arc.copy().flip().to_edge(LEFT + UP, buff = 0.15) left_line = right_line.copy().flip(axis = RIGHT).to_edge(LEFT, buff = 0.15) left_arc = right_arc.copy().rotate(-TAU/4) left_arc.next_to(infsum, LEFT).shift(0.5 * UP + 0.1 * LEFT) right_arc.shift(0.2 * RIGHT) right_line.shift(0.2 * RIGHT) self.play(FadeIn(right_arc)) self.play(ShowCreation(right_line)) self.play(FadeIn(ru_arc)) self.play(ShowCreation(up_line)) self.play(FadeIn(lu_arc)) self.play(ShowCreation(left_line)) self.play(FadeIn(left_arc)) self.wait() class RightAnglesOverlay(Scene): def construct(self): BASELINE_YPOS = -2.5 OBSERVER_POINT = [0,BASELINE_YPOS,0] LAKE0_RADIUS = 1.5 * 2 INDICATOR_RADIUS = 0.6 TICK_SIZE = 0.5 LIGHTHOUSE_HEIGHT = 0.2 LAKE_COLOR = BLUE LAKE_OPACITY = 0.15 LAKE_STROKE_WIDTH = 5.0 LAKE_STROKE_COLOR = BLUE TEX_SCALE = 0.8 DOT_COLOR = BLUE RIGHT_ANGLE_SIZE = 0.3 def right_angle(pointA, pointB, pointC, size = 1): v1 = pointA - pointB v1 = size * v1/get_norm(v1) v2 = pointC - pointB v2 = size * v2/get_norm(v2) P = pointB Q = pointB + v1 R = Q + v2 S = R - v1 angle_sign = VMobject() angle_sign.set_points_as_corners([P,Q,R,S,P]) angle_sign.mark_paths_closed = True angle_sign.set_fill(color = WHITE, opacity = 1) angle_sign.set_stroke(width = 0) return angle_sign lake_center = OBSERVER_POINT + LAKE0_RADIUS * UP points = [] lines = VGroup() for i in range(4): theta = -TAU/4 + (i+0.5)*TAU/4 v = np.array([np.cos(theta), np.sin(theta), 0]) P = lake_center + LAKE0_RADIUS * v points.append(P) lines.add(Line(lake_center, P, stroke_width = 8)) self.play(FadeIn(lines)) self.wait() for i in range(4): sign = right_angle(points[i-1], lake_center, points[i],RIGHT_ANGLE_SIZE) self.play(FadeIn(sign)) self.play(FadeOut(sign)) self.wait() self.play(FadeOut(lines)) flash_arcs(3)
from _2018.eop.reusables.binary_option import * from _2018.eop.reusables.brick_row import * from _2018.eop.reusables.coin_flip_tree import * from _2018.eop.reusables.coin_flipping_pi_creature import * from _2018.eop.reusables.coin_stacks import * from _2018.eop.reusables.dice import * from _2018.eop.reusables.eop_constants import * from _2018.eop.reusables.eop_helpers import * from _2018.eop.reusables.histograms import * from _2018.eop.reusables.sick_pi_creature import * from _2018.eop.reusables.upright_coins import *
from manim_imports_ext import * from once_useful_constructs.combinatorics import * nb_levels = 5 dev_x_step = 2 dev_y_step = 5 GRADE_COLOR_1 = RED GRADE_COLOR_2 = BLUE def graded_square(n,k): return Square( side_length = 1, fill_color = graded_color(n,k), fill_opacity = 1, stroke_width = 1 ) def graded_binomial(n,k): return Integer( choose(n,k), color = graded_color(n,k) ) def split_square(n,k): width = 1 height = 1 proportion = float(choose(n,k)) / 2**n lower_height = proportion * height upper_height = (1 - proportion) * height lower_rect = Rectangle( width = width, height = lower_height, fill_color = RED, fill_opacity = 1.0, stroke_color = WHITE, stroke_width = 3 ) upper_rect = Rectangle( width = width, height = upper_height, fill_color = BLUE, fill_opacity = 1.0, stroke_color = WHITE, stroke_width = 3 ) upper_rect.next_to(lower_rect,UP,buff = 0) square = VGroup(lower_rect, upper_rect).move_to(ORIGIN) return square class BuildNewPascalRow(Transform): def __init__(self,mobject, duplicate_row = None, **kwargs): if mobject.__class__ != GeneralizedPascalsTriangle and mobject.__class__ != PascalsTriangle: raise("Transform BuildNewPascalRow only works on members of (Generalized)PascalsTriangle!") n = mobject.nrows - 1 lowest_row_copy1 = mobject.get_lowest_row() lowest_row_copy2 = duplicate_row start_mob = VGroup(lowest_row_copy1, lowest_row_copy2) new_pt = mobject.copy() new_pt.nrows += 1 new_pt.init_points() # align with original (copy got centered on screen) c1 = new_pt.coords_to_mobs[0][0].get_center() c2 = mobject.coords_to_mobs[0][0].get_center() print(c1, c2) v = c2 - c1 new_pt.shift(v) new_row_left_copy = VGroup(*[ new_pt.coords_to_mobs[n+1][k] for k in range(0,n+1) ]) new_row_right_copy = VGroup(*[ new_pt.coords_to_mobs[n+1][k] for k in range(1,n+2) ]).copy() target_mob = VGroup(new_row_left_copy, new_row_right_copy) Transform.__init__(self, start_mob, target_mob, **kwargs) class SimplePascal(Scene): def build_new_pascal_row(self,old_pt): lowest_row_copy = old_pt.get_lowest_row().copy() self.add(lowest_row_copy) n = old_pt.nrows - 1 lowest_row_copy1 = old_pt.get_lowest_row() lowest_row_copy2 = lowest_row_copy1.copy() start_mob = VGroup(lowest_row_copy1, lowest_row_copy2) self.add(start_mob) new_pt = old_pt.copy() cell_height = old_pt.height / old_pt.nrows cell_width = old_pt.width / old_pt.nrows new_pt.nrows += 1 new_pt.height = new_pt.nrows * cell_height new_pt.width = new_pt.nrows * cell_width new_pt.init_points() # align with original (copy got centered on screen) c1 = new_pt.coords_to_mobs[0][0].get_center() c2 = old_pt.coords_to_mobs[0][0].get_center() v = c2 - c1 new_pt.shift(v) new_row_left_copy = VGroup(*[ new_pt.coords_to_mobs[n+1][k] for k in range(0,n+1) ]) new_row_right_copy = VGroup(*[ new_pt.coords_to_mobs[n+1][k] for k in range(1,n+2) ]).copy() target_mob = VGroup(new_row_left_copy, new_row_right_copy) self.play(Transform(start_mob, target_mob)) return new_pt def construct(self): cell_height = 1 cell_width = 1 nrows = 1 pt = GeneralizedPascalsTriangle( nrows = nrows, height = nrows * cell_height, width = nrows * cell_width, submob_class = graded_square, portion_to_fill = 0.9 ) pt.shift(3 * UP) self.add(pt) lowest_row_copy = pt.get_lowest_row().copy() self.add(lowest_row_copy) #self.play(BuildNewPascalRow(pt, duplicate_row = lowest_row_copy)) for i in range(7): pt = self.build_new_pascal_row(pt) class PascalNetScene(Scene): def construct(self): unit_width = 0.25 top_height = 4.0 level_height = 2.0 * top_height / nb_levels start_points = np.array([top_height * UP]) dev_start = start_points[0] j = 0 for n in range(nb_levels): half_width = 0.5 * (n + 0.5) * unit_width stop_points_left = start_points.copy() stop_points_left[:,0] -= 0.5 * unit_width stop_points_left[:,1] -= level_height stop_points_right = start_points.copy() stop_points_right[:,0] += 0.5 * unit_width stop_points_right[:,1] -= level_height for (p,q) in zip(start_points,stop_points_left): alpha = np.abs((p[0]+q[0])/2) / half_width color = rainbow_color(alpha) line = Line(p,q, stroke_color = color) self.add(line) for (i,(p,q)) in enumerate(zip(start_points,stop_points_right)): alpha = np.abs((p[0]+q[0])/2) / half_width color = rainbow_color(alpha) line = Line(p,q, stroke_color = color) self.add(line) if (n + 1) % dev_y_step == 0 and n != 1: j += dev_x_step dev_stop = stop_points_left[j] line = Line(dev_start,dev_stop,stroke_color = WHITE) self.add(line) dot = Dot(dev_stop, fill_color = WHITE) self.add_foreground_mobject(dot) dev_start = dev_stop start_points = np.append(stop_points_left,[stop_points_right[-1]], axis = 0) self.wait() class RescaledPascalNetScene(Scene): def construct(self): half_width = 3.0 top_height = 4.0 level_height = 2.0 * top_height / nb_levels start_points = np.array([top_height * UP]) left_edge = top_height * UP + half_width * LEFT right_edge = top_height * UP + half_width * RIGHT dev_start = start_points[0] j = 0 for n in range(nb_levels): if n == 0: start_points_left_shift = np.array([left_edge]) else: start_points_left_shift = start_points[:-1] start_points_left_shift = np.insert(start_points_left_shift,0,left_edge, axis = 0) stop_points_left = 0.5 * (start_points + start_points_left_shift) stop_points_left += level_height * DOWN if n == 0: start_points_right_shift = np.array([right_edge]) else: start_points_right_shift = start_points[1:] start_points_right_shift = np.append(start_points_right_shift,np.array([right_edge]), axis = 0) stop_points_right = 0.5 * (start_points + start_points_right_shift) stop_points_right += level_height * DOWN for (i,(p,q)) in enumerate(zip(start_points,stop_points_left)): color = GREY_B if n % 2 == 0 and i <= n/2: m = n/2 + 0.25 jj = i alpha = 1 - float(jj)/m color = rainbow_color(alpha) elif n % 2 == 0 and i > n/2: m = n/2 + 0.25 jj = n - i + 0.5 alpha = 1 - float(jj)/m color = rainbow_color(alpha) elif n % 2 == 1 and i <= n/2: m = n/2 + 0.75 jj = i alpha = 1 - float(jj)/m color = rainbow_color(alpha) elif n % 2 == 1 and i > n/2: m = n/2 + 0.75 jj = n - i + 0.5 alpha = 1 - float(jj)/m color = rainbow_color(alpha) line = Line(p,q, stroke_color = color) self.add(line) for (i,(p,q)) in enumerate(zip(start_points,stop_points_right)): color = GREY_B if n % 2 == 0 and i < n/2: m = n/2 + 0.25 jj = i + 0.5 alpha = 1 - float(jj)/m color = rainbow_color(alpha) elif n % 2 == 0 and i >= n/2: m = n/2 + 0.25 jj = n - i alpha = 1 - float(jj)/m color = rainbow_color(alpha) elif n % 2 == 1 and i <= n/2: m = n/2 + 0.75 jj = i + 0.5 alpha = 1 - float(jj)/m color = rainbow_color(alpha) elif n % 2 == 1 and i > n/2: m = n/2 + 0.75 jj = n - i alpha = 1 - float(jj)/m color = rainbow_color(alpha) line = Line(p,q, stroke_color = color) self.add(line) if (n + 1) % dev_y_step == 0 and n != 1: j += dev_x_step dev_stop = stop_points_left[j] line = Line(dev_start,dev_stop,stroke_color = WHITE) self.add(line) dot = Dot(dev_stop, fill_color = WHITE) self.add_foreground_mobject(dot) dev_start = dev_stop start_points = np.append(stop_points_left,[stop_points_right[-1]], axis = 0) left_edge += level_height * DOWN right_edge += level_height * DOWN self.wait()
from manim_imports_ext import * from _2018.eop.bayes import IntroducePokerHand SICKLY_GREEN = "#9BBD37" class BayesClassicExampleOpeningQuote(OpeningQuote): CONFIG = { "quote" : [ "When faced with a difficult question, we often " \ "answer an easier one instead, usually without " \ "noticing the substitution.", ], "author" : "Daniel Kahneman", } class Introduction(TeacherStudentsScene): def construct(self): self.hold_up_example() self.write_counter_intuitive() self.comment_on_crazy_results() self.put_it_first() self.swap_example_order() self.other_culprit() def hold_up_example(self): everyone = self.get_pi_creatures() self.teacher.change_mode("raise_right_hand") rect = ScreenRectangle() rect.set_stroke(YELLOW, 2) rect.to_edge(UP) randy = Randolph() randy.scale(0.7) name = OldTexText(r""" Bayes' theorem \\ disease example """) name.next_to(rect.get_top(), DOWN, SMALL_BUFF) randy.next_to(name, DOWN) example = VGroup(rect, name, randy) self.remove(everyone) self.add(name, randy) self.play( randy.change_mode, "sick", randy.set_color, SICKLY_GREEN ) self.play(ShowCreation(rect)) self.play( FadeIn(everyone), example.scale, 0.5, example.next_to, self.teacher.get_corner(UP+LEFT), UP, ) self.wait(2) self.example = example def write_counter_intuitive(self): bayes = OldTexText("Bayes") arrow = OldTex("\\leftrightarrow") intuition = OldTexText("Intuition") group = VGroup(bayes, arrow, intuition) group.arrange(RIGHT, buff = SMALL_BUFF) group.scale(0.8) group.next_to(self.example, UP, buff = SMALL_BUFF) group.shift_onto_screen() cross = VGroup( Line(UP+LEFT, DOWN+RIGHT), Line(UP+RIGHT, DOWN+LEFT), ) cross.replace(arrow, stretch = True) cross.set_stroke(RED, 6) group.add(cross) self.play(*list(map(FadeIn, [bayes, intuition]))) self.play(Write(arrow)) self.play(ShowCreation(cross)) self.play_student_changes(*["confused"]*3) self.wait(2) self.bayes_to_intuition = group def comment_on_crazy_results(self): disease_group = VGroup(self.example, self.bayes_to_intuition) disease_group.save_state() self.teacher_says( "Who doesn't love \\\\ crazy results?", target_mode = "hooray", added_anims = [disease_group.to_corner, UP+LEFT] ) self.wait(2) self.disease_group = disease_group def put_it_first(self): poker_example = self.get_poker_example() music_example = self.get_music_example() disease_group = self.disease_group self.play( disease_group.restore, disease_group.to_edge, LEFT, RemovePiCreatureBubble( self.teacher, target_mode = "hesitant" ) ) self.play_student_changes( *["pondering"]*3, look_at = disease_group ) poker_example.next_to(self.example, RIGHT) music_example.next_to(poker_example, RIGHT) examples = VGroup(poker_example, music_example) brace = Brace(examples, UP) bayes_to_intuition = VGroup(*list(map(TexText, [ "Bayes", "$\\leftrightarrow$", "Intuition" ]))) bayes_to_intuition.arrange(RIGHT, buff = SMALL_BUFF) bayes_to_intuition.next_to(brace, UP, SMALL_BUFF) check = OldTex("\\checkmark") check.set_color(GREEN) check.next_to(bayes_to_intuition[1], UP, SMALL_BUFF) for example in examples: self.play(FadeIn(example)) self.wait() self.play(GrowFromCenter(brace)) self.play(FadeIn(bayes_to_intuition)) self.play(Write(check)) self.wait(2) self.intuitive_examples = VGroup( examples, brace, bayes_to_intuition, check ) def swap_example_order(self): intuitive_examples = self.intuitive_examples disease_group = VGroup( self.example, self.bayes_to_intuition ) self.play( disease_group.next_to, self.teacher.get_corner(UP+LEFT), UP, disease_group.shift, LEFT, intuitive_examples.scale, 0.7, intuitive_examples.to_corner, UP+LEFT, self.teacher.change_mode, "sassy" ) def other_culprit(self): bayes = self.bayes_to_intuition[0] something_else = OldTexText("Something else") something_else.set_color(YELLOW) something_else.set_height(bayes.get_height()) something_else.move_to(bayes, RIGHT) new_group = VGroup( something_else, *self.bayes_to_intuition[1:] ) self.play(bayes.to_edge, UP) self.play(Write(something_else)) self.play(new_group.next_to, self.example, UP, SMALL_BUFF) self.play_student_changes( "erm", "confused", "hesitant", added_anims = [self.teacher.change_mode, "happy"] ) self.wait(3) ##### def get_poker_example(self): rect = self.get_example_rect() values = IntroducePokerHand.CONFIG["community_card_values"] community_cards = VGroup(*list(map(PlayingCard, values))) community_cards.arrange(RIGHT) deck = VGroup(*[ PlayingCard(turned_over = True) for x in range(5) ]) for i, card in enumerate(deck): card.shift(i*(0.03*RIGHT + 0.015*DOWN)) deck.next_to(community_cards, LEFT) cards = VGroup(deck, community_cards) cards.set_width(rect.get_width() - 2*SMALL_BUFF) cards.next_to(rect.get_bottom(), UP, MED_SMALL_BUFF) probability = OldTex( "P(", "\\text{Flush}", "|", "\\text{High bet}", ")" ) probability.set_color_by_tex("Flush", RED) probability.set_color_by_tex("High bet", GREEN) probability.scale(0.5) probability.next_to(rect.get_top(), DOWN) return VGroup(rect, probability, cards) def get_music_example(self): rect = self.get_example_rect() musician = Randolph(mode = "soulful_musician") musician.left_arm_range = [.36, .45] musician.arms = musician.get_arm_copies() guitar = musician.guitar = Guitar() guitar.move_to(musician) guitar.shift(0.31*RIGHT + 0.6*UP) musician.add(guitar, musician.arms) musician.set_height(0.7*rect.get_height()) musician.next_to(rect.get_bottom(), UP, SMALL_BUFF) probability = OldTex( "P(", "\\text{Suck }", "|", "\\text{ Good review}", ")" ) probability.set_color_by_tex("Suck", RED) probability.set_color_by_tex("Good", GREEN) probability.scale(0.5) probability.next_to(rect.get_top(), DOWN) return VGroup(rect, musician, probability) def get_example_rect(self): rect = self.example[0].copy() rect.set_color(WHITE) return rect class OneInOneThousandHaveDisease(Scene): def construct(self): title = OldTexText("1 in 1{,}000") title.to_edge(UP) creature = PiCreature() all_creatures = VGroup(*[ VGroup(*[ creature.copy() for y in range(25) ]).arrange(DOWN, SMALL_BUFF) for x in range(40) ]).arrange(RIGHT, SMALL_BUFF) all_creatures.set_width(FRAME_WIDTH - 4) all_creatures.next_to(title, DOWN) randy = all_creatures[0][0] all_creatures[0].remove(randy) randy.change_mode("sick") randy.set_color(SICKLY_GREEN) randy.save_state() randy.set_height(3) randy.center() randy.change_mode("plain") randy.set_color(BLUE) self.add(randy) self.play( randy.change_mode, "sick", randy.set_color, SICKLY_GREEN ) self.play(Blink(randy)) self.play(randy.restore) self.play( Write(title), LaggedStartMap(FadeIn, all_creatures, run_time = 3) ) self.wait() class TestScene(PiCreatureScene): def get_result(self, creature, word, color): arrow = self.get_test_arrow() test_result = OldTexText(word) test_result.set_color(color) test_result.next_to(arrow.get_end(), RIGHT) group = VGroup(arrow, test_result) group.next_to(creature, RIGHT, aligned_edge = UP) return group def get_positive_result(self, creature): return self.get_result(creature, "Diseased", SICKLY_GREEN) def get_negative_result(self, creature): return self.get_result(creature, "Healthy", GREEN) def get_test_arrow(self): arrow = Arrow( LEFT, RIGHT, color = WHITE, ) word = OldTexText("Test") word.scale(0.8) word.next_to(arrow, UP, buff = 0) arrow.add(word) return arrow def create_pi_creature(self): randy = Randolph() randy.next_to(ORIGIN, LEFT) return randy class TestDiseaseCase(TestScene): def construct(self): randy = self.pi_creature randy.change_mode("sick") randy.set_color(SICKLY_GREEN) result = self.get_positive_result(randy) accuracy = OldTexText("100\\% Accuracy") accuracy.next_to(VGroup(randy, result), UP) accuracy.to_edge(UP) self.add(randy) self.play(FadeIn(result[0])) self.play(Write(result[1])) self.play(FadeIn(accuracy)) self.wait() class TestNonDiseaseCase(TestScene): def construct(self): randy = self.pi_creature randy.change_mode("happy") randy.next_to(ORIGIN, LEFT) result = self.get_negative_result(randy) accuracy = OldTexText("99\\% Accuracy") accuracy.next_to(VGroup(randy, result), UP) accuracy.to_edge(UP) all_creatures = VGroup(*[ VGroup(*[ randy.copy() for y in range(10) ]).arrange(DOWN) for y in range(10) ]).arrange(RIGHT) all_creatures.set_height(6) all_creatures.to_corner(DOWN+LEFT) last_guy = all_creatures[-1][-1] rect = SurroundingRectangle(last_guy, buff = 0) rect.set_color(YELLOW) self.add(randy, accuracy) self.play(FadeIn(result[0])) self.play(Write(result[1])) self.play(Blink(randy)) self.play( ReplacementTransform(randy, all_creatures[0][0]), LaggedStartMap(FadeIn, all_creatures, run_time = 2), FadeOut(result) ) self.play(ShowCreation(rect)) self.play( last_guy.set_height, 2, last_guy.next_to, all_creatures, RIGHT ) result = self.get_positive_result(last_guy) false_positive = OldTexText("False positive") false_positive.scale(0.8) false_positive.next_to(result, UP, LARGE_BUFF) false_positive.to_edge(RIGHT) arrow = Arrow( false_positive.get_bottom(), result[1].get_top(), buff = SMALL_BUFF ) self.play(FadeIn(result)) self.play( FadeIn(false_positive), ShowCreation(arrow), last_guy.change, "confused", result, ) for x in range(2): self.play(Blink(last_guy)) self.wait(2) class ReceivePositiveResults(TestScene): def construct(self): status = OldTexText("Health status: ???") status.to_edge(UP) randy = self.pi_creature result = self.get_positive_result(randy) accuracy = OldTexText("99\% Accuracy") accuracy.next_to(result[1], DOWN, LARGE_BUFF) accuracy.set_color(YELLOW) self.add(status, randy) self.play(FadeIn(result[0])) self.wait() self.play(Write(result[1])) self.play(randy.change, "maybe", result) self.wait(2) self.play( randy.change, "pleading", accuracy, Write(accuracy, run_time = 1) ) self.wait() self.play(randy.change, "sad", accuracy) self.wait(2) class AskAboutRephrasingQuestion(TeacherStudentsScene): def construct(self): self.teacher_says( "What if we rephrased \\\\ the question?", run_time = 1 ) self.wait(3) class RephraseQuestion(Scene): def construct(self): words = VGroup(*list(map(TexText, [ r"1 in $1{,000}$ chance \\ of having disease", r"1 in $100$ \\ false positive rate.", r"""\underline{\phantom{1 in 10}} chance \\ of having disease \\ after testing positive. """, ]))) words.arrange(RIGHT, buff = LARGE_BUFF) words.set_width(2*(FRAME_X_RADIUS - MED_LARGE_BUFF)) prior = OldTexText("Prior") prior.set_color(GREEN) prior.next_to(words[0], UP, 1.5*LARGE_BUFF) prior_arrow = Arrow(prior, words[0]) prior_arrow.set_color(prior.get_color()) posterior = OldTexText("Posterior") posterior.next_to(words[2], UP) posterior.shift( (prior.get_center() - posterior.get_center())[1]*UP ) posterior.set_color(YELLOW) posterior_arrow = Arrow(posterior, words[2]) posterior_arrow.set_color(posterior.get_color()) self.add(words[0]) self.play( LaggedStartMap(FadeIn, prior), ShowCreation(prior_arrow), run_time = 1 ) self.wait() self.play(FadeIn(words[1])) self.wait() self.play(FadeIn(words[2])) self.play( LaggedStartMap(FadeIn, posterior), ShowCreation(posterior_arrow), run_time = 1 ) self.wait(2) class TryUnitSquareVisual(SampleSpaceScene): def construct(self): sample_space = self.get_sample_space() self.add_prior_division() self.add(sample_space) self.add_conditional_divisions() prior_label = sample_space.horizontal_parts.labels[0] final_labels = self.final_labels hard_to_see = OldTexText("Hard to see") hard_to_see.scale(0.7) hard_to_see.next_to(prior_label, UP) hard_to_see.to_edge(UP) hard_to_see.set_color(YELLOW) arrow = Arrow(hard_to_see, prior_label) self.wait() anims = self.get_division_change_animations( sample_space, sample_space.horizontal_parts, 0.001, new_label_kwargs = {"labels" : final_labels} ) self.play(*anims, run_time = 2) self.wait() self.play( Write(hard_to_see, run_time = 2), ShowCreation(arrow) ) self.wait(2) def add_prior_division(self): sample_space = self.sample_space sample_space.divide_horizontally(0.1) initial_labels, final_labels = [ VGroup( OldTex("P(\\text{Disease})", s1), OldTex("P(\\text{Not disease})", s2), ).scale(0.7) for s1, s2 in (("", ""), ("= 0.001", "= 0.999")) ] sample_space.get_side_braces_and_labels(initial_labels) sample_space.add_braces_and_labels() self.final_labels = final_labels def add_conditional_divisions(self): sample_space = self.sample_space top_part, bottom_part = sample_space.horizontal_parts top_brace = Brace(top_part, UP) top_label = OldTex( "P(", "+", "|", "\\text{Disease}", ")", "=", "1" ) top_label.scale(0.7) top_label.next_to(top_brace, UP) top_label.set_color_by_tex("+", GREEN) self.play(GrowFromCenter(top_brace)) self.play(FadeIn(top_label)) self.wait() bottom_part.divide_vertically( 0.95, colors = [BLUE_E, YELLOW_E] ) bottom_label = OldTex( "P(", "+", "|", "\\text{Not disease}", ")", "=", "1" ) bottom_label.scale(0.7) bottom_label.set_color_by_tex("+", GREEN) braces, labels = bottom_part.get_bottom_braces_and_labels( [bottom_label] ) bottom_brace = braces[0] self.play( FadeIn(bottom_part.vertical_parts), GrowFromCenter(bottom_brace), ) self.play(FadeIn(bottom_label)) self.wait() class ShowRestrictedSpace(Scene): CONFIG = { "n_rows" : 25, "n_cols" : 40, "n_false_positives" : 10, "false_positive_color" : YELLOW_E, } def construct(self): self.add_all_creatures() self.show_accurate_positive_result() self.show_false_positive_conditional() self.show_false_positive_individuals() self.fade_out_negative_result_individuals() self.show_posterior_probability() self.contrast_with_prior() def add_all_creatures(self): title = OldTexText("$1{,}000$ individuals") title.to_edge(UP) all_creatures = self.get_all_creatures() sick_one = all_creatures.sick_one healthy_creatures = all_creatures.healthy_creatures sick_one.save_state() sick_one_words = OldTexText("1 sick") sick_one_words.next_to(sick_one, RIGHT) sick_one_words.to_edge(RIGHT) sick_one_words.set_color(SICKLY_GREEN) sick_one_arrow = Arrow( sick_one_words, sick_one, color = SICKLY_GREEN ) healthy_words = OldTexText("999 healthy") healthy_words.next_to(sick_one_words, UP, MED_LARGE_BUFF) healthy_words.shift_onto_screen() healthy_words.set_color(BLUE) self.add(title) self.play(LaggedStartMap(FadeIn, all_creatures)) self.play( FadeIn(sick_one_words), ShowCreation(sick_one_arrow) ) self.play( sick_one.set_height, 2, sick_one.next_to, sick_one_words, DOWN, sick_one.to_edge, RIGHT, ) self.wait() self.play(sick_one.restore) self.play( Write(healthy_words), LaggedStartMap( ApplyMethod, healthy_creatures, lambda m : (m.shift, MED_SMALL_BUFF*UP), rate_func = there_and_back, lag_ratio = 0.2, ) ) self.wait() self.play(FadeOut(title)) self.all_creatures = all_creatures self.healthy_creatures = healthy_creatures self.sick_one = sick_one self.sick_one_label = VGroup(sick_one_words, sick_one_arrow) self.healthy_ones_label = healthy_words def show_accurate_positive_result(self): equation = OldTex( "P(", "\\text{Test positive }", "|", "\\text{ sick}", ")", "=", "100\\%" ) equation.set_color_by_tex("positive", YELLOW) equation.set_color_by_tex("sick", SICKLY_GREEN) equation.to_corner(UP+LEFT) self.play(Write(equation, run_time = 1)) self.wait(2) self.disease_conditional = equation def show_false_positive_conditional(self): equation = OldTex( "P(", "\\text{Test positive }", "|", "\\text{ healthy}", ")", "=", "1\\%" ) equation.set_color_by_tex("positive", YELLOW) equation.set_color_by_tex("healthy", BLUE) equation.to_corner(UP+LEFT) self.play(ReplacementTransform( self.disease_conditional, equation )) self.wait() self.healthy_conditional = equation def show_false_positive_individuals(self): all_creatures = self.all_creatures false_positives = VGroup( *all_creatures[-1][1:1+self.n_false_positives] ) self.healthy_creatures.remove(*false_positives) brace = Brace(false_positives, RIGHT) words = OldTexText("10 False positives") words.scale(0.8) words.next_to(brace, RIGHT) self.play( GrowFromCenter(brace), LaggedStartMap( ApplyMethod, false_positives, lambda pi : (pi.set_color, self.false_positive_color), run_time = 1 ) ) self.play(Write(words)) self.wait() self.false_positives = false_positives self.false_positives_brace = brace self.false_positives_words = words def fade_out_negative_result_individuals(self): to_fade = VGroup( self.healthy_creatures, self.healthy_conditional, self.sick_one_label, self.healthy_ones_label, ) movers = VGroup(self.sick_one, *self.false_positives) movers.generate_target() movers.target.set_width(1) movers.target.arrange(RIGHT) movers.target.shift(DOWN) brace = Brace(VGroup(*movers.target[1:])) words = OldTexText("You are one of these") words.to_edge(UP) arrows = [ Arrow(words.get_bottom(), movers.target[i].get_top()) for i in (0, -1) ] self.play(FadeOut(to_fade)) self.play( MoveToTarget(movers), ReplacementTransform(self.false_positives_brace, brace), self.false_positives_words.next_to, brace, DOWN ) self.play( Write(words, run_time = 2), ShowCreation(arrows[0]) ) self.play(Transform( *arrows, run_time = 4, rate_func = there_and_back )) self.play(*list(map(FadeOut, [words, arrows[0]]))) self.brace = brace def show_posterior_probability(self): posterior = OldTex( "P(", "\\text{Sick }", "|", "\\text{ Positive test result}", ")", "\\approx \\frac{1}{11}", "\\approx 9\\%" ) posterior.set_color_by_tex("Sick", SICKLY_GREEN) posterior.set_color_by_tex("Positive", YELLOW) posterior.to_edge(UP) posterior.shift(LEFT) self.play(FadeIn(posterior)) self.wait(2) self.posterior = posterior def contrast_with_prior(self): prior = OldTex( "P(", "\\text{Sick}", ")", "= 0.1\\%" ) prior.set_color_by_tex("Sick", SICKLY_GREEN) prior.move_to(self.posterior, UP+RIGHT) self.revert_to_original_skipping_status() self.play( Write(prior, run_time = 1), self.posterior.shift, DOWN, ) arrow = Arrow( prior.get_right(), self.posterior.get_right(), path_arc = -np.pi, ) times_90 = OldTex("\\times 90") times_90.next_to(arrow, RIGHT) self.play(ShowCreation(arrow)) self.play(Write(times_90, run_time = 1)) self.wait(2) ###### def get_all_creatures(self): creature = PiCreature() all_creatures = VGroup(*[ VGroup(*[ creature.copy() for y in range(self.n_rows) ]).arrange(DOWN, SMALL_BUFF) for x in range(self.n_cols) ]).arrange(RIGHT, SMALL_BUFF) all_creatures.set_height(5) all_creatures.center().to_edge(LEFT) healthy_creatures = VGroup(*it.chain(*all_creatures)) sick_one = all_creatures[-1][0] sick_one.change_mode("sick") sick_one.set_color(SICKLY_GREEN) healthy_creatures.remove(sick_one) all_creatures.sick_one = sick_one all_creatures.healthy_creatures = healthy_creatures return all_creatures class DepressingForMedicalTestDesigners(TestScene): def construct(self): self.remove(self.pi_creature) self.show_99_percent_accuracy() self.reject_test() def show_99_percent_accuracy(self): title = OldTexText("99\\% Accuracy") title.to_edge(UP) title.generate_target() title.target.to_corner(UP+LEFT) checks = VGroup(*[ VGroup(*[ OldTex("\\checkmark").set_color(GREEN) for y in range(10) ]).arrange(DOWN) for x in range(10) ]).arrange(RIGHT) cross = OldTex("\\times") cross.replace(checks[-1][-1]) cross.set_color(RED) Transform(checks[-1][-1], cross).update(1) checks.set_height(6) checks.next_to(title, DOWN) checks.generate_target() checks.target.scale(0.5) checks.target.next_to(title.target, DOWN) self.add(title) self.play(Write(checks)) self.wait(2) self.play(*list(map(MoveToTarget, [title, checks]))) def reject_test(self): randy = self.pi_creature randy.to_edge(DOWN) result = self.get_positive_result(randy) self.play(FadeIn(randy)) self.play( FadeIn(result), randy.change_mode, "pondering" ) self.wait() self.say( "Whatever, I'm 91\\% \\\\ sure that's wrong", target_mode = "shruggie" ) self.wait(2) class HowMuchCanYouChangeThisPrior(ShowRestrictedSpace, PiCreatureScene): def construct(self): self.single_out_new_sick_one() self.show_subgroups() self.isolate_special_group() def create_pi_creatures(self): creatures = self.get_all_creatures() creatures.set_height(6.5) creatures.center() creatures.submobjects = list(it.chain(*creatures)) self.add(creatures) self.sick_one = creatures.sick_one return creatures def single_out_new_sick_one(self): creatures = self.pi_creatures sick_one = self.sick_one new_sick_one = sick_one.copy() new_sick_one.shift(1.3*sick_one.get_width()*RIGHT) sick_one.change_mode("plain") sick_one.set_color(BLUE_E) self.add(new_sick_one) self.sick_one = new_sick_one def show_subgroups(self): subgroups = VGroup(*[ VGroup(*it.chain( self.pi_creatures[i:i+5], self.pi_creatures[i+25:i+25+5:] )) for i in range(0, 1000) if i%5 == 0 and (i/25)%2 == 0 ]) special_group = subgroups[-5] special_group.add(self.sick_one) subgroups.generate_target() width_factor = FRAME_WIDTH/subgroups.get_width() height_factor = FRAME_HEIGHT/subgroups.get_height() subgroups.target.stretch_in_place(width_factor, 0) subgroups.target.stretch_in_place(height_factor, 1) for subgroup in subgroups.target: subgroup.stretch_in_place(1./width_factor, 0) subgroup.stretch_in_place(1./height_factor, 1) self.wait() self.play(MoveToTarget(subgroups)) subgroups.remove(special_group) rects = VGroup(*[ SurroundingRectangle( group, buff = 0, color = GREEN ) for group in subgroups ]) special_rect = SurroundingRectangle( special_group, buff = 0, color = RED ) self.play(FadeIn(rects), FadeIn(special_rect)) self.wait() self.to_fade = VGroup(subgroups, rects) self.special_group = special_group self.special_rect = special_rect def isolate_special_group(self): to_fade, special_group = self.to_fade, self.special_group self.play(FadeOut(to_fade)) self.play( FadeOut(self.special_rect), special_group.set_height, 6, special_group.center, ) self.wait() class ShowTheFormula(TeacherStudentsScene): CONFIG = { "seconds_to_blink" : 3, } def construct(self): scale_factor = 0.7 sick = "\\text{sick}" positive = "\\text{positive}" formula = OldTex( "P(", sick, "\\,|\\,", positive, ")", "=", "{\\quad P(", sick, "\\text{ and }", positive, ") \\quad", "\\over", "P(", positive, ")}", "=", "{1/1{,}000", "\\over", "1/1{,}000", "+", "(999/1{,}000)(0.01)}" ) formula.scale(scale_factor) formula.next_to(self.pi_creatures, UP, LARGE_BUFF) formula.shift_onto_screen(buff = MED_LARGE_BUFF) equals_group = formula.get_parts_by_tex("=") equals_indices = [ formula.index_of_part(equals) for equals in equals_group ] lhs = VGroup(*formula[:equals_indices[0]]) initial_formula = VGroup(*formula[:equals_indices[1]]) initial_formula.save_state() initial_formula.shift(3*RIGHT) over = formula.get_part_by_tex("\\over") num_start_index = equals_indices[0] + 1 num_end_index = formula.index_of_part(over) numerator = VGroup( *formula[num_start_index:num_end_index] ) numerator_rect = SurroundingRectangle(numerator) alt_numerator = OldTex( "P(", sick, ")", "P(", positive, "\\,|\\,", sick, ")" ) alt_numerator.scale(scale_factor) alt_numerator.move_to(numerator) number_fraction = VGroup(*formula[equals_indices[-1]:]) rhs = OldTex("\\approx 0.09") rhs.scale(scale_factor) rhs.move_to(equals_group[-1], LEFT) rhs.set_color(YELLOW) for mob in formula, alt_numerator: mob.set_color_by_tex(sick, SICKLY_GREEN) mob.set_color_by_tex(positive, YELLOW) #Ask question self.student_says("What does the \\\\ formula look like here?") self.play(self.teacher.change, "happy") self.wait() self.play( Write(lhs), RemovePiCreatureBubble( self.students[1], target_mode = "pondering", ), self.teacher.change, "raise_right_hand", self.students[0].change, "pondering", self.students[2].change, "pondering", ) self.wait() #Show initial formula lhs_copy = lhs.copy() self.play( LaggedStartMap( FadeIn, initial_formula, lag_ratio = 0.7 ), Animation(lhs_copy, remover = True), ) self.wait(2) self.play(ShowCreation(numerator_rect)) self.play(FadeOut(numerator_rect)) self.wait() self.play(Transform(numerator, alt_numerator)) initial_formula.add(*numerator) formula.add(*numerator) self.wait(3) #Show number_fraction self.play( initial_formula.move_to, initial_formula.saved_state, FadeIn(VGroup(*number_fraction[:3])) ) self.wait(2) self.play(LaggedStartMap( FadeIn, VGroup(*number_fraction[3:]), run_time = 3, lag_ratio = 0.7 )) self.wait(2) #Show rhs self.play(formula.shift, UP) self.play(Write(rhs)) self.play_student_changes(*["happy"]*3) self.look_at(rhs) self.wait(2) class SourceOfConfusion(Scene): CONFIG = { "arrow_width" : 5, } def construct(self): self.add_progression() self.ask_question() self.write_bayes_rule() self.shift_arrow() def add_progression(self): prior = OldTex("P(", "S", ")", "= 0.001") arrow = Arrow(ORIGIN, self.arrow_width*RIGHT) posterior = OldTex("P(", "S", "|", "+", ")", "= 0.09") for mob in prior, posterior: mob.set_color_by_tex("S", SICKLY_GREEN) mob.set_color_by_tex("+", YELLOW) progression = VGroup(prior, arrow, posterior) progression.arrange(RIGHT) progression.shift(DOWN) bayes_rule_words = OldTexText("Bayes' rule") bayes_rule_words.next_to(arrow, UP, buff = 0) arrow.add(bayes_rule_words) for mob, word in (prior, "Prior"), (posterior, "Posterior"): brace = Brace(mob, DOWN) label = brace.get_text(word) mob.add(brace, label) self.add(progression) self.progression = progression self.bayes_rule_words = bayes_rule_words def ask_question(self): question = OldTexText( "Where do math and \\\\ intuition disagree?" ) question.to_corner(UP+LEFT) question_arrow = Arrow( question.get_bottom(), self.bayes_rule_words.get_top(), color = WHITE ) self.play(Write(question)) self.wait() self.play(ShowCreation(question_arrow)) self.question = question self.question_arrow = question_arrow def write_bayes_rule(self): words = self.bayes_rule_words words_rect = SurroundingRectangle(words) rule = OldTex( "P(", "S", "|", "+", ")", "=", "P(", "S", ")", "{P(", "+", "|", "S", ")", "\\over", "P(", "+", ")}" ) rule.set_color_by_tex("S", SICKLY_GREEN) rule.set_color_by_tex("+", YELLOW) rule.to_corner(UP+RIGHT) rule_rect = SurroundingRectangle(rule) rule_rect.set_color(BLUE) rule.save_state() rule.replace(words_rect) rule.scale(0.9) rule.set_fill(opacity = 0) self.play(ShowCreation(words_rect)) self.play( ReplacementTransform(words_rect, rule_rect), rule.restore, run_time = 2 ) self.wait(3) def shift_arrow(self): new_arrow = Arrow( self.question.get_bottom(), self.progression[0].get_top(), color = WHITE ) self.play(Transform( self.question_arrow, new_arrow )) self.wait(2) class StatisticsVsEmpathy(PiCreatureScene): def construct(self): randy, morty = self.randy, self.morty sick_one = PiCreature() sick_one.scale(0.5) sick_group = VGroup( sick_one, VectorizedPoint(sick_one.get_bottom()) ) priors = VGroup(*[ OldTex("%.1f"%p+ "\\%").move_to(ORIGIN, RIGHT) for p in np.arange(0.1, 2.0, 0.1) ]) priors.next_to(randy, UP+LEFT, LARGE_BUFF) prior = priors[0] prior.save_state() self.play(PiCreatureSays( morty, "1 in 1{,}000 people \\\\ have this disease.", look_at = randy.eyes )) self.play(randy.change, "pondering", morty.eyes) self.wait() self.play(Write(prior)) self.wait() self.play( prior.scale, 0.1, prior.set_fill, None, 0, prior.move_to, randy.eyes ) self.wait() self.play( PiCreatureBubbleIntroduction( randy, sick_group, target_mode = "guilty", bubble_type = ThoughtBubble, content_introduction_class = FadeIn, look_at = sick_one, ), RemovePiCreatureBubble(morty) ) self.play( sick_one.change_mode, "sick", sick_one.set_color, SICKLY_GREEN ) self.wait() probably_me = OldTexText("That's probably \\\\ me") probably_me.next_to(sick_one, DOWN) target_sick_group = VGroup( sick_one.copy(), probably_me ) target_sick_group.scale(0.8) self.pi_creature_thinks( target_sick_group, target_mode = "pleading", ) self.wait(2) self.play(prior.restore) for new_prior in priors[1:]: self.play(Transform(prior, new_prior, run_time = 0.5)) self.wait() ###### def create_pi_creatures(self): randy = self.randy = Randolph() morty = self.morty = Mortimer() randy.to_edge(DOWN).shift(3*LEFT) morty.to_edge(DOWN).shift(3*RIGHT) return VGroup(randy, morty) class LessMedicalExample(Scene): def construct(self): disease = OldTex("P(\\text{Having a disease})") telepathy = OldTex("P(\\text{Telepathy})") cross = Cross(disease) self.add(disease) self.wait() self.play(ShowCreation(cross)) self.play( FadeIn(telepathy), VGroup(disease, cross).shift, 2*UP ) self.wait() class PlaneCrashProbability(Scene): def construct(self): plane_prob = OldTex( "P(\\text{Dying in a }", "\\text{plane}", "\\text{ crash})", "\\approx", "1/", "11{,}000{,}000" ) plane_prob.set_color_by_tex("plane", BLUE) car_prob = OldTex( "P(\\text{Dying in a }", "\\text{car}", "\\text{ crash})", "\\approx", "1/", "5{,}000" ) car_prob.set_color_by_tex("car", YELLOW) plane_prob.shift(UP) car_prob.shift( plane_prob.get_part_by_tex("approx").get_center() -\ car_prob.get_part_by_tex("approx").get_center() +\ DOWN ) self.play(Write(plane_prob)) self.wait(2) self.play(ReplacementTransform( plane_prob.copy(), car_prob )) self.wait(2) class IntroduceTelepathyExample(StatisticsVsEmpathy): def construct(self): self.force_skipping() self.show_mind_reading_powers() self.claim_mind_reading_powers() self.generate_random_number() self.guess_number_correctly() self.ask_about_chances() self.revert_to_original_skipping_status() self.say_you_probably_got_lucky() def show_mind_reading_powers(self): randy, morty = self.randy, self.morty title = OldTexText("1 in 1{,}000 read minds") title.to_edge(UP) self.add(title) self.read_mind(randy, morty) self.title = title def claim_mind_reading_powers(self): randy, morty = self.randy, self.morty self.play(PiCreatureSays( randy, "I have the gift.", run_time = 1, look_at = morty.eyes, )) self.wait() self.play(RemovePiCreatureBubble( randy, target_mode = "happy", look_at = morty.eyes )) def generate_random_number(self): morty = self.morty bubble = morty.get_bubble("", direction = LEFT) numbers = [ Integer(random.choice(list(range(100)))) for x in range(30) ] numbers.append(Integer(67)) for number in numbers: number.next_to(morty, UP, LARGE_BUFF, RIGHT) for number in numbers: self.add(number) Scene.wait(self, 0.1) self.remove(number) self.play( ShowCreation(bubble), number.move_to, bubble.get_bubble_center(), DOWN+LEFT, morty.change, "pondering", ) self.wait() morty.bubble = bubble self.number = number def guess_number_correctly(self): randy, morty = self.randy, self.morty number_copy = self.number.copy() self.read_mind(randy, morty) self.play(PiCreatureSays( randy, number_copy, target_mode = "hooray", look_at = morty.eyes )) self.wait() def ask_about_chances(self): probability = OldTex( "P(", "\\text{Telepath }", "|", "\\text{ Correct}", ")", "=", "???" ) probability.set_color_by_tex("Telepath", BLUE) probability.set_color_by_tex("Correct", GREEN) probability.to_edge(UP) self.play(morty.change, "confused", randy.eyes) self.wait() self.play(ReplacementTransform( self.title, VGroup(*it.chain(*probability)) )) self.wait() def say_you_probably_got_lucky(self): randy, morty = self.randy, self.morty self.play( PiCreatureSays( morty, "You probably \\\\ got lucky.", target_mode = "sassy", look_at = randy.eyes, bubble_config = {"height" : 3, "width" : 4} ), RemovePiCreatureBubble( randy, target_mode = "plain", look_at = morty.eyes, ) ) self.wait(2) ### def read_mind(self, pi1, pi2): self.play(pi1.change, "telepath", pi2.eyes) self.send_mind_waves(pi1, pi2) self.send_mind_waves(pi2, pi1) self.wait() def send_mind_waves(self, pi1, pi2): angle = np.pi/3 n_arcs = 5 vect = pi2.eyes.get_center() - pi1.eyes.get_center() vect[1] = 0 arc = Arc(angle = angle) arc.rotate(-angle/2 + angle_of_vector(vect), about_point = ORIGIN) arc.scale(3) arcs = VGroup(*[arc.copy() for x in range(n_arcs)]) arcs.move_to(pi2.eyes.get_center(), vect) arcs.set_stroke(BLACK, 0) for arc in arcs: arc.save_state() arcs.scale(0.1) arcs.move_to(pi1.eyes, vect) arcs.set_stroke(WHITE, 4) self.play(LaggedStartMap( ApplyMethod, arcs, lambda m : (m.restore,), lag_ratio = 0.7, )) self.remove(arcs) class CompareNumbersInBothExamples(Scene): def construct(self): v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) v_line.shift(MED_LARGE_BUFF*LEFT) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.to_edge(UP, buff = 1.25*LARGE_BUFF) titles = VGroup() for word, vect in ("Disease", LEFT), ("Telepathy", RIGHT): title = OldTexText("%s example"%word) title.shift(vect*FRAME_X_RADIUS/2.0) title.to_edge(UP) titles.add(title) priors = VGroup(*[ OldTex( "P(", "\\text{%s}"%s, ")", "= 1/1{,}000}" ) for s in ("Sick", "Powers") ]) likelihoods = VGroup(*[ OldTex( "P(", "\\text{%s}"%s1, "|", "\\text{Not }", "\\text{%s}"%s2, ")", "=", "1/100" ) for s1, s2 in [("+", "Sick"), ("Correct", "Powers")] ]) priors.next_to(likelihoods, UP, LARGE_BUFF) for group in priors, likelihoods: for mob, vect in zip(group, [LEFT, RIGHT]): mob.set_color_by_tex("Sick", BLUE) mob.set_color_by_tex("Powers", BLUE) mob.set_color_by_tex("+", GREEN) mob.set_color_by_tex("Correct", GREEN) mob.scale(0.8) mob.shift(vect*FRAME_X_RADIUS/2) self.play( LaggedStartMap(FadeIn, titles, lag_ratio = 0.7), *list(map(ShowCreation, [h_line, v_line])) ) self.wait() self.play(FadeIn(priors)) self.wait() self.play(FadeIn(likelihoods)) self.wait(3) class NonchalantReactionToPositiveTest(TestScene): def construct(self): randy = self.pi_creature randy.shift(DOWN+2*RIGHT) result = self.get_positive_result(randy) accuracy = OldTexText("99\\% Accuracy") accuracy.set_color(YELLOW) accuracy.next_to(result, DOWN, LARGE_BUFF, RIGHT) self.add(accuracy) self.play(Write(result, run_time = 2)) self.play(randy.change, "pondering", result) self.wait() words = OldTexText("Pssht, I'm probably fine.") words.scale(0.8) self.pi_creature_says( words, target_mode = "shruggie", bubble_config = { "direction" : RIGHT, "width" : 6, "height" : 3, }, content_introduction_class = FadeIn, ) self.wait(4) class OneInOneThousandHaveDiseaseCopy(OneInOneThousandHaveDisease): pass class ExampleMeasuresDisbeliefInStatistics(Introduction): def construct(self): self.teacher.shift(LEFT) self.hold_up_example() self.write_counter_intuitive() self.write_new_theory() self.either_way() def write_new_theory(self): bayes_to_intuition = self.bayes_to_intuition cross = bayes_to_intuition[-1] bayes_to_intuition.remove(cross) statistics_to_belief = OldTexText( "Statistics ", "$\\leftrightarrow$", " Belief" ) statistics_to_belief.scale(0.8) arrow = statistics_to_belief.get_part_by_tex("arrow") statistics_to_belief.next_to(self.example, UP) self.revert_to_original_skipping_status() self.play(bayes_to_intuition.to_edge, UP) self.play( LaggedStartMap(FadeIn, statistics_to_belief), cross.move_to, arrow ) self.play_student_changes( *["pondering"]*3, look_at = statistics_to_belief ) self.wait(3) statistics_to_belief.add(cross) self.statistics_to_belief = statistics_to_belief def either_way(self): b_to_i = self.bayes_to_intuition s_to_b = self.statistics_to_belief self.play(FadeOut(self.example)) self.play( self.teacher.change_mode, "raise_left_hand", self.teacher.look, UP+RIGHT, b_to_i.next_to, self.teacher, UP, b_to_i.to_edge, RIGHT, MED_SMALL_BUFF, ) self.wait(2) self.play( self.teacher.change_mode, "raise_right_hand", self.teacher.look, UP+LEFT, s_to_b.next_to, self.teacher, UP, s_to_b.shift, LEFT, b_to_i.shift, 2*UP ) self.wait(2) class AlwaysPictureTheSpaceOfPossibilities(PiCreatureScene): def construct(self): self.pi_creature_thinks( "", bubble_config = { "height" : 4.5, "width" : 8, } ) self.wait(3) def create_pi_creature(self): return Randolph().to_corner(DOWN+LEFT) class Thumbnail(Scene): def construct(self): title = OldTexText("Why is this \\\\ counterintuitive?") title.scale(2) title.to_edge(UP) randy = Randolph(mode = "sick", color = SICKLY_GREEN) # randy.look_at(title) randy.scale(1.5) randy.shift(3*LEFT) randy.to_edge(DOWN) prob = OldTex("P(", "\\text{Sick}", "|", "\\text{Test+}", ")") prob.scale(2) prob.set_color_by_tex("Sick", YELLOW) prob.set_color_by_tex("Test", GREEN) prob.next_to(randy, RIGHT) self.add(title, randy, prob)
from manim_imports_ext import * #revert_to_original_skipping_status def get_stack( obj1, obj2, n, k, fixed_start = None, fixed_end = None, obj_to_obj_buff = SMALL_BUFF, vertical_buff = MED_SMALL_BUFF, ): stack = VGroup() for indices in it.combinations(list(range(n)), k): term = VGroup(*[ obj1.copy() if i in indices else obj2.copy() for i in range(n) ]) if fixed_start: term.add_to_back(fixed_start.copy()) if fixed_end: term.add(fixed_end.copy()) term.arrange(RIGHT, buff = obj_to_obj_buff) stack.add(term) stack.arrange(DOWN, buff = vertical_buff) return stack def get_stacks(obj1, obj2, n, **kwargs): stacks = VGroup() for k in range(n+1): stacks.add(get_stack(obj1, obj2, n, k, **kwargs)) stacks.arrange( RIGHT, buff = MED_LARGE_BUFF, aligned_edge = DOWN ) return stacks class Male(Tex): CONFIG = { "height" : 0.4, "tex" : "\\male", "color" : BLUE, } def __init__(self, **kwargs): digest_config(self, kwargs) Tex.__init__(self, self.tex, **kwargs) self.set_height(self.height) self.set_color(self.color) class Female(Male): CONFIG = { "tex" : "\\female", "color" : MAROON_B, } class PascalsTriangle(VGroup): CONFIG = { "n_rows" : 9, "distance" : 0.8, "max_width_to_distance_ratio" : 0.7, "angle" : 0.2*np.pi, } def __init__(self, **kwargs): VGroup.__init__(self, **kwargs) distance = self.distance angle = self.angle max_width = self.max_width_to_distance_ratio * distance t_down = rotate_vector(distance*DOWN, -angle) t_right = 2*distance*np.sin(angle)*RIGHT for n in range(self.n_rows): row = VGroup() for k in range(n+1): num = OldTex(str(choose(n, k))) num.shift(n*t_down + k*t_right) row.add(num) self.add(row) self.center() ###################### class ExperienceProblemSolver(PiCreatureScene): def construct(self): self.add_equation() self.jenny_solves() self.no_genius() self.think_about_patterns() def add_equation(self): equation = OldTex( "\\frac{x^3 + y^3}{(x+y)^2} + \\frac{3xy}{x+y}" ) equation.to_edge(UP) self.play(Write(equation)) self.wait() self.equation = equation def jenny_solves(self): randy, jenny = self.randy, self.jenny jenny_words = OldTexText("It's just $x+y$") randy_words = OldTexText("...wait...") randy_words.next_to(randy.get_corner(UP+RIGHT), RIGHT) self.pi_creature_says( jenny, jenny_words, target_mode = "hooray", bubble_config = {"height" : 2, "width" : 3} ) self.wait() self.play( randy.change, "confused", self.equation, Write(randy_words) ) self.play(randy.look_at, self.equation.get_left()) self.play(randy.look_at, jenny.eyes) self.play(jenny.change, "happy") self.play(randy.change, "tired") self.wait() self.play(*list(map(FadeOut, [ jenny.bubble, jenny_words, randy_words ]))) def no_genius(self): randy, jenny = self.randy, self.jenny lightbulb = Lightbulb() lightbulb.next_to(jenny, UP) cross = Cross(lightbulb) cross.set_stroke(RED, 8) self.play(LaggedStartMap(ShowCreation, lightbulb)) self.play( ShowCreation(cross), jenny.change, "sassy", cross, randy.change, "happy" ) self.wait(2) self.to_fade = VGroup(lightbulb, cross) def think_about_patterns(self): randy, jenny = self.randy, self.jenny rows = PascalsTriangle( n_rows = 6, distance = 0.6, ) rows.scale(0.8) for row in rows: for num in row: n = float(num.get_tex()) num.set_color(interpolate_color( BLUE, YELLOW, n/10.0 )) self.pi_creature_thinks( jenny, "", bubble_config = {"width" : 5, "height" : 4.2}, added_anims = [ FadeOut(self.to_fade), FadeOut(self.equation), randy.change, "plain" ] ) rows.move_to( jenny.bubble.get_bubble_center() + \ MED_SMALL_BUFF*(UP+LEFT) ) self.play(FadeIn(rows[0])) for last_row, curr_row in zip(rows, rows[1:]): self.play(*[ Transform( last_row.copy(), VGroup(*mobs), remover = True ) for mobs in (curr_row[1:], curr_row[:-1]) ]) self.add(curr_row) self.wait(3) ############ def create_pi_creatures(self): randy = Randolph() randy.to_edge(DOWN) randy.shift(4*LEFT) jenny = PiCreature(color = BLUE_C).flip() jenny.to_edge(DOWN) jenny.shift(4*RIGHT) self.randy, self.jenny = randy, jenny return randy, jenny class InitialFiveChooseThreeExample(Scene): CONFIG = { "n" : 5, "zero_color" : BLUE, "one_color" : PINK, } def construct(self): self.show_all_stacks() self.add_title() self.show_binomial_name() self.issolate_single_stack() self.count_chosen_stack() self.count_ways_to_fill_slots() self.walk_though_notation() self.emphasize_pattern_over_number() def show_all_stacks(self): stacks = get_stacks( self.get_obj1(), self.get_obj2(), self.n, vertical_buff = SMALL_BUFF ) stacks.to_edge(DOWN, buff = MED_LARGE_BUFF) for stack in stacks: self.play(FadeIn( stack, run_time = 0.2*len(stack), lag_ratio = 0.5 )) self.wait() self.set_variables_as_attrs(stacks) def add_title(self): n = self.n stacks = self.stacks n_choose_k = OldTex("n \\choose k") n_choose_k_words = OldTexText("``n choose k''") nCk_group = VGroup(n_choose_k, n_choose_k_words) nCk_group.arrange(RIGHT) nCk_group.to_edge(UP) binomials = VGroup(*[ OldTex("%d \\choose %d"%(n, k)) for k in range(n+1) ]) binomial_equations = VGroup() for k, binomial in enumerate(binomials): binomial.scale(0.75) number = OldTex(str(choose(n, k))) equation = VGroup(binomial, OldTex("="), number) equation.arrange(RIGHT, buff = SMALL_BUFF) equation.set_color(YELLOW) equation[1].set_color(WHITE) binomial_equations.add(equation) for stack, eq in zip(stacks, binomial_equations): eq.set_width(0.9*stack.get_width()) eq.next_to(stack, UP) mover = VGroup() for eq in binomial_equations: point = VectorizedPoint(n_choose_k.get_center()) group = VGroup(n_choose_k, point, point).copy() group.target = eq mover.add(group) self.play(FadeIn(nCk_group)) self.play(LaggedStartMap( MoveToTarget, mover, run_time = 3, )) self.remove(mover) self.add(binomial_equations) self.wait() self.set_variables_as_attrs( n_choose_k, n_choose_k_words, binomial_equations ) def show_binomial_name(self): new_words = OldTexText("``Binomial coefficients''") new_words.move_to(self.n_choose_k_words, LEFT) self.play(Transform(self.n_choose_k_words, new_words)) self.wait(2) def issolate_single_stack(self): stack = self.stacks[3] equation = self.binomial_equations[3] to_fade = VGroup(*self.stacks) to_fade.add(*self.binomial_equations) to_fade.add(self.n_choose_k, self.n_choose_k_words) to_fade.remove(stack, equation) self.play( FadeOut(to_fade), equation.scale, 1.5, equation.get_bottom(), ) self.wait() for line in stack: ones = VGroup(*[mob for mob in line if "1" in mob.get_tex()]) line.ones = ones self.play(LaggedStartMap( ApplyMethod, ones, lambda mob : (mob.set_color, YELLOW), rate_func = there_and_back, lag_ratio = 0.7, run_time = 1, )) def count_chosen_stack(self): stack = self.stacks[3] for i, line in enumerate(stack): number = OldTex(str(i+1)) number.next_to(stack, LEFT) brace = Brace(VGroup(*stack[:i+1]), LEFT) number.next_to(brace, LEFT) line.save_state() line.set_color(YELLOW) self.add(number, brace) self.wait(0.25) self.remove(number, brace) line.restore() self.add(number, brace) self.wait() self.set_variables_as_attrs( stack_brace = brace, stack_count = number ) def count_ways_to_fill_slots(self): lines = VGroup(*[Line(ORIGIN, 0.25*RIGHT) for x in range(5)]) lines.arrange(RIGHT) lines.next_to(self.stacks[3], LEFT, LARGE_BUFF, UP) self.play(ShowCreation(lines)) count = 1 for indices in it.combinations(list(range(5)), 3): ones = VGroup(*[ self.get_obj1().next_to(lines[i], UP) for i in indices ]) num = OldTex(str(count)) num.next_to(lines, DOWN) self.add(ones, num) self.wait(0.35) self.remove(ones, num) count += 1 self.add(num, ones) self.wait() self.play(*list(map(FadeOut, [lines, num, ones]))) def walk_though_notation(self): equation = self.binomial_equations[3] rect = SurroundingRectangle(equation[0]) rect.set_color(WHITE) words = OldTexText("``5 choose 3''") words.next_to(rect, UP) self.play(Write(words)) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.wait(2) def emphasize_pattern_over_number(self): morty = Mortimer().flip() morty.to_corner(DOWN+LEFT) words = OldTexText("Remember the pattern \\\\ not the number") words.next_to(morty, UP) words.shift_onto_screen() self.play(FadeIn(morty)) self.play( morty.change, "speaking", Write(words, run_time = 2) ) self.play( Blink(morty), morty.change, "happy" ) self.revert_to_original_skipping_status() last_ones = VGroup() last_ones.save_state() for x in range(2): for line in self.stacks[3]: ones = line.ones ones.save_state() self.play( ones.set_color, YELLOW, last_ones.restore, morty.look_at, ones, run_time = 0.25 ) last_ones = ones self.wait() #### def get_obj1(self): return OldTex("1").set_color(self.one_color) def get_obj2(self): return OldTex("0").set_color(self.zero_color) class SixChooseThreeExample(InitialFiveChooseThreeExample): CONFIG = { "n" : 6, "k" : 3, "stack_height" : 7, } def construct(self): self.show_stack() self.talk_through_one_line() self.count_stack() self.think_about_pattern() def show_stack(self): stack = get_stack( self.get_obj1(), self.get_obj2(), self.n, self.k, vertical_buff = SMALL_BUFF ) stack.set_height(self.stack_height) stack.to_edge(DOWN) for line in stack: line.ones = VGroup(*[mob for mob in line if "1" in mob.get_tex()]) equation = OldTex( "{%d \\choose %d}"%(self.n, self.k), "=", str(choose(self.n, self.k)) ) equation.set_color(YELLOW) equation.set_color_by_tex("=", WHITE) equation.next_to(stack, RIGHT, LARGE_BUFF) self.add(equation) self.play(LaggedStartMap( FadeIn, stack, lag_ratio = 0.1, run_time = 10, )) self.wait() self.set_variables_as_attrs(stack) def talk_through_one_line(self): line = self.stack[8] line.save_state() distance = FRAME_X_RADIUS/2 self.play(line.shift, distance*LEFT) brace = Brace(line, UP) n_options = OldTexText(str(self.n), "options") n_options.set_color_by_tex(str(self.n), YELLOW) n_options.next_to(brace, UP) arrows = VGroup(*[ Vector(0.5*UP).next_to(one, DOWN, SMALL_BUFF) for one in line.ones ]) arrows.set_color(self.one_color) choose_k = OldTexText("Choose", str(self.k), "of them") choose_k.set_color_by_tex(str(self.k), YELLOW) choose_k.next_to(arrows, DOWN) self.play( GrowFromCenter(brace), Write(n_options), run_time = 1 ) self.play( LaggedStartMap(GrowArrow, arrows), Write(choose_k, run_time = 1) ) self.wait(2) self.play( line.restore, *list(map(FadeOut, [brace, n_options, arrows, choose_k])) ) def count_stack(self): stack = self.stack for i, line in enumerate(stack): brace = Brace(VGroup(*stack[:i+1]), LEFT) num = OldTex(str(i+1)) num.next_to(brace, LEFT) line.ones.save_state() line.ones.set_color(YELLOW) line.ones.set_stroke(RED, 1) self.add(brace, num) self.wait(0.15) self.remove(brace, num) line.ones.restore() self.add(brace, num) self.wait() lhs = OldTex( "\\frac{6 \\cdot 5 \\cdot 3}{1 \\cdot 2 \\cdot 3} =" ) lhs.next_to(num, LEFT) coming_soon = OldTexText("Coming soon...") coming_soon.next_to(lhs, UP) coming_soon.set_color(MAROON_B) self.play(*list(map(FadeIn, [lhs, coming_soon]))) self.wait() self.play( ApplyMethod( lhs.shift, 0.65*FRAME_X_RADIUS*(LEFT+UP), path_arc = np.pi/2, rate_func = running_start, remover = True, ), *list(map(FadeOut, [brace, num, coming_soon])) ) self.wait() def think_about_pattern(self): self.revert_to_original_skipping_status() last_ones = VGroup() last_ones.save_state() for x in range(2): for line in self.stack: ones = line.ones ones.save_state() self.play( ones.set_color, YELLOW, ones.set_stroke, RED, 1, last_ones.restore, run_time = 0.2 ) last_ones = ones self.wait() class SixChooseThreeInOtherContext(Scene): def construct(self): self.add_dots() self.count_paths_to_three_three() def add_dots(self): n = 4 dots = VGroup(*[Dot() for x in range(n**2)]) dots.arrange_in_grid(n, n, buff = LARGE_BUFF) dots.next_to(ORIGIN, LEFT) self.add(dots) self.dots = dots self.dot_to_dot_distance = get_norm( dots[1].get_center() - dots[0].get_center() ) def count_paths_to_three_three(self): dots = self.dots d = self.dot_to_dot_distance lower_left = dots.get_corner(DOWN+LEFT) lower_left += dots[0].radius*(UP+RIGHT) right = Vector(d*RIGHT, color = PINK) up = Vector(d*UP, color = BLUE) last_rights = None last_ups = None last_line = None for indices in it.combinations(list(range(6)), 3): bools = [i in indices for i in range(6)] arrows = VGroup(*[ right.deepcopy() if b else up.deepcopy() for b in bools ]) last_point = np.array(lower_left) ups, rights = VGroup(), VGroup() for arrow, b in zip(arrows, bools): arrow.shift(last_point - arrow.get_start()) last_point = arrow.get_end() group = rights if b else ups group.add(arrow) line = VGroup(*[arrow.tip.copy() for arrow in arrows]) line.arrange(RIGHT, buff = 0.5*SMALL_BUFF) if last_line is None: line.shift(FRAME_X_RADIUS*RIGHT/2) line.to_edge(UP) self.play( ShowCreation(arrows), ShowCreation(line) ) else: line.next_to(last_line, DOWN, SMALL_BUFF) self.play( FadeIn(line), ReplacementTransform(last_rights, rights), ReplacementTransform(last_ups, ups), ) last_rights = rights last_ups = ups last_line = line self.wait() # class Introduction(Scene): # CONFIG = { # "start_n" : 4, # } # def construct(self): # self.write_n_choose_k() # self.show_binomial_coefficients() # self.perform_shift() # def write_n_choose_k(self): # symbol = OldTex("n \\choose k") # words = OldTexText("``n choose k''") # group = VGroup(symbol, words) # group.arrange(RIGHT) # self.play( # FadeIn(symbol), # Write(words) # ) # self.wait() # self.set_variables_as_attrs(n_choose_k_group = group) # def show_binomial_coefficients(self): # n = self.start_n # n_choose_k, n_choose_k_words = self.n_choose_k_group # binomials = VGroup(*[ # OldTex("%d \\choose %d"%(n, k)) # for k in range(n+1) # ]) # binomial_equations = VGroup() # for k, binomial in enumerate(binomials): # binomial.scale(0.75) # number = OldTex(str(choose(n, k))) # equation = VGroup(binomial, OldTex("="), number) # equation.arrange(RIGHT, buff = SMALL_BUFF) # equation.set_color(YELLOW) # equation[1].set_color(WHITE) # binomial_equations.add(equation) # new_words = OldTexText("``Binomial coefficients''") # stacks = get_stacks( # OldTex("x").set_color(BLUE), # OldTex("y").set_color(RED), # n # ) # stacks.to_edge(DOWN, buff = LARGE_BUFF) # for stack, eq in zip(stacks, binomial_equations): # eq.set_width(0.9*stack.get_width()) # eq.next_to(stack, UP) # self.play( # FadeIn(stacks, run_time = 2, lag_ratio = 0.5), # self.n_choose_k_group.to_edge, UP # ) # new_words.move_to(n_choose_k_words, LEFT) # self.play(Transform(n_choose_k_words, new_words)) # for eq in binomial_equations: # point = VectorizedPoint(n_choose_k.get_center()) # self.play(ReplacementTransform( # VGroup(n_choose_k, point, point).copy(), # eq # )) # self.wait() # self.set_variables_as_attrs(stacks, binomial_equations) # def perform_shift(self): # n = self.start_n # to_fade = VGroup( # self.n_choose_k_group, # self.binomial_equations # ) # stacks = self.stacks # top_stacks = stacks.copy() # top_stacks.to_edge(UP, buff = MED_SMALL_BUFF) # line = Line(LEFT, RIGHT, color = WHITE) # line.scale(FRAME_X_RADIUS) # line.next_to(top_stacks, DOWN) # x = OldTex("x").set_color(BLUE) # y = OldTex("y").set_color(RED) # add_x, add_y = [ # OldTexText("Prepend", "$%s$"%s).set_color_by_tex(s, color) # for s, color in ("x", BLUE), ("y", RED) # ] # add_x.to_corner(UP+LEFT) # add_y.to_edge(LEFT).shift(MED_SMALL_BUFF*DOWN) # new_stacks, new_top_stacks = [ # get_stacks(x, y, n, fixed_start = var) # for var in y, x # ] # new_top_stacks.to_edge(UP, buff = MED_SMALL_BUFF) # new_stacks.to_edge(DOWN) # for s in new_stacks, new_top_stacks: # s.start_terms = VGroup() # for stack in s: # for term in stack: # s.start_terms.add(term[0]) # s_to_s_distance = \ # new_stacks[1].get_center()[0] - \ # new_stacks[0].get_center()[0] # self.play( # FadeOut(to_fade), # stacks.to_edge, DOWN, # ReplacementTransform(stacks.copy(), top_stacks), # ) # self.play(ShowCreation(line)) # self.play(Write(add_x, run_time = 1)) # self.play(Transform(top_stacks, new_top_stacks)) # self.play(LaggedStartMap( # Indicate, new_top_stacks.start_terms, # rate_func = there_and_back, # run_time = 1, # remover = True # )) # self.wait() # self.play(Write(add_y, run_time = 1)) # self.play(Transform(stacks, new_stacks)) # self.play(LaggedStartMap( # Indicate, new_stacks.start_terms, # rate_func = there_and_back, # run_time = 1, # remover = True # )) # self.wait() # self.play( # top_stacks.shift, s_to_s_distance*RIGHT/2, # stacks.shift, s_to_s_distance*LEFT/2, # ) # self.play(*map(FadeOut, [add_x, add_y, line])) # point = VectorizedPoint() # point.move_to(top_stacks[0].get_bottom()) # point.shift(s_to_s_distance*LEFT) # top_stacks.add_to_back(point) # point = VectorizedPoint() # point.move_to(stacks[-1].get_bottom()) # point.shift(s_to_s_distance*RIGHT) # point.shift(MED_SMALL_BUFF*DOWN) # stacks.add(point) # for k, stack, top_stack in zip(it.count(), stacks, top_stacks): # top_stack.generate_target() # top_stack.target.next_to(stack, UP, MED_SMALL_BUFF) # # term = OldTex( # # str(choose(n+1, k)), # # "x^%d"%(n+1-k), # # "y^%d"%k # # ) # term = OldTex( # "{%d \\choose %d}"%(n+1, k), # "=", # str(choose(n+1, k)) # ) # term[0].scale(0.85, about_point = term[0].get_right()) # term[0].set_color(YELLOW) # term[2].set_color(YELLOW) # term.scale(0.85) # term.next_to(top_stack.target, UP) # self.play(MoveToTarget(top_stack)) # self.play(Write(term)) # self.wait() # class DifferentWaysToThinkAboutNChooseK(Scene): # CONFIG = { # "n" : 5, # "k" : 3, # "stack_height" : 5, # } # def construct(self): # self.add_n_choose_k_term() # self.add_stack() # self.choose_k() # self.split_stack_by_start() # self.split_choices_by_start() # def add_n_choose_k_term(self): # term = OldTex("{5 \\choose 3} = 10") # term.to_edge(UP) # self.play(FadeIn(term, lag_ratio = 0.5)) # self.wait() # self.n_choose_k_term = term # def add_stack(self): # n, k = self.n, self.k # x = OldTex("x").set_color(BLUE) # y = OldTex("y").set_color(RED) # stack = get_stack(x, y, n, k) # stack.set_height(self.stack_height) # stack.shift(FRAME_X_RADIUS*LEFT/2) # stack.to_edge(DOWN) # numbers = VGroup(*[ # OldTex("%d"%(d+1)) # for d in range(choose(n, k)) # ]) # numbers.next_to(stack, UP) # last_number = None # for term, number in zip(stack, numbers): # self.add(term, number) # if last_number: # self.remove(last_number) # self.wait(0.25) # last_number = number # self.wait() # self.stack = stack # self.stack_count = last_number # self.numbers = numbers # def choose_k(self): # n, k = self.n, self.k # letter_set = OldTex( # "(", # "A", ",", # "B", ",", # "C", ",", # "D", ",", # "E", ")" # ) # letters = VGroup(*letter_set[1::2]) # letter_set.shift(FRAME_X_RADIUS*RIGHT/2) # letter_set.to_edge(UP) # letter_subsets = list(it.combinations(letters, k)) # subset_mobs = VGroup(*[ # VGroup(*letter_subset).copy().arrange( # RIGHT, buff = SMALL_BUFF # ) # for letter_subset in letter_subsets # ]).arrange(DOWN, buff = MED_SMALL_BUFF) # subset_mobs.set_height(self.stack_height) # subset_mobs.shift(FRAME_X_RADIUS*RIGHT/2) # subset_mobs.to_edge(DOWN) # choose_words = OldTexText("Choose %d"%k) # choose_words.scale(0.9) # choose_words.next_to(letter_set, DOWN) # choose_words.set_color(YELLOW) # self.revert_to_original_skipping_status() # self.play(Write(letter_set, run_time = 1)) # self.play( # Write(choose_words, run_time = 1), # LaggedStartMap(FadeIn, subset_mobs) # ) # self.wait() # for subset, subset_mob in zip(letter_subsets, subset_mobs): # VGroup(subset_mob, *subset).set_color(BLUE) # self.wait(0.5) # VGroup(*subset).set_color(WHITE) # self.wait() # self.set_variables_as_attrs( # subset_mobs, letter_set, choose_words, # ) # def split_stack_by_start(self): # n, k = self.n, self.k # stack = self.stack # stack_count = self.stack_count # top_num = choose(n-1, k-1) # top_stack = VGroup(*stack[:top_num]) # bottom_stack = VGroup(*stack[top_num:]) # self.play( # FadeOut(stack_count), # top_stack.shift, UP # ) # for stack, new_k in (top_stack, k-1), (bottom_stack, k): # brace = Brace(stack, RIGHT) # brace_tex = brace.get_tex( # "{%d \\choose %d} = %d"%(n-1, new_k, choose(n-1, new_k)) # ) # rect = SurroundingRectangle(VGroup(*[ # VGroup(*term[1:]) # for term in stack # ]), buff = 0.5*SMALL_BUFF) # rect.set_stroke(WHITE, 2) # self.play( # GrowFromCenter(brace), # Write(brace_tex), # ShowCreation(rect) # ) # self.wait() # def split_choices_by_start(self): # subset_mobs = self.subset_mobs # subset_mobs.generate_target() # subset_mobs.target.shift(LEFT) # brace = Brace(subset_mobs.target, RIGHT) # expression = brace.get_tex( # "\\frac{5 \\cdot 4 \\cdot 3}{1 \\cdot 2 \\cdot 3}", # "= 10" # ) # self.play( # MoveToTarget(subset_mobs), # GrowFromCenter(brace) # ) # self.play(Write(expression)) # self.wait() # class FormulaVsPattern(TeacherStudentsScene): # def construct(self): # self.show_formula() # self.show_pattern() # def show_formula(self): # formula = OldTex( # "{n \\choose k} = {n! \\over (n-k)!k!}", # ) # for i in 1, 5, 9: # formula[i].set_color(BLUE) # for i in 2, 11, 14: # formula[i].set_color(YELLOW) # self.student_thinks(formula, index = 1) # self.play(self.teacher.change, "sassy") # self.wait(2) # self.play( # FadeOut(self.students[1].bubble), # FadeOut(formula), # self.teacher.change, "raise_right_hand", # self.change_students(*["pondering"]*3) # ) # def show_pattern(self): # words = OldTexText( # "What is the \\\\ probability of a flush?" # ) # values = random.sample(PlayingCard.CONFIG["possible_values"], 5) # cards = VGroup(*[ # PlayingCard(value = value, suit = "hearts") # for value in values # ]) # cards.arrange(RIGHT) # cards.to_corner(UP+RIGHT) # words.next_to(cards, LEFT) # words.shift_onto_screen() # self.play(LaggedStartMap(DrawBorderThenFill, cards)) # self.play(Write(words)) # self.wait(3) class ProbabilityOfKWomenInGroupOfFive(Scene): CONFIG = { "random_seed" : 0, "n_people_per_lineup" : 5, "n_examples" : 18, "item_line_width" : 0.4, } def construct(self): self.ask_question() self.show_all_possibilities() self.stack_all_choices_by_number_of_women() self.go_through_stacks() self.remember_this_sensation() self.show_answer_to_question() self.ask_about_pattern() def ask_question(self): title = OldTexText("5 randomly chosen people") title.to_edge(UP) self.add(title) lineup_point = 1.5*UP prob_words = VGroup(*[ OldTexText( "Probability of", str(n), "women?" ).set_color_by_tex(str(n), YELLOW) for n in range(self.n_people_per_lineup+1) ]) prob_words.arrange(DOWN) prob_words.next_to(lineup_point, DOWN, MED_LARGE_BUFF) def get_lineup(): lineup = self.get_random_lineup_of_men_and_women() lineup.scale(1.5) lineup.move_to(lineup_point, DOWN) return lineup last_lineup = get_lineup() self.play(LaggedStartMap(FadeIn, last_lineup, run_time = 1)) for x in range(self.n_examples): lineup = get_lineup() anims = [last_lineup.items.fade, 1] anims += list(map(GrowFromCenter, lineup.items)) if x >= 12 and x-12 < len(prob_words): anims.append(FadeIn(prob_words[x-12])) self.play(*anims, run_time = 0.75) self.remove(last_lineup) self.add(lineup) self.wait(0.25) last_lineup = lineup self.title = title self.prob_words = prob_words self.lineup = last_lineup def show_all_possibilities(self): man, woman = Male(), Female() vects = [ 1.5*UP, 0.65*UP, 0.25*UP, 3.5*RIGHT, 1.5*RIGHT, ] lineup_groups = VGroup() for k in range(6): lineup_group = VGroup() for tup in it.product(*[[woman, man]]*k): lineup = self.get_lineup(*list(tup) + (5-k)*[None]) lineup.scale(1.4*(0.9)**k) lineup.move_to(0.5*DOWN) for mob, vect in zip(tup, vects): if mob is woman: lineup.shift(vect) else: lineup.shift(-vect) lineup_group.add(lineup) lineup_groups.add(lineup_group) n_possibilities = OldTex( "2 \\cdot", "2 \\cdot", "2 \\cdot", "2 \\cdot", "2", "\\text{ Possibilities}" ) n_possibilities.next_to(self.title, DOWN) twos = VGroup(*n_possibilities[-2::-1]) twos.set_color(YELLOW) two_anims = [ ReplacementTransform( VectorizedPoint(twos[0].get_center()), twos[0] ) ] + [ ReplacementTransform(t1.copy(), t2) for t1, t2 in zip(twos, twos[1:]) ] curr_lineup_group = lineup_groups[0] self.play( ReplacementTransform(self.lineup, curr_lineup_group[0]), FadeOut(self.prob_words) ) for i, lineup_group in enumerate(lineup_groups[1:]): anims = [ReplacementTransform(curr_lineup_group, lineup_group)] anims += two_anims[:i+1] if i == 0: anims.append(FadeIn(n_possibilities[-1])) self.remove(twos) self.play(*anims) men, women = VGroup(), VGroup() for lineup in lineup_group: item = lineup.items[i] if "female" in item.get_tex(): women.add(item) else: men.add(item) for group in men, women: self.play(LaggedStartMap( ApplyMethod, group, lambda m : (m.shift, MED_SMALL_BUFF*RIGHT), rate_func = there_and_back, lag_ratio = 0.9**i, run_time = 1, )) self.wait() curr_lineup_group = lineup_group self.lineups = curr_lineup_group eq_32 = OldTex("=", "32") eq_32.move_to(twos.get_right()) eq_32.set_color_by_tex("32", YELLOW) self.play( n_possibilities[-1].next_to, eq_32, RIGHT, twos.next_to, eq_32, LEFT, FadeIn(eq_32), ) self.wait() n_possibilities.add(*eq_32) self.set_variables_as_attrs(n_possibilities) def stack_all_choices_by_number_of_women(self): lineups = self.lineups stacks = VGroup(*[VGroup() for x in range(6)]) for lineup in lineups: lineup.women = VGroup(*[m for m in lineup.items if "female" in m.get_tex()]) stacks[len(lineup.women)].add(lineup) stacks.generate_target() stacks.target.scale(0.75) for stack in stacks.target: stack.arrange(DOWN, buff = 1.5*SMALL_BUFF) stacks.target.arrange( RIGHT, buff = MED_LARGE_BUFF, aligned_edge = DOWN ) stacks.target.to_edge(DOWN) self.play(MoveToTarget( stacks, run_time = 2, path_arc = np.pi/2 )) self.wait() self.stacks = stacks def go_through_stacks(self): stacks = self.stacks n = len(stacks) - 1 equations = VGroup() for k, stack in enumerate(stacks): items = VGroup() lines = VGroup() women = VGroup() for lineup in stack: items.add(lineup.items) lines.add(lineup.lines) for item in lineup.items: if "female" in item.get_tex(): women.add(item) equation = OldTex( "{%d \\choose %d}"%(n, k), "=", str(len(stack)) ) equation[0].scale(0.6) equation.arrange(RIGHT, SMALL_BUFF) equation.set_color(YELLOW) equation.set_color_by_tex("=", WHITE) equation.next_to(stack, UP) equations.add(equation) self.play( items.set_fill, None, 1, lines.set_stroke, WHITE, 3, Write(equation, run_time = 1) ) self.play(LaggedStartMap(Indicate, women, rate_func = there_and_back)) self.wait() self.equations = equations self.numbers = VGroup(*[eq[-1] for eq in equations]) def remember_this_sensation(self): n_possibilities = self.n_possibilities n_possibilities_rect = SurroundingRectangle(n_possibilities) twos = VGroup(*n_possibilities[:5]) numbers = self.numbers self.play(ShowCreation(n_possibilities_rect)) self.play(LaggedStartMap( Indicate, twos, rate_func = wiggle )) self.play(FadeOut(n_possibilities_rect)) for number in numbers: self.play(Indicate(number, color = PINK, run_time = 0.5)) self.wait() def show_answer_to_question(self): stacks = self.stacks numbers = self.numbers n_possibilities = VGroup( self.n_possibilities[-1], self.n_possibilities[-3] ) n_possibilities_part_to_fade = VGroup( self.n_possibilities[-2], *self.n_possibilities[:-3] ) total = n_possibilities[-1] title = self.title n = self.n_people_per_lineup self.play( FadeOut(title), FadeOut(n_possibilities_part_to_fade), n_possibilities.to_corner, UP+RIGHT ) for k, stack, num in zip(it.count(), stacks, numbers): rect = SurroundingRectangle(stack) num.save_state() prob_words = OldTex( "P(", "\\#", "\\female", "=", str(k), ")" "=", "{\\quad \\over", "32}", "\\approx", "%0.3f"%(choose(n, k)/32.0) ) prob_words.set_color_by_tex_to_color_map({ "female" : MAROON_B, "32" : YELLOW, }) frac_line = prob_words.get_parts_by_tex("over") prob_words.to_corner(UP+LEFT) self.play( num.next_to, frac_line, UP, SMALL_BUFF, FadeIn(prob_words) ) self.play(ShowCreation(rect)) self.wait(2) self.play( num.restore, FadeOut(rect), FadeOut(prob_words) ) def ask_about_pattern(self): question = OldTexText("Where do these \\\\ numbers come from?") question.to_edge(UP) numbers = self.numbers circles = VGroup(*[ Circle().replace(num, dim_to_match = 1).scale(1.5) for num in numbers ]) circles.set_color(WHITE) self.play(LaggedStartMap(FadeIn, question)) self.play(LaggedStartMap(ShowCreationThenDestruction, circles)) self.wait(2) ###### def get_random_lineup_of_men_and_women(self): man, woman = Male(), Female() lineup = self.get_lineup(*[ woman if random.choice([True, False]) else man for y in range(self.n_people_per_lineup) ]) return lineup def get_lineup(self, *mobjects, **kwargs): buff = kwargs.get("buff", MED_SMALL_BUFF) lines = VGroup(*[ Line(ORIGIN, self.item_line_width*RIGHT) for mob in mobjects ]) lines.arrange(RIGHT, buff = buff) items = VGroup() for line, mob in zip(lines, mobjects): item = VectorizedPoint() if mob is None else mob.copy() item.next_to(line, UP, SMALL_BUFF) items.add(item) result = VGroup(lines, items) result.lines = lines result.items = items return result class AskAboutAllPossibilities(ProbabilityOfKWomenInGroupOfFive): def construct(self): man, woman = Male(), Female() all_lineups = VGroup() for bits in it.product(*[[False, True]]*5): mobs = [ woman.copy() if bit else man.copy() for bit in bits ] all_lineups.add(self.get_lineup(*mobs)) brace = Brace(all_lineups, UP) question = brace.get_text("What are all possibilities?") self.add(brace, question) for lineup in all_lineups: self.add(lineup) self.wait(0.25) self.remove(lineup) class RememberThisSensation(TeacherStudentsScene): def construct(self): self.teacher_says("Remember this \\\\ sensation") self.play_student_changes("confused", "pondering", "erm") self.wait(2) class TeacherHoldingSomething(TeacherStudentsScene): def construct(self): self.play( self.teacher.change, "raise_right_hand", ) self.play_student_changes( *["pondering"]*3, look_at = 2*UP+2*RIGHT ) self.wait(6) # class GroupsOf6(Scene): # def construct(self): # title = OldTex("2^6 =", "64", "\\text{ Possibilities}") # title.to_edge(UP, buff = MED_SMALL_BUFF) # title.set_color_by_tex("64", YELLOW) # man, woman = Male(), Female() # stacks = get_stacks(man, woman, 6, vertical_buff = SMALL_BUFF) # stacks.set_height(6.25) # stacks.to_edge(DOWN, buff = MED_SMALL_BUFF) # women_groups = VGroup() # for stack in stacks: # for lineup in stack: # group = VGroup() # for item in lineup: # if "female" in item.get_tex(): # group.add(item) # women_groups.add(group) # numbers = VGroup() # for stack in stacks: # number = OldTex(str(len(stack))) # number.next_to(stack, UP, SMALL_BUFF) # numbers.add(number) # self.add(title) # self.play(LaggedStartMap( # LaggedStartMap, stacks, # lambda s : (FadeIn, s), # run_time = 3, # )) # self.play(Write(numbers, run_time = 3)) # self.wait() # self.play(LaggedStartMap( # ApplyMethod, women_groups, # lambda m : (m.set_color, PINK), # lag_ratio = 0.1, # rate_func = wiggle, # run_time = 6, # )) # class GroupsOf7(Scene): # def construct(self): # stack = get_stack(Male(), Female(), 7, 3) # question = OldTexText( # "How many groups \\\\ of 7 with 3 ", "$\\female$", "?" # ) # question.set_color_by_tex("female", MAROON_B) # question.shift(1.5*UP) # self.add(question) # for n, item in enumerate(stack): # item.center() # number = OldTex(str(n)) # number.next_to(ORIGIN, DOWN, LARGE_BUFF) # self.add(item, number) # self.wait(0.2) # self.remove(item, number) # self.add(item, number) # self.wait(2) class BuildFiveFromFour(ProbabilityOfKWomenInGroupOfFive): def construct(self): self.show_all_configurations_of_four() self.organize_into_stacks() self.walk_through_stacks() self.split_into_two_possibilities() self.combine_stacks() def show_all_configurations_of_four(self): man, woman = Male(), Female() n = 4 vects = [ 1.5*UP, 0.5*UP, 3.5*RIGHT, 1.5*RIGHT, ] lineup_groups = VGroup() for k in range(n+1): lineup_group = VGroup() for tup in it.product(*[[man, woman]]*k): lineup = self.get_lineup(*list(tup) + (n-k)*[None]) lineup.scale(1.4*(0.9)**k) lineup.move_to(0.5*DOWN) for mob, vect in zip(tup, vects): if mob is woman: lineup.shift(vect) else: lineup.shift(-vect) lineup_group.add(lineup) lineup_groups.add(lineup_group) n_possibilities = OldTex( "2 \\cdot", "2 \\cdot", "2 \\cdot", "2", "\\text{ Possibilities}" ) n_possibilities.to_edge(UP) twos = VGroup(*n_possibilities[-2::-1]) two_anims = [ ReplacementTransform( VectorizedPoint(twos[0].get_center()), twos[0] ) ] + [ ReplacementTransform(t1.copy(), t2) for t1, t2 in zip(twos, twos[1:]) ] curr_lineup_group = lineup_groups[0] self.play( ShowCreation(curr_lineup_group[0]), ) for i, lineup_group in enumerate(lineup_groups[1:]): anims = [ReplacementTransform(curr_lineup_group, lineup_group)] anims += two_anims[:i+1] if i == 0: anims.append(FadeIn(n_possibilities[-1])) self.remove(twos) self.play(*anims) self.wait() curr_lineup_group = lineup_group self.lineups = curr_lineup_group eq_16 = OldTex("=", "16") eq_16.move_to(twos.get_right()) eq_16.set_color_by_tex("16", YELLOW) self.play( n_possibilities[-1].next_to, eq_16, RIGHT, twos.next_to, eq_16, LEFT, FadeIn(eq_16), ) self.wait() n_possibilities.add(eq_16) self.n_possibilities = n_possibilities def organize_into_stacks(self): lineups = self.lineups stacks = VGroup(*[VGroup() for x in range(5)]) for lineup in lineups: women = [m for m in lineup.items if "female" in m.get_tex()] stacks[len(women)].add(lineup) stacks.generate_target() stacks.target.scale(0.75) for stack in stacks.target: stack.arrange(DOWN, buff = SMALL_BUFF) stacks.target.arrange( RIGHT, buff = MED_LARGE_BUFF, aligned_edge = DOWN ) stacks.target.to_edge(DOWN, buff = MED_SMALL_BUFF) self.play(MoveToTarget( stacks, run_time = 2, path_arc = np.pi/2 )) self.wait() self.stacks = stacks def walk_through_stacks(self): stacks = self.stacks numbers = VGroup() for stack in stacks: rect = SurroundingRectangle(stack) rect.set_stroke(WHITE, 2) self.play(ShowCreation(rect)) for n, lineup in enumerate(stack): lineup_copy = lineup.copy() lineup_copy.set_color(YELLOW) number = OldTex(str(n+1)) number.next_to(stack, UP) self.add(lineup_copy, number) self.wait(0.25) self.remove(lineup_copy, number) self.add(number) numbers.add(number) self.play(FadeOut(rect)) self.wait() stacks.numbers = numbers def split_into_two_possibilities(self): bottom_stacks = self.stacks top_stacks = bottom_stacks.deepcopy() top_group = VGroup(top_stacks, top_stacks.numbers) h_line = DashedLine(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT) #Initial split self.play( FadeOut(self.n_possibilities), top_group.to_edge, UP, MED_SMALL_BUFF, ) self.play(ShowCreation(h_line)) #Add extra slot for stacks, sym in (top_stacks, Female()), (bottom_stacks, Male()): sym.set_fill(opacity = 0) new_stacks = VGroup() to_fade_in = VGroup() for stack in stacks: new_stack = VGroup() for lineup in stack: new_lineup = self.get_lineup(*[ Female() if "female" in item.get_tex() else Male() for item in lineup.items ] + [sym], buff = SMALL_BUFF) new_lineup.replace(lineup, dim_to_match = 1) new_stack.add(new_lineup) for group in lineup.items, lineup.lines: point = VectorizedPoint(group[-1].get_center()) group.add(point) to_fade_in.add(lineup.items[-1]) new_stacks.add(new_stack) new_stacks.arrange( RIGHT, buff = MED_LARGE_BUFF, aligned_edge = DOWN ) new_stacks.move_to(stacks, DOWN) stacks.target = new_stacks stacks.to_fade_in = to_fade_in stacks.numbers.generate_target() for number, stack in zip(stacks.numbers.target, new_stacks): number.next_to(stack, UP) for stacks in top_stacks, bottom_stacks: self.play( MoveToTarget(stacks), MoveToTarget(stacks.numbers) ) self.wait() #Fill extra slot add_man = OldTexText("Add", "$\\male$") add_man.set_color_by_tex("male", BLUE) add_woman = OldTexText("Add", "$\\female$") add_woman.set_color_by_tex("female", MAROON_B) add_man.next_to(ORIGIN, DOWN).to_edge(LEFT) add_woman.to_corner(UP+LEFT) for stacks, words in (bottom_stacks, add_man), (top_stacks, add_woman): to_fade_in = stacks.to_fade_in to_fade_in.set_fill(opacity = 1) to_fade_in.save_state() Transform(to_fade_in, VGroup(words[-1])).update(1) self.play(Write(words, run_time = 1)) self.play(to_fade_in.restore) self.wait() #Perform shift dist = top_stacks[1].get_center()[0] - top_stacks[0].get_center()[0] self.play( top_stacks.shift, dist*RIGHT/2, top_stacks.numbers.shift, dist*RIGHT/2, bottom_stacks.shift, dist*LEFT/2, bottom_stacks.numbers.shift, dist*LEFT/2, ) self.wait() self.play(*list(map(FadeOut, [add_man, add_woman, h_line]))) self.set_variables_as_attrs(top_stacks, bottom_stacks) def combine_stacks(self): top_stacks = self.top_stacks bottom_stacks = self.bottom_stacks rects = VGroup() for stacks, color in (top_stacks, MAROON_C), (bottom_stacks, BLUE_D): for stack in stacks: rect = SurroundingRectangle(stack) rect.set_stroke(color, 2) rects.add(rect) stack.add(rect) new_numbers = VGroup() self.play(LaggedStartMap(ShowCreation, rects, run_time = 1)) for i, top_stack in enumerate(top_stacks[:-1]): bottom_stack = bottom_stacks[i+1] top_number = top_stacks.numbers[i] bottom_number = bottom_stacks.numbers[i+1] movers = top_stack, top_number, bottom_number for mob in movers: mob.generate_target() top_stack.target.move_to(bottom_stack.get_top(), DOWN) plus = OldTex("+") expr = VGroup(top_number.target, plus, bottom_number.target) expr.arrange(RIGHT, buff = SMALL_BUFF) expr.next_to(top_stack.target.get_top(), UP) new_number = OldTex(str( len(top_stack) + len(bottom_stack) - 2 )) new_number.next_to(expr, UP) new_numbers.add(new_number) self.play( Write(plus), *list(map(MoveToTarget, movers)) ) self.play( VGroup(top_stacks[-1], top_stacks.numbers[-1]).align_to, bottom_stacks, DOWN ) self.wait() new_numbers.add_to_back(bottom_stacks.numbers[0].copy()) new_numbers.add(top_stacks.numbers[-1].copy()) new_numbers.set_color(PINK) self.play(Write(new_numbers, run_time = 3)) self.wait() class BuildUpFromStart(Scene): CONFIG = { "n_iterations" : 7, } def construct(self): stacks = VGroup(VGroup(Male()), VGroup(Female())) stacks.arrange(RIGHT, buff = LARGE_BUFF) stacks.numbers = self.get_numbers(stacks) max_width = FRAME_WIDTH - 3 max_height = FRAME_Y_RADIUS - 1 self.add(stacks, stacks.numbers) for x in range(self.n_iterations): if x < 2: wait_time = 1 else: wait_time = 0.2 #Divide low_stacks = stacks low_group = VGroup(low_stacks, low_stacks.numbers) top_stacks = stacks.deepcopy() top_group = VGroup(top_stacks, top_stacks.numbers) for group, vect in (top_group, UP), (low_group, DOWN): group.generate_target() if group[0].get_height() > max_height: group.target[0].stretch_to_fit_height(max_height) for stack, num in zip(*group.target): num.next_to(stack, UP) group.target.next_to(ORIGIN, vect) self.play(*list(map(MoveToTarget, [top_group, low_group]))) self.wait(wait_time) #Expand for stacks, i in (low_stacks, 0), (top_stacks, -1): sym = stacks[i][i][i] new_stacks = VGroup() for stack in stacks: new_stack = VGroup() for line in stack: new_line = line.copy() new_sym = sym.copy() buff = 0.3*line.get_height() new_sym.next_to(line, RIGHT, buff = buff) new_line.add(new_sym) line.add(VectorizedPoint(line[-1].get_center())) new_stack.add(new_line) new_stacks.add(new_stack) new_stacks.arrange( RIGHT, buff = LARGE_BUFF, aligned_edge = DOWN ) if new_stacks.get_width() > max_width: new_stacks.stretch_to_fit_width(max_width) if new_stacks.get_height() > max_height: new_stacks.stretch_to_fit_height(max_height) new_stacks.move_to(stacks, DOWN) stacks.target = new_stacks stacks.numbers.generate_target() for num, stack in zip(stacks.numbers.target, new_stacks): num.next_to(stack, UP) self.play(*list(map(MoveToTarget, [ top_stacks, low_stacks, top_stacks.numbers, low_stacks.numbers, ]))) self.wait(wait_time) #Shift dist = top_stacks[1].get_center()[0] - top_stacks[0].get_center()[0] self.play( top_group.shift, dist*RIGHT/2, low_group.shift, dist*LEFT/2, ) self.wait(wait_time) #Stack all_movers = VGroup() plusses = VGroup() expressions = VGroup(low_stacks.numbers[0]) stacks = VGroup(low_stacks[0]) v_buff = 0.25*stacks[0][0].get_height() for i, top_stack in enumerate(top_stacks[:-1]): low_stack = low_stacks[i+1] top_num = top_stacks.numbers[i] low_num = low_stacks.numbers[i+1] movers = [top_stack, top_num, low_num] for mover in movers: mover.generate_target() plus = OldTex("+") expr = VGroup(top_num.target, plus, low_num.target) expr.arrange(RIGHT, buff = SMALL_BUFF) top_stack.target.next_to(low_stack, UP, buff = v_buff) expr.next_to(top_stack.target, UP) all_movers.add(*movers) plusses.add(plus) expressions.add(VGroup(top_num, plus, low_num)) stacks.add(VGroup(*it.chain(low_stack, top_stack))) last_group = VGroup(top_stacks[-1], top_stacks.numbers[-1]) last_group.generate_target() last_group.target.align_to(low_stacks, DOWN) all_movers.add(last_group) stacks.add(top_stacks[-1]) expressions.add(top_stacks.numbers[-1]) self.play(*it.chain( list(map(MoveToTarget, all_movers)), list(map(Write, plusses)), )) #Add new_numbers = self.get_numbers(stacks) self.play(ReplacementTransform( expressions, VGroup(*list(map(VGroup, new_numbers))) )) self.wait(wait_time) stacks.numbers = new_numbers #### def get_numbers(self, stacks): return VGroup(*[ OldTex(str(len(stack))).next_to(stack, UP) for stack in stacks ]) class IntroducePascalsTriangle(Scene): CONFIG = { "max_n" : 9, } def construct(self): self.show_triangle() self.show_sum_of_two_over_rule() self.keep_in_mind_what_these_mean() self.issolate_9_choose_4_term() self.show_9_choose_4_pattern() self.cap_off_triangle() def show_triangle(self): rows = PascalsTriangle(n_rows = self.max_n+1) self.play(FadeIn(rows[1])) for last_row, curr_row in zip(rows[1:], rows[2:]): self.play(*[ Transform( last_row.copy(), VGroup(*mobs), remover = True ) for mobs in (curr_row[1:], curr_row[:-1]) ]) self.add(curr_row) self.wait() self.rows = rows def show_sum_of_two_over_rule(self): rows = self.rows example = rows[5][3] ex_top1 = rows[4][2] ex_top2 = rows[4][3] rects = VGroup() for mob, color in (example, GREEN), (ex_top1, BLUE), (ex_top2, YELLOW): mob.rect = SurroundingRectangle(mob, color = color) rects.add(mob.rect) rows_to_fade = VGroup(*rows[1:4], *rows[6:]) rows_to_fade.save_state() top_row = rows[4] low_row = rows[5] top_row_copy = top_row.copy() top_row.save_state() top_row.add(ex_top2.rect) top_row_copy.add(ex_top1.rect) h_line = Line(LEFT, RIGHT) h_line.stretch_to_fit_width(low_row.get_width() + 2) h_line.next_to(low_row, UP, 1.5*SMALL_BUFF) plus = OldTex("+") plus.next_to(h_line.get_left(), UP+RIGHT, buff = 1.5*SMALL_BUFF) self.play(ShowCreation(example.rect)) self.play( ReplacementTransform(example.rect.copy(), ex_top1.rect), ReplacementTransform(example.rect.copy(), ex_top2.rect), ) self.wait(2) self.play(rows_to_fade.fade, 1) self.play( top_row.align_to, low_row, LEFT, top_row_copy.next_to, top_row, UP, top_row_copy.align_to, low_row, RIGHT, ) self.play( ShowCreation(h_line), Write(plus) ) self.wait(2) for row in top_row, top_row_copy: row.remove(row[-1]) self.play( rows_to_fade.restore, top_row.restore, Transform( top_row_copy, top_row.saved_state, remover = True ), FadeOut(VGroup(h_line, plus)), FadeOut(rects), ) self.wait() def keep_in_mind_what_these_mean(self): morty = Mortimer().flip() morty.scale(0.7) morty.to_edge(LEFT) morty.shift(DOWN) numbers = VGroup(*it.chain(*self.rows[1:])) random.shuffle(numbers.submobjects) self.play(FadeIn(morty)) self.play(PiCreatureSays( morty, "Keep in mind \\\\ what these mean.", bubble_config = { "width" : 3.5, "height" : 2.5, } )) self.play( Blink(morty), LaggedStartMap( Indicate, numbers, rate_func = wiggle, color = PINK, ) ) self.play(*list(map(FadeOut, [ morty, morty.bubble, morty.bubble.content ]))) def issolate_9_choose_4_term(self): rows = self.rows for n in range(1, self.max_n+1): num = rows[n][0] line = get_stack(Female(), Male(), n, 0)[0] if n < self.max_n: line.next_to(num, LEFT) else: line.next_to(num, DOWN, MED_LARGE_BUFF) self.set_color_num(num) self.add(line) if n < self.max_n: self.wait(0.25) else: self.wait(1.25) self.dehighlight_num(num) self.remove(line) for k in range(1, 5): num = rows[self.max_n][k] line = get_stack(Female(), Male(), self.max_n, k)[0] line.next_to(num, DOWN, MED_LARGE_BUFF) self.set_color_num(num) self.add(line) self.wait(0.5) self.dehighlight_num(num) self.remove(line) num.set_color(YELLOW) num.scale(1.2) self.add(line) self.wait() self.nine_choose_four_term = num self.nine_choose_four_line = line def show_9_choose_4_pattern(self): rows = VGroup(*self.rows[1:]) all_stacks = get_stacks(Female(), Male(), 9) stack = all_stacks[4] all_lines = VGroup(*it.chain(*all_stacks)) self.play( rows.shift, 3*UP, self.nine_choose_four_line.shift, 2.5*UP, ) self.remove(self.nine_choose_four_line) for n, line in enumerate(stack): line.next_to(self.nine_choose_four_term, DOWN, LARGE_BUFF) num = Integer(n+1) num.next_to(line, DOWN, MED_LARGE_BUFF) self.add(line, num) self.wait(0.1) self.remove(line, num) self.add(line, num) self.wait() self.curr_line = line #Probability expr = OldTex( "P(4", "\\female", "\\text{ out of }", "9", ")", "=" ) expr.move_to(num.get_left()) expr.set_color_by_tex("female", MAROON_B) nine_choose_four_term = self.nine_choose_four_term.copy() nine_choose_four_term.generate_target() nine_choose_four_term.target.scale(1./1.2) over_512 = OldTex("\\quad \\over 2^9") frac = VGroup(nine_choose_four_term.target, over_512) frac.arrange(DOWN, buff = SMALL_BUFF) frac.next_to(expr, RIGHT, SMALL_BUFF) eq_result = OldTex("\\approx 0.246") eq_result.next_to(frac, RIGHT) def show_random_lines(n, wait_time = 1): for x in range(n): if x == n-1: wait_time = 0 new_line = random.choice(all_lines) new_line.move_to(self.curr_line) self.remove(self.curr_line) self.curr_line = new_line self.add(self.curr_line) self.wait(wait_time) self.play(FadeOut(num), FadeIn(expr)) show_random_lines(4) self.play( MoveToTarget(nine_choose_four_term), Write(over_512) ) show_random_lines(4) self.play(Write(eq_result)) show_random_lines(6) self.play( self.nine_choose_four_term.scale, 1./1.2, self.nine_choose_four_term.set_color, WHITE, *list(map(FadeOut, [ expr, nine_choose_four_term, over_512, eq_result, self.curr_line ])) ) self.play(rows.shift, 3*DOWN) def cap_off_triangle(self): top_row = self.rows[0] circle = Circle(color = YELLOW) circle.replace(top_row, dim_to_match = 1) circle.scale(1.5) line_groups = VGroup() for n in range(4, -1, -1): line = VGroup(*[ random.choice([Male, Female])() for k in range(n) ]) if n == 0: line.add(Line(LEFT, RIGHT).scale(0.1).set_stroke(BLACK, 0)) line.arrange(RIGHT, SMALL_BUFF) line.shift(FRAME_X_RADIUS*RIGHT/2 + FRAME_Y_RADIUS*UP/2) brace = Brace(line, UP) if n == 1: label = "1 Person" else: label = "%d People"%n brace_text = brace.get_text(label) line_group = VGroup(line, brace, brace_text) line_groups.add(line_group) self.play(ShowCreation(circle)) self.play(Write(top_row)) self.wait() curr_line_group = line_groups[0] self.play(FadeIn(curr_line_group)) for line_group in line_groups[1:]: self.play(ReplacementTransform( curr_line_group, line_group )) curr_line_group = line_group self.wait() ### def set_color_num(self, num): num.set_color(YELLOW) num.scale(1.2) def dehighlight_num(self, num): num.set_color(WHITE) num.scale(1.0/1.2) class StacksApproachBellCurve(Scene): CONFIG = { "n_iterations" : 30, } def construct(self): bar = Square(side_length = 1) bar.set_fill(BLUE) bar.set_stroke(width = 0) bars = VGroup(bar) numbers = VGroup(Integer(1)) numbers.next_to(bars, UP, SMALL_BUFF) max_width = FRAME_WIDTH - 2 max_height = FRAME_Y_RADIUS - 1.5 for x in range(self.n_iterations): if x == 0: distance = 1.5 else: distance = bars[1].get_center()[0] - bars[0].get_center()[0] bars_copy = bars.copy() #Copy and shift for mob, vect in (bars, DOWN), (bars_copy, UP): mob.generate_target() if mob.target.get_height() > max_height: mob.target.stretch_to_fit_height(max_height) if mob.target.get_width() > max_width: mob.target.stretch_to_fit_width(max_width) mob.target.next_to(ORIGIN, vect, MED_LARGE_BUFF) colors = color_gradient([BLUE, YELLOW], len(bars)+1) for color, bar in zip(colors, bars.target): bar.set_fill(color) for color, bar in zip(colors[1:], bars_copy.target): bar.set_fill(color) bars_copy.set_fill(opacity = 0) numbers_copy = numbers.copy() for bs, ns in (bars, numbers), (bars_copy, numbers_copy): ns.generate_target() for bar, number in zip(bs.target, ns.target): # if number.get_width() > bar.get_width(): # number.set_width(bar.get_width()) number.next_to(bar, UP, SMALL_BUFF) self.play(*list(map(MoveToTarget, [ bars, bars_copy, numbers, numbers_copy ]))) self.play( bars.shift, distance*LEFT/2, numbers.shift, distance*LEFT/2, bars_copy.shift, distance*RIGHT/2, numbers_copy.shift, distance*RIGHT/2, ) #Stack bars_copy.generate_target() numbers.generate_target() numbers_copy.generate_target() new_numbers = VGroup() min_scale_val = 1 for i in range(len(bars)-1): top_bar = bars_copy.target[i] low_bar = bars[i+1] top_num = numbers_copy.target[i] low_num = numbers.target[i+1] new_num = Integer(top_num.number + low_num.number) if new_num.get_width() > top_bar.get_width(): min_scale_val = min( min_scale_val, top_bar.get_width() / new_num.get_width() ) new_numbers.add(new_num) top_bar.move_to(low_bar.get_top(), DOWN) new_num.next_to(top_bar, UP, SMALL_BUFF) Transform(low_num, new_num).update(1) Transform(top_num, new_num).update(1) for group in new_numbers, numbers.target[1:], numbers_copy.target[:-1]: for num in group: num.scale(min_scale_val, about_point = num.get_bottom()) if x > 1: height = numbers.target[1].get_height() for mob in numbers.target[0], numbers_copy.target[-1]: mob.set_height(height) bars_copy.target[-1].align_to(bars, DOWN) numbers_copy.target[-1].next_to(bars_copy.target[-1], UP, SMALL_BUFF) self.play(*[ MoveToTarget(mob, lag_ratio = 0.5) for mob in (bars_copy, numbers, numbers_copy) ]) self.remove(numbers, numbers_copy) numbers = VGroup(numbers[0]) numbers.add(*new_numbers) numbers.add(numbers_copy[-1]) #Resize lower bars for top_bar, low_bar in zip(bars_copy[:-1], bars[1:]): bottom = low_bar.get_bottom() low_bar.replace( VGroup(low_bar, top_bar), stretch = True ) low_bar.move_to(bottom, DOWN) bars.add(bars_copy[-1]) self.remove(bars_copy) self.add(bars) self.add(numbers) self.wait() # class IsThereABetterWayToCompute(TeacherStudentsScene): # def construct(self): # self.student_says( # "Is there a better \\\\ way to compute these?", # target_mode = "raise_left_hand", # ) # self.play_student_changes("confused", "raise_left_hand", "erm") # self.wait() # self.play(self.teacher.change_mode, "happy") # self.wait() # self.teacher_says( # "There is! But first...", # target_mode = "hooray" # ) # self.wait(2) class ChooseThreeFromFive(InitialFiveChooseThreeExample, PiCreatureScene): CONFIG = { "n" : 5, "k" : 3, "pi_creature_scale_val" : 0.3, "people_colors" : [ PURPLE, BLUE, GREEN, GOLD_E, GREY, ], } def construct(self): self.remove(self.people) self.show_binary_strings() self.add_people() self.choose_triplets() self.show_association_with_binary(3) self.show_association_with_binary(5) self.order_doesnt_matter() self.that_phrase_is_confusing() self.pattern_is_unambiguous() def show_binary_strings(self): n, k = self.n, self.k stack = get_stack( self.get_obj1(), self.get_obj2(), n, k, vertical_buff = SMALL_BUFF, ) stack.to_edge(DOWN, buff = LARGE_BUFF) equation = OldTex( "{%d \\choose %d}"%(n, k), "=", str(choose(n, k)), ) equation[0].scale(0.75, about_point = equation[0].get_right()) equation.next_to(stack, UP) for i, line in enumerate(stack): num = OldTex(str(i+1)) num.next_to(stack, UP) self.add(line, num) self.wait(0.25) self.remove(num) self.play( Write(VGroup(*equation[:-1])), ReplacementTransform(num, equation[-1]) ) self.wait() self.set_variables_as_attrs(stack, equation) def add_people(self): people = self.people names = self.get_names(people) braces = self.get_people_braces(people) self.play( Write(braces), LaggedStartMap(FadeIn, people), VGroup(self.stack, self.equation).to_edge, RIGHT, LARGE_BUFF ) self.play(LaggedStartMap(FadeIn, names)) self.set_variables_as_attrs(names, braces) def choose_triplets(self): movers = VGroup() movers.generate_target() max_name_width = max([n.get_width() for n in self.names]) for name_triplet in it.combinations(self.names, 3): mover = VGroup(*name_triplet).copy() mover.generate_target() if hasattr(self, "stack"): mover.target.set_height(self.stack[0].get_height()) for name in mover.target[:2]: name[-1].set_fill(opacity = 1) mover.target.arrange(RIGHT, MED_SMALL_BUFF) movers.add(mover) movers.target.add(mover.target) movers.target.arrange( DOWN, buff = SMALL_BUFF, aligned_edge = LEFT, ) movers.target.next_to(self.people, DOWN, MED_LARGE_BUFF) if hasattr(self, "stack"): movers.target.align_to(self.stack, UP) self.play(LaggedStartMap( MoveToTarget, movers, lag_ratio = 0.2, run_time = 4, )) self.wait() self.name_triplets = movers def show_association_with_binary(self, index): people = self.people names = self.names for mob in people, names: mob.save_state() mob.generate_target() line = self.stack[index].copy() triplet = self.name_triplets[index] triplet.save_state() line.generate_target() for bit, name in zip(line.target, self.names): bit.next_to(name, UP) line_rect = SurroundingRectangle(line) full_line_rect = SurroundingRectangle(VGroup(line, triplet)) people_rects = VGroup() for pi, name, obj in zip(people.target, names.target, line): if "1" in obj.get_tex(): rect = SurroundingRectangle(VGroup(pi, name)) people_rects.add(rect) pi.change_mode("hooray") else: pi.fade(0.5) name.fade(0.5) self.play(ShowCreation(line_rect)) self.play(MoveToTarget(line)) self.play( LaggedStartMap(ShowCreation, people_rects), MoveToTarget(people), MoveToTarget(names), ) self.wait() self.play( ReplacementTransform(line_rect, full_line_rect), triplet.set_color, YELLOW ) self.wait(2) self.play( people.restore, names.restore, triplet.restore, FadeOut(line), FadeOut(full_line_rect), FadeOut(people_rects), ) def order_doesnt_matter(self): triplet = self.name_triplets[0].copy() triplet.set_fill(opacity = 1) triplet.next_to( self.name_triplets, RIGHT, buff = LARGE_BUFF, aligned_edge = UP, ) updownarrow = OldTex("\\Updownarrow") updownarrow.set_color(YELLOW) updownarrow.next_to(triplet, DOWN, SMALL_BUFF) permutations = VGroup() for indices in it.permutations(list(range(len(triplet)))): perm = triplet.copy() resorter = VGroup(*[ perm[i] for i in indices ]) resorter.arrange(RIGHT, MED_SMALL_BUFF) resorter.next_to(updownarrow, DOWN) permutations.add(perm) words = OldTexText("``Order doesn't matter''") words.scale(0.75) words.set_color(BLUE) words.next_to(permutations, DOWN) self.play(ReplacementTransform( self.name_triplets[0].copy(), triplet )) curr_perm = permutations[0] self.play( ReplacementTransform(triplet.copy(), curr_perm), Write(updownarrow) ) for i in range(8): new_perm = permutations[i%(len(permutations)-1)+1] anims = [ Transform( curr_perm, new_perm, path_arc = np.pi, ) ] if i == 1: self.wait() if i == 4: anims.append(Write(words, run_time = 1)) self.play(*anims) self.play(*list(map(FadeOut, [triplet, curr_perm, updownarrow]))) self.order_doesnt_matter_words = words def that_phrase_is_confusing(self): odm_words = self.order_doesnt_matter_words odm_words_outline = VGroup() for letter in odm_words: mob = VMobject() mob.set_points(letter.get_points()) odm_words_outline.add(mob) odm_words_outline.set_fill(opacity = 0) odm_words_outline.set_stroke(YELLOW, 1) line = self.stack[0].copy() q_marks = OldTexText("???") q_marks.next_to(odm_words, DOWN) q_marks.set_color(YELLOW) self.play( LaggedStartMap( ShowCreationThenDestruction, odm_words_outline, lag_ratio = 0.2, run_time = 1, ), LaggedStartMap( ApplyMethod, self.people, lambda pi : (pi.change, "confused", odm_words,) ), LaggedStartMap(FadeIn, q_marks), ) self.play(line.next_to, odm_words, UP) for x in range(6): line.generate_target() resorter = VGroup(*line.target) resorter.sort(lambda p : random.random()) resorter.arrange(RIGHT, buff = SMALL_BUFF) resorter.move_to(line) self.play(MoveToTarget(line, path_arc = np.pi)) self.play(FadeOut(q_marks)) line.sort(lambda p : p[0]) words = VGroup(*list(map(TexText, ["First", "Second", "Fifth"]))) words.set_color(YELLOW) words.scale(0.75) word_arrow_groups = VGroup() for i, word in zip([0, 1, 4], words): arrow = Vector(0.5*DOWN) arrow.set_color(YELLOW) arrow.next_to(line[i], UP, SMALL_BUFF) word.next_to(arrow, UP, SMALL_BUFF) word_arrow_groups.add(VGroup(word, arrow)) for x in range(2): for i in range(len(word_arrow_groups)+1): anims = [] if i > 0: anims.append(FadeOut(word_arrow_groups[i-1])) if i < len(word_arrow_groups): anims.append(FadeIn(word_arrow_groups[i])) self.play(*anims) self.wait() word_arrow_groups.submobjects = [ word_arrow_groups[j] for j in (1, 2, 0) ] self.play(*list(map(FadeOut, [line, odm_words]))) def pattern_is_unambiguous(self): all_ones = VGroup() for line in self.stack: ones = VGroup(*[m for m in line if "1" in m.get_tex()]).copy() ones.set_color(YELLOW) all_ones.add(ones) self.play( LaggedStartMap( FadeIn, all_ones, lag_ratio = 0.2, run_time = 3, rate_func = there_and_back ), LaggedStartMap( ApplyMethod, self.people, lambda pi : (pi.change, "happy", ones), ) ) self.wait() for trip in it.combinations(self.people, 3): rects = VGroup(*list(map(SurroundingRectangle, trip))) self.add(rects) self.wait(0.3) self.remove(rects) self.wait() ### def create_pi_creatures(self): people = VGroup(*[ PiCreature(color = color).scale(self.pi_creature_scale_val) for color in self.people_colors ]) people.arrange(RIGHT) people.shift(3*LEFT) people.to_edge(UP, buff = 1.25) self.people = people return people def get_names(self, people): names = VGroup(*[ OldTexText(name + ",") for name in ("Ali", "Ben", "Cam", "Denis", "Evan") ]) for name, pi in zip(names, people): name[-1].set_fill(opacity = 0) name.scale(0.75) name.next_to(pi, UP, 2*SMALL_BUFF) pi.name = name return names def get_people_braces(self, people): group = VGroup(people, *[pi.name for pi in people]) lb, rb = braces = OldTex("\\{ \\}") braces.scale(2) braces.stretch_to_fit_height(1.3*group.get_height()) lb.next_to(group, LEFT, SMALL_BUFF) rb.next_to(group, RIGHT, SMALL_BUFF) return braces class SubsetProbabilityExample(ChooseThreeFromFive): CONFIG = { "random_seed" : 1, } def construct(self): self.setup_people() self.ask_question() self.show_all_triplets() self.circle_those_with_ali() def setup_people(self): people = self.people names = self.get_names(people) braces = self.get_people_braces(people) group = VGroup(people, names, braces) self.play(group.shift, -group.get_center()[0]*RIGHT) self.wait() self.set_variables_as_attrs(names, braces) def ask_question(self): pi_name_groups = VGroup(*[ VGroup(pi, pi.name) for pi in self.people ]) words = OldTexText( "Choose 3 people randomly.\\\\", "Probability", "Ali", "is one of them?" ) words.set_color_by_tex("Ali", self.people[0].get_color()) words.next_to(pi_name_groups, DOWN, 2*LARGE_BUFF) checkmark = OldTex("\\checkmark").set_color(GREEN) cross = OldTex("\\times").set_color(RED) for mob in checkmark, cross: mob.scale(2) mob.next_to(self.braces, DOWN, aligned_edge = LEFT) mob.shift(MED_SMALL_BUFF*LEFT) ali = pi_name_groups[0] self.play(FadeIn(words)) for x in range(4): group = VGroup(*random.sample(pi_name_groups, 3)) group.save_state() group.generate_target() group.target.shift(LARGE_BUFF*DOWN) for pi, name in group.target: pi.change("hooray", checkmark) if ali in group: symbol = checkmark rect = SurroundingRectangle( group.target[group.submobjects.index(ali)] ) rect.set_stroke(GREEN) else: symbol = cross rect = VGroup() run_time = 1 self.play( MoveToTarget(group), FadeIn(symbol), ShowCreation(rect), run_time = run_time, ) self.wait(0.5) self.play( group.restore, FadeOut(symbol), FadeOut(rect), run_time = run_time, ) self.question = words self.set_variables_as_attrs(pi_name_groups) def show_all_triplets(self): self.play( self.question.scale, 0.75, self.question.to_corner, UP+RIGHT, VGroup(self.people, self.names, self.braces).to_edge, LEFT, ) self.choose_triplets() brace = Brace(self.name_triplets, RIGHT) total_count = brace.get_tex( "{5 \\choose 3}", "=", "10", buff = MED_LARGE_BUFF ) total_count.set_color(BLUE) self.play( GrowFromCenter(brace), Write(total_count), ) self.wait() self.set_variables_as_attrs(brace, total_count) def circle_those_with_ali(self): name_triplets = self.name_triplets five_choose_three, equals, ten = self.total_count names = self.names with_ali = VGroup(*name_triplets[:6]) alis = VGroup(*[group[0] for group in with_ali]) rect = SurroundingRectangle(with_ali) frac_lines = VGroup() for vect in LEFT, RIGHT: frac_line = OldTex("\\quad \\over \\quad") if vect is LEFT: frac_line.stretch(1.5, 0) frac_line.next_to(equals, vect) frac_lines.add(frac_line) four_choose_two = OldTex("4 \\choose 2") four_choose_two.next_to(frac_lines[0], UP, SMALL_BUFF) six = OldTex("6") six.next_to(frac_lines[1], UP, SMALL_BUFF) self.play( ShowCreation(rect), alis.set_color, YELLOW ) for pair in it.combinations(names[1:], 2): arrows = VGroup() for pi in pair: arrow = Vector(0.5*DOWN, color = YELLOW) arrow.next_to(pi, UP) arrows.add(arrow) self.add(arrows) self.wait(0.5) self.remove(arrows) self.add(arrows) self.wait() self.play( FadeIn(frac_lines), five_choose_three.next_to, frac_lines[0], DOWN, SMALL_BUFF, ten.next_to, frac_lines[1], DOWN, SMALL_BUFF, Write(four_choose_two) ) self.wait() self.play(ReplacementTransform( four_choose_two.copy(), six )) self.play(FadeOut(arrows)) for x in range(20): name_rect = SurroundingRectangle(random.choice(name_triplets)) name_rect.set_color(BLUE) name_rect.set_fill(BLUE, opacity = 0.25) self.play(Animation(name_rect, run_time = 0)) self.wait(0.25) self.remove(name_rect) class StudentsGetConfused(PiCreatureScene): def construct(self): pi1, pi2 = self.pi_creatures line = VGroup( Male(), Female(), Female(), Male(), Female() ) width = line.get_width() for i, mob in enumerate(line): mob.shift((i*width+SMALL_BUFF)*RIGHT) line.scale(1.5) line.arrange(RIGHT, SMALL_BUFF) line.move_to(self.pi_creatures, UP) self.add(line) self.play( self.get_shuffle_anim(line), PiCreatureSays( pi1, "Wait \\dots order matters now?", target_mode = "confused", look_at = line ) ) self.play( self.get_shuffle_anim(line), *[ ApplyMethod(pi.change, "confused", line) for pi in self.pi_creatures ] ) for x in range(4): self.play(self.get_shuffle_anim(line)) self.wait() def create_pi_creatures(self): pis = VGroup(*[ Randolph(color = color) for color in (BLUE_D, BLUE_B) ]) pis[1].flip() pis.arrange(RIGHT, buff = 5) pis.to_edge(DOWN) return pis def get_shuffle_anim(self, line): indices = list(range(len(line))) random.shuffle(indices) line.generate_target() for i, m in zip(indices, line.target): m.move_to(line[i]) return MoveToTarget(line, path_arc = np.pi) class HowToComputeNChooseK(ChooseThreeFromFive): CONFIG = { "n" : 5, "k" : 3, "line_colors" : [GREEN, YELLOW], "n_permutaitons_to_show" : 5, } def construct(self): self.force_skipping() self.setup_people() self.choose_example_ordered_triplets() self.count_possibilities() self.show_permutations_of_ABC() self.count_permutations_of_ABC() self.reset_stage() self.show_whats_being_counted() self.revert_to_original_skipping_status() self.indicate_final_answer() def setup_people(self): people = self.people names = self.get_names(people) braces = self.get_people_braces(people) people_group = VGroup(people, names, braces) people_group.center().to_edge(UP, buff = MED_LARGE_BUFF) self.add(people_group) self.set_variables_as_attrs( names, people_group, people_braces = braces ) def choose_example_ordered_triplets(self): n, k = self.n, self.k names = self.names lines, place_words = self.get_lines_and_place_words() for x in range(3): chosen_names = VGroup(*random.sample(names, k)) chosen_names.save_state() for name, line, word in zip(chosen_names, lines, place_words): name.generate_target() name.target.next_to(line, UP, SMALL_BUFF) anims = [MoveToTarget(name)] if x == 0: anims += [ShowCreation(line), FadeIn(word)] self.play(*anims) self.wait() self.play(chosen_names.restore) self.wait() self.set_variables_as_attrs(lines, place_words) def count_possibilities(self): n, k = self.n, self.k lines = self.lines choice_counts = self.get_choice_counts(n, k) arrows = self.get_choice_count_arrows(choice_counts) name_rects = VGroup() for name in self.names: name.rect = SurroundingRectangle(name) name_rects.add(name.rect) chosen_names = VGroup(*random.sample(self.names, k)) self.names.save_state() for name, line, count, arrow in zip(chosen_names, lines, choice_counts, arrows): self.play( FadeIn(count), LaggedStartMap( FadeIn, name_rects, rate_func = there_and_back, remover = True, ) ) self.play( name.next_to, line, UP, SMALL_BUFF, GrowArrow(arrow) ) self.wait() name_rects.remove(name.rect) name_rects.set_stroke(YELLOW, 3) #Consolidate choice counts choice_numbers = VGroup(*[ cc.submobjects.pop(1) for cc in choice_counts ]) choice_numbers.generate_target() dots = VGroup(*[Tex("\\cdot") for x in range(k-1)]) product = VGroup(*it.chain(*list(zip(choice_numbers.target, dots)))) product.add(choice_numbers.target[-1]) product.arrange(RIGHT, buff = SMALL_BUFF) chosen_names_brace = Brace(chosen_names, UP) product.next_to(chosen_names_brace, UP) self.play( FadeOut(choice_counts), FadeOut(arrows), MoveToTarget(choice_numbers), Write(dots), GrowFromCenter(chosen_names_brace), ) self.wait() self.set_variables_as_attrs( chosen_names, chosen_names_brace, choice_numbers, choice_numbers_dots = dots, ) def show_permutations_of_ABC(self): chosen_names = self.chosen_names lines = self.lines n_perms = self.n_permutaitons_to_show + 1 for indices in list(it.permutations(list(range(3))))[1:n_perms]: self.play(*[ ApplyMethod( name.next_to, lines[i], UP, SMALL_BUFF, path_arc = np.pi ) for i, name in zip(indices, chosen_names) ]) self.wait(0.5) def count_permutations_of_ABC(self): n, k = self.n, self.k lines = self.lines chosen_names = self.chosen_names brace = self.chosen_names_brace numerator = VGroup( self.choice_numbers, self.choice_numbers_dots, ) frac_line = Line(LEFT, RIGHT) frac_line.replace(numerator, dim_to_match = 0) frac_line.to_edge(RIGHT) choice_counts = self.get_choice_counts(k, k) arrows = self.get_choice_count_arrows(choice_counts) self.play( chosen_names.shift, UP, chosen_names.to_edge, LEFT, numerator.next_to, frac_line, UP, SMALL_BUFF, FadeOut(brace), ) shuffled_names = random.sample(chosen_names, k) for line, name, count, arrow in zip(lines, shuffled_names, choice_counts, arrows): self.play(FadeIn(count), GrowArrow(arrow)) self.play( name.next_to, line, UP, SMALL_BUFF, path_arc = -np.pi/3, ) self.wait() #Consolidate choice counts choice_numbers = VGroup(*[ cc.submobjects.pop(1) for cc in choice_counts ]) choice_numbers.generate_target() dots = VGroup(*[Tex("\\cdot") for x in range(k-1)]) product = VGroup(*it.chain(*list(zip(choice_numbers.target, dots)))) product.add(choice_numbers.target[-1]) product.arrange(RIGHT, buff = SMALL_BUFF) product.next_to(frac_line, DOWN, SMALL_BUFF) self.play( FadeOut(choice_counts), FadeOut(arrows), MoveToTarget(choice_numbers), Write(dots), ShowCreation(frac_line), ) self.wait() self.fraction = VGroup( numerator, frac_line, VGroup(choice_numbers, dots) ) def reset_stage(self): n, k = self.n, self.k n_choose_k_equals = OldTex( "{%d \\choose %d} ="%(n, k) ) n_choose_k_equals.next_to(ORIGIN, RIGHT, LARGE_BUFF) n_choose_k_equals.to_edge(UP, LARGE_BUFF) self.play( self.names.restore, FadeOut(self.lines), FadeOut(self.place_words), ) self.play( self.people_group.to_edge, LEFT, FadeIn(n_choose_k_equals), self.fraction.next_to, n_choose_k_equals, RIGHT, SMALL_BUFF ) def show_whats_being_counted(self): n, k = self.n, self.k letters = VGroup(*[name[0] for name in self.names]) rhs = OldTex("=", "{60", "\\over", "6}") rhs.next_to(self.fraction, RIGHT) all_groups = VGroup() lines = VGroup() for ordered_triplet in it.combinations(letters, k): line = VGroup() for triplet in it.permutations(ordered_triplet): group = VGroup(*triplet).copy() group.save_state() group.arrange(RIGHT, buff = SMALL_BUFF) line.add(group) all_groups.add(group) line.arrange(RIGHT, buff = LARGE_BUFF) lines.add(line) lines.arrange(DOWN) lines.scale(0.8) lines.to_edge(DOWN) rects = VGroup(*[ SurroundingRectangle( line, buff = 0, stroke_width = 0, fill_color = BLUE, fill_opacity = 0.5, ) for line in lines ]) self.play( Write(VGroup(*rhs[:-1])), LaggedStartMap( ApplyMethod, all_groups, lambda g : (g.restore,), rate_func = lambda t : smooth(1-t), run_time = 4, lag_ratio = 0.2, ), ) self.wait() self.play( LaggedStartMap(FadeIn, rects), Write(rhs[-1]) ) self.wait() self.ordered_triplets = lines self.triplet_group_rects = rects self.rhs = rhs def indicate_final_answer(self): ordered_triplets = self.ordered_triplets rects = self.triplet_group_rects fraction = VGroup(*self.rhs[1:]) frac_rect = SurroundingRectangle(fraction) brace = Brace(rects, LEFT) brace_tex = brace.get_tex("10") self.play(FocusOn(fraction)) self.play(ShowCreation(frac_rect)) self.play(FadeOut(frac_rect)) self.wait() self.play( GrowFromCenter(brace), Write(brace_tex), ) self.wait() #### def get_choice_counts(self, n, k): people_braces = self.people_braces choice_counts = VGroup(*[ OldTexText( "(", str(n0), " choices", ")", arg_separator = "" ) for n0 in range(n, n-k, -1) ]) choice_counts.arrange(RIGHT, buff = SMALL_BUFF) choice_counts.set_color_by_gradient(*self.line_colors) choice_counts.next_to(people_braces, DOWN) return choice_counts def get_choice_count_arrows(self, choice_counts): lines = self.lines return VGroup(*[ Arrow( count.get_bottom(), line.get_center() + MED_LARGE_BUFF*UP, color = line.get_color() ) for count, line in zip(choice_counts, lines) ]) def get_lines_and_place_words(self): n, k = self.n, self.k width = max([n.get_width() for n in self.names]) + MED_SMALL_BUFF lines = VGroup(*[ Line(ORIGIN, width*RIGHT) for x in range(k) ]) lines.arrange(RIGHT) lines.next_to(ORIGIN, DOWN, buff = LARGE_BUFF) place_words = VGroup(*[ OldTex("%d^\\text{%s}"%(i+1, s)) for i, s in zip( list(range(k)), it.chain(["st", "nd", "rd"], it.repeat("th")) ) ]) for mob in place_words, lines: mob.set_color_by_gradient(*self.line_colors) for word, line in zip(place_words, lines): word.next_to(line, DOWN, SMALL_BUFF) self.set_variables_as_attrs(lines, place_words) return lines, place_words class NineChooseFourExample(HowToComputeNChooseK): CONFIG = { "random_seed" : 2, "n" : 9, "k" : 4, "line_colors" : [RED, MAROON_B], "n_permutaitons_to_show" : 3, } def construct(self): self.setup_people() self.show_n_choose_k() self.show_n_choose_k_pattern() self.choose_k_people() self.count_how_to_choose_k() self.show_permutations() self.finish_computation() def setup_people(self): self.remove(self.people) self.people = OldTexText(" ".join([ chr(ord('A') + i ) for i in range(self.n) ])) self.people.set_color_by_gradient(BLUE, YELLOW) self.names = self.people self.people.to_edge(UP, buff = LARGE_BUFF + MED_SMALL_BUFF) lb, rb = braces = OldTexText("\\{\\}") braces.scale(1.5) lb.next_to(self.people, LEFT, SMALL_BUFF) rb.next_to(self.people, RIGHT, SMALL_BUFF) self.people_group = VGroup(braces, self.people) self.people_braces = braces def show_n_choose_k(self): n, k = self.n, self.k n_choose_k = OldTex("{%d \\choose %d}"%(n, k)) n_choose_k.to_corner(UP + LEFT) self.play(FadeIn(n_choose_k)) self.set_variables_as_attrs(n_choose_k) def show_n_choose_k_pattern(self): n, k = self.n, self.k stack = get_stack( OldTex("1").set_color(PINK), OldTex("0").set_color(BLUE), n, k ) l = len(stack) n_stacks = 6 columns = VGroup(*[ VGroup(*stack[(i*l)/n_stacks:((i+1)*l)/n_stacks]) for i in range(n_stacks) ]) columns.arrange( RIGHT, aligned_edge = UP, buff = MED_LARGE_BUFF ) columns.set_height(7) columns.to_corner(DOWN + RIGHT) for line in stack: self.play(FadeIn(line, run_time = 0.1)) self.wait(2) self.play(FadeOut( stack, lag_ratio = 0.5, run_time = 2 )) def choose_k_people(self): n, k = self.n, self.k people = self.people braces = self.people_braces n_items = OldTexText("%d items"%n) choose_k = OldTexText("choose %d"%k) n_items.next_to(people, UP, buff = MED_LARGE_BUFF) choose_k.next_to(people, DOWN, buff = LARGE_BUFF) chosen_subset = VGroup(*random.sample(people, k)) self.play( Write(braces), LaggedStartMap(FadeIn, people, run_time = 1), FadeIn(n_items), ) self.wait() self.play( FadeIn(choose_k), LaggedStartMap( ApplyMethod, chosen_subset, lambda m : (m.shift, MED_LARGE_BUFF*DOWN) ) ) self.wait() self.play( chosen_subset.shift, MED_LARGE_BUFF*UP, n_items.next_to, n_items.get_center(), LEFT, choose_k.next_to, n_items.get_center(), RIGHT, ) def count_how_to_choose_k(self): lines, place_words = self.get_lines_and_place_words() self.play( LaggedStartMap(FadeIn, lines), LaggedStartMap(FadeIn, place_words), run_time = 1 ) self.count_possibilities() def show_permutations(self): self.show_permutations_of_ABC() self.count_permutations_of_ABC() def finish_computation(self): equals = OldTex("=") equals.shift(2*LEFT) fraction = self.fraction six = fraction[0][0][3] eight = fraction[0][0][1] two_three = VGroup(*fraction[2][0][1:3]) four = fraction[2][0][0] rhs = OldTex("= 9 \\cdot 2 \\cdot 7 = 126") self.play( self.names.restore, FadeOut(self.lines), FadeOut(self.place_words), self.n_choose_k.next_to, equals, LEFT, self.fraction.next_to, equals, RIGHT, FadeIn(equals), ) self.wait() for mob in six, eight, two_three, four: mob.cross = Cross(mob) mob.cross.set_stroke("red", 5) two = OldTex("2") two.set_color(eight.get_fill_color()) two.next_to(eight, UP) rhs.next_to(fraction, RIGHT) self.play( ShowCreation(six.cross), ShowCreation(two_three.cross), ) self.wait() self.play( ShowCreation(eight.cross), ShowCreation(four.cross), FadeIn(two) ) self.wait() self.play(Write(rhs)) self.wait() class WeirdKindOfCancelation(TeacherStudentsScene): def construct(self): fraction = OldTex( "{5 \\cdot 4 \\cdot 3", "\\text{ ordered}", "\\text{ triplets}", "\\over", "1 \\cdot 2 \\cdot 3", "\\text{ orderings \\;\\qquad}}" ) top_numbers, ordered, triplets, frac_line, bottom_numbers, orderings = fraction for mob in top_numbers, bottom_numbers: mob.set_color_by_gradient(GREEN, YELLOW) fraction.next_to(self.teacher, UP+LEFT) names = VGroup(*list(map(TexText, [ "Ali", "Ben", "Cam", "Denis", "Evan" ]))) names.arrange(RIGHT) names.to_edge(UP, buff = LARGE_BUFF) names.save_state() lb, rb = braces = OldTex("\\{\\}") braces.scale(2) lb.next_to(names, LEFT, SMALL_BUFF) rb.next_to(names, RIGHT, SMALL_BUFF) chosen_names = VGroup(*random.sample(names, 3)) chosen_names.generate_target() chosen_names.target.arrange(RIGHT) chosen_names.target.next_to(top_numbers, UP, MED_LARGE_BUFF) for name, name_target in zip(chosen_names, chosen_names.target): name.target = name_target self.teacher_says("It's like unit cancellation.") self.play_student_changes(*["confused"]*3) self.play( RemovePiCreatureBubble( self.teacher, target_mode = "raise_right_hand" ), LaggedStartMap(FadeIn, fraction, run_time = 1), FadeIn(braces), LaggedStartMap(FadeIn, names) ) self.play_student_changes( *["pondering"]*3, look_at = fraction ) #Go through numerators for num, name in zip(top_numbers[::2], chosen_names): rect = SurroundingRectangle(num) name.target.set_color(num.get_color()) self.play( ShowCreationThenDestruction(rect), MoveToTarget(name), ) self.wait(2) #Go through denominators permutations = list(it.permutations(list(range(3))))[1:] self.shuffle(chosen_names, permutations[:2]) self.play(LaggedStartMap( ShowCreationThenDestruction, VGroup(*list(map(SurroundingRectangle, bottom_numbers[::2]))) )) self.shuffle(chosen_names, permutations[2:]) self.wait() #Show cancelation top_cross = Cross(ordered) bottom_cross = Cross(orderings) self.play( ShowCreation(top_cross), self.teacher.change, "maybe", ) self.play(ShowCreation(bottom_cross)) self.play_student_changes(*["happy"]*3) self.wait(3) ### def shuffle(self, mobject, permutations): for permutation in permutations: self.play(*[ ApplyMethod( m.move_to, mobject[i].get_center(), path_arc = np.pi, ) for i, m in zip(permutation, mobject) ]) class ABCNotBCA(Scene): def construct(self): words = OldTexText("If order mattered:") equation = OldTexText("(A, B, C) $\\ne$ (B, C, A)") equation.set_color(YELLOW) equation.next_to(words, DOWN) group = VGroup(words, equation) group.set_width(FRAME_WIDTH - 1) group.to_edge(DOWN) self.add(words, equation) class ShowFormula(Scene): def construct(self): specific_formula = OldTex( "{9 \\choose 4}", "=", "{9 \\cdot 8 \\cdot 7 \\cdot 6", "\\over", "4 \\cdot 3 \\cdot 2 \\cdot 1}" ) general_formula = OldTex( "{n \\choose k}", "=", "{n \\cdot (n-1) \\cdots (n-k+1)", "\\over", "k \\cdot (k-1) \\cdots 2 \\cdot 1}" ) for i, j in (0, 1), (2, 0), (2, 3), (2, 11): general_formula[i][j].set_color(BLUE) for i, j in (0, 2), (2, 13), (4, 0), (4, 3): general_formula[i][j].set_color(YELLOW) formulas = VGroup(specific_formula, general_formula) formulas.arrange(DOWN, buff = 2) formulas.to_edge(UP) self.play(FadeIn(specific_formula)) self.play(FadeIn(general_formula)) self.wait(3) class ConfusedPi(Scene): def construct(self): morty = Mortimer() morty.scale(2.5) morty.to_corner(UP+LEFT) morty.look(UP+LEFT) self.add(morty) self.play(Blink(morty)) self.play(morty.change, "confused") self.wait() self.play(Blink(morty)) self.wait(2) class SumsToPowerOf2(Scene): CONFIG = { "n" : 5, "alt_n" : 7, } def construct(self): self.setup_stacks() self.count_32() self.show_sum_as_n_choose_k() self.show_alternate_sum() def setup_stacks(self): stacks = get_stacks( OldTex("1").set_color(PINK), OldTex("0").set_color(BLUE), n = self.n, vertical_buff = SMALL_BUFF, ) stacks.to_corner(DOWN+LEFT) numbers = VGroup(*[ OldTex(str(choose(self.n, k))) for k in range(self.n + 1) ]) for number, stack in zip(numbers, stacks): number.next_to(stack, UP) self.play( LaggedStartMap(FadeIn, stacks), LaggedStartMap(FadeIn, numbers), ) self.wait() self.set_variables_as_attrs(stacks, numbers) def count_32(self): lines = VGroup(*it.chain(*self.stacks)) rhs = OldTex("= 2^{%d}"%self.n) rhs.to_edge(UP, buff = LARGE_BUFF) rhs.to_edge(RIGHT, buff = 2) numbers = self.numbers.copy() numbers.target = VGroup(*[ OldTex("{%d \\choose %d}"%(self.n, k)) for k in range(self.n + 1) ]) plusses = VGroup(*[Tex("+") for n in numbers]) plusses.remove(plusses[-1]) plusses.add(OldTex("=")) sum_group = VGroup(*it.chain(*list(zip( numbers.target, plusses )))) sum_group.arrange(RIGHT, SMALL_BUFF) sum_group.next_to(numbers, UP, LARGE_BUFF) sum_group.shift(MED_LARGE_BUFF*RIGHT) for i, line in zip(it.count(1), lines): line_copy = line.copy().set_color(YELLOW) number = Integer(i) number.scale(1.5) number.to_edge(UP) VGroup(number, line_copy).set_color(YELLOW) self.add(line_copy, number) self.wait(0.15) self.remove(line_copy, number) sum_result = number self.add(sum_result) self.wait() sum_result.target = OldTex(str(2**self.n)) sum_result.target.set_color(sum_result.get_color()) sum_result.target.next_to(sum_group, RIGHT) rhs.next_to(sum_result.target, RIGHT, aligned_edge = DOWN) self.play( MoveToTarget(sum_result), MoveToTarget(numbers), Write(plusses), Write(rhs), ) self.wait() self.set_variables_as_attrs( plusses, sum_result, rhs, n_choose_k_terms = numbers ) def show_sum_as_n_choose_k(self): numbers = self.numbers plusses = self.plusses n_choose_k_terms = self.n_choose_k_terms rhs = VGroup(self.sum_result, self.rhs) n = self.n fractions = self.get_fractions(n) plusses.generate_target() sum_group = VGroup(*it.chain(*list(zip( fractions, plusses.target )))) sum_group.arrange(RIGHT, buff = 2*SMALL_BUFF) sum_group.next_to(rhs, LEFT) sum_group.shift(0.5*SMALL_BUFF*DOWN) self.play( Transform(n_choose_k_terms, fractions), MoveToTarget(plusses), lag_ratio = 0.5, run_time = 2 ) self.wait() def show_alternate_sum(self): fractions = self.get_fractions(self.alt_n) fractions.remove(*fractions[4:-1]) fractions.submobjects.insert(4, OldTex("\\cdots")) plusses = VGroup(*[ OldTex("+") for f in fractions[:-1] ] + [Tex("=")]) sum_group = VGroup(*it.chain(*list(zip( fractions, plusses )))) sum_group.arrange(RIGHT) sum_group.next_to( self.n_choose_k_terms, DOWN, aligned_edge = LEFT, buff = LARGE_BUFF ) sum_group.shift(SMALL_BUFF*DOWN) rhs = OldTex( str(2**self.alt_n), "=", "2^{%d}"%(self.alt_n) ) rhs[0].set_color(YELLOW) rhs.next_to(sum_group, RIGHT) self.play( LaggedStartMap(FadeOut, self.stacks), LaggedStartMap(FadeOut, self.numbers), LaggedStartMap(FadeIn, sum_group), ) self.play(LaggedStartMap(FadeIn, rhs)) self.wait(2) #### def get_fractions(self, n): fractions = VGroup(OldTex("1")) dot_str = " \\!\\cdot\\! " for k in range(1, n+1): ts = str(n) bs = "1" for i in range(1, k): ts += dot_str + str(n-i) bs += dot_str + str(i+1) fraction = OldTex("{%s \\over %s}"%(ts, bs)) fractions.add(fraction) return fractions class AskWhyTheyAreCalledBinomial(TeacherStudentsScene): def construct(self): example_binomials = VGroup(*[ OldTex("(x+y)^%d"%d) for d in range(2, 7) ]) example_binomials.arrange(UP) example_binomials.next_to( self.teacher.get_corner(UP+LEFT), UP ) pascals = PascalsTriangle(n_rows = 6) pascals.set_height(3) pascals.to_corner(UP+LEFT, buff = MED_SMALL_BUFF) pascals.set_color_by_gradient(BLUE, YELLOW) binomial_word = OldTexText( "Bi", "nomials", arg_separator = "", ) binomial_word.set_color_by_tex("Bi", YELLOW) binomial_word.set_color_by_tex("nomials", WHITE) binomial_word.next_to(example_binomials, LEFT, buff = 1.5) arrows = VGroup(*[ Arrow(binomial_word.get_right(), binom.get_left()) for binom in example_binomials ]) arrows.set_color(BLUE) two_variables = OldTexText("Two", "variables") two_variables.next_to(binomial_word, DOWN) two_variables.shift(SMALL_BUFF*LEFT) for tv, bw in zip(two_variables, binomial_word): tv.set_color(bw.get_color()) self.student_says( "Why are they called \\\\ ``binomial coefficients''?" ) self.play(LaggedStartMap(FadeIn, pascals)) self.wait() self.play( FadeIn(example_binomials[0]), RemovePiCreatureBubble(self.students[1]), self.teacher.change, "raise_right_hand", ) moving_binom = example_binomials[0].copy() for binom in example_binomials[1:]: self.play(Transform(moving_binom, binom)) self.add(binom) self.wait() #Name themn self.play( Write(binomial_word), LaggedStartMap(GrowArrow, arrows) ) self.play_student_changes(*["pondering"]*3) self.play(Write(two_variables)) self.wait(2) class NextVideo(Scene): def construct(self): title = OldTexText("Next video: Binomial distribution") title.to_edge(UP) screen = ScreenRectangle(height = 6) screen.next_to(title, DOWN) self.play( Write(title), ShowCreation(screen) ) self.wait() class CombinationsPatreonEndScreen(PatreonEndScreen): CONFIG = { "specific_patrons" : [ "Randall Hunt", "Desmos", "Burt Humburg", "CrypticSwarm", "Juan Benet", "David Kedmey", "Ali Yahya", "Mayank M. Mehrotra", "Lukas Biewald", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Jordan Scales", "Markus Persson", "Egor Gumenuk", "Yoni Nazarathy", "Ryan Atallah", "Joseph John Cox", "Luc Ritchie", "Supershabam", "James Park", "Samantha D. Suplee", "Delton Ding", "Thomas Tarler", "Jonathan Eppele", "Isak Hietala", "1stViewMaths", "Jacob Magnuson", "Mark Govea", "Dagan Harrington", "Clark Gaebel", "Eric Chow", "Mathias Jansson", "David Clark", "Michael Gardner", "Mads Elvheim", "Erik Sundell", "Awoo", "Dr. David G. Stork", "Tianyu Ge", "Ted Suzman", "Linh Tran", "Andrew Busey", "John Haley", "Ankalagon", "Eric Lavault", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] } class Thumbnail(Scene): def construct(self): n_choose_k = OldTex("n \\choose k") n_choose_k[1].set_color(YELLOW) n_choose_k[2].set_color(YELLOW) n_choose_k.scale(2) n_choose_k.to_edge(UP) stacks = get_stacks( OldTex("1").set_color(PINK), OldTex("0").set_color(BLUE), n = 5, vertical_buff = SMALL_BUFF, ) stacks.to_edge(DOWN) stacks.shift(MED_SMALL_BUFF*LEFT) self.add(n_choose_k, stacks)
from manim_imports_ext import * class WhatDoesItReallyMean(TeacherStudentsScene): CONFIG = { "default_pi_creature_kwargs": { "color": MAROON_E, "flip_at_start": True, }, } def construct(self): student_q = OldTexText("What does", "``probability''", "\emph{actually}", "mean?") student_q.set_color_by_tex("probability", YELLOW) self.student_says(student_q, target_mode = "sassy") self.wait() question_bubble = VGroup(student_q, students[1].bubble) scaled_qb = question_bubble.copy() scaled_qb.scale(0.4).to_corner(UL) self.play(Transform(question_bubble, scaled_qb)) self.wait() self.teacher_says("Don't worry -- philosophy can come later!") self.wait()
from manim_imports_ext import * class Birthday(Scene): def construct(self): sidelength = 6.0 corner = np.array([-sidelength/2,-sidelength/2,0]) nb_days_left = 365.0 toggle = False def probability(): width = rect.get_width() height = rect.get_height() return width * height / sidelength**2 rect = Square().scale(sidelength/2) while probability() > 0.5: self.add(rect.copy()) nb_days_left -= 1 if toggle: dim = 0 else: dim = 1 rect.stretch_about_point(nb_days_left / 365, dim, corner) toggle = not toggle
from manim_imports_ext import * from tqdm import tqdm as ProgressDisplay import scipy #revert_to_original_skipping_status def get_binomial_distribution(n, p): return lambda k : choose(n, k)*(p**(k))*((1-p)**(n-k)) def get_quiz(*questions): q_mobs = VGroup(*list(map(TexText, [ "%d. %s"%(i+1, question) for i, question in enumerate(questions) ]))) q_mobs.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT, ) content = VGroup( OldTexText("Quiz").scale(1.5), Line(q_mobs.get_left(), q_mobs.get_right()), q_mobs ) content.arrange(DOWN, buff = MED_SMALL_BUFF) rect = SurroundingRectangle(content, buff = MED_LARGE_BUFF) rect.shift(MED_SMALL_BUFF*DOWN) rect.set_color(WHITE) quiz = VGroup(rect, content) quiz.questions = q_mobs quiz.scale(0.7) return quiz def get_slot_group( bool_list, buff = MED_LARGE_BUFF, include_qs = True, min_bool_list_len = 3, ): if len(bool_list) < min_bool_list_len: bool_list += [None]*(min_bool_list_len - len(bool_list)) n = len(bool_list) lines = VGroup(*[ Line(ORIGIN, MED_LARGE_BUFF*RIGHT) for x in range(n) ]) lines.arrange(RIGHT, buff = buff) if include_qs: labels = VGroup(*[ OldTexText("Q%d"%d) for d in range(1, n+1) ]) else: labels = VGroup(*[VectorizedPoint() for d in range(n)]) for label, line in zip(labels, lines): label.scale(0.7) label.next_to(line, DOWN, SMALL_BUFF) slot_group = VGroup() slot_group.lines = lines slot_group.labels = labels slot_group.content = VGroup() slot_group.digest_mobject_attrs() slot_group.to_edge(RIGHT) slot_group.bool_list = bool_list total_height = FRAME_Y_RADIUS base = 2.3 for i, line in enumerate(lines): if i >= len(bool_list) or bool_list[i] is None: mob = VectorizedPoint() elif bool_list[i]: mob = OldTex("\\checkmark") mob.set_color(GREEN) slot_group.shift(total_height*DOWN / (base**(i+1))) else: mob = OldTex("\\times") mob.set_color(RED) slot_group.shift(total_height*UP / (base**(i+1))) mob.next_to(line, UP, SMALL_BUFF) slot_group.content.add(mob) return slot_group def get_probability_of_slot_group(bool_list, conditioned_list = None): filler_tex = "Fi"*max(len(bool_list), 3) if conditioned_list is None: result = OldTex("P(", filler_tex, ")") else: result = OldTex("P(", filler_tex, "|", filler_tex, ")") fillers = result.get_parts_by_tex(filler_tex) for filler, bl in zip(fillers, [bool_list, conditioned_list]): slot_group = get_slot_group( bl, buff = SMALL_BUFF, include_qs = False, ) slot_group.replace(filler, dim_to_match = 0) slot_group.shift(0.5*SMALL_BUFF*DOWN) index = result.index_of_part(filler) result.submobjects[index] = slot_group return result ######### class IndependenceOpeningQuote(OpeningQuote): CONFIG = { "quote" : [ "Far better an ", "approximate", " answer to the ", " right question", ", which is often vague, than an ", "exact", " answer to the ", "wrong question", "." ], "highlighted_quote_terms" : { "approximate" : GREEN, "right" : GREEN, "exact" : RED, "wrong" : RED, }, "author" : "John Tukey", "quote_arg_separator" : "", } class DangerInProbability(Scene): def construct(self): warning = self.get_warning_sign() probability = OldTexText("Probability") probability.scale(2) self.play(Write(warning, run_time = 1)) self.play( warning.next_to, probability, UP, LARGE_BUFF, LaggedStartMap(FadeIn, probability) ) self.wait() ##### def get_warning_sign(self): triangle = RegularPolygon(n = 3, start_angle = np.pi/2) triangle.set_stroke(RED, 12) triangle.set_height(2) bang = OldTexText("!") bang.set_height(0.6*triangle.get_height()) bang.move_to(interpolate( triangle.get_bottom(), triangle.get_top(), 0.4, )) triangle.add(bang) return triangle class MeaningOfIndependence(SampleSpaceScene): CONFIG = { "sample_space_config" : { "height" : 4, "width" : 4, } } def construct(self): self.add_labeled_space() self.align_conditionals() self.relabel() self.assume_independence() self.no_independence() def add_labeled_space(self): self.add_sample_space(**self.sample_space_config) self.sample_space.shift(2*LEFT) self.sample_space.divide_horizontally(0.3) self.sample_space[0].divide_vertically( 0.9, colors = [BLUE_D, GREEN_C] ) self.sample_space[1].divide_vertically( 0.5, colors = [BLUE_E, GREEN_E] ) side_braces_and_labels = self.sample_space.get_side_braces_and_labels( ["P(A)", "P(\\overline A)"] ) top_braces_and_labels, bottom_braces_and_labels = [ part.get_subdivision_braces_and_labels( part.vertical_parts, labels = ["P(B | %s)"%s, "P(\\overline B | %s)"%s], direction = vect ) for part, s, vect in zip( self.sample_space.horizontal_parts, ["A", "\\overline A"], [UP, DOWN], ) ] braces_and_labels_groups = VGroup( side_braces_and_labels, top_braces_and_labels, bottom_braces_and_labels, ) self.add(self.sample_space) self.play(Write(braces_and_labels_groups, run_time = 4)) def align_conditionals(self): line = Line(*[ interpolate( self.sample_space.get_corner(vect+LEFT), self.sample_space.get_corner(vect+RIGHT), 0.7 ) for vect in (UP, DOWN) ]) line.set_stroke(RED, 8) word = OldTexText("Independence") word.scale(1.5) word.next_to(self.sample_space, RIGHT, buff = LARGE_BUFF) word.set_color(RED) self.play(*it.chain( self.get_top_conditional_change_anims(0.7), self.get_bottom_conditional_change_anims(0.7) )) self.play( ShowCreation(line), Write(word, run_time = 1) ) self.wait() self.independence_word = word self.independence_line = line def relabel(self): old_labels = self.sample_space[0].vertical_parts.labels ignored_braces, new_top_labels = self.sample_space[0].get_top_braces_and_labels( ["P(B)", "P(\\overline B)"] ) equation = OldTex( "P(B | A) = P(B)" ) equation.scale(1.5) equation.move_to(self.independence_word) self.play( Transform(old_labels, new_top_labels), FadeOut(self.sample_space[1].vertical_parts.labels), FadeOut(self.sample_space[1].vertical_parts.braces), ) self.play( self.independence_word.next_to, equation, UP, MED_LARGE_BUFF, Write(equation) ) self.wait() self.equation = equation def assume_independence(self): everything = VGroup(*self.get_top_level_mobjects()) morty = Mortimer() morty.scale(0.7) morty.to_corner(DOWN+RIGHT) bubble = ThoughtBubble(direction = RIGHT) bubble.pin_to(morty) bubble.set_fill(opacity = 0) self.play( FadeIn(morty), everything.scale, 0.5, everything.move_to, bubble.get_bubble_center(), ) self.play( morty.change, "hooray", everything, ShowCreation(bubble) ) self.wait() self.play(Blink(morty)) self.wait() self.morty = morty def no_independence(self): for part in self.sample_space.horizontal_parts: part.vertical_parts.labels = None self.play(*it.chain( self.get_top_conditional_change_anims(0.9), self.get_bottom_conditional_change_anims(0.5), [ self.independence_word.fade, 0.7, self.equation.fade, 0.7, self.morty.change, "confused", self.sample_space, FadeOut(self.independence_line) ] )) self.wait() class IntroduceBinomial(Scene): CONFIG = { "n" : 8, "p" : 0.7, } def construct(self): self.add_title() self.add_bar_chart() self.add_p_slider() self.write_independence_assumption() self.play_with_p_value(0.2, 0.5) self.cross_out_assumption() self.play_with_p_value(0.8, 0.4) self.shift_weight_to_tails() def add_title(self): title = OldTexText("Binomial distribution") title.scale(1.3) title.to_edge(RIGHT) title.shift(2*UP) formula = OldTex( "P(X=", "k", ")=", "{n \\choose k}", "p", "^k", "(1-", "p", ")", "^{n-", "k}", arg_separator = "" ) formula.set_color_by_tex("k", BLUE) formula.set_color_by_tex("p", YELLOW) choose_part = formula.get_part_by_tex("choose") choose_part.set_color(WHITE) choose_part[-2].set_color(BLUE) formula.next_to(title, DOWN, MED_LARGE_BUFF) self.formula = formula self.title = title self.add(title, formula) def add_bar_chart(self): n, p = self.n, self.p dist = get_binomial_distribution(n, p) chart = BarChart( [dist(k) for k in range(n+1)], bar_names = list(range(n+1)), ) chart.to_edge(LEFT) self.bar_chart = chart self.play(LaggedStartMap( FadeIn, VGroup(*it.chain(*chart)), run_time = 2 )) def add_p_slider(self): interval = UnitInterval(color = GREY_B) interval.set_width(4) interval.next_to( VGroup(self.bar_chart.x_axis, self.bar_chart.y_axis), UP, MED_LARGE_BUFF ) interval.add_numbers(0, 1) triangle = RegularPolygon( n=3, start_angle = -np.pi/2, stroke_width = 0, fill_color = YELLOW, fill_opacity = 1, ) triangle.set_height(0.25) triangle.move_to(interval.number_to_point(self.p), DOWN) label = OldTex("p") label.next_to(triangle, UP, SMALL_BUFF) label.set_color(triangle.get_color()) self.p_slider = VGroup(interval, triangle, label) self.play(Write(self.p_slider, run_time = 1)) def play_with_p_value(self, *values): for value in values: self.change_p(value) self.wait() def write_independence_assumption(self): assumption = OldTexText("Independence assumption") assumption.scale(1.2) assumption.next_to(self.formula, DOWN, MED_LARGE_BUFF, LEFT) assumption.set_color(GREEN_C) self.play(Write(assumption, run_time = 2)) self.wait() self.assumption = assumption def cross_out_assumption(self): cross = Cross(self.assumption) cross.set_color(GREY) self.bar_chart.save_state() self.play(ShowCreation(cross)) self.play(self.bar_chart.fade, 0.7) self.wait(2) self.play(self.bar_chart.restore) def shift_weight_to_tails(self): chart = self.bar_chart chart_copy = chart.copy() dist = get_binomial_distribution(self.n, self.p) values = np.array(list(map(dist, list(range(self.n+1))))) values += 0.1 values /= sum(values) old_bars = chart.bars old_bars.generate_target() new_bars = chart_copy.bars for bars, vect in (old_bars.target, LEFT), (new_bars, RIGHT): for bar in bars: corner = bar.get_corner(DOWN+vect) bar.stretch(0.5, 0) bar.move_to(corner, DOWN+vect) old_bars.target.set_color(RED) old_bars.target.fade() self.play( MoveToTarget(old_bars), ReplacementTransform( old_bars.copy().set_fill(opacity = 0), new_bars ) ) self.play( chart_copy.change_bar_values, values ) self.wait(2) ##### def change_p(self, p): interval, triangle, p_label = self.p_slider alt_dist = get_binomial_distribution(self.n, p) self.play( ApplyMethod( self.bar_chart.change_bar_values, [alt_dist(k) for k in range(self.n+1)], ), triangle.move_to, interval.number_to_point(p), DOWN, MaintainPositionRelativeTo(p_label, triangle) ) self.p = p class IntroduceQuiz(PiCreatureScene): def construct(self): self.add_quiz() self.ask_about_probabilities() self.show_distribution() self.show_single_question_probability() def add_quiz(self): quiz = self.get_example_quiz() quiz.next_to(self.randy, UP+RIGHT) self.play( Write(quiz), self.randy.change, "pondering", quiz ) self.wait() self.quiz = quiz def ask_about_probabilities(self): probabilities, abbreviated_probabilities = [ VGroup(*[ OldTex( "P(", s_tex, "=", str(score), ")", rhs ).set_color_by_tex_to_color_map({ str(score) : YELLOW, "text" : GREEN, }) for score in range(4) ]) for s_tex, rhs in [ ("\\text{Score}", "= \\, ???"), ("\\text{S}", "") ] ] for group in probabilities, abbreviated_probabilities: group.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) group.to_corner(UP+LEFT) self.play( LaggedStartMap(FadeIn, probabilities, run_time = 3), self.quiz.set_height, 0.7*self.randy.get_height(), self.quiz.next_to, self.randy, RIGHT, self.randy.change, "confused", probabilities ) self.wait() self.probabilities = probabilities self.abbreviated_probabilities = abbreviated_probabilities def show_distribution(self): dist = get_binomial_distribution(3, 0.7) values = list(map(dist, list(range(4)))) chart = BarChart( values, width = 7, bar_names = list(range(4)) ) chart.to_edge(RIGHT) for short_p, bar in zip(self.abbreviated_probabilities, chart.bars): short_p.set_width(1.75*bar.get_width()) short_p.next_to(bar, UP) self.play( LaggedStartMap(Write, VGroup( *[m for m in chart if m is not chart.bars] )), ) self.play(*[ ReplacementTransform( bar.copy().stretch_to_fit_height(0).move_to(bar.get_bottom()), bar ) for bar in chart.bars ]) self.play(*[ ReplacementTransform(p.copy(), short_p) for p, short_p in zip( self.probabilities, self.abbreviated_probabilities, ) ]) self.wait() self.bar_chart = chart def show_single_question_probability(self): prob = OldTex( "P(", "\\text{Can answer a given question}", ")", "= 0.8" ) prob.to_corner(UP+RIGHT) prob.set_color_by_tex("text", GREEN) rect = SurroundingRectangle(prob, buff = MED_SMALL_BUFF) self.play( Write(prob), self.randy.change, "happy", prob ) self.play(ShowCreation(rect)) self.wait() self.single_question_probability = VGroup( prob, rect ) ###### def create_pi_creature(self): randy = Randolph() randy.scale(0.7) randy.to_corner(DOWN+LEFT) self.randy = randy return randy def get_example_quiz(self): return get_quiz( "Define ``Brachistochrone'' ", "Define ``Tautochrone'' ", "Define ``Cycloid'' ", ) class BreakDownQuestionPatterns(IntroduceQuiz): def construct(self): self.add_parts_from_last_scene() self.break_down_possibilities() self.count_patterns() def add_parts_from_last_scene(self): self.force_skipping() IntroduceQuiz.construct(self) self.revert_to_original_skipping_status() chart_group = VGroup( self.bar_chart, self.abbreviated_probabilities ) self.play( self.single_question_probability.scale, 0.8, self.single_question_probability.to_corner, UP+LEFT, chart_group.scale, 0.7, chart_group.get_top(), chart_group.to_edge, LEFT, FadeOut(self.probabilities) ) def break_down_possibilities(self): slot_group_groups = VGroup(*[VGroup() for x in range(4)]) bool_lists = [[]] while bool_lists: bool_list = bool_lists.pop() slot_group = self.get_slot_group(bool_list) slot_group_groups[len(bool_list)].add(slot_group) if len(bool_list) < 3: bool_lists += [ list(bool_list) + [True], list(bool_list) + [False], ] group_group = slot_group_groups[0] self.revert_to_original_skipping_status() self.play(Write(group_group, run_time = 1)) self.wait() for new_group_group in slot_group_groups[1:]: self.play(Transform(group_group, new_group_group)) self.wait(2) self.slot_groups = slot_group_groups[-1] def count_patterns(self): brace = Brace(self.slot_groups, LEFT) count = OldTex("2^3 = 8") count.next_to(brace, LEFT) self.play( GrowFromCenter(brace), Write(count) ) self.wait() ####### def get_slot_group(self, bool_list): return get_slot_group(bool_list, include_qs = len(bool_list) < 3) class AssociatePatternsWithScores(BreakDownQuestionPatterns): CONFIG = { "score_group_scale_val" : 0.8, } def construct(self): self.add_slot_groups() self.show_score_groups() self.think_about_binomial_patterns() def add_slot_groups(self): self.slot_groups = VGroup(*list(map( self.get_slot_group, it.product(*[[True, False]]*3) ))) self.add(self.slot_groups) self.remove(self.randy) def show_score_groups(self): score_groups = [VGroup() for x in range(4)] scores = VGroup() full_score_groups = VGroup() for slot_group in self.slot_groups: score_groups[sum(slot_group.bool_list)].add(slot_group) for i, score_group in enumerate(score_groups): score = OldTexText("Score", "=", str(i)) score.set_color_by_tex("Score", GREEN) scores.add(score) score_group.organized = score_group.deepcopy() score_group.organized.arrange(UP, buff = SMALL_BUFF) score_group.organized.scale(self.score_group_scale_val) brace = Brace(score_group.organized, LEFT) score.next_to(brace, LEFT) score.add(brace) full_score_groups.add(VGroup(score, score_group.organized)) full_score_groups.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = RIGHT ) full_score_groups.to_edge(LEFT) for score, score_group in zip(scores, score_groups): score_group.save_state() self.play(score_group.next_to, score_group, LEFT, MED_LARGE_BUFF) self.wait() self.play( ReplacementTransform( score_group.copy(), score_group.organized ), LaggedStartMap(FadeIn, score, run_time = 1) ) self.play(score_group.restore) self.wait() def think_about_binomial_patterns(self): triangle = PascalsTriangle( nrows = 5, height = 3, width = 3, ) triangle.to_edge(UP+RIGHT) row = VGroup(*[ triangle.coords_to_mobs[3][k] for k in range(4) ]) self.randy.center().to_edge(DOWN) bubble = ThoughtBubble() bubble.add_content(triangle) bubble.resize_to_content() triangle.shift(SMALL_BUFF*(3*UP + RIGHT)) bubble.add(triangle) bubble.next_to(self.randy, UP+RIGHT, SMALL_BUFF) bubble.remove(triangle) self.play( FadeOut(self.slot_groups), FadeIn(self.randy), FadeIn(bubble) ) self.play( self.randy.change, "pondering", LaggedStartMap(FadeIn, triangle, run_time = 4), ) self.play(row.set_color, YELLOW) self.wait(4) class BeforeCounting(TeacherStudentsScene): def construct(self): triangle = PascalsTriangle(nrows = 7) triangle.set_height(4) triangle.next_to(self.teacher, UP+LEFT) prob = get_probability_of_slot_group([True, True, False]) prob.to_edge(UP) brace = Brace(prob, DOWN) q_marks = brace.get_text("???") self.teacher.change_mode("raise_right_hand") self.add(triangle) self.play_student_changes(*["hooray"]*3) self.play( triangle.scale, 0.5, triangle.to_corner, UP+RIGHT, self.teacher.change_mode, "sassy" ) self.play_student_changes(*["confused"]*3) self.play(Write(prob)) self.play( GrowFromCenter(brace), LaggedStartMap(FadeIn, q_marks) ) self.wait(2) class TemptingButWrongCalculation(BreakDownQuestionPatterns): def construct(self): self.add_title() self.write_simple_product() def add_title(self): title = OldTexText("Tempting$\\dots$") title.scale(1.5) title.to_edge(UP) self.add(title) self.title = title def write_simple_product(self): lhs = OldTex("P\\big(", "Filler Blah", "\\big)", "= ") lhs.next_to(ORIGIN, UP+LEFT) p_of = lhs.get_part_by_tex("P\\big(") filler = lhs.get_part_by_tex("Filler") rp = lhs.get_part_by_tex("\\big)") slot_group = self.get_slot_group([True, True, False]) slot_group.replace(filler, dim_to_match = 0) lhs.submobjects.remove(filler) rhs = VGroup(*[ OldTex("P(", "\\checkmark" if b else "\\times", ")") for b in slot_group.bool_list ]) rhs.arrange(RIGHT, SMALL_BUFF) rhs.next_to(lhs, RIGHT, SMALL_BUFF) for part, b in zip(rhs, slot_group.bool_list): part.set_color_by_tex_to_color_map({ "checkmark" : GREEN, "times" : RED, }) brace = Brace(part, UP) if b: value = OldTex("(0.8)") else: value = OldTex("(0.2)") value.set_color(part[1].get_color()) value.next_to(brace, UP) part.brace = brace part.value = value question = OldTexText("What about correlations?") question.next_to(rhs, DOWN, LARGE_BUFF) self.play( Write(lhs), ShowCreation(slot_group.lines), LaggedStartMap(FadeIn, slot_group.content, run_time = 3), self.randy.change, "pondering" ) self.wait(2) for part, mob in zip(rhs, slot_group.content): self.play(*[ ReplacementTransform( mob.copy(), subpart, path_arc = np.pi/6 ) for subpart, mob in zip(part, [ p_of, mob, rp ]) ]) self.play(GrowFromCenter(part.brace)) self.play(FadeIn(part.value)) self.wait() self.wait() self.play( Write(question), self.randy.change, "confused" ) self.wait(3) self.question = question self.rhs = rhs class ThousandPossibleQuizzes(Scene): CONFIG = { "n_quiz_rows" : 25, "n_quiz_cols" : 40, "n_movers" : 100, # "n_quiz_rows" : 5, # "n_quiz_cols" : 8, # "n_movers" : 4, "quizzes_height" : 4, } def construct(self): self.draw_all_quizzes() self.show_division_by_first_question() self.ask_about_second_question() self.show_uncorrelated_division_by_second() self.increase_second_correct_slice() self.second_division_among_first_wrong() self.show_that_second_is_still_80() self.emphasize_disproportionate_divide() self.show_third_question_results() def draw_all_quizzes(self): quizzes = self.get_thousand_quizzes() title = OldTexText("$1{,}000$ possible quizzes") title.scale(1.5) title.next_to(quizzes, UP) full_quizzes = VGroup( get_quiz( "Define ``Brachistochrone''", "Define ``Tautochrone''", "Define ``Cycloid''", ), get_quiz( "Define $\\dfrac{df}{dx}$", "Define $\\displaystyle \\lim_{h \\to 0} f(h)$", "Prove $\\dfrac{d(x^2)}{dx} = 2x$ ", ), get_quiz( "Find all primes $p$ \\\\ where $p+2$ is prime.", "Find all primes $p$ \\\\ where $2^{p}-1$ is prime.", "Solve $\\zeta(s) = 0$", ), ) full_quizzes.arrange(RIGHT) target_quizzes = VGroup(*quizzes[:len(full_quizzes)]) for quiz in full_quizzes: self.play(FadeIn(quiz, run_time = 3, lag_ratio = 0.5)) self.play( Transform(full_quizzes, target_quizzes), FadeIn(title) ) self.play( LaggedStartMap( FadeIn, quizzes, run_time = 3, lag_ratio = 0.2, ), Animation(full_quizzes, remover = True) ) self.wait() self.quizzes = quizzes self.title = title def show_division_by_first_question(self): n = int(0.8*len(self.quizzes)) top_split = VGroup(*self.quizzes[:n]) bottom_split = VGroup(*self.quizzes[n:]) for split, color, vect in (top_split, GREEN, UP), (bottom_split, RED, DOWN): split.sort(lambda p : p[0]) split.generate_target() split.target.shift(MED_LARGE_BUFF*vect) for quiz in split.target: quiz[0].set_color(color) labels = VGroup() for num, b, split in (800, True, top_split), (200, False, bottom_split): label = VGroup( OldTex(str(num)), get_slot_group([b], buff = SMALL_BUFF, include_qs = False) ) label.arrange(DOWN) label.next_to(split.target, LEFT, buff = LARGE_BUFF) labels.add(label) self.play( FadeOut(self.title), MoveToTarget(top_split), MoveToTarget(bottom_split), ) for label in labels: self.play(FadeIn(label)) self.wait() self.splits = VGroup(top_split, bottom_split) self.q1_split_labels = labels def ask_about_second_question(self): top_split = self.splits[0] sg1, sg2 = slot_groups = VGroup(*[ get_slot_group( [True, b], include_qs = False, buff = SMALL_BUFF ) for b in (True, False) ]) question = VGroup( OldTexText("Where are"), sg1, OldTexText("and"), sg2, OldTexText("?"), ) question.arrange(RIGHT, aligned_edge = DOWN) question[-1].next_to(question[-2], RIGHT, SMALL_BUFF) question.next_to(top_split, UP, MED_LARGE_BUFF) slot_groups.shift(SMALL_BUFF*DOWN) little_rects = VGroup(*[ SurroundingRectangle( VGroup(sg.lines[1], sg.content[1]) ) for sg in slot_groups ]) big_rect = SurroundingRectangle(top_split) self.play(Write(question)) self.play(ShowCreation(little_rects)) self.wait() self.play(FadeOut(little_rects)) self.play(ShowCreation(big_rect)) self.play( FadeOut(big_rect), FadeOut(question), ) self.wait() def show_uncorrelated_division_by_second(self): top_split = self.splits[0] top_label = self.q1_split_labels[0] n = int(0.8*len(top_split)) left_split = VGroup(*top_split[:n]) right_split = VGroup(*top_split[n:]) for split, color in (left_split, GREEN_E), (right_split, RED_E): split.generate_target() for quiz in split.target: quiz[1].set_color(color) left_split.target.shift(LEFT) left_label = VGroup( OldTex("(0.8)", "800 =", "640"), get_slot_group([True, True], buff = SMALL_BUFF, include_qs = False) ) left_label.arrange(RIGHT, buff = MED_LARGE_BUFF) left_label.next_to(left_split.target, UP) self.play( MoveToTarget(left_split), MaintainPositionRelativeTo(top_label, left_split), MoveToTarget(right_split), ) self.play(FadeIn(left_label)) self.play(LaggedStartMap( ApplyMethod, left_split, lambda m : (m.set_color, YELLOW), rate_func = there_and_back, lag_ratio = 0.2, )) self.wait() self.top_left_label = left_label self.top_splits = VGroup(left_split, right_split) def increase_second_correct_slice(self): left_split, right_split = self.top_splits left_label = self.top_left_label left_label_equation = left_label[0] movers = VGroup(*right_split[:self.n_movers]) movers.generate_target() for quiz in movers.target: quiz[1].set_color(left_split[0][1].get_color()) movers.target.shift(LEFT) new_equation = OldTex("(0.925)", "800 =", "740") for i in 0, 2: new_equation[i].set_color(YELLOW) new_equation.move_to(left_label_equation) self.play( MoveToTarget( movers, lag_ratio = 0.5, run_time = 3, ), Transform(left_label_equation, new_equation) ) self.wait(2) self.play(Indicate(left_label_equation[0])) self.wait() left_split.add(*movers) right_split.remove(*movers) self.top_left_split = left_split self.top_right_split = right_split self.top_movers = movers self.top_equation = left_label_equation def second_division_among_first_wrong(self): top_label, bottom_label = self.q1_split_labels top_split, bottom_split = self.splits top_left_label = self.top_left_label top_group = VGroup(top_split, top_left_label, top_label) n = int(0.8*len(bottom_split)) left_split = VGroup(*bottom_split[:n]) right_split = VGroup(*bottom_split[n:]) for split, color in (left_split, GREEN_E), (right_split, RED_E): split.generate_target() for quiz in split.target: quiz[1].set_color(color) left_split.target.shift(LEFT) movers = VGroup(*left_split[-self.n_movers:]) movers.generate_target() for quiz in movers.target: quiz[1].set_color(right_split.target[0][1].get_color()) equation = OldTex("(0.8)", "200 = ", "160") slot_group = get_slot_group([False, True], buff = SMALL_BUFF, include_qs = False) label = VGroup(equation, slot_group) label.arrange(DOWN, buff = SMALL_BUFF) label.next_to(left_split.target, UP, SMALL_BUFF, LEFT) alt_equation = OldTex("(0.3)", "200 = ", "60") for i in 0, 2: alt_equation[i].set_color(YELLOW) alt_equation.move_to(equation) self.play(top_group.to_edge, UP, SMALL_BUFF) self.play( bottom_label.shift, LEFT, *list(map(MoveToTarget, [left_split, right_split])) ) self.play(FadeIn(label)) self.wait() self.play( MoveToTarget( movers, lag_ratio = 0.5, run_time = 3, ), Transform(equation, alt_equation) ) self.wait() left_split.remove(*movers) right_split.add(*movers) self.bottom_left_split = left_split self.bottom_right_split = right_split self.bottom_movers = movers self.bottom_equation = equation self.bottom_left_label = label def show_that_second_is_still_80(self): second_right = VGroup( self.bottom_left_split, self.top_left_split ) second_wrong = VGroup( self.bottom_right_split, self.top_right_split ) rects = VGroup(*[ SurroundingRectangle(mob, buff = SMALL_BUFF) for mob in second_right ]) num1 = self.top_equation[-1].copy() num2 = self.bottom_equation[-1].copy() equation = OldTex("740", "+", "60", "=", "800") for tex in "740", "60": equation.set_color_by_tex(tex, YELLOW) slot_group = get_slot_group([True, True]) slot_group.content[0].set_fill(BLACK, 0) label = VGroup(equation, slot_group) label.arrange(DOWN) label.next_to(self.quizzes, LEFT, LARGE_BUFF) self.play( FadeOut(self.q1_split_labels), ShowCreation(rects) ) self.play( FadeIn(slot_group), Transform( num1, equation[0], rate_func = squish_rate_func(smooth, 0, 0.7), ), Transform( num2, equation[2], rate_func = squish_rate_func(smooth, 0.3, 1), ), run_time = 2 ) self.play( Write(equation), *list(map(Animation, [num1, num2])) ) self.remove(num1, num2) self.wait() self.play(FadeOut(rects)) def emphasize_disproportionate_divide(self): top_movers = self.top_movers bottom_movers = self.bottom_movers both_movers = VGroup(top_movers, bottom_movers) both_movers.save_state() top_movers.target = bottom_movers.copy().shift(LEFT) bottom_movers.target = top_movers.copy().shift(RIGHT) for quiz in top_movers.target: quiz[0].set_color(RED) for quiz in bottom_movers.target: quiz[0].set_color(GREEN) line = Line(UP, DOWN, color = YELLOW) line.set_height(self.quizzes.get_height()) line.next_to(bottom_movers.target, LEFT, MED_LARGE_BUFF, UP) self.revert_to_original_skipping_status() self.play(*list(map(MoveToTarget, both_movers))) self.play(ShowCreation(line)) self.play(FadeOut(line)) self.wait() self.play(both_movers.restore) self.wait() def show_third_question_results(self): all_splits = VGroup( self.top_left_split, self.top_right_split, self.bottom_left_split, self.bottom_right_split ) proportions = [0.9, 0.8, 0.8, 0.4] for split, prop in zip(all_splits, proportions): n = int(prop*len(split)) split.sort(lambda p : -p[1]) split.generate_target() top_part = VGroup(*split.target[:n]) top_part.shift(MED_SMALL_BUFF*UP) bottom_part = VGroup(*split.target[n:]) bottom_part.shift(MED_SMALL_BUFF*DOWN) for quiz in top_part: quiz[-1].set_color(GREEN) for quiz in bottom_part: quiz[-1].set_color(RED) split = self.top_left_split n_all_right = int(proportions[0]*len(split)) all_right = VGroup(*split[:n_all_right]) self.play( FadeOut(self.top_left_label), FadeOut(self.bottom_left_label), ) for split in all_splits: self.play(MoveToTarget(split)) self.wait() self.play(LaggedStartMap( ApplyMethod, all_right, lambda m : (m.set_color, YELLOW), rate_func = there_and_back, lag_ratio = 0.2, run_time = 2 )) self.wait(2) ##### def get_thousand_quizzes(self): rows = VGroup() for x in range(self.n_quiz_rows): quiz = VGroup(*[ Rectangle( height = SMALL_BUFF, width = 0.5*SMALL_BUFF ) for x in range(3) ]) quiz.arrange(RIGHT, buff = 0) quiz.set_stroke(width = 0) quiz.set_fill(GREY_B, 1) row = VGroup(*[quiz.copy() for y in range(self.n_quiz_cols)]) row.arrange(RIGHT, buff = SMALL_BUFF) rows.add(row) rows.arrange(DOWN, buff = SMALL_BUFF) quizzes = VGroup(*it.chain(*rows)) quizzes.set_height(self.quizzes_height) quizzes.to_edge(RIGHT) quizzes.shift(MED_LARGE_BUFF*DOWN) return quizzes class ExampleConditional(Scene): def construct(self): prob = get_probability_of_slot_group( [True, True], [True] ) rhs = OldTex("=", "0.925", ">", "0.8") rhs.set_color_by_tex("0.925", YELLOW) rhs.next_to(prob, RIGHT) expression = VGroup(prob, rhs) expression.set_width(FRAME_WIDTH - 1) expression.center().to_edge(DOWN) self.play(Write(expression)) self.wait() class HarderQuizzes(Scene): def construct(self): quizzes = VGroup( get_quiz( "Find all primes $p$ \\\\ where $p+2$ is prime.", "Find all primes $p$ \\\\ where $2^{p}-1$ is prime.", "Solve $\\zeta(s) = 0$", ), get_quiz( "Find $S$ such that \\\\ $\\#\\mathds{N} < \\#S < \\#\\mathcal{P}(\\mathds{N})$", "Describe ``forcing''", "Prove from ZFC that $S \\notin S$.", ), ) quizzes.arrange(RIGHT) quizzes.to_edge(DOWN) crosses = VGroup(*[ Cross(quiz.questions[0]) for quiz in quizzes ]) for quiz in quizzes: self.play(FadeIn(quiz)) self.wait() for cross in crosses: self.play(ShowCreation(cross)) self.wait() class WritePSecond(Scene): def construct(self): prob = get_probability_of_slot_group([None, True, None]) rhs = OldTex("= 0.8") rhs.next_to(prob, RIGHT) prob.add(rhs) prob.set_width(FRAME_WIDTH - 1) prob.center().to_edge(DOWN) self.play(Write(prob)) class SubmitToTemptation(TemptingButWrongCalculation): def construct(self): self.force_skipping() TemptingButWrongCalculation.construct(self) self.revert_to_original_skipping_status() title = self.title question = self.question title.generate_target() title.target.scale(1./1.5) new_words = OldTexText("and", "okay", "assuming independence.") new_words.set_color_by_tex("okay", GREEN) new_words.next_to(title.target, RIGHT) VGroup(title.target, new_words).center().to_edge(UP) self.play( MoveToTarget(title), FadeOut(question) ) self.play( Write(new_words, run_time = 2), self.randy.change, "hooray" ) for part in self.rhs: self.play(Indicate(part.value)) self.wait() class AccurateProductRule(SampleSpaceScene, ThreeDScene): def construct(self): self.setup_terms() self.add_sample_space() self.wait() self.show_first_division() self.show_second_division() self.move_to_third_dimension() self.show_final_probability() self.show_confusion() def setup_terms(self): filler_tex = "Filler" lhs = OldTex("P(", filler_tex, ")", "=") p1 = OldTex("P(", filler_tex, ")") p2 = OldTex("P(", filler_tex, "|", filler_tex, ")") p3 = OldTex("P(", filler_tex, "|", filler_tex, ")") terms = VGroup(lhs, p1, p2, p3) terms.arrange(RIGHT, buff = SMALL_BUFF) terms.to_edge(UP, buff = LARGE_BUFF) kwargs = {"buff" : SMALL_BUFF, "include_qs" : False} slot_group_lists = [ [get_slot_group([True, True, False], **kwargs)], [get_slot_group([True], **kwargs)], [ get_slot_group([True, True], **kwargs), get_slot_group([True], **kwargs), ], [ get_slot_group([True, True, False], **kwargs), get_slot_group([True, True], **kwargs), ], ] for term, slot_group_list in zip(terms, slot_group_lists): parts = term.get_parts_by_tex(filler_tex) for part, slot_group in zip(parts, slot_group_list): slot_group.replace(part, dim_to_match = 0) term.submobjects[term.index_of_part(part)] = slot_group # terms[2][1].content[0].set_fill(BLACK, 0) # VGroup(*terms[3][1].content[:2]).set_fill(BLACK, 0) value_texs = ["0.8", ">0.8", "<0.2"] for term, tex in zip(terms[1:], value_texs): term.value = OldTex(tex) term.value.next_to(term, UP) self.terms = terms self.add(terms[0]) def add_sample_space(self): SampleSpaceScene.add_sample_space(self, height = 4, width = 5) self.sample_space.to_edge(DOWN) def show_first_division(self): space = self.sample_space space.divide_horizontally( [0.8], colors = [GREEN_E, RED_E] ) space.horizontal_parts.fade(0.1) top_label = self.terms[1].copy() bottom_label = top_label.copy() slot_group = get_slot_group([False], buff = SMALL_BUFF, include_qs = False) slot_group.replace(bottom_label[1]) Transform(bottom_label[1], slot_group).update(1) braces_and_labels = space.get_side_braces_and_labels( [top_label, bottom_label] ) self.play( FadeIn(space.horizontal_parts), FadeIn(braces_and_labels) ) self.play(ReplacementTransform( top_label.copy(), self.terms[1] )) self.wait() self.play(Write(self.terms[1].value)) self.wait() space.add(braces_and_labels) self.top_part = space.horizontal_parts[0] def show_second_division(self): space = self.sample_space top_part = self.top_part green_red_mix = average_color(GREEN_E, RED_E) top_part.divide_vertically( [0.9], colors = [GREEN_E, green_red_mix] ) label = self.terms[2].deepcopy() braces_and_labels = top_part.get_top_braces_and_labels( labels = [label] ) self.play( FadeIn(top_part.vertical_parts), FadeIn(braces_and_labels) ) self.play(ReplacementTransform( label.copy(), self.terms[2] )) self.wait() self.play(Write(self.terms[2].value)) self.wait() space.add(braces_and_labels) self.top_left_part = top_part.vertical_parts[0] def move_to_third_dimension(self): space = self.sample_space part = self.top_left_part cubes = VGroup( Cube(fill_color = RED_E), Cube(fill_color = GREEN_E), ) cubes.set_fill(opacity = 0) cubes.stretch_to_fit_width(part.get_width()) cubes.stretch_to_fit_height(part.get_height()) cubes[1].move_to(part, IN) cubes[0].stretch(0.2, 2) cubes[0].move_to(cubes[1].get_edge_center(OUT), IN) space.add(cubes) self.play( space.rotate, 0.9*np.pi/2, LEFT, space.rotate, np.pi/12, UP, space.to_corner, DOWN+RIGHT, LARGE_BUFF ) space.remove(cubes) self.play( cubes[0].set_fill, None, 1, cubes[0].set_stroke, WHITE, 1, cubes[1].set_fill, None, 0.5, cubes[1].set_stroke, WHITE, 1, ) self.wait() self.cubes = cubes def show_final_probability(self): cube = self.cubes[0] face = cube[2] points = face.get_anchors() line = Line(points[2], points[3]) line.set_stroke(YELLOW, 8) brace = Brace(line, LEFT) label = self.terms[3].copy() label.next_to(brace, LEFT) self.play( GrowFromCenter(brace), FadeIn(label), ) self.wait() self.play(ReplacementTransform( label.copy(), self.terms[3] )) self.wait() def show_confusion(self): randy = Randolph() randy.to_corner(DOWN+LEFT) self.play(FadeIn(randy)) self.play(randy.change, "confused", self.terms) self.play(randy.look_at, self.cubes) self.play(Blink(randy)) self.play(randy.look_at, self.terms) self.wait() class ShowAllEightConditionals(Scene): def construct(self): self.show_all_conditionals() self.suggest_independence() def show_all_conditionals(self): equations = VGroup() filler_tex = "Filler" for bool_list in it.product(*[[True, False]]*3): equation = OldTex( "P(", filler_tex, ")", "=", "P(", filler_tex, ")", "P(", filler_tex, "|", filler_tex, ")", "P(", filler_tex, "|", filler_tex, ")", ) sub_bool_lists = [ bool_list[:n] for n in (3, 1, 2, 1, 3, 2) ] parts = equation.get_parts_by_tex(filler_tex) for part, sub_list in zip(parts, sub_bool_lists): slot_group = get_slot_group( sub_list, buff = SMALL_BUFF, include_qs = False ) slot_group.replace(part, dim_to_match = 0) index = equation.index_of_part(part) equation.submobjects[index] = slot_group equations.add(equation) equations.arrange(DOWN) rect = SurroundingRectangle( VGroup(*equations[0][7:], *equations[-1][7:]), buff = SMALL_BUFF ) rect.shift(0.5*SMALL_BUFF*RIGHT) self.play(LaggedStartMap( FadeIn, equations, run_time = 5, lag_ratio = 0.3 )) self.wait() self.play(ShowCreation(rect, run_time = 2)) self.play(FadeOut(rect)) self.wait() def suggest_independence(self): full_screen_rect = FullScreenFadeRectangle() randy = Randolph() randy.to_corner(DOWN+LEFT) self.play( FadeIn(full_screen_rect), FadeIn(randy) ) self.play(PiCreatureSays( randy, "Let's just assume \\\\ independence.", target_mode = "shruggie" )) self.play(Blink(randy)) self.wait() class ShowIndependenceSymbolically(Scene): def construct(self): filler_tex = "Filler" rhs = OldTex("=", "0.8") rhs.set_color_by_tex("0.8", YELLOW) rhs.next_to(ORIGIN, RIGHT, LARGE_BUFF) lhs = OldTex("P(", filler_tex, "|", filler_tex, ")") lhs.next_to(rhs, LEFT) VGroup(lhs, rhs).scale(1.5) for part in lhs.get_parts_by_tex(filler_tex): slot_group = get_slot_group( [True, True, True], buff = SMALL_BUFF, include_qs = False, ) slot_group.replace(part, dim_to_match = 0) lhs.submobjects[lhs.index_of_part(part)] = slot_group VGroup(*lhs[1].content[:2]).set_fill(BLACK, 0) condition = lhs[3] condition.content[2].set_fill(BLACK, 0) bool_lists = [ [False], [True, False], [False, True], [True], ] arrow = Arrow(UP, DOWN) arrow.next_to(condition, UP) arrow.set_color(RED) words = OldTexText("Doesn't matter") words.set_color(RED) words.next_to(arrow, UP) self.add(rhs, lhs, arrow, words) self.wait() for bool_list in bool_lists: slot_group = get_slot_group(bool_list, SMALL_BUFF, False) slot_group.replace(condition) slot_group.move_to(condition, DOWN) self.play(Transform(condition, slot_group)) self.wait() class ComputeProbabilityOfOneWrong(Scene): CONFIG = { "score" : 2, "final_result_rhs_tex" : [ "3", "(0.8)", "^2", "(0.2)", "=", "0.384", ], "default_bool" : True, "default_p" : "0.8", "default_q" : "0.2", } def construct(self): self.show_all_three_patterns() self.show_final_result() def show_all_three_patterns(self): probabilities = VGroup() point_8s = VGroup() point_2s = VGroup() for i in reversed(list(range(3))): bool_list = [self.default_bool]*3 bool_list[i] = not self.default_bool probs = ["(%s)"%self.default_p]*3 probs[i] = "(%s)"%self.default_q lhs = get_probability_of_slot_group(bool_list) rhs = OldTex("=", *probs) rhs.set_color_by_tex("0.8", GREEN) rhs.set_color_by_tex("0.2", RED) point_8s.add(*rhs.get_parts_by_tex("0.8")) point_2s.add(*rhs.get_parts_by_tex("0.2")) rhs.next_to(lhs, RIGHT) probabilities.add(VGroup(lhs, rhs)) probabilities.arrange(DOWN, buff = LARGE_BUFF) probabilities.center() self.play(Write(probabilities[0])) self.wait(2) for i in range(2): self.play(ReplacementTransform( probabilities[i].copy(), probabilities[i+1] )) self.wait() for group in point_8s, point_2s: self.play(LaggedStartMap( Indicate, group, rate_func = there_and_back, lag_ratio = 0.7 )) self.wait() def show_final_result(self): result = OldTex( "P(", "\\text{Score} = %s"%self.score, ")", "=", *self.final_result_rhs_tex ) result.set_color_by_tex_to_color_map({ "0.8" : GREEN, "0.2" : RED, "Score" : YELLOW, }) result[-1].set_color(YELLOW) result.set_color_by_tex("0.8", GREEN) result.set_color_by_tex("0.2", RED) result.to_edge(UP) self.play(Write(result)) self.wait() class ComputeProbabilityOfOneRight(ComputeProbabilityOfOneWrong): CONFIG = { "score" : 1, "final_result_rhs_tex" : [ "3", "(0.8)", "(0.2)", "^2", "=", "0.096", ], "default_bool" : False, "default_p" : "0.2", "default_q" : "0.8", } class ShowFullDistribution(Scene): def construct(self): self.add_scores_one_and_two() self.add_scores_zero_and_three() self.show_bar_chart() self.compare_to_binomial_pattern() self.show_alternate_values_of_p() def add_scores_one_and_two(self): scores = VGroup( OldTex( "P(", "\\text{Score} = 0", ")", "=", "(0.2)", "^3", "=", "0.008", ), OldTex( "P(", "\\text{Score} = 1", ")", "=", "3", "(0.8)", "(0.2)", "^2", "=", "0.096", ), OldTex( "P(", "\\text{Score} = 2", ")", "=", "3", "(0.8)", "^2", "(0.2)", "=", "0.384", ), OldTex( "P(", "\\text{Score} = 3", ")", "=", "(0.8)", "^3", "=", "0.512", ), ) scores.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) scores.shift(MED_LARGE_BUFF*UP) scores.to_edge(LEFT) for score in scores: score.set_color_by_tex_to_color_map({ "0.8" : GREEN, "0.2" : RED, }) score[-1].set_color(YELLOW) self.add(*scores[1:3]) self.scores = scores def add_scores_zero_and_three(self): self.p_slot_groups = VGroup() self.wait() self.add_edge_score(0, UP, False) self.add_edge_score(3, DOWN, True) def add_edge_score(self, index, vect, q_bool): score = self.scores[index] prob = VGroup(*score[:3]) brace = Brace(prob, vect) p_slot_group = get_probability_of_slot_group([q_bool]*3) p_slot_group.next_to(brace, vect) group = VGroup(*it.chain(p_slot_group, brace, score)) self.play(LaggedStartMap( FadeIn, group, run_time = 2, lag_ratio = 0.7, )) self.wait(2) self.p_slot_groups.add(brace, p_slot_group) def show_bar_chart(self): p_terms = VGroup() to_fade = VGroup(self.p_slot_groups) value_mobs = VGroup() for score in self.scores: p_terms.add(VGroup(*score[:3])) to_fade.add(VGroup(*score[3:-1])) value_mobs.add(score[-1]) dist = get_binomial_distribution(3, 0.8) values = list(map(dist, list(range(4)))) chart = BarChart( values, bar_names = list(range(4)), ) chart.shift(DOWN) new_p_terms = VGroup(*[ OldTex("P(", "S=%d"%k, ")") for k in range(4) ]) for term, bar in zip(new_p_terms, chart.bars): term[1].set_color(YELLOW) term.set_width(1.5*bar.get_width()) term.next_to(bar, UP) self.play( ReplacementTransform( value_mobs, chart.bars, lag_ratio = 0.5, run_time = 2 ) ) self.play( LaggedStartMap(FadeIn, VGroup(*it.chain(*[ submob for submob in chart if submob is not chart.bars ]))), Transform(p_terms, new_p_terms), FadeOut(to_fade), ) self.wait(2) chart.bar_top_labels = p_terms chart.add(p_terms) self.bar_chart = chart def compare_to_binomial_pattern(self): dist = get_binomial_distribution(3, 0.5) values = list(map(dist, list(range(4)))) alt_chart = BarChart(values) alt_chart.move_to(self.bar_chart) bars = alt_chart.bars bars.set_fill(GREY, opacity = 0.5) vect = 4*UP bars.shift(vect) nums = VGroup(*list(map(Tex, list(map(str, [1, 3, 3, 1]))))) for num, bar in zip(nums, bars): num.next_to(bar, UP) bars_copy = bars.copy() self.play( LaggedStartMap(FadeIn, bars), LaggedStartMap(FadeIn, nums), ) self.wait(2) self.play(bars_copy.shift, -vect) self.play(ReplacementTransform( bars_copy, self.bar_chart.bars )) self.wait(2) self.play( VGroup(self.bar_chart, bars, nums).to_edge, LEFT ) self.alt_bars = bars self.alt_bars_labels = nums def show_alternate_values_of_p(self): new_prob = OldTex( "P(", "\\text{Correct}", ")", "=", "0.8" ) new_prob.set_color_by_tex("Correct", GREEN) new_prob.shift(FRAME_X_RADIUS*RIGHT/2) new_prob.to_edge(UP) alt_ps = 0.5, 0.65, 0.25 alt_rhss = VGroup() alt_charts = VGroup() for p in alt_ps: rhs = OldTex(str(p)) rhs.set_color(YELLOW) rhs.move_to(new_prob[-1]) alt_rhss.add(rhs) dist = get_binomial_distribution(3, p) values = list(map(dist, list(range(4)))) chart = self.bar_chart.copy() chart.change_bar_values(values) for label, bar in zip(chart.bar_top_labels, chart.bars): label.next_to(bar, UP) alt_charts.add(chart) self.play(FadeIn(new_prob)) self.play(Transform(new_prob[-1], alt_rhss[0])) point_5_probs = self.show_point_5_probs(new_prob) self.wait() self.play(Transform(self.bar_chart, alt_charts[0])) self.wait() self.play(FadeOut(point_5_probs)) for rhs, chart in list(zip(alt_rhss, alt_charts))[1:]: self.play(Transform(new_prob[-1], rhs)) self.play(Transform(self.bar_chart, chart)) self.wait(2) def show_point_5_probs(self, mob): probs = VGroup() last = mob for k in range(4): buff = MED_LARGE_BUFF for indices in it.combinations(list(range(3)), k): bool_list = np.array([False]*3) bool_list[list(indices)] = True prob = get_probability_of_slot_group(bool_list) rhs = OldTex("= (0.5)^3") rhs.next_to(prob, RIGHT) prob.add(rhs) prob.scale(0.9) prob.next_to(last, DOWN, buff) probs.add(prob) last = prob buff = SMALL_BUFF self.play(LaggedStartMap(FadeIn, probs)) self.wait() return probs class ProbablyWrong(TeacherStudentsScene): def construct(self): self.teacher_says( "Probably wrong!", run_time = 1, ) self.play_student_changes( *["angry"]*3, run_time = 1 ) self.wait() class ShowTrueDistribution(PiCreatureScene): def construct(self): self.force_skipping() self.remove(self.randy) self.add_title() self.show_distributions() self.show_emotion() self.imagine_score_0() self.revert_to_original_skipping_status() self.get_angry() def add_title(self): title = OldTex("P(", "\\text{Correct}", ")", "=", "0.65") title.to_edge(UP) title.set_color_by_tex("Correct", GREEN) self.add(title) self.title = title def show_distributions(self): dist = get_binomial_distribution(3, 0.65) values = np.array(list(map(dist, list(range(4))))) alt_values = values + [0.2, 0, 0, 0.2] alt_values /= sum(alt_values) chart = BarChart(values, bar_names = list(range(4))) bars = chart.bars old_bars = bars.copy() arrows = VGroup() for bar, old_bar in zip(bars, old_bars): for mob, vect in (bar, RIGHT), (old_bar, LEFT): mob.generate_target() mob.target.do_about_point( mob.get_corner(DOWN+vect), mob.target.stretch, 0.5, 0 ) old_bar.target.set_color(average_color(RED_E, BLACK)) old_bar.target.set_stroke(width = 0) arrow = Arrow(ORIGIN, UP, buff = 0, color = GREEN) arrow.move_to(bar.get_bottom()) arrow.shift(3*UP) arrows.add(arrow) for arrow in arrows[1:3]: arrow.rotate(np.pi) arrow.set_color(RED) arrows.set_color_by_gradient(BLUE, YELLOW) self.add(chart) self.play(*list(map(MoveToTarget, it.chain(bars, old_bars)))) self.play( chart.change_bar_values, alt_values, *list(map(ShowCreation, arrows)) ) self.wait(2) self.bar_chart = chart self.old_bars = old_bars def show_emotion(self): randy = self.randy self.play(FadeIn(randy)) self.play(randy.change, "sad") self.play(Blink(randy)) def imagine_score_0(self): prob_rect = SurroundingRectangle(self.title[-1]) bar_rect = SurroundingRectangle(VGroup( self.bar_chart.bars[0], self.old_bars[0], self.bar_chart.bar_labels[0], )) self.play(ShowCreation(prob_rect)) self.wait() self.play(ReplacementTransform( prob_rect, bar_rect )) self.wait() self.play(FadeOut(bar_rect)) def get_angry(self): randy = self.randy self.play(randy.change, "angry") self.wait(2) self.play(PiCreatureSays( randy, "It's not representative!", target_mode = "pleading", bubble_config = {"fill_opacity" : 1} )) self.wait(2) ##### def create_pi_creature(self): self.randy = Randolph() self.randy.to_corner(DOWN+LEFT) return self.randy class TeacherAssessingLiklihoodOfZero(TeacherStudentsScene): def construct(self): self.add_title() self.fade_other_students() self.show_independence_probability() self.teacher_reacts() def add_title(self): title = OldTex("P(", "\\text{Correct}", ")", "=", "0.65") title.to_edge(UP) title.set_color_by_tex("Correct", GREEN) q_mark = OldTex("?") q_mark.next_to(title[-2], UP, SMALL_BUFF) title.add(q_mark) self.add(title) self.title = title def fade_other_students(self): for student in self.students[0::2]: student.fade(0.7) self.pi_creatures.remove(student) def show_independence_probability(self): prob = get_probability_of_slot_group(3*[False]) rhs = OldTex("=", "(0.35)", "^3", "\\approx 4.3\\%") rhs.set_color_by_tex("0.35", RED) rhs.next_to(prob, RIGHT) prob.add(rhs) prob.next_to(self.teacher, UP+LEFT) words = OldTexText("Assuming independence") words.next_to(prob, UP) self.play( self.teacher.change, "raise_right_hand", FadeIn(words), Write(prob) ) self.wait() self.ind_group = VGroup(prob, words) def teacher_reacts(self): ind_group = self.ind_group box = SurroundingRectangle(ind_group) box.set_stroke(WHITE, 0) ind_group.add(box) ind_group.generate_target() ind_group.target.scale(0.7) ind_group.target.to_corner(UP+RIGHT, MED_SMALL_BUFF) ind_group.target[-1].set_stroke(WHITE, 2) randy = self.students[1] self.teacher_says( "Highly unlikely", target_mode = "sassy", added_anims = [MoveToTarget(ind_group)], run_time = 2, ) self.play(randy.change, "sad") self.wait(2) self.play( RemovePiCreatureBubble( self.teacher, target_mode = "guilty", ), PiCreatureSays(randy, "Wait!", target_mode = "surprised"), run_time = 1 ) self.wait(1) class CorrelationsWith35Percent(ThousandPossibleQuizzes): def construct(self): self.add_top_calculation() self.show_first_split() self.show_second_split() self.show_third_split() self.comment_on_final_size() def add_top_calculation(self): equation = VGroup( get_probability_of_slot_group(3*[False]), OldTex("="), get_probability_of_slot_group([False]), get_probability_of_slot_group(2*[False], [False]), get_probability_of_slot_group(3*[False], 2*[False]), ) equation.arrange(RIGHT, buff = SMALL_BUFF) equation.to_edge(UP) self.add(equation) self.equation = equation def show_first_split(self): quizzes = self.get_thousand_quizzes() n = int(0.65*len(quizzes)) top_part = VGroup(*quizzes[:n]) bottom_part = VGroup(*quizzes[n:]) parts = [top_part, bottom_part] for part, color in zip(parts, [GREEN, RED]): part.generate_target() for quiz in part.target: quiz[0].set_color(color) top_part.target.shift(UP) brace = Brace(bottom_part, LEFT) prop = OldTex("0.35") prop.next_to(brace, LEFT) term = self.equation[2] term_brace = Brace(term, DOWN) self.add(quizzes) self.wait() self.play( GrowFromCenter(brace), FadeIn(prop), *list(map(MoveToTarget, parts)) ) self.wait() self.play( top_part.fade, 0.8, Transform(brace, term_brace), prop.next_to, term_brace, DOWN, ) self.wait() self.quizzes = bottom_part self.quizzes.sort(lambda p : p[0]) def show_second_split(self): n = int(0.45*len(self.quizzes)) left_part = VGroup(*self.quizzes[:n]) right_part = VGroup(*self.quizzes[n:]) parts = [left_part, right_part] for part, color in zip(parts, [GREEN, RED_E]): part.generate_target() for quiz in part.target: quiz[1].set_color(color) left_part.target.shift(LEFT) brace = Brace(right_part, UP) prop = OldTex(">0.35") prop.next_to(brace, UP) term = self.equation[3] term_brace = Brace(term, DOWN) self.play( GrowFromCenter(brace), FadeIn(prop), *list(map(MoveToTarget, parts)) ) self.wait() self.play( Transform(brace, term_brace), prop.next_to, term_brace, DOWN ) self.play(left_part.fade, 0.8) self.quizzes = right_part self.quizzes.sort(lambda p : -p[1]) def show_third_split(self): quizzes = self.quizzes n = int(0.22*len(quizzes)) top_part = VGroup(*quizzes[:n]) bottom_part = VGroup(*quizzes[n:]) parts = [top_part, bottom_part] for part, color in zip(parts, [GREEN, RED_B]): part.generate_target() for quiz in part.target: quiz[2].set_color(color) top_part.target.shift(0.5*UP) brace = Brace(bottom_part, LEFT) prop = OldTex("\\gg 0.35") prop.next_to(brace, LEFT) term = self.equation[4] term_brace = Brace(term, DOWN) self.play( GrowFromCenter(brace), FadeIn(prop), *list(map(MoveToTarget, parts)) ) self.wait() self.play( Transform(brace, term_brace), prop.next_to, term_brace, DOWN, ) self.play(top_part.fade, 0.8) self.wait() self.quizzes = bottom_part def comment_on_final_size(self): rect = SurroundingRectangle(self.quizzes) words = OldTexText( "Much more than ", "$(0.35)^3 \\approx 4.3\\%$" ) words.next_to(rect, LEFT) self.play( ShowCreation(rect), FadeIn(words) ) self.wait() class WeighingIndependenceAssumption(PiCreatureScene): def construct(self): randy = self.randy title = OldTexText("Independence") title.scale(1.5) title.to_edge(UP) self.add(title) formula = OldTex( "P(", "A", "B", ")", "=" "P(", "A", ")", "P(", "B", ")" ) formula.set_color_by_tex("A", BLUE) formula.set_color_by_tex("B", GREEN) clean = OldTexText("Clean") clean.next_to(formula, UP) VGroup(clean, formula).next_to(randy, UP+LEFT) clean.save_state() clean.shift(2*(DOWN+RIGHT)) clean.set_fill(opacity = 0) self.play( randy.change, "raise_left_hand", clean, clean.restore ) self.play(Write(formula)) self.play( randy.change, "raise_right_hand", randy.look, UP+RIGHT, ) self.wait(2) #### def create_pi_creature(self): self.randy = Randolph().to_edge(DOWN) return self.randy class NameBinomial(Scene): CONFIG = { "flip_indices" : [0, 2, 4, 5, 6, 7], } def construct(self): self.name_distribution() self.add_quiz_questions() self.change_to_gender() self.change_bar_chart_for_gender_example() self.point_out_example_input() self.write_probability_of_girl() self.think_through_probabilities() def name_distribution(self): ns = [3, 10] p = 0.65 charts = VGroup() for n in ns: dist = get_binomial_distribution(n, p) values = list(map(dist, list(range(n+1)))) chart = BarChart(values, bar_names = list(range(n+1))) chart.to_edge(LEFT) charts.add(chart) probability = OldTex( "P(", "\\checkmark", ")", "=", str(p) ) probability.set_color_by_tex("checkmark", GREEN) probability.move_to(charts, UP) title = OldTexText("``Binomial distribution''") title.next_to(charts, UP) title.to_edge(UP) formula = OldTex( "P(X=", "k", ")=", "{n \\choose k}", "p", "^k", "(1-", "p", ")", "^{n-", "k}", arg_separator = "" ) formula.set_color_by_tex("p", YELLOW) formula.set_color_by_tex("k", GREEN) choose_part = formula.get_part_by_tex("choose") choose_part.set_color(WHITE) choose_part[-2].set_color(GREEN) formula.to_corner(UP+RIGHT) self.add(charts[0], probability) self.wait() self.play(Write(title)) self.wait() self.play(ReplacementTransform(*charts)) self.play(Write(formula)) self.wait() self.play( formula.scale, 0.7, formula.next_to, charts, DOWN, ) self.chart = charts[1] self.probability = probability self.title = title self.formula = formula def add_quiz_questions(self): n = 10 checkmarks = VGroup(*[ OldTex("\\checkmark").set_color(GREEN) for x in range(n) ]) checkmarks.arrange(DOWN, buff = 0.3) crosses = VGroup() arrows = VGroup() for checkmark in checkmarks: cross = OldTex("\\times") cross.set_color(RED) cross.next_to(checkmark, RIGHT, LARGE_BUFF) crosses.add(cross) arrow = Arrow( checkmark, cross, tip_length = 0.15, color = WHITE ) arrows.add(arrow) full_group = VGroup(checkmarks, crosses, arrows) full_group.center().to_corner(UP + RIGHT, buff = MED_LARGE_BUFF) flip_indices = self.flip_indices flipped_arrows, faded_crosses, full_checks = [ VGroup(*[group[i] for i in flip_indices]) for group in (arrows, crosses, checkmarks) ] faded_checkmarks = VGroup(*[m for m in checkmarks if m not in full_checks]) self.play(*[ LaggedStartMap( Write, mob, run_time = 3, lag_ratio = 0.3 ) for mob in full_group ]) self.wait() self.play( LaggedStartMap( Rotate, flipped_arrows, angle = np.pi, in_place = True, run_time = 2, lag_ratio = 0.5 ), faded_crosses.set_fill, None, 0.5, faded_checkmarks.set_fill, None, 0.5, ) self.wait() self.checkmarks = checkmarks self.crosses = crosses self.arrows = arrows def change_to_gender(self): flip_indices = self.flip_indices male = self.get_male() female = self.get_female() girls, boys = [ VGroup(*[ template.copy().move_to(mob) for mob in group ]) for template, group in [ (female, self.checkmarks), (male, self.crosses) ] ] for i in range(len(boys)): mob = boys[i] if i in flip_indices else girls[i] mob.set_fill(opacity = 0.5) brace = Brace(girls, LEFT) words = brace.get_text("$n$ children") self.play( GrowFromCenter(brace), FadeIn(words) ) for m1, m2 in (self.crosses, boys), (self.checkmarks, girls): self.play(ReplacementTransform( m1, m2, lag_ratio = 0.5, run_time = 3 )) self.wait() self.boys = boys self.girls = girls self.children_brace = brace self.n_children_words = words def change_bar_chart_for_gender_example(self): checkmark = self.probability.get_part_by_tex("checkmark") p_mob = self.probability[-1] female = self.get_female() female.move_to(checkmark) new_p_mob = OldTex("0.49") new_p_mob.move_to(p_mob, LEFT) dist = get_binomial_distribution(10, 0.49) values = list(map(dist, list(range(11)))) self.play( Transform(checkmark, female), Transform(p_mob, new_p_mob), ) self.play(self.chart.change_bar_values, values) self.wait() def point_out_example_input(self): boy_girl_groups = VGroup(*[ VGroup(boy, girl) for boy, girl in zip(self.boys, self.girls) ]) girl_rects = VGroup(*[ SurroundingRectangle( boy_girl_groups[i], color = MAROON_B, buff = SMALL_BUFF, ) for i in sorted(self.flip_indices) ]) chart = self.chart n_girls = len(girl_rects) chart_rect = SurroundingRectangle( VGroup(chart.bars[n_girls], chart.bar_labels[n_girls]), buff = SMALL_BUFF ) prob = OldTex( "P(", "\\# \\text{Girls}", "=", "6", ")" ) prob.set_color_by_tex("Girls", MAROON_B) arrow = Arrow(UP, ORIGIN, tip_length = 0.15) arrow.set_color(MAROON_B) arrow.next_to(prob, DOWN) prob.add(arrow) prob.next_to(chart_rect, UP) girls = VGroup(*[self.girls[i] for i in self.flip_indices]) self.play(ShowCreation(chart_rect)) self.play(LaggedStartMap( ShowCreation, girl_rects, run_time = 2, lag_ratio = 0.5, )) self.wait() self.play(Write(prob)) self.play(LaggedStartMap( Indicate, girls, run_time = 3, lag_ratio = 0.3, rate_func = there_and_back )) self.play(FadeOut(prob)) self.wait() self.chart_rect = chart_rect self.girl_rects = girl_rects def write_probability_of_girl(self): probability = self.probability probability_copies = VGroup(*[ probability.copy().scale(0.7).next_to( girl, LEFT, MED_LARGE_BUFF ) for girl in self.girls ]) self.play(FocusOn(probability)) self.play(Indicate(probability[-1])) self.wait() self.play( ReplacementTransform( VGroup(probability.copy()), probability_copies ), FadeOut(self.children_brace), FadeOut(self.n_children_words), ) self.wait() self.probability_copies = probability_copies def think_through_probabilities(self): randy = Randolph().scale(0.5) randy.next_to(self.probability_copies, LEFT, LARGE_BUFF) self.play(FadeIn(randy)) self.play(randy.change, "pondering") self.play(Blink(randy)) self.wait() ## def get_male(self): return OldTex("\\male").scale(1.3).set_color(BLUE) def get_female(self): return OldTex("\\female").scale(1.3).set_color(MAROON_B) class CycleThroughPatterns(NameBinomial): CONFIG = { "n_patterns_shown" : 100, "pattern_scale_value" : 2.7, "n" : 10, "k" : 6, } def construct(self): n = self.n k = self.k question = OldTexText( "How many patterns have \\\\ %d "%k, "$\\female$", " and %d "%(n-k), "$\\male$", "?", arg_separator = "" ) question.set_color_by_tex("male", BLUE) question.set_color_by_tex("female", MAROON_B) question.set_width(FRAME_WIDTH - 1) question.to_edge(UP, buff = LARGE_BUFF) self.add(question) all_combinations = list(it.combinations(list(range(n)), k)) shown_combinations = all_combinations[:self.n_patterns_shown] patterns = VGroup(*[ self.get_pattern(indicies) for indicies in shown_combinations ]) patterns.to_edge(DOWN, buff = LARGE_BUFF) pattern = patterns[0] self.add(pattern) for new_pattern in ProgressDisplay(patterns[1:]): self.play(*[ Transform( getattr(pattern, attr), getattr(new_pattern, attr), path_arc = np.pi ) for attr in ("boys", "girls") ]) #### def get_pattern(self, indices): pattern = VGroup() pattern.boys = VGroup() pattern.girls = VGroup() for i in range(self.n): if i in indices: mob = self.get_female() pattern.girls.add(mob) else: mob = self.get_male() pattern.boys.add(mob) mob.shift(i*MED_LARGE_BUFF*RIGHT) pattern.add(mob) pattern.scale(self.pattern_scale_value) pattern.to_edge(LEFT) return pattern class Compute6of10GirlsProbability(CycleThroughPatterns): def construct(self): self.show_combinations() self.write_n_choose_k() def show_combinations(self): pattern_rect = ScreenRectangle(height = 4) pattern_rect.center() pattern_rect.to_edge(UP, buff = MED_SMALL_BUFF) self.add(pattern_rect) self.wait(5) self.pattern_rect = pattern_rect def write_n_choose_k(self): brace = Brace(self.pattern_rect, DOWN) ten_choose_six = brace.get_tex("{10 \\choose 6}") see_chapter_one = OldTexText("(See chapter 1)") see_chapter_one.next_to(ten_choose_six, DOWN) see_chapter_one.set_color(GREEN) computation = OldTex( "=\\frac{%s}{%s}"%( "\\cdot ".join(map(str, list(range(10, 4, -1)))), "\\cdot ".join(map(str, list(range(1, 7)))), ) ) computation.move_to(ten_choose_six, UP) rhs = OldTex("=", "210") rhs.next_to(computation, RIGHT) self.play( FadeIn(see_chapter_one), GrowFromCenter(brace) ) self.play(Write(ten_choose_six)) self.wait(2) self.play( ten_choose_six.next_to, computation.copy(), LEFT, Write(VGroup(computation, rhs)) ) self.wait() self.ten_choose_six = ten_choose_six self.rhs = rhs class ProbabilityOfAGivenBoyGirlPattern(CycleThroughPatterns): def construct(self): self.write_total_count() self.write_example_probability() self.write_total_probability() def write_total_count(self): count = OldTexText( "${10 \\choose 6}$", " $= 210$", "total patterns." ) count.to_edge(UP) self.add(count) self.count = count def write_example_probability(self): prob = OldTex("P\\big(", "O "*15, "\\big)", "=") indices = [1, 2, 4, 6, 8, 9] pattern = self.get_pattern(indices) pattern.replace(prob[1], dim_to_match = 0) prob.submobjects[1] = pattern prob.next_to(self.count, DOWN, LARGE_BUFF) gp = OldTex("P(\\female)") gp[2].set_color(MAROON_B) bp = OldTex("P(\\male)") bp[2].set_color(BLUE) gp_num = OldTex("(0.49)").set_color(MAROON_B) bp_num = OldTex("(0.51)").set_color(BLUE) gp_nums = VGroup() bp_nums = VGroup() factored = VGroup() factored_in_nums = VGroup() for i in range(10): if i in indices: num_mob = gp_num.copy() gp_nums.add(num_mob) p_mob = gp.copy() else: num_mob = bp_num.copy() bp_nums.add(num_mob) p_mob = bp.copy() factored_in_nums.add(num_mob) factored.add(p_mob) for group in factored, factored_in_nums: group.arrange(RIGHT, buff = SMALL_BUFF) group.next_to(prob, DOWN, MED_LARGE_BUFF) gp_nums.save_state() bp_nums.save_state() final_probability = OldTex( "(0.49)^6", "(0.51)^4" ) final_probability.set_color_by_tex("0.49", MAROON_B) final_probability.set_color_by_tex("0.51", BLUE) final_probability.next_to(factored_in_nums, DOWN, LARGE_BUFF) self.play(FadeIn(prob)) self.wait() self.play(ReplacementTransform( pattern.copy(), factored, run_time = 1.5, )) self.wait(2) self.play(ReplacementTransform( factored, factored_in_nums, run_time = 2, lag_ratio = 0.5 )) self.wait(2) for group, tex in (gp_nums, "0.49"), (bp_nums, "0.51"): part = final_probability.get_part_by_tex(tex) self.play(group.shift, MED_LARGE_BUFF*DOWN) self.play( ReplacementTransform( group.copy(), VGroup(VGroup(*part[:-1])) ), Write(part[-1]) ) self.wait() self.play(group.restore) self.wait() self.final_probability = final_probability def write_total_probability(self): ten_choose_six = self.count[0].copy() ten_choose_six.generate_target() ten_choose_six.target.move_to(self.final_probability) p_tex = OldTex("P(", "\\text{6 Girls}", ")", "=") p_tex.set_color_by_tex("Girls", MAROON_B) p_tex.next_to(ten_choose_six.target, LEFT) self.play( Write(p_tex, run_time = 2), self.final_probability.next_to, ten_choose_six.target, RIGHT ) self.play(MoveToTarget(ten_choose_six)) self.wait() class CycleThroughPatternsForThree(CycleThroughPatterns): CONFIG = { "k" : 3, "n_patterns_shown" : 20, } class GeneralBinomialDistributionValues(Scene): CONFIG = { "n" : 10, "alt_n" : 8, "p" : 0.49, } def construct(self): self.add_chart() self.show_a_few_values() self.compare_to_pascal_row() self.mention_center_concentration() self.generalize() self.play_with_p_value() def add_chart(self): dist = get_binomial_distribution(self.n, self.p) values = list(map(dist, list(range(self.n+1)))) chart = BarChart( values, bar_names = list(range(self.n+1)) ) chart.to_edge(LEFT) full_probability = self.get_probability_expression( "10", "k", "(0.49)", "(0.51)" ) full_probability.next_to(chart, UP, aligned_edge = LEFT) self.add(chart) self.chart = chart self.full_probability = full_probability def show_a_few_values(self): chart = self.chart probabilities = VGroup() for i, bar in enumerate(chart.bars): prob = self.get_probability_expression( "10", str(i), "(0.49)", "(0.51)", full = False ) arrow = Arrow( UP, DOWN, color = WHITE, tip_length = 0.15 ) arrow.next_to(bar, UP, SMALL_BUFF) prob.next_to(arrow, UP, SMALL_BUFF) ## prob.shift(LEFT) prob.shift_onto_screen() prob.shift(RIGHT) ## prob.add(arrow) probabilities.add(prob) shown_prob = probabilities[6].copy() self.play(FadeIn(shown_prob)) self.wait() self.play(LaggedStartMap( FadeIn, self.full_probability, run_time = 4, lag_ratio = 0.5, )) self.wait() last_k = 6 for k in 3, 8, 5, 9, 6: self.play(Transform( shown_prob, probabilities[k], path_arc = -np.pi/6 if k > last_k else np.pi/6 )) self.wait(2) last_k = k self.shown_prob = shown_prob def compare_to_pascal_row(self): triangle = PascalsTriangle(nrows = 11) triangle.set_width(6) triangle.to_corner(UP+RIGHT) last_row = VGroup(*[ triangle.coords_to_mobs[10][k] for k in range(11) ]) ten_choose_ks = VGroup() for k, mob in enumerate(last_row): ten_choose_k = OldTex("10 \\choose %s"%k) ten_choose_k.scale(0.5) ten_choose_k.stretch(0.8, 0) ten_choose_k.next_to(mob, DOWN) ten_choose_ks.add(ten_choose_k) ten_choose_ks.set_color_by_gradient(BLUE, YELLOW) self.play( LaggedStartMap(FadeIn, triangle), FadeOut(self.shown_prob) ) self.play( last_row.set_color_by_gradient, BLUE, YELLOW, Write(ten_choose_ks, run_time = 2) ) self.wait() self.play(ApplyWave(self.chart.bars, direction = UP)) self.play(FocusOn(last_row)) self.play(LaggedStartMap( ApplyMethod, last_row, lambda m : (m.scale, 1.2), rate_func = there_and_back, )) self.wait() self.pascals_triangle = triangle self.ten_choose_ks = ten_choose_ks def mention_center_concentration(self): bars = self.chart.bars bars.generate_target() bars.save_state() bars.target.arrange(UP, buff = 0) bars.target.stretch_to_fit_height(self.chart.height) bars.target.move_to( self.chart.x_axis.point_from_proportion(0.05), DOWN ) brace = Brace(VGroup(*bars.target[4:7]), RIGHT) words = brace.get_text("Most probability \\\\ in middle values") self.play(MoveToTarget(bars)) self.play( GrowFromCenter(brace), FadeIn(words) ) self.wait(2) self.play( bars.restore, *list(map(FadeOut, [ brace, words, self.pascals_triangle, self.ten_choose_ks ])) ) def generalize(self): alt_n = self.alt_n dist = get_binomial_distribution(alt_n, self.p) values = list(map(dist, list(range(alt_n + 1)))) alt_chart = BarChart( values, bar_names = list(range(alt_n + 1)) ) alt_chart.move_to(self.chart) alt_probs = [ self.get_probability_expression("n", "k", "(0.49)", "(0.51)"), self.get_probability_expression("n", "k", "p", "(1-p)"), ] for prob in alt_probs: prob.move_to(self.full_probability) self.play(FocusOn( self.full_probability.get_part_by_tex("choose") )) self.play( ReplacementTransform(self.chart, alt_chart), Transform(self.full_probability, alt_probs[0]) ) self.chart = alt_chart self.wait(2) self.play(Transform(self.full_probability, alt_probs[1])) self.wait() def play_with_p_value(self): p = self.p interval = UnitInterval(color = WHITE) interval.set_width(5) interval.next_to(self.full_probability, DOWN, LARGE_BUFF) interval.add_numbers(0, 0.5, 1) triangle = RegularPolygon( n=3, start_angle = -np.pi/2, fill_color = MAROON_B, fill_opacity = 1, stroke_width = 0, ) triangle.set_height(0.25) triangle.move_to(interval.number_to_point(p), DOWN) p_mob = OldTex("p") p_mob.set_color(MAROON_B) p_mob.next_to(triangle, UP, SMALL_BUFF) triangle.add(p_mob) new_p_values = [0.8, 0.4, 0.2, 0.9, 0.97, 0.6] self.play( ShowCreation(interval), Write(triangle, run_time = 1) ) self.wait() for new_p in new_p_values: p = new_p dist = get_binomial_distribution(self.alt_n, p) values = list(map(dist, list(range(self.alt_n + 1)))) self.play( self.chart.change_bar_values, values, triangle.move_to, interval.number_to_point(p), DOWN ) self.wait() ####### def get_probability_expression( self, n = "n", k = "k", p = "p", q = "(1-p)", full = True ): args = [] if full: args += ["P(", "\\# \\text{Girls}", "=", k, ")", "="] args += [ "{%s \\choose %s}"%(n, k), p, "^%s"%k, q, "^{%s"%n, "-", "%s}"%k, ] result = OldTex(*args, arg_separator = "") color_map = { "Girls" : MAROON_B, n : WHITE, k : YELLOW, p : MAROON_B, q : BLUE, } result.set_color_by_tex_to_color_map(color_map) choose_part = result.get_part_by_tex("choose") choose_part.set_color(WHITE) VGroup(*choose_part[1:1+len(n)]).set_color(color_map[n]) VGroup(*choose_part[-1-len(k):-1]).set_color(color_map[k]) return result class PointOutSimplicityOfFormula(TeacherStudentsScene, GeneralBinomialDistributionValues): def construct(self): prob = self.get_probability_expression(full = False) corner = self.teacher.get_corner(UP+LEFT) prob.next_to(corner, UP, MED_LARGE_BUFF) prob.save_state() prob.move_to(corner) prob.set_fill(opacity = 0) self.play( prob.restore, self.teacher.change_mode, "raise_right_hand" ) self.play_student_changes( *["pondering"]*3, look_at = prob ) self.wait() self.student_says( "Simpler than I feared", target_mode = "hooray", index = 0, added_anims = [prob.to_corner, UP+RIGHT] ) self.wait() self.teacher_says("Due to \\\\ independence") self.wait(2) class CorrectForDependence(NameBinomial): CONFIG = { "flip_indices" : [3, 6, 8], } def setup(self): self.force_skipping() self.name_distribution() self.add_quiz_questions() self.revert_to_original_skipping_status() def construct(self): self.mention_dependence() self.show_tendency_to_align() self.adjust_chart() def mention_dependence(self): brace = Brace(self.checkmarks, LEFT) words = brace.get_text("What if there's \\\\ correlation?") formula = self.formula cross = Cross(formula) self.play( GrowFromCenter(brace), Write(words) ) self.wait() self.play(ShowCreation(cross)) self.wait() def show_tendency_to_align(self): checkmarks = self.checkmarks arrows = self.arrows crosses = self.crosses groups = [ VGroup(*trip) for trip in zip(checkmarks, arrows, crosses) ] top_rect = SurroundingRectangle(groups[0]) top_rect.set_color(GREEN) indices_to_follow = [1, 4, 5, 7] self.play(ShowCreation(top_rect)) self.play(*self.get_arrow_flip_anims([0])) self.wait() self.play(*self.get_arrow_flip_anims(indices_to_follow)) self.play(FocusOn(self.chart.bars)) def adjust_chart(self): chart = self.chart bars = chart.bars old_bars = bars.copy() old_bars.generate_target() bars.generate_target() for group, vect in (old_bars, LEFT), (bars, RIGHT): for bar in group.target: side = bar.get_edge_center(vect) bar.stretch(0.5, 0) bar.move_to(side, vect) for bar in old_bars.target: bar.set_color(average_color(RED_E, BLACK)) dist = get_binomial_distribution(10, 0.65) values = np.array(list(map(dist, list(range(11))))) alt_values = values + 0.1 alt_values[0] -= 0.06 alt_values[1] -= 0.03 alt_values /= sum(alt_values) arrows = VGroup() arrow_template = Arrow( 0.5*UP, ORIGIN, buff = 0, tip_length = 0.15, color = WHITE ) for value, alt_value, bar in zip(values, alt_values, bars): arrow = arrow_template.copy() if value < alt_value: arrow.rotate(np.pi, about_point = ORIGIN) arrow.next_to(bar, UP) arrows.add(arrow) self.play( MoveToTarget(old_bars), MoveToTarget(bars), ) self.wait() self.play(*list(map(ShowCreation, arrows))) self.play(chart.change_bar_values, alt_values) ###### def get_arrow_flip_anims(self, indices): checkmarks, arrows, crosses = movers = [ VGroup(*[ group[i] for i in range(len(group)) if i in indices ]) for group in (self.checkmarks, self.arrows, self.crosses) ] for arrow in arrows: arrow.target = arrow.deepcopy() arrow.target.rotate(np.pi) for group in checkmarks, crosses: for mob, arrow in zip(group, arrows): mob.generate_target() c = mob.get_center() start, end = arrow.target.get_start_and_end() to_end = get_norm(c - end) to_start = get_norm(c - start) if to_end < to_start: mob.target.set_fill(opacity = 1) else: mob.target.set_fill(opacity = 0.5) for checkmark in checkmarks: checkmark.target.scale(1.2) kwargs = {"path_arc" : np.pi} if len(indices) > 1: kwargs.update({"run_time" : 2}) return [ LaggedStartMap( MoveToTarget, mover, **kwargs ) for mover in movers ] class ButWhatsTheAnswer(TeacherStudentsScene): def construct(self): self.student_says( "But what's the \\\\ actual answer?", target_mode = "confused" ) self.play_student_changes(*["confused"]*3) self.wait() self.play(self.teacher.change, "pondering") self.wait(3) class PermuteQuizQuestions(Scene): def construct(self): quiz = get_quiz( "Define ``Brachistochrone''", "Define ``Tautochrone''", "Define ``Cycloid''", ) questions = [ VGroup(*q[2:]) for q in quiz.questions ] colors = [BLUE, GREEN, RED] for color, question in zip(colors, questions): question.set_color(color) quiz.scale(2) self.add(quiz) self.wait() for m1, m2 in it.combinations(questions, 2): self.play( m1.move_to, m2, LEFT, m2.move_to, m1, LEFT, path_arc = np.pi ) self.wait() class AssumeOrderDoesntMatter(Scene): def construct(self): self.force_skipping() self.add_title() self.show_equality() self.mention_correlation() self.revert_to_original_skipping_status() self.coming_soon() def add_title(self): title = OldTexText( "Softer simplifying assumption: " +\ "Order doesn't matter" ) title.to_edge(UP) self.add(title) self.title = title def show_equality(self): n = 3 prob_groups = VGroup(*[ VGroup(*list(map( get_probability_of_slot_group, [t for t in it.product(*[[True, False]]*n) if sum(t) == k] ))) for k in range(n+1) ]) for prob_group in prob_groups: for prob in prob_group[:-1]: equals = OldTex("=") equals.next_to(prob, RIGHT) prob.add(equals) prob_group.arrange(RIGHT) max_width = FRAME_WIDTH - 1 if prob_group.get_width() > max_width: prob_group.set_width(max_width) prob_groups.arrange(DOWN, buff = 0.7) prob_groups.next_to(self.title, DOWN, MED_LARGE_BUFF) self.play(FadeIn( prob_groups[1], run_time = 2, lag_ratio = 0.5 )) self.wait(2) self.play(FadeIn( VGroup(prob_groups[0], *prob_groups[2:]), run_time = 3, lag_ratio = 0.5 )) self.wait() self.prob_groups = prob_groups def mention_correlation(self): assumption_group = VGroup(*self.get_top_level_mobjects()) question = OldTexText( "But what is ", "``correlation''", "?", arg_separator = "" ) question.set_color(BLUE) question.to_edge(UP) bottom = question.get_bottom() self.play( Write(question), assumption_group.next_to, bottom, DOWN, LARGE_BUFF ) self.wait() self.assumption_group = assumption_group self.question = question def coming_soon(self): self.play( LaggedStartMap( ApplyMethod, self.assumption_group, lambda m : (m.shift, FRAME_HEIGHT*DOWN), remover = True, ), ApplyMethod( self.question.center, rate_func = squish_rate_func(smooth, 0.5, 1), run_time = 2 ) ) part = self.question.get_part_by_tex("correlation") brace = Brace(part, UP) words = brace.get_text("Coming soon!") self.play( GrowFromCenter(brace), part.set_color, YELLOW ) self.play(Write(words)) self.wait() class FormulaCanBeRediscovered(PointOutSimplicityOfFormula): def construct(self): prob = self.get_probability_expression(full = False) corner = self.teacher.get_corner(UP+LEFT) prob.next_to(corner, UP, MED_LARGE_BUFF) brace = Brace(prob, UP) rediscover = brace.get_text("Rediscover") self.play( Write(prob), self.teacher.change, "hesitant", prob ) self.wait() self.play( GrowFromCenter(brace), Write(rediscover, run_time = 1) ) self.play_student_changes(*["happy"]*3) self.wait(2) class CompareTwoSituations(PiCreatureScene): def construct(self): randy = self.randy top_left, top_right = screens = [ ScreenRectangle(height = 3).to_corner(vect) for vect in (UP+LEFT, UP+RIGHT) ] arrow = DoubleArrow(*screens, buff = SMALL_BUFF) arrow.set_color(BLUE) for screen, s in zip(screens, ["left", "right"]): self.play( randy.change, "raise_%s_hand"%s, screen, ShowCreation(screen) ) self.wait(3) self.play( randy.change, "pondering", arrow, ShowCreation(arrow) ) self.wait(2) #### def create_pi_creature(self): self.randy = Randolph().to_edge(DOWN) return self.randy class SkepticalOfDistributions(TeacherStudentsScene): CONFIG = { "chart_height" : 3, } def construct(self): self.show_binomial() self.show_alternate_distributions() self.emphasize_underweighted_tails() def show_binomial(self): binomial = self.get_binomial() binomial.next_to(self.teacher.get_corner(UP+LEFT), UP) title = OldTexText("Probable scores") title.scale(0.85) title.next_to(binomial.bars, UP, 1.5*LARGE_BUFF) self.play( Write(title, run_time = 1), FadeIn(binomial, run_time = 1, lag_ratio = 0.5), self.teacher.change, "raise_right_hand" ) for values in binomial.values_list: self.play(binomial.change_bar_values, values) self.wait() self.student_says( "Is that valid?", target_mode = "sassy", index = 0, run_time = 1 ) self.play(self.teacher.change, "guilty") self.wait() binomial.add(title) self.binomial = binomial def show_alternate_distributions(self): poisson = self.get_poisson() VGroup(poisson, poisson.title).next_to( self.students, UP, LARGE_BUFF ).shift(RIGHT) gaussian = self.get_gaussian() VGroup(gaussian, gaussian.title).next_to( poisson, RIGHT, LARGE_BUFF ) self.play( FadeIn(poisson, lag_ratio = 0.5), RemovePiCreatureBubble(self.students[0]), self.teacher.change, "raise_right_hand", self.binomial.scale, 0.5, self.binomial.to_corner, UP+LEFT, ) self.play(Write(poisson.title, run_time = 1)) self.play(FadeIn(gaussian, lag_ratio = 0.5)) self.play(Write(gaussian.title, run_time = 1)) self.wait(2) self.play_student_changes( *["sassy"]*3, added_anims = [self.teacher.change, "plain"] ) self.wait(2) self.poisson = poisson self.gaussian = gaussian def emphasize_underweighted_tails(self): poisson_arrows = VGroup() arrow_template = Arrow( ORIGIN, UP, color = GREEN, tip_length = 0.15 ) for bar in self.poisson.bars[-4:]: arrow = arrow_template.copy() arrow.next_to(bar, UP, SMALL_BUFF) poisson_arrows.add(arrow) gaussian_arrows = VGroup() for prop in 0.2, 0.8: point = self.gaussian[0][0].point_from_proportion(prop) arrow = arrow_template.copy() arrow.next_to(point, UP, SMALL_BUFF) gaussian_arrows.add(arrow) for arrows in poisson_arrows, gaussian_arrows: self.play( ShowCreation( arrows, lag_ratio = 0.5, run_time = 2 ), *[ ApplyMethod(pi.change, "thinking", arrows) for pi in self.pi_creatures ] ) self.wait() self.wait(2) #### def get_binomial(self): k_range = list(range(11)) dists = [ get_binomial_distribution(10, p) for p in (0.2, 0.8, 0.5) ] values_list = [ list(map(dist, k_range)) for dist in dists ] chart = BarChart( values = values_list[-1], bar_names = k_range ) chart.set_height(self.chart_height) chart.values_list = values_list return chart def get_poisson(self): k_range = list(range(11)) L = 2 values = [ np.exp(-L) * (L**k) / (scipy.special.gamma(k+1)) for k in k_range ] chart = BarChart( values = values, bar_names = k_range, bar_colors = [RED, YELLOW] ) chart.set_height(self.chart_height) title = OldTexText( "Poisson distribution \\\\", "$e^{-\\lambda}\\frac{\\lambda^k}{k!}$" ) title.scale(0.75) title.move_to(chart, UP) title.shift(MED_SMALL_BUFF*RIGHT) title[0].shift(SMALL_BUFF*UP) chart.title = title return chart def get_gaussian(self): axes = VGroup(self.binomial.x_axis, self.binomial.y_axis).copy() graph = FunctionGraph( lambda x : 5*np.exp(-x**2), mark_paths_closed = True, fill_color = BLUE_E, fill_opacity = 1, stroke_color = BLUE, ) graph.set_width(axes.get_width()) graph.move_to(axes[0], DOWN) title = OldTexText( "Gaussian distribution \\\\ ", "$\\frac{1}{\\sqrt{2\\pi \\sigma^2}} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}$" ) title.scale(0.75) title.move_to(axes, UP) title.shift(MED_SMALL_BUFF*RIGHT) title[0].shift(SMALL_BUFF*UP) result = VGroup(axes, graph) result.title = title return result class IndependencePatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Desmos", "Burt Humburg", "CrypticSwarm", "Juan Benet", "Mayank M. Mehrotra", "Lukas Biewald", "Samantha D. Suplee", "James Park", "Erik Sundell", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Karan Bhargava", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Markus Persson", "Yoni Nazarathy", "Corey Ogburn", "Ed Kellett", "Joseph John Cox", "Dan Buchoff", "Luc Ritchie", "Tianyu Ge", "Ted Suzman", "Amir Fayazi", "Linh Tran", "Andrew Busey", "Michael McGuffin", "John Haley", "Mourits de Beer", "Ankalagon", "Eric Lavault", "Tomohiro Furusawa", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Mark Govea", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Nils Schneider", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], } class Thumbnail(DangerInProbability): def construct(self): n, p = 15, 0.5 dist = get_binomial_distribution(n, p) values = np.array(list(map(dist, list(range(n+1))))) values *= 2 chart = BarChart( values = values, label_y_axis = False, width = FRAME_WIDTH - 3, height = 1.5*FRAME_Y_RADIUS ) chart.to_edge(DOWN) self.add(chart) warning = self.get_warning_sign() warning.set_height(2) warning.to_edge(UP) self.add(warning) words = OldTexText("Independence") words.scale(2.5) words.next_to(warning, DOWN) self.add(words)
from manim_imports_ext import * class Introduction(TeacherStudentsScene): CONFIG = { "default_pi_creature_kwargs": { "color": MAROON_E, "flip_at_start": True, }, } def construct(self): self.show_series() self.show_examples() def show_series(self): series = VideoSeries(num_videos = 11) series.to_edge(UP) this_video = series[0] this_video.set_color(YELLOW) this_video.save_state() this_video.set_fill(opacity = 0) this_video.center() this_video.set_height(FRAME_HEIGHT) self.this_video = this_video words = OldTexText( "Welcome to \\\\", "Essence of Probability" ) words.set_color_by_tex("Essence of Probability", YELLOW) self.teacher.change_mode("happy") self.play( FadeIn( series, lag_ratio = 0.5, run_time = 2 ), Blink(self.get_teacher()) ) self.teacher_says(words, target_mode = "hooray") self.play_student_changes( *["hooray"]*3, look_at = series[1].get_left(), added_anims = [ ApplyMethod(this_video.restore, run_time = 3), ] ) self.play(*[ ApplyMethod( video.shift, 0.5*video.get_height()*DOWN, run_time = 3, rate_func = squish_rate_func( there_and_back, alpha, alpha+0.3 ) ) for video, alpha in zip(series, np.linspace(0, 0.7, len(series))) ]+[ Animation(self.teacher.bubble), Animation(self.teacher.bubble.content), ]) self.play( FadeOut(self.teacher.bubble), FadeOut(self.teacher.bubble.content), self.get_teacher().change_mode, "raise_right_hand", *[ ApplyMethod(pi.change_mode, "pondering") for pi in self.get_students() ] ) self.wait() self.series = series def show_examples(self): self.wait(10) # put examples here in video editor
from manim_imports_ext import * #revert_to_original_skipping_status ######### class BayesOpeningQuote(OpeningQuote): CONFIG = { "quote" : [ "Inside every non-Bayesian there \\\\ is a Bayesian struggling to get out." ], "author" : "Dennis V. Lindley", } class IntroducePokerHand(PiCreatureScene, SampleSpaceScene): CONFIG = { "community_cards_center" : 1.5*DOWN, "community_card_values" : ["10S", "QH", "AH", "2C", "5H"], "your_hand_values" : ["JS", "KC"], } def construct(self): self.add_cards() self.indicate_straight() self.show_flush_potential() self.compute_flush_probability() self.show_flush_sample_space() self.talk_through_sample_space() self.place_high_bet() self.change_belief() self.move_community_cards_out_of_the_way() self.name_bayes_rule() def add_cards(self): you, her = self.you, self.her community_cards = VGroup(*list(map( PlayingCard, self.community_card_values ))) community_cards.arrange(RIGHT) community_cards.move_to(self.community_cards_center) deck = VGroup(*[ PlayingCard(turned_over = True) for x in range(5) ]) for i, card in enumerate(deck): card.shift(i*(0.03*RIGHT + 0.015*DOWN)) deck.next_to(community_cards, LEFT) you.hand = self.get_hand(you, self.your_hand_values) her.hand = self.get_hand(her, None) hand_cards = VGroup(*it.chain(*list(zip(you.hand, her.hand)))) self.add(deck) for group in hand_cards, community_cards: for card in group: card.generate_target() card.scale(0.01) card.move_to(deck[-1], UP+RIGHT) self.play(LaggedStartMap(MoveToTarget, group, lag_ratio = 0.8)) self.wait() self.wait() self.community_cards = community_cards self.deck = deck def indicate_straight(self): you = self.you community_cards = self.community_cards you.hand.save_state() you.hand.generate_target() for card in you.hand.target: card.set_height(community_cards.get_height()) selected_community_cards = VGroup(*[card for card in community_cards if card.numerical_value >= 10]) selected_community_cards.submobjects.sort( key=lambda c: c.numerical_value ) selected_community_cards.save_state() for card in selected_community_cards: card.generate_target() straight_cards = VGroup(*it.chain( you.hand.target, [c.target for c in selected_community_cards] )) straight_cards.submobjects.sort( key=lambda c: c.numerical_value ) straight_cards.arrange(RIGHT, buff = SMALL_BUFF) straight_cards.next_to(community_cards, UP, aligned_edge = LEFT) you.hand.target.shift(MED_SMALL_BUFF*UP) self.play(LaggedStartMap( MoveToTarget, selected_community_cards, run_time = 1.5 )) self.play(MoveToTarget(you.hand)) self.play(LaggedStartMap( ApplyMethod, straight_cards, lambda m : (m.set_color, YELLOW), rate_func = there_and_back, run_time = 1.5, lag_ratio = 0.5, remover = True, )) self.play(you.change, "hooray", straight_cards) self.wait(2) self.play( selected_community_cards.restore, you.hand.restore, you.change_mode, "happy" ) self.wait() def show_flush_potential(self): you, her = self.you, self.her heart_cards = VGroup(*[c for c in self.community_cards if c.suit == "hearts"]) heart_cards.save_state() her.hand.save_state() her.hand.generate_target() her.hand.target.arrange(RIGHT) her.hand.target.next_to(heart_cards, UP) her.hand.target.to_edge(UP) her.glasses.save_state() her.glasses.move_to(her.hand.target) her.glasses.set_fill(opacity = 0) heart_qs = VGroup() hearts = VGroup() q_marks = VGroup() for target in her.hand.target: heart = SuitSymbol("hearts") q_mark = OldTex("?") heart_q = VGroup(heart, q_mark) for mob in heart_q: mob.set_height(0.5) heart_q.arrange(RIGHT, buff = SMALL_BUFF) heart_q.move_to(target) heart_qs.add(heart, q_mark) hearts.add(heart) q_marks.add(q_mark) self.play(heart_cards.shift, heart_cards.get_height()*UP) self.play(you.change_mode, "hesitant") self.play(MoveToTarget(her.hand)) self.play(LaggedStartMap(DrawBorderThenFill, heart_qs)) self.play( her.change, "happy", her.glasses.restore, ) self.pi_creatures.remove(her) new_suit_pairs = [ ("clubs", "diamonds"), ("diamonds", "spades"), ("spades", "clubs"), ("hearts", "hearts"), ] for new_suit_pair in new_suit_pairs: new_symbols = VGroup(*list(map(SuitSymbol, new_suit_pair))) for new_symbol, heart in zip(new_symbols, hearts): new_symbol.replace(heart, dim_to_match = 1) self.play(Transform( hearts, new_symbols, lag_ratio = 0.5 )) self.wait() self.play(FadeOut(heart_qs)) self.play( heart_cards.restore, her.hand.restore, you.change_mode, "pondering", ) self.q_marks = q_marks def compute_flush_probability(self): you, her = self.you, self.her equation = OldTex( "{ {10 \\choose 2}", "\\over", "{45 \\choose 2} }", "=", "{45 \\over 990}", "\\approx", "4.5\\%" ) equation.next_to(self.community_cards, UP, buff = LARGE_BUFF) percentage = equation.get_part_by_tex("4.5") ten = VGroup(*equation[0][1:3]) num_hearts = OldTexText("\\# Remaining hearts") num_hearts.scale(0.75) num_hearts.next_to( ten, UP, aligned_edge = LEFT ) num_hearts.to_edge(UP) num_hearts.set_color(RED) num_hearts_arrow = Arrow( num_hearts.get_bottom(), ten.get_right(), color = RED, buff = SMALL_BUFF ) fourty_five = VGroup(*equation[2][1:3]) num_cards = OldTexText("\\# Remaining cards") num_cards.scale(0.75) num_cards.next_to(fourty_five, LEFT) num_cards.to_edge(LEFT) num_cards.set_color(BLUE) num_cards_arrow = Arrow( num_cards, fourty_five, color = BLUE, buff = SMALL_BUFF ) self.play(LaggedStartMap(FadeIn, equation)) self.wait(2) self.play( FadeIn(num_hearts), ShowCreation(num_hearts_arrow), ten.set_color, RED, ) self.play( FadeIn(num_cards), ShowCreation(num_cards_arrow), fourty_five.set_color, BLUE ) self.wait(3) equation.remove(percentage) self.play(*list(map(FadeOut, [ equation, num_hearts, num_hearts_arrow, num_cards, num_cards_arrow, ]))) self.percentage = percentage def show_flush_sample_space(self): you, her = self.you, self.her percentage = self.percentage sample_space = self.get_sample_space() sample_space.add_title("Your belief") sample_space.move_to(VGroup(you.hand, her.hand)) sample_space.to_edge(UP, buff = MED_SMALL_BUFF) p = 1./22 sample_space.divide_horizontally( p, colors = [SuitSymbol.CONFIG["red"], BLUE_E] ) braces, labels = sample_space.get_side_braces_and_labels([ percentage.get_tex(), "95.5\\%" ]) top_label, bottom_label = labels self.play( FadeIn(sample_space), ReplacementTransform(percentage, top_label) ) self.play(*list(map(GrowFromCenter, [ brace for brace in braces ]))) self.wait(2) self.play(Write(bottom_label)) self.wait(2) self.sample_space = sample_space def talk_through_sample_space(self): her = self.her sample_space = self.sample_space top_part, bottom_part = self.sample_space.horizontal_parts flush_hands, non_flush_hands = hand_lists = [ [self.get_hand(her, keys) for keys in key_list] for key_list in [ [("3H", "8H"), ("4H", "5H"), ("JH", "KH")], [("AC", "6D"), ("3D", "6S"), ("JH", "4C")], ] ] for hand_list, part in zip(hand_lists, [top_part, bottom_part]): self.play(Indicate(part, scale_factor = 1)) for hand in hand_list: hand.save_state() hand.scale(0.01) hand.move_to(part.get_right()) self.play(hand.restore) self.wait() self.wait() self.play(*list(map(FadeOut, it.chain(*hand_lists)))) def place_high_bet(self): you, her = self.you, self.her pre_money = VGroup(*[ VGroup(*[ OldTex("\\$") for x in range(10) ]).arrange(RIGHT, buff = SMALL_BUFF) for y in range(4) ]).arrange(UP, buff = SMALL_BUFF) money = VGroup(*it.chain(*pre_money)) money.set_color(GREEN) money.scale(0.8) money.next_to(her.hand, DOWN) for dollar in money: dollar.save_state() dollar.scale(0.01) dollar.move_to(her.get_boundary_point(RIGHT)) dollar.set_fill(opacity = 0) self.play(LaggedStartMap( ApplyMethod, money, lambda m : (m.restore,), run_time = 5, )) self.play(you.change_mode, "confused") self.wait() self.money = money def change_belief(self): numbers = self.sample_space.horizontal_parts.labels rect = Rectangle(stroke_width = 0) rect.set_fill(BLACK, 1) rect.stretch_to_fit_width(numbers.get_width()) rect.stretch_to_fit_height(self.sample_space.get_height()) rect.move_to(numbers, UP) self.play(FadeIn(rect)) anims = self.get_horizontal_division_change_animations(0.2) anims.append(Animation(rect)) self.play( *anims, run_time = 3, rate_func = there_and_back ) self.play(FadeOut(rect)) def move_community_cards_out_of_the_way(self): cards = self.community_cards cards.generate_target() cards.target.arrange( RIGHT, buff = -cards[0].get_width() + MED_SMALL_BUFF, ) cards.target.move_to(self.deck) cards.target.to_edge(LEFT) self.sample_space.add_braces_and_labels() self.play( self.deck.scale, 0.7, self.deck.next_to, cards.target, UP, self.deck.to_edge, LEFT, self.sample_space.shift, 3*DOWN, MoveToTarget(cards) ) def name_bayes_rule(self): title = OldTexText("Bayes' rule") title.set_color(BLUE) title.to_edge(UP) subtitle = OldTexText("Update ", "prior ", "beliefs") subtitle.scale(0.8) subtitle.next_to(title, DOWN) prior_word = subtitle.get_part_by_tex("prior") numbers = self.sample_space.horizontal_parts.labels rect = SurroundingRectangle(numbers, color = GREEN) arrow = Arrow(prior_word.get_bottom(), rect.get_top()) arrow.set_color(GREEN) words = OldTexText( "Maybe she really \\\\ does have a flush $\\dots$", alignment = "" ) words.scale(0.7) words.next_to(self.money, DOWN, aligned_edge = LEFT) self.play( Write(title, run_time = 2), self.you.change_mode, "pondering" ) self.wait() self.play(FadeIn(subtitle)) self.play(prior_word.set_color, GREEN) self.play( ShowCreation(rect), ShowCreation(arrow) ) self.wait(3) self.play(Write(words)) self.wait(3) ###### def create_pi_creatures(self): shift_val = 3 you = PiCreature(color = BLUE_D) her = PiCreature(color = BLUE_B).flip() for pi in you, her: pi.scale(0.5) you.to_corner(UP+LEFT) her.to_corner(UP+RIGHT) you.make_eye_contact(her) glasses = SunGlasses(her) her.glasses = glasses self.you = you self.her = her return VGroup(you, her) def get_hand(self, pi_creature, keys = None): if keys is not None: hand = VGroup(*list(map(PlayingCard, keys))) else: hand = VGroup(*[ PlayingCard(turned_over = True) for x in range(2) ]) hand.scale(0.7) card1, card2 = hand vect = np.sign(pi_creature.get_center()[0])*LEFT card2.move_to(card1) card2.shift(MED_SMALL_BUFF*RIGHT + SMALL_BUFF*DOWN) hand.next_to( pi_creature, vect, buff = MED_LARGE_BUFF, aligned_edge = UP ) return hand class HowDoesPokerWork(TeacherStudentsScene): def construct(self): self.student_says( "Wait, how does \\\\ poker work again?", target_mode = "confused", run_time = 1 ) self.play_student_changes(*["confused"]*3) self.wait(2) class YourGutKnowsBayesRule(TeacherStudentsScene): def construct(self): self.teacher_says( "Your gut knows \\\\ Bayes' rule.", run_time = 1 ) self.play_student_changes("confused", "gracious", "guilty") self.wait(3) class UpdatePokerPrior(SampleSpaceScene): CONFIG = { "double_heart_template" : "HH", "cash_string" : "\\$\\$\\$", } def construct(self): self.add_sample_space() self.add_top_conditionals() self.react_to_top_conditionals() self.add_bottom_conditionals() self.ask_where_conditionals_come_from() self.vary_conditionals() self.show_restricted_space() self.write_P_flush_given_bet() self.reshape_rectangles() self.compare_prior_to_posterior() self.preview_tweaks() self.tweak_non_flush_case() self.tweak_flush_case() self.tweak_prior() self.compute_posterior() def add_sample_space(self): p = 1./22 sample_space = SampleSpace(fill_opacity = 0) sample_space.shift(LEFT) sample_space.divide_horizontally(p, colors = [ SuitSymbol.CONFIG["red"], BLUE_E ]) labels = self.get_prior_labels(p) braces_and_labels = sample_space.get_side_braces_and_labels(labels) self.play( LaggedStartMap(FadeIn, sample_space), Write(braces_and_labels) ) self.wait() sample_space.add(braces_and_labels) self.sample_space = sample_space def add_top_conditionals(self): top_part = self.sample_space.horizontal_parts[0] color = average_color(YELLOW, GREEN, GREEN) p = 0.97 top_part.divide_vertically(p, colors = [color, BLUE]) label = self.get_conditional_label(p, True) brace, _ignore = top_part.get_top_braces_and_labels([label]) explanation = OldTexText( "Probability of", "high bet", "given", "flush" ) explanation.set_color_by_tex("high bet", GREEN) explanation.set_color_by_tex("flush", RED) explanation.scale(0.6) explanation.next_to(label, UP) self.play( FadeIn(top_part.vertical_parts), FadeIn(label), GrowFromCenter(brace), ) self.play(Write(explanation, run_time = 3)) self.wait(2) self.sample_space.add(brace, label) self.top_explanation = explanation self.top_conditional_rhs = label[-1] def react_to_top_conditionals(self): her = PiCreature(color = BLUE_B).flip() her.next_to(self.sample_space, RIGHT) her.to_edge(RIGHT) glasses = SunGlasses(her) glasses.save_state() glasses.shift(UP) glasses.set_fill(opacity = 0) her.glasses = glasses self.play(FadeIn(her)) self.play(glasses.restore) self.play( her.change_mode, "happy", Animation(glasses) ) self.wait(2) self.her = her def add_bottom_conditionals(self): her = self.her bottom_part = self.sample_space.horizontal_parts[1] p = 0.3 bottom_part.divide_vertically(p, colors = [GREEN_E, BLUE_E]) label = self.get_conditional_label(p, False) brace, _ignore = bottom_part.get_bottom_braces_and_labels([label]) explanation = OldTexText( "Probability of", "high bet", "given", "no flush" ) explanation.set_color_by_tex("high bet", GREEN) explanation.set_color_by_tex("no flush", RED) explanation.scale(0.6) explanation.next_to(label, DOWN) self.play(DrawBorderThenFill(bottom_part.vertical_parts)) self.play( GrowFromCenter(brace), FadeIn(label) ) self.play( her.change_mode, "shruggie", MaintainPositionRelativeTo(her.glasses, her.eyes) ) self.wait() self.play(*[ ReplacementTransform( VGroup(*label[i1:i2]).copy(), VGroup(explanation[j]), run_time = 2, rate_func = squish_rate_func(smooth, a, a+0.5) ) for a, (i1, i2, j) in zip(np.linspace(0, 0.5, 4), [ (0, 1, 0), (1, 2, 1), (2, 3, 2), (3, 6, 3), ]) ]) self.wait() self.play(Write(VGroup(*label[-2:]))) self.wait(2) self.play(*list(map(FadeOut, [her, her.glasses]))) self.sample_space.add(brace, label) self.bottom_explanation = explanation self.bottom_conditional_rhs = label[-1] def ask_where_conditionals_come_from(self): randy = Randolph().flip() randy.scale(0.75) randy.to_edge(RIGHT) randy.shift(2*DOWN) words = OldTexText("Where do these \\\\", "numbers", "come from?") numbers_word = words.get_part_by_tex("numbers") numbers_word.set_color(YELLOW) words.scale(0.7) bubble = ThoughtBubble(height = 3, width = 4) bubble.pin_to(randy) bubble.shift(MED_LARGE_BUFF*RIGHT) bubble.add_content(words) numbers = VGroup( self.top_conditional_rhs, self.bottom_conditional_rhs ) numbers.save_state() arrows = VGroup(*[ Arrow( numbers_word.get_left(), num.get_right(), buff = 2*SMALL_BUFF ) for num in numbers ]) questions = VGroup(*list(map(TexText, [ "Does she bluff?", "How much does she have?", "Does she take risks?", "What's her model of me?", "\\vdots" ]))) questions.arrange(DOWN, aligned_edge = LEFT) questions[-1].next_to(questions[-2], DOWN) questions.scale(0.7) questions.next_to(randy, UP) questions.shift_onto_screen() self.play( randy.change_mode, "confused", ShowCreation(bubble), Write(words, run_time = 2) ) self.play(*list(map(ShowCreation, arrows))) self.play(numbers.set_color, YELLOW) self.play(Blink(randy)) self.play(randy.change_mode, "maybe") self.play(*list(map(FadeOut, [ bubble, words, arrows ]))) for question in questions: self.play( FadeIn(question), randy.look_at, question ) self.wait() self.play(Blink(randy)) self.wait() self.play( randy.change_mode, "pondering", FadeOut(questions) ) self.randy = randy def vary_conditionals(self): randy = self.randy rects = VGroup(*[ SurroundingRectangle( VGroup(explanation), buff = SMALL_BUFF, ) for explanation, rhs in zip( [self.top_explanation, self.bottom_explanation], [self.top_conditional_rhs, self.bottom_conditional_rhs], ) ]) new_conditionals = [ (0.91, 0.4), (0.83, 0.1), (0.99, 0.2), (0.97, 0.3), ] self.play(*list(map(ShowCreation, rects))) self.play(FadeOut(rects)) for i, value in enumerate(it.chain(*new_conditionals)): self.play( randy.look_at, rects[i%2], *self.get_conditional_change_anims(i%2, value) ) if i%2 == 1: self.wait() self.play(FadeOut(randy)) def show_restricted_space(self): high_bet_space, low_bet_space = [ VGroup(*[ self.sample_space.horizontal_parts[i].vertical_parts[j] for i in range(2) ]) for j in range(2) ] words = OldTex("P(", self.cash_string, ")") words.set_color_by_tex(self.cash_string, GREEN) words.next_to(self.sample_space, RIGHT) low_bet_space.generate_target() for submob in low_bet_space.target: submob.set_color(average_color( submob.get_color(), *[BLACK]*4 )) arrows = VGroup(*[ Arrow( words.get_left(), submob.get_edge_center(vect), color = submob.get_color() ) for submob, vect in zip(high_bet_space, [DOWN, RIGHT]) ]) self.play(MoveToTarget(low_bet_space)) self.play( Write(words), *list(map(ShowCreation, arrows)) ) self.wait() for rect in high_bet_space: self.play(Indicate(rect, scale_factor = 1)) self.play(*list(map(FadeOut, [words, arrows]))) self.high_bet_space = high_bet_space def write_P_flush_given_bet(self): posterior_tex = OldTex( "P(", self.double_heart_template, "|", self.cash_string, ")" ) posterior_tex.scale(0.7) posterior_tex.set_color_by_tex(self.cash_string, GREEN) self.insert_double_heart(posterior_tex) rects = self.high_bet_space.copy() rects = [rects[0].copy()] + list(rects) for rect in rects: rect.generate_target() numerator = rects[0].target plus = OldTex("+") denominator = VGroup(rects[1].target, plus, rects[2].target) denominator.arrange(RIGHT, buff = SMALL_BUFF) frac_line = OldTex("\\over") frac_line.stretch_to_fit_width(denominator.get_width()) fraction = VGroup(numerator, frac_line, denominator) fraction.arrange(DOWN) arrow = OldTex("\\downarrow") group = VGroup(posterior_tex, arrow, fraction) group.arrange(DOWN) group.to_corner(UP+RIGHT) self.play(LaggedStartMap(FadeIn, posterior_tex)) self.play(Write(arrow)) self.play(MoveToTarget(rects[0])) self.wait() self.play(*it.chain( list(map(Write, [frac_line, plus])), list(map(MoveToTarget, rects[1:])) )) self.wait(3) self.play(*list(map(FadeOut, [arrow, fraction] + rects))) self.posterior_tex = posterior_tex def reshape_rectangles(self): post_rects = self.get_posterior_rectangles() prior_rects = self.get_prior_rectangles() braces, labels = self.get_posterior_rectangle_braces_and_labels( post_rects, [self.posterior_tex.copy()] ) height_rect = SurroundingRectangle(braces) self.play( ReplacementTransform( prior_rects.copy(), post_rects, run_time = 2, ), ) self.wait(2) self.play(ReplacementTransform(self.posterior_tex, labels[0])) self.posterior_tex = labels[0] self.play(GrowFromCenter(braces)) self.wait() self.play(ShowCreation(height_rect)) self.play(FadeOut(height_rect)) self.wait() self.post_rects = post_rects def compare_prior_to_posterior(self): prior_tex = self.sample_space.horizontal_parts.labels[0] post_tex = self.posterior_tex prior_rect, post_rect = [ SurroundingRectangle(tex, stroke_width = 2) for tex in [prior_tex, post_tex] ] post_words = OldTexText("Posterior", "probability") post_words.scale(0.8) post_words.to_corner(UP+RIGHT) post_arrow = Arrow( post_words[0].get_bottom(), post_tex.get_top(), color = WHITE ) self.play(ShowCreation(prior_rect)) self.wait() self.play(ReplacementTransform(prior_rect, post_rect)) self.wait() self.play(FadeOut(post_rect)) self.play(Indicate(post_tex.get_part_by_tex(self.cash_string))) self.wait() self.play( Write(post_words), ShowCreation(post_arrow) ) self.wait() self.play(post_words[1].fade, 0.8) self.wait(2) self.play(*list(map(FadeOut, [post_words, post_arrow]))) def preview_tweaks(self): post_rects = self.post_rects new_value_lists = [ (0.85, 0.1, 0.11), (0.97, 0.3, 1./22), ] for new_values in new_value_lists: for i, value in zip(list(range(2)), new_values): self.play(*self.get_conditional_change_anims( i, value, post_rects )) self.play(*self.get_prior_change_anims( new_values[-1], post_rects )) self.wait(2) def tweak_non_flush_case(self): her = self.her her.scale(0.7) her.change_mode("plain") her.shift(DOWN) her.glasses = SunGlasses(her) post_rects = self.post_rects posterior = VGroup(post_rects.braces, post_rects.labels) prior_rects = self.get_prior_rectangles() risk_averse_words = OldTexText( "Suppose risk \\\\ averse \\dots" ) risk_averse_words.scale(0.7) risk_averse_words.next_to(her, DOWN) risk_averse_words.shift_onto_screen() arrows = VGroup(*[ Arrow(ORIGIN, LEFT, tip_length = SMALL_BUFF) for x in range(3) ]) arrows.arrange(DOWN) arrows.next_to(prior_rects[1], RIGHT, SMALL_BUFF) self.wait(2) self.play(*list(map(FadeIn, [her, her.glasses]))) self.play(LaggedStartMap(FadeIn, risk_averse_words)) self.play(her.change_mode, "sad", Animation(her.glasses)) self.wait() self.play(ShowCreation(arrows)) self.play( *it.chain( self.get_conditional_change_anims(1, 0.1, post_rects), [Animation(arrows)] ), run_time = 3 ) self.play(FadeOut(arrows)) self.wait(2) post_surrounding_rect = SurroundingRectangle(posterior) self.play(ShowCreation(post_surrounding_rect)) self.play(FadeOut(post_surrounding_rect)) self.wait() self.play( FadeOut(risk_averse_words), *self.get_conditional_change_anims(1, 0.3, post_rects), run_time = 2 ) def tweak_flush_case(self): her = self.her post_rects = self.post_rects self.play( her.change_mode, "erm", Animation(her.glasses) ) self.play( *self.get_conditional_change_anims(0, 0.47, post_rects), run_time = 3 ) self.wait(3) self.play(*self.get_conditional_change_anims( 0, 0.97, post_rects )) self.wait() def tweak_prior(self): her = self.her post_rects = self.post_rects self.play( her.change_mode, "happy", Animation(her.glasses) ) self.play( *self.get_prior_change_anims(0.3, post_rects), run_time = 2 ) self.wait(3) self.play( *self.get_prior_change_anims(1./22, post_rects), run_time = 2 ) self.play(*list(map(FadeOut, [her, her.glasses]))) def compute_posterior(self): prior_rects = self.get_prior_rectangles() post_tex = self.posterior_tex prior_rhs_group = self.get_prior_rhs_group() fraction = OldTex( "{(0.045)", "(0.97)", "\\over", "(0.995)", "(0.3)", "+", "(0.045)", "(0.97)}" ) products = [ VGroup(*[ fraction.get_parts_by_tex(tex)[i] for tex in tex_list ]) for i, tex_list in [ (0, ["0.045", "0.97"]), (0, ["0.995", "0.3"]), (1, ["0.045", "0.97"]), ] ] for i in 0, 2: products[i].set_color(prior_rects[0].get_color()) products[1].set_color(prior_rects[1].get_color()) fraction.scale(0.65) fraction.to_corner(UP+RIGHT, buff = MED_SMALL_BUFF) arrow_kwargs = { "color" : WHITE, "tip_length" : 0.15, } rhs = OldTex("\\approx", "0.13") rhs.scale(0.8) rhs.next_to(post_tex, RIGHT) to_rhs_arrow = Arrow( fraction.get_bottom(), rhs.get_top(), **arrow_kwargs ) pre_top_rect_products = VGroup( prior_rhs_group[0], self.top_conditional_rhs ) pre_bottom_rect_products = VGroup( prior_rhs_group[1], self.bottom_conditional_rhs ) self.play(Indicate(prior_rects[0], scale_factor = 1)) self.play(*[ ReplacementTransform( mob.copy(), term, run_time = 2, ) for mob, term in zip( pre_top_rect_products, products[0] ) ]) self.play(Write(fraction.get_part_by_tex("over"))) for pair in zip(pre_top_rect_products, products[0]): self.play(*list(map(Indicate, pair))) self.wait() self.wait() self.play(Indicate(prior_rects[1], scale_factor = 1)) self.play(*[ ReplacementTransform( mob.copy(), term, run_time = 2, ) for mob, term in zip( pre_bottom_rect_products, products[1] ) ]) self.wait() for pair in zip(pre_bottom_rect_products, products[1]): self.play(*list(map(Indicate, pair))) self.wait() self.play( Write(fraction.get_part_by_tex("+")), ReplacementTransform(products[0].copy(), products[2]) ) self.wait() self.play(ShowCreation(to_rhs_arrow)) self.play(Write(rhs)) self.wait(3) ###### def get_prior_labels(self, value): p_str = "%0.3f"%value q_str = "%0.3f"%(1-value) labels = [ OldTex( "P(", s, self.double_heart_template, ")", "= ", num ) for s, num in (("", p_str), ("\\text{not }", q_str)) ] for label in labels: label.scale(0.7) self.insert_double_heart(label) return labels def get_prior_rhs_group(self): labels = self.sample_space.horizontal_parts.labels return VGroup(*[label[-1] for label in labels]) def get_conditional_label(self, value, given_flush = True): label = OldTex( "P(", self.cash_string, "|", "" if given_flush else "\\text{not }", self.double_heart_template, ")", "=", str(value) ) self.insert_double_heart(label) label.set_color_by_tex(self.cash_string, GREEN) label.scale(0.7) return label def insert_double_heart(self, tex_mob): double_heart = SuitSymbol("hearts") double_heart.add(SuitSymbol("hearts")) double_heart.arrange(RIGHT, buff = SMALL_BUFF) double_heart.get_tex = lambda : self.double_heart_template template = tex_mob.get_part_by_tex(self.double_heart_template) double_heart.replace(template) tex_mob.submobjects[tex_mob.index_of_part(template)] = double_heart return tex_mob def get_prior_change_anims(self, value, post_rects = None): space = self.sample_space parts = space.horizontal_parts anims = self.get_horizontal_division_change_animations( value, new_label_kwargs = { "labels" : self.get_prior_labels(value) } ) if post_rects is not None: anims += self.get_posterior_rectangle_change_anims(post_rects) return anims def get_conditional_change_anims( self, sub_sample_space_index, value, post_rects = None ): given_flush = (sub_sample_space_index == 0) label = self.get_conditional_label(value, given_flush) return SampleSpaceScene.get_conditional_change_anims( self, sub_sample_space_index, value, post_rects, new_label_kwargs = {"labels" : [label]}, ) class BayesRuleInMemory(Scene): def construct(self): randy = Randolph() randy.to_corner(DOWN+LEFT) bubble = ThoughtBubble(height = 4) bubble.pin_to(randy) B = "\\text{Belief}" D = "\\text{Data}" rule = OldTex( "P(", B, "|", D, ")", "=", "P(", "B", ")", "{P(", D, "|", B, ")", "\\over", "P(", D, ")}" ) rule.set_color_by_tex(B, RED) rule.set_color_by_tex(D, GREEN) rule.next_to(randy, RIGHT, LARGE_BUFF, UP) rule.generate_target() bubble.add_content(rule.target) screen_rect = ScreenRectangle() screen_rect.next_to(randy, UP+RIGHT) self.add(randy) self.play( LaggedStartMap(FadeIn, rule), randy.change, "erm", rule ) self.play(Blink(randy)) self.play( ShowCreation(bubble), MoveToTarget(rule), randy.change, "pondering", ) self.wait() self.play(rule.fade, 0.7, run_time = 2) self.play(randy.change, "confused", rule) self.play(Blink(randy)) self.wait(2) self.play( FadeOut(VGroup(bubble, rule)), randy.change, "pondering", screen_rect, ) self.play( randy.look_at, screen_rect.get_right(), ShowCreation(screen_rect), ) self.wait(4) class NextVideoWrapper(TeacherStudentsScene): CONFIG = { "title" : "Upcoming chapter: Bayesian networks" } def construct(self): title = OldTexText(self.title) title.scale(0.8) title.to_edge(UP, buff = SMALL_BUFF) screen = ScreenRectangle(height = 4) screen.next_to(title, DOWN) title.save_state() title.shift(DOWN) title.set_fill(opacity = 0) self.play( title.restore, self.teacher.change, "raise_right_hand" ) self.play(ShowCreation(screen)) self.play_student_changes( *["pondering"]*3, look_at = screen ) self.play(Animation(screen)) self.wait(5) class BayesianNetworkPreview(Scene): def construct(self): self.add_network() self.show_propogation(self.network.nodes[0]) self.show_propogation(self.network.nodes[-1]) def add_network(self): radius = MED_SMALL_BUFF node = Circle(color = WHITE, radius = radius) node.shift(2*DOWN) nodes = VGroup(*[ node.copy().shift(x*RIGHT + y*UP) for x, y in [ (-1, 0), (1, 0), (-2, 2), (0, 2), (2, 2), (-2, 4), (0, 4), ] ]) for node in nodes: node.children = VGroup() node.parents = VGroup() node.outgoing_edges = VGroup() edge_index_pairs = [ (2, 0), (3, 0), (3, 1), (4, 1), (5, 2), (6, 3), ] edges = VGroup() for i1, i2 in edge_index_pairs: n1, n2 = nodes[i1], nodes[i2] edge = Arrow( n1.get_center(), n2.get_center(), buff = radius, color = WHITE, ) n1.outgoing_edges.add(edge) edges.add(edge) n1.children.add(n2) n2.parents.add(n1) network = VGroup(nodes, edges) network.nodes = nodes network.edges = edges self.add(network) self.network = network def show_propogation(self, node): self.set_network_fills() all_ghosts = VGroup() curr_nodes = [node] covered_nodes = set() self.play(GrowFromCenter(node.fill)) self.remove(node.fill) while curr_nodes: next_nodes = set([]) anims = [] for node in curr_nodes: node.ghost = node.fill.copy().fade() self.add(node.ghost) all_ghosts.add(node.ghost) connected_nodes = [n for n in it.chain(node.children, node.parents) if n not in covered_nodes] for next_node in connected_nodes: if next_node in covered_nodes: continue next_nodes.add(next_node) anims.append(Transform( node.fill.copy(), next_node.fill, remover = True )) if len(connected_nodes) == 0: anims.append(FadeOut(node.fill)) if anims: self.play(*anims) covered_nodes.update(curr_nodes) curr_nodes = list(next_nodes) self.wait() self.play(FadeOut(all_ghosts)) def set_network_fills(self): for node in self.network.nodes: node.fill = self.get_fill(node) def get_fill(self, node): fill = node.copy() fill.set_fill(YELLOW, 1) fill.set_stroke(width = 0) return fill class GeneralizeBayesRule(SampleSpaceScene): def construct(self): self.add_sample_space() self.add_title() self.add_posterior_rectangles() self.add_bayes_rule() self.talk_through_terms() self.name_likelihood() self.dont_memorize() self.show_space_restriction() def add_sample_space(self): sample_space = SampleSpace( full_space_config = { "height" : 3, "width" : 3, "fill_opacity" : 0 } ) sample_space.divide_horizontally(0.4) sample_space.horizontal_parts.set_fill(opacity = 0) labels = [ OldTex("P(", "B", ")"), OldTex("P(\\text{not }", "B", ")"), ] for label in labels: label.scale(0.7) self.color_label(label) sample_space.get_side_braces_and_labels(labels) sample_space.add_braces_and_labels() parts = sample_space.horizontal_parts values = [0.8, 0.4] given_strs = ["", "\\text{not }"] color_pairs = [(GREEN, BLUE), (GREEN_E, BLUE_E)] vects = [UP, DOWN] for tup in zip(parts, values, given_strs, color_pairs, vects): part, value, given_str, colors, vect = tup part.divide_vertically(value, colors = colors) part.vertical_parts.set_fill(opacity = 0.8) label = OldTex( "P(", "I", "|", given_str, "B", ")" ) label.scale(0.7) self.color_label(label) part.get_subdivision_braces_and_labels( part.vertical_parts, [label], vect ) sample_space.add( part.vertical_parts.braces, part.vertical_parts.labels, ) sample_space.to_edge(LEFT) self.add(sample_space) self.sample_space = sample_space def add_title(self): title = OldTexText( "Updating", "Beliefs", "from new", "Information" ) self.color_label(title) title.scale(0.8) title.to_corner(UP+LEFT) self.add(title) def add_posterior_rectangles(self): prior_rects = self.get_prior_rectangles() post_rects = self.get_posterior_rectangles() label = OldTex("P(", "B", "|", "I", ")") label.scale(0.7) self.color_label(label) braces, labels = self.get_posterior_rectangle_braces_and_labels( post_rects, [label] ) self.play(ReplacementTransform( prior_rects.copy(), post_rects, run_time = 2 )) self.play( GrowFromCenter(braces), Write(label) ) self.post_rects = post_rects self.posterior_tex = label def add_bayes_rule(self): rule = OldTex( "=", "{P(", "B", ")", "P(", "I", "|", "B", ")", "\\over", "P(", "I", ")}", ) self.color_label(rule) rule.scale(0.7) rule.next_to(self.posterior_tex, RIGHT) bayes_rule_words = OldTexText("Bayes' rule") bayes_rule_words.next_to(VGroup(*rule[1:]), UP, LARGE_BUFF) bayes_rule_words.shift_onto_screen() self.play(FadeIn(rule)) self.play(Write(bayes_rule_words)) self.wait(2) self.bayes_rule_words = bayes_rule_words self.bayes_rule = rule def talk_through_terms(self): prior = self.sample_space.horizontal_parts.labels[0] posterior = self.posterior_tex prior_target = VGroup(*self.bayes_rule[1:4]) likelihood = VGroup(*self.bayes_rule[4:9]) P_I = VGroup(*self.bayes_rule[-3:]) prior_word = OldTexText("Prior") posterior_word = OldTexText("Posterior") words = [prior_word, posterior_word] for word in words: word.set_color(YELLOW) word.scale(0.7) prior_rect = SurroundingRectangle(prior) posterior_rect = SurroundingRectangle(posterior) for rect in prior_rect, posterior_rect: rect.set_stroke(YELLOW, 2) prior_word.next_to(prior, UP, LARGE_BUFF) posterior_word.next_to(posterior, DOWN, LARGE_BUFF) for word in words: word.shift_onto_screen() prior_arrow = Arrow( prior_word.get_bottom(), prior.get_top(), tip_length = 0.15 ) posterior_arrow = Arrow( posterior_word.get_top(), posterior.get_bottom(), tip_length = 0.15 ) self.play( Write(prior_word), ShowCreation(prior_arrow), ShowCreation(prior_rect), ) self.wait() self.play(Transform( prior.copy(), prior_target, run_time = 2, path_arc = -np.pi/3, remover = True, )) self.wait() parts = self.sample_space[0].vertical_parts self.play( Indicate(likelihood), Indicate(parts.labels), Indicate(parts.braces), ) self.wait() self.play(Indicate(P_I)) self.play(FocusOn(self.sample_space[0][0])) for i in range(2): self.play(Indicate( self.sample_space[i][0], scale_factor = 1 )) self.wait() self.play( Write(posterior_word), ShowCreation(posterior_arrow), ShowCreation(posterior_rect), ) self.prior_label = VGroup(prior_word, prior_arrow, prior_rect) self.posterior_label = VGroup(posterior_word, posterior_arrow, posterior_rect) self.likelihood = likelihood def name_likelihood(self): likelihoods = [ self.sample_space[0].vertical_parts.labels[0], self.likelihood ] rects = [ SurroundingRectangle(mob, buff = SMALL_BUFF) for mob in likelihoods ] name = OldTexText("Likelihood") name.scale(0.7) name.next_to(self.posterior_tex, UP, 1.5*LARGE_BUFF) arrows = [ Arrow( name, rect.get_edge_center(vect), tip_length = 0.15 ) for rect, vect in zip(rects, [RIGHT, UP]) ] VGroup(name, *arrows+rects).set_color(YELLOW) morty = Mortimer() morty.scale(0.5) morty.next_to(rects[1], UP, buff = 0) morty.shift(SMALL_BUFF*RIGHT) self.play( self.bayes_rule_words.to_edge, UP, Write(name), *list(map(ShowCreation, arrows+rects)) ) self.wait() self.play(FadeIn(morty)) self.play(morty.change, "confused", name) self.play(Blink(morty)) self.play(morty.look, DOWN) self.wait() self.play(morty.look_at, name) self.play(Blink(morty)) self.play(morty.change, "shruggie") self.play(FadeOut(VGroup(name, *arrows+rects))) self.play(FadeOut(morty)) self.play(FadeOut(self.posterior_label)) self.play(FadeOut(self.prior_label)) def dont_memorize(self): rule = VGroup(*self.bayes_rule[1:]) word = OldTexText("Memorize") word.scale(0.7) word.next_to(rule, DOWN) cross = VGroup( Line(UP+LEFT, DOWN+RIGHT), Line(UP+RIGHT, DOWN+LEFT), ) cross.set_stroke(RED, 6) cross.replace(word, stretch = True) self.play(Write(word)) self.wait() self.play(ShowCreation(cross)) self.wait() self.play(FadeOut(VGroup(cross, word))) self.play(FadeOut(self.bayes_rule)) self.play( FadeOut(self.post_rects), FadeOut(self.post_rects.braces), FadeOut(self.post_rects.labels), ) def show_space_restriction(self): prior_rects = self.get_prior_rectangles() non_I_rects = VGroup(*[ self.sample_space[i][1] for i in range(2) ]) post_rects = self.post_rects self.play(non_I_rects.fade, 0.8) self.play(LaggedStartMap( ApplyMethod, prior_rects, lambda m : (m.set_color, YELLOW), rate_func = there_and_back, lag_ratio = 0.7 )) self.wait(2) self.play(ReplacementTransform( prior_rects.copy(), post_rects, run_time = 2 )) self.play(*list(map(FadeIn, [ post_rects.braces, post_rects.labels ]))) self.wait() self.play(*self.get_conditional_change_anims(1, 0.2, post_rects)) self.play(*self.get_conditional_change_anims(0, 0.6, post_rects)) self.wait() self.play(*it.chain( self.get_division_change_animations( self.sample_space, self.sample_space.horizontal_parts, 0.1 ), self.get_posterior_rectangle_change_anims(post_rects) )) self.wait(3) #### def color_label(self, label): label.set_color_by_tex("B", RED) label.set_color_by_tex("I", GREEN) class MoreExamples(TeacherStudentsScene): def construct(self): self.teacher_says("More examples!", target_mode = "hooray") self.play_student_changes(*["hooray"]*3) self.wait(2) class MusicExample(SampleSpaceScene, PiCreatureScene): def construct(self): self.introduce_musician() self.add_prior() self.record_track() self.add_bottom_conditionl() self.friend_gives_compliment() self.friends_dont_like() self.false_compliment() self.add_top_conditionl() self.get_positive_review() self.restrict_space() self.show_posterior_rectangles() self.show_prior_rectangle_areas() self.show_posterior_probability() self.intuition_of_positive_feedback() self.make_friends_honest() self.fade_out_post_rect() self.get_negative_feedback() self.compare_prior_to_post_given_negative() self.intuition_of_negative_feedback() def introduce_musician(self): randy = self.pi_creature randy.change_mode("soulful_musician") randy.arms = randy.get_arm_copies() guitar = randy.guitar = Guitar() guitar.move_to(randy) guitar.shift(0.31*RIGHT + 0.6*UP) randy.change_mode("plain") self.play( randy.change_mode, "soulful_musician", path_arc = np.pi/6, ) self.play( Animation(randy), DrawBorderThenFill(guitar), Animation(randy.arms) ) randy.add(guitar, randy.arms) self.wait() self.play_notes(guitar) self.change_pi_creature_with_guitar("concerned_musician") self.wait(2) self.play( randy.scale, 0.7, randy.to_corner, UP+LEFT, ) self.play_notes(guitar) def add_prior(self): sample_space = SampleSpace() sample_space.shift(DOWN) sample_space.divide_horizontally(0.8, colors = [MAROON_D, BLUE_E]) labels = VGroup( OldTex("P(S) = ", "0.8"), OldTex("P(\\text{not } S) = ", "0.2"), ) labels.scale(0.7) braces, labels = sample_space.get_side_braces_and_labels(labels) VGroup(sample_space, braces, labels).to_edge(LEFT) words = list(map(TexText, [ "Blunt honesty", "Some confidence" ])) for word, part in zip(words, sample_space.horizontal_parts): word.scale(0.6) word.move_to(part) self.play(LaggedStartMap(FadeIn, sample_space, run_time = 1)) self.play(*list(map(GrowFromCenter, braces))) for label in labels: self.play(Write(label, run_time = 2)) self.wait() for word, mode in zip(words, ["maybe", "soulful_musician"]): self.play(LaggedStartMap(FadeIn, word, run_time = 1)) self.change_pi_creature_with_guitar(mode) self.wait() self.wait() self.play(*list(map(FadeOut, words))) self.sample_space = sample_space def record_track(self): randy = self.pi_creature friends = VGroup(*[ PiCreature(mode = "happy", color = color).flip() for color in (BLUE_B, GREY_BROWN, MAROON_E) ]) friends.scale(0.6) friends.arrange(RIGHT) friends.next_to(randy, RIGHT, LARGE_BUFF, DOWN) friends.to_edge(RIGHT) for friend in friends: friend.look_at(randy.eyes) headphones = VGroup(*list(map(Headphones, friends))) self.play(FadeIn(friends)) self.pi_creatures.add(*friends) self.play( FadeIn(headphones), Animation(friends) ) self.play_notes(randy.guitar) self.play(LaggedStartMap( ApplyMethod, friends, lambda pi : (pi.change, "hooray"), run_time = 2, )) self.friends = friends self.headphones = headphones def add_bottom_conditionl(self): p = 0.99 bottom_part = self.sample_space[1] bottom_part.divide_vertically(p, colors = [GREEN_E, YELLOW]) label = self.get_conditional_label(p, False) braces, labels = bottom_part.get_bottom_braces_and_labels([label]) brace = braces[0] self.play(FadeIn(bottom_part.vertical_parts)) self.play(GrowFromCenter(brace)) self.play(Write(label)) self.wait() def friend_gives_compliment(self): friends = self.friends bubble = SpeechBubble( height = 1.25, width = 3, direction = RIGHT, fill_opacity = 0, ) content = OldTexText("Phenomenal!") content.scale(0.75) bubble.add_content(content) VGroup(bubble, content).next_to(friends, LEFT, SMALL_BUFF) VGroup(bubble, content).to_edge(UP, SMALL_BUFF) self.play(LaggedStartMap( ApplyMethod, friends, lambda pi : (pi.change_mode, "conniving") )) self.wait() self.play( ShowCreation(bubble), Write(bubble.content, run_time = 1), ApplyMethod(friends[0].change_mode, "hooray"), LaggedStartMap( ApplyMethod, VGroup(*friends[1:]), lambda pi : (pi.change_mode, "happy") ), ) self.wait(2) self.play(*list(map(FadeOut, [bubble, content]))) def friends_dont_like(self): friends = self.friends pi1, pi2, pi3 = friends for friend in friends: friend.generate_target() pi1.target.change("guilty", pi2.eyes) pi2.target.change("hesitant", pi1.eyes) pi3.target.change("pondering", pi2.eyes) self.play(LaggedStartMap( MoveToTarget, friends )) self.change_pi_creature_with_guitar("concerned_musician") self.wait() def false_compliment(self): friend = self.friends[0] bubble = SpeechBubble( height = 1.25, width = 4.5, direction = RIGHT, fill_opacity = 0, ) content = OldTexText("The beat was consistent.") content.scale(0.75) bubble.add_content(content) VGroup(bubble, content).next_to(friend, LEFT, SMALL_BUFF) VGroup(bubble, content).to_edge(UP, SMALL_BUFF) self.play( friend.change_mode, "maybe", ShowCreation(bubble), Write(content) ) self.change_pi_creature_with_guitar("happy") self.wait() self.play(*list(map(FadeOut, [bubble, content]))) self.bubble = bubble def add_top_conditionl(self): p = 0.9 top_part = self.sample_space[0] top_part.divide_vertically(p, colors = [TEAL_E, RED_E]) label = self.get_conditional_label(p, True) braces, labels = top_part.get_top_braces_and_labels([label]) brace = braces[0] self.play(FadeIn(top_part.vertical_parts)) self.play(GrowFromCenter(brace)) self.play(Write(label, run_time = 2)) self.wait() def get_positive_review(self): friends = self.friends self.change_pi_creature_with_guitar( "soulful_musician", LaggedStartMap( ApplyMethod, friends, lambda pi : (pi.change, "happy"), run_time = 1, ) ) self.play_notes(self.pi_creature.guitar) def restrict_space(self): positive_space, negative_space = [ VGroup(*[ self.sample_space[i][j] for i in range(2) ]) for j in range(2) ] negative_space.save_state() self.play(negative_space.fade, 0.8) self.play(LaggedStartMap( ApplyMethod, positive_space, lambda m : (m.set_color, YELLOW), rate_func = there_and_back, run_time = 2, lag_ratio = 0.7, )) self.wait() self.negative_space = negative_space def show_posterior_rectangles(self): prior_rects = self.get_prior_rectangles() post_rects = self.get_posterior_rectangles() label = OldTex("P(S | ", "\\checkmark", ")") label.scale(0.7) label.set_color_by_tex("\\checkmark", GREEN) braces, labels = self.get_posterior_rectangle_braces_and_labels( post_rects, [label] ) brace = braces[0] self.play(ReplacementTransform( prior_rects.copy(), post_rects, run_time = 2 )) self.play(GrowFromCenter(brace)) self.play(Write(label)) self.wait() self.post_rects = post_rects self.post_tex = label def show_prior_rectangle_areas(self): prior_rects = self.get_prior_rectangles() products = VGroup( OldTex("(", "0.8", ")(", "0.9", ")"), OldTex("(", "0.2", ")(", "0.99", ")"), ) top_product, bottom_product = products for product, rect in zip(products, prior_rects): product.scale(0.7) product.move_to(rect) side_labels = self.sample_space.horizontal_parts.labels top_labels = self.sample_space[0].vertical_parts.labels bottom_labels = self.sample_space[1].vertical_parts.labels self.play( ReplacementTransform( side_labels[0][-1].copy(), top_product[1], ), ReplacementTransform( top_labels[0][-1].copy(), top_product[3], ), Write(VGroup(*top_product[::2])) ) self.wait(2) self.play( ReplacementTransform( side_labels[1][-1].copy(), bottom_product[1], ), ReplacementTransform( bottom_labels[0][-1].copy(), bottom_product[3], ), Write(VGroup(*bottom_product[::2])) ) self.wait(2) self.products = products def show_posterior_probability(self): post_tex = self.post_tex rhs = OldTex("\\approx", "0.78") rhs.scale(0.7) rhs.next_to(post_tex, RIGHT) ratio = OldTex( "{(0.8)(0.9)", "\\over", "(0.8)(0.9)", "+", "(0.2)(0.99)}" ) ratio.scale(0.6) ratio.next_to(VGroup(post_tex, rhs), DOWN, LARGE_BUFF) ratio.to_edge(RIGHT) arrow_kwargs = { "tip_length" : 0.15, "color" : WHITE, "buff" : 2*SMALL_BUFF, } to_ratio_arrow = Arrow( post_tex.get_bottom(), ratio.get_top(), **arrow_kwargs ) to_rhs_arrow = Arrow( ratio.get_top(), rhs[1].get_bottom(), **arrow_kwargs ) prior_rects = self.get_prior_rectangles() self.play( ShowCreation(to_ratio_arrow), FadeIn(ratio) ) self.wait(2) for mob in prior_rects, prior_rects[0]: self.play( mob.set_color, YELLOW, Animation(self.products), rate_func = there_and_back, run_time = 2 ) self.wait() self.wait() self.play(ShowCreation(to_rhs_arrow)) self.play(Write(rhs, run_time = 1)) self.wait(2) self.post_rhs = rhs self.ratio_group = VGroup(ratio, to_ratio_arrow, to_rhs_arrow) def intuition_of_positive_feedback(self): friends = self.friends prior_num = self.sample_space.horizontal_parts.labels[0][-1] prior_num_ghost = prior_num.copy().set_fill(opacity = 0.5) post_num = self.post_rhs[-1] prior_rect = SurroundingRectangle(prior_num) post_rect = SurroundingRectangle(post_num) self.play(ShowCreation(prior_rect)) self.play(Transform( prior_num_ghost, post_num, remover = True, path_arc = -np.pi/6, run_time = 2, )) self.play(ShowCreation(post_rect)) self.wait(2) for mode, time in ("shruggie", 2), ("hesitant", 0): self.play(LaggedStartMap( ApplyMethod, friends, lambda pi : (pi.change, mode), run_time = 2, )) self.wait(time) self.play(*list(map(FadeOut, [ prior_rect, post_rect, self.ratio_group, self.post_rhs ]))) self.prior_num_rect = prior_rect def make_friends_honest(self): post_rects = self.post_rects self.play(FadeOut(self.products)) for value in 0.5, 0.1, 0.9: label = self.get_conditional_label(value) self.play(*self.get_top_conditional_change_anims( value, post_rects, new_label_kwargs = {"labels" : [label]}, ), run_time = 2) self.wait(2) def fade_out_post_rect(self): self.play(*list(map(FadeOut, [ self.post_rects, self.post_rects.braces, self.post_rects.labels, ]))) self.play(self.negative_space.restore) def get_negative_feedback(self): friends = self.friends old_prior_rects = self.get_prior_rectangles() for part in self.sample_space.horizontal_parts: part.vertical_parts.submobjects.reverse() new_prior_rects = self.get_prior_rectangles() post_rects = self.get_posterior_rectangles() label = OldTex( "P(S | \\text{not } ", "\\checkmark", ")", "\\approx", "0.98" ) label.scale(0.7) label.set_color_by_tex("\\checkmark", GREEN) braces, labels = self.get_posterior_rectangle_braces_and_labels( post_rects, [label] ) brace = braces[0] self.play(old_prior_rects.fade, 0.8) self.play(LaggedStartMap( ApplyMethod, friends, lambda pi : (pi.change, "pondering", post_rects), run_time = 1 )) self.wait() self.play(ReplacementTransform( new_prior_rects.copy(), post_rects, run_time = 2 )) self.play(GrowFromCenter(brace)) self.wait(2) self.play(Write(label)) self.wait(3) self.post_rects = post_rects def compare_prior_to_post_given_negative(self): post_num = self.post_rects.labels[0][-1] post_num_rect = SurroundingRectangle(post_num) self.play(ShowCreation(self.prior_num_rect)) self.wait() self.play(ShowCreation(post_num_rect)) self.wait() self.post_num_rect = post_num_rect def intuition_of_negative_feedback(self): friends = self.friends randy = self.pi_creature bubble = self.bubble modes = ["sassy", "pleading", "horrified"] for friend, mode in zip(friends, modes): friend.generate_target() friend.target.change(mode, randy.eyes) content = OldTexText("Horrible. Just horrible.") content.scale(0.6) bubble.add_content(content) self.play(*list(map(MoveToTarget, friends))) self.play( ShowCreation(bubble), Write(bubble.content) ) self.change_pi_creature_with_guitar("sad") self.wait() self.change_pi_creature_with_guitar("concerned_musician") self.wait(3) ###### def create_pi_creature(self): randy = Randolph() randy.left_arm_range = [.36, .45] self.randy = randy return randy def get_conditional_label(self, value, given_suck = True): positive_str = "\\checkmark" label = OldTex( "P(", positive_str, "|", "" if given_suck else "\\text{not }", "S", ")", "=", str(value) ) label.set_color_by_tex(positive_str, GREEN) label.scale(0.7) return label def change_pi_creature_with_guitar(self, target_mode, *added_anims): randy = self.pi_creature randy.remove(randy.arms, randy.guitar) target = randy.copy() target.change_mode(target_mode) target.arms = target.get_arm_copies() target.guitar = randy.guitar.copy() for pi in randy, target: pi.add(pi.guitar, pi.arms) self.play(Transform(randy, target), *added_anims) def play_notes(self, guitar): note = SVGMobject(file_name = "8th_note") note.set_height(0.5) note.set_stroke(width = 0) note.set_fill(BLUE, 1) note.move_to(guitar) note.shift(MED_SMALL_BUFF*(DOWN+2*LEFT)) notes = VGroup(*[note.copy() for x in range(10)]) sine_wave = FunctionGraph(np.sin, x_min = -5, x_max = 5) sine_wave.scale(0.75) sine_wave.rotate(np.pi/6, about_point = ORIGIN) sine_wave.shift( notes.get_center() - \ sine_wave.point_from_proportion(0) ) self.play(LaggedStartMap( MoveAlongPath, notes, lambda n : (n, sine_wave), path_arc = np.pi/2, run_time = 4, lag_ratio = 0.5, rate_func = lambda t : t, )) class FinalWordsOnRule(SampleSpaceScene): def construct(self): self.add_sample_space() self.add_uses() self.tweak_values() def add_sample_space(self): sample_space = self.sample_space = SampleSpace() prior = 0.2 top_conditional = 0.8 bottom_condional = 0.3 sample_space.divide_horizontally(prior) sample_space[0].divide_vertically( top_conditional, colors = [GREEN, RED] ) sample_space[1].divide_vertically( bottom_condional, colors = [GREEN_E, RED_E] ) B = "\\text{Belief}" D = "\\text{Data}" P_B = OldTex("P(", B, ")") P_D_given_B = OldTex("P(", D, "|", B, ")") P_D_given_not_B = OldTex( "P(", D, "|", "\\text{not }", B, ")" ) P_B_given_D = OldTex("P(", B, "|", D, ")") labels = VGroup(P_B, P_D_given_B, P_D_given_not_B, P_B_given_D) for label in labels: label.scale(0.7) label.set_color_by_tex(B, BLUE) label.set_color_by_tex(D, GREEN) prior_rects = self.get_prior_rectangles() post_rects = self.get_posterior_rectangles() for i in range(2): sample_space[i][1].fade(0.7) braces = VGroup() bs, ls = sample_space.get_side_braces_and_labels([P_B]) braces.add(*bs) bs, ls = sample_space[0].get_top_braces_and_labels([P_D_given_B]) braces.add(*bs) bs, ls = sample_space[1].get_bottom_braces_and_labels([P_D_given_not_B]) braces.add(*bs) bs, ls = self.get_posterior_rectangle_braces_and_labels( post_rects, [P_B_given_D] ) braces.add(*bs) group = VGroup(sample_space, braces, labels, post_rects) group.to_corner(DOWN + LEFT) self.add(group) self.post_rects = post_rects def add_uses(self): uses = OldTexText( "Machine learning, ", "scientific inference, $\\dots$", ) uses.to_edge(UP) for use in uses: self.play(Write(use, run_time = 2)) self.wait() def tweak_values(self): post_rects = self.post_rects new_value_lists = [ (0.85, 0.1, 0.11), (0.3, 0.9, 0.4), (0.97, 0.3, 1./22), ] for new_values in new_value_lists: for i, value in zip(list(range(2)), new_values): self.play(*self.get_conditional_change_anims( i, value, post_rects )) self.wait() self.play(*it.chain( self.get_horizontal_division_change_animations(new_values[-1]), self.get_posterior_rectangle_change_anims(post_rects) )) self.wait() self.wait(2) class FootnoteWrapper(NextVideoWrapper): CONFIG = { "title" : "Thoughts on the classic Bayes example" } class PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Burt Humburg", "CrypticSwarm", "Juan Benet", "Mark Zollo", "James Park", "Erik Sundell", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Karan Bhargava", "Ankit Agarwal", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Markus Persson", "Yoni Nazarathy", "Ed Kellett", "Joseph John Cox", "Dan Buchoff", "Luc Ritchie", "Michael McGuffin", "John Haley", "Mourits de Beer", "Ankalagon", "Eric Lavault", "Tomohiro Furusawa", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Mark Govea", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Nils Schneider", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] } class Thumbnail(SampleSpaceScene): def construct(self): title = OldTexText("Bayes' rule") title.scale(2) title.to_edge(UP) self.add(title) prior_label = OldTex("P(", "H", ")") post_label = OldTex("P(", "H", "|", "D", ")") for label in prior_label, post_label: label.set_color_by_tex("H", YELLOW) label.set_color_by_tex("D", GREEN) label.scale(1.5) sample_space = self.get_sample_space() sample_space.set_height(4.5) sample_space.divide_horizontally(0.3) sample_space[0].divide_vertically(0.8, colors = [GREEN, BLUE]) sample_space[1].divide_vertically(0.3, colors = [GREEN_E, BLUE_E]) sample_space.get_side_braces_and_labels([prior_label]) sample_space.add_braces_and_labels() post_rects = self.get_posterior_rectangles() group = self.get_posterior_rectangle_braces_and_labels( post_rects, [post_label] ) post_rects.add(group) VGroup(sample_space, post_rects).next_to(title, DOWN, LARGE_BUFF) self.add(sample_space, post_rects)
from mobject.geometry import * from _2018.eop.reusables.eop_helpers import * from _2018.eop.reusables.eop_constants import * class CoinFlipTree(VGroup): CONFIG = { "total_width": 12, "level_height": 0.8, "nb_levels": 4, "sort_until_level": 3 } def __init__(self, **kwargs): VGroup.__init__(self, **kwargs) self.rows = [] for n in range(self.nb_levels + 1): if n <= self.sort_until_level: self.create_row(n, sorted = True) else: self.create_row(n, sorted = False) for row in self.rows: for leaf in row: dot = Dot() dot.move_to(leaf[0]) line = Line(leaf[2], leaf[0]) if leaf[2][0] > leaf[0][0]: line_color = COLOR_HEADS else: line_color = COLOR_TAILS line.set_stroke(color = line_color) group = VGroup() group.add(dot) group.add_to_back(line) self.add(group) def create_row(self, level, sorted = True): if level == 0: new_row = [[ORIGIN,0,ORIGIN]] # is its own parent self.rows.append(new_row) return previous_row = self.rows[level - 1] new_row = [] dx = float(self.total_width) / (2 ** level) x = - 0.5 * self.total_width + 0.5 * dx y = - self.level_height * level for root in previous_row: root_point = root[0] root_tally = root[1] for i in range(2): # 0 = heads = left, 1 = tails = right leaf = x * RIGHT + y * UP new_row.append([leaf, root_tally + i, root_point]) # leaf and its parent x += dx if sorted: # sort the new_row by its tallies sorted_row = [] x = - 0.5 * self.total_width + 0.5 * dx for i in range(level + 1): for leaf in new_row: if leaf[1] == i: sorted_leaf = leaf sorted_leaf[0][0] = x x += dx sorted_row.append(leaf) self.rows.append(sorted_row) else: self.rows.append(new_row)
from mobject.types.vectorized_mobject import * from mobject.svg.tex_mobject import * class BinaryOption(VMobject): CONFIG = { "text_scale" : 0.5 } def __init__(self, mob1, mob2, **kwargs): VMobject.__init__(self, **kwargs) text = OldTexText("or").scale(self.text_scale) mob1.next_to(text, LEFT) mob2.next_to(text, RIGHT) self.add(mob1, text, mob2)
from manim_imports_ext import * from _2018.eop.reusables.eop_helpers import * from _2018.eop.reusables.eop_constants import * from _2018.eop.reusables.upright_coins import * class BrickRow(VMobject): CONFIG = { "left_color" : COLOR_HEADS, "right_color" : COLOR_TAILS, "height" : 1.0, "width" : 8.0, "outcome_shrinkage_factor_x" : 0.95, "outcome_shrinkage_factor_y" : 0.94 } def __init__(self, n, **kwargs): self.subdiv_level = n self.coloring_level = n VMobject.__init__(self, **kwargs) def init_points(self): self.submobjects = [] self.rects = self.get_rects_for_level(self.coloring_level) self.add(self.rects) self.subdivs = self.get_subdivs_for_level(self.subdiv_level) self.add(self.subdivs) self.border = SurroundingRectangle(self, buff = 0, color = WHITE) self.add(self.border) def get_rects_for_level(self,r): rects = VGroup() for k in range(r + 1): proportion = float(choose(r,k)) / 2**r new_rect = Rectangle( width = proportion * self.width, height = self.height, fill_color = graded_color(r,k), fill_opacity = 1, stroke_width = 0 ) if len(rects.submobjects) > 0: new_rect.next_to(rects,RIGHT,buff = 0) else: new_rect.next_to(self.get_center() + 0.5 * self.width * LEFT, RIGHT, buff = 0) rects.add(new_rect) return rects def get_subdivs_for_level(self,r): subdivs = VGroup() x = - 0.5 * self.width for k in range(0, r): proportion = float(choose(r,k)) / 2**r x += proportion * self.width subdiv = Line( x * RIGHT + 0.5 * self.height * UP, x * RIGHT + 0.5 * self.height * DOWN, ) subdivs.add(subdiv) subdivs.move_to(self.get_center()) return subdivs def get_sequence_subdivs_for_level(self,r): subdivs = VGroup() x = - 0.5 * self.width dx = 1.0 / 2**r for k in range(1, 2 ** r): proportion = dx x += proportion * self.width subdiv = DashedLine( x * RIGHT + 0.5 * self.height * UP, x * RIGHT + 0.5 * self.height * DOWN, ) subdivs.add(subdiv) subdivs.move_to(self.get_center()) return subdivs def get_outcome_centers_for_level(self,r): dpos = float(self.width) / (2 ** r) * RIGHT pos = 0.5 * self.width * LEFT + 0.5 * dpos centers = [] for k in range(0, 2 ** r): centers.append(self.get_center() + pos + k * dpos) return centers def get_outcome_rects_for_level(self, r, inset = False, with_labels = False): centers = self.get_outcome_centers_for_level(r) if inset == True: outcome_width = self.outcome_shrinkage_factor_x * float(self.width) / (2 ** r) outcome_height = self.outcome_shrinkage_factor_y * self.height else: outcome_width = float(self.width) / (2 ** r) outcome_height = self.height corner_radius = 0.1 # max(0.1, 0.3 * min(outcome_width, outcome_height)) # this scales down the corner radius for very narrow rects rect = RoundedRectangle( width = outcome_width, height = outcome_height, corner_radius = corner_radius, fill_color = OUTCOME_COLOR, fill_opacity = OUTCOME_OPACITY, stroke_width = 0 ) rects = VGroup() for center in centers: rects.add(rect.copy().move_to(center)) rects.move_to(self.get_center()) if with_labels == False: return rects # else sequences = self.get_coin_sequences_for_level(r) labels = VGroup() for (seq, rect) in zip(sequences, rects): coin_seq = CoinSequence(seq, direction = DOWN) coin_seq.shift(rect.get_center() - coin_seq.get_center()) # not simply move_to bc coin_seq is not centered rect.add(coin_seq) rect.label = coin_seq return rects def get_coin_sequences_for_level(self,r): # array of arrays of characters if r < 0 or int(r) != r: raise Exception("Level must be a positive integer") if r == 0: return [] if r == 1: return [["H"], ["T"]] previous_seq_array = self.get_coin_sequences_for_level(r - 1) subdiv_lengths = [choose(r - 1, k) for k in range(r)] seq_array = [] index = 0 for length in subdiv_lengths: for seq in previous_seq_array[index:index + length]: seq_copy = copy.copy(seq) seq_copy.append("H") seq_array.append(seq_copy) for seq in previous_seq_array[index:index + length]: seq_copy = copy.copy(seq) seq_copy.append("T") seq_array.append(seq_copy) index += length return seq_array def get_outcome_width_for_level(self,r): return self.width / (2**r) def get_rect_widths_for_level(self, r): ret_arr = [] for k in range(0, r): proportion = float(choose(r,k)) / 2**r ret_arr.append(proportion * self.width) return ret_arr class SplitRectsInBrickWall(AnimationGroup): def __init__(self, mobject, **kwargs): #print mobject.height, mobject.get_height() r = self.subdiv_level = mobject.subdiv_level + 1 subdivs = VGroup() x = -0.5 * mobject.get_width() anims = [] for k in range(0, r): proportion = float(choose(r,k)) / 2**r x += proportion * mobject.get_width() subdiv = DashedLine( mobject.get_top() + x * RIGHT, mobject.get_bottom() + x * RIGHT, dash_length = 0.05 ) subdivs.add(subdiv) anims.append(ShowCreation(subdiv)) mobject.add(subdivs) AnimationGroup.__init__(self, *anims, **kwargs)
from mobject.svg.svg_mobject import * from mobject.geometry import * from mobject.numbers import * class DieFace(SVGMobject): def __init__(self, value, **kwargs): self.value = value self.file_name = "Dice-" + str(value) self.ensure_valid_file() SVGMobject.__init__(self, file_name = self.file_name) class RowOfDice(VGroup): CONFIG = { "values" : list(range(1,7)), "direction": RIGHT, } def init_points(self): for value in self.values: new_die = DieFace(value) new_die.submobjects[0].set_fill(opacity = 0) new_die.submobjects[0].set_stroke(width = 7) new_die.next_to(self, self.direction) self.add(new_die) self.move_to(ORIGIN) class TwoDiceTable(VMobject): CONFIG = { "cell_size" : 1, "label_scale": 0.7 } def __init__(self, **kwargs): VMobject.__init__(self, **kwargs) colors = color_gradient([RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE], 13) self.cells = VGroup() self.labels = VGroup() for i in range(1,7): for j in range(1,7): cell = Square(side_length = self.cell_size) cell.set_fill(color = colors[i+j], opacity = 0.8) cell.move_to(i*self.cell_size*DOWN + j*self.cell_size*RIGHT) self.cells.add(cell) label = Integer(i+j).scale(self.label_scale) label.move_to(cell) self.labels.add(label) self.add(self.cells, self.labels) row1 = RowOfDice().match_width(self) row2 = row1.copy().rotate(-TAU/4) row1.next_to(self, UP) row2.next_to(self, LEFT) self.rows = VGroup(row1, row2) self.add(self.rows) self.center()
from for_3b1b_videos.pi_creature import * from _2018.eop.reusables.eop_constants import * class SicklyPiCreature(PiCreature): CONFIG = { "sick_color": SICKLY_GREEN } def get_slightly_sick(self): self.save_state() self.set_color(self.sick_color) def get_sick(self): self.get_slightly_sick() self.change_mode("sick") def get_better(self): self.restore()
from mobject.types.vectorized_mobject import * from animation.animation import * from animation.composition import * from mobject.geometry import Rectangle, Line from utils.rate_functions import * from for_3b1b_videos.pi_creature_scene import * from _2018.eop.reusables.eop_helpers import * from _2018.eop.reusables.eop_constants import * from _2018.eop.reusables.coin_flipping_pi_creature import * class PiCreatureCoin(VMobject): CONFIG = { "diameter": 0.8, "thickness": 0.2, "nb_ridges" : 7, "stroke_color": YELLOW, "stroke_width": 3, "fill_color": YELLOW, "fill_opacity": 0.7, } def init_points(self): outer_rect = Rectangle( width = self.diameter, height = self.thickness, fill_color = self.fill_color, fill_opacity = self.fill_opacity, stroke_color = self.stroke_color, stroke_width = 0, #self.stroke_width ) self.add(outer_rect) PI = TAU/2 ridge_angles = np.arange(PI/self.nb_ridges,PI,PI/self.nb_ridges) ridge_positions = 0.5 * self.diameter * np.array([ np.cos(theta) for theta in ridge_angles ]) ridge_color = interpolate_color(BLACK,self.stroke_color,0.5) for x in ridge_positions: ridge = Line( x * RIGHT + 0.5 * self.thickness * DOWN, x * RIGHT + 0.5 * self.thickness * UP, stroke_color = ridge_color, stroke_width = self.stroke_width ) self.add(ridge) class CoinFlippingPiCreature(PiCreature): CONFIG = { "flip_height": 3 } def __init__(self, mode = "coin_flip_1", **kwargs): coin = PiCreatureCoin() PiCreature.__init__(self, mode = mode, **kwargs) self.coin = coin self.add(coin) right_arm = self.get_arm_copies()[1] coin.rotate(-TAU/24) coin.next_to(right_arm, RIGHT+UP, buff = 0) coin.shift(0.1 * self.get_width() * LEFT) coin.shift(0.2 * DOWN) def flip_coin_up(self): self.change("coin_flip_2") class FlipUpAndDown(Animation): CONFIG = { "vector" : UP, "height" : 3, "nb_turns" : 1 } def update(self,t): self.mobject.shift(self.height * 4 * t * (1 - t) * self.vector) self.mobject.rotate(t * self.nb_turns * TAU) class FlipCoin(AnimationGroup): CONFIG = { "coin_rate_func" : there_and_back, "pi_rate_func" : lambda t : there_and_back_with_pause(t, 1./4) } def __init__(self, pi_creature, **kwargs): digest_config(self, kwargs) pi_creature_motion = ApplyMethod( pi_creature.flip_coin_up, rate_func = self.pi_rate_func, **kwargs ) coin_motion = Succession( EmptyAnimation(run_time = 1.0), FlipUpAndDown( pi_creature.coin, vector = UP, nb_turns = 5, height = pi_creature.flip_height * pi_creature.get_height(), rate_func = self.coin_rate_func, **kwargs ) ) AnimationGroup.__init__(self,pi_creature_motion, coin_motion) class CoinFlippingPiCreatureScene(Scene): def construct(self): randy = CoinFlippingPiCreature(color = MAROON_E) self.add(randy) self.play(FlipCoin(randy, run_time = 3))
from constants import * COIN_RADIUS = 0.18 COIN_THICKNESS = 0.4 * COIN_RADIUS COIN_FORESHORTENING = 0.5 COIN_NB_RIDGES = 20 COIN_STROKE_WIDTH = 2 COIN_SEQUENCE_SPACING = 0.1 GRADE_COLOR_1 = COLOR_HEADS = RED_E GRADE_COLOR_2 = COLOR_TAILS = BLUE_C COLOR_HEADS_COIN = RED COLOR_TAILS_COIN = BLUE_E TALLY_BACKGROUND_WIDTH = 1.0 TALLY_BACKGROUND_COLOR = BLACK SICKLY_GREEN = "#9BBD37" OUTCOME_COLOR = WHITE OUTCOME_OPACITY = 0.5
from manim_imports_ext import * from random import * def text_range(start,stop,step): # a range as a list of strings numbers = np.arange(start,stop,step) labels = [] for x in numbers: labels.append(str(x)) return labels class Histogram(VMobject): CONFIG = { "start_color" : RED, "end_color" : BLUE, "x_scale" : 1.0, "y_scale" : 1.0, "x_labels" : "auto", # widths, mids, auto, none, [...] "y_labels" : "auto", # auto, none, [...] "y_label_position" : "top", # "center" "x_min" : 0, "bar_stroke_width" : 5, "outline_stroke_width" : 0, "stroke_color" : WHITE } def __init__(self, x_values, y_values, mode = "widths", **kwargs): # mode = "widths" : x_values means the widths of the bars # mode = "posts" : x_values means the delimiters btw the bars digest_config(self, kwargs) if mode == "widths" and len(x_values) != len(y_values): raise Exception("Array lengths do not match up!") elif mode == "posts" and len(x_values) != len(y_values) + 1: raise Exception("Array lengths do not match up!") self.y_values = y_values self.x_values = x_values self.mode = mode self.process_values() VMobject.__init__(self, **kwargs) def process_values(self): # preliminaries self.y_values = np.array(self.y_values) if self.mode == "widths": self.widths = self.x_values self.posts = np.cumsum(self.widths) self.posts = np.insert(self.posts, 0, 0) self.posts += self.x_min self.x_max = self.posts[-1] elif self.mode == "posts": self.posts = self.x_values self.widths = self.x_values[1:] - self.x_values[:-1] self.x_min = self.posts[0] self.x_max = self.posts[-1] else: raise Exception("Invalid mode or no mode specified!") self.x_mids = 0.5 * (self.posts[:-1] + self.posts[1:]) self.widths_scaled = self.x_scale * self.widths self.posts_scaled = self.x_scale * self.posts self.x_min_scaled = self.x_scale * self.x_min self.x_max_scaled = self.x_scale * self.x_max self.y_values_scaled = self.y_scale * self.y_values def init_points(self): self.process_values() for submob in self.submobjects: self.remove(submob) def empty_string_array(n): arr = [] for i in range(n): arr.append("") return arr def num_arr_to_string_arr(arr): # converts number array to string array ret_arr = [] for x in arr: if x == np.floor(x): new_x = int(np.floor(x)) else: new_x = x ret_arr.append(str(new_x)) return ret_arr previous_bar = ORIGIN self.bars = VGroup() self.x_labels_group = VGroup() self.y_labels_group = VGroup() outline_points = [] if self.x_labels == "widths": self.x_labels = num_arr_to_string_arr(self.widths) elif self.x_labels == "mids": self.x_labels = num_arr_to_string_arr(self.x_mids) elif self.x_labels == "auto": self.x_labels = num_arr_to_string_arr(self.x_mids) elif self.x_labels == "none": self.x_labels = empty_string_array(len(self.widths)) if self.y_labels == "auto": self.y_labels = num_arr_to_string_arr(self.y_values) elif self.y_labels == "none": self.y_labels = empty_string_array(len(self.y_values)) for (i,x) in enumerate(self.x_mids): bar = Rectangle( width = self.widths_scaled[i], height = self.y_values_scaled[i], stroke_width = self.bar_stroke_width, stroke_color = self.stroke_color, ) if bar.height == 0: bar.height = 0.01 bar.init_points() t = float(x - self.x_min)/(self.x_max - self.x_min) bar_color = interpolate_color( self.start_color, self.end_color, t ) bar.set_fill(color = bar_color, opacity = 1) bar.next_to(previous_bar,RIGHT,buff = 0, aligned_edge = DOWN) self.bars.add(bar) x_label = OldTexText(self.x_labels[i]) x_label.next_to(bar,DOWN) self.x_labels_group.add(x_label) y_label = OldTexText(self.y_labels[i]) if self.y_label_position == "top": y_label.next_to(bar, UP) elif self.y_label_position == "center": y_label.move_to(bar) else: raise Exception("y_label_position must be top or center") self.y_labels_group.add(y_label) if i == 0: # start with the lower left outline_points.append(bar.get_anchors()[-2]) # upper two points of each bar outline_points.append(bar.get_anchors()[0]) outline_points.append(bar.get_anchors()[1]) previous_bar = bar # close the outline # lower right outline_points.append(bar.get_anchors()[2]) # lower left outline_points.append(outline_points[0]) self.outline = Polygon(*outline_points, stroke_width = self.outline_stroke_width, stroke_color = self.stroke_color) self.add(self.bars, self.x_labels_group, self.y_labels_group, self.outline) self.move_to(ORIGIN) def get_lower_left_point(self): return self.bars[0].get_anchors()[-2] class BuildUpHistogram(Animation): def __init__(self, hist, **kwargs): self.histogram = hist class FlashThroughHistogram(Animation): CONFIG = { "cell_color" : WHITE, "cell_opacity" : 0.8, "hist_opacity" : 0.2 } def __init__(self, mobject, direction = "horizontal", mode = "random", **kwargs): digest_config(self, kwargs) self.cell_height = mobject.y_scale self.prototype_cell = Rectangle( width = 1, height = self.cell_height, fill_color = self.cell_color, fill_opacity = self.cell_opacity, stroke_width = 0, ) x_values = mobject.x_values y_values = mobject.y_values self.mode = mode self.direction = direction self.generate_cell_indices(x_values,y_values) Animation.__init__(self,mobject,**kwargs) def generate_cell_indices(self,x_values,y_values): self.cell_indices = [] for (i,x) in enumerate(x_values): nb_cells = int(np.floor(y_values[i])) for j in range(nb_cells): self.cell_indices.append((i, j)) self.reordered_cell_indices = self.cell_indices if self.mode == "random": shuffle(self.reordered_cell_indices) def cell_for_index(self,i,j): if self.direction == "vertical": width = self.mobject.x_scale height = self.mobject.y_scale x = (i + 0.5) * self.mobject.x_scale y = (j + 0.5) * self.mobject.y_scale center = self.mobject.get_lower_left_point() + x * RIGHT + y * UP elif self.direction == "horizontal": width = self.mobject.x_scale / self.mobject.y_values[i] height = self.mobject.y_scale * self.mobject.y_values[i] x = i * self.mobject.x_scale + (j + 0.5) * width y = height / 2 center = self.mobject.get_lower_left_point() + x * RIGHT + y * UP cell = Rectangle(width = width, height = height) cell.move_to(center) return cell def interpolate_mobject(self,t): if t == 0: self.mobject.add(self.prototype_cell) flash_nb = int(t * (len(self.cell_indices))) - 1 (i,j) = self.reordered_cell_indices[flash_nb] cell = self.cell_for_index(i,j) self.prototype_cell.width = cell.get_width() self.prototype_cell.height = cell.get_height() self.prototype_cell.init_points() self.prototype_cell.move_to(cell.get_center()) if t == 1: self.mobject.remove(self.prototype_cell) def clean_up_from_scene(self, scene = None): Animation.clean_up_from_scene(self, scene) self.update(1) if scene is not None: if self.is_remover(): scene.remove(self.prototype_cell) else: scene.add(self.prototype_cell) return self class OutlineableBars(VGroup): # A group of bars (rectangles), together with # a method that draws an outline around them, # assuming the bars are arranged in a histogram # (aligned at the bottom without gaps). # We use this to morph a row of bricks into a histogram. CONFIG = { "outline_stroke_width" : 3, "stroke_color" : WHITE } def create_outline(self, animated = False, **kwargs): outline_points = [] for (i, bar) in enumerate(self.submobjects): if i == 0: # start with the lower left outline_points.append(bar.get_corner(DOWN + LEFT)) # upper two points of each bar outline_points.append(bar.get_corner(UP + LEFT)) outline_points.append(bar.get_corner(UP + RIGHT)) previous_bar = bar # close the outline # lower right outline_points.append(previous_bar.get_corner(DOWN + RIGHT)) # lower left outline_points.append(outline_points[0]) self.outline = Polygon(*outline_points, stroke_width = self.outline_stroke_width, stroke_color = self.stroke_color) if animated: self.play(FadeIn(self.outline, **kwargs)) return self.outline
from mobject.geometry import * from mobject.svg.tex_mobject import * from _2018.eop.reusables.upright_coins import * class CoinStack(VGroup): CONFIG = { "coin_thickness": COIN_THICKNESS, "size": 5, "face": FlatCoin, } def init_points(self): for n in range(self.size): coin = self.face(thickness = self.coin_thickness) coin.shift(n * self.coin_thickness * UP) self.add(coin) if self.size == 0: point = VectorizedPoint() self.add(point) class HeadsStack(CoinStack): CONFIG = { "face": FlatHeads } class TailsStack(CoinStack): CONFIG = { "face": FlatTails } class DecimalTally(TexText): def __init__(self, heads, tails, **kwargs): TexText.__init__(self, str(heads), "\\textemdash\,", str(tails), **kwargs) self[0].set_color(COLOR_HEADS) self[-1].set_color(COLOR_TAILS) # this only works for single-digit tallies class TallyStack(VGroup): CONFIG = { "coin_thickness": COIN_THICKNESS, "show_decimals": True } def __init__(self, h, t, anchor = ORIGIN, **kwargs): self.nb_heads = h self.nb_tails = t self.anchor = anchor VGroup.__init__(self,**kwargs) def init_points(self): stack1 = HeadsStack(size = self.nb_heads, coin_thickness = self.coin_thickness) stack2 = TailsStack(size = self.nb_tails, coin_thickness = self.coin_thickness) stack1.next_to(self.anchor, LEFT, buff = 0.5 * SMALL_BUFF) stack2.next_to(self.anchor, RIGHT, buff = 0.5 * SMALL_BUFF) stack1.align_to(self.anchor, DOWN) stack2.align_to(self.anchor, DOWN) self.heads_stack = stack1 self.tails_stack = stack2 self.add(stack1, stack2) self.background_rect = background_rect = RoundedRectangle( width = TALLY_BACKGROUND_WIDTH, height = TALLY_BACKGROUND_WIDTH, corner_radius = 0.1, fill_color = TALLY_BACKGROUND_COLOR, fill_opacity = 1.0, stroke_width = 3 ).align_to(self.anchor, DOWN).shift(0.1 * DOWN) self.add_to_back(background_rect) self.decimal_tally = DecimalTally(self.nb_heads, self.nb_tails) self.position_decimal_tally(self.decimal_tally) if self.show_decimals: self.add(self.decimal_tally) def position_decimal_tally(self, decimal_tally): decimal_tally.match_width(self.background_rect) decimal_tally.scale(0.6) decimal_tally.next_to(self.background_rect.get_top(), DOWN, buff = 0.15) return decimal_tally def move_anchor_to(self, new_anchor): for submob in self.submobjects: submob.shift(new_anchor - self.anchor) self.anchor = new_anchor self.position_decimal_tally(self.decimal_tally) return self
from mobject.geometry import * from mobject.svg.tex_mobject import * from utils.color import * from _2018.eop.reusables.eop_helpers import * from _2018.eop.reusables.eop_constants import * class UprightCoin(Circle): # For use in coin sequences CONFIG = { "radius": COIN_RADIUS, "stroke_width": COIN_STROKE_WIDTH, "stroke_color": WHITE, "fill_opacity": 1, "symbol": "\euro" } def __init__(self, **kwargs): Circle.__init__(self,**kwargs) self.symbol_mob = OldTexText(self.symbol, stroke_color = self.stroke_color) self.symbol_mob.set_height(0.5*self.get_height()).move_to(self) self.add(self.symbol_mob) class UprightHeads(UprightCoin): CONFIG = { "fill_color": COLOR_HEADS_COIN, "symbol": "H", } class UprightTails(UprightCoin): CONFIG = { "fill_color": COLOR_TAILS_COIN, "symbol": "T", } class CoinSequence(VGroup): CONFIG = { "sequence": [], "radius" : COIN_RADIUS, "spacing": COIN_SEQUENCE_SPACING, "direction": RIGHT } def __init__(self, sequence, **kwargs): VGroup.__init__(self, **kwargs) self.sequence = sequence offset = 0 for symbol in self.sequence: if symbol == "H": new_coin = UprightHeads(radius = self.radius) elif symbol == "T": new_coin = UprightTails(radius = self.radius) else: new_coin = UprightCoin(symbol = symbol, radius = self.radius) new_coin.shift(offset * self.direction) self.add(new_coin) offset += self.spacing class FlatCoin(UprightCoin): # For use in coin stacks CONFIG = { "thickness": COIN_THICKNESS, "foreshortening": COIN_FORESHORTENING, "nb_ridges": COIN_NB_RIDGES } def __init__(self, **kwargs): UprightCoin.__init__(self, **kwargs) self.symbol_mob.rotate(TAU/8) self.stretch_in_place(self.foreshortening, 1) # draw the edge control_points1 = self.get_points()[12:25].tolist() control_points2 = self.copy().shift(self.thickness * DOWN).get_points()[12:25].tolist() edge_anchors_and_handles = control_points1 edge_anchors_and_handles.append(edge_anchors_and_handles[-1] + self.thickness * DOWN) edge_anchors_and_handles.append(edge_anchors_and_handles[-1] + self.thickness * UP) edge_anchors_and_handles += control_points2[::-1] # list concatenation edge_anchors_and_handles.append(edge_anchors_and_handles[-1] + self.thickness * UP) edge_anchors_and_handles.append(edge_anchors_and_handles[-1] + self.thickness * DOWN) edge_anchors_and_handles.append(control_points1[0]) #edge_anchors_and_handles = edge_anchors_and_handles[::-1] edge = VMobject() edge.set_points(edge_anchors_and_handles) edge.set_fill( color = self.fill_color, opacity = self.fill_opacity ) edge.set_stroke(width = self.stroke_width) self.add(edge) # draw the ridges PI = TAU/2 dtheta = PI/self.nb_ridges ridge_angles = np.arange(dtheta,PI,dtheta) # add a twist onto each coin ridge_angles += np.random.rand(1) * dtheta # crop the angles that overshoot on either side ridge_angles = ridge_angles[(ridge_angles > 0) * (ridge_angles < PI)] ridge_positions = 0.5 * 2 * self.radius * np.array([ np.cos(theta) for theta in ridge_angles ]) ridge_color = interpolate_color(self.stroke_color, self.fill_color, 0.7) for x in ridge_positions: y = -(1 - (x/self.radius)**2)**0.5 * self.foreshortening * self.radius ridge = Line( x * RIGHT + y * UP, x * RIGHT + y * UP + self.thickness * DOWN, stroke_color = ridge_color, stroke_width = self.stroke_width ) self.add(ridge) # redraw the unfilled edge to cover the ridge ends empty_edge = edge.copy() empty_edge.set_fill(opacity = 0) self.add(empty_edge) class FlatHeads(FlatCoin): CONFIG = { "fill_color": COLOR_HEADS_COIN, "symbol": "H", } class FlatTails(FlatCoin): CONFIG = { "fill_color": COLOR_TAILS_COIN, "symbol": "T", }
from utils.color import * from _2018.eop.reusables.eop_constants import * def binary(i): # returns an array of 0s and 1s if i == 0: return [] j = i binary_array = [] while j > 0: jj = j/2 if jj > 0: binary_array.append(j % 2) else: binary_array.append(1) j = jj return binary_array[::-1] def nb_of_ones(i): return binary(i).count(1) def rainbow_color(alpha): nb_colors = 100 rainbow = color_gradient([RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE], nb_colors) rainbow = np.append(rainbow,PURPLE) index = int(alpha * nb_colors) return rainbow[index] def graded_color(n,k): if n != 0: alpha = float(k)/n else: alpha = 0.5 color = interpolate_color(GRADE_COLOR_1, GRADE_COLOR_2, alpha) return color
from manim_imports_ext import * from _2018.eop.reusable_imports import * class ProbabilityDistributions(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs": { "color": MAROON_E, "flip_at_start": False, }, } def construct(self): lag_ratio = 0.2 run_time = 3 # WEATHER FORECAST unit_rect = Rectangle( height = 3, width = 3 ).shift(DOWN) p_rain = 0.23 p_sun = 1 - p_rain opacity = 0.7 rain_rect = unit_rect.copy().stretch(p_rain, 0) rain_rect.align_to(unit_rect, LEFT) rain_rect.set_fill(color = BLUE, opacity = opacity) rain_rect.set_stroke(width = 0) sun_rect = unit_rect.copy().stretch(p_sun, 0) sun_rect.next_to(rain_rect, RIGHT, buff = 0) sun_rect.set_fill(color = YELLOW, opacity = opacity) sun_rect.set_stroke(width = 0) self.add(unit_rect, rain_rect, sun_rect) rain = SVGMobject(file_name = "rain").scale(0.25) sun = SVGMobject(file_name = "sun").scale(0.35) rain.flip().move_to(rain_rect) sun.move_to(sun_rect) self.add(rain, sun) text_scale = 0.7 brace_rain = Brace(rain_rect, UP) p_rain_label = OldTexText("$P($rain$)=$").scale(text_scale) p_rain_decimal = DecimalNumber(p_rain).scale(text_scale) p_rain_decimal.next_to(p_rain_label) p_rain_whole_label = VGroup(p_rain_label, p_rain_decimal) p_rain_whole_label.next_to(brace_rain, UP) brace_sun = Brace(sun_rect, DOWN) p_sun_label = OldTexText("$P($sunshine$)=$").scale(text_scale) p_sun_decimal = DecimalNumber(p_sun).scale(text_scale) p_sun_decimal.next_to(p_sun_label) p_sun_whole_label = VGroup(p_sun_label, p_sun_decimal) p_sun_whole_label.next_to(brace_sun, DOWN) self.add(brace_rain, p_rain_whole_label, brace_sun, p_sun_whole_label) self.wait(6) # new_p_rain = 0.68 # new_p_sun = 1 - new_p_rain # new_rain_rect = unit_rect.copy().stretch(new_p_rain, 0) # new_rain_rect.align_to(unit_rect, LEFT) # new_rain_rect.set_fill(color = BLUE, opacity = opacity) # new_rain_rect.set_stroke(width = 0) # new_sun_rect = unit_rect.copy().stretch(new_p_sun, 0) # new_sun_rect.next_to(new_rain_rect, RIGHT, buff = 0) # new_sun_rect.set_fill(color = YELLOW, opacity = opacity) # new_sun_rect.set_stroke(width = 0) # new_rain = SVGMobject(file_name = "rain").scale(0.35) # new_sun = SVGMobject(file_name = "sun").scale(0.35) # new_rain.flip().move_to(new_rain_rect) # new_sun.move_to(new_sun_rect) # new_brace_rain = Brace(new_rain_rect, UP) # new_p_rain_label = OldTexText("$P($rain$)=$").scale(text_scale) # new_p_rain_decimal = DecimalNumber(new_p_rain).scale(text_scale) # new_p_rain_decimal.next_to(new_p_rain_label) # new_p_rain_whole_label = VGroup(new_p_rain_label, new_p_rain_decimal) # new_p_rain_whole_label.next_to(new_brace_rain, UP) # new_brace_sun = Brace(new_sun_rect, DOWN) # new_p_sun_label = OldTexText("$P($sunshine$)=$").scale(text_scale) # new_p_sun_decimal = DecimalNumber(new_p_sun).scale(text_scale) # new_p_sun_decimal.next_to(new_p_sun_label) # new_p_sun_whole_label = VGroup(new_p_sun_label, new_p_sun_decimal) # new_p_sun_whole_label.next_to(new_brace_sun, DOWN) # def rain_update_func(alpha): # return alpha * new_p_rain + (1 - alpha) * p_rain # def sun_update_func(alpha): # return 1 - rain_update_func(alpha) # update_p_rain = ChangingDecimal( # p_rain_decimal, rain_update_func, # tracked_mobject = p_rain_label, # run_time = run_time # ) # update_p_sun = ChangingDecimal( # p_sun_decimal, sun_update_func, # tracked_mobject = p_sun_label, # run_time = run_time # ) # self.play( # Transform(rain_rect, new_rain_rect, run_time = run_time), # Transform(sun_rect, new_sun_rect, run_time = run_time), # Transform(rain, new_rain, run_time = run_time), # Transform(sun, new_sun, run_time = run_time), # Transform(brace_rain, new_brace_rain, run_time = run_time), # Transform(brace_sun, new_brace_sun, run_time = run_time), # Transform(p_rain_label, new_p_rain_label, run_time = run_time), # Transform(p_sun_label, new_p_sun_label, run_time = run_time), # update_p_rain, # update_p_sun # ) # move the forecast into a corner forecast = VGroup( rain_rect, sun_rect, rain, sun, brace_rain, brace_sun, p_rain_whole_label, p_sun_whole_label, unit_rect ) forecast.target = forecast.copy().scale(0.5) forecast.target.to_corner(UL) self.play(MoveToTarget(forecast)) self.play( FadeOut(brace_rain), FadeOut(brace_sun), FadeOut(p_rain_whole_label), FadeOut(p_sun_whole_label), ) self.wait(3) # DOUBLE DICE THROW cell_size = 0.5 dice_table = TwoDiceTable(cell_size = cell_size, label_scale = 0.7) dice_table.shift(0.8 * DOWN) dice_unit_rect = SurroundingRectangle( dice_table.cells, buff = 0, stroke_color=WHITE ) dice_table_grouped_cells = VGroup() for i in range(6): dice_table_grouped_cells.add(VGroup(*[ VGroup( dice_table.cells[6 * i - 5 * k], dice_table.labels[6 * i - 5 * k], ) for k in range(i + 1) ])) for i in range(5): dice_table_grouped_cells.add(VGroup(*[ VGroup( dice_table.cells[31 + i - 5 * k], dice_table.labels[31 + i - 5 * k], ) for k in range(5 - i) ])) # self.play( # FadeIn(dice_unit_rect), # FadeIn(dice_table.rows) # ) # for (cell, label) in zip(dice_table.cells, dice_table.labels): # cell.add(label) # self.play( # LaggedStartMap(FadeIn, dice_table_grouped_cells, # lag_ratio = lag_ratio, run_time = run_time) # ) self.play( FadeIn(dice_table_grouped_cells), FadeIn(dice_unit_rect), FadeIn(dice_table.rows) ) self.wait(3) self.play( dice_table_grouped_cells.space_out_submobjects, {"factor" : 1.5}, rate_func=there_and_back_with_pause, run_time=run_time ) dice_table.add(dice_unit_rect) dice_table_target = dice_table.deepcopy() dice_table_target.scale(0.5) dice_table_target.to_corner(UR, buff=LARGE_BUFF) dice_table_target.shift(0.4 * UP) self.play(Transform(dice_table, dice_table_target)) self.play( FadeOut(dice_table.rows), FadeOut(dice_unit_rect), ) self.wait(3) # TITLE text = OldTexText("Probability distributions") text.to_edge(UP) text_rect = SurroundingRectangle(text, buff=MED_SMALL_BUFF) text_rect.match_color(text) self.play( FadeIn(text), ShowCreation(text_rect) ) self.wait(3) # COIN FLIP brick_row = BrickRow(3, height = 2, width = 10) coin_flip_rect = VGroup(brick_row) tallies = VGroup() for (i, brick) in enumerate(brick_row.rects): tally = TallyStack(3 - i, i) tally.move_to(brick) tallies.add(tally) coin_flip_rect.add(tallies) coin_flip_rect.scale(0.65).shift(RIGHT) self.play(FadeIn(coin_flip_rect)) counts = [1, 3, 3, 1] braces = VGroup() labels = VGroup() for (rect, count) in zip(brick_row.rects, counts): label = OldTex("{" + str(count) + "\\over 8}").scale(0.5) brace = Brace(rect, DOWN) label.next_to(brace, DOWN) braces.add(brace) labels.add(label) self.play( FadeIn(braces), FadeIn(labels) ) coin_flip_rect.add(braces, labels) self.wait(6) outcomes = brick_row.get_outcome_rects_for_level(3, with_labels = True, inset = True) outcomes.scale(0.65) outcomes.move_to(brick_row.get_center()) outcome_braces = VGroup(*[ Brace(outcome, DOWN) for outcome in outcomes ]) outcome_labels = VGroup(*[ OldTex("{1\over 8}").scale(0.5).next_to(brace, DOWN) for brace in outcome_braces ]) self.play( FadeOut(tallies), FadeIn(outcomes), FadeOut(braces), FadeOut(labels), FadeIn(outcome_braces), FadeIn(outcome_labels) ) self.wait(10)
from manim_imports_ext import * from _2018.eop.reusable_imports import * class Chapter1OpeningQuote(OpeningQuote): CONFIG = { "fade_in_kwargs": { "lag_ratio": 0.5, "rate_func": linear, "run_time": 10, }, "text_size" : "\\normalsize", "use_quotation_marks": False, "quote" : [ "To see a world in a grain of sand\\\\", "And a heaven in a wild flower,\\\\", "Hold infinity in the palm of your hand\\\\", "\phantom{r}And eternity in an hour.\\\\" ], "quote_arg_separator" : " ", "highlighted_quote_terms" : {}, "author" : "William Blake: \\\\ \emph{Auguries of Innocence}", } class Introduction(TeacherStudentsScene): CONFIG = { "default_pi_creature_kwargs": { "color": MAROON_E, "flip_at_start": True, }, } def construct(self): self.wait(5) self.play_student_changes( "confused", "frustrated", "dejected", look_at = UP + 2 * RIGHT ) self.wait() self.play( self.get_teacher().change_mode,"raise_right_hand" ) self.wait() self.wait(30) # put examples here in video editor # # # # # # # # # # # # # # # # # # # show examples of the area model # # # # # # # # # # # # # # # # # # #
from manim_imports_ext import * from _2018.eop.reusable_imports import * class RandyIsSickOrNot(Scene): def construct(self): title = OldTexText("1 in 200") title.to_edge(UP) randy = SicklyPiCreature() randy.set_height(3) randy.move_to(2*LEFT) randy.change_mode("plain") randy.set_color(BLUE) randy.save_state() self.add(randy) p_sick = OldTex("p(","\\text{sick}",") = 0.5\%").scale(1.7) p_sick.set_color_by_tex("sick", SICKLY_GREEN) p_sick.next_to(randy, UP, buff = LARGE_BUFF) self.add(p_sick) self.wait() self.play( ApplyMethod(randy.get_slightly_sick, rate_func = there_and_back) ) self.play(Blink(randy)) self.wait(2) self.play( ApplyMethod(randy.get_sick) ) self.play(Blink(randy)) self.wait() self.play(randy.get_better) self.play( ApplyMethod(randy.get_slightly_sick, rate_func = there_and_back) ) self.play(Blink(randy)) self.wait(0.5) self.play( ApplyMethod(randy.get_sick) ) self.play(Blink(randy)) self.play(randy.get_better) self.wait(3) class OneIn200HasDisease(Scene): def construct(self): title = OldTexText("1 in 200") title.to_edge(UP) creature = PiCreature() all_creatures = VGroup(*[ VGroup(*[ creature.copy() for y in range(20) ]).arrange(DOWN, SMALL_BUFF) for x in range(10) ]).arrange(RIGHT, SMALL_BUFF) all_creatures.set_height(FRAME_HEIGHT * 0.8) all_creatures.next_to(title, DOWN) randy = all_creatures[0][0] all_creatures[0].remove(randy) randy.change_mode("sick") randy.set_color(SICKLY_GREEN) randy.save_state() randy.set_height(3) randy.center() randy.change_mode("plain") randy.set_color(BLUE) self.add(randy) #p_sick = OldTex("p(","\\text{sick}",") = 0.5\%") #p_sick.set_color_by_tex("sick", SICKLY_GREEN) #p_sick.next_to(randy, RIGHT+UP) #self.add(p_sick) self.wait() self.play( randy.change_mode, "sick", randy.set_color, SICKLY_GREEN ) self.play(Blink(randy)) self.play(randy.restore) self.wait() self.play( Write(title), LaggedStartMap(FadeIn, all_creatures, run_time = 3) ) self.wait()
from manim_imports_ext import * from _2018.eop.reusable_imports import * from _2018.eop.chapter1.brick_row_scene import BrickRowScene class EntireBrickWall(BrickRowScene, MovingCameraScene): def setup(self): super(BrickRowScene, self).setup() super(PiCreatureScene, self).setup() def construct(self): self.remove(self.get_primary_pi_creature()) row_height = 0.3 nb_rows = 20 start_point = 3 * UP + 1 * LEFT rows = VMobject() rows.add(BrickRow(0, height = row_height)) rows.move_to(start_point) self.add(rows) zero_counter = Integer(0).next_to(start_point + 0.5 * rows[0].width * RIGHT) nb_flips_text = OldTexText("\# of flips") nb_flips_text.next_to(zero_counter, RIGHT, buff = LARGE_BUFF) self.add(zero_counter, nb_flips_text) flip_counters = VGroup(zero_counter) for i in range(1, nb_rows + 1): rows.add(rows[-1].copy()) self.bring_to_back(rows[-1]) anims = [ rows[-1].shift, row_height * DOWN, Animation(rows[-2]) ] if i % 5 == 0: counter = Integer(i) counter.next_to(rows[-1].get_right() + row_height * DOWN, RIGHT) flip_counters.add(counter) anims.append(FadeIn(counter)) self.play(*anims) self.play(SplitRectsInBrickWall(rows[-1])) rows.submobjects[-1] = self.merge_rects_by_subdiv(rows[-1]) rows.submobjects[-1] = self.merge_rects_by_coloring(rows[-1]) # draw indices under the last row for the number of tails tails_counters = VGroup() for (i, rect) in enumerate(rows[-1].rects): if i < 6 or i > 14: continue if i == 6: counter = OldTex("\dots", color = COLOR_TAILS) counter.next_to(rect, DOWN, buff = 1.5 * MED_SMALL_BUFF) elif i == 14: counter = OldTex("\dots", color = COLOR_TAILS) counter.next_to(rect, DOWN, buff = 1.5 * MED_SMALL_BUFF) counter.shift(0.2 * RIGHT) else: counter = Integer(i, color = COLOR_TAILS) counter.next_to(rect, DOWN) tails_counters.add(counter) nb_tails_text = OldTexText("\# of tails", color = COLOR_TAILS) nb_tails_text.next_to(tails_counters[-1], RIGHT, buff = LARGE_BUFF) self.play( LaggedStartMap(FadeIn, tails_counters), FadeIn(nb_tails_text) ) # remove any hidden brick rows self.clear() self.add(nb_flips_text) mobs_to_shift = VGroup( rows, flip_counters, tails_counters, nb_tails_text, ) self.play(mobs_to_shift.shift, 3 * UP) last_row_rect = SurroundingRectangle(rows[-1], buff = 0) last_row_rect.set_stroke(color = YELLOW, width = 6) rows.save_state() self.play( rows.fade, 0.9, ShowCreation(last_row_rect) ) def highlighted_brick(row = 20, nb_tails = 10): brick_copy = rows[row].rects[nb_tails].copy() brick_copy.set_fill(color = YELLOW, opacity = 0.8) prob_percentage = float(choose(row, nb_tails)) / 2**row * 100 brick_label = DecimalNumber(prob_percentage, unit = "\%", num_decimal_places = 1, color = BLACK) brick_label.move_to(brick_copy) brick_label.set_height(0.8 * brick_copy.get_height()) return VGroup(brick_copy, brick_label) highlighted_bricks = [ highlighted_brick(row = 20, nb_tails = i) for i in range(20) ] self.wait() self.play( FadeIn(highlighted_bricks[10]) ) self.wait() self.play( FadeOut(highlighted_bricks[10]), FadeIn(highlighted_bricks[9]), FadeIn(highlighted_bricks[11]), ) self.wait() self.play( FadeOut(highlighted_bricks[9]), FadeOut(highlighted_bricks[11]), FadeIn(highlighted_bricks[8]), FadeIn(highlighted_bricks[12]), ) self.wait() self.play( FadeOut(highlighted_bricks[8]), FadeOut(highlighted_bricks[12]), FadeOut(last_row_rect), rows.restore, ) self.wait() new_frame = self.camera_frame.copy() new_frame.scale(0.0001).move_to(rows.get_corner(DR)) self.play( Transform(self.camera_frame, new_frame, run_time = 9, rate_func = exponential_decay ) )
from manim_imports_ext import * from _2018.eop.reusable_imports import * class IllustrateAreaModelExpectation(Scene): def construct(self): formula = OldTex("E[X] = \sum_{i=1}^N p_i x_i").move_to(3 * LEFT + UP) self.play(Write(formula)) x_scale = 5.0 y_scale = 1.0 probabilities = np.array([1./8, 3./8, 3./8, 1./8]) prob_strings = ["{1\over 8}","{3\over 8}","{3\over 8}","{1\over 8}"] cumulative_probabilities = np.cumsum(probabilities) cumulative_probabilities = np.insert(cumulative_probabilities, 0, 0) y_values = np.array([0, 1, 2, 3]) hist = Histogram(probabilities, y_values, mode = "widths", x_scale = x_scale, y_scale = y_scale, x_labels = "none" ) flat_hist = Histogram(probabilities, 0 * y_values, mode = "widths", x_scale = x_scale, y_scale = y_scale, x_labels = "none" ) self.play(FadeIn(flat_hist)) self.play( ReplacementTransform(flat_hist, hist) ) braces = VGroup() p_labels = VGroup() # add x labels (braces) for (p,string,bar) in zip(probabilities, prob_strings,hist.bars): brace = Brace(bar, DOWN, buff = 0.1) p_label = OldTex(string).next_to(brace, DOWN, buff = SMALL_BUFF).scale(0.7) group = VGroup(brace, p_label) braces.add(brace) p_labels.add(p_label) self.play( LaggedStartMap(FadeIn,braces), LaggedStartMap(FadeIn, p_labels) ) y_average = np.mean(y_values) averaged_y_values = y_average * np.ones(np.shape(y_values)) averaged_hist = flat_hist = Histogram(probabilities, averaged_y_values, mode = "widths", x_scale = x_scale, y_scale = y_scale, x_labels = "none", y_labels = "none" ).fade(0.2) ghost_hist = hist.copy().fade(0.8) self.bring_to_back(ghost_hist) self.play(Transform(hist, averaged_hist, run_time = 3)) self.wait() average_brace = Brace(averaged_hist, RIGHT, buff = 0.1) average_label = OldTex(str(y_average)).scale(0.7) average_label.next_to(average_brace, RIGHT, SMALL_BUFF) average_group = VGroup(average_brace, average_label) one_brace = Brace(averaged_hist, DOWN, buff = 0.1) one_p_label = OldTex(str(1)).next_to(one_brace, DOWN, buff = SMALL_BUFF).scale(0.7) one_group = VGroup(one_brace, one_p_label) self.play( FadeIn(average_group), Transform(braces, one_brace), Transform(p_labels, one_p_label), ) rect = SurroundingRectangle(formula, buff = 0.5 * MED_LARGE_BUFF) self.play(ShowCreation(rect))
from manim_imports_ext import * from _2018.eop.reusable_imports import * class ShuffleThroughAllSequences(Scene): CONFIG = { "nb_coins" : 20, "run_time" : 5, "fps" : int(1.0/PRODUCTION_QUALITY_FRAME_DURATION), "coin_size" : 0.5, "coin_spacing" : 0.65 } def construct(self): nb_frames = self.run_time * self.fps nb_relevant_coins = int(np.log2(nb_frames)) + 1 print("relevant coins:", nb_relevant_coins) nb_idle_coins = self.nb_coins - nb_relevant_coins idle_heads = CoinSequence(nb_idle_coins * ["H"], radius = self.coin_size * 0.5, spacing = self.coin_spacing) idle_tails = CoinSequence(nb_idle_coins * ["T"], radius = self.coin_size * 0.5, spacing = self.coin_spacing) idle_tails.fade(0.5) idle_part = VGroup(idle_heads, idle_tails) left_idle_part = CoinSequence(6 * ["H"], radius = self.coin_size * 0.5, spacing = self.coin_spacing) #self.add(idle_part, left_idle_part) self.add(left_idle_part) last_coin_seq = VGroup() for i in range(2**nb_relevant_coins): binary_seq = binary(i) # pad to the left with 0s nb_leading_zeroes = nb_relevant_coins - len(binary_seq) for j in range(nb_leading_zeroes): binary_seq.insert(0, 0) seq2 = ["H" if x == 0 else "T" for x in binary_seq] coin_seq = CoinSequence(seq2, radius = self.coin_size * 0.5, spacing = self.coin_spacing) coin_seq.next_to(idle_part, LEFT, buff = self.coin_spacing - self.coin_size) left_idle_part.next_to(coin_seq, LEFT, buff = self.coin_spacing - self.coin_size) all_coins = VGroup(left_idle_part, coin_seq) #, idle_part) all_coins.center() self.remove(last_coin_seq) self.add(coin_seq) #self.wait(1.0/self.fps) self.update_frame() self.add_frames(self.get_frame()) last_coin_seq = coin_seq print(float(i)/2**nb_relevant_coins)
from manim_imports_ext import * from _2018.eop.reusable_imports import * class ShowUncertaintyDice(Scene): def throw_a_die(self, run_time = 0.3): eye = np.random.randint(1,7) face = self.row_of_dice.submobjects[eye - 1] self.play( ApplyMethod(face.submobjects[0].set_fill, {"opacity": 1}, rate_func = there_and_back, run_time = run_time, ), ) def construct(self): self.row_of_dice = RowOfDice(direction = DOWN).scale(0.5) self.add(self.row_of_dice) for i in range(5): self.throw_a_die() self.wait(1) for i in range(10): self.throw_a_die() self.wait(0.3) for i in range(100): self.throw_a_die(0.05) self.wait(0.0) class IdealizedDieHistogram(Scene): def construct(self): self.probs = 1.0/6 * np.ones(6) x_scale = 1.3 y_labels = ["${1\over 6}$"] * 6 hist = Histogram(np.ones(6), self.probs, mode = "widths", x_labels = "none", y_labels = y_labels, y_label_position = "center", y_scale = 20, x_scale = x_scale, ) hist.rotate(-TAU/4) for label in hist.y_labels_group: label.rotate(TAU/4) hist.remove(hist.y_labels_group) self.play(FadeIn(hist)) self.play(LaggedStartMap(FadeIn, hist.y_labels_group))
from manim_imports_ext import * from _2018.eop.reusable_imports import * class RandyThinksAboutCoin(PiCreatureScene): def construct(self): randy = self.get_primary_pi_creature() randy.center() self.add(randy) self.wait() h_or_t = BinaryOption(UprightHeads().scale(3), UprightTails().scale(3), text_scale = 1.5) self.think(h_or_t, direction = LEFT) v = 0.3 self.play( h_or_t[0].shift,v*UP, h_or_t[2].shift,v*DOWN, ) self.play( h_or_t[0].shift,2*v*DOWN, h_or_t[2].shift,2*v*UP, ) self.play( h_or_t[0].shift,v*UP, h_or_t[2].shift,v*DOWN, ) self.wait()
from manim_imports_ext import * from _2018.eop.reusable_imports import * class StackingCoins(Scene): def construct(self): h = t = 0 heads_stack = HeadsStack(size = h) heads_stack.next_to(0.5*LEFT + 3*DOWN, UP) tails_stack = TailsStack(size = t) tails_stack.next_to(0.5*RIGHT + 3*DOWN, UP) self.add(heads_stack, tails_stack) for i in range(120): flip = np.random.choice(["H", "T"]) if flip == "H": h += 1 new_heads_stack = HeadsStack(size = h) new_heads_stack.next_to(0.5*LEFT + 3*DOWN, UP) self.play(Transform(heads_stack, new_heads_stack, run_time = 0.2)) elif flip == "T": t += 1 new_tails_stack = TailsStack(size = t) new_tails_stack.next_to(0.5*RIGHT + 3*DOWN, UP) self.play(Transform(tails_stack, new_tails_stack, run_time = 0.2))
from manim_imports_ext import * from _2018.eop.reusable_imports import * class MillionFlips(Scene): def construct(self): title = OldTexText("1{,}000{,}000 flips") title.to_edge(UP) self.add(title) small_wait_time = 1.0 / 15 # Um... n_flips_label = OldTexText("\\# Flips: ") n_heads_label = OldTexText("\\# Heads: ") n_flips_count = Integer(0) n_heads_count = Integer(0) n_heads_label.to_edge(RIGHT, buff=2 * LARGE_BUFF) n_flips_label.next_to(n_heads_label, DOWN, aligned_edge=LEFT) n_flips_count.next_to(n_flips_label[-1], RIGHT) n_heads_count.next_to(n_heads_label[-1], RIGHT) VGroup(n_flips_count, n_heads_count).shift(0.5 * SMALL_BUFF * UP) self.add(n_flips_label, n_heads_label, n_flips_count, n_heads_count) coins = VGroup(*[ FlatHeads() if random.random() < 0.5 else FlatTails() for x in range(100) ]) self.organize_group(coins) proportions = np.random.normal(0.5, 0.5 * 0.1, 100) hundred_boxes = VGroup(*[ Square( stroke_width=1, stroke_color=WHITE, fill_opacity=1, fill_color=interpolate_color(COLOR_HEADS, COLOR_TAILS, prop) ) for prop in proportions ]) self.organize_group(hundred_boxes) ten_k_proportions = np.random.normal(0.5, 0.5 * 0.01, 100) ten_k_boxes = VGroup(*[ Square( stroke_width=1, stroke_color=WHITE, fill_opacity=1, fill_color=interpolate_color(COLOR_HEADS, COLOR_TAILS, prop) ) for prop in ten_k_proportions ]) self.organize_group(ten_k_boxes) # Animations for coin in coins: self.add(coin) self.increment(n_flips_count) if isinstance(coin, FlatHeads): self.increment(n_heads_count) self.wait(small_wait_time) self.play( FadeIn(hundred_boxes[0]), coins.set_stroke, {"width": 0}, coins.replace, hundred_boxes[0] ) hundred_boxes[0].add(coins) for box, prop in list(zip(hundred_boxes, proportions))[1:]: self.add(box) self.increment(n_flips_count, 100) self.increment(n_heads_count, int(np.round(prop * 100))) self.wait(small_wait_time) self.play( FadeIn(ten_k_boxes[0]), hundred_boxes.set_stroke, {"width": 0}, hundred_boxes.replace, ten_k_boxes[0] ) ten_k_boxes[0].add(hundred_boxes) for box, prop in list(zip(ten_k_boxes, ten_k_proportions))[1:]: self.add(box) self.increment(n_flips_count, 10000) self.increment(n_heads_count, int(np.round(prop * 10000))) self.wait(small_wait_time) self.wait() def organize_group(self, group): group.arrange_in_grid(10) group.set_height(5) group.shift(DOWN + 2 * LEFT) def increment(self, integer_mob, value=1): new_int = Integer(integer_mob.number + value) new_int.move_to(integer_mob, DL) integer_mob.number += value integer_mob.submobjects = new_int.submobjects class PropHeadsWithinThousandth(Scene): def construct(self): prob = OldTex( "P(499{,}000 \\le", "\\# \\text{H}", "\\le 501{,}000)", "\\approx", "0.9545", ) prob[1].set_color(RED) prob[-1].set_color(YELLOW) self.add(prob) class PropHeadsWithinHundredth(Scene): def construct(self): prob = OldTex( "P(490{,}000 \\le", "\\# \\text{H}", "\\le 510{,}000)", "\\approx", "0.99999999\\dots", ) prob[1].set_color(RED) prob[-1].set_color(YELLOW) self.add(prob)
from manim_imports_ext import * from _2018.eop.reusable_imports import * from _2018.eop.combinations import * from _2018.eop.independence import * import itertools as it class RandyFlipsAndStacks(Scene): def construct(self): randy = CoinFlippingPiCreature(color = MAROON_E) randy.scale(0.5).to_edge(LEFT + DOWN) heads = tails = 0 tally = TallyStack(heads, tails, anchor = ORIGIN) nb_flips = 10 flips = np.random.randint(2, size = nb_flips) for i in range(nb_flips): self.play(FlipCoin(randy)) self.wait(0.5) flip = flips[i] if flip == 0: heads += 1 elif flip == 1: tails += 1 else: raise Exception("That side does not exist on this coin") new_tally = TallyStack(heads, tails, anchor = ORIGIN) if tally.nb_heads == 0 and new_tally.nb_heads == 1: self.play(FadeIn(new_tally.heads_stack)) elif tally.nb_tails == 0 and new_tally.nb_tails == 1: self.play(FadeIn(new_tally.tails_stack)) else: self.play(Transform(tally, new_tally)) tally = new_tally class TwoDiceTableScene(Scene): def construct(self): table = TwoDiceTable(cell_size = 1) table.center() self.add(table) class VisualCovariance(Scene): def construct(self): size = 4 square = Square(side_length = size) n_points = 30 cloud = VGroup(*[ Dot((x + 0.8*y) * RIGHT + y * UP).set_fill(WHITE, 1) for x, y in zip( np.random.normal(0, 1, n_points), np.random.normal(0, 1, n_points) ) ]) self.add_foreground_mobject(cloud) x_axis = Vector(8*RIGHT, color = WHITE).move_to(2.5*DOWN) y_axis = Vector(5*UP, color = WHITE).move_to(4*LEFT) self.add(x_axis, y_axis) random_pairs = [ (p1, p2) for (p1, p2) in it.combinations(cloud, 2) ] np.random.shuffle(random_pairs) for (p1, p2) in random_pairs: c1, c2 = p1.get_center(), p2.get_center() x1, y1, x2, y2 = c1[0], c1[1], c2[0], c2[1] if x1 >= x2: continue if y2 > y1: # make a red rect color = RED opacity = 0.1 elif y2 < y1: # make a blue rect color = BLUE opacity = 0.2 rect = Rectangle(width = x2 - x1, height = abs(y2 - y1)) rect.set_fill(color = color, opacity = opacity) rect.set_stroke(width = 0) rect.move_to((c1+c2)/2) self.play(FadeIn(rect), run_time = 0.05) class BinaryChoices(Scene): def construct(self): example1 = BinaryOption(UprightHeads(), UprightTails()) example2 = BinaryOption(Male(), Female()) example3 = BinaryOption(Checkmark(), Xmark()) example2.next_to(example1, DOWN, buff = MED_LARGE_BUFF) example3.next_to(example2, DOWN, buff = MED_LARGE_BUFF) all = VGroup(example1, example2, example3) all = all.scale(2) self.play( LaggedStartMap(FadeIn, all) )
from manim_imports_ext import * from _2018.eop.reusable_imports import * from _2018.eop.independence import * class QuizResult(PiCreatureScene): CONFIG = { "pi_creatures_start_on_screen" : False, "random_seed" : 0 } def construct(self): def get_example_quiz(): quiz = get_quiz( "Define ``Brachistochrone'' ", "Define ``Tautochrone'' ", "Define ``Cycloid'' ", ) rect = SurroundingRectangle(quiz, buff = 0) rect.set_fill(color = BLACK, opacity = 1) rect.set_stroke(width = 0) quiz.add_to_back(rect) return quiz highlight_color = WHITE nb_students_x = 5 nb_students_y = 3 spacing_students_x = 2.0 spacing_students_y = 2.2 all_students = PiCreatureClass( width = nb_students_x, height = nb_students_y)# Defunct() student_points = [] grades = [] grades_count = [] hist_y_values = np.zeros(4) for i in range(nb_students_x): for j in range(nb_students_y): x = i * spacing_students_x y = j * spacing_students_y #pi = PiCreature().scale(0.3) #pi.move_to([x,y,0]) #all_students.add(pi) all_students[i*nb_students_y + j].move_to([x,y,0]) q1 = np.random.choice([True, False]) q2 = np.random.choice([True, False]) q3 = np.random.choice([True, False]) student_points.append([q1, q2, q3]) grade = q1*1+q2*1+q3*1 grades.append(grade) hist_y_values[grade] += 1 # How many times has this grade already occured? grade_count = grades.count(grade) grades_count.append(grade_count) all_students.move_to(ORIGIN) self.pi_creatures = all_students self.play(FadeIn(all_students)) all_quizzes = VGroup() quiz = get_example_quiz().scale(0.2) for pi in all_students: quiz_copy = quiz.copy() quiz_copy.next_to(pi, UP) all_quizzes.add(quiz_copy) master_quiz = get_example_quiz() self.play(Write(master_quiz), run_time = 2) self.wait() self.play(ReplacementTransform( VGroup(master_quiz), all_quizzes, run_time=2, lag_ratio=0.5 )) self.wait(2) grades_mob = VGroup() for (pi, quiz, grade) in zip(all_students, all_quizzes, grades): grade_mob = OldTex(str(grade) + "/3") grade_mob.move_to(quiz) grades_mob.add(grade_mob) self.remove(master_quiz) self.wait() self.play( FadeOut(all_quizzes), FadeIn(grades_mob) ) # self.play( # all_students[2:].fade, 0.8, # grades_mob[2:].fade, 0.8 # ) students_points_mob = VGroup() for (pi, quiz, points) in zip(all_students, all_quizzes, student_points): slot = get_slot_group(points, include_qs = False) slot.scale(0.5).move_to(quiz) students_points_mob.add(slot) self.wait() self.play( #all_students.fade, 0, FadeOut(grades_mob), FadeIn(students_points_mob) ) all_students.save_state() students_points_mob.save_state() self.wait() randy = all_students[0] morty = all_students[nb_students_y] all_other_students = VGroup(*all_students) all_other_students.remove(randy, morty) randy_points = students_points_mob[0] morty_points = students_points_mob[nb_students_y] all_other_points = VGroup(*students_points_mob) all_other_points.remove(randy_points, morty_points) self.play( all_other_students.fade, 0.8, all_other_points.fade, 0.8, ) self.wait() scale = 1.5 self.play(randy_points.scale,scale) self.play(randy_points.scale,1.0/scale, morty_points.scale,scale) self.play(morty_points.scale,1.0/scale) self.wait() self.play( all_students.restore, students_points_mob.restore, ) self.wait() anims = [] for points in students_points_mob: anims.append(points.scale) anims.append(scale) self.play(*anims) self.wait() anims = [] for points in students_points_mob: anims.append(points.scale) anims.append(1.0/scale) self.play(*anims) anims = [] anchor_point = 3 * DOWN + 1 * LEFT for (pi, grade, grades_count) in zip(all_students, grades, grades_count): anims.append(pi.move_to) anims.append(anchor_point + grade * RIGHT + grades_count * UP) anims.append(FadeOut(students_points_mob)) self.wait() self.play(*anims) grade_labels = VGroup() for i in range(4): grade_label = Integer(i, color = highlight_color) grade_label.move_to(i * RIGHT) grade_labels.add(grade_label) grade_labels.next_to(all_students, DOWN) out_of_label = OldTexText("out of 3", color = highlight_color) out_of_label.next_to(grade_labels, RIGHT, buff = MED_LARGE_BUFF) grade_labels.add(out_of_label) self.wait() self.play(Write(grade_labels)) grade_hist = Histogram( np.ones(4), hist_y_values, mode = "widths", x_labels = "none", y_label_position = "center", bar_stroke_width = 0, outline_stroke_width = 5 ) grade_hist.move_to(all_students) self.wait() self.play( FadeIn(grade_hist), FadeOut(all_students) ) nb_students_label = OldTexText("\# of students", color = highlight_color) nb_students_label.move_to(5 * RIGHT + 1 * UP) arrows = VGroup(*[ Arrow(nb_students_label.get_left(), grade_hist.bars[i].get_center(), color = highlight_color) for i in range(4) ]) self.wait() self.play(Write(nb_students_label), LaggedStartMap(GrowArrow,arrows)) percentage_label = OldTexText("\% of students", color = highlight_color) percentage_label.move_to(nb_students_label) percentages = hist_y_values / (nb_students_x * nb_students_y) * 100 anims = [] for (label, percentage) in zip(grade_hist.y_labels_group, percentages): new_label = DecimalNumber(percentage, num_decimal_places = 1, unit = "\%", color = highlight_color ) new_label.scale(0.7) new_label.move_to(label) anims.append(Transform(label, new_label)) anims.append(ReplacementTransform(nb_students_label, percentage_label)) self.wait() self.play(*anims) self.remove(all_quizzes) # put small copy of class in corner for (i,pi) in enumerate(all_students): x = i % 5 y = i / 5 pi.move_to(x * RIGHT + y * UP) all_students.scale(0.8) all_students.to_corner(DOWN + LEFT) self.wait() self.play(FadeIn(all_students)) prob_label = OldTexText("probability", color = highlight_color) prob_label.move_to(percentage_label) self.wait() self.play( all_students[8].set_color, MAROON_E, #all_students[:8].fade, 0.6, #all_students[9:].fade, 0.6, ReplacementTransform(percentage_label, prob_label) ) self.wait() self.play( FadeOut(prob_label), FadeOut(arrows) ) flash_hist = FlashThroughHistogram( grade_hist, direction = "vertical", mode = "random", cell_opacity = 0.5, run_time = 5, rate_func = linear ) flash_class = FlashThroughClass( all_students, mode = "random", highlight_color = MAROON_E, run_time = 5, rate_func = linear ) self.wait() for i in range(3): self.play(flash_hist, flash_class) self.remove(flash_hist.prototype_cell)
from manim_imports_ext import * class IllustrateAreaModelBayes(Scene): def construct(self): color_A = YELLOW color_not_A = YELLOW_E color_B = MAROON color_not_B = MAROON_E opacity_B = 0.7 # show independent events sample_space_width = sample_space_height = 3 p_of_A = 0.7 p_of_not_A = 1 - p_of_A p_of_B = 0.8 p_of_not_B = 1 - p_of_B rect_A = Rectangle( width = p_of_A * sample_space_width, height = 1 * sample_space_height, stroke_width = 0, fill_color = color_A, fill_opacity = 1.0 ).move_to(3 * RIGHT + 1.5 * UP) rect_not_A = Rectangle( width = p_of_not_A * sample_space_width, height = 1 * sample_space_height, stroke_width = 0, fill_color = color_not_A, fill_opacity = 1.0 ).next_to(rect_A, RIGHT, buff = 0) brace_A = Brace(rect_A, DOWN) label_A = OldTex("P(A)").next_to(brace_A, DOWN).scale(0.7) brace_not_A = Brace(rect_not_A, DOWN) label_not_A = OldTex("P(\\text{not }A)").next_to(brace_not_A, DOWN).scale(0.7) # self.play( # LaggedStartMap(FadeIn, VGroup(rect_A, rect_not_A)) # ) # self.play( # ShowCreation(brace_A), # Write(label_A), # ) rect_B = Rectangle( width = 1 * sample_space_width, height = p_of_B * sample_space_height, stroke_width = 0, fill_color = color_B, fill_opacity = opacity_B ) rect_not_B = Rectangle( width = 1 * sample_space_width, height = p_of_not_B * sample_space_height, stroke_width = 0, fill_color = color_not_B, fill_opacity = opacity_B ).next_to(rect_B, UP, buff = 0) VGroup(rect_B, rect_not_B).move_to(VGroup(rect_A, rect_not_A)) brace_B = Brace(rect_B, LEFT) label_B = OldTex("P(B)").next_to(brace_B, LEFT).scale(0.7) brace_not_B = Brace(rect_not_B, LEFT) label_not_B = OldTex("P(\\text{not }B)").next_to(brace_not_B, LEFT).scale(0.7) # self.play( # LaggedStartMap(FadeIn, VGroup(rect_B, rect_not_B)) # ) # self.play( # ShowCreation(brace_B), # Write(label_B), # ) rect_A_and_B = Rectangle( width = p_of_A * sample_space_width, height = p_of_B * sample_space_height, stroke_width = 3, fill_opacity = 0.0 ).align_to(rect_A, DOWN).align_to(rect_A,LEFT) label_A_and_B = OldTex("P(A\\text{ and }B)").scale(0.7) label_A_and_B.move_to(rect_A_and_B) # self.play( # ShowCreation(rect_A_and_B) # ) indep_formula = OldTex("P(A\\text{ and }B)", "=", "P(A)", "\cdot", "P(B)") indep_formula = indep_formula.scale(0.7) label_p_of_b = indep_formula.get_part_by_tex("P(B)") label_A_and_B_copy = label_A_and_B.copy() label_A_copy = label_A.copy() label_B_copy = label_B.copy() # self.add(label_A_and_B_copy, label_A_copy, label_B_copy) # self.play(Transform(label_A_and_B_copy, indep_formula[0])) # self.play(FadeIn(indep_formula[1])) # self.play(Transform(label_A_copy, indep_formula[2])) # self.play(FadeIn(indep_formula[3])) # self.play(Transform(label_B_copy, indep_formula[4])) #self.wait() label_A_and_B_copy = indep_formula[0] label_A_copy = indep_formula[2] label_B_copy = indep_formula[4] # show conditional prob rect_A_and_B.set_fill(color = RED, opacity = 0.5) rect_A_and_not_B = Rectangle( width = p_of_A * sample_space_width, height = p_of_not_B * sample_space_height, stroke_width = 0, fill_color = color_not_B, fill_opacity = opacity_B ).next_to(rect_A_and_B, UP, buff = 0) rect_not_A_and_B = Rectangle( width = p_of_not_A * sample_space_width, height = p_of_B * sample_space_height, stroke_width = 0, fill_color = color_B, fill_opacity = opacity_B ).next_to(rect_A_and_B, RIGHT, buff = 0) rect_not_A_and_not_B = Rectangle( width = p_of_not_A * sample_space_width, height = p_of_not_B * sample_space_height, stroke_width = 0, fill_color = color_not_B, fill_opacity = opacity_B ).next_to(rect_not_A_and_B, UP, buff = 0) indep_formula.next_to(rect_not_A, LEFT, buff = 5) #indep_formula.shift(UP) self.play(Write(indep_formula)) self.play( FadeIn(VGroup( rect_A, rect_not_A, brace_A, label_A, brace_B, label_B, rect_A_and_not_B, rect_not_A_and_B, rect_not_A_and_not_B, rect_A_and_B, label_A_and_B, )) ) self.wait() p_of_B_knowing_A = 0.6 rect_A_and_B.target = Rectangle( width = p_of_A * sample_space_width, height = p_of_B_knowing_A * sample_space_height, stroke_width = 3, fill_color = color_B, fill_opacity = opacity_B ).align_to(rect_A_and_B, DOWN).align_to(rect_A_and_B, LEFT) rect_A_and_not_B.target = Rectangle( width = p_of_A * sample_space_width, height = (1 - p_of_B_knowing_A) * sample_space_height, stroke_width = 0, fill_color = color_not_B, fill_opacity = opacity_B ).next_to(rect_A_and_B.target, UP, buff = 0) brace_B.target = Brace(rect_A_and_B.target, LEFT) label_B.target = OldTex("P(B\mid A)").scale(0.7).next_to(brace_B.target, LEFT) self.play( MoveToTarget(rect_A_and_B), MoveToTarget(rect_A_and_not_B), MoveToTarget(brace_B), MoveToTarget(label_B), label_A_and_B.move_to,rect_A_and_B.target ) label_B_knowing_A = label_B #self.play(FadeOut(label_B_copy)) self.remove(indep_formula.get_part_by_tex("P(B)")) indep_formula.remove(indep_formula.get_part_by_tex("P(B)")) label_B_knowing_A_copy = label_B_knowing_A.copy() self.add(label_B_knowing_A_copy) self.play( label_B_knowing_A_copy.next_to, indep_formula.get_part_by_tex("\cdot"), RIGHT, ) # solve formula for P(B|A) rearranged_formula = OldTex("P(B\mid A)", "=", "{P(A\\text{ and }B) \over P(A)}") rearranged_formula.move_to(indep_formula) self.wait() self.play( # in some places get_part_by_tex does not find the correct part # so I picked out fitting indices label_B_knowing_A_copy.move_to, rearranged_formula.get_part_by_tex("P(B\mid A)"), label_A_copy.move_to, rearranged_formula[-1][10], label_A_and_B_copy.move_to, rearranged_formula[-1][3], indep_formula.get_part_by_tex("=").move_to, rearranged_formula.get_part_by_tex("="), Transform(indep_formula.get_part_by_tex("\cdot"), rearranged_formula[2][8]), ) rect = SurroundingRectangle(rearranged_formula, buff = 0.5 * MED_LARGE_BUFF) self.play(ShowCreation(rect)) self.wait()
from manim_imports_ext import * class WhatDoesItReallyMean(TeacherStudentsScene): CONFIG = { "default_pi_creature_kwargs": { "color": MAROON_E, "flip_at_start": True, }, } def construct(self): student_q = OldTexText( "What does", "``probability''\\\\", "\\emph{actually}", "mean?" ) student_q.set_color_by_tex("probability", YELLOW) self.student_says(student_q, target_mode="sassy") self.wait() self.play( self.students[1].change_mode, "confused" ) self.wait(2) student_bubble = self.students[1].bubble self.students[1].bubble = None student_bubble.add(student_bubble.content) self.play( student_bubble.scale, 0.5, student_bubble.to_corner, UL, ) self.teacher_says( "Don't worry -- philosophy\\\\ can come later!", added_anims=[self.change_students(*3 * ["happy"])], ) self.wait(2) self.play(RemovePiCreatureBubble(self.teacher)) self.play(*[ ApplyMethod(pi.look_at, ORIGIN) for pi in self.get_pi_creatures() ]) self.play_all_student_changes("pondering", look_at=UP) self.wait(3) self.play_student_changes("confused", look_at=UP) self.wait(3)
from manim_imports_ext import * from _2018.eoc.chapter8 import * import scipy.special class IllustrateAreaModelErf(GraphScene): CONFIG = { "x_min" : -3.0, "x_max" : 3.0, "y_min" : 0, "y_max" : 1.0, "num_rects": 400, "y_axis_label" : "", "x_axis_label" : "", "variable_point_label" : "a", "graph_origin": 2.5 * DOWN + 4 * RIGHT, "x_axis_width": 5, "y_axis_height": 5 } def construct(self): # integral bounds x_min_1 = -0.0001 x_max_1 = 0.0001 x_min_2 = self.x_min x_max_2 = self.x_max self.setup_axes() self.remove(self.x_axis, self.y_axis) graph = self.get_graph(lambda x: np.exp(-x**2) * 2.0 / TAU ** 0.5) area = self.area = self.get_area(graph, x_min_1, x_max_1) pdf_formula = OldTex("p(x) = {1\over \sigma\sqrt{2\pi}}e^{-{1\over 2}({x\over\sigma})^2}") pdf_formula.set_color(graph.color) cdf_formula = OldTex("P(|X| < ", "a", ") = \int", "_{-a}", "^a", "p(x) dx") cdf_formula.set_color_by_tex("a", YELLOW) cdf_formula.next_to(graph, LEFT, buff = 2) pdf_formula.next_to(cdf_formula, UP) formulas = VGroup(pdf_formula, cdf_formula) self.play(Write(pdf_formula)) self.play(Write(cdf_formula)) self.wait() self.play(ShowCreation(self.x_axis)) self.play(ShowCreation(graph)) self.play(FadeIn(area)) self.v_graph = graph self.add_T_label( x_min_1, label = "-a", side = LEFT, color = YELLOW, animated = False ) self.add_T_label( x_max_1, label = "a", side = RIGHT, color = YELLOW, animated = False ) # don't show the labels just yet self.remove( self.left_T_label_group[0], self.right_T_label_group[0], ) def integral_update_func(t): return scipy.special.erf( self.point_to_coords(self.right_v_line.get_center())[0] ) def integral_update_func_percent(t): return 100 * integral_update_func(t) equals_sign = OldTex("=").next_to(cdf_formula, buff = MED_LARGE_BUFF) cdf_value = DecimalNumber(0, color = graph.color, num_decimal_places = 3) cdf_value.next_to(equals_sign) self.play( FadeIn(equals_sign), FadeIn(cdf_value) ) self.add_foreground_mobject(cdf_value) cdf_percentage = DecimalNumber(0, unit = "\\%") cdf_percentage.move_to(self.coords_to_point(0,0.2)) self.add_foreground_mobject(cdf_percentage) cdf_value.add_updater( lambda m: m.set_value(integral_update_func()) ) anim = self.get_animation_integral_bounds_change( graph, x_min_2, x_max_2, run_time = 3) self.play( anim ) rect = SurroundingRectangle(formulas, buff = 0.5 * MED_LARGE_BUFF) self.play(ShowCreation(rect))
from manim_imports_ext import * from _2018.eop.reusable_imports import * class GenericMorphBrickRowIntoHistogram(Scene): CONFIG = { "level" : 3, "bar_width" : 2.0, "bar_anchor_height" : -3.0, "show_tallies" : False, "show_nb_flips" : True } def construct(self): self.row = BrickRow(self.level, height = self.bar_width, width = 10) self.bars = OutlineableBars(*[self.row.rects[i] for i in range(self.level + 1)]) self.bar_anchors = [self.bar_anchor_height * UP + self.row.height * (i - 0.5 * self.level) * RIGHT for i in range(self.level + 1)] self.add(self.row) if self.show_tallies: tallies = VMobject() for (i,brick) in enumerate(self.row.rects): tally = TallyStack(self.level - i, i) tally.move_to(brick) self.add(tally) tallies.add(tally) brick.set_stroke(width = 3) if self.show_nb_flips: nb_flips_text = OldTexText("\# of flips: " + str(self.level)) nb_flips_text.to_corner(UR) self.add(nb_flips_text) self.remove(self.row.subdivs, self.row.border) for rect in self.row.rects: rect.set_stroke(color = WHITE, width = 3) self.wait() self.play( self.row.rects.space_out_submobjects, {"factor" : 1.3}, FadeOut(tallies) ) self.wait() anims = [] for brick in self.row.rects: anims.append(brick.rotate) anims.append(TAU/4) self.play(*anims) self.wait() anims = [] for (i,brick) in enumerate(self.row.rects): anims.append(brick.next_to) anims.append(self.bar_anchors[i]) anims.append({"direction" : UP, "buff" : 0}) self.play(*anims) self.wait() self.bars.create_outline() anims = [ ApplyMethod(rect.set_stroke, {"width" : 0}) for rect in self.bars ] anims.append(FadeIn(self.bars.outline)) self.play(*anims) self.wait() class MorphBrickRowIntoHistogram3(GenericMorphBrickRowIntoHistogram): CONFIG = { "level" : 3, "prob_denominator" : 8, "bar_width" : 2.0, "bar_anchor_height" : -3.0, "show_tallies" : True, "show_nb_flips" : False } def construct(self): super(MorphBrickRowIntoHistogram3,self).construct() # draw x-axis x_axis = Line(ORIGIN, 10 * RIGHT, color = WHITE, buff = 0) x_axis.next_to(self.bars, DOWN, buff = 0) #x_labels = VMobject(*[Tex(str(i)) for i in range(4)]) x_labels = VMobject() for (i, bar) in enumerate(self.bars): label = Integer(i) label.next_to(self.bar_anchors[i], DOWN) x_labels.add(label) nb_tails_label = OldTexText("\# of tails") nb_tails_label.next_to(x_labels[-1], RIGHT, MED_LARGE_BUFF) # draw y-guides y_guides = VMobject() for i in range(0,self.prob_denominator + 1): y_guide = Line(5 * LEFT, 5 * RIGHT, stroke_color = GREY) y_guide.move_to(self.bar_anchor_height * UP + i * float(self.row.width) / self.prob_denominator * UP) y_guide_label = OldTex("{" + str(i) + "\over " + str(self.prob_denominator) + "}", color = GREY) y_guide_label.scale(0.7) y_guide_label.next_to(y_guide, LEFT) if i != 0: y_guide.add(y_guide_label) y_guides.add(y_guide) self.wait() self.play( FadeIn(y_guides), Animation(self.bars.outline), Animation(self.bars) ) self.wait() self.play( FadeIn(x_axis), FadeIn(x_labels), FadeIn(nb_tails_label) ) self.add_foreground_mobject(nb_tails_label) area_color = YELLOW total_area_text = OldTexText("total area =", color = area_color) area_decimal = DecimalNumber(0, color = area_color, num_decimal_places = 3) area_decimal.next_to(total_area_text, RIGHT) total_area_group = VGroup(total_area_text, area_decimal) total_area_group.move_to(2.7 * UP) self.wait() self.play( FadeIn(total_area_text), ) self.wait() cumulative_areas = [0.125, 0.5, 0.875, 1] covering_rects = self.bars.copy() for (i,rect) in enumerate(covering_rects): rect.set_fill(color = area_color, opacity = 0.5) self.play( FadeIn(rect, rate_func = linear), ChangeDecimalToValue(area_decimal, cumulative_areas[i], rate_func = linear) ) self.wait(0.2) self.wait() total_area_rect = SurroundingRectangle( total_area_group, buff = MED_SMALL_BUFF, stroke_color = area_color ) self.play( FadeOut(covering_rects), ShowCreation(total_area_rect) ) self.wait() class MorphBrickRowIntoHistogram20(GenericMorphBrickRowIntoHistogram): CONFIG = { "level" : 20, "prob_ticks" : 0.05, "bar_width" : 0.5, "bar_anchor_height" : -3.0, "x_ticks": 5 } def construct(self): super(MorphBrickRowIntoHistogram20, self).construct() x_axis = Line(ORIGIN, 10 * RIGHT, color = WHITE, buff = 0) x_axis.next_to(self.bars, DOWN, buff = 0) #x_labels = VMobject(*[Tex(str(i)) for i in range(4)]) x_labels = VMobject() for (i, bar) in enumerate(self.bars): if i % self.x_ticks != 0: continue label = Integer(i) label.next_to(self.bar_anchors[i], DOWN) x_labels.add(label) nb_tails_label = OldTexText("\# of tails") nb_tails_label.move_to(5 * RIGHT + 2.5 * DOWN) self.wait() self.play( FadeIn(x_axis), FadeIn(x_labels), FadeIn(nb_tails_label) ) self.wait() # draw y-guides max_prob = float(choose(self.level, self.level/2)) / 2 ** self.level y_guides = VMobject() y_guide_heights = [] prob_grid = np.arange(self.prob_ticks, 1.3 * max_prob, self.prob_ticks) for i in prob_grid: y_guide = Line(5 * LEFT, 5 * RIGHT, stroke_color = GREY) y_guide_height = self.bar_anchor_height + i * float(self.row.width) y_guide_heights.append(y_guide_height) y_guide.move_to(y_guide_height * UP) y_guide_label = DecimalNumber(i, num_decimal_places = 2, color = GREY) y_guide_label.scale(0.7) y_guide_label.next_to(y_guide, LEFT) y_guide.add(y_guide_label) y_guides.add(y_guide) self.bring_to_back(y_guides) self.play(FadeIn(y_guides), Animation(self.bars)) self.wait() histogram_width = self.bars.get_width() histogram_height = self.bars.get_height() # scale to fit screen self.scale_x = 10.0/((len(self.bars) - 1) * self.bar_width) self.scale_y = 6.0/histogram_height anims = [] for (bar, x_label) in zip(self.bars, x_labels): v = (self.scale_x - 1) * x_label.get_center()[0] * RIGHT anims.append(x_label.shift) anims.append(v) anims.append(self.bars.stretch_about_point) anims.append(self.scale_x) anims.append(0) anims.append(ORIGIN) anims.append(self.bars.outline.stretch_about_point) anims.append(self.scale_x) anims.append(0) anims.append(ORIGIN) self.play(*anims) self.wait() anims = [] for (guide, i, h) in zip(y_guides, prob_grid, y_guide_heights): new_y_guide_height = self.bar_anchor_height + i * self.scale_y * float(self.row.width) v = (new_y_guide_height - h) * UP anims.append(guide.shift) anims.append(v) anims.append(self.bars.stretch_about_point) anims.append(self.scale_y) anims.append(1) anims.append(self.bars.get_bottom()) anims.append(self.bars.outline.stretch_about_point) anims.append(self.scale_y) anims.append(1) anims.append(self.bars.get_bottom()) self.play(*anims) self.wait() class MorphBrickRowIntoHistogram100(MorphBrickRowIntoHistogram20): CONFIG = { "level" : 100, "x_ticks": 20, "prob_ticks": 0.02 } class MorphBrickRowIntoHistogram500(MorphBrickRowIntoHistogram20): CONFIG = { "level" : 500, "x_ticks": 100, "prob_ticks": 0.01 }
from manim_imports_ext import * from _2018.eop.reusable_imports import * class ShowUncertaintyDarts(Scene): def throw_darts(self, n, run_time = 1): points = np.random.normal( loc = self.dartboard.get_center(), scale = 0.6 * np.ones(3), size = (n,3) ) points[:,2] = 0 dots = VGroup() for point in points: dot = Dot(point, radius = 0.04, fill_opacity = 0.7) dots.add(dot) self.add(dot) self.play( LaggedStartMap(FadeIn, dots, lag_ratio = 0.01, run_time = run_time) ) def construct(self): self.dartboard = ImageMobject("dartboard").scale(2) dartboard_circle = Circle( radius = self.dartboard.get_width() / 2, fill_color = BLACK, fill_opacity = 0.5, stroke_color = WHITE, stroke_width = 5 ) self.dartboard.add(dartboard_circle) self.add(self.dartboard) self.throw_darts(5,5) self.throw_darts(20,5) self.throw_darts(100,5) self.throw_darts(1000,5)
from manim_imports_ext import * from _2018.eop.reusable_imports import * class JustFlipping(Scene): def construct(self): randy = CoinFlippingPiCreature(color = MAROON_E, flip_height = 1).shift(2 * DOWN) self.add(randy) self.wait(2) for i in range(10): self.wait() self.play(FlipCoin(randy)) class JustFlippingWithResults(Scene): def construct(self): randy = CoinFlippingPiCreature(color = MAROON_E, flip_height = 1).shift(2 * DOWN) self.add(randy) self.wait(2) for i in range(10): self.wait() self.play(FlipCoin(randy)) result = random.choice(["H", "T"]) if result == "H": coin = UprightHeads().scale(3) else: coin = UprightTails().scale(3) coin.move_to(2 * UP + 2.5 * LEFT + i * 0.6 * RIGHT) self.play(FadeIn(coin))
from manim_imports_ext import * class ProbabilityRect(VMobject): CONFIG = { "unit_width" : 2, "unit_height" : 2, "alignment" : LEFT, "color": YELLOW, "opacity": 1.0, "num_decimal_places": 2, "use_percent" : False } def __init__(self, p0, **kwargs): VMobject.__init__(self, **kwargs) self.unit_rect = Rectangle( width = self.unit_width, height = self.unit_height, stroke_color = self.color ) self.p = p0 self.prob_rect = self.create_prob_rect(p0) self.prob_label = self.create_prob_label(p0) self.add(self.unit_rect, self.prob_rect, self.prob_label) def create_prob_rect(self, p): prob_width, prob_height = self.unit_width, self.unit_height if self.alignment in [LEFT, RIGHT]: prob_width *= p elif self.alignment in [UP, DOWN]: prob_height *= p else: raise Exception("Aligment must be LEFT, RIGHT, UP or DOWN") prob_rect = Rectangle( width = prob_width, height = prob_height, fill_color = self.color, fill_opacity = self.opacity, stroke_color = self.color ) prob_rect.align_to(self.unit_rect, direction = self.alignment) return prob_rect def create_prob_label(self, p): if self.use_percent: prob_label = DecimalNumber( p * 100, color = BLACK, num_decimal_places = self.num_decimal_places, unit = "\%" ) else: prob_label = DecimalNumber( p, color = BLACK, num_decimal_places = self.num_decimal_places, ) prob_label.move_to(self.prob_rect) return prob_label class ChangeProbability(Animation): def __init__(self, prob_mob, p1, **kwargs): if not isinstance(prob_mob, ProbabilityRect): raise Exception("ChangeProportion's mobject must be a ProbabilityRect") self.p1 = p1 self.p0 = prob_mob.p Animation.__init__(self, prob_mob, **kwargs) def interpolate_mobject(self, alpha): p = (1 - alpha) * self.p0 + alpha * self.p1 self.mobject.remove(self.mobject.prob_rect, self.mobject.prob_label) self.mobject.prob_rect = self.mobject.create_prob_rect(p) self.mobject.prob_label = self.mobject.create_prob_label(p) self.mobject.add(self.mobject.prob_rect, self.mobject.prob_label) def clean_up_from_scene(self, scene=None): self.mobject.p = self.p1 super(ChangeProbability, self).clean_up_from_scene(scene = scene) class ShowProbAsProportion(Scene): def construct(self): p0 = 0.3 p1 = 1 p2 = 0.18 p3 = 0.64 prob_mob = ProbabilityRect(p0, unit_width = 4, unit_height = 2, use_percent = False, num_decimal_places = 2 ) self.add(prob_mob) self.wait() self.play( ChangeProbability(prob_mob, p1, run_time = 3) ) self.wait(0.5) self.play( ChangeProbability(prob_mob, p2, run_time = 3) ) self.wait(0.5) self.play( ChangeProbability(prob_mob, p3, run_time = 3) )
from manim_imports_ext import * from _2018.eop.reusable_imports import * class BrickRowScene(PiCreatureScene): def split_tallies(self, row, direction = DOWN): # Split all tally symbols at once and move the copies # either horizontally on top of the brick row # or diagonally into the bricks self.tallies_copy = self.tallies.copy() self.add_foreground_mobject(self.tallies_copy) tally_targets_left = [ rect.get_center() + 0.25 * rect.get_width() * LEFT for rect in row.rects ] tally_targets_right = [ rect.get_center() + 0.25 * rect.get_width() * RIGHT for rect in row.rects ] if np.all(direction == LEFT) or np.all(direction == RIGHT): tally_y_pos = self.tallies[0].anchor[1] for target in tally_targets_left: target[1] = tally_y_pos for target in tally_targets_right: target[1] = tally_y_pos for (i, tally) in enumerate(self.tallies): target_left = tally_targets_left[i] new_tally_left = TallyStack(tally.nb_heads + 1, tally.nb_tails) new_tally_left.move_anchor_to(target_left) v = target_left - tally.anchor self.play( tally.move_anchor_to, target_left, ) tally.anchor = target_left self.play(Transform(tally, new_tally_left)) tally_copy = self.tallies_copy[i] target_right = tally_targets_right[i] new_tally_right = TallyStack(tally.nb_heads, tally.nb_tails + 1) new_tally_right.move_anchor_to(target_right) v = target_right - tally_copy.anchor self.play(tally_copy.move_anchor_to, target_right) tally_copy.anchor = target_right self.play(Transform(tally_copy, new_tally_right)) tally_copy.nb_heads = new_tally_right.nb_heads tally_copy.nb_tails = new_tally_right.nb_tails tally.nb_heads = new_tally_left.nb_heads tally.nb_tails = new_tally_left.nb_tails def tally_split_animations(self, row, direction = DOWN): # Just creates the animations and returns them # Execution can be timed afterwards # Returns two lists: first all those going left, then those to the right self.tallies_copy = self.tallies.copy() self.add_foreground_mobject(self.tallies_copy) tally_targets_left = [ rect.get_center() + 0.25 * rect.get_width() * LEFT for rect in row.rects ] tally_targets_right = [ rect.get_center() + 0.25 * rect.get_width() * RIGHT for rect in row.rects ] if np.all(direction == LEFT) or np.all(direction == RIGHT): tally_y_pos = self.tallies[0].anchor[1] for target in tally_targets_left: target[1] = tally_y_pos for target in tally_targets_right: target[1] = tally_y_pos anims1 = [] for (i, tally) in enumerate(self.tallies): new_tally_left = TallyStack(tally.nb_heads + 1, tally.nb_tails) target_left = tally_targets_left[i] new_tally_left.move_to(target_left) anims1.append(Transform(tally, new_tally_left)) tally.anchor = target_left tally.nb_heads = new_tally_left.nb_heads tally.nb_tails = new_tally_left.nb_tails anims2 = [] for (i, tally) in enumerate(self.tallies_copy): new_tally_right = TallyStack(tally.nb_heads, tally.nb_tails + 1) target_right = tally_targets_right[i] new_tally_right.move_to(target_right) anims2.append(Transform(tally, new_tally_right)) tally.anchor = target_right tally.nb_heads = new_tally_right.nb_heads tally.nb_tails = new_tally_right.nb_tails return anims1, anims2 def split_tallies_at_once(self, row, direction = DOWN): anims1, anims2 = self.tally_split_animations(row, direction = direction) self.play(*(anims1 + anims2)) def split_tallies_in_two_steps(self, row, direction = DOWN): # First all those to the left, then those to the right anims1, anims2 = self.tally_split_animations(row, direction = direction) self.play(*anims1) self.wait(0.3) self.play(*anims2) def merge_rects_by_subdiv(self, row): half_merged_row = row.copy() half_merged_row.subdiv_level += 1 half_merged_row.init_points() half_merged_row.move_to(row) self.play(FadeIn(half_merged_row)) self.remove(row) return half_merged_row def merge_tallies(self, row, target_pos = UP): r = row.subdiv_level if np.all(target_pos == DOWN): tally_targets = [ rect.get_center() for rect in row.get_rects_for_level(r) ] elif np.all(target_pos == UP): y_pos = row.get_center()[1] + 1.2 * 0.5 * row.get_height() for target in tally_targets: target[1] = y_pos else: raise Exception("Invalid target position (either UP or DOWN)") anims = [] for (tally, target) in zip(self.tallies[1:], tally_targets[1:-1]): anims.append(tally.move_anchor_to) anims.append(target) for (tally, target) in zip(self.tallies_copy[:-1], tally_targets[1:-1]): anims.append(tally.move_anchor_to) anims.append(target) self.play(*anims) # update anchors for (tally, target) in zip(self.tallies[1:], tally_targets[1:-1]): tally.anchor = target for (tally, target) in zip(self.tallies_copy[:-1], tally_targets[1:-1]): tally.anchor = target self.remove(self.tallies_copy) self.tallies.add(self.tallies_copy[-1]) def merge_rects_by_coloring(self, row): merged_row = row.copy() merged_row.coloring_level += 1 merged_row.init_points() merged_row.move_to(row) self.play(FadeIn(merged_row)) self.remove(row) return merged_row def move_tallies_on_top(self, row): self.play( self.tallies.shift, 1.2 * 0.5 * row.height * UP ) for tally in self.tallies: tally.anchor += 1.2 * 0.5 * row.height * UP def create_pi_creature(self): randy = CoinFlippingPiCreature(color = MAROON_E) return randy def construct(self): self.force_skipping() randy = self.get_primary_pi_creature() randy = randy.scale(0.5).move_to(3*DOWN + 6*LEFT) #self.add(randy) self.row = BrickRow(0, height = 2, width = 10) self.wait() self.play(FadeIn(self.row)) self.wait() # move in all kinds of sequences coin_seqs = VGroup() for i in range(20): n = np.random.randint(1,10) seq = [np.random.choice(["H", "T"]) for j in range(n)] coin_seq = CoinSequence(seq).scale(1.5) loc = np.random.uniform(low = -10, high = 10) * RIGHT loc += np.random.uniform(low = -6, high = 6) * UP coin_seq.move_to(loc) coin_seq.target = coin_seq.copy().scale(0.3).move_to(0.4 * loc) coin_seq.target.fade(1) coin_seqs.add(coin_seq) self.play( LaggedStartMap( Succession, coin_seqs, lambda m: (FadeIn(m, run_time = 0.1), MoveToTarget(m)), run_time = 5, lag_ratio = 0.5 ) ) # # # # # # # # # FIRST FLIP # # # # # # # # # self.play(FlipCoin(randy)) self.play(SplitRectsInBrickWall(self.row)) self.row = self.merge_rects_by_subdiv(self.row) self.row = self.merge_rects_by_coloring(self.row) # # put tallies on top single_flip_labels = VGroup(UprightHeads(), UprightTails()) for (label, rect) in zip(single_flip_labels, self.row.rects): label.next_to(rect, UP) self.play(FadeIn(label)) self.wait() self.wait() # # # # # # # # # SECOND FLIP # # # # # # # # # self.play(FlipCoin(randy)) self.wait() self.play( SplitRectsInBrickWall(self.row) ) self.wait() # split sequences single_flip_labels_copy = single_flip_labels.copy() self.add(single_flip_labels_copy) v = self.row.get_outcome_centers_for_level(2)[0] - single_flip_labels[0].get_center() self.play( single_flip_labels.shift, v ) new_heads = VGroup(UprightHeads(), UprightHeads()) for i in range(2): new_heads[i].move_to(single_flip_labels[i]) new_heads[i].shift(COIN_SEQUENCE_SPACING * DOWN) self.play(FadeIn(new_heads)) v = self.row.get_outcome_centers_for_level(2)[-1] - single_flip_labels_copy[-1].get_center() self.play( single_flip_labels_copy.shift, v ) new_tails = VGroup(UprightTails(), UprightTails()) for i in range(2): new_tails[i].move_to(single_flip_labels_copy[i]) new_tails[i].shift(COIN_SEQUENCE_SPACING * DOWN) self.play(FadeIn(new_tails)) self.add_foreground_mobject(single_flip_labels) self.add_foreground_mobject(new_heads) self.add_foreground_mobject(single_flip_labels_copy) self.add_foreground_mobject(new_tails) # get individual outcomes outcomes = self.row.get_outcome_rects_for_level(2, with_labels = False, inset = True) grouped_outcomes = VGroup(outcomes[0], outcomes[1:3], outcomes[3]) decimal_tallies = VGroup() # introduce notion of tallies rects = self.row.get_rects_for_level(2) rect = rects[0] tally = DecimalTally(2,0) tally.next_to(rect, UP) decimal_tallies.add(tally) self.play( FadeIn(tally), FadeIn(grouped_outcomes[0]) ) self.wait() rect = rects[1] tally = DecimalTally(1,1) tally.next_to(rect, UP) decimal_tallies.add(tally) self.play( FadeIn(tally), FadeOut(grouped_outcomes[0]), FadeIn(grouped_outcomes[1]) ) self.wait() rect = rects[2] tally = DecimalTally(0,2) tally.next_to(rect, UP) decimal_tallies.add(tally) self.play( FadeIn(tally), FadeOut(grouped_outcomes[1]), FadeIn(grouped_outcomes[2]) ) self.wait() self.play( FadeOut(grouped_outcomes[2]) ) self.wait() self.wait() self.play( FadeOut(single_flip_labels), FadeOut(new_heads), FadeOut(single_flip_labels_copy), FadeOut(new_tails) ) self.wait() self.tallies = VGroup() for (i, rect) in enumerate(self.row.get_rects_for_level(2)): tally = TallyStack(2-i, i, show_decimals = False) tally.move_to(rect) self.tallies.add(tally) self.play(FadeIn(self.tallies)) self.wait() anims = [] for (decimal_tally, tally_stack) in zip(decimal_tallies, self.tallies): anims.append(ApplyFunction( tally_stack.position_decimal_tally, decimal_tally )) self.play(*anims) self.wait() # replace the original decimal tallies with # the ones that belong to the TallyStacks for (decimal_tally, tally_stack) in zip(decimal_tallies, self.tallies): self.remove(decimal_tally) tally_stack.position_decimal_tally(tally_stack.decimal_tally) tally_stack.add(tally_stack.decimal_tally) self.add_foreground_mobject(self.tallies) self.row = self.merge_rects_by_subdiv(self.row) self.wait() self.row = self.merge_rects_by_coloring(self.row) self.wait() # # # # # # # # # # # # # # CALLBACK TO SEQUENCES # # # # # # # # # # # # # # outcomes = self.row.get_outcome_rects_for_level(2, with_labels = True, inset = True) subdivs = self.row.get_sequence_subdivs_for_level(2) self.play( FadeIn(outcomes), FadeIn(subdivs), FadeOut(self.tallies) ) self.wait() rect_to_dice = self.row.get_outcome_rects_for_level(2, with_labels = False, inset = False)[1] N = 10 dice_width = rect_to_dice.get_width()/N dice_height = rect_to_dice.get_height()/N prototype_dice = Rectangle( width = dice_width, height = dice_height, stroke_width = 2, stroke_color = WHITE, fill_color = WHITE, fill_opacity = 0 ) prototype_dice.align_to(rect_to_dice, direction = UP) prototype_dice.align_to(rect_to_dice, direction = LEFT) all_dice = VGroup() for i in range(N): for j in range(N): dice_copy = prototype_dice.copy() dice_copy.shift(j * dice_width * RIGHT + i * dice_height * DOWN) all_dice.add(dice_copy) self.play( LaggedStartMap(FadeIn, all_dice), FadeOut(outcomes[1]) ) self.wait() table = Ellipse(width = 1.5, height = 1) table.set_fill(color = GREEN_E, opacity = 1) table.next_to(rect_to_dice, UP) self.add(table) coin1 = UprightHeads(radius = 0.1) coin2 = UprightTails(radius = 0.1) def get_random_point_in_ellipse(ellipse): width = ellipse.get_width() height = ellipse.get_height() x = y = 1 while x**2 + y**2 > 0.9: x = np.random.uniform(-1,1) y = np.random.uniform(-1,1) x *= width/2 y *= height/2 return ellipse.get_center() + x * RIGHT + y * UP for dice in all_dice: p1 = get_random_point_in_ellipse(table) p2 = get_random_point_in_ellipse(table) coin1.move_to(p1) coin2.move_to(p2) self.add(coin1, coin2) self.play( ApplyMethod(dice.set_fill, {"opacity" : 0.5}, rate_func = there_and_back, run_time = 0.05) ) self.wait() self.play( FadeOut(outcomes), FadeOut(subdivs), FadeOut(all_dice), FadeOut(table), FadeOut(coin1), FadeOut(coin2), FadeIn(self.tallies) ) self.wait() # # # # # # # # # THIRD FLIP # # # # # # # # # # move row up, leave a copy without tallies below new_row = self.row.copy() self.clear() self.add(randy, self.row, self.tallies) self.bring_to_back(new_row) self.play( self.row.shift, 2.5 * UP, self.tallies.shift, 2.5 * UP, ) old_row = self.row self.row = new_row self.play(FlipCoin(randy)) self.wait() self.play( SplitRectsInBrickWall(self.row) ) self.wait() self.split_tallies_in_two_steps(self.row) self.wait() self.add_foreground_mobject(self.tallies) self.add_foreground_mobject(self.tallies_copy) self.remove(new_row) new_row = self.row self.clear() self.add(randy, self.row, old_row) self.add_foreground_mobject(self.tallies) self.add_foreground_mobject(self.tallies_copy) self.play( self.row.fade, 0.7, old_row.fade, 0.7, FadeOut(self.tallies), FadeOut(self.tallies_copy), ) # # # # # # # # # # # # # # # # # # SHOW SPLITTING WITH OUTCOMES # # # # # # # # # # # # # # # # # # # # show individual outcomes # old_outcomes = old_row.get_outcome_rects_for_level(2, with_labels = True) # old_outcomes_copy = old_outcomes.copy() # new_outcomes = self.row.get_outcome_rects_for_level(3, with_labels = True) # self.play( # FadeIn(old_outcomes[0]), # FadeIn(old_outcomes_copy[0]), # ) # self.wait() # self.play( # Transform(old_outcomes_copy[0], new_outcomes[1]) # ) # self.wait() # self.play( # FadeIn(old_outcomes[1:3]), # FadeIn(old_outcomes_copy[1:3]), # ) # self.wait() # self.play( # Transform(old_outcomes_copy[1:3], new_outcomes[2:4]) # ) # self.wait() # self.row = self.merge_rects_by_subdiv(self.row) # self.wait() # self.play( # FadeOut(old_row), # FadeOut(old_outcomes[0:3]), # FadeOut(new_outcomes[1:4]), # self.row.fade,0, # FadeIn(self.tallies[1]), # FadeIn(self.tallies_copy[0]), # ) # # rest of the new row # self.play( # FadeIn(self.tallies[:1]), # FadeIn(self.tallies[2:]), # FadeIn(self.tallies_copy[1:]) # ) # self.wait() # self.merge_tallies(self.row, target_pos = DOWN) # self.add_foreground_mobject(self.tallies) # self.row = self.merge_rects_by_coloring(self.row) # self.wait() # # # # # # # # # # # # # # # # # SHOW SPLITTING WITH TALLIES # # # # # # # # # # # # # # # # # tally_left = TallyStack(2,0) tally_left.move_to(old_row.rects[0]) tally_right = TallyStack(1,1) tally_right.move_to(old_row.rects[1]) rect_left = old_row.rects[0].copy() rect_right = old_row.rects[1].copy() self.play( FadeIn(rect_left), FadeIn(rect_right), FadeIn(tally_left), FadeIn(tally_right) ) rect_left.target = rect_left.copy() rect_left.target.stretch(0.5,0) left_target_pos = self.row.get_outcome_centers_for_level(3)[1] left_v = left_target_pos - rect_left.get_center() rect_left.target.move_to(left_target_pos) rect_right.target = rect_right.copy() rect_right.target.stretch(0.5,0) right_target_pos = 0.5 * (self.row.get_outcome_centers_for_level(3)[2] + self.row.get_outcome_centers_for_level(3)[3]) right_v = right_target_pos - rect_right.get_center() rect_right.target.move_to(right_target_pos) self.play( MoveToTarget(rect_left), tally_left.move_to, left_target_pos ) #tally_left.anchor += left_v self.wait() new_tally_left = TallyStack(2,1) #new_tally_left.move_anchor_to(tally_left.anchor) new_tally_left.move_to(tally_left) self.play( Transform(tally_left, new_tally_left) ) self.play( MoveToTarget(rect_right), tally_right.move_to, right_target_pos ) #tally_right.anchor += right_v self.wait() new_tally_right = TallyStack(2,1) #new_tally_right.move_anchor_to(tally_right.anchor) new_tally_right.move_to(tally_right) self.play( Transform(tally_right, new_tally_right) ) self.wait() self.row = self.merge_rects_by_subdiv(self.row) self.wait() self.play( FadeOut(old_row), self.row.fade,0, FadeOut(new_tally_left), FadeOut(new_tally_right), FadeIn(self.tallies[1]), FadeIn(self.tallies_copy[0]), ) # rest of the new row self.play( FadeIn(self.tallies[:1]), FadeIn(self.tallies[2:]), FadeIn(self.tallies_copy[1:]) ) self.wait() self.merge_tallies(self.row, target_pos = DOWN) self.add_foreground_mobject(self.tallies) self.row = self.merge_rects_by_coloring(self.row) self.wait() # show the 8 individual outcomes outcomes = self.row.get_outcome_rects_for_level(3, with_labels = True, inset = True) self.play(FadeOut(self.tallies)) self.wait() self.play(LaggedStartMap( FadeIn, outcomes, #rate_func = there_and_back_with_pause, run_time = 5)) self.wait() braces = VGroup(*[Brace(rect, UP) for rect in self.row.rects]) counts = [choose(3, i) for i in range(4)] probs = VGroup(*[Tex("{" + str(k) + "\over 8}") for k in counts]) for (brace, prob) in zip(braces, probs): prob.next_to(brace, UP) self.play( LaggedStartMap(ShowCreation, braces), LaggedStartMap(Write, probs) ) self.wait() self.play(LaggedStartMap( FadeOut, outcomes, #rate_func = there_and_back_with_pause, run_time = 5), ) self.play( FadeIn(self.tallies) ) self.wait() self.play( FadeOut(braces), FadeOut(probs) ) self.wait() # put visuals for other probability distribtuions here # back to three coin flips, show all 8 outcomes run_time = 5 self.play( LaggedStartMap(FadeIn, outcomes, #rate_func = there_and_back_with_pause, run_time = run_time), FadeOut(self.tallies, run_time = run_time) ) self.wait() self.play( LaggedStartMap(FadeOut, outcomes, #rate_func = there_and_back_with_pause, run_time = 5), FadeIn(self.tallies, run_time = run_time) ) # # # # # # # # # FOURTH FLIP # # # # # # # # # previous_row = self.row.copy() self.add(previous_row) v = 1.25 * self.row.height * UP self.play( previous_row.shift, v, self.tallies.shift, v, ) self.add_foreground_mobject(self.tallies) self.play( SplitRectsInBrickWall(self.row) ) self.wait() self.row = self.merge_rects_by_subdiv(self.row) self.revert_to_original_skipping_status() self.wait() n = 3 # level to split k = 1 # tally to split # show individual outcomes outcomes = previous_row.get_outcome_rects_for_level(n, with_labels = False, inset = True ) grouped_outcomes = VGroup() index = 0 for i in range(n + 1): size = choose(n,i) grouped_outcomes.add(VGroup(outcomes[index:index + size])) index += size grouped_outcomes_copy = grouped_outcomes.copy() original_grouped_outcomes = grouped_outcomes.copy() # for later reference self.play( LaggedStartMap(FadeIn, grouped_outcomes), LaggedStartMap(FadeIn, grouped_outcomes_copy), ) self.wait() # show how the outcomes in one tally split into two copies # going into the neighboring tallies #self.revert_to_original_skipping_status() target_outcomes = self.row.get_outcome_rects_for_level(n + 1, with_labels = False, inset = True ) grouped_target_outcomes = VGroup() index = 0 old_tally_sizes = [choose(n,i) for i in range(n + 1)] new_tally_sizes = [choose(n + 1,i) for i in range(n + 2)] for i in range(n + 2): size = new_tally_sizes[i] grouped_target_outcomes.add(VGroup(target_outcomes[index:index + size])) index += size old_tally_sizes.append(0) # makes the edge cases work properly # split all tallies for i in range(n + 1): self.play( Transform(grouped_outcomes[i][0], grouped_target_outcomes[i][0][old_tally_sizes[i - 1]:] ), Transform(grouped_outcomes_copy[i][0], grouped_target_outcomes[i + 1][0][:old_tally_sizes[i]] ) ) return self.wait() # fade in new tallies new_rects = self.row.get_rects_for_level(4) new_tallies = VGroup(*[ TallyStack(n + 1 - i, i).move_to(rect) for (i, rect) in enumerate(new_rects) ]) self.play(FadeIn(new_tallies)) self.add_foreground_mobject(new_tallies[1]) # remove outcomes and sizes except for one tally anims = [] for i in range(n + 1): if i != k - 1: anims.append(FadeOut(grouped_outcomes_copy[i])) if i != k: anims.append(FadeOut(grouped_outcomes[i])) anims.append(FadeOut(new_tallies[i])) #anims.append(FadeOut(self.tallies[0])) #anims.append(FadeOut(self.tallies[2:])) anims.append(FadeOut(new_tallies[-1])) self.play(*anims) self.wait() self.play( Transform(grouped_outcomes_copy[k - 1], original_grouped_outcomes[k - 1]) ) self.play( Transform(grouped_outcomes[k], original_grouped_outcomes[k]) ) new_rects = self.row.get_rects_for_level(n + 1) self.play( Transform(grouped_outcomes[k][0],grouped_target_outcomes[k][0][old_tally_sizes[k - 1]:]), Transform(grouped_outcomes_copy[k - 1][0],grouped_target_outcomes[k][0][:old_tally_sizes[k - 1]]), ) self.play( FadeOut(previous_row), FadeOut(self.tallies), ) self.row = self.merge_rects_by_coloring(self.row) self.play( FadeIn(new_tallies[0]), FadeIn(new_tallies[2:]), ) # # # # # # # # # # # EVEN MORE FLIPS # # # # # # # # # # # self.play(FadeOut(new_tallies)) self.clear() self.row = BrickRow(3) self.add(randy, self.row) for i in range(3): self.play(FlipCoin(randy)) self.wait() previous_row = self.row.copy() self.play(previous_row.shift, 1.25 * self.row.height * UP) self.play( SplitRectsInBrickWall(self.row) ) self.wait() self.row = self.merge_rects_by_subdiv(self.row) self.wait() self.row = self.merge_rects_by_coloring(self.row) self.wait() self.play(FadeOut(previous_row)) class ShowProbsInBrickRow3(BrickRowScene): def construct(self): randy = self.get_primary_pi_creature() randy = randy.scale(0.5).move_to(3*DOWN + 6*LEFT) #self.add(randy) self.row = BrickRow(3, height = 2, width = 10) self.wait() self.add(self.row) tallies = VGroup() for (i, rect) in enumerate(self.row.get_rects_for_level(3)): tally = TallyStack(3-i, i, show_decimals = False) tally.move_to(rect) tallies.add(tally) self.add(tallies) self.wait(6) braces = VGroup(*[Brace(rect, UP) for rect in self.row.rects]) counts = [choose(3, i) for i in range(4)] probs = VGroup(*[Tex("{" + str(k) + "\over 8}") for k in counts]) for (brace, prob) in zip(braces, probs): prob.next_to(brace, UP) self.wait() self.play( LaggedStartMap(ShowCreation, braces, run_time = 3), LaggedStartMap(Write, probs, run_time = 3) ) self.wait() self.play(FadeOut(braces),FadeOut(probs)) class ShowOutcomesInBrickRow4(BrickRowScene): def construct(self): randy = self.get_primary_pi_creature() randy = randy.scale(0.5).move_to(3*DOWN + 6*LEFT) #self.add(randy) self.row = BrickRow(3, height = 2, width = 10) previous_row = self.row.copy() v = 1.25 * self.row.height * UP self.play( previous_row.shift, v, ) self.add(self.row) self.add(previous_row) self.wait() previous_outcomes = previous_row.get_outcome_rects_for_level(3, with_labels = True, inset = True) previous_outcomes_copy = previous_outcomes.copy() self.play( LaggedStartMap(FadeIn, previous_outcomes), LaggedStartMap(FadeIn, previous_outcomes_copy), ) self.wait() new_outcomes = self.row.get_outcome_rects_for_level(4, with_labels = True, inset = True) # remove each last coin new_outcomes_left = VGroup( new_outcomes[0], new_outcomes[2], new_outcomes[3], new_outcomes[4], new_outcomes[8], new_outcomes[9], new_outcomes[10], new_outcomes[14] ) new_outcomes_right = VGroup( new_outcomes[1], new_outcomes[5], new_outcomes[6], new_outcomes[7], new_outcomes[11], new_outcomes[12], new_outcomes[13], new_outcomes[15] ) heads_labels = VGroup(*[outcome.label[-1] for outcome in new_outcomes_left]) tails_labels = VGroup(*[outcome.label[-1] for outcome in new_outcomes_right]) heads_labels.save_state() tails_labels.save_state() for outcome in new_outcomes: outcome.label[-1].fade(1) run_time = 0.5 self.play(Transform(previous_outcomes[0], new_outcomes_left[0], run_time = run_time)) self.play(Transform(previous_outcomes[1:4], new_outcomes_left[1:4], run_time = run_time)) self.play(Transform(previous_outcomes[4:7], new_outcomes_left[4:7], run_time = run_time)) self.play(Transform(previous_outcomes[7], new_outcomes_left[7], run_time = run_time)) self.play(heads_labels.restore) self.play(Transform(previous_outcomes_copy[0], new_outcomes_right[0], run_time = run_time)) self.play(Transform(previous_outcomes_copy[1:4], new_outcomes_right[1:4], run_time = run_time)) self.play(Transform(previous_outcomes_copy[4:7], new_outcomes_right[4:7], run_time = run_time)) self.play(Transform(previous_outcomes_copy[7], new_outcomes_right[7], run_time = run_time)) self.play(tails_labels.restore) self.wait() anims = [FadeOut(previous_outcomes),FadeOut(previous_outcomes_copy)] for outcome in new_outcomes_left: anims.append(FadeOut(outcome.label[-1])) for outcome in new_outcomes_right: anims.append(FadeOut(outcome.label[-1])) self.play(*anims) self.wait() class SplitTalliesIntoBrickRow4(BrickRowScene): def construct(self): randy = self.get_primary_pi_creature() randy = randy.scale(0.5).move_to(3*DOWN + 6*LEFT) #self.add(randy) self.row = BrickRow(3, height = 2, width = 10) previous_row = self.row.copy() v = 1.25 * self.row.height * UP self.play( previous_row.shift, v, ) tallies = VGroup() for (i, rect) in enumerate(previous_row.get_rects_for_level(3)): tally = TallyStack(3-i, i, show_decimals = True) tally.move_to(rect) tallies.add(tally) moving_tallies_left = tallies.copy() moving_tallies_right = tallies.copy() self.add(self.row, previous_row) self.add_foreground_mobject(tallies) self.add_foreground_mobject(moving_tallies_left) self.add_foreground_mobject(moving_tallies_right) self.play(SplitRectsInBrickWall(self.row)) anims = [] for (tally, rect) in zip(moving_tallies_left, previous_row.rects): anims.append(tally.move_to) anims.append(rect.get_center() + rect.get_width() * 0.25 * LEFT) self.play(*anims) new_tallies_left = VGroup() for (i, tally) in enumerate(moving_tallies_left): new_tally = TallyStack(4-i,i, with_labels = True) new_tally.move_to(tally) new_tallies_left.add(new_tally) self.play(Transform(moving_tallies_left, new_tallies_left)) anims = [] for (tally, rect) in zip(moving_tallies_right, previous_row.rects): anims.append(tally.move_to) anims.append(rect.get_center() + rect.get_width() * 0.25 * RIGHT) self.play(*anims) new_tallies_right = VGroup() for (i, tally) in enumerate(moving_tallies_right): new_tally = TallyStack(3-i,i+1, with_labels = True) new_tally.move_to(tally) new_tallies_right.add(new_tally) self.play(Transform(moving_tallies_right, new_tallies_right)) hypothetical_new_row = BrickRow(4, height = 2, width = 10) anims = [] for (tally, rect) in zip(moving_tallies_left[1:], hypothetical_new_row.rects[1:-1]): anims.append(tally.move_to) anims.append(rect) for (tally, rect) in zip(moving_tallies_right[:-1], hypothetical_new_row.rects[1:-1]): anims.append(tally.move_to) anims.append(rect) self.play(*anims) self.wait() self.row = self.merge_rects_by_subdiv(self.row) self.wait() self.row = self.merge_rects_by_coloring(self.row) self.wait()
from manim_imports_ext import * class Introduction(TeacherStudentsScene): CONFIG = { "default_pi_creature_kwargs": { "color": MAROON_E, "flip_at_start": True, }, } def construct(self): self.show_series() self.show_examples() def show_series(self): series = VideoSeries(num_videos = 11) series.to_edge(UP) this_video = series[0] this_video.set_color(YELLOW) this_video.save_state() this_video.set_fill(opacity = 0) this_video.center() this_video.set_height(FRAME_HEIGHT) self.this_video = this_video words = OldTexText( "Welcome to \\\\", "Essence of Probability" ) words.set_color_by_tex("Essence of Probability", YELLOW) self.teacher.change_mode("happy") self.play( FadeIn( series, lag_ratio = 0.5, run_time = 2 ), Blink(self.get_teacher()) ) self.teacher_says(words, target_mode = "hooray") self.play_student_changes( *["hooray"]*3, look_at = series[1].get_left(), added_anims = [ ApplyMethod(this_video.restore, run_time = 3), ] ) self.play(*[ ApplyMethod( video.shift, 0.5*video.get_height()*DOWN, run_time = 3, rate_func = squish_rate_func( there_and_back, alpha, alpha+0.3 ) ) for video, alpha in zip(series, np.linspace(0, 0.7, len(series))) ]+[ Animation(self.teacher.bubble), Animation(self.teacher.bubble.content), ]) self.play( FadeOut(self.teacher.bubble), FadeOut(self.teacher.bubble.content), self.get_teacher().change_mode, "raise_right_hand", *[ ApplyMethod(pi.change_mode, "pondering") for pi in self.get_students() ] ) self.wait() self.series = series def show_examples(self): self.wait(10) # put examples here in video editor
from manim_imports_ext import * def print_permutation(index_list): n = max(max(index_list), len(index_list)) for i in range(0,n): if index_list[i] > n - i: raise Exception("Impossible indices!") #print "given index list:", index_list perm_list = n * ["_"] alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] free_indices = list(range(n)) free_indices_p1 = list(range(1,n + 1)) #print perm_list for i in range(n): findex = index_list[i] - 1 #print "place next letter at", findex + 1, "th free place" tindex = free_indices[findex] #print "so at position", tindex + 1 perm_list[tindex] = alphabet[i] free_indices.remove(tindex) free_indices_p1.remove(tindex + 1) #print "remaining free places:", free_indices_p1 #print perm_list return "".join(perm_list) class PermutationGrid(Scene): def text_box(self, str): box = OldTexText(str).scale(0.3) box.add(SurroundingRectangle(box, stroke_color = GREY_D)) return box def construct(self): N = 5 index_list = [] perm5_box = VGroup() for i in range(1, N + 1): index_list.append(i) perm4_box = VGroup() for j in range(1, N): index_list.append(j) perm3_box = VGroup() for k in range(1, N - 1): index_list.append(k) perm2_box = VGroup() for l in range(1, N - 2): index_list.append(l) index_list.append(1) perm_box = self.text_box(print_permutation(index_list)) if l > 1: perm_box.next_to(perm2_box[-1], DOWN, buff = 0) perm2_box.add(perm_box) index_list.pop() index_list.pop() if k > 1: perm2_box.next_to(perm3_box[-1], RIGHT, buff = 0.08) perm3_box.add(perm2_box) index_list.pop() perm3_box.add(SurroundingRectangle(perm3_box, buff = 0.12, stroke_color = GREY_B)) if j > 1: perm3_box.next_to(perm4_box[-1], DOWN, buff = 0) perm4_box.add(perm3_box) index_list.pop() if i > 1: perm4_box.next_to(perm5_box[-1], RIGHT, buff = 0.16) perm5_box.add(perm4_box) index_list.pop() perm5_box.move_to(ORIGIN) self.add(perm5_box)
from manim_imports_ext import * def get_factors(n): return filter( lambda k: (n % k) == 0, range(1, n) ) class AmicableNumbers(Scene): CONFIG = { "n1": 28, "n2": 284, "colors": [ BLUE_C, BLUE_B, BLUE_D, GREY_BROWN, GREEN_C, GREEN_B, GREEN_D, GREY, ] } def construct(self): self.show_n1() self.show_n1_factors() self.show_n1_factor_sum() self.show_n2_factors() self.show_n2_factor_sum() def show_n1(self): dots = VGroup(*[Dot() for x in range(self.n1)]) dots.set_color(BLUE) dots.set_sheen(0.2, UL) dots.arrange(RIGHT, buff=SMALL_BUFF) dots.set_width(FRAME_WIDTH - 1) rects = self.get_all_factor_rectangles(dots) rects.rotate(90 * DEGREES) rects.arrange(RIGHT, buff=MED_SMALL_BUFF, aligned_edge=DOWN) for rect in rects: rect.first_col.set_stroke(WHITE, 3) rects.set_height(FRAME_HEIGHT - 1) self.add(rects) def show_n1_factors(self): pass def show_n1_factor_sum(self): pass def show_n2_factors(self): pass def show_n2_factor_sum(self): pass # def show_factors(self, dot_group): pass def get_all_factor_rectangles(self, dot_group): n = len(dot_group) factors = get_factors(n) colors = it.cycle(self.colors) result = VGroup() for k, color in zip(factors, colors): group = dot_group.copy() group.set_color(color) group.arrange_in_grid(n_rows=k, buff=SMALL_BUFF) group.first_col = group[::(n // k)] result.add(group) return result
from manim_imports_ext import * class PrimePiEPttern(Scene): def construct(self): self.add(FullScreenFadeRectangle(fill_color=WHITE, fill_opacity=1)) tex0 = OldTex( "\\frac{1}{1^2}", "+" "\\frac{1}{2^2}", "+" "\\frac{1}{3^2}", "+" "\\frac{1}{4^2}", "+" "\\frac{1}{5^2}", "+" "\\frac{1}{6^2}", "+" # "\\frac{1}{7^2}", "+" # "\\frac{1}{8^2}", "+" # "\\frac{1}{9^2}", "+" # "\\frac{1}{10^2}", "+" # "\\frac{1}{11^2}", "+" # "\\frac{1}{12^2}", "+" "\\cdots", "=", "\\frac{\\pi^2}{6}", ) self.alter_tex(tex0) # self.add(tex0) tex1 = OldTex( "\\underbrace{\\frac{1}{1^2}}_{\\text{kill}}", "+", "\\underbrace{\\frac{1}{2^2}}_{\\text{keep}}", "+", "\\underbrace{\\frac{1}{3^2}}_{\\text{keep}}", "+", "\\underbrace{\\frac{1}{4^2}}_{\\times (1 / 2)}", "+", "\\underbrace{\\frac{1}{5^2}}_{\\text{keep}}", "+", "\\underbrace{\\frac{1}{6^2}}_{\\text{kill}}", "+", "\\underbrace{\\frac{1}{7^2}}_{\\text{keep}}", "+", "\\underbrace{\\frac{1}{8^2}}_{\\times (1 / 3)}", "+", "\\underbrace{\\frac{1}{9^2}}_{\\times (1 / 2)}", "+", "\\underbrace{\\frac{1}{10^2}}_{\\text{kill}}", "+", "\\underbrace{\\frac{1}{11^2}}_{\\text{keep}}", "+", "\\underbrace{\\frac{1}{12^2}}_{\\text{kill}}", "+", "\\cdots", # "=", # "\\frac{\\pi^2}{6}" ) self.alter_tex(tex1) tex1.set_color_by_tex("kill", RED) tex1.set_color_by_tex("keep", GREEN_E) tex1.set_color_by_tex("times", BLUE_D) self.add(tex1) return # tex1 = OldTex( # "\\underbrace{\\frac{1}{1}}_{\\text{kill}}", "+", # "\\underbrace{\\frac{-1}{3}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{1}{5}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{-1}{7}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{1}{9}}_{\\times (1 / 2)}", "+", # "\\underbrace{\\frac{-1}{11}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{1}{13}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{-1}{15}}_{\\text{kill}}", "+", # "\\underbrace{\\frac{1}{17}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{-1}{19}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{1}{21}}_{\\text{kill}}", "+", # "\\underbrace{\\frac{-1}{23}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{1}{25}}_{\\times (1 / 2)}", "+", # "\\underbrace{\\frac{-1}{27}}_{\\times (1 / 3)}", "+", # "\\cdots", # "=", # "\\frac{\\pi}{4}" # ) # self.alter_tex(tex1) # VGroup( # tex1[2 * 0], # tex1[2 * 7], # tex1[2 * 10], # ).set_color(RED) # VGroup( # tex1[2 * 1], # tex1[2 * 2], # tex1[2 * 3], # tex1[2 * 5], # tex1[2 * 6], # tex1[2 * 8], # tex1[2 * 9], # tex1[2 * 11], # ).set_color(GREEN_E) # VGroup( # tex1[2 * 4], # tex1[2 * 12], # tex1[2 * 13], # ).set_color(BLUE_D) # self.add(tex1) # tex2 = OldTex( # "\\frac{-1}{3}", "+", # "\\frac{1}{5}", "+", # "\\frac{-1}{7}", "+", # "\\frac{1}{2}", "\\cdot", "\\frac{1}{9}", "+", # "\\frac{-1}{11}", "+", # "\\frac{1}{13}", "+", # "\\frac{1}{17}", "+", # "\\frac{-1}{19}", "+", # "\\frac{-1}{23}", "+", # "\\frac{1}{2}", "\\cdot", "\\frac{1}{25}", "+", # "\\frac{1}{3}", "\\cdot", "\\frac{-1}{27}", "+", # "\\cdots", # ) # self.alter_tex(tex2) # VGroup( # tex2[2 * 0], # tex2[2 * 1], # tex2[2 * 2], # tex2[2 * 5], # tex2[2 * 6], # tex2[2 * 7], # tex2[2 * 8], # tex2[2 * 9], # ).set_color(GREEN_E) # VGroup( # tex2[2 * 3], # tex2[2 * 4], # tex2[2 * 10], # tex2[2 * 11], # tex2[2 * 12], # tex2[2 * 13], # ).set_color(BLUE_D) tex2 = OldTex( "\\frac{1}{2^2}", "+", "\\frac{1}{3^2}", "+", "\\frac{1}{2}", "\\cdot", "\\frac{1}{4^2}", "+", "\\frac{1}{5^2}", "+", "\\frac{1}{7^2}", "+", "\\frac{1}{3}", "\\cdot", "\\frac{1}{8^2}", "+", "\\frac{1}{2}", "\\cdot", "\\frac{1}{9^2}", "+", "\\frac{1}{11^2}", "+", "\\frac{1}{13^2}", "+", "\\frac{1}{4}", "\\cdot", "\\frac{1}{16^2}", "+", "\\cdots", ) self.alter_tex(tex2) VGroup( tex2[2 * 0], tex2[2 * 1], tex2[2 * 4], tex2[2 * 5], tex2[2 * 10], tex2[2 * 11], ).set_color(GREEN_E) VGroup( tex2[2 * 2], tex2[2 * 3], tex2[2 * 6], tex2[2 * 7], tex2[2 * 8], tex2[2 * 9], tex2[2 * 12], tex2[2 * 13], ).set_color(BLUE_D) self.add(tex2) exp = OldTex( "e^{\\left(", "0" * 30, "\\right)}", "= \\frac{\\pi^2}{6}" ) self.alter_tex(exp) exp[1].set_opacity(0) tex2.replace(exp[1], dim_to_match=0) self.add(exp, tex2) def alter_tex(self, tex): tex.set_color(BLACK) tex.set_stroke(BLACK, 0, background=True) tex.set_width(FRAME_WIDTH - 1)
from manim_imports_ext import * class PowersOfTwo(MovingCameraScene): def construct(self): R = 3 circle = Circle(radius=R) circle.set_stroke(BLUE, 2) n = 101 dots = VGroup() numbers = VGroup() points = [ rotate_vector(R * DOWN, k * TAU / n) for k in range(n) ] dots = VGroup(*[ Dot(point, radius=0.03, color=YELLOW) for point in points ]) numbers = VGroup(*[ Integer(k).scale(0.2).move_to((1.03) * point) for k, point in enumerate(points) ]) lines = VGroup(*[ Line(points[k], points[(2 * k) % n]) for k in range(n) ]) lines.set_stroke(RED, 2) arrows = VGroup(*[ Arrow( n1.get_bottom(), n2.get_bottom(), path_arc=90 * DEGREES, buff=0.02, max_tip_length_to_length_ratio=0.1, ) for n1, n2 in zip(numbers, numbers[::2]) ]) transforms = [ Transform( numbers[k].copy(), numbers[(2 * k) % n].copy(), ) for k in range(n) ] title = OldTex( "\\mathds{Z} / (101 \\mathds{Z})" ) title.scale(2) frame = self.camera_frame frame.save_state() self.add(circle, title) self.play( LaggedStart(*map(FadeInFromLarge, dots)), LaggedStart(*[ FadeIn(n, -normalize(n.get_center())) for n in numbers ]), run_time=2, ) self.play( frame.scale, 0.25, {"about_point": circle.get_bottom() + SMALL_BUFF * DOWN} ) n_examples = 6 for k in range(1, n_examples): self.play( ShowCreation(lines[k]), transforms[k], ShowCreation(arrows[k]) ) self.play( frame.restore, FadeOut(arrows[:n_examples]) ) self.play( LaggedStart(*map(ShowCreation, lines[n_examples:])), LaggedStart(*transforms[n_examples:]), FadeOut(title, rate_func=squish_rate_func(smooth, 0, 0.5)), run_time=10, lag_ratio=0.01, ) self.play( LaggedStart(*[ ShowCreationThenFadeOut(line.copy().set_stroke(PINK, 3)) for line in lines ]), run_time=3 ) self.wait(4) class Cardiod(Scene): def construct(self): r = 1 big_circle = Circle(color=BLUE, radius=r) big_circle.set_stroke(width=1) big_circle.rotate(-PI / 2) time_tracker = ValueTracker() get_time = time_tracker.get_value def get_lil_circle(): lil_circle = big_circle.copy() lil_circle.set_color(YELLOW) time = get_time() lil_circle.rotate(time) angle = 0.5 * time lil_circle.shift( rotate_vector(UP, angle) * 2 * r ) return lil_circle lil_circle = always_redraw(get_lil_circle) cardiod = ParametricCurve( lambda t: op.add( rotate_vector(UP, 0.5 * t) * (2 * r), -rotate_vector(UP, 1.0 * t) * r, ), t_min=0, t_max=(2 * TAU), ) cardiod.set_color(MAROON_B) dot = Dot(color=RED) dot.add_updater(lambda m: m.move_to(lil_circle.get_start())) self.add(big_circle, lil_circle, dot, cardiod) for color in [RED, PINK, MAROON_B]: self.play( ShowCreation(cardiod.copy().set_color(color)), time_tracker.increment_value, TAU * 2, rate_func=linear, run_time=6, )
from manim_imports_ext import * OUTPUT_DIRECTORY = "hyperdarts" BROWN_PAPER = "#958166" class HyperdartScene(MovingCameraScene): CONFIG = { "square_width": 6, "square_style": { "stroke_width": 2, "fill_color": BLUE, "fill_opacity": 0.5, }, "circle_style": { "fill_color": RED_E, "fill_opacity": 1, "stroke_width": 0, }, "circle_center_dot_radius": 0.025, "default_line_style": { "stroke_width": 2, "stroke_color": WHITE, }, "default_dot_config": { "fill_color": WHITE, "background_stroke_width": 1, "background_stroke_color": BLACK, "radius": 0.5 * DEFAULT_DOT_RADIUS, }, "dart_sound": "dart_low", "default_bullseye_shadow_opacity": 0.35, } def setup(self): MovingCameraScene.setup(self) self.square = self.get_square() self.circle = self.get_circle() self.circle_center_dot = self.get_circle_center_dot() self.add(self.square) self.add(self.circle) self.add(self.circle_center_dot) def get_square(self): return Square( side_length=self.square_width, **self.square_style ) def get_circle(self, square=None): square = square or self.square circle = Circle(**self.circle_style) circle.replace(square) return circle def get_circle_center_dot(self, circle=None): circle = circle or self.circle return Dot( circle.get_center(), radius=self.circle_center_dot_radius, fill_color=BLACK, ) def get_number_plane(self): square = self.square unit_size = square.get_width() / 2 plane = NumberPlane( axis_config={ "unit_size": unit_size, } ) plane.add_coordinates() plane.shift(square.get_center() - plane.c2p(0, 0)) return plane def get_random_points(self, n): square = self.square points = np.random.uniform(-1, 1, 3 * n).reshape((n, 3)) points[:, 0] *= square.get_width() / 2 points[:, 1] *= square.get_height() / 2 points[:, 2] = 0 points += square.get_center() return points def get_random_point(self): return self.get_random_points(1)[0] def get_dot(self, point): return Dot(point, **self.default_dot_config) # Hit transform rules def is_inside(self, point, circle=None): circle = circle or self.circle return get_norm(point - circle.get_center()) <= circle.get_width() / 2 def get_new_radius(self, point, circle=None): circle = circle or self.circle center = circle.get_center() radius = circle.get_width() / 2 p_dist = get_norm(point - center) return np.sqrt(radius**2 - p_dist**2) def get_hit_distance_line(self, point, circle=None): circle = circle or self.circle line = Line( circle.get_center(), point, **self.default_line_style ) return line def get_chord(self, point, circle=None): circle = circle or self.circle center = circle.get_center() p_angle = angle_of_vector(point - center) chord = Line(DOWN, UP) new_radius = self.get_new_radius(point, circle) chord.scale(new_radius) chord.rotate(p_angle) chord.move_to(point) chord.set_style(**self.default_line_style) return chord def get_radii_to_chord(self, chord, circle=None): circle = circle or self.circle center = circle.get_center() radii = VGroup(*[ DashedLine(center, point) for point in chord.get_start_and_end() ]) radii.set_style(**self.default_line_style) return radii def get_all_hit_lines(self, point, circle=None): h_line = self.get_hit_distance_line(point, circle) chord = self.get_chord(point, circle) # radii = self.get_radii_to_chord(chord, circle) elbow = Elbow(width=0.15) elbow.set_stroke(WHITE, 2) elbow.rotate(h_line.get_angle() - PI, about_point=ORIGIN) elbow.shift(point) return VGroup(h_line, chord, elbow) def get_dart(self, length=1.5): dart = SVGMobject(file_name="dart") dart.rotate(135 * DEGREES) dart.set_width(length) dart.rotate(45 * DEGREES, UP) dart.rotate(-10 * DEGREES) dart.set_fill(GREY) dart.set_sheen(2, UL) dart.set_stroke(BLACK, 0.5, background=True) dart.set_stroke(width=0) return dart # New circle def get_new_circle_from_point(self, point, circle=None): return self.get_new_circle( self.get_new_radius(point, circle), circle, ) def get_new_circle_from_chord(self, chord, circle=None): return self.get_new_circle( chord.get_length() / 2, circle, ) def get_new_circle(self, new_radius, circle=None): circle = circle or self.circle new_circle = self.get_circle() new_circle.set_width(2 * new_radius) new_circle.move_to(circle) return new_circle # Sound def add_dart_sound(self, time_offset=0, gain=-20, **kwargs): self.add_sound( self.dart_sound, time_offset=time_offset, gain=-20, **kwargs, ) # Animations def show_full_hit_process(self, point, pace="slow", with_dart=True): assert(pace in ["slow", "fast"]) to_fade = VGroup() if with_dart: dart, dot = self.show_hit_with_dart(point) to_fade.add(dart, dot) else: dot = self.show_hit(point) to_fade.add(dot) if pace == "slow": self.wait(0.5) # TODO, automatically act based on hit or miss? lines = self.show_geometry(point, pace) chord_and_shadow = self.show_circle_shrink(lines[1], pace=pace) to_fade.add_to_back(chord_and_shadow, lines) self.play( FadeOut(to_fade), run_time=(1 if pace == "slow" else 0.5) ) def show_hits_with_darts(self, points, run_time=0.5, added_anims=None): if added_anims is None: added_anims = [] darts = VGroup(*[ self.get_dart().move_to(point, DR) for point in points ]) dots = VGroup(*[ self.get_dot(point) for point in points ]) for dart in darts: dart.save_state() dart.set_x(-(FRAME_WIDTH + dart.get_width()) / 2) dart.rotate(20 * DEGREES) n_points = len(points) self.play( ShowIncreasingSubsets( dots, rate_func=squish_rate_func(linear, 0.5, 1), ), LaggedStart(*[ Restore( dart, path_arc=-20 * DEGREES, rate_func=linear, run_time=run_time, ) for dart in darts ], lag_ratio=(1 / n_points)), *added_anims, run_time=run_time ) for n in range(n_points): self.add_dart_sound( time_offset=(-n / (2 * n_points)) ) return darts, dots def show_hit_with_dart(self, point, run_time=0.25, **kwargs): darts, dots = self.show_hits_with_darts([point], run_time, **kwargs) return darts[0], dots[0] def show_hit(self, point, pace="slow", added_anims=None): assert(pace in ["slow", "fast"]) if added_anims is None: added_anims = [] dot = self.get_dot(point) if pace == "slow": self.play( FadeInFromLarge(dot, rate_func=rush_into), *added_anims, run_time=0.5, ) elif pace == "fast": self.add(dot) # self.add_dart_sound() return dot def show_geometry(self, point, pace="slow"): assert(pace in ["slow", "fast"]) lines = self.get_all_hit_lines(point, self.circle) h_line, chord, elbow = lines # Note, note animating radii anymore...does that mess anything up? if pace == "slow": self.play( ShowCreation(h_line), GrowFromCenter(chord), ) self.play(ShowCreation(elbow)) elif pace == "fast": self.play( ShowCreation(h_line), GrowFromCenter(chord), ShowCreation(elbow), run_time=0.5 ) # return VGroup(h_line, chord) return lines def show_circle_shrink(self, chord, pace="slow", shadow_opacity=None): circle = self.circle chord_copy = chord.copy() new_circle = self.get_new_circle_from_chord(chord) to_fade = VGroup(chord_copy) if shadow_opacity is None: shadow_opacity = self.default_bullseye_shadow_opacity if shadow_opacity > 0: shadow = circle.copy() shadow.set_opacity(shadow_opacity) to_fade.add_to_back(shadow) if circle in self.mobjects: index = self.mobjects.index(circle) self.mobjects.insert(index, shadow) else: self.add(shadow, self.circle_center_dot) outline = VGroup(*[ VMobject().pointwise_become_partial(new_circle, a, b) for (a, b) in [(0, 0.5), (0.5, 1)] ]) outline.rotate(chord.get_angle()) outline.set_fill(opacity=0) outline.set_stroke(YELLOW, 2) assert(pace in ["slow", "fast"]) if pace == "slow": self.play( chord_copy.move_to, circle.get_center(), circle.set_opacity, 0.5, ) self.play( Rotating( chord_copy, radians=PI, ), ShowCreation( outline, lag_ratio=0 ), run_time=1, rate_func=smooth, ) self.play( Transform(circle, new_circle), FadeOut(outline), ) elif pace == "fast": outline = new_circle.copy() outline.set_fill(opacity=0) outline.set_stroke(YELLOW, 2) outline.move_to(chord) outline.generate_target() outline.target.move_to(circle) self.play( chord_copy.move_to, circle, Transform(circle, new_circle), # MoveToTarget( # outline, # remover=True # ) ) # circle.become(new_circle) # circle.become(new_circle) # self.remove(new_circle) return to_fade def show_miss(self, point, with_dart=True): square = self.square miss = OldTexText("Miss!") miss.next_to(point, UP) to_fade = VGroup(miss) if with_dart: dart, dot = self.show_hit_with_dart(point) to_fade.add(dart, dot) else: dot = self.show_hit(point) to_fade.add(dot) self.play( ApplyMethod( square.set_color, YELLOW, rate_func=lambda t: (1 - t), ), GrowFromCenter(miss), run_time=0.25 ) return to_fade def show_game_over(self): game_over = OldTexText("GAME OVER") game_over.set_width(FRAME_WIDTH - 1) rect = FullScreenFadeRectangle(opacity=0.25) self.play( FadeIn(rect), FadeInFromLarge(game_over), ) return VGroup(rect, game_over) # Scenes to overlay on Numerphile class TableOfContents(Scene): def construct(self): rect = FullScreenFadeRectangle(opacity=0.75) self.add(rect) parts = VGroup( OldTexText("The game"), OldTexText("The puzzle"), OldTexText("The micropuzzles"), OldTexText("The answer"), ) parts.scale(1.5) parts.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) parts.to_edge(LEFT, buff=2) parts.set_opacity(0.5) self.add(parts) for part in parts: dot = Dot() dot.next_to(part, LEFT, SMALL_BUFF) dot.match_style(part) self.add(dot) last_part = VMobject() last_part.save_state() for part in parts: part.save_state() self.play( part.scale, 1.5, {"about_edge": LEFT}, part.set_opacity, 1, Restore(last_part) ) self.wait() last_part = part class ShowGiantBullseye(HyperdartScene): def construct(self): square = self.square circle = self.circle self.remove(square, circle) board = Dartboard() board.replace(circle) bullseye = board.bullseye bullseye_border = bullseye.copy() bullseye_border.set_fill(opacity=0) bullseye_border.set_stroke(YELLOW, 3) self.add(board) # Label label = OldTexText("``", "Bullseye", "''") label.scale(1.5) label.next_to(square, LEFT, aligned_edge=UP) label.set_color(RED) arrow = Arrow( label.get_bottom(), bullseye.get_corner(DR) ) self.play( FadeInFromDown(label[1]), ShowCreation(arrow), ) self.play( bullseye.match_width, board, ApplyMethod( arrow.scale, 0.4, {"about_point": arrow.get_start()} ), run_time=2, ) self.play(Write(label[::2])) self.wait() class ShowExampleHit(HyperdartScene): def construct(self): square = self.square circle = self.circle circle.set_fill(BROWN_PAPER, opacity=0.95) old_board = VGroup(square, circle) self.remove(square) board = Dartboard() board.replace(old_board) self.add(board, circle) # Show hit point = 0.75 * UP dart, dot = self.show_hit_with_dart(point) # Draw lines (with labels) lines = self.get_all_hit_lines(point) h_line, chord, elbow = lines h_label = OldTex("h") h_label.next_to(h_line, LEFT, SMALL_BUFF) chord_word = OldTexText("Chord") chord_word.next_to(chord.get_center(), UR, SMALL_BUFF) self.add(h_line, dot) self.play(ShowCreation(h_line)) self.play(Write(h_label)) self.wait() self.play( ShowCreation(chord), ShowCreation(elbow), Write(chord_word, run_time=1) ) self.wait() # Show shrinkage chord_copy = chord.copy() chord_copy.move_to(ORIGIN) new_circle = circle.copy() new_circle.set_fill(RED, 1) new_circle.match_width(chord_copy) new_circle.move_to(ORIGIN) new_diam_word = OldTexText("New diameter") new_diam_word.next_to(chord_copy, DOWN, SMALL_BUFF) outline = VGroup( Arc(start_angle=0, angle=PI), Arc(start_angle=PI, angle=PI), ) outline.set_stroke(YELLOW, 3) outline.set_fill(opacity=0) outline.replace(new_circle) self.play( circle.set_color, GREY_D, TransformFromCopy(chord, chord_copy), FadeIn(new_diam_word, UP) ) self.play( Rotate(chord_copy, PI), ShowCreation(outline, lag_ratio=0), ) self.play() # Show variable hit_point self.remove(lines) point_tracker = VectorizedPoint(point) self.remove(lines, *lines) lines = always_redraw( lambda: self.get_all_hit_lines(point_tracker.get_location()) ) dot.add_updater(lambda m: m.move_to(point_tracker)) dart.add_updater(lambda m: m.move_to(point_tracker, DR)) chord_copy.add_updater( lambda m: m.match_width(lines[1]).move_to(ORIGIN) ) new_circle.add_updater(lambda m: m.match_width(chord_copy).move_to(ORIGIN)) h_label.add_updater(lambda m: m.next_to(lines[0], LEFT, SMALL_BUFF)) chord_word.add_updater(lambda m: m.next_to(lines[1].get_center(), UR, SMALL_BUFF)) ndw_width = new_diam_word.get_width() new_diam_word.add_updater( lambda m: m.set_width( min(ndw_width, chord_copy.get_width()) ).next_to(chord_copy, DOWN, SMALL_BUFF) ) self.add(new_circle, chord_copy, lines, h_label, dart, dot, chord_word, new_diam_word) self.play( FadeOut(outline), FadeIn(new_circle) ) self.wait() self.play( point_tracker.shift, 2.1 * UP, run_time=9, rate_func=there_and_back_with_pause, ) class QuicklyAnimatedShrinking(HyperdartScene): def construct(self): # square = self.square # circle = self.circle for x in range(5): point = self.get_random_point() while not self.is_inside(point): point = self.get_random_point() self.show_full_hit_process(point, pace="fast") # self.show_game_over() class SimulateRealGame(HyperdartScene): CONFIG = { "circle_style": { # "fill_color": BROWN_PAPER, } } def construct(self): board = Dartboard() board.set_opacity(0.5) self.remove(self.square) self.square.set_opacity(0) self.add(board, self.circle) points = [ 0.5 * UP, 2.0 * UP, 1.9 * LEFT + 0.4 * DOWN, ] for point in points: self.show_full_hit_process(point) self.show_miss(1.8 * DL) self.show_game_over() class GameOver(HyperdartScene): def construct(self): self.clear() self.show_game_over() class SquareAroundTheDartBoard(HyperdartScene): def construct(self): square = self.square circle = self.circle VGroup(square, circle).to_edge(DOWN, MED_SMALL_BUFF) self.clear() board = Dartboard() board.replace(square) title = OldTexText("Square around the dart board") title.scale(1.5) title.next_to(square, UP, MED_LARGE_BUFF) self.add(board) self.play(FadeInFromDown(title)) self.add(square, board) self.play(DrawBorderThenFill(square, run_time=2)) self.wait() class ContrastDistributions(HyperdartScene): def construct(self): square = self.square circle = self.circle board = Dartboard() board.replace(circle) group = VGroup(square, circle, board) group.to_edge(LEFT) group.scale(0.8, about_edge=DOWN) group_copy = group.copy() square_copy, circle_copy, board_copy = group_copy group_copy.set_x(-group.get_center()[0]) v_line = DashedLine(FRAME_HEIGHT * UP / 2, FRAME_HEIGHT * DOWN / 2) left_label = OldTexText("Our distribution\\\\(uniform in the square)") left_label.match_x(group) left_label.to_edge(UP) right_label = OldTexText("More realistic distribution") right_label.match_x(group_copy) right_label.to_edge(UP) n_points = 2000 left_points = self.get_random_points(n_points) right_points = np.random.multivariate_normal( mean=board_copy.get_center(), cov=0.6 * np.identity(3), size=n_points ) left_dots, right_dots = [ VGroup(*[ Dot(p, radius=0.02) for p in points ]) for points in [left_points, right_points] ] left_rect = FullScreenFadeRectangle(opacity=0.75) left_rect.stretch(0.49, 0, about_edge=LEFT) right_rect = left_rect.copy() right_rect.to_edge(RIGHT, buff=0) self.add(group, board_copy) self.add(left_label, right_label) self.add(v_line) self.add(left_rect) self.play( LaggedStartMap(FadeInFromLarge, right_dots), run_time=5 ) self.wait() self.play( FadeOut(left_rect), FadeIn(right_rect), ) self.play( LaggedStartMap(FadeInFromLarge, left_dots), run_time=5 ) self.wait() class ChooseXThenYUniformly(Scene): def construct(self): # Setup unit_size = 3 axes = Axes( x_min=-1.25, x_max=1.25, y_min=-1.25, y_max=1.25, axis_config={ "tick_frequency": 0.25, "unit_size": unit_size, }, ) numbers = [-1, -0.5, 0.5, 1] num_config = { "num_decimal_places": 1, "background_stroke_width": 3, } axes.x_axis.add_numbers( *numbers, **num_config, ) axes.y_axis.add_numbers( *numbers, **num_config, direction=LEFT, ) circle = Circle(radius=unit_size) circle.set_stroke(WHITE, 0) circle.set_fill(RED, 0.7) square = Square() square.replace(circle) square.set_stroke(GREY_B, 1) square = DashedVMobject(square, num_dashes=101) self.add(square, circle) self.add(axes) # x and y stuff x_tracker = ValueTracker(-1) y_tracker = ValueTracker(-1) get_x = x_tracker.get_value get_y = y_tracker.get_value x_tip = ArrowTip(start_angle=PI / 2, color=BLUE) y_tip = ArrowTip(start_angle=0, color=YELLOW) for tip in [x_tip, y_tip]: tip.scale(0.5) x_tip.add_updater(lambda m: m.move_to(axes.c2p(get_x(), 0), UP)) y_tip.add_updater(lambda m: m.move_to(axes.c2p(0, get_y()), RIGHT)) x_eq = VGroup(OldTex("x = "), DecimalNumber(0)) x_eq.arrange(RIGHT, SMALL_BUFF) x_eq[1].match_y(x_eq[0][0][1]) x_eq[1].add_updater(lambda m: m.set_value(get_x())) x_eq.match_color(x_tip) y_eq = VGroup(OldTex("y = "), DecimalNumber(0)) y_eq.arrange(RIGHT, SMALL_BUFF) y_eq[1].match_y(y_eq[0][0][1]) y_eq[1].add_updater(lambda m: m.set_value(get_y())) y_eq.match_color(y_tip) eqs = VGroup(x_eq, y_eq) eqs.arrange(DOWN, buff=MED_LARGE_BUFF) eqs.to_edge(UR) self.add(x_tip) self.add(x_eq) # Choose x self.play( x_tracker.set_value, 1, run_time=2, ) self.play( x_tracker.set_value, np.random.random(), run_time=1, ) # Choose y self.play( FadeIn(y_tip), FadeIn(y_eq), ) self.play( y_tracker.set_value, 1, run_time=2, ) self.play( y_tracker.set_value, np.random.random(), run_time=1, ) point = axes.c2p(get_x(), get_y()) dot = Dot(point) x_line = DashedLine(axes.c2p(0, get_y()), point) y_line = DashedLine(axes.c2p(get_x(), 0), point) lines = VGroup(x_line, y_line) lines.set_stroke(WHITE, 2) self.play(*map(ShowCreation, lines)) self.play(DrawBorderThenFill(dot)) self.wait() points = [ axes.c2p(*np.random.uniform(-1, 1, size=2)) for n in range(2000) ] dots = VGroup(*[ Dot(point, radius=0.02) for point in points ]) self.play( LaggedStartMap(FadeInFromLarge, dots), run_time=3, ) self.wait() class ShowDistributionOfScores(Scene): CONFIG = { "axes_config": { "x_min": -1, "x_max": 10, "x_axis_config": { "unit_size": 1.2, "tick_frequency": 1, }, "y_min": 0, "y_max": 100, "y_axis_config": { "unit_size": 0.065, "tick_frequency": 10, "include_tip": False, }, }, "random_seed": 1, } def construct(self): # Add axes axes = self.get_axes() self.add(axes) # setup scores n_scores = 10000 scores = np.array([self.get_random_score() for x in range(n_scores)]) index_tracker = ValueTracker(n_scores) def get_index(): value = np.clip(index_tracker.get_value(), 0, n_scores - 1) return int(value) # Setup histogram bars = self.get_histogram_bars(axes) bars.add_updater( lambda b: self.set_histogram_bars( b, scores[:get_index()], axes ) ) self.add(bars) # Add score label score_label = VGroup( OldTexText("Last score: "), Integer(1) ) score_label.scale(1.5) score_label.arrange(RIGHT) score_label[1].align_to(score_label[0][0][-1], DOWN) score_label[1].add_updater( lambda m: m.set_value(scores[get_index() - 1]) ) score_label[1].add_updater( lambda m: m.set_fill(bars[scores[get_index() - 1]].get_fill_color()) ) n_trials_label = VGroup( OldTexText("\\# Games: "), Integer(0), ) n_trials_label.scale(1.5) n_trials_label.arrange(RIGHT, aligned_edge=UP) n_trials_label[1].add_updater( lambda m: m.set_value(get_index()) ) n_trials_label.to_corner(UR, buff=LARGE_BUFF) score_label.next_to( n_trials_label, DOWN, buff=LARGE_BUFF, aligned_edge=LEFT, ) self.add(score_label) self.add(n_trials_label) # Add curr_score_arrow curr_score_arrow = Arrow(0.25 * UP, ORIGIN, buff=0) curr_score_arrow.set_stroke(WHITE, 5) curr_score_arrow.add_updater( lambda m: m.next_to(bars[scores[get_index() - 1] - 1], UP, SMALL_BUFF) ) self.add(curr_score_arrow) # Add mean bar mean_line = DashedLine(ORIGIN, 4 * UP) mean_line.set_stroke(YELLOW, 2) def get_mean(): return np.mean(scores[:get_index()]) mean_line.add_updater( lambda m: m.move_to(axes.c2p(get_mean(), 0), DOWN) ) mean_label = VGroup( OldTexText("Mean = "), DecimalNumber(num_decimal_places=3), ) mean_label.arrange(RIGHT) mean_label.match_color(mean_line) mean_label.add_updater(lambda m: m.next_to(mean_line, UP, SMALL_BUFF)) mean_label[1].add_updater(lambda m: m.set_value(get_mean())) # Show many runs index_tracker.set_value(1) for value in [10, 100, 1000, 10000]: anims = [ ApplyMethod( index_tracker.set_value, value, rate_func=linear, run_time=5, ), ] if value == 10: anims.append( FadeIn( VGroup(mean_line, mean_label), rate_func=squish_rate_func(smooth, 0.5, 1), run_time=2, ), ) self.play(*anims) self.wait() # def get_axes(self): axes = Axes(**self.axes_config) axes.to_corner(DL) axes.x_axis.add_numbers(*range(1, 12)) axes.y_axis.add_numbers( *range(20, 120, 20), unit="\\%" ) x_label = OldTexText("Score") x_label.next_to(axes.x_axis.get_right(), UR, buff=0.5) x_label.shift_onto_screen() axes.x_axis.add(x_label) y_label = OldTexText("Relative proportion") y_label.next_to(axes.y_axis.get_top(), RIGHT, buff=0.75) y_label.to_edge(UP, buff=MED_SMALL_BUFF) axes.y_axis.add(y_label) return axes def get_histogram_bars(self, axes): bars = VGroup() for x in range(1, 10): bar = Rectangle(width=axes.x_axis.unit_size) bar.move_to(axes.c2p(x, 0), DOWN) bar.x = x bars.add(bar) bars.set_fill(opacity=0.7) bars.set_color_by_gradient(BLUE, YELLOW, RED) bars.set_stroke(WHITE, 1) return bars def get_relative_proportion_map(self, all_scores): scores = set(all_scores) n_scores = len(all_scores) return dict([ (s, np.sum(all_scores == s) / n_scores) for s in set(scores) ]) def set_histogram_bars(self, bars, scores, axes): prop_map = self.get_relative_proportion_map(scores) epsilon = 1e-6 for bar in bars: prop = prop_map.get(bar.x, epsilon) bar.set_height( prop * axes.y_axis.unit_size * 100, stretch=True, about_edge=DOWN, ) def get_random_score(self): score = 1 radius = 1 while True: point = np.random.uniform(-1, 1, size=2) hit_radius = get_norm(point) if hit_radius > radius: return score else: score += 1 radius = np.sqrt(radius**2 - hit_radius**2) class ExactBullseye(HyperdartScene): def construct(self): board = Dartboard() board.replace(self.square) lines = VGroup(Line(DOWN, UP), Line(LEFT, RIGHT)) lines.set_stroke(WHITE, 1) lines.replace(self.square) self.add(board, lines) dart, dot = self.show_hit_with_dart(0.0037 * DOWN) self.play(FadeOut(dot)) frame = self.camera_frame self.play(frame.scale, 0.02, run_time=5) self.wait() class ShowProbabilityForFirstShot(HyperdartScene): def construct(self): square = self.square circle = self.circle VGroup(square, circle).to_edge(LEFT) r_line = DashedLine(circle.get_center(), circle.get_right()) r_label = OldTex("r = 1") r_label.next_to(r_line, DOWN, SMALL_BUFF) self.add(r_line, r_label) points = self.get_random_points(3000) dots = VGroup(*[Dot(point, radius=0.02) for point in points]) dots.set_fill(WHITE, 0.5) p_label = OldTex("P", "(S > 1)", "= ") square_frac = VGroup( circle.copy().set_height(0.5), Line(LEFT, RIGHT).set_width(0.7), square.copy().set_height(0.5).set_stroke(width=0) ) square_frac.arrange(DOWN, buff=SMALL_BUFF) result = OldTex("=", "{\\pi \\over 4}") equation = VGroup(p_label, square_frac, result) equation.arrange(RIGHT) equation.scale(1.4) equation.to_edge(RIGHT, buff=MED_LARGE_BUFF) brace = Brace(p_label[1], UP, buff=SMALL_BUFF) brace_label = brace.get_text("At least one\\\\``bullseye''") self.add(equation, brace, brace_label) self.play( LaggedStartMap(FadeInFromLarge, dots), run_time=5, ) self.play( ReplacementTransform( circle.copy().set_fill(opacity=0).set_stroke(WHITE, 1), square_frac[0] ), ) self.play( ReplacementTransform( square.copy().set_fill(opacity=0), square_frac[2] ), ) self.wait(2) # Dar on the line x = np.random.random() y = np.sqrt(1 - x**2) unit = circle.get_width() / 2 point = circle.get_center() + unit * x * RIGHT + unit * y * UP point += 0.004 * DOWN frame = self.camera_frame dart, dot = self.show_hit_with_dart(point) self.remove(dot) self.play( frame.scale, 0.05, frame.move_to, point, run_time=5, ) class SamplingFourRandomNumbers(Scene): CONFIG = { "n_terms": 4, "title_tex": "P\\left(x_0{}^2 + y_0{}^2 + x_1{}^2 + y_1{}^2 < 1\\right) = \\, ???", "nl_to_nl_buff": 0.75, "to_floor_buff": 0.5, "tip_scale_factor": 0.75, "include_half_labels": True, "include_title": True, } def construct(self): texs = ["x_0", "y_0", "x_1", "y_1", "x_2", "y_2"][:self.n_terms] colors = [BLUE, YELLOW, BLUE_B, YELLOW_B, BLUE_A, YELLOW_A][:self.n_terms] t2c = dict([(t, c) for t, c in zip(texs, colors)]) # Title if self.include_title: title = OldTex( self.title_tex, tex_to_color_map=t2c ) title.scale(1.5) title.to_edge(UP) h_line = DashedLine(title.get_left(), title.get_right()) h_line.next_to(title, DOWN, MED_SMALL_BUFF) self.add(title, h_line) # Number lines number_lines = VGroup(*[ NumberLine( x_min=-1, x_max=1, tick_frequency=0.25, unit_size=3, ) for x in range(self.n_terms) ]) for line in number_lines: line.add_numbers(-1, 0, 1) if self.include_half_labels: line.add_numbers( -0.5, 0.5, num_decimal_places=1, ) number_lines.arrange(DOWN, buff=self.nl_to_nl_buff) number_lines.to_edge(LEFT, buff=0.5) number_lines.to_edge(DOWN, buff=self.to_floor_buff) self.add(number_lines) # Trackers trackers = Group(*[ValueTracker(0) for x in range(self.n_terms)]) tips = VGroup(*[ ArrowTip( start_angle=-PI / 2, color=color ).scale(self.tip_scale_factor) for color in colors ]) labels = VGroup(*[ OldTex(tex) for tex in texs ]) for tip, tracker, line, label in zip(tips, trackers, number_lines, labels): tip.line = line tip.tracker = tracker tip.add_updater(lambda t: t.move_to( t.line.n2p(t.tracker.get_value()), DOWN )) label.tip = tip label.match_color(tip) label.arrange(RIGHT, buff=MED_SMALL_BUFF) label.add_updater(lambda l: l.next_to(l.tip, UP, SMALL_BUFF)) # label.add_updater(lambda l: l[1].set_value(l.tip.tracker.get_value())) self.add(tips, labels) # Write bit sum summands = VGroup(*[ OldTex("\\big(", "+0.00", "\\big)^2").set_color(color) for color in colors ]) summands.arrange(DOWN) summands.to_edge(RIGHT, buff=3) for summand, tracker in zip(summands, trackers): dec = DecimalNumber(include_sign=True) dec.match_color(summand) dec.tracker = tracker dec.add_updater(lambda d: d.set_value(d.tracker.get_value())) dec.move_to(summand[1]) summand.submobjects[1] = dec h_line = Line(LEFT, RIGHT) h_line.set_width(3) h_line.next_to(summands, DOWN, aligned_edge=RIGHT) plus = OldTex("+") plus.next_to(h_line.get_left(), UR) h_line.add(plus) total = DecimalNumber() total.scale(1.5) total.next_to(h_line, DOWN) total.match_x(summands) total.add_updater(lambda d: d.set_value(np.sum([ t.get_value()**2 for t in trackers ]))) VGroup(summands, h_line, total).shift_onto_screen() self.add(summands, h_line, total) # < or > 1 lt, gt = signs = VGroup( OldTex("< 1 \\quad \\checkmark"), OldTex("\\ge 1 \\quad"), ) for sign in signs: sign.scale(1.5) sign.next_to(total, RIGHT, MED_LARGE_BUFF) lt.set_color(GREEN) gt.set_color(RED) def update_signs(signs): i = int(total.get_value() > 1) signs[1 - i].set_opacity(0) signs[i].set_opacity(1) signs.add_updater(update_signs) self.add(signs) # Run simulation for x in range(9): trackers.generate_target() for t in trackers.target: t.set_value(np.random.uniform(-1, 1)) if x == 8: for t in trackers.target: t.set_value(np.random.uniform(-0.5, 0.5)) self.remove(signs) self.play(MoveToTarget(trackers)) self.add(signs) self.wait() # Less than 0.5 nl = number_lines[0] line = Line(nl.n2p(-0.5), nl.n2p(0.5)) rect = Rectangle(height=0.25) rect.set_stroke(width=0) rect.set_fill(GREEN, 0.5) rect.match_width(line, stretch=True) rects = VGroup(*[ rect.copy().move_to(line.n2p(0)) for line in number_lines ]) self.play(LaggedStartMap(GrowFromCenter, rects)) self.wait() self.play(LaggedStartMap(FadeOut, rects)) # Set one to 0.5 self.play(trackers[0].set_value, 0.9) self.play(ShowCreationThenFadeAround(summands[0])) self.wait() self.play(LaggedStart(*[ ShowCreationThenFadeAround(summand) for summand in summands[1:] ])) self.play(*[ ApplyMethod(tracker.set_value, 0.1) for tracker in trackers[1:] ]) self.wait(10) class SamplingTwoRandomNumbers(SamplingFourRandomNumbers): CONFIG = { "n_terms": 2, "title_tex": "P\\left(x_0{}^2 + y_0{}^2 < 1\\right) = \\, ???", "nl_to_nl_buff": 1, "to_floor_buff": 2, "random_seed": 1, } class SamplingSixRandomNumbers(SamplingFourRandomNumbers): CONFIG = { "n_terms": 6, "nl_to_nl_buff": 0.5, "include_half_labels": False, "include_title": False, "tip_scale_factor": 0.5, } class SamplePointIn3d(SpecialThreeDScene): def construct(self): axes = self.axes = self.get_axes() sphere = self.get_sphere() sphere.set_fill(BLUE_E, 0.25) sphere.set_stroke(opacity=0.5) cube = Cube() cube.replace(sphere) cube.set_fill(GREY, 0.2) cube.set_stroke(WHITE, 1, opacity=0.5) self.set_camera_orientation( phi=80 * DEGREES, theta=-120 * DEGREES, ) self.begin_ambient_camera_rotation(rate=0.03) dot = Sphere() # dot = Dot() dot.set_shade_in_3d(True) dot.set_width(0.1) dot.move_to(axes.c2p(*np.random.uniform(0, 1, size=3))) lines = always_redraw(lambda: self.get_lines(dot.get_center())) labels = always_redraw(lambda: self.get_labels(lines)) self.add(axes) self.add(cube) for line, label in zip(lines, labels): self.play( ShowCreation(line), FadeIn(label) ) self.add(lines, labels) self.play(GrowFromCenter(dot)) self.play(DrawBorderThenFill(sphere, stroke_width=1)) self.wait(2) n_points = 3000 points = [ axes.c2p(*np.random.uniform(-1, 1, 3)) for x in range(n_points) ] # point_cloud = PMobject().add_points(points) dots = VGroup(*[ Dot( point, radius=0.01, shade_in_3d=True, ) for point in points ]) dots.set_stroke(WHITE, 2) dots.set_opacity(0.5) self.play(ShowIncreasingSubsets(dots, run_time=9)) # self.play(ShowCreation(point_cloud, run_time=3)) self.wait(4) return for x in range(6): self.play( point.move_to, axes.c2p(*np.random.uniform(-1, 1, size=3)) ) self.wait(2) self.wait(7) def get_lines(self, point): axes = self.axes x, y, z = axes.p2c(point) p0 = axes.c2p(0, 0, 0) p1 = axes.c2p(x, 0, 0) p2 = axes.c2p(x, y, 0) p3 = axes.c2p(x, y, z) x_line = DashedLine(p0, p1, color=GREEN) y_line = DashedLine(p1, p2, color=RED) z_line = DashedLine(p2, p3, color=BLUE) lines = VGroup(x_line, y_line, z_line) lines.set_shade_in_3d(True) return lines def get_labels(self, lines): x_label = OldTex("x") y_label = OldTex("y") z_label = OldTex("z") result = VGroup(x_label, y_label, z_label) result.rotate(90 * DEGREES, RIGHT) result.set_shade_in_3d(True) x_line, y_line, z_line = lines x_label.match_color(x_line) y_label.match_color(y_line) z_label.match_color(z_line) x_label.next_to(x_line, IN, SMALL_BUFF) y_label.next_to(y_line, RIGHT + OUT, SMALL_BUFF) z_label.next_to(z_line, RIGHT, SMALL_BUFF) return result class OverlayToPointIn3d(Scene): def construct(self): t2c = { "{x}": GREEN, "{y}": RED, "{z}": BLUE, } ineq = OldTex( "{x}^2 + {y}^2 + {z}^2 < 1", tex_to_color_map=t2c, ) ineq.scale(1.5) ineq.move_to(FRAME_WIDTH * LEFT / 4) ineq.to_edge(UP) equiv = OldTex("\\Leftrightarrow") equiv.scale(2) equiv.match_y(ineq) rhs = OldTexText( "$({x}, {y}, {z})$", " lies within a\\\\sphere with radius 1" ) rhs[0][1].set_color(GREEN) rhs[0][3].set_color(RED) rhs[0][5].set_color(BLUE) rhs.scale(1.3) rhs.next_to(equiv, RIGHT) rhs.to_edge(UP) self.add(ineq) self.wait() self.play(Write(equiv)) self.wait() self.play(FadeIn(rhs)) self.wait() class TwoDPlusTwoDEqualsFourD(HyperdartScene): def construct(self): board = VGroup(*self.mobjects) unit_size = 1.5 axes = Axes( x_min=-1.25, x_max=1.25, y_min=-1.25, y_max=1.25, axis_config={ "unit_size": unit_size, "tick_frequency": 0.5, "include_tip": False, } ) board.set_height(2 * unit_size) axes.move_to(board) axes.set_stroke(width=1) board.add(axes) board.to_edge(LEFT) self.add(board) # Set up titles kw = { "tex_to_color_map": { "x_0": WHITE, "y_0": WHITE, "x_1": WHITE, "y_1": WHITE, } } title1 = VGroup( OldTexText("First shot"), OldTex("(x_0, y_0)", **kw), ) title2 = VGroup( OldTexText("Second shot"), OldTex("(x_1, y_1)", **kw), ) title3 = VGroup( OldTexText("Point in 4d space"), OldTex("(x_0, y_0, x_1, y_1)", **kw) ) titles = VGroup(title1, title2, title3) for title in titles: title.arrange(DOWN) plus = OldTex("+").scale(2) equals = OldTex("=").scale(2) label1 = OldTex("(x_0, y_0)") label2 = OldTex("(x_1, y_1)") VGroup(label1, label2).scale(0.8) title1.next_to(board, UP) # First hit point1 = axes.c2p(0.5, 0.7) dart1, dot1 = self.show_hit_with_dart(point1) label1.next_to(dot1, UR, buff=0) self.add(title1, label1) # lines1 = self.show_geometry(point1, pace="fast") # chord_and_shadow1 = self.show_circle_shrink(lines1[1], pace="fast") board_copy = board.copy() board_copy.next_to(board, RIGHT, buff=LARGE_BUFF) self.square = board_copy[0] title2.next_to(board_copy, UP) plus.move_to(titles[:2]) self.play(ReplacementTransform(board.copy().fade(1), board_copy)) point2 = self.get_random_point() dart2, dot2 = self.show_hit_with_dart(point2) label2.next_to(dot2, UR, buff=0) self.add(plus, title2, label2) self.wait() # Set up the other titles title3.to_edge(RIGHT) title3.match_y(title2) equals.move_to(midpoint(title2.get_right(), title3.get_left())) randy = Randolph(height=2.5) randy.next_to(title3, DOWN, buff=LARGE_BUFF) randy.look_at(title3) kw = {"path_arc": -20 * DEGREES} self.play( LaggedStart( *[ TransformFromCopy( title1[1].get_part_by_tex(tex), title3[1].get_part_by_tex(tex), **kw ) for tex in ["(", "x_0", ",", "y_0"] ], *[ TransformFromCopy( title2[1].get_part_by_tex(tex), title3[1].get_parts_by_tex(tex)[-1], **kw ) for tex in ["x_1", ",", "y_1", ")"] ], TransformFromCopy( title2[1].get_part_by_tex(","), title3[1].get_parts_by_tex(",")[1], **kw ), lag_ratio=0.01, ), Write(equals), ) self.play( FadeInFromDown(title3[0]), FadeIn(randy), ) self.play(randy.change, "horrified") self.play(Blink(randy)) self.wait() self.play(randy.change, "confused") self.play(Blink(randy)) self.wait() class ExpectedValueComputation(Scene): def construct(self): t2c = { "0": MAROON_C, "1": BLUE, "2": GREEN, "3": YELLOW, "4": RED, } line1 = OldTex( "E[S]", "=", "1 \\cdot", "P(S = 1)", "+", "2 \\cdot", "P(S = 2)", "+", "3 \\cdot", "P(S = 3)", "+", "\\cdots", tex_to_color_map=t2c ) line2 = OldTex( "=&\\phantom{-}", "1 \\cdot", "\\big(", "P(S > 0)", "-", "P(S > 1)", "\\big)", "\\\\&+", "2 \\cdot", "\\big(", "P(S > 1)", "-", "P(S > 2)", "\\big)", "\\\\&+", "3 \\cdot", "\\big(", "P(S > 2)", "-", "P(S > 3)", "\\big)", "\\\\&+", "\\cdots", tex_to_color_map=t2c ) line2[1:12].align_to(line2[13], LEFT) line3 = OldTex( "=", "P(S > 0)", "+", "P(S > 1)", "+", "P(S > 2)", "+", "P(S > 3)", "+", "\\cdots", tex_to_color_map=t2c, ) line1.to_corner(UL) line2.next_to(line1, DOWN, buff=MED_LARGE_BUFF) line2.align_to(line1[1], LEFT) line3.next_to(line2, DOWN, buff=MED_LARGE_BUFF) line3.align_to(line1[1], LEFT) # Write line 1 self.add(line1[:2]) self.play(Write(line1[2:7])) self.wait() self.play(FadeIn(line1[7])) self.play(Write(line1[8:13])) self.wait() self.play(FadeIn(line1[13])) self.play(Write(line1[14:19])) self.wait() self.play(Write(line1[19:])) self.wait() # line 2 scaffold kw = { "path_arc": 90 * DEGREES } bigs = line2.get_parts_by_tex("big") self.play( LaggedStart( TransformFromCopy( line1.get_part_by_tex("="), line2.get_part_by_tex("="), **kw ), TransformFromCopy( line1.get_parts_by_tex("\\cdot"), line2.get_parts_by_tex("\\cdot"), **kw ), TransformFromCopy( line1.get_parts_by_tex("+"), line2.get_parts_by_tex("+"), **kw ), TransformFromCopy( line1.get_part_by_tex("1"), line2.get_part_by_tex("1"), **kw ), TransformFromCopy( line1.get_part_by_tex("2"), line2.get_part_by_tex("2"), **kw ), TransformFromCopy( line1.get_part_by_tex("3"), line2.get_part_by_tex("3"), **kw ), run_time=3, lag_ratio=0, ), LaggedStart(*[ GrowFromCenter(bigs[i:i + 2]) for i in range(0, len(bigs), 2) ]) ) self.wait() # Expand out sum for n in range(3): i = 6 * n j = 12 * n rect1 = SurroundingRectangle(line1[i + 4:i + 7]) rect2 = SurroundingRectangle(line2[j + 4:j + 11]) color = line1[i + 5].get_color() VGroup(rect1, rect2).set_stroke(color, 2) self.play(ShowCreation(rect1)) self.play( TransformFromCopy( line1[i + 4:i + 7], line2[j + 4:j + 7], ), TransformFromCopy( line1[i + 4:i + 7], line2[j + 8:j + 11], ), FadeIn(line2[j + 7]), ReplacementTransform(rect1, rect2), ) self.play(FadeOut(rect2)) # Show telescoping line2.generate_target() line2.target.set_opacity(0.2) line2.target[4:7].set_opacity(1) self.play(MoveToTarget(line2)) self.wait() self.play( TransformFromCopy(line2[0], line3[0]), TransformFromCopy(line2[4:7], line3[1:4]), ) self.wait() line2.target.set_opacity(0.2) VGroup( line2.target[1:4], line2.target[7:12], line2.target[12:19], line2.target[23], ).set_opacity(1) self.play(MoveToTarget(line2)) self.wait() self.play( TransformFromCopy(line2[12], line3[4]), TransformFromCopy(line2[16:19], line3[5:8]), ) self.wait() n = 12 line2.target.set_opacity(0.2) VGroup( line2.target[n + 1:n + 4], line2.target[n + 7:n + 12], line2.target[n + 12:n + 19], line2.target[n + 23], ).set_opacity(1) self.play(MoveToTarget(line2)) self.wait() self.play( TransformFromCopy(line2[n + 12], line3[8]), TransformFromCopy(line2[n + 16:n + 19], line3[9:12]), ) self.wait() self.play(Write(line3[12:])) self.wait() rect = SurroundingRectangle(line3, buff=MED_SMALL_BUFF) rect.set_stroke(WHITE, 2) self.play(ShowCreation(rect)) self.wait() self.wait(3) class SubtractHistogramParts(ShowDistributionOfScores): def construct(self): n_scores = 10000 scores = np.array([self.get_random_score() for x in range(n_scores)]) axes = self.get_axes() bars = self.get_histogram_bars(axes) self.set_histogram_bars(bars, scores, axes) self.add(axes) self.add(bars) # P(S = 2) p2_arrow = Vector( 0.75 * DOWN, max_stroke_width_to_length_ratio=10, max_tip_length_to_length_ratio=0.35, ) p2_arrow.next_to(bars[1], UP, SMALL_BUFF) p2_arrow = VGroup( p2_arrow.copy().set_stroke(BLACK, 9), p2_arrow, ) p2_label = OldTex("P(S = 2)") p2_label.next_to(p2_arrow, UP, SMALL_BUFF) p2_label.set_color(bars[1].get_fill_color()) self.play( GrowFromPoint(p2_arrow, p2_arrow.get_top()), FadeInFromDown(p2_label), bars[0].set_opacity, 0.1, bars[2:].set_opacity, 0.1, ) self.wait() # Culumative probabilities rhs = OldTex("=", "P(S > 1)", "-", "P(S > 2)") rhs[1].set_color(YELLOW) rhs[3].set_color(bars[2].get_fill_color()) rhs[2:].set_opacity(0.2) rhs.next_to(p2_label, RIGHT) brace1 = Brace(bars[1:5], UP)[0] brace1.next_to(rhs[1], DOWN) brace1.match_color(rhs[1]) rf = 3.5 lf = 1.4 brace1[:2].stretch(rf, 0, about_edge=LEFT) brace1[0].stretch(1 / rf, 0, about_edge=LEFT) brace1[4:].stretch(lf, 0, about_edge=RIGHT) brace1[5:].stretch(1 / lf, 0, about_edge=RIGHT) brace2 = Brace(bars[2:], UP) brace2.match_color(rhs[3]) brace2.set_width(10, about_edge=LEFT) brace2.shift(1.5 * UP) self.add(brace1, p2_arrow) self.play( FadeIn(rhs), bars[2:].set_opacity, 1, GrowFromPoint(brace1, rhs[1].get_bottom()), p2_arrow.set_opacity, 0.5, ) self.wait() self.play( rhs[:2].set_opacity, 0.2, brace1.set_opacity, 0.2, rhs[2:].set_opacity, 1, bars[1].set_opacity, 0.1, GrowFromCenter(brace2), ) self.wait() self.play( bars[2:].set_opacity, 0.1, bars[1].set_opacity, 1, rhs.set_opacity, 1, brace1.set_opacity, 1, p2_arrow.set_opacity, 1, ) self.wait() # for i, part in enumerate(brace1): # self.add(Integer(i).scale(0.5).move_to(part)) class GameWithSpecifiedScore(HyperdartScene): CONFIG = { "score": 1, "random_seed": 1, } def construct(self): board = VGroup(self.square, self.circle, self.circle_center_dot) board.to_edge(DOWN, buff=0.5) score_label = VGroup( OldTexText("Score: "), Integer(1) ) score_label.scale(2) score_label.arrange(RIGHT, aligned_edge=DOWN) score_label.to_edge(UP, buff=0.25) self.add(score_label) score = 1 pace = "fast" while True: point = self.get_random_point() want_to_continue = (score < self.score) if want_to_continue: while not self.is_inside(point): point = self.get_random_point() dart, dot = self.show_hit_with_dart(point) score_label[1].increment_value() lines = self.show_geometry(point, pace) chord_and_shadow = self.show_circle_shrink(lines[1], pace=pace) self.play( FadeOut(VGroup(dart, dot, lines, chord_and_shadow)), run_time=0.5, ) score += 1 else: while self.is_inside(point): point = self.get_random_point() self.show_miss(point) self.play(ShowCreationThenFadeAround(score_label[1])) self.wait() return class Score1Game(GameWithSpecifiedScore): CONFIG = { "score": 1, } class Score2Game(GameWithSpecifiedScore): CONFIG = { "score": 2, } class Score3Game(GameWithSpecifiedScore): CONFIG = { "score": 3, } class Score4Game(GameWithSpecifiedScore): CONFIG = { "score": 4, } class HistogramScene(ShowDistributionOfScores): CONFIG = { "n_scores": 10000, "mean_line_height": 4, } def setup(self): self.scores = np.array([ self.get_random_score() for x in range(self.n_scores) ]) self.axes = self.get_axes() self.bars = self.get_histogram_bars(self.axes) self.set_histogram_bars(self.bars, self.scores, self.axes) self.add(self.axes) self.add(self.bars) def get_mean_label(self): mean_line = DashedLine(ORIGIN, self.mean_line_height * UP) mean_line.set_stroke(YELLOW, 2) mean = np.mean(self.scores) mean_line.move_to(self.axes.c2p(mean, 0), DOWN) mean_label = VGroup( *TexText("E[S]", "="), DecimalNumber(mean, num_decimal_places=3), ) mean_label.arrange(RIGHT) mean_label.match_color(mean_line) mean_label.next_to( mean_line.get_end(), UP, SMALL_BUFF, index_of_submobject_to_align=0, ) return VGroup(mean_line, *mean_label) class ExpectedValueFromBars(HistogramScene): def construct(self): axes = self.axes bars = self.bars mean_label = self.get_mean_label() mean_label.remove(mean_label[-1]) equation = OldTex( "P(S = 1)", "\\cdot", "1", "+", "P(S = 2)", "\\cdot", "2", "+", "P(S = 3)", "\\cdot", "3", "+", "\\cdots" ) equation.scale(0.9) equation.next_to(mean_label[-1], RIGHT) equation.shift(LEFT) for i in range(3): equation.set_color_by_tex( str(i + 1), bars[i].get_fill_color() ) equation[4:].set_opacity(0.2) self.add(mean_label) self.play( mean_label[1:].shift, LEFT, FadeIn(equation, LEFT) ) p_parts = VGroup() p_part_copies = VGroup() for i in range(3): bar = bars[i] num = axes.x_axis.numbers[i] p_part = equation[4 * i] s_part = equation[4 * i + 2] p_part_copy = p_part.copy() p_part_copy.set_width(0.8 * bar.get_width()) p_part_copy.next_to(bar, UP, SMALL_BUFF) p_part_copy.set_opacity(1) self.remove(mean_label[0]) self.play( bars[:i + 1].set_opacity, 1, bars[i + 1:].set_opacity, 0.2, equation[:4 * (i + 1)].set_opacity, 1, FadeInFromDown(p_part_copy), Animation(mean_label[0]), ) kw = { "surrounding_rectangle_config": { "color": bar.get_fill_color(), "buff": 0.5 * SMALL_BUFF, } } self.play( LaggedStart( AnimationGroup( ShowCreationThenFadeAround(p_part, **kw), ShowCreationThenFadeAround(p_part_copy, **kw), ), AnimationGroup( ShowCreationThenFadeAround(s_part, **kw), ShowCreationThenFadeAround(num, **kw), ), lag_ratio=0.5, ) ) self.wait() p_parts.add(p_part) p_part_copies.add(p_part_copy) self.add(bars, mean_label) self.play( bars.set_opacity, 1, equation.set_opacity, 1, FadeOut(p_part_copies) ) braces = VGroup(*[ Brace(p_part, UP) for p_part in p_parts ]) for brace in braces: brace.add(brace.get_text("???")) self.play(LaggedStartMap(FadeIn, braces)) self.wait() class ProbabilitySGtOne(HistogramScene): def construct(self): axes = self.axes bars = self.bars brace = Brace(bars[1:], UP) label = brace.get_tex("P(S > 1)") brace[0][:2].stretch(1.5, 0, about_edge=LEFT) outlines = bars[1:].copy() for bar in outlines: bar.set_stroke(bar.get_fill_color(), 2) bar.set_fill(opacity=0) self.play( GrowFromEdge(brace, LEFT), bars[0].set_opacity, 0.2, bars[1:].set_opacity, 0.8, ShowCreationThenFadeOut(outlines), FadeIn(label, LEFT), ) self.wait() square = Square() square.set_fill(BLUE, 0.75) square.set_stroke(WHITE, 1) square.set_height(0.5) circle = Circle() circle.set_fill(RED, 0.75) circle.set_stroke(WHITE, 1) circle.set_height(0.5) bar = Line(LEFT, RIGHT) bar.set_stroke(WHITE, 3) bar.set_width(0.5) geo_frac = VGroup(circle, bar, square) geo_frac.arrange(DOWN, SMALL_BUFF, buff=SMALL_BUFF) rhs = VGroup( OldTex("="), geo_frac, OldTex("= \\frac{\\pi}{4}") ) rhs.arrange(RIGHT) rhs.next_to(label) shift_val = 2.05 * LEFT + 0.25 * UP rhs.shift(shift_val) self.play( label.shift, shift_val, FadeIn(rhs, LEFT) ) self.wait() # P(S > 2) new_brace = brace.copy() new_brace.next_to( bars[2], UP, buff=SMALL_BUFF, aligned_edge=LEFT, ) self.add(new_brace) new_label = OldTex( "P(S > 2)", "=", "\\,???" ) new_label.next_to(new_brace[0][2], UP) self.play( bars[1].set_opacity, 0.2, label.set_opacity, 0.5, rhs.set_opacity, 0.5, brace.set_opacity, 0.5, GrowFromEdge(new_brace, LEFT), ReplacementTransform( new_label.copy().fade(1).move_to(label, LEFT), new_label, ) ) self.wait() new_rhs = OldTex( "{\\text{4d ball}", " \\over", " \\text{4d cube}}", # "=", # "{\\pi^2 / 2", "\\over", "2^4}" ) new_rhs[0].set_color(RED) new_rhs[2].set_color(BLUE) new_rhs.move_to(new_label[-1], LEFT) shift_val = 0.75 * LEFT + 0.15 * UP new_rhs.shift(shift_val) new_label.generate_target() new_label.target.shift(shift_val) new_label.target[-1].set_opacity(0) self.play( MoveToTarget(new_label), FadeIn(new_rhs, LEFT) ) self.wait() # P(S > 3) final_brace = brace.copy() final_brace.set_opacity(1) final_brace.next_to( bars[3], UP, buff=SMALL_BUFF, aligned_edge=LEFT, ) self.add(final_brace) final_label = OldTex("P(S > 3)") final_label.next_to(final_brace[0][2], UP, SMALL_BUFF) self.play( bars[2].set_opacity, 0.2, new_label[:-1].set_opacity, 0.5, new_rhs.set_opacity, 0.5, new_brace.set_opacity, 0.5, GrowFromEdge(final_brace, LEFT), ReplacementTransform( final_label.copy().fade(1).move_to(new_label, LEFT), final_label, ), axes.x_axis[-1].set_opacity, 0, ) self.wait() class VolumsOfNBalls(Scene): def construct(self): title, alt_title = [ OldTexText( "Volumes of " + tex + "-dimensional balls", tex_to_color_map={tex: YELLOW}, ) for tex in ["$N$", "$2n$"] ] for mob in [title, alt_title]: mob.scale(1.5) mob.to_edge(UP) formulas = VGroup(*[ OldTex( tex, tex_to_color_map={"R": WHITE} ) for tex in [ "2R", "\\pi R^2", "\\frac{4}{3} \\pi R^3", "\\frac{1}{2} \\pi^2 R^4", "\\frac{8}{15} \\pi^2 R^5", "\\frac{1}{6} \\pi^3 R^6", "\\frac{16}{105} \\pi^3 R^7", "\\frac{1}{24} \\pi^4 R^8", "\\frac{32}{945} \\pi^4 R^9", "\\frac{1}{120} \\pi^5 R^{10}", "\\frac{64}{10{,}395} \\pi^5 R^{11}", "\\frac{1}{720} \\pi^6 R^{12}", ] ]) formulas.arrange(RIGHT, buff=LARGE_BUFF) formulas.scale(0.9) formulas.to_edge(LEFT) lines = VGroup() d_labels = VGroup() for dim, formula in zip(it.count(1), formulas): label = VGroup(Integer(dim), OldTex("D")) label.arrange(RIGHT, buff=0, aligned_edge=DOWN) label[0].set_color(YELLOW) label.move_to(formula) label.shift(UP) line = Line(UP, DOWN) line.set_stroke(WHITE, 1) line.next_to(formula, RIGHT, buff=MED_LARGE_BUFF) line.shift(0.5 * UP) d_labels.add(label) lines.add(line) # coefs.add(formula[0]) formula[0].set_color(BLUE_B) lines.remove(lines[-1]) line = Line(formulas.get_left(), formulas.get_right()) line.set_stroke(WHITE, 1) line.next_to(d_labels, DOWN, MED_SMALL_BUFF) lines.add(line) chart = VGroup(lines, d_labels, formulas) chart.save_state() self.add(title) self.add(d_labels) self.add(lines) self.play(LaggedStartMap(FadeInFromDown, formulas, run_time=3, lag_ratio=0.1)) self.play(chart.to_edge, RIGHT, {"buff": MED_SMALL_BUFF}, run_time=5) self.wait() self.play(Restore(chart)) self.play(FadeOut(formulas[4:])) rect1 = SurroundingRectangle(formulas[2][0][-1]) rect2 = SurroundingRectangle(formulas[3][0][-2:]) self.play(ShowCreation(rect1)) self.play(TransformFromCopy(rect1, rect2)) self.play(FadeOut(VGroup(rect1, rect2))) arrows = VGroup(*[ Arrow( formulas[i].get_bottom(), formulas[i + 1].get_bottom(), path_arc=150 * DEGREES, ) for i in (1, 2) ]) for arrow in arrows: self.play(ShowCreation(arrow)) self.wait() self.play( FadeOut(arrows), FadeIn(formulas[4:]), ) # General formula for even dimensions braces = VGroup(*[ Brace(formula, DOWN) for formula in formulas[1::2] ]) gen_form = OldTex("{\\pi^n \\over n!}", "R^{2n}") gen_form[0].set_color(BLUE_B) gen_form.scale(1.5) gen_form.to_edge(DOWN) self.play( formulas[::2].set_opacity, 0.25, ReplacementTransform(title, alt_title) ) for brace in braces[:3]: self.play(GrowFromCenter(brace)) self.wait() self.play( FadeOut(braces[:3]), FadeIn(gen_form, UP), ) self.wait() class RepeatedSamplesGame(Scene): def construct(self): pass # Old scenes, before decision to collaborate with numberphile class IntroduceGame(HyperdartScene): CONFIG = { "random_seed": 0, "square_width": 5, "num_darts_in_initial_flurry": 5, } def construct(self): self.show_flurry_of_points() self.show_board_dimensions() self.introduce_bullseye() self.show_miss_example() self.show_shrink_rule() def show_flurry_of_points(self): square = self.square circle = self.circle title = OldTexText("Hyperdarts") title.scale(1.5) title.to_edge(UP) n = self.num_darts_in_initial_flurry points = np.random.normal(size=n * 3).reshape((n, 3)) points[:, 2] = 0 points *= 0.75 board = Dartboard() board.match_width(square) board.move_to(square) pre_square = Circle(color=WHITE) pre_square.replace(square) self.remove(circle, square) self.add(board) darts, dots = self.show_hits_with_darts( points, added_anims=[FadeInFromDown(title)] ) self.wait() def func(p): theta = angle_of_vector(p) % (TAU / 4) if theta > TAU / 8: theta = TAU / 4 - theta p *= 1 / np.cos(theta) return p self.play( *[ ApplyPointwiseFunction(func, pieces, run_time=1) for pieces in [*board[:3], *dots] ], *[ MaintainPositionRelativeTo(dart, dot) for dart, dot in zip(darts, dots) ] ) self.flurry_dots = dots self.darts = darts self.title = title self.board = board def show_board_dimensions(self): square = self.square labels = VGroup(*[ OldTexText("2 ft").next_to( square.get_edge_center(vect), vect, ) for vect in [DOWN, RIGHT] ]) labels.set_color(YELLOW) h_line, v_line = lines = VGroup(*[ DashedLine( square.get_edge_center(v1), square.get_edge_center(-v1), ).next_to(label, v2) for label, v1, v2 in zip(labels, [LEFT, UP], [UP, LEFT]) ]) lines.match_color(labels) self.play( LaggedStartMap(ShowCreation, lines), LaggedStartMap(FadeInFromDown, labels), lag_ratio=0.5 ) self.wait() self.square_dimensions = VGroup(lines, labels) def introduce_bullseye(self): square = self.square circle = self.circle board = self.board circle.save_state() circle.replace(board[-1]) label = OldTexText("Bullseye") label.scale(1.5) label.next_to(square, LEFT, aligned_edge=UP) label.set_color(RED) arrow = Arrow( label.get_bottom(), circle.get_corner(DR) ) radius = DashedLine( square.get_center(), square.get_left(), stroke_width=2, ) radius_label = OldTexText("1 ft") radius_label.next_to(radius, DOWN, SMALL_BUFF) self.add(circle, self.square_dimensions) self.play( FadeInFromLarge(circle), FadeInFromDown(label), ShowCreation(arrow), LaggedStartMap(FadeOut, self.flurry_dots, run_time=1), LaggedStartMap(FadeOut, self.darts, run_time=1), ) self.wait() self.add(square, board, arrow, circle) self.play( Restore(circle), ApplyMethod( arrow.scale, 0.4, {"about_point": arrow.get_start()} ), ) self.add(radius, self.circle_center_dot) self.play( ShowCreation(radius), FadeIn(radius_label, RIGHT), FadeIn(self.circle_center_dot), ) self.play( FadeOut(label), Uncreate(arrow), FadeOut(board) ) self.wait() s_lines, s_labels = self.square_dimensions self.play( FadeOut(s_lines), FadeOut(radius), FadeOut(radius_label), FadeOut(self.title), ) self.circle_dimensions = VGroup( radius, radius_label, ) def show_miss_example(self): square = self.square point = square.get_corner(UL) + 0.5 * DR miss_word = OldTexText("Miss!") miss_word.scale(1.5) miss_word.next_to(point, UP, LARGE_BUFF) dart, dot = self.show_hit_with_dart(point) self.play(FadeInFromDown(miss_word)) self.wait() game_over = self.show_game_over() self.wait() self.play( *map(FadeOut, [dart, dot, miss_word, game_over]) ) def show_shrink_rule(self): circle = self.circle point = 0.5 * circle.point_from_proportion(0.2) # First example self.show_full_hit_process(point) self.wait() # Close to border label = OldTexText("Bad shot $\\Rightarrow$ much shrinkage") label.scale(1.5) label.to_edge(UP) point = 0.98 * circle.point_from_proportion(3 / 8) circle.save_state() self.play(FadeInFromDown(label)) self.show_full_hit_process(point) self.wait() self.play(Restore(circle)) # Close to center new_label = OldTexText("Good shot $\\Rightarrow$ less shrinkage") new_label.scale(1.5) new_label.to_edge(UP) point = 0.2 * circle.point_from_proportion(3 / 8) self.play( FadeInFromDown(new_label), FadeOut(label, UP), ) self.show_full_hit_process(point) self.wait() self.play(FadeOut(new_label)) # Play on for x in range(3): r1, r2 = np.random.random(size=2) point = r1 * circle.point_from_proportion(r2) self.show_full_hit_process(point) point = circle.get_right() + 0.5 * UR self.show_miss(point) self.wait() self.show_game_over() class ShowScoring(HyperdartScene): def setup(self): super().setup() self.add_score_counter() def construct(self): self.comment_on_score() self.show_several_hits() def comment_on_score(self): score_label = self.score_label comment = OldTexText("\\# Bullseyes") # rect = SurroundingRectangle(comment) # rect.set_stroke(width=1) # comment.add(rect) comment.set_color(YELLOW) comment.next_to(score_label, DOWN, LARGE_BUFF) comment.set_x(midpoint( self.square.get_left(), LEFT_SIDE, )[0]) arrow = Arrow( comment.get_top(), score_label[1].get_bottom(), buff=0.2, ) arrow.match_color(comment) self.play( FadeInFromDown(comment), GrowArrow(arrow), ) def show_several_hits(self): points = [UR, DL, 0.5 * UL, 0.5 * DR] for point in points: self.show_full_hit_process(point, pace="fast") self.show_miss(2 * UR) self.wait() # def add_score_counter(self): score = Integer(0) score_label = VGroup( OldTexText("Score: "), score ) score_label.arrange(RIGHT, aligned_edge=DOWN) score_label.scale(1.5) score_label.to_corner(UL) self.add(score_label) self.score = score self.score_label = score_label def increment_score(self): score = self.score new_score = score.copy() new_score.increment_value(1) self.play( FadeOut(score, UP), FadeIn(new_score, DOWN), run_time=1, ) self.remove(new_score) score.increment_value() score.move_to(new_score) self.add(score) def show_hit(self, point, *args, **kwargs): result = super().show_hit(point, *args, **kwargs) if self.is_inside(point): self.increment_score() return result def show_hit_with_dart(self, point, *args, **kwargs): result = super().show_hit_with_dart(point, *args, **kwargs) if self.is_inside(point): self.increment_score() return result class ShowSeveralRounds(ShowScoring): CONFIG = { "n_rounds": 5, } def construct(self): for x in range(self.n_rounds): self.show_single_round() self.reset_board() def show_single_round(self, pace="fast"): while True: point = self.get_random_point() if self.is_inside(point): self.show_full_hit_process(point, pace=pace) else: to_fade = self.show_miss(point) self.wait(0.5) self.play( ShowCreationThenFadeAround(self.score_label), FadeOut(to_fade) ) return def reset_board(self): score = self.score new_score = score.copy() new_score.set_value(0) self.play( self.circle.match_width, self.square, FadeOut(score, UP), FadeIn(new_score, DOWN), ) score.set_value(0) self.add(score) self.remove(new_score) class ShowSeveralRoundsQuickly(ShowSeveralRounds): CONFIG = { "n_rounds": 15, } def show_full_hit_process(self, point, *args, **kwargs): lines = self.get_all_hit_lines(point) dart = self.show_hit_with_dart(point) self.add(lines) self.score.increment_value(1) to_fade = self.show_circle_shrink(lines[1], pace="fast") to_fade.add(*lines, *dart) self.play(FadeOut(to_fade), run_time=0.5) def increment_score(self): pass # Handled elsewhere class ShowSeveralRoundsVeryQuickly(ShowSeveralRoundsQuickly): def construct(self): pass class ShowUniformDistribution(HyperdartScene): CONFIG = { "dart_sound": "dart_high", "n_points": 1000, } def construct(self): self.add_title() self.show_random_points() self.exchange_titles() self.show_random_points() def get_square(self): return super().get_square().to_edge(DOWN) def add_title(self): # square = self.square title = OldTexText("All points in the square are equally likely") title.scale(1.5) title.to_edge(UP) new_title = OldTexText("``Uniform distribution'' on the square") new_title.scale(1.5) new_title.to_edge(UP) self.play(FadeInFromDown(title)) self.title = title self.new_title = new_title def show_random_points(self): points = self.get_random_points(self.n_points) dots = VGroup(*[ Dot(point, radius=0.02) for point in points ]) dots.set_fill(opacity=0.75) run_time = 5 self.play(LaggedStartMap( FadeInFromLarge, dots, run_time=run_time, )) for x in range(1000): self.add_dart_sound( time_offset=-run_time * np.random.random(), gain=-10, gain_to_background=-5, ) self.wait() def exchange_titles(self): self.play( FadeInFromDown(self.new_title), FadeOut(self.title, UP), ) class ExpectedScoreEqualsQMark(Scene): def construct(self): equation = OldTexText( "\\textbf{E}[Score] = ???", tex_to_color_map={ "???": YELLOW, } ) aka = OldTexText("a.k.a. Long-term average") aka.next_to(equation, DOWN) self.play(Write(equation)) self.wait(2) self.play(FadeIn(aka, UP)) self.wait()
from manim_imports_ext import * import json import numbers OUTPUT_DIRECTORY = "spirals" INV_113_MOD_710 = 377 # Inverse of 113 mode 710 INV_7_MOD_44 = 19 def is_prime(n): if n < 2: return False for k in range(2, int(np.sqrt(n)) + 1): if n % k == 0: return False return True def generate_prime_list(*args): if len(args) == 1: start, stop = 2, args[0] elif len(args) == 2: start, stop = args start = max(start, 2) else: raise TypeError("generate_prime_list takes 1 or 2 arguments") result = [ n for n in range(start, stop) if is_prime(n) ] return result def get_gcd(x, y): while y > 0: x, y = y, x % y return x def read_in_primes(max_N=None): if max_N is None: max_N = int(1e7) if max_N < 1e5: file = "primes_1e5.json" elif max_N < 1e6: file = "primes_1e6.json" else: file = "primes_1e7.json" with open(os.path.join("assets", file)) as fp: primes = np.array(json.load(fp)) return primes[primes <= max_N] class SpiralScene(Scene): CONFIG = { "axes_config": { "axis_config": { "stroke_width": 1.5, } }, "default_dot_color": TEAL, "p_spiral_width": 6, } def setup(self): super().setup() self.axes = Axes(**self.axes_config) self.add(self.axes) def get_v_spiral(self, sequence, axes=None, box_width=None): if axes is None: axes = self.axes if box_width is None: unit = get_norm(axes.c2p(1, 0) - axes.c2p(0, 0)), box_width = max( 0.2 / (-np.log10(unit) + 1), 0.02, ) return VGroup(*[ Square( side_length=box_width, fill_color=self.default_dot_color, fill_opacity=1, stroke_width=0, ).move_to(self.get_polar_point(n, n, axes)) for n in sequence ]) def get_p_spiral(self, sequence, axes=None): if axes is None: axes = self.axes result = PMobject( color=self.default_dot_color, stroke_width=self.p_spiral_width, ) result.add_points([ self.get_polar_point(n, n, axes) for n in sequence ]) return result def get_prime_v_spiral(self, max_N, **kwargs): primes = read_in_primes(max_N) return self.get_v_spiral(primes, **kwargs) def get_prime_p_spiral(self, max_N, **kwargs): primes = read_in_primes(max_N) return self.get_p_spiral(primes, **kwargs) def get_polar_point(self, r, theta, axes=None): if axes is None: axes = self.axes return axes.c2p(r * np.cos(theta), r * np.sin(theta)) def set_scale(self, scale, axes=None, spiral=None, to_shrink=None, min_box_width=0.05, target_p_spiral_width=None, added_anims=[], run_time=3): if axes is None: axes = self.axes if added_anims is None: added_anims = [] sf = self.get_scale_factor(scale, axes) anims = [] for mob in [axes, spiral, to_shrink]: if mob is None: continue mob.generate_target() mob.target.scale(sf, about_point=ORIGIN) if mob is spiral: if isinstance(mob, VMobject): old_width = mob[0].get_width() for submob in mob.target: submob.set_width(max( old_width * sf, min_box_width, )) elif isinstance(mob, PMobject): if target_p_spiral_width is not None: mob.target.set_stroke_width(target_p_spiral_width) anims.append(MoveToTarget(mob)) anims += added_anims if run_time == 0: for anim in anims: anim.begin() anim.update(1) anim.finish() else: self.play( *anims, run_time=run_time, rate_func=lambda t: interpolate( smooth(t), smooth(t)**(sf**(0.5)), t, ) ) def get_scale_factor(self, target_scale, axes=None): if axes is None: axes = self.axes unit = get_norm(axes.c2p(1, 0) - axes.c2p(0, 0)) return 1 / (target_scale * unit) def get_labels(self, sequence, scale_func=np.sqrt): labels = VGroup() for n in sequence: label = Integer(n) label.set_stroke(width=0, background=True) label.scale(scale_func(n)) label.next_to( self.get_polar_point(n, n), UP, buff=0.5 * label.get_height(), ) labels.add(label) return labels def get_prime_labels(self, max_N): primes = read_in_primes(max_N) return self.get_labels(primes) # Scenes class AltTitle(Scene): def construct(self): title_text = """ How pretty but pointless patterns\\\\ in polar plots of primes\\\\ prompt pretty important ponderings\\\\ on properties of those primes. """ words = [w + " " for w in title_text.split(" ") if w] title = OldTexText(*words) title.set_width(FRAME_WIDTH - 1) title[2:5].set_color(TEAL) title[12:15].set_color(YELLOW) title.set_stroke(BLACK, 5, background=True) image = ImageMobject("PrimeSpiral") image.set_height(FRAME_HEIGHT) rect = FullScreenFadeRectangle(fill_opacity=0.25) self.add(image, rect) for word in title: self.play( FadeIn( word, run_time=0.05 * len(word), lag_ratio=0.4, ) ) self.wait() class HoldUpMathExchange(TeacherStudentsScene): def construct(self): title = OldTexText("Mathematics Stack Exchange") title.scale(1.5) title.to_edge(UP) self.add(title) self.play(self.teacher.change, "raise_right_hand", ORIGIN), self.play_all_student_changes("thinking", look_at=ORIGIN) self.wait(3) self.play_all_student_changes("confused", look_at=ORIGIN) self.wait(3) class MathExchangeNames(Scene): def construct(self): names = VGroup( OldTexText("dwymark"), OldTexText("Greg Martin"), ) names.arrange(DOWN, buff=1) for name in names: self.play(FadeIn(name, RIGHT)) self.wait() class MathExchange(ExternallyAnimatedScene): pass class PrimesAndPi(Scene): def construct(self): self.show_primes() self.show_rational_approximations() def show_primes(self): n_rows = 10 n_cols = 10 matrix = IntegerMatrix([ [n_cols * x + y for y in range(n_cols)] for x in range(n_rows) ]) numbers = matrix.get_entries() primes = VGroup(*filter( lambda m: is_prime(m.get_value()), numbers, )) non_primes = VGroup(*filter( lambda m: not is_prime(m.get_value()), numbers )) self.add(numbers) self.play( LaggedStart(*[ ApplyFunction( lambda m: m.set_color(TEAL).scale(1.2), prime ) for prime in primes ]), non_primes.set_opacity, 0.25, run_time=2, ) self.wait() self.numbers = numbers def show_rational_approximations(self): numbers = self.numbers approxs = OldTex( "{22 \\over 7} &=", "{:.12}\\dots\\\\".format(22 / 7), "{355 \\over 113} &=", "{:.12}\\dots\\\\".format(355 / 113), "\\pi &=", "{:.12}\\dots\\\\".format(PI), ) approxs[:2].shift(MED_LARGE_BUFF * UP) approxs[-2:].shift(MED_LARGE_BUFF * DOWN) approxs[-2:].set_color(YELLOW) approxs[1][:4].set_color(YELLOW) approxs[3][:8].set_color(YELLOW) approxs.scale(1.5) randy = Randolph(color=YELLOW, height=1) randy.move_to(approxs[-2][0], RIGHT) approxs[-2][0].set_opacity(0) self.play( LaggedStartMap(FadeOutAndShiftDown, numbers), LaggedStartMap(FadeIn, approxs), FadeIn(randy) ) self.play(Blink(randy)) self.play(randy.change, "pondering", UR) self.wait() class RefresherOnPolarCoordinates(Scene): CONFIG = { "x_color": GREEN, "y_color": RED, "r_color": YELLOW, "theta_color": LIGHT_PINK, } def construct(self): self.show_xy_coordinates() self.transition_to_polar_grid() self.show_polar_coordinates() self.show_all_nn_tuples() def show_xy_coordinates(self): plane = NumberPlane() plane.add_coordinates() x = 3 * np.cos(PI / 6) y = 3 * np.sin(PI / 6) point = plane.c2p(x, y) xp = plane.c2p(x, 0) origin = plane.c2p(0, 0) x_color = self.x_color y_color = self.y_color x_line = Line(origin, xp, color=x_color) y_line = Line(xp, point, color=y_color) dot = Dot(point) coord_label = self.get_coord_label(0, 0, x_color, y_color) x_coord = coord_label.x_coord y_coord = coord_label.y_coord coord_label.next_to(dot, UR, SMALL_BUFF) x_brace = Brace(x_coord, UP) y_brace = Brace(y_coord, UP) x_brace.add(x_brace.get_tex("x").set_color(x_color)) y_brace.add(y_brace.get_tex("y").set_color(y_color)) x_brace.add_updater(lambda m: m.next_to(x_coord, UP, SMALL_BUFF)) y_brace.add_updater(lambda m: m.next_to(y_coord, UP, SMALL_BUFF)) self.add(plane) self.add(dot, coord_label) self.add(x_brace, y_brace) coord_label.add_updater( lambda m: m.next_to(dot, UR, SMALL_BUFF) ) self.play( ShowCreation(x_line), ChangeDecimalToValue(x_coord, x), UpdateFromFunc( dot, lambda d: d.move_to(x_line.get_end()), ), run_time=2, ) self.play( ShowCreation(y_line), ChangeDecimalToValue(y_coord, y), UpdateFromFunc( dot, lambda d: d.move_to(y_line.get_end()), ), run_time=2, ) self.wait() self.xy_coord_mobjects = VGroup( x_line, y_line, coord_label, x_brace, y_brace, ) self.plane = plane self.dot = dot def transition_to_polar_grid(self): self.polar_grid = self.get_polar_grid() self.add(self.polar_grid, self.dot) self.play( FadeOut(self.xy_coord_mobjects), FadeOut(self.plane), ShowCreation(self.polar_grid, run_time=2), ) self.wait() def show_polar_coordinates(self): dot = self.dot plane = self.plane origin = plane.c2p(0, 0) r_color = self.r_color theta_color = self.theta_color r_line = Line(origin, dot.get_center()) r_line.set_color(r_color) r_value = r_line.get_length() theta_value = r_line.get_angle() coord_label = self.get_coord_label(r_value, theta_value, r_color, theta_color) r_coord = coord_label.x_coord theta_coord = coord_label.y_coord coord_label.add_updater(lambda m: m.next_to(dot, UP, buff=SMALL_BUFF)) r_coord.add_updater(lambda d: d.set_value( get_norm(dot.get_center()) )) theta_coord.add_background_rectangle() theta_coord.add_updater(lambda d: d.set_value( (angle_of_vector(dot.get_center()) % TAU) )) coord_label[-1].add_updater( lambda m: m.next_to(theta_coord, RIGHT, SMALL_BUFF) ) non_coord_parts = VGroup(*[ part for part in coord_label if part not in [r_coord, theta_coord] ]) r_label = OldTex("r") r_label.set_color(r_color) r_label.add_updater(lambda m: m.next_to(r_coord, UP)) theta_label = OldTex("\\theta") theta_label.set_color(theta_color) theta_label.add_updater(lambda m: m.next_to(theta_coord, UP)) r_coord_copy = r_coord.copy() r_coord_copy.add_updater( lambda m: m.next_to(r_line.get_center(), UL, buff=0) ) degree_label = DecimalNumber(0, num_decimal_places=1, unit="^\\circ") arc = Arc(radius=1, angle=theta_value) arc.set_color(theta_color) degree_label.set_color(theta_color) # Show r self.play( ShowCreation(r_line, run_time=2), ChangeDecimalToValue(r_coord_copy, r_value, run_time=2), VFadeIn(r_coord_copy, run_time=0.5), ) r_coord.set_value(r_value) self.add(non_coord_parts, r_coord_copy) self.play( FadeIn(non_coord_parts), ReplacementTransform(r_coord_copy, r_coord), FadeInFromDown(r_label), ) self.wait() # Show theta degree_label.next_to(arc.get_start(), UR, SMALL_BUFF) line = r_line.copy() line.rotate(-theta_value, about_point=ORIGIN) line.set_color(theta_color) self.play( ShowCreation(arc), Rotate(line, theta_value, about_point=ORIGIN), VFadeInThenOut(line), ChangeDecimalToValue(degree_label, theta_value / DEGREES), ) self.play( degree_label.scale, 0.9, degree_label.move_to, theta_coord, FadeInFromDown(theta_label), ) self.wait() degree_cross = Cross(degree_label) radians_word = OldTexText("in radians") radians_word.scale(0.9) radians_word.set_color(theta_color) radians_word.add_background_rectangle() radians_word.add_updater( lambda m: m.next_to(theta_label, RIGHT, aligned_edge=DOWN) ) self.play(ShowCreation(degree_cross)) self.play( FadeOut( VGroup(degree_label, degree_cross), DOWN ), FadeIn(theta_coord) ) self.play(FadeIn(radians_word)) self.wait() # Move point around r_line.add_updater( lambda l: l.put_start_and_end_on(ORIGIN, dot.get_center()) ) theta_tracker = ValueTracker(0) theta_tracker.add_updater( lambda m: m.set_value(r_line.get_angle() % TAU) ) self.add(theta_tracker) arc.add_updater( lambda m: m.become( self.get_arc(theta_tracker.get_value()) ) ) self.add(coord_label) for angle in [PI - theta_value, PI - 0.001, -TAU + 0.002]: self.play( Rotate(dot, angle, about_point=ORIGIN), run_time=3, ) self.wait() self.play( FadeOut(coord_label), FadeOut(r_label), FadeOut(theta_label), FadeOut(radians_word), FadeOut(r_line), FadeOut(arc), FadeOut(dot), ) self.dot = dot self.r_line = r_line self.arc = arc self.theta_tracker = theta_tracker def show_all_nn_tuples(self): dot = self.dot arc = self.arc r_line = self.r_line theta_tracker = self.theta_tracker primes = generate_prime_list(20) non_primes = list(range(1, 20)) for prime in primes: non_primes.remove(prime) pp_points = VGroup(*map(self.get_nn_point, primes)) pp_points[0][1].shift(0.3 * LEFT + SMALL_BUFF * UP) np_points = VGroup(*map(self.get_nn_point, non_primes)) pp_points.set_color(TEAL) np_points.set_color(WHITE) pp_points.set_stroke(BLACK, 4, background=True) np_points.set_stroke(BLACK, 4, background=True) frame = self.camera_frame self.play( ApplyMethod(frame.scale, 2), LaggedStartMap( FadeInFromDown, pp_points ), run_time=2 ) self.wait() self.play(LaggedStartMap(FadeIn, np_points)) self.play(frame.scale, 0.5) self.wait() # Talk about 1 one = np_points[0] dot.move_to(self.get_polar_point(1, 1)) self.add(dot) theta_tracker.clear_updaters() theta_tracker.set_value(1) # r_line = Line(ORIGIN, one.dot.get_center()) # r_line.set_color(self.r_color) # pre_arc = Line(RIGHT, UR, color=self.r_color) # theta_tracker = ValueTracker(1) # arc = always_redraw(lambda: self.get_arc(theta_tracker.get_value())) one_rect = SurroundingRectangle(one) one_r_rect = SurroundingRectangle(one.label[1]) one_theta_rect = SurroundingRectangle(one.label[3]) one_theta_rect.set_color(self.theta_color) self.play(ShowCreation(one_rect)) self.add(r_line, np_points, pp_points, one_rect) self.play( ReplacementTransform(one_rect, one_r_rect), ShowCreation(r_line) ) self.wait() # self.play(TransformFromCopy(r_line, pre_arc)) # self.add(pre_arc, one) self.play( ReplacementTransform( Line(*r_line.get_start_and_end()), arc ), ReplacementTransform(one_r_rect, one_theta_rect) ) self.add(arc, one, one_theta_rect) self.play(FadeOut(one_theta_rect)) self.wait() # Talk about 2, 3 then 4 for n in [2, 3, 4]: self.play( Rotate(dot, 1, about_point=ORIGIN), theta_tracker.set_value, n, ) self.wait() self.play(dot.move_to, self.get_polar_point(n, n)) self.wait() # Zoom out and show spiral big_anim = Succession(*3 * [Animation(Mobject())], *it.chain(*[ [ AnimationGroup( Rotate(dot, 1, about_point=ORIGIN), ApplyMethod(theta_tracker.set_value, n), ), ApplyMethod(dot.move_to, self.get_polar_point(n, n)) ] for n in [5, 6, 7, 8, 9] ])) spiral = ParametricCurve( lambda t: self.get_polar_point(t, t), t_min=0, t_max=25, stroke_width=1.5, ) # self.add(spiral, pp_points, np_points) self.polar_grid.generate_target() for mob in self.polar_grid: if not isinstance(mob[0], Integer): mob.set_stroke(width=1) self.play( frame.scale, 3, big_anim, run_time=10, ) self.play( # ApplyMethod( # frame.scale, 1.5, # run_time=2, # rate_func=lambda t: smooth(t, 2) # ), ShowCreation( spiral, run_time=4, ), FadeOut(r_line), FadeOut(arc), FadeOut(dot), # MoveToTarget(self.polar_grid) ) self.wait() # def get_nn_point(self, n): point = self.get_polar_point(n, n) dot = Dot(point) coord_label = self.get_coord_label( n, n, include_background_rectangle=False, num_decimal_places=0 ) coord_label.next_to(dot, UR, buff=0) result = VGroup(dot, coord_label) result.dot = dot result.label = coord_label return result def get_polar_grid(self, radius=25): plane = self.plane axes = VGroup( Line(radius * DOWN, radius * UP), Line(radius * LEFT, radius * RIGHT), ) axes.set_stroke(width=2) circles = VGroup(*[ Circle(color=BLUE, stroke_width=1, radius=r) for r in range(1, int(radius)) ]) rays = VGroup(*[ Line( ORIGIN, radius * RIGHT, color=BLUE, stroke_width=1, ).rotate(angle, about_point=ORIGIN) for angle in np.arange(0, TAU, TAU / 16) ]) labels = VGroup(*[ Integer(n).scale(0.5).next_to( plane.c2p(n, 0), DR, SMALL_BUFF ) for n in range(1, int(radius)) ]) return VGroup( circles, rays, labels, axes, ) def get_coord_label(self, x=0, y=0, x_color=WHITE, y_color=WHITE, include_background_rectangle=True, **decimal_kwargs): coords = VGroup() for n in x, y: if isinstance(n, numbers.Number): coord = DecimalNumber(n, **decimal_kwargs) elif isinstance(n, str): coord = OldTex(n) else: raise Exception("Invalid type") coords.add(coord) x_coord, y_coord = coords x_coord.set_color(x_color) y_coord.set_color(y_color) coord_label = VGroup( OldTex("("), x_coord, OldTex(","), y_coord, OldTex(")") ) coord_label.arrange(RIGHT, buff=SMALL_BUFF) coord_label[2].align_to(coord_label[0], DOWN) coord_label.x_coord = x_coord coord_label.y_coord = y_coord if include_background_rectangle: coord_label.add_background_rectangle() return coord_label def get_polar_point(self, r, theta): plane = self.plane return plane.c2p(r * np.cos(theta), r * np.sin(theta)) def get_arc(self, theta, r=1, color=None): if color is None: color = self.theta_color return ParametricCurve( lambda t: self.get_polar_point(1 + 0.025 * t, t), t_min=0, t_max=theta, dt=0.25, color=color, stroke_width=3, ) # return Arc( # angle=theta, # radius=r, # stroke_color=color, # ) class IntroducePolarPlot(RefresherOnPolarCoordinates): def construct(self): self.plane = NumberPlane() grid = self.get_polar_grid() title = OldTexText("Polar coordinates") title.scale(3) title.set_stroke(BLACK, 10, background=True) title.to_edge(UP) self.add(grid, title) self.play( ShowCreation(grid, lag_ratio=0.1), run_time=3, ) class ReplacePolarCoordinatesWithPrimes(RefresherOnPolarCoordinates): def construct(self): coords, p_coords = [ self.get_coord_label( *pair, x_color=self.r_color, y_color=self.theta_color, ).scale(2) for pair in [("r", "\\theta"), ("p", "p")] ] p_coords.x_coord.set_color(GREY_B) p_coords.y_coord.set_color(GREY_B) some_prime = OldTexText("Some prime") some_prime.scale(1.5) some_prime.next_to(p_coords.get_left(), DOWN, buff=1.5) arrows = VGroup(*[ Arrow( some_prime.get_top(), coord.get_bottom(), stroke_width=5, tip_length=0.4 ) for coord in [p_coords.x_coord, p_coords.y_coord] ]) equals = OldTex("=") equals.next_to(p_coords, LEFT) self.add(coords) self.wait() self.play( coords.next_to, equals, LEFT, FadeIn(equals), FadeIn(p_coords), ) self.play( FadeInFromDown(some_prime), ShowCreation(arrows), ) self.wait() class IntroducePrimePatterns(SpiralScene): CONFIG = { "small_n_primes": 25000, "big_n_primes": 1000000, "axes_config": { "x_min": -25, "x_max": 25, "y_min": -25, "y_max": 25, }, "spiral_scale": 3e3, "ray_scale": 1e5, } def construct(self): self.slowly_zoom_out() self.show_clumps_of_four() def slowly_zoom_out(self): zoom_time = 8 prime_spiral = self.get_prime_p_spiral(self.small_n_primes) prime_spiral.set_stroke_width(25) self.add(prime_spiral) self.set_scale(3, spiral=prime_spiral) self.wait() self.set_scale( self.spiral_scale, spiral=prime_spiral, target_p_spiral_width=8, run_time=zoom_time, ) self.wait() self.remove(prime_spiral) prime_spiral = self.get_prime_p_spiral(self.big_n_primes) prime_spiral.set_stroke_width(8) self.set_scale( self.ray_scale, spiral=prime_spiral, target_p_spiral_width=4, run_time=zoom_time, ) self.wait() def show_clumps_of_four(self): line_groups = VGroup() for n in range(71): group = VGroup() for k in [-3, -1, 1, 3]: r = ((10 * n + k) * INV_113_MOD_710) % 710 group.add(self.get_arithmetic_sequence_line( 710, r, self.big_n_primes )) line_groups.add(group) line_groups.set_stroke(YELLOW, 2, opacity=0.5) self.play(ShowCreation(line_groups[0])) for g1, g2 in zip(line_groups, line_groups[1:5]): self.play( FadeOut(g1), ShowCreation(g2) ) self.play( FadeOut(line_groups[4]), LaggedStartMap( VFadeInThenOut, line_groups[4:], lag_ratio=0.5, run_time=5, ) ) self.wait() def get_arithmetic_sequence_line(self, N, r, max_val, skip_factor=5): line = VMobject() line.set_points_smoothly([ self.get_polar_point(x, x) for x in range(r, max_val, skip_factor * N) ]) return line class AskWhat(TeacherStudentsScene): def construct(self): screen = self.screen self.student_says( "I'm sorry,\\\\what?!?", target_mode="angry", look_at=screen, index=2, added_anims=[ self.teacher.change, "happy", screen, self.students[0].change, "confused", screen, self.students[1].change, "confused", screen, ] ) self.wait(3) class CountSpirals(IntroducePrimePatterns): CONFIG = { "count_sound": "pen_click.wav", } def construct(self): prime_spiral = self.get_prime_p_spiral(self.small_n_primes) self.add(prime_spiral) self.set_scale( self.spiral_scale, spiral=prime_spiral, run_time=0, ) spiral_lines = self.get_all_primitive_arithmetic_lines( 44, self.small_n_primes, INV_7_MOD_44, ) spiral_lines.set_stroke(YELLOW, 2, opacity=0.5) counts = VGroup() for n, spiral in zip(it.count(1), spiral_lines): count = Integer(n) count.move_to(spiral.point_from_proportion(0.25)) counts.add(count) run_time = 3 self.play( ShowIncreasingSubsets(spiral_lines), ShowSubmobjectsOneByOne(counts), run_time=run_time, rate_func=linear, ) self.add_count_clicks(len(spiral_lines), run_time) self.play( counts[-1].scale, 3, counts[-1].set_stroke, BLACK, 5, {"background": True}, ) self.wait() def get_all_primitive_arithmetic_lines(self, N, max_val, mult_factor): lines = VGroup() for r in range(1, N): if get_gcd(N, r) == 1: lines.add( self.get_arithmetic_sequence_line(N, (mult_factor * r) % N, max_val) ) return lines def add_count_clicks(self, N, time, rate_func=linear): alphas = np.arange(0, 1, 1 / N) if rate_func is linear: delays = time * alphas else: delays = time * np.array([ binary_search(rate_func, alpha, 0, 1) for alpha in alphas ]) for delay in delays: self.add_sound( self.count_sound, time_offset=-delay, gain=-15, ) class CountRays(CountSpirals): def construct(self): prime_spiral = self.get_prime_p_spiral(self.big_n_primes) self.add(prime_spiral) self.set_scale( self.ray_scale, spiral=prime_spiral, run_time=0, ) spiral_lines = self.get_all_primitive_arithmetic_lines( 710, self.big_n_primes, INV_113_MOD_710, ) spiral_lines.set_stroke(YELLOW, 2, opacity=0.5) counts = VGroup() for n, spiral in zip(it.count(1), spiral_lines): count = Integer(n) count.move_to(spiral.point_from_proportion(0.25)) counts.add(count) run_time = 6 self.play( ShowIncreasingSubsets(spiral_lines), ShowSubmobjectsOneByOne(counts), run_time=run_time, rate_func=smooth, ) self.add_count_clicks(len(spiral_lines), run_time, rate_func=smooth) self.play( counts[-1].scale, 3, counts[-1].set_stroke, BLACK, 5, {"background": True}, ) self.wait() self.play(FadeOut(spiral_lines)) self.wait() class AskAboutRelationToPrimes(TeacherStudentsScene): def construct(self): numbers = OldTexText("20, 280") arrow = Arrow(LEFT, RIGHT) primes = OldTexText("2, 3, 5, 7, 11, \\dots") q_marks = OldTexText("???") q_marks.set_color(YELLOW) group = VGroup(primes, arrow, numbers) group.arrange(RIGHT) q_marks.next_to(arrow, UP) group.add(q_marks) group.scale(1.5) group.next_to(self.pi_creatures, UP, LARGE_BUFF) self.play( self.change_students( *3 * ["maybe"], look_at=numbers, ), self.teacher.change, "maybe", numbers, ShowCreation(arrow), FadeIn(numbers, RIGHT) ) self.play( FadeIn(primes, LEFT), ) self.play( LaggedStartMap(FadeInFromDown, q_marks[0]), Blink(self.teacher) ) self.wait(3) class ZoomOutOnPrimesWithNumbers(IntroducePrimePatterns): CONFIG = { "n_labeled_primes": 1000, "big_n_primes": int(5e6), "thicknesses": [8, 3, 2], "thicker_target": False, } def construct(self): zoom_time = 20 prime_spiral = self.get_prime_p_spiral(self.big_n_primes) prime_spiral.set_stroke_width(25) prime_labels = self.get_prime_labels(self.n_labeled_primes) self.add(prime_spiral) self.add(prime_labels) scales = [self.spiral_scale, self.ray_scale, 5e5] thicknesses = self.thicknesses for scale, tp in zip(scales, thicknesses): kwargs = { "spiral": prime_spiral, "to_shrink": prime_labels, "run_time": zoom_time, "target_p_spiral_width": tp, } if self.thicker_target: kwargs["target_p_spiral_width"] += 1 self.set_scale(scale, **kwargs) prime_spiral.set_stroke_width(tp) self.wait() self.remove(prime_labels) class ThickZoomOutOnPrimesWithNumbers(ZoomOutOnPrimesWithNumbers): CONFIG = { # The only purpose of this scene is for overlay # with the last one to smooth things out. "thicker_target": True, } class HighlightGapsInSpirals(IntroducePrimePatterns): def construct(self): self.setup_spiral() max_n_tracker = ValueTracker(0) get_max_n = max_n_tracker.get_value gaps = always_redraw(lambda: VGroup(*[ self.get_highlighted_gap(n - 1, n + 1, get_max_n()) for n in [11, 33] ])) self.add(gaps) self.play(max_n_tracker.set_value, 25000, run_time=5) gaps.clear_updaters() self.play(FadeOut(gaps)) def setup_spiral(self): p_spiral = self.get_p_spiral(read_in_primes(self.small_n_primes)) self.add(p_spiral) self.set_scale( scale=self.spiral_scale, spiral=p_spiral, target_p_spiral_width=8, run_time=0, ) def get_highlighted_gap(self, n1, n2, max_n): l1, l2 = [ [ self.get_polar_point(k, k) for k in range(INV_7_MOD_44 * n, int(max_n), 5 * 44) ] for n in (n1, n2) ] if len(l1) == 0 or len(l2) == 0: return VectorizedPoint() result = VMobject() result.set_points_as_corners( [*l1, *reversed(l2)] ) result.make_smooth() result.set_stroke(GREY, width=0) result.set_fill(GREY_D, 1) return result class QuestionIsMisleading(TeacherStudentsScene): def construct(self): self.student_says( "Whoa, is this some\\\\divine hidden structure\\\\in the primes?", target_mode="surprised", index=0, added_anims=[ self.students[1].change, "pondering", self.students[2].change, "pondering", ] ) self.wait(2) self.students[0].bubble = None self.teacher_says( "Er...not exactly", bubble_config={"width": 3, "height": 2}, target_mode="guilty" ) self.wait(3) class JustPrimesLabel(Scene): def construct(self): text = OldTexText("Just the primes") text.scale(2) text.to_corner(UL) self.play(Write(text)) self.wait(3) self.play(FadeOut(text, DOWN)) class DirichletComingUp(Scene): def construct(self): image = ImageMobject("Dirichlet") image.set_height(3) words = OldTexText( "Coming up: \\\\", "Dirichlet's theorem", alignment="", ) words.set_color_by_tex("Dirichlet's", YELLOW) words.scale(1.5) words.next_to(image, RIGHT) words.set_stroke(BLACK, 8, background=True) Group(words, image).center() self.play( FadeIn(image, RIGHT), FadeIn(words, LEFT), ) self.wait() class ImagineYouFoundIt(TeacherStudentsScene): def construct(self): you = self.students[1] others = VGroup( self.students[0], self.students[2], self.teacher, ) bubble = you.get_bubble(direction=LEFT) bubble[-1].set_fill(GREEN_SCREEN, 1) you_label = OldTexText("You") arrow = Vector(DOWN) arrow.next_to(you, UP) you_label.next_to(arrow, UP) self.play( you.change, "hesitant", you_label, FadeInFromDown(you_label), GrowArrow(arrow), others.set_opacity, 0.25, ) self.play(Blink(you)) self.play( FadeIn(bubble), FadeOut(you_label), FadeOut(arrow), you.change, "pondering", ) self.play(you.look_at, bubble.get_corner(UR)) self.play(Blink(you)) self.wait() self.play(you.change, "hooray") self.play(Blink(you)) self.wait() self.play(you.change, "sassy", bubble.get_top()) self.wait(6) class ShowSpiralsForWholeNumbers(CountSpirals): CONFIG = { "max_prime": 10000, "scale_44": 1e3, "scale_6": 10, "n_labels": 100, "axes_config": { "x_min": -50, "x_max": 50, "y_min": -50, "y_max": 50, }, } def construct(self): self.zoom_out_with_whole_numbers() self.count_44_spirals() self.zoom_back_in_to_6() def zoom_out_with_whole_numbers(self): wholes = self.get_p_spiral(range(self.max_prime)) primes = self.get_prime_p_spiral(self.max_prime) wholes.set_color(YELLOW) wholes.set_stroke_width(20) primes.set_stroke_width(20) spiral = PGroup(wholes, primes) labels = self.get_labels(range(1, self.n_labels)) self.add(spiral, labels) self.set_scale( self.scale_44, spiral=spiral, to_shrink=labels, target_p_spiral_width=6, run_time=10, ) self.wait(2) self.spiral = spiral self.labels = labels def count_44_spirals(self): curr_spiral = self.spiral new_spirals = PGroup(*[ self.get_p_spiral(range( (INV_7_MOD_44 * k) % 44, self.max_prime, 44 )) for k in range(44) ]) new_spirals.set_color(YELLOW) counts = VGroup() for n, spiral in zip(it.count(1), new_spirals): count = Integer(n) count.scale(2) count.move_to(spiral.get_points()[50]) counts.add(count) self.remove(curr_spiral) run_time = 3 self.play( ShowIncreasingSubsets(new_spirals), ShowSubmobjectsOneByOne(counts), run_time=run_time, rate_func=linear, ) self.add_count_clicks(44, run_time) self.play( counts[-1].scale, 2, {"about_edge": DL}, counts[-1].set_stroke, BLACK, 5, {"background": True}, ) self.wait() self.play( FadeOut(counts[-1]), FadeOut(new_spirals), FadeIn(curr_spiral), ) def zoom_back_in_to_6(self): spiral = self.spiral self.rescale_labels(self.labels) self.set_scale( self.scale_6, spiral=spiral, to_shrink=self.labels, target_p_spiral_width=15, run_time=6, ) self.wait() def rescale_labels(self, labels): for i, label in zip(it.count(1), labels): height = label.get_height() label.set_height( 3 * height / (i**0.25), about_point=label.get_bottom() + 0.5 * label.get_height() * DOWN, ) class PrimeSpiralsAtScale1000(SpiralScene): def construct(self): spiral = self.get_prime_p_spiral(10000) self.add(spiral) self.set_scale( scale=1000, spiral=spiral, target_p_spiral_width=15, run_time=0, ) class SeparateIntoTwoQuestions(Scene): def construct(self): top_q = OldTexText("Why do", " primes", " cause", " spirals", "?") top_q.scale(2) top_q.to_edge(UP) q1 = OldTexText("Where do the\\\\", "spirals", " come from?") q2 = OldTexText("What happens when\\\\", "filtering to", " primes", "?") for q in q1, q2: q.scale(1.3) q.next_to(top_q, DOWN, LARGE_BUFF) q1.to_edge(LEFT) q1.set_color(YELLOW) q2.to_edge(RIGHT) q2.set_color(TEAL) v_line = DashedLine( top_q.get_bottom() + MED_SMALL_BUFF * DOWN, FRAME_HEIGHT * DOWN / 2, ) self.add(top_q) self.wait() for q, text in [(q1, "spirals"), (q2, "primes")]: self.play( top_q.get_part_by_tex(text).set_color, q.get_color(), TransformFromCopy( top_q.get_part_by_tex(text), q.get_part_by_tex(text), ), LaggedStartMap( FadeIn, filter( lambda m: m is not q.get_part_by_tex(text), q, ) ), ) self.wait() self.play(ShowCreation(v_line)) self.wait() class TopQuestionCross(Scene): def construct(self): top_q = OldTexText("Why do", " primes", " cause", " spirals", "?") top_q.scale(2) top_q.to_edge(UP) cross = Cross(top_q) self.play(ShowCreation(cross)) self.wait() class ExplainSixSpirals(ShowSpiralsForWholeNumbers): CONFIG = { "max_N": 150, } def construct(self): self.add_spirals_and_labels() self.comment_on_arms() self.talk_though_multiples_of_six() self.limit_to_primes() def add_spirals_and_labels(self): max_N = self.max_N spiral = self.get_v_spiral(range(max_N)) primes = generate_prime_list(max_N) spiral.set_color(YELLOW) for n, box in enumerate(spiral): if n in primes: box.set_color(TEAL) labels = self.get_labels(range(max_N)) self.add(spiral, labels) self.set_scale( spiral=spiral, scale=self.scale_6, to_shrink=labels, min_box_width=0.08, run_time=0, ) self.rescale_labels(labels) self.spiral = spiral self.labels = labels def comment_on_arms(self): labels = self.labels spiral = self.spiral label_groups = VGroup(*[labels[k::6] for k in range(6)]) spiral_groups = VGroup(*[spiral[k::6] for k in range(6)]) six_groups = VGroup(*[ VGroup(sg, lg) for sg, lg in zip(spiral_groups, label_groups) ]) rect_groups = VGroup(*[ VGroup(*[ SurroundingRectangle(label, stroke_width=2, buff=0.05) for label in group ]) for group in label_groups ]) formula = VGroup( *Tex("6k", "+"), Integer(1) ) formula.arrange(RIGHT, buff=SMALL_BUFF) formula.scale(2) formula.set_color(YELLOW) formula.to_corner(UL) formula_rect = SurroundingRectangle(formula, buff=MED_LARGE_BUFF - SMALL_BUFF) formula_rect.set_fill(GREY_D, opacity=1) formula_rect.set_stroke(WHITE, 1) # 6k self.add(six_groups, formula_rect) self.play( LaggedStartMap(ShowCreation, rect_groups[0]), FadeInFromDown(formula_rect), FadeInFromDown(formula[0]), *[ ApplyMethod(group.set_opacity, 0.25) for group in six_groups[1:] ], run_time=2 ) self.play( LaggedStartMap( FadeOut, rect_groups[0], run_time=1, ), ) self.wait() # 6k + 1 self.play( six_groups[0].set_opacity, 0.25, six_groups[1].set_opacity, 1, FadeIn(formula[1:]), ) self.wait(2) # 6k + m for m in [2, 3, 4, 5]: self.play( six_groups[m - 1].set_opacity, 0.25, six_groups[m].set_opacity, 1, ChangeDecimalToValue(formula[2], m), ) self.wait() self.play( six_groups[5].set_opacity, 0.25, six_groups[0].set_opacity, 1, formula[1:].set_opacity, 0, ) self.wait() self.six_groups = six_groups self.formula = VGroup(formula_rect, *formula) def talk_though_multiples_of_six(self): spiral = self.spiral labels = self.labels formula = self.formula # Zoom in self.add(spiral, labels, formula) self.set_scale( 4.5, spiral=spiral, to_shrink=labels, run_time=2, ) self.wait() boxes = VGroup(*[ VGroup(b.copy(), l.copy()) for b, l in zip(spiral, labels) ]) boxes.set_opacity(1) lines = VGroup(*[ Line(ORIGIN, box[0].get_center()) for box in boxes ]) lines.set_stroke(GREY_B, width=2) arcs = self.get_arcs(range(31)) trash = VGroup() def show_steps(start, stop, added_anims=None, run_time=2): if added_anims is None: added_anims = [] self.play( *[ ShowSubmobjectsOneByOne(group[start:stop + 1]) for group in [arcs, boxes, lines] ], *added_anims, rate_func=linear, run_time=run_time, ) self.add_count_clicks(N=6, time=run_time) trash.add(VGroup(arcs[stop], boxes[stop], lines[stop])) # Writing next to the 6 six = boxes[6][1] rhs = OldTex( "\\text{radians}", "\\approx", "2\\pi", "\\text{ radians}" ) rhs.next_to(six, RIGHT, 2 * SMALL_BUFF, aligned_edge=DOWN) rhs.add_background_rectangle() tau_value = OldTex("{:.8}\\dots".format(TAU)) tau_value.next_to(rhs[3], UP, aligned_edge=LEFT) # Animations show_steps(0, 6, run_time=3) self.wait() self.play(FadeIn(rhs)) self.wait() self.play(FadeInFromDown(tau_value)) self.wait(2) show_steps(6, 12) self.wait() show_steps(12, 18) self.wait() # Zoom out frame = self.camera_frame frame.add(formula) show_steps(18, 24, added_anims=[frame.scale, 2.5]) self.wait() show_steps(24, 30) self.wait(2) self.play( FadeOut(trash), FadeOut(rhs), FadeOut(tau_value), spiral.set_opacity, 1, labels.set_opacity, 1, formula[1].set_opacity, 0, ) def limit_to_primes(self): formula = self.formula formula_rect, six_k, plus, m_sym = formula spiral = self.spiral labels = self.labels six_groups = self.six_groups frame = self.camera_frame boxes = VGroup(*[ VGroup(b, l) for b, l in zip(spiral, labels) ]) prime_numbers = read_in_primes(self.max_N) primes = VGroup() non_primes = VGroup() for n, box in enumerate(boxes): if n in prime_numbers: primes.add(box) else: non_primes.add(box) prime_label = OldTexText("Primes") prime_label.set_color(TEAL) prime_label.match_width(VGroup(six_k, m_sym)) prime_label.move_to(six_k, LEFT) # Show just primes self.add(primes, non_primes, formula) self.play( FadeIn(prime_label), non_primes.set_opacity, 0.25, ) frame.add(prime_label) self.play( frame.scale, 1.5, run_time=2, ) self.wait(2) cross_groups = VGroup() for group in six_groups: group.save_state() boxes, labels = group cross_group = VGroup() for label in labels: cross_group.add(Cross(label)) cross_groups.add(cross_group) cross_groups.set_stroke(width=3) cross_groups[2].remove(cross_groups[2][0]) cross_groups[3].remove(cross_groups[3][0]) # Show multiples of 6 for r in [0, 2, 4, 3]: arm = six_groups[r] crosses = cross_groups[r] self.add(arm, frame) anims = [arm.set_opacity, 1] if r == 0: anims += [ prime_label.set_opacity, 0, six_k.set_opacity, 1 ] elif r == 2: m_sym.set_value(2) anims += [ plus.set_opacity, 1, m_sym.set_opacity, 1, ] else: anims.append(ChangeDecimalToValue(m_sym, r)) self.play(*anims) self.add(*crosses, frame) self.play( LaggedStartMap(ShowCreation, crosses), ) self.wait() # Fade forbidden groups to_fade = VGroup(*[ VGroup(six_groups[r], cross_groups[r]) for r in (0, 2, 3, 4) ]) self.add(to_fade, frame) self.play( to_fade.set_opacity, 0.25, VGroup(six_k, plus, m_sym).set_opacity, 0, prime_label.set_opacity, 1, ) self.wait() # def arc_func(self, t): r = 0.25 + 0.02 * t return r * np.array([np.cos(t), np.sin(t), 0]) def get_arc(self, n): if n == 0: return VectorizedPoint() return ParametricCurve( self.arc_func, t_min=0, t_max=n, step_size=0.1, stroke_width=2, stroke_color=PINK, ) def get_arcs(self, sequence): return VGroup(*map(self.get_arc, sequence)) class IntroduceResidueClassTerminology(Scene): def construct(self): self.add_title() self.add_sequences() self.add_terms() self.highlight_example() self.simple_english() def add_title(self): title = OldTexText("Overly-fancy ", "terminology") title.scale(1.5) title.to_edge(UP, buff=MED_SMALL_BUFF) underline = Line().match_width(title) underline.next_to(title, DOWN, SMALL_BUFF) pre_title = OldTexText("Terminology") pre_title.replace(title, dim_to_match=1) self.play(FadeInFromDown(pre_title)) self.wait() title[0].set_color(BLUE) underline.set_color(BLUE) self.play( ReplacementTransform(pre_title[0], title[1]), FadeIn(title[0], RIGHT), GrowFromCenter(underline) ) self.play( title[0].set_color, WHITE, underline.set_color, WHITE, ) self.wait() title.add(underline) self.add(title) self.title = title self.underline = underline def add_sequences(self): sequences = VGroup() n_terms = 7 for r in range(6): sequence = VGroup(*[ Integer(6 * k + r) for k in range(n_terms) ]) sequence.arrange(RIGHT, buff=0.4) sequences.add(sequence) sequences.arrange(DOWN, buff=0.7, aligned_edge=LEFT) for sequence in sequences: for s1, s2 in zip(sequence[:n_terms], sequences[-1]): s1.align_to(s2, RIGHT) commas = VGroup() for num in sequence[:-1]: comma = OldTexText(",") comma.next_to(num.get_corner(DR), RIGHT, SMALL_BUFF) commas.add(comma) dots = OldTex("\\dots") dots.next_to(sequence.get_corner(DR), RIGHT, SMALL_BUFF) sequence.numbers = VGroup(*sequence) sequence.commas = commas sequence.dots = dots sequence.add(*commas) sequence.add(dots) sequence.sort(lambda p: p[0]) labels = VGroup(*[ OldTex("6k + {}:".format(r)) for r in range(6) ]) labels.set_color(YELLOW) for label, sequence in zip(labels, sequences): label.next_to(sequence, LEFT, MED_LARGE_BUFF) group = VGroup(sequences, labels) group.to_edge(LEFT).to_edge(DOWN, buff=MED_LARGE_BUFF) self.add(labels) self.play(LaggedStart(*[ LaggedStartMap( FadeInFrom, sequence, lambda m: (m, LEFT), ) for sequence in sequences ], lag_ratio=0.3)) self.wait() self.sequences = sequences self.sequence_labels = labels def add_terms(self): sequences = self.sequences terms = OldTexText( "``", "Residue\\\\", "classes\\\\", "mod ", "6''" ) terms.scale(1.5) terms.set_color(YELLOW) terms.to_edge(RIGHT) res_brace = Brace(terms.get_part_by_tex("Residue"), UP) remainder = OldTexText("Remainder") remainder.next_to(res_brace, UP, SMALL_BUFF) mod_brace = Brace(terms.get_part_by_tex("mod"), DOWN) mod_def = OldTexText( "``where the thing\\\\you divide by is''" ) mod_def.next_to(mod_brace, DOWN, SMALL_BUFF) arrows = VGroup(*[ Arrow(terms.get_left(), sequence.get_right()) for sequence in sequences ]) arrows.set_color(YELLOW) self.play( FadeIn(terms), LaggedStartMap(ShowCreation, arrows), ) self.wait() self.play( GrowFromCenter(res_brace), FadeInFromDown(remainder), ) self.wait() self.play(GrowFromCenter(mod_brace)) self.play(Write(mod_def)) self.wait() self.terminology = VGroup( terms, res_brace, remainder, mod_brace, mod_def, arrows ) def highlight_example(self): sequences = self.sequences labels = self.sequence_labels r = 2 k = 3 sequence = sequences[r] label = labels[r] r_tex = label[0][3] n_rects = VGroup(*[ SurroundingRectangle(num) for num in sequence.numbers ]) r_rect = SurroundingRectangle(r_tex) n_rects.set_color(RED) r_rect.set_color(RED) n_rect = n_rects.submobjects.pop(k) self.play(ShowCreation(n_rect)) self.wait() self.play( TransformFromCopy(n_rect, r_rect, path_arc=30 * DEGREES) ) self.wait() self.play(ShowCreation(n_rects)) self.wait() self.play( ShowCreationThenFadeOut( self.underline.copy().set_color(PINK), ) ) def simple_english(self): terminology = self.terminology sequences = self.sequences randy = Randolph() randy.set_height(2) randy.flip() randy.to_corner(DR) new_phrase = OldTexText("Everything 2 above\\\\a multiple of 6") new_phrase.scale(1.2) new_phrase.set_color(RED_B) new_phrase.next_to(sequences[2]) self.play( FadeOut(terminology), FadeIn(new_phrase), VFadeIn(randy), randy.change, "sassy" ) self.wait() self.play(randy.change, "angry") for x in range(2): self.play(Blink(randy)) self.wait() self.play( FadeOut(new_phrase), FadeIn(terminology), FadeOut(randy, DOWN) ) self.wait() self.wait(6) class SimpleLongDivision(Scene): CONFIG = { "camera_config": { "background_color": GREY_E } } def construct(self): divisor = Integer(6) num = Integer(20) quotient = Integer(num.get_value() // divisor.get_value()) to_subtract = Integer(-1 * quotient.get_value() * divisor.get_value()) remainder = Integer(num.get_value() + to_subtract.get_value()) div_sym = VMobject() div_sym.set_points_as_corners([0.2 * UP, UP, UP + 3 * RIGHT]) divisor.next_to(div_sym, LEFT, MED_SMALL_BUFF) num.next_to(divisor, RIGHT, MED_LARGE_BUFF) to_subtract.next_to(num, DOWN, buff=MED_LARGE_BUFF, aligned_edge=RIGHT) h_line = Line(LEFT, RIGHT) h_line.next_to(to_subtract, DOWN, buff=MED_SMALL_BUFF) remainder.next_to(to_subtract, DOWN, buff=MED_LARGE_BUFF, aligned_edge=RIGHT) quotient.next_to(num, UP, buff=MED_LARGE_BUFF, aligned_edge=RIGHT) remainder_rect = SurroundingRectangle(remainder) remainder_rect.set_color(RED) frame = self.camera_frame frame.scale(0.7, about_point=ORIGIN) divisor.set_color(YELLOW) num.set_color(RED) self.add(divisor) self.add(div_sym) self.add(num) self.play(FadeInFromDown(quotient)) self.play( TransformFromCopy(divisor, to_subtract.copy()), TransformFromCopy(quotient, to_subtract), ) self.play(ShowCreation(h_line)) self.play(Write(remainder)) self.play(ShowCreation(remainder_rect)) self.wait() self.play(FadeOut(remainder_rect)) class ZoomOutWords(Scene): def construct(self): words = OldTexText("Zoom out!") words.scale(3) self.play(FadeInFromLarge(words)) self.wait() class Explain44Spirals(ExplainSixSpirals): CONFIG = { "max_N": 3000, "initial_scale": 10, "zoom_factor_1": 7, "zoom_factor_2": 3, "n_labels": 80, } def construct(self): self.add_spirals_and_labels() self.show_44_steps() self.show_top_right_arithmetic() self.show_pi_approx_arithmetic() self.count_by_44() def add_spirals_and_labels(self): max_N = self.max_N wholes = self.get_p_spiral(range(max_N)) primes = self.get_prime_p_spiral(max_N) wholes.set_color(YELLOW) spiral = PGroup(wholes, primes) labels = self.get_labels(range(self.n_labels)) self.add(spiral, labels) self.set_scale( spiral=spiral, scale=self.initial_scale, to_shrink=labels, target_p_spiral_width=10, run_time=0, ) self.rescale_labels(labels) self.spiral = spiral self.labels = labels def show_44_steps(self): labels = self.labels ns = range(45) points = [self.get_polar_point(n, n) for n in ns] lines = VGroup(*[ Line(ORIGIN, point) for point in points ]) lines.set_stroke(WHITE, 2) arcs = self.get_arcs(ns) opaque_labels = labels.copy() labels.set_opacity(0.25) trash = VGroup() def show_steps(start, stop, added_anims=None, run_time=2): if added_anims is None: added_anims = [] def rate_func(t): return smooth(t, 2) self.play( *[ ShowSubmobjectsOneByOne(group[start:stop + 1]) for group in [arcs, opaque_labels, lines] ], *added_anims, rate_func=rate_func, run_time=run_time, ) self.add_count_clicks( N=(stop - start), time=run_time, rate_func=rate_func ) trash.add(arcs[stop], opaque_labels[stop], lines[stop]) show_steps(0, 6) self.wait() show_steps(6, 44, added_anims=[FadeOut(trash)], run_time=4) self.wait() self.spiral_group = trash[-3:] def show_top_right_arithmetic(self): labels = self.labels ff = labels[44].copy() ff.generate_target() radians = OldTexText("radians") ff.target.scale(1.5) ff.target.set_opacity(1) unit_conversion = OldTex( "/\\,", "\\left(", "2\\pi", "{\\text{radians}", "\\over", "\\text{rotations}}", "\\right)" ) unit_conversion[1:].scale(0.7, about_edge=LEFT) top_line = VGroup(ff.target, radians, unit_conversion) top_line.arrange(RIGHT) ff.target.align_to(radians, DOWN) top_line.to_corner(UR, buff=0.4) next_line = OldTex( "=", "44", "/", "2\\pi", "\\text{ rotations}" ) next_line.next_to(top_line, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) brace = Brace(next_line[1:4], DOWN, buff=SMALL_BUFF) value = DecimalNumber(44 / TAU, num_decimal_places=8, show_ellipsis=True) value.next_to(brace, DOWN) rect = SurroundingRectangle(VGroup(top_line, value), buff=MED_SMALL_BUFF) rect.set_stroke(WHITE, 2) rect.set_fill(GREY_E, 0.9) self.play(MoveToTarget(ff)) top_line.add(ff) self.play(FadeIn(radians, LEFT)) self.wait() self.add(rect, top_line, unit_conversion) self.play( FadeIn(rect), FadeIn(unit_conversion), ) self.wait() self.play( TransformFromCopy(ff, next_line.get_part_by_tex("44")), FadeIn(next_line.get_part_by_tex("=")), TransformFromCopy( unit_conversion.get_part_by_tex("/"), next_line.get_part_by_tex("/"), ), TransformFromCopy( unit_conversion.get_part_by_tex("rotations"), next_line.get_part_by_tex("rotations"), ), TransformFromCopy( unit_conversion.get_part_by_tex("2\\pi"), next_line.get_part_by_tex("2\\pi"), ), ) self.wait() self.play( GrowFromCenter(brace), Write(value), ) self.wait() self.right_arithmetic = VGroup( rect, top_line, next_line, brace, value ) def show_pi_approx_arithmetic(self): ra = self.right_arithmetic ra_rect, ra_l1, ra_l2, ra_brace, ra_value = ra lines = VGroup( OldTex("{44", "\\over", "2\\pi}", "\\approx", "7"), OldTex("\\Leftrightarrow"), OldTex("{44", "\\over", "7}", "\\approx", "2\\pi"), OldTex("{22", "\\over", "7}", "\\approx", "\\pi"), ) lines.arrange(RIGHT, buff=MED_SMALL_BUFF) lines.to_corner(UL) lines[3].move_to(lines[2], LEFT) rect = SurroundingRectangle(lines, buff=MED_LARGE_BUFF) rect.match_style(ra_rect) self.play( FadeIn(rect), LaggedStart( TransformFromCopy(ra_l2[1:4], lines[0][:3]), FadeIn(lines[0].get_part_by_tex("approx")), TransformFromCopy(ra_value[0], lines[0].get_part_by_tex("7")), run_time=2, ) ) self.wait() l0_copy = lines[0].copy() self.play( l0_copy.move_to, lines[2], Write(lines[1]), ) self.play( LaggedStart(*[ ReplacementTransform( l0_copy.get_part_by_tex(tex), lines[2].get_part_by_tex(tex), path_arc=60 * DEGREES, ) for tex in ["44", "\\over", "7", "approx", "2\\pi"] ], lag_ratio=0.1, run_time=2), ) self.wait() self.play(Transform(lines[2], lines[3])) self.wait() left_arithmetic = VGroup(rect, lines[:3]) self.play( LaggedStart( FadeOut(self.spiral_group[0]), FadeOut(left_arithmetic), FadeOut(self.right_arithmetic), ) ) def count_by_44(self): ff_label, ff_line = self.spiral_group[1:] faded_labels = self.labels frame = self.camera_frame n_values = 100 mod = 44 values = range(mod, n_values * mod, mod) points = [ self.get_polar_point(n, n) for n in values ] p2l_tracker = ValueTracker( get_norm(ff_label.get_bottom() - points[0]) ) get_p2l = p2l_tracker.get_value l_height_ratio_tracker = ValueTracker( ff_label.get_height() / frame.get_height() ) get_l_height_ratio = l_height_ratio_tracker.get_value n_labels = 10 labels = VGroup(*[Integer(n) for n in values[:n_labels]]) for label, point in zip(labels, points): label.point = point label.add_updater( lambda l: l.set_height( frame.get_height() * get_l_height_ratio() ) ) label.add_updater( lambda l: l.move_to( l.point + get_p2l() * UP, DOWN, ) ) labels.set_stroke(BLACK, 2, background=True) lines = VGroup(ff_line) for p1, p2 in zip(points, points[1:]): lines.add(Line(p1, p2)) lines.match_style(ff_line) self.remove(self.spiral_group) self.remove(faded_labels[44]) self.play( frame.scale, self.zoom_factor_1, p2l_tracker.set_value, 1, l_height_ratio_tracker.set_value, 0.025, FadeOut( ff_label, rate_func=squish_rate_func(smooth, 0, 1 / 8), ), LaggedStart( *2 * [Animation(Group())], # Weird and dumb *map(FadeIn, labels), lag_ratio=0.5, ), LaggedStart( *2 * [Animation(Group())], *map(ShowCreation, lines[:len(labels)]), lag_ratio=1, ), run_time=8, ) self.play( frame.scale, self.zoom_factor_2, l_height_ratio_tracker.set_value, 0.01, ShowCreation(lines[len(labels):]), run_time=8, ) self.ff_spiral_lines = lines self.ff_spiral_labels = labels # def arc_func(self, t): r = 0.1 * t return r * np.array([np.cos(t), np.sin(t), 0]) class Label44Spirals(Explain44Spirals): def construct(self): self.setup_spirals() self.enumerate_spirals() def setup_spirals(self): max_N = self.max_N mod = 44 primes = read_in_primes(max_N) spirals = VGroup() for r in range(mod): ns = range(r, max_N, mod) spiral = self.get_v_spiral(ns, box_width=1) for box, n in zip(spiral, ns): box.n = n if n in primes: box.set_color(TEAL) else: box.set_color(YELLOW) spirals.add(spiral) self.add(spirals) scale = np.prod([ self.initial_scale, self.zoom_factor_1, self.zoom_factor_2, ]) self.set_scale( spiral=VGroup(*it.chain(*spirals)), scale=scale, run_time=0 ) self.spirals = spirals def enumerate_spirals(self): spirals = self.spirals labels = self.get_spiral_arm_labels(spirals) self.play( spirals[1:].set_opacity, 0.25, FadeIn(labels[0]), ) self.wait() for n in range(10): arc = Arc( start_angle=n + 0.2, angle=0.9, radius=1.5, ) arc.add_tip() mid_point = arc.point_from_proportion(0.5) r_label = OldTexText("1 radian") # r_label.rotate( # angle_of_vector(arc.get_end() - arc.get_start()) - PI # ) r_label.next_to(mid_point, normalize(mid_point)) if n > 2: r_label.set_opacity(0) self.play( ShowCreation(arc), FadeIn(r_label), spirals[n + 1].set_opacity, 1, TransformFromCopy(labels[n], labels[n + 1]) ) self.play( FadeOut(arc), FadeOut(r_label), spirals[n].set_opacity, 0.25, FadeOut(labels[n]), ) # def get_spiral_arm_labels(self, spirals, index=15): mod = 44 labels = VGroup(*[ VGroup( *Tex("44k", "+"), Integer(n) ).arrange(RIGHT, buff=SMALL_BUFF) for n in range(mod) ]) labels[0][1:].set_opacity(0) labels.scale(1.5) labels.set_color(YELLOW) for label, spiral in zip(labels, spirals): box = spiral[index] vect = rotate_vector(box.get_center(), 90 * DEGREES) label.next_to(box, normalize(vect), SMALL_BUFF) labels[0].shift(UR + 1.25 * RIGHT) return labels class ResidueClassMod44Label(Scene): def construct(self): text = OldTexText( "``Residue class mod 44''" ) text.scale(2) text.to_corner(UL) self.play(Write(text)) self.wait() class EliminateNonPrimativeResidueClassesOf44(Label44Spirals): CONFIG = { "max_N": 7000, } def construct(self): self.setup_spirals() self.eliminate_classes() self.zoom_out() self.filter_to_primes() def eliminate_classes(self): spirals = self.spirals labels = self.get_spiral_arm_labels(spirals) # Eliminate factors of 2 self.play( spirals[1:].set_opacity, 0.5, FadeIn(labels[0]), ) self.wait() self.play( FadeOut(spirals[0]), FadeOut(labels[0]), ) for n in range(2, 8, 2): self.play( FadeIn(labels[n]), spirals[n].set_opacity, 1, ) self.play(FadeOut(VGroup(labels[n], spirals[n]))) words = OldTexText("All even numbers") words.scale(1.5) words.to_corner(UL) self.play( LaggedStart(*[ ApplyMethod(spiral.set_opacity, 1) for spiral in spirals[8::2] ], lag_ratio=0.01), FadeIn(words), ) self.play( FadeOut(words), FadeOut(spirals[8::2]) ) self.wait() # Eliminate factors of 11 for k in [11, 33]: self.play( spirals[k].set_opacity, 1, FadeIn(labels[k]) ) self.wait() self.play( FadeOut(spirals[k]), FadeOut(labels[k]), ) admissible_spirals = VGroup(*[ spiral for n, spiral in enumerate(spirals) if n % 2 != 0 and n % 11 != 0 ]) self.play(admissible_spirals.set_opacity, 1) self.admissible_spirals = admissible_spirals def zoom_out(self): frame = self.camera_frame admissible_spirals = self.admissible_spirals admissible_spirals.generate_target() for spiral in admissible_spirals.target: for box in spiral: box.scale(3) self.play( frame.scale, 4, MoveToTarget(admissible_spirals), run_time=3, ) def filter_to_primes(self): admissible_spirals = self.admissible_spirals frame = self.camera_frame primes = read_in_primes(self.max_N) to_fade = VGroup(*[ box for spiral in admissible_spirals for box in spiral if box.n not in primes ]) words = OldTexText("Just the primes") words.set_height(0.1 * frame.get_height()) words.next_to(frame.get_corner(UL), DR, LARGE_BUFF) self.play( LaggedStartMap(FadeOut, to_fade, lag_ratio=2 / len(to_fade)), FadeIn(words), ) self.wait() class IntroduceTotientJargon(TeacherStudentsScene): def construct(self): self.add_title() self.eliminate_non_coprimes() def add_title(self): self.teacher_says( "More jargon!", target_mode="hooray", ) self.play_all_student_changes("erm") words = self.teacher.bubble.content words.generate_target() words.target.scale(1.5) words.target.center().to_edge(UP, buff=MED_SMALL_BUFF) words.target.set_color(BLUE) underline = Line(LEFT, RIGHT) underline.match_width(words.target) underline.next_to(words.target, DOWN, SMALL_BUFF) underline.scale(1.2) self.play( MoveToTarget(words), FadeOut(self.teacher.bubble), LaggedStart(*[ FadeOut(pi, 4 * DOWN) for pi in self.pi_creatures ]), ShowCreation(underline) ) def eliminate_non_coprimes(self): number_grid = VGroup(*[ VGroup(*[ Integer(n) for n in range(11 * k, 11 * (k + 1)) ]).arrange(DOWN) for k in range(4) ]).arrange(RIGHT, buff=1) numbers = VGroup(*it.chain(*number_grid)) numbers.set_height(6) numbers.move_to(4 * LEFT) numbers.to_edge(DOWN) evens = VGroup(*filter( lambda nm: nm.get_value() % 2 == 0, numbers )) div11 = VGroup(*filter( lambda nm: nm.get_value() % 11 == 0, numbers )) coprimes = VGroup(*filter( lambda nm: nm not in evens and nm not in div11, numbers )) words = OldTexText( "Which ones ", "don't\\\\", "share any factors\\\\", "with ", "44", alignment="" ) words.scale(1.5) words.next_to(ORIGIN, RIGHT) ff = words.get_part_by_tex("44") ff.set_color(YELLOW) ff.generate_target() # Show coprimes self.play( ShowIncreasingSubsets(numbers, run_time=3), FadeIn(words, LEFT) ) self.wait() for group in evens, div11: rects = VGroup(*[ SurroundingRectangle(number, color=RED) for number in group ]) self.play(LaggedStartMap(ShowCreation, rects, run_time=1)) self.play( LaggedStart(*[ ApplyMethod(number.set_opacity, 0.2) for number in group ]), LaggedStartMap(FadeOut, rects), run_time=1 ) self.wait() # Rearrange words dsf = words[1:3] dsf.generate_target() dsf.target.arrange(RIGHT) dsf.target[0].align_to(dsf.target[1][0], DOWN) example = numbers[35].copy() example.generate_target() example.target.match_height(ff) num_pair = VGroup( ff.target, OldTexText("and").scale(1.5), example.target, ) num_pair.arrange(RIGHT) num_pair.move_to(words.get_top(), DOWN) dsf.target.next_to(num_pair, DOWN, MED_LARGE_BUFF) phrase1 = OldTexText("are ", "``relatively prime''") phrase2 = OldTexText("are ", "``coprime''") for phrase in phrase1, phrase2: phrase.scale(1.5) phrase.move_to(dsf.target) phrase[1].set_color(BLUE) phrase.arrow = OldTex("\\Updownarrow") phrase.arrow.scale(1.5) phrase.arrow.next_to(phrase, DOWN, 2 * SMALL_BUFF) phrase.rect = SurroundingRectangle(phrase[1]) phrase.rect.set_stroke(BLUE) self.play( FadeOut(words[0]), FadeOut(words[3]), MoveToTarget(dsf), MoveToTarget(ff), GrowFromCenter(num_pair[1]), ) self.play( MoveToTarget(example, path_arc=30 * DEGREES), ) self.wait() self.play( dsf.next_to, phrase1.arrow, DOWN, SMALL_BUFF, GrowFromEdge(phrase1.arrow, UP), GrowFromCenter(phrase1), ShowCreation(phrase1.rect) ) self.play(FadeOut(phrase1.rect)) self.wait() self.play( VGroup(dsf, phrase1, phrase1.arrow).next_to, phrase2.arrow, DOWN, SMALL_BUFF, GrowFromEdge(phrase2.arrow, UP), GrowFromCenter(phrase2), ShowCreation(phrase2.rect) ) self.play(FadeOut(phrase2.rect)) self.wait() # Count through coprimes coprime_rects = VGroup(*map(SurroundingRectangle, coprimes)) coprime_rects.set_stroke(BLUE, 2) example_anim = UpdateFromFunc( example, lambda m: m.set_value(coprimes[len(coprime_rects) - 1].get_value()) ) self.play( ShowIncreasingSubsets(coprime_rects, int_func=np.ceil), example_anim, run_time=3, rate_func=linear, ) self.wait() # Show totient function words_to_keep = VGroup(ff, num_pair[1], example, phrase2) to_fade = VGroup(phrase2.arrow, phrase1, phrase1.arrow, dsf) totient = OldTex("\\phi", "(", "44", ")", "=", "20") totient.set_color_by_tex("44", YELLOW) totient.scale(1.5) totient.move_to(num_pair, UP) phi = totient.get_part_by_tex("phi") rhs = Integer(20) rhs.replace(totient[-1], dim_to_match=1) totient.submobjects[-1] = rhs self.play( words_to_keep.to_edge, DOWN, MaintainPositionRelativeTo(to_fade, words_to_keep), VFadeOut(to_fade), ) self.play(FadeIn(totient)) self.wait() # Label totient brace = Brace(phi, DOWN) etf = OldTexText("Euler's totient function") etf.next_to(brace, DOWN) etf.shift(RIGHT) self.play( GrowFromCenter(brace), FadeIn(etf, UP) ) self.wait() self.play( ShowIncreasingSubsets(coprime_rects), UpdateFromFunc( rhs, lambda m: m.set_value(len(coprime_rects)), ), example_anim, rate_func=linear, run_time=3, ) self.wait() # Show totatives totient_group = VGroup(totient, brace, etf) for cp, rect in zip(coprimes, coprime_rects): cp.add(rect) self.play( coprimes.arrange, RIGHT, {"buff": SMALL_BUFF}, coprimes.set_width, FRAME_WIDTH - 1, coprimes.move_to, 2 * UP, FadeOut(evens), FadeOut(div11[1::2]), FadeOutAndShiftDown(words_to_keep), totient_group.center, totient_group.to_edge, DOWN, ) totatives = OldTexText("``Totatives''") totatives.scale(2) totatives.set_color(BLUE) totatives.move_to(ORIGIN) arrows = VGroup(*[ Arrow(totatives.get_top(), coprime.get_bottom()) for coprime in coprimes ]) arrows.set_color(WHITE) self.play( FadeIn(totatives), LaggedStartMap(VFadeInThenOut, arrows, run_time=4, lag_ratio=0.05) ) self.wait(2) class TwoUnrelatedFacts(Scene): def construct(self): self.add_title() self.show_columns() def add_title(self): title = OldTexText("Two (unrelated) bits of number theory") title.set_width(FRAME_WIDTH - 1) title.to_edge(UP) h_line = Line() h_line.match_width(title) h_line.next_to(title, DOWN, SMALL_BUFF) h_line.set_stroke(GREY_B) self.play( FadeIn(title), ShowCreation(h_line), ) self.h_line = h_line def show_columns(self): h_line = self.h_line v_line = Line( h_line.get_center() + MED_SMALL_BUFF * DOWN, FRAME_HEIGHT * DOWN / 2, ) v_line.match_style(h_line) approx = OldTex( "{44 \\over 7} \\approx 2\\pi" ) approx.scale(1.5) approx.next_to( h_line.point_from_proportion(0.25), DOWN, MED_LARGE_BUFF, ) mod = 44 n_terms = 9 residue_classes = VGroup() prime_numbers = read_in_primes(1000) primes = VGroup() non_primes = VGroup() for r in range(mod): if r <= 11 or r == 43: row = VGroup() for n in range(r, r + n_terms * mod, mod): elem = Integer(n) comma = OldTex(",") comma.next_to( elem.get_corner(DR), RIGHT, SMALL_BUFF ) elem.add(comma) row.add(elem) if n in prime_numbers: primes.add(elem) else: non_primes.add(elem) row.arrange(RIGHT, buff=0.3) dots = OldTex("\\dots") dots.next_to(row.get_corner(DR), RIGHT, SMALL_BUFF) dots.shift(SMALL_BUFF * UP) row.add(dots) row.r = r if r == 12: row = OldTex("\\vdots") residue_classes.add(row) residue_classes.arrange(DOWN) residue_classes[-2].align_to(residue_classes, LEFT) residue_classes[-2].shift(MED_SMALL_BUFF * RIGHT) residue_classes.set_height(6) residue_classes.next_to(ORIGIN, RIGHT) residue_classes.to_edge(DOWN, buff=MED_SMALL_BUFF) def get_line(row): return Line( row.get_left(), row.get_right(), stroke_color=RED, stroke_width=4, ) even_lines = VGroup(*[ get_line(row) for row in residue_classes[:12:2] ]) eleven_line = get_line(residue_classes[11]) eleven_line.set_color(PINK) for line in [even_lines[1], eleven_line]: line.scale(0.93, about_edge=RIGHT) self.play(ShowCreation(v_line)) self.wait() self.play(FadeIn(approx, DOWN)) self.wait() self.play(FadeIn(residue_classes)) self.wait() self.play( LaggedStartMap(ShowCreation, even_lines), ) self.wait() self.play(ShowCreation(eleven_line)) self.wait() self.play( primes.set_color, TEAL, non_primes.set_opacity, 0.25, even_lines.set_opacity, 0.25, eleven_line.set_opacity, 0.25, ) self.wait() class ExplainRays(Explain44Spirals): CONFIG = { "max_N": int(5e5), "axes_config": { "x_min": -1000, "x_max": 1000, "y_min": -1000, "y_max": 1000, "axis_config": { "tick_frequency": 50, }, }, } def construct(self): self.add_spirals_and_labels() self.show_710th_point() self.show_arithmetic() self.zoom_and_count() def show_710th_point(self): spiral = self.spiral axes = self.axes labels = self.labels scale_factor = 12 fade_rect = FullScreenFadeRectangle() fade_rect.scale(scale_factor) new_ns = list(range(711)) bright_boxes = self.get_v_spiral(new_ns) bright_boxes.set_color(YELLOW) for n, box in enumerate(bright_boxes): box.set_height(0.02 * np.sqrt(n)) big_labels = self.get_labels(new_ns) index_tracker = ValueTracker(44) labeled_box = VGroup(Square(), Integer(0)) def update_labeled_box(mob): index = int(index_tracker.get_value()) labeled_box[0].become(bright_boxes[index]) labeled_box[1].become(big_labels[index]) labeled_box.add_updater(update_labeled_box) self.set_scale( scale=120, spiral=spiral, to_shrink=labels, ) box_710 = self.get_v_spiral([710])[0] box_710.scale(2) box_710.set_color(YELLOW) label_710 = Integer(710) label_710.scale(1.5) label_710.next_to(box_710, UP) arrow = Arrow( ORIGIN, DOWN, stroke_width=6, max_tip_length_to_length_ratio=0.35, max_stroke_width_to_length_ratio=10, tip_length=0.35 ) arrow.match_color(box_710) arrow.next_to(box_710, UP, SMALL_BUFF) label_710.next_to(arrow, UP, SMALL_BUFF) self.add(spiral, fade_rect, axes, labels) self.play( FadeIn(fade_rect), FadeOut(labels), FadeInFromLarge(box_710), FadeIn(label_710, DOWN), ShowCreation(arrow), ) self.wait() self.fade_rect = fade_rect self.box_710 = box_710 self.label_710 = label_710 self.arrow = arrow def show_arithmetic(self): label_710 = self.label_710 equation = OldTex( "710", "\\text{ radians}", "=", "(710 / 2\\pi)", "\\text{ rotations}", ) equation.to_corner(UL) frac = equation.get_part_by_tex("710 / 2\\pi") brace = Brace(frac, DOWN, buff=SMALL_BUFF) value = OldTexText("{:.15}".format(710 / TAU)) value.next_to(brace, DOWN, SMALL_BUFF) values = VGroup(*[ value[0][:n].deepcopy().next_to(brace, DOWN, SMALL_BUFF) for n in [3, *range(5, 13)] ]) group = VGroup(equation, brace, value) rect = SurroundingRectangle(group, buff=MED_SMALL_BUFF) rect.set_stroke(WHITE, 2) rect.set_fill(GREY_D, 1) approx = OldTex( "{710", "\\over", "113}", "\\approx", "2\\pi", ) approx.next_to(rect, DOWN) approx.align_to(equation, LEFT) approx2 = OldTex( "{355", "\\over", "113}", "\\approx", "\\pi", ) approx2.next_to(approx, RIGHT, LARGE_BUFF) self.play( FadeIn(rect), TransformFromCopy(label_710, equation[0]), FadeIn(equation[1:3]), ) self.play( FadeIn(equation[3:], LEFT) ) self.play(GrowFromCenter(brace)) self.play( ShowSubmobjectsOneByOne(values), run_time=3, rate_func=linear, ) self.wait() self.play( rect.stretch, 2, 1, {"about_edge": UP}, LaggedStart( TransformFromCopy( # 710 equation[3][1:4], approx[0], ), FadeIn(approx[1][0]), TransformFromCopy( # 113 values[-1][:3], approx[2], ), FadeIn(approx[3]), TransformFromCopy( # 2pi equation[3][5:7], approx[4], ), run_time=2, ) ) self.wait() self.play( TransformFromCopy(approx, approx2), ) self.wait() self.play( FadeOut(VGroup( rect, equation, brace, values[-1], approx, approx2 )), self.fade_rect.set_opacity, 0.25, ) def zoom_and_count(self): label = self.label_710 arrow = self.arrow box = self.box_710 axes = self.axes spiral = self.spiral times = OldTex("\\times") times.next_to(label, LEFT, SMALL_BUFF) k_label = Integer(1) k_label.match_height(label) k_label.set_color(YELLOW) k_label.next_to(times, LEFT) boxes = VGroup(*[box.copy() for x in range(150)]) box_height_tracker = ValueTracker(box.get_height()) def get_k(): max_x = axes.x_axis.p2n(label.get_center()) return max(1, int(max_x / 710)) def get_k_point(k): return self.get_polar_point(710 * k, 710 * k) def update_arrow(arrow): point = get_k_point(get_k()) arrow.put_start_and_end_on( label.get_bottom() + SMALL_BUFF * DOWN, point + SMALL_BUFF * UP ) def get_unit(): return get_norm(axes.c2p(1, 0) - axes.c2p(0, 0)) def update_boxes(boxes): box_height = box_height_tracker.get_value() for k, box in enumerate(boxes): box.set_height(box_height) box.move_to(get_k_point(k)) arrow.add_updater(update_arrow) boxes.add_updater(update_boxes) k_label.add_updater( lambda d: d.set_value(get_k()).next_to( times, LEFT, SMALL_BUFF ) ) self.remove(box) self.add(times, k_label, boxes) self.set_scale( scale=10000, spiral=self.spiral, run_time=8, target_p_spiral_width=2, added_anims=[ box_height_tracker.set_value, 0.035, ] ) self.wait() # Show other residue classes new_label = OldTex( "710", "k", "+", tex_to_color_map={"k": YELLOW} ) new_label.match_height(label) new_label.next_to(boxes, UP, SMALL_BUFF) new_label.to_edge(RIGHT) new_label[2].set_opacity(0) r_label = Integer(1) r_label.match_height(new_label) r_label.set_opacity(0) r_label.add_updater( lambda m: m.next_to(new_label, RIGHT, SMALL_BUFF) ) k_label.clear_updaters() self.play( FadeOut(times), ReplacementTransform(label, new_label[0]), ReplacementTransform(k_label, new_label[1]), FadeOut(arrow) ) boxes.clear_updaters() for r in range(1, 12): if r in [3, 6]: vect = UR else: vect = RIGHT point = rotate_vector(boxes[40].get_center(), 1) new_boxes = boxes.copy() new_boxes.rotate(1, about_point=ORIGIN) for box in new_boxes: box.rotate(-1) self.play( FadeOut(boxes), LaggedStartMap(FadeIn, new_boxes, lag_ratio=0.01), new_label.set_opacity, 1, new_label.next_to, point, vect, r_label.set_opacity, 1, ChangeDecimalToValue(r_label, r), run_time=1, ) self.remove(boxes) boxes = new_boxes self.add(boxes) self.wait() # Show just the primes self.play( FadeOut(boxes), FadeOut(new_label), FadeOut(r_label), FadeOut(self.fade_rect) ) self.set_scale( 30000, spiral=spiral, run_time=4, ) self.wait() self.remove(spiral) self.add(spiral[1]) self.wait() class CompareTauToApprox(Scene): def construct(self): eqs = VGroup( OldTex("2\\pi", "=", "{:.10}\\dots".format(TAU)), OldTex("\\frac{710}{113}", "=", "{:.10}\\dots".format(710 / 113)), ) eqs.arrange(DOWN, buff=LARGE_BUFF) eqs[1].shift((eqs[0][2].get_left()[0] - eqs[1][2].get_left()[0]) * RIGHT) eqs.generate_target() for eq in eqs.target: eq[2][:8].set_color(RED) eq.set_stroke(BLACK, 8, background=True) self.play(LaggedStart( FadeIn(eqs[0], DOWN), FadeIn(eqs[1], UP), )) self.play(MoveToTarget(eqs)) self.wait() class RecommendedMathologerVideo(Scene): def construct(self): full_rect = FullScreenFadeRectangle() full_rect.set_fill(GREY_D, 1) self.add(full_rect) title = OldTexText("Recommended Mathologer video") title.set_width(FRAME_WIDTH - 1) title.to_edge(UP) screen_rect = SurroundingRectangle(ScreenRectangle(height=5.9), buff=SMALL_BUFF) screen_rect.next_to(title, DOWN) screen_rect.set_fill(BLACK, 1) screen_rect.set_stroke(WHITE, 3) self.add(screen_rect) self.play(Write(title)) self.wait() class ShowClassesOfPrimeRays(SpiralScene): CONFIG = { "max_N": int(1e6), "scale": 1e5 } def construct(self): self.setup_rays() self.show_classes() def setup_rays(self): spiral = self.get_prime_p_spiral(self.max_N) self.add(spiral) self.set_scale( scale=self.scale, spiral=spiral, target_p_spiral_width=3, run_time=0 ) def show_classes(self): max_N = self.max_N mod = 710 primes = read_in_primes(max_N) rect = FullScreenFadeRectangle() rect.set_opacity(0) self.add(rect) last_ray = PMobject() last_label = VGroup(*[VectorizedPoint() for x in range(3)]) for i in range(40): if get_gcd(i, mod) != 1: continue r = (INV_113_MOD_710 * i) % mod sequence = filter( lambda x: x in primes, range(r, max_N, mod) ) ray = self.get_v_spiral(sequence, box_width=0.03) ray.set_color(GREEN) ray.set_opacity(0.9) label = VGroup( *Tex("710k", "+"), Integer(r) ) label.arrange(RIGHT, buff=SMALL_BUFF) label.next_to(ray[100], UL, SMALL_BUFF) label[2].save_state() label[2].set_opacity(0) label[2].move_to(last_label, RIGHT) self.play( rect.set_opacity, 0.5, ShowCreation(ray), LaggedStartMap(FadeOut, last_ray), ReplacementTransform(last_label[:2], label[:2]), Restore(label[2]), last_label[2].move_to, label[2].saved_state, last_label[2].set_opacity, 0, ) self.remove(last_label) self.add(label) self.wait() last_ray = ray last_label = label class ShowFactorsOf710(Scene): def construct(self): equation = OldTex( "710", "=", "71", "\\cdot", "5", "\\cdot", "2", ) equation.scale(1.5) equation.to_corner(UL) ten = OldTex("10") ten.match_height(equation) ten.move_to(equation.get_part_by_tex("5"), LEFT) self.add(equation[0]) self.wait() self.play( TransformFromCopy( equation[0][:2], equation[2], ), FadeIn(equation[1]), FadeIn(equation[3]), TransformFromCopy( equation[0][2:], ten, ) ) self.wait() self.remove(ten) self.play(*[ TransformFromCopy(ten, mob) for mob in equation[4:] ]) self.wait() # Circle factors colors = [RED, BLUE, PINK] for factor, color in zip(equation[:-6:-2], colors): rect = SurroundingRectangle(factor) rect.set_color(color) self.play(ShowCreation(rect)) self.wait() self.play(FadeOut(rect)) class LookAtRemainderMod710(Scene): def construct(self): t2c = { "n": YELLOW, "r": GREEN } equation = OldTex( "n", "=", "710", "k", "+", "r", tex_to_color_map=t2c, ) equation.scale(1.5) n_arrow = Vector(UP).next_to(equation.get_part_by_tex("n"), DOWN) r_arrow = Vector(UP).next_to(equation.get_part_by_tex("r"), DOWN) n_arrow.set_color(t2c["n"]) r_arrow.set_color(t2c["r"]) n_label = OldTexText("Some\\\\number") r_label = OldTexText("Remainder") VGroup(n_label, r_label).scale(1.5) n_label.next_to(n_arrow, DOWN) n_label.match_color(n_arrow) r_label.next_to(r_arrow, DOWN) r_label.match_color(r_arrow) self.add(equation) self.play( FadeIn(n_label, UP), ShowCreation(n_arrow), ) self.wait() self.play( FadeIn(r_label, DOWN), ShowCreation(r_arrow), ) self.wait() class EliminateNonPrimative710Residues(ShowClassesOfPrimeRays): CONFIG = { "max_N": int(5e5), "scale": 5e4, } def construct(self): self.setup_rays() self.eliminate_classes() def setup_rays(self): mod = 710 rays = PGroup(*[ self.get_p_spiral(range(r, self.max_N, mod)) for r in range(mod) ]) rays.set_color(YELLOW) self.add(rays) self.set_scale( scale=self.scale, spiral=rays, target_p_spiral_width=1, run_time=0, ) self.rays = rays def eliminate_classes(self): rays = self.rays rect = FullScreenFadeRectangle() rect.set_opacity(0) for r, ray in enumerate(rays): ray.r = r mod = 710 odds = PGroup(*[rays[i] for i in range(1, mod, 2)]) mult5 = PGroup(*[rays[i] for i in range(0, mod, 5) if i % 2 != 0]) mult71 = PGroup(*[rays[i] for i in range(0, mod, 71) if (i % 2 != 0 and i % 5 != 0)]) colors = [RED, BLUE, PINK] pre_label, r_label = label = VGroup( OldTex("710k + "), Integer(100) ) label.scale(1.5) label.arrange(RIGHT, buff=SMALL_BUFF) label.set_stroke(BLACK, 5, background=True, family=True) label.next_to(ORIGIN, DOWN) r_label.group = odds r_label.add_updater( lambda m: m.set_value(m.group[-1].r if len(m.group) > 0 else 1), ) self.remove(rays) # Odds odds.set_stroke_width(3) self.add(odds, label) self.play( ShowIncreasingSubsets(odds, int_func=np.ceil), run_time=10, ) self.play(FadeOut(label)) self.remove(odds) self.add(*odds) self.wait() # Multiples of 5 then 71 for i, group in [(1, mult5), (2, mult71)]: group_copy = group.copy() group_copy.set_color(colors[i]) group_copy.set_stroke_width(4) r_label.group = group_copy self.add(group_copy, label) self.play( ShowIncreasingSubsets(group_copy, int_func=np.ceil, run_time=10), ) self.play(FadeOut(label)) self.wait() self.remove(group_copy, *group) self.wait() class Show280Computation(Scene): def construct(self): equation = OldTex( "\\phi(710) = ", "710", "\\left({1 \\over 2}\\right)", "\\left({4 \\over 5}\\right)", "\\left({70 \\over 71}\\right)", "=", "280", ) equation.set_width(FRAME_WIDTH - 1) equation.move_to(UP) words = VGroup( OldTexText("Filter out\\\\evens"), OldTexText("Filter out\\\\multiples of 5"), OldTexText("Filter out\\\\multiples of 71"), ) vects = [DOWN, UP, DOWN] colors = [RED, BLUE, LIGHT_PINK] for part, word, vect, color in zip(equation[2:5], words, vects, colors): brace = Brace(part, vect) brace.stretch(0.8, 0) word.brace = brace word.next_to(brace, vect) part.set_color(color) word.set_color(color) word.set_stroke(BLACK, 5, background=True) equation.set_stroke(BLACK, 5, background=True) etf_label = OldTexText("Euler's totient function") etf_label.to_corner(UL) arrow = Arrow(etf_label.get_bottom(), equation[0][0].get_top()) equation[0][0].set_color(YELLOW) etf_label.set_color(YELLOW) rect = FullScreenFadeRectangle(fill_opacity=0.9) self.play( FadeIn(rect), FadeInFromDown(equation), FadeIn(etf_label), GrowArrow(arrow), ) self.wait() for word in words: self.play( FadeIn(word), GrowFromCenter(word.brace), ) self.wait() class TeacherHoldUp(TeacherStudentsScene): def construct(self): self.play_all_student_changes( "pondering", look_at=2 * UP, added_anims=[ self.teacher.change, "raise_right_hand" ] ) self.wait(8) class DiscussPrimesMod10(Scene): def construct(self): labels = VGroup(*[ OldTexText(str(n), " mod 10:") for n in range(10) ]) labels.arrange(DOWN, buff=0.35, aligned_edge=LEFT) labels.to_edge(LEFT) # digits = VGroup(*[l[0] for l in labels]) labels.set_submobject_colors_by_gradient(YELLOW, BLUE) sequences = VGroup(*[ VGroup(*[ Integer(n).shift((n // 10) * RIGHT) for n in range(r, 100 + r, 10) ]) for r in range(10) ]) for sequence, label in zip(sequences, labels): sequence.next_to(label, RIGHT, buff=MED_LARGE_BUFF) for item in sequence: if item is sequence[-1]: punc = OldTex("\\dots") else: punc = OldTexText(",") punc.next_to(item.get_corner(DR), RIGHT, SMALL_BUFF) item.add(punc) # Introduce everything self.play(LaggedStart(*[ FadeIn(label, UP) for label in labels ])) self.wait() self.play( LaggedStart(*[ LaggedStart(*[ FadeIn(item, LEFT) for item in sequence ]) for sequence in sequences ]) ) self.wait() # Highlight 0's then 1's for sequence in sequences[:2]: lds = VGroup(*[item[-2] for item in sequence]) rects = VGroup(*[ SurroundingRectangle(ld, buff=0.05) for ld in lds ]) rects.set_color(YELLOW) self.play( LaggedStartMap( ShowCreationThenFadeOut, rects ) ) self.wait() # Eliminate certain residues two = sequences[2][0] five = sequences[5][0] evens = VGroup(*it.chain(*sequences[::2])) evens.remove(two) div5 = sequences[5][1:] prime_numbers = read_in_primes(100) primes = VGroup(*[ item for seq in sequences for item in seq if int(item.get_value()) in prime_numbers ]) non_primes = VGroup(*[ item for seq in sequences for item in seq if reduce(op.and_, [ int(item.get_value()) not in prime_numbers, item.get_value() % 2 != 0, item.get_value() % 5 != 0, ]) ]) for prime, group in [(two, evens), (five, div5)]: self.play(ShowCreationThenFadeAround(prime)) self.play(LaggedStart(*[ ApplyMethod(item.set_opacity, 0.2) for item in group ])) self.wait() # Highlight primes self.play( LaggedStart(*[ ApplyFunction( lambda m: m.scale(1.2).set_color(TEAL), prime ) for prime in primes ]), LaggedStart(*[ ApplyFunction( lambda m: m.scale(0.8).set_opacity(0.8), non_prime ) for non_prime in non_primes ]), ) self.wait() # Highlight coprime residue classes rects = VGroup(*[ SurroundingRectangle(VGroup(labels[r], sequences[r])) for r in [1, 3, 7, 9] ]) for rect in rects: rect.reverse_points() fade_rect = FullScreenFadeRectangle() fade_rect.scale(1.1) new_fade_rect = fade_rect.copy() fade_rect.append_vectorized_mobject(rects[0]) for rect in rects: new_fade_rect.append_vectorized_mobject(rect) self.play(DrawBorderThenFill(fade_rect)) self.wait() self.play( FadeOut(fade_rect), FadeIn(new_fade_rect), ) self.wait() class BucketPrimesByLastDigit(Scene): CONFIG = { "bar_colors": [YELLOW, BLUE], "mod": 10, "max_n": 10000, "n_to_animate": 20, "n_to_show": 1000, "x_label_scale_factor": 1, "x_axis_label": "Last digit", "bar_width": 0.5, } def construct(self): self.add_axes() self.add_bars() self.bucket_primes() def add_axes(self): mod = self.mod axes = Axes( x_min=0, x_max=mod + 0.5, x_axis_config={ "unit_size": 10 / mod, "include_tip": False, }, y_min=0, y_max=100, y_axis_config={ "unit_size": 0.055, "tick_frequency": 12.5, "include_tip": False, }, ) x_labels = VGroup() for x in range(mod): digit = Integer(x) digit.scale(self.x_label_scale_factor) digit.next_to(axes.x_axis.n2p(x + 1), DOWN, MED_SMALL_BUFF) x_labels.add(digit) self.modify_x_labels(x_labels) x_labels.set_submobject_colors_by_gradient(*self.bar_colors) axes.add(x_labels) axes.x_labels = x_labels y_labels = VGroup() for y in range(25, 125, 25): label = Integer(y, unit="\\%") label.next_to(axes.y_axis.n2p(y), LEFT, MED_SMALL_BUFF) y_labels.add(label) axes.add(y_labels) x_axis_label = OldTexText(self.x_axis_label) x_axis_label.next_to(axes.x_axis.get_end(), RIGHT, buff=MED_LARGE_BUFF) axes.add(x_axis_label) y_axis_label = OldTexText("Proportion") y_axis_label.next_to(axes.y_axis.get_end(), UP, buff=MED_LARGE_BUFF) # y_axis_label.set_color(self.bar_colors[0]) axes.add(y_axis_label) axes.center() axes.set_width(FRAME_WIDTH - 1) axes.to_edge(DOWN) self.axes = axes self.add(axes) def add_bars(self): axes = self.axes mod = self.mod count_trackers = Group(*[ ValueTracker(0) for x in range(mod) ]) bars = VGroup() for x in range(mod): bar = Rectangle( height=1, width=self.bar_width, fill_opacity=1, ) bar.bottom = axes.x_axis.n2p(x + 1) bars.add(bar) bars.set_submobject_colors_by_gradient(*self.bar_colors) bars.set_stroke(WHITE, 1) def update_bars(bars): values = [ct.get_value() for ct in count_trackers] total = sum(values) if total == 0: props = [0 for x in range(mod)] elif total < 1: props = values else: props = [value / total for value in values] for bar, prop in zip(bars, props): bar.set_height( max( 1e-5, 100 * prop * axes.y_axis.unit_size, ), stretch=True ) # bar.set_height(1) bar.move_to(bar.bottom, DOWN) bars.add_updater(update_bars) self.add(count_trackers) self.add(bars) self.bars = bars self.count_trackers = count_trackers def bucket_primes(self): bars = self.bars count_trackers = self.count_trackers max_n = self.max_n n_to_animate = self.n_to_animate n_to_show = self.n_to_show mod = self.mod primes = VGroup(*[ Integer(prime).scale(2).to_edge(UP, buff=LARGE_BUFF) for prime in read_in_primes(max_n) ]) arrow = Arrow(ORIGIN, DOWN) x_labels = self.axes.x_labels rects = VGroup(*map(SurroundingRectangle, x_labels)) rects.set_color(RED) self.play(FadeIn(primes[0])) for i, p, np in zip(it.count(), primes[:n_to_show], primes[1:]): d = int(p.get_value()) % mod self.add(rects[d]) if i < n_to_animate: self.play( p.scale, 0.5, p.move_to, bars[d].get_top(), p.set_opacity, 0, FadeIn(np), count_trackers[d].increment_value, 1, ) self.remove(p) else: arrow.next_to(bars[d], UP) self.add(arrow) self.add(p) count_trackers[d].increment_value(1) self.wait(0.1) self.remove(p) self.remove(rects[d]) # def modify_x_labels(self, labels): pass class PhraseDirichletsTheoremFor10(TeacherStudentsScene): def construct(self): expression = OldTex( "\\lim_{x \\to \\infty}", "\\left(", "{\\text{\\# of primes $p$ where $p \\le x$} \\text{ and $p \\equiv 1$ mod 10}", "\\over", "\\text{\\# of primes $p$ where $p \\le x$}}", "\\right)", "=", "\\frac{1}{4}", ) lim, lp, num, over, denom, rp, eq, fourth = expression expression.shift(UP) denom.save_state() denom.move_to(self.hold_up_spot, DOWN) denom.shift_onto_screen() num[len(denom):].set_color(YELLOW) x_example = VGroup( OldTexText("Think, for example, $x = $"), Integer(int(1e6)), ) x_example.arrange(RIGHT) x_example.scale(1.5) x_example.to_edge(UP) # teacher = self.teacher students = self.students self.play( FadeInFromDown(denom), teacher.change, "raise_right_hand", self.change_students(*["pondering"] * 3), ) self.wait() self.play(FadeInFromDown(x_example)) self.wait() self.play( Restore(denom), teacher.change, "thinking", ) self.play( TransformFromCopy(denom, num[:len(denom)]), Write(over), ) self.play( Write(num[len(denom):]), students[0].change, "confused", students[2].change, "erm", ) self.wait(2) self.play( Write(lp), Write(rp), Write(eq), ) self.play(FadeIn(fourth, LEFT)) self.play(FadeIn(lim, RIGHT)) self.play( ChangeDecimalToValue( x_example[1], int(1e7), run_time=8, rate_func=linear, ), VFadeOut(x_example, run_time=8), self.change_students(*["thinking"] * 3), Blink( teacher, run_time=4, rate_func=squish_rate_func(there_and_back, 0.65, 0.7) ), ) class InsertNewResidueClasses(Scene): def construct(self): nums = VGroup(*map(Integer, [3, 7, 9])) colors = [GREEN, TEAL, BLUE] for num, color in zip(nums, colors): num.set_color(color) num.add_background_rectangle(buff=SMALL_BUFF, opacity=1) self.play(FadeIn(num, UP)) self.wait() class BucketPrimesBy44(BucketPrimesByLastDigit): CONFIG = { "mod": 44, "n_to_animate": 5, "x_label_scale_factor": 0.5, "x_axis_label": "r mod 44", "bar_width": 0.1, } def modify_x_labels(self, labels): labels[::2].set_opacity(0) class BucketPrimesBy9(BucketPrimesByLastDigit): CONFIG = { "mod": 9, "n_to_animate": 5, "x_label_scale_factor": 1, "x_axis_label": "r mod 9", "bar_width": 1, } def modify_x_labels(self, labels): pass class DirichletIn1837(Scene): def construct(self): # Add timeline dates = list(range(1780, 2030, 10)) timeline = NumberLine( x_min=1700, x_max=2020, tick_frequency=1, numbers_with_elongated_ticks=dates, unit_size=0.2, stroke_color=GREY, stroke_width=2, ) timeline.add_numbers( *dates, group_with_commas=False, ) timeline.numbers.shift(SMALL_BUFF * DOWN) timeline.to_edge(RIGHT) # Special dates d_arrow, rh_arrow, pnt_arrow = arrows = VGroup(*[ Vector(DOWN).next_to(timeline.n2p(date), UP) for date in [1837, 1859, 1896] ]) d_label, rh_label, pnt_label = labels = VGroup(*[ OldTexText(text).next_to(arrow, UP) for arrow, text in zip(arrows, [ "Dirichlet's\\\\theorem\\\\1837", "Riemann\\\\hypothesis\\\\1859", "Prime number\\\\theorem\\\\1896", ]) ]) # Back in time frame = self.camera_frame self.add(timeline, arrows, labels) self.play( frame.move_to, timeline.n2p(1837), run_time=4, ) self.wait() # Show picture image = ImageMobject("Dirichlet") image.set_height(3) image.next_to(d_label, LEFT) self.play(FadeIn(image, RIGHT)) self.wait() # Flash self.play( Flash( d_label.get_center(), num_lines=12, line_length=0.25, flash_radius=1.5, line_stroke_width=3, lag_ratio=0.05, ) ) self.wait() # Transition title title, underline = self.get_title_and_underline() n = len(title[0]) self.play( ReplacementTransform(d_label[0][:n], title[0][:n]), FadeOut(d_label[0][n:]), LaggedStartMap( FadeOutAndShiftDown, Group( image, d_arrow, rh_label, rh_arrow, pnt_label, pnt_arrow, *timeline, ) ), ) self.play(ShowCreation(underline)) self.wait() def get_title_and_underline(self): frame = self.camera_frame title = OldTexText("Dirichlet's theorem") title.scale(1.5) title.next_to(frame.get_top(), DOWN, buff=MED_LARGE_BUFF) underline = Line() underline.match_width(title) underline.next_to(title, DOWN, SMALL_BUFF) return title, underline class PhraseDirichletsTheorem(DirichletIn1837): def construct(self): self.add(*self.get_title_and_underline()) # Copy-pasted, which isn't great expression = OldTex( "\\lim_{x \\to \\infty}", "\\left(", "{\\text{\\# of primes $p$ where $p \\le x$} \\text{ and $p \\equiv 1$ mod 10}", "\\over", "\\text{\\# of primes $p$ where $p \\le x$}}", "\\right)", "=", "\\frac{1}{4}", ) lim, lp, num, over, denom, rp, eq, fourth = expression expression.shift(1.5 * UP) expression.to_edge(LEFT, MED_SMALL_BUFF) num[len(denom):].set_color(YELLOW) # # Terms and labels ten = num[-2:] one = num[-6] four = fourth[-1] N = OldTex("N") r = OldTex("r") one_over_phi_N = OldTex("1", "\\over", "\\phi(", "N", ")") N.set_color(MAROON_B) r.set_color(BLUE) one_over_phi_N.set_color_by_tex("N", N.get_color()) N.move_to(ten, DL) r.move_to(one, DOWN) one_over_phi_N.move_to(fourth, LEFT) N_label = OldTexText("$N$", " is any number") N_label.set_color_by_tex("N", N.get_color()) N_label.next_to(expression, DOWN, LARGE_BUFF) r_label = OldTexText("$r$", " is coprime to ", "$N$") r_label[0].set_color(r.get_color()) r_label[2].set_color(N.get_color()) r_label.next_to(N_label, DOWN, MED_LARGE_BUFF) phi_N_label = OldTex( "\\phi({10}) = ", "\\#\\{1, 3, 7, 9\\} = 4", tex_to_color_map={ "{10}": N.get_color(), } ) phi_N_label[-1][2:9:2].set_color(r.get_color()) phi_N_label.next_to(r_label, DOWN, MED_LARGE_BUFF) # self.play( LaggedStart(*[ FadeIn(denom), ShowCreation(over), FadeIn(num), Write(VGroup(lp, rp)), FadeIn(lim), Write(VGroup(eq, fourth)), ]), run_time=3, lag_ratio=0.7, ) self.wait() for mob in denom, num: self.play(ShowCreationThenFadeAround(mob)) self.wait() self.play( FadeIn(r, DOWN), FadeOut(one, UP), ) self.play( FadeIn(N, DOWN), FadeOut(ten, UP), ) self.wait() self.play( TransformFromCopy(N, N_label[0]), FadeIn(N_label[1:], DOWN) ) self.wait() self.play( FadeIn(r_label[1:-1], DOWN), TransformFromCopy(r, r_label[0]), ) self.play( TransformFromCopy(N_label[0], r_label[-1]), ) self.wait() self.play( ShowCreationThenFadeAround(fourth), ) self.play( FadeIn(one_over_phi_N[2:], LEFT), FadeOut(four, RIGHT), ReplacementTransform(fourth[0], one_over_phi_N[0][0]), ReplacementTransform(fourth[1], one_over_phi_N[1][0]), ) self.play( FadeIn(phi_N_label, DOWN) ) self.wait() # Fancier version new_expression = OldTex( "\\lim_{x \\to \\infty}", "\\left(", "{\\pi(x; {N}, {r})", "\\over", "\\pi(x)}", "\\right)", "=", "\\frac{1}{\\phi({N})}", tex_to_color_map={ "{N}": N.get_color(), "{r}": r.get_color(), "\\pi": WHITE, } ) pis = new_expression.get_parts_by_tex("\\pi") randy = Randolph(height=2) randy.next_to(new_expression, LEFT, buff=LARGE_BUFF) randy.shift(0.75 * DOWN) new_expression.next_to(expression, DOWN, LARGE_BUFF) ne_rect = SurroundingRectangle(new_expression, color=BLUE) label_group = VGroup(N_label, r_label) label_group.generate_target() label_group.target.arrange(RIGHT, buff=LARGE_BUFF) label_group.target.next_to(new_expression, DOWN, buff=LARGE_BUFF) self.play( FadeIn(randy), ) self.play( randy.change, "hooray", expression ) self.play(Blink(randy)) self.wait() self.play( FadeIn(new_expression), MoveToTarget(label_group), phi_N_label.to_edge, DOWN, MED_LARGE_BUFF, randy.change, "horrified", new_expression, ) self.play(ShowCreation(ne_rect)) self.play(randy.change, "confused") self.play(Blink(randy)) self.wait() self.play( LaggedStartMap( ShowCreationThenFadeAround, pis, ), randy.change, "angry", new_expression ) self.wait() self.play(Blink(randy)) self.wait() class MoreModestDirichlet(Scene): def construct(self): ed = OldTexText( "Each (coprime) residue class ", "is equally dense with ", "primes." ) inf = OldTexText( "Each (coprime) residue class ", "has infinitely many ", "primes." ) ed[1].set_color(BLUE) inf[1].set_color(GREEN) for mob in [*ed, *inf]: mob.save_state() cross = Cross(ed[1]) c_group = VGroup(ed[1], cross) self.add(ed) self.wait() self.play(ShowCreation(cross)) self.play( c_group.shift, DOWN, c_group.set_opacity, 0.5, ReplacementTransform(ed[::2], inf[::2]), FadeIn(inf[1]) ) self.wait() self.remove(*inf) self.play( inf[1].shift, UP, Restore(ed[0]), Restore(ed[1]), Restore(ed[2]), FadeOut(cross), ) self.wait() class TalkAboutProof(TeacherStudentsScene): def construct(self): teacher = self.teacher students = self.students # Ask question self.student_says( "So how'd he\\\\prove it?", index=0, ) bubble = students[0].bubble students[0].bubble = None self.play( teacher.change, "hesitant", students[1].change, "happy", students[2].change, "happy", ) self.wait() self.teacher_says( "...er...it's a\\\\bit complicated", target_mode="guilty", ) self.play_all_student_changes( "tired", look_at=teacher.bubble, lag_ratio=0.1, ) self.play( FadeOut(bubble), FadeOut(bubble.content), ) self.wait(3) # Bring up complex analysis ca = OldTexText("Complex ", "Analysis") ca.move_to(self.hold_up_spot, DOWN) self.play( teacher.change, "raise_right_hand", FadeInFromDown(ca), FadeOut(teacher.bubble), FadeOut(teacher.bubble.content), self.change_students(*["pondering"] * 3), ) self.wait() self.play( ca.scale, 2, ca.center, ca.to_edge, UP, teacher.change, "happy", ) self.play(ca[1].set_color, GREEN) self.wait(2) self.play(ca[0].set_color, YELLOW) self.wait(2) self.play_all_student_changes( "confused", look_at=ca, ) self.wait(4) class HighlightTwinPrimes(Scene): def construct(self): self.add_paper_titles() self.show_twin_primes() def add_paper_titles(self): gpy = OldTexText( "Goldston, Pintz, Yildirim\\\\", "2005", ) zhang = OldTexText("Zhang\\\\2014") gpy.move_to(FRAME_WIDTH * LEFT / 4) gpy.to_edge(UP) zhang.move_to(FRAME_WIDTH * RIGHT / 4) zhang.to_edge(UP) self.play(LaggedStartMap( FadeInFromDown, VGroup(gpy, zhang), lag_ratio=0.3, )) def show_twin_primes(self): max_x = 300 line = NumberLine( x_min=0, x_max=max_x, unit_size=0.5, numbers_with_elongated_ticks=range(10, max_x, 10), ) line.move_to(2.5 * DOWN + 7 * LEFT, LEFT) line.add_numbers(*range(10, max_x, 10)) primes = read_in_primes(max_x) prime_mobs = VGroup(*[ Integer(p).next_to(line.n2p(p), UP) for p in primes ]) dots = VGroup(*[Dot(line.n2p(p)) for p in primes]) arcs = VGroup() for pm, npm in zip(prime_mobs, prime_mobs[1:]): p = pm.get_value() np = npm.get_value() if np - p == 2: angle = 30 * DEGREES arc = Arc( start_angle=angle, angle=PI - 2 * angle, color=RED, ) arc.set_width( get_norm(npm.get_center() - pm.get_center()) ) arc.next_to(VGroup(pm, npm), UP, SMALL_BUFF) arcs.add(arc) dots.set_color(TEAL) prime_mobs.set_color(TEAL) line.add(dots) self.play( FadeIn(line, lag_ratio=0.9), LaggedStartMap(FadeInFromDown, prime_mobs), run_time=2, ) line.add(prime_mobs) self.wait() self.play(FadeIn(arcs)) self.play( line.shift, 100 * LEFT, arcs.shift, 100 * LEFT, run_time=20, rate_func=lambda t: smooth(t, 5) ) self.wait() class RandomToImportant(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs": { "color": GREY_BROWN, }, "camera_config": { "background_color": GREY_E, } } def construct(self): morty = self.pi_creature morty.center().to_edge(DOWN) left_comment = OldTexText("Arbitrary question") left_comment.to_edge(UP) left_comment.shift(3.5 * LEFT) right_comment = OldTexText("Deep fact") right_comment.to_edge(UP) right_comment.shift(3.5 * RIGHT) arrow = Arrow( left_comment.get_right(), right_comment.get_left(), buff=0.5, ) self.play( morty.change, "raise_left_hand", left_comment, FadeInFromDown(left_comment) ) self.wait(2) self.play( morty.change, "raise_right_hand", right_comment, FadeInFromDown(right_comment) ) self.play( ShowCreation(arrow), morty.look_at, right_comment, ) self.wait(2) class RandomWalkOfTopics(Scene): CONFIG = { "n_dots": 30, "n_edge_range": [2, 4], "super_dot_n_edges": 20, "isolated_threashold": 0.5, } def construct(self): self.setup_network() self.define_important() self.perform_walk() def setup_network(self): n_dots = self.n_dots dots = VGroup() while len(dots) < n_dots: point = np.random.uniform(-1, 1, size=3) point[2] = 0 point[0] *= 7 point[1] *= 3 isolated = True for dot in dots: if get_norm(dot.get_center() - point) < self.isolated_threashold: isolated = False if not isolated: continue dot = Dot(point) dot.edges = VGroup() dot.neighbors = VGroup() dots.add(dot) super_dot = dots[len(dots) // 2] all_edges = VGroup() def add_edge(d1, d2): if d1 is d2: return edge = Line( d1.get_center(), d2.get_center(), buff=d1.get_width() / 2 ) d1.edges.add(edge) d2.edges.add(edge) d1.neighbors.add(d2) d2.neighbors.add(d1) all_edges.add(edge) for dot in dots: # others = list(dots[i + 1:]) others = [d for d in dots if d is not dot] others.sort(key=lambda d: get_norm(d.get_center() - dot.get_center())) n_edges = np.random.randint(*self.n_edge_range) for other in others[:n_edges]: if dot in other.neighbors: continue add_edge(dot, other) for dot in dots: if len(super_dot.neighbors) > self.super_dot_n_edges: break elif dot in super_dot.neighbors: continue add_edge(super_dot, dot) dots.sort(lambda p: p[0]) all_edges.set_stroke(WHITE, 2) dots.set_fill(GREY_B, 1) VGroup(dots, all_edges).to_edge(DOWN, buff=MED_SMALL_BUFF) self.dots = dots self.edges = all_edges self.super_dot = super_dot def define_important(self): sd = self.super_dot dots = self.dots edges = self.edges sd.set_color(RED) for mob in [*dots, *edges]: mob.save_state() mob.set_opacity(0) sd.set_opacity(1) sd.edges.set_opacity(1) sd.neighbors.set_opacity(1) # angles = np.arange(0, TAU, TAU / len(sd.neighbors)) # center = 0.5 * DOWN # sd.move_to(center) # for dot, edge, angle in zip(sd.neighbors, sd.edges, angles): # dot.move_to(center + rotate_vector(2.5 * RIGHT, angle)) # if edge.get_length() > 0: # edge.put_start_and_end_on( # sd.get_center(), # dot.get_center() # ) # rad = dot.get_width() / 2 # llen = edge.get_length() # edge.scale((llen - 2 * rad) / llen) title = VGroup( OldTexText("Important"), OldTex("\\Leftrightarrow"), OldTexText("Many connections"), ) title.scale(1.5) title.arrange(RIGHT, buff=MED_LARGE_BUFF) title.to_edge(UP) arrow_words = OldTexText("(in my view)") arrow_words.set_width(2 * title[1].get_width()) arrow_words.next_to(title[1], UP, SMALL_BUFF) title[0].save_state() title[0].set_x(0) self.add(title[0]) self.play( FadeInFromLarge(sd), title[0].set_color, RED, ) title[0].saved_state.set_color(RED) self.play( Restore(title[0]), GrowFromCenter(title[1]), FadeIn(arrow_words), FadeIn(title[2], LEFT), LaggedStartMap( ShowCreation, sd.edges, run_time=3, ), LaggedStartMap( GrowFromPoint, sd.neighbors, lambda m: (m, sd.get_center()), run_time=3, ), ) self.wait() self.play(*map(Restore, [*dots, *edges])) self.wait() def perform_walk(self): # dots = self.dots # edges = self.edges sd = self.super_dot path = VGroup(sd) random.seed(1) for x in range(3): new_choice = None while new_choice is None or new_choice in path: new_choice = random.choice(path[0].neighbors) path.add_to_back(new_choice) for d1, d2 in zip(path, path[1:]): self.play(Flash(d1.get_center())) self.play( ShowCreationThenDestruction( Line( d1.get_center(), d2.get_center(), color=YELLOW, ) ) ) self.play(Flash(sd)) self.play(LaggedStart(*[ ApplyMethod( edge.set_stroke, YELLOW, 5, rate_func=there_and_back, ) for edge in sd.edges ])) self.wait() class DeadEnds(RandomWalkOfTopics): CONFIG = { "n_dots": 20, "n_edge_range": [2, 4], "super_dot_n_edges": 2, "random_seed": 1, } def construct(self): self.setup_network() dots = self.dots edges = self.edges self.add(dots, edges) VGroup( edges[3], edges[4], edges[7], edges[10], edges[12], edges[15], edges[27], edges[30], edges[33], ).set_opacity(0) # for i, edge in enumerate(edges): # self.add(Integer(i).move_to(edge)) class Rediscovery(Scene): def construct(self): randy = Randolph() randy.to_edge(DOWN) randy.shift(2 * RIGHT) lightbulb = Lightbulb() lightbulb.set_stroke(width=4) lightbulb.scale(1.5) lightbulb.next_to(randy, UP) rings = self.get_rings( lightbulb.get_center(), max_radius=10.0, delta_r=0.1, ) bubble = ThoughtBubble() bubble.pin_to(randy) # bubble[-1].set_fill(GREEN_SCREEN, 0.5) self.play( randy.change, "pondering", ShowCreation(bubble), FadeInFromDown(lightbulb), ) self.add(rings, bubble) self.play( randy.change, "thinking", LaggedStartMap( VFadeInThenOut, rings, lag_ratio=0.002, run_time=3, ) ) self.wait(4) def get_rings(self, center, max_radius, delta_r): radii = np.arange(0, max_radius, delta_r) rings = VGroup(*[ Annulus( inner_radius=r1, outer_radius=r2, fill_opacity=0.75 * (1 - fdiv(r1, max_radius)), fill_color=YELLOW ) for r1, r2 in zip(radii, radii[1:]) ]) rings.move_to(center) return rings class BePlayful(TeacherStudentsScene): def construct(self): self.teacher_says( "So be playful!", target_mode="hooray", ) self.play_student_changes("thinking", "hooray", "happy") self.wait(3) class SpiralsPatronThanks(PatreonEndScreen): CONFIG = { "specific_patrons": [ "Juan Benet", "Kurt Dicus", "Vassili Philippov", "Burt Humburg", "Matt Russell", "Scott Gray", "soekul", "Tihan Seale", "D. Sivakumar", "Ali Yahya", "Arthur Zey", "dave nicponski", "Joseph Kelly", "Kaustuv DeBiswas", "kkm", "Lambda AI Hardware", "Lukas Biewald", "Mark Heising", "Nicholas Cahill", "Peter Mcinerney", "Quantopian", "Scott Walter, Ph.D.", "Tauba Auerbach", "Yana Chernobilsky", "Yu Jun", "Jordan Scales", "Lukas -krtek.net- Novy", "Andrew Weir", "Britt Selvitelle", "Britton Finley", "David Gow", "J", "Jonathan Wilson", "Joseph John Cox", "Magnus Dahlström", "Mattéo Delabre", "Randy C. Will", "Ryan Atallah", "Luc Ritchie", "1stViewMaths", "Aidan Shenkman", "Alex Mijalis", "Alexis Olson", "Andreas Benjamin Brössel", "Andrew Busey", "Andrew R. Whalley", "Ankalagon", "Anthony Turvey", "Antoine Bruguier", "Antonio Juarez", "Arjun Chakroborty", "Art Ianuzzi", "Austin Goodman", "Avi Finkel", "Awoo", "Azeem Ansar", "AZsorcerer", "Barry Fam", "Bernd Sing", "Boris Veselinovich", "Bradley Pirtle", "Brian Staroselsky", "Calvin Lin", "Charles Southerland", "Charlie N", "Chris Connett", "Christian Kaiser", "Clark Gaebel", "Danger Dai", "Daniel Herrera C", "Daniel Pang", "Dave B", "Dave Kester", "David B. Hill", "David Clark", "DeathByShrimp", "Delton Ding", "Dominik Wagner", "eaglle", "emptymachine", "Eric Younge", "Ero Carrera", "Eryq Ouithaqueue", "Federico Lebron", "Fernando Via Canel", "Frank R. Brown, Jr.", "Giovanni Filippi", "Hal Hildebrand", "Hause Lin", "Hitoshi Yamauchi", "Ivan Sorokin", "j eduardo perez", "Jacob Baxter", "Jacob Harmon", "Jacob Hartmann", "Jacob Magnuson", "Jameel Syed", "James Stevenson", "Jason Hise", "Jeff Linse", "Jeff Straathof", "John C. Vesey", "John Griffith", "John Haley", "John V Wertheim", "Jonathan Eppele", "Josh Kinnear", "Joshua Claeys", "Kai-Siang Ang", "Kanan Gill", "Kartik Cating-Subramanian", "L0j1k", "Lee Redden", "Linh Tran", "Ludwig Schubert", "Magister Mugit", "Mark B Bahu", "Mark Mann", "Martin Price", "Mathias Jansson", "Matt Langford", "Matt Roveto", "Matthew Bouchard", "Matthew Cocke", "Michael Faust", "Michael Hardel", "Michele Donadoni", "Mirik Gogri", "Mustafa Mahdi", "Márton Vaitkus", "Nero Li", "Nikita Lesnikov", "Omar Zrien", "Owen Campbell-Moore", "Patrick Lucas", "Pedro Igor Salomão Budib", "Peter Ehrnstrom", "RedAgent14", "rehmi post", "Rex Godby", "Richard Barthel", "Ripta Pasay", "Rish Kundalia", "Roman Sergeychik", "Roobie", "Ryan Williams", "Sebastian Garcia", "Solara570", "Steven Siddals", "Stevie Metke", "Suthen Thomas", "Tal Einav", "Ted Suzman", "The Responsible One", "Thomas Tarler", "Tianyu Ge", "Tom Fleming", "Tyler VanValkenburg", "Valeriy Skobelev", "Veritasium", "Vinicius Reis", "Xuanji Li", "Yavor Ivanov", "YinYangBalance.Asia", ] } class Thumbnail(SpiralScene): CONFIG = { "max_N": 8000, "just_show": True, } def construct(self): self.add_dots() if not self.just_show: pass def add_dots(self): self.set_scale(scale=1e3) p_spiral = self.get_prime_p_spiral(self.max_N) dots = VGroup(*[ Dot( point, radius=interpolate(0.01, 0.07, min(0.5 * get_norm(point), 1)), fill_color=TEAL, # fill_opacity=interpolate(0.5, 1, min(get_norm(point), 1)) ) for point in p_spiral.get_points() ]) dots.set_fill([TEAL_E, TEAL_A]) dots.set_stroke(BLACK, 1) label = OldTexText( "($p$, $p$) for all primes $p$,\\\\", "in polar coordinates", tex_to_color_map={ "$p$": YELLOW, }, ) label.scale(2) label.set_stroke(BLACK, 10, background=True) label.add_background_rectangle_to_submobjects() label.to_corner(DL, MED_LARGE_BUFF) self.add(dots) # self.add(label) self.dots = dots
from manim_imports_ext import * import json class IntroduceIMO(Scene): CONFIG = { "num_countries": 130, "use_real_images": True, # "use_real_images": False, "include_labels": False, "camera_config": {"background_color": GREY_E}, "random_seed": 6, "year": 2019, "n_flag_rows": 10, "reorganize_students": True, } def construct(self): self.add_title() self.show_flags() self.show_students() self.move_title() self.isolate_usa() def add_title(self): title = OldTexText( "International ", "Mathematical ", "Olympiad", ) title.scale(1.25) logo = ImageMobject("imo_logo") logo.set_height(1) group = Group(logo, title) group.arrange(RIGHT) group.to_edge(UP, buff=MED_SMALL_BUFF) self.add(title, logo) self.title = title self.logo = logo def show_flags(self): flags = self.get_flags() flags.set_height(6) flags.to_edge(DOWN) random_flags = Group(*flags) random_flags.shuffle() self.play( LaggedStartMap( FadeInFromDown, random_flags, run_time=2, lag_ratio=0.03, ) ) self.remove(random_flags) self.add(flags) self.wait() self.flags = flags def show_students(self): flags = self.flags student_groups = VGroup() all_students = VGroup() for flag in flags: group = self.get_students(flag) student_groups.add(group) for student in group: student.preimage = VectorizedPoint() student.preimage.move_to(flag) all_students.add(student) all_students.shuffle() student_groups.generate_target() student_groups.target.arrange_in_grid( n_rows=self.n_flag_rows, buff=SMALL_BUFF, ) # student_groups.target[-9:].align_to(student_groups.target[0], LEFT) student_groups.target.match_height(flags) student_groups.target.match_y(flags) student_groups.target.to_edge(RIGHT, buff=0.25) self.play(LaggedStart( *[ ReplacementTransform( student.preimage, student ) for student in all_students ], run_time=2, lag_ratio=0.2, )) self.wait() if self.reorganize_students: self.play( MoveToTarget(student_groups), flags.space_out_submobjects, 0.75, flags.to_edge, LEFT, MED_SMALL_BUFF, ) self.wait() self.student_groups = student_groups def move_title(self): title = self.title logo = self.logo new_title = OldTexText("IMO") new_title.match_height(title) logo.generate_target() group = Group(logo.target, new_title) group.arrange(RIGHT, buff=SMALL_BUFF) group.match_y(title) group.match_x(self.student_groups, UP) title.generate_target() for word, letter in zip(title.target, new_title[0]): for nl in word: nl.move_to(letter) word.set_opacity(0) word[0].set_opacity(1) word[0].become(letter) self.play( MoveToTarget(title), MoveToTarget(logo), ) self.wait() def isolate_usa(self): flags = self.flags student_groups = self.student_groups us_flag = flags[0] random_flags = Group(*flags[1:]) random_flags.shuffle() old_height = us_flag.get_height() us_flag.label.set_width(0.8 * us_flag.get_width()) us_flag.label.next_to( us_flag, DOWN, buff=0.2 * us_flag.get_height(), ) us_flag.label.set_opacity(0) us_flag.add(us_flag.label) us_flag.generate_target() us_flag.target.scale(1 / old_height) us_flag.target.to_corner(UL) us_flag.target[1].set_opacity(1) self.remove(us_flag) self.play( LaggedStart( *[ FadeOut(flag, DOWN) for flag in random_flags ], lag_ratio=0.05, run_time=1.5 ), MoveToTarget(us_flag), student_groups[1:].fade, 0.9, ) self.wait() # def get_students(self, flag): dots = VGroup(*[Dot() for x in range(6)]) dots.arrange_in_grid(n_cols=2, buff=SMALL_BUFF) dots.match_height(flag) dots.next_to(flag, RIGHT, SMALL_BUFF) dots[flag.n_students:].set_opacity(0) if isinstance(flag, ImageMobject): rgba = random.choice(random.choice(flag.pixel_array)) if np.all(rgba < 100): rgba = interpolate(rgba, 256 * np.ones(len(rgba)), 0.5) color = rgba_to_color(rgba / 256) else: color = random_bright_color() dots.set_color(color) dots.set_stroke(WHITE, 1, background=True) return dots def get_flags(self): year = self.year file = "{}_imo_countries.json".format(year) with open(os.path.join("assets", file)) as fp: countries_with_counts = json.load(fp) with open(os.path.join("assets", "country_codes.json")) as fp: country_codes = json.load(fp) country_to_code2 = dict([ (country.lower(), code2.lower()) for country, code2, code3 in country_codes ]) country_to_code3 = dict([ (country.lower(), code3.lower()) for country, code2, code3 in country_codes ]) images = Group() for country, count in countries_with_counts: country = country.lower() alt_names = [ ("united states of america", "united states"), ("people's republic of china", "china"), ("macau", "macao"), ("syria", "syrian arab republic"), ("north macedonia", "macedonia, the former yugoslav republic of"), ("tanzania", "united republic of tanzania"), ("vietnam", "viet nam"), ("ivory coast", "cote d'ivoire") ] for n1, n2 in alt_names: if country == n1: country = n2 if country not in country_to_code2: print("Can't find {}".format(country)) continue short_code = country_to_code2[country] try: image = ImageMobject(os.path.join("flags", short_code)) image.set_width(1) label = VGroup(*[ OldTexText(l) for l in country_to_code3[country].upper() ]) label.arrange(RIGHT, buff=0.05, aligned_edge=DOWN) label.set_height(0.25) if not self.use_real_images: rect = SurroundingRectangle(image, buff=0) rect.set_stroke(WHITE, 1) image = rect image.label = label image.n_students = count images.add(image) except OSError: print("Failed on {}".format(country)) n_rows = self.n_flag_rows images.arrange_in_grid( n_rows=n_rows, buff=1.25, ) images[-(len(images) % n_rows):].align_to(images[0], LEFT) sf = 1.7 images.stretch(sf, 0) for i, image in enumerate(images): image.set_height(1) image.stretch(1 / sf, 0) image.label.next_to(image, DOWN, SMALL_BUFF) if self.include_labels: image.add(image.label) images.set_width(FRAME_WIDTH - 1) if images.get_height() > FRAME_HEIGHT - 1: images.set_height(FRAME_HEIGHT - 1) images.center() return images class ShowTinyTao(IntroduceIMO): CONFIG = { "reorganize_students": False, } def construct(self): self.force_skipping() self.add_title() self.show_flags() self.show_students() self.revert_to_original_skipping_status() image = ImageMobject("TerryTaoIMO") label = OldTexText("Terence Tao at 12") label.match_width(image) label.next_to(image, DOWN, SMALL_BUFF) image.add(label) ausie = self.flags[17] image.replace(ausie) image.set_opacity(0) self.play(image.set_opacity, 1) self.play( image.set_height, 5, image.to_corner, DR, {"buff": MED_SMALL_BUFF}, ) self.wait() self.play(FadeOut(image)) class FootnoteToIMOIntro(Scene): def construct(self): words = OldTexText("$^*$Based on data from 2019 test") self.play(FadeIn(words, UP)) self.wait() class ShowTest(Scene): def construct(self): self.introduce_test() def introduce_test(self): test = self.get_test() test.generate_target() test.target.to_edge(UP) # Time label time_labels = VGroup( OldTexText("Day 1", ": 4.5 hours"), OldTexText("Day 2", ": 4.5 hours"), ) time_labels.scale(1.5) day_labels = VGroup() hour_labels = VGroup() for label, page in zip(time_labels, test.target): label.next_to(page, DOWN) label[0].save_state() label[0].next_to(page, DOWN) label[1][1:].set_color(YELLOW) day_labels.add(label[0]) hour_labels.add(label[1]) # Problem descriptions problem_rects = self.get_problem_rects(test.target[0]) proof_words = VGroup() for rect in problem_rects: word = OldTexText("Proof") word.scale(2) word.next_to(rect, RIGHT, buff=3) word.set_color(BLUE) proof_words.add(word) proof_words.space_out_submobjects(2) proof_arrows = VGroup() for rect, word in zip(problem_rects, proof_words): arrow = Arrow(word.get_left(), rect.get_right()) arrow.match_color(word) proof_arrows.add(arrow) scores = VGroup() for word in proof_words: score = VGroup(Integer(0), OldTex("/"), Integer(7)) score.arrange(RIGHT, buff=SMALL_BUFF) score.scale(2) score.move_to(word) score.to_edge(RIGHT) scores.add(score) score[0].add_updater(lambda m: m.set_color( interpolate_color(RED, GREEN, m.get_value() / 7) )) # Introduce test self.play( LaggedStart( FadeIn(test[0], 2 * RIGHT), FadeIn(test[1], 2 * LEFT), lag_ratio=0.3, ) ) self.wait() self.play( MoveToTarget(test, lag_ratio=0.2), FadeIn(day_labels, UP, lag_ratio=0.2), ) self.wait() self.play( *map(Restore, day_labels), FadeIn(hour_labels, LEFT), ) self.wait() # Discuss problems self.play( FadeOut(test[1]), FadeOut(time_labels[1]), LaggedStartMap(ShowCreation, problem_rects), run_time=1, ) self.play( LaggedStart(*[ FadeIn(word, LEFT) for word in proof_words ]), LaggedStart(*[ GrowArrow(arrow) for arrow in proof_arrows ]), ) self.wait() self.play(FadeIn(scores)) self.play( LaggedStart(*[ ChangeDecimalToValue(score[0], 7) for score in scores ], lag_ratio=0.2, rate_func=rush_into) ) self.wait() self.scores = scores self.proof_arrows = proof_arrows self.proof_words = proof_words self.problem_rects = problem_rects self.test = test self.time_labels = time_labels def get_test(self): group = Group( ImageMobject("imo_2011_p1"), ImageMobject("imo_2011_p2"), ) group.set_height(6) group.arrange(RIGHT, buff=LARGE_BUFF) for page in group: rect = SurroundingRectangle(page, buff=0.01) rect.set_stroke(WHITE, 1) page.add(rect) # page.pixel_array[:, :, :3] = 255 - page.pixel_array[:, :, :3] return group def get_problem_rects(self, page): pw = page.get_width() rects = VGroup(*[Rectangle() for x in range(3)]) rects.set_stroke(width=2) rects.set_color_by_gradient([BLUE_E, BLUE_C, BLUE_D]) rects.set_width(pw * 0.75) for factor, rect in zip([0.095, 0.16, 0.1], rects): rect.set_height(factor * pw, stretch=True) rects.arrange(DOWN, buff=0.08) rects.move_to(page) rects.shift(0.09 * pw * DOWN) return rects class USProcessAlt(IntroduceIMO): CONFIG = { } def construct(self): self.add_flag_and_label() self.show_tests() self.show_imo() def add_flag_and_label(self): flag = ImageMobject("flags/us") flag.set_height(1) flag.to_corner(UL) label = VGroup(*map(TexText, "USA")) label.arrange(RIGHT, buff=0.05, aligned_edge=DOWN) label.set_width(0.8 * flag.get_width()) label.next_to(flag, DOWN, buff=0.2 * flag.get_height()) self.add(flag, label) self.flag = flag def show_tests(self): tests = VGroup( self.get_test( ["American ", "Mathematics ", "Contest"], n_questions=25, time_string="75 minutes", hours=1.25, n_students=250000, ), self.get_test( ["American ", "Invitational ", "Math ", "Exam"], n_questions=15, time_string="3 hours", hours=3, n_students=12000, ), self.get_test( ["U", "S", "A ", "Math ", "Olympiad"], n_questions=6, time_string="$2 \\times 4.5$ hours", hours=4.5, n_students=500, ), self.get_test( ["Mathematical ", "Olympiad ", "Program"], n_questions=None, time_string="3 weeks", hours=None, n_students=60 ) ) amc, aime, usamo, mop = tests arrows = VGroup() amc.to_corner(UR) top_point = amc.get_top() last_arrow = VectorizedPoint() last_arrow.to_corner(DL) next_anims = [] self.force_skipping() for test in tests: test.move_to(top_point, UP) test.shift_onto_screen() self.play( Write(test.name), *next_anims, run_time=1, ) self.wait() self.animate_name_abbreviation(test) self.wait() if isinstance(test.nq_label[0], Integer): int_mob = test.nq_label[0] n = int_mob.get_value() int_mob.set_value(0) self.play( ChangeDecimalToValue(int_mob, n), FadeIn(test.nq_label[1:]) ) else: self.play(FadeIn(test.nq_label)) self.play( FadeIn(test.t_label) ) self.wait() test.generate_target() test.target.scale(0.575) test.target.next_to(last_arrow, RIGHT, buff=SMALL_BUFF) test.target.shift_onto_screen() next_anims = [ MoveToTarget(test), GrowArrow(last_arrow), ] last_arrow = Vector(0.5 * RIGHT) last_arrow.set_color(WHITE) last_arrow.next_to(test.target, RIGHT, SMALL_BUFF) arrows.add(last_arrow) self.play(*next_anims) self.revert_to_original_skipping_status() self.play( LaggedStartMap( FadeInFrom, tests, lambda m: (m, LEFT), ), LaggedStartMap( GrowArrow, arrows[:-1] ), lag_ratio=0.4, ) self.wait() self.tests = tests def show_imo(self): tests = self.tests logo = ImageMobject("imo_logo") logo.set_height(1) name = OldTexText("IMO") name.scale(2) group = Group(logo, name) group.arrange(RIGHT) group.to_corner(UR) group.shift(2 * LEFT) students = VGroup(*[ PiCreature() for x in range(6) ]) students.arrange_in_grid(n_cols=3, buff=LARGE_BUFF) students.set_height(2) students.next_to(group, DOWN) colors = it.cycle([RED, GREY_B, BLUE]) for student, color in zip(students, colors): student.set_color(color) student.save_state() student.move_to(tests[-1]) student.fade(1) self.play( FadeInFromDown(group), LaggedStartMap( Restore, students, run_time=3, lag_ratio=0.3, ) ) self.play( LaggedStart(*[ ApplyMethod(student.change, "hooray") for student in students ]) ) for x in range(3): self.play(Blink(random.choice(students))) self.wait() # def animate_name_abbreviation(self, test): name = test.name short_name = test.short_name short_name.move_to(name, LEFT) name.generate_target() for p1, p2 in zip(name.target, short_name): for letter in p1: letter.move_to(p2[0]) letter.set_opacity(0) p1[0].set_opacity(1) self.add(test.rect, test.name, test.ns_label) self.play( FadeIn(test.rect), MoveToTarget(name), FadeIn(test.ns_label), ) test.remove(name) test.add(short_name) self.remove(name) self.add(short_name) def get_test(self, name_parts, n_questions, time_string, hours, n_students): T_COLOR = GREEN_B Q_COLOR = YELLOW name = OldTexText(*name_parts) short_name = OldTexText(*[np[0] for np in name_parts]) if n_questions: nq_label = VGroup( Integer(n_questions), OldTexText("questions") ) nq_label.arrange(RIGHT) else: nq_label = OldTexText("Lots of training") nq_label.set_color(Q_COLOR) if time_string: t_label = OldTexText(time_string) t_label.set_color(T_COLOR) else: t_label = Integer(0).set_opacity(0) clock = Clock() clock.hour_hand.set_opacity(0) clock.minute_hand.set_opacity(0) clock.set_stroke(WHITE, 2) if hours: sector = Sector( start_angle=TAU / 4, angle=-TAU * (hours / 12), outer_radius=clock.get_width() / 2, arc_center=clock.get_center() ) sector.set_fill(T_COLOR, 0.5) sector.set_stroke(T_COLOR, 2) clock.add(sector) if hours == 4.5: plus = OldTex("+").scale(2) plus.next_to(clock, RIGHT) clock_copy = clock.copy() clock_copy.next_to(plus, RIGHT) clock.add(plus, clock_copy) else: clock.set_opacity(0) clock.set_height(1) clock.next_to(t_label, RIGHT, buff=MED_LARGE_BUFF) t_label.add(clock) ns_label = OldTexText("$\\sim${:,} students".format(n_students)) result = VGroup( name, nq_label, t_label, ns_label, ) result.arrange( DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT, ) rect = SurroundingRectangle(result, buff=MED_SMALL_BUFF) rect.set_width( result[1:].get_width() + MED_LARGE_BUFF, about_edge=LEFT, stretch=True, ) rect.set_stroke(WHITE, 2) rect.set_fill(BLACK, 1) result.add_to_back(rect) result.name = name result.short_name = short_name result.nq_label = nq_label result.t_label = t_label result.ns_label = ns_label result.rect = rect result.clock = clock return result class Describe2011IMO(IntroduceIMO): CONFIG = { "year": 2011, "use_real_images": True, "n_flag_rows": 10, "student_data": [ [1, "Lisa Sauermann", "de", [7, 7, 7, 7, 7, 7]], [2, "Jeck Lim", "sg", [7, 5, 7, 7, 7, 7]], [3, "Lin Chen", "cn", [7, 3, 7, 7, 7, 7]], [4, "Jun Jie Joseph Kuan", "sg", [7, 7, 7, 7, 7, 1]], [4, "David Yang", "us", [7, 7, 7, 7, 7, 1]], [6, "Jie Jun Ang", "sg", [7, 7, 7, 7, 7, 0]], [6, "Kensuke Yoshida", "jp", [7, 6, 7, 7, 7, 1]], [6, "Raul Sarmiento", "pe", [7, 7, 7, 7, 7, 0]], [6, "Nipun Pitimanaaree", "th", [7, 7, 7, 7, 7, 0]], ], } def construct(self): self.add_title() self.add_flags_and_students() self.comment_on_primality() self.show_top_three_scorers() def add_title(self): year = OldTex("2011") logo = ImageMobject("imo_logo") imo = OldTexText("IMO") group = Group(year, logo, imo) group.scale(1.25) logo.set_height(1) group.arrange(RIGHT) group.to_corner(UR, buff=MED_SMALL_BUFF) group.shift(LEFT) self.add(group) self.play(FadeIn(year, RIGHT)) self.title = group def add_flags_and_students(self): flags = self.get_flags() flags.space_out_submobjects(0.8) sf = 0.8 flags.stretch(sf, 0) for flag in flags: flag.stretch(1 / sf, 0) flags.set_height(5) flags.to_corner(DL) student_groups = VGroup(*[ self.get_students(flag) for flag in flags ]) student_groups.arrange_in_grid( n_rows=self.n_flag_rows, buff=SMALL_BUFF, ) student_groups[-1].align_to(student_groups, LEFT) student_groups.set_height(6) student_groups.next_to(self.title, DOWN) flags.align_to(student_groups, UP) all_students = VGroup(*it.chain(*[ [ student for student in group if student.get_fill_opacity() > 0 ] for group in student_groups ])) # Counters student_counter = VGroup( Integer(0), OldTexText("Participants"), ) student_counter.set = all_students student_counter.next_to(self.title, LEFT, MED_LARGE_BUFF) student_counter.right_edge = student_counter.get_right() def update_counter(counter): counter[0].set_value(len(counter.set)) counter.arrange(RIGHT) counter[0].align_to(counter[1][0][0], DOWN) counter.move_to(counter.right_edge, RIGHT) student_counter.add_updater(update_counter) flag_counter = VGroup( Integer(0), OldTexText("Countries") ) flag_counter.set = flags flag_counter.next_to(student_counter, LEFT, buff=0.75) flag_counter.align_to(student_counter[0], DOWN) flag_counter.right_edge = flag_counter.get_right() flag_counter.add_updater(update_counter) self.add(student_counter) self.play( ShowIncreasingSubsets(all_students), run_time=3, ) self.wait() self.add(flag_counter) self.play( ShowIncreasingSubsets(flags), run_time=3, ) self.wait() self.student_counter = student_counter self.flag_counter = flag_counter self.all_students = all_students self.student_groups = student_groups self.flags = flags def comment_on_primality(self): full_rect = FullScreenFadeRectangle(opacity=0.9) numbers = VGroup( self.title[0], self.student_counter[0], self.flag_counter[0], ) lines = VGroup(*[ Line().match_width(number).next_to(number, DOWN, SMALL_BUFF) for number in numbers ]) lines.set_stroke(TEAL, 2) randy = Randolph() randy.to_corner(DL) randy.look_at(numbers) words = VGroup(*[ OldTexText("Prime").next_to(line, DOWN) for line in reversed(lines) ]) words.match_color(lines) self.add(full_rect, numbers) self.play( FadeIn(full_rect), randy.change, "sassy", VFadeIn(randy), ) self.play( ShowCreation(lines), randy.change, "pondering", ) self.play(Blink(randy)) self.play( randy.change, "thinking", LaggedStart(*[ FadeIn(word, UP) for word in words ], run_time=3, lag_ratio=0.5) ) self.play(Blink(randy)) self.play( FadeOut(randy), FadeOut(words), ) self.play(FadeOut(full_rect), FadeOut(lines)) def show_top_three_scorers(self): student_groups = self.student_groups all_students = self.all_students flags = self.flags student_counter = self.student_counter flag_counter = self.flag_counter student = student_groups[10][0] flag = flags[10] students_to_fade = VGroup(*filter( lambda s: s is not student, all_students )) flags_to_fade = Group(*filter( lambda s: s is not flag, flags )) grid = self.get_score_grid() grid.shift(3 * DOWN) title_row = grid.rows[0] top_row = grid.rows[1] self.play( LaggedStartMap(FadeOutAndShiftDown, students_to_fade), LaggedStartMap(FadeOutAndShiftDown, flags_to_fade), ChangeDecimalToValue(student_counter[0], 1), FadeOut(flag_counter), run_time=2 ) student_counter[1][0][-1].fade(1) self.play( Write(top_row[0]), ReplacementTransform(student, top_row[1][1]), flag.replace, top_row[1][0], ) self.remove(flag) self.add(top_row[1]) self.play( LaggedStartMap(FadeIn, title_row[2:]), LaggedStartMap(FadeIn, top_row[2:]), ) self.wait() self.play( LaggedStart(*[ FadeIn(row, UP) for row in grid.rows[2:4] ]), LaggedStart(*[ ShowCreation(line) for line in grid.h_lines[:2] ]), lag_ratio=0.5, ) self.wait() self.play( ShowCreationThenFadeAround( Group(title_row[3], grid.rows[3][3]), ) ) self.wait() student_counter.clear_updaters() self.play( FadeOut(self.title, UP), FadeOut(student_counter, UP), grid.rows[:4].shift, 3 * UP, grid.h_lines[:3].shift, 3 * UP, ) remaining_rows = grid.rows[4:] remaining_lines = grid.h_lines[3:] Group(remaining_rows, remaining_lines).shift(3 * UP) self.play( LaggedStartMap( FadeInFrom, remaining_rows, lambda m: (m, UP), ), LaggedStartMap(ShowCreation, remaining_lines), lag_ratio=0.3, run_time=2, ) self.wait() def get_score_grid(self): data = self.student_data ranks = VGroup(*[ Integer(row[0]) for row in data ]) # Combine students with flags students = VGroup(*[ OldTexText(row[1]) for row in data ]) flags = Group(*[ ImageMobject("flags/{}.png".format(row[2])).set_height(0.3) for row in data ]) students = Group(*[ Group(flag.next_to(student, LEFT, buff=0.2), student) for flag, student in zip(flags, students) ]) score_rows = VGroup(*[ VGroup(*map(Integer, row[3])) for row in data ]) colors = color_gradient([RED, YELLOW, GREEN], 8) for score_row in score_rows: for score in score_row: score.set_color(colors[score.get_value()]) titles = VGroup(*[ VectorizedPoint(), VectorizedPoint(), *[ OldTexText("P{}".format(i)) for i in range(1, 7) ] ]) titles.arrange(RIGHT, buff=MED_LARGE_BUFF) titles[2:].shift(students.get_width() * RIGHT) rows = Group(titles, *[ Group(rank, student, *score_row) for rank, flag, student, score_row in zip( ranks, flags, students, score_rows ) ]) rows.arrange(DOWN) rows.to_edge(UP) for row in rows: for i, e1, e2 in zip(it.count(), titles, row): if i < 2: e2.align_to(e1, LEFT) else: e2.match_x(e1) ranks.next_to(students, LEFT) h_lines = VGroup() for r1, r2 in zip(rows[1:], rows[2:]): line = Line() line.set_stroke(WHITE, 0.5) line.match_width(r2) line.move_to(midpoint(r1.get_bottom(), r2.get_top())) line.align_to(r2, LEFT) h_lines.add(line) grid = Group(rows, h_lines) grid.rows = rows grid.h_lines = h_lines return grid class AskWhatsOnTest(ShowTest, MovingCameraScene): def construct(self): self.force_skipping() self.introduce_test() self.revert_to_original_skipping_status() self.ask_about_questions() def ask_about_questions(self): scores = self.scores arrows = self.proof_arrows proof_words = self.proof_words question = OldTexText("What kind \\\\ of problems?") question.scale(1.5) question.move_to(proof_words, LEFT) research = OldTexText("Research-lite") research.scale(1.5) research.move_to(question, LEFT) research.shift(MED_SMALL_BUFF * RIGHT) research.set_color(BLUE) arrows.generate_target() for arrow in arrows.target: end = arrow.get_end() start = arrow.get_start() arrow.put_start_and_end_on( interpolate(question.get_left(), start, 0.1), end ) self.play( FadeOut(scores), FadeOut(proof_words), MoveToTarget(arrows), Write(question), ) self.wait() self.play( FadeIn(research, DOWN), question.shift, 2 * UP, ) self.wait() # Experience randy = Randolph(height=2) randy.move_to(research.get_corner(UL), DL) randy.shift(SMALL_BUFF * RIGHT) clock = Clock() clock.set_height(1) clock.next_to(randy, UR) self.play( FadeOut(question), FadeIn(randy), FadeInFromDown(clock), ) self.play( randy.change, "pondering", ClockPassesTime(clock, run_time=5, hours_passed=5), ) self.play( ClockPassesTime(clock, run_time=2, hours_passed=2), VFadeOut(clock), Blink(randy), VFadeOut(randy), LaggedStartMap( FadeOut, VGroup( research, *arrows, *self.problem_rects, self.time_labels[0] ) ), ) # Second part big_rect = FullScreenFadeRectangle() lil_rect = self.problem_rects[1].copy() lil_rect.reverse_points() big_rect.append_vectorized_mobject(lil_rect) frame = self.camera_frame frame.generate_target() frame.target.scale(0.35) frame.target.move_to(lil_rect) self.play( FadeInFromDown(self.test[1]), ) self.wait() self.play( FadeIn(big_rect), MoveToTarget(frame, run_time=6), ) self.wait() class ReadQuestions(Scene): def construct(self): background = ImageMobject("AskWhatsOnTest_final_image") background.set_height(FRAME_HEIGHT) self.add(background) lines = SVGMobject("imo_2011_2_underline-01") lines.set_width(FRAME_WIDTH - 1) lines.move_to(0.1 * DOWN) lines.set_stroke(TEAL, 3) clump_sizes = [1, 2, 3, 2, 1, 2] partial_sums = list(np.cumsum(clump_sizes)) clumps = VGroup(*[ lines[i:j] for i, j in zip( [0] + partial_sums, partial_sums, ) ]) faders = [] for clump in clumps: rects = VGroup() for line in clump: rect = Rectangle() rect.set_stroke(width=0) rect.set_fill(TEAL, 0.25) rect.set_width(line.get_width() + SMALL_BUFF) rect.set_height(0.35, stretch=True) rect.move_to(line, DOWN) rects.add(rect) self.play( ShowCreation(clump, run_time=2), FadeIn(rects), *faders, ) self.wait() faders = [ FadeOut(clump), FadeOut(rects), ] self.play(*faders) self.wait() # Windmill scenes class WindmillScene(Scene): CONFIG = { "dot_config": { "fill_color": GREY_B, "radius": 0.05, "background_stroke_width": 2, "background_stroke_color": BLACK, }, "windmill_style": { "stroke_color": RED, "stroke_width": 2, "background_stroke_width": 3, "background_stroke_color": BLACK, }, "windmill_length": 2 * FRAME_WIDTH, "windmill_rotation_speed": 0.25, # "windmill_rotation_speed": 0.5, # "hit_sound": "pen_click.wav", "hit_sound": "pen_click.wav", "leave_shadows": False, } def get_random_point_set(self, n_points=11, width=6, height=6): return np.array([ [ -width / 2 + np.random.random() * width, -height / 2 + np.random.random() * height, 0 ] for n in range(n_points) ]) def get_dots(self, points): return VGroup(*[ Dot(point, **self.dot_config) for point in points ]) def get_windmill(self, points, pivot=None, angle=TAU / 4): line = Line(LEFT, RIGHT) line.set_length(self.windmill_length) line.set_angle(angle) line.set_style(**self.windmill_style) line.point_set = points if pivot is not None: line.pivot = pivot else: line.pivot = points[0] line.rot_speed = self.windmill_rotation_speed line.add_updater(lambda l: l.move_to(l.pivot)) return line def get_pivot_dot(self, windmill, color=YELLOW): pivot_dot = Dot(color=YELLOW) pivot_dot.add_updater(lambda d: d.move_to(windmill.pivot)) return pivot_dot def start_leaving_shadows(self): self.leave_shadows = True self.add(self.get_windmill_shadows()) def get_windmill_shadows(self): if not hasattr(self, "windmill_shadows"): self.windmill_shadows = VGroup() return self.windmill_shadows def next_pivot_and_angle(self, windmill): curr_angle = windmill.get_angle() pivot = windmill.pivot non_pivots = list(filter( lambda p: not np.all(p == pivot), windmill.point_set )) angles = np.array([ -(angle_of_vector(point - pivot) - curr_angle) % PI for point in non_pivots ]) # Edge case for 2 points tiny_indices = angles < 1e-6 if np.all(tiny_indices): return non_pivots[0], PI angles[tiny_indices] = np.inf index = np.argmin(angles) return non_pivots[index], angles[index] def rotate_to_next_pivot(self, windmill, max_time=None, added_anims=None): """ Returns animations to play following the contact, and total run time """ new_pivot, angle = self.next_pivot_and_angle(windmill) change_pivot_at_end = True if added_anims is None: added_anims = [] run_time = angle / windmill.rot_speed if max_time is not None and run_time > max_time: ratio = max_time / run_time rate_func = (lambda t: ratio * t) run_time = max_time change_pivot_at_end = False else: rate_func = linear for anim in added_anims: if anim.run_time > run_time: anim.run_time = run_time self.play( Rotate( windmill, -angle, rate_func=rate_func, run_time=run_time, ), *added_anims, ) if change_pivot_at_end: self.handle_pivot_change(windmill, new_pivot) # Return animations to play return [self.get_hit_flash(new_pivot)], run_time def handle_pivot_change(self, windmill, new_pivot): windmill.pivot = new_pivot self.add_sound(self.hit_sound) if self.leave_shadows: new_shadow = windmill.copy() new_shadow.fade(0.5) new_shadow.set_stroke(width=1) new_shadow.clear_updaters() shadows = self.get_windmill_shadows() shadows.add(new_shadow) def let_windmill_run(self, windmill, time): # start_time = self.get_time() # end_time = start_time + time # curr_time = start_time anims_from_last_hit = [] while time > 0: anims_from_last_hit, last_run_time = self.rotate_to_next_pivot( windmill, max_time=time, added_anims=anims_from_last_hit, ) time -= last_run_time # curr_time = self.get_time() def add_dot_color_updater(self, dots, windmill, **kwargs): for dot in dots: dot.add_updater(lambda d: self.update_dot_color( d, windmill, **kwargs )) def update_dot_color(self, dot, windmill, color1=BLUE, color2=GREY_BROWN): perp = rotate_vector(windmill.get_vector(), TAU / 4) dot_product = np.dot(perp, dot.get_center() - windmill.pivot) if dot_product > 0: dot.set_color(color1) # elif dot_product < 0: else: dot.set_color(color2) # else: # dot.set_color(WHITE) dot.set_stroke( # interpolate_color(dot.get_fill_color(), WHITE, 0.5), WHITE, width=2, background=True ) def get_hit_flash(self, point): flash = Flash( point, line_length=0.1, flash_radius=0.2, run_time=0.5, remover=True, ) flash_mob = flash.mobject for submob in flash_mob: submob.reverse_points() return Uncreate( flash.mobject, run_time=0.25, lag_ratio=0, ) def get_pivot_counters(self, windmill, counter_height=0.25, buff=0.2, color=WHITE): points = windmill.point_set counters = VGroup() for point in points: counter = Integer(0) counter.set_color(color) counter.set_height(counter_height) counter.next_to(point, UP, buff=buff) counter.point = point counter.windmill = windmill counter.is_pivot = False counter.add_updater(self.update_counter) counters.add(counter) return counters def update_counter(self, counter): dist = get_norm(counter.point - counter.windmill.pivot) counter.will_be_pivot = (dist < 1e-6) if (not counter.is_pivot) and counter.will_be_pivot: counter.increment_value() counter.is_pivot = counter.will_be_pivot def get_orientation_arrows(self, windmill, n_tips=20): tips = VGroup(*[ ArrowTip(start_angle=0) for x in range(n_tips) ]) tips.stretch(0.75, 1) tips.scale(0.5) tips.rotate(windmill.get_angle()) tips.match_color(windmill) tips.set_stroke(BLACK, 1, background=True) for tip, a in zip(tips, np.linspace(0, 1, n_tips)): tip.shift( windmill.point_from_proportion(a) - tip.get_points()[0] ) return tips def get_left_right_colorings(self, windmill, opacity=0.3): rects = VGroup(VMobject(), VMobject()) rects.const_opacity = opacity def update_regions(rects): p0, p1 = windmill.get_start_and_end() v = p1 - p0 vl = rotate_vector(v, 90 * DEGREES) vr = rotate_vector(v, -90 * DEGREES) p2 = p1 + vl p3 = p0 + vl p4 = p1 + vr p5 = p0 + vr rects[0].set_points_as_corners([p0, p1, p2, p3]) rects[1].set_points_as_corners([p0, p1, p4, p5]) rects.set_stroke(width=0) rects[0].set_fill(BLUE, rects.const_opacity) rects[1].set_fill(GREY_BROWN, rects.const_opacity) return rects rects.add_updater(update_regions) return rects class IntroduceWindmill(WindmillScene): CONFIG = { "final_run_time": 60, "windmill_rotation_speed": 0.5, } def construct(self): self.add_points() self.exclude_colinear() self.add_line() self.switch_pivots() self.continue_and_count() def add_points(self): points = self.get_random_point_set(8) points[-1] = midpoint(points[0], points[1]) dots = self.get_dots(points) dots.set_color(YELLOW) dots.set_height(3) braces = VGroup( Brace(dots, LEFT), Brace(dots, RIGHT), ) group = VGroup(dots, braces) group.set_height(4) group.center().to_edge(DOWN) S, eq = S_eq = OldTex("\\mathcal{S}", "=") S_eq.scale(2) S_eq.next_to(braces, LEFT) self.play( FadeIn(S_eq), FadeIn(braces[0], RIGHT), FadeIn(braces[1], LEFT), ) self.play( LaggedStartMap(FadeInFromLarge, dots) ) self.wait() self.play( S.next_to, dots, LEFT, {"buff": 2, "aligned_edge": UP}, FadeOut(braces), FadeOut(eq), ) self.S_label = S self.dots = dots def exclude_colinear(self): dots = self.dots line = Line(dots[0].get_center(), dots[1].get_center()) line.scale(1.5) line.set_stroke(WHITE) words = OldTexText("Not allowed!") words.scale(2) words.set_color(RED) words.next_to(line.get_center(), RIGHT) self.add(line, dots) self.play( ShowCreation(line), FadeIn(words, LEFT), dots[-1].set_color, RED, ) self.wait() self.play( FadeOut(line), FadeOut(words), ) self.play( FadeOut( dots[-1], 3 * RIGHT, path_arc=-PI / 4, rate_func=running_start, ) ) dots.remove(dots[-1]) self.wait() def add_line(self): dots = self.dots points = np.array(list(map(Mobject.get_center, dots))) p0 = points[0] windmill = self.get_windmill(points, p0, angle=60 * DEGREES) pivot_dot = self.get_pivot_dot(windmill) l_label = OldTex("\\ell") l_label.scale(1.5) p_label = OldTex("P") l_label.next_to( p0 + 2 * normalize(windmill.get_vector()), RIGHT, ) l_label.match_color(windmill) p_label.next_to(p0, RIGHT) p_label.match_color(pivot_dot) arcs = VGroup(*[ Arc(angle=-45 * DEGREES, radius=1.5) for x in range(2) ]) arcs[1].rotate(PI, about_point=ORIGIN) for arc in arcs: arc.add_tip(tip_length=0.2) arcs.rotate(windmill.get_angle()) arcs.shift(p0) self.add(windmill, dots) self.play( GrowFromCenter(windmill), FadeIn(l_label, DL), ) self.wait() self.play( TransformFromCopy(pivot_dot, p_label), GrowFromCenter(pivot_dot), dots.set_color, WHITE, ) self.wait() self.play(*map(ShowCreation, arcs)) self.wait() # Rotate to next pivot next_pivot, angle = self.next_pivot_and_angle(windmill) self.play( *[ Rotate( mob, -0.99 * angle, about_point=p0, rate_func=linear, ) for mob in [windmill, arcs, l_label] ], VFadeOut(l_label), ) self.add_sound(self.hit_sound) self.play( self.get_hit_flash(next_pivot) ) self.wait() self.pivot2 = next_pivot self.pivot_dot = pivot_dot self.windmill = windmill self.p_label = p_label self.arcs = arcs def switch_pivots(self): windmill = self.windmill pivot2 = self.pivot2 p_label = self.p_label arcs = self.arcs q_label = OldTex("Q") q_label.set_color(YELLOW) q_label.next_to(pivot2, DR, buff=SMALL_BUFF) self.rotate_to_next_pivot(windmill) self.play( FadeIn(q_label, LEFT), FadeOut(p_label), FadeOut(arcs), ) self.wait() flashes, run_time = self.rotate_to_next_pivot(windmill) self.remove(q_label) self.add_sound(self.hit_sound) self.play(*flashes) self.wait() self.let_windmill_run(windmill, 10) def continue_and_count(self): windmill = self.windmill pivot_dot = self.pivot_dot p_label = OldTex("P") p_label.match_color(pivot_dot) p_label.next_to(pivot_dot, DR, buff=0) l_label = OldTex("\\ell") l_label.scale(1.5) l_label.match_color(windmill) l_label.next_to( windmill.get_center() + -3 * normalize(windmill.get_vector()), DR, buff=SMALL_BUFF, ) self.play(FadeIn(p_label, UL)) self.play(FadeIn(l_label, LEFT)) self.wait() self.add( windmill.copy().fade(0.75), pivot_dot.copy().fade(0.75), ) pivot_counters = self.get_pivot_counters(windmill) self.add(pivot_counters) windmill.rot_speed *= 2 self.let_windmill_run(windmill, self.final_run_time) class ContrastToOtherOlympiadProblems(AskWhatsOnTest): def construct(self): self.zoom_to_other_questions() def zoom_to_other_questions(self): test = self.get_test() rects = self.get_all_rects() big_rects = VGroup() for rect in rects: big_rect = FullScreenFadeRectangle() rect.reverse_points() big_rect.append_vectorized_mobject(rect) big_rects.add(big_rect) frame = self.camera_frame frame.generate_target() frame.target.scale(0.35) frame.target.move_to(rects[1]) big_rect = big_rects[1].copy() self.add(test) self.play( FadeIn(big_rect), MoveToTarget(frame, run_time=3), ) self.wait() for i in [2, 0, 3, 5]: self.play( frame.move_to, rects[i], Transform(big_rect, big_rects[i]) ) self.wait() def get_all_rects(self, test): rects = self.get_problem_rects(test[0]) new_rects = VGroup(rects[1], rects[0], rects[2]).copy() new_rects[0].stretch(0.85, 1) new_rects[1].stretch(0.8, 1) new_rects[2].stretch(0.8, 1) new_rects.arrange(DOWN, buff=0.08) new_rects.move_to(test[1]) new_rects.align_to(rects, UP) rects.add(*new_rects) return rects class WindmillExample30Points(WindmillScene): CONFIG = { "n_points": 30, "random_seed": 0, "run_time": 60, "counter_config": { "counter_height": 0.15, "buff": 0.1, }, } def construct(self): points = self.get_random_point_set(self.n_points) points[:, 0] *= 1.5 sorted_points = sorted(list(points), key=lambda p: p[1]) sorted_points[4] += RIGHT dots = self.get_dots(points) windmill = self.get_windmill(points, sorted_points[5], angle=PI / 4) pivot_dot = self.get_pivot_dot(windmill) # self.add_dot_color_updater(dots, windmill) self.add(windmill) self.add(dots) self.add(pivot_dot) self.add(self.get_pivot_counters( windmill, **self.counter_config )) self.let_windmill_run(windmill, self.run_time) class WindmillExample15Points(WindmillExample30Points): CONFIG = { "n_points": 15, "run_time": 60, "random_seed": 2, "counter_config": { "counter_height": 0.25, "buff": 0.1, }, } class TheQuestion(Scene): def construct(self): words = OldTexText( "Will each point be hit infinitely many times?" ) words.set_width(FRAME_WIDTH - 1) words.to_edge(UP) self.add(words) class SpiritOfIMO(PiCreatureScene): def construct(self): randy = self.pi_creature problems = VGroup(*[ OldTexText("P{})".format(i)) for i in range(1, 7) ]) problems.arrange_in_grid(n_cols=2, buff=LARGE_BUFF) problems.scale(1.5) problems[3:].shift(1.5 * RIGHT) problems.to_corner(UR, buff=LARGE_BUFF) problems.shift(2 * LEFT) light_bulbs = VGroup() lights = VGroup() for problem in problems: light_bulb = Lightbulb() light_bulb.base = light_bulb[:3] light_bulb.light = light_bulb[3:] light_bulb.set_height(1) light_bulb.next_to(problem, RIGHT) light_bulbs.add(light_bulb) light = self.get_light(light_bulb.get_center()) lights.add(light) self.play( LaggedStartMap(FadeInFromDown, problems) ) self.play( LaggedStartMap( FadeIn, light_bulbs, run_time=1, ), LaggedStartMap( LaggedStartMap, lights, lambda l: (VFadeInThenOut, l), run_time=3 ), randy.change, "thinking" ) self.wait() self.pi_creature_thinks( "Oh, I've\\\\seen this...", target_mode="surprised", ) self.wait(3) def get_light(self, point): radii = np.arange(0, 5, 0.1) result = VGroup(*[ Annulus( inner_radius=r1, outer_radius=r2, arc_center=point, fill_opacity=(1 / (r1 + 1)**2), fill_color=YELLOW, ) for r1, r2 in zip(radii[1:], radii[2:]) ]) return result # TODO class HowToPrepareForThis(Scene): def construct(self): pass class HarderThanExpected(TeacherStudentsScene): def construct(self): title = OldTexText("Unusual aspect \\#2") title.scale(1.5) title.to_edge(UP) line = Line(LEFT, RIGHT) line.match_width(title) line.next_to(title, DOWN) words = OldTexText("Harder than expected") words.set_color(RED) words.scale(1.5) words.next_to(line, DOWN, LARGE_BUFF) self.play( FadeInFromDown(title), ShowCreation(line), self.teacher.change, "raise_right_hand", self.change_students("pondering", "confused", "sassy") ) self.wait() self.play( FadeIn(words, UP), self.change_students(*3 * ["horrified"]), ) self.wait(3) class TraditionalDifficulty(ContrastToOtherOlympiadProblems): def construct(self): test = self.get_test() rects = self.get_all_rects(test) for rect in rects: rect.reverse_points() big_rects = VGroup(*[ FullScreenFadeRectangle() for x in range(3) ]) for br, r1, r2 in zip(big_rects, rects, rects[3:]): br.append_vectorized_mobject(r1) br.append_vectorized_mobject(r2) big_rect = big_rects[0].copy() p_labels = VGroup() for i, rect in enumerate(rects): p_label = OldTexText("P{}".format(i + 1)) p_label.next_to(rect, LEFT) p_labels.add(p_label) arrow = Vector(3 * DOWN) arrow.next_to(test[0], RIGHT) arrow.match_y(rects) harder_words = OldTexText("Get harder") harder_words.scale(2) harder_words.next_to(arrow, RIGHT) harder_words.set_color(RED) p_words = VGroup( OldTexText("Doable", color=GREEN), OldTexText("Challenging", color=YELLOW), OldTexText("Brutal", color=RED), ) p_words.add(*p_words.copy()) for rect, word, label in zip(rects, p_words, p_labels): word.next_to(rect, UP) label.match_color(word) self.add(test[0]) self.play( FadeIn(harder_words), GrowArrow(arrow), LaggedStart(*[FadeIn(p, UP) for p in p_labels[:3]]), LaggedStartMap(ShowCreation, rects[:3]), ) self.wait() self.play( FadeIn(test[1]), FadeIn(p_labels[3:]), FadeIn(rects[3:]), FadeOut(harder_words), FadeOut(arrow), ) self.wait() self.add(big_rect, p_labels[0], p_labels[3]) self.play( FadeIn(big_rect), FadeOut(rects), FadeOut(p_labels[1:3]), FadeOut(p_labels[4:]), FadeInFromDown(p_words[0::3]), ) self.wait() self.play( Transform(big_rect, big_rects[1]), FadeOut(p_labels[0::3]), FadeIn(p_labels[1::3]), FadeOut(p_words[0::3], DOWN), FadeIn(p_words[1::3], UP), ) self.wait() self.play( Transform(big_rect, big_rects[2]), FadeOut(p_labels[1::3]), FadeIn(p_labels[2::3]), FadeOut(p_words[1::3], DOWN), FadeIn(p_words[2::3], UP), ) self.wait() class PerfectScoreData(Describe2011IMO): CONFIG = { "n_students": 563, "n_perfect_scores_per_problem": [ 345, 22, 51, 267, 170, 6, ], "full_bar_width": 7, } def construct(self): self.add_title() self.show_total_number_of_students() self.add_subtitle() self.show_data() self.analyze_data() def add_title(self): self.force_skipping() super().add_title() self.revert_to_original_skipping_status() self.title.center().to_edge(UP) def show_total_number_of_students(self): title = self.title bar = self.get_bar(self.n_students, ORIGIN) bar.next_to(title, DOWN, buff=0.3) counter = self.get_bar_counter(bar) counter_label = OldTexText("Students") counter_label.add_updater( lambda m: m.next_to(counter, RIGHT) ) self.add(counter, counter_label) self.play( self.get_bar_growth_anim(bar), run_time=2, ) self.wait() def add_subtitle(self): title = self.title subtitle = OldTexText( "Number of perfect scores on each problem:" ) subtitle.scale(1.25) subtitle.set_color(GREEN) subtitle.next_to(title, DOWN, buff=LARGE_BUFF) problems = VGroup(*[ OldTexText("P{})".format(i)) for i in range(1, 7) ]) problems.arrange_in_grid(n_cols=2, buff=LARGE_BUFF) problems[3:].shift(5 * RIGHT) problems.next_to(subtitle, DOWN, LARGE_BUFF) problems.to_edge(LEFT) self.play( FadeInFromDown(subtitle), LaggedStartMap(FadeInFromDown, problems), ) self.problems = problems def show_data(self): problems = self.problems bars = VGroup(*[ self.get_bar(n, p.get_right() + SMALL_BUFF * RIGHT) for n, p in zip( self.n_perfect_scores_per_problem, problems, ) ]) counters = VGroup(*map(self.get_bar_counter, bars)) self.play( VFadeIn(counters), *[ self.get_bar_growth_anim(bar) for bar in bars ], ) counters.set_fill(WHITE, 1) self.wait() self.problem_bars = bars self.problem_counters = counters def analyze_data(self): problems = VGroup(*[ VGroup(p, pb, pc) for p, pb, pc in zip( self.problems, self.problem_bars, self.problem_counters, ) ]) rects = VGroup(*[ SurroundingRectangle(p, color=p[1].get_color()) for p in problems ]) rect = rects[1].copy() self.play(ShowCreation(rect)) self.wait() self.play(TransformFromCopy(rect, rects[4])) self.wait() self.play(TransformFromCopy(rect, rects[2])) self.wait() self.play( ReplacementTransform(rect, rects[5]), ReplacementTransform(rects[4], rects[5]), ReplacementTransform(rects[2], rects[5]), ) self.wait() # def get_bar(self, number, left_side): bar = Rectangle() bar.set_stroke(width=0) bar.set_fill(WHITE, 1) bar.set_height(0.25) bar.set_width( self.full_bar_width * number / self.n_students, stretch=True ) bar.move_to(left_side, LEFT) def update_bar_color(bar): frac = bar.get_width() / self.full_bar_width if 0 < frac <= 0.25: alpha = 4 * frac bar.set_color(interpolate_color(RED, YELLOW, alpha)) elif 0.25 < frac <= 0.5: alpha = 4 * (frac - 0.25) bar.set_color(interpolate_color(YELLOW, GREEN, alpha)) else: alpha = 2 * (frac - 0.5) bar.set_color(interpolate_color(GREEN, BLUE, alpha)) bar.add_updater(update_bar_color) return bar def get_bar_growth_anim(self, bar): bar.save_state() bar.stretch(0, 0, about_edge=LEFT) return Restore( bar, suspend_mobject_updating=False, run_time=2, ) def get_bar_counter(self, bar): counter = Integer() counter.add_updater( lambda m: m.set_value( self.n_students * bar.get_width() / self.full_bar_width ) ) counter.add_updater(lambda m: m.next_to(bar, RIGHT, SMALL_BUFF)) return counter class SixOnSix(Describe2011IMO): CONFIG = { "student_data": [ [1, "Lisa Sauermann", "de", [7, 7, 7, 7, 7, 7]], [2, "Jeck Lim", "sg", [7, 5, 7, 7, 7, 7]], [3, "Lin Chen", "cn", [7, 3, 7, 7, 7, 7]], [14, "Mina Dalirrooyfard", "ir", [7, 0, 2, 7, 7, 7]], [202, "Georgios Kalantzis", "gr", [7, 0, 1, 1, 2, 7]], [202, "Chi Hong Chow", "hk", [7, 0, 3, 1, 0, 7]], ], } def construct(self): grid = self.get_score_grid() grid.to_edge(DOWN, buff=LARGE_BUFF) for row in grid.rows: row[0].set_opacity(0) grid.h_lines.stretch(0.93, 0, about_edge=RIGHT) sf = 1.25 title = OldTexText("Only 6 solved P6") title.scale(sf) title.to_edge(UP, buff=MED_SMALL_BUFF) subtitle = OldTexText("P2 evaded 5 of them") subtitle.set_color(YELLOW) subtitle.scale(sf) subtitle.next_to(title, DOWN) six_rect, two_rect = [ SurroundingRectangle(VGroup( grid.rows[0][index], grid.rows[-1][index], )) for index in [7, 3] ] self.play( Write(title), LaggedStart(*[FadeIn(row, UP) for row in grid.rows]), LaggedStart(*[ShowCreation(line) for line in grid.h_lines]), ) self.play(ShowCreation(six_rect)) self.wait() self.play( ReplacementTransform(six_rect, two_rect), FadeIn(subtitle, UP) ) self.wait() class AlwaysStartSimple(TeacherStudentsScene): def construct(self): self.teacher_says("Always start\\\\simple") self.play_all_student_changes("pondering") self.wait(3) class TryOutSimplestExamples(WindmillScene): CONFIG = { "windmill_rotation_speed": TAU / 8, } def construct(self): self.two_points() self.add_third_point() self.add_fourth_point() self.move_starting_line() def two_points(self): points = [1.5 * LEFT, 1.5 * RIGHT] dots = self.dots = self.get_dots(points) windmill = self.windmill = self.get_windmill(points, angle=TAU / 8) pivot_dot = self.pivot_dot = self.get_pivot_dot(windmill) self.play( ShowCreation(windmill), LaggedStartMap( FadeInFromLarge, dots, scale_factor=10, run_time=1, lag_ratio=0.4, ), GrowFromCenter(pivot_dot), ) self.let_windmill_run(windmill, 8) def add_third_point(self): windmill = self.windmill new_point = 2 * DOWN new_dot = self.get_dots([new_point]) windmill.point_set.append(new_point) self.add(new_dot, self.pivot_dot) self.play(FadeInFromLarge(new_dot, scale_factor=10)) self.let_windmill_run(windmill, 8) def add_fourth_point(self): windmill = self.windmill dot = self.get_dots([ORIGIN]) dot.move_to(DOWN + 2 * RIGHT) words = OldTexText("Never hit!") words.set_color(RED) words.scale(0.75) words.move_to(0.7 * DOWN, DOWN) self.add(dot, self.pivot_dot) self.play( FadeInFromLarge(dot, scale_factor=10) ) windmill.point_set.append(dot.get_center()) windmill.rot_speed = TAU / 4 self.let_windmill_run(windmill, 4) # Shift point self.play( dot.next_to, words, DOWN, FadeIn(words, RIGHT), ) windmill.point_set[3] = dot.get_center() self.let_windmill_run(windmill, 4) self.wait() self.dots.add(dot) self.never_hit_words = words def move_starting_line(self): windmill = self.windmill dots = self.dots windmill.suspend_updating() self.play( windmill.move_to, dots[-1], FadeOut(self.never_hit_words), ) windmill.pivot = dots[-1].get_center() windmill.resume_updating() counters = self.get_pivot_counters(windmill) self.play( LaggedStart(*[ FadeIn(counter, DOWN) for counter in counters ]) ) self.wait() windmill.rot_speed = TAU / 8 self.let_windmill_run(windmill, 16) highlight = windmill.copy() highlight.set_stroke(YELLOW, 4) self.play( ShowCreationThenDestruction(highlight), ) self.let_windmill_run(windmill, 8) class FearedCase(WindmillScene): CONFIG = { "n_points": 25, "windmill_rotation_speed": TAU / 16, } def construct(self): points = self.get_random_point_set(self.n_points) sorted_points = sorted(list(points), key=lambda p: p[1]) dots = self.get_dots(points) windmill = self.get_windmill( points, sorted_points[self.n_points // 2], angle=0, ) pivot_dot = self.get_pivot_dot(windmill) # self.add_dot_color_updater(dots, windmill) counters = self.get_pivot_counters( windmill, counter_height=0.15, buff=0.1 ) self.add(windmill) self.add(dots) self.add(pivot_dot) self.add(counters) self.let_windmill_run(windmill, 32) windmill.pivot = sorted_points[0] self.let_windmill_run(windmill, 32) class WhereItStartsItEnds(WindmillScene): CONFIG = { "n_points": 11, "windmill_rotation_speed": TAU / 8, "random_seed": 1, "points_shift_val": 2 * LEFT, } def construct(self): self.show_stays_in_middle() self.ask_about_proof() def show_stays_in_middle(self): points = self.get_random_point_set(self.n_points) points += self.points_shift_val sorted_points = sorted(list(points), key=lambda p: p[1]) dots = self.get_dots(points) windmill = self.get_windmill( points, sorted_points[self.n_points // 2], angle=0 ) pivot_dot = self.get_pivot_dot(windmill) sf = 1.25 start_words = OldTexText("Starts in the ", "``middle''") start_words.scale(sf) start_words.next_to(windmill, UP, MED_SMALL_BUFF) start_words.to_edge(RIGHT) end_words = OldTexText("Stays in the ", "``middle''") end_words.scale(sf) end_words.next_to(windmill, DOWN, MED_SMALL_BUFF) end_words.to_edge(RIGHT) start_words.match_x(end_words) self.add(dots) self.play( ShowCreation(windmill), GrowFromCenter(pivot_dot), FadeIn(start_words, LEFT), ) self.wait() self.start_leaving_shadows() self.add(windmill, dots, pivot_dot) half_time = PI / windmill.rot_speed self.let_windmill_run(windmill, time=half_time) self.play(FadeIn(end_words, UP)) self.wait() self.let_windmill_run(windmill, time=half_time) self.wait() self.start_words = start_words self.end_words = end_words self.windmill = windmill self.dots = dots self.pivot_dot = pivot_dot def ask_about_proof(self): sf = 1.25 middle_rects = self.get_middle_rects() middle_words = OldTexText("Can you formalize this?") middle_words.scale(sf) middle_words.next_to(middle_rects, DOWN, MED_LARGE_BUFF) middle_words.to_edge(RIGHT) middle_words.match_color(middle_rects) proof_words = OldTexText("Can you prove this?") proof_words.next_to( self.end_words.get_left(), DL, buff=2, ) proof_words.shift(RIGHT) proof_words.scale(sf) proof_arrow = Arrow( proof_words.get_top(), self.end_words.get_corner(DL), buff=SMALL_BUFF, ) proof_words2 = OldTexText("Then prove the result?") proof_words2.scale(sf) proof_words2.next_to(middle_words, DOWN, MED_LARGE_BUFF) proof_words2.to_edge(RIGHT) VGroup(proof_words, proof_words2, proof_arrow).set_color(YELLOW) self.play( Write(proof_words), GrowArrow(proof_arrow), run_time=1, ) self.wait() self.play( FadeOut(proof_arrow), FadeOut(proof_words), LaggedStartMap(ShowCreation, middle_rects), Write(middle_words), ) self.wait() self.play(FadeIn(proof_words2, UP)) self.wait() self.let_windmill_run(self.windmill, time=10) def get_middle_rects(self): middle_rects = VGroup(*[ SurroundingRectangle(words[1]) for words in [ self.start_words, self.end_words ] ]) middle_rects.set_color(TEAL) return middle_rects class AltWhereItStartsItEnds(WhereItStartsItEnds): CONFIG = { "n_points": 9, "random_seed": 3, } class FormalizeMiddle(WhereItStartsItEnds): CONFIG = { "random_seed": 2, "points_shift_val": 3 * LEFT, } def construct(self): self.show_stays_in_middle() self.problem_solving_tip() self.define_colors() self.mention_odd_case() self.ask_about_numbers() def problem_solving_tip(self): mid_words = VGroup( self.start_words, self.end_words, ) mid_words.save_state() sf = 1.25 pst = OldTexText("Problem-solving tip:") pst.scale(sf) underline = Line(LEFT, RIGHT) underline.match_width(pst) underline.move_to(pst.get_bottom()) pst.add(underline) pst.to_corner(UR) # pst.set_color(YELLOW) steps = VGroup( OldTexText("Vague idea"), OldTexText("Put numbers to it"), OldTexText("Ask about those numbers"), ) steps.scale(sf) steps.arrange(DOWN, buff=LARGE_BUFF) steps.next_to(pst, DOWN, buff=MED_LARGE_BUFF) steps.shift_onto_screen() pst.match_x(steps) colors = color_gradient([BLUE, YELLOW], 3) for step, color in zip(steps, colors): step.set_color(color) arrows = VGroup() for s1, s2 in zip(steps, steps[1:]): arrow = Arrow(s1.get_bottom(), s2.get_top(), buff=SMALL_BUFF) arrows.add(arrow) self.play(Write(pst), run_time=1) self.wait() self.play( mid_words.scale, 0.75, mid_words.set_opacity, 0.25, mid_words.to_corner, DL, FadeInFromDown(steps[0]), ) self.wait() for arrow, step in zip(arrows, steps[1:]): self.play( FadeIn(step, UP), GrowArrow(arrow), ) self.wait() steps.generate_target() steps.target.scale(0.75) steps.target.arrange(DOWN, buff=0.2) steps.target.to_corner(UR) self.play( FadeOut(pst), MoveToTarget(steps), Restore(mid_words), FadeOut(arrows) ) self.wait() self.tip_words = steps self.mid_words = mid_words def define_colors(self): windmill = self.windmill mid_words = self.mid_words tip_words = self.tip_words shadows = self.windmill_shadows self.leave_shadows = False full_time = TAU / windmill.rot_speed self.play(FadeOut(shadows)) self.add(windmill, tip_words, mid_words, self.dots, self.pivot_dot) self.let_windmill_run(windmill, time=full_time / 4) windmill.rotate(PI) self.wait() # Show regions rects = self.get_left_right_colorings(windmill) rects.suspend_updating() rects.save_state() rects.stretch(0, 0, about_point=windmill.get_center()) counters = VGroup(Integer(0), Integer(0)) counters.scale(2) counters[0].set_stroke(BLUE, 3, background=True) counters[1].set_stroke(GREY_BROWN, 3, background=True) new_dots = self.dots.copy() new_dots.set_color(WHITE) for dot in new_dots: dot.scale(1.25) new_dots.sort(lambda p: p[0]) k = self.n_points // 2 dot_sets = VGroup(new_dots[:k], new_dots[-k:]) label_sets = VGroup() for dot_set, direction in zip(dot_sets, [LEFT, RIGHT]): label_set = VGroup() for i, dot in zip(it.count(1), dot_set): label = Integer(i) label.set_height(0.15) label.next_to(dot, direction, SMALL_BUFF) label_set.add(label) label_sets.add(label_set) for counter, dot_set in zip(counters, dot_sets): counter.move_to(dot_set) counter.to_edge(UP) self.add(rects, *self.get_mobjects()) self.play( Restore(rects), FadeIn(counters), ) for counter, dot_set, label_set in zip(counters, dot_sets, label_sets): self.play( ShowIncreasingSubsets(dot_set), ShowIncreasingSubsets(label_set), ChangingDecimal(counter, lambda a: len(dot_set)), rate_func=linear, ) self.wait() self.wait() self.remove(self.dots) self.dots = new_dots # Show orientation tips = self.get_orientation_arrows(windmill) self.play(ShowCreation(tips)) windmill.add(tips) self.wait() self.add_dot_color_updater(new_dots, windmill) rects.suspend_updating() for rect in rects: self.play(rect.set_opacity, 1) self.play(rect.set_opacity, rects.const_opacity) rects.resume_updating() self.wait() self.play( counters.space_out_submobjects, 0.8, counters.next_to, mid_words, DOWN, LARGE_BUFF, FadeOut(label_sets), ) eq = OldTex("=") eq.scale(2) eq.move_to(counters) self.play(FadeIn(eq)) self.wait() self.counters = counters self.colored_regions = rects rects.resume_updating() def mention_odd_case(self): dots = self.dots counters = self.counters sf = 1.0 words = OldTexText( "Assume odd \\# points" ) words.scale(sf) words.to_corner(UL) example = VGroup( OldTexText("Example:"), Integer(0) ) example.arrange(RIGHT) example.scale(sf) example.next_to(words, DOWN) example.align_to(words, LEFT) k = self.n_points // 2 dot_rects = VGroup() for i, dot in zip(it.count(1), dots): dot_rect = SurroundingRectangle(dot) dot_rect.match_color(dot) dot_rects.add(dot_rect) self.play(FadeIn(words, DOWN)) self.wait() self.play( ShowCreationThenFadeAround(dots[k]), self.pivot_dot.set_color, WHITE, ) self.play(FadeIn(example, UP)) self.play( ShowIncreasingSubsets(dot_rects), ChangingDecimal( example[1], lambda a: len(dot_rects) ), rate_func=linear ) self.wait() self.remove(dot_rects) self.play( ShowCreationThenFadeOut(dot_rects[:k]), ShowCreationThenFadeOut( SurroundingRectangle(counters[0], color=BLUE) ), ) self.play( ShowCreationThenFadeOut(dot_rects[-k:]), ShowCreationThenFadeOut( SurroundingRectangle(counters[1], color=GREY_BROWN) ), ) self.wait() self.play( FadeOut(words), FadeOut(example), ) def ask_about_numbers(self): self.windmill.rot_speed *= 0.5 self.add(self.dots, self.pivot_dot) self.let_windmill_run(self.windmill, 20) class SecondColoringExample(WindmillScene): CONFIG = { "run_time": 30, "n_points": 9, } def construct(self): points = self.get_random_point_set(self.n_points) points += RIGHT sorted_points = sorted(list(points), key=lambda p: p[0]) dots = self.get_dots(points) windmill = self.get_windmill( points, pivot=sorted_points[self.n_points // 2], angle=PI / 2 ) pivot_dot = self.get_pivot_dot(windmill) pivot_dot.set_color(WHITE) rects = self.get_left_right_colorings(windmill) self.add_dot_color_updater(dots, windmill) counts = VGroup( OldTexText("\\# Blues = 4"), OldTexText("\\# Browns = 4"), ) counts.arrange(DOWN, aligned_edge=LEFT, buff=MED_LARGE_BUFF) counts.to_corner(UL) counts[0].set_color(interpolate_color(BLUE, WHITE, 0.25)) counts[1].set_color(interpolate_color(GREY_BROWN, WHITE, 0.5)) counts[0].set_stroke(BLACK, 5, background=True) counts[1].set_stroke(BLACK, 5, background=True) const_words = OldTexText("Stay constant$\\dots$why?") const_words.next_to(counts, RIGHT, buff=1.5, aligned_edge=UP) arrows = VGroup(*[ Arrow( const_words.get_left(), count.get_right(), buff=SMALL_BUFF, max_tip_length_to_length_ratio=0.15, max_stroke_width_to_length_ratio=3, ) for count in counts ]) self.add(rects, windmill, dots, pivot_dot) self.add(counts, const_words, arrows) self.let_windmill_run(windmill, time=self.run_time) class TalkThroughPivotChange(WindmillScene): CONFIG = { "windmill_rotation_speed": 0.2, } def construct(self): self.setup_windmill() self.ask_about_pivot_change() self.show_above_and_below() self.change_pivot() def setup_windmill(self): points = self.points = np.array([ DR, UR, UL, DL, 0.5 * LEFT ]) points *= 3 self.dots = self.get_dots(points) self.windmill = self.get_windmill(points, points[-1]) self.pivot_dot = self.get_pivot_dot(self.windmill) self.pivot_dot.set_color(WHITE) self.add_dot_color_updater(self.dots, self.windmill) self.rects = self.get_left_right_colorings(self.windmill) self.add( self.rects, self.windmill, self.dots, self.pivot_dot, ) def ask_about_pivot_change(self): windmill = self.windmill new_pivot, angle = self.next_pivot_and_angle(windmill) words = OldTexText("Think about\\\\pivot change") words.next_to(new_pivot, UP, buff=2) words.to_edge(LEFT) arrow = Arrow(words.get_bottom(), new_pivot, buff=0.2) self.play( Rotate( windmill, -0.9 * angle, run_time=3, rate_func=linear ), Write(words, run_time=1), ShowCreation(arrow), ) self.wait() self.question = words self.question_arrow = arrow def show_above_and_below(self): windmill = self.windmill vect = normalize(windmill.get_vector()) angle = windmill.get_angle() tips = self.get_orientation_arrows(windmill) top_half = Line(windmill.get_center(), windmill.get_end()) low_half = Line(windmill.get_center(), windmill.get_start()) top_half.set_stroke(YELLOW, 3) low_half.set_stroke(PINK, 3) halves = VGroup(top_half, low_half) top_words = OldTexText("Above pivot") low_words = OldTexText("Below pivot") all_words = VGroup(top_words, low_words) for words, half in zip(all_words, halves): words.next_to(ORIGIN, DOWN) words.rotate(angle, about_point=ORIGIN) words.shift(half.point_from_proportion(0.15)) words.match_color(half) self.play(ShowCreation(tips)) self.wait() self.add(top_half, tips) self.play( ShowCreationThenFadeOut(top_half), FadeIn(top_words, -vect), ) self.add(low_half, tips) self.play( ShowCreationThenFadeOut(low_half), FadeIn(low_words, vect), ) self.wait() windmill.add(tips) self.above_below_words = all_words def change_pivot(self): windmill = self.windmill dots = self.dots arrow = self.question_arrow blue_rect = SurroundingRectangle(dots[3]) blue_rect.set_color(BLUE) new_pivot_word = OldTexText("New pivot") new_pivot_word.next_to(blue_rect, LEFT) old_pivot_word = OldTexText("Old pivot") old_pivot = windmill.pivot old_pivot_word.next_to( old_pivot, LEFT, buff=SMALL_BUFF + MED_SMALL_BUFF ) self.play( FadeOut(self.above_below_words), ReplacementTransform( self.question, new_pivot_word, ), ReplacementTransform(arrow, blue_rect), ) self.wait() anims, time = self.rotate_to_next_pivot(windmill) self.play( *anims, Rotate( windmill, angle=-windmill.rot_speed, rate_func=linear, ) ) self.wait() self.play( TransformFromCopy(new_pivot_word, old_pivot_word), blue_rect.move_to, old_pivot, ) self.wait(2) # Hit new point brown_rect = SurroundingRectangle(dots[1]) brown_rect.set_color(GREY_BROWN) self.play(TransformFromCopy(blue_rect, brown_rect)) self.play( blue_rect.move_to, windmill.pivot, blue_rect.set_color, GREY_BROWN, old_pivot_word.move_to, new_pivot_word, FadeOut(new_pivot_word, DL) ) self.let_windmill_run(windmill, 1) self.wait() self.play( FadeOut(old_pivot_word), FadeOut(blue_rect), FadeOut(brown_rect), ) self.let_windmill_run(windmill, 20) class InsightNumber1(Scene): def construct(self): words = OldTexText( "Key insight 1: ", "\\# Points on either side is constant" ) words[0].set_color(YELLOW) words.set_width(FRAME_WIDTH - 1) self.play(FadeInFromDown(words)) self.wait() class Rotate180Argument(WindmillScene): CONFIG = { "n_points": 21, "random_seed": 3, } def construct(self): self.setup_windmill() self.add_total_rotation_label() self.rotate_180() self.show_parallel_lines() self.rotate_180() self.rotate_180() def setup_windmill(self): n = self.n_points points = self.get_random_point_set(n) points[:, 0] *= 1.5 points += RIGHT points = sorted(points, key=lambda p: p[0]) mid_point = points[n // 2] points[n // 2 - 1] += 0.2 * LEFT self.points = points self.dots = self.get_dots(points) self.windmill = self.get_windmill(points, mid_point) self.pivot_dot = self.get_pivot_dot(self.windmill) self.pivot_dot.set_color(WHITE) self.add_dot_color_updater(self.dots, self.windmill) self.rects = self.get_left_right_colorings(self.windmill) p_label = OldTex("P_0") p_label.next_to(mid_point, RIGHT, SMALL_BUFF) self.p_label = p_label self.add( self.rects, self.windmill, self.dots, self.pivot_dot, self.p_label, ) def add_total_rotation_label(self): windmill = self.windmill words = OldTexText("Total rotation:") counter = Integer(0, unit="^\\circ") title = VGroup(words, counter) title.arrange(RIGHT) title.to_corner(UL) rot_arrow = Vector(UP) rot_arrow.set_color(RED) rot_arrow.next_to(title, DOWN) circle = Circle() circle.replace(rot_arrow, dim_to_match=1) circle.set_stroke(WHITE, 1) rot_arrow.add_updater( lambda m: m.set_angle(windmill.get_angle()) ) rot_arrow.add_updater( lambda m: m.move_to(circle) ) def update_count(c): new_val = 90 - windmill.get_angle() * 360 / TAU while abs(new_val - c.get_value()) > 90: new_val += 360 c.set_value(new_val) counter.add_updater(update_count) rect = SurroundingRectangle( VGroup(title, circle), buff=MED_LARGE_BUFF, ) rect.set_fill(BLACK, 0.8) rect.set_stroke(WHITE, 1) title.shift(MED_SMALL_BUFF * LEFT) self.rotation_label = VGroup( rect, words, counter, circle, rot_arrow ) self.add(self.rotation_label) def rotate_180(self): windmill = self.windmill self.add(self.pivot_dot) self.let_windmill_run( windmill, PI / windmill.rot_speed, ) self.wait() def show_parallel_lines(self): points = self.get_points() rotation_label = self.rotation_label dots = self.dots windmill = self.windmill lines = VGroup() for point in points: line = Line(DOWN, UP) line.set_height(2 * FRAME_HEIGHT) line.set_stroke(RED, 1, opacity=0.5) line.move_to(point) lines.add(line) lines.shuffle() self.add(lines, dots, rotation_label) self.play( ShowCreation(lines, lag_ratio=0.5, run_time=3) ) self.wait() self.rects.suspend_updating() for rect in self.rects: self.play( rect.set_opacity, 0, rate_func=there_and_back, run_time=2 ) self.rects.resume_updating() self.wait() pivot_tracker = VectorizedPoint(windmill.pivot) pivot_tracker.save_state() def update_pivot(w): w.pivot = pivot_tracker.get_center() windmill.add_updater(update_pivot) for x in range(4): point = random.choice(points) self.play( pivot_tracker.move_to, point ) self.wait() self.play(Restore(pivot_tracker)) self.play(FadeOut(lines)) windmill.remove_updater(update_pivot) self.wait() class Rotate180ArgumentFast(Rotate180Argument): CONFIG = { "windmill_rotation_speed": 0.5, } class EvenCase(Rotate180Argument): CONFIG = { "n_points": 10, "dot_config": {"radius": 0.075}, } def construct(self): self.ask_about_even_number() self.choose_halfway_point() self.add_total_rotation_label() self.rotate_180() self.rotate_180() self.show_parallel_lines() self.rotate_180() self.rotate_180() def ask_about_even_number(self): n = self.n_points points = self.get_random_point_set(n) points[:, 0] *= 2 points += DOWN points = sorted(points, key=lambda p: p[0]) dots = self.get_dots(points) windmill = self.get_windmill(points, points[3]) region_rects = self.rects = self.get_left_right_colorings(windmill) pivot_dot = self.get_pivot_dot(windmill) pivot_dot.set_color(WHITE) dot_rects = VGroup(*map(SurroundingRectangle, dots)) question = OldTexText("What about an even number?") # question.to_corner(UL) question.to_edge(UP) counter_label = OldTexText("\\# Points", ":") counter = Integer(0) counter_group = VGroup(counter_label, counter) counter_group.arrange(RIGHT) counter.align_to(counter_label[1], DOWN) counter_group.next_to(question, DOWN, MED_LARGE_BUFF) counter_group.set_color(YELLOW) # counter_group.align_to(question, LEFT) self.add(question, counter_label) self.add(windmill, dots, pivot_dot) self.add_dot_color_updater(dots, windmill) self.add(region_rects, question, counter_group, windmill, dots, pivot_dot) self.play( ShowIncreasingSubsets(dot_rects), ChangingDecimal(counter, lambda a: len(dot_rects)), rate_func=linear ) self.play(FadeOut(dot_rects)) self.wait() # region_rects.suspend_updating() # self.play( # FadeIn(region_rects), # FadeOut(dot_rects), # ) # region_rects.resume_updating() # self.wait() # Count by color blue_rects = dot_rects[:3] blue_rects.set_color(BLUE) brown_rects = dot_rects[4:] brown_rects.set_color(GREY_BROWN) pivot_rect = dot_rects[3] pivot_rect.set_color(GREY_BROWN) blues_label = OldTexText("\\# Blues", ":") blues_counter = Integer(len(blue_rects)) blues_group = VGroup(blues_label, blues_counter) blues_group.set_color(BLUE) browns_label = OldTexText("\\# Browns", ":") browns_counter = Integer(len(brown_rects)) browns_group = VGroup(browns_label, browns_counter) browns_group.set_color(interpolate_color(GREY_BROWN, WHITE, 0.5)) groups = VGroup(blues_group, browns_group) for group in groups: group.arrange(RIGHT) group[-1].align_to(group[0][-1], DOWN) groups.arrange(DOWN, aligned_edge=LEFT) groups.next_to(counter_group, DOWN, aligned_edge=LEFT) self.play( FadeIn(blues_group, UP), ShowCreation(blue_rects), ) self.play( FadeIn(browns_group, UP), ShowCreation(brown_rects), ) self.wait() # Pivot counts as brown pivot_words = OldTexText("Pivot counts as brown") arrow = Vector(LEFT) arrow.next_to(pivot_dot, RIGHT, SMALL_BUFF) pivot_words.next_to(arrow, RIGHT, SMALL_BUFF) self.play( FadeIn(pivot_words, LEFT), ShowCreation(arrow), ) self.play( ShowCreation(pivot_rect), ChangeDecimalToValue(browns_counter, len(brown_rects) + 1), FadeOut(pivot_dot), ) self.wait() self.play( FadeOut(dot_rects), FadeOut(pivot_words), FadeOut(arrow), ) self.wait() blues_counter.add_updater( lambda c: c.set_value(len(list(filter( lambda d: d.get_fill_color() == Color(BLUE), dots )))) ) browns_counter.add_updater( lambda c: c.set_value(len(list(filter( lambda d: d.get_fill_color() == Color(GREY_BROWN), dots )))) ) self.windmill = windmill self.dots = dots self.points = points self.question = question self.counter_group = VGroup( counter_group, blues_group, browns_group, ) def choose_halfway_point(self): windmill = self.windmill points = self.points n = self.n_points p_label = OldTex("P_0") p_label.next_to(points[n // 2], RIGHT, SMALL_BUFF) pivot_tracker = VectorizedPoint(windmill.pivot) def update_pivot(w): w.pivot = pivot_tracker.get_center() windmill.add_updater(update_pivot) self.play( pivot_tracker.move_to, points[n // 2], run_time=2 ) self.play(FadeIn(p_label, LEFT)) self.wait() windmill.remove_updater(update_pivot) def add_total_rotation_label(self): super().add_total_rotation_label() self.rotation_label.scale(0.8, about_edge=UL) self.play( FadeOut(self.question), FadeIn(self.rotation_label), self.counter_group.to_edge, UP, ) class TwoTakeaways(TeacherStudentsScene): def construct(self): title = OldTexText("Two takeaways") title.scale(2) title.to_edge(UP) line = Line() line.match_width(title) line.next_to(title, DOWN, SMALL_BUFF) items = VGroup(*[ OldTexText("1) Social"), OldTexText("2) Mathematical"), ]) items.scale(1.5) items.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) items.next_to(line, DOWN, buff=MED_LARGE_BUFF) self.play( ShowCreation(line), GrowFromPoint(title, self.hold_up_spot), self.teacher.change, "raise_right_hand", ) self.play_all_student_changes("pondering") self.wait() for item in items: self.play(FadeIn(item, LEFT)) item.big = item.copy() item.small = item.copy() item.big.scale(1.5, about_edge=LEFT) item.big.set_color(BLUE) item.small.scale(0.75, about_edge=LEFT) item.small.fade(0.5) self.play(self.teacher.change, "happy") self.wait() for i, j in [(0, 1), (1, 0)]: self.play( items[i].become, items[i].big, items[j].become, items[j].small, ) self.wait() class EasyToFoolYourself(PiCreatureScene): CONFIG = { "default_pi_creature_kwargs": { "color": GREY_BROWN, } } def construct(self): morty = self.pi_creature morty.to_corner(DL) bubble = ThoughtBubble() for i, part in enumerate(bubble): part.shift(2 * i * SMALL_BUFF * DOWN) bubble.pin_to(morty) fool_word = OldTexText("Fool") fool_word.scale(1.5) fool_arrow = Vector(LEFT) fool_arrow.next_to(morty, RIGHT, buff=0) fool_word.next_to(fool_arrow, RIGHT) self.add(morty) self.play( ShowCreation(bubble), morty.change, "pondering", ) self.play( bubble[3].set_fill, GREEN_SCREEN, 0.5, ) self.wait() self.play(morty.change, "thinking") self.play( FadeIn(fool_word, LEFT), ShowCreation(fool_arrow), ) self.wait() self.pi_creature_says( "Isn't it\\\\obvious?", target_mode="maybe", added_anims=[FadeOut(bubble)] ) self.wait(4) # words = OldTexText("No it's not!") words.scale(1.5) words.set_color(RED) words.next_to(morty.bubble, RIGHT, LARGE_BUFF) words.match_y(morty.bubble.content) self.play( FadeInFromLarge(words), morty.change, "guilty", ) self.wait() # for i, part in enumerate(bubble): # self.add(Integer(i).move_to(part)) class FailureToEmpathize(PiCreatureScene): def construct(self): randy, morty = self.pi_creatures # What a mess... big_bubble = ThoughtBubble(height=4, width=5) big_bubble.scale(1.75) big_bubble.flip(UR) for part in big_bubble: part.rotate(90 * DEGREES) big_bubble[:3].rotate(-30 * DEGREES) for i, part in enumerate(big_bubble[:3]): part.rotate(30 * DEGREES) part.shift((3 - i) * SMALL_BUFF * DOWN) big_bubble[0].shift(MED_SMALL_BUFF * RIGHT) big_bubble[:3].next_to(big_bubble[3], LEFT) big_bubble[:3].shift(0.3 * DOWN) big_bubble.set_fill(GREY_E) big_bubble.to_corner(UR) equation = OldTex( "\\sum_{k=1}^n (2k - 1) = n^2" ) self.pi_creature_thinks( randy, equation, target_mode="confused", look_at=equation, ) randy_group = VGroup( randy, randy.bubble, randy.bubble.content ) self.wait() self.play( DrawBorderThenFill(big_bubble), morty.change, "confused", randy_group.scale, 0.5, randy_group.move_to, big_bubble.get_bubble_center(), randy_group.shift, 0.5 * DOWN + RIGHT, ) self.wait() self.play(morty.change, "maybe") self.wait(2) # Zoom out morty_group = VGroup(morty, big_bubble) ap = 5 * RIGHT + 2.5 * UP self.add(morty_group, randy_group) self.play( morty_group.scale, 2, {"about_point": ap}, morty_group.fade, 1, randy_group.scale, 2, {"about_point": ap}, run_time=2 ) self.wait() def create_pi_creatures(self): randy = Randolph() morty = Mortimer() randy.flip().to_corner(DR) morty.flip().to_corner(DL) return (randy, morty) class DifficultyEstimateVsReality(Scene): def construct(self): axes = Axes( x_min=-1, x_max=10, x_axis_config={ "include_tip": False, }, y_min=-1, y_max=5, ) axes.set_height(FRAME_HEIGHT - 1) axes.center() axes.x_axis.tick_marks.set_opacity(0) y_label = OldTexText("Average score") y_label.scale(1.25) y_label.rotate(90 * DEGREES) y_label.next_to(axes.y_axis, LEFT, SMALL_BUFF) y_label.shift(UP) estimated = [1.8, 2.6, 3, 4, 5] actual = [1.5, 0.5, 1, 1.2, 1.8] colors = [GREEN, RED] estimated_color, actual_color = colors estimated_bars = VGroup() actual_bars = VGroup() bar_pairs = VGroup() width = 0.25 for a, e in zip(actual, estimated): bars = VGroup( Rectangle(width=width, height=e), Rectangle(width=width, height=a), ) bars.set_stroke(width=1) bars[0].set_fill(estimated_color, 0.75) bars[1].set_fill(actual_color, 0.75) bars.arrange(RIGHT, buff=0, aligned_edge=DOWN) bar_pairs.add(bars) estimated_bars.add(bars[0]) actual_bars.add(bars[1]) bar_pairs.arrange(RIGHT, buff=1.5, aligned_edge=DOWN) bar_pairs.move_to(axes.c2p(5, 0), DOWN) for bp in bar_pairs: for bar in bp: bar.save_state() bar.stretch(0, 1, about_edge=DOWN) x_labels = VGroup(*[ OldTexText("Q{}".format(i)).next_to(bp, DOWN) for i, bp in zip(it.count(1), bar_pairs) ]) data_labels = VGroup( OldTexText("Estimated average"), OldTexText("Actual average"), ) data_labels.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) data_labels.to_edge(UP) for color, label in zip(colors, data_labels): square = Square() square.set_height(0.5) square.set_fill(color, 0.75) square.set_stroke(WHITE, 1) square.next_to(label, LEFT, SMALL_BUFF) label.add(square) self.play(Write(axes)) self.play(Write(y_label)) self.play( LaggedStartMap( FadeInFrom, x_labels, lambda m: (m, UP), run_time=2, ), LaggedStartMap( Restore, estimated_bars, run_time=3, ), FadeIn(data_labels[0]), ) self.wait() self.play( LaggedStartMap( Restore, actual_bars, run_time=3, ), FadeIn(data_labels[1]), ) self.wait() class KeepInMindWhenTeaching(TeacherStudentsScene): def construct(self): self.teacher_says( "I don't know\\\\what you know!", target_mode="pleading" ) self.wait(2) self.play( PiCreatureSays( self.students[0], "We know", target_mode="hooray", ), self.students[1].change, "happy", self.students[2].change, "happy", ) self.wait(2) class VastSpaceOfConsiderations(Scene): def construct(self): considerations = VGroup(*[ OldTexText(phrase) for phrase in [ "Define ``outer'' points", "Convex hulls", "Linear equations", "Sort points by when they're hit", "Sort points by some kind of angle?", "How does this permute the $n \\choose 2$ lines through pairs?", "Some points are hit more than others, can we quantify this?", ] ]) considerations.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) considerations.to_edge(LEFT) self.play(LaggedStart(*[ FadeIn(mob, UP) for mob in considerations ], run_time=3, lag_ratio=0.2)) class WhatStaysConstantWrapper(Scene): CONFIG = { "camera_config": { "background_color": GREY_E } } def construct(self): rect = ScreenRectangle() rect.set_height(6) rect.set_stroke(WHITE, 2) rect.set_fill(BLACK, 1) title1 = OldTexText("What stays constant?") title2 = OldTexText("Find an ", "``invariant''") title2[1].set_color(YELLOW) for title in [title1, title2]: title.scale(2) title.to_edge(UP) rect.next_to(title1, DOWN) self.add(rect) self.play(FadeInFromDown(title1)) self.wait() self.play( FadeOut(title1, UP), FadeInFromDown(title2), ) self.wait() class CountHoles(Scene): def construct(self): labels = VGroup( OldTexText("Genus ", "0"), OldTexText("Genus ", "1"), OldTexText("Genus ", "2"), ) labels.scale(2) labels.arrange(RIGHT, buff=1.5) labels.move_to(2 * DOWN) equation = OldTex("y^2 = x^3 + ax + b") equation.scale(1.5) equation.shift(UP) equation.to_edge(LEFT) # arrow = OldTex("\\approx").scale(2) arrow = Vector(2 * RIGHT) arrow.next_to(equation, RIGHT) equation_text = OldTexText("Some other problem") equation_text.next_to(equation, DOWN, MED_LARGE_BUFF) equation_text.match_width(equation) equation_text.set_color(YELLOW) self.play(LaggedStartMap( FadeInFromDown, labels, lag_ratio=0.5, )) self.wait() self.play( labels[1].shift, 4 * RIGHT, FadeOut(labels[0::2]), ) self.play( FadeIn(equation, RIGHT), GrowArrow(arrow), ) self.play(FadeIn(equation_text, UP)) self.wait() class LorenzTransform(Scene): def construct(self): grid = NumberPlane( # faded_line_ratio=0, # y_axis_config={ # "y_min": -10, # "y_max": 10, # } ) grid.scale(2) back_grid = grid.copy() back_grid.set_stroke(GREY, 0.5) # back_grid.set_opacity(0.5) c_lines = VGroup(Line(DL, UR), Line(DR, UL)) c_lines.scale(FRAME_HEIGHT) c_lines.set_stroke(YELLOW, 3) equation = OldTex( "d\\tau^2 = dt^2 - dx^2" ) equation.scale(1.7) equation.to_corner(UL, buff=MED_SMALL_BUFF) equation.shift(2.75 * DOWN) equation.set_stroke(BLACK, 5, background=True) self.add(back_grid, grid, c_lines) self.add(equation) beta = 0.4 self.play( grid.apply_matrix, np.array([ [1, beta], [beta, 1], ]) / (1 - beta**2), run_time=2 ) self.wait() class OnceACleverDiscovery(Scene): def construct(self): energy = OldTexText("energy") rect = SurroundingRectangle(energy) words = OldTexText("Once a clever discovery") vect = Vector(DR) vect.next_to(rect.get_top(), UL, SMALL_BUFF) words.next_to(vect.get_start(), UP) words.set_color(YELLOW) vect.set_color(YELLOW) self.play( ShowCreation(vect), ShowCreation(rect), ) self.play(FadeInFromDown(words)) self.wait() class TerryTaoQuote(Scene): def construct(self): image = ImageMobject("TerryTao") image.set_height(4) name = OldTexText("Terence Tao") name.scale(1.5) name.next_to(image, DOWN, buff=0.2) tao = Group(image, name) tao.to_corner(DL, buff=MED_SMALL_BUFF) tiny_tao = ImageMobject("TerryTaoIMO") tiny_tao.match_height(image) tiny_tao.next_to(image, RIGHT, LARGE_BUFF) quote = self.get_quote() self.play( FadeInFromDown(image), Write(name), ) self.wait() self.play( FadeIn(tiny_tao, LEFT) ) self.wait() self.play(FadeOut(tiny_tao)) # self.play( FadeIn( quote, lag_ratio=0.05, run_time=5, rate_func=bezier([0, 0, 1, 1]) ) ) self.wait() story_line = Line() story_line.match_width(quote.story_part) story_line.next_to(quote.story_part, DOWN, buff=0) story_line.set_color(TEAL), self.play( quote.story_part.set_color, TEAL, ShowCreation(story_line), lag_ratio=0.2, ) self.wait() def get_quote(self): story_words = "fables, stories, and anecdotes" quote = OldTexText( """ \\Large ``Mathematical problems, or puzzles, are important to real mathematics (like solving real-life problems), just as fables, stories, and anecdotes are important to the young in understanding real life.''\\\\ """, alignment="", arg_separator=" ", isolate=[story_words] ) quote.story_part = quote.get_part_by_tex(story_words) quote.set_width(FRAME_WIDTH - 2.5) quote.to_edge(UP) return quote class WindmillFairyTale(Scene): def construct(self): paths = SVGMobject(file_name="windmill_fairytale") paths.set_height(FRAME_HEIGHT - 1) paths.set_stroke(width=0) paths.set_fill([GREY_B, WHITE]) for path in paths: path.reverse_points() self.play(Write(paths[0], run_time=3)) self.wait() self.play( LaggedStart( FadeIn(paths[1], RIGHT), FadeIn(paths[2], RIGHT), lag_ratio=0.2, run_time=3, ) ) class SolveAProblemOneDay(SpiritOfIMO, PiCreatureScene): def construct(self): randy = self.pi_creature light_bulb = Lightbulb() light_bulb.base = light_bulb[:3] light_bulb.light = light_bulb[3:] light_bulb.set_height(1) light_bulb.next_to(randy, UP, MED_LARGE_BUFF) light = self.get_light(light_bulb.get_center()) bubble = ThoughtBubble() bubble.pin_to(randy) you = OldTexText("You") you.scale(1.5) arrow = Vector(LEFT) arrow.next_to(randy, RIGHT) you.next_to(arrow) self.play( ShowCreation(bubble), randy.change, "pondering", ) self.play( FadeIn(you, LEFT), GrowArrow(arrow) ) self.wait(2) self.play( FadeInFromDown(light_bulb), randy.change, "hooray", ) self.play( LaggedStartMap( VFadeInThenOut, light, run_time=2 ), randy.change, "thinking", light, ) self.wait(2) class QuixoteReference(Scene): def construct(self): rect = FullScreenFadeRectangle() rect.set_fill([GREY_D, GREY]) windmill = SVGMobject("windmill") windmill.set_fill([GREY_BROWN, WHITE], 1) windmill.set_stroke(width=0) windmill.set_height(6) windmill.to_edge(RIGHT) # windmill.to_edge(DOWN, buff=0) quixote = SVGMobject("quixote") quixote.flip() quixote.set_height(4) quixote.to_edge(LEFT) quixote.set_stroke(BLACK, width=0) quixote.set_fill(BLACK, 1) quixote.align_to(windmill, DOWN) self.add(rect) # self.add(windmill) self.play(LaggedStart( DrawBorderThenFill(windmill), DrawBorderThenFill( quixote, stroke_width=1, ), lag_ratio=0.4, run_time=3 )) self.wait() class WindmillEndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "Juan Benet", "Kurt Dicus", "Vassili Philippov", "Davie Willimoto", "Burt Humburg", "Hardik Meisheri", "L. Z.", "Matt Russell", "Scott Gray", "soekul", "Tihan Seale", "D. Sivakumar", "Richard Barthel", "Ali Yahya", "Arthur Zey", "dave nicponski", "Joseph Kelly", "Kaustuv DeBiswas", "kkm", "Lambda AI Hardware", "Lukas Biewald", "Mark Heising", "Nicholas Cahill", "Peter Mcinerney", "Quantopian", "Roy Larson", "Scott Walter, Ph.D.", "Tauba Auerbach", "Yana Chernobilsky", "Yu Jun", "Jordan Scales", "Lukas -krtek.net- Novy", "Britt Selvitelle", "David Gow", "J", "Jonathan Wilson", "Joseph John Cox", "Magnus Dahlström", "Randy C. Will", "Ryan Atallah", "Luc Ritchie", "1stViewMaths", "Adrian Robinson", "Aidan Shenkman", "Alex Mijalis", "Alexis Olson", "Andreas Benjamin Brössel", "Andrew Busey", "Ankalagon", "Antoine Bruguier", "Antonio Juarez", "Arjun Chakroborty", "Art Ianuzzi", "Austin Goodman", "Awoo", "Ayan Doss", "AZsorcerer", "Barry Fam", "Bernd Sing", "Boris Veselinovich", "Bradley Pirtle", "Brian Staroselsky", "Charles Southerland", "Charlie N", "Chris Connett", "Christian Kaiser", "Clark Gaebel", "Cooper Jones", "Danger Dai", "Daniel Pang", "Dave B", "Dave Kester", "David B. Hill", "David Clark", "DeathByShrimp", "Delton Ding", "Dheeraj Vepakomma", "eaglle", "Empirasign", "emptymachine", "Eric Younge", "Ero Carrera", "Eryq Ouithaqueue", "Federico Lebron", "Fernando Via Canel", "Gero Bone-Winkel", "Giovanni Filippi", "Hal Hildebrand", "Hitoshi Yamauchi", "Isaac Jeffrey Lee", "Ivan Sorokin", "j eduardo perez", "Jacob Harmon", "Jacob Hartmann", "Jacob Magnuson", "Jameel Syed", "Jason Hise", "Jeff Linse", "Jeff Straathof", "John C. Vesey", "John Griffith", "John Haley", "John V Wertheim", "Jonathan Eppele", "Jordan A Purcell", "Josh Kinnear", "Joshua Claeys", "Kai-Siang Ang", "Kanan Gill", "Kartik Cating-Subramanian", "L0j1k", "Lee Redden", "Linh Tran", "Ludwig Schubert", "Magister Mugit", "Mark B Bahu", "Martin Price", "Mathias Jansson", "Matt Langford", "Matt Roveto", "Matthew Bouchard", "Matthew Cocke", "Michael Faust", "Michael Hardel", "Mirik Gogri", "Mustafa Mahdi", "Márton Vaitkus", "Nero Li", "Nikita Lesnikov", "Omar Zrien", "Owen Campbell-Moore", "Patrick Lucas", "Peter Ehrnstrom", "RedAgent14", "rehmi post", "Ripta Pasay", "Rish Kundalia", "Roman Sergeychik", "Roobie", "Ryan Williams", "Sebastian Garcia", "Solara570", "Steven Siddals", "Stevie Metke", "Tal Einav", "Ted Suzman", "Thomas Tarler", "Tianyu Ge", "Tom Fleming", "Tyler VanValkenburg", "Valeriy Skobelev", "Vinicius Reis", "Xuanji Li", "Yavor Ivanov", "YinYangBalance.Asia", "Zach Cardwell", ], } class Thumbnail(WindmillScene): CONFIG = { "dot_config": { "radius": 0.15, "stroke_width": 1, }, "random_seed": 7, "animate": False, } def construct(self): points = self.get_random_point_set(11) points[:, 0] *= 1.7 points += 0.5 * LEFT points[1] = ORIGIN points[10] += LEFT points[6] += 3 * RIGHT windmill = self.get_windmill( points, points[1], angle=45 * DEGREES, ) dots = self.get_dots(points) # rects = self.get_left_right_colorings(windmill) pivot_dot = self.get_pivot_dot(windmill) pivot_dot.scale(2) pivot_dot.set_color(WHITE) new_pivot = points[5] new_pivot2 = points[3] flash = Flash(pivot_dot, flash_radius=0.5) wa = windmill.get_angle() arcs = VGroup(*[ Arc( start_angle=wa + a, angle=90 * DEGREES, radius=1.5, stroke_width=10, ).add_tip(tip_length=0.7) for a in [0, PI] ]) arcs.move_to(windmill.pivot) arcs.set_color([GREY_B, WHITE]) polygon1 = Polygon( (FRAME_HEIGHT * UP + FRAME_WIDTH * LEFT) / 2, (FRAME_HEIGHT * UP + FRAME_HEIGHT * RIGHT) / 2, (FRAME_HEIGHT * DOWN + FRAME_HEIGHT * LEFT) / 2, (FRAME_HEIGHT * DOWN + FRAME_WIDTH * LEFT) / 2, ) polygon1.set_color([BLUE, GREY_E]) polygon1.set_fill(opacity=0.5) polygon2 = Polygon( (FRAME_HEIGHT * UP + FRAME_WIDTH * RIGHT) / 2, (FRAME_HEIGHT * UP + FRAME_HEIGHT * RIGHT) / 2, (FRAME_HEIGHT * DOWN + FRAME_HEIGHT * LEFT) / 2, (FRAME_HEIGHT * DOWN + FRAME_WIDTH * RIGHT) / 2, ) polygon2.set_sheen_direction(DR) polygon2.set_color([GREY_BROWN, BLACK]) polygon2.set_fill(opacity=1) self.add(polygon1, polygon2) # self.add(rects[0]) self.add(windmill, dots, pivot_dot) self.add(arcs) self.add(flash.mobject) self.add_dot_color_updater(dots, windmill, color2=WHITE) words = OldTexText("Next\\\\", "pivot") words2 = OldTexText("Next\\\\", "next\\\\", "pivot", alignment="") words.scale(2) words2.scale(2) # words.next_to(windmill.pivot, RIGHT) words.to_edge(UR) words2.to_corner(DL) arrow = Arrow(words[1].get_left(), new_pivot, buff=0.6) arrow.set_stroke(width=10) arrow.set_color(YELLOW) arrow2 = Arrow(words2[-1].get_right(), new_pivot2, buff=0.6) arrow2.match_style(arrow) arrow.rotate( arrow2.get_angle() + PI - arrow.get_angle(), about_point=new_pivot, ) self.add(words, arrow) self.add(words2, arrow2) # for i, dot in enumerate(dots): # self.add(Integer(i).move_to(dot)) if self.animate: sorted_dots = VGroup(*dots) sorted_dots.sort(lambda p: np.dot(p, DR)) self.play( polygon1.shift, FRAME_WIDTH * LEFT, polygon2.shift, FRAME_WIDTH * RIGHT, LaggedStart(*[ ApplyMethod(mob.scale, 0) for mob in [sorted_dots[6], *flash.mobject, windmill, pivot_dot] ]), LaggedStart(*[ ApplyMethod(dot.to_edge, LEFT, {"buff": -1}) for dot in sorted_dots[:6] ]), LaggedStart(*[ ApplyMethod(dot.to_edge, RIGHT, {"buff": -1}) for dot in sorted_dots[7:] ]), LaggedStart(*[ FadeOut(word, RIGHT) for word in words ]), LaggedStart(*[ FadeOut(word, LEFT) for word in words2 ]), LaggedStartMap( Uncreate, VGroup(arrow, arrow2, *arcs), ), run_time=3, ) class ThumbanailAnimated(Thumbnail): CONFIG = { "animate": True, } class Thumbnail2(Scene): def construct(self): words = OldTexText("Olympics\\\\", "for\\\\", "math", alignment="") # words.arrange(DOWN, aligned_edge=LEFT) words.set_height(FRAME_HEIGHT - 1.5) words.to_edge(LEFT) logo = ImageMobject("imo_logo") logo.set_height(4.5) logo.to_corner(DR, buff=LARGE_BUFF) rect = FullScreenFadeRectangle() rect.set_fill([GREY, BLACK], 1) self.clear() self.add(rect) self.add(words) self.add(logo)
from manim_imports_ext import * class TriangleModuliSpace(Scene): CONFIG = { "camera_config": { "background_image": "chalkboard", }, "degen_color": GREEN_D, "x1_color": GREEN_B, "y1_color": RED, "x_eq_y_color": YELLOW, "right_color": TEAL, "obtuse_color": PINK, "acute_color": GREEN, "triangle_fill_opacity": 0.5, "random_seed": 0, "example_triangle_width": 6, } def setup(self): self.plane = NumberPlane( axis_config={ "unit_size": 2, } ) def construct(self): self.show_meaning_of_similar() self.show_xy_rule() def show_meaning_of_similar(self): # Setup titles title = OldTexText("Space", " of all ", "triangles") title.scale(1.5) title.to_edge(UP) subtitle = OldTexText("up to similarity.") subtitle.scale(1.5) subtitle.next_to(title, DOWN, MED_SMALL_BUFF) question = OldTexText("What ", "is ", "a\\\\", "moduli ", "space", "?") question.scale(2) # Setup all triangles all_triangles, tri_classes = self.get_triangles_and_classes() tri_classes[2][1].scale(0.5) tri_classes[2][1].scalar *= 0.5 all_triangles.to_edge(DOWN) # Triangles pop up... self.play( LaggedStartMap(FadeInFromDown, question), ) self.wait() self.play( ReplacementTransform( question.get_part_by_tex("space"), title.get_part_by_tex("Space"), ), FadeOut(question[:-2]), FadeOut(question[-1]), FadeIn(title[1:]), LaggedStartMap( DrawBorderThenFill, all_triangles, rate_func=bezier([0, 0, 1.5, 1, 1]), run_time=5, lag_ratio=0.05, ) ) self.wait() # ...Then divide into classes tri_classes.generate_target() colors = Color(BLUE).range_to(Color(RED), len(tri_classes)) for group, color in zip(tri_classes.target, colors): group.arrange(DOWN) group.set_color(color) tri_classes.target.arrange(RIGHT, buff=1.25, aligned_edge=UP) tri_classes.target.scale(0.85) tri_classes.target.to_corner(DL) max_width = max([tc.get_width() for tc in tri_classes.target]) height = tri_classes.target.get_height() + 0.5 rects = VGroup(*[ Rectangle( height=height, width=max_width + 0.25, stroke_width=2, ).move_to(tri_class, UP) for tri_class in tri_classes.target ]) rects.shift(MED_SMALL_BUFF * UP) # Dumb shifts # tri_classes.target[1][2].shift(0.25 * UP) tri_classes.target[2].scale(0.9, about_edge=UP) tri_classes.target[2][2].shift(0.2 * UP) tri_classes.target[3][0].shift(0.5 * DOWN) tri_classes.target[3][1].shift(1.0 * DOWN) tri_classes.target[3][2].shift(1.2 * DOWN) tri_classes.target[4][1:].shift(0.7 * UP) # Dots per_class_dots = VGroup(*[ OldTex("\\vdots").move_to( tri_class ).set_y(rects.get_bottom()[1] + 0.4) for tri_class in tri_classes.target ]) all_class_dots = OldTex("\\dots").next_to( rects, RIGHT, MED_SMALL_BUFF, ) self.play( FadeInFromDown(subtitle), MoveToTarget(tri_classes), ) self.play( LaggedStartMap(FadeIn, rects), Write(per_class_dots), Write(all_class_dots), ) self.wait(2) # Similar tri1 = tri_classes[2][1] tri2 = tri_classes[2][2] tri1.save_state() tri2.save_state() sim_sign = OldTex("\\sim") sim_sign.set_width(1) sim_sign.move_to(midpoint(rects.get_top(), TOP)) sim_sign.shift(0.25 * DOWN) similar_word = OldTexText("Similar") similar_word.scale(1.5) similar_word.move_to(sim_sign) similar_word.to_edge(UP) self.play( FadeOut(VGroup(title, subtitle), UP), tri1.next_to, sim_sign, LEFT, 0.75, tri2.next_to, sim_sign, RIGHT, 0.75, ) self.play( FadeInFromDown(sim_sign), Write(similar_word, run_time=1) ) self.wait() # Move into place tri1_copy = tri1.copy() self.play( tri1_copy.next_to, tri2, RIGHT, LARGE_BUFF, path_arc=90 * DEGREES, ) self.play(Rotate(tri1_copy, tri2.angle - tri1.angle)) self.play(tri1_copy.scale, tri2.scalar / tri1.scalar) self.play( tri1_copy.move_to, tri2, ) tri1_copy.set_color(YELLOW) self.play( FadeOut(tri1_copy), rate_func=rush_from, ) self.wait(2) # Show non-similar example not_similar_word = OldTexText("Not ", "Similar") not_similar_word.scale(1.5) not_similar_word.move_to(similar_word) not_similar_word.set_color(RED) sim_cross = Line(DL, UR) sim_cross.set_color(RED) sim_cross.match_width(sim_sign) sim_cross.move_to(sim_sign) sim_cross.set_stroke(BLACK, 5, background=True) tri3 = tri_classes[1][2] tri3.save_state() tri3.generate_target() tri3.target.move_to(tri2, LEFT) tri1_copy = tri1.copy() self.play( Restore(tri2), MoveToTarget(tri3), ) self.play( ReplacementTransform( similar_word[0], not_similar_word[1], ), GrowFromCenter(not_similar_word[0]), ShowCreation(sim_cross), ) self.play(tri1_copy.move_to, tri3) self.play(Rotate(tri1_copy, 90 * DEGREES)) self.play( tri1_copy.match_height, tri3, tri1_copy.move_to, tri3, RIGHT, ) self.play(WiggleOutThenIn(tri1_copy, n_wiggles=10)) self.play(FadeOut(tri1_copy)) self.wait() # Back to classes new_title = OldTexText("Space of all\\\\", "Similarity classes") new_title.scale(1.5) new_title[1].set_color(YELLOW) new_title.to_edge(UP) new_title_underline = Line(LEFT, RIGHT) new_title_underline.match_width(new_title[1]) new_title_underline.match_color(new_title[1]) new_title_underline.next_to(new_title, DOWN, buff=0.05) self.play( Restore(tri1), Restore(tri2), Restore(tri3), FadeOut(not_similar_word), FadeOut(sim_sign), FadeOut(sim_cross), FadeIn(new_title[1], UP), ) self.play( ShowCreationThenDestruction(new_title_underline), LaggedStartMap( ApplyMethod, rects, lambda m: (m.set_stroke, YELLOW, 5), rate_func=there_and_back, run_time=1, ) ) self.wait() self.play(Write(new_title[0])) self.wait() # Show abstract space blob = ThoughtBubble()[-1] blob.set_height(2) blob.to_corner(UR) dots = VGroup(*[ Dot(color=tri.get_color()).move_to( self.get_triangle_x(tri) * RIGHT + self.get_triangle_y(tri) * UP, ) for tri_class in tri_classes for tri in tri_class[0] ]) dots.space_out_submobjects(2) dots.move_to(blob) self.play( DrawBorderThenFill(blob), new_title.shift, LEFT, ) self.play(LaggedStart( *[ ReplacementTransform( tri_class.copy().set_fill(opacity=0), dot ) for tri_class, dot in zip(tri_classes, dots) ], run_time=3, lag_ratio=0.3, )) # Isolate one triangle tri = tri_classes[0][0] verts = tri.get_vertices() angle = PI + angle_of_vector(verts[1] - verts[2]) self.play( tri.rotate, -angle, tri.set_width, self.example_triangle_width, tri.center, FadeOut(tri_classes[0][1:]), FadeOut(tri_classes[1:]), FadeOut(rects), FadeOut(per_class_dots), FadeOut(all_class_dots), FadeOut(blob), FadeOut(dots), FadeOut(new_title), ) self.triangle = tri def show_xy_rule(self): unit_factor = 4.0 if hasattr(self, "triangle"): triangle = self.triangle else: triangle = self.get_triangles_and_classes()[0][0] verts = triangle.get_vertices() angle = PI + angle_of_vector(verts[1] - verts[2]) triangle.rotate(-angle) triangle.set_width(self.example_triangle_width) triangle.center() self.add(triangle) side_trackers = VGroup(*[Line() for x in range(3)]) side_trackers.set_stroke(width=0, opacity=0) side_trackers.triangle = triangle def update_side_trackers(st): verts = st.triangle.get_vertices() st[0].put_start_and_end_on(verts[0], verts[1]) st[1].put_start_and_end_on(verts[1], verts[2]) st[2].put_start_and_end_on(verts[2], verts[0]) side_trackers.add_updater(update_side_trackers) def get_length_labels(): result = VGroup() for line in side_trackers: vect = normalize(line.get_vector()) perp_vect = rotate_vector(vect, -90 * DEGREES) perp_vect = np.round(perp_vect, 1) label = DecimalNumber(line.get_length() / unit_factor) label.move_to(line.get_center()) label.next_to(line.get_center(), perp_vect, buff=0.15) result.add(label) return result side_labels = always_redraw(get_length_labels) b_label, c_label, a_label = side_labels b_side, c_side, a_side = side_trackers # Rescale self.add(side_trackers) self.play(LaggedStartMap(FadeIn, side_labels, lag_ratio=0.3, run_time=1)) self.add(side_labels) self.wait() self.play(triangle.set_width, unit_factor) self.play(ShowCreationThenFadeAround(c_label)) self.wait() # Label x and y x_label = OldTex("x") y_label = OldTex("y") xy_labels = VGroup(x_label, y_label) xy_labels.scale(1.5) x_color = self.x1_color y_color = self.y1_color x_label[0].set_color(x_color) y_label[0].set_color(y_color) # side_labels.clear_updaters() for var, num, vect in zip(xy_labels, [b_label, a_label], [DR, DL]): buff = 0.15 var.move_to(num, vect) var.brace = Brace(num, UP) var.brace.num = num var.brace.add_updater( lambda m: m.next_to(m.num, UP, buff=buff) ) var.add_updater( lambda m: m.next_to(m.brace, UP, buff=buff) ) var.suspend_updating() var.brace.suspend_updating() self.play( FadeIn(var, DOWN), Write(var.brace, run_time=1), # MoveToTarget(num) ) self.wait() # Show plane to_move = VGroup( triangle, side_labels, x_label, x_label.brace, y_label, y_label.brace, ) axes = Axes( x_min=-0.25, x_max=1.5, y_min=-0.25, y_max=1.5, axis_config={ "tick_frequency": 0.25, "unit_size": 3, } ) x_axis = axes.x_axis y_axis = axes.y_axis x_axis.add(OldTex("x", color=x_color).next_to(x_axis, RIGHT)) y_axis.add(OldTex("y", color=y_color).next_to(y_axis, UP)) for axis, vect in [(x_axis, DOWN), (y_axis, LEFT)]: axis.add_numbers( 0.5, 1.0, direction=vect, num_decimal_places=1, ) axes.to_corner(DR, buff=LARGE_BUFF) self.play( to_move.to_corner, UL, {"buff": LARGE_BUFF}, to_move.shift, MED_LARGE_BUFF * DOWN, Write(axes), ) # Show coordinates coords = VGroup(b_label.copy(), a_label.copy()) x_coord, y_coord = coords x_coord.add_updater(lambda m: m.set_value(b_side.get_length() / unit_factor)) y_coord.add_updater(lambda m: m.set_value(a_side.get_length() / unit_factor)) def get_coord_values(): return [c.get_value() for c in coords] def get_ms_point(): return axes.c2p(*get_coord_values()) dot = always_redraw( lambda: triangle.copy().set_width(0.1).move_to(get_ms_point()) ) y_line = always_redraw( lambda: DashedLine( x_axis.n2p(x_coord.get_value()), get_ms_point(), color=y_color, stroke_width=1, ) ) x_line = always_redraw( lambda: DashedLine( y_axis.n2p(y_coord.get_value()), get_ms_point(), color=x_color, stroke_width=1, ) ) coord_label = OldTex("(", "0.00", ",", "0.00", ")") cl_buff = 0 coord_label.next_to(dot, UR, buff=cl_buff) for i, coord in zip([1, 3], coords): coord.generate_target() coord.target.replace(coord_label[i], dim_to_match=0) coord_label[i].set_opacity(0) self.play( MoveToTarget(x_coord), MoveToTarget(y_coord), FadeIn(coord_label), ReplacementTransform(triangle.copy().set_fill(opacity=0), dot), ) coord_label.add(*coords) coord_label.add_updater(lambda m: m.next_to(dot, UR, buff=cl_buff)) self.add(x_label, y_label, dot) self.play( ShowCreation(x_line), ShowCreation(y_line), ) self.wait() # Adjust triangle tip_tracker = VectorizedPoint(triangle.get_points()[0]) def update_triangle(tri): point = tip_tracker.get_location() tri.get_points()[0] = point tri.get_points()[-1] = point tri.make_jagged() triangle.add_updater(update_triangle) self.add(tip_tracker) self.play(tip_tracker.shift, 0.5 * LEFT + 1.0 * UP) self.play(tip_tracker.shift, 2.0 * DOWN) self.play(tip_tracker.shift, 1.5 * RIGHT) self.play(tip_tracker.shift, 1.0 * LEFT + 1.0 * UP) self.wait() # Show box t2c = {"x": x_color, "y": y_color} ineq1 = OldTex("0", "\\le ", "x", "\\le", "1", tex_to_color_map=t2c) ineq2 = OldTex("0", "\\le ", "y", "\\le", "1", tex_to_color_map=t2c) ineqs = VGroup(ineq1, ineq2) ineqs.scale(1.5) ineqs.arrange(DOWN, buff=MED_LARGE_BUFF) ineqs.next_to(triangle, DOWN, buff=1.5) box = Square( fill_color=GREY_D, fill_opacity=0.75, stroke_color=GREY_B, stroke_width=2, ) box.replace(Line(axes.c2p(0, 0), axes.c2p(1, 1))) box_outline = box.copy() box_outline.set_fill(opacity=0) box_outline.set_stroke(YELLOW, 3) self.add(box, axes, x_line, y_line, coord_label, dot) self.play( FadeIn(box), LaggedStartMap(FadeInFromDown, ineqs) ) self.play( ShowCreationThenFadeOut(box_outline) ) self.wait() # x >= y slice region = Polygon( axes.c2p(0, 0), axes.c2p(1, 0), axes.c2p(1, 1), fill_color=GREY_BROWN, fill_opacity=0.75, stroke_color=GREY_BROWN, stroke_width=2, ) region_outline = region.copy() region_outline.set_fill(opacity=0) region_outline.set_stroke(YELLOW, 3) x_eq_y_line = Line(axes.c2p(0, 0), axes.c2p(1, 1)) x_eq_y_line.set_stroke(self.x_eq_y_color, 2) x_eq_y_label = OldTex("x=y", tex_to_color_map=t2c) x_eq_y_label.next_to(x_eq_y_line.get_end(), LEFT, MED_LARGE_BUFF) x_eq_y_label.shift(0.75 * DL) ineq = OldTex("0", "\\le", "y", "\\le", "x", "\\le", "1") ineq.set_color_by_tex("x", x_color) ineq.set_color_by_tex("y", y_color) ineq.scale(1.5) ineq.move_to(ineqs, LEFT) self.add(region, axes, x_line, y_line, coord_label, dot) self.play( FadeIn(region), ShowCreation(x_eq_y_line), # FadeInFromDown(x_eq_y_label), Transform(ineq1[:2], ineq[:2], remover=True), Transform(ineq1[2:], ineq[4:], remover=True), Transform(ineq2[:4], ineq[:4], remover=True), Transform(ineq2[4:], ineq[6:], remover=True), ) self.add(ineq) self.play(ShowCreationThenFadeOut(region_outline)) self.wait() # x + y <= 1 slice xpy1_line = Line(axes.c2p(0, 1), axes.c2p(1, 0)) xpy1_line.set_stroke(GREEN, 2) xpy1_label = OldTex("x+y=1", tex_to_color_map=t2c) xpy1_label.next_to(xpy1_line.get_start(), RIGHT, MED_LARGE_BUFF) xpy1_label.shift(0.75 * DR) xpy1_ineq = OldTex("1 \\le x + y", tex_to_color_map=t2c) xpy1_ineq.scale(1.5) xpy1_ineq.next_to(ineq, DOWN, buff=MED_LARGE_BUFF) ms_region = Polygon( axes.c2p(1, 0), axes.c2p(0.5, 0.5), axes.c2p(1, 1), fill_color=BLUE_E, fill_opacity=0.75, stroke_width=0, ) ms_outline = ms_region.copy() ms_outline.set_fill(opacity=0) ms_outline.set_stroke(YELLOW, 2) tt_line = Line(DOWN, UP, color=WHITE) tt_line.set_height(0.25) tt_line.add_updater(lambda m: m.move_to(tip_tracker)) self.play( ShowCreation(xpy1_line), # FadeIn(xpy1_label, DOWN), FadeIn(xpy1_ineq, UP) ) self.wait() self.play( tip_tracker.set_y, triangle.get_bottom()[1] + 0.01, FadeIn(tt_line), ) self.wait() self.add(ms_region, axes, x_line, y_line, coord_label, dot) self.play( FadeIn(ms_region), region.set_fill, GREY_D, ) self.wait() # Move tip around self.play( tip_tracker.shift, UP + RIGHT, FadeOut(tt_line), ) self.wait() self.play(tip_tracker.shift, 0.5 * DOWN + LEFT, run_time=2) self.wait() self.play(tip_tracker.shift, UP + 0.7 * LEFT, run_time=2) self.wait() equilateral_point = triangle.get_bottom() + unit_factor * 0.5 * np.sqrt(3) * UP self.play( tip_tracker.move_to, equilateral_point, run_time=2, ) self.wait() # Label as moduli space ms_words = OldTexText("Moduli\\\\", "Space") ms_words.scale(1.5) ms_words.next_to(ms_region, RIGHT, buff=0.35) ms_arrow = Arrow( ms_words[1].get_corner(DL), ms_region.get_center(), path_arc=-90 * DEGREES, buff=0.1, ) # ms_arrow.rotate(-10 * DEGREES) ms_arrow.shift(0.1 * RIGHT) ms_arrow.scale(0.95) self.play( FadeIn(ms_words, LEFT), ) self.play(ShowCreation(ms_arrow)) self.wait() # Show right triangles alpha = np.arcsin(0.8) vect = rotate_vector(0.6 * unit_factor * LEFT, -alpha) new_tip = triangle.get_corner(DR) + vect elbow = VMobject() elbow.start_new_path(RIGHT) elbow.add_line_to(UR) elbow.add_line_to(UP) elbow.rotate(3 * TAU / 4 - alpha, about_point=ORIGIN) elbow.scale(0.2, about_point=ORIGIN) elbow.shift(new_tip) elbow_circle = Circle() elbow_circle.replace(elbow) elbow_circle.scale(3) elbow_circle.move_to(new_tip) elbow_circle.set_stroke(self.right_color, 3) right_words = OldTexText("Right triangle") right_words.scale(1.5) right_words.set_color(self.right_color) right_words.next_to(triangle, DOWN, buff=1.5) ineqs = VGroup(ineq, xpy1_ineq) self.play( tip_tracker.move_to, new_tip, FadeOut(ms_words), FadeOut(ms_arrow), ) self.play( ShowCreation(elbow), FadeIn(right_words, UP), FadeOut(ineqs, DOWN), ) self.play( ShowCreationThenFadeOut(elbow_circle), ) # Show circular arc pythag_eq = OldTex("x^2 + y^2", "=", "1", tex_to_color_map=t2c) pythag_eq.scale(1.5) pythag_eq.next_to(right_words, DOWN, buff=MED_LARGE_BUFF) arc = Arc( start_angle=90 * DEGREES, angle=-90 * DEGREES, color=self.right_color, ) arc.replace(box) self.play( FadeIn(pythag_eq, UP), ) self.add(arc, arc) self.play(ShowCreation(arc)) self.wait() # Acute region arc_piece = VMobject() arc_piece.pointwise_become_partial(arc, 0.5, 1.0) acute_region = VMobject() acute_region.start_new_path(axes.c2p(1, 1)) acute_region.add_line_to(arc_piece.get_start()) acute_region.append_vectorized_mobject(arc_piece) acute_region.add_line_to(axes.c2p(1, 1)) acute_region.set_fill(self.acute_color, 1) acute_region.set_stroke(width=0) obtuse_region = VMobject() obtuse_region.start_new_path(axes.c2p(1, 0)) obtuse_region.add_line_to(axes.c2p(0.5, 0.5)) obtuse_region.add_line_to(arc_piece.get_start()) obtuse_region.append_vectorized_mobject(arc_piece) obtuse_region.set_fill(self.obtuse_color, 1) obtuse_region.set_stroke(width=0) acute_words = OldTexText("Acute triangle") acute_words.set_color(self.acute_color) obtuse_words = OldTexText("Obtuse triangle") obtuse_words.set_color(self.obtuse_color) for words in [acute_words, obtuse_words]: words.scale(1.5) words.move_to(right_words) eq = pythag_eq[-2] gt = OldTex(">").replace(eq) gt.set_color(self.acute_color) lt = OldTex("<").replace(eq) lt.set_color(self.obtuse_color) self.add(acute_region, coord_label, x_line, y_line, xpy1_line, x_eq_y_line, dot) self.play( tip_tracker.shift, 0.5 * UP, coord_label.set_opacity, 0, FadeOut(elbow), FadeIn(acute_region), FadeOut(right_words, UP), FadeOut(eq, UP), FadeIn(acute_words, DOWN), FadeIn(gt, DOWN), ) self.wait() self.play(tip_tracker.shift, 0.5 * RIGHT) self.wait() self.add(obtuse_region, coord_label, x_line, y_line, xpy1_line, x_eq_y_line, dot) self.play( tip_tracker.shift, 1.5 * DOWN, FadeIn(obtuse_region), FadeOut(acute_words, DOWN), FadeOut(gt, DOWN), FadeIn(obtuse_words, UP), FadeIn(lt, UP), ) self.wait() self.play(tip_tracker.shift, 0.5 * LEFT) self.play(tip_tracker.shift, 0.5 * DOWN) self.play(tip_tracker.shift, 0.5 * RIGHT) self.play(tip_tracker.shift, 0.5 * UP) self.wait() # Ambient changes self.play( FadeOut(obtuse_words), FadeOut(pythag_eq[:-2]), FadeOut(pythag_eq[-1]), FadeOut(lt), ) self.play( tip_tracker.move_to, equilateral_point + 0.25 * DL, path_arc=30 * DEGREES, run_time=8, ) # def get_triangles_and_classes(self): original_triangles = VGroup(*[ self.get_random_triangle() for x in range(5) ]) original_triangles.submobjects[4] = self.get_random_triangle() # Hack all_triangles = VGroup() tri_classes = VGroup() for triangle in original_triangles: all_triangles.add(triangle) tri_class = VGroup() tri_class.add(triangle) for x in range(2): tri_copy = triangle.copy() angle = TAU * np.random.random() scalar = 0.25 + 1.5 * np.random.random() tri_copy.rotate(angle - tri_copy.angle) tri_copy.angle = angle tri_copy.scale(scalar / tri_copy.scalar) tri_copy.scalar = scalar all_triangles.add(tri_copy) tri_class.add(tri_copy) tri_classes.add(tri_class) colors = Color(BLUE).range_to(Color(RED), len(all_triangles)) for triangle, color in zip(all_triangles, colors): # triangle.set_color(random_bright_color()) triangle.set_color(color) all_triangles.shuffle() all_triangles.arrange_in_grid(3, 5, buff=MED_LARGE_BUFF) all_triangles.set_height(6) sf = 1.25 all_triangles.stretch(sf, 0) for triangle in all_triangles: triangle.stretch(1 / sf, 0) # all_triangles.next_to(title, DOWN) all_triangles.to_edge(DOWN, LARGE_BUFF) return all_triangles, tri_classes def get_random_triangle(self, x=None, y=None): y = np.random.random() x = y + np.random.random() if x + y <= 1: diff = 1 - (x + y) x += diff y += diff tri = self.get_triangle(x, y) tri.angle = TAU * np.random.random() tri.scalar = 0.25 + np.random.random() * 1.5 tri.rotate(tri.angle) tri.scale(tri.scalar) return tri def get_triangle(self, x, y): # Enforce assumption that x > y if y > x: raise Exception("Please ensure x >= y. Thank you.") plane = self.plane # Heron s = (1 + x + y) / 2.0 area = np.sqrt(s * (s - 1.0) * (s - x) * (s - y)) beta = np.arcsin(2 * area / x) tip_point = RIGHT + rotate_vector(x * LEFT, -beta) color = self.get_triangle_color(x, y) return Polygon( plane.c2p(0, 0), plane.c2p(1, 0), plane.c2p(*tip_point[:2]), color=color, fill_opacity=self.triangle_fill_opacity, ) def get_triangle_color(self, x, y): epsilon = 1e-4 if x + y == 1: return self.x_eq_y_color elif x == 1: return self.x1_color elif y == 1: return self.y1_color elif np.abs(x**2 + y**2 - 1) < epsilon: return self.right_color elif x**2 + y**2 < 1: return self.obtuse_color elif x**2 + y**2 > 1: return self.acute_color assert(False) # Should not get here def get_triangle_xy(self, triangle): A, B, C = triangle.get_start_anchors()[:3] a = get_norm(B - C) b = get_norm(C - A) c = get_norm(A - B) sides = np.array(sorted([a, b, c])) sides = sides / np.max(sides) return sides[1], sides[0] def get_triangle_x(self, triangle): return self.get_triangle_xy(triangle)[0] def get_triangle_y(self, triangle): return self.get_triangle_xy(triangle)[1] class Credits(Scene): def construct(self): items = VGroup( OldTexText("Written by\\\\Jayadev Athreya"), OldTexText("Illustrated and Narrated by\\\\Grant Sanderson"), OldTexText( "3Blue1Brown\\\\", "\\copyright {} Copyright 2019\\\\", "www.3blue1brown.com\\\\", ), ) items.arrange(DOWN, buff=LARGE_BUFF) items[-1].set_color(GREY_B) items[-1].scale(0.8, about_edge=UP) items[-1].to_edge(DOWN) self.add(items[-1]) self.play(LaggedStartMap(FadeInFromDown, items[:-1])) self.wait()
from manim_imports_ext import * from _2017.mug import HappyHolidays # For Q&A Video class Questions(Scene): def construct(self): kw = { "alignment": "" } TexText.CONFIG.update(kw) questions = VGroup( OldTexText( "Who is your favorite mathematician?" ), OldTexText( "A teenage kid walks up to you and says they\\\\", "hate maths. What do you tell/show them?" ), OldTexText( "What advice would you want to give to give a\\\\", "math enthusiast suffering from an anxiety\\\\", "disorder, clinical depression and ADHD?", ), OldTexText( "Is Ben, Ben and Blue still a thing?" ), OldTexText( "Favorite podcasts?" ), OldTexText( "Hey Grant, if you had, both, the responsibility and\\\\", "opportunity to best introduce the world of mathematics\\\\", "to curious and intelligent minds before they are shaped\\\\", "by the antiquated, disempowering and demotivational\\\\", "education system of today, what would you do? (Asking\\\\", "because I will soon be a father).\\\\", ), OldTexText( "What's something you think could've\\\\", "been discovered long before it was\\\\", "actually discovered?", ), OldTexText( "Can we fix math on Wikipedia? Really serious\\\\", "here. I constantly go there after your vids for\\\\", "a bit of deeper dive and learn - nothing more, ever.\\\\", "Compared to almost any topic in the natural sciences\\\\", "or physics where at least I get an outline of where\\\\", "to go next. It's such a shame." ), ) last_question = VMobject() for question in questions: question.set_width(FRAME_WIDTH - 1) self.play( FadeInFromDown(question), FadeOut(last_question, UP) ) last_question = question self.wait(2) class MathematicianPlusX(Scene): def construct(self): text = OldTexText( "Side note:\\\\", "``The Mathematician + X''\\\\", "would make a great band name.", ) text.set_width(FRAME_WIDTH - 1) self.add(text) class NoClearCutPath(Scene): def construct(self): path1 = VMobject() path1.start_new_path(3 * LEFT) path1.add_line_to(ORIGIN) path1.append_points([ ORIGIN, 2.5 * RIGHT, 2.5 * RIGHT + 3 * UP, 5 * RIGHT + 3 * UP, ]) path2 = path1.copy() path2.rotate(PI, axis=RIGHT, about_point=ORIGIN) paths = VGroup(path1, path2) paths.to_edge(LEFT) paths.set_stroke(WHITE, 2) labels = VGroup( OldTexText("Pure mathematicians"), OldTexText("Applied mathematicians"), ) for label, path in zip(labels, paths): label.next_to(path.get_end(), RIGHT) animations = [] n_animations = 20 colors = [BLUE_C, BLUE_D, BLUE_E, GREY_BROWN] for x in range(n_animations): dot = self.get_dot(random.choice(colors)) path = random.choice(paths) dot.move_to(path.get_start()) anim = Succession( # FadeIn(dot), MoveAlongPath(dot, path, run_time=4, rate_func=lambda t: smooth(t, 2)), FadeOut(dot), ) animations.append(anim) alt_path = VMobject() alt_path.start_new_path(paths.get_left()) alt_path.add_line_to(paths.get_left() + 3 * RIGHT) alt_path.add_line_to(2 * UP) alt_path.add_line_to(2 * DOWN + RIGHT) alt_path.add_line_to(2 * RIGHT) alt_path.add_line_to(3 * RIGHT) alt_path.add_line_to(8 * RIGHT) alt_path.make_smooth() alt_path.set_stroke(YELLOW, 3) dashed_path = DashedVMobject(alt_path, num_dashes=100) alt_dot = self.get_dot(YELLOW) alt_dot.move_to(alt_path.get_start()) alt_dot_anim = MoveAlongPath( alt_dot, alt_path, run_time=10, rate_func=linear, ) self.add(paths) self.add(labels) self.play( LaggedStart( *animations, run_time=10, lag_ratio=1 / n_animations, ), ShowCreation( dashed_path, rate_func=linear, run_time=10, ), alt_dot_anim, ) self.wait() def get_dot(self, color): dot = Dot() dot.scale(1.5) dot.set_color(color) dot.set_stroke(BLACK, 2, background=True) return dot class Cumulative(Scene): def construct(self): colors = list(Color(BLUE_B).range_to(BLUE_D, 20)) rects = VGroup(*[ Rectangle( height=0.3, width=4, fill_color=random.choice(colors), fill_opacity=1, stroke_color=WHITE, stroke_width=1, ) for i, color in zip(range(20), it.cycle(colors)) ]) rects.arrange(UP, buff=0) check = OldTex("\\checkmark").set_color(GREEN) cross = OldTex("\\times").set_color(RED) checks, crosses = [ VGroup(*[ mob.copy().next_to(rect, RIGHT, SMALL_BUFF) for rect in rects ]) for mob in [check, cross] ] rects.set_fill(opacity=0) self.add(rects) for i in range(7): self.play( rects[i].set_fill, None, 1.0, Write(checks[i]), run_time=0.5, ) self.play(FadeOut(rects[7], 2 * LEFT)) self.play( LaggedStartMap(Write, crosses[8:]), LaggedStartMap( ApplyMethod, rects[8:], lambda m: (m.set_fill, None, 0.2), ) ) self.wait() rects[7].set_opacity(1) self.play( FadeIn(rects[7], 2 * LEFT), FadeIn(checks[7], 2 * LEFT), ) self.play( LaggedStartMap( ApplyMethod, rects[8:], lambda m: (m.set_fill, None, 1.0), ), LaggedStart(*[ ReplacementTransform(cross, check) for cross, check in zip(crosses[8:], checks[8:]) ]) ) self.wait() class HolidayStorePromotionTime(HappyHolidays): def construct(self): title = OldTexText("Holiday store promotion time!") title.set_width(FRAME_WIDTH - 1) title.to_edge(UP) self.add(title) HappyHolidays.construct(self)
from manim_imports_ext import * class PrimePiEPttern(Scene): def construct(self): self.add(FullScreenFadeRectangle(fill_color=WHITE, fill_opacity=1)) tex0 = OldTex( "\\frac{1}{1^2}", "+" "\\frac{1}{2^2}", "+" "\\frac{1}{3^2}", "+" "\\frac{1}{4^2}", "+" "\\frac{1}{5^2}", "+" "\\frac{1}{6^2}", "+" # "\\frac{1}{7^2}", "+" # "\\frac{1}{8^2}", "+" # "\\frac{1}{9^2}", "+" # "\\frac{1}{10^2}", "+" # "\\frac{1}{11^2}", "+" # "\\frac{1}{12^2}", "+" "\\cdots", "=", "\\frac{\\pi^2}{6}", ) self.alter_tex(tex0) # self.add(tex0) tex1 = OldTex( "\\underbrace{\\frac{1}{1^2}}_{\\text{kill}}", "+", "\\underbrace{\\frac{1}{2^2}}_{\\text{keep}}", "+", "\\underbrace{\\frac{1}{3^2}}_{\\text{keep}}", "+", "\\underbrace{\\frac{1}{4^2}}_{\\times (1 / 2)}", "+", "\\underbrace{\\frac{1}{5^2}}_{\\text{keep}}", "+", "\\underbrace{\\frac{1}{6^2}}_{\\text{kill}}", "+", "\\underbrace{\\frac{1}{7^2}}_{\\text{keep}}", "+", "\\underbrace{\\frac{1}{8^2}}_{\\times (1 / 3)}", "+", "\\underbrace{\\frac{1}{9^2}}_{\\times (1 / 2)}", "+", "\\underbrace{\\frac{1}{10^2}}_{\\text{kill}}", "+", "\\underbrace{\\frac{1}{11^2}}_{\\text{keep}}", "+", "\\underbrace{\\frac{1}{12^2}}_{\\text{kill}}", "+", "\\cdots", # "=", # "\\frac{\\pi^2}{6}" ) self.alter_tex(tex1) tex1.set_color_by_tex("kill", RED) tex1.set_color_by_tex("keep", GREEN_E) tex1.set_color_by_tex("times", BLUE_D) self.add(tex1) return # tex1 = OldTex( # "\\underbrace{\\frac{1}{1}}_{\\text{kill}}", "+", # "\\underbrace{\\frac{-1}{3}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{1}{5}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{-1}{7}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{1}{9}}_{\\times (1 / 2)}", "+", # "\\underbrace{\\frac{-1}{11}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{1}{13}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{-1}{15}}_{\\text{kill}}", "+", # "\\underbrace{\\frac{1}{17}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{-1}{19}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{1}{21}}_{\\text{kill}}", "+", # "\\underbrace{\\frac{-1}{23}}_{\\text{keep}}", "+", # "\\underbrace{\\frac{1}{25}}_{\\times (1 / 2)}", "+", # "\\underbrace{\\frac{-1}{27}}_{\\times (1 / 3)}", "+", # "\\cdots", # "=", # "\\frac{\\pi}{4}" # ) # self.alter_tex(tex1) # VGroup( # tex1[2 * 0], # tex1[2 * 7], # tex1[2 * 10], # ).set_color(RED) # VGroup( # tex1[2 * 1], # tex1[2 * 2], # tex1[2 * 3], # tex1[2 * 5], # tex1[2 * 6], # tex1[2 * 8], # tex1[2 * 9], # tex1[2 * 11], # ).set_color(GREEN_E) # VGroup( # tex1[2 * 4], # tex1[2 * 12], # tex1[2 * 13], # ).set_color(BLUE_D) # self.add(tex1) # tex2 = OldTex( # "\\frac{-1}{3}", "+", # "\\frac{1}{5}", "+", # "\\frac{-1}{7}", "+", # "\\frac{1}{2}", "\\cdot", "\\frac{1}{9}", "+", # "\\frac{-1}{11}", "+", # "\\frac{1}{13}", "+", # "\\frac{1}{17}", "+", # "\\frac{-1}{19}", "+", # "\\frac{-1}{23}", "+", # "\\frac{1}{2}", "\\cdot", "\\frac{1}{25}", "+", # "\\frac{1}{3}", "\\cdot", "\\frac{-1}{27}", "+", # "\\cdots", # ) # self.alter_tex(tex2) # VGroup( # tex2[2 * 0], # tex2[2 * 1], # tex2[2 * 2], # tex2[2 * 5], # tex2[2 * 6], # tex2[2 * 7], # tex2[2 * 8], # tex2[2 * 9], # ).set_color(GREEN_E) # VGroup( # tex2[2 * 3], # tex2[2 * 4], # tex2[2 * 10], # tex2[2 * 11], # tex2[2 * 12], # tex2[2 * 13], # ).set_color(BLUE_D) tex2 = OldTex( "\\frac{1}{2^2}", "+", "\\frac{1}{3^2}", "+", "\\frac{1}{2}", "\\cdot", "\\frac{1}{4^2}", "+", "\\frac{1}{5^2}", "+", "\\frac{1}{7^2}", "+", "\\frac{1}{3}", "\\cdot", "\\frac{1}{8^2}", "+", "\\frac{1}{2}", "\\cdot", "\\frac{1}{9^2}", "+", "\\frac{1}{11^2}", "+", "\\frac{1}{13^2}", "+", "\\frac{1}{4}", "\\cdot", "\\frac{1}{16^2}", "+", "\\cdots", ) self.alter_tex(tex2) VGroup( tex2[2 * 0], tex2[2 * 1], tex2[2 * 4], tex2[2 * 5], tex2[2 * 10], tex2[2 * 11], ).set_color(GREEN_E) VGroup( tex2[2 * 2], tex2[2 * 3], tex2[2 * 6], tex2[2 * 7], tex2[2 * 8], tex2[2 * 9], tex2[2 * 12], tex2[2 * 13], ).set_color(BLUE_D) self.add(tex2) exp = OldTex( "e^{\\left(", "0" * 30, "\\right)}", "= \\frac{\\pi^2}{6}" ) self.alter_tex(exp) exp[1].set_opacity(0) tex2.replace(exp[1], dim_to_match=0) self.add(exp, tex2) def alter_tex(self, tex): tex.set_color(BLACK) tex.set_stroke(BLACK, 0, background=True) tex.set_width(FRAME_WIDTH - 1)
from manim_imports_ext import * class GREquations(Scene): CONFIG = { "mu_color": BLUE_E, "nu_color": RED_E, "camera_config": { "background_color": WHITE, }, "tex_config": { "color": BLACK, "background_stroke_width": 0, }, } def construct(self): eq1 = self.get_field_eq("\\mu", "\\nu") indices = list(filter( lambda t: t[0] <= t[1], it.product(range(4), range(4)) )) sys1, sys2 = [ VGroup(*[ self.get_field_eq(i, j, simple=simple) for i, j in indices ]) for simple in (True, False) ] for sys in sys1, sys2: sys.arrange(DOWN, buff=MED_LARGE_BUFF) sys.set_height(FRAME_HEIGHT - 0.5) sys2.center() sys1.next_to(ORIGIN, RIGHT) eq1.generate_target() group = VGroup(eq1.target, sys1) group.arrange(RIGHT, buff=2) arrows = VGroup(*[ Arrow( eq1.target.get_right(), eq.get_left(), buff=0.2, color=BLACK, stroke_width=2, tip_length=0.2, ) for eq in sys1 ]) self.play(FadeIn(eq1, DOWN)) self.wait() self.play( MoveToTarget(eq1), LaggedStart(*[ GrowArrow(arrow) for arrow in arrows ]), ) self.play( LaggedStart(*[ TransformFromCopy(eq1, eq) for eq in sys1 ], lag_ratio=0.2), ) self.wait() # sys1.generate_target() sys1.target.to_edge(LEFT) sys2.to_edge(RIGHT) new_arrows = VGroup(*[ Arrow( e1.get_right(), e2.get_left(), buff=SMALL_BUFF, color=BLACK, stroke_width=2, tip_length=0.2, ) for e1, e2 in zip(sys1.target, sys2) ]) self.play( MoveToTarget(sys1), MaintainPositionRelativeTo(arrows, sys1), MaintainPositionRelativeTo(eq1, sys1), VFadeOut(arrows), VFadeOut(eq1), ) # sys1_rects, sys2_rects = [ VGroup(*map(self.get_rects, sys)) for sys in [sys1, sys2] ] self.play( LaggedStartMap(FadeIn, sys1_rects), LaggedStartMap(GrowArrow, new_arrows), run_time=1, ) self.play( TransformFromCopy(sys1_rects, sys2_rects), TransformFromCopy(sys1, sys2), ) self.play( FadeOut(sys1_rects), FadeOut(sys2_rects), ) self.wait() def get_field_eq(self, mu, nu, simple=True): mu = "{" + str(mu) + " }" # Deliberate space nu = "{" + str(nu) + "}" config = dict(self.tex_config) config["tex_to_color_map"] = { mu: self.mu_color, nu: self.nu_color, } if simple: tex_args = [ ("R_{%s%s}" % (mu, nu),), ("-{1 \\over 2}",), ("g_{%s%s}" % (mu, nu),), ("R",), ("=",), ("8\\pi T_{%s%s}" % (mu, nu),), ] else: tex_args = [ ( "\\left(", "\\partial_\\rho \\Gamma^{\\rho}_{%s%s} -" % (mu, nu), "\\partial_%s \\Gamma^{\\rho}_{\\rho%s} +" % (nu, mu), "\\Gamma^{\\rho}_{\\rho\\lambda}", "\\Gamma^{\\lambda}_{%s%s} -" % (nu, mu), "\\Gamma^{\\rho}_{%s \\lambda}" % nu, "\\Gamma^{\\lambda}_{\\rho %s}" % mu, "\\right)", ), ("-{1 \\over 2}",), ("g_{%s%s}" % (mu, nu),), ( "g^{\\alpha \\beta}", "\\left(", "\\partial_\\rho \\Gamma^{\\rho}_{\\beta \\alpha} -" "\\partial_\\beta \\Gamma^{\\rho}_{\\rho\\alpha} +", "\\Gamma^{\\rho}_{\\rho\\lambda}", "\\Gamma^{\\lambda}_{\\beta\\alpha} -" "\\Gamma^{\\rho}_{\\beta \\lambda}", "\\Gamma^{\\lambda}_{\\rho \\alpha}", "\\right)", ), ("=",), ("8\\pi T_{%s%s}" % (mu, nu),), ] result = VGroup(*[ OldTex(*args, **config) for args in tex_args ]) result.arrange(RIGHT, buff=SMALL_BUFF) return result def get_rects(self, equation): return VGroup(*[ SurroundingRectangle( equation[i], buff=0.025, color=color, stroke_width=1, ) for i, color in zip( [0, 3], [GREY, GREY] ) ])
from manim_imports_ext import * import scipy.integrate OUTPUT_DIRECTORY = "bayes/part1" HYPOTHESIS_COLOR = YELLOW NOT_HYPOTHESIS_COLOR = GREY EVIDENCE_COLOR1 = BLUE_C EVIDENCE_COLOR2 = BLUE_E NOT_EVIDENCE_COLOR1 = GREY NOT_EVIDENCE_COLOR2 = GREY_D # def get_bayes_formula(expand_denominator=False): t2c = { "{H}": HYPOTHESIS_COLOR, "{\\neg H}": NOT_HYPOTHESIS_COLOR, "{E}": EVIDENCE_COLOR1, } isolate = ["P", "\\over", "=", "\\cdot", "+"] tex = "P({H} | {E}) = {P({H}) P({E} | {H}) \\over " if expand_denominator: tex += "P({H}) P({E} | {H}) + P({\\neg H}) \\cdot P({E} | {\\neg H})}" else: tex += "P({E})}" formula = OldTex( tex, tex_to_color_map=t2c, isolate=isolate, ) formula.posterior = formula[:6] formula.prior = formula[8:12] formula.likelihood = formula[13:19] if expand_denominator: pass formula.denom_prior = formula[20:24] formula.denom_likelihood = formula[25:31] formula.denom_anti_prior = formula[32:36] formula.denom_anti_likelihood = formula[37:42] else: formula.p_evidence = formula[20:] return formula class BayesDiagram(VGroup): CONFIG = { "height": 2, "square_style": { "fill_color": GREY_D, "fill_opacity": 1, "stroke_color": WHITE, "stroke_width": 2, }, "rect_style": { "stroke_color": WHITE, "stroke_width": 1, "fill_opacity": 1, }, "hypothesis_color": HYPOTHESIS_COLOR, "not_hypothesis_color": NOT_HYPOTHESIS_COLOR, "evidence_color1": EVIDENCE_COLOR1, "evidence_color2": EVIDENCE_COLOR2, "not_evidence_color1": NOT_EVIDENCE_COLOR1, "not_evidence_color2": NOT_EVIDENCE_COLOR2, "prior_rect_direction": DOWN, } def __init__(self, prior, likelihood, antilikelihood, **kwargs): super().__init__(**kwargs) square = Square(side_length=self.height) square.set_style(**self.square_style) # Create all rectangles h_rect, nh_rect, he_rect, nhe_rect, hne_rect, nhne_rect = [ square.copy().set_style(**self.rect_style) for x in range(6) ] # Add as attributes self.square = square self.h_rect = h_rect # Hypothesis self.nh_rect = nh_rect # Not hypothesis self.he_rect = he_rect # Hypothesis and evidence self.hne_rect = hne_rect # Hypothesis and not evidence self.nhe_rect = nhe_rect # Not hypothesis and evidence self.nhne_rect = nhne_rect # Not hypothesis and not evidence # Stretch the rectangles for rect in h_rect, he_rect, hne_rect: rect.stretch(prior, 0, about_edge=LEFT) for rect in nh_rect, nhe_rect, nhne_rect: rect.stretch(1 - prior, 0, about_edge=RIGHT) he_rect.stretch(likelihood, 1, about_edge=DOWN) hne_rect.stretch(1 - likelihood, 1, about_edge=UP) nhe_rect.stretch(antilikelihood, 1, about_edge=DOWN) nhne_rect.stretch(1 - antilikelihood, 1, about_edge=UP) # Color the rectangles h_rect.set_fill(self.hypothesis_color) nh_rect.set_fill(self.not_hypothesis_color) he_rect.set_fill(self.evidence_color1) hne_rect.set_fill(self.not_evidence_color1) nhe_rect.set_fill(self.evidence_color2) nhne_rect.set_fill(self.not_evidence_color2) # Add them self.hypothesis_split = VGroup(h_rect, nh_rect) self.evidence_split = VGroup(he_rect, hne_rect, nhe_rect, nhne_rect) # Don't add hypothesis split by default self.add(self.square, self.hypothesis_split, self.evidence_split) self.square.set_opacity(0) self.hypothesis_split.set_opacity(0) def add_brace_attrs(self, buff=SMALL_BUFF): braces = self.braces = self.create_braces(buff) self.braces_buff = buff attrs = [ "h_brace", "nh_brace", "he_brace", "hne_brace", "nhe_brace", "nhne_brace", ] for brace, attr in zip(braces, attrs): setattr(self, attr, brace) return self def create_braces(self, buff=SMALL_BUFF): kw = { "buff": buff, "min_num_quads": 1, } return VGroup( Brace(self.h_rect, self.prior_rect_direction, **kw), Brace(self.nh_rect, self.prior_rect_direction, **kw), Brace(self.he_rect, LEFT, **kw), Brace(self.hne_rect, LEFT, **kw), Brace(self.nhe_rect, RIGHT, **kw), Brace(self.nhne_rect, RIGHT, **kw), ) def refresh_braces(self): if hasattr(self, "braces"): self.braces.become( self.create_braces(self.braces_buff) ) return self def set_prior(self, new_prior): p = new_prior q = 1 - p full_width = self.square.get_width() left_rects = [self.h_rect, self.he_rect, self.hne_rect] right_rects = [self.nh_rect, self.nhe_rect, self.nhne_rect] for group, vect, value in [(left_rects, LEFT, p), (right_rects, RIGHT, q)]: for rect in group: rect.set_width( value * full_width, stretch=True, about_edge=vect, ) self.refresh_braces() return self def general_set_likelihood(self, new_likelihood, low_rect, high_rect): height = self.square.get_height() low_rect.set_height( new_likelihood * height, stretch=True, about_edge=DOWN, ) high_rect.set_height( (1 - new_likelihood) * height, stretch=True, about_edge=UP, ) self.refresh_braces() return self def set_likelihood(self, new_likelihood): self.general_set_likelihood( new_likelihood, self.he_rect, self.hne_rect, ) return self def set_antilikelihood(self, new_antilikelihood): self.general_set_likelihood( new_antilikelihood, self.nhe_rect, self.nhne_rect, ) return self def copy(self): return self.deepcopy() class ProbabilityBar(VGroup): CONFIG = { "color1": BLUE_D, "color2": GREY_BROWN, "height": 0.5, "width": 6, "rect_style": { "stroke_width": 1, "stroke_color": WHITE, "fill_opacity": 1, }, "include_braces": False, "brace_direction": UP, "include_percentages": True, "percentage_background_stroke_width": 2, } def __init__(self, p=0.5, **kwargs): super().__init__(**kwargs) self.add_backbone() self.add_p_tracker(p) self.add_bars() if self.include_braces: self.braces = always_redraw(lambda: self.get_braces()) self.add(self.braces) if self.include_percentages: self.percentages = always_redraw(lambda: self.get_percentages()) self.add(self.percentages) def add_backbone(self): backbone = Line() backbone.set_opacity(0) backbone.set_width(self.width) self.backbone = backbone self.add(backbone) def add_p_tracker(self, p): self.p_tracker = ValueTracker(p) def add_bars(self): bars = VGroup(Rectangle(), Rectangle()) bars.set_height(self.height) colors = [self.color1, self.color2] for bar, color in zip(bars, colors): bar.set_style(**self.rect_style) bar.set_fill(color=color) bars.add_updater(self.update_bars) self.bars = bars self.add(bars) def update_bars(self, bars): vects = [LEFT, RIGHT] p = self.p_tracker.get_value() values = [p, 1 - p] total_width = self.backbone.get_width() for bar, vect, value in zip(bars, vects, values): bar.set_width(value * total_width, stretch=True) bar.move_to(self.backbone, vect) return bars def get_braces(self): return VGroup(*[ Brace( bar, self.brace_direction, min_num_quads=1, buff=SMALL_BUFF, ) for bar in self.bars ]) def get_percentages(self): p = self.p_tracker.get_value() labels = VGroup(*[ Integer(value, unit="\\%") for value in [ np.floor(p * 100), 100 - np.floor(p * 100), ] ]) for label, bar in zip(labels, self.bars): label.set_height(0.75 * bar.get_height()) min_width = 0.75 * bar.get_width() if label.get_width() > min_width: label.set_width(min_width) label.move_to(bar) label.set_stroke( BLACK, self.percentage_background_stroke_width, background=True ) return labels def add_icons(self, *icons, buff=SMALL_BUFF): if hasattr(self, "braces"): refs = self.braces else: refs = self.bars for icon, ref in zip(icons, refs): icon.ref = ref icon.add_updater(lambda i: i.next_to( i.ref, self.brace_direction, buff=buff )) self.icons = VGroup(*icons) self.add(self.icons) class Steve(SVGMobject): CONFIG = { "file_name": "steve", "fill_color": GREY, "sheen_factor": 0.5, "sheen_direction": UL, "stroke_width": 0, "height": 3, "include_name": True, "name": "Steve" } def __init__(self, **kwargs): super().__init__(**kwargs) if self.include_name: self.add_name() def add_name(self): self.name = OldTexText(self.name) self.name.match_width(self) self.name.next_to(self, DOWN, SMALL_BUFF) self.add(self.name) class Linda(Steve): CONFIG = { "file_name": "linda", "name": "Linda" } class LibrarianIcon(SVGMobject): CONFIG = { "file_name": "book", "stroke_width": 0, "fill_color": GREY_B, "sheen_factor": 0.5, "sheen_direction": UL, "height": 0.75, } class FarmerIcon(SVGMobject): CONFIG = { "file_name": "farming", "stroke_width": 0, "fill_color": GREEN_E, "sheen_factor": 0.5, "sheen_direction": UL, "height": 1.5, } class PitchforkIcon(SVGMobject): CONFIG = { "file_name": "pitch_fork_and_roll", "stroke_width": 0, "fill_color": GREY_B, "sheen_factor": 0.5, "sheen_direction": UL, "height": 1.5, } class Person(SVGMobject): CONFIG = { "file_name": "person", "height": 1.5, "stroke_width": 0, "fill_opacity": 1, "fill_color": GREY_B, } class Librarian(Person): CONFIG = { "IconClass": LibrarianIcon, "icon_style": { "background_stroke_width": 5, "background_stroke_color": BLACK, }, } def __init__(self, **kwargs): super().__init__(**kwargs) icon = self.IconClass() icon.set_style(**self.icon_style) icon.match_width(self) icon.move_to(self.get_corner(DR), DOWN) self.add(icon) class Farmer(Librarian): CONFIG = { "IconClass": FarmerIcon, "icon_style": { "background_stroke_width": 2, }, "fill_color": GREEN, } # Scenes class Test(Scene): def construct(self): icon = FarmerIcon() icon.scale(2) self.add(icon) # self.add(get_submobject_index_labels(icon)) # class FullFormulaIndices(Scene): # def construct(self): # formula = get_bayes_formula(expand_denominator=True) # formula.set_width(FRAME_WIDTH - 1) # self.add(formula) # self.add(get_submobject_index_labels(formula)) class IntroduceFormula(Scene): def construct(self): formula = get_bayes_formula() formula.save_state() formula.set_width(FRAME_WIDTH - 1) def get_formula_slice(*indices): return VGroup(*[formula[i] for i in indices]) H_label = formula.get_part_by_tex("{H}") E_label = formula.get_part_by_tex("{E}") hyp_label = OldTexText("Hypothesis") hyp_label.set_color(HYPOTHESIS_COLOR) hyp_label.next_to(H_label, UP, LARGE_BUFF) evid_label = OldTexText("Evidence") evid_label.set_color(EVIDENCE_COLOR1) evid_label.next_to(E_label, DOWN, LARGE_BUFF) hyp_arrow = Arrow(hyp_label.get_bottom(), H_label.get_top(), buff=SMALL_BUFF) evid_arrow = Arrow(evid_label.get_top(), E_label.get_bottom(), buff=SMALL_BUFF) self.add(formula[:6]) # self.add(get_submobject_index_labels(formula)) # return self.play( FadeIn(hyp_label, DOWN), GrowArrow(hyp_arrow), FadeIn(evid_label, UP), GrowArrow(evid_arrow), ) self.wait() # Prior self.play( ShowCreation(formula.get_part_by_tex("=")), TransformFromCopy( get_formula_slice(0, 1, 2, 5), get_formula_slice(8, 9, 10, 11), ), ) # Likelihood lhs_copy = formula[:6].copy() likelihood = formula[12:18] run_time = 1 self.play( lhs_copy.next_to, likelihood, UP, run_time=run_time, ) self.play( Swap(lhs_copy[2], lhs_copy[4]), run_time=run_time, ) self.play( lhs_copy.move_to, likelihood, run_time=run_time, ) # Evidence self.play( ShowCreation(formula.get_part_by_tex("\\over")), TransformFromCopy( get_formula_slice(0, 1, 4, 5), get_formula_slice(19, 20, 21, 22), ), ) self.wait() self.clear() self.play( formula.restore, formula.scale, 1.5, formula.to_edge, UP, FadeOut(VGroup( hyp_arrow, hyp_label, evid_arrow, evid_label, )) ) class StateGoal(PiCreatureScene, Scene): CONFIG = { "default_pi_creature_kwargs": { "color": BLUE_B, "height": 2, }, } def construct(self): # Zoom to later you = self.pi_creature line = NumberLine( x_min=-2, x_max=12, include_tip=True ) line.to_edge(DOWN, buff=1.5) line.to_edge(LEFT, buff=-0.5) you.next_to(line.n2p(0), UP) you_label = OldTexText("you") you_label.next_to(you, RIGHT, MED_LARGE_BUFF) you_arrow = Arrow(you_label.get_left(), you.get_right() + 0.5 * LEFT, buff=0.1) now_label = OldTexText("Now") later_label = OldTexText("Later") now_label.next_to(line.n2p(0), DOWN) later_label.next_to(line.n2p(10), DOWN) self.add(line, now_label) self.add(you) self.play( FadeIn(you_label, LEFT), GrowArrow(you_arrow), you.change, "pondering", ) self.wait() you_label.add(you_arrow) self.play( you.change, "horrified", you.look, DOWN, you.next_to, line.n2p(10), UP, MaintainPositionRelativeTo(you_label, you), FadeInFromPoint(later_label, now_label.get_center()), ) self.wait() # Add bubble bubble = you.get_bubble( height=4, width=6, ) bubble.set_fill(opacity=0) formula = get_bayes_formula() bubble.position_mobject_inside(formula) self.play( you.change, "confused", bubble, ShowCreation(bubble), ) self.play(FadeIn(formula)) self.play(you.change, "hooray", formula) self.wait(2) # Show examples icons = VGroup( SVGMobject(file_name="science"), SVGMobject(file_name="robot"), ) for icon in icons: icon.set_stroke(width=0) icon.set_fill(GREY) icon.set_sheen(1, UL) icon.set_height(1.5) icons[0].set_stroke(GREY, 3, background=True) gold = self.get_gold() icons.add(gold) icons.arrange(DOWN, buff=MED_LARGE_BUFF) icons.to_corner(UL) for icon in icons[:2]: self.play( Write(icon, run_time=2), you.change, "thinking", icon, ) self.play( Blink(you), FadeOut(VGroup( line, now_label, later_label, you_label, you_arrow )), ) self.play( FadeIn(gold, LEFT), you.change, "erm", gold, ) self.play(Blink(you)) # Brief Thompson description words = VGroup( OldTexText("1988").scale(1.5), OldTexText("Tommy Thompson\\\\and friends"), ) words.arrange(DOWN, buff=0.75) ship = ImageMobject("ss_central_america") ship.set_width(4) ship.move_to(gold, DL) ship_title = OldTexText("SS Central America") ship_title.next_to(ship, UP) words.next_to(ship, RIGHT) self.play( FadeIn(words[0], LEFT), you.change, "tease", words, FadeOut(icons[:2]), ) self.play(FadeIn(words[1], UP)) self.wait() self.add(ship, gold) self.play( FadeIn(ship), gold.scale, 0.2, gold.move_to, ship, ) self.play(FadeInFromDown(ship_title)) self.play(you.change, "thinking", ship) amount = OldTex("> \\$700{,}000{,}000") amount.scale(1.5) amount.next_to(ship, DOWN, MED_LARGE_BUFF) amount.to_edge(LEFT, buff=2) amount.set_color(YELLOW) gold_copy = gold.copy() self.play( gold_copy.scale, 3, gold_copy.next_to, amount, LEFT, FadeIn(amount), ) self.play(Blink(you)) self.wait() self.play(LaggedStartMap( FadeOutAndShift, Group(*words, ship_title, ship, gold, gold_copy, amount), )) # Levels of understanding # Turn bubble into level points level_points = VGroup(*[bubble.copy() for x in range(3)]) for n, point in enumerate(level_points): point.set_width(0.5) point.set_height(0.5, stretch=True) point.add(*[ point[-1].copy().scale(1.2**k) for k in range(1, n + 1) ]) point[:3].scale(1.2**n, about_point=point[3].get_center()) point.set_stroke(width=2) point.set_fill(opacity=0) level_points.arrange(DOWN, buff=LARGE_BUFF) title = OldTexText("Levels of understanding") title.scale(1.5) title.to_corner(UL) underline = Line() underline.match_width(title) underline.move_to(title, DOWN) title.add(underline) level_points.next_to(title, DOWN, buff=1.5) level_points.to_edge(LEFT) level_points.set_submobject_colors_by_gradient(GREEN, YELLOW, RED) self.remove(bubble) self.play( formula.to_corner, UR, FadeOut(you), *[ ReplacementTransform(bubble.copy(), point) for point in level_points ], ) self.play(Write(title, run_time=1)) self.wait() # Write level 1 level_labels = VGroup( OldTexText("What is it saying?"), OldTexText("Why is it true?"), OldTexText("When is it useful?"), ) for lp, ll in zip(level_points, level_labels): ll.scale(1.25) ll.match_color(lp) ll.next_to(lp, RIGHT) formula_parts = VGroup( formula.prior, formula.likelihood, formula.p_evidence, formula.posterior, ).copy() formula_parts.generate_target() formula_parts.target.scale(1.5) formula_parts.target.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) formula_parts.target.next_to(formula, DOWN, buff=LARGE_BUFF) formula_parts.target.shift(3 * LEFT) equal_signs = VGroup(*[ OldTexText("=").next_to(fp, RIGHT) for fp in formula_parts.target ]) kw = { "tex_to_color_map": { "hypothesis": HYPOTHESIS_COLOR, "evidence": EVIDENCE_COLOR1, }, "alignment": "", } meanings = VGroup( OldTexText("Probability a hypothesis is true\\\\(before any evidence)", **kw), OldTexText("Probability of seeing the evidence \\quad \\\\if the hypothesis is true", **kw), OldTexText("Probability of seeing the evidence", **kw), OldTexText("Probability a hypothesis is true\\\\given some evidence", **kw), ) for meaning, equals in zip(meanings, equal_signs): meaning.scale(0.5) meaning.next_to(equals, RIGHT) self.play( FadeIn(level_labels[0], lag_ratio=0.1), MoveToTarget(formula_parts), LaggedStartMap(FadeInFrom, equal_signs, lambda m: (m, RIGHT)), LaggedStartMap(FadeIn, meanings), ) self.wait() # Write level 2 diagram = BayesDiagram(0.35, 0.5, 0.2, height=2.5) diagram.next_to(formula, DOWN, aligned_edge=LEFT) braces = VGroup(*[ Brace(diagram.he_rect, vect, buff=SMALL_BUFF) for vect in [DOWN, LEFT] ]) formula_parts.generate_target() formula_parts.target[:2].scale(0.5) formula_parts.target[0].next_to(braces[0], DOWN, SMALL_BUFF) formula_parts.target[1].next_to(braces[1], LEFT, SMALL_BUFF) pe_picture = VGroup( diagram.he_rect.copy(), OldTex("+"), diagram.nhe_rect.copy() ) pe_picture.arrange(RIGHT, buff=SMALL_BUFF) pe_picture.next_to(equal_signs[2], RIGHT) phe_picture = VGroup( diagram.he_rect.copy(), Line().match_width(pe_picture), pe_picture.copy(), ) phe_picture.arrange(DOWN, buff=MED_SMALL_BUFF) phe_picture.next_to(equal_signs[3], RIGHT) pe_picture.scale(0.5, about_edge=LEFT) phe_picture.scale(0.3, about_edge=LEFT) self.play( FadeOut(meanings), FadeOut(equal_signs[:2]), MoveToTarget(formula_parts), FadeIn(diagram), LaggedStartMap(GrowFromCenter, braces), FadeIn(level_labels[1], lag_ratio=0.1), level_labels[0].set_opacity, 0.5, ) self.play( TransformFromCopy(diagram.he_rect, pe_picture[0]), TransformFromCopy(diagram.nhe_rect, pe_picture[2]), FadeIn(pe_picture[1]), ) self.play( TransformFromCopy(pe_picture, phe_picture[2]), TransformFromCopy(pe_picture[0], phe_picture[0]), ShowCreation(phe_picture[1]) ) self.wait() # Write level 3 steve = Steve(height=3) steve.to_edge(RIGHT, buff=2) arrow = Arrow(level_points.get_bottom(), level_points.get_top(), buff=0) arrow.shift(0.25 * LEFT) self.play( LaggedStartMap( FadeOutAndShift, VGroup( VGroup(diagram, braces, formula_parts[:2]), VGroup(formula_parts[2], equal_signs[2], pe_picture), VGroup(formula_parts[3], equal_signs[3], phe_picture), ), lambda m: (m, 3 * RIGHT), ), FadeIn(level_labels[2], lag_ratio=0.1), level_labels[1].set_opacity, 0.5, ) self.wait() self.play( GrowArrow(arrow), level_points.shift, 0.5 * RIGHT, level_labels.shift, 0.5 * RIGHT, level_labels.set_opacity, 1, ) self.wait() self.play(Write(steve, run_time=3)) self.wait() # Transition to next scene self.play( steve.to_corner, UR, Uncreate(arrow), LaggedStartMap( FadeOutAndShift, VGroup( title, formula, *level_points, *level_labels, ), lambda m: (m, DOWN), ), ) self.wait() def get_gold(self): gold = SVGMobject(file_name="gold_bars")[0] gold.set_stroke(width=0) gold.set_fill(GOLD) gold.set_sheen(0.5, UP) gold.flip(UP) gold_copy = gold.copy() gold_copy.shift(2 * OUT) rects = VGroup() for curve in CurvesAsSubmobjects(gold): p1 = curve.get_points()[0] p2 = curve.get_points()[-1] rect = Polygon(p1, p2, p2 + 2 * OUT, p1 + 2 * OUT) rect.match_style(gold) # rect.set_fill(GOLD) # rect.set_sheen(1, UL) rects.add(rect) rects.sort(lambda p: p[1]) gold.add(*rects) gold.add(gold_copy) # gold = rects gold.rotate(2 * DEGREES, UP) gold.rotate(2 * DEGREES, RIGHT) gold.set_shade_in_3d(True) gold.set_height(1.5) gold.set_stroke(BLACK, 0.5) return gold class DescriptionOfSteve(Scene): def construct(self): self.write_description() self.compare_probabilities() def write_description(self): steve = Steve(height=3) steve.to_corner(UR) description = self.get_description() description.to_edge(LEFT) description.align_to(steve, UP) mt_parts = VGroup( description.get_part_by_tex("meek"), description.get_part_by_tex("soul"), ) mt_parts.set_color(WHITE) self.add(steve) self.play( FadeIn(description), run_time=3, lag_ratio=0.01, rate_func=linear, ) self.wait(3) lines = VGroup(*[ Line(mob.get_corner(DL), mob.get_corner(DR), color=YELLOW) for mob in mt_parts ]) self.play( ShowCreation(lines), mt_parts.set_color, YELLOW, ) self.play(FadeOut(lines)) self.wait() def compare_probabilities(self): bar = ProbabilityBar( 0.5, width=10, include_braces=True, percentage_background_stroke_width=2, ) icons = VGroup( LibrarianIcon(), FarmerIcon(), ) for icon, text, half in zip(icons, ["Librarian", "Farmer"], bar.bars): icon.set_height(0.7) label = OldTexText(text) label.next_to(icon, DOWN, buff=SMALL_BUFF) label.set_color( interpolate_color(half.get_color(), WHITE, 0.5) ) icon.add(label) bar.add_icons(*icons) bar.move_to(1.75 * DOWN) bar.icons.set_opacity(0) q_marks = OldTex(*"???") q_marks.scale(1.5) q_marks.space_out_submobjects(1.5) q_marks.next_to(bar, DOWN) self.play(FadeIn(bar)) self.wait() self.play( bar.p_tracker.set_value, 0.9, bar.icons[0].set_opacity, 1, ) self.wait() self.play( bar.p_tracker.set_value, 0.1, bar.icons[1].set_opacity, 1, ) self.play( LaggedStartMap( FadeInFrom, q_marks, lambda m: (m, UP), run_time=2, ), ApplyMethod( bar.p_tracker.set_value, 0.7, run_time=8, ) ) for value in 0.3, 0.7: self.play( bar.p_tracker.set_value, 0.3, run_time=7, ) def get_description(self): return OldTexText( """ Steve is very shy and withdrawn,\\\\ invariably helpful but with very\\\\ little interest in people or in the\\\\ world of reality. A meek and tidy\\\\ soul, he has a need for order and\\\\ structure, and a passion for detail.\\\\ """, tex_to_color_map={ "shy and withdrawn": BLUE, "meek and tidy": YELLOW, "soul": YELLOW, }, alignment="", ) class IntroduceKahnemanAndTversky(DescriptionOfSteve): def construct(self): # Introduce K and T images = Group( ImageMobject("kahneman"), ImageMobject("tversky"), ) danny, amos = images images.set_height(3.5) images.arrange(DOWN, buff=0.5) images.to_edge(LEFT, buff=MED_LARGE_BUFF) names = VGroup( OldTexText("Daniel\\\\Kahneman", alignment=""), OldTexText("Amos\\\\Tversky", alignment=""), ) for name, image in zip(names, images): name.scale(1.25) name.next_to(image, RIGHT) image.name = name prize = ImageMobject("nobel_prize", height=1) prize.move_to(danny, UR) prize.shift(MED_SMALL_BUFF * UR) books = Group( ImageMobject("thinking_fast_and_slow"), ImageMobject("undoing_project"), ) books.set_height(5) books.arrange(RIGHT, buff=0.5) books.to_edge(RIGHT, buff=MED_LARGE_BUFF) self.play( FadeIn(danny, DOWN), FadeIn(danny.name, LEFT), ) self.play( FadeIn(amos, UP), FadeIn(amos.name, LEFT), ) self.wait() self.play(FadeInFromLarge(prize)) self.wait() for book in books: self.play(FadeIn(book, LEFT)) self.wait() # Show them thinking for image in images: image.generate_target() amos.target.to_corner(DL) danny.target.to_corner(DR) targets = Group(amos.target, danny.target) bubble = ThoughtBubble( width=7, height=4, ) bubble.next_to(targets, UP) new_stem = bubble[:-1].copy() new_stem.rotate(PI, UP, about_point=targets.get_top()) new_stem.shift(SMALL_BUFF * DR) bubble.add_to_back(*new_stem) bubble[-1].scale(1.2) bubble[-1].to_edge(UP, buff=0) bubble[:-1].shift(DOWN) bubble.set_fill(GREY_D, 1) randy = Randolph(color=BLUE_B) randy.set_height(1) randy.next_to(bubble[-1].get_center(), DL) randy.shift(LEFT) lil_bubble = ThoughtBubble(height=1.5, width=2) lil_bubble.next_to(randy, UR, buff=0) lil_bubble[:-1].rotate( PI, axis=UR, about_point=lil_bubble[:-1].get_corner(UL), ) lil_bubble.move_to(randy.get_top(), DL) for i, part in enumerate(lil_bubble[-2::-1]): part.rotate(90 * DEGREES) part.shift(0.05 * i * UR) lil_bubble[-1].scale(0.8) librarian = OldTexText("Librarian") librarian.set_color(BLUE) librarian.scale(0.5) librarian.move_to(lil_bubble[-1]) bar = ProbabilityBar(percentage_background_stroke_width=1) bar.add_icons( LibrarianIcon(height=1), FarmerIcon(height=1), ) bar.scale(0.5) bar.next_to(randy, RIGHT, buff=0.75) bar.update() self.play( LaggedStartMap(MoveToTarget, images), LaggedStartMap(FadeOutAndShiftDown, books), LaggedStartMap(FadeOut, Group(prize, *names)), ) self.play( DrawBorderThenFill(bubble), FadeIn( randy, UR, rate_func=squish_rate_func(smooth, 0.5, 1), run_time=2, ) ) self.play( DrawBorderThenFill(lil_bubble), randy.change, "pondering", ) self.play(Blink(randy)) self.play(Write(librarian)) self.add(bar, lil_bubble, librarian) self.play(FadeIn(bar)) self.play( bar.p_tracker.set_value, 1 / 6, randy.change, "thinking", bar, ) self.play(Blink(randy)) self.wait() # Zoom in description = self.get_description() description.scale(0.4) description.next_to(randy, UL) description.shift(1.25 * RIGHT + 0.75 * UP) description.set_color(WHITE) frame = self.camera_frame steve = Steve() steve.match_height(description) steve.align_to(bar, RIGHT) steve.align_to(description, UP) # cross = Cross(librarian) book_border = bar.icons[0].copy() farm_border = bar.icons[1].copy() for border in [book_border, farm_border]: border.set_fill(opacity=0) border.set_stroke(YELLOW, 1) seems_bookish = OldTexText("Seems\\\\bookish") seems_bookish.match_width(librarian) seems_bookish.scale(0.8) seems_bookish.move_to(librarian) self.play( frame.scale, 0.5, frame.move_to, bubble[-1], DOWN, frame.shift, 0.75 * LEFT, FadeOut(bubble), FadeOut(images), FadeOut(lil_bubble), FadeOut(librarian), FadeIn(description, lag_ratio=0.05), randy.change, "pondering", description, run_time=6, ) self.play(randy.change, "happy", description) self.play( description.get_part_by_tex("shy").set_color, BLUE, lag_ratio=0.1, ) self.play( description.get_part_by_tex("meek").set_color, YELLOW, description.get_part_by_tex("soul").set_color, YELLOW, lag_ratio=0.1, ) self.play( bar.p_tracker.set_value, 0.9, FadeIn(lil_bubble), Write(librarian), ) self.play(ShowCreationThenFadeOut(book_border)) self.play(Blink(randy)) self.play( FadeInFromDown(steve), randy.look_at, steve, ) self.play( randy.change, "tease", steve, FadeOut(librarian), FadeIn(seems_bookish), ) lil_bubble.add(seems_bookish) self.wait() self.play(Blink(randy)) self.play( LaggedStartMap( FadeOutAndShift, lil_bubble, lambda m: (m, LEFT), run_time=1, ), bar.p_tracker.set_value, 1 / 6, randy.change, "confused", bar, ) self.play( ShowCreationThenFadeOut(farm_border) ) self.wait() # Transition to next scene fh = frame.get_height() fw = frame.get_width() center = frame.get_center() right = (fw / FRAME_WIDTH) * RIGHT up = (fh / FRAME_HEIGHT) * UP left = -right down = -up book, farm = bar.icons.deepcopy() bar.clear_updaters() bar.icons.set_opacity(0) for mob in book, farm: mob.clear_updaters() mob.generate_target(use_deepcopy=True) mob.target.set_height(get_norm(up)) mob.target.move_to(center + down + 2 * left) farm.target.shift(4 * right) steve.generate_target() steve.target.match_width(book.target) steve.target.move_to(book.target, DOWN) steve.target.shift(3 * up) steve_copy = steve.target.copy() steve_copy.match_x(farm.target), self.play( TransformFromCopy(steve, steve_copy), LaggedStartMap(MoveToTarget, VGroup(steve, book, farm)), LaggedStartMap( FadeOutAndShift, description, lambda m: (m, LEFT) ), FadeOut(randy, LEFT), FadeOut(bar, LEFT), ) class CorrectViewOfFarmersAndLibrarians(Scene): def construct(self): # Match last scene steves = VGroup(Steve(), Steve()) book = LibrarianIcon() farm = FarmerIcon() icons = VGroup(book, farm) for mob in icons: mob.set_height(1) mob.move_to(DOWN + 2 * LEFT) farm.shift(4 * RIGHT) steves.match_width(book) steves.move_to(book, DOWN) steves.shift(3 * UP) steve1, steve2 = steves steve2.match_x(farm) self.add(steves, book, farm) # Add arrows arrows = VGroup(*[ Arrow(s.get_bottom(), m.get_top()) for s, m in zip(steves, icons) ]) words = VGroup( OldTexText("Stereotype"), OldTexText("Unexpected"), ) for arrow, word, vect in zip(arrows, words, [LEFT, RIGHT]): word.scale(1.5) word.next_to(arrow, vect) self.play( GrowArrow(arrow), FadeIn(word, UP), ) self.wait() # Show people proportions librarian = Librarian() farmer = Farmer() librarian.move_to(LEFT).to_edge(UP) farmer.move_to(RIGHT).to_edge(UP) farmer_ul = farmer.get_corner(UL) farmers = VGroup(farmer, *[farmer.copy() for x in range(19)]) farmers.arrange_in_grid(n_rows=4) farmers.move_to(farmer_ul, UL) farmer_outlines = farmers.copy() farmer_outlines.set_fill(opacity=0) farmer_outlines.set_stroke(YELLOW, 1) farmer_count = Integer(1) farmer_count.scale(2) farmer_count.set_color(GREEN) farmer_count.next_to(farmers, LEFT, buff=LARGE_BUFF) farmer_count.add_updater(lambda m: m.set_value(len(farmer_outlines))) for person, icon in zip([librarian, farmer], icons): person.save_state() person[:-1].set_opacity(0) person.scale( icon.get_height() / person[-1].get_height() ) person.move_to(icon, DR) self.remove(*icons) self.play( LaggedStartMap(FadeOut, VGroup(steves, arrows, words)), Restore(librarian), Restore(farmer), run_time=1, ) self.play( LaggedStartMap(FadeIn, farmers[1:]) ) self.wait() self.add(farmer_count) self.play( ShowIncreasingSubsets(farmer_outlines), int_func=np.ceil, rate_func=linear, run_time=2, ) self.play(FadeOut(farmer_outlines)) self.wait() # Show higher number of farmers farmers.save_state() farmers.generate_target() farmers.target.scale(0.5, about_edge=UL) new_farmers = VGroup(*it.chain(*[ farmers.target.copy().next_to( farmers.target, vect, buff=SMALL_BUFF, ) for vect in [RIGHT, DOWN] ])) new_farmers[-10:].align_to(new_farmers, RIGHT) new_farmers[-10:].align_to(new_farmers[-20], UP) farmer_count.clear_updaters() self.play( MoveToTarget(farmers), ShowIncreasingSubsets(new_farmers), ChangeDecimalToValue(farmer_count, 60), ) self.wait() self.play( FadeOut(new_farmers), Restore(farmers), ChangeDecimalToValue(farmer_count, 20), ) self.wait() # Organize into a representative sample farmers.generate_target() librarian.generate_target() group = VGroup(librarian.target, *farmers.target) self.arrange_bottom_row(group) l_brace = self.get_count_brace(VGroup(librarian.target)) f_brace = self.get_count_brace(farmers.target) self.play( MoveToTarget(librarian), MoveToTarget(farmers), ReplacementTransform(farmer_count, f_brace[-1]), GrowFromCenter(f_brace[:-1]), ) self.play(GrowFromCenter(l_brace)) self.wait() def get_count_brace(self, people): brace = Brace(people, UP, buff=SMALL_BUFF) count = Integer(len(people), edge_to_fix=DOWN) count.next_to(brace, UP, SMALL_BUFF) brace.add(count) brace.count = count return brace def arrange_bottom_row(self, group): group.arrange(RIGHT, buff=0.5) group.set_width(FRAME_WIDTH - 3) group.to_edge(DOWN) for person in group: person[-1].set_stroke(BLACK, 1, background=True) class ComplainAboutNotKnowingTheStats(TeacherStudentsScene): def construct(self): self.student_says( "Are people expected\\\\to know that?", index=2 ) self.play_student_changes( "sassy", "sassy", ) self.play(self.teacher.change, "hesitant") self.look_at(self.screen) self.wait(3) self.teacher_says( "No, but did you\\\\think to estimate it?", bubble_config={"width": 4.5, "height": 3.5}, ) self.play_all_student_changes("guilty") self.wait(2) self.play_all_student_changes("pondering") self.wait(3) class SpoilerAlert(Scene): def construct(self): sa_words = OldTexText("Spoiler Alert") sa_words.scale(2) sa_words.to_edge(UP) sa_words.set_color(RED) alert = Triangle(start_angle=90 * DEGREES) alert.set_stroke(RED, 8) alert.set_height(sa_words.get_height()) alert.round_corners(0.1) bang = OldTexText("!") bang.set_color(RED) bang.scale(1.5) bang.move_to(alert) alert.add(bang) alert.next_to(sa_words, LEFT) sa_words.add(alert.copy()) alert.next_to(sa_words, RIGHT) sa_words.add(alert) formula = get_bayes_formula() formula_words = OldTexText("This is secretly ") formula_words.scale(1.5) formula_group = VGroup(formula_words, formula) formula_group.arrange(DOWN, buff=MED_LARGE_BUFF) formula_group.next_to(sa_words, DOWN, LARGE_BUFF) self.add(sa_words) self.wait() self.play(FadeIn(formula_group, UP)) self.wait() class ReasonByRepresentativeSample(CorrectViewOfFarmersAndLibrarians): CONFIG = { "ignore_icons": False, # "ignore_icons": True, } def construct(self): # Match previous scene librarians = VGroup(Librarian()) farmers = VGroup(*[Farmer() for x in range(20)]) everyone = VGroup(*librarians, *farmers) self.arrange_bottom_row(everyone) self.add(everyone) if self.ignore_icons: for person in everyone: person.submobjects.pop() l_brace = self.get_count_brace(librarians) f_brace = self.get_count_brace(farmers) braces = VGroup(l_brace, f_brace) for brace in braces: brace.count.set_stroke(BLACK, 3, background=True) brace.count.brace = brace brace.remove(brace.count) brace.count_tracker = ValueTracker(brace.count.get_value()) brace.count.add_updater( lambda c: c.set_value( c.brace.count_tracker.get_value(), ).next_to(c.brace, UP, SMALL_BUFF) ) self.add(brace, brace.count) # Multiply by 10 new_people = VGroup() for group in [librarians, farmers]: new_rows = VGroup(*[group.copy() for x in range(9)]) new_rows.arrange(UP, buff=SMALL_BUFF) new_rows.next_to(group, UP, SMALL_BUFF) new_people.add(new_rows) new_librarians, new_farmers = new_people self.play( *[ FadeIn(new_rows, lag_ratio=0.1) for new_rows in new_people ], *[ ApplyMethod(brace.next_to, new_rows, UP, {"buff": SMALL_BUFF}) for brace, new_rows in zip(braces, new_people) ], *[ ApplyMethod( brace.count_tracker.set_value, 10 * brace.count_tracker.get_value(), ) for brace in braces ], ) farmers = VGroup(farmers, *new_farmers) librarians = VGroup(librarians, *new_librarians) everyone = VGroup(farmers, librarians) # Add background rectangles big_rect = SurroundingRectangle( everyone, buff=0.05, stroke_width=1, stroke_color=WHITE, fill_opacity=1, fill_color=GREY_E, ) left_rect = big_rect.copy() prior = 1 / 21 left_rect.stretch(prior, 0, about_edge=LEFT) right_rect = big_rect.copy() right_rect.stretch(1 - prior, 0, about_edge=RIGHT) dl_rect = left_rect.copy() ul_rect = left_rect.copy() dl_rect.stretch(0.4, 1, about_edge=DOWN) ul_rect.stretch(0.6, 1, about_edge=UP) dr_rect = right_rect.copy() ur_rect = right_rect.copy() dr_rect.stretch(0.1, 1, about_edge=DOWN) ur_rect.stretch(0.9, 1, about_edge=UP) colors = [ interpolate_color(color, BLACK, 0.5) for color in [EVIDENCE_COLOR1, EVIDENCE_COLOR2] ] for rect, color in zip([dl_rect, dr_rect], colors): rect.set_fill(color) all_rects = VGroup( left_rect, right_rect, dl_rect, ul_rect, dr_rect, ur_rect, ) all_rects.set_opacity(0) self.add(all_rects, everyone) self.play( left_rect.set_opacity, 1, right_rect.set_opacity, 1, ) self.wait() # 40% of librarians and 10% of farmers for rect, vect in zip([dl_rect, dr_rect], [LEFT, RIGHT]): rect.set_opacity(1) rect.save_state() rect.brace = Brace(rect, vect, buff=SMALL_BUFF) rect.brace.save_state() rect.number = Integer(0, unit="\\%") rect.number.scale(0.75) rect.number.next_to(rect.brace, vect, SMALL_BUFF) rect.number.brace = rect.brace rect.number.vect = vect rect.number.add_updater( lambda d: d.set_value(100 * d.brace.get_height() / big_rect.get_height()) ) rect.number.add_updater(lambda d: d.next_to(d.brace, d.vect, SMALL_BUFF)) for mob in [rect, rect.brace]: mob.stretch(0, 1, about_edge=DOWN) for rect, to_fade in [(dl_rect, librarians[4:]), (dr_rect, farmers[1:])]: self.add(rect.brace, rect.number) self.play( Restore(rect), Restore(rect.brace), to_fade.set_opacity, 0.1, ) self.wait() # Emphasize restricted set highlighted_librarians = librarians[:4].copy() highlighted_farmers = farmers[0].copy() for highlights in [highlighted_librarians, highlighted_farmers]: highlights.set_color(YELLOW) self.add(braces, *[b.count for b in braces]) self.play( l_brace.next_to, librarians[:4], UP, SMALL_BUFF, l_brace.count_tracker.set_value, 4, ShowIncreasingSubsets(highlighted_librarians) ) self.play(FadeOut(highlighted_librarians)) self.play( f_brace.next_to, farmers[:1], UP, SMALL_BUFF, f_brace.count_tracker.set_value, 20, ShowIncreasingSubsets(highlighted_farmers), run_time=2, ) self.play(FadeOut(highlighted_farmers)) self.wait() # Write answer equation = OldTex( "P\\left(", "\\text{Librarian }", "\\text{given }", "\\text{description}", "\\right)", "=", "{4", "\\over", " 4", "+", "20}", "\\approx", "16.7\\%", ) equation.set_color_by_tex_to_color_map({ "Librarian": HYPOTHESIS_COLOR, "description": EVIDENCE_COLOR1, }) equation.set_width(FRAME_WIDTH - 2) equation.to_edge(UP) equation_rect = BackgroundRectangle(equation, buff=MED_SMALL_BUFF) equation_rect.set_fill(opacity=1) equation_rect.set_stroke(WHITE, width=1, opacity=1) self.play( FadeIn(equation_rect), FadeInFromDown(equation[:6]) ) self.wait() self.play( TransformFromCopy( l_brace.count, equation.get_parts_by_tex("4")[0], ), Write(equation.get_part_by_tex("\\over")), ) self.play( Write(equation.get_part_by_tex("+")), TransformFromCopy( f_brace.count, equation.get_part_by_tex("20"), ), TransformFromCopy( l_brace.count, equation.get_parts_by_tex("4")[1], ), ) self.wait() self.play(FadeIn(equation[-2:])) self.wait() # Compare raw likelihoods axes = Axes( x_min=0, x_max=10, y_min=0, y_max=100, y_axis_config={ "unit_size": 0.07, "tick_frequency": 10, }, axis_config={ "include_tip": False, }, ) axes.x_axis.tick_marks.set_opacity(0) axes.y_axis.add_numbers( *range(20, 120, 20), unit="\\%" ) axes.center().to_edge(DOWN) title = OldTexText("Likelihood of fitting the description") title.scale(1.25) title.to_edge(UP) title.shift(RIGHT) axes.add(title) lines = VGroup( Line(axes.c2p(3, 0), axes.c2p(3, 40)), Line(axes.c2p(7, 0), axes.c2p(7, 10)), ) rects = VGroup(*[Rectangle() for x in range(2)]) rects.set_fill(EVIDENCE_COLOR1, 1) rects[1].set_fill(GREEN) rects.set_stroke(WHITE, 1) icons = VGroup(LibrarianIcon(), FarmerIcon()) for rect, line, icon in zip(rects, lines, icons): rect.replace(line, dim_to_match=1) rect.set_width(1, stretch=True) icon.set_width(1) icon.next_to(rect, UP) y = axes.y_axis.p2n(rect.get_top()) y_point = axes.y_axis.n2p(y) rect.line = DashedLine(y_point, rect.get_corner(UL)) pre_rects = VGroup() for r in dl_rect, dr_rect: r_copy = r.deepcopy() pre_rects.add(r_copy) people_copy = VGroup(librarians[:4], farmers[:1]).copy() everything = self.get_mobjects() self.play( *[FadeOut(mob) for mob in everything], FadeIn(axes), FadeIn(icons), *[ TransformFromCopy(pr, r) for pr, r in zip(pre_rects, rects) ], FadeOut(people_copy), ) self.play(*[ ShowCreation(rect.line) for rect in rects ]) self.wait() self.play( FadeOut(axes), FadeOut(rects[0].line), FadeOut(rects[1].line), FadeOut(icons), *[ ReplacementTransform(r, pr) for pr, r in zip(pre_rects, rects) ], # FadeOut(fsfr), *[FadeIn(mob) for mob in everything], ) self.remove(*pre_rects) self.wait() # Emphasize prior belief prior_equation = OldTex( "P\\left(", "\\text{Librarian}", "\\right)", "=", "{1", "\\over", "21}", "\\approx", "4.8\\%", ) prior_equation.set_color_by_tex_to_color_map({ "Librarian": HYPOTHESIS_COLOR, }) prior_equation.match_height(equation) prior_rect = BackgroundRectangle(prior_equation, buff=MED_SMALL_BUFF) prior_rect.match_style(equation_rect) group = VGroup(prior_equation, prior_rect) group.align_to(equation_rect, UP) group.shift( ( equation.get_part_by_tex("\\over").get_x() - prior_equation.get_part_by_tex("\\over").get_x() ) * RIGHT ) prior_label = OldTexText("Prior belief") prior_label.scale(1.5) prior_label.next_to(prior_rect, LEFT, buff=1.5) prior_label.to_edge(UP, buff=0.25) prior_label.set_stroke(BLACK, 5, background=True) prior_arrow = Arrow( prior_label.get_right(), prior_equation.get_left(), buff=SMALL_BUFF, ) self.play( VGroup(equation_rect, equation).shift, prior_rect.get_height() * DOWN, FadeIn(prior_rect), FadeIn(prior_equation), FadeIn(prior_label, RIGHT), GrowArrow(prior_arrow), ) self.wait() class NewEvidenceUpdatesPriorBeliefs(DescriptionOfSteve): def construct(self): # Determining belief in a vacuum description = self.get_description() rect = SurroundingRectangle(description) rect.set_stroke(WHITE, 2) rect.set_fill(BLACK, 0.9) evid = VGroup(rect, description) evid.set_height(2) librarian = Librarian() librarian.set_height(2) arrow = Arrow(LEFT, RIGHT) arrow.set_stroke(WHITE, 5) group = VGroup(evid, arrow, librarian) group.arrange(RIGHT, buff=LARGE_BUFF) cross = Cross(VGroup(group)) cross.set_stroke(RED, 12) cross.scale(1.2) self.add(evid) self.play( GrowArrow(arrow), FadeIn(librarian, LEFT) ) self.play(ShowCreation(cross)) self.wait() # icons = VGroup(LibrarianIcon(), FarmerIcon()) for icon in icons: icon.set_height(0.5) kw = { "include_braces": True, "width": 11, "height": 0.75, } top_bar = ProbabilityBar(p=1 / 21, **kw) low_bar = ProbabilityBar(p=1 / 21, brace_direction=DOWN, **kw) bars = VGroup(top_bar, low_bar) for bar in bars: bar.percentages[1].add_updater(lambda m: m.set_opacity(0)) bar.add_icons(*icons.copy()) bar.suspend_updating() new_arrow = Arrow(1.5 * UP, 1.5 * DOWN) new_arrow.set_stroke(WHITE, 5) top_bar.next_to(new_arrow, UP) low_bar.next_to(new_arrow, DOWN) self.add(arrow, evid, cross) self.play( FadeOut(cross), Transform(arrow, new_arrow), evid.scale, 0.6, evid.move_to, new_arrow, ReplacementTransform(librarian, low_bar.icons[0]), FadeIn(bars) ) self.play(low_bar.p_tracker.set_value, 1 / 6) self.wait() class HeartOfBayesTheorem(Scene): def construct(self): title = OldTexText("Heart of Bayes' theorem") title.scale(1.5) title.add(Underline(title)) title.to_edge(UP) # Bayes diagrams # prior_tracker = ValueTracker(0.1) # likelihood_tracker = ValueTracker(0.4) # antilikelihood_tracker = ValueTracker(0.1) diagram = self.get_diagram( prior=0.1, likelihood=0.4, antilikelihood=0.1, # prior_tracker.get_value(), # likelihood_tracker.get_value(), # antilikelihood_tracker.get_value(), ) diagram.nh_rect.set_fill(GREEN_E) diagram.hypothesis_split.set_opacity(1) diagram.evidence_split.set_opacity(0) restricted_diagram = self.get_restricted_diagram(diagram) diagram_copy = diagram.copy() diagram_copy.move_to(restricted_diagram) diagrams = VGroup(diagram, restricted_diagram) label1 = OldTexText("All possibilities") label2 = OldTexText( "All possibilities\\\\", "fitting the evidence", tex_to_color_map={"evidence": EVIDENCE_COLOR1}, ) labels = VGroup(label1, label2) labels.scale(diagram.get_width() / label1.get_width()) for l, d in zip(labels, diagrams): l.next_to(d, UP) label2.save_state() label2[0].move_to(label2, DOWN) label2[1:].shift(0.25 * UP) label2[1:].set_opacity(0) # Final fraction written geometrically fraction = always_redraw( lambda: self.get_geometric_fraction(restricted_diagram) ) frac_box = always_redraw(lambda: DashedVMobject( SurroundingRectangle( fraction, buff=MED_SMALL_BUFF, stroke_width=2, stroke_color=WHITE, ), num_dashes=100, )) prob = OldTex( "P\\left(", "{\\text{Librarian }", "\\text{given}", "\\over", "\\text{the evidence}}", "\\right)" ) prob.set_color_by_tex("Librarian", HYPOTHESIS_COLOR) prob.set_color_by_tex("evidence", EVIDENCE_COLOR1) prob.get_part_by_tex("\\over").set_opacity(0) prob.match_width(frac_box) prob.next_to(frac_box, UP) updaters = VGroup( diagram, restricted_diagram, fraction, frac_box ) updaters.suspend_updating() self.play( FadeIn(diagram), FadeInFromDown(label1), ) self.play( TransformFromCopy(diagram, diagram_copy), TransformFromCopy(label1[0], label2[0]), ) self.play( Restore(label2), ReplacementTransform(diagram_copy, restricted_diagram) ) self.wait() self.play( TransformFromCopy( restricted_diagram.he_rect, fraction[0], ), TransformFromCopy( restricted_diagram.he_rect, fraction[2][0], ), TransformFromCopy( restricted_diagram.nhe_rect, fraction[2][2], ), ShowCreation(fraction[1]), Write(fraction[2][1]), ) self.add(fraction) self.play( ShowCreation(frac_box), FadeIn(prob) ) self.wait() self.play(Write(title, run_time=1)) self.wait() # Mess with some numbers updaters.resume_updating() self.play(*[ ApplyMethod(d.set_prior, 0.4, run_time=2) for d in diagrams ]) self.play(*[ ApplyMethod(d.set_likelihood, 0.3, run_time=2) for d in diagrams ]) self.play(*[ ApplyMethod(d.set_antilikelihood, 0.6, run_time=2) for d in diagrams ]) # self.play(prior_tracker.set_value, 0.4, run_time=2) # self.play(antilikelihood_tracker.set_value, 0.3, run_time=2) # self.play(likelihood_tracker.set_value, 0.6, run_time=2) self.wait() updaters.suspend_updating() # Ask about a formula words = OldTexText("Write this more\\\\mathematically") words.scale(1.25) words.set_color(RED) words.to_corner(UR) arrow = Arrow(words.get_bottom(), frac_box.get_top(), buff=SMALL_BUFF) arrow.match_color(words) arrow.set_stroke(width=5) self.play( FadeIn(words, DOWN), GrowArrow(arrow), FadeOut(prob), title.to_edge, LEFT ) self.wait() def get_diagram(self, prior, likelihood, antilikelihood): diagram = BayesDiagram( prior, likelihood, antilikelihood, not_evidence_color1=GREY, not_evidence_color2=GREEN_E, ) diagram.set_height(3) diagram.move_to(5 * LEFT + DOWN) diagram.add_brace_attrs() braces = VGroup(diagram.h_brace, diagram.nh_brace) diagram.add(*braces) icons = VGroup(LibrarianIcon(), FarmerIcon()) icons[0].set_color(YELLOW_D) for icon, brace in zip(icons, braces): icon.set_height(0.5) icon.brace = brace icon.add_updater(lambda m: m.next_to(m.brace, DOWN, SMALL_BUFF)) diagram.add(icon) return diagram def get_restricted_diagram(self, diagram): restricted_diagram = diagram.deepcopy() restricted_diagram.set_x(0) restricted_diagram.hypothesis_split.set_opacity(0) restricted_diagram.evidence_split.set_opacity(1) restricted_diagram.hne_rect.set_opacity(0.1) restricted_diagram.nhne_rect.set_opacity(0.1) return restricted_diagram def get_geometric_fraction(self, diagram): fraction = VGroup( diagram.he_rect.copy(), Line(LEFT, RIGHT), VGroup( diagram.he_rect.copy(), OldTex("+"), diagram.nhe_rect.copy(), ).arrange(RIGHT, buff=SMALL_BUFF) ) fraction.arrange(DOWN) fraction[1].match_width(fraction) fraction.to_edge(RIGHT) fraction.align_to(diagram.square, UP) return fraction class WhenDoesBayesApply(DescriptionOfSteve): def construct(self): title = OldTexText("When to use Bayes' rule") title.add(Underline(title, buff=-SMALL_BUFF)) title.scale(1.5) title.to_edge(UP) self.add(title) # Words all_words = VGroup( OldTexText("You have a\\\\", "hypothesis"), OldTexText("You've observed\\\\some ", "evidence"), OldTex( "\\text{You want}\\\\", "P", "(", "H", "|", "E", ")\\\\", "P", "\\left(", "\\substack{""\\text{Hypothesis} \\\\", "\\textbf{given} \\\\", "\\, \\text{the evidence} \\,}", "\\right)", ), ) for words in all_words: words.set_color_by_tex_to_color_map({ "hypothesis": HYPOTHESIS_COLOR, "H": HYPOTHESIS_COLOR, "evidence": EVIDENCE_COLOR1, "E": EVIDENCE_COLOR1, }) goal = all_words[2] prob = goal[1:7] big_prob = goal[7:] for mob in [prob, big_prob]: mob.match_x(goal[0]) prob.shift(0.2 * DOWN) big_prob.shift(0.4 * DOWN) VGroup(big_prob[1], big_prob[-1]).stretch(1.2, 1) all_words.arrange(RIGHT, buff=2, aligned_edge=UP) all_words.next_to(title, DOWN, buff=MED_LARGE_BUFF) big_prob.save_state() big_prob.move_to(prob, UP) # Icons hypothesis_icon = self.get_hypothesis_icon() evidence_icon = self.get_evidence_icon() hypothesis_icon.next_to(all_words[0], DOWN, LARGE_BUFF) evidence_icon.next_to(all_words[1], DOWN, LARGE_BUFF) # Show icons self.play(FadeInFromDown(all_words[0])) self.play( LaggedStart( FadeIn(hypothesis_icon[0], DOWN), Write(hypothesis_icon[1]), FadeIn(hypothesis_icon[2], UP), run_time=1, ) ) self.wait() self.play(FadeInFromDown(all_words[1])) self.play( FadeIn(evidence_icon), lag_ratio=0.1, run_time=2, ) self.wait() # More compact probability self.play(FadeInFromDown(VGroup(goal[0], big_prob))) self.wait() self.play( Restore(big_prob), *[ TransformFromCopy(big_prob[i], prob[i]) for i in [0, 1, -1] ] ) self.play(LaggedStart(*[ TransformFromCopy(big_prob[i][j], prob[i]) for i, j in [(2, 0), (3, 1), (4, 3)] ])) self.wait() # Highlight "given" rects = VGroup(*[ SurroundingRectangle( goal.get_part_by_tex(tex), buff=0.05, stroke_width=2, stroke_color=RED, ) for tex in ("|", "given") ]) self.play(ShowCreation(rects)) self.play(Transform(rects[0].copy(), rects[1], remover=True)) self.play(FadeOut(rects)) self.wait() self.remove(prob) everything = Group(*self.get_mobjects()) self.play( LaggedStartMap(FadeOut, everything, run_time=2), prob.copy().to_corner, UR, ) def get_hypothesis_icon(self): group = VGroup( Steve().set_height(1.5), OldTex("\\updownarrow"), LibrarianIcon().set_color(YELLOW_D) ) group.arrange(DOWN) return group def get_evidence_icon(self): result = self.get_description() result.scale(0.5) result.set_color_by_tex("meek", EVIDENCE_COLOR1) result.set_color_by_tex("soul", EVIDENCE_COLOR1) rect = SurroundingRectangle(result) rect.set_stroke(WHITE, 2) result.add(rect) return result class CreateFormulaFromDiagram(Scene): CONFIG = { "tex_to_color_map": { "P": WHITE, "H": HYPOTHESIS_COLOR, "E": EVIDENCE_COLOR1, "\\neg": RED, }, "bayes_diagram_config": { "prior": 1 / 21, "likelihood": 0.4, "antilikelihood": 0.1, "not_evidence_color1": GREY, "not_evidence_color2": GREY_D, "prior_rect_direction": UP, }, } def construct(self): t2c = self.tex_to_color_map # Add posterior posterior = OldTex("P(H|E)", tex_to_color_map=t2c) posterior.to_corner(UR) posterior_words = OldTexText("Goal: ") posterior_words.next_to(posterior, LEFT, aligned_edge=UP) self.add(posterior) self.add(posterior_words) # Show prior diagram = self.get_diagram() prior_label = OldTex("P(H)", tex_to_color_map=t2c) prior_label.add_updater( lambda m: m.next_to(diagram.h_brace, UP, SMALL_BUFF) ) prior_example = OldTex("= 1 / 21") prior_example.add_updater( lambda m: m.next_to(prior_label, RIGHT).shift(0.03 * UP) ) # example_words = OldTexText("In our example") # example_words.next_to(prior_example[0][1:], UP, buff=SMALL_BUFF, aligned_edge=LEFT) # prior_example.add(example_words) prior_arrow = Vector(0.7 * RIGHT) prior_arrow.next_to(prior_label, LEFT, SMALL_BUFF) prior_word = OldTexText("``Prior''") prior_word.next_to(prior_arrow, LEFT, SMALL_BUFF) prior_word.align_to(prior_label[0], DOWN) prior_word.set_color(HYPOTHESIS_COLOR) self.add(diagram) self.play(ShowIncreasingSubsets(diagram.people, run_time=2)) self.wait() self.play( diagram.hypothesis_split.set_opacity, 1, FadeIn(diagram.h_brace), FadeInFromDown(prior_label), ) self.wait() self.play(FadeIn(prior_example)) self.play( LaggedStartMap( Indicate, diagram.people[::10], color=BLUE, ) ) self.wait() self.play( FadeIn(prior_word, RIGHT), GrowArrow(prior_arrow) ) self.wait() prior_group = VGroup( prior_word, prior_arrow, prior_label, prior_example, diagram.h_brace, ) # First likelihood split like_example = OldTex("= 0.4") like_example.add_updater( lambda m: m.next_to(diagram.he_brace, LEFT) ) like_example.update() like_label = OldTex("P(E|H)", tex_to_color_map=t2c) like_label.add_updater( lambda m: m.next_to(like_example, LEFT) ) like_label.update() like_word = OldTexText("``Likelihood''") like_word.next_to(like_label, UP, buff=LARGE_BUFF, aligned_edge=LEFT) like_arrow = Arrow( like_word.get_bottom(), like_label.get_top(), buff=0.2, ) limit_arrow = Vector(0.5 * UP) limit_arrow.next_to(like_label.get_part_by_tex("|"), UP, SMALL_BUFF) limit_arrow.set_stroke(WHITE, 4) limit_word = OldTexText("Limit\\\\your\\\\view") limit_word.next_to(limit_arrow, UP) hne_people = diagram.people[:6] he_people = diagram.people[6:10] nhe_people = diagram.people[19::10] nhne_people = diagram.people[10:] nhne_people.remove(*nhe_people) for group in [hne_people, nhne_people]: group.generate_target() group.target.set_opacity(0.25) group.target.set_stroke(BLACK, 0, background=True) self.play( diagram.he_rect.set_opacity, 1, diagram.hne_rect.set_opacity, 1, MoveToTarget(hne_people), GrowFromCenter(diagram.he_brace), FadeIn(like_label, RIGHT), FadeIn(like_example, RIGHT), ) self.wait() self.play( ShowCreationThenFadeAround( like_label.get_part_by_tex("E"), surrounding_rectangle_config={ "color": EVIDENCE_COLOR1 } ), ) self.play(WiggleOutThenIn(like_label.get_part_by_tex("|"))) self.play( ShowCreationThenFadeAround( like_label.get_part_by_tex("H") ), ) self.wait() self.play( diagram.people[10:].set_opacity, 0.2, diagram.nh_rect.set_opacity, 0.2, FadeIn(limit_word, DOWN), GrowArrow(limit_arrow), rate_func=there_and_back_with_pause, run_time=6, ) self.wait() self.play( Write(like_word, run_time=1), GrowArrow(like_arrow), ) self.wait() # Show anti-likelihood anti_label = OldTex("P(E| \\neg H)", tex_to_color_map=t2c) anti_label.add_updater( lambda m: m.next_to(diagram.nhe_brace, RIGHT) ) anti_example = OldTex("= 0.1") anti_example.add_updater( lambda m: m.next_to(anti_label, RIGHT).align_to(anti_label[0], DOWN) ) neg_sym = anti_label.get_part_by_tex("\\neg").copy() neg_sym.generate_target() neg_sym.target.scale(2.5) not_word = OldTexText("means ", "``not''") not_word[1].set_color(RED) neg_group = VGroup(neg_sym.target, not_word) neg_group.arrange(RIGHT) neg_group.next_to(anti_label, UP, LARGE_BUFF) neg_group.to_edge(RIGHT, buff=MED_SMALL_BUFF) diagram.nhe_rect.set_opacity(1) diagram.nhe_rect.save_state() diagram.nhe_rect.become(diagram.nh_rect) self.play( Restore(diagram.nhe_rect), GrowFromCenter(diagram.nhe_brace), MoveToTarget(nhne_people), FadeIn(anti_label, LEFT), FadeIn(anti_example, LEFT), ) diagram.nhne_rect.set_opacity(1) self.wait() self.play( ShowCreationThenFadeAround( anti_label[2], surrounding_rectangle_config={"color": EVIDENCE_COLOR1}, ) ) self.play( ShowCreationThenFadeAround( anti_label[4:6], surrounding_rectangle_config={"color": RED}, ) ) self.wait() self.play( MoveToTarget(neg_sym), FadeIn(not_word) ) self.wait() self.play( FadeOut(not_word), Transform(neg_sym, anti_label.get_part_by_tex("\\neg")) ) self.remove(neg_sym) # Recall final answer, geometrically he_group = VGroup(diagram.he_rect, he_people) nhe_group = VGroup(diagram.nhe_rect, nhe_people) denom = VGroup( he_group.copy(), OldTex("+"), nhe_group.copy(), ) denom.arrange(RIGHT) answer = VGroup( he_group.copy(), Underline(denom, stroke_width=2), denom, ) answer.arrange(DOWN) answer.scale(0.5) answer.to_edge(UP, MED_SMALL_BUFF) answer.shift(LEFT) equals = OldTex("=") posterior.generate_target() post_group = VGroup(posterior.target, equals, answer) post_group.arrange(RIGHT) post_group.to_corner(UL) post_word = OldTexText("``Posterior''") post_word.set_color(YELLOW) post_word.to_corner(UL, buff=MED_SMALL_BUFF) post_arrow = Arrow( post_word.get_bottom(), posterior.target[1].get_top(), buff=0.2, ) post_arrow.set_stroke(WHITE, 5) dividing_line = DashedLine(ORIGIN, FRAME_WIDTH * RIGHT) dividing_line.set_stroke(WHITE, 1) dividing_line.next_to(answer, DOWN) dividing_line.set_x(0) diagram.add( diagram.h_brace, diagram.he_brace, diagram.nhe_brace, ) diagram.generate_target(use_deepcopy=True) diagram.target.scale(0.5, about_edge=DL) diagram.target.refresh_braces() like_group = VGroup(like_word, like_arrow) like_vect = like_group.get_center() - like_label.get_center() self.play( ShowCreation(dividing_line), MoveToTarget(diagram), MaintainPositionRelativeTo(like_group, like_label), MaintainPositionRelativeTo( VGroup(prior_word, prior_arrow), prior_label, ), MoveToTarget(posterior), ReplacementTransform(posterior_words, equals), ) like_group.move_to(like_label.get_center() + like_vect) self.wait() self.play(TransformFromCopy(he_group, answer[0])) self.play(ShowCreation(answer[1])) self.play(LaggedStart( TransformFromCopy(he_group, answer[2][0]), GrowFromCenter(answer[2][1]), TransformFromCopy(nhe_group, answer[2][2]), )) self.wait() # Write final answer, as a formula formula = OldTex( "=", "{P(H) P(E | H)", "\\over", "P(H) P(E | H) + P(\\neg H) P(E | \\neg H)}", tex_to_color_map=t2c ) formula.scale(0.9) formula.next_to(answer, RIGHT) ph = formula[2:6] peh = formula[6:12] over = formula.get_part_by_tex("\\over") ph2 = formula[13:17] peh2 = formula[17:23] pnh = formula[23:28] penh = formula[28:] parts = VGroup(ph, peh, ph2, peh2, pnh, penh) parts.save_state() np1 = OldTex("(\\# I )")[0] person = Person() person.replace(np1[2], dim_to_match=1) person.scale(1.5) np1.submobjects[2] = person np1.match_height(ph) np1.next_to(ph, LEFT, SMALL_BUFF) VGroup(np1, ph, peh).match_x(over) np2 = np1.copy() np2.next_to(ph2, LEFT, SMALL_BUFF) VGroup(np2, ph2, peh2).match_width( VGroup(ph2, peh2), about_edge=RIGHT ) np3 = np1.copy() np3.next_to(pnh, LEFT, SMALL_BUFF) VGroup(np3, pnh, penh).match_width( VGroup(pnh, penh), about_edge=RIGHT ) nps = VGroup(np1, np2, np3) crosses = VGroup(*[Cross(np)[0] for np in nps]) top_brace = Brace(np1, UP, buff=SMALL_BUFF) top_count = Integer(210) top_count.add_updater(lambda m: m.next_to(top_brace, UP, SMALL_BUFF)) low_brace = Brace(np3, DOWN, buff=SMALL_BUFF) low_count = Integer(210) low_count.add_updater(lambda m: m.next_to(low_brace, DOWN, SMALL_BUFF)) h_rect = Rectangle( # Highlighting rectangle stroke_color=YELLOW, stroke_width=3, fill_color=YELLOW, fill_opacity=0.25, ) h_rect.replace(diagram.square, stretch=True) s_rect = SurroundingRectangle(answer[0]) diagram.refresh_braces() nh_group = VGroup( diagram.nh_brace, OldTex("P(\\neg H)", tex_to_color_map=t2c), OldTex("= 20 / 21"), ) nh_group[1].next_to(nh_group[0], UP, SMALL_BUFF) nh_group[2].next_to(nh_group[1], RIGHT, SMALL_BUFF) self.play( Write(formula.get_part_by_tex("=")), Write(formula.get_part_by_tex("\\over")), run_time=1 ) self.play(ShowCreation(s_rect)) self.wait() self.play( FadeIn(np1), FadeIn(top_brace), FadeIn(top_count), ) self.wait() self.play(h_rect.replace, diagram.h_rect, {"stretch": True}) self.play( TransformFromCopy(prior_label, ph), top_brace.become, Brace(VGroup(np1, ph), UP, buff=SMALL_BUFF), ChangeDecimalToValue(top_count, 10), ) self.wait() self.play(h_rect.replace, diagram.he_rect, {"stretch": True}) self.play( TransformFromCopy(like_label, peh), top_brace.become, Brace(VGroup(np1, peh), UP, buff=SMALL_BUFF), ChangeDecimalToValue(top_count, 4) ) self.wait() self.play( s_rect.move_to, answer[2][0], TransformFromCopy(np1, np2), TransformFromCopy(ph, ph2), TransformFromCopy(peh, peh2), ) self.wait() self.play( FadeOut(h_rect), s_rect.become, SurroundingRectangle(answer[2][2]), FadeOut(prior_group), FadeIn(nh_group), ) self.wait() h_rect.replace(diagram.square, stretch=True) self.play( FadeIn(np3), FadeIn(low_brace), FadeIn(low_count), ) self.play(h_rect.replace, diagram.nh_rect, {"stretch": True}) self.play( TransformFromCopy(nh_group[1], pnh), low_brace.become, Brace(VGroup(np3, pnh), DOWN, buff=SMALL_BUFF), ChangeDecimalToValue(low_count, 200), ) self.play(h_rect.replace, diagram.nhe_rect, {"stretch": True}) self.play( TransformFromCopy(anti_label, penh), low_brace.become, Brace(VGroup(np3, penh), DOWN, buff=SMALL_BUFF), ChangeDecimalToValue(low_count, 20), ) self.wait() # Clean up self.play( FadeOut(nh_group), FadeOut(s_rect), FadeOut(h_rect), FadeIn(prior_group), ) self.wait() self.play( ShowCreation(crosses), FadeOut(low_brace), FadeOut(top_brace), FadeOut(low_count), FadeOut(top_count), ) self.wait() self.play( Restore(parts), FadeOut(crosses), FadeOut(nps), answer.set_opacity, 0.2 ) self.wait() # Write Bayes' theorem formula_rect = SurroundingRectangle(formula[1:]) formula_rect.set_stroke(TEAL, 2) bayes_words = OldTexText("Bayes' theorem") bayes_words.scale(1.5) bayes_words.next_to(formula_rect, UP, SMALL_BUFF) bayes_words.match_color(formula_rect) self.play(ShowCreation(formula_rect)) self.play(FadeInFromDown(bayes_words)) self.wait() # Simplify denominator simpler_form = get_bayes_formula()[7:] simpler_form.move_to(answer) pe = simpler_form[-4:].copy() pe.save_state() big_denom_rect = SurroundingRectangle(VGroup(ph2, penh)) lil_denom_rect = SurroundingRectangle(pe) for rect in big_denom_rect, lil_denom_rect: rect.set_stroke(BLUE, 0) rect.set_fill(BLUE, 0.25) pe.move_to(big_denom_rect) pe.set_opacity(0) self.play( FadeOut(answer), FadeIn(simpler_form[:-4]) ) self.play(TransformFromCopy(formula_rect, big_denom_rect)) self.wait() self.play( Restore(pe), ReplacementTransform(big_denom_rect, lil_denom_rect), Transform( formula_rect, SurroundingRectangle(simpler_form, color=TEAL), ), bayes_words.match_x, simpler_form, ) self.remove(pe) self.add(simpler_form) self.wait() # Show all evidence cases he_group_copy = he_group.copy() nhe_group_copy = nhe_group.copy() copies = VGroup(he_group_copy, nhe_group_copy) self.play( copies.arrange, RIGHT, {"buff": LARGE_BUFF}, copies.move_to, DOWN, copies.to_edge, RIGHT, LARGE_BUFF, ) self.wait() self.play( he_group_copy.next_to, VGroup(ph2, peh2), DOWN, ) self.play( nhe_group_copy.next_to, VGroup(pnh, penh), DOWN, ) self.wait() self.play( FadeOut(copies), FadeOut(lil_denom_rect), ) self.wait() # Name posterior self.play( GrowArrow(post_arrow), FadeIn(post_word, RIGHT), FadeOut(formula_rect), FadeOut(bayes_words), ) self.wait() # Show confusion randy = Randolph() randy.flip() randy.next_to(dividing_line, DOWN) randy.to_edge(RIGHT) prior_rect = SurroundingRectangle(prior_word) post_rect = SurroundingRectangle(post_word) VGroup(prior_rect, post_rect).set_stroke(WHITE, 2) self.play(FadeIn(randy)) self.play(randy.change, "confused", formula) self.play(Blink(randy)) self.play(randy.change, "horrified", formula) self.play(randy.look_at, diagram) self.play(Blink(randy)) self.play(randy.look_at, formula) self.play(randy.change, "tired") self.wait(2) self.play( randy.change, "pondering", prior_label, ShowCreation(prior_rect) ) self.play(Blink(randy)) self.play( ReplacementTransform(prior_rect, post_rect), randy.look_at, post_rect, ) self.play(randy.change, "thinking") self.play(FadeOut(post_rect)) self.play(Blink(randy)) self.wait() self.play(randy.look_at, formula) self.play(Blink(randy)) self.wait() # Transition to next scene return # Skip to_move = VGroup(posterior, formula) self.remove(to_move, *to_move, *to_move[1]) to_move.generate_target() to_move.target[1].scale(1 / 0.9) to_move.target.arrange(RIGHT) to_move.target.to_corner(UL) everything = Group(*self.get_mobjects()) self.play( LaggedStartMap(FadeOutAndShiftDown, everything), MoveToTarget(to_move, rate_func=squish_rate_func(smooth, 0.5, 1)), run_time=2, ) def get_diagram(self, include_people=True): diagram = BayesDiagram(**self.bayes_diagram_config) diagram.set_height(5.5) diagram.set_width(5.5, stretch=True) diagram.move_to(0.5 * DOWN) diagram.add_brace_attrs() diagram.evidence_split.set_opacity(0) diagram.hypothesis_split.set_opacity(0) diagram.nh_rect.set_fill(GREY_D) if include_people: people = VGroup(*[Person() for x in range(210)]) people.set_color(interpolate_color(GREY_B, WHITE, 0.5)) people.arrange_in_grid(n_cols=21) people.set_width(diagram.get_width() - SMALL_BUFF) people.set_height(diagram.get_height() - SMALL_BUFF, stretch=True) people.move_to(diagram) people[10:].set_color(GREEN_D) people.set_stroke(BLACK, 2, background=True) diagram.add(people) diagram.people = people return diagram class DiscussFormulaAndAreaModel(CreateFormulaFromDiagram): CONFIG = { "bayes_diagram_config": { "prior_rect_direction": DOWN, }, } def construct(self): # Show smaller denominator t2c = self.tex_to_color_map formula = OldTex( "P(H | E)", "=", "{P(H) P(E | H)", "\\over", "P(H) P(E | H) + P(\\neg H) P(E | \\neg H)}", tex_to_color_map=t2c ) equals = formula.get_part_by_tex("=") equals_index = formula.index_of_part(equals) lhs = formula[:equals_index] rhs = formula[equals_index + 1:] lhs.next_to(equals, LEFT) formula.to_corner(UL) alt_rhs = OldTex( "{P(H)P(E|H)", "\\over", "P(E)}", "=", tex_to_color_map=t2c, ) alt_rhs.next_to(equals, RIGHT, SMALL_BUFF) s_rect = SurroundingRectangle(rhs[12:], color=BLUE) self.add(formula) self.wait() self.play(ShowCreation(s_rect)) self.add(alt_rhs, s_rect) self.play( VGroup(rhs, s_rect).next_to, alt_rhs, RIGHT, SMALL_BUFF, GrowFromCenter(alt_rhs), ) self.play( s_rect.become, SurroundingRectangle(alt_rhs[12:-1], color=BLUE) ) self.wait() # Bring in diagram diagram = self.get_diagram(include_people=False) diagram.evidence_split.set_opacity(1) diagram.set_height(3) diagram.set_prior(0.1) diagram.refresh_braces() diagram.add( diagram.h_brace, diagram.he_brace, diagram.nhe_brace, ) h_label, he_label, nhe_label = labels = [ OldTex(tex, tex_to_color_map=t2c) for tex in ["P(H)", "P(E|H)", "P(E|\\neg H)"] ] h_label.add_updater(lambda m: m.next_to(diagram.h_brace, DOWN)) he_label.add_updater(lambda m: m.next_to(diagram.he_brace, LEFT)) nhe_label.add_updater(lambda m: m.next_to(diagram.nhe_brace, RIGHT)) diagram.add(*labels) diagram.to_corner(DL) he_rect_copy = diagram.he_rect.copy() nhe_rect_copy = diagram.nhe_rect.copy() self.play( FadeIn(diagram), # FadeOut(s_rect), ReplacementTransform( VGroup(s_rect, s_rect.copy()), VGroup(he_rect_copy, nhe_rect_copy), ), ) self.wait() self.play(LaggedStart( ApplyMethod(he_rect_copy.next_to, rhs[12:22], DOWN), ApplyMethod(nhe_rect_copy.next_to, rhs[23:], DOWN), lag_ratio=0.7, run_time=1.5 )) self.wait() self.play(FadeOut(VGroup(he_rect_copy, nhe_rect_copy))) # Tell what to memorize big_rect = SurroundingRectangle(formula) big_rect.set_stroke(WHITE, 2) big_rect.set_fill(BLACK, 0) words1 = OldTexText("Don't memorize\\\\this") words2 = OldTexText("Remember\\\\this") for words in words1, words2: words.scale(1.5) words.to_edge(RIGHT) arrow1 = Arrow(words1.get_corner(UL), big_rect.get_bottom()) arrow2 = Arrow(words2.get_left(), diagram.square.get_right()) self.play( FadeIn(words1), ShowCreation(arrow1), ShowCreation(big_rect) ) self.wait() self.play( ReplacementTransform(arrow1, arrow2), FadeOut(words1), FadeIn(words2), big_rect.set_stroke, WHITE, 0, big_rect.set_fill, BLACK, 0.7, ) self.wait() # Talk about diagram slices to_fade = VGroup( diagram.evidence_split, diagram.he_brace, diagram.nhe_brace, he_label, nhe_label, ) to_fade.save_state() h_part = VGroup( diagram.hypothesis_split, diagram.h_brace, h_label, ) people = self.get_diagram().people people.set_width(diagram.square.get_width() - 0.05) people.move_to(diagram.square) sides = VGroup( DashedLine( diagram.square.get_corner(UL), diagram.square.get_corner(UR), ), DashedLine( diagram.square.get_corner(UL), diagram.square.get_corner(DL), ), ) sides.set_stroke(YELLOW, 4) ones = VGroup( OldTex("1").next_to(diagram.square, UP), OldTex("1").next_to(diagram.square, LEFT), ) self.play( to_fade.set_opacity, 0, h_part.set_opacity, 0, diagram.square.set_opacity, 1, ShowIncreasingSubsets(people), ) self.play(FadeOut(people)) self.play( LaggedStartMap(ShowCreation, sides, lag_ratio=0.8), LaggedStartMap(FadeIn, ones, lag_ratio=0.8), ) self.wait() self.play( h_part.set_opacity, 1, ) diagram.square.set_opacity(0) self.wait() self.play( FadeOut(sides), FadeOut(ones), ) self.wait() VGroup( to_fade[1:], to_fade[0][::2], ).stretch(0, 1, about_edge=DOWN) self.play( Restore(to_fade), diagram.hypothesis_split.set_opacity, 0, diagram.hne_rect.set_opacity, 0.2, diagram.nhne_rect.set_opacity, 0.2, ) self.wait() # Add posterior bar post_bar = always_redraw( lambda: self.get_posterior_bar( diagram.he_rect, diagram.nhe_rect, ) ) post_label = OldTex("P(H|E)", tex_to_color_map=t2c) post_label.add_updater(lambda m: m.next_to(post_bar.brace, DOWN)) self.play( FadeOut(words2), FadeOut(arrow2), TransformFromCopy( diagram.he_rect, post_bar.rects[0], ), TransformFromCopy( diagram.nhe_rect, post_bar.rects[1], ), FadeIn(post_bar.brace), FadeIn(post_label), ) self.add(post_bar) self.wait() self.play( diagram.set_likelihood, 0.8, rate_func=there_and_back, run_time=4, ) self.wait() self.play(diagram.set_antilikelihood, 0.4) self.wait() self.play( diagram.set_likelihood, 0.8, diagram.set_antilikelihood, 0.05, ) self.wait() self.play( diagram.set_likelihood, 0.4, diagram.set_antilikelihood, 0.1, ) self.wait() self.play( big_rect.set_width, rhs.get_width() + 0.7, {"about_edge": RIGHT, "stretch": True}, ) self.wait() # Terms from formula to sides in diagram hs_rect = SurroundingRectangle(alt_rhs[:5], buff=0.05) hes_rect = SurroundingRectangle(alt_rhs[5:11], buff=0.05) hs_rect.set_stroke(YELLOW, 3) hes_rect.set_stroke(BLUE, 3) self.play(ShowCreation(hs_rect)) self.play(ShowCreation(hes_rect)) self.wait() self.play(hs_rect.move_to, h_label) self.play(hes_rect.move_to, he_label) self.wait() self.play(FadeOut(VGroup(hs_rect, hes_rect))) def get_posterior_bar(self, he_rect, nhe_rect): he_height = he_rect.get_height() he_width = he_rect.get_width() nhe_height = nhe_rect.get_height() nhe_width = nhe_rect.get_width() total_width = he_width + nhe_width he_area = he_width * he_height nhe_area = nhe_width * nhe_height posterior = he_area / (he_area + nhe_area) new_he_width = posterior * total_width new_he_height = he_area / new_he_width new_nhe_width = (1 - posterior) * total_width new_nhe_height = nhe_area / new_nhe_width new_he_rect = Rectangle( width=new_he_width, height=new_he_height, ).match_style(he_rect) new_nhe_rect = Rectangle( width=new_nhe_width, height=new_nhe_height, ).match_style(nhe_rect) rects = VGroup(new_he_rect, new_nhe_rect) rects.arrange(RIGHT, buff=0) brace = Brace( new_he_rect, DOWN, buff=SMALL_BUFF, min_num_quads=2, ) result = VGroup(rects, brace) result.rects = rects result.brace = brace # Put positioning elsewhere? result.to_edge(RIGHT) return result class RandomShapes(Scene): def construct(self): diagram = BayesDiagram(0.1, 0.4, 0.1) diagram.set_height(3) e_part = VGroup(diagram.he_rect, diagram.nhe_rect).copy() e_part.set_fill(BLUE) circle = Circle() circle.set_fill(RED, 0.5) circle.set_stroke(RED, 2) circle.move_to(diagram) tri = Polygon(UP, ORIGIN, RIGHT) tri.match_height(diagram) tri.set_fill(PURPLE, 0.5) tri.set_stroke(PURPLE, 2) tri.move_to(diagram) h_rect = diagram.h_rect h_rect.set_fill(YELLOW, 1) pi = OldTex("\\pi") pi.set_height(2) pi.set_stroke(GREEN, 2) pi.set_fill(GREEN, 0.5) events = VGroup( e_part, h_rect, circle, pi, tri, ) last = VMobject() for event in events: self.play( FadeIn(event), FadeOut(last) ) self.wait() last = event class BigArrow(Scene): def construct(self): arrow = Arrow( 3 * DOWN + 4 * LEFT, 3 * RIGHT + DOWN, path_arc=50 * DEGREES, ) self.play(ShowCreation(arrow)) self.wait() class UsesOfBayesTheorem(Scene): def construct(self): formula = get_bayes_formula() formula.to_corner(UL) rhs = formula[7:] bubble = ThoughtBubble(direction=RIGHT) bubble.set_fill(opacity=0) arrow = Vector(RIGHT) arrow.next_to(formula, RIGHT, MED_LARGE_BUFF) bubble.set_height(2) bubble.next_to(arrow, RIGHT, MED_LARGE_BUFF) bubble.align_to(formula, UP) bar = ProbabilityBar( 0.1, percentage_background_stroke_width=1, include_braces=False, ) bar.set_width(0.8 * bubble[-1].get_width()) bar.move_to(bubble.get_bubble_center()) scientist = SVGMobject(file_name="scientist") programmer = SVGMobject(file_name="programmer") randy = Randolph().flip() people = VGroup(scientist, programmer, randy) people.set_stroke(width=0) for person in people: person.set_height(2.5) if person is not randy: person.set_fill(GREY) person.set_sheen(0.5, UL) people.arrange(RIGHT, buff=2.5) # programmer.shift(0.5 * RIGHT) people.to_edge(DOWN, buff=LARGE_BUFF) self.add(formula) self.wait() self.play(GrowArrow(arrow)) self.play(ShowCreation(bubble), FadeIn(bar)) self.play(bar.p_tracker.set_value, 0.8) self.wait() # Add people for person in [scientist, programmer]: self.play(FadeIn(person, DOWN)) rhs_copy = rhs.copy() rhs_copy.add_to_back( SurroundingRectangle( rhs_copy, fill_color=BLACK, fill_opacity=0.8, stroke_color=WHITE, stroke_width=2, ) ) rhs_copy.generate_target() rhs_copy[0].set_stroke(width=0) rhs_copy.target.scale(0.5) rhs_copy.target.move_to(person.get_corner(DR)) self.add(rhs_copy, formula) self.play(MoveToTarget(rhs_copy)) self.wait() person.add(rhs_copy) self.play(FadeInFromDown(randy)) self.play(randy.change, "pondering") self.play(Blink(randy)) bubble_group = VGroup(bubble, bar) self.play( bubble_group.scale, 1.4, bubble_group.move_to, randy.get_corner(UL), DR, randy.look_at, bubble, FadeOut(arrow), ) self.wait() self.play(Blink(randy)) self.play(bar.p_tracker.set_value, 0.3, run_time=3) self.play(randy.change, "thinking") self.play(Blink(randy)) self.wait() self.play(LaggedStartMap( FadeOutAndShift, VGroup(*people, bubble_group), lambda m: (m, DOWN), lag_ratio=0.15, )) class AskAboutWhenProbabilityIsIntuitive(TeacherStudentsScene): def construct(self): words = OldTexText("What makes probability\\\\more intuitive?") words.move_to(self.hold_up_spot, DOWN) words.shift_onto_screen() self.play( self.teacher.change, "speaking", self.change_students( "pondering", "sassy", "happy", look_at=self.screen, ) ) self.wait(2) self.play( self.teacher.change, "raise_right_hand", FadeIn(words, DOWN), self.change_students("erm", "pondering", "confused") ) self.wait(2) self.play( words.scale, 2, words.center, words.to_edge, UP, self.teacher.change, "pondering", 3 * UP, self.change_students( "pondering", "thinking", "thinking", look_at=3 * UP, ) ) self.wait(6) class IntroduceLinda(DescriptionOfSteve): def construct(self): # Kahneman and Tversky images = self.get_images() self.play( LaggedStartMap( FadeInFrom, images, lambda m: (m, LEFT), lag_ratio=0.3, run_time=3, ) ) self.wait() # Add steve steve = Steve() steve.set_height(3) steve.move_to(2 * RIGHT) steve.to_edge(DOWN, buff=LARGE_BUFF) steve_words = self.get_description() steve_words.scale(0.8) steve_words.next_to(steve, UP, LARGE_BUFF) self.play(LaggedStart( FadeIn(steve, LEFT), FadeIn(steve_words, LEFT), )) self.wait() # Replace with Linda linda = Linda() linda_words = self.get_linda_description() linda_words.scale(0.8) linda.replace(steve) linda_words.move_to(steve_words) self.play( LaggedStart( FadeOut(steve_words, 2 * RIGHT), FadeOut(steve, 2 * RIGHT), FadeIn(linda, 2 * LEFT), lag_ratio=0.15, ) ) self.wait() self.play( FadeIn(linda_words), lag_ratio=0.1, run_time=6, rate_func=linear, ) self.wait() # Ask question options = VGroup( OldTexText("1) Linda is a bank teller."), OldTexText( "2) Linda is a bank teller and is active\\\\", "\\phantom{2)} in the feminist movement.", alignment="", ), ) options.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) options.to_edge(DOWN, buff=LARGE_BUFF) self.play( linda.match_height, linda_words, linda.next_to, linda_words, LEFT, LARGE_BUFF, LaggedStartMap( FadeOutAndShift, images, lambda m: (m, 2 * LEFT), ) ) for option in options: self.play(FadeIn(option, lag_ratio=0.1, run_time=2)) self.wait() # Show result rect = SurroundingRectangle(options[1], color=RED) options.generate_target() rect.generate_target() VGroup(options.target, rect.target).to_edge(LEFT) result = VGroup( Integer(85, unit="\\%"), OldTexText("chose this!") ) result.arrange(RIGHT) result.scale(1.25) result.set_color(RED) result.move_to(rect) result.to_edge(RIGHT) result.shift(2 * UP) arrow = Arrow(result.get_bottom(), rect.target.get_corner(UR)) self.play( MoveToTarget(options), MoveToTarget(rect), VFadeIn(rect), FadeIn(result, LEFT), GrowArrow(arrow) ) self.wait() # Show subsets fb_words = OldTexText("Active feminist\\\\bank tellers") fb_words.scale(0.5) fb_words.set_stroke(BLACK, 0, background=True) fb_set = Circle() fb_set.flip(RIGHT) fb_set.rotate(3 * TAU / 8) fb_set.set_stroke(WHITE, 1) fb_set.set_fill(YELLOW, 0.5) fb_set.replace(fb_words, stretch=True) fb_set.scale(1.2) fb_set.stretch(1.4, 1) fb_group = VGroup(fb_set, fb_words) fb_group.move_to(linda_words, RIGHT) b_set = fb_set.copy() b_set.set_fill(BLUE) b_set.scale(3, about_edge=RIGHT) b_set.stretch(1.5, 1) b_set.to_corner(UR) b_words = OldTexText("Bank\\\\tellers") b_words.next_to(b_set.get_left(), RIGHT, LARGE_BUFF) self.play( FadeOut(linda_words), TransformFromCopy(rect, fb_set), ReplacementTransform( VectorizedPoint(rect.get_center()), fb_words, ), ) self.add(fb_set, fb_words) self.wait() self.add(b_set, fb_set, fb_words) self.play( DrawBorderThenFill(b_set), TransformFromCopy( options[0][0][10:], b_words[0] ), ) sets_group = VGroup(b_set, b_words, fb_set, fb_words) self.add(sets_group) self.wait() # Reduce 85 number = result[0] self.play( LaggedStart( FadeOut(arrow), FadeOut(result[1]), FadeOut(rect), FadeOut(options[0]), FadeOut(options[1]), ), number.scale, 1.5, number.move_to, DOWN, ) self.play( ChangeDecimalToValue(number, 0), UpdateFromAlphaFunc( number, lambda m, a: m.set_color(interpolate_color( RED, GREEN, a, )) ), run_time=2, ) self.wait() self.play( FadeOut(number), FadeOut(sets_group), FadeIn(linda_words), ) # New options words = OldTexText("100 people fit this description. How many are:") words.set_color(BLUE_B) kw = {"tex_to_color_map": {"\\underline{\\qquad}": WHITE}} new_options = VGroup( OldTexText("1) Bank tellers? \\underline{\\qquad} of 100", **kw), OldTexText( "2) Bank tellers and active in the", " feminist movement? \\underline{\\qquad} of 100", **kw ), ) new_options.scale(0.9) new_options.arrange(DOWN, aligned_edge=LEFT, buff=MED_LARGE_BUFF) new_options.to_edge(DOWN, buff=LARGE_BUFF) words.next_to(new_options, UP, LARGE_BUFF) self.play( FadeIn(words, lag_ratio=0.1, rate_func=linear) ) self.wait() for option in new_options: self.play(FadeIn(option)) self.wait() example_numbers = VGroup(Integer(8), Integer(5)) for exn, option in zip(example_numbers, new_options): line = option.get_part_by_tex("underline") exn.scale(1.1) exn.next_to(line, UP, buff=0.05) exn.set_color(YELLOW) self.play(Write(exn)) self.wait() def get_images(self): images = Group( ImageMobject("kahneman"), ImageMobject("tversky"), ) images.set_height(3.5) images.arrange(DOWN, buff=0.5) images.to_edge(LEFT, buff=MED_LARGE_BUFF) names = VGroup( OldTexText("Kahneman", alignment=""), OldTexText("Tversky", alignment=""), ) for name, image in zip(names, images): name.next_to(image, DOWN) image.name = name image.add(name) images.arrange(DOWN, buff=1, aligned_edge=LEFT) images.set_height(FRAME_HEIGHT - 1) images.to_edge(LEFT) return images def get_linda_description(self): result = OldTexText( "Linda is 31 years old, single, outspoken, and\\\\", "very bright. She majored in philosophy. As a \\\\", "student, she was deeply concerned with issues\\\\", "of discrimination and social justice, and also\\\\", "participated in anti-nuclear demonstrations.\\\\", alignment="", tex_to_color_map={ "deeply concerned with issues": YELLOW, "of discrimination": YELLOW, } ) return result class LindaDescription(IntroduceLinda): def construct(self): words = self.get_linda_description() words.set_color(WHITE) highlighted_part = VGroup( *words.get_part_by_tex("deeply"), *words.get_part_by_tex("discrimination"), ) self.add(words) self.play( FadeIn(words), run_time=3, lag_ratio=0.01, rate_func=linear, ) self.wait(1) self.play( highlighted_part.set_color, YELLOW, lag_ratio=0.1, run_time=2 ) self.wait() class AlternatePhrasings(PiCreatureScene): CONFIG = { "camera_config": { "background_color": GREY_E, } } def construct(self): randy = self.pi_creature phrases = VGroup( OldTexText("40 out of 100"), OldTex("40\\%"), OldTex("0.4"), OldTexText("What's more likely$\\dots$"), ) for phrase in phrases: phrase.scale(1.5) phrase.next_to(randy, RIGHT, buff=LARGE_BUFF) phrase.align_to(randy, UP) def push_down(phrase): phrase.scale(0.8, about_edge=LEFT) phrase.shift(1 * DOWN) phrase.set_opacity(0.5) return phrase bubble = randy.get_bubble() content_width = 4.5 people = VGroup(*[Person() for x in range(100)]) people.arrange_in_grid(n_cols=20) people.set_width(content_width) people.move_to(bubble.get_bubble_center()) people.shift(SMALL_BUFF * UP) people[:40].set_color(YELLOW) bar = ProbabilityBar(0.9999) bar.set_width(content_width) bar.move_to(people) steve = Steve() steve.set_height(1) steve_words = OldTexText("seems bookish...") steve_words.next_to(steve, RIGHT, MED_LARGE_BUFF) steve.add(steve_words) linda = Linda() linda.set_height(1) linda_words = OldTexText("seems activist...") linda_words.next_to(linda, RIGHT, MED_LARGE_BUFF) linda.add(linda_words) stereotypes = VGroup(steve, linda) stereotypes.arrange(DOWN, buff=MED_SMALL_BUFF, aligned_edge=LEFT) stereotypes.move_to(people) self.play( FadeIn(phrases[0], UP), randy.change, "pondering", ) self.play( DrawBorderThenFill(bubble, lag_ratio=0.1), FadeIn(people, lag_ratio=0.1), randy.change, "thinking", people, ) self.wait() self.play( FadeIn(phrases[1], UP), randy.change, "confused", phrases[1], FadeOut(people), ApplyFunction(push_down, phrases[0]), FadeIn(bar), ) self.play(bar.p_tracker.set_value, 0.4) bar.clear_updaters() self.play( FadeIn(phrases[2], UP), ApplyFunction(push_down, phrases[:2]), FadeOut(bar.percentages), randy.change, "guilty", ) self.wait() bar.remove(bar.percentages) self.play( FadeIn(phrases[3], UP), ApplyFunction(push_down, phrases[:3]), FadeOut(bar), FadeIn(stereotypes), randy.change, "shruggie", stereotypes, ) self.wait(6) class WhenDiscreteChunksArentSoClean(Scene): def construct(self): squares = VGroup(*[Square() for x in range(100)]) squares.arrange_in_grid(n_cols=10, buff=0) squares.set_stroke(WHITE, 1) squares.set_fill(GREY_E, 1) squares.set_height(6) squares.to_edge(DOWN) target_p = 0.3612 rain, sun = icon_templates = VGroup( SVGMobject("rain_cloud"), SVGMobject("sunny"), ) for icon in icon_templates: icon.set_width(0.6 * squares[0].get_width()) icon.set_stroke(width=0) icon.set_sheen(0.5, UL) rain.set_color(BLUE_E) sun.set_color(YELLOW) partial_rects = VGroup() icons = VGroup() q_marks = VGroup() for i, square in enumerate(squares): icon = rain.copy() if i < 40 else sun.copy() icon.move_to(square) icons.add(icon) partial_rect = square.copy() partial_rect.set_stroke(width=0) partial_rect.scale(0.95) partial_rect.stretch( 0.4, 0, about_edge=RIGHT ) partial_rects.add(partial_rect) q_mark = OldTex("?") q_mark.replace(partial_rect, dim_to_match=0) q_mark.scale(0.8) q_marks.add(q_mark) p_label = VGroup( OldTex("P", "(", "\\text{Rain}", ")", "="), DecimalNumber(40, unit="\\%", num_decimal_places=2) ) percentage = p_label[1] p_label.arrange(RIGHT) p_label.to_edge(UP) p_label[0].set_color_by_tex("Rain", BLUE) percentage.align_to(p_label[0][0], DOWN) alt_percentage = Integer(0, unit="\\%") alt_percentage.move_to(percentage, LEFT) self.add(squares) self.add(p_label[0]) self.play( ChangeDecimalToValue(alt_percentage, 40), ShowIncreasingSubsets(icons[:40]) ) self.play(FadeIn(icons[40:])) self.wait() self.remove(alt_percentage) self.add(percentage) self.play( ChangeDecimalToValue(percentage, 100 * target_p), FadeIn(partial_rects[30:40]), FadeIn(q_marks[30:40], lag_ratio=0.3) ) self.wait(2) l_rect = Rectangle(fill_color=BLUE_D) r_rect = Rectangle(fill_color=GREY_B) rects = VGroup(l_rect, r_rect) for rect, p in (l_rect, target_p), (r_rect, 1 - target_p): rect.set_height(squares.get_height()) rect.set_width(p * squares.get_width(), stretch=True) rect.set_stroke(WHITE, 2) rect.set_fill(opacity=1) rects.arrange(RIGHT, buff=0) rects.move_to(squares) brace = Brace(l_rect, UP, buff=SMALL_BUFF) sun = icons[40].copy() rain = icons[0].copy() for mob, rect in [(rain, l_rect), (sun, r_rect)]: mob.generate_target() mob.target.set_stroke(BLACK, 3, background=True) mob.target.set_height(1) mob.target.move_to(rect) self.play( FadeIn(rects), MoveToTarget(rain), MoveToTarget(sun), GrowFromCenter(brace), p_label.shift, brace.get_top() + MED_SMALL_BUFF * UP - percentage.get_bottom(), ) self.wait() # With updaters full_width = rects.get_width() rain.add_updater(lambda m: m.move_to(l_rect)) sun.add_updater(lambda m: m.move_to(r_rect)) r_rect.add_updater(lambda m: m.set_width( full_width - l_rect.get_width(), about_edge=RIGHT, stretch=True, )) brace.add_updater(lambda m: m.match_width(l_rect, stretch=True)) brace.add_updater(lambda m: m.next_to(l_rect, UP, SMALL_BUFF)) percentage.add_updater(lambda m: m.set_value( 100 * l_rect.get_width() / full_width, )) percentage.add_updater(lambda m: m.next_to(brace, UP, MED_SMALL_BUFF)) self.play( MaintainPositionRelativeTo(p_label[0], percentage), l_rect.stretch, 2, 0, {"about_edge": LEFT}, run_time=8, rate_func=there_and_back, ) class RandomnessVsProportions(Scene): def construct(self): prob_word = OldTexText("Probability") unc_word = OldTexText("Uncertainty") prop_word = OldTexText("Proportions") words = VGroup(prop_word, prob_word, unc_word) words.arrange(RIGHT, buff=LARGE_BUFF) words.set_width(FRAME_WIDTH - 1) words.to_edge(UP) arrows = VGroup() for w1, w2 in zip(words, words[1:]): arrow = OldTex("\\rightarrow") arrow.move_to(midpoint(w1.get_right(), w2.get_left())) arrows.add(arrow) random_dice = self.get_random_dice() random_dice.next_to(unc_word, DOWN, LARGE_BUFF) diagram = self.get_dice_diagram() diagram.next_to(prop_word, DOWN, LARGE_BUFF) diagram.shift_onto_screen() grid = diagram[0] border = grid[0][0].copy() border.set_stroke(BLACK, 3) border.set_fill(WHITE, opacity=0.2) border.scale(1.02) def update_border(border): r1, r2 = random_dice i = len(r1[1]) - 1 j = len(r2[1]) - 1 border.move_to(diagram[0][i][j]) border.add_updater(update_border) example = VGroup( OldTexText("P(X = 5)", tex_to_color_map={"5": YELLOW}), Line(LEFT, RIGHT) ) example.arrange(RIGHT) example.next_to(grid, RIGHT, LARGE_BUFF) example.align_to(random_dice, RIGHT) example.shift(0.5 * DOWN) grid_copy = grid.copy() five_part = VGroup(*[ square for i, row in enumerate(grid_copy) for j, square in enumerate(row) if i + j == 3 ]) self.play(FadeInFromDown(prob_word)) self.play( FadeIn(unc_word, LEFT), Write(arrows[1]), ) self.add(random_dice) self.wait(9) self.play( FadeIn(prop_word, RIGHT), Write(arrows[0]) ) self.play(FadeIn(diagram)) self.add(border) self.wait(2) self.play(FadeIn(example)) self.add(grid_copy, diagram[1]) self.play( grid_copy.set_width, 0.8 * example[1].get_width(), grid_copy.next_to, example[1], DOWN, ) self.play(five_part.copy().next_to, example[1], UP) self.wait(6) def get_die_faces(self): 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_dice(self): faces = list(self.get_die_faces()) def get_random_pair(): result = VGroup(*random.sample(faces, 2)).copy() result.arrange(RIGHT) for mob in result: mob.shift(random.random() * RIGHT * MED_SMALL_BUFF) mob.shift(random.random() * UP * MED_SMALL_BUFF) return result result = VGroup(*get_random_pair()) result.time = 0 result.iter_count = 0 def update_result(group, dt): group.time += dt group.iter_count += 1 if int(group.time) % 3 == 2: group.set_stroke(YELLOW) return group elif result.iter_count % 3 != 0: return group else: pair = get_random_pair() pair.move_to(group) group.submobjects = [*pair] result.add_updater(update_result) result.update() return result def get_dice_diagram(self): grid = VGroup(*[ VGroup(*[ Square() for x in range(6) ]).arrange(RIGHT, buff=0) for y in range(6) ]).arrange(DOWN, buff=0) grid.set_stroke(WHITE, 1) grid.set_height(5) colors = color_gradient([RED, YELLOW, GREEN, BLUE], 11) numbers = VGroup() for i, row in enumerate(grid): for j, square in enumerate(row): num = Integer(i + j + 2) num.set_height(square.get_height() - MED_LARGE_BUFF) num.move_to(square) # num.set_stroke(BLACK, 2, background=True) num.set_fill(GREY_D) square.set_fill(colors[i + j], 0.9) numbers.add(num) faces = VGroup() face_templates = self.get_die_faces() face_templates.scale(0.5) for face, row in zip(face_templates, grid): face.next_to(row, LEFT, MED_SMALL_BUFF) faces.add(face) for face, square in zip(faces.copy(), grid[0]): face.next_to(square, UP, MED_SMALL_BUFF) faces.add(face) result = VGroup(grid, numbers, faces) return result class JustRandomDice(RandomnessVsProportions): def construct(self): random_dice = self.get_random_dice() random_dice.center() self.add(random_dice) self.wait(60) class BayesTheoremOnProportions(Scene): def construct(self): # Place on top of visuals from "HeartOfBayes" formula = get_bayes_formula() formula.scale(1.5) title = OldTexText("Bayes' theorem") title.scale(2) title.next_to(formula, UP, LARGE_BUFF) group = VGroup(formula, title) equals = OldTex("=") equals.next_to(formula, RIGHT) h_line = Line(LEFT, RIGHT) h_line.set_width(4) h_line.next_to(equals, RIGHT) h_line.set_stroke(WHITE, 3) self.add(group) self.wait() self.play( group.to_edge, LEFT, MaintainPositionRelativeTo(equals, group), VFadeIn(equals), MaintainPositionRelativeTo(h_line, group), VFadeIn(h_line), ) # People people = VGroup(*[Person() for x in range(7)]) people.arrange(RIGHT) people.match_width(h_line) people.next_to(h_line, DOWN) people.set_color(BLUE_E) people[:3].set_color(GREEN) num_people = people[:3].copy() self.play(FadeIn(people, lag_ratio=0.1)) self.play(num_people.next_to, h_line, UP) self.wait(0.5) # Diagrams diagram = BayesDiagram(0.25, 0.5, 0.2) diagram.set_width(0.7 * h_line.get_width()) diagram.next_to(h_line, DOWN) diagram.hne_rect.set_fill(opacity=0.1) diagram.nhne_rect.set_fill(opacity=0.1) num_diagram = diagram.deepcopy() num_diagram.next_to(h_line, UP) num_diagram.nhe_rect.set_fill(opacity=0.1) low_diagram_rects = VGroup(diagram.he_rect, diagram.nhe_rect) top_diagram_rects = VGroup(num_diagram.he_rect) self.play( FadeOut(people), FadeOut(num_people), FadeIn(diagram), FadeIn(num_diagram), ) self.wait() # Circle each part E_part = VGroup(formula[4], *formula[19:]).copy() H_part = VGroup(formula[2], *formula[8:18]).copy() E_arrow = Vector(UP, color=BLUE) E_arrow.next_to(E_part[0], DOWN) E_words = OldTexText( "...among cases where\\\\$E$ is True", tex_to_color_map={"$E$": BLUE}, ) E_words.next_to(E_arrow, DOWN) H_arrow = Vector(DOWN, color=YELLOW) H_arrow.next_to(H_part[0], UP) H_words = OldTexText( "How often is\\\\$H$ True...", tex_to_color_map={"$H$": YELLOW}, ) H_words.next_to(H_arrow, UP) denom_rect = SurroundingRectangle(E_part[1:], color=BLUE) numer_rect = SurroundingRectangle(H_part[1:], color=YELLOW) self.play( formula.set_opacity, 0.5, ApplyMethod( E_part.set_stroke, YELLOW, 3, {"background": True}, rate_func=there_and_back, ), FadeIn(denom_rect), ShowCreation(E_arrow), FadeIn(E_words, UP), low_diagram_rects.set_stroke, TEAL, 3, ) self.wait() self.play( FadeOut(E_part), FadeIn(H_part), FadeOut(denom_rect), FadeIn(numer_rect), ShowCreation(H_arrow), FadeIn(H_words, DOWN), FadeOut(title, UP), low_diagram_rects.set_stroke, WHITE, 1, top_diagram_rects.set_stroke, YELLOW, 3, ) self.wait() class GraphScene(Scene): pass class GlimpseOfNextVideo(GraphScene): CONFIG = { "x_axis_label": "", "y_axis_label": "", "x_min": 0, "x_max": 15, "x_axis_width": 12, "y_min": 0, "y_max": 1.0, "y_axis_height": 6, "y_tick_frequency": 0.125, "add_x_coords": True, "formula_position": ORIGIN, "dx": 0.2, } def setup(self): super().setup() self.setup_axes() self.y_axis.add_numbers( 0.25, 0.5, 0.75, 1, num_decimal_places=2, direction=LEFT, ) if self.add_x_coords: self.x_axis.add_numbers(*range(1, 15),) def construct(self): f1 = self.prior def f2(x): return f1(x) * self.likelihood(x) pe = scipy.integrate.quad(f2, 0, 20)[0] graph1 = self.get_graph(f1) graph2 = self.get_graph(f2) rects1 = self.get_riemann_rectangles(graph1, dx=self.dx) rects2 = self.get_riemann_rectangles(graph2, dx=self.dx) rects1.set_color(YELLOW_D) rects2.set_color(BLUE) for rects in rects1, rects2: rects.set_stroke(WHITE, 1) rects1.save_state() rects1.stretch(0, 1, about_edge=DOWN) formula = self.get_formula() self.play( FadeInFromDown(formula[:4]), Restore(rects1, lag_ratio=0.05, run_time=2) ) self.wait() self.add(rects1.copy().set_opacity(0.4)) self.play( FadeInFromDown(formula[4:10]), Transform(rects1, rects2), ) self.wait() self.play( rects1.stretch, 1 / pe, 1, {"about_edge": DOWN}, Write(formula[10:], run_time=1) ) self.wait() def get_formula(self): formula = OldTex( "p(H) p(E|H) \\over p(E)", tex_to_color_map={ "H": HYPOTHESIS_COLOR, "E": EVIDENCE_COLOR1, }, isolate=list("p(|)") ) formula.move_to(self.formula_position) return formula def prior(self, x): return (x**3 / 6) * np.exp(-x) def likelihood(self, x): return np.exp(-0.5 * x) class ComingUp(Scene): CONFIG = { "camera_config": {"background_color": GREY_D} } def construct(self): rect = ScreenRectangle() rect.set_height(6) rect.set_fill(BLACK, 1) rect.set_stroke(WHITE, 2) words = OldTexText("Later...") words.scale(2) words.to_edge(UP) rect.next_to(words, DOWN) self.add(rect) self.play(FadeIn(words)) self.wait() class QuestionSteveConclusion(HeartOfBayesTheorem, DescriptionOfSteve): def construct(self): # Setup steve = Steve() steve.shift(UP) self.add(steve) kt = Group( ImageMobject("kahneman"), ImageMobject("tversky"), ) kt.arrange(DOWN) kt.set_height(6) randy = Randolph() kt.next_to(randy, RIGHT, LARGE_BUFF) randy.align_to(kt, DOWN) farmers = VGroup(*[Farmer() for x in range(20)]) farmers.arrange_in_grid(n_cols=5) people = VGroup(Librarian(), farmers) people.arrange(RIGHT, aligned_edge=UP) people.set_height(3) people.next_to(randy.get_corner(UL), UP) cross = Cross(people) cross.set_stroke(RED, 8) # Question K&T self.play( steve.scale, 0.5, steve.to_corner, DL, FadeIn(randy), FadeInFromDown(kt, lag_ratio=0.3), ) self.play(randy.change, "sassy") self.wait() self.play( FadeIn(people, RIGHT, lag_ratio=0.01), randy.change, "raise_left_hand", people, ) self.wait() self.play( ShowCreation(cross), randy.change, "angry" ) self.wait() # Who is Steve? people.add(cross) self.play( people.scale, 0.3, people.to_corner, UL, steve.scale, 1.5, steve.next_to, randy.get_corner(UL), LEFT, randy.change, "pondering", steve, ) self.play(randy.look_at, steve) self.play(Blink(randy)) kt.generate_target() steve.generate_target() steve.target.set_height(0.9 * kt[0].get_height()) group = Group(kt.target[0], steve.target, kt.target[1]) group.arrange(RIGHT) group.to_edge(RIGHT) self.play( MoveToTarget(kt), MoveToTarget(steve), randy.shift, 2 * LEFT, randy.change, 'erm', kt.target, FadeOut(people, 2 * LEFT), ) self.remove(people, cross) self.play(Blink(randy)) self.wait() jessy = Randolph(color=BLUE_B) jessy.next_to(randy, LEFT, MED_LARGE_BUFF) steve.target.match_height(randy) steve.target.next_to(randy, RIGHT, MED_LARGE_BUFF) morty = Mortimer() morty.next_to(steve.target, RIGHT, MED_LARGE_BUFF) morty.look_at(steve.target), jessy.look_at(steve.target), VGroup(jessy, morty, steve.target).to_edge(DOWN) pis = VGroup(randy, jessy, morty) self.play( LaggedStartMap(FadeOutAndShift, kt, lambda m: (m, 3 * UR)), MoveToTarget(steve), randy.to_edge, DOWN, randy.change, "happy", steve.target, FadeIn(jessy), FadeIn(morty), ) self.play(LaggedStart(*[ ApplyMethod(pi.change, "hooray", steve) for pi in pis ])) self.play(Blink(morty)) self.play(Blink(jessy)) # The assumption changes the prior diagram = self.get_diagram(0.05, 0.4, 0.1) diagram.nhne_rect.set_fill(GREY_D) diagram.set_height(3.5) diagram.center().to_edge(UP, buff=MED_SMALL_BUFF) self.play( FadeIn(diagram), *[ ApplyMethod(pi.change, "pondering", diagram) for pi in pis ], ) self.play(diagram.set_prior, 0.5) self.play(Blink(jessy)) self.wait() self.play(Blink(morty)) self.play( morty.change, "raise_right_hand", diagram, ApplyMethod(diagram.set_prior, 0.9, run_time=2), ) self.play(Blink(randy)) self.wait() # Likelihood of description description = self.get_description() description.scale(0.5) description.to_corner(UL) self.play( FadeIn(description), *[ApplyMethod(pi.change, "sassy", description) for pi in pis] ) self.play( diagram.set_likelihood, 0.2, run_time=2, ) self.play( diagram.set_antilikelihood, 0.5, run_time=2, ) self.play(Blink(jessy)) self.play(Blink(randy)) self.wait() # Focus on diagram diagram.generate_target() diagram.target.set_height(6) diagram.target.move_to(3 * LEFT) formula = get_bayes_formula() formula.scale(0.75) formula.to_corner(UR) self.play( FadeInFromDown(formula), LaggedStart(*[ ApplyMethod(pi.change, "thinking", formula) for pi in pis ]) ) self.play(Blink(randy)) self.play( LaggedStartMap( FadeOutAndShiftDown, VGroup(description, *pis, steve), ), MoveToTarget(diagram, run_time=3), ApplyMethod( formula.scale, 1.5, {"about_edge": UR}, run_time=2.5, ), ) self.wait() kw = {"run_time": 2} self.play(diagram.set_prior, 0.1, **kw) self.play(diagram.set_prior, 0.6, **kw) self.play(diagram.set_likelihood, 0.5, **kw), self.play(diagram.set_antilikelihood, 0.1, **kw), self.wait() class WhoAreYou(Scene): def construct(self): words = OldTexText("Who are you?") self.add(words) class FadeInHeart(Scene): def construct(self): heart = SuitSymbol("hearts") self.play(FadeInFromDown(heart)) self.play(FadeOut(heart)) class ReprogrammingThought(Scene): CONFIG = { "camera_config": { "background_color": GREY_E, } } def construct(self): brain = SVGMobject("brain") brain.set_fill(GREY, 1) brain.set_sheen(1, UL) brain.set_stroke(width=0) arrow = DoubleArrow(ORIGIN, 3 * RIGHT) formula = get_bayes_formula() group = VGroup(brain, arrow, formula) group.arrange(RIGHT) group.center() q_marks = OldTex("???") q_marks.scale(1.5) q_marks.next_to(arrow, UP, SMALL_BUFF) kt = Group( ImageMobject("kahneman"), ImageMobject("tversky"), ) kt.arrange(RIGHT) kt.set_height(2) kt.to_corner(UR) brain_outline = brain.copy() brain_outline.set_fill(opacity=0) brain_outline.set_stroke(TEAL, 4) self.play(FadeIn(brain, RIGHT)) self.play( GrowFromCenter(arrow), LaggedStartMap(FadeInFromDown, q_marks[0]), run_time=1 ) self.play(FadeIn(formula, LEFT)) self.wait() kw = {"run_time": 1, "lag_ratio": 0.3} self.play(LaggedStartMap(FadeInFromDown, kt, **kw)) self.play(LaggedStartMap(FadeOut, kt, **kw)) self.wait() self.add(brain) self.play(ShowCreationThenFadeOut( brain_outline, lag_ratio=0.01, run_time=2 )) # Bubble bubble = ThoughtBubble() bubble.next_to(brain, UR, SMALL_BUFF) bubble.shift(2 * DOWN) diagram = BayesDiagram(0.25, 0.8, 0.5) diagram.set_height(2.5) diagram.move_to(bubble.get_bubble_center()) group = VGroup(brain, arrow, q_marks, formula) self.play( DrawBorderThenFill(VGroup(*reversed(bubble))), group.shift, 2 * DOWN, ) self.play(FadeIn(diagram)) self.wait() self.play( q_marks.scale, 1.5, q_marks.space_out_submobjects, 1.5, q_marks.set_opacity, 0, ) self.remove(q_marks) self.wait() # Move parts prior_outline = formula[7:12].copy() prior_outline.set_stroke(YELLOW, 5, background=True) like_outline = formula[12:18].copy() like_outline.set_stroke(BLUE, 5, background=True) self.play( FadeIn(prior_outline), ApplyMethod(diagram.set_prior, 0.5, run_time=2) ) self.play(FadeOut(prior_outline)) self.play( FadeIn(like_outline), ApplyMethod(diagram.set_likelihood, 0.2, run_time=2), ) self.play(FadeOut(like_outline)) self.wait() class MassOfEarthEstimates(GlimpseOfNextVideo): CONFIG = { "add_x_coords": False, "formula_position": 2 * UP + 0.5 * RIGHT, "dx": 0.05, } def setup(self): super().setup() earth = SVGMobject( file_name="earth", height=1.5, fill_color=BLACK, ) earth.set_stroke(width=0) # earth.set_stroke(BLACK, 1, background=True) circle = Circle( stroke_width=3, stroke_color=GREEN, fill_opacity=1, fill_color=BLUE_C, ) circle.replace(earth) earth.add_to_back(circle) earth.set_height(0.75) words = OldTexText("Mass of ") words.next_to(earth, LEFT) group = VGroup(words, earth) group.to_edge(DOWN).shift(2 * RIGHT) self.add(group) def get_formula(self): formula = OldTex( "p(M) p(\\text{data}|M) \\over p(\\text{data})", tex_to_color_map={ "M": HYPOTHESIS_COLOR, "\\text{data}": EVIDENCE_COLOR1, }, isolate=list("p(|)") ) formula.move_to(self.formula_position) return formula def prior(self, x, mu=6, sigma=1): factor = (1 / sigma / np.sqrt(TAU)) return factor * np.exp(-0.5 * ((x - mu) / sigma)**2) def likelihood(self, x): return self.prior(x, 5, 1) class ShowProgrammer(Scene): CONFIG = { "camera_config": { "background_color": GREY_E, } } def construct(self): programmer = SVGMobject(file_name="programmer") programmer.set_stroke(width=0) programmer.set_fill(GREY, 1) programmer.set_sheen(1, UL) programmer.set_height(3) programmer.to_corner(DL) self.play(FadeIn(programmer, DOWN)) self.wait() class BayesEndScene(PatreonEndScreen): CONFIG = { "specific_patrons": [ "Juan Benet", "Vassili Philippov", "Burt Humburg", "D. Sivakumar", "John Le", "Matt Russell", "Scott Gray", "soekul", "Steven Braun", "Tihan Seale", "Ali Yahya", "Arthur Zey", "dave nicponski", "Joseph Kelly", "Kaustuv DeBiswas", "Lambda AI Hardware", "Lukas Biewald", "Mark Heising", "Nicholas Cahill", "Peter Mcinerney", "Quantopian", "Scott Walter, Ph.D.", "Tauba Auerbach", "Yana Chernobilsky", "Yu Jun", "Lukas -krtek.net- Novy", "Britt Selvitelle", "Britton Finley", "David Gow", "J", "Jonathan Wilson", "Joseph John Cox", "Magnus Dahlström", "Matteo Delabre", "Randy C. Will", "Ray Hua Wu", "Ryan Atallah", "Luc Ritchie", "1stViewMaths", "Adam Dřínek", "Aidan Shenkman", "Alan Stein", "Alex Mijalis", "Alexis Olson", "Andreas Benjamin Brössel", "Andrew Busey", "Andrew Cary", "Andrew R. Whalley", "Anthony Turvey", "Antoine Bruguier", "Antonio Juarez", "Arjun Chakroborty", "Austin Goodman", "Avi Finkel", "Awoo", "Azeem Ansar", "AZsorcerer", "Barry Fam", "Bernd Sing", "Boris Veselinovich", "Bradley Pirtle", "Brian Staroselsky", "Calvin Lin", "Chaitanya Upmanu", "Charles Southerland", "Charlie N", "Chenna Kautilya", "Chris Connett", "Christian Kaiser", "Clark Gaebel", "Cooper Jones", "Corey Ogburn", "Danger Dai", "Daniel Herrera C", "Dave B", "Dave Kester", "David B. Hill", "David Clark", "David Pratt", "DeathByShrimp", "Delton Ding", "Dominik Wagner", "eaglle", "emptymachine", "Eric Younge", "Eryq Ouithaqueue", "Federico Lebron", "Fernando Via Canel", "Frank R. Brown, Jr.", "Giovanni Filippi", "Hal Hildebrand", "Hitoshi Yamauchi", "Ivan Sorokin", "j eduardo perez", "Jacob Baxter", "Jacob Harmon", "Jacob Hartmann", "Jacob Magnuson", "Jameel Syed", "James Liao", "Jason Hise", "Jayne Gabriele", "Jeff Linse", "Jeff Straathof", "John C. Vesey", "John Griffith", "John Haley", "John V Wertheim", "Jonathan Heckerman", "Josh Kinnear", "Joshua Claeys", "Kai-Siang Ang", "Kanan Gill", "Kartik Cating-Subramanian", "L0j1k", "Lee Redden", "Linh Tran", "Ludwig Schubert", "Magister Mugit", "Mark B Bahu", "Mark Mann", "Martin Price", "Mathias Jansson", "Matt Godbolt", "Matt Langford", "Matt Roveto", "Matthew Bouchard", "Matthew Cocke", "Michael Hardel", "Michael W White", "Mirik Gogri", "Mustafa Mahdi", "Márton Vaitkus", "Nikita Lesnikov", "Omar Zrien", "Owen Campbell-Moore", "Patrick Lucas", "Pedro Igor S. Budib", "Peter Ehrnstrom", "rehmi post", "Rex Godby", "Richard Barthel", "Ripta Pasay", "Rish Kundalia", "Roman Sergeychik", "Roobie", "SansWord Huang", "Sebastian Garcia", "Solara570", "Steven Siddals", "Stevie Metke", "Suthen Thomas", "Tal Einav", "Ted Suzman", "The Responsible One", "Thomas Roets", "Thomas Tarler", "Tianyu Ge", "Tom Fleming", "Tyler VanValkenburg", "Valeriy Skobelev", "Veritasium", "Vinicius Reis", "Xuanji Li", "Yavor Ivanov", "YinYangBalance.Asia", ], } class Thumbnail(Scene): def construct(self): diagram = BayesDiagram(0.25, 0.4, 0.1) diagram.set_height(3) diagram.add_brace_attrs() braces = VGroup( diagram.h_brace, diagram.he_brace, diagram.nhe_brace, ) diagram.add(*braces) kw = { "tex_to_color_map": { "H": YELLOW, "E": BLUE, "\\neg": RED, } } labels = VGroup( OldTex("P(H)", **kw), OldTex("P(E|H)", **kw), OldTex("P(E|\\neg H)", **kw), ) labels.scale(1) for label, brace, vect in zip(labels, braces, [DOWN, LEFT, RIGHT]): label.next_to(brace, vect) diagram.add(*labels) # diagram.set_height(6) diagram.to_edge(DOWN, buff=MED_SMALL_BUFF) diagram.shift(2 * LEFT) self.add(diagram) diagram.set_height(FRAME_HEIGHT - 1) diagram.center().to_edge(DOWN) for rect in diagram.evidence_split: rect.set_sheen(0.2, UL) return # Formula formula = get_bayes_formula() formula.scale(1.5) formula.to_corner(UL) frac = VGroup( diagram.he_rect.copy(), Line(ORIGIN, 4 * RIGHT).set_stroke(WHITE, 3), VGroup( diagram.he_rect.copy(), OldTex("+"), diagram.nhe_rect.copy(), ).arrange(RIGHT) ) frac.arrange(DOWN) equals = OldTex("=") equals.next_to(formula, RIGHT) frac.next_to(equals, RIGHT) self.add(formula) self.add(equals, frac) VGroup(formula, equals, frac).to_edge(UP, buff=SMALL_BUFF) class Thumbnail2(Scene): def construct(self): diagram = BayesDiagram(0.25, 0.4, 0.1) # Labels diagram.set_height(3) diagram.add_brace_attrs() braces = VGroup( diagram.h_brace, diagram.he_brace, diagram.nhe_brace, ) diagram.add(*braces) kw = { "tex_to_color_map": { "H": YELLOW, "E": BLUE, "\\neg": RED, }, "font_size": 24, } labels = VGroup( OldTex("P(H)", **kw), OldTex("P(E|H)", **kw), OldTex("P(E|\\neg H)", **kw), ) for label, brace, vect in zip(labels, braces, [DOWN, LEFT, RIGHT]): label.next_to(brace, vect, buff=SMALL_BUFF) diagram.add(*labels) # End labels diagram.set_height(5) diagram.to_edge(LEFT) diagram.to_edge(DOWN) self.add(diagram) frac = VGroup( diagram.he_rect.copy(), Line(LEFT, RIGHT).set_width(7), VGroup( diagram.he_rect.copy(), OldTex("+", font_size=120), diagram.nhe_rect.copy(), ).arrange(RIGHT) ).arrange(DOWN, buff=0.5) frac.set_width(5) frac.move_to(diagram, UP) frac.to_edge(RIGHT) self.add(frac) right_arrow = Arrow( diagram.get_right(), frac[1].get_left(), thickness=0.1, fill_color=GREEN ) words = OldTexText("This is Bayes' rule", font_size=108) words.to_edge(UP) arrow = Arrow( words, frac, thickness=0.1, ) arrow.scale(1.5, about_point=arrow.get_start()) self.add(words, arrow)
from manim_imports_ext import * from _2019.bayes.part1 import BayesDiagram from _2019.bayes.part1 import LibrarianIcon from _2019.bayes.part1 import Person from _2019.bayes.part1 import RandomnessVsProportions OUTPUT_DIRECTORY = "bayes/footnote" TEX_TO_COLOR_MAP = { "A": YELLOW, "B": BLUE, } MID_COLOR = interpolate_color(BLUE_D, YELLOW, 0.5) SICKLY_GREEN = "#9BBD37" def get_bayes_formula(): return OldTex( "P(A|B) = {P(A)P(B|A) \\over P(B)}", tex_to_color_map={ "A": YELLOW, "B": BLUE, }, isolate=list("P(|)") ) # Scenes class ThisIsAFootnote(TeacherStudentsScene): def construct(self): image = ImageMobject("bayes_thumbnail") image.set_height(2.5) rect = SurroundingRectangle(image, buff=0) rect.set_stroke(WHITE, 3) title = OldTexText("Bayes' theorem") title.match_width(image) title.next_to(image, UP) image_group = Group(rect, image, title) image_group.to_corner(UL) asterisk = OldTexText("*") asterisk.set_height(0.5) asterisk.set_stroke(BLACK, 3, background=True) asterisk.move_to(image.get_corner(UR), LEFT) formula = get_bayes_formula() formula.move_to(self.hold_up_spot, DOWN) pab = formula[:6] eq = formula[6] pa = formula[7:11] pba = formula[11:17] over = formula[17] pb = formula[18:23] # Show main video self.play( FadeInFromDown(image_group), self.change_students( "pondering", "hooray", "tease", look_at=image ) ) self.play( Write(asterisk), self.teacher.change, "speaking", ) self.play( self.change_students( "thinking", "erm", "thinking" ) ) self.wait(3) self.play( self.teacher.change, "raise_right_hand", FadeInFromDown(formula), self.change_students(*3 * ["pondering"]) ) self.wait() # Rearrange parts = VGroup( pb, pab, eq, pa, pba, ) parts.generate_target() parts.target.arrange(RIGHT, buff=SMALL_BUFF) parts.target.move_to(self.hold_up_spot) self.play( MoveToTarget(parts, path_arc=-30 * DEGREES), FadeOut(over), self.teacher.change, "pondering", ) self.wait() # Move to top p_both = OldTex( "P(A \\text{ and } B)", tex_to_color_map={"A": YELLOW, "B": BLUE}, ) eq2 = OldTex("=") full_equation = VGroup( pb, pab, eq, p_both, eq2, pa, pba ) full_equation.generate_target() full_equation.target.arrange(RIGHT, buff=SMALL_BUFF) full_equation.target.set_width(FRAME_WIDTH - 1) full_equation.target.center() full_equation.target.to_edge(UP) p_both.set_opacity(0) p_both.scale(0.2) p_both.move_to(eq) eq2.move_to(eq) self.play( MoveToTarget(full_equation), FadeOut(image_group, 2 * LEFT), FadeOut(asterisk, 2 * LEFT), self.teacher.look_at, 4 * UP, self.change_students( "thinking", "erm", "confused", look_at=4 * UP ) ) self.wait(2) class ShowTwoPerspectives(Scene): CONFIG = { "pa": 1 / 3, "pb": 1 / 4, "p_both": 1 / 6, "diagram_height": 4, } def construct(self): # Ask about intersection formula = self.get_formula() venn_diagram = self.get_venn_diagram() venn_diagram.next_to(formula, DOWN, LARGE_BUFF) arrow = Arrow( formula[3].get_bottom(), venn_diagram.get_center(), ) self.add(formula) self.play( formula[:3].set_opacity, 0.2, formula[-3:].set_opacity, 0.2, ) for i in (0, 1): self.play( FadeIn(venn_diagram[0][i]), Write(venn_diagram[1][i]), run_time=1, ) self.play(ShowCreation(arrow)) self.wait() # Think with respect to A diagram1 = self.get_diagram1() diagram1.evidence_split.set_opacity(0) diagram1.hypothesis_split.set_opacity(1) diagram1.to_edge(RIGHT, LARGE_BUFF) diagram1.refresh_braces() d1_line = DashedLine( diagram1.h_rect.get_corner(UR), diagram1.h_rect.get_corner(DR), ) d1_line.set_stroke(BLACK, 2) space_words = OldTexText( "Space of all\\\\possibilities" ) space_words.match_width(diagram1.square) space_words.scale(0.9) space_words.move_to(diagram1.square) space_words.set_fill(BLACK) space_outline = SurroundingRectangle(diagram1.square, buff=0) space_outline.set_stroke(WHITE, 10) self.play( FadeOut(venn_diagram[0][1]), FadeOut(venn_diagram[1][1]), FadeOut(arrow), formula[4:6].set_opacity, 1, ) diagram1.pa_label.update() self.play( FadeIn(diagram1.nh_rect), ReplacementTransform( venn_diagram[0][0], diagram1.h_rect, ), ReplacementTransform( venn_diagram[1][0], diagram1.pa_label.get_part_by_tex("A"), ), FadeIn(diagram1.h_brace), FadeIn(diagram1.pa_label[0]), FadeIn(diagram1.pa_label[2]), ShowCreation(d1_line), ) self.add(diagram1.pa_label) self.wait() self.play( FadeIn(space_words), ShowCreation(space_outline), ) self.play( FadeOut(space_words), FadeOut(space_outline), ) self.wait() # Show B part B_rects = VGroup(diagram1.he_rect, diagram1.nhe_rect) B_rects.set_opacity(1) B_rects.set_sheen(0.2, UL) diagram1.nhe_rect.set_fill(BLUE_D) diagram1.he_rect.set_fill(MID_COLOR) diagram1.save_state() B_rects.stretch(0.001, 1, about_edge=DOWN) diagram1.he_brace.save_state() diagram1.he_brace.stretch(0.001, 1, about_edge=DOWN) self.add(diagram1.he_brace, diagram1.pba_label) self.add(diagram1, d1_line) self.play( Restore(diagram1), Restore(diagram1.he_brace), VFadeIn(diagram1.he_brace), VFadeIn(diagram1.pba_label), formula.pba.set_opacity, 1, ) self.wait() # Show symmetric perspective diagram1_copy = diagram1.deepcopy() diagram2 = self.get_diagram2() d2_line = DashedLine( diagram2.b_rect.get_corner(UL), diagram2.b_rect.get_corner(UR), ) d2_line.set_stroke(BLACK, 2) for rect in [diagram2.ba_rect, diagram2.nba_rect]: rect.save_state() rect.stretch(0.001, 0, about_edge=LEFT) self.play( diagram1_copy.move_to, diagram2, formula.pb.set_opacity, 1, ) self.play( diagram1_copy.set_likelihood, self.pb, diagram1_copy.set_antilikelihood, self.pb, VFadeOut(diagram1_copy), FadeIn(diagram2), TransformFromCopy(formula.pb, diagram2.pb_label), FadeIn(diagram2.pb_brace), ShowCreation(d2_line), ) self.wait() self.play( formula.pab.set_opacity, 1, formula.eq1.set_opacity, 1, ) self.play( TransformFromCopy(formula.pab, diagram2.pab_label), FadeIn(diagram2.pab_brace), Restore(diagram2.ba_rect), Restore(diagram2.nba_rect), ) self.wait() def get_formula(self): kw = { "tex_to_color_map": { "A": YELLOW, "B": BLUE, } } parts = VGroup(*[ OldTex(tex, **kw) for tex in [ "P(B)", "P(A|B)", "=", "P(A \\text{ and } B)", "=", "P(A)", "P(B|A)", ] ]) attrs = [ "pb", "pab", "eq1", "p_both", "eq2", "pa", "pba" ] for attr, part in zip(attrs, parts): setattr(parts, attr, part) parts.arrange(RIGHT, buff=SMALL_BUFF), parts.set_width(FRAME_WIDTH - 1) parts.center().to_edge(UP) return parts def get_venn_diagram(self): c1 = Circle( radius=2.5, stroke_width=2, stroke_color=YELLOW, fill_opacity=0.5, fill_color=YELLOW, ) c1.flip(RIGHT) c1.rotate(3 * TAU / 8) c2 = c1.copy() c2.set_color(BLUE) c1.shift(LEFT) c2.shift(RIGHT) circles = VGroup(c1, c2) titles = VGroup( OldTex("A"), OldTex("B"), ) for title, circle, vect in zip(titles, circles, [UL, UR]): title.match_color(circle) title.scale(2) title.next_to( circle.get_boundary_point(vect), vect, buff=SMALL_BUFF ) return VGroup(circles, titles) def get_diagram1(self): likelihood = (self.p_both / self.pa) antilikelihood = (self.pb - self.p_both) / (1 - self.pa) diagram = BayesDiagram(self.pa, likelihood, antilikelihood) diagram.set_height(self.diagram_height) diagram.add_brace_attrs() kw = {"tex_to_color_map": TEX_TO_COLOR_MAP} diagram.pa_label = OldTex("P(A)", **kw) diagram.pba_label = OldTex("P(B|A)", **kw) diagram.pa_label.add_updater( lambda m: m.next_to(diagram.h_brace, DOWN, SMALL_BUFF), ) diagram.pba_label.add_updater( lambda m: m.next_to(diagram.he_brace, LEFT, SMALL_BUFF), ) return diagram def get_diagram2(self): pa = self.pa pb = self.pb p_both = self.p_both square = Square() square.set_stroke(WHITE, 1) square.set_fill(GREY_B, 1) square.set_height(self.diagram_height) b_rect = square.copy() b_rect.stretch(pb, 1, about_edge=DOWN) b_rect.set_fill(BLUE) b_rect.set_sheen(0.2, UL) nb_rect = square.copy() nb_rect.stretch(1 - pb, 1, about_edge=UP) ba_rect = b_rect.copy() ba_rect.stretch((p_both / pb), 0, about_edge=LEFT) ba_rect.set_fill(MID_COLOR) nba_rect = nb_rect.copy() nba_rect.stretch((pa - p_both) / (1 - pb), 0, about_edge=LEFT) nba_rect.set_fill(YELLOW) result = VGroup( square.set_opacity(0), b_rect, nb_rect, ba_rect, nba_rect, ) result.b_rect = b_rect result.nb_rect = nb_rect result.ba_rect = ba_rect result.nba_rect = nba_rect pb_brace = Brace(b_rect, LEFT, buff=SMALL_BUFF) pab_brace = Brace(ba_rect, DOWN, buff=SMALL_BUFF) kw = {"tex_to_color_map": TEX_TO_COLOR_MAP} pb_label = OldTex("P(B)", **kw) pab_label = OldTex("P(A|B)", **kw) pb_label.next_to(pb_brace, LEFT, SMALL_BUFF) pab_label.next_to(pab_brace, DOWN, SMALL_BUFF) result.pb_brace = pb_brace result.pab_brace = pab_brace result.pb_label = pb_label result.pab_label = pab_label VGroup( result, pb_brace, pab_brace, pb_label, pab_label, ).to_edge(LEFT) return result class Rearrange(ShowTwoPerspectives): def construct(self): formula = self.get_formula() pb, pab, eq1, p_both, eq2, pa, pba = formula over = OldTex("{\\qquad\\qquad \\over \\quad}") over.match_width(formula[:2]) eq3 = eq1.copy() new_line = VGroup( formula.pb, formula.pab, eq3, formula.pa, formula.pba, ) new_line.generate_target() new_line.target.arrange(RIGHT, buff=MED_SMALL_BUFF) new_line.target[0].shift(SMALL_BUFF * RIGHT) new_line.target[-1].shift(SMALL_BUFF * LEFT) new_line.target.center() eq3.set_opacity(0) eq1.generate_target() eq1.target.rotate(PI / 3) eq1.target.move_to(midpoint( p_both.get_corner(DL), new_line.target[0].get_corner(UR) )) eq2.generate_target() eq2.target.rotate(-PI / 3) eq2.target.move_to(midpoint( p_both.get_corner(DR), new_line.target[4].get_corner(UL) )) self.add(formula) self.play( MoveToTarget(new_line), MoveToTarget(eq1), MoveToTarget(eq2), ) self.wait() over.move_to(VGroup(pa, pba)) self.play( ApplyMethod( pb.next_to, over, DOWN, path_arc=30 * DEGREES, ), VGroup(pa, pba).next_to, over, UP, ShowCreation(over), FadeOut(VGroup(eq1, eq2)) ) self.wait(2) over.generate_target() over.target.next_to(eq3, LEFT) numer = VGroup(pb, pab) numer.generate_target() numer.target.arrange(RIGHT, buff=SMALL_BUFF) numer.target.next_to(over.target, UP) self.play(LaggedStart( MoveToTarget(over, path_arc=-30 * DEGREES), MoveToTarget(numer, path_arc=-30 * DEGREES), ApplyMethod(pa.next_to, over.target, DOWN), ApplyMethod(pba.next_to, eq3, RIGHT), lag_ratio=0.3, )) self.wait(2) # Numbers pb_brace = Brace(pb, UP, buff=SMALL_BUFF) pab_brace = Brace(pab, UP, buff=SMALL_BUFF) pa_brace = Brace(pa, DOWN, buff=SMALL_BUFF) pb_value = pb_brace.get_tex("(1/21)") pab_value = pab_brace.get_tex("(4/10)") pa_value = pa_brace.get_tex("(24/210)") braces = VGroup(pb_brace, pab_brace, pa_brace) values = VGroup(pb_value, pab_value, pa_value) self.play( LaggedStartMap(GrowFromCenter, braces, lag_ratio=0.3), LaggedStartMap(GrowFromCenter, values, lag_ratio=0.3), FadeOut(p_both), ) self.wait() # Replace symbols mag = SVGMobject(file_name="magnifying_glass") mag.set_stroke(width=0) mag.set_fill(GREY, 1) mag.set_sheen(1, UL) Bs = VGroup(*[ mob.get_part_by_tex("B") for mob in [pb, pab, pba] ]) As = VGroup(*[ mob.get_part_by_tex("A") for mob in [pab, pa, pba] ]) books = VGroup(*[ LibrarianIcon().replace(B, dim_to_match=0) for B in Bs ]) books.set_color(YELLOW) mags = VGroup(*[ mag.copy().replace(A) for A in As ]) self.play(LaggedStart(*[ ReplacementTransform(A, mag, path_arc=PI) for A, mag in zip(As, mags) ])) self.play(LaggedStart(*[ ReplacementTransform(B, book, path_arc=PI) for B, book in zip(Bs, books) ])) self.wait() class ClassLooking(TeacherStudentsScene): def construct(self): self.play( self.teacher.change, "pondering", self.change_students( "pondering", "confused", "sassy", look_at=self.screen, ), ) self.wait(5) self.play( self.teacher.change, "raise_right_hand", ) self.play( self.change_students( "thinking", "pondering", "pondering", look_at=self.hold_up_spot + 2 * UP, ) ) self.wait(3) class LandscapeOfTools(TeacherStudentsScene): def construct(self): group = self.get_formulas() bayes = group[0].copy() self.play( self.teacher.change, "raise_right_hand", self.change_students( *3 * ["confused"], look_at=group, ), FadeInFromDown(bayes), ) self.remove(bayes) self.play( ShowSubmobjectsOneByOne(group, remover=True), run_time=5 ) self.add(bayes) self.wait(2) bubble = self.students[0].get_bubble() self.add(bubble, bayes) self.play( bayes.move_to, bubble.get_bubble_center(), DrawBorderThenFill(bubble), self.teacher.change, "happy", self.change_students( "pondering", "erm", "erm", look_at=bubble, ) ) self.play_all_student_changes( "thinking", look_at=bayes, ) self.wait() self.play( FadeOut(bayes), bubble.set_fill, BLACK, 0.2, bubble.set_stroke, WHITE, 1, self.change_students( "pleading", "guilty", "guilty", ), self.teacher.change, "hesitant" ) self.wait(2) def get_formulas(self): group = VGroup( get_bayes_formula(), OldTex( "P(X = k) = {\\lambda^k \\over k!}", "e^{-\\lambda}", tex_to_color_map={ "k": YELLOW, "\\lambda": GREEN, } ), OldTex( "{1 \\over \\sigma\\sqrt{2\\pi}}", "e^{\\frac{1}{2}\\left({(x - \\mu) \\over \\sigma}\\right)^2}", tex_to_color_map={ "\\sigma": GREEN, "\\mu": BLUE, } ), OldTex( "P(X = k) =", "\\left({n \\over k}\\right)", "p^k(1-p)^{n-k}", tex_to_color_map={ "\\over": BLACK, "p": WHITE, "k": YELLOW, "n": BLUE, "k": GREEN } ), OldTex( "E[X + Y] = E[x] + E[y]" ), OldTex( "\\text{Var}(X + Y) = \\text{Var}(x) + \\text{Var}(y) + 2\\text{Cov}(X, Y)" ), OldTex( "H = \\sum_{i} -p_i \\log", "(p_i)", tex_to_color_map={ "p_i": YELLOW, } ), OldTex( "{n \\choose k}", "{B(k + \\alpha, n -k + \\beta) \\over B(\\alpha, \\beta)}", tex_to_color_map={ "\\alpha": BLUE, "\\beta": YELLOW, } ), OldTex( "P(d) = \\log_{10}\\left(1 + {1 \\over d}\\right)", tex_to_color_map={"d": BLUE}, ), OldTex( "\\text{Cov}(X, Y) = \\sum_{i, j} p({x}_i, {y}_j)({x}_i - \\mu_{x})({y}_j - \\mu_{y})", tex_to_color_map={ "{x}": BLUE, "{y}": RED, } ), ) group.move_to(self.hold_up_spot, DOWN) group.shift_onto_screen() return group class TemptingFormula(ShowTwoPerspectives, RandomnessVsProportions): def construct(self): # Show venn diagram kw = { "tex_to_color_map": TEX_TO_COLOR_MAP, "isolate": list("P()"), } formula = VGroup( OldTex("P(A \\text{ and } B)", **kw), OldTex("="), OldTex("P(A)P(B)", "\\,", "\\,", **kw), ) formula.arrange(RIGHT) formula.scale(1.5) formula.to_edge(UP) q_marks = OldTex("???")[0] q_marks.scale(1.25) q_marks.next_to(formula[1], UP, SMALL_BUFF) formula.save_state() for part in formula: part.set_x(0) formula[1:].set_opacity(0) and_part = formula[0][2:5].copy() venn = self.get_venn_diagram() venn.next_to(formula, DOWN, LARGE_BUFF) self.add(formula) for i in 0, 1: self.play( DrawBorderThenFill(venn[0][i]), FadeIn(venn[1][i]), ) self.play( and_part.scale, 0.5, and_part.move_to, venn, ) self.remove(and_part) venn.add(and_part) self.add(venn) self.wait() self.play(Restore(formula)) self.play(LaggedStartMap(FadeInFromDown, q_marks)) # 1 in 4 heart disease related deaths people = VGroup(*[Person() for x in range(4)]) people.arrange(RIGHT) people.set_height(2) people[0].set_color(RED) heart = SuitSymbol("hearts") heart.set_fill(BLACK) heart.set_height(0.25) heart.move_to(people[0]) heart.shift(0.2 * UR) people[0].add(heart) grid = self.get_grid(4, 4, height=4) grid.to_corner(DL, buff=LARGE_BUFF) both_square = grid[0][0].copy() people.generate_target() people.target.set_height(both_square.get_height() - SMALL_BUFF) left_people = people.target.copy() self.label_grid(grid, left_people, people.target) pairs = self.get_grid_entries(grid, left_people, people.target) for pair in pairs: pair.generate_target() pair.restore() pair = pairs[0].target.copy() prob = OldTex( "P(", "OO", ")", "= \\frac{1}{4} \\cdot \\frac{1}{4} = \\frac{1}{16}", ) pair.move_to(prob[1]) prob.submobjects[1] = pair prob.scale(1.5) prob.next_to(grid, RIGHT, LARGE_BUFF) self.play( FadeOut(venn), LaggedStartMap(FadeInFromDown, people), ) self.play(WiggleOutThenIn(heart)) self.wait() self.play( MoveToTarget(people), TransformFromCopy(people, left_people), Write(grid), FadeIn(prob[:3]), run_time=1, ) self.add(both_square, pairs) self.play( LaggedStartMap(MoveToTarget, pairs, path_arc=30 * DEGREES), both_square.set_stroke, YELLOW, 5, both_square.set_fill, YELLOW, 0.25, ) self.play(FadeIn(prob[3:])) self.wait() grid_group = VGroup(grid, people, left_people, both_square, pairs) # Coin flips ht_grid = self.get_grid(2, 2, height=3) ht_grid.move_to(grid) ht_labels = VGroup(OldTexText("H"), OldTexText("T")) ht_labels.set_submobject_colors_by_gradient(BLUE, RED) ht_labels.scale(2) left_ht_labels = ht_labels.copy() self.label_grid(ht_grid, left_ht_labels, ht_labels) ht_pairs = self.get_grid_entries(ht_grid, left_ht_labels, ht_labels) ht_both_square = ht_grid[1][1].copy() ht_both_square.set_stroke(YELLOW, 5) ht_both_square.set_fill(YELLOW, 0.25) ht_prob = OldTex( "P(\\text{TT}) = \\frac{1}{2} \\cdot \\frac{1}{2} = \\frac{1}{4}", tex_to_color_map={"\\text{TT}": RED} ) ht_prob.scale(1.5) ht_prob.next_to(ht_grid, RIGHT, LARGE_BUFF) ht_grid_group = VGroup( ht_grid, ht_labels, left_ht_labels, ht_both_square, ht_pairs, ) self.play( FadeOut(grid_group), FadeOut(prob), FadeIn(ht_grid_group), FadeIn(ht_prob), ) self.wait() # Dice throws dice_grid = self.get_grid(6, 6, height=4) dice_grid.set_stroke(WHITE, 1) dice_grid.move_to(grid) dice_labels = self.get_die_faces() dice_labels.set_height(0.5) left_dice_labels = dice_labels.copy() self.label_grid(dice_grid, left_dice_labels, dice_labels) dice_pairs = self.get_grid_entries(dice_grid, left_dice_labels, dice_labels) for pair in dice_pairs: pair.space_out_submobjects(0.9) pair.scale(0.75) dice_both_square = dice_grid[0][0].copy() dice_both_square.set_stroke(YELLOW, 5) dice_both_square.set_fill(YELLOW, 0.25) dice_prob = OldTex( "P(", "OO", ") = \\frac{1}{6} \\cdot \\frac{1}{6} = \\frac{1}{36}", ) pair = dice_pairs[0].copy() pair.scale(1.5) pair.move_to(dice_prob[1]) dice_prob.submobjects[1] = pair dice_prob.scale(1.5) dice_prob.next_to(dice_grid, RIGHT, LARGE_BUFF) dice_grid_group = VGroup( dice_grid, dice_labels, left_dice_labels, dice_both_square, dice_pairs, ) self.play( FadeOut(ht_grid_group), FadeOut(ht_prob), FadeIn(dice_grid_group), FadeIn(dice_prob), ) self.wait() # Show correlation self.play( FadeOut(dice_grid_group), FadeOut(dice_prob), FadeIn(prob), FadeIn(grid_group), ) self.wait() cross = Cross(prob[3]) for pair in pairs: pair.add_updater(lambda m: m.move_to(m.square)) for person, square in zip(people, grid[0]): person.square = square person.add_updater(lambda m: m.next_to(m.square, UP)) row_rect = SurroundingRectangle( VGroup(grid[0], left_people[0]), buff=SMALL_BUFF ) row_rect.set_stroke(RED, 3) self.play(ShowCreation(cross)) self.play( FadeOut(prob), FadeOut(cross), ) self.play( ShowCreation(row_rect) ) self.wait() self.play( grid[0][0].stretch, 2, 0, {"about_edge": LEFT}, grid[0][1:].stretch, 2 / 3, 0, {"about_edge": RIGHT}, both_square.stretch, 2, 0, {"about_edge": LEFT}, *[ ApplyMethod(grid[i][0].stretch, 2 / 3, 0, {"about_edge": LEFT}) for i in range(1, 4) ], *[ ApplyMethod(grid[i][1:].stretch, 10 / 9, 0, {"about_edge": RIGHT}) for i in range(1, 4) ], ) self.wait() grid_group.add(row_rect) # Show correct formula cross = Cross(formula) cross.set_stroke(RED, 6) real_rhs = OldTex("P(A)P(B|A)", **kw) real_rhs.scale(1.5) real_formula = VGroup(*formula[:2].copy(), real_rhs) real_formula.shift(1.5 * DOWN) real_rhs.next_to(real_formula[:2], RIGHT) real_rect = SurroundingRectangle(real_formula, buff=SMALL_BUFF) real_rect.set_stroke(GREEN) check = OldTex("\\checkmark") check.set_color(GREEN) check.match_height(real_formula) check.next_to(real_rect, LEFT) small_cross = Cross(check) small_cross.match_style(cross) small_cross.next_to(formula, LEFT) self.play( ShowCreationThenFadeAround(formula), FadeOut(q_marks), ) self.play(ShowCreation(cross)) self.wait() self.play( TransformFromCopy(formula, real_formula), grid_group.scale, 0.7, grid_group.to_corner, DL, ) self.play( FadeIn(real_rect), FadeIn(check, RIGHT), ) self.wait() # Show other grid ht_grid_group.scale(0.7) ht_grid_group.next_to(grid_group, RIGHT, buff=1.5) dice_grid_group.scale(0.7) dice_grid_group.next_to(ht_grid_group, RIGHT, buff=1.5) Bs = VGroup(formula[2][4:], real_formula[2][4:]) B_rect = SurroundingRectangle( Bs, stroke_color=BLUE, # buff=SMALL_BUFF, buff=0, ) B_rect.scale(1.1, about_edge=LEFT) B_rect.set_fill(BLUE, 0.5) B_rect.set_stroke(width=0) big_rect = SurroundingRectangle( VGroup(ht_grid_group, dice_grid_group), buff=MED_LARGE_BUFF, color=BLUE, ) # B_rect.get_points()[0] += 0.2 * RIGHT # B_rect.get_points()[-1] += 0.2 * RIGHT # B_rect.get_points()[3] += 0.2 * LEFT # B_rect.get_points()[4] += 0.2 * LEFT # B_rect.make_jagged() self.play(FadeIn(ht_grid_group)) self.play(FadeIn(dice_grid_group)) self.wait() self.add(B_rect, Bs.copy()) self.play( FadeIn(B_rect), FadeIn(big_rect), Transform(cross, small_cross), FadeOut(real_rect), ) self.wait() def get_grid(self, n, m, height=4): grid = VGroup(*[ VGroup( *[Square() for x in range(m)] ).arrange(RIGHT, buff=0) for y in range(n) ]).arrange(DOWN, buff=0) grid.set_height(height) grid.set_stroke(WHITE, 2) return grid def label_grid(self, grid, row_labels, col_labels): for label, row in zip(row_labels, grid): label.next_to(row, LEFT) for label, square in zip(col_labels, grid[0]): label.next_to(square, UP) def get_grid_entries(self, grid, row_labels, col_labels): pairs = VGroup() for i, p1 in enumerate(row_labels): for j, p2 in enumerate(col_labels): pair = VGroup(p1, p2).copy() pair.save_state() pair.scale(0.6) pair.arrange(RIGHT, buff=0.05) pair.square = grid[i][j] pair.move_to(grid[i][j]) pairs.add(pair) return pairs class DiseaseBayes(Scene): def construct(self): formula = OldTex( "P(D | +) = {P(D) P(+ | D) \\over P(+)}", tex_to_color_map={ "D": YELLOW, "+": BLUE, }, isolate=list("P(|)=") ) formula.scale(2.5) Ds = formula.get_parts_by_tex("D") for D in Ds: index = formula.index_of_part(D) pi = Randolph() pi.change("sick") pi.set_color(SICKLY_GREEN) pi.replace(D) formula.submobjects[index] = pi pi.get_tex = lambda: "" lhs = formula[:6] lhs.save_state() lhs.center() sicky = lhs[2] sick_words = OldTexText( "You are sick", tex_to_color_map={ "sick": SICKLY_GREEN, }, ) sick_words.scale(1.5) sick_words.next_to(sicky, UP, 2 * LARGE_BUFF) positive_words = OldTexText("Positive test result") positive_words.scale(1.5) positive_words.set_color(BLUE) positive_words.next_to(lhs[4], DOWN, 2 * LARGE_BUFF) sick_arrow = Arrow(sicky.get_top(), sick_words.get_bottom()) positive_arrow = Arrow(lhs[4].get_bottom(), positive_words.get_top()) arrow_groups = VGroup( sick_words, sick_arrow, positive_words, positive_arrow, ) sicky.save_state() sicky.change("happy") sicky.set_color(BLUE) self.play(FadeInFromDown(lhs)) self.play( Restore(sicky), GrowArrow(sick_arrow), FadeInFromDown(sick_words), ) self.play( GrowArrow(positive_arrow), FadeIn(positive_words, UP), ) self.wait(2) self.play( Restore(lhs), MaintainPositionRelativeTo(arrow_groups, lhs), FadeIn(formula[6]), ) # Prior def get_formula_slice(*indices): return VGroup(*[formula[i] for i in indices]) self.play( TransformFromCopy( get_formula_slice(0, 1, 2, 5), get_formula_slice(8, 9, 10, 11), ), ) # Likelihood lhs_copy = formula[:6].copy() likelihood = formula[12:18] run_time = 1 self.play( lhs_copy.next_to, likelihood, UP, run_time=run_time, ) self.play( Swap(lhs_copy[2], lhs_copy[4]), run_time=run_time, ) self.play( lhs_copy.move_to, likelihood, run_time=run_time, ) # Evidence self.play( ShowCreation(formula.get_part_by_tex("\\over")), TransformFromCopy( get_formula_slice(12, 13, 14, 17), get_formula_slice(19, 20, 21, 22), ), ) self.wait() class EndScreen(Scene): CONFIG = { "camera_config": { "background_color": GREY_E } } def construct(self): width = (475 / 1280) * FRAME_WIDTH height = width * (323 / 575) video_rect = Rectangle( width=width, height=height, fill_color=BLACK, fill_opacity=1, ) video_rect.shift(UP) date = OldTexText( "Solution will be\\\\" "posted", "1/20/19", ) date[1].set_color(YELLOW) date.set_width(video_rect.get_width() - 2 * MED_SMALL_BUFF) date.move_to(video_rect) handle = OldTexText("@3blue1brown") handle.next_to(video_rect, DOWN, MED_LARGE_BUFF) self.add(video_rect, handle) self.add(AnimatedBoundary(video_rect)) self.wait(20)
from manim_imports_ext import * from _2019.clacks.question import * from _2018.div_curl import ShowTwoPopulations OUTPUT_DIRECTORY = "clacks/solution1" class FromPuzzleToSolution(MovingCameraScene): def construct(self): big_rect = FullScreenFadeRectangle() big_rect.set_fill(GREY_D, 0.5) self.add(big_rect) rects = VGroup(ScreenRectangle(), ScreenRectangle()) rects.set_height(3) rects.arrange(RIGHT, buff=2) titles = VGroup( OldTexText("Puzzle"), OldTexText("Solution"), ) images = Group( ImageMobject("BlocksAndWallExampleMass16"), ImageMobject("AnalyzeCircleGeometry"), ) for title, rect, image in zip(titles, rects, images): title.scale(1.5) title.next_to(rect, UP) image.replace(rect) self.add(image, rect, title) frame = self.camera_frame frame.save_state() self.play( frame.replace, images[0], run_time=3 ) self.wait() self.play(Restore(frame, run_time=3)) self.play( frame.replace, images[1], run_time=3, ) self.wait() class BlocksAndWallExampleMass16(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 16, "velocity": -1.5, }, }, "wait_time": 25, } class Mass16WithElasticLabel(Mass1e1WithElasticLabel): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 16, } }, } class BlocksAndWallExampleMass64(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 64, "velocity": -1.5, }, }, "wait_time": 25, } class BlocksAndWallExampleMass1e4(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e4, "velocity": -1.5, }, }, "wait_time": 25, } class BlocksAndWallExampleMassMillion(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e6, "velocity": -0.9, "label_text": "$100^{3}$ kg" }, }, "wait_time": 30, "million_fade_time": 4, "min_time_between_sounds": 0.002, } def setup(self): super().setup() self.add_million_label() def add_million_label(self): first_label = self.blocks.block1.label brace = Brace(first_label[:-2], UP, buff=SMALL_BUFF) new_label = OldTex("1{,}000{,}000") new_label.next_to(brace, UP, buff=SMALL_BUFF) new_label.add(brace) new_label.set_color(YELLOW) def update_label(label): d_time = self.get_time() - self.million_fade_time opacity = smooth(d_time) label.set_fill(opacity=d_time) new_label.add_updater(update_label) first_label.add(new_label) class BlocksAndWallExampleMassTrillion(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e12, "velocity": -1, }, }, "wait_time": 30, "min_time_between_sounds": 0.001, } class First6DigitsOfPi(DigitsOfPi): CONFIG = {"n_digits": 6} class FavoritesInDescription(Scene): def construct(self): words = OldTexText("(See the description for \\\\ some favorites)") words.scale(1.5) self.add(words) class V1EqualsV2Line(Scene): def construct(self): line = Line(LEFT, 7 * RIGHT) eq = OldTex("v_1", "=", "v_2") eq.set_color_by_tex("v_", RED) eq.next_to(RIGHT, UR, SMALL_BUFF) self.play( Write(eq, run_time=1), ShowCreation(line), ) self.wait() class PhaseSpaceTitle(Scene): def construct(self): title = OldTexText("Phase space") title.scale(1.5) title.to_edge(UP) rect = ScreenRectangle(height=6) rect.next_to(title, DOWN) self.add(rect) self.play(Write(title, run_time=1)) self.wait() class AskAboutFindingNewVelocities(Scene): CONFIG = { "floor_y": -3, "wall_x": -6.5, "wall_height": 7, "block1_config": { "mass": 10, "fill_color": BLUE_E, "velocity": -1, }, "block2_config": {"mass": 1}, "block1_start_x": 7, "block2_start_x": 3, "v_arrow_scale_value": 1.0, "is_halted": False, } def setup(self): self.add_clack_sound_file() def construct(self): self.add_clack_sound_file() self.add_floor() self.add_wall() self.add_blocks() self.add_velocity_labels() self.ask_about_transfer() self.show_ms_and_vs() self.show_value_on_equations() def add_clack_sound_file(self): self.clack_file = os.path.join(SOUND_DIR, "clack.wav") def add_floor(self): floor = self.floor = Line( self.wall_x * RIGHT, (FRAME_WIDTH / 2) * RIGHT, ) floor.shift(self.floor_y * UP) self.add(floor) def add_wall(self): wall = self.wall = Wall(height=self.wall_height) wall.move_to( self.wall_x * RIGHT + self.floor_y * UP, DR, ) self.add(wall) def add_blocks(self): block1 = self.block1 = Block(**self.block1_config) block2 = self.block2 = Block(**self.block2_config) blocks = self.blocks = VGroup(block1, block2) block1.move_to(self.block1_start_x * RIGHT + self.floor_y * UP, DOWN) block2.move_to(self.block2_start_x * RIGHT + self.floor_y * UP, DOWN) self.add_velocity_phase_space_point() # Add arrows for block in blocks: arrow = Vector(self.block_to_v_vector(block)) arrow.set_color(RED) arrow.set_stroke(BLACK, 1, background=True) arrow.move_to(block.get_center(), RIGHT) block.arrow = arrow block.add(arrow) block.v_label = DecimalNumber( block.velocity, num_decimal_places=2, background_stroke_width=2, ) block.v_label.set_color(RED) block.add(block.v_label) # Add updater blocks.add_updater(self.update_blocks) self.add( blocks, block2.arrow, block1.arrow, block2.v_label, block1.v_label, ) def add_velocity_phase_space_point(self): self.vps_point = VectorizedPoint([ np.sqrt(self.block1.mass) * self.block1.velocity, np.sqrt(self.block2.mass) * self.block2.velocity, 0 ]) def add_velocity_labels(self): v_labels = self.get_next_velocity_labels() self.add(v_labels) def ask_about_transfer(self): energy_expression, momentum_expression = \ self.get_energy_and_momentum_expressions() energy_words = OldTexText("Conservation of energy:") energy_words.move_to(UP) energy_words.to_edge(LEFT, buff=1.5) momentum_words = OldTexText("Conservation of momentum:") momentum_words.next_to( energy_words, DOWN, buff=0.7, ) energy_expression.next_to(energy_words, RIGHT, MED_LARGE_BUFF) momentum_expression.next_to(energy_expression, DOWN) momentum_expression.next_to(momentum_words, RIGHT) velocity_labels = self.all_velocity_labels randy = Randolph(height=2) randy.next_to(velocity_labels, DR) randy.save_state() randy.fade(1) # Up to collisions self.go_through_next_collision(include_velocity_label_animation=True) self.play( randy.restore, randy.change, "pondering", velocity_labels[0], ) self.halt() self.play(randy.look_at, velocity_labels[-1]) self.play(Blink(randy)) self.play(randy.change, "confused") self.play(Blink(randy)) self.wait() self.play( FadeIn(energy_words, RIGHT), FadeInFromDown(energy_expression), FadeOut(randy), ) self.wait() self.play( FadeIn(momentum_words, RIGHT), FadeInFromDown(momentum_expression) ) self.wait() self.energy_expression = energy_expression self.energy_words = energy_words self.momentum_expression = momentum_expression self.momentum_words = momentum_words def show_ms_and_vs(self): block1 = self.block1 block2 = self.block2 energy_expression = self.energy_expression momentum_expression = self.momentum_expression for block in self.blocks: block.shift_onto_screen() m1_labels = VGroup( block1.label, energy_expression.get_part_by_tex("m_1"), momentum_expression.get_part_by_tex("m_1"), ) m2_labels = VGroup( block2.label, energy_expression.get_part_by_tex("m_2"), momentum_expression.get_part_by_tex("m_2"), ) v1_labels = VGroup( block1.v_label, energy_expression.get_part_by_tex("v_1"), momentum_expression.get_part_by_tex("v_1"), ) v2_labels = VGroup( block2.v_label, energy_expression.get_part_by_tex("v_2"), momentum_expression.get_part_by_tex("v_2"), ) label_groups = VGroup( m1_labels, m2_labels, v1_labels, v2_labels, ) for group in label_groups: group.rects = VGroup(*map( SurroundingRectangle, group )) for group in label_groups: self.play(LaggedStartMap( ShowCreation, group.rects, lag_ratio=0.8, run_time=1, )) self.play(FadeOut(group.rects)) def show_value_on_equations(self): energy_expression = self.energy_expression momentum_expression = self.momentum_expression energy_text = VGroup(energy_expression, self.energy_words) momentum_text = VGroup(momentum_expression, self.momentum_words) block1 = self.block1 block2 = self.block2 block1.save_state() block2.save_state() v_terms, momentum_v_terms = [ VGroup(*[ expr.get_part_by_tex("v_{}".format(d)) for d in [1, 2] ]) for expr in [energy_expression, momentum_expression] ] v_braces = VGroup(*[ Brace(term, UP, buff=SMALL_BUFF) for term in v_terms ]) v_decimals = VGroup(*[DecimalNumber(0) for x in range(2)]) def update_v_decimals(v_decimals): values = self.get_velocities() for decimal, value, brace in zip(v_decimals, values, v_braces): decimal.set_value(value) decimal.next_to(brace, UP, SMALL_BUFF) update_v_decimals(v_decimals) energy_const_brace, momentum_const_brace = [ Brace( expr.get_part_by_tex("const"), UP, buff=SMALL_BUFF, ) for expr in [energy_expression, momentum_expression] ] sqrt_m_vect = np.array([ np.sqrt(self.block1.mass), np.sqrt(self.block2.mass), 0 ]) def get_energy(): return 0.5 * get_norm(self.vps_point.get_location())**2 def get_momentum(): return np.dot(self.vps_point.get_location(), sqrt_m_vect) energy_decimal = DecimalNumber(get_energy()) energy_decimal.next_to(energy_const_brace, UP, SMALL_BUFF) momentum_decimal = DecimalNumber(get_momentum()) momentum_decimal.next_to(momentum_const_brace, UP, SMALL_BUFF) VGroup( energy_const_brace, energy_decimal, momentum_const_brace, momentum_decimal, ).set_color(YELLOW) self.play( ShowCreationThenFadeAround(energy_expression), momentum_text.set_fill, {"opacity": 0.25}, FadeOut(self.all_velocity_labels), ) self.play(*[ *map(GrowFromCenter, v_braces), *map(VFadeIn, v_decimals), GrowFromCenter(energy_const_brace), FadeIn(energy_decimal), ]) energy_decimal.add_updater( lambda m: m.set_value(get_energy()) ) v_decimals.add_updater(update_v_decimals) self.add(v_decimals) self.unhalt() self.vps_point.save_state() for x in range(8): self.go_through_next_collision() energy_decimal.clear_updaters() momentum_decimal.set_value(get_momentum()) self.halt() self.play(*[ momentum_text.set_fill, {"opacity": 1}, FadeOut(energy_text), FadeOut(energy_const_brace), FadeOut(energy_decimal), GrowFromCenter(momentum_const_brace), FadeIn(momentum_decimal), *[ ApplyMethod(b.next_to, vt, UP, SMALL_BUFF) for b, vt in zip(v_braces, momentum_v_terms) ], ]) self.unhalt() self.vps_point.restore() momentum_decimal.add_updater( lambda m: m.set_value(get_momentum()) ) momentum_decimal.add_updater( lambda m: m.next_to(momentum_const_brace, UP, SMALL_BUFF) ) for x in range(9): self.go_through_next_collision() self.wait(10) # Helpers def get_energy_and_momentum_expressions(self): tex_to_color_map = { "v_1": RED_B, "v_2": RED_B, "m_1": BLUE_C, "m_2": BLUE_C, } energy_expression = OldTex( "\\frac{1}{2} m_1 (v_1)^2 + ", "\\frac{1}{2} m_2 (v_2)^2 = ", "\\text{const.}", tex_to_color_map=tex_to_color_map, ) momentum_expression = OldTex( "m_1 v_1 + m_2 v_2 =", "\\text{const.}", tex_to_color_map=tex_to_color_map ) return VGroup( energy_expression, momentum_expression, ) def go_through_next_collision(self, include_velocity_label_animation=False): block2 = self.block2 if block2.velocity >= 0: self.wait_until(self.blocks_are_hitting) self.add_sound(self.clack_file) self.transfer_momentum() edge = RIGHT else: self.wait_until(self.block2_is_hitting_wall) self.add_sound(self.clack_file) self.reflect_block2() edge = LEFT anims = [Flash(block2.get_edge_center(edge))] if include_velocity_label_animation: anims.append(self.get_next_velocity_labels_animation()) self.play(*anims, run_time=0.5) def get_next_velocity_labels_animation(self): return FadeIn( self.get_next_velocity_labels(), LEFT, run_time=0.5 ) def get_next_velocity_labels(self, v1=None, v2=None): new_labels = self.get_velocity_labels(v1, v2) if hasattr(self, "all_velocity_labels"): arrow = Vector(RIGHT) arrow.next_to(self.all_velocity_labels) new_labels.next_to(arrow, RIGHT) new_labels.add(arrow) else: self.all_velocity_labels = VGroup() self.all_velocity_labels.add(new_labels) return new_labels def get_velocity_labels(self, v1=None, v2=None): default_vs = self.get_velocities() v1 = v1 or default_vs[0] v2 = v2 or default_vs[1] labels = VGroup( OldTex("v_1 = {:.2f}".format(v1)), OldTex("v_2 = {:.2f}".format(v2)), ) labels.arrange( DOWN, buff=MED_SMALL_BUFF, aligned_edge=LEFT, ) labels.scale(0.9) for label in labels: label[:2].set_color(RED) labels.next_to(self.wall, RIGHT) labels.to_edge(UP, buff=MED_SMALL_BUFF) return labels def update_blocks(self, blocks, dt): for block, velocity in zip(blocks, self.get_velocities()): block.velocity = velocity if not self.is_halted: block.shift(block.velocity * dt * RIGHT) center = block.get_center() block.arrow.put_start_and_end_on( center, center + self.block_to_v_vector(block), ) max_height = 0.25 block.v_label.set_value(block.velocity) if block.v_label.get_height() > max_height: block.v_label.set_height(max_height) block.v_label.next_to( block.arrow.get_start(), UP, buff=SMALL_BUFF, ) return blocks def block_to_v_vector(self, block): return block.velocity * self.v_arrow_scale_value * RIGHT def blocks_are_hitting(self): x1 = self.block1.get_left()[0] x2 = self.block2.get_right()[0] buff = 0.01 return (x1 < x2 + buff) def block2_is_hitting_wall(self): x2 = self.block2.get_left()[0] buff = 0.01 return (x2 < self.wall_x + buff) def get_velocities(self): m1 = self.block1.mass m2 = self.block2.mass vps_coords = self.vps_point.get_location() return [ vps_coords[0] / np.sqrt(m1), vps_coords[1] / np.sqrt(m2), ] def transfer_momentum(self): m1 = self.block1.mass m2 = self.block2.mass theta = np.arctan(np.sqrt(m2 / m1)) self.reflect_block2() self.vps_point.rotate(2 * theta, about_point=ORIGIN) def reflect_block2(self): self.vps_point.get_points()[:, 1] *= -1 def halt(self): self.is_halted = True def unhalt(self): self.is_halted = False class IntroduceVelocityPhaseSpace(AskAboutFindingNewVelocities): CONFIG = { "wall_height": 1.5, "floor_y": -3.5, "block1_start_x": 5, "block2_start_x": 0, "axes_config": { "x_axis_config": { "x_min": -5.5, "x_max": 6, }, "y_axis_config": { "x_min": -3.5, "x_max": 4, }, "axis_config": { "unit_size": 0.7, }, }, "momentum_line_scale_factor": 4, } def construct(self): self.add_wall_floor_and_blocks() self.show_two_equations() self.draw_axes() self.draw_ellipse() self.rescale_axes() self.show_starting_point() self.show_initial_collide() self.ask_about_where_to_land() self.show_conservation_of_momentum_equation() self.show_momentum_line() self.reiterate_meaning_of_line_and_circle() self.reshow_first_jump() self.show_bounce_off_wall() self.show_reflection_about_x() self.show_remaining_collisions() def add_wall_floor_and_blocks(self): self.add_floor() self.add_wall() self.add_blocks() self.halt() def show_two_equations(self): equations = self.get_energy_and_momentum_expressions() equations.arrange(DOWN, buff=LARGE_BUFF) equations.shift(UP) v1_terms, v2_terms = v_terms = VGroup(*[ VGroup(*[ expr.get_parts_by_tex(tex) for expr in equations ]) for tex in ("v_1", "v_2") ]) for eq in equations: eq.highlighted_copy = eq.copy() eq.highlighted_copy.set_fill(opacity=0) eq.highlighted_copy.set_stroke(YELLOW, 3) self.add(equations) self.play( ShowCreation(equations[0].highlighted_copy), run_time=0.75, ) self.play( FadeOut(equations[0].highlighted_copy), ShowCreation(equations[1].highlighted_copy), run_time=0.75, ) self.play( FadeOut(equations[1].highlighted_copy), run_time=0.75, ) self.play(LaggedStartMap( Indicate, v_terms, lag_ratio=0.75, rate_func=there_and_back, )) self.wait() self.equations = equations def draw_axes(self): equations = self.equations energy_expression, momentum_expression = equations axes = self.axes = Axes(**self.axes_config) axes.to_edge(UP, buff=SMALL_BUFF) axes.set_stroke(width=2) # Axes labels x_axis_labels = VGroup( OldTex("x = ", "v_1"), OldTex("x = ", "\\sqrt{m_1}", "\\cdot", "v_1"), ) y_axis_labels = VGroup( OldTex("y = ", "v_2"), OldTex("y = ", "\\sqrt{m_2}", "\\cdot", "v_2"), ) axis_labels = self.axis_labels = VGroup(x_axis_labels, y_axis_labels) for label_group in axis_labels: for label in label_group: label.set_color_by_tex("v_", RED) label.set_color_by_tex("m_", BLUE) for label in x_axis_labels: label.next_to(axes.x_axis.get_right(), UP) for label in y_axis_labels: label.next_to(axes.y_axis.get_top(), DR) # Introduce axes and labels self.play( equations.scale, 0.8, equations.to_corner, UL, {"buff": MED_SMALL_BUFF}, Write(axes), ) self.wait() self.play( momentum_expression.set_fill, {"opacity": 0.2}, Indicate(energy_expression, scale_factor=1.05), ) self.wait() for n in range(2): tex = "v_{}".format(n + 1) self.play( TransformFromCopy( energy_expression.get_part_by_tex(tex), axis_labels[n][0].get_part_by_tex(tex), ), FadeInFromDown(axis_labels[n][0][0]), ) # Show vps_dot vps_dot = self.vps_dot = Dot(color=RED) vps_dot.set_stroke(BLACK, 2, background=True) vps_dot.add_updater( lambda m: m.move_to(axes.coords_to_point( *self.get_velocities() )) ) vps_point = self.vps_point vps_point.save_state() kwargs = { "path_arc": PI / 3, "run_time": 2, } target_locations = [ 6 * RIGHT + 2 * UP, 6 * RIGHT + 2 * DOWN, 6 * LEFT + 1 * UP, ] self.add(vps_dot) for target_location in target_locations: self.play( vps_point.move_to, target_location, **kwargs, ) self.play(Restore(vps_point, **kwargs)) self.wait() def draw_ellipse(self): vps_dot = self.vps_dot vps_point = self.vps_point axes = self.axes energy_expression = self.equations[0] ellipse = self.ellipse = Circle(color=YELLOW) ellipse.set_stroke(BLACK, 5, background=True) ellipse.rotate(PI) mass_ratio = self.block1.mass / self.block2.mass ellipse.replace( Polygon(*[ axes.coords_to_point(x, y * np.sqrt(mass_ratio)) for x, y in [(1, 0), (0, 1), (-1, 0), (0, -1)] ]), stretch=True ) self.play(Indicate(energy_expression, scale_factor=1.05)) self.add(ellipse, vps_dot) self.play( ShowCreation(ellipse), Rotating(vps_point, about_point=ORIGIN), run_time=6, rate_func=lambda t: smooth(t, 3), ) self.wait() def rescale_axes(self): ellipse = self.ellipse axis_labels = self.axis_labels equations = self.equations vps_point = self.vps_point vps_dot = self.vps_dot vps_dot.clear_updaters() vps_dot.add_updater( lambda m: m.move_to(ellipse.get_left()) ) mass_ratio = self.block1.mass / self.block2.mass brief_circle = ellipse.copy() brief_circle.stretch(np.sqrt(mass_ratio), 0) brief_circle.set_stroke(WHITE, 2) xy_equation = self.xy_equation = OldTex( "\\frac{1}{2}", "\\left(", "x^2", "+", "y^2", "\\right)", "=", "\\text{const.}" ) xy_equation.scale(0.8) xy_equation.next_to(equations[0], DOWN) self.play(ShowCreationThenFadeOut(brief_circle)) for i, labels, block in zip(it.count(), axis_labels, self.blocks): self.play(ShowCreationThenFadeAround(labels[0])) self.play( ReplacementTransform(labels[0][0], labels[1][0]), ReplacementTransform(labels[0][-1], labels[1][-1]), FadeInFromDown(labels[1][1:-1]), ellipse.stretch, np.sqrt(block.mass), i, ) self.wait() vps_dot.clear_updaters() vps_dot.add_updater( lambda m: m.move_to(self.axes.coords_to_point( *self.vps_point.get_location()[:2] )) ) self.play( FadeIn(xy_equation, UP), FadeOut(equations[1]) ) self.wait() curr_x = vps_point.get_location()[0] for x in [0.5 * curr_x, 2 * curr_x, curr_x]: axes_center = self.axes.coords_to_point(0, 0) self.play( vps_point.move_to, x * RIGHT, UpdateFromFunc( ellipse, lambda m: m.set_width( 2 * get_norm( vps_dot.get_center() - axes_center, ), ).move_to(axes_center) ), run_time=2, ) self.wait() def show_starting_point(self): vps_dot = self.vps_dot block1, block2 = self.blocks self.unhalt() self.wait(3) self.halt() self.play(ShowCreationThenFadeAround(vps_dot)) self.wait() def show_initial_collide(self): self.unhalt() self.go_through_next_collision() self.wait() self.halt() self.wait() def ask_about_where_to_land(self): self.play( Rotating( self.vps_point, about_point=ORIGIN, run_time=6, rate_func=lambda t: smooth(t, 3), ), ) self.wait(2) def show_conservation_of_momentum_equation(self): equations = self.equations energy_expression, momentum_expression = equations momentum_expression.set_fill(opacity=1) momentum_expression.shift(MED_SMALL_BUFF * UP) momentum_expression.shift(MED_SMALL_BUFF * LEFT) xy_equation = self.xy_equation momentum_xy_equation = self.momentum_xy_equation = OldTex( "\\sqrt{m_1}", "x", "+", "\\sqrt{m_2}", "y", "=", "\\text{const.}", ) momentum_xy_equation.set_color_by_tex("m_", BLUE) momentum_xy_equation.scale(0.8) momentum_xy_equation.next_to( momentum_expression, DOWN, buff=MED_LARGE_BUFF, aligned_edge=RIGHT, ) self.play( FadeOut(xy_equation), energy_expression.set_fill, {"opacity": 0.2}, FadeInFromDown(momentum_expression) ) self.play(ShowCreationThenFadeAround(momentum_expression)) self.wait() self.play(FadeIn(momentum_xy_equation, UP)) self.wait() def show_momentum_line(self): vps_dot = self.vps_dot m1 = self.block1.mass m2 = self.block2.mass line = Line(np.sqrt(m2) * LEFT, np.sqrt(m1) * DOWN) line.scale(self.momentum_line_scale_factor) line.set_stroke(GREEN, 3) line.move_to(vps_dot) slope_label = OldTex( "\\text{Slope =}", "-\\sqrt{\\frac{m_1}{m_2}}" ) slope_label.scale(0.8) slope_label.next_to(vps_dot, LEFT, LARGE_BUFF) slope_arrow = Arrow( slope_label.get_right(), line.point_from_proportion(0.45), buff=SMALL_BUFF, ) slope_group = VGroup(line, slope_label, slope_arrow) foreground_mobs = VGroup( self.equations[1], self.momentum_xy_equation, self.blocks, self.vps_dot ) for mob in foreground_mobs: if isinstance(mob, Tex): mob.set_stroke(BLACK, 3, background=True) self.add(line, *foreground_mobs) self.play(ShowCreation(line)) self.play( FadeIn(slope_label, RIGHT), GrowArrow(slope_arrow), ) self.wait() self.add(slope_group, *foreground_mobs) self.play(slope_group.shift, 4 * RIGHT, run_time=3) self.play(slope_group.shift, 5 * LEFT, run_time=3) self.play( slope_group.shift, RIGHT, run_time=1, rate_func=lambda t: t**4, ) self.wait() self.momentum_line = line self.slope_group = slope_group def reiterate_meaning_of_line_and_circle(self): line_vect = self.momentum_line.get_vector() vps_point = self.vps_point for x in [0.25, -0.5, 0.25]: self.play( vps_point.shift, x * line_vect, run_time=2 ) self.wait() self.play(Rotating( vps_point, about_point=ORIGIN, rate_func=lambda t: smooth(t, 3), )) self.wait() def reshow_first_jump(self): vps_point = self.vps_point curr_point = vps_point.get_location() start_point = get_norm(curr_point) * LEFT for n in range(8): vps_point.move_to( [start_point, curr_point][n % 2] ) self.wait(0.5) self.wait() def show_bounce_off_wall(self): self.unhalt() self.go_through_next_collision() self.halt() def show_reflection_about_x(self): vps_point = self.vps_point curr_location = vps_point.get_location() old_location = np.array(curr_location) old_location[1] *= -1 # self.play( # ApplyMethod( # self.block2.move_to, self.wall.get_corner(DR), DL, # path_arc=30 * DEGREES, # ) # ) for n in range(4): self.play( vps_point.move_to, [old_location, curr_location][n % 2] ) self.wait() group = VGroup( self.ellipse, self.lines[-1], self.vps_dot.copy().clear_updaters() ) for x in range(2): self.play( Rotate( group, PI, RIGHT, about_point=self.axes.coords_to_point(0, 0) ), ) self.remove(group[-1]) def show_remaining_collisions(self): line = self.momentum_line # slope_group = self.slope_group vps_dot = self.vps_dot axes = self.axes slope = np.sqrt(self.block2.mass / self.block1.mass) end_region = Polygon( axes.coords_to_point(0, 0), axes.coords_to_point(10, 0), axes.coords_to_point(10, slope * 10), stroke_width=0, fill_color=GREEN, fill_opacity=0.3 ) self.unhalt() for x in range(7): self.go_through_next_collision() if x == 0: self.halt() self.play(line.move_to, vps_dot) self.wait() self.unhalt() self.play(FadeIn(end_region)) self.go_through_next_collision() self.wait(5) # Helpers def add_update_line(self, func): if not hasattr(self, "lines"): self.lines = VGroup() if hasattr(self, "vps_dot"): old_vps_point = self.vps_dot.get_center() func() self.vps_dot.update() new_vps_point = self.vps_dot.get_center() line = Line(old_vps_point, new_vps_point) line.set_stroke(WHITE, 2) self.add(line) self.lines.add(line) else: func() def transfer_momentum(self): self.add_update_line(super().transfer_momentum) def reflect_block2(self): self.add_update_line(super().reflect_block2) class IntroduceVelocityPhaseSpaceWith16(IntroduceVelocityPhaseSpace): CONFIG = { "block1_config": { "mass": 16, "velocity": -0.5, }, "momentum_line_scale_factor": 0, } class SimpleRect(Scene): def construct(self): self.add(Rectangle(width=6, height=2, color=WHITE)) class SurprisedRandy(Scene): def construct(self): randy = Randolph() self.play(FadeIn(randy)) self.play(randy.change, "surprised", 3 * UR) self.play(Blink(randy)) self.wait() self.play(randy.change, "pondering", 3 * UR) self.play(Blink(randy)) self.wait(2) self.play(FadeOut(randy)) class HuntForPi(TeacherStudentsScene): def construct(self): self.student_says( "Hunt for $\\pi$!", bubble_config={"direction": LEFT}, target_mode="hooray" ) self.play_all_student_changes( "hooray", added_anims=[self.teacher.change, "happy"] ) self.wait() class StretchBySqrt10(Scene): def construct(self): arrow = DoubleArrow(2 * LEFT, 2 * RIGHT) arrow.tip[1].shift(0.05 * LEFT) value = OldTex("\\sqrt{10}") value.next_to(arrow, UP) arrow.save_state() arrow.stretch(0, 0) self.play( Restore(arrow), Write(value, run_time=1), ) self.wait() class XCoordNegative(Scene): def construct(self): rect = Rectangle(height=4, width=4) rect.set_stroke(width=0) rect.set_fill(RED, 0.5) rect.save_state() rect.stretch(0, 0, about_edge=RIGHT) self.play(Restore(rect)) self.wait() class YCoordZero(Scene): def construct(self): rect = Rectangle(height=4, width=8) rect.set_stroke(width=0) rect.set_fill(WHITE, 0.5) rect.save_state() self.play( rect.stretch, 0.01, 1, rect.set_fill, {"opacity": 1} ) self.wait() class CircleDiagramFromSlidingBlocks(Scene): CONFIG = { "BlocksAndWallSceneClass": BlocksAndWallExampleMass1e1, "circle_config": { "radius": 2, "stroke_color": YELLOW, "stroke_width": 3, }, "lines_style": { "stroke_color": WHITE, "stroke_width": 2, }, "axes_config": { "style": { "stroke_color": GREY_B, "stroke_width": 1, }, "width": 5, "height": 4.5, }, "end_zone_style": { "stroke_width": 0, "fill_color": GREEN, "fill_opacity": 0.3, }, "show_dot": True, "show_vector": False, } def construct(self): sliding_blocks_scene = self.BlocksAndWallSceneClass( show_flash_animations=False, write_to_movie=False, wait_time=0, file_writer_config={ "output_directory": ".", } ) blocks = sliding_blocks_scene.blocks times = [pair[1] for pair in blocks.clack_data] self.mass_ratio = 1 / blocks.mass_ratio self.show_circle_lines( times=times, slope=(-1 / np.sqrt(blocks.mass_ratio)) ) def show_circle_lines(self, times, slope): circle = self.get_circle() axes = self.get_axes() lines = self.get_lines(circle.radius, slope) end_zone = self.get_end_zone() dot = Dot(color=RED, radius=0.06) dot.move_to(lines[0].get_start()) vector = Vector(lines[0].get_start()) vector.set_color(RED) vector.add_updater(lambda v: v.put_start_and_end_on( ORIGIN, dot.get_center() )) vector.set_stroke(BLACK, 2, background=True) dot.set_opacity(int(self.show_dot)) vector.set_opacity(int(self.show_vector)) self.add(end_zone, axes, circle, dot, vector) last_time = 0 for time, line in zip(times, lines): if time > 300: time = last_time + 1 self.wait(time - last_time) last_time = time dot.move_to(line.get_end()) self.add(line, dot, vector) self.wait() def get_circle(self): circle = Circle(**self.circle_config) circle.rotate(PI) # Nice to have start point on left return circle def get_axes(self): config = self.axes_config axes = VGroup( Line(LEFT, RIGHT).set_width(config["width"]), Line(DOWN, UP).set_height(config["height"]) ) axes.set_style(**config["style"]) return axes def get_lines(self, radius, slope): theta = np.arctan(-1 / slope) n_clacks = int(PI / theta) points = [] for n in range(n_clacks + 1): theta_mult = (n + 1) // 2 angle = 2 * theta * theta_mult if n % 2 == 0: angle *= -1 new_point = radius * np.array([ -np.cos(angle), -np.sin(angle), 0 ]) points.append(new_point) lines = VGroup(*[ Line(p1, p2) for p1, p2 in zip(points, points[1:]) ]) lines.set_style(**self.lines_style) return lines def get_end_zone(self): slope = 1 / np.sqrt(self.mass_ratio) x = self.axes_config["width"] / 2 zone = Polygon( ORIGIN, x * RIGHT, x * RIGHT + slope * x * UP, ) zone.set_style(**self.end_zone_style) return zone class CircleDiagramFromSlidingBlocksSameMass(CircleDiagramFromSlidingBlocks): CONFIG = { "BlocksAndWallSceneClass": BlocksAndWallExampleSameMass } class CircleDiagramFromSlidingBlocksSameMass1e1(CircleDiagramFromSlidingBlocks): CONFIG = { "BlocksAndWallSceneClass": BlocksAndWallExampleMass1e1 } class CircleDiagramFromSlidingBlocks1e2(CircleDiagramFromSlidingBlocks): CONFIG = { "BlocksAndWallSceneClass": BlocksAndWallExampleMass1e2 } class CircleDiagramFromSlidingBlocks1e4(CircleDiagramFromSlidingBlocks): CONFIG = { "BlocksAndWallSceneClass": BlocksAndWallExampleMass1e4 } class AnnouncePhaseDiagram(CircleDiagramFromSlidingBlocks): def construct(self): pd_words = OldTexText("Phase diagram") pd_words.scale(1.5) pd_words.move_to(self.hold_up_spot, DOWN) pd_words_border = pd_words.copy() pd_words_border.set_stroke(YELLOW, 2) pd_words_border.set_fill(opacity=0) simple_words = OldTexText("Simple but powerful") simple_words.next_to(pd_words, UP, LARGE_BUFF) simple_words.shift(LEFT) simple_words.set_color(BLUE) simple_arrow = Arrow( simple_words.get_bottom(), pd_words.get_top(), color=simple_words.get_color(), ) self.play( self.teacher.change, "raise_right_hand", FadeInFromDown(pd_words) ) self.play_student_changes( "pondering", "thinking", "pondering", added_anims=[ShowCreationThenFadeOut(pd_words_border)] ) self.wait() self.play( FadeIn(simple_words, RIGHT), GrowArrow(simple_arrow), self.teacher.change, "hooray", ) self.play_student_changes( "thinking", "happy", "thinking", ) self.wait(3) class AnalyzeCircleGeometry(CircleDiagramFromSlidingBlocks, MovingCameraScene): CONFIG = { "mass_ratio": 16, "circle_config": { "radius": 3, }, "axes_config": { "width": FRAME_WIDTH, "height": FRAME_HEIGHT, }, "lines_style": { "stroke_width": 2, }, } def construct(self): self.add_mass_ratio_label() self.add_circle_with_lines() self.show_equal_arc_lengths() self.use_arc_lengths_to_count() self.focus_on_three_points() self.show_likewise_for_all_jumps() self.drop_arc_for_each_hop() self.try_adding_one_more_arc() self.zoom_out() def add_mass_ratio_label(self, mass_ratio=None): mass_ratio = mass_ratio or self.mass_ratio mass_ratio_label = OldTexText( "Mass ratio =", "{:,} : 1".format(mass_ratio) ) mass_ratio_label.to_corner(UL, buff=MED_SMALL_BUFF) self.add(mass_ratio_label) self.mass_ratio_label = mass_ratio_label def add_circle_with_lines(self): circle = self.get_circle() axes = self.get_axes() axes_labels = self.get_axes_labels(axes) slope = -np.sqrt(self.mass_ratio) lines = self.get_lines( radius=circle.radius, slope=slope, ) end_zone = self.get_end_zone() end_zone_words = OldTexText("End zone") end_zone_words.set_height(0.25) end_zone_words.next_to(ORIGIN, UP, SMALL_BUFF) end_zone_words.to_edge(RIGHT, buff=MED_SMALL_BUFF) end_zone_words.set_color(GREEN) self.add( axes, axes_labels, circle, end_zone, end_zone_words, ) self.play(ShowCreation(lines, run_time=3, rate_func=linear)) self.wait() self.set_variables_as_attrs( circle, axes, lines, end_zone, end_zone_words, ) def show_equal_arc_lengths(self): circle = self.circle radius = circle.radius theta = self.theta = np.arctan(1 / np.sqrt(self.mass_ratio)) n_arcs = int(PI / (2 * theta)) lower_arcs = VGroup(*[ Arc( start_angle=(PI + n * 2 * theta), angle=(2 * theta), radius=radius ) for n in range(n_arcs + 1) ]) lower_arcs[0::2].set_color(RED) lower_arcs[1::2].set_color(BLUE) upper_arcs = lower_arcs.copy() upper_arcs.rotate(PI, axis=RIGHT, about_point=ORIGIN) upper_arcs[0::2].set_color(BLUE) upper_arcs[1::2].set_color(RED) all_arcs = VGroup(*it.chain(*zip(lower_arcs, upper_arcs))) if int(PI / theta) % 2 == 1: all_arcs.remove(all_arcs[-1]) arc_copies = lower_arcs.copy() for arc_copy in arc_copies: arc_copy.generate_target() for arc in arc_copies: arc.target.rotate(-(arc.start_angle - PI + theta)) equal_signs = VGroup(*[ OldTex("=") for x in range(len(lower_arcs)) ]) equal_signs.scale(0.8) for sign in equal_signs: sign.generate_target() movers = VGroup(*it.chain(*zip( arc_copies, equal_signs ))) movers.remove(movers[-1]) mover_targets = VGroup(*[mover.target for mover in movers]) mover_targets.arrange(RIGHT, buff=SMALL_BUFF) mover_targets.next_to(ORIGIN, DOWN) mover_targets.to_edge(LEFT) equal_signs.scale(0) equal_signs.fade(1) equal_signs.move_to(mover_targets) all_arcs.save_state() for arc in all_arcs: arc.rotate(90 * DEGREES) arc.fade(1) arc.set_stroke(width=20) self.play(Restore( all_arcs, lag_ratio=0.5, run_time=2, )) self.wait() self.play(LaggedStartMap(MoveToTarget, movers)) self.wait() self.arcs_equation = movers self.lower_arcs = lower_arcs self.upper_arcs = upper_arcs self.all_arcs = all_arcs def use_arc_lengths_to_count(self): all_arcs = self.all_arcs lines = self.lines arc_counts = VGroup() for n, arc in enumerate(all_arcs): count_mob = Integer(n + 1) count_mob.scale(0.75) buff = SMALL_BUFF if len(all_arcs) > 100: count_mob.scale(0.1) count_mob.set_stroke(WHITE, 0.25) buff = 0.4 * SMALL_BUFF point = arc.point_from_proportion(0.5) count_mob.next_to(point, normalize(point), buff) arc_counts.add(count_mob) self.play( FadeOut(lines), FadeOut(all_arcs), FadeOut(self.arcs_equation), ) self.play( ShowIncreasingSubsets(all_arcs), ShowIncreasingSubsets(lines), ShowIncreasingSubsets(arc_counts), run_time=5, rate_func=bezier([0, 0, 1, 1]) ) self.wait() for group in all_arcs, arc_counts: targets = VGroup() for elem in group: elem.generate_target() targets.add(elem.target) targets.space_out_submobjects(1.2) kwargs = { "rate_func": there_and_back, "run_time": 3, } self.play( LaggedStartMap(MoveToTarget, all_arcs, **kwargs), LaggedStartMap(MoveToTarget, arc_counts, **kwargs), ) self.arc_counts = arc_counts def focus_on_three_points(self): lines = self.lines arcs = self.all_arcs arc_counts = self.arc_counts theta = self.theta arc = arcs[4] lines.save_state() line_pair = lines[3:5] lines_to_fade = VGroup(*lines[:3], *lines[5:]) three_points = [ line_pair[0].get_start(), line_pair[1].get_start(), line_pair[1].get_end(), ] three_dots = VGroup(*map(Dot, three_points)) three_dots.set_color(RED) theta_arc = Arc( radius=1, start_angle=-90 * DEGREES, angle=theta ) theta_arc.shift(three_points[1]) theta_label = OldTex("\\theta") theta_label.next_to(theta_arc, DOWN, SMALL_BUFF) center_lines = VGroup( Line(three_points[0], ORIGIN), Line(ORIGIN, three_points[2]), ) center_lines.match_style(line_pair) two_theta_arc = Arc( radius=1, start_angle=(center_lines[0].get_angle() + PI), angle=2 * theta ) two_theta_label = OldTex("2\\theta") arc_center = two_theta_arc.point_from_proportion(0.5) two_theta_label.next_to( arc_center, normalize(arc_center), SMALL_BUFF ) two_theta_label.shift(SMALL_BUFF * RIGHT) to_fade = VGroup(arc_counts, arcs, lines_to_fade) self.play( LaggedStartMap( FadeOut, VGroup(*to_fade.family_members_with_points()) ) ) lines_to_fade.fade(1) self.play(FadeInFromLarge(three_dots[0])) self.play(TransformFromCopy(*three_dots[:2])) self.play(TransformFromCopy(*three_dots[1:3])) self.wait() self.play( ShowCreation(theta_arc), FadeIn(theta_label, UP) ) self.wait() self.play( line_pair.set_stroke, WHITE, 1, TransformFromCopy(line_pair, center_lines), TransformFromCopy(theta_arc, two_theta_arc), TransformFromCopy(theta_label, two_theta_label), ) self.wait() self.play( TransformFromCopy(two_theta_arc, arc), two_theta_label.move_to, 2.7 * arc_center, ) self.wait() self.three_dots = three_dots self.theta_group = VGroup(theta_arc, theta_label) self.center_lines_group = VGroup( center_lines, two_theta_arc, ) self.two_theta_label = two_theta_label def show_likewise_for_all_jumps(self): lines = self.lines arcs = self.all_arcs every_other_line = lines[::2] self.play( Restore( lines, lag_ratio=0.5, run_time=2 ), FadeOut(self.center_lines_group), FadeOut(self.three_dots), ) self.play(LaggedStartMap( ApplyFunction, every_other_line, lambda line: ( lambda l: l.scale(10 / l.get_length()).set_stroke(BLUE, 3), line ) )) self.play(Restore(lines)) self.wait() # Shift theta label last_point = lines[3].get_end() last_arc = arcs[4] two_theta_label = self.two_theta_label theta_group_copy = self.theta_group.copy() for line, arc in zip(lines[5:10:2], arcs[6:11:2]): new_point = line.get_end() arc_point = arc.point_from_proportion(0.5) self.play( theta_group_copy.shift, new_point - last_point, two_theta_label.move_to, 1.1 * arc_point, FadeIn(arc), FadeOut(last_arc), ) self.wait() last_point = new_point last_arc = arc self.play( FadeOut(theta_group_copy), FadeOut(two_theta_label), FadeOut(last_arc), ) self.wait() def drop_arc_for_each_hop(self): lines = self.lines arcs = self.all_arcs two_theta_labels = VGroup() wedges = VGroup() for arc in arcs: label = OldTex("2\\theta") label.scale(0.8) label.move_to(1.1 * arc.point_from_proportion(0.5)) two_theta_labels.add(label) wedge = arc.copy() wedge.add_line_to(ORIGIN) wedge.add_line_to(wedge.get_points()[0]) wedge.set_stroke(width=0) wedge.set_fill(arc.get_color(), 0.2) wedges.add(wedge) self.remove(lines) for line, arc, label, wedge in zip(lines, arcs, two_theta_labels, wedges): self.play( ShowCreation(line), FadeIn(arc, normalize(arc.get_center())), FadeIn(label, normalize(arc.get_center())), FadeIn(wedge), ) self.wedges = wedges self.two_theta_labels = two_theta_labels def try_adding_one_more_arc(self): wedges = self.wedges theta = self.theta last_wedge = wedges[-1] new_wedge = last_wedge.copy() new_wedge.set_color(PURPLE) new_wedge.set_stroke(WHITE, 1) self.play(FadeIn(new_wedge)) for angle in [-2 * theta, 4 * DEGREES, -2 * DEGREES]: self.play(Rotate(new_wedge, angle, about_point=ORIGIN)) self.wait() self.play( new_wedge.shift, 10 * RIGHT, rate_func=running_start, path_arc=-30 * DEGREES, ) self.remove(new_wedge) def zoom_out(self): frame = self.camera_frame self.play( frame.scale, 2, {"about_point": (TOP + RIGHT_SIDE)}, run_time=3 ) self.wait() # Helpers def get_axes_labels(self, axes): axes_labels = VGroup( OldTex("x = ", "\\sqrt{m_1}", "\\cdot", "v_1"), OldTex("y = ", "\\sqrt{m_2}", "\\cdot", "v_2"), ) for label in axes_labels: label.set_height(0.4) axes_labels[0].next_to(ORIGIN, DOWN, SMALL_BUFF) axes_labels[0].to_edge(RIGHT, MED_SMALL_BUFF) axes_labels[1].next_to(ORIGIN, RIGHT, SMALL_BUFF) axes_labels[1].to_edge(UP, SMALL_BUFF) return axes_labels class InscribedAngleTheorem(Scene): def construct(self): self.add_title() self.show_circle() self.let_point_vary() def add_title(self): title = OldTexText("Inscribed angle theorem") title.scale(1.5) title.to_edge(UP) self.add(title) self.title = title def show_circle(self): # Boy is this over engineered... circle = self.circle = Circle( color=BLUE, radius=2, ) center_dot = Dot(circle.get_center(), color=WHITE) self.add(circle, center_dot) angle_trackers = self.angle_trackers = VGroup( ValueTracker(TAU / 4), ValueTracker(PI), ValueTracker(-TAU / 4), ) def get_point(angle): return circle.point_from_proportion( (angle % TAU) / TAU ) def get_dot(angle): dot = Dot(get_point(angle)) dot.set_color(RED) dot.set_stroke(BLACK, 3, background=True) return dot def get_dots(): return VGroup(*[ get_dot(at.get_value()) for at in angle_trackers ]) def update_labels(labels): center = circle.get_center() for dot, label in zip(dots, labels): label.move_to( center + 1.2 * (dot.get_center() - center) ) def get_lines(): lines = VGroup(*[ Line(d1.get_center(), d2.get_center()) for d1, d2 in zip(dots, dots[1:]) ]) lines.set_stroke(WHITE, 3) return lines def get_center_lines(): points = [ dots[0].get_center(), circle.get_center(), dots[2].get_center(), ] lines = VGroup(*[ Line(p1, p2) for p1, p2 in zip(points, points[1:]) ]) lines.set_stroke(GREY_B, 3) return lines def get_angle_label(lines, tex, reduce_angle=True): a1 = (lines[0].get_angle() + PI) % TAU a2 = lines[1].get_angle() diff = (a2 - a1) if reduce_angle: diff = ((diff + PI) % TAU) - PI point = lines[0].get_end() arc = Arc( start_angle=a1, angle=diff, radius=0.5, ) arc.shift(point) arc_center = arc.point_from_proportion(0.5) label = OldTex(tex) vect = (arc_center - point) vect = (0.3 + get_norm(vect)) * normalize(vect) label.move_to(point + vect) return VGroup(arc, label) def get_theta_label(): return get_angle_label(lines, "\\theta") def get_2theta_label(): return get_angle_label(center_lines, "2\\theta", False) dots = get_dots() lines = get_lines() center_lines = get_center_lines() labels = VGroup(*[ OldTex("P_{}".format(n + 1)) for n in range(3) ]) update_labels(labels) theta_label = get_theta_label() two_theta_label = get_2theta_label() self.play( FadeInFromDown(labels[0]), FadeInFromLarge(dots[0]), ) self.play( TransformFromCopy(*labels[:2]), TransformFromCopy(*dots[:2]), ShowCreation(lines[0]), ) self.play( ShowCreation(lines[1]), TransformFromCopy(*labels[1:3]), TransformFromCopy(*dots[1:3]), Write(theta_label), ) self.wait() # Add updaters labels.add_updater(update_labels) dots.add_updater(lambda m: m.become(get_dots())) lines.add_updater(lambda m: m.become(get_lines())) center_lines.add_updater(lambda m: m.become(get_center_lines())) theta_label.add_updater(lambda m: m.become(get_theta_label())) two_theta_label.add_updater(lambda m: m.become(get_2theta_label())) self.add(labels, lines, dots, theta_label) # Further animations self.play( angle_trackers[0].set_value, TAU / 8, ) self.play( angle_trackers[2].set_value, -TAU / 8, ) self.wait() center_lines.update() two_theta_label.update() self.play( TransformFromCopy(lines.copy().clear_updaters(), center_lines), TransformFromCopy(theta_label.copy().clear_updaters(), two_theta_label), ) self.wait() self.add(center_lines, two_theta_label) def let_point_vary(self): p1_tracker, p2_tracker, p3_tracker = self.angle_trackers kwargs = {"run_time": 2} for angle in [TAU / 4, 3 * TAU / 4]: self.play( p2_tracker.set_value, angle, **kwargs ) self.wait() self.play( p1_tracker.set_value, PI, **kwargs ) self.wait() self.play( p3_tracker.set_value, TAU / 3, **kwargs ) self.wait() self.play( p2_tracker.set_value, 7 * TAU / 8, **kwargs ) self.wait() class SimpleSlopeLabel(Scene): def construct(self): label = OldTex( "\\text{Slope}", "=", "-\\frac{\\sqrt{m_1}}{\\sqrt{m_2}}" ) vector = Vector(DOWN + 2 * LEFT, color=WHITE) vector.move_to(label[0].get_bottom(), UR) vector.shift(SMALL_BUFF * DOWN) self.play( Write(label), GrowArrow(vector), ) self.wait() class AddTwoThetaManyTimes(Scene): def construct(self): expression = OldTex( "2\\theta", "+", "2\\theta", "+", "2\\theta", "+", "\\cdots", "+", "2\\theta", "<", "2\\pi", ) expression.to_corner(UL) brace = Brace(expression[:-2], DOWN) question = brace.get_text("Max number of times?") question.set_color(YELLOW) central_question_group = self.get_central_question() simplified, lil_brace, new_question = central_question_group central_question_group.next_to(question, DOWN, LARGE_BUFF) new_question.align_to(question, LEFT) for n in range(5): self.add(expression[:2 * n + 1]) self.wait(0.25) self.play( FadeIn(expression[-2:], LEFT), GrowFromCenter(brace), FadeIn(question, UP) ) self.wait(3) self.play( TransformFromCopy(expression[:-2], simplified[:3]), TransformFromCopy(expression[-2:], simplified[3:]), TransformFromCopy(brace, lil_brace), ) self.play(Write(new_question)) self.wait() self.central_question_group = central_question_group self.show_example() def get_central_question(self, brace_vect=DOWN): expression = OldTex( "N", "\\cdot", "\\theta", "<", "\\pi" ) N = expression[0] N.set_color(BLUE) brace = Brace(N, brace_vect, buff=SMALL_BUFF) question = brace.get_text( "Maximal integer?", ) question.set_color(YELLOW) result = VGroup(expression, brace, question) result.to_corner(UL) return result def show_example(self): equation = self.get_changable_equation(0.01, n_decimal_places=2) expression, brace, question = self.central_question_group N_mob, dot_theta_eq, rhs, comp_pi = equation equation.next_to(expression, DOWN, 2, aligned_edge=LEFT) self.play( TransformFromCopy(expression[0], N_mob), TransformFromCopy(expression[1:4], dot_theta_eq), TransformFromCopy(expression[4], rhs), TransformFromCopy(expression[4], comp_pi), ) self.wait() self.play( ChangeDecimalToValue(N_mob, 314, run_time=5) ) self.wait() self.play(ChangeDecimalToValue(N_mob, 315)) self.wait() self.play(ChangeDecimalToValue(N_mob, 314)) self.wait() self.play(ShowCreationThenFadeAround(N_mob)) # def get_changable_equation(self, value, tex_string=None, n_decimal_places=10): int_mob = Integer(1) int_mob.set_color(BLUE) formatter = "({:0." + str(n_decimal_places) + "f})" tex_string = tex_string or formatter.format(value) tex_mob = OldTex("\\cdot", tex_string, "=") rhs = DecimalNumber(value, num_decimal_places=n_decimal_places) def align_number(mob): y0 = mob[0].get_center()[1] y1 = tex_mob[1][1:-1].get_center()[1] mob.shift((y1 - y0) * UP) int_mob.add_updater( lambda m: m.next_to(tex_mob, LEFT, SMALL_BUFF) ) int_mob.add_updater(align_number) rhs.add_updater( lambda m: m.set_value(value * int_mob.get_value()) ) rhs.add_updater( lambda m: m.next_to(tex_mob, RIGHT, SMALL_BUFF) ) rhs.add_updater(align_number) def get_comp_pi(): if rhs.get_value() < np.pi: result = OldTex("< \\pi") result.set_color(GREEN) elif rhs.get_value() > np.pi: result = OldTex("> \\pi") result.set_color(RED) else: result = OldTex("= \\pi") result.next_to(rhs, RIGHT, 2 * SMALL_BUFF) result[1].scale(1.5, about_edge=LEFT) return result comp_pi = always_redraw(get_comp_pi) return VGroup(int_mob, tex_mob, rhs, comp_pi) class AskAboutTheta(TeacherStudentsScene): def construct(self): self.student_says( "But what is $\\theta$?", target_mode="raise_left_hand", ) self.play_student_changes( "confused", "sassy", "raise_left_hand", added_anims=[self.teacher.change, "happy"] ) self.wait(3) class ComputeThetaFor1e4(AnalyzeCircleGeometry): CONFIG = { "mass_ratio": 100, } def construct(self): self.add_mass_ratio_label() self.add_circle_with_three_lines() self.write_slope() self.show_tangent() def add_circle_with_three_lines(self): circle = self.get_circle() axes = self.get_axes() slope = -np.sqrt(self.mass_ratio) lines = self.get_lines( radius=circle.radius, slope=slope, ) end_zone = self.get_end_zone() axes_labels = self.get_axes_labels(axes) axes.add(axes_labels) lines_to_fade = VGroup(*lines[:11], *lines[13:]) two_lines = lines[11:13] theta = self.theta = np.arctan(-1 / slope) arc = Arc( start_angle=(-90 * DEGREES), angle=theta, radius=2, arc_center=two_lines[0].get_end(), ) theta_label = OldTex("\\theta") theta_label.scale(0.8) theta_label.next_to(arc, DOWN, SMALL_BUFF) self.add(end_zone, axes, circle) self.play(ShowCreation(lines, rate_func=linear)) self.play( lines_to_fade.set_stroke, WHITE, 1, 0.3, ShowCreation(arc), FadeIn(theta_label, UP) ) self.two_lines = two_lines self.lines = lines self.circle = circle self.axes = axes self.theta_label_group = VGroup(theta_label, arc) def write_slope(self): line = self.two_lines[1] slope_label = OldTex( "\\text{Slope}", "=", "\\frac{\\text{rise}}{\\text{run}}", "=", "\\frac{-\\sqrt{m_1}}{\\sqrt{m_2}}", "=", "-10" ) for mob in slope_label: mob.add_to_back(mob.copy().set_stroke(BLACK, 6)) slope_label.next_to(line.get_center(), UR, buff=1) slope_arrow = Arrow( slope_label[0].get_bottom(), line.point_from_proportion(0.45), color=RED, buff=SMALL_BUFF, ) new_line = line.copy().set_color(RED) self.play( FadeInFromDown(slope_label[:3]), ShowCreation(new_line), GrowArrow(slope_arrow), ) self.remove(new_line) line.match_style(new_line) self.play( FadeIn(slope_label[3:5], LEFT) ) self.wait() self.play( Write(slope_label[5]), TransformFromCopy( self.mass_ratio_label[1][:3], slope_label[6] ) ) self.wait() self.slope_label = slope_label self.slope_arrow = slope_arrow def show_tangent(self): l1, l2 = self.two_lines theta = self.theta theta_label_group = self.theta_label_group tan_equation = OldTex( "\\tan", "(", "\\theta", ")", "=", "{\\text{run}", "\\over", "-\\text{rise}}", "=", "\\frac{1}{10}", ) tan_equation.scale(0.9) tan_equation.to_edge(LEFT, buff=MED_SMALL_BUFF) tan_equation.shift(2 * UP) run_word = tan_equation.get_part_by_tex("run") rise_word = tan_equation.get_part_by_tex("rise") p1, p2 = l1.get_start(), l1.get_end() p3 = p1 + get_norm(p2 - p1) * np.tan(theta) * RIGHT triangle = Polygon(p1, p2, p3) triangle.set_stroke(width=0) triangle.set_fill(GREEN, 0.5) opposite = Line(p1, p3) adjacent = Line(p1, p2) opposite.set_stroke(BLUE, 3) adjacent.set_stroke(PINK, 3) arctan_equation = OldTex( "\\theta", "=", "\\arctan", "(", "1 / 10", ")" ) arctan_equation.next_to(tan_equation, DOWN, MED_LARGE_BUFF) self.play( FadeInFromDown(tan_equation[:8]), ) self.play( TransformFromCopy(theta_label_group[1], opposite), run_word.set_color, opposite.get_color() ) self.play(WiggleOutThenIn(run_word)) self.play( TransformFromCopy(opposite, adjacent), rise_word.set_color, adjacent.get_color() ) self.play(WiggleOutThenIn(rise_word)) self.wait() self.play(TransformFromCopy( self.slope_label[-1], tan_equation[-2:], )) self.wait(2) indices = [2, 4, 0, 1, -1, 3] movers = VGroup(*[tan_equation[i] for i in indices]).copy() for mover, target in zip(movers, arctan_equation): mover.target = target # Swap last two sm = movers.submobjects sm[-1], sm[-2] = sm[-2], sm[-1] self.play(LaggedStartMap( Transform, movers[:-1], lambda m: (m, m.target), lag_ratio=1, run_time=1, path_arc=PI / 6, )) self.play(MoveToTarget(movers[-1])) self.remove(movers) self.add(arctan_equation) self.play(ShowCreationThenFadeAround(arctan_equation)) self.wait() class ThetaChart(Scene): def construct(self): self.create_columns() self.populate_columns() self.show_values() self.highlight_example(2) self.highlight_example(3) def create_columns(self): titles = VGroup(*[ OldTexText("Mass ratio"), OldTexText("$\\theta$ formula"), OldTexText("$\\theta$ value"), ]) titles.scale(1.5) titles.arrange(RIGHT, buff=1.5) titles[1].shift(MED_SMALL_BUFF * LEFT) titles[2].shift(MED_SMALL_BUFF * RIGHT) titles.to_corner(UL) lines = VGroup() for t1, t2 in zip(titles, titles[1:]): line = Line(TOP, BOTTOM) x = np.mean([t1.get_center()[0], t2.get_center()[0]]) line.shift(x * RIGHT) lines.add(line) h_line = Line(LEFT_SIDE, RIGHT_SIDE) h_line.next_to(titles, DOWN) h_line.to_edge(LEFT, buff=0) lines.add(h_line) lines.set_stroke(WHITE, 1) self.play( LaggedStartMap(FadeInFromDown, titles), LaggedStartMap(ShowCreation, lines, lag_ratio=0.8), ) self.h_line = h_line self.titles = titles def populate_columns(self): top_h_line = self.h_line x_vals = [t.get_center()[0] for t in self.titles] entries = [ ( "$m_1$ : $m_2$", "$\\arctan(\\sqrt{m_2} / \\sqrt{m_1})$", "" ) ] + [ ( "{:,} : 1".format(10**(2 * exp)), "$\\arctan(1 / {:,})$".format(10**exp), self.get_theta_decimal(exp), ) for exp in [1, 2, 3, 4, 5] ] h_lines = VGroup(top_h_line) entry_mobs = VGroup() for entry in entries: mobs = VGroup(*map(TexText, entry)) for mob, x in zip(mobs, x_vals): mob.shift(x * RIGHT) delta_y = (mobs.get_height() / 2) + MED_SMALL_BUFF y = h_lines[-1].get_center()[1] - delta_y mobs.shift(y * UP) mobs[0].set_color(BLUE) mobs[2].set_color(YELLOW) entry_mobs.add(mobs) h_line = DashedLine(LEFT_SIDE, RIGHT_SIDE) h_line.shift((y - delta_y) * UP) h_lines.add(h_line) self.play( LaggedStartMap( FadeInFromDown, VGroup(*[em[:2] for em in entry_mobs]), ), LaggedStartMap(ShowCreation, h_lines[1:]), lag_ratio=0.1, run_time=5, ) self.entry_mobs = entry_mobs self.h_lines = h_lines def show_values(self): values = VGroup(*[em[2] for em in self.entry_mobs]) for value in values: self.play(LaggedStartMap( FadeIn, value, lag_ratio=0.1, run_time=0.5 )) self.wait(0.5) def highlight_example(self, exp): entry_mobs = self.entry_mobs example = entry_mobs[exp] other_entries = VGroup(*entry_mobs[:exp], *entry_mobs[exp + 1:]) value = example[-1] rhs = OldTex("\\approx {:}".format(10**(-exp))) rhs.next_to(value, RIGHT) rhs.to_edge(RIGHT, buff=MED_SMALL_BUFF) value.generate_target() value.target.set_fill(opacity=1) value.target.scale(0.9) value.target.next_to(rhs, LEFT, SMALL_BUFF) self.play( other_entries.set_fill, {"opacity": 0.25}, example.set_fill, {"opacity": 1}, ShowCreationThenFadeAround(example) ) self.wait() self.play( MoveToTarget(value), Write(rhs), ) self.wait() value.add(rhs) def get_theta_decimal(self, exp): theta = np.arctan(10**(-exp)) rounded_theta = np.floor(1e10 * theta) / 1e10 return "{:0.10f}\\dots".format(rounded_theta) class CentralQuestionFor1e2(AddTwoThetaManyTimes): CONFIG = { "exp": 2, } def construct(self): exp = self.exp question = self.get_central_question(UP) pi_value = OldTex(" = {:0.10f}\\dots".format(PI)) pi_value.next_to(question[0][-1], RIGHT, SMALL_BUFF) pi_value.shift(0.3 * SMALL_BUFF * UP) question.add(pi_value) max_count = int(PI * 10**exp) question.center().to_edge(UP) self.add(question) b10_equation = self.get_changable_equation( 10**(-exp), n_decimal_places=exp ) b10_equation.next_to(question, DOWN, buff=1.5) arctan_equation = self.get_changable_equation( np.arctan(10**(-exp)), n_decimal_places=10, ) arctan_equation.next_to(b10_equation, DOWN, MED_LARGE_BUFF) eq_centers = [ eq[1][2].get_center() for eq in [b10_equation, arctan_equation] ] arctan_equation.shift((eq_centers[1][0] - eq_centers[1][0]) * RIGHT) # b10_brace = Brace(b10_equation[1][1][1:-1], UP) arctan_brace = Brace(arctan_equation[1][1][1:-1], DOWN) # b10_tex = b10_brace.get_tex("1 / 10") arctan_tex = arctan_brace.get_tex( "\\theta = \\arctan(1 / {:,})".format(10**exp) ) int_mobs = b10_equation[0], arctan_equation[0] self.add(*b10_equation, *arctan_equation) # self.add(b10_brace, b10_tex) self.add(arctan_brace, arctan_tex) self.wait() self.play(*[ ChangeDecimalToValue(int_mob, max_count, run_time=8) for int_mob in int_mobs ]) self.wait() self.play(*[ ChangeDecimalToValue(int_mob, max_count + 1, run_time=1) for int_mob in int_mobs ]) self.wait() self.play(*[ ChangeDecimalToValue(int_mob, max_count, run_time=1) for int_mob in int_mobs ]) self.play(ShowCreationThenFadeAround(int_mobs[1])) self.wait() class AnalyzeCircleGeometry1e2(AnalyzeCircleGeometry): CONFIG = { "mass_ratio": 100, } class CentralQuestionFor1e3(CentralQuestionFor1e2): CONFIG = {"exp": 3} class AskAboutArctanOfSmallValues(TeacherStudentsScene): def construct(self): self.add_title() equation1 = OldTex( "\\arctan", "(", "x", ")", "\\approx", "x" ) equation1.set_color_by_tex("arctan", YELLOW) equation2 = OldTex( "x", "\\approx", "\\tan", "(", "x", ")", ) equation2.set_color_by_tex("tan", BLUE) for mob in equation1, equation2: mob.move_to(self.hold_up_spot, DOWN) self.play( FadeInFromDown(equation1), self.teacher.change, "raise_right_hand", self.change_students( "erm", "sassy", "confused" ) ) self.look_at(3 * UL) self.play(equation1.shift, UP) self.play( TransformFromCopy( VGroup(*[equation1[i] for i in (2, 4, 5)]), VGroup(*[equation2[i] for i in (0, 1, 4)]), ) ) self.play( TransformFromCopy( VGroup(*[equation1[i] for i in (0, 1, 3)]), VGroup(*[equation2[i] for i in (2, 3, 5)]), ), self.change_students( "confused", "erm", "sassy", ), ) self.look_at(3 * UL) self.wait(3) # self.student_says("Why?", target_mode="maybe") # self.wait(3) def add_title(self): title = OldTexText("For small $x$") subtitle = OldTexText("(e.g. $x = 0.001$)") subtitle.scale(0.75) subtitle.next_to(title, DOWN) title.add(subtitle) # title.scale(1.5) # title.to_edge(UP, buff=MED_SMALL_BUFF) title.move_to(self.hold_up_spot) title.to_edge(UP) self.add(title) class ActanAndTanGraphs(GraphScene): CONFIG = { "x_min": -PI / 8, "x_max": 5 * PI / 8, "y_min": -PI / 8, "y_max": 4 * PI / 8, "x_tick_frequency": PI / 8, "x_leftmost_tick": -PI / 8, "y_tick_frequency": PI / 8, "y_leftmost_tick": -PI / 8, "x_axis_width": 10, "y_axis_height": 7, "graph_origin": 2.5 * DOWN + 5 * LEFT, "num_graph_anchor_points": 500, } def construct(self): self.setup_axes() axes = self.axes labels = VGroup( OldTex("\\pi / 8"), OldTex("\\pi / 4"), OldTex("3\\pi / 8"), OldTex("\\pi / 2"), ) for n, label in zip(it.count(1), labels): label.scale(0.75) label.next_to(self.coords_to_point(n * PI / 8, 0), DOWN) self.add(label) id_graph = self.get_graph(lambda x: x, x_max=1.5) arctan_graph = self.get_graph(np.arctan, x_max=1.5) tan_graph = self.get_graph(np.tan, x_max=1.5) graphs = VGroup(id_graph, arctan_graph, tan_graph) id_label = OldTex("f(x) = x") arctan_label = OldTex("\\arctan(x)") tan_label = OldTex("\\tan(x)") labels = VGroup(id_label, arctan_label, tan_label) for label, graph in zip(labels, graphs): label.match_color(graph) label.next_to(graph.get_points()[-1], RIGHT) if label.get_bottom()[1] > FRAME_HEIGHT / 2: label.next_to(graph.point_from_proportion(0.75), LEFT) arctan_x_tracker = ValueTracker(3 * PI / 8) arctan_v_line = always_redraw( lambda: self.get_vertical_line_to_graph( arctan_x_tracker.get_value(), arctan_graph, line_class=DashedLine, color=WHITE, ) ) tan_x_tracker = ValueTracker(2 * PI / 8) tan_v_line = always_redraw( lambda: self.get_vertical_line_to_graph( tan_x_tracker.get_value(), tan_graph, line_class=DashedLine, color=WHITE, ) ) self.add(axes) self.play( ShowCreation(id_graph), Write(id_label) ) self.play( ShowCreation(arctan_graph), Write(arctan_label) ) self.add(arctan_v_line) self.play(arctan_x_tracker.set_value, 0, run_time=2) self.wait() self.play( TransformFromCopy(arctan_graph, tan_graph), TransformFromCopy(arctan_label, tan_label), ) self.add(tan_v_line) self.play(tan_x_tracker.set_value, 0, run_time=2) self.wait() class UnitCircleIntuition(Scene): def construct(self): self.draw_unit_circle() self.show_angle() self.show_fraction() self.show_fraction_approximation() def draw_unit_circle(self): unit_size = 2.5 axes = Axes( axis_config={"unit_size": unit_size}, x_min=-2.5, x_max=2.5, y_min=-1.5, y_max=1.5, ) axes.set_stroke(width=1) self.add(axes) radius_line = Line(ORIGIN, axes.coords_to_point(1, 0)) radius_line.set_color(BLUE) r_label = OldTex("1") r_label.add_updater( lambda m: m.next_to(radius_line.get_center(), DOWN, SMALL_BUFF) ) circle = Circle(radius=unit_size, color=WHITE) self.add(radius_line, r_label) self.play( Rotating(radius_line, about_point=ORIGIN), ShowCreation(circle), run_time=2, rate_func=smooth, ) self.radius_line = radius_line self.r_label = r_label self.circle = circle self.axes = axes def show_angle(self): circle = self.circle tan_eq = OldTex( "\\tan", "(", "\\theta", ")", "=", tex_to_color_map={"\\theta": RED}, ) tan_eq.next_to(ORIGIN, RIGHT, LARGE_BUFF) tan_eq.to_edge(UP, buff=LARGE_BUFF) theta_tracker = ValueTracker(0) get_theta = theta_tracker.get_value def get_r_line(): return Line( circle.get_center(), circle.point_at_angle(get_theta()) ) r_line = always_redraw(get_r_line) def get_arc(radius=None, **kwargs): if radius is None: alpha = inverse_interpolate(0, 20 * DEGREES, get_theta()) radius = interpolate(2, 1, alpha) return Arc( radius=radius, start_angle=0, angle=get_theta(), arc_center=circle.get_center(), **kwargs ) arc = always_redraw(get_arc) self.circle_arc = always_redraw( lambda: get_arc(radius=circle.radius, color=RED) ) def get_theta_label(): label = OldTex("\\theta") label.set_height(min(arc.get_height(), 0.3)) label.set_color(RED) center = circle.get_center() vect = arc.point_from_proportion(0.5) - center vect = (get_norm(vect) + 2 * SMALL_BUFF) * normalize(vect) label.move_to(center + vect) return label theta_label = always_redraw(get_theta_label) def get_height_line(): p2 = circle.point_at_angle(get_theta()) p1 = np.array(p2) p1[1] = circle.get_center()[1] return Line( p1, p2, stroke_color=YELLOW, stroke_width=3, ) self.height_line = always_redraw(get_height_line) def get_width_line(): p2 = circle.get_center() p1 = circle.point_at_angle(get_theta()) p1[1] = p2[1] return Line( p1, p2, stroke_color=PINK, stroke_width=3, ) self.width_line = always_redraw(get_width_line) def get_h_label(): label = OldTex("h") height_line = self.height_line label.match_color(height_line) label.set_height(min(height_line.get_height(), 0.3)) label.set_stroke(BLACK, 3, background=True) label.next_to(height_line, RIGHT, SMALL_BUFF) return label self.h_label = always_redraw(get_h_label) def get_w_label(): label = OldTex("w") width_line = self.width_line label.match_color(width_line) label.next_to(width_line, DOWN, SMALL_BUFF) return label self.w_label = always_redraw(get_w_label) self.add(r_line, theta_label, arc, self.radius_line) self.play( FadeInFromDown(tan_eq), theta_tracker.set_value, 20 * DEGREES, ) self.wait() self.tan_eq = tan_eq self.theta_tracker = theta_tracker def show_fraction(self): height_line = self.height_line width_line = self.width_line h_label = self.h_label w_label = self.w_label tan_eq = self.tan_eq rhs = OldTex( "{\\text{height}", "\\over", "\\text{width}}" ) rhs.next_to(tan_eq, RIGHT) rhs.get_part_by_tex("height").match_color(height_line) rhs.get_part_by_tex("width").match_color(width_line) for mob in [height_line, width_line, h_label, w_label]: mob.update() self.play( ShowCreation(height_line.copy().clear_updaters(), remover=True), FadeIn(h_label.copy().clear_updaters(), RIGHT, remover=True), Write(rhs[:2]) ) self.add(height_line, h_label) self.play( ShowCreation(width_line.copy().clear_updaters(), remover=True), FadeIn(w_label.copy().clear_updaters(), UP, remover=True), self.r_label.fade, 1, Write(rhs[2]) ) self.add(width_line, w_label) self.wait() self.rhs = rhs def show_fraction_approximation(self): theta_tracker = self.theta_tracker approx_rhs = OldTex( "\\approx", "{\\theta", "\\over", "1}", ) height, over1, width = self.rhs approx, theta, over2, one = approx_rhs approx_rhs.set_color_by_tex("\\theta", RED) approx_rhs.next_to(self.rhs, RIGHT, MED_SMALL_BUFF) self.play(theta_tracker.set_value, 5 * DEGREES) self.play(Write(VGroup(approx, over2))) self.wait() self.play(Indicate(width)) self.play(TransformFromCopy(width, one)) self.wait() self.play(Indicate(height)) self.play(TransformFromCopy(height, theta)) self.wait() class TangentTaylorSeries(TeacherStudentsScene): def construct(self): series = OldTex( "\\tan", "(", "\\theta", ")", "=", "\\theta", "+", "\\frac{1}{3}", "\\theta", "^3", "+", "\\frac{2}{15}", "\\theta", "^5", "+", "\\cdots", tex_to_color_map={"\\theta": YELLOW}, ) series.move_to(2 * UP) series.move_to(self.hold_up_spot, DOWN) series_error = series[7:] series_error_rect = SurroundingRectangle(series_error) example = OldTex( "\\tan", "\\left(", "\\frac{1}{100}", "\\right)", "=", "\\frac{1}{100}", "+", "\\frac{1}{3}", "\\left(", "\\frac{1}{1{,}000{,}000}", "\\right)", "+", "\\frac{2}{15}", "\\left(", "\\frac{1}{10{,}000{,}000{,}000}", "\\right)", "+", "\\cdots", ) example.set_color_by_tex("\\frac{1}{1", BLUE) example.set_width(FRAME_WIDTH - 1) example.next_to(self.students, UP, buff=2) example.shift_onto_screen() error = example[7:] error_rect = SurroundingRectangle(error) error_rect.set_color(RED) error_decimal = DecimalNumber( np.tan(0.01) - 0.01, num_decimal_places=15, ) error_decimal.next_to(error_rect, DOWN) approx = OldTex("\\approx") approx.next_to(error_decimal, LEFT) error_decimal.add(approx) error_decimal.match_color(error_rect) self.play( FadeInFromDown(series), self.teacher.change, "raise_right_hand", ) self.play( ShowCreation(series_error_rect), self.change_students(*3 * ["pondering"]) ) self.play(FadeOut(series_error_rect)) self.play( series.center, series.to_edge, UP, ) self.look_at(series) self.play( TransformFromCopy(series[:8], example[:8]), TransformFromCopy(series[8], example[9]), TransformFromCopy(series[10:12], example[11:13]), TransformFromCopy(series[12], example[14]), TransformFromCopy(series[14:], example[16:]), *map(GrowFromCenter, [example[i] for i in (8, 10, 13, 15)]) ) self.play_student_changes("happy", "confused", "sad") self.play(ShowCreation(error_rect)) self.play(ShowIncreasingSubsets(error_decimal)) self.play_all_student_changes("hooray") self.wait(3) class AnalyzeCircleGeometry1e4(AnalyzeCircleGeometry): CONFIG = { "mass_ratio": 10000, } class SumUpWrapper(Scene): def construct(self): title = OldTexText("To sum up:") title.scale(1.5) title.to_edge(UP) screen_rect = ScreenRectangle(height=6) screen_rect.set_fill(BLACK, 1) screen_rect.next_to(title, DOWN) self.add(FullScreenFadeRectangle( fill_color=GREY_D, fill_opacity=0.5 )) self.play( FadeInFromDown(title), FadeIn(screen_rect), ) self.wait() class ConservationLawSummary(Scene): def construct(self): energy_eq = OldTex( "\\frac{1}{2}", "m_1", "(", "v_1", ")", "^2", "+", "\\frac{1}{2}", "m_2", "(", "v_2", ")", "^2", "=", "\\text{const.}", ) energy_word = OldTexText("Energy") energy_word.scale(2) circle = Circle(color=YELLOW, radius=2) energy_group = VGroup(energy_word, energy_eq, circle) momentum_eq = OldTex( "m_1", "v_1", "+", "m_2", "v_2", "=", "\\text{const.}", ) momentum_word = OldTexText("Momentum") momentum_word.scale(2) line = Line(ORIGIN, RIGHT + np.sqrt(10) * DOWN) line.set_color(GREEN) momentum_group = VGroup(momentum_word, momentum_eq, line) equations = VGroup(energy_eq, momentum_eq) words = VGroup(energy_word, momentum_word) for equation in equations: equation.set_color_by_tex("m_", BLUE) equation.set_color_by_tex("v_", RED) words.arrange( DOWN, buff=3, ) words.to_edge(LEFT, buff=1.5) for group in energy_group, momentum_group: arrow = Arrow( LEFT, 2 * RIGHT, rectangular_stem_width=0.1, tip_length=0.5, color=WHITE ) arrow.next_to(group[0], RIGHT) group[1].next_to(group[0], DOWN) group[2].next_to(arrow, RIGHT) group[2].set_stroke(width=6) group.add(arrow) # line.scale(4, about_edge=DR) red_energy_word = energy_word.copy() red_energy_word.set_fill(opacity=0) red_energy_word.set_stroke(RED, 2) self.add(energy_group, momentum_group) self.wait() self.play( LaggedStartMap( ShowCreationThenDestruction, red_energy_word ), ) for color in [RED, BLUE, PINK, YELLOW]: self.play(ShowCreation( circle.copy().set_color(color), )) class FinalCommentsOnPhaseSpace(Scene): def construct(self): self.add_title() self.show_related_fields() self.state_to_point() self.puzzle_as_remnant() def add_title(self): title = self.title = OldTexText("Phase space") title.scale(2) title.to_edge(UP) title.set_color(YELLOW) self.play(Write(title)) def show_related_fields(self): title = self.title images = Group( ImageMobject("ClacksThumbnail"), ImageMobject("PictoralODE"), # ImageMobject("DoublePendulumStart"), ImageMobject("MobiusStrip"), ) colors = [BLUE_D, GREY_BROWN, BLUE_C] for image, color in zip(images, colors): image.set_height(2.5) image.add(SurroundingRectangle( image, color=color, stroke_width=5, buff=0, )) images.arrange(RIGHT) images.move_to(DOWN) arrows = VGroup(*[ Arrow( title.get_bottom(), image.get_top(), color=WHITE, ) for image in images ]) for image, arrow in zip(images, arrows): self.play( GrowArrow(arrow), GrowFromPoint(image, title.get_bottom()), ) self.wait() self.wait() self.to_fade = Group(images, arrows) def state_to_point(self): state = OldTexText("State") arrow = Arrow( 2 * LEFT, 2 * RIGHT, color=WHITE, rectangular_stem_width=0.1, tip_length=0.5 ) point = OldTexText("Point") dynamics = OldTexText("Dynamics") geometry = OldTexText("Geometry") words = VGroup(state, point, dynamics, geometry) for word in words: word.scale(2) group = VGroup(state, arrow, point) group.arrange(RIGHT, buff=MED_LARGE_BUFF) group.move_to(2.5 * DOWN) dynamics.move_to(state, RIGHT) geometry.move_to(point, LEFT) self.play( FadeOut(self.to_fade, UP), FadeIn(state, UP) ) self.play( GrowArrow(arrow), FadeIn(point, LEFT) ) self.wait(2) for w1, w2 in [(state, dynamics), (point, geometry)]: self.play( FadeOut(w1, UP), FadeIn(w2, DOWN), ) self.wait() self.wait() def puzzle_as_remnant(self): pass class AltShowTwoPopulations(ShowTwoPopulations): CONFIG = { "count_word_scale_val": 2, } class SimpleTeacherHolding(TeacherStudentsScene): def construct(self): self.play(self.teacher.change, "raise_right_hand") self.play_all_student_changes("pondering") self.wait(3) class EndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "Juan Benet", "Vassili Philippov", "Burt Humburg", "Matt Russell", "soekul", "Richard Barthel", "Nathan Jessurun", "Ali Yahya", "dave nicponski", "Yu Jun", "Kaustuv DeBiswas", "Yana Chernobilsky", "Lukas Biewald", "Arthur Zey", "Roy Larson", "Joseph Kelly", "Peter Mcinerney", "Scott Walter, Ph.D.", "Magnus Lysfjord", "Evan Phillips", "Graham", "Mauricio Collares", "Quantopian", "Jordan Scales", "Lukas -krtek.net- Novy", "John Shaughnessy", "Joseph John Cox", "Ryan Atallah", "Britt Selvitelle", "Jonathan Wilson", "Randy C. Will", "Magnus Dahlström", "David Gow", "J", "Luc Ritchie", "Rish Kundalia", "Bob Sanderson", "Mathew Bramson", "Mustafa Mahdi", "Robert Teed", "Cooper Jones", "Jeff Linse", "John Haley", "Boris Veselinovich", "Andrew Busey", "Awoo", "Linh Tran", "Ripta Pasay", "David Clark", "Mathias Jansson", "Clark Gaebel", "Bernd Sing", "Jason Hise", "Ankalagon", "Dave B", "Ted Suzman", "Chris Connett", "Eric Younge", "1stViewMaths", "Jacob Magnuson", "Jonathan Eppele", "Delton Ding", "James Hughes", "Stevie Metke", "Yaw Etse", "John Griffith", "Magister Mugit", "Ludwig Schubert", "Giovanni Filippi", "Matt Langford", "Matt Roveto", "Jameel Syed", "Richard Burgmann", "Solara570", "Alexis Olson", "Jeff Straathof", "John V Wertheim", "Sindre Reino Trosterud", "Song Gao", "Peter Ehrnstrom", "Valeriy Skobelev", "Art Ianuzzi", "Michael Faust", "Omar Zrien", "Adrian Robinson", "Federico Lebron", "Kai-Siang Ang", "Michael Hardel", "Nero Li", "Ryan Williams", "Charles Southerland", "Devarsh Desai", "Hal Hildebrand", "Jan Pijpers", "L0j1k", "Mark B Bahu", "Márton Vaitkus", "Richard Comish", "Zach Cardwell", "Brian Staroselsky", "Matthew Cocke", "Christian Kaiser", "Danger Dai", "Dave Kester", "eaglle", "Florian Chudigiewitsch", "Roobie", "Xavier Bernard", "YinYangBalance.Asia", "Eryq Ouithaqueue", "Kanan Gill", "j eduardo perez", "Antonio Juarez", "Owen Campbell-Moore", ], } class SolutionThumbnail(Thumbnail): CONFIG = { "sliding_blocks_config": { "block1_config": { "label_text": "$100^{d}$ kg", }, "collect_clack_data": False, }, } def add_text(self): word = OldTexText("Solution") question = OldTexText("How many collisions?") word.set_width(7) question.match_width(word) question.next_to(word, UP) group = VGroup(word, question) group.to_edge(UP, buff=MED_LARGE_BUFF) word.set_color(RED) question.set_color(YELLOW) group.set_stroke(RED, 2, background=True) self.add(group)
#!/usr/bin/env python from manim_imports_ext import * from _2019.clacks.question import BlocksAndWallExample class NameBump(BlocksAndWallExample): CONFIG = { "name": "Grant Sanderson", "sliding_blocks_config": { "block1_config": { "mass": 1e6, "velocity": -0.5, "distance": 7, }, "block2_config": {}, }, "wait_time": 25, } def setup(self): names = self.name.split(" ") n = len(names) if n == 1: names = 2 * [names[0]] elif n > 2: names = [ " ".join(names[:n // 2]), " ".join(names[n // 2:]), ] # Swap, to show first name on the left names = [names[1], names[0]] name_mobs = VGroup(*map(TexText, names)) name_mobs.set_stroke(BLACK, 3, background=True) name_mobs.set_fill(GREY_B, 1) name_mobs.set_sheen(3, UL) name_mobs.scale(2) configs = [ self.sliding_blocks_config["block1_config"], self.sliding_blocks_config["block2_config"], ] for name_mob, config in zip(name_mobs, configs): config["width"] = name_mob.get_width() self.name_mobs = name_mobs super().setup() def add_blocks(self): super().add_blocks() blocks = self.blocks name_mobs = self.name_mobs blocks.fade(1) def update_name_mobs(name_mobs): for name_mob, block in zip(name_mobs, self.blocks): name_mob.move_to(block) target_y = block.get_bottom()[1] + SMALL_BUFF curr_y = name_mob[0].get_bottom()[1] name_mob.shift((target_y - curr_y) * UP) name_mobs.add_updater(update_name_mobs) self.add(name_mobs) clack_y = self.name_mobs[1].get_center()[1] for location, time in self.clack_data: location[1] = clack_y for block, name_mob in zip(blocks, name_mobs): block.label.next_to(name_mob, UP) block.label.set_fill(YELLOW, opacity=1) # for name in names: # file_name = name.replace(".", "") # file_name += " Name Bump" # scene = NameBump( # name=name, # write_to_movie=True, # output_file_name=file_name, # camera_config=UHD_QUALITY_CAMERA_CONFIG, # )
from manim_imports_ext import * OUTPUT_DIRECTORY = "clacks/question" class Block(Square): CONFIG = { "mass": 1, "velocity": 0, "width": None, "label_text": None, "label_scale_value": 0.8, "fill_opacity": 1, "stroke_width": 3, "stroke_color": WHITE, "fill_color": None, "sheen_direction": UL, "sheen_factor": 0.5, "sheen_direction": UL, } def __init__(self, **kwargs): digest_config(self, kwargs) if self.width is None: self.width = self.mass_to_width(self.mass) if self.fill_color is None: self.fill_color = self.mass_to_color(self.mass) if self.label_text is None: self.label_text = self.mass_to_label_text(self.mass) if "width" in kwargs: kwargs.pop("width") Square.__init__(self, side_length=self.width, **kwargs) self.label = self.get_label() self.add(self.label) def get_label(self): label = OldTexText(self.label_text) label.scale(self.label_scale_value) label.next_to(self, UP, SMALL_BUFF) return label def get_points_defining_boundary(self): return self.get_points() def mass_to_color(self, mass): colors = [ GREY_B, BLUE_D, BLUE_D, BLUE_E, BLUE_E, GREY_D, GREY_D, BLACK, ] index = min(int(np.log10(mass)), len(colors) - 1) return colors[index] def mass_to_width(self, mass): return 1 + 0.25 * np.log10(mass) def mass_to_label_text(self, mass): return "{:,}\\,kg".format(int(mass)) class SlidingBlocks(VGroup): CONFIG = { "block1_config": { "distance": 7, "mass": 1e6, "velocity": -2, }, "block2_config": { "distance": 3, "mass": 1, "velocity": 0, }, "collect_clack_data": True, } def __init__(self, scene, **kwargs): VGroup.__init__(self, **kwargs) self.scene = scene self.floor = scene.floor self.wall = scene.wall self.block1 = self.get_block(**self.block1_config) self.block2 = self.get_block(**self.block2_config) self.mass_ratio = self.block2.mass / self.block1.mass self.phase_space_point_tracker = self.get_phase_space_point_tracker() self.add( self.block1, self.block2, self.phase_space_point_tracker, ) self.add_updater(self.__class__.update_positions) if self.collect_clack_data: self.clack_data = self.get_clack_data() def get_block(self, distance, **kwargs): block = Block(**kwargs) block.move_to( self.floor.get_top()[1] * UP + (self.wall.get_right()[0] + distance) * RIGHT, DL, ) return block def get_phase_space_point_tracker(self): block1, block2 = self.block1, self.block2 w2 = block2.get_width() s1 = block1.get_left()[0] - self.wall.get_right()[0] - w2 s2 = block2.get_right()[0] - self.wall.get_right()[0] - w2 result = VectorizedPoint([ s1 * np.sqrt(block1.mass), s2 * np.sqrt(block2.mass), 0 ]) result.velocity = np.array([ np.sqrt(block1.mass) * block1.velocity, np.sqrt(block2.mass) * block2.velocity, 0 ]) return result def update_positions(self, dt): self.phase_space_point_tracker.shift( self.phase_space_point_tracker.velocity * dt ) self.update_blocks_from_phase_space_point_tracker() def update_blocks_from_phase_space_point_tracker(self): block1, block2 = self.block1, self.block2 ps_point = self.phase_space_point_tracker.get_location() theta = np.arctan(np.sqrt(self.mass_ratio)) ps_point_angle = angle_of_vector(ps_point) n_clacks = int(ps_point_angle / theta) reflected_point = rotate_vector( ps_point, -2 * np.ceil(n_clacks / 2) * theta ) reflected_point = np.abs(reflected_point) shadow_wall_x = self.wall.get_right()[0] + block2.get_width() floor_y = self.floor.get_top()[1] s1 = reflected_point[0] / np.sqrt(block1.mass) s2 = reflected_point[1] / np.sqrt(block2.mass) block1.move_to( (shadow_wall_x + s1) * RIGHT + floor_y * UP, DL, ) block2.move_to( (shadow_wall_x + s2) * RIGHT + floor_y * UP, DR, ) self.scene.update_num_clacks(n_clacks) def get_clack_data(self): ps_point = self.phase_space_point_tracker.get_location() ps_velocity = self.phase_space_point_tracker.velocity if ps_velocity[1] != 0: raise Exception( "Haven't implemented anything to gather clack " "data from a start state with block2 moving" ) y = ps_point[1] theta = np.arctan(np.sqrt(self.mass_ratio)) clack_data = [] for k in range(1, int(PI / theta) + 1): clack_ps_point = np.array([ y / np.tan(k * theta), y, 0 ]) time = get_norm(ps_point - clack_ps_point) / get_norm(ps_velocity) reflected_point = rotate_vector( clack_ps_point, -2 * np.ceil((k - 1) / 2) * theta ) block2 = self.block2 s2 = reflected_point[1] / np.sqrt(block2.mass) location = np.array([ self.wall.get_right()[0] + s2, block2.get_center()[1], 0 ]) if k % 2 == 1: location += block2.get_width() * RIGHT clack_data.append((location, time)) return clack_data # TODO, this is untested after turning it from a # ContinualAnimation into a VGroup class ClackFlashes(VGroup): CONFIG = { "flash_config": { "run_time": 0.5, "line_length": 0.1, "flash_radius": 0.2, }, "start_up_time": 0, "min_time_between_flashes": 1 / 30, } def __init__(self, clack_data, **kwargs): VGroup.__init__(self, **kwargs) self.flashes = [] last_time = 0 for location, time in clack_data: if (time - last_time) < self.min_time_between_flashes: continue last_time = time flash = Flash(location, **self.flash_config) flash.begin() for sm in flash.mobject.family_members_with_points(): if isinstance(sm, VMobject): sm.set_stroke(YELLOW, 3) sm.set_stroke(WHITE, 6, 0.5, background=True) flash.start_time = time flash.end_time = time + flash.run_time self.flashes.append(flash) self.time = 0 self.add_updater(lambda m: m.update(dt)) def update(self, dt): time = self.time self.time += dt for flash in self.flashes: if flash.start_time < time < flash.end_time: if flash.mobject not in self.submobjects: self.add(flash.mobject) flash.update( (time - flash.start_time) / flash.run_time ) else: if flash.mobject in self.submobjects: self.remove(flash.mobject) class Wall(Line): CONFIG = { "tick_spacing": 0.5, "tick_length": 0.25, "tick_style": { "stroke_width": 1, "stroke_color": WHITE, }, } def __init__(self, height, **kwargs): Line.__init__(self, ORIGIN, height * UP, **kwargs) self.height = height self.ticks = self.get_ticks() self.add(self.ticks) def get_ticks(self): n_lines = int(self.height / self.tick_spacing) lines = VGroup(*[ Line(ORIGIN, self.tick_length * UR).shift(n * self.tick_spacing * UP) for n in range(n_lines) ]) lines.set_style(**self.tick_style) lines.move_to(self, DR) return lines class BlocksAndWallScene(Scene): CONFIG = { "include_sound": True, "collision_sound": "clack.wav", "count_clacks": True, "counter_group_shift_vect": LEFT, "sliding_blocks_config": {}, "floor_y": -2, "wall_x": -6, "n_wall_ticks": 15, "counter_label": "\\# Collisions: ", "show_flash_animations": True, "min_time_between_sounds": 0.004, } def setup(self): self.track_time() self.add_floor_and_wall() self.add_blocks() if self.show_flash_animations: self.add_flash_animations() if self.count_clacks: self.add_counter() def add_floor_and_wall(self): self.floor = self.get_floor() self.wall = self.get_wall() self.add(self.floor, self.wall) def add_blocks(self): self.blocks = SlidingBlocks(self, **self.sliding_blocks_config) if hasattr(self.blocks, "clack_data"): self.clack_data = self.blocks.clack_data self.add(self.blocks) def add_flash_animations(self): self.clack_flashes = ClackFlashes(self.clack_data) self.add(self.clack_flashes) def track_time(self): time_tracker = ValueTracker() time_tracker.add_updater(lambda m, dt: m.increment_value(dt)) self.add(time_tracker) self.get_time = time_tracker.get_value def add_counter(self): self.n_clacks = 0 counter_label = OldTexText(self.counter_label) counter_mob = Integer(self.n_clacks) counter_mob.next_to( counter_label[-1], RIGHT, ) counter_mob.align_to(counter_label[-1][-1], DOWN) counter_group = VGroup( counter_label, counter_mob, ) counter_group.to_corner(UR) counter_group.shift(self.counter_group_shift_vect) self.add(counter_group) self.counter_mob = counter_mob def get_wall(self): height = (FRAME_HEIGHT / 2) - self.floor_y wall = Wall(height=height) wall.shift(self.wall_x * RIGHT) wall.to_edge(UP, buff=0) return wall def get_floor(self): floor = Line(self.wall_x * RIGHT, FRAME_WIDTH * RIGHT / 2) floor.shift(self.floor_y * UP) return floor def update_num_clacks(self, n_clacks): if hasattr(self, "n_clacks"): if n_clacks == self.n_clacks: return self.counter_mob.set_value(n_clacks) def add_clack_sounds(self, clack_data): clack_file = self.collision_sound total_time = self.get_time() times = [ time for location, time in clack_data if time < total_time ] last_time = 0 for time in times: d_time = time - last_time if d_time < self.min_time_between_sounds: continue last_time = time self.add_sound( clack_file, time_offset=(time - total_time), gain=-20, ) return self def tear_down(self): super().tear_down() if self.include_sound: self.add_clack_sounds(self.clack_data) # Animated scenes class NameIntro(Scene): def construct(self): name = OldTexText("3Blue", "1Brown", arg_separator="") blue, brown = name name.scale(2.5) for part in name: part.save_state() brown.to_edge(RIGHT, buff=0) flash_time = 0.75 self.add(blue, brown) self.play( VFadeIn(blue), VFadeIn(brown), Restore(brown, rate_func=linear), ) self.play( Flash(blue.get_right(), run_time=flash_time), ApplyMethod( blue.to_edge, LEFT, {"buff": 0}, rate_func=linear, ), ) self.play( Flash(blue.get_left(), run_time=flash_time), Restore(blue, rate_func=linear), ) self.play( Flash(blue.get_right(), run_time=flash_time), ApplyMethod( brown.to_edge, RIGHT, {"buff": 0}, rate_func=linear, ) ) self.play( Flash(brown.get_right(), run_time=flash_time), Restore(brown, rate_func=linear) ) class MathAndPhysicsConspiring(Scene): def construct(self): v_line = Line(DOWN, UP).scale(FRAME_HEIGHT) v_line.save_state() v_line.fade(1) v_line.scale(0) math_title = OldTexText("Math") math_title.set_color(BLUE) physics_title = OldTexText("Physics") physics_title.set_color(YELLOW) for title, vect in (math_title, LEFT), (physics_title, RIGHT): title.scale(2) title.shift(vect * FRAME_WIDTH / 4) title.to_edge(UP) math_stuffs = VGroup( OldTex("\\pi = {:.16}\\dots".format(PI)), self.get_tangent_image(), ) math_stuffs.arrange(DOWN, buff=MED_LARGE_BUFF) math_stuffs.next_to(math_title, DOWN, LARGE_BUFF) to_fade = VGroup(math_title, *math_stuffs, physics_title) self.play( LaggedStartMap( FadeInFromDown, to_fade, lag_ratio=0.7, run_time=3, ), Restore(v_line, run_time=2, path_arc=PI / 2), ) self.wait() def get_tangent_image(self): axes = Axes( x_min=-1.5, x_max=1.5, y_min=-1.5, y_max=1.5, ) circle = Circle() circle.set_color(WHITE) theta = 30 * DEGREES arc = Arc(angle=theta, radius=0.4) theta_label = OldTex("\\theta") theta_label.scale(0.5) theta_label.next_to(arc.get_center(), RIGHT, buff=SMALL_BUFF) theta_label.shift(0.025 * UL) line = Line(ORIGIN, rotate_vector(RIGHT, theta)) line.set_color(WHITE) one = OldTex("1").scale(0.5) one.next_to(line.point_from_proportion(0.7), UL, 0.5 * SMALL_BUFF) tan_line = Line( line.get_end(), (1.0 / np.cos(theta)) * RIGHT ) tan_line.set_color(RED) tan_text = OldTex("\\tan(\\theta)") tan_text.rotate(tan_line.get_angle()) tan_text.scale(0.5) tan_text.move_to(tan_line) tan_text.match_color(tan_line) tan_text.shift(0.2 * normalize(line.get_vector())) result = VGroup( axes, circle, line, one, arc, theta_label, tan_line, tan_text, ) result.set_height(4) return result class LightBouncing(MovingCameraScene): CONFIG = { "theta": np.arctan(0.15), "show_fanning": False, "mirror_shift_vect": 5 * LEFT, "mirror_length": 10, "beam_start_x": 12, "beam_height": 1, } def construct(self): theta = self.theta h_line = Line(ORIGIN, self.mirror_length * RIGHT) d_line = h_line.copy().rotate(theta, about_point=ORIGIN) mirrors = VGroup(h_line, d_line) self.add(mirrors) beam_height = self.beam_height start_point = self.beam_start_x * RIGHT + beam_height * UP points = [start_point] + [ np.array([ (beam_height / np.tan(k * theta)), beam_height, 0, ]) for k in range(1, int(PI / theta)) ] + [rotate(start_point, PI, UP)] reflected_points = [] for k, point in enumerate(points): reflected_point = rotate_vector(point, -2 * (k // 2) * theta) reflected_point[1] = abs(reflected_point[1]) reflected_points.append(reflected_point) beam = VMobject() beam.set_points_as_corners(reflected_points) beam.set_stroke(YELLOW, 2) anims = [self.get_beam_anim(beam)] if self.show_fanning: for k in range(2, int(PI / theta) + 1): line = h_line.copy() line.set_stroke(WHITE, 1) line.rotate(k * theta, about_point=ORIGIN) self.add(line) straight_beam = VMobject() straight_beam.set_points_as_corners(points) straight_beam.set_stroke(YELLOW, 2) anims.append(self.get_beam_anim(straight_beam)) self.camera_frame.shift(-self.mirror_shift_vect) self.play(*anims) self.wait() def get_beam_anim(self, beam): dot = Dot() dot.scale(0.5) dot.match_color(beam) return AnimationGroup( ShowPassingFlash( beam, run_time=5, rate_func=lambda t: smooth(t, 5), time_width=0.05, ), UpdateFromFunc( dot, lambda m: m.move_to(beam.get_points()[-1]) ), ) class BlocksAndWallExample(BlocksAndWallScene): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e0, "velocity": -2, } }, "wait_time": 15, } def construct(self): self.wait(self.wait_time) class BlocksAndWallExampleMass1e1(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e1, "velocity": -1.5, } }, "wait_time": 20, } class TwoBlocksLabel(Scene): def construct(self): label = OldTexText("Two sliding \\\\ blocks") label.to_edge(UP) arrows = VGroup(*[ Arrow(label.get_bottom(), point) for point in [RIGHT, LEFT] ]) arrows.set_color(RED) self.play( Write(label), LaggedStartMap(GrowArrow, arrows, lag_ratio=0.7), run_time=1 ) self.wait() class WallLabel(Scene): def construct(self): wall = Line(TOP, 2 * DOWN) wall.set_stroke(YELLOW, 10) word = OldTexText("Wall") word.rotate(-90 * DEGREES) word.next_to(wall, RIGHT, MED_SMALL_BUFF) self.play( Write(word), ShowPassingFlash(wall) ) self.wait() class CowToSphere(ExternallyAnimatedScene): pass class NoFrictionLabel(Scene): def construct(self): words = OldTexText("Frictionless") words.shift(2 * RIGHT) words.add_updater( lambda m, dt: m.shift(dt * LEFT) ) self.play(VFadeIn(words)) self.wait(2) self.play(VFadeOut(words)) class Mass1e1WithElasticLabel(BlocksAndWallExampleMass1e1): def add_flash_animations(self): super().add_flash_animations() flashes = self.clack_flashes label = OldTexText( "Purely elastic collisions\\\\" "(no energy lost)" ) label.set_color(YELLOW) label.move_to(2 * LEFT + 2 * UP) self.add(label) self.add(*[ self.get_arrow(label, flashes, flash) for flash in flashes.flashes ]) def get_arrow(self, label, clack_flashes, flash): arrow = Arrow( label.get_bottom(), flash.mobject.get_center() + 0.0 * UP, ) arrow.set_fill(YELLOW) arrow.set_stroke(BLACK, 1, background=True) arrow.original_length = arrow.get_length() def set_opacity(arrow): time = self.get_time() from_start = time - flash.start_time if from_start < 0: opacity = 0 else: opacity = smooth(1 - 2 * from_start) arrow.set_fill(opacity=opacity) arrow.set_stroke(opacity=opacity, background=True) # if opacity > 0: # arrow.scale( # opacity * arrow.original_length / arrow.get_length(), # about_point=arrow.get_end() # ) arrow.add_updater(set_opacity) return arrow class AskAboutSoundlessness(TeacherStudentsScene): def construct(self): self.student_says( "No sound,\\\\right?" ) self.play(self.teacher.change, "guilty") self.wait(2) self.teacher_says( "Focus on \\\\ collisions", target_mode="speaking", added_anims=[ self.change_students("pondering", "confused", "thinking") ] ) self.look_at(self.screen) self.wait(3) class ShowCreationRect(Scene): def construct(self): rect = SurroundingRectangle(OldTexText("\\# Collisions: 3")) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.wait() class BlocksAndWallExampleSameMass(BlocksAndWallExample): pass class ShowLeftArrow(Scene): def construct(self): arrow = Vector(2 * LEFT, color=RED) self.play(GrowArrow(arrow)) self.wait() self.play(FadeOut(arrow)) class AskWhatWillHappen(PiCreatureScene): def construct(self): morty = self.pi_creature morty.set_color(GREY_BROWN) self.pi_creature_says( "What will\\\\" "happen?", target_mode="maybe", look_at=4 * DR, ) self.wait(3) class BlocksAndWallExampleMass1e2(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e2, "velocity": -0.6, } }, "wait_time": 35, } class BlocksAndWallExampleMassSameSpeedAtEnd(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1 / np.tan(PI / 5)**2, "velocity": -1, "label_text": "$\\frac{1}{\\tan(\\pi / 5)^2}$ kg" } }, "wait_time": 25, } class BlocksAndWallExampleMass1e4(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e4, "velocity": -1.5, }, }, "wait_time": 25, } class BlocksAndWallExampleMass1e4SlowMo(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e4, "velocity": -0.1, "distance": 4.1 }, }, "wait_time": 50, "collision_sound": "slow_clack.wav", } class SlowMotionLabel(Scene): def construct(self): words = OldTexText("Slow motion replay") words.scale(2).to_edge(UP) self.play(Write(words)) self.wait() class BlocksAndWallExampleMass1e6(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e6, "velocity": -1, }, }, "wait_time": 20, } class BlocksAndWallExampleMass1e6SlowMo(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e6, "velocity": -0.1, "distance": 4.1 }, }, "wait_time": 60, "collision_sound": "slow_clack.wav", } class BlocksAndWallExampleMass1e8(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e8, "velocity": -1, }, }, "wait_time": 25, } class BlocksAndWallExampleMass1e10(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e10, "velocity": -1, }, }, "wait_time": 25, } class DigitsOfPi(Scene): CONFIG = {"n_digits": 9} def construct(self): nd = self.n_digits pow10 = int(10**nd) rounded_pi = int(pow10 * PI) / pow10 equation = OldTex( ("\\pi = {:." + str(nd) + "f}...").format(rounded_pi) ) equation.set_color(YELLOW) pi_creature = Randolph(color=YELLOW) pi_creature.match_width(equation[0]) pi_creature.scale(1.4) pi_creature.move_to(equation[0], DOWN) self.add(pi_creature, equation[1]) self.play(ShowIncreasingSubsets( equation[2:], rate_func=linear, run_time=1, )) self.play(Blink(pi_creature)) self.wait() class GalperinPaperScroll(ExternallyAnimatedScene): pass class PiComputingAlgorithmsAxes(Scene): def construct(self): self.setup_axes() self.add_methods() def setup_axes(self): axes = Axes( x_min=0, y_min=0, x_max=9, y_max=5, axis_config={ "tick_frequency": 100, "numbers_with_elongated_ticks": [], } ) y_label = OldTexText("Efficiency") y_label.rotate(90 * DEGREES) y_label.next_to(axes.y_axis, LEFT, SMALL_BUFF) x_label = OldTexText("Elegance") x_label.next_to(axes.x_axis, DOWN, SMALL_BUFF) axes.add(y_label, x_label) axes.center().to_edge(DOWN) self.axes = axes title = OldTexText("Algorithms for computing $\\pi$") title.scale(1.5) title.to_edge(UP, buff=MED_SMALL_BUFF) self.add(title, axes) def add_methods(self): method_location_list = [ (self.get_machin_like_formula(), (1, 4.5)), (self.get_viete(), (3, 3.5)), (self.get_measuring_tape(), (0.5, 1)), (self.get_monte_carlo(), (2, 0.2)), (self.get_basel(), (6, 1)), (self.get_blocks_image(), (8, 0.1)), ] algorithms = VGroup() for method, location in method_location_list: cross = OldTex("\\times") cross.set_color(RED) cross.move_to(self.axes.coords_to_point(*location)) method.next_to(cross, UP, SMALL_BUFF) method.align_to(cross, LEFT) method.shift_onto_screen() algorithms.add(VGroup(method, cross)) self.play(LaggedStartMap( FadeInFromDown, algorithms, run_time=4, lag_ratio=0.4, )) self.wait() self.play(ShowCreationThenFadeAround(algorithms[-1][0])) def get_machin_like_formula(self): formula = OldTex( "\\frac{\\pi}{4} = " "12\\arctan\\left(\\frac{1}{49}\\right) + " "32\\arctan\\left(\\frac{1}{57}\\right) - " "5\\arctan\\left(\\frac{1}{239}\\right) + " "12\\arctan\\left(\\frac{1}{110{,}443}\\right)" ) formula.scale(0.5) return formula def get_viete(self): formula = OldTex( "\\frac{2}{\\pi} = " "\\frac{\\sqrt{2}}{2} \\cdot" "\\frac{\\sqrt{2 + \\sqrt{2}}}{2} \\cdot" "\\frac{\\sqrt{2 + \\sqrt{2 + \\sqrt{2}}}}{2} \\cdots" ) formula.scale(0.5) return formula def get_measuring_tape(self): return OldTexText("Measuring tape").scale(0.75) def get_monte_carlo(self): return OldTexText("Monte Carlo").scale(0.75) def get_basel(self): formula = OldTex( "\\frac{\\pi^2}{6} = " "\\sum_{n=1}^\\infty \\frac{1}{n^2}" ) formula.scale(0.5) return formula def get_blocks_image(self): scene = BlocksAndWallScene( write_to_movie=False, skip_animations=True, count_clacks=False, floor_y=1, wall_x=0, n_wall_ticks=6, sliding_blocks_config={ "block1_config": { "mass": 1e2, "velocity": -0.01, "distance": 3.5 }, "block2_config": { "distance": 1, "velocity": 0, }, } ) group = VGroup( scene.wall, scene.floor, scene.blocks.block1, scene.blocks.block2, ) group.set_width(3) return group class StepsOfTheAlgorithm(TeacherStudentsScene): def construct(self): steps = self.get_steps() steps.arrange( DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT, ) steps.to_corner(UL) steps.scale(0.8) for step in steps: self.play( FadeInFromDown(step[0]), self.teacher.change, "raise_right_hand" ) self.play( Write(step[1], run_time=2), self.change_students( *["pondering"] * 3, look_at=step, ) ) self.wait() self.play_student_changes( "sassy", "erm", "confused", look_at=steps, added_anims=[self.teacher.change, "happy"] ) self.wait(3) def get_steps(self): return VGroup( OldTexText("Step 1:", "Implement a physics engine"), OldTexText( "Step 2:", "Choose the number of digits, $d$,\\\\" "of $\\pi$ that you want to compute" ), OldTexText( "Step 3:", "Set one mass to $100^{d - 1}$,\\\\" "the other to $1$" ), OldTexText("Step 4:", "Count collisions"), ) class StepsOfTheAlgorithmJustTitles(StepsOfTheAlgorithm): def construct(self): self.remove(*self.pi_creatures) titles = self.get_steps() for title in titles: title.scale(1.5) title.to_edge(UP) last_title = VectorizedPoint() for title in titles: self.play( FadeInFromDown(title), FadeOut(last_title, UP), ) self.wait() last_title = title class BlocksAndWallExampleToShowWithSteps(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e22, "velocity": -1, "label_text": "$100^{(12 - 1)}$\\,kg", "width": 2, }, "collect_clack_data": False, }, "wait_time": 25, "counter_group_shift_vect": 5 * LEFT, "count_clacks": True, "include_sound": False, "show_flash_animations": False, } class CompareToGalacticMass(Scene): def construct(self): self.add_digits_of_pi() self.show_mass() self.show_galactic_black_holes() self.show_total_count() def add_digits_of_pi(self): # 20 digits of pi digits = OldTex("3.1415926535897932384...") digits.set_width(FRAME_WIDTH - 3) digits.to_edge(UP) highlighted_digits = VGroup(*[ d.copy().set_background_stroke(color=BLUE, width=5) for d in [digits[0], *digits[2:-3]] ]) counter = Integer(0) counter.scale(1.5) counter.set_color(BLUE) brace = VMobject() self.add(counter, brace) for k in range(len(highlighted_digits)): if k == 0: self.add(digits[0]) else: self.remove(highlighted_digits[k - 1]) self.add(digits[k + 1]) self.add(highlighted_digits[k]) counter.increment_value() brace.become(Brace(highlighted_digits[:k + 1], DOWN)) counter.next_to(brace, DOWN) self.wait(0.1) self.add(digits) self.remove(*highlighted_digits) digits_word = OldTexText("digits") digits_word.scale(1.5) digits_word.match_color(counter) counter.generate_target() group = VGroup(counter.target, digits_word) group.arrange( RIGHT, index_of_submobject_to_align=0, aligned_edge=DOWN, buff=0.7, ) group.next_to(brace, DOWN) self.play( MoveToTarget(counter), FadeIn(digits_word, LEFT), ) self.wait() self.pi_digits_group = VGroup( digits, brace, counter, digits_word ) def show_mass(self): bw_scene = BlocksAndWallExample( write_to_movie=False, skip_animations=True, count_clacks=False, show_flash_animations=False, floor_y=0, wall_x=-2, n_wall_ticks=8, sliding_blocks_config={ "block1_config": { "mass": 1e6, "velocity": -0.01, "distance": 4.5, "label_text": "$100^{(20 - 1)}$ kg", "fill_color": BLACK, }, "block2_config": { "distance": 1, "velocity": 0, }, } ) block1 = bw_scene.blocks.block1 block2 = bw_scene.blocks.block2 group = VGroup( bw_scene.wall, bw_scene.floor, block1, block2 ) group.center() group.to_edge(DOWN) arrow = Vector(2 * LEFT, color=RED) arrow.shift(block1.get_center()) group.add(arrow) brace = Brace(block1.label[:-2], UP, buff=SMALL_BUFF) number_words = OldTexText( "100", *["billion"] * 4, ) number_words.next_to(brace, UP, buff=SMALL_BUFF) VGroup(brace, number_words).set_color(YELLOW) self.play(Write(group)) self.wait() last_word = number_words[0].copy() last_word.next_to(brace, UP, SMALL_BUFF) self.play( GrowFromCenter(brace), FadeInFromDown(last_word), ) for k in range(1, len(number_words) + 1): self.remove(last_word) last_word = number_words[:k].copy() last_word.next_to(brace, UP, SMALL_BUFF) self.add(last_word) self.wait(0.4) self.wait() self.remove(last_word) self.add(number_words) group.add(brace, number_words) self.play(group.to_corner, DL) self.block1 = block1 self.block2 = block2 self.block_setup_group = group def show_galactic_black_holes(self): black_hole = SVGMobject(file_name="black_hole") black_hole.set_color(BLACK) black_hole.set_sheen(0.2, UL) black_hole.set_height(1) black_holes = VGroup(*[ black_hole.copy() for k in range(10) ]) black_holes.arrange_in_grid(5, 2) black_holes.to_corner(DR) random.shuffle(black_holes.submobjects) for bh in black_holes: bh.save_state() bh.scale(3) bh.set_fill(GREY_D, 0) equals = OldTex("=") equals.scale(2) equals.next_to(self.block1, RIGHT) words = OldTexText("10x Sgr A$^*$ \\\\ supermassive \\\\ black hole") words.next_to(equals, RIGHT) self.add(words) self.play( Write(equals), Write(words), LaggedStartMap( Restore, black_holes, run_time=3 ) ) self.wait() self.black_hole_words = VGroup(equals, words) self.black_holes = black_holes def show_total_count(self): digits = self.pi_digits_group[0] to_fade = self.pi_digits_group[1:] tex_string = "{:,}".format(31415926535897932384) number = OldTex(tex_string) number.scale(1.5) number.to_edge(UP) commas = VGroup(*[ mob for c, mob in zip(tex_string, number) if c is "," ]) dots = VGroup(*[ mob for c, mob in zip(digits.get_tex(), digits) if c is "." ]) self.play(FadeOut(to_fade)) self.play( ReplacementTransform( VGroup(*filter(lambda m: m not in dots, digits)), VGroup(*filter(lambda m: m not in commas, number)), ), ReplacementTransform( dots, commas, lag_ratio=0.5, run_time=2 ) ) group0 = number[:2].copy() group1 = number[3:3 + 9 + 2].copy() group2 = number[-(9 + 2):].copy() for group in group0, group1, group2: group.set_background_stroke(color=BLUE, width=5) self.add(group) self.wait(0.5) self.remove(group) class BlocksAndWallExampleGalacticMass(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e10, "velocity": -1, "label_text": "$100^{(20 - 1)}$\\,kg", "width": 2, }, }, "wait_time": 25, "counter_group_shift_vect": 5 * LEFT, "count_clacks": False, } def setup(self): super().setup() words = OldTexText( "Burst of $10^{38}$ clacks per second" ) words.scale(1.5) words.to_edge(UP) self.add(words) class RealPhysicsVsThis(Scene): def construct(self): physics = OldTexText("Real physics") this = OldTexText("This process") this.set_color() physics.to_edge(LEFT) this.next_to(physics) self.add(physics, this) self.play( this.shift, FRAME_WIDTH * RIGHT, rate_func=rush_into, run_time=3, ) self.wait() class CompareAlgorithmToPhysics(PiCreatureScene): def construct(self): morty = self.pi_creature right_pic = ImageMobject( self.get_image_file_path().replace( str(self), "PiComputingAlgorithmsAxes" ) ) right_rect = SurroundingRectangle(right_pic, buff=0, color=WHITE) right_pic.add(right_rect) right_pic.set_height(3) right_pic.next_to(morty, UR) right_pic.shift_onto_screen() left_rect = right_rect.copy() left_rect.next_to(morty, UL) left_rect.shift_onto_screen() self.play( FadeInFromDown(right_pic), morty.change, "raise_right_hand", ) self.wait() self.play( FadeInFromDown(left_rect), morty.change, "raise_left_hand", ) self.wait() digits = OldTex("3.141592653589793238462643383279502884197...") digits.set_width(FRAME_WIDTH - 1) digits.to_edge(UP) self.play( FadeOut(right_pic, 5 * RIGHT), # FadeOut(left_rect, 5 * LEFT), FadeOut(left_rect), PiCreatureBubbleIntroduction( morty, "This doesn't seem \\\\ like me...", bubble_type=ThoughtBubble, bubble_config={"direction": LEFT}, target_mode="pondering", look_at=left_rect, ), LaggedStartMap( FadeInFrom, digits, lambda m: (m, LEFT), run_time=5, lag_ratio=0.2, ) ) self.blink() self.wait() self.play(morty.change, "confused", left_rect) self.wait(5) def create_pi_creature(self): return Mortimer().flip().to_edge(DOWN) class AskAboutWhy(TeacherStudentsScene): def construct(self): circle = Circle(radius=2, color=YELLOW) circle.next_to(self.teacher, UL) ke_conservation = OldTex( "\\frac{1}{2}m_1 v_1^2 + " "\\frac{1}{2}m_2 v_2^2 = \\text{const.}" ) ke_conservation.move_to(circle) self.student_says("But why?") self.play_student_changes( "erm", "raise_left_hand", "sassy", added_anims=[self.teacher.change, "happy"] ) self.wait() self.play( ShowCreation(circle), RemovePiCreatureBubble(self.students[1]), self.teacher.change, "raise_right_hand", ) self.play_all_student_changes( "pondering", look_at=circle ) self.wait(2) self.play( Write(ke_conservation), circle.stretch, 1.5, 0, ) self.play_all_student_changes("confused") self.look_at(circle) self.wait(3) class LightBouncingNoFanning(LightBouncing): CONFIG = { "mirror_shift_vect": 2 * DOWN, "mirror_length": 6, "beam_start_x": 8, "beam_height": 0.5, } class LightBouncingFanning(LightBouncingNoFanning): CONFIG = { "show_fanning": True, } class NextVideo(Scene): def construct(self): videos = VGroup(*[VideoIcon() for x in range(2)]) videos.set_height(2) for video in videos: video.set_color(BLUE) video.set_sheen(0.5, UL) videos.arrange(RIGHT, buff=2) titles = VGroup( OldTexText("Here and now"), OldTexText("Solution"), ) for title, video in zip(titles, videos): # title.scale(1.5) title.next_to(video, UP) video.add(title) dots = OldTexText(".....") dots.scale(2) dots.move_to(videos) mid_words = OldTexText( "Patient\\\\", "problem\\\\", "solving" ) mid_words.next_to(dots, DOWN) randy = Randolph(height=1) randy.next_to(dots, UP, SMALL_BUFF) thought_bubble = ThoughtBubble(height=2, width=2, direction=LEFT) thought_bubble.set_stroke(width=2) thought_bubble.move_to(randy.get_corner(UR), DL) speech_bubble = SpeechBubble(height=2, width=2) speech_bubble.pin_to(randy) speech_bubble.write("What do \\\\ you think?") friends = VGroup( PiCreature(color=BLUE_E), PiCreature(color=BLUE_C), Mortimer() ) friends.set_height(1) friends.arrange(RIGHT, buff=MED_SMALL_BUFF) friends[:2].next_to(randy, LEFT) friends[2].next_to(randy, RIGHT) self.add(videos[0]) self.wait() self.play( TransformFromCopy(*videos), ) self.play(Write(dots)) self.wait() self.play( LaggedStartMap( FadeInFrom, mid_words, lambda m: (m, UP), lag_ratio=0.8, ), randy.change, "pondering", VFadeIn(randy), videos.space_out_submobjects, 1.3, ) self.play(ShowCreation(thought_bubble)) self.play(Blink(randy)) self.play( Uncreate(thought_bubble), ShowCreation(speech_bubble), Write(speech_bubble.content), randy.change, "maybe", friends[0].eyes, LaggedStartMap(FadeInFromDown, friends), videos.space_out_submobjects, 1.6, ) self.play( LaggedStartMap( ApplyMethod, friends, lambda m: (m.change, "pondering"), run_time=1, lag_ratio=0.7, ) ) self.play(Blink(friends[2])) self.play(friends[0].change, "confused") self.wait() class EndScreen(Scene): def construct(self): width = (475 / 1280) * FRAME_WIDTH height = width * (323 / 575) video_rect = Rectangle( width=width, height=height, ) video_rect.shift(UP) video_rects = VGroup(*[ video_rect.copy().set_color(color) for color in [BLUE_E, BLUE_C, BLUE_D, GREY_BROWN] ]) for rect in video_rects[1::2]: rect.reverse_points() video_rect.set_fill(GREY_D, 0.5) video_rect.set_stroke(GREY_BROWN, 0.5) date = OldTexText( "Solution will be\\\\" "posted", "1/20/19", ) date[1].set_color(YELLOW) date.set_width(video_rect.get_width() - 2 * MED_SMALL_BUFF) date.move_to(video_rect) handle = OldTexText("@3blue1brown") handle.next_to(video_rect, DOWN, MED_LARGE_BUFF) self.add(video_rect, date, handle) for n in range(10): self.play( FadeOut(video_rects[(n - 1) % 4]), ShowCreation(video_rects[n % 4]), run_time=2, ) class Thumbnail(BlocksAndWallExample, MovingCameraScene): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e4, "velocity": -1.5, }, "collect_clack_data": False, }, "wait_time": 0, "count_clacks": False, "show_flash_animations": False, "floor_y": -3.0, "include_sound": False, } def setup(self): MovingCameraScene.setup(self) BlocksAndWallExample.setup(self) def construct(self): self.camera_frame.shift(0.9 * UP) # self.mobjects.insert( # 0, # FullScreenFadeRectangle( # color=GREY_D, # opacity=0.5, # sheen_direction=UL, # sheen=0.5, # ), # ) self.thicken_lines() self.grow_labels() self.add_vector() self.add_text() def thicken_lines(self): self.floor.set_stroke(WHITE, 10) self.wall.set_stroke(WHITE, 10) self.wall[1:].set_stroke(WHITE, 4) def grow_labels(self): blocks = self.blocks for block in blocks.block1, blocks.block2: block.remove(block.label) block.label.scale(2.5, about_point=block.get_top()) self.add(block.label) def add_vector(self): blocks = self.blocks arrow = self.arrow = Vector( 2.5 * LEFT, color=RED, rectangular_stem_width=1.5, tip_length=0.5 ) arrow.move_to(blocks.block1.get_center(), RIGHT) arrow.add_to_back( arrow.copy().set_stroke(GREY, 5) ) self.add(arrow) def add_text(self): question = self.question = OldTexText( "How many\\\\collisions?" ) question.scale(2.5) question.to_edge(UP) question.set_color(YELLOW) question.set_stroke(RED, 2, background=True) self.add(question)
from _2019.clacks import question from _2019.clacks.solution2 import block_collision_scenes from _2019.clacks.solution2 import mirror_scenes from _2019.clacks.solution2 import pi_creature_scenes from _2019.clacks.solution2 import position_phase_space from _2019.clacks.solution2 import simple_scenes from _2019.clacks.solution2 import wordy_scenes OUTPUT_DIRECTORY = "clacks/solution2" SCENES_IN_ORDER = [ question.NameIntro, block_collision_scenes.IntroducePreviousTwoVideos, block_collision_scenes.PreviousTwoVideos, simple_scenes.ComingUpWrapper, wordy_scenes.ConnectionToOptics, pi_creature_scenes.OnAnsweringTwice, simple_scenes.LastVideoWrapper, simple_scenes.Rectangle, simple_scenes.ShowRectangleCreation, simple_scenes.LeftEdge, simple_scenes.RightEdge, position_phase_space.IntroducePositionPhaseSpace, position_phase_space.UnscaledPositionPhaseSpaceMass100, simple_scenes.FourtyFiveDegreeLine, position_phase_space.EqualMassCase, pi_creature_scenes.AskAboutEqualMassMomentumTransfer, position_phase_space.FailedAngleRelation, position_phase_space.UnscaledPositionPhaseSpaceMass10, pi_creature_scenes.ComplainAboutRelevanceOfAnalogy, simple_scenes.LastVideoWrapper, simple_scenes.NoteOnEnergyLostToSound, position_phase_space.RescaleCoordinates, wordy_scenes.ConnectionToOpticsTransparent, position_phase_space.RescaleCoordinatesMass16, position_phase_space.RescaleCoordinatesMass64, position_phase_space.RescaleCoordinatesMass100, position_phase_space.IntroduceVelocityVector, position_phase_space.IntroduceVelocityVectorWithoutZoom, position_phase_space.ShowMomentumConservation, wordy_scenes.RearrangeMomentumEquation, simple_scenes.DotProductVideoWrapper, simple_scenes.ShowDotProductMeaning, position_phase_space.JustTheProcessNew, mirror_scenes.ShowTrajectoryWithChangingTheta, pi_creature_scenes.ReplaceOneTrickySceneWithAnother, mirror_scenes.MirrorAndWiresOverlay, pi_creature_scenes.NowForTheGoodPart, mirror_scenes.ReflectWorldThroughMirrorNew, mirror_scenes.ReflectWorldThroughMirrorThetaPoint2, mirror_scenes.ReflectWorldThroughMirrorThetaPoint1, simple_scenes.AskAboutAddingThetaToItself, simple_scenes.AskAboutAddingThetaToItselfThetaPoint1, simple_scenes.AskAboutAddingThetaToItselfThetaPoint2, simple_scenes.FinalFormula, simple_scenes.ArctanSqrtPoint1Angle, simple_scenes.ReviewWrapper, simple_scenes.SurprisedRandy, simple_scenes.TwoSolutionsWrapper, simple_scenes.FinalQuote, simple_scenes.EndScreen, simple_scenes.ClacksSolution2Thumbnail, ]
from manim_imports_ext import * class OnAnsweringTwice(TeacherStudentsScene): def construct(self): question = OldTexText("Why $\\pi$?") question.move_to(self.screen) question.to_edge(UP) other_questions = VGroup( OldTexText("Frequency of collisions?"), OldTexText("Efficient simulation?"), OldTexText("Time until last collision?"), ) for mob in other_questions: mob.move_to(self.hold_up_spot, DOWN) self.add(question) self.student_says( "But we already \\\\ solved it", bubble_config={"direction": LEFT}, target_mode="raise_left_hand", added_anims=[self.teacher.change, "thinking"] ) self.play_student_changes("sassy", "angry") self.wait() self.play( RemovePiCreatureBubble(self.students[2]), self.change_students("erm", "erm"), ApplyMethod( question.move_to, self.hold_up_spot, DOWN, path_arc=-90 * DEGREES, ), self.teacher.change, "raise_right_hand", ) shown_questions = VGroup(question) for oq in other_questions: self.play( shown_questions.shift, 0.85 * UP, FadeInFromDown(oq), self.change_students( *["pondering"] * 3, look_at=oq ) ) shown_questions.add(oq) self.wait(3) class AskAboutEqualMassMomentumTransfer(TeacherStudentsScene): def construct(self): self.student_says("Why?") self.play_student_changes("confused", "confused") self.wait() self.play( RemovePiCreatureBubble(self.students[2]), self.teacher.change, "raise_right_hand" ) self.play_all_student_changes("pondering") self.look_at(self.hold_up_spot + 2 * UP) self.wait(5) class ComplainAboutRelevanceOfAnalogy(TeacherStudentsScene): def construct(self): self.student_says( "Why would \\\\ you care", target_mode="maybe" ) self.play_student_changes( "angry", "sassy", "maybe", added_anims=[self.teacher.change, "guilty"] ) self.wait(2) self.play( self.teacher.change, "raise_right_hand", self.change_students( "pondering", "erm", "pondering", look_at=self.hold_up_spot, ), RemovePiCreatureBubble(self.students[2]) ) self.play( self.students[2].change, "thinking", self.hold_up_spot + UP, ) self.wait(3) class ReplaceOneTrickySceneWithAnother(TeacherStudentsScene): def construct(self): self.student_says( "This replaces one tricky\\\\problem with another", index=1, target_mode="sassy", added_anims=[self.teacher.change, "happy"], ) self.play_student_changes("erm", "sassy", "angry") self.wait(4) self.play( RemovePiCreatureBubble(self.students[1]), self.teacher.change, "raise_right_hand", self.change_students(*3 * ["pondering"]) ) self.look_at(self.hold_up_spot + 2 * UP) self.wait(5) class NowForTheGoodPart(TeacherStudentsScene): def construct(self): self.teacher_says( r"Now for the \\ good part!", target_mode="hooray", added_anims=[self.change_students( "hooray", "surprised", "happy" )], ) self.wait(2)
from manim_imports_ext import * class MirrorScene(Scene): CONFIG = { "center": DOWN + 3 * LEFT, "line_length": FRAME_WIDTH, "start_theta": np.arctan(0.25), "start_y_offset": 0.5, "start_x_offset": 8, "arc_config": { "radius": 1, "stroke_color": WHITE, "stroke_width": 2, }, "trajectory_point_spacing": 0.1, "trajectory_style": { "stroke_color": YELLOW, "stroke_width": 2, }, "ghost_lines_style": { "stroke_color": WHITE, "stroke_width": 1, "stroke_opacity": 0.5, }, # "reflect_sound": "ping", "reflect_sound": "pen_click", } def setup(self): self.theta_tracker = ValueTracker(self.start_theta) self.start_y_offset_tracker = ValueTracker(self.start_y_offset) self.start_x_offset_tracker = ValueTracker(self.start_x_offset) self.center_tracker = VectorizedPoint(self.center) self.beam_point = VectorizedPoint(np.array([ self.get_start_x_offset(), self.get_start_y_offset(), 0 ])) self.ghost_beam_point = self.beam_point.copy() self.is_sound_allowed = False self.mirrors = self.get_mirrors() self.arc = self.get_arc() self.theta_symbol = self.get_theta_symbol() self.trajectory = self.get_trajectory() self.ghost_trajectory = self.get_ghost_trajectory() self.theta_display = self.get_theta_display() self.count_display_word = self.get_count_display_word() self.count_display_number = self.get_count_display_number() self.last_count = self.get_count() # Add some of them self.add( self.mirrors, self.arc, self.theta_symbol, self.theta_display, self.count_display_word, self.count_display_number, ) def get_center(self): return self.center_tracker.get_location() def get_theta(self): return self.theta_tracker.get_value() def get_start_y_offset(self): return self.start_y_offset_tracker.get_value() def get_start_x_offset(self): return self.start_x_offset_tracker.get_value() def get_mirror(self): mirror = VGroup( Line(ORIGIN, 2 * RIGHT), Line(ORIGIN, 2 * RIGHT), Line(ORIGIN, (self.line_length - 4) * RIGHT), ) mirror.arrange(RIGHT, buff=0) mirror.set_stroke(width=5) mirror[0::2].set_stroke((WHITE, GREY)) mirror[1::2].set_stroke((GREY, WHITE)) return mirror def get_mirrors(self): mirrors = VGroup(self.get_mirror(), self.get_mirror()) def update_mirrors(mirrors): m1, m2 = mirrors center = self.get_center() theta = self.get_theta() m1.move_to(center, DL) m2.become(m1) m2.rotate(theta, about_point=center) mirrors.add_updater(update_mirrors) return mirrors def get_arc(self, radius=0.5): return always_redraw(lambda: Arc( start_angle=0, angle=self.get_theta(), arc_center=self.get_center(), **self.arc_config, )) def get_theta_symbol(self, arc=None, buff=0.15): if arc is None: arc = self.arc symbol = OldTex("\\theta") def update_symbol(symbol): midpoint = arc.point_from_proportion(0.5) center = arc.arc_center vect = (midpoint - center) max_height = 0.8 * arc.get_height() if symbol.get_height() > max_height: symbol.set_height(max_height) symbol.move_to( center + vect + buff * normalize(vect) ) symbol.add_updater(update_symbol) return symbol def get_ghost_collision_points(self): x = self.get_start_x_offset() y = self.get_start_y_offset() theta = self.get_theta() points = [np.array([x, y, 0])] points += [ np.array([x, y, 0]) for k in range(1, int(PI / theta) + 1) for x in [y / np.tan(k * theta)] if abs(x) < FRAME_WIDTH ] points.append(points[-1] + x * LEFT) points = np.array(points) points += self.get_center() return points def get_collision_points(self, ghost_points=None): if ghost_points is None: ghost_points = self.get_ghost_collision_points() theta = self.get_theta() center = self.get_center() points = [] for ghost_point in ghost_points: vect = ghost_point - center angle = angle_of_vector(vect) k = int(angle / theta) if k % 2 == 0: vect = rotate_vector(vect, -k * theta) else: vect = rotate_vector(vect, -(k + 1) * theta) vect[1] = abs(vect[1]) points.append(center + vect) return points def get_trajectory(self, collision_points=None): if collision_points is None: collision_points = self.get_collision_points() points = [] spacing = self.trajectory_point_spacing for p0, p1 in zip(collision_points, collision_points[1:]): n_intervals = max(1, int(get_norm(p1 - p0) / spacing)) for alpha in np.linspace(0, 1, n_intervals + 1): points.append(interpolate(p0, p1, alpha)) trajectory = VMobject() trajectory.set_points_as_corners(points) trajectory.set_style(**self.trajectory_style) return trajectory def get_ghost_trajectory(self): return self.get_trajectory(self.get_ghost_collision_points()) def get_collision_point_counts(self, collision_points=None): if collision_points is None: collision_points = self.get_collision_points()[1:-1] result = VGroup() for n, point in enumerate(collision_points): count = Integer(n + 1) count.set_height(0.25) vect = UP if n % 2 == 0 else DOWN count.next_to(point, vect, SMALL_BUFF) result.add(count) return result def get_collision_count_anim(self, collision_point_counts=None): if collision_point_counts is None: collision_point_counts = self.get_collision_point_counts() group = VGroup() def update(group): count = self.get_count() if count == 0: group.submobjects = [] elif count < len(collision_point_counts) + 1: group.submobjects = [ collision_point_counts[count - 1] ] return UpdateFromFunc(group, update, remover=True) def get_ghost_lines(self): line = self.mirrors[0] center = self.get_center() theta = self.get_theta() lines = VGroup() for k in range(1, int(PI / theta) + 2): new_line = line.copy() new_line.rotate(k * theta, about_point=center) lines.add(new_line) lines.set_style(**self.ghost_lines_style) return lines # Displays def get_theta_display(self): lhs = OldTex("\\theta = ") radians = DecimalNumber() radians.add_updater( lambda m: m.set_value(self.get_theta()) ) radians_word = OldTexText("radians") radians_word.next_to( radians, RIGHT, aligned_edge=DOWN ) equals = OldTex("=") degrees = Integer(0, unit="^\\circ") degrees.add_updater( lambda m: m.set_value( int(np.round(self.get_theta() / DEGREES)) ) ) group = VGroup(lhs, radians, radians_word, equals, degrees) group.arrange(RIGHT, aligned_edge=DOWN) equals.align_to(lhs[-1], DOWN) group.to_corner(UL) return group def get_count_display_word(self): result = OldTexText("\\# Bounces: ") result.to_corner(UL) result.shift(DOWN) result.set_color(YELLOW) return result def get_count_display_number(self, count_display_word=None, ghost_beam_point=None): if count_display_word is None: count_display_word = self.count_display_word result = Integer() result.next_to( count_display_word[-1], RIGHT, aligned_edge=DOWN, ) result.set_color(YELLOW) result.add_updater( lambda m: m.set_value(self.get_count()) ) return result def get_count(self, ghost_beam_point=None): if ghost_beam_point is None: ghost_beam_point = self.ghost_beam_point.get_location() angle = angle_of_vector( ghost_beam_point - self.get_center() ) return int(angle / self.get_theta()) # Sounds def allow_sound(self): self.is_sound_allowed = True def disallow_sound(self): self.is_sound_allowed = False def update_mobjects(self, dt): super().update_mobjects(dt) if self.get_count() != self.last_count: self.last_count = self.get_count() if self.is_sound_allowed: self.add_sound( self.reflect_sound, gain=-20, ) # Bouncing animations def show_bouncing(self, run_time=5): trajectory = self.trajectory ghost_trajectory = self.get_ghost_trajectory() beam_anims = self.get_shooting_beam_anims( trajectory, ghost_trajectory ) count_anim = self.get_collision_count_anim() self.allow_sound() self.play(count_anim, *beam_anims, run_time=run_time) self.disallow_sound() def get_special_flash(self, mobject, stroke_width, time_width, rate_func=linear, **kwargs): kwargs["rate_func"] = rate_func mob_copy = mobject.copy() mob_copy.set_stroke(width=stroke_width) mob_copy.time_width = time_width return UpdateFromAlphaFunc( mob_copy, lambda m, a: m.pointwise_become_partial( mobject, max(a - (1 - a) * m.time_width, 0), a, ), **kwargs ) def get_shooting_beam_anims(self, trajectory, ghost_trajectory=None, update_beam_point=True, num_flashes=20, min_time_width=0.01, max_time_width=0.5, min_stroke_width=0.01, max_stroke_width=6, fade_trajectory=True, faded_trajectory_width=0.25, faded_trajectory_time_exp=0.2, ): # Most flashes result = [ self.get_special_flash(trajectory, stroke_width, time_width) for stroke_width, time_width in zip( np.linspace(max_stroke_width, min_stroke_width, num_flashes), np.linspace(min_time_width, max_time_width, num_flashes), ) ] # Make sure beam point is updated if update_beam_point: smallest_flash = result[0] result.append( UpdateFromFunc( self.beam_point, lambda m: m.move_to(smallest_flash.mobject.get_points()[-1]) ) ) # Make sure ghost beam point is updated if ghost_trajectory: ghost_flash = self.get_special_flash( ghost_trajectory, 0, min_time_width, ) ghost_beam_point_update = UpdateFromFunc( self.ghost_beam_point, lambda m: m.move_to(ghost_flash.mobject.get_points()[-1]) ) result += [ ghost_flash, ghost_beam_point_update, ] # Fade trajectory if fade_trajectory: ftte = faded_trajectory_time_exp result.append( ApplyMethod( trajectory.set_stroke, {"width": faded_trajectory_width}, rate_func=lambda t: there_and_back(t)**ftte ), ) return result class ShowTrajectoryWithChangingTheta(MirrorScene): def construct(self): trajectory = self.trajectory self.add(trajectory) angles = [30 * DEGREES, 10 * DEGREES] ys = [1, 1] self.show_bouncing() for angle, y in zip(angles, ys): rect = SurroundingRectangle(self.theta_display) self.play( self.theta_tracker.set_value, angle, self.start_y_offset_tracker.set_value, y, FadeIn(rect, rate_func=there_and_back, remover=True), UpdateFromFunc( trajectory, lambda m: m.become(self.get_trajectory()) ), run_time=2 ) self.show_bouncing() self.wait(2) class ReflectWorldThroughMirrorNew(MirrorScene): CONFIG = { "start_y_offset": 1.25, "center": DOWN, "randy_height": 1, "partial_trajectory_values": [ 0, 0.22, 0.28, 0.315, 1, ], } def construct(self): self.add_randy() self.shift_displays() self.add_ghost_beam_point() self.up_through_first_bounce() self.create_reflected_worlds() self.create_reflected_trajectories() self.first_reflection() self.next_reflection(2) self.next_reflection(3) self.unfold_all_reflected_worlds() self.show_completed_beam() self.blink_all_randys() self.add_randy_updates() self.show_all_trajectories() self.focus_on_two_important_trajectories() def add_randy(self): randy = self.randy = Randolph() randy.flip() randy.set_height(self.randy_height) randy.change("pondering") randy.align_to(self.mirrors, DOWN) randy.shift(0.01 * UP) randy.to_edge(RIGHT, buff=1) randy.tracked_mobject = self.trajectory randy.add_updater( lambda m: m.look_at( m.tracked_mobject.get_points()[-1] ) ) self.add(randy) def shift_displays(self): VGroup( self.theta_display, self.count_display_word, self.count_display_number, ).to_edge(DOWN) def add_ghost_beam_point(self): self.ghost_beam_point.add_updater( lambda m: m.move_to( self.ghost_trajectory.get_points()[-1] ) ) self.add(self.ghost_beam_point) def up_through_first_bounce(self): self.play(*self.get_both_partial_trajectory_anims( *self.partial_trajectory_values[:2] )) self.wait() def create_reflected_worlds(self): mirrors = self.mirrors triangle = Polygon(*[ mirrors.get_corner(corner) for corner in (DR, DL, UR) ]) triangle.set_stroke(width=0) triangle.set_fill(BLUE_E, opacity=0) world = self.world = VGroup( triangle, mirrors, self.arc, self.theta_symbol, self.randy, ) reflected_worlds = self.get_reflected_worlds(world) self.reflected_worlds = reflected_worlds # Alternating triangle opacities for rw in reflected_worlds[::2]: rw[0].set_fill(opacity=0.25) def create_reflected_trajectories(self): self.reflected_trajectories = always_redraw( lambda: self.get_reflected_worlds(self.trajectory) ) def first_reflection(self): reflected_trajectory = self.reflected_trajectories[0] reflected_world = self.reflected_worlds[0] world = self.world trajectory = self.trajectory ghost_trajectory = self.ghost_trajectory self.play( TransformFromCopy(world, reflected_world), TransformFromCopy(trajectory, reflected_trajectory), run_time=2 ) beam_anims = self.get_shooting_beam_anims( ghost_trajectory, fade_trajectory=False, ) self.play( *[ ApplyMethod(m.set_stroke, GREY, 1) for m in (trajectory, reflected_trajectory) ] + beam_anims, run_time=2 ) for x in range(2): self.play(*beam_anims, run_time=2) ghost_trajectory.set_stroke(YELLOW, 4) self.bring_to_front(ghost_trajectory) self.play(FadeIn(ghost_trajectory)) self.wait() def next_reflection(self, index=2): i = index self.play( *self.get_both_partial_trajectory_anims( *self.partial_trajectory_values[i - 1:i + 1] ), UpdateFromFunc( VMobject(), # Null lambda m: self.reflected_trajectories.update(), remover=True, ), ) anims = [ TransformFromCopy(*reflections[i - 2:i]) for reflections in [ self.reflected_worlds, self.reflected_trajectories ] ] self.play(*anims, run_time=2) self.add(self.ghost_trajectory) self.wait() def unfold_all_reflected_worlds(self): worlds = self.reflected_worlds trajectories = self.reflected_trajectories pairs = [ (VGroup(w1, t1), VGroup(w2, t2)) for w1, w2, t1, t2 in zip( worlds[2:], worlds[3:], trajectories[2:], trajectories[3:], ) ] new_worlds = VGroup() # Brought to you by Dvorak for m1, m2 in pairs: m2.pre_world = m1.copy() new_worlds.add(m2) for mob in new_worlds: mob.save_state() mob.become(mob.pre_world) mob.fade(1) self.play(LaggedStartMap( Restore, new_worlds, lag_ratio=0.4, run_time=3 )) def show_completed_beam(self): self.add(self.reflected_trajectories) self.add(self.ghost_trajectory) self.play(*self.get_both_partial_trajectory_anims( *self.partial_trajectory_values[-2:], run_time=7 )) def blink_all_randys(self): randys = self.randys = VGroup(self.randy) randys.add(*[rw[-1] for rw in self.reflected_worlds]) self.play(LaggedStartMap(Blink, randys)) def add_randy_updates(self): # Makes it run slower, but it's fun! reflected_randys = VGroup(*[ rw[-1] for rw in self.reflected_worlds ]) reflected_randys.add_updater( lambda m: m.become( self.get_reflected_worlds(self.randy) ) ) self.add(reflected_randys) def show_all_trajectories(self): ghost_trajectory = self.ghost_trajectory reflected_trajectories = self.reflected_trajectories trajectory = self.trajectory reflected_trajectories.suspend_updating() trajectories = VGroup(trajectory, *reflected_trajectories) all_mirrors = VGroup(*[ world[1] for world in it.chain([self.world], self.reflected_worlds) ]) self.play( FadeOut(ghost_trajectory), trajectories.set_stroke, YELLOW, 0.5, all_mirrors.set_stroke, {"width": 1}, ) # All trajectory light beams flash_groups = [ self.get_shooting_beam_anims( mob, fade_trajectory=False, ) for mob in trajectories ] all_flashes = list(it.chain(*flash_groups)) # Have all the pi creature eyes follows self.randy.tracked_mobject = all_flashes[0].mobject # Highlight the illustory straight beam red_ghost = self.ghost_trajectory.copy() red_ghost.set_color(RED) red_ghost_beam = self.get_shooting_beam_anims( red_ghost, fade_trajectory=False, ) num_repeats = 3 for x in range(num_repeats): anims = list(all_flashes) if x == num_repeats - 1: anims += list(red_ghost_beam) self.randy.tracked_mobject = red_ghost_beam[0].mobject for flash in all_flashes: if hasattr(flash.mobject, "time_width"): flash.mobject.set_stroke( width=0.25 * flash.mobject.get_stroke_width() ) flash.mobject.time_width *= 0.25 self.play(*anims, run_time=3) def focus_on_two_important_trajectories(self): self.ghost_trajectory.set_stroke(YELLOW, 1) self.play( FadeOut(self.reflected_trajectories), FadeIn(self.ghost_trajectory), self.trajectory.set_stroke, YELLOW, 1, ) self.add_flashing_windows() t_beam_anims = self.get_shooting_beam_anims(self.trajectory) gt_beam_anims = self.get_shooting_beam_anims(self.ghost_trajectory) self.ghost_beam_point.clear_updaters() self.ghost_beam_point.add_updater( lambda m: m.move_to( gt_beam_anims[0].mobject.get_points()[-1] ) ) self.randy.tracked_mobject = t_beam_anims[0].mobject self.allow_sound() self.play( *t_beam_anims, *gt_beam_anims, run_time=6 ) self.add_room_color_updates() self.play( *t_beam_anims, *gt_beam_anims, run_time=6 ) self.blink_all_randys() self.play( *t_beam_anims, *gt_beam_anims, run_time=6 ) # Helpers def get_reflected_worlds(self, world, n_reflections=None): theta = self.get_theta() center = self.get_center() if n_reflections is None: n_reflections = int(PI / theta) result = VGroup() last_world = world for n in range(n_reflections): vect = rotate_vector(RIGHT, (n + 1) * theta) reflected_world = last_world.copy() reflected_world.clear_updaters() reflected_world.rotate( PI, axis=vect, about_point=center, ) last_world = reflected_world result.add(last_world) return result def get_partial_trajectory_anims(self, trajectory, a, b, **kwargs): if not hasattr(trajectory, "full_self"): trajectory.full_self = trajectory.copy() return UpdateFromAlphaFunc( trajectory, lambda m, alpha: m.pointwise_become_partial( m.full_self, 0, interpolate(a, b, alpha) ), **kwargs ) def get_both_partial_trajectory_anims(self, a, b, run_time=2, **kwargs): kwargs["run_time"] = run_time return [ self.get_partial_trajectory_anims( mob, a, b, **kwargs ) for mob in (self.trajectory, self.ghost_trajectory) ] def add_flashing_windows(self): theta = self.get_theta() center = self.get_center() windows = self.windows = VGroup(*[ Line( center, center + rotate_vector(10 * RIGHT, k * theta), color=BLUE, stroke_width=0, ) for k in range(0, self.get_count() + 1) ]) windows[0].set_stroke(opacity=0) # Warning, windows update manager may launch def update_windows(windows): windows.set_stroke(width=0) windows[self.get_count()].set_stroke(width=5) windows.add_updater(update_windows) self.add(windows) def add_room_color_updates(self): def update_reflected_worlds(worlds): for n, world in enumerate(worlds): worlds[n][0].set_fill( opacity=(0.25 if (n % 2 == 0) else 0) ) index = self.get_count() - 1 if index < 0: return worlds[index][0].set_fill(opacity=0.5) self.reflected_worlds.add_updater(update_reflected_worlds) self.add(self.reflected_worlds) class ReflectWorldThroughMirrorThetaPoint2(ReflectWorldThroughMirrorNew): CONFIG = { "start_theta": 0.2, "randy_height": 0.8, } class ReflectWorldThroughMirrorThetaPoint1(ReflectWorldThroughMirrorNew): CONFIG = { "start_theta": 0.1, "randy_height": 0.5, "start_y_offset": 0.5, "arc_config": { "radius": 0.5, }, } class MirrorAndWiresOverlay(MirrorScene): CONFIG = { "wire_pixel_points": [ (355, 574), (846, 438), (839, 629), (845, 288), (1273, 314), ], "max_x_pixel": 1440, "max_y_pixel": 1440, } def setup(self): self.last_count = 0 def get_count(self): return 0 def get_shooting_beam_anims(self, mobject, **new_kwargs): kwargs = { "update_beam_point": False, "fade_trajectory": False, "max_stroke_width": 10, } kwargs.update(new_kwargs) return super().get_shooting_beam_anims(mobject, **kwargs) def construct(self): self.add_wires() self.add_diagram() self.introduce_wires() self.show_illusion() self.show_angles() # self.show_reflecting_beam() def add_wires(self): ul_corner = TOP + LEFT_SIDE points = self.wire_points = [ ul_corner + np.array([ (x / self.max_x_pixel) * FRAME_HEIGHT, (-y / self.max_y_pixel) * FRAME_HEIGHT, 0 ]) for x, y in self.wire_pixel_points ] wires = self.wires = VGroup( Line(points[0], points[1]), Line(points[1], points[2]), Line(points[1], points[3]), Line(points[1], points[4]), ) wires.set_stroke(RED, 4) self.dl_wire, self.dr_wire, self.ul_wire, self.ur_wire = wires self.trajectory = VMobject() self.trajectory.set_points_as_corners(points[:3]) self.ghost_trajectory = VMobject() self.ghost_trajectory.set_points_as_corners([*points[:2], points[4]]) VGroup(self.trajectory, self.ghost_trajectory).match_style( self.wires ) def add_diagram(self): diagram = self.diagram = VGroup() rect = diagram.rect = Rectangle( height=4, width=5, stroke_color=WHITE, stroke_width=1, fill_color=BLACK, fill_opacity=0.9, ) rect.to_corner(UR) diagram.add(rect) center = rect.get_center() mirror = diagram.mirror = VGroup( Line(rect.get_left(), center + 1.5 * LEFT), Line(center + 1.5 * LEFT, rect.get_right()), ) mirror.scale(0.8) mirror[0].set_color((WHITE, GREY)) mirror[1].set_color((GREY, WHITE)) diagram.add(mirror) def set_as_reflection(m1, m2): m1.become(m2) m1.rotate(PI, axis=UP, about_point=center) def set_as_mirror_image(m1, m2): m1.become(m2) m1.rotate(PI, axis=RIGHT, about_point=center) wires = VGroup(*[ Line(center + np.array([-1, -1.5, 0]), center) for x in range(4) ]) dl_wire, dr_wire, ul_wire, ur_wire = wires dr_wire.add_updater( lambda m: set_as_reflection(m, dl_wire) ) ul_wire.add_updater( lambda m: set_as_mirror_image(m, dl_wire) ) ur_wire.add_updater( lambda m: set_as_mirror_image(m, dr_wire) ) diagram.wires = wires diagram.wires.set_stroke(RED, 2) diagram.add(diagram.wires) def introduce_wires(self): dl_wire = self.dl_wire dr_wire = self.dr_wire def get_rect(wire): rect = Rectangle( width=wire.get_length(), height=0.25, color=YELLOW, ) rect.rotate(wire.get_angle()) rect.move_to(wire) return rect for wire in dl_wire, dr_wire: self.play(ShowCreationThenFadeOut(get_rect(wire))) self.play(*self.get_shooting_beam_anims(wire)) self.wait() diagram = self.diagram.copy() diagram.clear_updaters() self.play( FadeIn(diagram.rect), ShowCreation(diagram.mirror), LaggedStartMap(ShowCreation, diagram.wires), run_time=1 ) self.remove(diagram) self.add(self.diagram) self.wait() def show_illusion(self): g_trajectory = self.ghost_trajectory d_trajectory = self.d_trajectory = Line( self.diagram.wires[0].get_start(), self.diagram.wires[3].get_start(), ) d_trajectory.match_style(g_trajectory) g_trajectory.get_points()[0] += 0.2 * RIGHT + 0.1 * DOWN g_trajectory.make_jagged() for x in range(3): self.play( *self.get_shooting_beam_anims(g_trajectory), *self.get_shooting_beam_anims(d_trajectory), ) self.wait() def show_angles(self): dl_wire = self.diagram.wires[0] dr_wire = self.diagram.wires[1] center = self.diagram.get_center() arc_config = { "radius": 0.5, "arc_center": center, } def get_dl_arc(): return Arc( start_angle=PI, angle=dl_wire.get_angle(), **arc_config, ) dl_arc = always_redraw(get_dl_arc) def get_dr_arc(): return Arc( start_angle=0, angle=dr_wire.get_angle() - PI, **arc_config, ) dr_arc = always_redraw(get_dr_arc) incidence = OldTexText("Incidence") reflection = OldTexText("Reflection") words = VGroup(incidence, reflection) words.scale(0.75) incidence.add_updater( lambda m: m.next_to(dl_arc, LEFT, SMALL_BUFF) ) reflection.add_updater( lambda m: m.next_to(dr_arc, RIGHT, SMALL_BUFF) ) for word in words: word.set_background_stroke(width=0) word.add_updater(lambda m: m.shift(SMALL_BUFF * DOWN)) self.add(incidence) self.play( ShowCreation(dl_arc), UpdateFromAlphaFunc( VMobject(), lambda m, a: incidence.set_fill(opacity=a), remover=True ), ) self.wait() self.add(reflection) self.play( ShowCreation(dr_arc), UpdateFromAlphaFunc( VMobject(), lambda m, a: reflection.set_fill(opacity=a), remover=True ), ) self.wait() # Change dr wire angle # dr_wire.suspend_updating() dr_wire.clear_updaters() for angle in [20 * DEGREES, -20 * DEGREES]: self.play( Rotate( dr_wire, angle, about_point=dr_wire.get_end(), run_time=2, ), ) self.play( *self.get_shooting_beam_anims(self.ghost_trajectory), *self.get_shooting_beam_anims(self.d_trajectory), ) self.wait() def show_reflecting_beam(self): self.play( *self.get_shooting_beam_anims(self.trajectory), *self.get_shooting_beam_anims(self.ghost_trajectory), ) self.wait()
from manim_imports_ext import * from _2019.clacks.question import Block from _2019.clacks.question import Wall from _2019.clacks.question import ClackFlashes class PositionPhaseSpaceScene(Scene): CONFIG = { "rescale_coordinates": True, "wall_x": -6, "wall_config": { "height": 1.6, "tick_spacing": 0.35, "tick_length": 0.2, }, "wall_height": 1.5, "floor_y": -3.5, "block1_config": { "mass": 10, "distance": 9, "velocity": -1, "width": 1.6, }, "block2_config": { "mass": 1, "distance": 4, }, "axes_config": { "x_min": -0.5, "x_max": 31, "y_min": -0.5, "y_max": 10.5, "x_axis_config": { "unit_size": 0.4, "tick_frequency": 2, }, "y_axis_config": { "unit_size": 0.4, "tick_frequency": 2, }, }, "axes_center": 5 * LEFT + 0.65 * DOWN, "ps_dot_config": { "fill_color": RED, "background_stroke_width": 1, "background_stroke_color": BLACK, "radius": 0.05, }, "ps_d2_label_vect": RIGHT, "ps_x_line_config": { "color": GREEN, "stroke_width": 2, }, "ps_y_line_config": { "color": RED, "stroke_width": 2, }, "clack_sound": "clack", "mirror_line_class": Line, "mirror_line_style": { "stroke_color": WHITE, "stroke_width": 1, }, "d1_eq_d2_line_color": MAROON_B, "d1_eq_d2_tex": "d1 = d2", "trajectory_style": { "stroke_color": YELLOW, "stroke_width": 2, }, "ps_velocity_vector_length": 0.75, "ps_velocity_vector_config": { "color": PINK, "rectangular_stem_width": 0.025, "tip_length": 0.15, }, "block_velocity_vector_length_multiple": 2, "block_velocity_vector_config": { "color": PINK, }, } def setup(self): self.total_sliding_time = 0 self.all_items = [ self.get_floor(), self.get_wall(), self.get_blocks(), self.get_axes(), self.get_phase_space_point(), self.get_phase_space_x_line(), self.get_phase_space_y_line(), self.get_phase_space_dot(), self.get_phase_space_d1_label(), self.get_phase_space_d2_label(), self.get_d1_brace(), self.get_d2_brace(), self.get_d1_label(), self.get_d2_label(), self.get_d1_eq_d2_line(), self.get_d1_eq_d2_label(), self.get_d2_eq_w2_line(), self.get_d2_eq_w2_label(), ] def get_floor_wall_corner(self): return self.wall_x * RIGHT + self.floor_y * UP def get_mass_ratio(self): return op.truediv( self.block1.mass, self.block2.mass, ) def d1_to_x(self, d1): if self.rescale_coordinates: d1 *= np.sqrt(self.block1.mass) return d1 def d2_to_y(self, d2): if self.rescale_coordinates: d2 *= np.sqrt(self.block2.mass) return d2 def ds_to_point(self, d1, d2): return self.axes.coords_to_point( self.d1_to_x(d1), self.d2_to_y(d2), ) def point_to_ds(self, point): x, y = self.axes.point_to_coords(point) if self.rescale_coordinates: x /= np.sqrt(self.block1.mass) y /= np.sqrt(self.block2.mass) return (x, y) def get_d1(self): return self.get_ds()[0] def get_d2(self): return self.get_ds()[1] def get_ds(self): return self.point_to_ds(self.ps_point.get_location()) # Relevant for sliding def tie_blocks_to_ps_point(self): def update_blocks(blocks): d1, d2 = self.point_to_ds(self.ps_point.get_location()) b1, b2 = blocks corner = self.get_floor_wall_corner() b1.move_to(corner + d1 * RIGHT, DL) b2.move_to(corner + d2 * RIGHT, DR) self.blocks.add_updater(update_blocks) def time_to_ds(self, time): # Deals in its own phase space, different # from the one displayed m1 = self.block1.mass m2 = self.block2.mass v1 = self.block1.velocity start_d1 = self.block1_config["distance"] start_d2 = self.block2_config["distance"] w2 = self.block2.width start_d2 += w2 ps_speed = np.sqrt(m1) * abs(v1) theta = np.arctan(np.sqrt(m2 / m1)) def ds_to_ps_point(d1, d2): return np.array([ d1 * np.sqrt(m1), d2 * np.sqrt(m2), 0 ]) def ps_point_to_ds(point): return ( point[0] / np.sqrt(m1), point[1] / np.sqrt(m2), ) ps_point = ds_to_ps_point(start_d1, start_d2) wedge_corner = ds_to_ps_point(w2, w2) ps_point -= wedge_corner # Pass into the mirror worlds ps_point += time * ps_speed * LEFT # Reflect back to the real world angle = angle_of_vector(ps_point) n = int(angle / theta) if n % 2 == 0: ps_point = rotate_vector(ps_point, -n * theta) else: ps_point = rotate_vector( ps_point, -(n + 1) * theta, ) ps_point[1] = abs(ps_point[1]) ps_point += wedge_corner return ps_point_to_ds(ps_point) def get_clack_data(self): # Copying from time_to_ds. Not great, but # maybe I'll factor things out properly later. m1 = self.block1.mass m2 = self.block2.mass v1 = self.block1.velocity w2 = self.block2.get_width() h2 = self.block2.get_height() start_d1, start_d2 = self.get_ds() ps_speed = np.sqrt(m1) * abs(v1) theta = np.arctan(np.sqrt(m2 / m1)) def ds_to_ps_point(d1, d2): return np.array([ d1 * np.sqrt(m1), d2 * np.sqrt(m2), 0 ]) def ps_point_to_ds(point): return ( point[0] / np.sqrt(m1), point[1] / np.sqrt(m2), ) ps_point = ds_to_ps_point(start_d1, start_d2) wedge_corner = ds_to_ps_point(w2, w2) ps_point -= wedge_corner y = ps_point[1] clack_data = [] for k in range(1, int(PI / theta) + 1): clack_ps_point = np.array([ y / np.tan(k * theta), y, 0 ]) time = get_norm(ps_point - clack_ps_point) / ps_speed reflected_point = rotate_vector( clack_ps_point, -2 * np.ceil((k - 1) / 2) * theta ) d1, d2 = ps_point_to_ds(reflected_point + wedge_corner) loc1 = self.get_floor_wall_corner() + h2 * UP / 2 + d2 * RIGHT if k % 2 == 0: loc1 += w2 * LEFT loc2 = self.ds_to_point(d1, d2) clack_data.append((time, loc1, loc2)) return clack_data def tie_ps_point_to_time_tracker(self): if not hasattr(self, "sliding_time_tracker"): self.sliding_time_tracker = self.get_time_tracker() def update_ps_point(p): time = self.sliding_time_tracker.get_value() ds = self.time_to_ds(time) p.move_to(self.ds_to_point(*ds)) self.ps_point.add_updater(update_ps_point) self.add(self.sliding_time_tracker, self.ps_point) def add_clack_flashes(self): if hasattr(self, "flash_anims"): self.add(*self.flash_anims) else: clack_data = self.get_clack_data() self.clack_times = [ time for (time, loc1, loc2) in clack_data ] self.block_flashes = ClackFlashes([ (loc1, time) for (time, loc1, loc2) in clack_data ]) self.ps_flashes = ClackFlashes([ (loc2, time) for (time, loc1, loc2) in clack_data ]) self.flash_anims = [self.block_flashes, self.ps_flashes] for anim in self.flash_anims: anim.get_time = self.sliding_time_tracker.get_value self.add(*self.flash_anims) def get_continually_building_trajectory(self): trajectory = VMobject() self.trajectory = trajectory trajectory.set_style(**self.trajectory_style) def get_point(): return np.array(self.ps_point.get_location()) points = [get_point(), get_point()] trajectory.set_points_as_corners(points) epsilon = 0.001 def update_trajectory(trajectory): new_point = get_point() p1, p2 = trajectory.get_anchors()[-2:] angle = angle_between_vectors( p2 - p1, new_point - p2, ) if angle > epsilon: points.append(new_point) else: points[-1] = new_point trajectory.set_points_as_corners(points) trajectory.add_updater(update_trajectory) return trajectory def begin_sliding(self, show_trajectory=True): self.tie_ps_point_to_time_tracker() self.add_clack_flashes() if show_trajectory: if hasattr(self, "trajectory"): self.trajectory.resume_updating() else: self.add(self.get_continually_building_trajectory()) def end_sliding(self): self.update_mobjects(dt=0) self.ps_point.clear_updaters() if hasattr(self, "sliding_time_tracker"): self.remove(self.sliding_time_tracker) if hasattr(self, "flash_anims"): self.remove(*self.flash_anims) if hasattr(self, "trajectory"): self.trajectory.suspend_updating() old_total_sliding_time = self.total_sliding_time new_total_sliding_time = self.sliding_time_tracker.get_value() self.total_sliding_time = new_total_sliding_time for time in self.clack_times: if old_total_sliding_time < time < new_total_sliding_time: offset = time - new_total_sliding_time self.add_sound( "clack", time_offset=offset, ) def slide(self, time, stop_condition=None): self.begin_sliding() self.wait(time, stop_condition) self.end_sliding() def slide_until(self, stop_condition, max_time=60): self.slide(max_time, stop_condition=stop_condition) def get_ps_point_change_anim(self, d1, d2, **added_kwargs): b1 = self.block1 ps_speed = np.sqrt(b1.mass) * abs(b1.velocity) curr_d1, curr_d2 = self.get_ds() distance = get_norm([curr_d1 - d1, curr_d2 - d2]) # Default kwargs = { "run_time": (distance / ps_speed), "rate_func": linear, } kwargs.update(added_kwargs) return ApplyMethod( self.ps_point.move_to, self.ds_to_point(d1, d2), **kwargs ) # Mobject getters def get_floor(self): floor = self.floor = Line( self.wall_x * RIGHT, FRAME_WIDTH * RIGHT / 2, stroke_color=WHITE, stroke_width=3, ) floor.move_to(self.get_floor_wall_corner(), LEFT) return floor def get_wall(self): wall = self.wall = Wall(**self.wall_config) wall.move_to(self.get_floor_wall_corner(), DR) return wall def get_blocks(self): blocks = self.blocks = VGroup() for n in [1, 2]: config = getattr(self, "block{}_config".format(n)) block = Block(**config) block.move_to(self.get_floor_wall_corner(), DL) block.shift(config["distance"] * RIGHT) block.label.move_to(block) block.label.set_fill(BLACK) block.label.set_stroke(WHITE, 1, background=True) self.blocks.add(block) self.block1, self.block2 = blocks return blocks def get_axes(self): axes = self.axes = Axes(**self.axes_config) axes.set_stroke(GREY_B, 2) axes.shift( self.axes_center - axes.coords_to_point(0, 0) ) axes.labels = self.get_axes_labels(axes) axes.add(axes.labels) axes.added_lines = self.get_added_axes_lines(axes) axes.add(axes.added_lines) return axes def get_added_axes_lines(self, axes): c2p = axes.coords_to_point x_mult = y_mult = 1 if self.rescale_coordinates: x_mult = np.sqrt(self.block1.mass) y_mult = np.sqrt(self.block2.mass) y_lines = VGroup(*[ Line( c2p(0, 0), c2p(0, axes.y_max * y_mult + 1), ).move_to(c2p(x, 0), DOWN) for x in np.arange(0, axes.x_max) * x_mult ]) x_lines = VGroup(*[ Line( c2p(0, 0), c2p(axes.x_max * x_mult, 0), ).move_to(c2p(0, y), LEFT) for y in np.arange(0, axes.y_max) * y_mult ]) line_groups = VGroup(x_lines, y_lines) for lines in line_groups: lines.set_stroke(BLUE, 1, 0.5) lines[1::2].set_stroke(width=0.5, opacity=0.25) return line_groups def get_axes_labels(self, axes, with_sqrts=None): if with_sqrts is None: with_sqrts = self.rescale_coordinates x_label = OldTex("x", "=", "d_1") y_label = OldTex("y", "=", "d_2") labels = VGroup(x_label, y_label) if with_sqrts: additions = map(Tex, [ "\\sqrt{m_1}", "\\sqrt{m_2}" ]) for label, addition in zip(labels, additions): addition.move_to(label[2], DL) label[2].next_to( addition, RIGHT, SMALL_BUFF, aligned_edge=DOWN ) addition[2:].set_color(BLUE) label.submobjects.insert(2, addition) x_label.next_to(axes.x_axis.get_right(), DL, MED_SMALL_BUFF) y_label.next_to(axes.y_axis.get_top(), DR, MED_SMALL_BUFF) for label in labels: label.shift_onto_screen() return labels def get_phase_space_point(self): ps_point = self.ps_point = VectorizedPoint() ps_point.move_to(self.ds_to_point( self.block1.distance, self.block2.distance + self.block2.width )) self.tie_blocks_to_ps_point() return ps_point def get_phase_space_x_line(self): def get_x_line(): origin = self.axes.coords_to_point(0, 0) point = self.ps_point.get_location() y_axis_point = np.array(origin) y_axis_point[1] = point[1] return DashedLine( y_axis_point, point, **self.ps_x_line_config, ) self.x_line = always_redraw(get_x_line) return self.x_line def get_phase_space_y_line(self): def get_y_line(): origin = self.axes.coords_to_point(0, 0) point = self.ps_point.get_location() x_axis_point = np.array(origin) x_axis_point[0] = point[0] return DashedLine( x_axis_point, point, **self.ps_y_line_config, ) self.y_line = always_redraw(get_y_line) return self.y_line def get_phase_space_dot(self): self.ps_dot = ps_dot = Dot(**self.ps_dot_config) ps_dot.add_updater(lambda m: m.move_to(self.ps_point)) return ps_dot def get_d_label(self, n, get_d): label = VGroup( OldTex("d_{}".format(n), "="), DecimalNumber(), ) color = GREEN if n == 1 else RED label[0].set_color_by_tex("d_", color) label.scale(0.7) label.set_stroke(BLACK, 3, background=True) def update_value(label): lhs, rhs = label rhs.set_value(get_d()) rhs.next_to( lhs, RIGHT, SMALL_BUFF, aligned_edge=DOWN, ) label.add_updater(update_value) return label def get_phase_space_d_label(self, n, get_d, line, vect): label = self.get_d_label(n, get_d) label.add_updater( lambda m: m.next_to(line, vect, SMALL_BUFF) ) return label def get_phase_space_d1_label(self): self.ps_d1_label = self.get_phase_space_d_label( 1, self.get_d1, self.x_line, UP, ) return self.ps_d1_label def get_phase_space_d2_label(self): self.ps_d2_label = self.get_phase_space_d_label( 2, self.get_d2, self.y_line, self.ps_d2_label_vect, ) return self.ps_d2_label def get_d_brace(self, get_right_point): line = Line(LEFT, RIGHT).set_width(6) def get_brace(): right_point = get_right_point() left_point = np.array(right_point) left_point[0] = self.wall_x line.put_start_and_end_on(left_point, right_point) return Brace(line, UP, buff=SMALL_BUFF) brace = always_redraw(get_brace) return brace def get_d1_brace(self): self.d1_brace = self.get_d_brace( lambda: self.block1.get_corner(UL) ) return self.d1_brace def get_d2_brace(self): self.d2_brace = self.get_d_brace( lambda: self.block2.get_corner(UR) ) # self.flip_brace_nip() return self.d2_brace def flip_brace_nip(self, brace): nip_index = (len(brace) // 2) - 1 nip = brace[nip_index:nip_index + 2] rect = brace[nip_index - 1] center = rect.get_center() center[0] = nip.get_center()[0] nip.rotate(PI, about_point=center) def get_brace_d_label(self, n, get_d, brace, vect, buff): label = self.get_d_label(n, get_d) label.add_updater( lambda m: m.next_to(brace, vect, buff) ) return label def get_d1_label(self): self.d1_label = self.get_brace_d_label( 1, self.get_d1, self.d1_brace, UP, SMALL_BUFF, ) return self.d1_label def get_d2_label(self): self.d2_label = self.get_brace_d_label( 2, self.get_d2, self.d2_brace, UP, 0 ) return self.d2_label def get_d1_eq_d2_line(self): start = self.ds_to_point(0, 0) end = self.ds_to_point(15, 15) line = self.d1_eq_d2_line = self.mirror_line_class(start, end) line.set_style(**self.mirror_line_style) line.set_color(self.d1_eq_d2_line_color) return self.d1_eq_d2_line def get_d1_eq_d2_label(self): label = OldTex(self.d1_eq_d2_tex) label.scale(0.75) line = self.d1_eq_d2_line point = interpolate( line.get_start(), line.get_end(), 0.7, ) label.next_to(point, DR, SMALL_BUFF) label.match_color(line) label.set_stroke(BLACK, 5, background=True) self.d1_eq_d2_label = label return label def get_d2_eq_w2_line(self): w2 = self.block2.width start = self.ds_to_point(0, w2) end = np.array(start) end[0] = FRAME_WIDTH / 2 self.d2_eq_w2_line = self.mirror_line_class(start, end) self.d2_eq_w2_line.set_style(**self.mirror_line_style) return self.d2_eq_w2_line def get_d2_eq_w2_label(self): label = OldTex("d2 = \\text{block width}") label.scale(0.75) label.next_to(self.d2_eq_w2_line, UP, SMALL_BUFF) label.to_edge(RIGHT, buff=MED_SMALL_BUFF) self.d2_eq_w2_label = label return label def get_time_tracker(self, time=0): time_tracker = self.time_tracker = ValueTracker(time) time_tracker.add_updater( lambda m, dt: m.increment_value(dt) ) return time_tracker # Things associated with velocity def get_ps_velocity_vector(self, trajectory): vector = Vector( self.ps_velocity_vector_length * LEFT, **self.ps_velocity_vector_config, ) def update_vector(v): anchors = trajectory.get_anchors() index = len(anchors) - 2 vect = np.array(ORIGIN) while get_norm(vect) == 0 and index > 0: p0, p1 = anchors[index:index + 2] vect = p1 - p0 index -= 1 angle = angle_of_vector(vect) point = self.ps_point.get_location() v.set_angle(angle) v.shift(point - v.get_start()) vector.add_updater(update_vector) self.ps_velocity_vector = vector return vector def get_block_velocity_vectors(self, ps_vect): blocks = self.blocks vectors = VGroup(*[ Vector(LEFT, **self.block_velocity_vector_config) for x in range(2) ]) # TODO: Put in config vectors[0].set_color(GREEN) vectors[1].set_color(RED) def update_vectors(vs): v_2d = ps_vect.get_vector()[:2] v_2d *= self.block_velocity_vector_length_multiple for v, coord, block in zip(vs, v_2d, blocks): v.put_start_and_end_on(ORIGIN, coord * RIGHT) start = block.get_edge_center(v.get_vector()) v.shift(start) vectors.add_updater(update_vectors) self.block_velocity_vectors = vectors return vectors class IntroducePositionPhaseSpace(PositionPhaseSpaceScene): CONFIG = { "rescale_coordinates": False, "d1_eq_d2_tex": "x = y", "block1_config": { "velocity": 1.5, }, "slide_wait_time": 12, } def setup(self): super().setup() self.add( self.floor, self.wall, self.blocks, self.axes, ) def construct(self): self.show_coordinates() self.show_xy_line() self.let_process_play_out() self.show_w2_line() def show_coordinates(self): ps_point = self.ps_point axes = self.axes self.play(Write(axes.added_lines)) self.play(FadeInFromLarge(self.ps_dot, scale_factor=10)) self.play( ShowCreation(self.x_line), GrowFromPoint( self.d1_brace, self.d1_brace.get_left(), ), Indicate(axes.labels[0]), ) self.play( FadeInFromDown(self.ps_d1_label), FadeInFromDown(self.d1_label), ) self.play(ps_point.shift, 0.5 * LEFT) self.play(ps_point.shift, 0.5 * RIGHT) self.wait() self.play( ShowCreation(self.y_line), GrowFromPoint( self.d2_brace, self.d2_brace.get_left(), ), Indicate(axes.labels[1]), ) self.play( FadeInFromDown(self.ps_d2_label), FadeInFromDown(self.d2_label), ) self.play(ps_point.shift, 0.5 * UP) self.play(ps_point.shift, 0.5 * DOWN) self.wait() self.play(Rotating( ps_point, about_point=ps_point.get_location() + 0.5 * RIGHT, run_time=3, rate_func=smooth, )) self.wait() def show_xy_line(self): ps_point = self.ps_point ps_point.save_state() d1, d2 = self.point_to_ds(ps_point.get_location()) xy_line = self.d1_eq_d2_line xy_label = self.d1_eq_d2_label self.play( ShowCreation(xy_line), Write(xy_label), ) self.play( ps_point.move_to, self.ds_to_point(d2, d2), run_time=3 ) self.wait() for d in [3, 7]: self.play( ps_point.move_to, self.ds_to_point(d, d), run_time=2 ) self.wait() self.play(ps_point.restore) self.wait() def let_process_play_out(self): self.begin_sliding() sliding_trajectory = self.get_continually_building_trajectory() self.add(sliding_trajectory, self.ps_dot) self.wait(self.slide_wait_time) def show_w2_line(self): line = self.d2_eq_w2_line label = self.d2_eq_w2_label self.play(ShowCreation(line)) self.play(FadeInFromDown(label)) self.wait(self.slide_wait_time) self.end_sliding() self.wait(self.slide_wait_time) class SpecialShowPassingFlash(ShowPassingFlash): CONFIG = { "max_time_width": 0.1, } def get_bounds(self, alpha): tw = self.time_width max_tw = self.max_time_width upper = interpolate(0, 1 + max_tw, alpha) lower = upper - tw upper = min(upper, 1) lower = max(lower, 0) return (lower, upper) class EqualMassCase(PositionPhaseSpaceScene): CONFIG = { "block1_config": { "mass": 1, "width": 1, "velocity": 1.5, }, "rescale_coordinates": False, "d1_eq_d2_tex": "x = y", } def setup(self): super().setup() self.add( self.floor, self.wall, self.blocks, self.axes, self.d1_eq_d2_line, self.d1_eq_d2_label, self.d2_eq_w2_line, self.d2_eq_w2_label, self.ps_dot, self.x_line, self.y_line, self.ps_d1_label, self.ps_d2_label, ) def construct(self): self.show_same_mass() self.show_first_point() self.up_to_first_collision() self.up_to_second_collision() self.up_to_third_collision() self.fade_distance_indicators() self.show_beam_bouncing() def show_same_mass(self): blocks = self.blocks self.play(LaggedStartMap( Indicate, blocks, lag_ratio=0.8, run_time=1, )) def show_first_point(self): ps_dot = self.ps_dot ps_point = self.ps_point d1, d2 = self.get_ds() self.play(FocusOn(ps_dot)) self.play(ShowCreationThenFadeOut( Circle(color=RED).replace(ps_dot).scale(2), run_time=1 )) self.wait() self.play( ps_point.move_to, self.ds_to_point(d1 - 1, d2), rate_func=wiggle, run_time=3, ) # self.play(ps_point.move_to, self.ds_to_point(d1, d2)) self.wait() def up_to_first_collision(self): ps_point = self.ps_point d1, d2 = self.get_ds() block1 = self.block1 block2 = self.block2 xy_line = self.d1_eq_d2_line xy_line_label = self.d1_eq_d2_label block_arrow = Vector(LEFT, color=RED) block_arrow.block = block1 block_arrow.add_updater( lambda m: m.shift( m.block.get_center() - m.get_start() ) ) ps_arrow = Vector(LEFT, color=RED) ps_arrow.next_to(ps_point, DL, buff=SMALL_BUFF) block_labels = VGroup(block1.label, block2.label) block_label_copies = block_labels.copy() def update_bl_copies(bl_copies): for bc, b in zip(bl_copies, block_labels): bc.move_to(b) block_label_copies.add_updater(update_bl_copies) trajectory = self.get_continually_building_trajectory() self.add(block_arrow, ps_arrow, block_label_copies) self.play( GrowArrow(block_arrow), GrowArrow(ps_arrow), ) self.add(trajectory) self.play(self.get_ps_point_change_anim(d2, d2)) block_arrow.block = block2 ps_arrow.rotate(90 * DEGREES) ps_arrow.next_to(ps_point, DR, SMALL_BUFF) self.add_sound(self.clack_sound) self.play( Flash(ps_point), Flash(block1.get_left()), self.get_ps_point_change_anim(d2, d2 - 1) ) self.play( ShowPassingFlash( xy_line.copy().set_stroke(YELLOW, 3) ), Indicate(xy_line_label), ) trajectory.suspend_updating() self.wait() self.ps_arrow = ps_arrow self.block_arrow = block_arrow def up_to_second_collision(self): trajectory = self.trajectory ps_point = self.ps_point ps_arrow = self.ps_arrow block_arrow = self.block_arrow d1, d2 = self.get_ds() w2 = self.block2.get_width() trajectory.resume_updating() self.play(self.get_ps_point_change_anim(d1, w2)) block_arrow.rotate(PI) ps_arrow.rotate(PI) ps_arrow.next_to(ps_point, UR, SMALL_BUFF) self.add_sound(self.clack_sound) self.play( Flash(self.block2.get_left()), Flash(ps_point), self.get_ps_point_change_anim(d1, w2 + 1) ) trajectory.suspend_updating() self.wait() def up_to_third_collision(self): trajectory = self.trajectory ps_point = self.ps_point ps_arrow = self.ps_arrow block_arrow = self.block_arrow d1, d2 = self.get_ds() trajectory.resume_updating() self.play(self.get_ps_point_change_anim(d1, d1)) block_arrow.block = self.block1 ps_arrow.rotate(-90 * DEGREES) ps_arrow.next_to(ps_point, DR, SMALL_BUFF) self.add_sound(self.clack_sound) self.play( Flash(self.block2.get_left()), Flash(ps_point.get_location()), self.get_ps_point_change_anim(d1 + 10, d1) ) trajectory.suspend_updating() def fade_distance_indicators(self): trajectory = self.trajectory self.play( trajectory.set_stroke, {"width": 1}, *map(FadeOut, [ self.ps_arrow, self.block_arrow, self.x_line, self.y_line, self.ps_d1_label, self.ps_d2_label, ]) ) trajectory.clear_updaters() def show_beam_bouncing(self): d1, d2 = self.get_ds() d1 = int(d1) d2 = int(d2) # w2 = self.block2.get_width() ps_point = self.ps_point points = [] while d1 > d2: points.append(self.ds_to_point(d1, d2)) d1 -= 1 while d2 >= 1: points.append(self.ds_to_point(d1, d2)) d2 -= 1 points += list(reversed(points))[1:] trajectory = VMobject() trajectory.set_points_as_corners(points) flashes = [ SpecialShowPassingFlash( trajectory.copy().set_stroke(YELLOW, width=6 - n), time_width=(0.01 * n), max_time_width=0.05, remover=True ) for n in np.arange(0, 6, 0.25) ] flash_mob = flashes[0].mobject # Lol def update_ps_point_from_flas_mob(ps_point): if len(flash_mob.get_points()) > 0: ps_point.move_to(flash_mob.get_points()[-1]) else: ps_point.move_to(trajectory.get_points()[0]) # Mirror words xy_line = self.d1_eq_d2_line w2_line = self.d2_eq_w2_line lines = VGroup(xy_line, w2_line) for line in lines: word = OldTexText("Mirror") word.next_to(ORIGIN, UP, SMALL_BUFF) word.rotate(line.get_angle(), about_point=ORIGIN) word.shift(line.get_center()) line.word = word for line in lines: line.set_stroke(GREY_B) line.set_sheen(1, LEFT) self.play( Write(line.word), line.set_sheen, 1, RIGHT, line.set_stroke, {"width": 2}, run_time=1, ) # TODO, clacks? for x in range(3): self.play( UpdateFromFunc( ps_point, update_ps_point_from_flas_mob, ), *flashes, run_time=3, rate_func=linear, ) self.wait() class FailedAngleRelation(PositionPhaseSpaceScene): CONFIG = { "block1_config": { "distance": 10, "velocity": -1.5, }, "block2_config": { "distance": 5, }, "rescale_coordinates": False, "trajectory_style": { "stroke_width": 2, } } def setup(self): super().setup() self.add( self.floor, self.wall, self.blocks, self.axes, self.ps_dot, self.x_line, self.y_line, self.d1_eq_d2_line, self.d1_eq_d2_label, self.d2_eq_w2_line, self.d2_eq_w2_label, ) def construct(self): self.show_first_collision() self.show_angles() def show_first_collision(self): self.slide_until(lambda: self.get_ds()[1] < 2) def show_angles(self): trajectory = self.trajectory arcs = self.get_arcs(trajectory) equation = self.get_word_equation() equation.next_to( trajectory.get_points()[0], UR, MED_SMALL_BUFF, index_of_submobject_to_align=0, ) for arc in arcs: line = Line(ORIGIN, RIGHT) line.set_stroke(WHITE, 2) line.rotate(arc.start_angle) line.shift(arc.arc_center - line.get_start()) arc.line = line arc1, arc2 = arcs arc1.arrow = Arrow( equation[0].get_left(), arc1.get_right(), buff=SMALL_BUFF, color=WHITE, path_arc=0, ) arc2.arrow = Arrow( equation[2].get_corner(DL), arc2.get_left(), path_arc=-120 * DEGREES, buff=SMALL_BUFF, ) arc2.arrow.pointwise_become_partial(arc.arrow, 0, 0.95) arc1.word = equation[0] arc2.word = equation[1:] for arc in arcs: self.play( FadeIn(arc.word, LEFT), GrowArrow(arc.arrow, path_arc=arc.arrow.path_arc), ) self.play( ShowCreation(arc), arc.line.rotate, arc.angle, {"about_point": arc.line.get_start()}, UpdateFromAlphaFunc( arc.line, lambda m, a: m.set_stroke( opacity=(there_and_back(a)**0.5) ) ), ) # def get_arcs(self, trajectory): p0, p1, p2 = trajectory.get_anchors()[1:4] arc_config = { "stroke_color": WHITE, "stroke_width": 2, "radius": 0.5, "arc_center": p1, } arc1 = Arc( start_angle=0, angle=45 * DEGREES, **arc_config ) a2_start = angle_of_vector(DL) a2_angle = angle_between_vectors((p2 - p1), DL) arc2 = Arc( start_angle=a2_start, angle=a2_angle, **arc_config ) return VGroup(arc1, arc2) def get_word_equation(self): result = VGroup( OldTexText("Angle of incidence"), OldTex("\\ne").rotate(90 * DEGREES), OldTexText("Angle of reflection") ) result.arrange(DOWN) result.set_stroke(BLACK, 5, background=True) return result class UnscaledPositionPhaseSpaceMass10(FailedAngleRelation): CONFIG = { "block1_config": { "mass": 10 }, "wait_time": 25, } def construct(self): self.slide(self.wait_time) class UnscaledPositionPhaseSpaceMass100(UnscaledPositionPhaseSpaceMass10): CONFIG = { "block1_config": { "mass": 100 } } class RescaleCoordinates(PositionPhaseSpaceScene, MovingCameraScene): CONFIG = { "rescale_coordinates": False, "ps_d2_label_vect": LEFT, "axes_center": 6 * LEFT + 0.65 * DOWN, "block1_config": {"distance": 7}, "wait_time": 30, } def setup(self): PositionPhaseSpaceScene.setup(self) MovingCameraScene.setup(self) self.add( self.floor, self.wall, self.blocks, self.axes, self.d1_eq_d2_line, self.d1_eq_d2_label, self.d2_eq_w2_line, self.ps_dot, self.x_line, self.y_line, self.ps_d1_label, self.ps_d2_label, self.d1_brace, self.d2_brace, self.d1_label, self.d2_label, ) def construct(self): self.show_rescaling() self.comment_on_ugliness() self.put_into_frame() def show_rescaling(self): axes = self.axes blocks = self.blocks to_stretch = VGroup( axes.added_lines, self.d1_eq_d2_line, self.ps_point, ) m1 = self.block1.mass new_axes_labels = self.get_axes_labels(axes, with_sqrts=True) # Show label def show_label(index, block, vect): self.play( ShowCreationThenFadeAround(axes.labels[index]) ) self.play( Transform( axes.labels[index], VGroup( *new_axes_labels[index][:2], new_axes_labels[index][3] ), ), GrowFromCenter(new_axes_labels[index][2]) ) group = VGroup( new_axes_labels[index][2][-2:].copy(), OldTex("="), block.label.copy(), ) group.generate_target() group.target.arrange(RIGHT, buff=SMALL_BUFF) group.target.next_to(block, vect) group[1].scale(0) group[1].move_to(group.target[1]) group.target[2].set_fill(WHITE) group.target[2].set_stroke(width=0, background=True) self.play(MoveToTarget( group, rate_func=there_and_back_with_pause, run_time=3 )) self.remove(group) self.wait() show_label(0, self.block1, RIGHT) # The stretch blocks.suspend_updating() self.play( ApplyMethod( to_stretch.stretch, np.sqrt(m1), 0, {"about_point": axes.coords_to_point(0, 0)}, ), self.d1_eq_d2_label.shift, 6 * RIGHT, run_time=2, ) self.rescale_coordinates = True blocks.resume_updating() self.wait() # Show wiggle d1, d2 = self.get_ds() for new_d1 in [d1 - 2, d1]: self.play(self.get_ps_point_change_anim( new_d1, d2, rate_func=smooth, run_time=2, )) self.wait() # Change y-coord show_label(1, self.block2, LEFT) axes.remove(axes.labels) self.remove(axes.labels) axes.labels = new_axes_labels axes.add(axes.labels) self.add(axes) def comment_on_ugliness(self): axes = self.axes randy = Randolph(height=1.7) randy.flip() randy.next_to(self.d2_eq_w2_line, UP, buff=0) randy.to_edge(RIGHT) randy.change("sassy") randy.save_state() randy.fade(1) randy.change("plain") self.play(Restore(randy)) self.play( PiCreatureSays( randy, "Hideous!", bubble_config={"height": 1.5, "width": 2}, target_mode="angry", look_at=axes.labels[0] ) ) self.play(randy.look_at, axes.labels[1]) self.play(Blink(randy)) self.play( RemovePiCreatureBubble( randy, target_mode="confused" ) ) self.play(Blink(randy)) self.play(randy.look_at, axes.labels[0]) self.wait() self.play(FadeOut(randy)) def put_into_frame(self): rect = ScreenRectangle(height=FRAME_HEIGHT + 10) inner_rect = ScreenRectangle(height=FRAME_HEIGHT) rect.add_subpath(inner_rect.get_points()[::-1]) rect.set_fill("#333333", opacity=1) frame = self.camera_frame self.begin_sliding() self.add(rect) self.play( frame.scale, 1.5, {"about_point": frame.get_bottom() + UP}, run_time=2, ) self.wait(self.wait_time) self.end_sliding() # def get_ds(self): if self.rescale_coordinates: return super().get_ds() return ( self.block1_config["distance"], self.block2_config["distance"], ) class RescaleCoordinatesMass16(RescaleCoordinates): CONFIG = { "block1_config": { "mass": 16, "distance": 10, }, "rescale_coordinates": True, "wait_time": 20, } def construct(self): self.put_into_frame() class RescaleCoordinatesMass64(RescaleCoordinatesMass16): CONFIG = { "block1_config": { "mass": 64, "distance": 6, }, "block2_config": {"distance": 3}, } class RescaleCoordinatesMass100(RescaleCoordinatesMass16): CONFIG = { "block1_config": { "mass": 100, "distance": 6, "velocity": 0.5, }, "block2_config": {"distance": 2}, "wait_time": 25, } class IntroduceVelocityVector(PositionPhaseSpaceScene, MovingCameraScene): CONFIG = { "zoom": True, "ps_x_line_config": { "color": WHITE, "stroke_width": 1, "stroke_opacity": 0.5, }, "ps_y_line_config": { "color": WHITE, "stroke_width": 1, "stroke_opacity": 0.5, }, "axes_center": 6 * LEFT + 0.65 * DOWN, "slide_time": 20, "new_vect_config": { "tip_length": 0.1, "rectangular_stem_width": 0.02, } } def setup(self): MovingCameraScene.setup(self) PositionPhaseSpaceScene.setup(self) self.add( self.floor, self.wall, self.blocks, self.axes, self.d1_eq_d2_line, self.d1_eq_d2_label, self.d2_eq_w2_line, self.x_line, self.y_line, self.ps_dot, ) def construct(self): self.show_velocity_vector() self.contrast_with_physical_velocities() self.zoom_in_on_vector() self.break_down_components() self.zoom_out() self.relate_x_dot_y_dot_to_v1_v2() self.calculate_magnitude() self.let_process_play_out() def show_velocity_vector(self): self.slide(2) ps_vect = self.get_ps_velocity_vector(self.trajectory) self.play(GrowArrow(ps_vect)) self.play(ShowCreationThenFadeAround(ps_vect)) self.wait() def contrast_with_physical_velocities(self): ps_vect = self.ps_velocity_vector block_vectors = self.get_block_velocity_vectors(ps_vect) self.play(LaggedStartMap(GrowArrow, block_vectors)) self.play(Rotating( ps_vect, angle=TAU, about_point=ps_vect.get_start(), run_time=5, rate_func=smooth, )) self.wait() self.slide_until(lambda: self.get_d2() < 2.5) def zoom_in_on_vector(self): if not self.zoom: self.wait(3) return ps_vect = self.ps_velocity_vector new_vect = Arrow( ps_vect.get_start(), ps_vect.get_end(), buff=0, **self.new_vect_config ) new_vect.match_style(ps_vect) camera_frame = self.camera_frame camera_frame.save_state() point = self.ps_point.get_location() point += MED_SMALL_BUFF * DOWN self.play( camera_frame.scale, 0.25, {"about_point": point}, Transform(ps_vect, new_vect), run_time=2, ) self.wait() def break_down_components(self): # Create vectors ps_vect = self.ps_velocity_vector start = ps_vect.get_start() end = ps_vect.get_end() ul_corner = np.array(start) dr_corner = np.array(start) ul_corner[0] = end[0] dr_corner[1] = end[1] x_vect = Arrow( start, ul_corner, buff=0, **self.new_vect_config ) y_vect = Arrow( start, dr_corner, buff=0, **self.new_vect_config ) x_vect.set_fill(GREEN, opacity=0.75) y_vect.set_fill(RED, opacity=0.75) vects = VGroup(x_vect, y_vect) # Projection lines x_line, y_line = [ DashedLine( ps_vect.get_end(), vect.get_end(), dash_length=0.01, color=vect.get_color(), ) for vect in (x_vect, y_vect) ] self.projection_lines = VGroup(x_line, y_line) # Vector labels dx_label = OldTex("\\frac{dx}{dt}") dy_label = OldTex("\\frac{dy}{dt}") labels = VGroup(dx_label, dy_label) for label, arrow, direction in zip(labels, vects, [UP, RIGHT]): label.scale(0.25) buff = 0.25 * SMALL_BUFF label.next_to(arrow, direction, buff=buff) label.set_stroke(BLACK, 3, background=True) if not self.zoom: self.grow_labels(labels) self.play( TransformFromCopy(ps_vect, x_vect), ShowCreation(x_line), ) self.play(FadeIn(dx_label, 0.25 * DOWN)) self.wait() self.play( TransformFromCopy(ps_vect, y_vect), ShowCreation(y_line), ) self.play(FadeIn(dy_label, 0.25 * LEFT)) self.wait() # Ask about dx_dt randy = Randolph() randy.match_height(dx_label) randy.next_to(dx_label, LEFT, SMALL_BUFF) randy.change("confused", dx_label) randy.save_state() randy.fade(1) randy.change("plain") self.play(Restore(randy)) self.play(WiggleOutThenIn(dx_label)) self.play(Blink(randy)) self.play(FadeOut(randy)) self.derivative_labels = labels self.component_vectors = vects def zoom_out(self): if not self.zoom: self.wait(2) return labels = self.derivative_labels self.play( Restore(self.camera_frame), ApplyFunction(self.grow_labels, labels), run_time=2 ) def relate_x_dot_y_dot_to_v1_v2(self): derivative_labels = self.derivative_labels.copy() dx_label, dy_label = derivative_labels x_label, y_label = self.axes.labels m_part = x_label[2] block1 = self.block1 block_vectors = self.block_velocity_vectors x_eq = x_label[1] dx_eq = OldTex("=") dx_eq.next_to( x_eq, DOWN, buff=LARGE_BUFF, aligned_edge=RIGHT, ) for label in derivative_labels: label.generate_target() label.target.scale(1.5) dx_label.target.next_to(dx_eq, LEFT) dx_rhs = OldTex("\\sqrt{m_1}", "v_1") dx_rhs[0][2:].set_color(BLUE) dx_rhs[1].set_color(GREEN) dx_rhs.next_to(dx_eq, RIGHT) alt_v1 = dx_rhs[1].copy() self.play(ShowCreationThenFadeAround(x_label)) self.play(MoveToTarget(dx_label)) self.play(TransformFromCopy(x_eq, dx_eq)) self.wait() self.play( VGroup(block1, m_part).shift, SMALL_BUFF * UP, rate_func=wiggle, ) self.wait() self.d1_brace.update() self.d1_label.update() self.play( ShowCreationThenFadeAround(x_label[3]), FadeIn(self.d1_brace), FadeIn(self.d1_label), ) self.wait() self.play( TransformFromCopy(x_label[3], dx_rhs[1]), TransformFromCopy(x_label[2], VGroup(dx_rhs[0])), ) block_vectors.suspend_updating() self.play(alt_v1.next_to, block_vectors[0], UP, SMALL_BUFF) self.play( Rotate( block_vectors[0], 10 * DEGREES, about_point=block_vectors[0].get_start(), rate_func=wiggle, run_time=1, ) ) self.play(FadeOut(alt_v1)) block_vectors.resume_updating() self.wait() # dy_label y_eq = y_label[1] dy_eq = OldTex("=") dy_eq.next_to(y_eq, DOWN, LARGE_BUFF) dy_label.target.next_to(dy_eq, LEFT) dy_rhs = OldTex("\\sqrt{m_2}", "v_2") dy_rhs[0][2:].set_color(BLUE) dy_rhs[1].set_color(RED) dy_rhs.next_to(dy_eq, RIGHT) VGroup(dy_label.target, dy_eq, dy_rhs).align_to(y_label, LEFT) alt_v2 = dy_rhs[1].copy() self.play(MoveToTarget(dy_label)) self.play( Write(dy_eq), Write(dy_rhs), ) self.play(alt_v2.next_to, block_vectors[1], UP, SMALL_BUFF) self.wait() self.play(FadeOut(alt_v2)) self.wait() self.derivative_equations = VGroup( VGroup(dx_label, dx_eq, dx_rhs), VGroup(dy_label, dy_eq, dy_rhs), ) def calculate_magnitude(self): corner_rect = Rectangle( stroke_color=WHITE, stroke_width=1, fill_color=BLACK, fill_opacity=1, height=2.5, width=8.5, ) corner_rect.to_corner(UR, buff=0) ps_vect = self.ps_velocity_vector big_ps_vect = Arrow( ps_vect.get_start(), ps_vect.get_end(), buff=0, ) big_ps_vect.match_style(ps_vect) big_ps_vect.scale(1.5) magnitude_bars = OldTex("||", "||") magnitude_bars.match_height( big_ps_vect, stretch=True ) rhs_scale_val = 0.8 rhs = OldTex( "=\\sqrt{" "\\left( dx/dt \\right)^2 + " "\\left( dy/dt \\right)^2" "}" ) rhs.scale(rhs_scale_val) group = VGroup( magnitude_bars[0], big_ps_vect, magnitude_bars[1], rhs ) group.arrange(RIGHT) group.next_to(corner_rect.get_corner(UL), DR) new_rhs = OldTex( "=", "\\sqrt", "{m_1(v_1)^2 + m_2(v_2)^2}", tex_to_color_map={ "m_1": BLUE, "m_2": BLUE, "v_1": GREEN, "v_2": RED, } ) new_rhs.scale(rhs_scale_val) new_rhs.next_to(rhs, DOWN, aligned_edge=LEFT) final_rhs = OldTex( "=", "\\sqrt{2(\\text{Kinetic energy})}" ) final_rhs.scale(rhs_scale_val) final_rhs.next_to(new_rhs, DOWN, aligned_edge=LEFT) self.play( FadeIn(corner_rect), TransformFromCopy(ps_vect, big_ps_vect) ) self.play(Write(magnitude_bars), Write(rhs[0])) self.wait() self.play(Write(rhs[1:])) self.wait() self.play(FadeIn(new_rhs, UP)) for equation in self.derivative_equations: self.play(ShowCreationThenFadeAround(equation)) self.wait() self.play(FadeIn(final_rhs, UP)) self.wait() def let_process_play_out(self): self.play(*map(FadeOut, [ self.projection_lines, self.derivative_labels, self.component_vectors, self.d1_brace, self.d1_label, ])) self.add(self.blocks, self.derivative_equations) self.blocks.resume_updating() self.slide(self.slide_time) # def grow_labels(self, labels): for label, vect in zip(labels, [DOWN, LEFT]): p = label.get_edge_center(vect) p += SMALL_BUFF * vect label.scale(2.5, about_point=p) return labels class IntroduceVelocityVectorWithoutZoom(IntroduceVelocityVector): CONFIG = { "zoom": False, } class ShowMomentumConservation(IntroduceVelocityVector): CONFIG = { "ps_velocity_vector_length": 1.25, "block_velocity_vector_length_multiple": 1, "block1_config": { "distance": 7, }, "axes_config": { "y_max": 11, }, "axes_center": 6.5 * LEFT + 1.2 * DOWN, "floor_y": -3.75, "wait_time": 15, } def construct(self): self.add_velocity_vectors() self.contrast_d1_d2_line_with_xy_line() self.rearrange_for_slope() self.up_to_first_collision() self.ask_what_next() self.show_conservation_of_momentum() self.show_rate_of_change_vector() self.show_sqrty_m_vector() self.show_dot_product() self.show_same_angles() self.show_horizontal_bounce() self.let_process_play_out() def add_velocity_vectors(self): self.slide(1) self.ps_vect = self.get_ps_velocity_vector(self.trajectory) self.block_vectors = self.get_block_velocity_vectors(self.ps_vect) self.play( GrowArrow(self.ps_vect), LaggedStartMap(GrowArrow, self.block_vectors, run_time=1), ) self.add(self.ps_vect, self.block_vectors) def contrast_d1_d2_line_with_xy_line(self): line = self.d1_eq_d2_line label = self.d1_eq_d2_label label.to_edge(RIGHT, buff=1.1) label.shift(0.65 * DOWN) xy_line = line.copy() xy_line.set_stroke(YELLOW, 3) xy_line.set_angle(45 * DEGREES) xy_label = OldTex("x = y") xy_label.next_to(ORIGIN, DOWN, SMALL_BUFF) xy_label.rotate(45 * DEGREES, about_point=ORIGIN) xy_label.shift(xy_line.point_from_proportion(0.2)) self.xy_group = VGroup(xy_line, xy_label) self.play( ShowPassingFlash( line.copy().set_stroke(YELLOW, 4) ), Write(label), ) self.play( TransformFromCopy(line, xy_line, run_time=2) ) self.play(Write(xy_label)) self.wait() def rearrange_for_slope(self): eqs = VGroup(*reversed(self.axes.labels)).copy() y_eq, x_eq = eqs for eq in eqs: point = VectorizedPoint(eq[1].get_center()) eq.submobjects.insert(1, point) eq.submobjects[3] = eq[3].submobjects[0] eq.generate_target() eqs_targets = VGroup(*[eq.target for eq in eqs]) new_eqs = VGroup( OldTex("{y", "\\over", "\\sqrt{m_2}}", "=", "d_2"), OldTex("{x", "\\over", "\\sqrt{m_1}}", "=", "d_1"), ) new_x_eq, new_y_eq = new_eqs # Shuffle to align with x_eq and y_eq for new_eq in new_eqs: new_eq[2][2:].set_color(BLUE) new_eq.submobjects = [new_eq[i] for i in [0, 1, 3, 2, 4]] eqs_targets.arrange(DOWN, buff=LARGE_BUFF) eqs_targets.move_to(RIGHT).to_edge(UP) for eq, new_eq in zip(eqs_targets, new_eqs): new_eq.move_to(eq) self.play(LaggedStartMap(MoveToTarget, eqs, lag_ratio=0.7)) self.play(*[ Transform( eq, new_eq, path_arc=-90 * DEGREES, ) for eq, new_eq in zip(eqs, new_eqs) ]) self.wait() # Shuffle back for eq in eqs: eq[2][2:].set_color(BLUE) eq.submobjects = [eq[i] for i in [0, 1, 3, 2, 4]] # Set equal equals = OldTex("=") for eq in eqs: eq.generate_target() VGroup( x_eq.target[4], x_eq.target[3], x_eq.target[:3], ).arrange(RIGHT) for p1, p2 in zip(x_eq, x_eq.target): p2.align_to(p1, DOWN) group = VGroup(y_eq.target, equals, x_eq.target) group.arrange(RIGHT) x_eq.target.align_to(y_eq.target, DOWN) equals.align_to(y_eq.target[3], DOWN) group.to_edge(UP, buff=MED_SMALL_BUFF) group.to_edge(RIGHT, buff=3) self.play( MoveToTarget(y_eq), MoveToTarget(x_eq, path_arc=90 * DEGREES), GrowFromCenter(equals) ) self.wait() # Simplify final_eq = OldTex( "y", "=", "{\\sqrt{m_2}", "\\over", "\\sqrt{m_1}}", "x", ) for part in final_eq.get_parts_by_tex("sqrt"): part[2:].set_color(BLUE) m_part = final_eq[2:5] final_eq.next_to(group, DOWN) final_eq.shift(0.4 * UP) movers = VGroup( y_eq[0], equals.submobjects[0], y_eq[2], y_eq[1], x_eq[2], x_eq[0] ).copy() for mover, part in zip(movers, final_eq): mover.target = part self.play( LaggedStartMap( MoveToTarget, movers, path_arc=30 * DEGREES, lag_ratio=0.9 ), VGroup(x_eq, equals, y_eq).scale, 0.7, {"about_edge": UP}, ) self.remove(movers) self.add(final_eq) self.wait() # Highlight slope flash_line = self.d1_eq_d2_line.copy() flash_line.set_stroke(YELLOW, 5) self.play(ShowPassingFlash(flash_line)) self.play(ShowCreationThenFadeAround(m_part)) self.wait() # Tuck away slope in mind slope = m_part.copy() slope.generate_target() randy = Randolph(height=1.5) randy.next_to(final_eq, LEFT, MED_SMALL_BUFF) randy.align_to(self.d2_eq_w2_line, DOWN) bubble = ThoughtBubble( height=1.3, width=1.3, direction=RIGHT, ) bubble.pin_to(randy) slope.target.scale(0.5) slope.target.move_to(bubble.get_bubble_center()) randy.change("pondering", slope.target) randy.save_state() randy.change("plane") randy.fade(1) self.play( Restore(randy), Write(bubble), MoveToTarget(slope) ) self.play(Blink(randy)) self.thinking_on_slope_group = VGroup( randy, bubble, slope, ) self.to_fade = VGroup( eqs, equals, final_eq, self.thinking_on_slope_group, self.xy_group, ) def up_to_first_collision(self): self.begin_sliding() self.play(FadeOut(self.to_fade)) self.wait_until( lambda: abs(self.ps_velocity_vector.get_vector()[1]) > 0.01 ) self.end_sliding() self.wait(3 + 3 / 60) # Final cut reasons def ask_what_next(self): ps_vect = self.ps_velocity_vector question = OldTexText("What next?") question.set_background_stroke(color=BLACK, width=3) question.next_to(self.ps_point, UP) self.play(FadeIn(question, DOWN)) ps_vect.suspend_updating() angles = [0.75 * PI, -0.5 * PI, -0.25 * PI] for last_angle, angle in zip(np.cumsum([0] + angles), angles): # This is dumb and shouldn't be needed ps_vect.rotate(last_angle, about_point=ps_vect.get_start()) target = ps_vect.copy() target.rotate( angle, about_point=ps_vect.get_start() ) self.play( Transform( ps_vect, target, path_arc=angle ), ) ps_vect.resume_updating() self.whats_next_question = question def show_conservation_of_momentum(self): equation = self.get_momentum_equation() # Main equation self.play(FadeInFromDown(equation)) for part in equation[:2], equation[3:5]: outline = part.copy() outline.set_fill(opacity=0) outline.set_stroke(YELLOW, 3) self.play(ShowPassingFlash( outline, run_time=1.5 )) self.wait(0.5) # Dot product dot_product = self.get_dot_product() dot_product.next_to(equation, DOWN) sqrty_m_array = dot_product[0] x_label, y_label = self.axes.labels self.play( FadeOut(self.whats_next_question), FadeIn(dot_product), Transform( x_label[2].copy(), sqrty_m_array.get_entries()[0], remover=True, ), Transform( y_label[2].copy(), sqrty_m_array.get_entries()[1], remover=True, ), ) self.momentum_equation = equation self.dot_product = dot_product def show_rate_of_change_vector(self): ps_vect = self.ps_velocity_vector original_d_array = self.dot_product[2] d_array = original_d_array.copy() d_array.generate_target() d_array.scale(0.75) d_array.add_updater(lambda m: m.next_to( ps_vect.get_end(), np.sign(ps_vect.get_vector()[0]) * RIGHT, SMALL_BUFF )) self.play(TransformFromCopy(original_d_array, d_array)) self.wait() self.d_array = d_array def show_sqrty_m_vector(self): original_sqrty_m_array = self.dot_product[0] sqrty_m_vector = Arrow( self.ds_to_point(0, 0), # self.ds_to_point(1, 1), self.ds_to_point(2, 2), buff=0, color=YELLOW, ) sqrty_m_array = original_sqrty_m_array.deepcopy() sqrty_m_array.scale(0.75) sqrty_m_array.next_to( sqrty_m_vector.get_end(), UP, SMALL_BUFF ) rise = DashedLine( sqrty_m_vector.get_end(), sqrty_m_vector.get_corner(DR), color=RED, ) run = DashedLine( sqrty_m_vector.get_corner(DR), sqrty_m_vector.get_start(), color=GREEN, ) sqrty_m_array.add_background_to_entries() run_label, rise_label = sqrty_m_array.get_entries().copy() rise_label.next_to(rise, RIGHT, SMALL_BUFF) run_label.next_to(run, DOWN, SMALL_BUFF) randy_group = self.thinking_on_slope_group randy_group.align_to(self.d2_eq_w2_line, DOWN) randy_group.to_edge(LEFT) randy_group.shift(2 * RIGHT) self.play(GrowArrow(sqrty_m_vector)) self.play(TransformFromCopy( original_sqrty_m_array, sqrty_m_array, )) self.play(FadeIn(randy_group)) self.play( ShowCreation(rise), TransformFromCopy( sqrty_m_array.get_entries()[1], rise_label, ), ) self.add(run, randy_group) self.play( ShowCreation(run), TransformFromCopy( sqrty_m_array.get_entries()[0], run_label, ), ) self.wait() self.play(FadeOut(randy_group)) self.play(FadeOut(VGroup( rise, run, rise_label, run_label, ))) # move to ps_point point = self.ps_point.get_location() sqrty_m_vector.generate_target() sqrty_m_vector.target.shift( point - sqrty_m_vector.get_start() ) sqrty_m_array.generate_target() sqrty_m_array.target.next_to( sqrty_m_vector.target.get_end(), RIGHT, SMALL_BUFF, ) sqrty_m_array.target.shift(SMALL_BUFF * UP) self.play( MoveToTarget(sqrty_m_vector), MoveToTarget(sqrty_m_array), run_time=2 ) self.sqrty_m_vector = sqrty_m_vector self.sqrty_m_array = sqrty_m_array def show_dot_product(self): # Highlight arrays d_array = self.d_array big_d_array = self.dot_product[2] m_array = self.sqrty_m_array big_m_array = self.dot_product[0] self.play( ShowCreationThenFadeAround(big_d_array), ShowCreationThenFadeAround(d_array), ) self.play( ShowCreationThenFadeAround(big_m_array), ShowCreationThenFadeAround(m_array), ) # Before and after ps_vect = self.ps_velocity_vector theta = np.arctan(np.sqrt(self.block2.mass / self.block1.mass)) self.theta = theta ps_vect.suspend_updating() kwargs = {"about_point": ps_vect.get_start()} for x in range(2): for u in [-1, 1]: ps_vect.rotate(u * 2 * theta, **kwargs) self.update_mobjects(dt=0) self.wait() ps_vect.resume_updating() # Circle circle = Circle( radius=ps_vect.get_length(), arc_center=ps_vect.get_start(), color=RED, stroke_width=1, ) self.play( Rotating( ps_vect, about_point=ps_vect.get_start(), run_time=5, rate_func=lambda t: smooth(t, 3), ), FadeIn(circle), ) self.wait() self.ps_vect_circle = circle def show_same_angles(self): # circle = self.ps_vect_circle ps_vect = self.ps_velocity_vector ps_point = self.ps_point point = ps_point.get_center() ghost_ps_vect = ps_vect.copy() ghost_ps_vect.clear_updaters() ghost_ps_vect.set_fill(opacity=0.5) theta = self.theta ghost_ps_vect.rotate( -2 * theta, about_point=ghost_ps_vect.get_start(), ) arc1 = Arc( start_angle=PI, angle=theta, arc_center=point, radius=0.5, color=WHITE, ) arc2 = arc1.copy() arc2.rotate(theta, about_point=point) arc3 = arc1.copy() arc3.rotate(PI, about_point=point) arc1.set_color(BLUE) line_pair = VGroup(*[ Line(point, point + LEFT).rotate( angle, about_point=point ) for angle in [0, theta] ]) line_pair.set_stroke(width=0) ps_vect.suspend_updating() self.play( ShowCreation(arc1), FadeIn(ghost_ps_vect) ) self.wait() self.play( Rotate(ps_vect, 2 * theta, about_point=point) ) self.begin_sliding() ps_vect.resume_updating() self.play(GrowFromPoint(arc2, point)) self.wait(0.5) self.end_sliding() self.play( TransformFromCopy(arc1, arc3, path_arc=-PI), Rotate(line_pair, -PI, about_point=point), UpdateFromAlphaFunc( line_pair, lambda m, a: m.set_stroke( width=there_and_back(a)**0.5 ) ), ) # Show light beam along trajectory self.show_trajectory_beam_bounce() self.wait() # TODO: Add labels for angles? self.play(FadeOut(VGroup( self.ps_vect_circle, ghost_ps_vect, arc1 ))) def show_horizontal_bounce(self): self.slide_until( lambda: self.ps_velocity_vector.get_vector()[1] > 0 ) point = self.ps_point.get_location() theta = self.theta arc1 = Arc( start_angle=0, angle=2 * theta, radius=0.5, arc_center=point, ) arc2 = arc1.copy() arc2.rotate(PI - 2 * theta, about_point=point) arcs = VGroup(arc1, arc2) self.slide(0.5) self.play(LaggedStartMap( FadeInFromLarge, arcs, lag_ratio=0.75, )) self.show_trajectory_beam_bounce() def let_process_play_out(self): self.slide(self.wait_time) self.wait(10) # Just to be sure... # def show_trajectory_beam_bounce(self, n_times=2): # Show light beam along trajectory beam = self.trajectory.copy() beam.clear_updaters() beam.set_stroke(YELLOW, 3) for x in range(n_times): self.play(ShowPassingFlash( beam, run_time=2, rate_func=bezier([0, 0, 1, 1]) )) def get_momentum_equation(self): equation = OldTex( "m_1", "v_1", "+", "m_2", "v_2", "=", "\\text{const.}", tex_to_color_map={ "m_1": BLUE, "m_2": BLUE, "v_1": RED, "v_2": RED, } ) equation.to_edge(UP, buff=MED_SMALL_BUFF) return equation def get_dot_product(self, m1="\\sqrt{m_1}", m2="\\sqrt{m_2}", d1="dx/dt", d2="dy/dt"): sqrty_m = Matrix([[m1], [m2]]) deriv_array = Matrix([[d1], [d2]]) for entry in sqrty_m.get_entries(): if "sqrt" in entry.get_tex(): entry[2:].set_color(BLUE) for matrix in sqrty_m, deriv_array: matrix.add_to_back(BackgroundRectangle(matrix)) matrix.get_brackets().scale(0.9) matrix.set_height(1.25) dot = OldTex("\\cdot") rhs = OldTex("= \\text{const.}") dot_product = VGroup( sqrty_m, dot, deriv_array, rhs ) dot_product.arrange(RIGHT, buff=SMALL_BUFF) return dot_product class JustTheProcessNew(PositionPhaseSpaceScene): CONFIG = { "block1_config": { "mass": 16, "velocity": -2 }, "wait_time": 10, } def setup(self): super().setup() self.add( self.floor, self.wall, self.blocks, self.axes, self.d1_eq_d2_line, self.d2_eq_w2_line, ) def construct(self): self.slide(self.wait_time)
from manim_imports_ext import * from _2019.clacks.solution2.position_phase_space import ShowMomentumConservation class ConnectionToOptics(Scene): def construct(self): e_group, m_group = k_groups = self.get_kinematics_groups() c_group, a_group = o_groups = self.get_optics_groups() arrows = VGroup() for g1, g2 in zip(k_groups, o_groups): g2.align_to(g1, UP) g2.to_edge(RIGHT) arrow = OldTex("\\Rightarrow") arrow.scale(1.5) arrow.move_to(interpolate( g1[0].get_right(), g2[0].get_left(), 0.5 )) arrows.add(arrow) everything = VGroup(k_groups, arrows, o_groups) everything.to_edge(UP) everything.generate_target() everything.target.scale(0.9) everything.target.to_edge(DOWN) width = max([m.get_width() for m in everything.target]) width += 2 * MED_SMALL_BUFF rects = VGroup() for k in [0, 2]: rect = DashedVMobject(Rectangle( height=FRAME_HEIGHT - 1.5, width=width ), num_dashes=100) rect.move_to(everything.target[k]) rect.to_edge(DOWN, buff=SMALL_BUFF) rects.add(rect) titles = VGroup( OldTexText("Kinematics"), OldTexText("Optics"), ) titles.scale(1.5) for title, rect in zip(titles, rects): title.next_to(rect, UP) titles[0].align_to(titles[1], UP) self.play(FadeInFromDown(e_group)) self.play( Write(arrows[0]), FadeIn(c_group, LEFT) ) self.wait() self.play(FadeInFromDown(m_group)) self.play( Write(arrows[1]), FadeIn(a_group, LEFT) ) self.wait(4) for k in range(2): anims = [ ShowCreation(rects[k]), FadeInFromDown(titles[k]), ] if k == 0: anims.append(MoveToTarget(everything)) self.play(*anims) self.wait() self.wait() self.wait(4) def get_kinematics_groups(self): tex_to_color_map = { "m_1": BLUE, "m_2": BLUE, "v_1": RED, "v_2": RED, } energy_eq = OldTex( "\\frac{1}{2} m_1 (v_1)^2 + " "\\frac{1}{2} m_2 (v_2)^2 = " "\\text{const.}", tex_to_color_map=tex_to_color_map ) energy_eq.scale(0.8) momentum_eq = OldTex( "m_1 v_1 + m_2 v_2 = \\text{const.}", tex_to_color_map=tex_to_color_map ) energy_label = OldTexText( "Conservation of energy" ) momentum_label = OldTexText( "Conservation of momentum" ) energy_group = VGroup(energy_label, energy_eq) momentum_group = VGroup(momentum_label, momentum_eq) groups = VGroup(energy_group, momentum_group) for group in groups: group.arrange(DOWN, buff=MED_LARGE_BUFF) group[0].set_color(GREEN) groups.arrange(DOWN, buff=2) groups.to_edge(LEFT) return groups def get_optics_groups(self): self.time_tracker = ValueTracker(0) self.time_tracker.add_updater( lambda m, dt: m.increment_value(dt) ) self.add(self.time_tracker) return VGroup( self.get_speed_group(), self.get_angle_group() ) def get_speed_group(self): speed_label = OldTexText("Constant speed of light") speed_label.set_color(YELLOW) speed_light_template = Line(LEFT, RIGHT) speed_light_template.fade(1) speed_light_template.match_width(speed_label) speed_light_template.next_to(speed_label, DOWN, MED_LARGE_BUFF) speed_light = speed_light_template.deepcopy() def update_speed_light(light, period=2, time_width=0.05): time = self.time_tracker.get_value() alpha = (time / period) % 1 # alpha = 1 - 2 * abs(alpha - 0.5) alpha *= 1.5 a = alpha - time_width / 2 b = alpha + time_width / 2 light.pointwise_become_partial( speed_light_template, max(a, 0), min(b, 1) ) opacity = speed_label.family_members_with_points()[0].get_fill_opacity() light.set_stroke(YELLOW, width=3, opacity=opacity) # light.stretch(0.5, 0) # point = speed_light_template.point_from_proportion(0.25) # light.stretch(2, 0, about_point=point) speed_light.add_updater(update_speed_light) result = VGroup( speed_label, speed_light_template, speed_light ) return result def get_angle_group(self): title = VGroup(*map(TexText, [ "Angle of\\\\Incidence", "=", "Angle of\\\\Reflection", ])).arrange(RIGHT) title.set_color(YELLOW) h_line = Line(LEFT, RIGHT) h_line.match_width(title) h_line.set_stroke(GREY_B) h_line.set_sheen(1, UL) points = [ h_line.get_left() + UP, h_line.get_center(), h_line.get_right() + UP, ] dashed_lines = VGroup( DashedLine(*points[0:2]), DashedLine(*points[1:3]) ) dashed_lines.set_stroke(WHITE, 2) v_shape = VMobject() v_shape.set_points_as_corners(points) v_shape.fade(1) theta = dashed_lines[1].get_angle() arcs = VGroup( Arc(start_angle=0, angle=theta), Arc(start_angle=PI, angle=-theta), ) arcs.set_stroke(WHITE, 2) thetas = VGroup() for v in LEFT, RIGHT: theta = OldTex("\\theta") theta.next_to(arcs, v, aligned_edge=DOWN) theta.shift(SMALL_BUFF * UP) thetas.add(theta) beam = VMobject() def update_beam(beam, period=2, time_width=0.05): time = self.time_tracker.get_value() alpha = (time / period) % 1 alpha *= 1.5 a = alpha - time_width / 2 b = alpha + time_width / 2 beam.pointwise_become_partial( v_shape, max(a, 0), min(b, 1) ) opacity = title.family_members_with_points()[0].get_fill_opacity() beam.set_stroke(YELLOW, width=3, opacity=opacity) beam.add_updater(update_beam) title.next_to(v_shape, UP, MED_LARGE_BUFF) return VGroup( title, h_line, arcs, thetas, dashed_lines, v_shape, beam ) class ConnectionToOpticsTransparent(ConnectionToOptics): pass class RearrangeMomentumEquation(ShowMomentumConservation): def setup(self): pass # Don't build all the things def construct(self): self.add(FullScreenFadeRectangle( fill_color=BLACK, fill_opacity=0.95, )) self.show_initial_dot_product() self.show_with_x_and_y() def show_initial_dot_product(self): equation = self.get_momentum_equation() dot_product = self.get_dot_product( "m_1", "m_2", "v_1", "v_2" ) dot_product.next_to(equation, DOWN, LARGE_BUFF) m_array, dot, v_array, rhs = dot_product m_array.get_entries().set_color(BLUE) v_array.get_entries().set_color(RED) self.add(equation) self.play(FadeInFromDown(VGroup( m_array.get_brackets(), dot, v_array.get_brackets(), rhs, ))) self.play(TransformFromCopy( equation.get_parts_by_tex("m_"), m_array.get_entries(), )) self.play(TransformFromCopy( equation.get_parts_by_tex("v_"), v_array.get_entries(), )) self.wait() self.simple_dot_product = dot_product self.momentum_equation = equation def show_with_x_and_y(self): simple_dot_product = self.simple_dot_product momentum_equation = self.momentum_equation new_equation = OldTex( "\\sqrt{m_1}", "\\left(", "\\sqrt{m_1}", "v_1", "\\right)", "+", "\\sqrt{m_2}", "\\left(", "\\sqrt{m_2}", "v_2", "\\right)", "=", "\\text{const.}", ) new_equation.set_color_by_tex_to_color_map({ "m_": BLUE, "v_": RED, }) new_equation.next_to(momentum_equation, DOWN, MED_LARGE_BUFF) x_term = new_equation[1:5] y_term = new_equation[7:11] x_brace = Brace(x_term, DOWN) y_brace = Brace(y_term, DOWN) dx_dt = x_brace.get_tex("dx / dt") dy_dt = y_brace.get_tex("dy / dt") new_eq_group = VGroup( new_equation, x_brace, y_brace, dx_dt, dy_dt ) new_eq_group.generate_target() new_dot_product = self.get_dot_product() m_array, dot, d_array, rhs = new_dot_product new_dot_product.next_to(momentum_equation, DOWN) new_eq_group.target.next_to(new_dot_product, DOWN, LARGE_BUFF) self.play( FadeIn(new_equation, UP), simple_dot_product.to_edge, DOWN, LARGE_BUFF, ) self.wait() self.play( GrowFromCenter(x_brace), GrowFromCenter(y_brace), FadeIn(dx_dt, UP), FadeIn(dy_dt, UP), ) self.wait() self.play( FadeIn(VGroup( m_array.get_brackets(), dot, d_array.get_brackets(), rhs )), MoveToTarget(new_eq_group) ) self.play(TransformFromCopy( VGroup( VGroup(new_equation[0]), VGroup(new_equation[6]), ), m_array.get_entries(), )) self.play(TransformFromCopy( VGroup(dx_dt, dy_dt), d_array.get_entries(), )) self.wait() class NewSceneName(Scene): def construct(self): pass
from manim_imports_ext import * from _2018.lost_lecture import ShowWord from _2019.clacks.solution2.mirror_scenes import ReflectWorldThroughMirrorNew from _2019.clacks.question import Thumbnail class WrapperScene(Scene): CONFIG = { "title": "Title", "shade_of_grey": "#333333" } def construct(self): title = OldTexText(self.title) title.scale(1.5) title.to_edge(UP) big_rect = self.get_big_rect() screen_rect = self.get_screen_rect() screen_rect.next_to(title, DOWN) self.add(big_rect, screen_rect) self.play( FadeIn(big_rect), FadeIn(title, DOWN), FadeIn(screen_rect, UP), ) self.wait() def get_big_rect(self): big_rect = FullScreenFadeRectangle() big_rect.set_fill(self.shade_of_grey, 1) return big_rect def get_screen_rect(self, height=6): screen_rect = ScreenRectangle(height=height) screen_rect.set_fill(BLACK, 1) return screen_rect class ComingUpWrapper(WrapperScene): CONFIG = {"title": "Coming up..."} class LastVideoWrapper(WrapperScene): CONFIG = {"title": "Last time..."} class LeftEdge(Scene): CONFIG = { "text": "Left edge", "vect": LEFT, } def construct(self): words = OldTexText(self.text) arrow = Vector(self.vect) arrow.match_width(words) arrow.next_to(words, DOWN) self.play( FadeInFromDown(words), GrowArrow(arrow) ) self.wait() class RightEdge(LeftEdge): CONFIG = { "text": "Right edge", "vect": RIGHT, } class NoteOnEnergyLostToSound(Scene): def construct(self): self.add(OldTexText( "Yeah yeah, the clack sound\\\\" "would require energy, but\\\\" "don't let accuracy get in the\\\\" "way of delight!", alignment="", )) class DotProductVideoWrapper(WrapperScene): CONFIG = {"title": "Dot product"} class Rectangle(Scene): def construct(self): rect = ScreenRectangle(height=FRAME_HEIGHT - 0.25) rect.set_stroke(WHITE, 6) self.add(rect) class ShowRectangleCreation(Scene): def construct(self): rect = ScreenRectangle(height=2) rect.set_stroke(YELLOW, 6) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) class ShowDotProductMeaning(Scene): def construct(self): v_vect = Vector(2 * RIGHT, color=YELLOW) w_vect = Vector(3 * RIGHT, color=PINK) dot = Dot(color=RED) dot.shift(DOWN) v_vect.angle_tracker = ValueTracker() w_vect.angle_tracker = ValueTracker() def update_vect(vect): target = vect.angle_tracker.get_value() vect.rotate(target - vect.get_angle()) vect.shift(dot.get_center() - vect.get_start()) v_vect.add_updater(update_vect) w_vect.add_updater(update_vect) v_label = OldTex("\\vec{\\textbf{v}}") v_label.vect = v_vect w_label = OldTex("\\vec{\\textbf{w}}") w_label.vect = w_vect for label in v_label, w_label: label.match_color(label.vect) label.set_stroke(BLACK, 5, background=True) def update_label(label): target = np.array(label.vect.get_end()) target += 0.25 * normalize(label.vect.get_vector()) label.move_to(target) v_label.add_updater(update_label) w_label.add_updater(update_label) title = OldTex( "\\vec{\\textbf{w}}", "\\cdot", "\\vec{\\textbf{v}}", "=", "||", "\\vec{\\textbf{w}}", "||", "\\cdot", "||", "\\vec{\\textbf{v}}", "||", "\\cdot", "\\cos(\\theta)" ) title.set_color_by_tex_to_color_map({ "textbf{v}": v_vect.get_color(), "textbf{w}": w_vect.get_color(), }) title.to_edge(UP) def get_w_line(): center = dot.get_center() direction = w_vect.get_vector() return Line( center - 3 * direction, center + 3 * direction, stroke_color=GREY_B, stroke_width=1, ) w_line = always_redraw(get_w_line) def get_proj_v(): center = dot.get_center() v = v_vect.get_vector() w = w_vect.get_vector() w_unit = normalize(w) result = Vector(np.dot(v, w_unit) * w_unit) result.set_fill(v_vect.get_color(), 0.5) result.shift(center - result.get_start()) return result proj_v = always_redraw(get_proj_v) def get_proj_line(): return DashedLine( v_vect.get_end(), proj_v.get_end(), stroke_width=1, dash_length=0.025, ) proj_line = always_redraw(get_proj_line) template_line = Line(LEFT, RIGHT) def get_vect_brace(vect): brace = Brace(template_line, UP, buff=SMALL_BUFF) brace.set_width(vect.get_length(), stretch=True) angle = vect.get_angle() % TAU if angle < PI: angle += PI brace.rotate(angle, about_point=ORIGIN) brace.shift(vect.get_center()) return brace w_brace = always_redraw( lambda: get_vect_brace(w_vect) ) proj_v_brace = always_redraw( lambda: get_vect_brace(proj_v) ) def get_arc(): center = dot.get_center() a1 = w_vect.get_angle() a2 = v_vect.get_angle() arc = Arc( start_angle=a1, angle=a2 - a1, radius=0.5, arc_center=center, ) theta = OldTex("\\theta") p = arc.point_from_proportion(0.5) theta.move_to( center + 1.5 * (p - center) ) return VGroup(arc, theta) arc = always_redraw(get_arc) self.add( title[:3], w_vect, v_vect, dot, w_label, v_label, ) self.play( v_vect.angle_tracker.set_value, 170 * DEGREES, w_vect.angle_tracker.set_value, 45 * DEGREES, run_time=2, ) self.wait() w_brace.update() self.play( GrowFromCenter(w_brace), Write(title[3:7]) ) self.add(w_line, w_vect, w_label, dot) self.play(ShowCreation(w_line)) proj_v.update() self.play( ShowCreation(proj_line), TransformFromCopy(v_vect, proj_v), ) self.add(proj_v, proj_line, dot) proj_v_brace.update() self.play( GrowFromCenter(proj_v_brace), FadeInFromDown(title[7:]) ) arc.update() self.play(Write(arc)) self.wait() for angle in [135, 225, 270, 90, 150]: self.play( v_vect.angle_tracker.set_value, angle * DEGREES, run_time=2 ) self.wait() class FinalComment(Scene): def construct(self): self.add(OldTexText( "Thoughts on what ending should go here?\\\\" "See the Patreon post." )) class FourtyFiveDegreeLine(Scene): CONFIG = { "angle": 45 * DEGREES, "label_config": { "num_decimal_places": 0, "unit": "^\\circ", "label_height": 0.3, }, "degrees": True } def construct(self): angle = self.angle arc = Arc(angle, radius=1) label = DecimalNumber(0, **self.label_config) label.set_height(self.label_config["label_height"]) label.next_to(arc, RIGHT) label.shift(0.5 * SMALL_BUFF * UP) line1 = Line(ORIGIN, 3 * RIGHT) line2 = line1.copy() if self.degrees: target_value = int(angle / DEGREES) else: target_value = angle self.add(line1, label) self.play( ChangeDecimalToValue(label, target_value), ShowCreation(arc), Rotate(line2, angle, about_point=ORIGIN) ) self.wait() class ArctanSqrtPoint1Angle(FourtyFiveDegreeLine): CONFIG = { "angle": np.arctan(np.sqrt(0.1)), } class AskAboutAddingThetaToItself(Scene): CONFIG = { "theta": np.arctan(0.25), "wait_time": 0.25, "wedge_radius": 3, "theta_symbol_scale_val": 0.5, "number_height": 0.2, } def construct(self): theta = self.theta groups = self.get_groups(theta) horizon = self.get_horizon() counter = ValueTracker(0) dynamic_ineq = self.get_dynamic_inequality(counter) semicircle = self.get_semicircle() self.add(horizon) self.add(dynamic_ineq) for n in range(len(groups)): counter.set_value(n + 1) if n < len(groups) - 1: groups[n][-1].set_color(YELLOW) if n > 0: groups[n - 1][-1].set_color(WHITE) self.add(groups[:n + 1]) self.add_sound("pen_click", gain=-20) self.wait(self.wait_time) self.wait(0.5) counter.set_value(counter.get_value() - 1) self.remove(groups[-1]) self.add_sound("pen_click", gain=-20) self.wait() self.play(ShowCreation(semicircle)) self.play(FadeOut(semicircle)) self.wait(3) def get_group(self, theta): # Define group wedge_radius = self.wedge_radius wedge = VGroup( Line(ORIGIN, wedge_radius * RIGHT), Line(ORIGIN, wedge_radius * RIGHT).rotate( theta, about_point=ORIGIN ), ) wedge.set_stroke((WHITE, GREY), 2) arc = Arc(theta, radius=1) theta_symbol = OldTex("\\theta") tssv = self.theta_symbol_scale_val theta_symbol.scale(tssv) theta_symbol.next_to(arc, RIGHT, tssv / 2) theta_symbol.shift(tssv * SMALL_BUFF * UP) return VGroup(wedge, arc, theta_symbol) def get_groups(self, theta): group = self.get_group(theta) angles = [k * theta for k in range(int(PI / theta) + 1)] groups = VGroup(*[ group.copy().rotate(angle, about_point=ORIGIN) for angle in angles ]) # colors = it.cycle([BLUE_D, BLUE_B, BLUE_C, GREY_BROWN]) colors = it.cycle([BLUE_D, GREY_BROWN]) for n, angle, group, color in zip(it.count(1), angles, groups, colors): wedge, arc, symbol = group symbol.rotate(-angle) arc.set_color(color) number = Integer(n) number.set_height(self.number_height) number.move_to(center_of_mass([ wedge[0].get_end(), wedge[1].get_end(), ])) group.add(number) groups[-1][-1].set_color(RED) return groups def get_horizon(self): horizon = DashedLine(5 * LEFT, 5 * RIGHT) horizon.set_stroke(WHITE, 1) return horizon def get_semicircle(self): return Arc( start_angle=0, angle=PI, radius=self.wedge_radius / 2, color=YELLOW, stroke_width=4, ) def get_inequality(self): ineq = OldTex( "N", "\\cdot", "\\theta", "<", "\\pi", "=", "3.1415926\\dots" ) N = ineq.get_part_by_tex("N") self.pi_symbol = ineq.get_part_by_tex("\\pi") N.set_color(YELLOW) # ineq[-3:].set_color(BLUE) brace = Brace(N, UP, buff=SMALL_BUFF) text = brace.get_text("Maximum", buff=SMALL_BUFF) group = VGroup(ineq, brace, text) group.next_to(ORIGIN, DOWN, MED_LARGE_BUFF) return group def get_dynamic_inequality(self, counter): multiple = Integer(0) dot = OldTex("\\cdot") theta_tex = OldTex("({:.2f})".format(self.theta)) eq = OldTex("=") value = DecimalNumber(0) ineq = OldTex("<") pi = OldTex("\\pi", "=", "3.1415926\\dots") # pi.set_color(BLUE) group = VGroup( multiple, dot, theta_tex, eq, value, ineq, pi ) group.arrange(RIGHT, buff=0.2) group.next_to(ORIGIN, DOWN, buff=LARGE_BUFF) theta_brace = Brace(group[2], DOWN, buff=SMALL_BUFF) theta_symbol = theta_brace.get_tex("\\theta") group.add(theta_brace, theta_symbol) # group.align_to(self.pi_symbol, RIGHT) def get_count(): return int(counter.get_value()) def get_product(): return get_count() * self.theta def is_greater_than_pi(): return get_product() > PI def get_color(): return RED if is_greater_than_pi() else YELLOW def get_ineq(): result = OldTex( ">" if is_greater_than_pi() else "<" ) result.set_color(get_color()) result.move_to(ineq) return result dynamic_ineq = always_redraw(get_ineq) group.remove(ineq) group.add(dynamic_ineq) multiple.add_updater(lambda m: m.set_value(get_count())) multiple.add_updater(lambda m: m.next_to(dot, LEFT, 0.2)) multiple.add_updater(lambda m: m.set_color(get_color())) value.add_updater(lambda m: m.set_value(get_product())) return group class AskAboutAddingThetaToItselfThetaPoint1(AskAboutAddingThetaToItself): CONFIG = { "theta": 0.1, "wait_time": 0.1, "theta_symbol_scale_val": 0.25, "number_height": 0.15, } class AskAboutAddingThetaToItselfThetaPoint2(AskAboutAddingThetaToItself): CONFIG = { "theta": 0.2, "wait_time": 0.1, } class FinalFormula(Scene): def construct(self): text = OldTexText("Final answer: ") t2c_map = { "\\theta": BLUE, "m_1": GREEN, "m_2": RED, } formula = OldTex( "\\left\\lfloor", "{\\pi", "\\over", "\\theta}", "\\right\\rfloor" ) formula.set_color_by_tex_to_color_map(t2c_map) group = VGroup(text, formula) group.arrange(RIGHT) group.scale(1.5) group.to_edge(UP) self.play(Write(text)) self.play(FadeIn(formula)) self.play(ShowCreationThenFadeAround(formula)) self.wait() theta_eq = OldTex( "\\theta", "=", "\\arctan", "\\left(", "\\sqrt", "{{m_2", "\\over", "m_1}}", "\\right)" ) theta_eq.set_color_by_tex_to_color_map(t2c_map) theta_eq.scale(1.5) theta_eq.next_to(group, DOWN, MED_LARGE_BUFF) self.play(TransformFromCopy( formula.get_part_by_tex("\\theta"), theta_eq.get_part_by_tex("\\theta"), )) self.play(Write(theta_eq[1:])) self.wait() class ReviewWrapper(WrapperScene): CONFIG = {"title": "To review:"} class SurprisedRandy(Scene): def construct(self): randy = Randolph() self.play(randy.change, "surprised", 3 * UR) self.play(Blink(randy)) self.play(randy.change, "confused") self.play(Blink(randy)) self.wait() class TwoSolutionsWrapper(WrapperScene): def construct(self): big_rect = self.get_big_rect() screen_rects = VGroup(*[ self.get_screen_rect(height=3) for x in range(2) ]) screen_rects.arrange(RIGHT, buff=LARGE_BUFF) title = OldTexText("Two solutions") title.scale(1.5) title.to_edge(UP) screen_rects.next_to(title, DOWN, LARGE_BUFF) # pi creatures pis = VGroup( Randolph(color=BLUE_D), Randolph(color=BLUE_E), Randolph(color=BLUE_B), Mortimer().scale(1.2) ) pis.set_height(2) pis.arrange(RIGHT, buff=MED_LARGE_BUFF) pis.to_edge(DOWN, buff=SMALL_BUFF) self.add(big_rect, title, pis) self.play( LaggedStartMap( ShowCreation, screen_rects.copy().set_fill(opacity=0), lag_ratio=0.8 ), LaggedStartMap( FadeIn, screen_rects, lag_ratio=0.8 ), LaggedStartMap( ApplyMethod, pis, lambda pi: (pi.change, "pondering", screen_rects[0]) ), ) self.play(Blink(random.choice(pis))) self.play(LaggedStartMap( ApplyMethod, pis, lambda pi: (pi.change, "thinking", screen_rects[1]) )) self.play(Blink(random.choice(pis))) self.wait() class FinalQuote(Scene): def construct(self): quote_text = """ A change of perspective\\\\ is worth 80 IQ points. """ quote_parts = [s for s in quote_text.split(" ") if s] quote = OldTexText( *quote_parts, ) quote.scale(1.2) quote.shift(2 * RIGHT + UP) image = ImageMobject("AlanKay") image.set_height(6) image.to_corner(UL) image.shift(2 * LEFT + 0.5 * UP) name = OldTexText("Alan Kay") name.scale(1.5) name.next_to(image, DOWN) name.shift_onto_screen() self.play( FadeInFromDown(image), Write(name), ) self.wait() for word in quote: self.play(ShowWord(word)) self.wait(0.005 * len(word)**1.5) self.wait() class EndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "1stViewMaths", "Adam Kozak", "Adrian Robinson", "Alexis Olson", "Ali Yahya", "Andreas Benjamin Brössel", "Andrew Busey", "Ankalagon", "Antonio Juarez", "Arjun Chakroborty", "Art Ianuzzi", "Arthur Zey", "Awoo", "Bernd Sing", "Bob Sanderson", "Boris Veselinovich", "Brian Staroselsky", "Britt Selvitelle", "Burt Humburg", "Chad Hurst", "Charles Southerland", "Chris Connett", "Christian Kaiser", "Clark Gaebel", "Cooper Jones", "D. Sivakumar", "Danger Dai", "Dave B", "Dave Kester", "dave nicponski", "David Clark", "David Gow", "Delton Ding", "Devarsh Desai", "eaglle", "emptymachine", "Eric Younge", "Eryq Ouithaqueue", "Evan Phillips", "Federico Lebron", "Florian Chudigiewitsch", "Giovanni Filippi", "Graham", "Hal Hildebrand", "Hitoshi Yamauchi", "J", "j eduardo perez", "Jacob Magnuson", "Jameel Syed", "James Hughes", "Jan Pijpers", "Jason Hise", "Jeff Linse", "Jeff Straathof", "John Griffith", "John Haley", "John Shaughnessy", "John V Wertheim", "Jonathan Eppele", "Jonathan Wilson", "Jordan Scales", "Joseph John Cox", "Joseph Kelly", "Juan Benet", "Kai-Siang Ang", "Kanan Gill", "Kaustuv DeBiswas", "L0j1k", "Lee Redden", "Linh Tran", "Luc Ritchie", "Ludwig Schubert", "Lukas -krtek.net- Novy", "Lukas Biewald", "Magister Mugit", "Magnus Dahlström", "Magnus Lysfjord", "Mark B Bahu", "Mark Heising", "Mathew Bramson", "Mathias Jansson", "Matt Langford", "Matt Roveto", "Matt Russell", "Matthew Cocke", "Mauricio Collares", "Michael Faust", "Michael Hardel", "Mike Coleman", "Mustafa Mahdi", "Márton Vaitkus", "Nathan Jessurun", "Nero Li", "Omar Zrien", "Owen Campbell-Moore", "Peter Ehrnstrom", "Peter Mcinerney", "Quantopian", "Randy C. Will", "Richard Barthel", "Richard Burgmann", "Richard Comish", "Ripta Pasay", "Rish Kundalia", "Robert Teed", "Roobie", "Roy Larson", "Ryan Atallah", "Ryan Williams", "Samuel D. Judge", "Scott Gray", "Scott Walter, Ph.D.", "Sindre Reino Trosterud", "soekul", "Solara570", "Song Gao", "Stevie Metke", "Ted Suzman", "Tihan Seale", "Valeriy Skobelev", "Vassili Philippov", "Xavier Bernard", "Yana Chernobilsky", "Yaw Etse", "YinYangBalance.Asia", "Yu Jun", "Zach Cardwell", ], } class ClacksSolution2Thumbnail(Scene): def construct(self): self.add_scene1() self.add_scene2() arrow = Arrow( self.block_word.get_top(), self.light_dot.get_bottom(), tip_length=0.75, rectangular_stem_width=0.2, color=RED, buff=0.5, ) arrow.add_to_back(arrow.copy().set_stroke(BLACK, 20)) self.add(arrow) return arrow = OldTex("\\Updownarrow") arrow.set_height(2) arrow.set_color(YELLOW) arrow.set_stroke(Color("red"), 2, background=True) self.add(arrow) def add_scene1(self): scene1 = Thumbnail( sliding_blocks_config={ "block1_config": { "label_text": "$100^{d}$ kg", "distance": 8, }, } ) group = Group(*scene1.mobjects) group.scale(0.75, about_point=ORIGIN) group.shift(1.5 * DOWN + 3 * LEFT) scene1.remove(scene1.question) self.add(*scene1.mobjects) black_rect = FullScreenFadeRectangle(fill_opacity=1) black_rect.shift(3.5 * UP) self.add(black_rect) word = OldTexText("Blocks") word.set_color(YELLOW) word.scale(3) word.to_corner(DR, buff=LARGE_BUFF) word.shift(0.5 * LEFT) self.block_word = word self.add(word) def add_scene2(self): scene2 = ReflectWorldThroughMirrorNew( skip_animations=True, file_writer_config={ "write_to_movie": False, }, end_at_animation_number=18, # center=1.5 * DOWN, center=ORIGIN, ) worlds = VGroup(scene2.world, *scene2.reflected_worlds) mirrors = VGroup(*[rw[1] for rw in worlds]) mirrors.set_stroke(width=5) triangles = VGroup(*[rw[0] for rw in worlds]) trajectories = VGroup( scene2.trajectory, *scene2.reflected_trajectories ) trajectories.set_stroke(YELLOW, 1) beams1, beams2 = [ scene2.get_shooting_beam_anims( path, max_stroke_width=20, max_time_width=1, num_flashes=50, ) for path in [ scene2.trajectory, scene2.ghost_trajectory, ] ] beams = beams1 + beams2 beams = beams2 flashes = VGroup() for beam in beams: beam.update(0.5) flashes.add(beam.mobject) dot = self.light_dot = Dot(color=YELLOW, radius=0.1) dot.move_to(flashes[0].get_left()) flashes.add(dot) self.add(triangles, mirrors) # self.add(randys) self.add(trajectories[0].set_stroke(width=2)) self.add(flashes) word = OldTexText("Light beam") word.scale(3.5) word.set_color(YELLOW) # word.set_stroke(BLACK, 25, background=True) word.add_to_back(word.copy().set_stroke( BLACK, 25, )) word.next_to(dot, UR) word.shift(-word.get_center()[0] * RIGHT) word.shift(SMALL_BUFF * RIGHT) self.light_word = word self.add(word)
from manim_imports_ext import * class PreviousTwoVideos(BlocksAndWallExample): CONFIG = { "sliding_blocks_config": { "block1_config": { "mass": 1e2, "velocity": -2, "width": 4, "distance": 8, }, "block2_config": { "width": 4, "distance": 3, }, }, "floor_y": -3, "wait_time": 15, } def setup(self): super().setup() blocks = self.blocks videos = Group( ImageMobject("ClacksSolution1Thumbnail"), ImageMobject("ClacksQuestionThumbnail"), ) for n, video, block in zip([2, 1], videos, blocks): block.fade(1) video.add(SurroundingRectangle( video, buff=0, color=BLUE, stroke_width=3, )) video.replace(block) title = OldTexText("Part {}".format(n)) title.scale(1.5) title.next_to(video, UP, MED_SMALL_BUFF) video.add(title) def update_videos(videos): for video, block in zip(videos, blocks): video.move_to(block, DOWN) video.shift(0.04 * UP) videos.add_updater(update_videos) self.add(videos) if self.show_flash_animations: self.add(self.clack_flashes.mobject) self.videos = videos class IntroducePreviousTwoVideos(PreviousTwoVideos): CONFIG = { "show_flash_animations": False, "include_sound": False, } def construct(self): blocks = self.blocks videos = self.videos self.remove(blocks) videos.clear_updaters() self.remove(videos) self.play(FadeInFromLarge(videos[1])) self.play(TransformFromCopy( videos[0].copy().fade(1).shift(2 * RIGHT), videos[0], rate_func=lambda t: rush_into(t, 3), )) # self.wait()
from _2019.diffyq.part1.pendulum import * from _2019.diffyq.part1.staging import * from _2019.diffyq.part1.pi_scenes import * from _2019.diffyq.part1.phase_space import * from _2019.diffyq.part1.wordy_scenes import * OUTPUT_DIRECTORY = "diffyq/part1" SCENES_IN_ORDER = [ WhenChangeIsEasier, VectorFieldTest, IntroducePendulum, MultiplePendulumsOverlayed, PeriodFormula, FormulasAreLies, MediumAnglePendulum, MediumHighAnglePendulum, HighAnglePendulum, LowAnglePendulum, SomeOfYouWatching, SmallAngleApproximationTex, VeryLowAnglePendulum, FormulasAreLies, TourOfDifferentialEquations, WherePendulumLeads, LongDoublePendulum, # FollowThisThread, StrogatzQuote, ShowHorizontalDashedLine, RabbitFoxPopulations, RabbitFoxEquation, # Something... ShowSimpleTrajectory, SimpleProjectileEquation, SimpleProjectileEquationVGraphFreedom, ShowGravityAcceleration, UniversalGravityLawSymbols, ExampleTypicalODE, AnalyzePendulumForce, ShowSineValues, BuildUpEquation, AirResistanceBrace, ShowDerivativeVideo, SubtleAirCurrents, SimpleDampenedPendulum, DefineODE, SecondOrderEquationExample, ODEvsPDEinFrames, ProveTeacherWrong, SetAsideSeekingSolution, # WriteInRadians, XEqLThetaToCorner, ComingUp, InputLabel, SoWhatIsThetaThen, ReallyHardToSolve, ReasonForSolution, PhysicistPhaseSpace, GleickQuote, SpectrumOfStartingStates, WritePhaseFlow, AskAboutStability, LoveExample, PassageOfTime, LovePhaseSpace, ComparePhysicsToLove, FramesComparingPhysicsToLove, SetupToTakingManyTinySteps, ShowClutterPrevention, # VisualizeHeightSlopeCurvature, VisualizeStates, ReferencePiCollisionStateSpaces, IntroduceVectorField, XComponentArrows, BreakingSecondOrderIntoTwoFirstOrder, ShowPendulumPhaseFlow, ShowHighVelocityCase, TweakMuInFormula, TweakMuInVectorField, FromODEToVectorField, LorenzVectorField, ThreeBodiesInSpace, AltThreeBodiesInSpace, TwoBodiesInSpace, TwoBodiesWithZPart, ThreeBodyTitle, ThreeBodySymbols, # HighAmplitudePendulum, WritePhaseSpace, # AskAboutActuallySolving, WriteODESolvingCode, TakeManyTinySteps, ManyStepsFromDifferentStartingPoints, InaccurateComputation, HungerForExactness, ShowRect, ShowSquare, JumpToThisPoint, ThreeBodyEquation, ItGetsWorse, ChaosTitle, RevisitQuote, EndScreen, Thumbnail, ]
from _2019.diffyq.part2.staging import * from _2019.diffyq.part2.fourier_series import * from _2019.diffyq.part2.heat_equation import * from _2019.diffyq.part2.pi_scenes import * from _2019.diffyq.part2.wordy_scenes import * OUTPUT_DIRECTORY = "diffyq/part2" SCENES_IN_ORDER = [ PartTwoOfTour, HeatEquationIntroTitle, BrownianMotion, BlackScholes, ContrastChapters1And2, FourierSeriesIntro, FourierSeriesIntroBackground20, ExplainCircleAnimations, # FourierSeriesIntroBackground4, # FourierSeriesIntroBackground8, # FourierSeriesIntroBackground12, TwoDBodyWithManyTemperatures, TwoDBodyWithManyTemperaturesGraph, TwoDBodyWithManyTemperaturesContour, BringTwoRodsTogether, ShowEvolvingTempGraphWithArrows, # TodaysTargetWrapper, WriteHeatEquation, ReactionsToInitialHeatEquation, TalkThrough1DHeatGraph, ShowCubeFormation, CompareInputsOfGeneralCaseTo1D, ContrastXChangesToTChanges, ShowPartialDerivativeSymbols, WriteHeatEquation, ShowCurvatureToRateOfChangeIntuition, ContrastPDEToODE, TransitionToTempVsTime, Show1DAnd3DEquations, # AskAboutWhereEquationComesFrom, DiscreteSetup, ]
from _2019.diffyq.part4.staging import * from _2019.diffyq.part4.fourier_series_scenes import * from _2019.diffyq.part4.pi_creature_scenes import * from _2019.diffyq.part4.three_d_graphs import * from _2019.diffyq.part4.temperature_scenes import * from _2019.diffyq.part4.complex_functions import * from _2019.diffyq.part4.long_fourier_scenes import * from _2019.diffyq.part3.staging import * OUTPUT_DIRECTORY = "diffyq/part4" SCENES_IN_ORDER = [ ComplexFourierSeriesExample, FourierOfFourier, FourierOfFourierZoomedIn, FourierOfFourier100xZoom, FourierSeriesFormula, RelationToOtherVideos, WhyWouldYouCare, ShowLinearity, CombineSeveralSolutions, FourierGainsImmortality, SolveForWavesNothingElse, CycleThroughManyLinearCombinations, StepFunctionExample, WhichWavesAreAvailable, AlternateBoundaryConditions, AskQuestionOfGraph, CommentOnFouriersImmortality, HangOnThere, ShowInfiniteSum, TechnicalNuances, BreakDownStepFunction, StepFunctionSolutionFormla, # How to compute FourierSeriesOfLineIllustration, GeneralizeToComplexFunctions, ClarifyInputAndOutput, GraphForFlattenedPi, PiFourierSeries, RealValuedFunctionFourierSeries, YouSaidThisWasEasier, AskAboutComplexNotVector, SimpleComplexExponentExample, LooseWithLanguage, DemonstrateAddingArrows, TRangingFrom0To1, LabelRotatingVectors, IntegralTrick, SwapIntegralAndSum, FootnoteOnSwappingIntegralAndSum, FormulaOutOfContext, ShowRangeOfCnFormulas, DescribeSVG, # TODO IncreaseOrderOfApproximation, ShowStepFunctionIn2dView, StepFunctionIntegral, GeneralChallenge, # Oldies # FourierSeriesIllustraiton, # FourierNameIntro, # CircleAnimationOfF, ]
import numpy as np # Physical constants g = 9.8 L = 2 mu = 0.1 THETA_0 = np.pi / 3 # 60 degrees THETA_DOT_0 = 0 # No initial angular velocity # Definition of ODE def get_theta_double_dot(theta, theta_dot): return -mu * theta_dot - (g / L) * np.sin(theta) # Solution to the differential equation def theta(t): # Initialize changing values theta = THETA_0 theta_dot = THETA_DOT_0 delta_t = 0.01 # Some time step for time in np.arange(0, t, delta_t): # Take many little time steps of size delta_t # until the total time is the function's input theta_double_dot = get_theta_double_dot( theta, theta_dot ) theta += theta_dot * delta_t theta_dot += theta_double_dot * delta_t return theta
from _2019.diffyq.part4.long_fourier_scenes import * OUTPUT_DIRECTORY = "diffyq/part4" SCENES_IN_ORDER = [ ZoomedInFourierSeriesExample, FourierSeriesExampleWithRectForZoom, ZoomedInFourierSeriesExample100x, FourierOfFourier100xZoom, FourierOfFourierZoomedIn, FourierOfFourier, SigmaZoomedInFourierSeriesExample, SigmaFourierSeriesExampleWithRectForZoom, NailAndGearZoomedInFourierSeriesExample, NailAndGearFourierSeriesExampleWithRectForZoom, TrebleClefZoomedInFourierSeriesExample, TrebleClefFourierSeriesExampleWithRectForZoom, FourierOfSeattle, FourierOfSeattleZoomedIn, FourierOfBritain, FourierOfBritainZoomedIn, FourierOfHilbert, FourierOfHilbertZoomedIn, ]
from _2019.diffyq.part5.staging import * OUTPUT_DIRECTORY = "diffyq/part5" SCENES_IN_ORDER = [ ]
from _2019.diffyq.part3.staging import * from _2019.diffyq.part3.temperature_graphs import * from _2019.diffyq.part3.pi_creature_scenes import * from _2019.diffyq.part3.wordy_scenes import * from _2019.diffyq.part3.discrete_case import * OUTPUT_DIRECTORY = "diffyq/part3" SCENES_IN_ORDER = [ LastChapterWrapper, ThreeConstraints, OceanOfPossibilities, ThreeMainObservations, SimpleCosExpGraph, AddMultipleSolutions, FourierSeriesIllustraiton, BreakDownAFunction, SineCurveIsUnrealistic, AnalyzeSineCurve, EquationAboveSineAnalysis, ExponentialDecay, InvestmentGrowth, GrowingPileOfMoney, CarbonDecayCurve, CarbonDecayingInMammoth, SineWaveScaledByExp, ShowSinExpDerivatives, IfOnly, BoundaryConditionInterlude, BoundaryConditionReference, GiantCross, SimulateRealSineCurve, DerivativesOfLinearFunction, StraightLine3DGraph, SimulateLinearGraph, EmphasizeBoundaryPoints, ShowNewRuleAtDiscreteBoundary, DiscreteEvolutionPoint25, DiscreteEvolutionPoint1, FlatEdgesForDiscreteEvolution, FlatEdgesForDiscreteEvolutionTinySteps, FlatEdgesContinuousEvolution, FlatAtBoundaryWords, SlopeToHeatFlow, CloserLookAtStraightLine, WriteOutBoundaryCondition, SoWeGotNowhere, ManipulateSinExpSurface, HeatEquationFrame, ShowFreq1CosExpDecay, ShowFreq2CosExpDecay, ShowFreq4CosExpDecay, CompareFreqDecays1to2, CompareFreqDecays1to4, CompareFreqDecays2to4, ShowHarmonics, ShowHarmonicSurfaces, # SimpleCosExpGraph, # AddMultipleSolutions, # IveHeardOfThis, # FourierSeriesOfLineIllustration, # InFouriersShoes, ] PART_4_SCENES = [ FourierSeriesIllustraiton, FourierNameIntro, CircleAnimationOfF, ]
from manim_imports_ext import * from _2019.diffyq.part3.staging import FourierSeriesIllustraiton from _2019.diffyq.part2.wordy_scenes import WriteHeatEquationTemplate class FourierName(Scene): def construct(self): name = OldTexText("Joseph Fourier") name.scale(1.5) self.add(name) class FourierSeriesFormula(Scene): def construct(self): formula = OldTex( "c_{n} = \\int_0^1 e^{-2\\pi i {n} {t}}f({t}){dt}", tex_to_color_map={ "{n}": YELLOW, "{t}": PINK, } ) self.play(Write(formula)) self.wait() class Zoom100Label(Scene): def construct(self): text = OldTexText("100x Zoom") text.scale(2) self.play(GrowFromCenter(text)) self.wait() class RelationToOtherVideos(Scene): CONFIG = { "camera_config": { "background_color": GREY_D, }, } def construct(self): # Show three videos videos = self.get_video_thumbnails() brace = Brace(videos, UP) text = OldTexText("Heat equation") text.scale(2) text.next_to(brace, UP) self.play( LaggedStartMap( FadeInFrom, videos, lambda m: (m, LEFT), lag_ratio=0.4, run_time=2, ), GrowFromCenter(brace), FadeInFromDown(text), ) self.wait() group = Group(text, brace, videos) # Show Fourier thinking fourier = ImageMobject("Joseph Fourier") fourier.set_height(4) fourier.to_edge(RIGHT) group.generate_target() group.target.to_edge(DOWN) fourier.align_to(group.target[0], DOWN) bubble = ThoughtBubble( direction=RIGHT, width=3, height=2, fill_opacity=0.5, stroke_color=WHITE, ) bubble[-1].shift(0.25 * DOWN + 0.5 * LEFT) bubble[:-1].rotate(20 * DEGREES) for mob in bubble[:-1]: mob.rotate(-20 * DEGREES) bubble.move_to( fourier.get_center(), RIGHT ) bubble.shift(LEFT) bubble.to_edge(UP, buff=SMALL_BUFF) self.play( MoveToTarget(group), FadeIn(fourier, LEFT) ) self.play(Write(bubble, run_time=1)) self.wait() # Discount first two first_two = videos[:2] first_two.generate_target() first_two.target.scale(0.5) first_two.target.to_corner(DL) new_brace = Brace(first_two.target, UP) self.play( # fourier.scale, 0.8, fourier.match_x, new_brace, fourier.to_edge, UP, MoveToTarget(first_two), Transform(brace, new_brace), text.scale, 0.7, text.next_to, new_brace, UP, FadeOut(bubble, LEFT), ) self.play( videos[2].scale, 1.7, videos[2].to_corner, UR, ) self.wait() # def get_video_thumbnails(self): thumbnails = Group( ImageMobject("diffyq_part2_thumbnail"), ImageMobject("diffyq_part3_thumbnail"), ImageMobject("diffyq_part4_thumbnail"), ) for thumbnail in thumbnails: thumbnail.set_height(4) thumbnail.add(SurroundingRectangle( thumbnail, color=WHITE, stroke_width=2, buff=0 )) thumbnails.arrange(RIGHT, buff=LARGE_BUFF) thumbnails.set_width(FRAME_WIDTH - 1) return thumbnails class FourierGainsImmortality(Scene): CONFIG = { "mathematicians": [ "Pythagoras", "Euclid", "Archimedes", "Fermat", "Newton", "Leibniz", "Johann_Bernoulli2", "Euler", "Joseph Fourier", "Gauss", "Riemann", "Cantor", "Noether", "Ramanujan", "Godel", "Turing", ] } def construct(self): fourier = ImageMobject("Joseph Fourier") fourier.set_height(5) fourier.to_edge(LEFT) name = OldTexText("Joseph Fourier") name.next_to(fourier, DOWN) immortals = self.get_immortals() immortals.remove(immortals.fourier) immortals.to_edge(RIGHT) self.add(fourier, name) self.play(LaggedStartMap( FadeIn, immortals, lag_ratio=0.1, run_time=2, )) self.play( TransformFromCopy(fourier, immortals.fourier) ) self.wait() def get_immortals(self): images = Group(*[ ImageMobject(name) for name in self.mathematicians ]) for image in images: image.set_height(1) images.arrange_in_grid(n_rows=4) last_row = images[-4:] low_center = last_row.get_center() last_row.arrange(RIGHT, buff=0.4, center=False) last_row.move_to(low_center) frame = SurroundingRectangle(images) frame.set_color(WHITE) title = OldTexText("Immortals of Math") title.match_width(frame) title.next_to(frame, UP) result = Group(title, frame, *images) result.set_height(FRAME_HEIGHT - 1) result.to_edge(RIGHT) for image, name in zip(images, self.mathematicians): setattr( result, name.split(" ")[-1].lower(), image, ) return result class WhichWavesAreAvailable(Scene): CONFIG = { "axes_config": { "x_min": 0, "x_max": TAU, "y_min": -1.5, "y_max": 1.5, "x_axis_config": { "tick_frequency": PI / 2, "unit_size": 1, "include_tip": False, }, "y_axis_config": { "unit_size": 1, "tick_frequency": 0.5, "include_tip": False, }, }, "n_axes": 5, "trig_func": np.cos, "trig_func_tex": "\\cos", "bc_words": "Restricted by\\\\boundary conditions", } def construct(self): self.setup_little_axes() self.show_cosine_waves() def setup_little_axes(self): axes_group = VGroup(*[ Axes(**self.axes_config) for n in range(self.n_axes) ]) axes_group.set_stroke(width=2) axes_group.arrange(DOWN, buff=1) axes_group.set_height(FRAME_HEIGHT - 1.25) axes_group.to_edge(RIGHT) axes_group.to_edge(UP, buff=MED_SMALL_BUFF) dots = OldTexText("\\vdots") dots.next_to(axes_group, DOWN) dots.shift_onto_screen() self.add(axes_group) self.add(dots) self.axes_group = axes_group def show_cosine_waves(self): axes_group = self.axes_group colors = [BLUE, GREEN, RED, YELLOW, PINK] graphs = VGroup() h_lines = VGroup() func_labels = VGroup() for k, axes, color in zip(it.count(1), axes_group, colors): L = axes.x_max graph = axes.get_graph( lambda x: self.trig_func(x * k * PI / L), color=color ) graph.set_stroke(width=2) graphs.add(graph) func_label = OldTex( self.trig_func_tex + "\\left(", str(k), "(\\pi / L)x\\right)", tex_to_color_map={ str(k): color, } ) func_label.scale(0.7) func_label.next_to(axes, LEFT) func_labels.add(func_label) hl1 = DashedLine(LEFT, RIGHT) hl1.set_width(0.5) hl1.set_stroke(WHITE, 2) hl1.move_to(graph.get_start()) hl2 = hl1.copy() hl2.move_to(graph.get_end()) h_lines.add(hl1, hl2) words = OldTexText(self.bc_words) words.next_to(axes_group, LEFT) words.to_edge(UP) self.play( FadeIn(words), LaggedStartMap( ShowCreation, graphs, ) ) self.play(Write(h_lines)) self.play(FadeOut(h_lines)) self.wait() self.play( words.next_to, func_labels, LEFT, words.to_edge, UP, LaggedStartMap( FadeInFrom, func_labels, lambda m: (m, RIGHT) ) ) self.wait() class AlternateBoundaryConditions(WhichWavesAreAvailable): CONFIG = { "trig_func": np.sin, "trig_func_tex": "\\sin", "bc_words": "Alternate\\\\boundary condition" } class AskQuestionOfGraph(PiCreatureScene): def construct(self): randy = self.pi_creature self.pi_creature_says( randy, "What sine waves\\\\are you made of?", target_mode="sassy", ) self.wait(2) self.play( randy.change, "pondering", randy.bubble.get_right() ) self.wait(2) class CommentOnFouriersImmortality(FourierGainsImmortality): def construct(self): immortals = self.get_immortals() immortals.to_edge(LEFT) fourier = immortals.fourier name = OldTexText("Joseph", "Fourier") name.scale(1.5) name.move_to(FRAME_WIDTH * RIGHT / 4) name.to_edge(DOWN) fourier_things = VGroup( OldTexText("Fourier transform"), OldTexText("Fourier series"), OldTexText("Complex Fourier series"), OldTexText("Discrete Fourier transform"), OldTexText("Fractional Fourier transform"), OldTexText("Fast Fourier transform"), OldTexText("Quantum Fourier transform"), OldTexText("Fourier transform spectroscopy"), OldTex("\\vdots"), ) fourier_things.arrange( DOWN, aligned_edge=LEFT, buff=MED_LARGE_BUFF ) fourier_things.to_corner(UL) fourier_things[-1].shift(RIGHT + 0.25 * UP) self.add(immortals) immortals.remove(immortals.fourier) self.play( fourier.set_height, 6, fourier.next_to, name, UP, FadeInFromDown(name), ) self.play(FadeOut(immortals)) self.wait(2) self.play( LaggedStartMap( FadeInFrom, fourier_things, lambda m: (m, UP), run_time=5, lag_ratio=0.3, ) ) self.wait() class ShowInfiniteSum(FourierSeriesIllustraiton): CONFIG = { "n_range": range(1, 101, 2), "colors": [BLUE, GREEN, RED, YELLOW, PINK], "axes_config": { "y_max": 1.5, "y_min": -1.5, "y_axis_config": { "tick_frequency": 0.5, "unit_size": 1.0, "stroke_width": 2, }, "x_axis_config": { "tick_frequency": 0.1, "stroke_width": 2, }, }, } def construct(self): self.add_equation() self.add_graphs() self.show_to_infinity() self.walk_through_constants() self.ask_about_infinite_sum() self.show_inf_sum_of_numbers() self.show_many_inputs_in_parallel() self.follow_single_inputs() def add_equation(self): inf_sum = self.get_infinite_sum() step_func_def = self.get_step_func_definition() step_func_def.next_to(inf_sum, RIGHT) equation = VGroup(inf_sum, step_func_def) equation.set_width(FRAME_WIDTH - 1) equation.center().to_edge(UP) self.add(equation) self.equation = equation self.inf_sum = inf_sum self.inf_sum = inf_sum self.step_func_def = step_func_def def add_graphs(self): aaa_group = self.get_axes_arrow_axes() aaa_group.next_to(self.equation, DOWN, buff=1.5) axes1, arrow, axes2 = aaa_group tfg = self.get_target_func_graph(axes2) tfg.set_color(WHITE) axes2.add(tfg) sine_graphs = self.get_sine_graphs(axes1) partial_sums = self.get_partial_sums(axes1, sine_graphs) partial_sums.set_stroke(width=0.5) partial_sums[-1].set_stroke(width=2) colors = self.colors partial_sums[len(colors):].set_color_by_gradient(*colors) self.add(aaa_group) self.add(partial_sums) self.partial_sums = partial_sums self.sine_graphs = sine_graphs self.aaa_group = aaa_group def show_to_infinity(self): dots = self.inf_sum.dots arrow = Vector(1.5 * RIGHT) arrow.next_to( dots, DOWN, MED_LARGE_BUFF, aligned_edge=RIGHT ) words = OldTexText("Sum to $\\infty$") words.next_to(arrow, DOWN) self.play( FadeIn(words, LEFT), GrowArrow(arrow) ) self.wait() self.inf_words = VGroup(arrow, words) def walk_through_constants(self): inf_sum = self.inf_sum terms = self.inf_sum.terms sine_graphs = self.sine_graphs partial_sums = self.partial_sums rects = VGroup(*[ SurroundingRectangle( term, color=term[-1].get_color(), stroke_width=2 ) for term in terms ]) dots_rect = SurroundingRectangle(inf_sum.dots) dots_rect.set_stroke(width=2) curr_rect = rects[0].copy() curr_partial_sum = partial_sums[0] curr_partial_sum.set_stroke(width=3) self.play( FadeOut(partial_sums[1:]), FadeIn(curr_rect), FadeIn(curr_partial_sum), ) for sg, ps, rect in zip(sine_graphs[1:], partial_sums[1:], rects[1:]): self.play( FadeOut(curr_rect), FadeIn(rect), FadeIn(sg), ) curr_rect.become(rect) self.remove(rect) self.add(curr_rect) ps.set_stroke(width=3) self.play( curr_partial_sum.set_stroke, {"width": 0.5}, ReplacementTransform(sg, ps), ) curr_partial_sum = ps self.play( Transform(curr_rect, dots_rect), curr_partial_sum.set_stroke, {"width": 0.5}, LaggedStart( *[ UpdateFromAlphaFunc( ps, lambda m, a: m.set_stroke( width=(3 * there_and_back(a) + 0.5 * a) ), ) for ps in partial_sums[4:] ], run_time=3, lag_ratio=0.2, ), ) self.play(partial_sums[-1].set_stroke, {"width": 2}) self.play( FadeOut(curr_rect), ShowCreationThenFadeAround(inf_sum.four_over_pi), ) self.wait() def ask_about_infinite_sum(self): inf_words = self.inf_words randy = Randolph(mode="confused") randy.set_height(1.5) outline = inf_words[1].copy() outline.set_stroke(YELLOW, 1) outline.set_fill(opacity=0) question = OldTexText( "What$\\dots$\\\\ does this mean?" ) question.scale(0.7) question.next_to(inf_words, LEFT) randy.next_to(question, DOWN, aligned_edge=RIGHT) self.play(FadeIn(question)) self.play(FadeIn(randy)) self.play( Blink(randy), ShowCreationThenFadeOut(outline) ) self.wait() self.play(FadeOut(randy), FadeOut(question)) def show_inf_sum_of_numbers(self): inf_sum = self.inf_sum graph_group = VGroup( self.aaa_group, self.partial_sums ) number_line = NumberLine( x_min=0, x_max=1, tick_frequency=0.1, numbers_with_elongated_ticks=[0, 0.5, 1], unit_size=8, # line_to_number_buff=0.4, ) number_line.set_stroke(GREY_B, 2) number_line.move_to(2 * DOWN) number_line.add_numbers( *np.arange(0, 1.5, 0.5), num_decimal_places=1 ) num_inf_sum = OldTex( "{1 \\over 1}", "-{1 \\over 3}", "+{1 \\over 5}", "-{1 \\over 7}", "+{1 \\over 9}", "-{1 \\over 11}", "+\\cdots", "= {\\pi \\over 4}" ) num_inf_sum.move_to(UP) self.play( FadeOut(graph_group, DOWN), FadeIn(number_line, UP), FadeOut(self.inf_words), *[ TransformFromCopy(t1[-1:], t2) for t1, t2 in zip( inf_sum.terms, num_inf_sum, ) ], TransformFromCopy( inf_sum.dots, num_inf_sum[-2], ), TransformFromCopy( inf_sum.dots, num_inf_sum[-4:-2] ), self.equation.set_opacity, 0.5, ) self.play(Write(num_inf_sum[-1])) # Show sums terms = [ u / n for u, n in zip( it.cycle([1, -1]), range(1, 1001, 2) ) ] partial_sums = np.cumsum(terms) tip = ArrowTip(start_angle=-TAU / 4) value_tracker = ValueTracker(1) get_value = value_tracker.get_value tip.add_updater( lambda t: t.move_to( number_line.n2p(get_value()), DOWN, ) ) n_braces = 7 braces = VGroup(*[ Brace(num_inf_sum[:n], DOWN) for n in range(1, n_braces + 1) ]) brace = braces[0].copy() decimal = DecimalNumber( 0, num_decimal_places=6, ) decimal.add_updater(lambda d: d.set_value(get_value())) decimal.add_updater(lambda d: d.next_to(tip, UP, SMALL_BUFF)) term_count = VGroup( Integer(1), OldTexText("terms") ) term_count_tracker = ValueTracker(1) term_count[0].set_color(YELLOW) term_count.add_updater( lambda m: m[0].set_value(term_count_tracker.get_value()) ) term_count.add_updater(lambda m: m.arrange( RIGHT, aligned_edge=DOWN )) term_count.add_updater(lambda m: m.next_to(brace, DOWN)) pi_fourths_tip = ArrowTip(start_angle=90 * DEGREES) pi_fourths_tip.set_color(WHITE) pi_fourths_tip.move_to( number_line.n2p(PI / 4), UP, ) pi_fourths_label = OldTex( "{\\pi \\over 4} =" ) pi_fourths_value = DecimalNumber( PI / 4, num_decimal_places=4 ) pi_fourths_value.scale(0.8) pi_fourths_value.next_to(pi_fourths_label, RIGHT, buff=0.2) pi_fourths_label.add(pi_fourths_value) # pi_fourths_label.scale(0.7) pi_fourths_label.next_to( pi_fourths_tip, DOWN, MED_SMALL_BUFF, aligned_edge=LEFT, ) self.play( LaggedStartMap( FadeIn, VGroup( brace, tip, decimal, term_count, ) ), FadeIn(pi_fourths_tip), FadeIn(pi_fourths_label), ) for ps, new_brace in zip(partial_sums[1:], braces[1:]): term_count_tracker.increment_value(1) self.play( Transform(brace, new_brace), value_tracker.set_value, ps, ) self.leave_mark(number_line, ps) self.wait() count = 0 num_moving_values = n_braces + 8 for ps in partial_sums[n_braces:num_moving_values]: value_tracker.set_value(ps) self.leave_mark(number_line, ps) count += 1 term_count_tracker.increment_value(1) self.wait(0.5) decimal.remove_updater(decimal.updaters[-1]) decimal.match_x(pi_fourths_tip) new_marks = VGroup(*[ self.leave_mark(number_line, ps) for ps in partial_sums[num_moving_values:] ]) number_line.remove(*new_marks) term_count_tracker.increment_value(1) self.play( UpdateFromAlphaFunc( value_tracker, lambda m, a: m.set_value( partial_sums[integer_interpolate( num_moving_values, len(partial_sums) - 1, a, )[0]] ), ), ShowIncreasingSubsets(new_marks), term_count_tracker.set_value, len(partial_sums), run_time=10, rate_func=smooth, ) self.play(LaggedStartMap( FadeOut, VGroup( num_inf_sum, brace, decimal, term_count, tip, number_line, new_marks, pi_fourths_tip, pi_fourths_label, ), lag_ratio=0.3, )) self.play( FadeInFromDown(graph_group), self.equation.set_opacity, 1, ) def show_many_inputs_in_parallel(self): aaa_group = self.aaa_group axes1, arrow, axes2 = aaa_group partial_sums = self.partial_sums inputs = np.linspace(0, 1, 21) n_iterations = 100 values = np.array([ [ (4 / PI) * (u / n) * np.cos(n * PI * x) for x in inputs ] for u, n in zip( it.cycle([1, -1]), range(1, 2 * n_iterations + 1, 2), ) ]) p_sums = np.apply_along_axis(np.cumsum, 0, values) dots = VGroup(*[Dot() for x in inputs]) dots.scale(0.5) dots.set_color_by_gradient(BLUE, YELLOW) n_tracker = ValueTracker(0) def update_dots(dots): n = int(n_tracker.get_value()) outputs = p_sums[n] for dot, x, y in zip(dots, inputs, outputs): dot.move_to(axes1.c2p(x, y)) dots.add_updater(update_dots) lines = VGroup(*[ self.get_dot_line(dot, axes1.x_axis) for dot in dots ]) self.remove(*self.inf_words) self.play( FadeOut(partial_sums), FadeIn(dots), FadeIn(lines), ) self.play( n_tracker.set_value, len(p_sums) - 1, run_time=5, ) dots.clear_updaters() index = 4 self.input_dot = dots[index] self.input_line = lines[index] self.partial_sum_values = p_sums[:, index] self.cosine_values = values[:, index] dots.remove(self.input_dot) lines.remove(self.input_line) self.add(self.input_line) self.add(self.input_dot) self.play( FadeOut(dots), FadeOut(lines), ) def follow_single_inputs(self): aaa_group = self.aaa_group inf_sum = self.inf_sum axes1, arrow, axes2 = aaa_group x_axis = axes1.x_axis dot = self.input_dot partial_sums = self.partial_sums partial_sums.set_stroke(width=2) input_tracker = ValueTracker( x_axis.p2n(dot.get_center()) ) get_input = input_tracker.get_value input_label = OldTex("x =", "0.2") input_decimal = DecimalNumber(get_input()) input_decimal.replace(input_label[1]) input_decimal.set_color(BLUE) input_label.remove(input_label[1]) input_label.add(input_decimal) input_label.next_to(dot, UR, SMALL_BUFF) def get_brace_value_label(brace, u, n): result = DecimalNumber() result.scale(0.7) result.next_to(brace, DOWN, SMALL_BUFF) result.add_updater(lambda d: d.set_value( (u / n) * np.cos(PI * n * get_input()) )) return result braces = VGroup(*[ Brace(term, DOWN) for term in inf_sum.terms ]) brace_value_labels = VGroup(*[ get_brace_value_label(brace, u, n) for brace, u, n in zip( braces, it.cycle([1, -1]), it.count(1, 2), ) ]) bv_rects = VGroup(*[ SurroundingRectangle( brace_value_labels[:n], color=BLUE, stroke_width=1, ) for n in range(1, len(braces) + 1) ]) bv_rect = bv_rects[0].copy() partial_sum = partial_sums[0].copy() dot.add_updater( lambda d: d.move_to(partial_sum.point_from_proportion( inverse_interpolate( x_axis.x_min, x_axis.x_max, get_input(), ) )) ) n_waves_label = OldTexText( "Sum of", "10", "waves" ) n_waves_label.next_to(axes1.c2p(0.5, 1), UR) n_tracker = ValueTracker(1) n_dec = Integer(1) n_dec.set_color(YELLOW) n_dec.move_to(n_waves_label[1]) n_waves_label[1].set_opacity(0) n_waves_label.add(n_dec) n_dec.add_updater(lambda n: n.set_value( n_tracker.get_value() )) n_dec.add_updater(lambda m: m.move_to( n_waves_label[1] )) self.play( FadeIn(input_label, LEFT), dot.scale, 1.5, ) self.wait() self.play( LaggedStartMap(GrowFromCenter, braces), LaggedStartMap(GrowFromCenter, brace_value_labels), *[ TransformFromCopy( input_label[0][0], term[n][1], ) for i, term in enumerate(inf_sum.terms) for n in [2 if i == 0 else 4] ] ) self.wait() self.add(partial_sum, dot) dot.set_stroke(BLACK, 1, background=True) self.play( FadeOut(input_label), FadeIn(n_waves_label), FadeIn(bv_rect), FadeIn(partial_sum), ) self.wait() ps_iter = iter(partial_sums[1:]) def get_ps_anim(): return AnimationGroup( Transform(partial_sum, next(ps_iter)), ApplyMethod(n_tracker.increment_value, 1), ) for i in range(1, 4): self.play( Transform(bv_rect, bv_rects[i]), get_ps_anim(), ) self.wait() self.play( FadeOut(bv_rect), get_ps_anim() ) for x in range(3): self.play(get_ps_anim()) self.play( input_tracker.set_value, 0.7, ) for x in range(6): self.play(get_ps_anim()) self.play(input_tracker.set_value, 0.5) for x in range(40): self.play( get_ps_anim(), run_time=0.5, ) # def get_dot_line(self, dot, axis, line_class=Line): def get_line(): p = dot.get_center() lp = axis.n2p(axis.p2n(p)) return line_class(lp, p, stroke_width=1) return always_redraw(get_line) def leave_mark(self, number_line, value): tick = number_line.get_tick(value) tick.set_color(BLUE) number_line.add(tick) return tick def get_infinite_sum(self): colors = self.colors inf_sum = OldTex( "{4 \\over \\pi}", "\\left(", "{\\cos\\left({1}\\pi x\\right) \\over {1}}", "-", "{\\cos\\left({3}\\pi x\\right) \\over {3}}", "+", "{\\cos\\left({5}\\pi x\\right) \\over {5}}", "-", "{\\cos\\left({7}\\pi x\\right) \\over {7}}", "+", "\\cdots", "\\right)", tex_to_color_map={ "{1}": colors[0], "{-1 \\over 3}": colors[1], "{3}": colors[1], "{1 \\over 5}": colors[2], "{5}": colors[2], "{-1 \\over 7}": colors[3], "{7}": colors[3], "{1 \\over 9}": colors[4], "{9}": colors[4], } ) inf_sum.get_parts_by_tex("-")[0].set_color(colors[1]) inf_sum.get_parts_by_tex("-")[1].set_color(colors[3]) inf_sum.get_parts_by_tex("+")[0].set_color(colors[2]) inf_sum.terms = VGroup( inf_sum[2:6], inf_sum[6:12], inf_sum[12:18], inf_sum[18:24], ) inf_sum.dots = inf_sum.get_part_by_tex("\\cdots") inf_sum.four_over_pi = inf_sum.get_part_by_tex( "{4 \\over \\pi}" ) return inf_sum def get_step_func_definition(self): values = VGroup(*map(Integer, [1, 0, -1])) conditions = VGroup(*map(TexText, [ "if $x < 0.5$", "if $x = 0.5$", "if $x > 0.5$", ])) values.arrange(DOWN, buff=MED_LARGE_BUFF) for condition, value in zip(conditions, values): condition.move_to(value) condition.align_to(conditions[0], LEFT) conditions.next_to(values, RIGHT, LARGE_BUFF) brace = Brace(values, LEFT) eq = OldTex("=") eq.scale(1.5) eq.next_to(brace, LEFT) return VGroup(eq, brace, values, conditions) class StepFunctionSolutionFormla(WriteHeatEquationTemplate): CONFIG = { "tex_mobject_config": { "tex_to_color_map": { "{1}": WHITE, # BLUE, "{3}": WHITE, # GREEN, "{5}": WHITE, # RED, "{7}": WHITE, # YELLOW, }, }, } def construct(self): formula = OldTex( "T({x}, {t}) = ", "{4 \\over \\pi}", "\\left(", "{\\cos\\left({1}\\pi {x}\\right) \\over {1}}", "e^{-\\alpha {1}^2 {t} }", "-" "{\\cos\\left({3}\\pi {x}\\right) \\over {3}}", "e^{-\\alpha {3}^2 {t} }", "+", "{\\cos\\left({5}\\pi {x}\\right) \\over {5}}", "e^{-\\alpha {5}^2 {t} }", "- \\cdots", "\\right)", **self.tex_mobject_config, ) formula.set_width(FRAME_WIDTH - 1) formula.to_edge(UP) self.play(FadeInFromDown(formula)) self.wait() class TechnicalNuances(Scene): def construct(self): title = OldTexText("Technical nuances not discussed") title.scale(1.5) title.set_color(YELLOW) line = DashedLine(title.get_left(), title.get_right()) line.next_to(title, DOWN, SMALL_BUFF) line.set_stroke(GREY_B, 3) questions = VGroup(*map(TexText, [ "Does the value at $0.5$ matter?", "What does it mean to solve a PDE with\\\\" "a discontinuous initial condition?", "Is the limit of a sequence of solutions\\\\" "also a solution?", "Do all functions have a Fourier series?", ])) self.play( Write(title), ShowCreation(line), ) title.add(line) self.play( title.to_edge, UP, ) last_question = VMobject() for question in questions: question.next_to(line, DOWN, MED_LARGE_BUFF) self.play( FadeInFromDown(question), FadeOut(last_question, UP) ) self.wait(2) last_question = question class ArrowAndCircle(Scene): def construct(self): circle = Circle(color=RED) circle.set_stroke(width=4) circle.set_height(0.25) arrow = Vector(DL) arrow.set_color(RED) arrow.next_to(circle, UR) self.play(ShowCreation(arrow)) self.play(ShowCreation(circle)) self.play(FadeOut(circle)) self.wait() class SineWaveResidue(Scene): def construct(self): f = 2 wave = FunctionGraph( lambda x: np.cos(-0.1 * f * TAU * x), x_min=0, x_max=20, color=YELLOW, ) wave.next_to(LEFT_SIDE, LEFT, buff=0) time = 10 self.play( wave.shift, time * RIGHT, run_time=f * time, rate_func=linear, ) class AskAboutComplexNotVector(Scene): def construct(self): c_ex = DecimalNumber( complex(2, 1), num_decimal_places=0 ) i_part = c_ex[-1] v_ex = IntegerMatrix( [[2], [1]], bracket_h_buff=SMALL_BUFF, bracket_v_buff=SMALL_BUFF, ) group = VGroup(v_ex, c_ex) group.scale(1.5) # group.arrange(RIGHT, buff=4) group.arrange(DOWN, buff=0.9) group.to_corner(UL, buff=0.2) q1, q2 = questions = VGroup( OldTexText("Why not this?").set_color(BLUE), OldTexText("Instead of this?").set_color(YELLOW), ) questions.scale(1.5) for q, ex in zip(questions, group): ex.add_background_rectangle() q.add_background_rectangle() q.next_to(ex, RIGHT) plane = NumberPlane(axis_config={"unit_size": 2}) vect = Vector([4, 2, 0]) self.play( ShowCreation(plane, lag_ratio=0.1), FadeIn(vect), ) for q, ex in zip(questions, group): self.play( FadeIn(q, LEFT), FadeIn(ex) ) self.wait() self.play(ShowCreationThenFadeAround(i_part)) self.wait() class SwapIntegralAndSum(Scene): def construct(self): self.perform_swap() self.show_average_of_individual_terms() self.ask_about_c2() self.multiply_f_by_exp_neg_2() self.show_modified_averages() self.add_general_expression() def perform_swap(self): light_pink = self.light_pink = interpolate_color( PINK, WHITE, 0.25 ) tex_config = self.tex_config = { "tex_to_color_map": { "=": WHITE, "\\int_0^1": WHITE, "+": WHITE, "\\cdots": WHITE, "{t}": PINK, "{dt}": light_pink, "{-2}": YELLOW, "{\\cdot 1}": YELLOW, "{0}": YELLOW, "{1}": YELLOW, "{2}": YELLOW, "{n}": YELLOW, }, } int_ft = OldTex( "\\int_0^1 f({t}) {dt}", **tex_config ) int_sum = OldTex( """ = \\int_0^1 \\left( \\cdots + c_{\\cdot 1}e^{{\\cdot 1} \\cdot 2\\pi i {t}} + c_{0}e^{{0} \\cdot 2\\pi i {t}} + c_{1}e^{{1} \\cdot 2\\pi i {t}} + c_{2}e^{{2} \\cdot 2\\pi i {t}} + \\cdots \\right){dt} """, **tex_config ) sum_int = OldTex( """ = \\cdots + \\int_0^1 c_{\\cdot 1}e^{{\\cdot 1} \\cdot 2\\pi i {t}} {dt} + \\int_0^1 c_{0}e^{{0} \\cdot 2\\pi i {t}} {dt} + \\int_0^1 c_{1}e^{{1} \\cdot 2\\pi i {t}} {dt} + \\int_0^1 c_{2}e^{{2} \\cdot 2\\pi i {t}} {dt} + \\cdots """, **tex_config ) self.fix_minuses(int_sum) self.fix_minuses(sum_int) group = VGroup(int_ft, int_sum, sum_int) group.arrange( DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT ) group.set_width(FRAME_WIDTH - 1) group.to_corner(UL) int_ft.align_to(int_sum[1], LEFT) int_ft.shift(0.2 * RIGHT) int_sum.exp_terms = self.get_exp_terms(int_sum) sum_int.exp_terms = self.get_exp_terms(sum_int) sum_int.int_terms = self.get_integral_terms(sum_int) breakdown_label = OldTexText( "Break this down" ) arrow = Vector(LEFT) arrow.next_to(int_ft, RIGHT) breakdown_label.next_to(arrow, RIGHT) aos_label = OldTexText( "Average of a sum", tex_to_color_map={ "Average": light_pink, "sum": YELLOW, } ) soa_label = OldTexText( "Sum over averages", tex_to_color_map={ "averages": light_pink, "Sum": YELLOW, } ) aos_label.next_to(ORIGIN, RIGHT, buff=2) aos_label.to_edge(UP) soa_label.move_to(2.5 * DOWN) aos_arrow = Arrow( aos_label.get_corner(DL), int_sum.get_corner(TOP) + 2 * RIGHT, buff=0.3, ) soa_arrow = Arrow( soa_label.get_top(), sum_int.get_bottom(), buff=0.3, ) self.add(int_ft) self.play( FadeIn(breakdown_label, LEFT), GrowArrow(arrow), ) self.wait() self.play( FadeOut(breakdown_label), FadeOut(arrow), FadeIn(int_sum.get_parts_by_tex("=")), FadeIn(int_sum.get_parts_by_tex("+")), FadeIn(int_sum.get_parts_by_tex("\\cdots")), FadeIn(int_sum.get_parts_by_tex("(")), FadeIn(int_sum.get_parts_by_tex(")")), *[ TransformFromCopy( int_ft.get_part_by_tex(tex), int_sum.get_part_by_tex(tex), ) for tex in ["\\int_0^1", "{dt}"] ] ) self.play(LaggedStart(*[ GrowFromPoint( term, int_ft.get_part_by_tex("{t}").get_center(), ) for term in int_sum.exp_terms ])) self.wait() self.play( FadeIn(aos_label), GrowArrow(aos_arrow) ) self.play( *[ TransformFromCopy( int_sum.get_parts_by_tex(tex), sum_int.get_parts_by_tex(tex), run_time=2, ) for tex in ["\\cdots", "+"] ], TransformFromCopy( int_sum.exp_terms, sum_int.exp_terms, run_time=2, ), FadeIn(soa_label), GrowArrow(soa_arrow), ) self.play( *[ TransformFromCopy( int_sum.get_part_by_tex("\\int_0^1"), part, run_time=2, ) for part in sum_int.get_parts_by_tex( "\\int_0^1" ) ], FadeIn(sum_int.get_parts_by_tex("{dt}")) ) self.wait() self.play( FadeOut(soa_arrow), soa_label.to_edge, DOWN, ) self.int_sum = int_sum self.sum_int = sum_int self.int_ft = int_ft self.aos_label = aos_label self.aos_arrow = aos_arrow self.soa_label = soa_label self.soa_arrow = soa_arrow def show_average_of_individual_terms(self): sum_int = self.sum_int int_ft = self.int_ft braces = VGroup(*[ Brace(term, DOWN, buff=SMALL_BUFF) for term in sum_int.int_terms ]) self.play(LaggedStartMap( GrowFromCenter, braces )) self.show_individual_average(braces[0], -1) self.show_individual_average(braces[2], 1) self.show_individual_average(braces[3], 2) self.show_individual_average(braces[1], 0) eq = OldTex("=") eq.next_to(int_ft, RIGHT) c0 = self.c0.copy() c0.generate_target() c0.target.next_to(eq, RIGHT) c0.target.shift(0.05 * DOWN) self.play( FadeIn(eq), MoveToTarget(c0, run_time=2) ) self.wait() self.braces = braces self.eq_c0 = VGroup(eq, c0) def ask_about_c2(self): int_sum = self.int_sum sum_int = self.sum_int c2 = int_sum.exp_terms[-1][:2] c2_rect = SurroundingRectangle(c2, buff=0.05) c2_rect.set_stroke(WHITE, 2) c2_rect.stretch(1.5, 1, about_edge=DOWN) q_marks = OldTex("???") q_marks.next_to(c2_rect, UP) last_diagram = self.all_average_diagrams[-2] last_int = sum_int.int_terms[-1] big_rect = SurroundingRectangle( VGroup(last_int, last_diagram) ) big_rect.set_stroke(WHITE, 2) self.play( ShowCreation(c2_rect), FadeOut(self.aos_arrow), FadeInFromDown(q_marks), ) self.play(ShowCreation(big_rect)) self.wait(2) self.to_fade = VGroup(c2_rect, q_marks, big_rect) def multiply_f_by_exp_neg_2(self): int_ft = self.int_ft int_sum = self.int_sum sum_int = self.sum_int eq_c0 = self.eq_c0 diagrams = self.all_average_diagrams diagrams.sort(lambda p: p[0]) dt_part = int_ft.get_part_by_tex("{dt}") pre_dt_part = int_ft[:-1] new_exp = OldTex( "e^{{-2} \\cdot 2\\pi i {t}}", **self.tex_config, ) new_exp.next_to(pre_dt_part, RIGHT, SMALL_BUFF) new_exp.shift(0.05 * UP) something = OldTexText("(something)") something.replace(new_exp, dim_to_match=0) something.align_to(new_exp, DOWN) self.play( FadeOut(eq_c0), Write(something, run_time=1), dt_part.next_to, new_exp, RIGHT, SMALL_BUFF, dt_part.align_to, dt_part, DOWN, ) self.wait() self.play(*[ Rotating( diagram[2], radians=n * TAU, about_point=diagram[0].n2p(0), run_time=3, rate_func=lambda t: smooth(t, 1) ) for n, diagram in zip(it.count(-3), diagrams) ]) self.wait() self.play( FadeOut(something, UP), FadeIn(new_exp, DOWN), ) self.play(FadeOut(self.to_fade)) # Go through each term moving_exp = new_exp.copy() rect = SurroundingRectangle(moving_exp) rect.set_stroke(GREY_B, width=1) times = OldTex("\\times") times.next_to(rect, LEFT, SMALL_BUFF) moving_exp.add(VGroup(rect, times)) moving_exp[-1].set_opacity(0) moving_exp.save_state() moving_exp.generate_target() quads = zip( it.count(-3), int_sum.exp_terms, sum_int.exp_terms, diagrams, ) for n, c_exp1, c_exp2, diagram in quads: exp1 = c_exp1[2:] exp2 = c_exp2[2:] moving_exp.target[-1][0].set_stroke(opacity=1) moving_exp.target[-1][1].set_fill(opacity=1) moving_exp.target.next_to(exp1, UP, SMALL_BUFF) if n < 0: n_str = "{\\cdot" + str(abs(n)) + "}" else: n_str = "{" + str(n) + "}" replacement1 = OldTex( "e^{", n_str, "\\cdot 2\\pi i", "{t}", tex_to_color_map={ "{t}": PINK, n_str: YELLOW, } ) self.fix_minuses(replacement1) replacement1[1][0].shift(0.025 * LEFT) replacement1.match_height(exp1) replacement1.move_to(exp1, DL) replacement2 = replacement1.copy() replacement2.move_to(exp2, DL) self.play(MoveToTarget(moving_exp)) self.play( TransformFromCopy( moving_exp[1], replacement1[1], ), FadeOut(exp1[1], DOWN), Transform(exp1[0], replacement1[0]), Transform(exp1[2:], replacement1[2:]), ) self.play( TransformFromCopy(replacement1, replacement2), FadeOut(exp2, DOWN), FadeOut(diagram), ) self.play(Restore(moving_exp)) def show_modified_averages(self): braces = self.braces for brace, n in zip(braces, it.count(-3)): self.show_individual_average(brace, n, "c_2") int_ft = self.int_ft c2 = self.c0.copy() c2.generate_target() eq = OldTex("=") eq.next_to(int_ft, RIGHT) c2.target.next_to(eq, RIGHT) c2.target.shift(0.05 * DOWN) self.play( FadeIn(eq), MoveToTarget(c2) ) self.wait() def add_general_expression(self): expression = OldTex( """ c_{n} = \\int_0^1 f({t}) e^{-{n} \\cdot 2\\pi i {t}}{dt} """, **self.tex_config, ) rect = SurroundingRectangle(expression, buff=MED_SMALL_BUFF) rect.set_fill(GREY_D, 1) rect.set_stroke(WHITE, 3) group = VGroup(rect, expression) group.to_edge(UP, buff=SMALL_BUFF) group.to_edge(RIGHT, buff=LARGE_BUFF) self.play( FadeOut(self.aos_label), FadeIn(rect), FadeIn(expression) ) self.wait() # def show_individual_average(self, brace, n, cn_tex=None): if not hasattr(self, "all_average_diagrams"): self.all_average_diagrams = VGroup() seed = brace.get_center()[0] + 1 int_seed = np.array([seed]).astype("uint32") np.random.seed(int_seed) if n == 0: if cn_tex is None: cn_tex = "c_" + str(n) result = OldTex(cn_tex) result[0][1].set_color(YELLOW) self.c0 = result else: result = OldTex("0") result.set_color(self.light_pink) result.next_to(brace, DOWN, SMALL_BUFF) coord_max = 1.25 plane = ComplexPlane( x_min=-coord_max, x_max=coord_max, y_min=-coord_max, y_max=coord_max, axis_config={ "stroke_color": GREY_B, "stroke_width": 1, "unit_size": 0.75, }, background_line_style={ "stroke_color": GREY_B, "stroke_width": 1, }, ) plane.next_to(result, DOWN, SMALL_BUFF) vector = Arrow( plane.n2p(0), plane.n2p( (0.2 + 0.8 * np.random.random()) * np.exp(complex( 0, TAU * np.random.random() )) ), buff=0, color=WHITE, ) circle = Circle() circle.set_stroke(BLUE, 2) circle.rotate(vector.get_angle()) circle.set_width(2 * vector.get_length()) circle.move_to(plane.n2p(0)) dots = VGroup(*[ Dot( circle.point_from_proportion( (n * a) % 1 ), radius=0.04, color=PINK, fill_opacity=0.75, ) for a in np.arange(0, 1, 1 / 25) ]) dot_center = center_of_mass([ d.get_center() for d in dots ]) self.play( FadeIn(plane), FadeIn(circle), FadeIn(vector), ) self.play( Rotating( vector, radians=n * TAU, about_point=plane.n2p(0), ), ShowIncreasingSubsets( dots, int_func=np.ceil, ), rate_func=lambda t: smooth(t, 1), run_time=3, ) dot_copies = dots.copy() self.play(*[ ApplyMethod(dot.move_to, dot_center) for dot in dot_copies ]) self.play( TransformFromCopy(dot_copies[0], result) ) self.wait() self.all_average_diagrams.add(VGroup( plane, circle, vector, dots, dot_copies, result, )) # def fix_minuses(self, tex_mob): for mob in tex_mob.get_parts_by_tex("{\\cdot"): minus = OldTex("-") minus.match_style(mob[0]) minus.set_width( 3 * mob[0].get_width(), stretch=True, ) minus.move_to(mob, LEFT) mob.submobjects[0] = minus def get_terms_by_tex_bounds(self, tex_mob, tex1, tex2): c_parts = tex_mob.get_parts_by_tex(tex1) t_parts = tex_mob.get_parts_by_tex(tex2) result = VGroup() for p1, p2 in zip(c_parts, t_parts): i1 = tex_mob.index_of_part(p1) i2 = tex_mob.index_of_part(p2) result.add(tex_mob[i1:i2 + 1]) return result def get_exp_terms(self, tex_mob): return self.get_terms_by_tex_bounds( tex_mob, "c_", "{t}" ) def get_integral_terms(self, tex_mob): return self.get_terms_by_tex_bounds( tex_mob, "\\int", "{dt}" ) class FootnoteOnSwappingIntegralAndSum(Scene): def construct(self): words = OldTexText( """ Typically in math, you have to be more\\\\ careful swapping the order of sums like\\\\ this when infinities are involved. Again,\\\\ such questions are what real analysis \\\\ is built for. """, alignment="" ) self.add(words) self.wait() class ShowRangeOfCnFormulas(Scene): def construct(self): formulas = VGroup(*[ self.get_formula(n) for n in [-50, None, -1, 0, 1, None, 50] ]) formulas.scale(0.7) formulas.arrange( DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT ) dots = formulas[1::4] dots.shift(MED_LARGE_BUFF * RIGHT) formulas.set_height(FRAME_HEIGHT - 0.5) formulas.to_edge(LEFT) self.play(LaggedStartMap( FadeInFrom, formulas, lambda m: (m, UP), lag_ratio=0.2, run_time=4, )) self.wait() def get_formula(self, n): if n is None: return OldTex("\\vdots") light_pink = interpolate_color(PINK, WHITE, 0.25) n_str = "{" + str(n) + "}" neg_n_str = "{" + str(-n) + "}" expression = OldTex( "c_" + n_str, "=", "\\int_0^1 f({t})", "e^{", neg_n_str, "\\cdot 2\\pi i {t}}{dt}", tex_to_color_map={ "{t}": light_pink, "{dt}": light_pink, n_str: YELLOW, neg_n_str: YELLOW, } ) return expression class DescribeSVG(Scene): def construct(self): plane = ComplexPlane( axis_config={"unit_size": 2} ) plane.add_coordinates() self.add(plane) svg_mob = SVGMobject("TrebleClef") path = svg_mob.family_members_with_points()[0] path.set_fill(opacity=0) path.set_stroke(YELLOW, 2) path.set_height(6) path.shift(0.5 * RIGHT) path_parts = CurvesAsSubmobjects(path) path_parts.set_stroke(GREEN, 3) self.add(path) dot = Dot() dot.set_color(PINK) ft_label = OldTex("f(t) = ") ft_label.to_corner(UL) z_decimal = DecimalNumber(num_decimal_places=3) z_decimal.next_to(ft_label, RIGHT) z_decimal.add_updater(lambda m: m.set_value( plane.p2n(dot.get_center()) )) z_decimal.set_color(interpolate_color(PINK, WHITE, 0.25)) rect = BackgroundRectangle(VGroup(ft_label, z_decimal)) brace = Brace(rect, DOWN) question = OldTexText("Where is this defined?") question.add_background_rectangle() question.next_to(brace, DOWN) answer = OldTexText("Read in some .svg") answer.add_background_rectangle() answer.next_to(question, DOWN, LARGE_BUFF) self.add(rect, ft_label, z_decimal) self.add(question, brace) self.play(UpdateFromAlphaFunc( dot, lambda d, a: d.move_to(path.point_from_proportion(a)), run_time=5, rate_func=lambda t: 0.3 * there_and_back(t) )) self.wait() self.play(FadeIn(answer, UP)) self.play( FadeOut(path), FadeOut(dot), FadeIn(path_parts), ) path_parts.generate_target() path_parts.save_state() path_parts.target.space_out_submobjects(1.3) for part in path_parts.target: part.shift(0.2 * part.get_center()[0] * RIGHT) path_parts.target.move_to(path_parts) self.play( MoveToTarget(path_parts) ) indicators = self.get_bezier_point_indicators(path_parts) self.play(ShowCreation( indicators, lag_ratio=0.5, run_time=3, )) self.wait() self.play( FadeOut(indicators), path_parts.restore, ) def get_bezier_point_indicators(self, path): dots = VGroup() lines = VGroup() for part in path.family_members_with_points(): for tup in part.get_cubic_bezier_tuples(): a1, h1, h2, a2 = tup dots.add( Dot(a1), Dot(a2), Dot(h2, color=YELLOW), Dot(h1, color=YELLOW), ) lines.add( Line(a1, h1), Line(a2, h2), ) for dot in dots: dot.set_width(0.05) lines.set_stroke(WHITE, 1) return VGroup(dots, lines) class NumericalIntegration(Scene): CONFIG = { "tex_config": { "tex_to_color_map": { "{t}": LIGHT_PINK, "{dt}": LIGHT_PINK, "{n}": YELLOW, "{0.01}": WHITE, } } } def construct(self): self.add_title() self.add_integral() def add_title(self): title = OldTexText("Integrate numerically") title.scale(1.5) title.to_edge(UP) line = Line() line.set_width(title.get_width() + 1) line.next_to(title, DOWN) self.add(title, line) self.title = title def add_integral(self): integral = OldTex( "c_{n}", "=", "\\int_0^1 f({t})" "e^{-{n} \\cdot 2\\pi i {t}}{dt}", **self.tex_config, ) integral.to_edge(LEFT) sum_tex = OldTex( " \\approx \\text{sum([} \\dots", "f({0.01}) e^{-{n} \\cdot 2\\pi i ({0.01})}({0.01})" "\\dots \\text{])}", **self.tex_config, ) sum_tex.next_to( integral.get_part_by_tex("="), DOWN, buff=LARGE_BUFF, aligned_edge=LEFT, ) group = VGroup(integral, sum_tex) group.next_to(self.title, DOWN, LARGE_BUFF) t_tracker = ValueTracker(0) decimal_templates = sum_tex.get_parts_by_tex("{0.01}") decimal_templates.set_color(LIGHT_PINK) decimals = VGroup(*[DecimalNumber() for x in range(2)]) for d, dt in zip(decimals, decimal_templates): d.replace(dt) d.set_color(LIGHT_PINK) d.add_updater(lambda d: d.set_value( t_tracker.get_value() )) dt.set_opacity(0) delta_t_brace = Brace(decimal_templates[-1], UP, buff=SMALL_BUFF) delta_t = delta_t_brace.get_tex( "\\Delta t", buff=SMALL_BUFF ) delta_t.set_color(PINK) input_line = UnitInterval( unit_size=10, ) input_line.next_to(group, DOWN, LARGE_BUFF) input_line.add_numbers(0, 0.5, 1) dots = VGroup(*[ Dot( input_line.n2p(t), color=PINK, radius=0.03, ).stretch(2, 1) for t in np.arange(0, 1, 0.01) ]) self.add(integral) self.add(sum_tex) self.add(decimals) self.add(delta_t, delta_t_brace) self.add(input_line) time = 15 self.play( t_tracker.set_value, 0.99, ShowIncreasingSubsets(dots), run_time=time, rate_func=lambda t: smooth(t, 1), ) self.wait() def get_term(self, t, dt): pass class StepFunctionIntegral(Scene): def construct(self): light_pink = interpolate_color(PINK, WHITE, 0.25) tex_config = { "tex_to_color_map": { "{t}": light_pink, "{dt}": light_pink, "{n}": YELLOW, } } cn_expression = OldTex( """ c_{n} = \\int_0^1 \\text{step}({t}) e^{-{n}\\cdot 2\\pi i {t}} {dt} """, **tex_config ) expansion = OldTex( """ = \\int_0^{0.5} 1 \\cdot e^{-{n}\\cdot 2\\pi i {t}} {dt} + \\int_{0.5}^1 -1 \\cdot e^{-{n}\\cdot 2\\pi i {t}} {dt} """, **tex_config ) group = VGroup(cn_expression, expansion) group.arrange(RIGHT) group.set_width(FRAME_WIDTH - 1) group.to_corner(UL) words1 = OldTex( "\\text{Challenge 1: Show that }" "c_{n} = {2 \\over {n} \\pi i}", "\\text{ for odd }", "{n}", "\\text{ and 0 otherwise}", **tex_config, ) words2 = OldTex( "\\text{Challenge 2: }", "&\\text{Using }", "\\sin(x) = (e^{ix} - e^{-ix}) / 2i,", "\\text{ show that}\\\\" "&\\text{step}({t}) = " "\\sum_{n = -\\infty}^{\\infty}", "c_{n} e^{{n} \\cdot 2\\pi i {t}}", "=", "\\sum_{n = 1, 3, 5, \\dots}", "{4 \\over {n} \\pi}", "\\sin\\left({n} \\cdot 2\\pi {t}\\right)", **tex_config, ) words3 = OldTexText( "Challenge 3: How can you turn this into an " "expansion with \\\\ \\phantom{Challenge 3:} cosines? " "(Hint: Draw the sine waves over $[0.25, 0.75]$)", # "Challenge 3: By focusing on the range $[0.25, 0.75]$, relate\\\\" # "\\quad\\;\\, this to an expansion with cosines." alignment="", ) all_words = VGroup(words1, words2, words3) all_words.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) all_words.scale(0.8) all_words.to_edge(DOWN) self.add(cn_expression) self.wait() self.play(FadeIn(expansion, LEFT)) for words in all_words: self.play(FadeIn(words)) self.wait() class GeneralChallenge(Scene): def construct(self): title = OldTexText("More ambitious challenge") title.scale(1.5) title.to_edge(UP, buff=MED_SMALL_BUFF) title.set_color(BLUE) line = Line() line.match_width(title) line.next_to(title, DOWN, SMALL_BUFF) self.add(title, line) light_pink = interpolate_color(PINK, WHITE, 0.25) tex_config = { "tex_to_color_map": { "{t}": light_pink, "{dt}": light_pink, # "{0}": YELLOW, "{n}": YELLOW, } } words1 = OldTexText( "In some texts, for a function $f$ on the input range $[0, 1]$,\\\\", "its Fourier series is presented like this:", alignment="", ) formula1 = OldTex( "f(t) = {a_{0} \\over 2} + " "\\sum_{n = 1}^{\\infty} \\big(" "a_{n} \\cos\\left({n} \\cdot 2\\pi {t}\\right) + " "b_{n} \\sin\\left({n} \\cdot 2\\pi {t}\\right) \\big)", **tex_config ) formula1[0][6].set_color(YELLOW) words2 = OldTexText("where") formula2 = OldTex( "a_{n} = 2\\int_0^1 f({t})\\cos\\left({n} \\cdot 2\\pi {t}\\right) {dt}\\\\" # "\\text{ and }" "b_{n} = 2\\int_0^1 f({t})\\sin\\left({n} \\cdot 2\\pi {t}\\right) {dt}", **tex_config ) words3 = OldTexText("How is this the same as what we just did?") prompt = VGroup(words1, formula1, words2, formula2, words3) prompt.arrange(DOWN, buff=MED_LARGE_BUFF) words2.align_to(words1, LEFT) words3.align_to(words1, LEFT) prompt.set_height(6) prompt.next_to(line, DOWN) self.add(prompt) self.wait() class HintToGeneralChallenge(Scene): def construct(self): self.add(FullScreenFadeRectangle( fill_color=GREY_E, fill_opacity=1, )) words1 = OldTexText("Hint: Try writing") formula1 = OldTex( "c_{n} =", "{", "a_{n} \\over 2} +", "{", "b_{n} \\over 2} i", tex_to_color_map={ "{n}": YELLOW, } ) words2 = OldTexText("and") formula2 = OldTex( "e^{i{x}} =", "\\cos\\left({x}\\right) +", "i\\sin\\left({x}\\right)", tex_to_color_map={ "{x}": GREEN } ) all_words = VGroup( words1, formula1, words2, formula2 ) all_words.arrange(DOWN, buff=LARGE_BUFF) self.add(all_words) class OtherResources(Scene): def construct(self): thumbnails = Group( ImageMobject("MathologerFourier"), ImageMobject("CodingTrainFourier"), ) names = VGroup( OldTexText("Mathologer"), OldTexText("The Coding Train"), ) for thumbnail, name in zip(thumbnails, names): thumbnail.set_height(3) thumbnails.arrange(RIGHT, buff=LARGE_BUFF) thumbnails.set_width(FRAME_WIDTH - 1) for thumbnail, name in zip(thumbnails, names): name.scale(1.5) name.next_to(thumbnail, UP) thumbnail.add(name) self.play( FadeInFromDown(name), GrowFromCenter(thumbnail) ) self.wait() url = OldTexText("www.jezzamon.com") url.scale(1.5) url.move_to(FRAME_WIDTH * RIGHT / 5) url.to_edge(UP) self.play( thumbnails.arrange, DOWN, {"buff": LARGE_BUFF}, thumbnails.set_height, FRAME_HEIGHT - 2, thumbnails.to_edge, LEFT ) self.play(FadeInFromDown(url)) self.wait() class ExponentialsMoreBroadly(Scene): def construct(self): self.write_fourier_series() self.pull_out_complex_exponent() self.show_matrix_exponent() def write_fourier_series(self): formula = OldTex( "f({t}) = " "\\sum_{n = -\\infty}^\\infty", "c_{n}", "e^{{n} \\cdot 2\\pi i {t}}" "", tex_to_color_map={ "{t}": LIGHT_PINK, "{n}": YELLOW } ) formula[2][4].set_color(YELLOW) formula.scale(1.5) formula.to_edge(UP) formula.add_background_rectangle_to_submobjects() plane = ComplexPlane( axis_config={"unit_size": 2} ) self.play(FadeInFromDown(formula)) self.wait() self.add(plane, formula) self.play( formula.scale, 0.7, formula.to_corner, UL, ShowCreation(plane) ) self.formula = formula self.plane = plane def pull_out_complex_exponent(self): formula = self.formula c_exp = OldTex("e^{it}") c_exp[0][2].set_color(LIGHT_PINK) c_exp.set_stroke(BLACK, 3, background=True) c_exp.move_to(formula.get_part_by_tex("e^"), DL) c_exp.set_opacity(0) dot = Dot() circle = Circle(radius=2) circle.set_color(YELLOW) dot.add_updater(lambda d: d.move_to(circle.get_end())) self.play( c_exp.set_opacity, 1, c_exp.scale, 1.5, c_exp.next_to, dot, UR, SMALL_BUFF, GrowFromCenter(dot), ) c_exp.add_updater( lambda m: m.next_to(dot, UR, SMALL_BUFF) ) self.play( ShowCreation(circle), run_time=4, ) self.wait() self.c_exp = c_exp self.circle = circle self.dot = dot def show_matrix_exponent(self): c_exp = self.c_exp formula = self.formula circle = self.circle dot = self.dot m_exp = OldTex( "\\text{exp}\\left(" "\\left[ \\begin{array}{cc}0 & -1 \\\\ 1 & 0 \\end{array} \\right]", "{t} \\right)", "=", "\\left[ \\begin{array}{cc}" "\\cos(t) & -\\sin(t) \\\\ \\sin(t) & \\cos(t)" "\\end{array} \\right]", ) VGroup( m_exp[1][0], m_exp[3][5], m_exp[3][12], m_exp[3][18], m_exp[3][24], ).set_color(LIGHT_PINK) m_exp.to_corner(UL) m_exp.add_background_rectangle_to_submobjects() vector_field = VectorField( lambda p: rotate_vector(p, TAU / 4), max_magnitude=7, delta_x=0.5, delta_y=0.5, length_func=lambda norm: 0.35 * sigmoid(norm), ) vector_field.sort(get_norm) self.play( FadeInFromDown(m_exp), FadeOut(formula, UP), FadeOut(c_exp) ) self.add(vector_field, circle, dot, m_exp) self.play( ShowCreation( vector_field, lag_ratio=0.001, ) ) self.play(Rotating(circle, run_time=TAU)) self.wait() class Part4EndScreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "1stViewMaths", "Adrian Robinson", "Alexis Olson", "Andreas Benjamin Brössel", "Andrew Busey", "Ankalagon", "Antoine Bruguier", "Antonio Juarez", "Arjun Chakroborty", "Art Ianuzzi", "Awoo", "Ayan Doss", "AZsorcerer", "Barry Fam", "Bernd Sing", "Boris Veselinovich", "Brian Staroselsky", "Caleb Johnstone", "Charles Southerland", "Chris Connett", "Christian Kaiser", "Clark Gaebel", "Cooper Jones", "Danger Dai", "Daniel Pang", "Dave B", "Dave Kester", "David B. Hill", "David Clark", "DeathByShrimp", "Delton Ding", "eaglle", "Empirasign", "emptymachine", "Eric Younge", "Eryq Ouithaqueue", "Federico Lebron", "Fernando Via Canel", "Giovanni Filippi", "Hal Hildebrand", "Hitoshi Yamauchi", "Isaac Jeffrey Lee", "j eduardo perez", "Jacob Harmon", "Jacob Hartmann", "Jacob Magnuson", "Jameel Syed", "Jason Hise", "Jeff Linse", "Jeff Straathof", "John C. Vesey", "John Griffith", "John Haley", "John V Wertheim", "Jonathan Eppele", "Josh Kinnear", "Kai-Siang Ang", "Kanan Gill", "Kartik Cating-Subramanian", "L0j1k", "Lee Redden", "Linh Tran", "Ludwig Schubert", "Magister Mugit", "Mark B Bahu", "Martin Price", "Mathias Jansson", "Matt Langford", "Matt Roveto", "Matthew Bouchard", "Matthew Cocke", "Michael Faust", "Michael Hardel", "Michael R Rader", "Mirik Gogri", "Mustafa Mahdi", "Márton Vaitkus", "Nero Li", "Nikita Lesnikov", "Omar Zrien", "Oscar Wu", "Owen Campbell-Moore", "Patrick Lucas", "Peter Ehrnstrom", "RedAgent14", "rehmi post", "Richard Comish", "Ripta Pasay", "Rish Kundalia", "Roobie", "Ryan Williams", "Sebastian Garcia", "Solara570", "Steven Siddals", "Stevie Metke", "Tal Einav", "Ted Suzman", "Tianyu Ge", "Tom Fleming", "Tyler VanValkenburg", "Valeriy Skobelev", "Xuanji Li", "Yavor Ivanov", "YinYangBalance.Asia", "Zach Cardwell", "Luc Ritchie", "Britt Selvitelle", "David Gow", "J", "Jonathan Wilson", "Joseph John Cox", "Magnus Dahlström", "Randy C. Will", "Ryan Atallah", "Lukas -krtek.net- Novy", "Jordan Scales", "Ali Yahya", "Arthur Zey", "Atul S", "dave nicponski", "Evan Phillips", "Joseph Kelly", "Kaustuv DeBiswas", "Lambda AI Hardware", "Lukas Biewald", "Mark Heising", "Mike Coleman", "Nicholas Cahill", "Peter Mcinerney", "Quantopian", "Roy Larson", "Scott Walter, Ph.D.", "Yana Chernobilsky", "Yu Jun", "D. Sivakumar", "Richard Barthel", "Burt Humburg", "Matt Russell", "Scott Gray", "soekul", "Tihan Seale", "Juan Benet", "Vassili Philippov", "Kurt Dicus", ], }
from manim_imports_ext import * from _2019.diffyq.part4.fourier_series_scenes import ComplexFourierSeriesExample from manimlib.once_useful_constructs.fractals import HilbertCurve class FourierSeriesExampleWithRectForZoom(ComplexFourierSeriesExample): CONFIG = { "n_vectors": 100, "slow_factor": 0.01, "rect_scale_factor": 0.1, "start_drawn": True, "drawing_height": 7, "rect_stroke_width": 1, } def construct(self): self.add_vectors_circles_path() self.circles.set_stroke(opacity=0.5) rect = self.rect = self.get_rect() rect.set_height(self.rect_scale_factor * FRAME_HEIGHT) rect.add_updater(lambda m: m.move_to( self.get_rect_center() )) self.add(rect) self.run_one_cycle() def get_rect_center(self): return center_of_mass([ v.get_end() for v in self.vectors ]) def get_rect(self): return ScreenRectangle( color=BLUE, stroke_width=self.rect_stroke_width, ) class ZoomedInFourierSeriesExample(FourierSeriesExampleWithRectForZoom, MovingCameraScene): CONFIG = { "vector_config": { "max_tip_length_to_length_ratio": 0.15, "tip_length": 0.05, }, "parametric_function_step_size": 0.001, } def setup(self): ComplexFourierSeriesExample.setup(self) MovingCameraScene.setup(self) def get_rect(self): return self.camera_frame def add_vectors_circles_path(self): super().add_vectors_circles_path() for v in self.vectors: if v.get_stroke_width() < 1: v.set_stroke(width=1) class ZoomedInFourierSeriesExample100x(ZoomedInFourierSeriesExample): CONFIG = { "vector_config": { "max_tip_length_to_length_ratio": 0.15 * 0.4, "tip_length": 0.05 * 0.2, "max_stroke_width_to_length_ratio": 80, "stroke_width": 3, }, "max_circle_stroke_width": 0.5, "rect_scale_factor": 0.01, # "parametric_function_step_size": 0.01, } def get_rect_center(self): return self.vectors[-1].get_end() # def get_drawn_path(self, vectors, stroke_width=2, **kwargs): # return self.get_path_end(vectors, stroke_width, **kwargs) class TrebleClefFourierSeriesExampleWithRectForZoom(FourierSeriesExampleWithRectForZoom): CONFIG = { "file_name": "TrebleClef", "drawn_path_stroke_width": 10, } class TrebleClefZoomedInFourierSeriesExample(ZoomedInFourierSeriesExample): CONFIG = { "file_name": "TrebleClef", } class NailAndGearFourierSeriesExampleWithRectForZoom(FourierSeriesExampleWithRectForZoom): CONFIG = { "file_name": "Nail_And_Gear", "n_vectors": 200, "drawn_path_color": "#39FF14", } class NailAndGearZoomedInFourierSeriesExample(ZoomedInFourierSeriesExample): CONFIG = { "file_name": "Nail_And_Gear", "n_vectors": 200, "drawn_path_color": "#39FF14", } class SigmaFourierSeriesExampleWithRectForZoom(FourierSeriesExampleWithRectForZoom): CONFIG = { "n_vectors": 200, "drawn_path_color": PINK, "rect_stroke_width": 0, } def get_shape(self): return OldTex("\\Sigma") class SigmaZoomedInFourierSeriesExample(SigmaFourierSeriesExampleWithRectForZoom, ZoomedInFourierSeriesExample): pass class FourierOfFourier(FourierSeriesExampleWithRectForZoom): CONFIG = { "file_name": "FourierOneLine", "n_vectors": 300, "rect_stroke_width": 1, } class FourierOfFourierZoomedIn(ZoomedInFourierSeriesExample): CONFIG = { "file_name": "FourierOneLine", "max_circle_stroke_width": 0.3, "n_vectors": 300, } class FourierOfFourier100xZoom(ZoomedInFourierSeriesExample100x): CONFIG = { "file_name": "FourierOneLine", "max_circle_stroke_width": 0.3, "n_vectors": 300, "slow_factor": 0.001, } def run_one_cycle(self): self.vector_clock.set_value(0.3) self.wait(40) class FourierOfHilbert(FourierSeriesExampleWithRectForZoom): CONFIG = { "n_vectors": 300, "rect_stroke_width": 1, "drawn_path_stroke_width": 4, "drawn_path_color": BLUE, } def get_path(self): path = HilbertCurve(order=5) path.set_height(self.drawing_height) path.to_edge(DOWN) combined_path = VMobject() for sm in path.family_members_with_points(): combined_path.append_vectorized_mobject(sm) start = combined_path.get_start() end = combined_path.get_end() points = [ interpolate(end, start, alpha) for alpha in np.linspace(0, 1, 10) ] for point in points: combined_path.add_line_to(point) combined_path.set_stroke(width=0) return combined_path class FourierOfHilbertZoomedIn(FourierOfHilbert, ZoomedInFourierSeriesExample): pass class FourierOfBritain(FourierSeriesExampleWithRectForZoom): CONFIG = { "file_name": "Britain", "n_vectors": 500, "drawn_path_color": RED, } class FourierOfBritainZoomedIn(FourierOfBritain, ZoomedInFourierSeriesExample): pass class FourierOfSeattle(FourierSeriesExampleWithRectForZoom): CONFIG = { "file_name": "SeattleSkyline", "drawing_height": 7, "n_vectors": 400, "drawn_path_color": TEAL, "drawn_path_stroke_width": 5, } class FourierOfSeattleZoomedIn(ZoomedInFourierSeriesExample): CONFIG = { "file_name": "SeattleSkyline", "drawing_height": 7, "n_vectors": 400, "drawn_path_color": TEAL, "drawn_path_stroke_width": 5, "max_circle_stroke_width": 0.3, } class VideoWrapper(Scene): def construct(self): fade_rect = FullScreenFadeRectangle() fade_rect.set_fill(GREY_D, 1) screen_rect = ScreenRectangle() screen_rect.set_height(4) screen_rect.set_fill(BLACK, 1) screen_rect.set_stroke(width=0) boundary = AnimatedBoundary(screen_rect) title = OldTexText("Learn the math") title.scale(1.5) title.next_to(screen_rect, UP) self.add(fade_rect) self.add(screen_rect) self.add(boundary) self.play(FadeInFromDown(title)) self.wait(19)
from manim_imports_ext import * class WhyWouldYouCare(TeacherStudentsScene): def construct(self): self.student_says( "Who cares!", target_mode="sassy", index=2, added_anims=[self.teacher.change, "guilty"], ) self.wait() self.play( RemovePiCreatureBubble(self.students[2]), self.teacher.change, "raise_right_hand", self.change_students( "pondering", "erm", "thinking", look_at=self.screen, ) ) self.look_at(self.screen) self.wait(5) class SolveForWavesNothingElse(TeacherStudentsScene): def construct(self): self.student_says( "Sure, we can\\\\solve it for\\\\sums of waves...", target_mode="sassy", index=2, added_anims=[self.teacher.change, "guilty"] ) self.play_student_changes("pondering", "pondering", "sassy") self.look_at(self.screen) self.wait(4) self.student_says( "But nothing else!", target_mode="angry", ) self.play_student_changes( "concerned_musician", "concerned_musician", "angry", ) self.wait(5) class HangOnThere(TeacherStudentsScene): def construct(self): student = self.students[2] axes1 = Axes( x_min=0, x_max=1, y_min=-1.5, y_max=1.5, x_axis_config={ "tick_frequency": 0.25, "include_tip": False, "unit_size": 3, }, y_axis_config={ "tick_frequency": 0.5, "include_tip": False, }, ) axes1.set_stroke(width=2) axes2 = axes1.deepcopy() neq = OldTex("\\neq") neq.scale(2) group = VGroup(axes1, neq, axes2) group.arrange(RIGHT) group.set_height(4) group.next_to( student.get_corner(UL), UP, buff=LARGE_BUFF, ) step_graph = axes1.get_graph( lambda x: (1 if x < 0.5 else -1), discontinuities=[0.5], ) step_graph.set_color(YELLOW) wave_graphs = VGroup(*[ axes2.get_graph( lambda x: (4 / PI) * np.sum([ (u / n) * np.cos(n * PI * x) for u, n in zip( it.cycle([1, -1]), range(1, max_n, 2), ) ]), ) for max_n in range(3, 103, 2) ]) wave_graphs.set_stroke(width=3) wave_graphs.set_color_by_gradient(WHITE, PINK) last_wave_graph = wave_graphs[-1] last_wave_graph.set_stroke(PINK, 2) wave_graphs.remove(last_wave_graph) # wave_graphs[-1].set_stroke(width=3) # wave_graphs[-1].set_stroke(BLACK, 5, background=True) group.add(step_graph) self.student_says( "Hang on\\\\hang on\\\\hang on...", target_mode="surprised", content_introduction_class=FadeIn, index=2, added_anims=[ self.teacher.change, "guilty" ], run_time=1, ) self.wait() self.play( RemovePiCreatureBubble( student, target_mode="raise_left_hand", look_at=group, ), FadeInFromDown(group), ) last_wg = VectorizedPoint() n_first_fades = 4 for wg in wave_graphs[:n_first_fades]: self.play( last_wg.set_stroke, {"width": 0.1}, FadeIn(wg), ) last_wg = wg self.play( LaggedStart( *[ UpdateFromAlphaFunc( wg, lambda m, a: m.set_stroke( width=(3 * there_and_back(a) + 0.1 * a) ), ) for wg in wave_graphs[n_first_fades:] ], run_time=5, lag_ratio=0.2, ), ApplyMethod( last_wg.set_stroke, {"width": 0.1}, run_time=0.25, ), FadeIn( last_wave_graph, rate_func=squish_rate_func(smooth, 0.9, 1), run_time=5, ), self.teacher.change, "thinking", ) self.play_student_changes( "confused", "confused", "angry" ) self.wait(3) class YouSaidThisWasEasier(TeacherStudentsScene): def construct(self): self.play_all_student_changes( "confused", look_at=self.screen, ) self.student_says( "I'm sorry, you said\\\\this was easier?", target_mode="sassy" ) self.play(self.teacher.change, "guilty") self.wait(3) self.teacher_says( "Bear with\\\\me", bubble_config={"height": 3, "width": 3}, ) self.look_at(self.screen) self.wait(3) class LooseWithLanguage(TeacherStudentsScene): def construct(self): terms = VGroup( OldTexText("``Complex number''"), OldTexText("``Vector''"), ) colors = [YELLOW, BLUE] for term, color in zip(terms, colors): term.set_color(color) terms.scale(1.5) terms.arrange(DOWN, buff=LARGE_BUFF) terms.to_edge(UP) terms.match_x(self.students) self.teacher_says( "Loose with\\\\language", bubble_config={"width": 3, "height": 3}, run_time=2, ) self.play( FadeIn(terms[1], DOWN), self.change_students( "thinking", "pondering", "erm", look_at=terms, ) ) self.play(FadeInFromDown(terms[0])) self.wait() self.play(Swap(*terms)) self.wait(3) class FormulaOutOfContext(TeacherStudentsScene): def construct(self): formula = OldTex( "c_{n} = \\int_0^1 e^{-2\\pi i {n} {t}}f({t}){dt}", tex_to_color_map={ "{n}": YELLOW, "{t}": PINK, } ) formula.scale(1.5) formula.next_to(self.students, UP, LARGE_BUFF) self.add(formula) self.play_all_student_changes( "horrified", look_at=formula, ) self.play(self.teacher.change, "tease") self.wait(3)
from manim_imports_ext import * from _2019.diffyq.part2.heat_equation import BringTwoRodsTogether from _2019.diffyq.part3.staging import FourierSeriesIllustraiton class StepFunctionExample(BringTwoRodsTogether, FourierSeriesIllustraiton): CONFIG = { "axes_config": { "y_min": -1.5, "y_max": 1.5, "y_axis_config": { "unit_size": 2.5, "tick_frequency": 0.5, }, "x_min": 0, "x_max": 1, "x_axis_config": { "unit_size": 8, "tick_frequency": 0.1, "include_tip": False, }, }, "y_labels": [-1, 1], "graph_x_min": 0, "graph_x_max": 1, "midpoint": 0.5, "min_temp": -1, "max_temp": 1, "alpha": 0.25, "step_size": 0.01, "n_range": range(1, 41, 2), } def construct(self): self.setup_axes() self.setup_graph() self.setup_clock() self.bring_rods_together() self.let_evolve_for_a_bit() self.add_labels() self.compare_to_sine_wave() self.sum_of_sine_waves() def bring_rods_together(self): rods = VGroup( self.get_rod(0, 0.5), self.get_rod(0.5, 1), ) rods.add_updater(self.update_rods) arrows = VGroup( Vector(RIGHT).next_to(rods[0], UP), Vector(LEFT).next_to(rods[1], UP), ) words = VGroup( OldTexText("Hot").next_to(rods[0], DOWN), OldTexText("Cold").next_to(rods[1], DOWN), ) for pair in rods, words: pair.save_state() pair.space_out_submobjects(1.2) black_rects = VGroup(*[ Square( side_length=1, fill_color=BLACK, fill_opacity=1, stroke_width=0, ).move_to(self.axes.c2p(0, u)) for u in [1, -1] ]) black_rects[0].add_updater( lambda m: m.align_to(rods[0].get_right(), LEFT) ) black_rects[1].add_updater( lambda m: m.align_to(rods[1].get_left(), RIGHT) ) self.add( self.axes, self.graph, self.clock, ) self.add(rods, words) self.add(black_rects) kw = { "run_time": 2, "rate_func": rush_into, } self.play( Restore(rods, **kw), Restore(words, **kw), *map(ShowCreation, arrows) ) self.remove(black_rects) self.to_fade = VGroup(words, arrows) self.rods = rods def let_evolve_for_a_bit(self): rods = self.rods # axes = self.axes time_label = self.time_label graph = self.graph graph.save_state() graph.add_updater(self.update_graph) time_label.next_to(self.clock, DOWN) time_label.add_updater( lambda d, dt: d.increment_value(dt) ) rods.add_updater(self.update_rods) self.add(time_label) self.play( FadeOut(self.to_fade), self.get_clock_anim(1) ) self.play(self.get_clock_anim(3)) time_label.clear_updaters() graph.clear_updaters() self.play( self.get_clock_anim( -4, run_time=1, rate_func=smooth, ), graph.restore, time_label.set_value, 0, ) rods.clear_updaters() self.wait() def add_labels(self): axes = self.axes y_axis = axes.y_axis x_axis = axes.x_axis y_numbers = y_axis.get_number_mobjects( *np.arange(-1, 1.5, 0.5), unit="^\\circ", num_decimal_places=1 ) x_numbers = x_axis.get_number_mobjects( *np.arange(0.2, 1.2, 0.2), num_decimal_places=1, ) self.play(FadeIn(y_numbers)) self.play(ShowCreationThenFadeAround(y_numbers[-1])) self.play(ShowCreationThenFadeAround(y_numbers[0])) self.play( LaggedStartMap( FadeInFrom, x_numbers, lambda m: (m, UP) ), self.rods.set_opacity, 0.8, ) self.wait() def compare_to_sine_wave(self): phi_tracker = ValueTracker(0) get_phi = phi_tracker.get_value k_tracker = ValueTracker(TAU) get_k = k_tracker.get_value A_tracker = ValueTracker(1) get_A = A_tracker.get_value sine_wave = always_redraw(lambda: self.axes.get_graph( lambda x: get_A() * np.sin( get_k() * x - get_phi() ), x_min=self.graph_x_min, x_max=self.graph_x_max, ).color_using_background_image("VerticalTempGradient")) self.play(ShowCreation(sine_wave, run_time=3)) self.wait() self.play(A_tracker.set_value, 1.25) self.play(A_tracker.set_value, 0.75) self.play(phi_tracker.set_value, -PI / 2) self.play(k_tracker.set_value, 3 * TAU) self.play(k_tracker.set_value, 2 * TAU) self.play( k_tracker.set_value, PI, A_tracker.set_value, 4 / PI, run_time=3 ) self.wait() self.sine_wave = sine_wave def sum_of_sine_waves(self): curr_sine_wave = self.sine_wave axes = self.axes sine_graphs = self.get_sine_graphs(axes) partial_sums = self.get_partial_sums(axes, sine_graphs) curr_partial_sum = partial_sums[0] curr_partial_sum.set_color(WHITE) self.play( FadeOut(curr_sine_wave), FadeIn(curr_partial_sum), FadeOut(self.rods), ) # Copy-pasting from superclass...in theory, # this should be better abstracted, but eh. pairs = list(zip(sine_graphs, partial_sums))[1:] for sine_graph, partial_sum in pairs: anims1 = [ ShowCreation(sine_graph) ] partial_sum.set_stroke(BLACK, 4, background=True) anims2 = [ curr_partial_sum.set_stroke, {"width": 1, "opacity": 0.25}, curr_partial_sum.set_stroke, {"width": 0, "background": True}, ReplacementTransform( sine_graph, partial_sum, remover=True ), ] self.play(*anims1) self.play(*anims2) curr_partial_sum = partial_sum # def setup_axes(self): super().setup_axes() self.axes.shift( self.axes.c2p(0, 0)[1] * DOWN ) class BreakDownStepFunction(StepFunctionExample): CONFIG = { "axes_config": { "x_axis_config": { "stroke_width": 2, }, "y_axis_config": { "tick_frequency": 0.25, "stroke_width": 2, }, "y_min": -1.25, "y_max": 1.25, }, "alpha": 0.1, "wait_time": 30, } def construct(self): self.setup_axes() self.setup_graph() self.setup_clock() self.add_rod() self.wait() self.init_updaters() self.play( self.get_clock_anim(self.wait_time) ) def setup_axes(self): super().setup_axes() axes = self.axes axes.to_edge(LEFT) mini_axes = VGroup(*[ axes.deepcopy() for x in range(4) ]) for n, ma in zip(it.count(1, 2), mini_axes): if n == 1: t1 = OldTex("1") t2 = OldTex("-1") else: t1 = OldTex("1 / " + str(n)) t2 = OldTex("-1 / " + str(n)) VGroup(t1, t2).scale(1.5) t1.next_to(ma.y_axis.n2p(1), LEFT, MED_SMALL_BUFF) t2.next_to(ma.y_axis.n2p(-1), LEFT, MED_SMALL_BUFF) ma.y_axis.numbers.set_opacity(0) ma.y_axis.add(t1, t2) for mob in mini_axes.get_family(): if isinstance(mob, Line): mob.set_stroke(width=1, family=False) mini_axes.arrange(DOWN, buff=2) mini_axes.set_height(FRAME_HEIGHT - 1.5) mini_axes.to_corner(UR) self.scale_factor = fdiv( mini_axes[0].get_width(), axes.get_width(), ) # mini_axes.arrange(RIGHT, buff=2) # mini_axes.set_width(FRAME_WIDTH - 1.5) # mini_axes.to_edge(LEFT) dots = OldTex("\\vdots") dots.next_to(mini_axes, DOWN) dots.shift_onto_screen() self.add(axes) self.add(mini_axes) self.add(dots) self.mini_axes = mini_axes def setup_graph(self): super().setup_graph() graph = self.graph self.add(graph) mini_axes = self.mini_axes mini_graphs = VGroup() for axes, u, n in zip(mini_axes, it.cycle([1, -1]), it.count(1, 2)): mini_graph = axes.get_graph( lambda x: (4 / PI) * (u / 1) * np.cos(PI * n * x), ) mini_graph.set_stroke(WHITE, width=2) mini_graphs.add(mini_graph) # mini_graphs.set_color_by_gradient( # BLUE, GREEN, RED, YELLOW, # ) self.mini_graphs = mini_graphs self.add(mini_graphs) def setup_clock(self): super().setup_clock() clock = self.clock time_label = self.time_label clock.move_to(3 * RIGHT) clock.to_corner(UP) time_label.next_to(clock, DOWN) self.add(clock) self.add(time_label) def add_rod(self): self.rod = self.get_rod(0, 1) self.add(self.rod) def init_updaters(self): self.graph.add_updater(self.update_graph) for mg in self.mini_graphs: mg.add_updater( lambda m, dt: self.update_graph( m, dt, alpha=self.scale_factor * self.alpha ) ) self.time_label.add_updater( lambda d, dt: d.increment_value(dt) ) self.rod.add_updater( lambda r: self.update_rods([r]) )
from manim_imports_ext import * from _2019.diffyq.part3.temperature_graphs import TemperatureGraphScene from _2019.diffyq.part2.wordy_scenes import WriteHeatEquationTemplate class ShowLinearity(WriteHeatEquationTemplate, TemperatureGraphScene): CONFIG = { "temp_text": "Temp", "alpha": 0.1, "axes_config": { "z_max": 2, "z_min": -2, "z_axis_config": { "tick_frequency": 0.5, "unit_size": 1.5, }, }, "default_surface_config": { "resolution": (16, 16) # "resolution": (4, 4) }, "freqs": [2, 5], } def setup(self): TemperatureGraphScene.setup(self) WriteHeatEquationTemplate.setup(self) def construct(self): self.init_camera() self.add_three_graphs() self.show_words() self.add_function_labels() self.change_scalars() def init_camera(self): self.camera.set_distance(1000) def add_three_graphs(self): axes_group = self.get_axes_group() axes0, axes1, axes2 = axes_group freqs = self.freqs scalar_trackers = Group( ValueTracker(1), ValueTracker(1), ) graphs = VGroup( self.get_graph(axes0, [freqs[0]], [scalar_trackers[0]]), self.get_graph(axes1, [freqs[1]], [scalar_trackers[1]]), self.get_graph(axes2, freqs, scalar_trackers), ) plus = OldTex("+").scale(2) equals = OldTex("=").scale(2) plus.move_to(midpoint( axes0.get_right(), axes1.get_left(), )) equals.move_to(midpoint( axes1.get_right(), axes2.get_left(), )) self.add(axes_group) self.add(graphs) self.add(plus) self.add(equals) self.axes_group = axes_group self.graphs = graphs self.scalar_trackers = scalar_trackers self.plus = plus self.equals = equals def show_words(self): equation = self.get_d1_equation() name = OldTexText("Heat equation") name.next_to(equation, DOWN) name.set_color_by_gradient(RED, YELLOW) group = VGroup(equation, name) group.to_edge(UP) shift_val = 0.5 * RIGHT arrow = Vector(1.5 * RIGHT) arrow.move_to(group) arrow.shift(shift_val) linear_word = OldTexText("``Linear''") linear_word.scale(2) linear_word.next_to(arrow, RIGHT) self.add(group) self.wait() self.play( ShowCreation(arrow), group.next_to, arrow, LEFT ) self.play(FadeIn(linear_word, LEFT)) self.wait() def add_function_labels(self): axes_group = self.axes_group graphs = self.graphs solution_labels = VGroup() for axes in axes_group: label = OldTexText("Solution", "$\\checkmark$") label.set_color_by_tex("checkmark", GREEN) label.next_to(axes, DOWN) solution_labels.add(label) kw = { "tex_to_color_map": { "T_1": BLUE, "T_2": GREEN, } } T1 = OldTex("a", "T_1", **kw) T2 = OldTex("b", "T_2", **kw) T_sum = OldTex("T_1", "+", "T_2", **kw) T_sum_with_scalars = OldTex( "a", "T_1", "+", "b", "T_2", **kw ) T1.next_to(graphs[0], UP) T2.next_to(graphs[1], UP) T_sum.next_to(graphs[2], UP) T_sum.shift(SMALL_BUFF * DOWN) T_sum_with_scalars.move_to(T_sum) a_brace = Brace(T1[0], UP, buff=SMALL_BUFF) b_brace = Brace(T2[0], UP, buff=SMALL_BUFF) s1_decimal = DecimalNumber() s1_decimal.match_color(T1[1]) s1_decimal.next_to(a_brace, UP, SMALL_BUFF) s1_decimal.add_updater(lambda m: m.set_value( self.scalar_trackers[0].get_value() )) s2_decimal = DecimalNumber() s2_decimal.match_color(T2[1]) s2_decimal.next_to(b_brace, UP, SMALL_BUFF) s2_decimal.add_updater(lambda m: m.set_value( self.scalar_trackers[1].get_value() )) self.play( FadeIn(T1[1], DOWN), FadeIn(solution_labels[0], UP), ) self.play( FadeIn(T2[1], DOWN), FadeIn(solution_labels[1], UP), ) self.wait() self.play( TransformFromCopy(T1[1], T_sum[0]), TransformFromCopy(T2[1], T_sum[2]), TransformFromCopy(self.plus, T_sum[1]), *[ Transform( graph.copy().set_fill(opacity=0), graphs[2].copy().set_fill(opacity=0), remover=True ) for graph in graphs[:2] ] ) self.wait() self.play(FadeIn(solution_labels[2], UP)) self.wait() # Show constants self.play( FadeIn(T1[0]), FadeIn(T2[0]), FadeIn(a_brace), FadeIn(b_brace), FadeIn(s1_decimal), FadeIn(s2_decimal), FadeOut(T_sum), FadeIn(T_sum_with_scalars), ) def change_scalars(self): s1, s2 = self.scalar_trackers kw = { "run_time": 2, } for graph in self.graphs: graph.resume_updating() self.play(s2.set_value, -0.5, **kw) self.play(s1.set_value, -0.2, **kw) self.play(s2.set_value, 1.5, **kw) self.play(s1.set_value, 1.2, **kw) self.play(s2.set_value, 0.3, **kw) self.wait() # def get_axes_group(self): axes_group = VGroup(*[ self.get_axes() for x in range(3) ]) axes_group.arrange(RIGHT, buff=2) axes_group.set_width(FRAME_WIDTH - 1) axes_group.to_edge(DOWN, buff=1) return axes_group def get_axes(self, **kwargs): axes = self.get_three_d_axes(**kwargs) # axes.input_plane.set_fill(opacity=0) # axes.input_plane.set_stroke(width=0.5) # axes.add(axes.input_plane) self.orient_three_d_mobject(axes) axes.rotate(-5 * DEGREES, UP) axes.set_width(4) axes.x_axis.label.next_to( axes.x_axis.get_end(), DOWN, buff=2 * SMALL_BUFF ) return axes def get_graph(self, axes, freqs, scalar_trackers): L = axes.x_max a = self.alpha def func(x, t): scalars = [st.get_value() for st in scalar_trackers] return np.sum([ s * np.cos(k * x) * np.exp(-a * (k**2) * t) for freq, s in zip(freqs, scalars) for k in [freq * PI / L] ]) def get_surface_graph_group(): return VGroup( self.get_surface(axes, func), self.get_time_slice_graph(axes, func, t=0), ) result = always_redraw(get_surface_graph_group) result.func = func result.suspend_updating() return result class CombineSeveralSolutions(ShowLinearity): CONFIG = { "default_surface_config": { "resolution": (16, 16), # "resolution": (4, 4), }, "n_top_graphs": 5, "axes_config": { "y_max": 15, }, "target_scalars": [ 0.81, -0.53, 0.41, 0.62, -0.95 ], "final_run_time": 14, } def construct(self): self.init_camera() self.add_all_axes() self.setup_all_graphs() self.show_infinite_family() self.show_sum() self.show_time_passing() def add_all_axes(self): top_axes_group = VGroup(*[ self.get_axes( z_min=-1.25, z_max=1.25, z_axis_config={ "unit_size": 2, "tick_frequency": 0.5, }, ) for x in range(self.n_top_graphs) ]) top_axes_group.arrange(RIGHT, buff=2) top_axes_group.set_width(FRAME_WIDTH - 1.5) top_axes_group.to_corner(UL) dots = OldTex("\\dots") dots.next_to(top_axes_group, RIGHT) low_axes = self.get_axes() low_axes.center() low_axes.scale(1.2) low_axes.to_edge(DOWN, buff=SMALL_BUFF) self.add(top_axes_group) self.add(dots) self.add(low_axes) self.top_axes_group = top_axes_group self.low_axes = low_axes def setup_all_graphs(self): scalar_trackers = Group(*[ ValueTracker(1) for x in range(self.n_top_graphs) ]) freqs = np.arange(self.n_top_graphs) freqs += 1 self.top_graphs = VGroup(*[ self.get_graph(axes, [n], [st]) for axes, n, st in zip( self.top_axes_group, freqs, scalar_trackers, ) ]) self.low_graph = self.get_graph( self.low_axes, freqs, scalar_trackers ) self.scalar_trackers = scalar_trackers def show_infinite_family(self): top_axes_group = self.top_axes_group top_graphs = self.top_graphs scalar_trackers = self.scalar_trackers decimals = self.get_decimals( top_axes_group, scalar_trackers ) self.play(LaggedStart(*[ AnimationGroup( Write(graph[0]), FadeIn(graph[1]), ) for graph in top_graphs ])) self.wait() self.play(FadeIn(decimals)) for graph in top_graphs: graph.resume_updating() self.play(LaggedStart(*[ ApplyMethod(st.set_value, value) for st, value in zip( scalar_trackers, self.target_scalars, ) ]), run_time=3) self.wait() def show_sum(self): top_graphs = self.top_graphs low_graph = self.low_graph low_graph.resume_updating() low_graph.update() self.play( LaggedStart(*[ Transform( top_graph.copy().set_fill(opacity=0), low_graph.copy().set_fill(opacity=0), remover=True, ) for top_graph in top_graphs ]), FadeIn( low_graph, rate_func=squish_rate_func(smooth, 0.7, 1) ), run_time=3, ) self.wait() def show_time_passing(self): all_graphs = [*self.top_graphs, self.low_graph] all_axes = [*self.top_axes_group, self.low_axes] time_tracker = ValueTracker(0) get_t = time_tracker.get_value anims = [ ApplyMethod( time_tracker.set_value, 1, run_time=1, rate_func=linear ) ] for axes, graph_group in zip(all_axes, all_graphs): graph_group.clear_updaters() surface, gslice = graph_group plane = self.get_const_time_plane(axes) plane.t_tracker.add_updater( lambda m: m.set_value(get_t()) ) gslice.axes = axes gslice.func = graph_group.func gslice.add_updater(lambda m: m.become( self.get_time_slice_graph( m.axes, m.func, t=get_t() ) )) self.add(gslice) self.add(plane.t_tracker) anims.append(FadeIn(plane)) self.play(*anims) run_time = self.final_run_time self.play( time_tracker.increment_value, run_time, run_time=run_time, rate_func=linear, ) # def get_decimals(self, axes_group, scalar_trackers): result = VGroup() for axes, st in zip(axes_group, scalar_trackers): decimal = DecimalNumber() decimal.move_to(axes.get_bottom(), UP) decimal.shift(SMALL_BUFF * RIGHT) decimal.set_color(YELLOW) decimal.scalar_tracker = st times = OldTex("\\times") times.next_to(decimal, LEFT, SMALL_BUFF) decimal.add_updater(lambda d: d.set_value( d.scalar_tracker.get_value() )) group = VGroup(times, decimal) group.scale(0.7) result.add(group) return result class CycleThroughManyLinearCombinations(CombineSeveralSolutions): CONFIG = { "default_surface_config": { "resolution": (16, 16), # "resolution": (4, 4), }, "n_cycles": 10, } def construct(self): self.init_camera() self.add_all_axes() self.setup_all_graphs() # self.cycle_through_superpositions() def cycle_through_superpositions(self): top_graphs = self.top_graphs low_graph = self.low_graph scalar_trackers = self.scalar_trackers self.add(self.get_decimals( self.top_axes_group, scalar_trackers )) for graph in [low_graph, *top_graphs]: graph.resume_updating() self.add(graph) nst = len(scalar_trackers) for x in range(self.n_cycles): self.play(LaggedStart(*[ ApplyMethod(st.set_value, value) for st, value in zip( scalar_trackers, 3 * np.random.random(nst) - 1.5 ) ]), run_time=3) self.wait()
from manim_imports_ext import * from _2019.diffyq.part2.fourier_series import FourierOfTrebleClef from _2019.diffyq.part4.complex_functions import TRangingFrom0To1 from _2019.diffyq.part4.complex_functions import SimpleComplexExponentExample class ComplexFourierSeriesExample(FourierOfTrebleClef): CONFIG = { "file_name": "EighthNote", "run_time": 10, "n_vectors": 200, "n_cycles": 2, "max_circle_stroke_width": 0.75, "drawing_height": 5, "center_point": DOWN, "top_row_center": 3 * UP, "top_row_label_y": 2, "top_row_x_spacing": 1.75, "top_row_copy_scale_factor": 0.9, "start_drawn": False, "plane_config": { "axis_config": {"unit_size": 2}, "y_min": -1.25, "y_max": 1.25, "x_min": -2.5, "x_max": 2.5, "background_line_style": { "stroke_width": 1, "stroke_color": GREY_B, }, }, "top_rect_height": 2.5, } def construct(self): self.add_vectors_circles_path() self.add_top_row(self.vectors, self.circles) self.write_title() self.highlight_vectors_one_by_one() self.change_shape() def write_title(self): title = OldTexText("Complex\\\\Fourier series") title.scale(1.5) title.to_edge(LEFT) title.match_y(self.path) self.wait(11) self.play(FadeInFromDown(title)) self.wait(2) self.title = title def highlight_vectors_one_by_one(self): # Don't know why these vectors can't get copied. # That seems like a problem that will come up again. labels = self.top_row[-1] next_anims = [] for vector, circle, label in zip(self.vectors, self.circles, labels): # v_color = vector.get_color() c_color = circle.get_color() c_stroke_width = circle.get_stroke_width() rect = SurroundingRectangle(label, color=PINK) self.play( # vector.set_color, PINK, circle.set_stroke, RED, 3, FadeIn(rect), *next_anims ) self.wait() next_anims = [ # vector.set_color, v_color, circle.set_stroke, c_color, c_stroke_width, FadeOut(rect), ] self.play(*next_anims) def change_shape(self): # path_mob = OldTex("\\pi") path_mob = SVGMobject("Nail_And_Gear") new_path = path_mob.family_members_with_points()[0] new_path.set_height(4) new_path.move_to(self.path, DOWN) new_path.shift(0.5 * UP) self.transition_to_alt_path(new_path) for n in range(self.n_cycles): self.run_one_cycle() def transition_to_alt_path(self, new_path, morph_path=False): new_coefs = self.get_coefficients_of_path(new_path) new_vectors = self.get_rotating_vectors( coefficients=new_coefs ) new_drawn_path = self.get_drawn_path(new_vectors) self.vector_clock.suspend_updating() vectors = self.vectors anims = [] for vect, new_vect in zip(vectors, new_vectors): new_vect.update() new_vect.clear_updaters() line = Line(stroke_width=0) line.put_start_and_end_on(*vect.get_start_and_end()) anims.append(ApplyMethod( line.put_start_and_end_on, *new_vect.get_start_and_end() )) vect.freq = new_vect.freq vect.coefficient = new_vect.coefficient vect.line = line vect.add_updater( lambda v: v.put_start_and_end_on( *v.line.get_start_and_end() ) ) if morph_path: anims.append( ReplacementTransform( self.drawn_path, new_drawn_path ) ) else: anims.append( FadeOut(self.drawn_path) ) self.play(*anims, run_time=3) for vect in self.vectors: vect.remove_updater(vect.updaters[-1]) if not morph_path: self.add(new_drawn_path) self.vector_clock.set_value(0) self.vector_clock.resume_updating() self.drawn_path = new_drawn_path # def get_path(self): path = super().get_path() path.set_height(self.drawing_height) path.to_edge(DOWN) return path def add_top_row(self, vectors, circles, max_freq=3): self.top_row = self.get_top_row( vectors, circles, max_freq ) self.add(self.top_row) def get_top_row(self, vectors, circles, max_freq=3): vector_copies = VGroup() circle_copies = VGroup() for vector, circle in zip(vectors, circles): if vector.freq > max_freq: break vcopy = vector.copy() vcopy.clear_updaters() ccopy = circle.copy() ccopy.clear_updaters() ccopy.original = circle vcopy.original = vector vcopy.center_point = op.add( self.top_row_center, vector.freq * self.top_row_x_spacing * RIGHT, ) ccopy.center_point = vcopy.center_point vcopy.add_updater(self.update_top_row_vector_copy) ccopy.add_updater(self.update_top_row_circle_copy) vector_copies.add(vcopy) circle_copies.add(ccopy) dots = VGroup(*[ OldTex("\\dots").next_to( circle_copies, direction, MED_LARGE_BUFF, ) for direction in [LEFT, RIGHT] ]) labels = self.get_top_row_labels(vector_copies) return VGroup( vector_copies, circle_copies, dots, labels, ) def update_top_row_vector_copy(self, vcopy): vcopy.become(vcopy.original) vcopy.scale(self.top_row_copy_scale_factor) vcopy.shift(vcopy.center_point - vcopy.get_start()) return vcopy def update_top_row_circle_copy(self, ccopy): ccopy.become(ccopy.original) ccopy.scale(self.top_row_copy_scale_factor) ccopy.move_to(ccopy.center_point) return ccopy def get_top_row_labels(self, vector_copies): labels = VGroup() for vector_copy in vector_copies: freq = vector_copy.freq label = Integer(freq) label.move_to(np.array([ freq * self.top_row_x_spacing, self.top_row_label_y, 0 ])) labels.add(label) return labels def setup_plane(self): plane = ComplexPlane(**self.plane_config) plane.shift(self.center_point) plane.add_coordinates() top_rect = Rectangle( width=FRAME_WIDTH, fill_color=BLACK, fill_opacity=1, stroke_width=0, height=self.top_rect_height, ) top_rect.to_edge(UP, buff=0) self.plane = plane self.add(plane) self.add(top_rect) def get_path_end(self, vectors, stroke_width=None, **kwargs): if stroke_width is None: stroke_width = self.drawn_path_st full_path = self.get_vector_sum_path(vectors, **kwargs) path = VMobject() path.set_stroke( self.drawn_path_color, stroke_width ) def update_path(p): alpha = self.get_vector_time() % 1 p.pointwise_become_partial( full_path, np.clip(alpha - 0.01, 0, 1), np.clip(alpha, 0, 1), ) p.get_points()[-1] = vectors[-1].get_end() path.add_updater(update_path) return path def get_drawn_path_alpha(self): return super().get_drawn_path_alpha() - 0.002 def get_drawn_path(self, vectors, stroke_width=2, **kwargs): odp = super().get_drawn_path(vectors, stroke_width, **kwargs) return VGroup( odp, self.get_path_end(vectors, stroke_width, **kwargs), ) def get_vertically_falling_tracing(self, vector, color, stroke_width=3, rate=0.25): path = VMobject() path.set_stroke(color, stroke_width) path.start_new_path(vector.get_end()) path.vector = vector def update_path(p, dt): p.shift(rate * dt * DOWN) p.add_smooth_curve_to(p.vector.get_end()) path.add_updater(update_path) return path class PiFourierSeries(ComplexFourierSeriesExample): CONFIG = { "tex": "\\pi", "n_vectors": 101, "path_height": 3.5, "max_circle_stroke_width": 1, "top_row_copy_scale_factor": 0.6, } def construct(self): self.setup_plane() self.add_vectors_circles_path() self.add_top_row(self.vectors, self.circles) for n in range(self.n_cycles): self.run_one_cycle() def get_path(self): pi = OldTex(self.tex) path = pi.family_members_with_points()[0] path.set_height(self.path_height) path.move_to(3 * DOWN, DOWN) path.set_stroke(YELLOW, 0) path.set_fill(opacity=0) return path class RealValuedFunctionFourierSeries(PiFourierSeries): CONFIG = { "n_vectors": 101, "start_drawn": True, } def construct(self): self.setup_plane() self.add_vectors_circles_path() self.add_top_row(self.vectors, self.circles) self.flatten_path() self.focus_on_vector_pair() def flatten_path(self): new_path = self.path.copy() new_path.stretch(0, 1) new_path.set_y(self.plane.n2p(0)[1]) self.vector_clock.set_value(10) self.transition_to_alt_path(new_path, morph_path=True) self.run_one_cycle() def focus_on_vector_pair(self): vectors = self.vectors circles = self.circles top_row = self.top_row top_vectors, top_circles, dots, labels = top_row rects1, rects2, rects3 = [ VGroup(*[ SurroundingRectangle(VGroup( top_circles[i], labels[i], )) for i in pair ]).set_stroke(GREY_B, 2) for pair in [(1, 2), (3, 4), (5, 6)] ] def get_opacity_animation(i1, i2, alpha_func): v_group = vectors[i1:i2] c_group = circles[i1:i2] return AnimationGroup( UpdateFromAlphaFunc( VectorizedPoint(), lambda m, a: v_group.set_opacity( alpha_func(a) ) ), UpdateFromAlphaFunc( VectorizedPoint(), lambda m, a: c_group.set_stroke( opacity=alpha_func(a) ) ), ) self.remove(self.path, self.drawn_path) self.play( get_opacity_animation( 3, len(vectors), lambda a: smooth(1 - a), ), ShowCreation(rects1, lag_ratio=0.3), ) traced_path2 = self.get_vertically_falling_tracing(vectors[2], GREEN) self.add(traced_path2) for n in range(3): self.run_one_cycle() self.play( get_opacity_animation(3, 5, smooth), get_opacity_animation( 0, 3, lambda a: 1 - 0.75 * smooth(a) ), ReplacementTransform(rects1, rects2), ) traced_path2.set_stroke(width=1) traced_path4 = self.get_vertically_falling_tracing(vectors[4], YELLOW) self.add(traced_path4) self.run_one_cycle() self.play( get_opacity_animation(5, 7, smooth), get_opacity_animation( 3, 5, lambda a: 1 - 0.75 * smooth(a) ), ReplacementTransform(rects2, rects3), ) traced_path2.set_stroke(width=1) traced_path4.set_stroke(width=1) traced_path6 = self.get_vertically_falling_tracing(vectors[6], TEAL) self.add(traced_path6) for n in range(2): self.run_one_cycle() class DemonstrateAddingArrows(PiFourierSeries): CONFIG = { "tex": "\\leftarrow", "n_arrows": 21, "parametric_function_step_size": 0.1, } def construct(self): self.setup_plane() self.add_vectors_circles_path() self.add_top_row(self.vectors, self.circles) circles = self.circles original_vectors = self.vectors vectors = VGroup(*[ Vector( **self.vector_config ).put_start_and_end_on(*v.get_start_and_end()) for v in original_vectors ]) original_top_vectors = self.top_row[0] top_vectors = VGroup(*[ Vector( **self.vector_config ).put_start_and_end_on(*v.get_start_and_end()) for v in original_top_vectors ]) self.plane.axes.set_stroke(GREY_B, 1) self.vector_clock.suspend_updating() self.remove(circles, original_vectors) self.remove(self.path, self.drawn_path) anims1 = [ TransformFromCopy(tv, v) for tv, v in zip(top_vectors, vectors) ] anims2 = [ ShowCreation(v) for v in vectors[len(top_vectors):25] ] self.play( LaggedStart(*anims1), run_time=3, lag_ratio=0.2, ) self.play( LaggedStart(*anims2), lag_ratio=0.1, run_time=5, ) class LabelRotatingVectors(PiFourierSeries): CONFIG = { "n_vectors": 6, "center_point": 1.5 * DOWN, "top_rect_height": 3, "plane_config": { "axis_config": { "unit_size": 1.75, "stroke_color": GREY_B, }, }, "top_row_x_spacing": 1.9, "top_row_center": 3 * UP + 0.2 * LEFT, } def construct(self): self.setup_plane() self.setup_top_row() self.ask_about_labels() self.initialize_at_one() self.show_complex_exponents() # self.show_complex_exponents_temp() self.tweak_initial_states() self.constant_examples() def setup_top_row(self): vectors = self.get_rotating_vectors( coefficients=0.5 * np.ones(self.n_vectors) ) circles = self.get_circles(vectors) top_row = self.get_top_row(vectors, circles) top_row.shift(0.5 * DOWN + 0.25 * RIGHT) v_copies, c_copies, dots, labels = top_row labels.to_edge(UP, MED_SMALL_BUFF) freq_label = OldTexText("Frequencies:") freq_label.to_edge(LEFT, MED_SMALL_BUFF) freq_label.match_y(labels) VGroup(freq_label, labels).set_color(YELLOW) def get_constant_func(const): return lambda: const for vector, v_copy in zip(vectors, v_copies): vector.center_func = get_constant_func( v_copy.get_start() ) vectors.update(0) circles.update(0) self.add(vectors) self.add(circles) self.add(dots) self.add(freq_label) self.add(labels) self.vectors = vectors self.circles = circles self.labels = labels self.freq_label = freq_label def ask_about_labels(self): circles = self.circles formulas = OldTexText("Formulas:") formulas.next_to(circles, DOWN) formulas.to_edge(LEFT, MED_SMALL_BUFF) q_marks = VGroup(*[ OldTex("??").scale(1.0).next_to(circle, DOWN) for circle in circles ]) self.play(FadeIn(formulas, DOWN)) self.play(LaggedStartMap( FadeInFrom, q_marks, lambda m: (m, UP), lag_ratio=0.2, run_time=3, )) self.wait(3) self.q_marks = q_marks self.formulas_word = formulas def initialize_at_one(self): vectors = self.vectors circles = self.circles vector_clock = self.vector_clock plane = self.plane q_marks = self.q_marks # Why so nuclear? vc_updater = vector_clock.updaters.pop() self.play( vector_clock.set_value, 0, run_time=2, ) zero_vect = Vector() zero_vect.replace(vectors[0]) zero_circle = self.get_circle(zero_vect) zero_circle.match_style(circles[0]) self.add(zero_circle) one_label = OldTex("1") one_label.move_to(q_marks[0]) self.play( zero_vect.put_start_and_end_on, plane.n2p(0), plane.n2p(1), ) vector_clock.add_updater(vc_updater) self.wait() self.play( FadeOut(q_marks[0], UP), FadeIn(one_label, DOWN), ) self.wait(4) self.one_label = one_label self.zero_vect = zero_vect self.zero_circle = zero_circle def show_complex_exponents(self): vectors = self.vectors circles = self.circles q_marks = self.q_marks labels = self.labels one_label = self.one_label v_lines = self.get_v_lines(circles) # Vector 1 v1_rect = SurroundingRectangle( VGroup(circles[1], q_marks[1], labels[1]), stroke_color=GREY, stroke_width=2, ) f1_exp = self.get_exp_tex() f1_exp.move_to(q_marks[1], DOWN) self.play( FadeOut(self.zero_vect), FadeOut(self.zero_circle), FadeIn(v1_rect) ) vg1 = self.get_vector_in_plane_group( vectors[1], circles[1], ) vg1_copy = vg1.copy() vg1_copy.clear_updaters() vg1_copy.replace(circles[1]) cps_1 = self.get_cps_label(1) circle_copy = vg1[1].copy().clear_updaters() circle_copy.set_stroke(YELLOW, 3) arclen_decimal = DecimalNumber( num_decimal_places=3, show_ellipsis=True, ) arclen_tracker = ValueTracker(0) arclen_decimal.add_updater(lambda m: m.next_to( circle_copy.get_end(), UR, SMALL_BUFF, )) arclen_decimal.add_updater(lambda m: m.set_value( arclen_tracker.get_value() )) self.play( ReplacementTransform(vg1_copy, vg1), ) self.play(FadeIn(cps_1, DOWN)) self.wait(2) self.play( FadeOut(q_marks[1], UP), FadeIn(f1_exp, DOWN), ) self.wait(2) self.play(ShowCreationThenFadeAround( f1_exp.get_part_by_tex("2\\pi") )) self.add(arclen_decimal), self.play( ShowCreation(circle_copy), arclen_tracker.set_value, TAU, run_time=3, ) self.wait() self.play( FadeOut(circle_copy), FadeOut(arclen_decimal), ) self.wait(8) self.play( v1_rect.move_to, circles[2], v1_rect.match_y, v1_rect, FadeOut(vg1), FadeOut(cps_1), ) # Vector -1 vgm1 = self.get_vector_in_plane_group( vectors[2], circles[2], ) vgm1_copy = vgm1.copy() vgm1_copy.clear_updaters() vgm1_copy.replace(circles[2]) cps_m1 = self.get_cps_label(-1) fm1_exp = self.get_exp_tex(-1) fm1_exp.move_to(q_marks[2], DOWN) self.play( ReplacementTransform(vgm1_copy, vgm1), FadeInFromDown(cps_m1) ) self.wait(2) self.play( FadeOut(q_marks[2], UP), FadeInFromDown(fm1_exp), v1_rect.stretch, 1.4, 0, ) self.wait(5) self.play( v1_rect.move_to, circles[3], v1_rect.match_y, v1_rect, FadeOut(vgm1), FadeOut(cps_m1), ) # Vector 2 # (Lots of copy-pasting here) vg2 = self.get_vector_in_plane_group( vectors[3], circles[3], ) vg2_copy = vg2.copy() vg2_copy.clear_updaters() vg2_copy.replace(circles[3]) cps_2 = self.get_cps_label(2) f2_exp = self.get_exp_tex(2) f2_exp.move_to(q_marks[3], DOWN) circle_copy.append_vectorized_mobject(circle_copy) self.play( ReplacementTransform(vg2_copy, vg2), FadeInFromDown(cps_2) ) self.wait() self.play( FadeOut(q_marks[3], UP), FadeInFromDown(f2_exp), ) self.wait(3) self.play(ShowCreationThenFadeAround( f2_exp.get_parts_by_tex("2"), )) self.add(arclen_decimal) arclen_tracker.set_value(0) self.play( ShowCreation(circle_copy), arclen_tracker.set_value, 2 * TAU, run_time=5 ) self.wait(3) self.play( FadeOut(circle_copy), FadeOut(arclen_decimal), ) self.play( FadeOut(vg2), FadeOut(cps_2), FadeOut(v1_rect), ) # Show all formulas fm2_exp = self.get_exp_tex(-2) fm2_exp.move_to(q_marks[4], DOWN) f3_exp = self.get_exp_tex(3) f3_exp.move_to(q_marks[5], DOWN) f1_exp_new = self.get_exp_tex(1) f1_exp_new.move_to(q_marks[1], DOWN) f0_exp = self.get_exp_tex(0) f0_exp.move_to(q_marks[0], DOWN) f_exp_general = self.get_exp_tex("n") f_exp_general.next_to(self.formulas_word, DOWN) self.play( FadeOut(q_marks[4:]), FadeOut(f1_exp), FadeIn(f1_exp_new), FadeInFromDown(fm2_exp), FadeInFromDown(f3_exp), FadeIn(v_lines, lag_ratio=0.2) ) self.play( FadeIn(f_exp_general, UP) ) self.play(ShowCreationThenFadeAround(f_exp_general)) self.wait(3) self.play( FadeOut(one_label, UP), TransformFromCopy(f_exp_general, f0_exp), ) self.wait(5) self.f_exp_labels = VGroup( f0_exp, f1_exp_new, fm1_exp, f2_exp, fm2_exp, f3_exp, ) self.f_exp_general = f_exp_general def show_complex_exponents_temp(self): self.f_exp_labels = VGroup(*[ self.get_exp_tex(n).move_to(qm, DOWN) for n, qm in zip( [0, 1, -1, 2, -2, 3], self.q_marks, ) ]) self.f_exp_general = self.get_exp_tex("n") self.f_exp_general.next_to(self.formulas_word, DOWN) self.remove(*self.q_marks, self.one_label) self.remove(self.zero_vect, self.zero_circle) self.add(self.f_exp_labels, self.f_exp_general) def tweak_initial_states(self): vector_clock = self.vector_clock f_exp_labels = self.f_exp_labels f_exp_general = self.f_exp_general vectors = self.vectors cn_terms = VGroup() for i, f_exp in enumerate(f_exp_labels): n = (i + 1) // 2 if i % 2 == 0 and i > 0: n *= -1 cn_terms.add(self.get_cn_label(n, f_exp)) cn_general = self.get_cn_label("n", f_exp_general) new_coefs = [ 0.5, np.exp(complex(0, TAU / 8)), 0.7 * np.exp(-complex(0, TAU / 8)), 0.6 * np.exp(complex(0, TAU / 3)), 1.1 * np.exp(-complex(0, TAU / 12)), 0.3 * np.exp(complex(0, TAU / 12)), ] def update_vectors(alpha): for vect, new_coef in zip(vectors, new_coefs): vect.coefficient = 0.5 * interpolate( 1, new_coef, alpha ) vector_clock.incrementer = vector_clock.updaters.pop() self.play( vector_clock.set_value, int(vector_clock.get_value()) ) self.play( LaggedStartMap( MoveToTarget, VGroup(f_exp_general, *f_exp_labels), ), LaggedStartMap( FadeInFromDown, VGroup(cn_general, *cn_terms), ), UpdateFromAlphaFunc( VectorizedPoint(), lambda m, a: update_vectors(a) ), run_time=2 ) self.wait() self.play( LaggedStart(*[ ShowCreationThenFadeAround( cn_term, surrounding_rectangle_config={ "buff": 0.05, "stroke_width": 2, }, ) for cn_term in cn_terms ]) ) self.cn_terms = cn_terms self.cn_general = cn_general def constant_examples(self): cn_terms = self.cn_terms vectors = self.vectors circles = self.circles # c0 term c0_brace = Brace(cn_terms[0], DOWN, buff=SMALL_BUFF) c0_label = OldTex("0.5") c0_label.next_to(c0_brace, DOWN, SMALL_BUFF) c0_label.add_background_rectangle() vip_group0 = self.get_vector_in_plane_group( vectors[0], circles[0] ) vip_group0_copy = vip_group0.copy() vip_group0_copy.clear_updaters() vip_group0_copy.replace(circles[0]) self.play( Transform(vip_group0_copy, vip_group0) ) self.wait() self.play(vip_group0_copy.scale, 2) self.play( vip_group0_copy.scale, 0.5, GrowFromCenter(c0_brace), GrowFromCenter(c0_label), ) self.wait(2) self.play( FadeOut(c0_brace), FadeOut(c0_label), FadeOut(vip_group0_copy), ) # c1 term c1_brace = Brace(cn_terms[1], DOWN, buff=SMALL_BUFF) c1_label = OldTex("e^{(\\pi / 4)i}") c1_label.next_to(c1_brace, DOWN, SMALL_BUFF) c1_decimal = DecimalNumber( np.exp(np.complex(0, PI / 4)), num_decimal_places=3, ) approx = OldTex("\\approx") approx.next_to(c1_label, RIGHT, MED_SMALL_BUFF) c1_decimal.next_to(approx, RIGHT, MED_SMALL_BUFF) scalar = DecimalNumber(0.3) scalar.next_to( c1_label, LEFT, SMALL_BUFF, aligned_edge=DOWN, ) vip_group1 = self.get_vector_in_plane_group( vectors[1], circles[1] ) vip_group1_copy = vip_group1.copy() vip_group1_copy[0].stroke_width = 3 vip_group1_copy.clear_updaters() vip_group1_copy.save_state() vip_group1_copy.replace(circles[1]) self.play( Restore(vip_group1_copy) ) self.play(Rotate(vip_group1_copy, -PI / 4)) self.play(Rotate(vip_group1_copy, PI / 4)) self.play( GrowFromCenter(c1_brace), FadeIn(c1_label), ) self.play( Write(approx), Write(c1_decimal), run_time=1, ) self.wait(2) def update_v1(alpha): vectors[1].coefficient = 0.5 * interpolate( np.exp(complex(0, PI / 4)), 0.3 * np.exp(complex(0, PI / 4)), alpha ) self.play( FadeIn(scalar), c1_decimal.set_value, scalar.get_value() * c1_decimal.get_value(), vip_group1_copy.scale, scalar.get_value(), UpdateFromAlphaFunc( VMobject(), lambda m, a: update_v1(a) ) ) self.wait() self.play( FadeOut(c1_brace), FadeOut(c1_label), FadeOut(approx), FadeOut(c1_decimal), FadeOut(scalar), FadeOut(vip_group1_copy), ) fade_anims = [] for cn_term, vect in zip(cn_terms[2:], vectors[2:]): rect = SurroundingRectangle(cn_term, buff=0.025) rect.set_stroke(width=2) decimal = DecimalNumber(vect.coefficient) decimal.next_to(rect, DOWN) decimal.add_background_rectangle() if cn_term is cn_terms[4]: decimal.shift(0.7 * RIGHT) self.play( ShowCreation(rect), FadeIn(decimal), *fade_anims ) self.wait() fade_anims = [FadeOut(rect), FadeOut(decimal)] self.play(*fade_anims) # def get_vector_in_plane_group(self, top_vector, top_circle): plane = self.plane origin = plane.n2p(0) vector = Vector() vector.add_updater( lambda v: v.put_start_and_end_on( origin, plane.n2p(2 * top_vector.coefficient) ).set_angle(top_vector.get_angle()) ) circle = Circle() circle.match_style(top_circle) circle.set_width(2 * vector.get_length()) circle.move_to(origin) return VGroup(vector, circle) def get_exp_tex(self, freq=None): if freq is None: freq_str = "{}" else: freq_str = "{" + str(freq) + "}" + "\\cdot" result = OldTex( "e^{", freq_str, "2\\pi i {t}}", tex_to_color_map={ "2\\pi": WHITE, "{t}": PINK, freq_str: YELLOW, } ) result.scale(0.9) return result def get_cn_label(self, n, exp_label): exp_label.generate_target() exp_label.target.scale(0.9) n_str = "{" + str(n) + "}" term = OldTex("c_", n_str) term.set_color(GREEN) term[1].set_color(YELLOW) term[1].set_width(0.12) term[1].move_to(term[0].get_corner(DR), LEFT) if isinstance(n, str): term[1].scale(1.4, about_edge=LEFT) term[1].shift(0.03 * RIGHT) elif n < 0: term[1].scale(1.4, about_edge=LEFT) term[1].set_stroke(width=0.5) else: term[1].shift(0.05 * RIGHT) term.scale(0.9) term.shift( exp_label.target[0].get_corner(LEFT) - term[0].get_corner(RIGHT) + 0.2 * LEFT ) VGroup(exp_label.target, term).move_to( exp_label, DOWN ) if isinstance(n, str): VGroup(term, exp_label.target).scale( 1.3, about_edge=UP ) return term def get_cps_label(self, n): n_str = str(n) if n == 1: frac_tex = "\\frac{\\text{cycle}}{\\text{second}}" else: frac_tex = "\\frac{\\text{cycles}}{\\text{second}}" result = OldTex( n_str, frac_tex, tex_to_color_map={ n_str: YELLOW }, ) result[1].scale(0.7, about_edge=LEFT) result[0].scale(1.2, about_edge=RIGHT) result.next_to(self.plane.n2p(2), UR) return result def get_v_lines(self, circles): lines = VGroup() o_circles = VGroup(*circles) o_circles.sort(lambda p: p[0]) for c1, c2 in zip(o_circles, o_circles[1:]): line = DashedLine(3 * UP, ORIGIN) line.set_stroke(WHITE, 1) line.move_to(midpoint( c1.get_center(), c2.get_center(), )) lines.add(line) return lines class IntegralTrick(LabelRotatingVectors, TRangingFrom0To1): CONFIG = { "file_name": "EighthNote", "n_vectors": 101, "path_height": 3.5, "plane_config": { "x_min": -1.75, "x_max": 1.75, "axis_config": { "unit_size": 1.75, "stroke_color": GREY_B, }, }, "center_point": 1.5 * DOWN + 3 * RIGHT, "input_space_rect_config": { "width": 6, "height": 1.5, }, "start_drawn": True, "parametric_function_step_size": 0.01, "top_row_center": 2 * UP + RIGHT, "top_row_x_spacing": 2.25, } def construct(self): self.setup_plane() self.add_vectors_circles_path() self.setup_input_space() self.setup_input_trackers() self.setup_top_row() self.setup_sum() self.introduce_sum() self.issolate_c0() self.show_center_of_mass() self.write_integral() def setup_input_space(self): super().setup_input_space() self.input_line.next_to( self.input_rect.get_bottom(), UP, ) group = VGroup( self.input_rect, self.input_line, ) group.move_to(self.plane.n2p(0)) group.to_edge(LEFT) def setup_top_row(self): top_row = self.get_top_row( self.vectors, self.circles, max_freq=2, ) self.top_vectors, self.top_circles, dots, labels = top_row self.add(*top_row) self.remove(labels) def setup_sum(self): top_vectors = self.top_vectors terms = VGroup() for vect in top_vectors: freq = vect.freq exp = self.get_exp_tex(freq) cn = self.get_cn_label(freq, exp) exp.become(exp.target) term = VGroup(cn, exp) term.move_to(vect.get_start()) term.shift(UP) terms.add(term) for vect in [LEFT, RIGHT]: dots = OldTex("\\cdots") dots.next_to(terms, vect, MED_LARGE_BUFF) terms.add(dots) plusses = VGroup() o_terms = VGroup(*terms) o_terms.sort(lambda p: p[0]) for t1, t2 in zip(o_terms, o_terms[1:]): plus = OldTex("+") plus.scale(0.7) plus.move_to(midpoint( t1.get_right(), t2.get_left(), )) plusses.add(plus) terms[:-2].shift(0.05 * UP) ft_eq = OldTex("f(t)", "= ") ft_eq.next_to(terms, LEFT) self.add(terms) self.add(plusses) self.add(ft_eq) self.terms = terms self.plusses = plusses self.ft_eq = ft_eq def introduce_sum(self): self.remove( self.vector_clock, self.vectors, self.circles, self.drawn_path, ) ft = self.ft_eq[0] terms = self.terms path = self.path input_tracker = self.input_tracker rect = SurroundingRectangle(ft) coefs = VGroup(*[term[0] for term in terms[:-2]]) terms_rect = SurroundingRectangle(terms) terms_rect.set_stroke(YELLOW, 1.5) dot = Dot() dot.add_updater(lambda d: d.move_to(path.get_end())) self.play(ShowCreation(rect)) self.wait() self.play( ReplacementTransform(rect, dot) ) path.set_stroke(YELLOW, 2) self.play( ShowCreation(path), input_tracker.set_value, 1, run_time=3, rate_func=lambda t: smooth(t, 1), ) self.wait() input_tracker.add_updater( lambda m: m.set_value( self.vector_clock.get_value() % 1 ) ) self.add( self.vector_clock, self.vectors, self.circles, ) self.play( FadeOut(path), FadeOut(dot), FadeIn(self.drawn_path), ) self.play(FadeIn(terms_rect)) self.wait() self.play(FadeOut(terms_rect)) fade_outs = [] for coef in coefs: rect = SurroundingRectangle(coef) self.play(FadeIn(rect), *fade_outs) fade_outs = [FadeOut(rect)] self.play(*fade_outs) self.wait(2) self.vector_clock.clear_updaters() def issolate_c0(self): vectors = self.vectors circles = self.circles terms = self.terms top_circles = self.top_circles path = self.path path.set_stroke(YELLOW, 1) c0_rect = SurroundingRectangle( VGroup(top_circles[0], terms[0]) ) c0_rect.set_stroke(WHITE, 1) opacity_tracker = ValueTracker(1) for vect in vectors[1:]: vect.add_updater( lambda v: v.set_opacity( opacity_tracker.get_value() ) ) for circle in circles[0:]: circle.add_updater( lambda c: c.set_stroke( opacity=opacity_tracker.get_value() ) ) self.play(ShowCreation(c0_rect)) self.play( opacity_tracker.set_value, 0.2, FadeOut(self.drawn_path), FadeIn(path) ) v0 = vectors[0] v0_point = VectorizedPoint(v0.get_end()) origin = self.plane.n2p(0) v0.add_updater(lambda v: v.put_start_and_end_on( origin, v0_point.get_location(), )) self.play( MaintainPositionRelativeTo(path, v0_point), ApplyMethod( v0_point.shift, 1.5 * LEFT, run_time=4, rate_func=there_and_back, path_arc=60 * DEGREES, ) ) v0.updaters.pop() self.opacity_tracker = opacity_tracker def show_center_of_mass(self): dot_sets = VGroup(*[ self.get_sample_dots(dt=dt, radius=radius) for dt, radius in [ (0.05, 0.04), (0.01, 0.03), (0.0025, 0.02), ] ]) input_dots, output_dots = dot_sets[0] v0_dot = input_dots[0].deepcopy() v0_dot.move_to(center_of_mass([ od.get_center() for od in output_dots ])) v0_dot.set_color(RED) self.play(LaggedStartMap( FadeInFromLarge, input_dots, lambda m: (m, 5), run_time=2, lag_ratio=0.5, )) self.wait() self.play( TransformFromCopy( input_dots, output_dots, run_time=3 ) ) self.wait() self.play(*[ Transform( od.copy(), v0_dot.copy(), remover=True ) for od in output_dots ]) self.add(v0_dot) self.wait() for ds1, ds2 in zip(dot_sets, dot_sets[1:]): ind1, outd1 = ds1 ind2, outd2 = ds2 new_v0_dot = v0_dot.copy() new_v0_dot.move_to(center_of_mass([ od.get_center() for od in outd2 ])) self.play( FadeOut(ind1), LaggedStartMap( FadeInFrom, ind2, lambda m: (m, UP), lag_ratio=4 / len(ind2), run_time=2, ) ) self.play( TransformFromCopy(ind2, outd2), FadeOut(outd1), run_time=2, ) self.play( FadeOut(v0_dot), *[ Transform( od.copy(), v0_dot.copy(), remover=True ) for od in outd2 ] ) v0_dot = new_v0_dot self.add(v0_dot) self.wait() self.input_dots, self.output_dots = dot_sets[-1] self.v0_dot = v0_dot def write_integral(self): t_tracker = self.vector_clock path = self.path expression = OldTex( "c_{0}", "=" "\\int_0^1 f({t}) d{t}", tex_to_color_map={ "{t}": PINK, "{0}": YELLOW, }, ) expression.next_to(self.input_rect, UP) brace = Brace(expression[2:], UP, buff=SMALL_BUFF) average = brace.get_text("Average", buff=SMALL_BUFF) self.play( FadeInFromDown(expression), GrowFromCenter(brace), FadeIn(average), ) t_tracker.clear_updaters() t_tracker.set_value(0) self.add(path) self.play( t_tracker.set_value, 0.999, ShowCreation(path), run_time=8, rate_func=lambda t: smooth(t, 1), ) self.wait() # def get_path(self): mob = SVGMobject(self.file_name) path = mob.family_members_with_points()[0] path.set_height(self.path_height) path.move_to(self.center_point) path.shift(0.5 * UR) path.set_stroke(YELLOW, 0) path.set_fill(opacity=0) return path def get_sample_dots(self, dt, radius): input_line = self.input_line path = self.path t_values = np.arange(0, 1 + dt, dt) dot = Dot(color=PINK, radius=radius) dot.set_stroke( RED, 1, opacity=0.8, background=True, ) input_dots = VGroup() output_dots = VGroup() for t in t_values: in_dot = dot.copy() out_dot = dot.copy() in_dot.move_to(input_line.n2p(t)) out_dot.move_to(path.point_from_proportion(t)) input_dots.add(in_dot) output_dots.add(out_dot) return VGroup(input_dots, output_dots) class IncreaseOrderOfApproximation(ComplexFourierSeriesExample): CONFIG = { "file_name": "FourierOneLine", "drawing_height": 6, "n_vectors": 250, "parametric_function_step_size": 0.001, "run_time": 10, # "n_vectors": 25, # "parametric_function_step_size": 0.01, # "run_time": 5, "slow_factor": 0.05, } def construct(self): path = self.get_path() path.to_edge(DOWN) path.set_stroke(YELLOW, 2) freqs = self.get_freqs() coefs = self.get_coefficients_of_path( path, freqs=freqs, ) vectors = self.get_rotating_vectors(freqs, coefs) circles = self.get_circles(vectors) n_tracker = ValueTracker(2) n_label = VGroup( OldTexText("Approximation using"), Integer(100).set_color(YELLOW), OldTexText("vectors") ) n_label.arrange(RIGHT) n_label.to_corner(UL) n_label.add_updater( lambda n: n[1].set_value( n_tracker.get_value() ).align_to(n[2], DOWN) ) changing_path = VMobject() vector_copies = VGroup() circle_copies = VGroup() def update_changing_path(cp): n = n_label[1].get_value() cp.become(self.get_vector_sum_path(vectors[:n])) cp.set_stroke(YELLOW, 2) # While we're at it... vector_copies.submobjects = list(vectors[:n]) circle_copies.submobjects = list(circles[:n]) changing_path.add_updater(update_changing_path) self.add(n_label, n_tracker, changing_path) self.add(vector_copies, circle_copies) self.play( n_tracker.set_value, self.n_vectors, rate_func=smooth, run_time=self.run_time, ) self.wait(5) class ShowStepFunctionIn2dView(SimpleComplexExponentExample, ComplexFourierSeriesExample): CONFIG = { "input_space_rect_config": { "width": 5, "height": 2, }, "input_line_config": { "unit_size": 3, "x_min": 0, "x_max": 1, "tick_frequency": 0.1, "stroke_width": 2, "decimal_number_config": { "num_decimal_places": 1, } }, "input_numbers": [0, 0.5, 1], "input_tex_args": [], # "n_vectors": 300, "n_vectors": 2, } def construct(self): self.setup_plane() self.setup_input_space() self.setup_input_trackers() self.clear() self.transition_from_step_function() self.show_output() self.show_fourier_series() def setup_input_space(self): super().setup_input_space() rect = self.input_rect line = self.input_line # rect.stretch(1.2, 1, about_edge=UP) line.shift(MED_SMALL_BUFF * UP) sf = 1.2 line.stretch(sf, 0) for n in line.numbers: n.stretch(1 / sf, 0) label = OldTexText("Input space") label.next_to(rect.get_bottom(), UP, SMALL_BUFF) self.add(label) self.input_space_label = label def transition_from_step_function(self): x_axis = self.input_line input_tip = self.input_tip input_label = self.input_label input_rect = self.input_rect input_space_label = self.input_space_label plane = self.plane plane.set_opacity(0) x_axis.save_state() # x_axis.center() x_axis.move_to(ORIGIN, LEFT) sf = 1.5 x_axis.stretch(sf, 0) for number in x_axis.numbers: number.stretch(1 / sf, 0) x_axis.numbers[0].set_opacity(0) y_axis = NumberLine( unit_size=2, x_min=-1.5, x_max=1.5, tick_frequency=0.5, stroke_color=GREY_B, stroke_width=2, ) # y_axis.match_style(x_axis) y_axis.rotate(90 * DEGREES) y_axis.shift(x_axis.n2p(0) - y_axis.n2p(0)) y_axis.add_numbers( -1, 0, 1, direction=LEFT, ) axes = Axes() axes.x_axis = x_axis axes.y_axis = y_axis axes.axes = VGroup(x_axis, y_axis) graph = VGroup( Line( axes.c2p(0, 1), axes.c2p(0.5, 1), color=RED, ), Line( axes.c2p(0.5, -1), axes.c2p(1, -1), color=BLUE, ), ) dot1 = Dot(color=RED) dot2 = Dot(color=BLUE) dot1.add_updater(lambda d: d.move_to(y_axis.n2p(1))) dot2.add_updater(lambda d: d.move_to(y_axis.n2p(-1))) squish_graph = VGroup(dot1, dot2) self.add(x_axis) self.add(y_axis) self.add(input_tip) self.add(input_label) self.play( self.input_tracker.set_value, 1, ShowCreation(graph), run_time=3, rate_func=lambda t: smooth(t, 1) ) self.wait() self.add( plane, input_rect, input_space_label, x_axis, input_tip, input_label, ) self.play( FadeIn(input_rect), FadeIn(input_space_label), Restore(x_axis), ) self.play(ReplacementTransform(graph, squish_graph)) # Rotate y-axis, fade in plane y_axis.generate_target(use_deepcopy=True) y_axis.target.rotate(-TAU / 4) y_axis.target.shift( plane.n2p(0) - y_axis.target.n2p(0) ) y_axis.target.numbers.set_opacity(0) plane.set_opacity(1) self.play( MoveToTarget(y_axis), ShowCreation(plane), ) self.play(FadeOut(y_axis)) self.wait() self.play(self.input_tracker.set_value, 0) self.output_dots = squish_graph def show_output(self): input_tracker = self.input_tracker def get_output_point(): return self.get_output_point(input_tracker.get_value()) tip = ArrowTip(start_angle=-TAU / 4) tip.set_fill(YELLOW) tip.match_height(self.input_tip) tip.add_updater(lambda m: m.move_to( get_output_point(), DOWN, )) output_label = OldTexText("Output") output_label.add_background_rectangle() output_label.add_updater(lambda m: m.next_to( tip, UP, SMALL_BUFF, )) self.play( FadeIn(tip), FadeIn(output_label), ) self.play( input_tracker.set_value, 1, run_time=8, rate_func=linear ) self.wait() self.play(input_tracker.set_value, 0) self.output_tip = tip def show_fourier_series(self): plane = self.plane input_tracker = self.input_tracker output_tip = self.output_tip self.play( plane.axes.set_stroke, WHITE, 1, plane.background_lines.set_stroke, GREY_B, 0.5, plane.faded_lines.set_stroke, GREY_B, 0.25, 0.5, ) self.vector_clock.set_value(0) self.add(self.vector_clock) input_tracker.add_updater(lambda m: m.set_value( self.vector_clock.get_value() % 1 )) self.add_vectors_circles_path() self.remove(self.drawn_path) self.add(self.vectors) output_tip.clear_updaters() output_tip.add_updater(lambda m: m.move_to( self.vectors[-1].get_end(), DOWN )) self.run_one_cycle() path = self.get_vertically_falling_tracing( self.vectors[1], GREEN, rate=0.5, ) self.add(path) for x in range(3): self.run_one_cycle() # def get_freqs(self): n = self.n_vectors all_freqs = [ *range(1, n + 1 // 2, 2), *range(-1, -n + 1 // 2, -2), ] all_freqs.sort(key=abs) return all_freqs def get_path(self): path = VMobject() p0, p1 = [ self.get_output_point(x) for x in [0, 1] ] for p in p0, p1: path.start_new_path(p) path.add_line_to(p) return path def get_output_point(self, x): return self.plane.n2p(self.step(x)) def step(self, x): if x < 0.5: return 1 elif x == 0.5: return 0 else: return -1 class AddVectorsOneByOne(IntegralTrick): CONFIG = { "file_name": "TrebleClef", # "start_drawn": True, "n_vectors": 101, "path_height": 5, } def construct(self): self.setup_plane() self.add_vectors_circles_path() self.setup_input_space() self.setup_input_trackers() self.setup_top_row() self.setup_sum() self.show_sum() def show_sum(self): vectors = self.vectors vector_clock = self.vector_clock terms = self.terms vector_clock.suspend_updating() coef_tracker = ValueTracker(0) def update_vector(vector): vector.coefficient = interpolate( 1, vector.original_coefficient, coef_tracker.get_value() ) for vector in vectors: vector.original_coefficient = vector.coefficient vector.add_updater(update_vector) rects = VGroup(*[ SurroundingRectangle(t[0]) for t in terms[:5] ]) self.remove(self.drawn_path) self.play(LaggedStartMap( VFadeInThenOut, rects )) self.play( coef_tracker.set_value, 1, run_time=3 ) self.wait() vector_clock.resume_updating() self.input_tracker.add_updater( lambda m: m.set_value(vector_clock.get_value() % 1) ) self.add(self.drawn_path, self.input_tracker) self.wait(10) def get_path(self): mob = SVGMobject(self.file_name) path = mob.family_members_with_points()[0] path.set_height(self.path_height) path.move_to(self.plane.n2p(0)) path.set_stroke(YELLOW, 0) path.set_fill(opacity=0) return path class DE4Thumbnail(ComplexFourierSeriesExample): CONFIG = { "file_name": "FourierOneLine", "start_drawn": True, "n_vectors": 300, "parametric_function_step_size": 0.0025, "drawn_path_stroke_width": 7, "drawing_height": 6, } def construct(self): path = self.get_path() path.to_edge(DOWN) path.set_stroke(YELLOW, 2) freqs = self.get_freqs() coefs = self.get_coefficients_of_path(path, freqs=freqs) vectors = self.get_rotating_vectors(freqs, coefs) circles = self.get_circles(vectors) ns = [10, 50, 250] approxs = VGroup(*[ self.get_vector_sum_path(vectors[:n]) for n in ns ]) approxs.set_height(4) approxs.arrange(RIGHT, buff=1.0) approxs.set_width(FRAME_WIDTH - 2) # approxs.set_y(-0.5) for a, c, w in zip(approxs, [BLUE, GREEN, YELLOW], [4, 3, 2]): shadows = VGroup() for w2 in zip(np.linspace(1, 15, 10)): shadow = a.deepcopy() shadow.set_stroke(c, w2, opacity=0.05) shadows.add(shadow) a.set_stroke(c, w) # a.set_stroke(c, w + w / 2, background=True) # a.add_to_back(shadows) self.add(shadows) labels = VGroup() for n, approx in zip(ns, approxs): label = OldTex("n = ", str(n)) label[1].match_color(approx) label.scale(2) label.next_to(approx, UP, MED_LARGE_BUFF) label.shift_onto_screen() labels.add(label) for label in labels: label.align_to(labels[-1], DOWN) title = Text("Drawn with circles") title.set_width(FRAME_WIDTH - 4) title.next_to(approxs, DOWN) title.shift_onto_screen(buff=0.1) title.set_stroke(WHITE, 1) self.add(approxs) self.add(labels) self.add(title) return # Old name = OldTexText("Fourier series") name.to_edge(UP) name.set_color(YELLOW) subname = OldTexText("a.k.a ``everything is rotations''") subname.match_width(name) subname.next_to(name, DOWN, SMALL_BUFF) names = VGroup(name, subname) names.set_width(8) names.to_edge(DOWN, buff=MED_SMALL_BUFF) self.add_vectors_circles_path() n = 6 self.circles[n:].set_opacity(0) self.circles[:n].set_stroke(width=3) path = self.drawn_path # path.set_stroke(BLACK, 8, background=True) # path = self.path # path.set_stroke(YELLOW, 5) # path.set_stroke(BLACK, 8, background=True) self.add(path, self.circles, self.vectors) self.update_mobjects(0)
from manim_imports_ext import * class GeneralizeToComplexFunctions(Scene): CONFIG = { "axes_config": { "x_min": 0, "x_max": 10, "x_axis_config": { "stroke_width": 2, }, "y_min": -2.5, "y_max": 2.5, "y_axis_config": { "tick_frequency": 0.25, "unit_size": 1.5, "include_tip": False, "stroke_width": 2, }, }, "complex_plane_config": { "axis_config": { "unit_size": 2 } }, } def construct(self): self.show_cosine_wave() self.transition_to_complex_plane() self.add_rotating_vectors_making_cos() def show_cosine_wave(self): axes = Axes(**self.axes_config) axes.shift(2 * LEFT - axes.c2p(0, 0)) y_axis = axes.y_axis y_labels = y_axis.get_number_mobjects( *range(-2, 3), num_decimal_places=1 ) t_tracker = ValueTracker(0) t_tracker.add_updater(lambda t, dt: t.increment_value(dt)) get_t = t_tracker.get_value def func(x): return 2 * np.cos(x) cos_x_max = 20 cos_wave = axes.get_graph(func, x_max=cos_x_max) cos_wave.set_color(YELLOW) shown_cos_wave = cos_wave.copy() shown_cos_wave.add_updater( lambda m: m.pointwise_become_partial( cos_wave, 0, np.clip(get_t() / cos_x_max, 0, 1), ), ) dot = Dot() dot.set_color(PINK) dot.add_updater(lambda d: d.move_to( y_axis.n2p(func(get_t())), )) h_line = always_redraw(lambda: Line( dot.get_right(), shown_cos_wave.get_end(), stroke_width=1, )) real_words = OldTexText( "Real number\\\\output" ) real_words.to_edge(LEFT) real_words.shift(2 * UP) real_arrow = Arrow() real_arrow.add_updater( lambda m: m.put_start_and_end_on( real_words.get_corner(DR), dot.get_center(), ).scale(0.9), ) self.add(t_tracker) self.add(axes) self.add(y_labels) self.add(shown_cos_wave) self.add(dot) self.add(h_line) self.wait(2) self.play( FadeIn(real_words, RIGHT), FadeIn(real_arrow), ) self.wait(5) y_axis.generate_target() y_axis.target.rotate(-90 * DEGREES) y_axis.target.center() y_axis.target.scale(2 / 1.5) y_labels.generate_target() for label in y_labels.target: label.next_to( y_axis.target.n2p(label.get_value()), DOWN, MED_SMALL_BUFF, ) self.play( FadeOut(shown_cos_wave), FadeOut(axes.x_axis), FadeOut(h_line), ) self.play( MoveToTarget(y_axis), MoveToTarget(y_labels), real_words.shift, 2 * RIGHT + UP, ) self.wait() self.y_axis = y_axis self.y_labels = y_labels self.real_words = real_words self.real_arrow = real_arrow self.dot = dot self.t_tracker = t_tracker def transition_to_complex_plane(self): y_axis = self.y_axis y_labels = self.y_labels plane = self.get_complex_plane() plane_words = plane.label self.add(plane, *self.get_mobjects()) self.play( FadeOut(y_labels), FadeOut(y_axis), ShowCreation(plane), ) self.play(Write(plane_words)) self.wait() self.plane = plane self.plane_words = plane_words def add_rotating_vectors_making_cos(self): plane = self.plane real_words = self.real_words real_arrow = self.real_arrow t_tracker = self.t_tracker get_t = t_tracker.get_value v1 = Vector(2 * RIGHT) v2 = Vector(2 * RIGHT) v1.set_color(BLUE) v2.set_color(interpolate_color(GREY_BROWN, WHITE, 0.5)) v1.add_updater( lambda v: v.set_angle(get_t()) ) v2.add_updater( lambda v: v.set_angle(-get_t()) ) v1.add_updater( lambda v: v.shift(plane.n2p(0) - v.get_start()) ) # Change? v2.add_updater( lambda v: v.shift(plane.n2p(0) - v.get_start()) ) ghost_v1 = v1.copy() ghost_v1.set_opacity(0.5) ghost_v1.add_updater( lambda v: v.shift( v2.get_end() - v.get_start() ) ) ghost_v2 = v2.copy() ghost_v2.set_opacity(0.5) ghost_v2.add_updater( lambda v: v.shift( v1.get_end() - v.get_start() ) ) circle = Circle(color=GREY_BROWN) circle.set_stroke(width=1) circle.set_width(2 * v1.get_length()) circle.move_to(plane.n2p(0)) formula = OldTex( # "\\cos(x) =" # "{1 \\over 2}e^{ix} +" # "{1 \\over 2}e^{-ix}", "2\\cos(x) =", "e^{ix}", "+", "e^{-ix}", tex_to_color_map={ "e^{ix}": v1.get_color(), "e^{-ix}": v2.get_color(), } ) formula.next_to(ORIGIN, UP, buff=0.75) # formula.add_background_rectangle() formula.set_stroke(BLACK, 3, background=True) formula.to_edge(LEFT, buff=MED_SMALL_BUFF) formula_brace = Brace(formula[1:], UP) formula_words = formula_brace.get_text( "Sum of\\\\rotations" ) formula_words.set_stroke(BLACK, 3, background=True) randy = Randolph() randy.to_corner(DL) randy.look_at(formula) self.play( FadeOut(real_words), FadeOut(real_arrow), ) self.play( FadeIn(v1), FadeIn(v2), FadeIn(circle), FadeIn(ghost_v1), FadeIn(ghost_v2), ) self.wait(3) self.play(FadeInFromDown(formula)) self.play( GrowFromCenter(formula_brace), FadeIn(formula_words), ) self.wait(2) self.play(FadeIn(randy)) self.play(randy.change, "pleading") self.play(Blink(randy)) self.wait() self.play(randy.change, "confused") self.play(Blink(randy)) self.wait() self.play(FadeOut(randy)) self.wait(20) # def get_complex_plane(self): plane = ComplexPlane(**self.complex_plane_config) plane.add_coordinates() plane.label = OldTexText("Complex plane") plane.label.scale(1.5) plane.label.to_corner(UR, buff=MED_SMALL_BUFF) return plane class ClarifyInputAndOutput(GeneralizeToComplexFunctions): CONFIG = { "input_space_rect_config": { "stroke_color": WHITE, "stroke_width": 1, "fill_color": GREY_E, "fill_opacity": 1, "width": 6, "height": 2, }, } def construct(self): self.setup_plane() self.setup_input_space() self.setup_input_trackers() self.describe_input() self.describe_output() def setup_plane(self): plane = self.get_complex_plane() plane.sublabel = OldTexText("(Output space)") plane.sublabel.add_background_rectangle() plane.sublabel.next_to(plane.label, DOWN) self.add(plane, plane.label) self.plane = plane def setup_input_space(self): rect = Rectangle(**self.input_space_rect_config) rect.to_corner(UL, buff=SMALL_BUFF) input_line = self.get_input_line(rect) input_words = OldTexText("Input space") input_words.next_to( rect.get_bottom(), UP, SMALL_BUFF, ) self.add(rect) self.add(input_line) self.input_rect = rect self.input_line = input_line self.input_words = input_words def setup_input_trackers(self): plane = self.plane input_line = self.input_line input_tracker = ValueTracker(0) get_input = input_tracker.get_value input_dot = Dot() input_dot.set_color(PINK) f_always( input_dot.move_to, lambda: input_line.n2p(get_input()) ) input_decimal = DecimalNumber() input_decimal.scale(0.7) always(input_decimal.next_to, input_dot, UP) f_always(input_decimal.set_value, get_input) path = self.get_path() def get_output_point(): return path.point_from_proportion( get_input() ) output_dot = Dot() output_dot.match_style(input_dot) f_always(output_dot.move_to, get_output_point) output_vector = Vector() output_vector.set_color(WHITE) output_vector.add_updater( lambda v: v.put_start_and_end_on( plane.n2p(0), get_output_point() ) ) output_decimal = DecimalNumber() output_decimal.scale(0.7) always(output_decimal.next_to, output_dot, UR, SMALL_BUFF) f_always( output_decimal.set_value, lambda: plane.p2n(get_output_point()), ) self.input_tracker = input_tracker self.input_dot = input_dot self.input_decimal = input_decimal self.path = path self.output_dot = output_dot self.output_vector = output_vector self.output_decimal = output_decimal def describe_input(self): input_tracker = self.input_tracker self.play(FadeIn(self.input_words, UP)) self.play( FadeInFromLarge(self.input_dot), FadeIn(self.input_decimal), ) for value in 1, 0: self.play( input_tracker.set_value, value, run_time=2 ) self.wait() def describe_output(self): path = self.path output_dot = self.output_dot output_decimal = self.output_decimal input_dot = self.input_dot input_tracker = self.input_tracker plane = self.plane real_line = plane.x_axis.copy() real_line.set_stroke(RED, 4) real_words = OldTexText("Real number line") real_words.next_to(ORIGIN, UP) real_words.to_edge(RIGHT) traced_path = TracedPath(output_dot.get_center) traced_path.match_style(path) self.play( ShowCreation(real_line), FadeIn(real_words, DOWN) ) self.play( FadeOut(real_line), FadeOut(real_words), ) self.play( FadeIn(plane.sublabel, UP) ) self.play( FadeIn(output_decimal), TransformFromCopy(input_dot, output_dot), ) kw = { "run_time": 10, "rate_func": lambda t: smooth(t, 1), } self.play( ApplyMethod(input_tracker.set_value, 1, **kw), ShowCreation(path.copy(), remover=True, **kw), ) self.add(path) self.add(output_dot) self.wait() # Flatten to 1d real_function_word = OldTexText( "Real-valued function" ) real_function_word.next_to(ORIGIN, DOWN, MED_LARGE_BUFF) path.generate_target() path.target.stretch(0, 1) path.target.move_to(plane.n2p(0)) self.play( FadeIn(real_function_word), MoveToTarget(path), ) input_tracker.set_value(0) self.play( input_tracker.set_value, 1, **kw ) # def get_input_line(self, input_rect): input_line = UnitInterval() input_line.move_to(input_rect) input_line.shift(0.25 * UP) input_line.set_width( input_rect.get_width() - 1 ) input_line.add_numbers(0, 0.5, 1) return input_line def get_path(self): # mob = SVGMobject("BatmanLogo") mob = OldTex("\\pi") path = mob.family_members_with_points()[0] path.set_height(3.5) path.move_to(2 * DOWN, DOWN) path.set_stroke(YELLOW, 2) path.set_fill(opacity=0) return path class GraphForFlattenedPi(ClarifyInputAndOutput): CONFIG = { "camera_config": {"background_color": GREY_E}, } def construct(self): self.setup_plane() plane = self.plane self.remove(plane, plane.label) path = self.get_path() axes = Axes( x_min=0, x_max=1, x_axis_config={ "unit_size": 7, "include_tip": False, "tick_frequency": 0.1, }, y_min=-1.5, y_max=1.5, y_axis_config={ "include_tip": False, "unit_size": 2.5, "tick_frequency": 0.5, }, ) axes.set_width(FRAME_WIDTH - 1) axes.set_height(FRAME_HEIGHT - 1, stretch=True) axes.center() axes.x_axis.add_numbers( 0.5, 1.0, num_decimal_places=1, ) axes.y_axis.add_numbers( -1.0, 1.0, num_decimal_places=1 ) def func(t): return plane.x_axis.p2n( path.point_from_proportion(t) ) graph = axes.get_graph(func) graph.set_color(PINK) v_line = always_redraw(lambda: Line( axes.x_axis.n2p(axes.x_axis.p2n(graph.get_end())), graph.get_end(), stroke_width=1, )) self.add(axes) self.add(v_line) kw = { "run_time": 10, "rate_func": lambda t: smooth(t, 1), } self.play(ShowCreation(graph, **kw)) self.wait() class SimpleComplexExponentExample(ClarifyInputAndOutput): CONFIG = { "input_space_rect_config": { "width": 14, "height": 1.5, }, "input_line_config": { "unit_size": 0.5, "x_min": 0, "x_max": 25, "stroke_width": 2, }, "input_numbers": range(0, 30, 5), "input_tex_args": ["t", "="], } def construct(self): self.setup_plane() self.setup_input_space() self.setup_input_trackers() self.setup_output_trackers() # Testing time = self.input_line.x_max self.play( self.input_tracker.set_value, time, run_time=time, rate_func=linear, ) def setup_plane(self): plane = ComplexPlane() plane.scale(2) plane.add_coordinates() plane.shift(DOWN) self.plane = plane self.add(plane) def setup_input_trackers(self): input_line = self.input_line input_tracker = ValueTracker(0) get_input = input_tracker.get_value input_tip = ArrowTip(start_angle=-TAU / 4) input_tip.scale(0.5) input_tip.set_color(PINK) f_always( input_tip.move_to, lambda: input_line.n2p(get_input()), lambda: DOWN, ) input_label = VGroup( OldTex(*self.input_tex_args), DecimalNumber(), ) input_label[0].set_color_by_tex("t", PINK) input_label.scale(0.7) input_label.add_updater( lambda m: m.arrange(RIGHT, buff=SMALL_BUFF) ) input_label.add_updater( lambda m: m[1].set_value(get_input()) ) input_label.add_updater( lambda m: m.next_to(input_tip, UP, SMALL_BUFF) ) self.input_tracker = input_tracker self.input_tip = input_tip self.input_label = input_label self.add(input_tip, input_label) def setup_output_trackers(self): plane = self.plane get_input = self.input_tracker.get_value def get_output(): return np.exp(complex(0, get_input())) def get_output_point(): return plane.n2p(get_output()) output_label, static_output_label = [ OldTex( "e^{i t}" + s, tex_to_color_map={"t": PINK}, background_stroke_width=3, ) for s in ["", "\\approx"] ] output_label.scale(1.2) output_label.add_updater( lambda m: m.shift( -m.get_bottom() + get_output_point() + rotate_vector( 0.35 * RIGHT, get_input(), ) ) ) output_vector = Vector() output_vector.set_opacity(0.75) output_vector.add_updater( lambda m: m.put_start_and_end_on( plane.n2p(0), get_output_point(), ) ) t_max = 40 full_output_path = ParametricCurve( lambda t: plane.n2p(np.exp(complex(0, t))), t_min=0, t_max=t_max ) output_path = VMobject() output_path.set_stroke(YELLOW, 2) output_path.add_updater( lambda m: m.pointwise_become_partial( full_output_path, 0, get_input() / t_max, ) ) static_output_label.next_to(plane.c2p(1, 1), UR) output_decimal = DecimalNumber( include_sign=True, ) output_decimal.scale(0.8) output_decimal.set_stroke(BLACK, 3, background=True) output_decimal.add_updater( lambda m: m.set_value(get_output()) ) output_decimal.add_updater( lambda m: m.next_to( static_output_label, RIGHT, 2 * SMALL_BUFF, aligned_edge=DOWN, ) ) self.add(output_path) self.add(output_vector) self.add(output_label) self.add(static_output_label) self.add(BackgroundRectangle(output_decimal)) self.add(output_decimal) # def get_input_line(self, input_rect): input_line = NumberLine(**self.input_line_config) input_line.move_to(input_rect) input_line.set_width( input_rect.get_width() - 1.5, stretch=True, ) input_line.add_numbers(*self.input_numbers) return input_line class TRangingFrom0To1(SimpleComplexExponentExample): CONFIG = { "input_space_rect_config": { "width": 6, "height": 2, }, } def construct(self): self.setup_input_space() self.setup_input_trackers() self.play( self.input_tracker.set_value, 1, run_time=10, rate_func=linear ) def get_input_line(self, rect): result = ClarifyInputAndOutput.get_input_line(self, rect) result.stretch(0.9, 0) result.set_stroke(width=2) for sm in result.get_family(): if isinstance(sm, DecimalNumber): sm.stretch(1 / 0.9, 0) sm.set_stroke(width=0) return result
from manim_imports_ext import * from _2019.diffyq.part1.staging import TourOfDifferentialEquations class PartTwoOfTour(TourOfDifferentialEquations): CONFIG = { "zoomed_thumbnail_index": 1, } def construct(self): self.add_title() self.show_thumbnails() self.zoom_in_to_one_thumbnail() def zoom_in_to_one_thumbnail(self): frame = self.camera_frame thumbnails = self.thumbnails ode = OldTexText("Ordinary\\\\", "Differential Equation") pde = OldTexText("Partial\\\\", "Differential Equation") for word, thumbnail, vect in zip([ode, pde], thumbnails, [DOWN, UP]): word.match_width(thumbnail) word.next_to(thumbnail, vect) ode[0].set_color(BLUE) pde[0].set_color(YELLOW) self.add(ode) frame.save_state() self.play( frame.replace, thumbnails[0], run_time=1, ) self.play( Restore(frame, run_time=3), ) self.play( TransformFromCopy(ode, pde), ) self.play( ApplyMethod( frame.replace, thumbnails[1], path_arc=(-30 * DEGREES), run_time=3 ), ) self.wait() class BrownianMotion(Scene): CONFIG = { "wait_time": 60, "L": 3, # Box in [-L, L] x [-L, L] "n_particles": 100, "m1": 1, "m2": 100, "r1": 0.05, "r2": 0.5, "max_v": 5, "random_seed": 2, } def construct(self): self.add_title() self.add_particles() self.wait(self.wait_time) def add_title(self): square = Square(side_length=2 * self.L) title = OldTexText("Brownian motion") title.scale(1.5) title.next_to(square, UP) self.add(square) self.add(title) def add_particles(self): m1 = self.m1 m2 = self.m2 r1 = self.r1 r2 = self.r2 L = self.L max_v = self.max_v n_particles = self.n_particles lil_particles = VGroup(*[ self.get_particle(m1, r1, L, max_v) for k in range(n_particles) ]) big_particle = self.get_particle(m2, r2, L=r2, max_v=0) big_particle.set_fill(YELLOW, 1) for p in lil_particles: if self.are_colliding(p, big_particle): lil_particles.remove(p) all_particles = VGroup(big_particle, *lil_particles) all_particles.add_updater(self.update_particles) path = self.get_traced_path(big_particle) self.add(all_particles) self.add(path) self.particles = all_particles self.big_particle = big_particle self.path = path def get_particle(self, m, r, L, max_v): dot = Dot(radius=r) dot.set_fill(WHITE, 0.7) dot.mass = m dot.radius = r dot.center = op.add( np.random.uniform(-L + r, L - r) * RIGHT, np.random.uniform(-L + r, L - r) * UP ) dot.move_to(dot.center) dot.velocity = rotate_vector( np.random.uniform(0, max_v) * RIGHT, np.random.uniform(0, TAU), ) return dot def are_colliding(self, p1, p2): d = get_norm(p1.get_center() - p2.get_center()) return (d < p1.radius + p2.radius) def get_traced_path(self, particle): path = VMobject() path.set_stroke(BLUE, 3) path.start_new_path(particle.get_center()) buff = 0.02 def update_path(path): new_point = particle.get_center() if get_norm(new_point - path.get_last_point()) > buff: path.add_line_to(new_point) path.add_updater(update_path) return path def update_particles(self, particles, dt): for p1 in particles: p1.center += p1.velocity * dt # Check particle collisions buff = 0.01 for p2 in particles: if p1 is p2: continue v = p2.center - p1.center dist = get_norm(v) r_sum = p1.radius + p2.radius diff = dist - r_sum if diff < 0: unit_v = v / dist p1.center += (diff - buff) * unit_v / 2 p2.center += -(diff - buff) * unit_v / 2 u1 = p1.velocity u2 = p2.velocity m1 = p1.mass m2 = p2.mass v1 = ( (m2 * (u2 - u1) + m1 * u1 + m2 * u2) / (m1 + m2) ) v2 = ( (m1 * (u1 - u2) + m1 * u1 + m2 * u2) / (m1 + m2) ) p1.velocity = v1 p2.velocity = v2 # Check edge collisions r1 = p1.radius c1 = p1.center for i in [0, 1]: if abs(c1[i]) + r1 > self.L: c1[i] = np.sign(c1[i]) * (self.L - r1) p1.velocity[i] *= -1 * op.mul( np.sign(p1.velocity[i]), np.sign(c1[i]) ) for p in particles: p.move_to(p.center) return particles class AltBrownianMotion(BrownianMotion): CONFIG = { "wait_time": 20, "n_particles": 100, "m2": 10, } class BlackScholes(AltBrownianMotion): def construct(self): # For some reason I'm amused by the thought # Of this graph perfectly matching the Brownian # Motion y-coordiante self.add_title() self.add_particles() self.particles.set_opacity(0) self.remove(self.path) self.add_graph() self.wait(self.wait_time) def add_title(self): title = OldTexText("Black-Scholes equations") title.scale(1.5) title.next_to(2 * UP, UP) equation = OldTex( "{\\partial V \\over \\partial t}", "+", "\\frac{1}{2} \\sigma^2 S^2", "{\\partial^2 V \\over \\partial S^2}", "+", "rS", "{\\partial V \\over \\partial S}", "-rV", "=", "0", ) equation.scale(0.8) equation.next_to(title, DOWN) self.add(title) self.add(equation) self.title = title self.equation = equation def add_graph(self): axes = Axes( x_min=-1, x_max=20, y_min=0, y_max=10, axis_config={ "unit_size": 0.5, }, ) axes.set_height(4) axes.move_to(DOWN) def get_graph_point(): return axes.c2p( self.get_time(), 5 + 2 * self.big_particle.get_center()[1] ) graph = VMobject() graph.match_style(self.path) graph.start_new_path(get_graph_point()) graph.add_updater( lambda g: g.add_line_to(get_graph_point()) ) self.add(axes) self.add(graph) class ContrastChapters1And2(Scene): def construct(self): c1_frame, c2_frame = frames = VGroup(*[ ScreenRectangle(height=3.5) for x in range(2) ]) frames.arrange(RIGHT, buff=LARGE_BUFF) c1_title, c2_title = titles = VGroup( OldTexText("Chapter 1"), OldTexText("Chapter 2"), ) titles.scale(1.5) ode, pde = des = VGroup( OldTexText( "Ordinary", "Differential Equations\\\\", "ODEs", ), OldTexText( "Partial", "Differential Equations\\\\", "PDEs", ), ) ode[0].set_color(BLUE) pde[0].set_color(YELLOW) for de in des: de[-1][0].match_color(de[0]) de[-1].scale(1.5, about_point=de.get_top()) for title, frame, de in zip(titles, frames, des): title.next_to(frame, UP) de.match_width(frame) de.next_to(frame, DOWN) lt = OldTex("<") lt.move_to(Line(ode.get_right(), pde.get_left())) lt.scale(2, about_edge=UP) c1_words = OldTexText( "They're", "really\\\\", "{}", "freaking", "hard\\\\", "to", "solve\\\\", ) c1_words.set_height(0.5 * c1_frame.get_height()) c1_words.move_to(c1_frame) c2_words = OldTexText( "They're", "really", "\\emph{really}\\\\", "freaking", "hard\\\\", "to", "solve\\\\", ) c2_words.set_color_by_tex("\\emph", YELLOW) c2_words.move_to(c2_frame) edit_shift = MED_LARGE_BUFF * RIGHT c2_edits = VGroup( OldTexText("sometimes").next_to( c2_words[1:3], UP, aligned_edge=LEFT, ), Line( c2_words[1].get_left(), c2_words[2].get_right(), stroke_width=8, ), OldTexText("not too").next_to( c2_words[3], LEFT, ), Line( c2_words[3].get_left(), c2_words[3].get_right(), stroke_width=8, ), ) c2_edits.set_color(RED) c2_edits[2:].shift(edit_shift) self.add(titles) self.add(frames) self.add(des) self.wait() self.play(LaggedStartMap( FadeInFromDown, c1_words, lag_ratio=0.1, )) self.wait() # self.play(FadeIn(ode)) self.play( # TransformFromCopy(ode, pde), TransformFromCopy(c1_words, c2_words), Write(lt) ) self.wait() self.play( Write(c2_edits[:2], run_time=1), ) self.play( c2_words[3:5].shift, edit_shift, Write(c2_edits[2:]), run_time=1, ) self.wait() class ShowCubeFormation(ThreeDScene): CONFIG = { "camera_config": { "shading_factor": 1.0, }, "color": False, } def construct(self): light_source = self.camera.light_source light_source.move_to(np.array([-6, -3, 6])) cube = Cube( side_length=4, fill_color=GREY, stroke_color=WHITE, stroke_width=0.5, ) cube.set_fill(opacity=1) if self.color: # cube[0].set_color(BLUE) # cube[1].set_color(RED) # for face in cube[2:]: # face.set_color([BLUE, RED]) cube.color_using_background_image("VerticalTempGradient") # light_source.next_to(cube, np.array([1, -1, 1]), buff=2) cube_3d = cube.copy() cube_2d = cube_3d.copy().stretch(0, 2) cube_1d = cube_2d.copy().stretch(0, 1) cube_0d = cube_1d.copy().stretch(0, 0) cube.become(cube_0d) self.set_camera_orientation( phi=70 * DEGREES, theta=-145 * DEGREES, ) self.begin_ambient_camera_rotation(rate=0.05) for target in [cube_1d, cube_2d, cube_3d]: self.play( Transform(cube, target, run_time=1.5) ) self.wait(8) class ShowCubeFormationWithColor(ShowCubeFormation): CONFIG = { "color": True, } class ShowRect(Scene): CONFIG = { "height": 1, "width": 3, } def construct(self): rect = Rectangle( height=self.height, width=self.width, ) rect.set_color(YELLOW) self.play(ShowCreationThenFadeOut(rect)) class ShowSquare(ShowRect): CONFIG = { "height": 1, "width": 1, } class ShowHLine(Scene): def construct(self): line = Line(LEFT, RIGHT) line.set_color(BLUE) self.play(ShowCreationThenFadeOut(line)) class ShowCross(Scene): def construct(self): cross = Cross(Square()) cross.set_width(3) cross.set_height(1, stretch=True) self.play(ShowCreation(cross)) class TwoBodyEquations(Scene): def construct(self): kw = { "tex_to_color_map": { "x_1": GREY_B, "y_1": GREY_B, "x_2": BLUE, "y_2": BLUE, "=": WHITE, } } equations = VGroup( OldTex( "{d^2 x_1 \\over dt^2}", "=", "{x_2 - x_1 \\over m_1 \\left(", "(x_2 - x_1)^2 + (y_2 - y_1)^2", "\\right)^{3/2}", **kw ), OldTex( "{d^2 y_1 \\over dt^2}", "=", "{y_2 - y_1 \\over m_1 \\left(", "(x_2 - x_1)^2 + (y_2 - y_1)^2", "\\right)^{3/2}", **kw ), OldTex( "{d^2 x_2 \\over dt^2}", "=", "{x_1 - x_2 \\over m_2 \\left(", "(x_2 - x_1)^2 + (y_2 - y_1)^2", "\\right)^{3/2}", **kw ), OldTex( "{d^2 y_2 \\over dt^2}", "=", "{y_1 - y_2 \\over m_2 \\left(", "(x_2 - x_1)^2 + (y_2 - y_1)^2", "\\right)^{3/2}", **kw ), ) equations.arrange(DOWN, buff=LARGE_BUFF) equations.set_height(6) equations.to_edge(LEFT) variables = VGroup() lhss = VGroup() rhss = VGroup() for equation in equations: variable = equation[1] lhs = equation[:4] rhs = equation[4:] variables.add(variable) lhss.add(lhs) rhss.add(rhs) lhss_copy = lhss.copy() for variable, lhs in zip(variables, lhss): variable.save_state() variable.match_height(lhs) variable.scale(0.7) variable.move_to(lhs, LEFT) self.play(LaggedStart(*[ FadeIn(v, RIGHT) for v in variables ])) self.wait() self.play( LaggedStartMap(Restore, variables), FadeIn( lhss_copy, remover=True, lag_ratio=0.1, run_time=2, ) ) self.add(lhss) self.wait() self.play(LaggedStartMap( FadeIn, rhss )) self.wait() self.play( LaggedStart(*[ ShowCreationThenFadeAround(lhs[:3]) for lhs in lhss ]) ) self.wait() self.play( LaggedStartMap( ShowCreationThenFadeAround, rhss, ) ) self.wait() class LaplacianIntuition(SpecialThreeDScene): CONFIG = { "three_d_axes_config": { "x_min": -5, "x_max": 5, "y_min": -5, "y_max": 5, }, "surface_resolution": 32, } def construct(self): axes = self.get_axes() axes.scale(0.5, about_point=ORIGIN) self.set_camera_to_default_position() self.begin_ambient_camera_rotation() def func(x, y): return np.array([ x, y, 2.7 + 0.5 * (np.sin(x) + np.cos(y)) - 0.025 * (x**2 + y**2) ]) surface_config = { "u_min": -5, "u_max": 5, "v_min": -5, "v_max": 5, "resolution": self.surface_resolution, } # plane = ParametricSurface( # lambda u, v: np.array([u, v, 0]), # **surface_config # ) # plane.set_stroke(WHITE, width=0.1) # plane.set_fill(WHITE, opacity=0.1) plane = Square( side_length=10, stroke_width=0, fill_color=WHITE, fill_opacity=0.1, ) plane.center() plane.set_shade_in_3d(True) surface = ParametricSurface( func, **surface_config ) surface.set_stroke(BLUE, width=0.1) surface.set_fill(BLUE, opacity=0.25) self.add(axes, plane, surface) point = VectorizedPoint(np.array([2, -2, 0])) dot = Dot() dot.set_color(GREEN) dot.add_updater(lambda d: d.move_to(point)) line = always_redraw(lambda: DashedLine( point.get_location(), func(*point.get_location()[:2]), background_image_file="VerticalTempGradient", )) circle = Circle(radius=0.25) circle.set_color(YELLOW) circle.insert_n_curves(20) circle.add_updater(lambda m: m.move_to(point)) circle.set_shade_in_3d(True) surface_circle = always_redraw( lambda: circle.copy().apply_function( lambda p: func(*p[:2]) ).shift( 0.02 * IN ).color_using_background_image("VerticalTempGradient") ) self.play(FadeInFromLarge(dot)) self.play(ShowCreation(line)) self.play(TransformFromCopy(dot, circle)) self.play( Transform( circle.copy(), surface_circle.copy().clear_updaters(), remover=True, ) ) self.add(surface_circle) self.wait() for vect in [4 * LEFT, DOWN, 4 * RIGHT, UP]: self.play( point.shift, vect, run_time=3, ) class StrogatzMention(PiCreatureScene): def construct(self): self.show_book() self.show_motives() self.show_pages() def show_book(self): morty = self.pi_creature book = ImageMobject("InfinitePowers") book.set_height(5) book.to_edge(LEFT) steve = ImageMobject("Strogatz_by_bricks") steve.set_height(5) steve.to_edge(LEFT) name = OldTexText("Steven Strogatz") name.match_width(steve) name.next_to(steve, DOWN) self.think( "Hmm...many good\\\\lessons here...", run_time=1 ) self.wait() self.play(FadeInFromDown(steve)) self.wait() self.play( FadeIn(book, DOWN), steve.shift, 4 * RIGHT, RemovePiCreatureBubble( morty, target_mode="thinking" ) ) self.wait(3) self.play( FadeOut(steve), FadeOut(morty), ) self.book = book def show_motives(self): motives = VGroup( OldTexText("1) Scratch and itch"), OldTexText("2) Make people love math"), ) motives.scale(1.5) motives.arrange( DOWN, LARGE_BUFF, aligned_edge=LEFT, ) motives.move_to( Line( self.book.get_right(), FRAME_WIDTH * RIGHT / 2 ) ) motives.to_edge(UP) for motive in motives: self.play(FadeInFromDown(motive)) self.wait(2) self.play(FadeOut(motives)) def show_pages(self): book = self.book pages = Group(*[ ImageMobject("IP_Sample_Page{}".format(i)) for i in range(1, 4) ]) for page in pages: page.match_height(book) page.next_to(book, RIGHT) last_page = VectorizedPoint() for page in pages: self.play( FadeOut(last_page), FadeIn(page) ) self.wait() last_page = page self.play(FadeOut(last_page)) def create_pi_creature(self): return Mortimer().to_corner(DR) class Thumbnail(Scene): def construct(self): image = ImageMobject("HeatSurfaceExampleFlipped") image.set_height(6.5) image.to_edge(DOWN, buff=-SMALL_BUFF) self.add(image) equation = OldTex( "{\\partial {T} \\over \\partial {t}}", "=", "\\alpha", "\\nabla^2 {T}", tex_to_color_map={ "{t}": YELLOW, "{T}": RED, } ) equation.scale(2) equation.to_edge(UP) self.add(equation) Group(equation, image).shift(1.5 * RIGHT) question = OldTexText("What is\\\\this?") question.scale(2.5) question.to_edge(LEFT) arrow = Arrow( question.get_top(), equation.get_left(), buff=0.5, path_arc=-90 * DEGREES, ) arrow.set_stroke(width=5) self.add(question, arrow) class ShowNewton(Scene): def construct(self): pass class ShowCupOfWater(Scene): def construct(self): pass
from manim_imports_ext import * TIME_COLOR = YELLOW X_COLOR = GREEN def get_heat_equation(): pass def temperature_to_color(temp, min_temp=-1, max_temp=1): colors = [BLUE, TEAL, GREEN, YELLOW, "#ff0000"] alpha = inverse_interpolate(min_temp, max_temp, temp) index, sub_alpha = integer_interpolate( 0, len(colors) - 1, alpha ) return interpolate_color( colors[index], colors[index + 1], sub_alpha ) def two_d_temp_func(x, y, t): return np.sum([ c * np.sin(f * var) * np.exp(-(f**2) * t) for c, f, var in [ (0.2, 1, x), (0.3, 3, x), (0.02, 5, x), (0.01, 7, x), (0.5, 2, y), (0.1, 10, y), (0.01, 20, y), ] ])
from manim_imports_ext import * from _2019.diffyq.part2.shared_constructs import * class TwoDBodyWithManyTemperatures(ThreeDScene): CONFIG = { "cells_per_side": 20, "body_height": 6, } def construct(self): self.introduce_body() self.show_temperature_at_all_points() def introduce_body(self): height = self.body_height buff = 0.025 rows = VGroup(*[ VGroup(*[ Dot( # stroke_width=0.5, stroke_width=0, fill_opacity=1, ) for x in range(self.cells_per_side) ]).arrange(RIGHT, buff=buff) for y in range(self.cells_per_side) ]).arrange(DOWN, buff=buff) for row in rows[1::2]: row.submobjects.reverse() body = self.body = VGroup(*it.chain(*rows)) body.set_height(height) body.center() body.to_edge(LEFT) axes = self.axes = Axes( x_min=-5, x_max=5, y_min=-5, y_max=5, ) axes.match_height(body) axes.move_to(body) for cell in body: self.color_cell(cell) # body.set_stroke(WHITE, 0.5) # Do this? plate = Square( stroke_width=0, fill_color=GREY_D, sheen_direction=UL, sheen_factor=1, fill_opacity=1, ) plate.replace(body) plate_words = OldTexText("Piece of \\\\ metal") plate_words.scale(2) plate_words.set_stroke(BLACK, 2, background=True) plate_words.set_color(BLACK) plate_words.move_to(plate) self.play( DrawBorderThenFill(plate), Write( plate_words, run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1) ) ) self.wait() self.remove(plate_words) def show_temperature_at_all_points(self): body = self.body start_corner = body[0].get_center() dot = Dot(radius=0.01, color=WHITE) dot.move_to(start_corner) get_point = dot.get_center lhs = OldTex("T = ") lhs.next_to(body, RIGHT, LARGE_BUFF) decimal = DecimalNumber( num_decimal_places=1, unit="^\\circ" ) decimal.next_to(lhs, RIGHT, MED_SMALL_BUFF, DOWN) decimal.add_updater( lambda d: d.set_value( 40 + 50 * self.point_to_temp(get_point()) ) ) arrow = Arrow(color=YELLOW) arrow.set_stroke(BLACK, 8, background=True) arrow.tip.set_stroke(BLACK, 2, background=True) # arrow.add_to_back(arrow.copy().set_stroke(BLACK, 5)) arrow.add_updater(lambda a: a.put_start_and_end_on( lhs.get_left() + MED_SMALL_BUFF * LEFT, get_point(), )) dot.add_updater(lambda p: p.move_to( body[-1] if (1 < len(body)) else start_corner )) self.add(body, dot, lhs, decimal, arrow) self.play( ShowIncreasingSubsets( body, run_time=10, rate_func=linear, ) ) self.wait() self.remove(dot) self.play( FadeOut(arrow), FadeOut(lhs), FadeOut(decimal), ) # def point_to_temp(self, point, time=0): x, y = self.axes.point_to_coords(point) return two_d_temp_func( 0.3 * x, 0.3 * y, t=time ) def color_cell(self, cell, vect=RIGHT): p0 = cell.get_corner(-vect) p1 = cell.get_corner(vect) colors = [] for point in p0, p1: temp = self.point_to_temp(point) color = temperature_to_color(temp) colors.append(color) cell.set_color(color=colors) cell.set_sheen_direction(vect) return cell class TwoDBodyWithManyTemperaturesGraph(ExternallyAnimatedScene): pass class TwoDBodyWithManyTemperaturesContour(ExternallyAnimatedScene): pass class BringTwoRodsTogether(Scene): CONFIG = { "step_size": 0.05, "axes_config": { "x_min": -1, "x_max": 11, "y_min": -10, "y_max": 100, "y_axis_config": { "unit_size": 0.06, "tick_frequency": 10, }, }, "y_labels": range(20, 100, 20), "graph_x_min": 0, "graph_x_max": 10, "midpoint": 5, "max_temp": 90, "min_temp": 10, "wait_time": 30, "default_n_rod_pieces": 20, "alpha": 1.0, } def construct(self): self.setup_axes() self.setup_graph() self.setup_clock() self.show_rods() self.show_equilibration() def setup_axes(self): axes = Axes(**self.axes_config) axes.center().to_edge(UP) y_label = axes.get_y_axis_label("\\text{Temperature}") y_label.to_edge(UP) axes.y_axis.label = y_label axes.y_axis.add(y_label) axes.y_axis.add_numbers(*self.y_labels) self.axes = axes self.y_label = y_label def setup_graph(self): graph = self.axes.get_graph( self.initial_function, x_min=self.graph_x_min, x_max=self.graph_x_max, step_size=self.step_size, discontinuities=[self.midpoint], ) graph.color_using_background_image("VerticalTempGradient") self.graph = graph def setup_clock(self): clock = Clock() clock.set_height(1) clock.to_corner(UR) clock.shift(MED_LARGE_BUFF * LEFT) time_lhs = OldTexText("Time: ") time_label = DecimalNumber( 0, num_decimal_places=2, ) time_rhs = OldTexText("s") time_group = VGroup( time_lhs, time_label, # time_rhs ) time_group.arrange(RIGHT, aligned_edge=DOWN) time_rhs.shift(SMALL_BUFF * LEFT) time_group.next_to(clock, DOWN) self.time_group = time_group self.time_label = time_label self.clock = clock def show_rods(self): rod1, rod2 = rods = VGroup( self.get_rod(0, 5), self.get_rod(5, 10), ) rod1.set_color(rod1[0].get_color()) rod2.set_color(rod2[-1].get_color()) rods.save_state() rods.space_out_submobjects(1.5) rods.center() labels = VGroup( OldTex("90^\\circ"), OldTex("10^\\circ"), ) for rod, label in zip(rods, labels): label.next_to(rod, DOWN) rod.label = label self.play( FadeIn(rod1, UP), Write(rod1.label), ) self.play( FadeIn(rod2, DOWN), Write(rod2.label) ) self.wait() self.rods = rods self.rod_labels = labels def show_equilibration(self): rods = self.rods axes = self.axes graph = self.graph labels = self.rod_labels self.play( Write(axes), rods.restore, rods.space_out_submobjects, 1.1, FadeIn(self.time_group), FadeIn(self.clock), *[ MaintainPositionRelativeTo( rod.label, rod ) for rod in rods ], ) br1 = Rectangle(height=0.2, width=1) br1.set_stroke(width=0) br1.set_fill(BLACK, opacity=1) br2 = br1.copy() br1.add_updater(lambda b: b.move_to(axes.c2p(0, 90))) br1.add_updater( lambda b: b.align_to(rods[0].get_right(), LEFT) ) br2.add_updater(lambda b: b.move_to(axes.c2p(0, 10))) br2.add_updater( lambda b: b.align_to(rods[1].get_left(), RIGHT) ) self.add(graph, br1, br2) self.play( ShowCreation(graph), labels[0].align_to, axes.c2p(0, 87), UP, labels[1].align_to, axes.c2p(0, 13), DOWN, ) self.play() self.play( rods.restore, rate_func=rush_into, ) self.remove(br1, br2) graph.add_updater(self.update_graph) self.time_label.add_updater( lambda d, dt: d.increment_value(dt) ) rods.add_updater(self.update_rods) self.play( self.get_clock_anim(self.wait_time), FadeOut(labels) ) # def get_clock_anim(self, time, **kwargs): config = { "run_time": time, "hours_passed": time, } config.update(kwargs) return ClockPassesTime(self.clock, **config) def initial_function(self, x): epsilon = 1e-10 if x < self.midpoint - epsilon: return self.max_temp elif x > self.midpoint + epsilon: return self.min_temp else: return (self.min_temp + self.max_temp) / 2 def update_graph(self, graph, dt, alpha=None, n_mini_steps=500): if alpha is None: alpha = self.alpha points = np.append( graph.get_start_anchors(), [graph.get_last_point()], axis=0, ) for k in range(n_mini_steps): y_change = np.zeros(points.shape[0]) dx = points[1][0] - points[0][0] for i in range(len(points)): p = points[i] lp = points[max(i - 1, 0)] rp = points[min(i + 1, len(points) - 1)] d2y = (rp[1] - 2 * p[1] + lp[1]) if (0 < i < len(points) - 1): second_deriv = d2y / (dx**2) else: second_deriv = 2 * d2y / (dx**2) # second_deriv = 0 y_change[i] = alpha * second_deriv * dt / n_mini_steps # y_change[0] = y_change[1] # y_change[-1] = y_change[-2] # y_change[0] = 0 # y_change[-1] = 0 # y_change -= np.mean(y_change) points[:, 1] += y_change graph.set_points_smoothly(points) return graph def get_second_derivative(self, x, dx=0.001): graph = self.graph x_min = self.graph_x_min x_max = self.graph_x_max ly, y, ry = [ graph.point_from_proportion( inverse_interpolate(x_min, x_max, alt_x) )[1] for alt_x in (x - dx, x, x + dx) ] # At the boundary, don't return the second deriv, # but instead something matching the Neumann # boundary condition. if x == x_max: return (ly - y) / dx elif x == x_min: return (ry - y) / dx else: d2y = ry - 2 * y + ly return d2y / (dx**2) def get_rod(self, x_min, x_max, n_pieces=None): if n_pieces is None: n_pieces = self.default_n_rod_pieces axes = self.axes line = Line(axes.c2p(x_min, 0), axes.c2p(x_max, 0)) rod = VGroup(*[ Square() for n in range(n_pieces) ]) rod.arrange(RIGHT, buff=0) rod.match_width(line) rod.set_height(0.2, stretch=True) rod.move_to(axes.c2p(x_min, 0), LEFT) rod.set_fill(opacity=1) rod.set_stroke(width=1) rod.set_sheen_direction(RIGHT) self.color_rod_by_graph(rod) return rod def update_rods(self, rods): for rod in rods: self.color_rod_by_graph(rod) def color_rod_by_graph(self, rod): for piece in rod: piece.set_color(color=[ self.rod_point_to_color(piece.get_left()), self.rod_point_to_color(piece.get_right()), ]) def rod_point_to_graph_y(self, point): axes = self.axes x = axes.x_axis.p2n(point) graph = self.graph alpha = inverse_interpolate( self.graph_x_min, self.graph_x_max, x, ) return axes.y_axis.p2n( graph.point_from_proportion(alpha) ) def y_to_color(self, y): y_max = self.max_temp y_min = self.min_temp alpha = inverse_interpolate(y_min, y_max, y) return temperature_to_color(interpolate(-0.8, 0.8, alpha)) def rod_point_to_color(self, point): return self.y_to_color( self.rod_point_to_graph_y(point) ) class ShowEvolvingTempGraphWithArrows(BringTwoRodsTogether): CONFIG = { "alpha": 0.1, "arrow_xs": np.linspace(0, 10, 22)[1:-1], "arrow_scale_factor": 0.5, "max_magnitude": 1.5, "wait_time": 30, "freq_amplitude_pairs": [ (1, 0.5), (2, 1), (3, 0.5), (4, 0.3), (5, 0.3), (7, 0.2), (21, 0.1), (41, 0.05), ], } def construct(self): self.add_axes() self.add_graph() self.add_clock() self.add_rod() self.add_arrows() self.initialize_updaters() self.let_play() def add_axes(self): self.setup_axes() self.add(self.axes) def add_graph(self): self.setup_graph() self.add(self.graph) def add_clock(self): self.setup_clock() self.add(self.clock) self.add(self.time_label) self.time_label.next_to(self.clock, DOWN) def add_rod(self): rod = self.rod = self.get_rod( self.graph_x_min, self.graph_x_max, ) self.add(rod) def add_arrows(self): graph = self.graph x_min = self.graph_x_min x_max = self.graph_x_max xs = self.arrow_xs arrows = VGroup(*[Vector(DOWN) for x in xs]) asf = self.arrow_scale_factor def update_arrows(arrows): for x, arrow in zip(xs, arrows): d2y_dx2 = self.get_second_derivative(x) mag = asf * np.sign(d2y_dx2) * abs(d2y_dx2) mag = np.clip( mag, -self.max_magnitude, self.max_magnitude, ) arrow.put_start_and_end_on( ORIGIN, mag * UP ) point = graph.point_from_proportion( inverse_interpolate(x_min, x_max, x) ) arrow.shift(point - arrow.get_start()) arrow.set_color( self.rod_point_to_color(point) ) arrows.add_updater(update_arrows) self.add(arrows) self.arrows = arrows def initialize_updaters(self): if hasattr(self, "graph"): self.graph.add_updater(self.update_graph) if hasattr(self, "rod"): self.rod.add_updater(self.color_rod_by_graph) if hasattr(self, "time_label"): self.time_label.add_updater( lambda d, dt: d.increment_value(dt) ) def let_play(self): self.run_clock(self.wait_time) def run_clock(self, time): self.play( ClockPassesTime( self.clock, run_time=time, hours_passed=time, ), ) # def temp_func(self, x, t): new_x = TAU * x / 10 return 50 + 20 * np.sum([ amp * np.sin(freq * new_x) * np.exp(-(self.alpha * freq**2) * t) for freq, amp in self.freq_amplitude_pairs ]) def initial_function(self, x, time=0): return self.temp_func(x, 0) class TalkThrough1DHeatGraph(ShowEvolvingTempGraphWithArrows, SpecialThreeDScene): CONFIG = { "freq_amplitude_pairs": [ (1, 0.5), (2, 1), (3, 0.5), (4, 0.3), (5, 0.3), (7, 0.2), ], "surface_resolution": 20, "graph_slice_step": 10 / 20, } def construct(self): self.add_axes() self.add_graph() self.add_rod() self.emphasize_graph() self.emphasize_rod() self.show_x_axis() self.show_changes_over_time() self.show_surface() def add_graph(self): self.graph = self.get_graph() self.add(self.graph) def emphasize_graph(self): graph = self.graph q_marks = VGroup(*[ OldTex("?").move_to( graph.point_from_proportion(a), UP, ).set_stroke(BLACK, 3, background=True) for a in np.linspace(0, 1, 20) ]) self.play(LaggedStart(*[ Succession( FadeInFromLarge(q_mark), FadeOut(q_mark, DOWN), ) for q_mark in q_marks ])) self.wait() def emphasize_rod(self): alt_rod = self.get_rod(0, 10, 50) word = OldTexText("Rod") word.scale(2) word.next_to(alt_rod, UP, MED_SMALL_BUFF) self.play( LaggedStart( *[ Rotating(piece, rate_func=smooth) for piece in alt_rod ], run_time=2, lag_ratio=0.01, ), Write(word) ) self.remove(*alt_rod) self.wait() self.rod_word = word def show_x_axis(self): rod = self.rod axes = self.axes graph = self.graph x_axis = axes.x_axis x_numbers = x_axis.get_number_mobjects(*range(1, 11)) x_axis_label = OldTex("x") x_axis_label.next_to(x_axis.get_right(), UP) self.play( rod.set_opacity, 0.5, FadeIn(x_axis_label, UL), LaggedStartMap( FadeInFrom, x_numbers, lambda m: (m, UP), ) ) self.wait() # Show x-values triangle = ArrowTip( start_angle=-90 * DEGREES, color=GREY_B, ) x_tracker = ValueTracker(PI) get_x = x_tracker.get_value def get_x_point(): return x_axis.n2p(get_x()) def get_graph_point(): return graph.point_from_proportion( inverse_interpolate( self.graph_x_min, self.graph_x_max, get_x(), ) ) triangle.add_updater( lambda t: t.next_to(get_x_point(), UP) ) x_label = VGroup( OldTex("x"), OldTex("="), DecimalNumber( 0, num_decimal_places=3, include_background_rectangle=True, ).scale(0.9) ) x_label.set_stroke(BLACK, 5, background=True) x_label.add_updater(lambda m: m[-1].set_value(get_x())) x_label.add_updater(lambda m: m.arrange(RIGHT, buff=SMALL_BUFF)) x_label.add_updater(lambda m: m[-1].align_to(m[0], DOWN)) x_label.add_updater(lambda m: m.next_to(triangle, UP, SMALL_BUFF)) x_label.add_updater(lambda m: m.shift(SMALL_BUFF * RIGHT)) rod_piece = always_redraw( lambda: self.get_rod( get_x() - 0.05, get_x() + 0.05, n_pieces=1, ) ) self.play( FadeIn(triangle, UP), FadeIn(x_label), FadeIn(rod_piece), FadeOut(self.rod_word), ) for value in [np.exp(2), (np.sqrt(5) + 1) / 2]: self.play(x_tracker.set_value, value, run_time=2) self.wait() # Show graph v_line = always_redraw( lambda: DashedLine( get_x_point(), get_graph_point(), color=self.rod_point_to_color(get_x_point()), ) ) graph_dot = Dot() graph_dot.add_updater( lambda m: m.set_color( self.rod_point_to_color(m.get_center()) ) ) graph_dot.add_updater( lambda m: m.move_to(get_graph_point()) ) t_label = OldTex("T(", "x", ")") t_label.set_stroke(BLACK, 3, background=True) t_label.add_updater( lambda m: m.next_to(graph_dot, UR, buff=0) ) self.add(v_line, rod_piece, x_label, triangle) self.play( TransformFromCopy(x_label[0], t_label[1]), FadeIn(t_label[0::2]), ShowCreation(v_line), GrowFromPoint(graph_dot, get_x_point()), ) self.add(t_label) self.wait() self.play( x_tracker.set_value, TAU, run_time=5, ) self.x_tracker = x_tracker self.graph_label_group = VGroup( v_line, rod_piece, triangle, x_label, graph_dot, t_label, ) self.set_variables_as_attrs(*self.graph_label_group) self.set_variables_as_attrs(x_numbers, x_axis_label) def show_changes_over_time(self): graph = self.graph t_label = self.t_label new_t_label = OldTex("T(", "x", ",", "t", ")") new_t_label.set_color_by_tex("t", YELLOW) new_t_label.match_updaters(t_label) self.setup_clock() clock = self.clock time_label = self.time_label time_group = self.time_group time = 5 self.play( FadeIn(clock), FadeIn(time_group), ) self.play( self.get_graph_time_change_animation( graph, time ), ClockPassesTime(clock), ChangeDecimalToValue( time_label, time, rate_func=linear, ), ReplacementTransform( t_label, new_t_label, rate_func=squish_rate_func(smooth, 0.5, 0.7), ), run_time=time ) self.play( ShowCreationThenFadeAround( new_t_label.get_part_by_tex("t") ), ) self.wait() self.play( FadeOut(clock), ChangeDecimalToValue(time_label, 0), VFadeOut(time_group), self.get_graph_time_change_animation( graph, new_time=0, ), run_time=1, rate_func=smooth, ) self.graph_label_group.remove(t_label) self.graph_label_group.add(new_t_label) def show_surface(self): axes = self.axes graph = self.graph t_min = 0 t_max = 10 axes_copy = axes.deepcopy() self.original_axes = self.axes # Set rod final state final_graph = self.get_graph(t_max) curr_graph = self.graph self.graph = final_graph final_rod = self.rod.copy() final_rod.set_opacity(1) self.color_rod_by_graph(final_rod) self.graph = curr_graph # Time axis t_axis = NumberLine( x_min=t_min, x_max=t_max, ) origin = axes.c2p(0, 0) t_axis.shift(origin - t_axis.n2p(0)) t_axis.add_numbers( *range(1, t_max + 1), direction=UP, ) time_label = OldTexText("Time") time_label.scale(1.5) time_label.next_to(t_axis, UP) t_axis.time_label = time_label t_axis.add(time_label) # t_axis.rotate(90 * DEGREES, LEFT, about_point=origin) t_axis.rotate(90 * DEGREES, UP, about_point=origin) # New parts of graph step = self.graph_slice_step graph_slices = VGroup(*[ self.get_graph(time=t).shift( t * IN ) for t in np.arange(0, t_max + step, step) ]) graph_slices.set_stroke(width=1) graph_slices.set_shade_in_3d(True) # Input plane x_axis = self.axes.x_axis y = axes.c2p(0, 0)[1] surface_config = { "u_min": self.graph_x_min, "u_max": self.graph_x_max, "v_min": t_min, "v_max": t_max, "resolution": self.surface_resolution, } input_plane = ParametricSurface( lambda x, t: np.array([ x_axis.n2p(x)[0], y, t_axis.n2p(t)[2], ]), **surface_config, ) input_plane.set_style( fill_opacity=0.5, fill_color=BLUE_B, stroke_width=0.5, stroke_color=WHITE, ) # Surface y_axis = axes.y_axis surface = ParametricSurface( lambda x, t: np.array([ x_axis.n2p(x)[0], y_axis.n2p(self.temp_func(x, t))[1], t_axis.n2p(t)[2], ]), **surface_config, ) surface.set_style( fill_opacity=0.1, fill_color=GREY_B, stroke_width=0.5, stroke_color=WHITE, stroke_opacity=0.5, ) # Rotate everything on screen and move camera # in such a way that it looks the same curr_group = Group(*self.get_mobjects()) curr_group.clear_updaters() self.set_camera_orientation( phi=90 * DEGREES, ) mobs = [ curr_group, graph_slices, t_axis, input_plane, surface, ] for mob in mobs: self.orient_mobject_for_3d(mob) # Clean current mobjects self.x_label.set_stroke(BLACK, 2, background=True) self.x_label[-1][0].fade(1) self.move_camera( phi=80 * DEGREES, theta=-85 * DEGREES, added_anims=[ Write(input_plane), Write(t_axis), FadeOut(self.graph_label_group), self.rod.set_opacity, 1, ] ) self.begin_ambient_camera_rotation() self.add(*graph_slices, *self.get_mobjects()) self.play( FadeIn(surface), LaggedStart(*[ TransformFromCopy(graph, graph_slice) for graph_slice in graph_slices ], lag_ratio=0.02) ) self.wait(4) # Show slices self.axes = axes_copy # So get_graph works... slicing_plane = Rectangle( stroke_width=0, fill_color=WHITE, fill_opacity=0.2, ) slicing_plane.set_shade_in_3d(True) slicing_plane.replace( Line(axes_copy.c2p(0, 0), axes_copy.c2p(10, 100)), stretch=True ) self.orient_mobject_for_3d(slicing_plane) def get_time_slice(t): new_slice = self.get_graph(t) new_slice.set_shade_in_3d(True) self.orient_mobject_for_3d(new_slice) new_slice.shift(t * UP) return new_slice graph.set_shade_in_3d(True) t_tracker = ValueTracker(0) graph.add_updater(lambda g: g.become( get_time_slice(t_tracker.get_value()) )) self.orient_mobject_for_3d(final_rod) final_rod.shift(10 * UP) kw = {"run_time": 10, "rate_func": linear} self.rod.save_state() self.play( ApplyMethod(t_tracker.set_value, 10, **kw), Transform(self.rod, final_rod, **kw), ApplyMethod(slicing_plane.shift, 10 * UP, **kw), ) self.wait() self.set_variables_as_attrs( t_axis, input_plane, surface, graph_slices, slicing_plane, t_tracker, ) # def get_graph(self, time=0): graph = self.axes.get_graph( lambda x: self.temp_func(x, time), x_min=self.graph_x_min, x_max=self.graph_x_max, step_size=self.step_size, ) graph.time = time graph.color_using_background_image("VerticalTempGradient") return graph def get_graph_time_change_animation(self, graph, new_time, **kwargs): old_time = graph.time graph.time = new_time config = { "run_time": abs(new_time - old_time), "rate_func": linear, } config.update(kwargs) return UpdateFromAlphaFunc( graph, lambda g, a: g.become( self.get_graph(interpolate( old_time, new_time, a )) ), **config ) def orient_mobject_for_3d(self, mob): mob.rotate( 90 * DEGREES, axis=RIGHT, about_point=ORIGIN ) return mob class ContrastXChangesToTChanges(TalkThrough1DHeatGraph): CONFIG = { # "surface_resolution": 5, # "graph_slice_step": 1, } def construct(self): self.catchup_with_last_scene() self.emphasize_dimensions_of_input_space() self.reset_time_to_zero() self.show_changes_with_x() self.show_changes_with_t() def catchup_with_last_scene(self): self.force_skipping() self.add_axes() self.add_graph() self.add_rod() self.rod_word = Point() self.show_x_axis() self.show_surface() self.revert_to_original_skipping_status() def emphasize_dimensions_of_input_space(self): plane = self.input_plane plane_copy = plane.copy() plane_copy.set_color(BLUE_E) plane_copy.shift(SMALL_BUFF * 0.5 * OUT) plane_copy1 = plane_copy.copy() plane_copy1.stretch(0.01, 1, about_edge=DOWN) plane_copy0 = plane_copy1.copy() plane_copy0.stretch(0, 0, about_edge=LEFT) words = OldTexText("2d input\\\\space") words.scale(2) words.move_to(plane.get_center() + SMALL_BUFF * OUT) self.play( Write(words), self.camera.phi_tracker.set_value, 60 * DEGREES, self.camera.theta_tracker.set_value, -90 * DEGREES, run_time=1 ) self.play( ReplacementTransform(plane_copy0, plane_copy1) ) self.play( ReplacementTransform(plane_copy1, plane_copy) ) self.wait(2) self.play(FadeOut(plane_copy)) self.input_plane_words = words def reset_time_to_zero(self): self.play( self.t_tracker.set_value, 0, VFadeOut(self.slicing_plane), Restore(self.rod), ) def show_changes_with_x(self): alpha_tracker = ValueTracker(0) line = always_redraw( lambda: self.get_tangent_line( self.graph, alpha_tracker.get_value(), ) ) self.stop_ambient_camera_rotation() self.play( ShowCreation(line), FadeOut(self.input_plane_words), self.camera.phi_tracker.set_value, 80 * DEGREES, self.camera.theta_tracker.set_value, -90 * DEGREES, ) self.play( alpha_tracker.set_value, 0.425, run_time=5, rate_func=bezier([0, 0, 1, 1]), ) # Show dx and dT p0 = line.point_from_proportion(0.3) p2 = line.point_from_proportion(0.7) p1 = np.array([p2[0], *p0[1:]]) dx_line = DashedLine(p0, p1) dT_line = DashedLine(p1, p2) dx = OldTex("dx") dT = OldTex("dT") VGroup(dx, dT).scale(0.7) VGroup(dx, dT).rotate(90 * DEGREES, RIGHT) dx.next_to(dx_line, IN, SMALL_BUFF) dT.next_to(dT_line, RIGHT, SMALL_BUFF) self.play( ShowCreation(dx_line), FadeIn(dx, LEFT) ) self.wait() self.play( ShowCreation(dT_line), FadeIn(dT, IN) ) self.wait() self.play(*map(FadeOut, [ line, dx_line, dT_line, dx, dT, ])) def show_changes_with_t(self): slices = self.graph_slices slice_alpha = 0.075 graph = VMobject() graph.set_points_smoothly([ gs.point_from_proportion(slice_alpha) for gs in slices ]) graph.color_using_background_image("VerticalTempGradient") graph.set_shade_in_3d(True) alpha_tracker = ValueTracker(0) line = always_redraw( lambda: self.get_tangent_line( graph, alpha_tracker.get_value(), ) ) plane = Square() plane.set_stroke(width=0) plane.set_fill(WHITE, 0.1) plane.set_shade_in_3d(True) plane.rotate(90 * DEGREES, RIGHT) plane.rotate(90 * DEGREES, OUT) plane.set_height(10) plane.set_depth(8, stretch=True) plane.move_to(self.t_axis.n2p(0), IN + DOWN) plane.shift(RIGHT) self.play( self.camera.theta_tracker.set_value, -20 * DEGREES, self.camera.frame_center.shift, 4 * LEFT, ) self.play( ShowCreation( graph.copy(), remover=True ), FadeIn(plane, 6 * DOWN, run_time=2), VFadeIn(line), ApplyMethod( alpha_tracker.set_value, 1, run_time=8, ), ) self.add(graph) self.begin_ambient_camera_rotation(-0.02) self.camera.frame_center.add_updater( lambda m, dt: m.shift(0.05 * dt * RIGHT) ) self.play( FadeOut(line), FadeOut(plane), ) self.wait(30) # Let rotate self.t_graph = graph # def get_tangent_line(self, graph, alpha, d_alpha=0.001, length=2): if alpha < 1 - d_alpha: a1 = alpha a2 = alpha + d_alpha else: a1 = alpha - d_alpha a2 = alpha p1 = graph.point_from_proportion(a1) p2 = graph.point_from_proportion(a2) line = Line(p1, p2, color=WHITE) line.scale( length / line.get_length() ) line.move_to(p1) return line class TransitionToTempVsTime(ContrastXChangesToTChanges): CONFIG = { # "surface_resolution": 5, # "graph_slice_step": 1, } def construct(self): self.catchup_with_last_scene() axes = self.original_axes t_axis = self.t_axis y_axis = axes.y_axis x_axis = axes.x_axis for mob in self.get_mobjects(): mob.clear_updaters() self.stop_ambient_camera_rotation() self.move_camera( phi=90 * DEGREES, theta=0 * DEGREES, added_anims=[ Rotate( y_axis, 90 * DEGREES, axis=OUT, about_point=y_axis.n2p(0), ), FadeOut(VGroup( self.graph_slices, self.surface, self.slicing_plane, self.rod, self.graph, self.x_numbers, self.x_axis_label, self.t_graph, )), self.camera.frame_center.move_to, 5 * LEFT, ] ) self.play( VGroup(x_axis, self.input_plane).stretch, 0, 0, {"about_point": y_axis.n2p(0)}, ) self.play( t_axis.time_label.scale, 1 / 1.5, t_axis.time_label.next_to, t_axis, IN, MED_LARGE_BUFF, t_axis.numbers.shift, 0.7 * IN, ) self.wait() def catchup_with_last_scene(self): self.force_skipping() self.add_axes() self.add_graph() self.add_rod() self.rod_word = Point() self.show_x_axis() self.show_surface() self.emphasize_dimensions_of_input_space() self.reset_time_to_zero() self.show_changes_with_x() self.show_changes_with_t() self.revert_to_original_skipping_status() class ShowDelTermsAsTinyNudges(TransitionToTempVsTime): CONFIG = { # "surface_resolution": 5, # "graph_slice_step": 1, "tangent_line_length": 4, } def construct(self): self.catchup_with_last_scene() self.stop_camera() self.show_del_t() self.show_del_x() def stop_camera(self): self.stop_ambient_camera_rotation() for mob in self.get_mobjects(): mob.clear_updaters() def show_del_x(self): x_tracker = ValueTracker(3) dx_tracker = ValueTracker(0.5) line_group = self.get_line_group( self.graph, x_tracker, dx_tracker, corner_index=0, ) dx_line, dT_line, tan_line = line_group del_x = OldTex("\\partial x") del_x.set_color(GREEN) del_x.line = dx_line del_x.direction = OUT del_T = OldTex("\\partial T") del_T.line = dT_line del_T.direction = RIGHT syms = VGroup(del_T, del_x) for sym in syms: sym.add_updater(lambda m: m.set_width( dx_line.get_length() )) sym.rect = SurroundingRectangle(sym) group = VGroup(sym, sym.rect) group.rotate(90 * DEGREES, RIGHT) for sym in syms: sym.add_updater(lambda m: m.next_to( m.line, m.direction, SMALL_BUFF, )) sym.rect.move_to(sym) self.move_camera( phi=80 * DEGREES, theta=-90 * DEGREES, added_anims=[ self.camera.frame_center.move_to, ORIGIN, ], ) for sym in reversed(syms): self.play( FadeIn(sym, -sym.direction), ShowCreation( sym.line.copy(), remover=True ), ) self.add(sym.line) self.play(ShowCreation(tan_line)) for sym in syms: self.play( ShowCreationThenDestruction(sym.rect) ) self.wait() self.wait() self.add(line_group) self.play( dx_tracker.set_value, 0.01, run_time=5, ) self.play( FadeOut(syms), FadeOut(line_group), ) def show_del_t(self): # Largely copy pasted from above. # Reconsolidate if any of this will actually # be used later. t_tracker = ValueTracker(1) dt_tracker = ValueTracker(1) line_group = self.get_line_group( self.t_graph, t_tracker, dt_tracker, corner_index=1, ) dt_line, dT_line, tan_line = line_group del_t = OldTex("\\partial t") del_t.set_color(YELLOW) del_t.line = dt_line del_t.direction = OUT del_T = OldTex("\\partial T") del_T.line = dT_line del_T.direction = UP syms = VGroup(del_T, del_t) for sym in syms: sym.rect = SurroundingRectangle(sym) group = VGroup(sym, sym.rect) group.rotate(90 * DEGREES, RIGHT) group.rotate(90 * DEGREES, OUT) sym.add_updater(lambda m: m.set_height( 0.8 * dT_line.get_length() )) del_t.add_updater(lambda m: m.set_height( min(0.5, m.line.get_length()) )) del_T.add_updater(lambda m: m.set_depth( min(0.5, m.line.get_length()) )) for sym in syms: sym.add_updater(lambda m: m.next_to( m.line, m.direction, SMALL_BUFF, )) sym.rect.move_to(sym) self.move_camera( phi=80 * DEGREES, theta=-10 * DEGREES, added_anims=[ self.camera.frame_center.move_to, 5 * LEFT, ], ) for sym in reversed(syms): self.play( FadeIn(sym, -sym.direction), ShowCreation( sym.line.copy(), remover=True ), ) self.add(sym.line) self.play(ShowCreation(tan_line)) for sym in syms: self.play( ShowCreationThenDestruction(sym.rect) ) self.wait() self.wait() self.add(line_group) self.play( dt_tracker.set_value, 0.01, run_time=5, ) self.play( FadeOut(syms), FadeOut(line_group), ) # def get_line_group(self, graph, input_tracker, nudge_tracker, corner_index): get_x = input_tracker.get_value get_dx = nudge_tracker.get_value def get_graph_point(x): return graph.point_from_proportion( inverse_interpolate( self.graph_x_min, self.graph_x_max, x, ) ) def get_corner(p1, p2): result = np.array(p1) result[corner_index] = p2[corner_index] return result line_group = VGroup( Line(color=WHITE), Line(color=RED), Line(color=WHITE, stroke_width=2), ) def update_line_group(group): dxl, dTl, tl = group p0 = get_graph_point(get_x()) p2 = get_graph_point(get_x() + get_dx()) p1 = get_corner(p0, p2) dxl.set_points_as_corners([p0, p1]) dTl.set_points_as_corners([p1, p2]) tl.set_points_as_corners([p0, p2]) tl.scale( self.tangent_line_length / tl.get_length() ) line_group.add_updater(update_line_group) return line_group class ShowCurvatureToRateOfChangeIntuition(ShowEvolvingTempGraphWithArrows): CONFIG = { "freq_amplitude_pairs": [ (1, 0.7), (2, 1), (3, 0.5), (4, 0.3), (5, 0.3), (7, 0.2), ], "arrow_xs": [0.7, 3.8, 4.6, 5.4, 6.2, 9.3], "arrow_scale_factor": 0.2, "max_magnitude": 1.0, "wait_time": 20, } def let_play(self): arrows = self.arrows curves = VGroup(*[ self.get_mini_curve( inverse_interpolate( self.graph_x_min, self.graph_x_max, x, ) ) for x in self.arrow_xs ]) curves.set_stroke(WHITE, 5) curve_words = VGroup() for curve, arrow in zip(curves, arrows): word = OldTexText("curve") word.scale(0.7) word.next_to(curve, arrow.get_vector()[1] * DOWN, SMALL_BUFF) curve_words.add(word) self.remove(arrows) self.play( ShowCreation(curves), LaggedStartMap(FadeIn, curve_words), self.y_label.set_fill, {"opacity": 0}, ) self.wait() self.add(*arrows, curves) self.play(LaggedStartMap(GrowArrow, arrows)) self.wait() self.play(FadeOut(VGroup(curves, curve_words))) self.add(arrows) super().let_play() def get_mini_curve(self, alpha, d_alpha=0.02): result = VMobject() result.pointwise_become_partial( self.graph, alpha - d_alpha, alpha + d_alpha, ) return result class DiscreteSetup(ShowEvolvingTempGraphWithArrows): CONFIG = { "step_size": 1, "rod_piece_size_ratio": 1 / 3, "dashed_line_stroke_opacity": 1.0, "dot_radius": DEFAULT_DOT_RADIUS, "freq_amplitude_pairs": [ (1, 0.5), (2, 1), (3, 0.5), (4, 0.3), (5, 0.3), (7, 0.2), (21, 0.1), # (41, 0.05), ], } def construct(self): self.add_axes() self.add_graph() self.discretize() self.let_time_pass() self.show_nieghbor_rule() self.focus_on_three_points() self.show_difference_formula() self.gut_check_new_interpretation() self.write_second_difference() self.emphasize_final_expression() def add_axes(self): super().add_axes() self.axes.shift(MED_SMALL_BUFF * LEFT) def add_graph(self): points = self.get_points(time=0) graph = VMobject() graph.set_points_smoothly(points) graph.color_using_background_image("VerticalTempGradient") self.add(graph) self.graph = graph self.points = points def discretize(self): axes = self.axes x_axis = axes.x_axis graph = self.graph piecewise_graph = CurvesAsSubmobjects(graph) dots = self.get_dots() v_lines = VGroup(*map(self.get_v_line, dots)) rod_pieces = VGroup() for x in self.get_sample_inputs(): piece = Line(LEFT, RIGHT) piece.set_width( self.step_size * self.rod_piece_size_ratio ) piece.move_to(axes.c2p(x, 0)) piece.set_color( self.rod_point_to_color(piece.get_center()) ) rod_pieces.add(piece) word = OldTexText("Discrete version") word.scale(1.5) word.next_to(x_axis, UP) word.set_stroke(BLACK, 3, background=True) self.remove(graph) self.play( ReplacementTransform( piecewise_graph, dots, ), Write(word, run_time=1) ) self.add(v_lines, word) self.play( x_axis.fade, 0.8, TransformFromCopy( x_axis.tick_marks[1:], rod_pieces, ), LaggedStartMap(ShowCreation, v_lines) ) self.play(FadeOut(word)) self.wait() self.rod_pieces = rod_pieces self.dots = dots self.v_lines = v_lines def let_time_pass(self): dots = self.dots t_tracker = ValueTracker(0) t_tracker.add_updater(lambda m, dt: m.increment_value(dt)) self.add(t_tracker) self.add_clock() self.time_label.next_to(self.clock, DOWN) self.time_label.add_updater( lambda m: m.set_value(t_tracker.get_value()) ) dots.add_updater(lambda d: d.become( self.get_dots(t_tracker.get_value()) )) run_time = 5 self.play( ClockPassesTime( self.clock, run_time=run_time, hours_passed=run_time, ), ) t_tracker.clear_updaters() t_tracker.set_value(run_time) self.wait() self.play( t_tracker.set_value, 0, FadeOut(self.clock), FadeOut(self.time_label), ) self.remove(t_tracker) dots.clear_updaters() def show_nieghbor_rule(self): dots = self.dots rod_pieces = self.rod_pieces index = self.index = 2 p1, p2, p3 = rod_pieces[index:index + 3] d1, d2, d3 = dots[index:index + 3] point_label = OldTexText("Point") neighbors_label = OldTexText("Neighbors") words = VGroup(point_label, neighbors_label) for word in words: word.scale(0.7) word.add_background_rectangle() point_label.next_to(p2, DOWN) neighbors_label.next_to(p2, UP, buff=1) bottom = neighbors_label.get_bottom() kw = { "buff": 0.1, "stroke_width": 2, "tip_length": 0.15 } arrows = VGroup( Arrow(bottom, p1.get_center(), **kw), Arrow(bottom, p3.get_center(), **kw), ) arrows.set_color(WHITE) dot = Dot() dot.set_fill(GREY, opacity=0.2) dot.replace(p2) dot.scale(3) self.play( dot.scale, 0, dot.set_opacity, 0, FadeIn(point_label, DOWN) ) self.play( FadeIn(neighbors_label, DOWN), *map(GrowArrow, arrows) ) self.wait() # Let d2 change self.play( d1.set_y, 3, d3.set_y, 3, ) def get_v(): return 0.25 * np.sum([ d1.get_y(), -2 * d2.get_y(), + d3.get_y(), ]) v_vect_fader = ValueTracker(0) v_vect = always_redraw( lambda: Vector( get_v() * UP, color=temperature_to_color( get_v(), -2, 2, ), ).shift(d2.get_center()).set_opacity( v_vect_fader.get_value(), ) ) d2.add_updater( lambda d, dt: d.shift( get_v() * dt * UP, ) ) self.add(v_vect) self.play(v_vect_fader.set_value, 1) self.wait(3) self.play( d1.set_y, 0, d3.set_y, 0, ) self.wait(4) self.play(FadeOut(VGroup( point_label, neighbors_label, arrows ))) self.v_vect = v_vect self.example_pieces = VGroup(p1, p2, p3) self.example_dots = VGroup(d1, d2, d3) def focus_on_three_points(self): dots = self.example_dots d1, d2, d3 = dots pieces = self.example_pieces y_axis = self.axes.y_axis x_labels, T_labels = [ VGroup(*[ OldTex("{}_{}".format(s, i)) for i in [1, 2, 3] ]).scale(0.8) for s in ("x", "T") ] for xl, piece in zip(x_labels, pieces): xl.next_to(piece, DOWN) xl.add_background_rectangle() for Tl, dot in zip(T_labels, dots): Tl.dot = dot Tl.add_updater(lambda m: m.next_to( m.dot, RIGHT, SMALL_BUFF )) Tl.add_background_rectangle() T1, T2, T3 = T_labels d2.movement_updater = d2.get_updaters()[0] dots.clear_updaters() self.remove(self.v_vect) self.play( ShowCreationThenFadeAround(pieces), FadeOut(self.dots[:self.index]), FadeOut(self.v_lines[:self.index]), FadeOut(self.rod_pieces[:self.index]), FadeOut(self.dots[self.index + 3:]), FadeOut(self.v_lines[self.index + 3:]), FadeOut(self.rod_pieces[self.index + 3:]), ) self.play(LaggedStartMap( FadeInFrom, x_labels, lambda m: (m, LEFT), lag_ratio=0.3, run_time=2, )) self.play( d3.set_y, 1, d2.set_y, 0.25, d1.set_y, 0, ) self.wait() self.play(LaggedStart(*[ TransformFromCopy(xl, Tl) for xl, Tl in zip(x_labels, T_labels) ], lag_ratio=0.3, run_time=2)) self.wait() # Show lines h_lines = VGroup(*map(self.get_h_line, dots)) hl1, hl2, hl3 = h_lines average_pointer = ArrowTip( start_angle=0, length=0.2, ) average_pointer.set_color(YELLOW) average_pointer.stretch(0.25, 1) average_pointer.add_updater( lambda m: m.move_to( 0.5 * (hl1.get_start() + hl3.get_start()), RIGHT ) ) average_arrows = always_redraw(lambda: VGroup(*[ Arrow( hl.get_start(), average_pointer.get_right(), color=WHITE, buff=0.0, ) for hl in [hl1, hl3] ])) average_label = OldTex( "{T_1", "+", "T_3", "\\over", "2}" ) average_label.scale(0.5) average_label.add_updater(lambda m: m.next_to( average_pointer, LEFT, SMALL_BUFF )) average_rect = SurroundingRectangle(average_label) average_rect.add_updater( lambda m: m.move_to(average_label) ) average_words = OldTexText("Neighbor\\\\average") average_words.match_width(average_rect) average_words.match_color(average_rect) average_words.add_updater( lambda m: m.next_to(average_rect, UP, SMALL_BUFF) ) mini_T1 = average_label.get_part_by_tex("T_1") mini_T3 = average_label.get_part_by_tex("T_3") for mini, line in (mini_T1, hl1), (mini_T3, hl3): mini.save_state() mini.next_to(line, LEFT, SMALL_BUFF) self.add(hl1, hl3, T_labels) y_axis.remove(y_axis.numbers) self.play( GrowFromPoint(hl1, hl1.get_end()), GrowFromPoint(hl3, hl3.get_end()), TransformFromCopy( T1, mini_T1, ), TransformFromCopy( T3, mini_T3, ), FadeOut(y_axis.numbers), y_axis.set_stroke, {"width": 1}, ) self.play( FadeIn(average_pointer), Restore(mini_T1), Restore(mini_T3), FadeIn(average_label[1]), FadeIn(average_label[3:]), *map(GrowArrow, average_arrows) ) self.add(average_arrows, average_label) self.play( ShowCreation(average_rect), FadeIn(average_words), ) self.play( GrowFromPoint(hl2, hl2.get_end()) ) self.wait() # Show formula formula = OldTex( "\\left(", "{T_1", "+", "T_3", "\\over", "2}", "-", "T_2", "\\right)" ) formula.to_corner(UR, buff=MED_LARGE_BUFF) formula.shift(1.7 * LEFT) brace = Brace(formula, DOWN) diff_value = DecimalNumber(include_sign=True) diff_value.add_updater(lambda m: m.set_value( y_axis.p2n(average_pointer.get_right()) - y_axis.p2n(d2.get_center()) )) diff_value.next_to(brace, DOWN) self.play( ReplacementTransform( average_label.deepcopy(), formula[1:1 + len(average_label)] ), TransformFromCopy(T2, formula[-2]), FadeIn(formula[-3]), FadeIn(formula[-1]), FadeIn(formula[0]), GrowFromCenter(brace), FadeIn(diff_value) ) self.wait() # Changes self.play(FadeIn(self.v_vect)) d2.add_updater(d2.movement_updater) self.wait(5) self.play( d3.set_y, 3, d1.set_y, 2.5, d2.set_y, -2, ) self.wait(5) self.play( d3.set_y, 1, d1.set_y, -1, ) self.wait(8) # Show derivative lhs = OldTex( "{dT_2", "\\over", "dt}", "=", "\\alpha" ) dt = lhs.get_part_by_tex("dt") alpha = lhs.get_part_by_tex("\\alpha") lhs.next_to(formula, LEFT, SMALL_BUFF) self.play(Write(lhs)) self.play(ShowCreationThenFadeAround(dt)) self.wait() self.play(ShowCreationThenFadeAround(alpha)) self.wait() self.play( FadeOut(brace), FadeOut(diff_value), ) self.lhs = lhs self.rhs = formula def show_difference_formula(self): lhs = self.lhs rhs = self.rhs d1, d2, d3 = self.example_dots new_rhs = OldTex( "=", "{\\alpha", "\\over", "2}", "\\left(", "(", "T_3", "-", "T_2", ")", "-", "(", "T_2", "-", "T_1", ")", "\\right)" ) big_parens = VGroup( new_rhs.get_part_by_tex("\\left("), new_rhs.get_part_by_tex("\\right)"), ) for paren in big_parens: paren.scale(2) new_rhs.next_to(rhs, DOWN) new_rhs.align_to(lhs.get_part_by_tex("="), LEFT) def p2p_anim(mob1, mob2, tex, index=0): return TransformFromCopy( mob1.get_parts_by_tex(tex)[index], mob2.get_parts_by_tex(tex)[index], ) self.play( p2p_anim(lhs, new_rhs, "="), p2p_anim(rhs, new_rhs, "\\left("), p2p_anim(rhs, new_rhs, "\\right)"), p2p_anim(lhs, new_rhs, "\\alpha"), p2p_anim(rhs, new_rhs, "\\over"), p2p_anim(rhs, new_rhs, "2"), ) self.play( p2p_anim(rhs, new_rhs, "T_3"), p2p_anim(rhs, new_rhs, "-"), p2p_anim(rhs, new_rhs, "T_2"), FadeIn(new_rhs.get_parts_by_tex("(")[1]), FadeIn(new_rhs.get_parts_by_tex(")")[0]), ) self.play( p2p_anim(rhs, new_rhs, "T_2", -1), p2p_anim(rhs, new_rhs, "-", -1), p2p_anim(rhs, new_rhs, "T_1"), FadeIn(new_rhs.get_parts_by_tex("-")[1]), FadeIn(new_rhs.get_parts_by_tex("(")[2]), FadeIn(new_rhs.get_parts_by_tex(")")[1]), ) self.wait() self.rhs2 = new_rhs # Show deltas T1_index = new_rhs.index_of_part_by_tex("T_1") T3_index = new_rhs.index_of_part_by_tex("T_3") diff1 = new_rhs[T1_index - 2:T1_index + 1] diff2 = new_rhs[T3_index:T3_index + 3] brace1 = Brace(diff1, DOWN, buff=SMALL_BUFF) brace2 = Brace(diff2, DOWN, buff=SMALL_BUFF) delta_T1 = OldTex("\\Delta T_1") delta_T1.next_to(brace1, DOWN, SMALL_BUFF) delta_T2 = OldTex("\\Delta T_2") delta_T2.next_to(brace2, DOWN, SMALL_BUFF) minus = OldTex("-") minus.move_to(Line( delta_T1.get_right(), delta_T2.get_left(), )) braces = VGroup(brace1, brace2) deltas = VGroup(delta_T1, delta_T2) kw = { "direction": LEFT, "buff": SMALL_BUFF, "min_num_quads": 2, } lil_brace1 = always_redraw(lambda: Brace( Line(d1.get_left(), d2.get_left()), **kw )) lil_brace2 = always_redraw(lambda: Brace( Line(d2.get_left(), d3.get_left()), **kw )) lil_braces = VGroup(lil_brace1, lil_brace2) lil_delta_T1 = delta_T1.copy() lil_delta_T2 = delta_T2.copy() lil_deltas = VGroup(lil_delta_T1, lil_delta_T2) for brace, delta in zip(lil_braces, lil_deltas): delta.brace = brace delta.add_updater(lambda d: d.next_to( d.brace, LEFT, SMALL_BUFF, )) delta_T1.set_color(BLUE) lil_delta_T1.set_color(BLUE) delta_T2.set_color(RED) lil_delta_T2.set_color(RED) double_difference_brace = Brace(deltas, DOWN) double_difference_words = OldTexText( "Difference of differences" ) double_difference_words.next_to( double_difference_brace, DOWN ) self.play( GrowFromCenter(brace1), GrowFromCenter(lil_brace1), FadeIn(delta_T1), FadeIn(lil_delta_T1), ) self.wait() self.play( GrowFromCenter(brace2), GrowFromCenter(lil_brace2), FadeIn(delta_T2), FadeIn(lil_delta_T2), ) self.wait() self.play( Write(minus), GrowFromCenter(double_difference_brace), Write(double_difference_words), ) self.wait() self.braces = braces self.deltas = deltas self.delta_minus = minus self.lil_braces = lil_braces self.lil_deltas = lil_deltas self.double_difference_brace = double_difference_brace self.double_difference_words = double_difference_words def gut_check_new_interpretation(self): lil_deltas = self.lil_deltas d1, d2, d3 = self.example_dots self.play(ShowCreationThenFadeAround(lil_deltas[0])) self.play(ShowCreationThenFadeAround(lil_deltas[1])) self.wait() self.play( d2.shift, MED_SMALL_BUFF * UP, rate_func=there_and_back, ) self.wait() self.play( d3.set_y, 3, d1.set_y, -0.5, ) self.wait(5) self.play( d3.set_y, 1.5, d1.set_y, -2, ) self.wait(5) def write_second_difference(self): dd_word = self.double_difference_words delta_delta = OldTex("\\Delta \\Delta T_1") delta_delta.set_color(MAROON_B) delta_delta.move_to(dd_word, UP) second_difference_word = OldTexText( "``Second difference''" ) second_difference_word.next_to(delta_delta, DOWN) self.play( FadeOut(dd_word, UP), FadeIn(delta_delta, UP), ) self.wait() self.play( Write(second_difference_word), ) self.wait() # Random play d1, d2, d3 = self.example_dots self.play( d3.set_y, 3, d1.set_y, -0.5, ) self.wait(5) self.play( d3.set_y, 1.5, d1.set_y, -2, ) self.wait(5) self.delta_delta = delta_delta self.second_difference_word = second_difference_word def emphasize_final_expression(self): lhs = self.lhs rhs = self.rhs rhs2 = self.rhs2 old_dd = self.delta_delta dd = old_dd.copy() old_ao2 = rhs2[1:4] ao2 = old_ao2.copy() new_lhs = lhs[:-1] full_rhs = VGroup( lhs[-1], lhs[-2].copy(), rhs, rhs2, self.braces, self.deltas, self.delta_minus, self.double_difference_brace, old_dd, self.second_difference_word, ) new_rhs = VGroup(ao2, dd) new_rhs.arrange(RIGHT, buff=SMALL_BUFF) new_rhs.next_to(new_lhs, RIGHT) self.play( full_rhs.to_edge, DOWN, {"buff": LARGE_BUFF}, ) self.play( TransformFromCopy(old_ao2, ao2), TransformFromCopy(old_dd, dd), ) self.play( ShowCreationThenFadeAround( VGroup(new_lhs, new_rhs) ) ) self.wait() # def get_sample_inputs(self): return np.arange( self.graph_x_min, self.graph_x_max + self.step_size, self.step_size, ) def get_points(self, time=0): return [ self.axes.c2p(x, self.temp_func(x, t=time)) for x in self.get_sample_inputs() ] def get_dots(self, time=0): points = self.get_points(time) dots = VGroup(*[ Dot( point, radius=self.dot_radius ) for point in points ]) dots.color_using_background_image("VerticalTempGradient") return dots def get_dot_dashed_line(self, dot, index, color=False): direction = np.zeros(3) direction[index] = -1 def get_line(): p1 = dot.get_edge_center(direction) p0 = np.array(p1) p0[index] = self.axes.c2p(0, 0)[index] result = DashedLine( p0, p1, stroke_width=2, color=WHITE, stroke_opacity=self.dashed_line_stroke_opacity, ) if color: result.color_using_background_image( "VerticalTempGradient" ) return result return always_redraw(get_line) def get_h_line(self, dot): return self.get_dot_dashed_line(dot, 0, True) def get_v_line(self, dot): return self.get_dot_dashed_line(dot, 1) class ShowFinitelyManyX(DiscreteSetup): def construct(self): self.setup_axes() axes = self.axes axes.fade(1) points = [ axes.c2p(x, 0) for x in self.get_sample_inputs()[1:] ] x_labels = VGroup(*[ OldTex("x_{}".format(i)).next_to( p, DOWN ) for i, p in enumerate(points) ]) self.play(LaggedStartMap( FadeInFromLarge, x_labels )) self.play(LaggedStartMap(FadeOut, x_labels)) self.wait() class DiscreteGraphStillImage1(DiscreteSetup): CONFIG = { "step_size": 1, } def construct(self): self.add_axes() self.add_graph() self.discretize() class DiscreteGraphStillImageFourth(DiscreteGraphStillImage1): CONFIG = { "step_size": 0.25, } class DiscreteGraphStillImageTenth(DiscreteGraphStillImage1): CONFIG = { "step_size": 0.1, "dashed_line_stroke_opacity": 0.25, "dot_radius": 0.04, } class DiscreteGraphStillImageHundredth(DiscreteGraphStillImage1): CONFIG = { "step_size": 0.01, "dashed_line_stroke_opacity": 0.1, "dot_radius": 0.01, } class TransitionToContinuousCase(DiscreteSetup): CONFIG = { "step_size": 0.1, "tangent_line_length": 3, "wait_time": 30, } def construct(self): self.add_axes() self.add_graph() self.show_temperature_difference() self.show_second_derivative() self.show_curvature_examples() self.show_time_changes() def add_graph(self): self.setup_graph() self.play( ShowCreation( self.graph, run_time=3, ) ) self.wait() def show_temperature_difference(self): x_tracker = ValueTracker(2) dx_tracker = ValueTracker(1) line_group = self.get_line_group( x_tracker, dx_tracker, ) dx_line, dT_line, tan_line, dx_sym, dT_sym = line_group tan_line.set_stroke(width=0) brace = Brace(dx_line, UP) fixed_distance = OldTexText("Fixed\\\\distance") fixed_distance.scale(0.7) fixed_distance.next_to(brace, UP) delta_T = OldTex("\\Delta T") delta_T.move_to(dT_sym, LEFT) self.play( ShowCreation(VGroup(dx_line, dT_line)), FadeIn(delta_T, LEFT) ) self.play( GrowFromCenter(brace), FadeInFromDown(fixed_distance), ) self.wait() self.play( FadeOut(delta_T, UP), FadeIn(dT_sym, DOWN), FadeOut(brace, UP), FadeOut(fixed_distance, UP), FadeIn(dx_sym, DOWN), ) self.add(line_group) self.play( dx_tracker.set_value, 0.01, run_time=5 ) self.wait() self.play( dx_tracker.set_value, 0.3, ) # Show rate of change to_zero = OldTex("\\rightarrow 0") to_zero.match_height(dT_sym) to_zero.next_to(dT_sym, buff=SMALL_BUFF) ratio = OldTex( "{\\partial T", "\\over", "\\partial x}" ) ratio[0].match_style(dT_sym) ratio.to_edge(UP) self.play(ShowCreationThenFadeAround( dT_sym, surrounding_rectangle_config={ "buff": 0.05, "stroke_width": 1, } )) self.play(GrowFromPoint(to_zero, dT_sym.get_right())) self.wait() self.play( TransformFromCopy( dT_sym, ratio.get_part_by_tex("\\partial T") ), TransformFromCopy( dx_sym, ratio.get_part_by_tex("\\partial x") ), Write(ratio.get_part_by_tex("\\over")) ) self.play( ShowCreation( tan_line.copy().set_stroke(width=2), remover=True ), FadeOut(to_zero), ) tan_line.set_stroke(width=2) self.wait() # Look at neighbors x0 = x_tracker.get_value() dx = dx_tracker.get_value() v_line, lv_line, rv_line = v_lines = VGroup(*[ self.get_v_line(x) for x in [x0, x0 - dx, x0 + dx] ]) v_lines[1:].set_color(BLUE) self.play(ShowCreation(v_line)) self.play( TransformFromCopy(v_line, lv_line), TransformFromCopy(v_line, rv_line), ) self.wait() self.play( FadeOut(v_lines[1:]), ApplyMethod( dx_tracker.set_value, 0.01, run_time=2 ), ) self.line_group = line_group self.deriv = ratio self.x_tracker = x_tracker self.dx_tracker = dx_tracker self.v_line = v_line def show_second_derivative(self): x_tracker = self.x_tracker deriv = self.deriv v_line = self.v_line deriv_of_deriv = OldTex( "{\\partial", "\\left(", "{\\partial T", "\\over", "\\partial x}", "\\right)", "\\over", "\\partial x}" ) deriv_of_deriv.set_color_by_tex("\\partial T", RED) deriv_of_deriv.to_edge(UP) dT_index = deriv_of_deriv.index_of_part_by_tex("\\partial T") inner_deriv = deriv_of_deriv[dT_index:dT_index + 3] self.play( ReplacementTransform(deriv, inner_deriv), Write(VGroup(*filter( lambda m: m not in inner_deriv, deriv_of_deriv, ))) ) v_line.add_updater(lambda m: m.become( self.get_v_line(x_tracker.get_value()) )) for change in [-0.1, 0.1]: self.play( x_tracker.increment_value, change, run_time=3 ) # Write second deriv second_deriv = OldTex( "{\\partial^2 T", "\\over", "\\partial x^2}" ) second_deriv[0].set_color(RED) eq = OldTex("=") eq.next_to(deriv_of_deriv, RIGHT) second_deriv.next_to(eq, RIGHT) second_deriv.align_to(deriv_of_deriv, DOWN) eq.match_y(second_deriv.get_part_by_tex("\\over")) self.play(Write(eq)) self.play( TransformFromCopy( deriv_of_deriv.get_parts_by_tex("\\partial")[:2], second_deriv.get_parts_by_tex("\\partial^2 T"), ), ) self.play( Write(second_deriv.get_part_by_tex("\\over")), TransformFromCopy( deriv_of_deriv.get_parts_by_tex("\\partial x"), second_deriv.get_parts_by_tex("\\partial x"), ), ) self.wait() def show_curvature_examples(self): x_tracker = self.x_tracker v_line = self.v_line line_group = self.line_group x_tracker.set_value(3.6) self.wait() self.play( x_tracker.set_value, 3.8, run_time=4, ) self.wait() x_tracker.set_value(6.2) self.wait() self.play( x_tracker.set_value, 6.4, run_time=4, ) self.wait() # dx = 0.2 neighbor_lines = always_redraw(lambda: VGroup(*[ self.get_v_line( x_tracker.get_value() + u * dx, line_class=Line, ) for u in [-1, 1] ])) neighbor_lines.set_color(BLUE) self.play(FadeOut(line_group)) self.play(*[ TransformFromCopy(v_line, nl) for nl in neighbor_lines ]) self.add(neighbor_lines) self.play( x_tracker.set_value, 5, run_time=5, rate_func=lambda t: smooth(t, 3) ) v_line.clear_updaters() self.play( FadeOut(v_line), FadeOut(neighbor_lines), ) self.wait() def show_time_changes(self): self.setup_clock() graph = self.graph time_label = self.time_label clock = self.clock time_label.next_to(clock, DOWN) graph.add_updater(self.update_graph) time_label.add_updater( lambda d, dt: d.increment_value(dt) ) self.add(time_label) self.add_arrows() self.play( ClockPassesTime( clock, run_time=self.wait_time, hours_passed=self.wait_time, ), ) # def get_v_line(self, x, line_class=DashedLine, stroke_width=2): axes = self.axes graph = self.graph line = line_class( axes.c2p(x, 0), graph.point_from_proportion( inverse_interpolate( self.graph_x_min, self.graph_x_max, x, ) ), stroke_width=stroke_width, ) return line def get_line_group(self, x_tracker, dx_tracker, dx_tex="\\partial x", dT_tex="\\partial T", max_sym_width=0.5, ): graph = self.graph get_x = x_tracker.get_value get_dx = dx_tracker.get_value dx_line = Line(color=WHITE) dT_line = Line(color=RED) tan_line = Line(color=WHITE) lines = VGroup(dx_line, dT_line, tan_line) lines.set_stroke(width=2) dx_sym = OldTex(dx_tex) dT_sym = OldTex(dT_tex) dT_sym.match_color(dT_line) syms = VGroup(dx_sym, dT_sym) group = VGroup(*lines, *syms) def update_group(group): dxl, dTl, tanl, dxs, dTs = group x = get_x() dx = get_dx() p0, p2 = [ graph.point_from_proportion( inverse_interpolate( self.graph_x_min, self.graph_x_max, x ) ) for x in [x, x + dx] ] p1 = np.array([p2[0], *p0[1:]]) dxl.put_start_and_end_on(p0, p1) dTl.put_start_and_end_on(p1, p2) tanl.put_start_and_end_on(p0, p2) tanl.scale( self.tangent_line_length / tanl.get_length() ) dxs.match_width(dxl) dTs.set_height(0.7 * dTl.get_height()) for sym in dxs, dTs: if sym.get_width() > max_sym_width: sym.set_width(max_sym_width) dxs.next_to( dxl, -dTl.get_vector(), SMALL_BUFF, ) dTs.next_to( dTl, dxl.get_vector(), SMALL_BUFF, ) group.add_updater(update_group) return group class ShowManyVLines(TransitionToContinuousCase): CONFIG = { "wait_time": 20, "max_denom": 10, "x_step": 0.025, } def construct(self): self.add_axes() self.add_graph() self.add_v_lines() self.show_time_changes() def add_arrows(self): pass def add_v_lines(self): axes = self.axes v_lines = always_redraw(lambda: VGroup(*[ self.get_v_line( x, line_class=Line, stroke_width=0.5, ) for x in np.arange(0, 10, self.x_step) ])) group = VGroup(*v_lines) x_pointer = ArrowTip(start_angle=PI / 2) x_pointer.set_color(WHITE) x_pointer.next_to(axes.c2p(0, 0), DOWN, buff=0) x_eq = VGroup( OldTex("x="), DecimalNumber(0) ) x_eq.add_updater( lambda m: m.arrange(RIGHT, buff=SMALL_BUFF) ) x_eq.add_updater( lambda m: m[1].set_value(axes.x_axis.p2n(x_pointer.get_top())) ) x_eq.add_updater(lambda m: m.next_to( x_pointer, DOWN, SMALL_BUFF, submobject_to_align=x_eq[0] )) self.add(x_pointer, x_eq) self.play( Write( group, remover=True, lag_ratio=self.x_step / 2, run_time=6, ), ApplyMethod( x_pointer.next_to, axes.c2p(10, 0), DOWN, {"buff": 0}, rate_func=linear, run_time=5, ), ) self.add(v_lines) x_eq.clear_updaters() self.play( FadeOut(x_eq), FadeOut(x_pointer), ) class ShowNewtonsLawGraph(Scene): CONFIG = { "k": 0.2, "initial_water_temp": 80, "room_temp": 20, "delta_T_color": YELLOW, } def construct(self): self.setup_axes() self.show_temperatures() self.show_graph() self.show_equation() self.talk_through_examples() def setup_axes(self): axes = Axes( x_min=0, x_max=10, y_min=0, y_max=100, y_axis_config={ "unit_size": 0.06, "tick_frequency": 10, }, center_point=5 * LEFT + 2.5 * DOWN ) x_axis = axes.x_axis y_axis = axes.y_axis y_axis.add_numbers(*range(20, 100, 20)) x_axis.add_numbers(*range(1, 11)) x_axis.label = OldTexText("Time") x_axis.label.next_to(x_axis, DOWN, MED_SMALL_BUFF) y_axis.label = OldTex("\\text{Temperature}") y_axis.label.next_to(y_axis, RIGHT, buff=SMALL_BUFF) y_axis.label.align_to(axes, UP) for axis in [x_axis, y_axis]: axis.add(axis.label) self.add(axes) self.axes = axes def show_temperatures(self): axes = self.axes water_dot = Dot() water_dot.color_using_background_image("VerticalTempGradient") water_dot.move_to(axes.c2p(0, self.initial_water_temp)) room_line = DashedLine( axes.c2p(0, self.room_temp), axes.c2p(10, self.room_temp), ) room_line.set_color(BLUE) room_line.color_using_background_image("VerticalTempGradient") water_arrow = Vector(LEFT, color=WHITE) water_arrow.next_to(water_dot, RIGHT, SMALL_BUFF) water_words = OldTexText( "Initial water\\\\temperature" ) water_words.scale(0.7) water_words.next_to(water_arrow, RIGHT) room_words = OldTexText("Room temperature") room_words.scale(0.7) room_words.next_to(room_line, DOWN, SMALL_BUFF) self.play( FadeIn(water_dot, RIGHT), GrowArrow(water_arrow), Write(water_words), run_time=1, ) self.play(ShowCreation(room_line)) self.play(FadeInFromDown(room_words)) self.wait() self.set_variables_as_attrs( water_dot, water_arrow, water_words, room_line, room_words, ) def show_graph(self): axes = self.axes water_dot = self.water_dot k = self.k rt = self.room_temp t0 = self.initial_water_temp graph = axes.get_graph( lambda t: rt + (t0 - rt) * np.exp(-k * t) ) graph.color_using_background_image("VerticalTempGradient") def get_x(): return axes.x_axis.p2n(water_dot.get_center()) brace_line = always_redraw(lambda: Line( axes.c2p(get_x(), rt), water_dot.get_center(), stroke_width=0, )) brace = always_redraw( lambda: Brace( brace_line, RIGHT, buff=SMALL_BUFF ) ) delta_T = OldTex("\\Delta T") delta_T.set_color(self.delta_T_color) delta_T.add_updater(lambda m: m.next_to( brace, RIGHT, SMALL_BUFF )) self.add(brace_line) self.play( GrowFromCenter(brace), Write(delta_T), ) self.play( ShowCreation(graph), UpdateFromFunc( water_dot, lambda m: m.move_to(graph.get_end()) ), run_time=10, rate_func=linear, ) self.wait() self.graph = graph self.brace = brace self.delta_T = delta_T def show_equation(self): delta_T = self.delta_T equation = OldTex( "{d ({\\Delta T}) \\over dt} = -k \\cdot {\\Delta T}", tex_to_color_map={ "{\\Delta T}": self.delta_T_color, "-k": WHITE, "=": WHITE, } ) equation.to_corner(UR) equation.shift(LEFT) delta_T_parts = equation.get_parts_by_tex("\\Delta T") eq_i = equation.index_of_part_by_tex("=") deriv = equation[:eq_i] prop_to = equation.get_part_by_tex("-k") parts = VGroup(deriv, prop_to, delta_T_parts[1]) words = OldTexText( "Rate of change", "is proportional to", "itself", ) words.scale(0.7) words.next_to(equation, DOWN) colors = [BLUE, WHITE, YELLOW] for part, word, color in zip(parts, words, colors): part.word = word word.set_color(color) word.save_state() words[0].next_to(parts[0], DOWN) self.play( TransformFromCopy( VGroup(delta_T), delta_T_parts, ), Write(VGroup(*filter( lambda p: p not in delta_T_parts, equation ))) ) rects = VGroup() for part in parts: rect = SurroundingRectangle( part, color=part.word.get_color(), buff=SMALL_BUFF, stroke_width=2, ) anims = [ ShowCreation(rect), FadeIn(part.word), ] if part is parts[1]: anims.append(Restore(words[0])) self.play(*anims) rects.add(rect) self.play(FadeOut(rects, lag_ratio=0.2)) self.equation = equation self.equation_words = words def talk_through_examples(self): dot = self.water_dot graph = self.graph self.play( MoveAlongPath( dot, graph, rate_func=lambda t: smooth(1 - t), run_time=2, ) ) # def get_slope_line(self, graph, x): pass
from manim_imports_ext import * # import scipy class FourierCirclesScene(Scene): CONFIG = { "n_vectors": 10, "big_radius": 2, "colors": [ BLUE_D, BLUE_C, BLUE_E, GREY_BROWN, ], "circle_style": { "stroke_width": 2, }, "vector_config": { "buff": 0, "max_tip_length_to_length_ratio": 0.35, "fill_opacity": 0.75, }, "circle_config": { "stroke_width": 1, "stroke_opacity": 0.75, }, "base_frequency": 1, "slow_factor": 0.25, "center_point": ORIGIN, "parametric_function_step_size": 0.01, "drawn_path_color": YELLOW, "drawn_path_stroke_width": 2, } def setup(self): self.slow_factor_tracker = ValueTracker( self.slow_factor ) self.vector_clock = ValueTracker(0) self.vector_clock.add_updater( lambda m, dt: m.increment_value( self.get_slow_factor() * dt ) ) self.add(self.vector_clock) def get_slow_factor(self): return self.slow_factor_tracker.get_value() def get_vector_time(self): return self.vector_clock.get_value() # def get_freqs(self): n = self.n_vectors all_freqs = list(range(n // 2, -n // 2, -1)) all_freqs.sort(key=abs) return all_freqs def get_coefficients(self): return [complex(0) for x in range(self.n_vectors)] def get_color_iterator(self): return it.cycle(self.colors) def get_rotating_vectors(self, freqs=None, coefficients=None): vectors = VGroup() self.center_tracker = VectorizedPoint(self.center_point) if freqs is None: freqs = self.get_freqs() if coefficients is None: coefficients = self.get_coefficients() last_vector = None for freq, coefficient in zip(freqs, coefficients): if last_vector is not None: center_func = last_vector.get_end else: center_func = self.center_tracker.get_location vector = self.get_rotating_vector( coefficient=coefficient, freq=freq, center_func=center_func ) vectors.add(vector) last_vector = vector return vectors def get_rotating_vector(self, coefficient, freq, center_func): vector = Vector(RIGHT, **self.vector_config) vector.scale(abs(coefficient)) if abs(coefficient) == 0: phase = 0 else: phase = np.log(coefficient).imag vector.rotate(phase, about_point=ORIGIN) vector.freq = freq vector.coefficient = coefficient vector.center_func = center_func vector.add_updater(self.update_vector) return vector def update_vector(self, vector, dt): time = self.get_vector_time() coef = vector.coefficient freq = vector.freq phase = np.log(coef).imag vector.set_length(abs(coef)) vector.set_angle(phase + time * freq * TAU) vector.shift(vector.center_func() - vector.get_start()) return vector def get_circles(self, vectors): return VGroup(*[ self.get_circle( vector, color=color ) for vector, color in zip( vectors, self.get_color_iterator() ) ]) def get_circle(self, vector, color=BLUE): circle = Circle(color=color, **self.circle_config) circle.center_func = vector.get_start circle.radius_func = vector.get_length circle.add_updater(self.update_circle) return circle def update_circle(self, circle): circle.set_width(2 * circle.radius_func()) circle.move_to(circle.center_func()) return circle def get_vector_sum_path(self, vectors, color=YELLOW): coefs = [v.coefficient for v in vectors] freqs = [v.freq for v in vectors] center = vectors[0].get_start() path = ParametricCurve( lambda t: center + reduce(op.add, [ complex_to_R3(coef * np.exp(TAU * 1j * freq * t)) for coef, freq in zip(coefs, freqs) ]), t_min=0, t_max=1, color=color, step_size=self.parametric_function_step_size, ) return path # TODO, this should be a general animated mobect def get_drawn_path_alpha(self): return self.get_vector_time() def get_drawn_path(self, vectors, stroke_width=None, fade_rate=0.2, **kwargs): if stroke_width is None: stroke_width = self.drawn_path_stroke_width path = self.get_vector_sum_path(vectors, **kwargs) path.set_stroke(self.drawn_path_color, stroke_width) self.add_path_fader(path, fade_rate) return path def add_path_fader(self, path, fade_rate=0.2): stroke_width = np.max(path.get_stroke_width()) stroke_opacity = np.max(path.get_stroke_opacity()) def update_path(path_, dt): alpha = self.get_vector_time() n = path_.get_num_points() fade_factors = (np.linspace(0, 1, n) - alpha) % 1 fade_factors = fade_factors**fade_rate path_.set_stroke( width=stroke_width * fade_factors, opacity=stroke_opacity * fade_factors, ) return path_ path.add_updater(update_path) return path def get_y_component_wave(self, vectors, left_x=1, color=PINK, n_copies=2, right_shift_rate=5): path = self.get_vector_sum_path(vectors) wave = ParametricCurve( lambda t: op.add( right_shift_rate * t * LEFT, path.function(t)[1] * UP ), t_min=path.t_min, t_max=path.t_max, color=color, ) wave_copies = VGroup(*[ wave.copy() for x in range(n_copies) ]) wave_copies.arrange(RIGHT, buff=0) top_point = wave_copies.get_top() wave.creation = ShowCreation( wave, run_time=(1 / self.get_slow_factor()), rate_func=linear, ) cycle_animation(wave.creation) wave.add_updater(lambda m: m.shift( (m.get_left()[0] - left_x) * LEFT )) def update_wave_copies(wcs): index = int( wave.creation.total_time * self.get_slow_factor() ) wcs[:index].match_style(wave) wcs[index:].set_stroke(width=0) wcs.next_to(wave, RIGHT, buff=0) wcs.align_to(top_point, UP) wave_copies.add_updater(update_wave_copies) return VGroup(wave, wave_copies) def get_wave_y_line(self, vectors, wave): return DashedLine( vectors[-1].get_end(), wave[0].get_end(), stroke_width=1, dash_length=DEFAULT_DASH_LENGTH * 0.5, ) # Computing Fourier series # i.e. where all the math happens def get_coefficients_of_path(self, path, n_samples=10000, freqs=None): if freqs is None: freqs = self.get_freqs() dt = 1 / n_samples ts = np.arange(0, 1, dt) samples = np.array([ path.point_from_proportion(t) for t in ts ]) samples -= self.center_point complex_samples = samples[:, 0] + 1j * samples[:, 1] result = [] for freq in freqs: riemann_sum = np.array([ np.exp(-TAU * 1j * freq * t) * cs for t, cs in zip(ts, complex_samples) ]).sum() * dt result.append(riemann_sum) return result class FourierSeriesIntroBackground4(FourierCirclesScene): CONFIG = { "n_vectors": 4, "center_point": 4 * LEFT, "run_time": 30, "big_radius": 1.5, } def construct(self): circles = self.get_circles() path = self.get_drawn_path(circles) wave = self.get_y_component_wave(circles) h_line = always_redraw( lambda: self.get_wave_y_line(circles, wave) ) # Why? circles.update(-1 / self.camera.frame_rate) # self.add(circles, path, wave, h_line) self.wait(self.run_time) def get_ks(self): return np.arange(1, 2 * self.n_vectors + 1, 2) def get_freqs(self): return self.base_frequency * self.get_ks() def get_coefficients(self): return self.big_radius / self.get_ks() class FourierSeriesIntroBackground8(FourierSeriesIntroBackground4): CONFIG = { "n_vectors": 8, } class FourierSeriesIntroBackground12(FourierSeriesIntroBackground4): CONFIG = { "n_vectors": 12, } class FourierSeriesIntroBackground20(FourierSeriesIntroBackground4): CONFIG = { "n_vectors": 20, } class FourierOfPiSymbol(FourierCirclesScene): CONFIG = { "n_vectors": 101, "center_point": ORIGIN, "slow_factor": 0.1, "n_cycles": 1, "tex": "\\pi", "start_drawn": False, "max_circle_stroke_width": 1, } def construct(self): self.add_vectors_circles_path() for n in range(self.n_cycles): self.run_one_cycle() def add_vectors_circles_path(self): path = self.get_path() coefs = self.get_coefficients_of_path(path) for freq, coef in zip(self.get_freqs(), coefs): print(freq, "\t", coef) vectors = self.get_rotating_vectors(coefficients=coefs) circles = self.get_circles(vectors) self.set_decreasing_stroke_widths(circles) # approx_path = self.get_vector_sum_path(circles) drawn_path = self.get_drawn_path(vectors) if self.start_drawn: self.vector_clock.increment_value(1) self.add(path) self.add(vectors) self.add(circles) self.add(drawn_path) self.vectors = vectors self.circles = circles self.path = path self.drawn_path = drawn_path def run_one_cycle(self): time = 1 / self.slow_factor self.wait(time) def set_decreasing_stroke_widths(self, circles): mcsw = self.max_circle_stroke_width for k, circle in zip(it.count(1), circles): circle.set_stroke(width=max( # mcsw / np.sqrt(k), mcsw / k, mcsw, )) return circles def get_path(self): tex_mob = OldTex(self.tex) tex_mob.set_height(6) path = tex_mob.family_members_with_points()[0] path.set_fill(opacity=0) path.set_stroke(WHITE, 1) return path class FourierOfTexPaths(FourierOfPiSymbol): CONFIG = { "n_vectors": 100, "name_color": WHITE, "animated_name": "Abc", "conjoined": False, "time_per_symbol": 5, "slow_factor": 1 / 5, "parametric_function_step_size": 0.001, "max_circle_stroke_width": 1.0, "vector_config": { "buff": 0, "fill_opacity": 0.75, "thickness": 0.02, "max_tip_length_to_length_ratio": 0.5, "max_width_to_length_ratio": 0.05, }, } def construct(self): name = OldTexText(self.animated_name) if self.conjoined: new_name = VMobject() for path in name.family_members_with_points(): new_name.append_points(path.get_points()) name = new_name max_width = FRAME_WIDTH - 2 max_height = FRAME_HEIGHT - 2 name.set_width(max_width) if name.get_height() > max_height: name.set_height(max_height) frame = self.camera.frame frame.save_state() vectors = None circles = None for path in name.family_members_with_points(): subpaths = [path.get_points()] if self.conjoined else path.get_subpaths() for subpath in subpaths: sp_mob = VMobject() sp_mob.set_points(subpath) sp_mob.insert_n_curves(10) sp_mob.set_color("#2561d9") coefs = self.get_coefficients_of_path(sp_mob) new_vectors = self.get_rotating_vectors(coefficients=coefs) new_circles = self.get_circles(new_vectors) self.set_decreasing_stroke_widths(new_circles) drawn_path = self.get_drawn_path(new_vectors) drawn_path.clear_updaters() drawn_path.set_stroke(self.name_color, 1.5) drawn_path.set_fill(opacity=0) static_vectors = self.get_rotating_vectors(coefficients=coefs) static_circles = self.get_circles(static_vectors) self.set_decreasing_stroke_widths(static_circles) static_vectors.clear_updaters() static_circles.clear_updaters() if vectors is None: vectors = static_vectors.deepcopy() circles = static_circles.deepcopy() vectors.scale(0) circles.scale(0) self.play( Transform(vectors, static_vectors, remover=True), Transform(circles, static_circles, remover=True), frame.set_max_width, 1.25 * name.get_width(), frame.move_to, path, ) self.add(drawn_path, new_vectors, new_circles) self.vector_clock.set_value(0) self.play( ShowCreation(drawn_path), rate_func=linear, run_time=self.time_per_symbol ) self.remove(new_vectors, new_circles) self.add(static_vectors, static_circles) vectors = static_vectors circles = static_circles self.play( FadeOut(vectors), Restore(frame), run_time=2 ) self.wait(3) class FourierOfPiSymbol5(FourierOfPiSymbol): CONFIG = { "n_vectors": 5, "run_time": 10, } class FourierOfTrebleClef(FourierOfPiSymbol): CONFIG = { "n_vectors": 101, "run_time": 10, "start_drawn": True, "file_name": "TrebleClef", "height": 7.5, } def get_shape(self): shape = SVGMobject(self.file_name) return shape def get_path(self): shape = self.get_shape() path = shape.family_members_with_points()[0] path.set_height(self.height) path.set_fill(opacity=0) path.set_stroke(WHITE, 0) return path class FourierOfIP(FourierOfTrebleClef): CONFIG = { "file_name": "IP_logo2", "height": 6, "n_vectors": 100, } # def construct(self): # path = self.get_path() # self.add(path) def get_shape(self): shape = SVGMobject(self.file_name) return shape def get_path(self): shape = self.get_shape() path = shape.family_members_with_points()[0] path.add_line_to(path.get_start()) # path.make_smooth() path.set_height(self.height) path.set_fill(opacity=0) path.set_stroke(WHITE, 0) return path class FourierOfEighthNote(FourierOfTrebleClef): CONFIG = { "file_name": "EighthNote" } class FourierOfN(FourierOfTrebleClef): CONFIG = { "height": 6, "n_vectors": 1000, } def get_shape(self): return OldTex("N") class FourierNailAndGear(FourierOfTrebleClef): CONFIG = { "height": 6, "n_vectors": 200, "run_time": 100, "slow_factor": 0.01, "parametric_function_step_size": 0.0001, "arrow_config": { "tip_length": 0.1, "stroke_width": 2, } } def get_shape(self): shape = SVGMobject("Nail_And_Gear")[1] return shape class FourierBatman(FourierOfTrebleClef): CONFIG = { "height": 4, "n_vectors": 100, "run_time": 10, "arrow_config": { "tip_length": 0.1, "stroke_width": 2, } } def get_shape(self): shape = SVGMobject("BatmanLogo")[1] return shape class FourierHeart(FourierOfTrebleClef): CONFIG = { "height": 4, "n_vectors": 100, "run_time": 10, "arrow_config": { "tip_length": 0.1, "stroke_width": 2, } } def get_shape(self): shape = SuitSymbol("hearts") return shape def get_drawn_path(self, *args, **kwargs): kwargs["stroke_width"] = 5 path = super().get_drawn_path(*args, **kwargs) path.set_color(PINK) return path class FourierNDQ(FourierOfTrebleClef): CONFIG = { "height": 4, "n_vectors": 1000, "run_time": 10, "arrow_config": { "tip_length": 0.1, "stroke_width": 2, } } def get_shape(self): path = VMobject() shape = OldTex("NDQ") for sp in shape.family_members_with_points(): path.append_points(sp.get_points()) return path class FourierGoogleG(FourierOfTrebleClef): CONFIG = { "n_vectors": 10, "height": 5, "g_colors": [ "#4285F4", "#DB4437", "#F4B400", "#0F9D58", ] } def get_shape(self): g = SVGMobject("google_logo")[5] g.center() self.add(g) return g def get_drawn_path(self, *args, **kwargs): kwargs["stroke_width"] = 7 path = super().get_drawn_path(*args, **kwargs) blue, red, yellow, green = self.g_colors path[:250].set_color(blue) path[250:333].set_color(green) path[333:370].set_color(yellow) path[370:755].set_color(red) path[755:780].set_color(yellow) path[780:860].set_color(green) path[860:].set_color(blue) return path class ExplainCircleAnimations(FourierCirclesScene): CONFIG = { "n_vectors": 100, "center_point": 2 * DOWN, "n_top_circles": 9, "path_height": 3, } def construct(self): self.add_path() self.add_circles() self.wait(8) self.organize_circles_in_a_row() self.show_frequencies() self.show_examples_for_frequencies() self.show_as_vectors() self.show_vector_sum() self.tweak_starting_vectors() def add_path(self): self.path = self.get_path() self.add(self.path) def add_circles(self): coefs = self.get_coefficients_of_path(self.path) self.circles = self.get_circles(coefficients=coefs) self.add(self.circles) self.drawn_path = self.get_drawn_path(self.circles) self.add(self.drawn_path) def organize_circles_in_a_row(self): circles = self.circles top_circles = circles[:self.n_top_circles].copy() center_trackers = VGroup() for circle in top_circles: tracker = VectorizedPoint(circle.center_func()) circle.center_func = tracker.get_location center_trackers.add(tracker) tracker.freq = circle.freq tracker.circle = circle center_trackers.submobjects.sort( key=lambda m: m.freq ) center_trackers.generate_target() right_buff = 1.45 center_trackers.target.arrange(RIGHT, buff=right_buff) center_trackers.target.to_edge(UP, buff=1.25) self.add(top_circles) self.play( MoveToTarget(center_trackers), run_time=2 ) self.wait(4) self.top_circles = top_circles self.center_trackers = center_trackers def show_frequencies(self): center_trackers = self.center_trackers freq_numbers = VGroup() for ct in center_trackers: number = Integer(ct.freq) number.next_to(ct, DOWN, buff=1) freq_numbers.add(number) ct.circle.number = number ld, rd = [ OldTex("\\dots") for x in range(2) ] ld.next_to(freq_numbers, LEFT, MED_LARGE_BUFF) rd.next_to(freq_numbers, RIGHT, MED_LARGE_BUFF) freq_numbers.add_to_back(ld) freq_numbers.add(rd) freq_word = OldTexText("Frequencies") freq_word.scale(1.5) freq_word.set_color(YELLOW) freq_word.next_to(freq_numbers, DOWN, MED_LARGE_BUFF) self.play( LaggedStartMap( FadeInFromDown, freq_numbers ) ) self.play( Write(freq_word), LaggedStartMap( ShowCreationThenFadeAround, freq_numbers, ) ) self.wait(2) self.freq_numbers = freq_numbers self.freq_word = freq_word def show_examples_for_frequencies(self): top_circles = self.top_circles c1, c2, c3 = [ list(filter( lambda c: c.freq == k, top_circles ))[0] for k in (1, 2, 3) ] neg_circles = VGroup(*filter( lambda c: c.freq < 0, top_circles )) for c in [c1, c2, c3, *neg_circles]: c.rect = SurroundingRectangle(c) self.play( ShowCreation(c2.rect), WiggleOutThenIn(c2.number), ) self.wait(2) self.play( ReplacementTransform(c2.rect, c1.rect), ) self.play(FadeOut(c1.rect)) self.wait() self.play( ShowCreation(c3.rect), WiggleOutThenIn(c3.number), ) self.play( FadeOut(c3.rect), ) self.wait(2) self.play( LaggedStart(*[ ShowCreationThenFadeOut(c.rect) for c in neg_circles ]) ) self.wait(3) self.play(FadeOut(self.freq_word)) def show_as_vectors(self): top_circles = self.top_circles top_vectors = self.get_rotating_vectors(top_circles) top_vectors.set_color(WHITE) original_circles = top_circles.copy() self.play( FadeIn(top_vectors), top_circles.set_opacity, 0, ) self.wait(3) self.play( top_circles.match_style, original_circles ) self.remove(top_vectors) self.top_vectors = top_vectors def show_vector_sum(self): trackers = self.center_trackers.copy() trackers.sort( submob_func=lambda t: abs(t.circle.freq - 0.1) ) plane = self.plane = NumberPlane( x_min=-3, x_max=3, y_min=-2, y_max=2, axis_config={ "stroke_color": GREY_B, } ) plane.set_stroke(width=1) plane.fade(0.5) plane.move_to(self.center_point) self.play( FadeOut(self.drawn_path), FadeOut(self.circles), self.slow_factor_tracker.set_value, 0.05, ) self.add(plane, self.path) self.play(FadeIn(plane)) new_circles = VGroup() last_tracker = None for tracker in trackers: if last_tracker: tracker.new_location_func = last_tracker.circle.get_start else: tracker.new_location_func = lambda: self.center_point original_circle = tracker.circle tracker.circle = original_circle.copy() tracker.circle.center_func = tracker.get_location new_circles.add(tracker.circle) self.add(tracker, tracker.circle) start_point = tracker.get_location() self.play( UpdateFromAlphaFunc( tracker, lambda t, a: t.move_to( interpolate( start_point, tracker.new_location_func(), a, ) ), run_time=2 ) ) tracker.add_updater(lambda t: t.move_to( t.new_location_func() )) self.wait(2) last_tracker = tracker self.wait(3) self.clear() self.slow_factor_tracker.set_value(0.1) self.add( self.top_circles, self.freq_numbers, self.path, ) self.add_circles() for tc in self.top_circles: for c in self.circles: if c.freq == tc.freq: tc.rotate( angle_of_vector(c.get_start() - c.get_center()) - angle_of_vector(tc.get_start() - tc.get_center()) ) self.wait(10) def tweak_starting_vectors(self): top_circles = self.top_circles circles = self.circles path = self.path drawn_path = self.drawn_path new_path = self.get_new_path() new_coefs = self.get_coefficients_of_path(new_path) new_circles = self.get_circles(coefficients=new_coefs) new_top_circles = VGroup() new_top_vectors = VGroup() for top_circle in top_circles: for circle in new_circles: if circle.freq == top_circle.freq: new_top_circle = circle.copy() new_top_circle.center_func = top_circle.get_center new_top_vector = self.get_rotating_vector( new_top_circle ) new_top_circles.add(new_top_circle) new_top_vectors.add(new_top_vector) self.play( self.slow_factor_tracker.set_value, 0, FadeOut(drawn_path) ) self.wait() self.play( ReplacementTransform(top_circles, new_top_circles), ReplacementTransform(circles, new_circles), FadeOut(path), run_time=3, ) new_drawn_path = self.get_drawn_path( new_circles, stroke_width=4, ) self.add(new_drawn_path) self.slow_factor_tracker.set_value(0.1) self.wait(20) # def configure_path(self, path): path.set_stroke(WHITE, 1) path.set_fill(BLACK, opacity=1) path.set_height(self.path_height) path.move_to(self.center_point) return path def get_path(self): tex = OldTex("f") path = tex.family_members_with_points()[0] self.configure_path(path) return path # return Square().set_height(3) def get_new_path(self): shape = SVGMobject("TrebleClef") path = shape.family_members_with_points()[0] self.configure_path(path) path.scale(1.5, about_edge=DOWN) return path
from manim_imports_ext import * from _2019.diffyq.part2.wordy_scenes import WriteHeatEquationTemplate class ReactionsToInitialHeatEquation(PiCreatureScene): def construct(self): randy = self.pi_creature randy.set_color(BLUE_C) randy.center() point = VectorizedPoint().next_to(randy, UL, LARGE_BUFF) randy.add_updater(lambda r: r.look_at(point)) self.play(randy.change, "horrified") self.wait() self.play(randy.change, "pondering") self.wait() self.play( randy.change, "confused", point.next_to, randy, UR, LARGE_BUFF, ) self.wait(2) self.play( point.shift, 2 * DOWN, randy.change, "horrified" ) self.wait(4) class ContrastPDEToODE(TeacherStudentsScene): CONFIG = { "random_seed": 2, } def construct(self): student = self.students[2] pde, ode = words = VGroup(*[ OldTexText( text + "\\\\", "Differential\\\\", "Equation" ) for text in ("Partial", "Ordinary") ]) pde[0].set_color(YELLOW) ode[0].set_color(BLUE) for word in words: word.arrange(DOWN, aligned_edge=LEFT) words.arrange(RIGHT, buff=LARGE_BUFF) words.next_to(student.get_corner(UR), UP, MED_LARGE_BUFF) words.shift(UR) lt = OldTex("<") lt.scale(1.5) lt.move_to(Line(pde.get_right(), ode.get_left())) for pi in self.pi_creatures: pi.add_updater(lambda p: p.look_at(pde)) self.play( FadeInFromDown(VGroup(words, lt)), student.change, "raise_right_hand", ) self.play( self.change_students("pondering", "pondering", "hooray"), self.teacher.change, "happy" ) self.wait(3) self.play( Swap(ode, pde), self.teacher.change, "raise_right_hand", self.change_students( "erm", "sassy", "confused" ) ) self.look_at(words) self.play_student_changes( "thinking", "thinking", "tease", ) self.wait(3) class AskAboutWhereEquationComesFrom(TeacherStudentsScene, WriteHeatEquationTemplate): def construct(self): equation = self.get_d1_equation() equation.move_to(self.hold_up_spot, DOWN) self.play( FadeInFromDown(equation), self.teacher.change, "raise_right_hand" ) self.student_says( "Um...why?", target_mode="sassy", index=2, bubble_config={"direction": RIGHT}, ) self.play_student_changes( "confused", "confused", "sassy", ) self.wait() self.play( self.teacher.change, "pondering", ) self.wait(2) class AskWhyRewriteIt(TeacherStudentsScene): def construct(self): self.student_says( "Why?", index=1, bubble_config={"height": 2, "width": 2}, ) self.students[1].bubble = None self.teacher_says( "One step closer\\\\to derivatives" ) self.play_student_changes( "thinking", "thinking", "thinking", look_at=4 * LEFT + 2 * UP ) self.wait(2) class ReferenceKhanVideo(TeacherStudentsScene): def construct(self): khan_logo = ImageMobject("KhanLogo") khan_logo.set_height(1) khan_logo.next_to(self.teacher, UP, buff=2) khan_logo.shift(2 * LEFT) self.play( self.teacher.change, "raise_right_hand", ) self.play_student_changes( "thinking", "pondering", "thinking", look_at=self.screen ) self.wait() self.play(FadeInFromDown(khan_logo)) self.look_at(self.screen) self.wait(15)
from manim_imports_ext import * class WriteHeatEquationTemplate(Scene): CONFIG = { "tex_mobject_config": { "tex_to_color_map": { "{T}": WHITE, "{t}": YELLOW, "{x}": GREEN, "{y}": RED, "{z}": BLUE, "\\partial": WHITE, "2": WHITE, }, }, } def get_d1_equation(self): return OldTex( "{\\partial {T} \\over \\partial {t}}({x}, {t})", "=", "\\alpha \\cdot", "{\\partial^2 {T} \\over \\partial {x}^2} ({x}, {t})", **self.tex_mobject_config ) def get_d1_equation_without_inputs(self): return OldTex( "{\\partial {T} \\over \\partial {t}}", "=", "\\alpha \\cdot", "{\\partial^2 {T} \\over \\partial {x}^2}", **self.tex_mobject_config ) def get_d3_equation(self): return OldTex( "{\\partial {T} \\over \\partial {t}}", "=", "\\alpha \\left(", "{\\partial^2 {T} \\over \\partial {x}^2} + ", "{\\partial^2 {T} \\over \\partial {y}^2} + ", "{\\partial^2 {T} \\over \\partial {z}^2}", "\\right)", **self.tex_mobject_config ) def get_general_equation(self): return OldTex( "{\\partial {T} \\over \\partial {t}}", "=", "\\alpha", "\\nabla^2 {T}", **self.tex_mobject_config, ) def get_d3_equation_with_inputs(self): return OldTex( "{\\partial {T} \\over \\partial {t}}", "({x}, {y}, {z}, {t})", "=", "\\alpha \\left(", "{\\partial^2 {T} \\over \\partial {x}^2}", "({x}, {y}, {z}, {t}) + ", "{\\partial^2 {T} \\over \\partial {y}^2}", "({x}, {y}, {z}, {t}) + ", "{\\partial^2 {T} \\over \\partial {z}^2}", "({x}, {y}, {z}, {t})", "\\right)", **self.tex_mobject_config ) def get_d1_words(self): return OldTexText("Heat equation\\\\", "(1 dimension)") def get_d3_words(self): return OldTexText("Heat equation\\\\", "(3 dimensions)") def get_d1_group(self): group = VGroup( self.get_d1_words(), self.get_d1_equation(), ) group.arrange(DOWN, buff=MED_LARGE_BUFF) return group def get_d3_group(self): group = VGroup( self.get_d3_words(), self.get_d3_equation(), ) group.arrange(DOWN, buff=MED_LARGE_BUFF) return group class HeatEquationIntroTitle(WriteHeatEquationTemplate): def construct(self): scale_factor = 1.25 title = OldTexText("The Heat Equation") title.scale(scale_factor) title.to_edge(UP) equation = self.get_general_equation() equation.scale(scale_factor) equation.next_to(title, DOWN, MED_LARGE_BUFF) equation.set_color_by_tex("{T}", RED) self.play( FadeIn(title, DOWN), FadeIn(equation, UP), ) self.wait() class BringTogether(Scene): def construct(self): arrows = VGroup(Vector(2 * RIGHT), Vector(2 * LEFT)) arrows.arrange(RIGHT, buff=2) words = OldTexText("Bring together")[0] words.next_to(arrows, DOWN) words.save_state() words.space_out_submobjects(1.2) self.play( VFadeIn(words), Restore(words), arrows.arrange, RIGHT, {"buff": SMALL_BUFF}, VFadeIn(arrows), ) self.play(FadeOut(words), FadeOut(arrows)) class FourierSeriesIntro(WriteHeatEquationTemplate): def construct(self): title_scale_value = 1.5 title = OldTexText( "Fourier ", "Series", ) title.scale(title_scale_value) title.to_edge(UP) title.generate_target() details_coming = OldTexText("Details coming...") details_coming.next_to(title.get_corner(DR), DOWN) details_coming.set_color(GREY_B) # physics = OldTexText("Physics") heat = OldTexText("Heat") heat.scale(title_scale_value) physics = self.get_general_equation() physics.set_color_by_tex("{T}", RED) arrow1 = Arrow(LEFT, RIGHT) arrow2 = Arrow(LEFT, RIGHT) group = VGroup( heat, arrow1, physics, arrow2, title.target ) group.arrange(RIGHT) # physics.align_to(title.target, UP) group.to_edge(UP) rot_square = Square() rot_square.fade(1) rot_square.add_updater(lambda m, dt: m.rotate(dt)) def update_heat_colors(heat): colors = [YELLOW, RED] vertices = rot_square.get_vertices() letters = heat.family_members_with_points() for letter, vertex in zip(letters, vertices): alpha = (normalize(vertex)[0] + 1) / 2 i, sa = integer_interpolate(0, len(colors) - 1, alpha) letter.set_color(interpolate_color( colors[i], colors[i + 1], alpha, )) heat.add_updater(update_heat_colors) image = ImageMobject("Joseph Fourier") image.set_height(5) image.next_to(title, DOWN, LARGE_BUFF) image.to_edge(LEFT) name = OldTexText("Joseph", "Fourier") name.next_to(image, DOWN) bubble = ThoughtBubble( height=2, width=2.5, direction=RIGHT, ) bubble.set_fill(opacity=0) bubble.set_stroke(WHITE) bubble.set_stroke(BLACK, 5, background=True) bubble.shift(heat.get_center() - bubble.get_bubble_center()) bubble[:-1].shift(LEFT + 0.2 * DOWN) bubble[:-1].rotate(-20 * DEGREES) for mob in bubble[:-1]: mob.rotate(20 * DEGREES) # self.play(FadeInFromDown(title)) self.add(title) self.play( FadeInFromDown(image), TransformFromCopy( title.get_part_by_tex("Fourier"), name.get_part_by_tex("Fourier"), path_arc=90 * DEGREES, ), FadeIn(name.get_part_by_tex("Joseph")), ) self.play(Write(details_coming, run_time=1)) self.play(LaggedStartMap(FadeOut, details_coming[0], run_time=1)) self.wait() self.add(rot_square) self.play( FadeIn(physics, RIGHT), GrowArrow(arrow2), FadeIn(heat, RIGHT), GrowArrow(arrow1), MoveToTarget(title), ) self.play(ShowCreation(bubble)) self.wait(10) class CompareODEToPDE(Scene): def construct(self): pass class TodaysTargetWrapper(Scene): def construct(self): pass class TwoGraphTypeTitles(Scene): def construct(self): left_title = OldTexText( "Represent time\\\\with actual time" ) left_title.shift(FRAME_WIDTH * LEFT / 4) right_title = OldTexText( "Represent time\\\\with an axis" ) right_title.shift(FRAME_WIDTH * RIGHT / 4) titles = VGroup(left_title, right_title) for title in titles: title.scale(1.25) title.to_edge(UP) self.play(FadeInFromDown(right_title)) self.wait() self.play(FadeInFromDown(left_title)) self.wait() class ShowPartialDerivativeSymbols(Scene): def construct(self): t2c = { "{x}": GREEN, "{t}": YELLOW, } d_derivs, del_derivs = VGroup(*[ VGroup(*[ OldTex( "{" + sym, "T", "\\over", sym, var + "}", "(", "{x}", ",", "{t}", ")", ).set_color_by_tex_to_color_map(t2c) for var in ("{x}", "{t}") ]) for sym in ("d", "\\partial") ]) dTdx, dTdt = d_derivs delTdelx, delTdelx = del_derivs dels = VGroup(*it.chain(*[ del_deriv.get_parts_by_tex("\\partial") for del_deriv in del_derivs ])) dTdx.to_edge(UP) self.play(FadeIn(dTdx, DOWN)) self.wait() self.play(ShowCreationThenFadeAround(dTdx[3:5])) self.play(ShowCreationThenFadeAround(dTdx[:2])) self.wait() dTdt.move_to(dTdx) self.play( dTdx.next_to, dTdt, RIGHT, {"buff": 1.5}, dTdx.set_opacity, 0.5, FadeInFromDown(dTdt) ) self.wait() for m1, m2 in zip(d_derivs, del_derivs): m2.move_to(m1) pd_words = OldTexText("Partial derivatives") pd_words.next_to(del_derivs, DOWN, MED_LARGE_BUFF) self.play( Write(pd_words), dTdx.set_opacity, 1, run_time=1, ) self.wait() self.play( ReplacementTransform(d_derivs, del_derivs) ) self.play( LaggedStartMap( ShowCreationThenFadeAround, dels, surrounding_rectangle_config={ "color": BLUE, "buff": 0.5 * SMALL_BUFF, "stroke_width": 2, } ) ) self.wait() num_words = VGroup(*[ OldTexText( "Change in $T$\\\\caused by {}", "$\\partial$", "${}$".format(var), arg_separator="", ).set_color_by_tex_to_color_map(t2c) for var in ("{x}", "{t}") ]) num_words.scale(0.8) for word, deriv in zip(num_words, del_derivs): num = deriv[:2] word.move_to(num, UP) word.to_edge(UP, buff=MED_SMALL_BUFF) deriv.rect = SurroundingRectangle( num, buff=SMALL_BUFF, stroke_width=2, color=word[-1].get_color(), ) deriv.rect.mob = num deriv.rect.add_updater(lambda r: r.move_to(r.mob)) self.play( Write(num_words[1]), VGroup(del_derivs, pd_words).shift, DOWN, ShowCreation(del_derivs[1].rect), ) self.play( Write(num_words[0]), ShowCreation(del_derivs[0].rect), ) self.wait() class WriteHeatEquation(WriteHeatEquationTemplate): def construct(self): title = OldTexText("The Heat Equation") title.to_edge(UP) equation = self.get_d1_equation() equation.next_to(title, DOWN) eq_i = equation.index_of_part_by_tex("=") dt_part = equation[:eq_i] dx_part = equation[eq_i + 3:] dt_rect = SurroundingRectangle(dt_part) dt_rect.set_stroke(YELLOW, 2) dx_rect = SurroundingRectangle(dx_part) dx_rect.set_stroke(GREEN, 2) two_outlines = equation.get_parts_by_tex("2").copy() two_outlines.set_stroke(YELLOW, 2) two_outlines.set_fill(opacity=0) to_be_explained = OldTexText( "To be explained shortly..." ) to_be_explained.scale(0.7) to_be_explained.next_to(equation, RIGHT, MED_LARGE_BUFF) to_be_explained.fade(1) pde = OldTexText("Partial Differential Equation") pde.move_to(title) del_outlines = equation.get_parts_by_tex("\\partial").copy() del_outlines.set_stroke(YELLOW, 2) del_outlines.set_fill(opacity=0) self.play( FadeIn(title, 0.5 * DOWN), FadeIn(equation, 0.5 * UP), ) self.wait() self.play(ShowCreation(dt_rect)) self.wait() self.play(TransformFromCopy(dt_rect, dx_rect)) self.play(ShowCreationThenDestruction(two_outlines)) self.wait() self.play(Write(to_be_explained, run_time=1)) self.wait(2) self.play( ShowCreationThenDestruction( del_outlines, lag_ratio=0.1, ) ) self.play( FadeOut(title, UP), FadeIn(pde, DOWN), FadeOut(dt_rect), FadeOut(dx_rect), ) self.wait() class Show3DEquation(WriteHeatEquationTemplate): def construct(self): equation = self.get_d3_equation_with_inputs() equation.set_width(FRAME_WIDTH - 1) inputs = VGroup(*it.chain(*[ equation.get_parts_by_tex(s) for s in ["{x}", "{y}", "{z}", "{t}"] ])) inputs.sort() equation.to_edge(UP) self.add(equation) self.play(LaggedStartMap( ShowCreationThenFadeAround, inputs, surrounding_rectangle_config={ "buff": 0.05, "stroke_width": 2, } )) self.wait() class Show1DAnd3DEquations(WriteHeatEquationTemplate): def construct(self): d1_group = self.get_d1_group() d3_group = self.get_d3_group() d1_words, d1_equation = d1_group d3_words, d3_equation = d3_group groups = VGroup(d1_group, d3_group) for group in groups: group.arrange(DOWN, buff=MED_LARGE_BUFF) groups.arrange(RIGHT, buff=1.5) groups.to_edge(UP) d3_rhs = d3_equation[9:-2] d3_brace = Brace(d3_rhs, DOWN) nabla_words = OldTexText("Sometimes written as") nabla_words.match_width(d3_brace) nabla_words.next_to(d3_brace, DOWN) nabla_exp = OldTex( "\\nabla^2 {T}", **self.tex_mobject_config, ) nabla_exp.next_to(nabla_words, DOWN) # nabla_group = VGroup(nabla_words, nabla_exp) d1_group.save_state() d1_group.center().to_edge(UP) self.play( Write(d1_words), FadeIn(d1_equation, UP), run_time=1, ) self.wait(2) self.play( Restore(d1_group), FadeIn(d3_group, LEFT) ) self.wait() self.play( GrowFromCenter(d3_brace), Write(nabla_words), TransformFromCopy(d3_rhs, nabla_exp), run_time=1, ) self.wait() class D1EquationNoInputs(WriteHeatEquationTemplate): def construct(self): equation = self.get_d1_equation_without_inputs() equation.to_edge(UP) # i1 = equation.index_of_part_by_tex("\\partial") # i2 = equation.index_of_part_by_tex("\\cdot") # equation[i1:i1 + 2].set_color(RED) # equation[i2 + 1:i2 + 6].set_color(RED) equation.set_color_by_tex("{T}", RED) self.add(equation) class AltHeatRHS(Scene): def construct(self): formula = OldTex( "{\\alpha \\over 2}", "\\Big(", "T({x} - 1, {t}) + T({x} + 1, {t})" "\\Big)", tex_to_color_map={ "{x}": GREEN, "{t}": YELLOW, } ) self.add(formula) class CompareInputsOfGeneralCaseTo1D(WriteHeatEquation): def construct(self): three_d_expr, one_d_expr = [ OldTex( "{T}(" + inputs + ", {t})", **self.tex_mobject_config, ) for inputs in ["{x}, {y}, {z}", "{x}"] ] for expr in three_d_expr, one_d_expr: expr.scale(2) expr.to_edge(UP) x, y, z = [ three_d_expr.get_part_by_tex(letter) for letter in ["x", "y", "z"] ] self.play(FadeInFromDown(three_d_expr)) self.play(LaggedStartMap( ShowCreationThenFadeAround, VGroup(x, y, z) )) self.wait() low = 3 high = -3 self.play( ReplacementTransform(three_d_expr[:low], one_d_expr[:low]), ReplacementTransform(three_d_expr[high:], one_d_expr[high:]), three_d_expr[low:high].scale, 0, ) self.wait() class ShowLaplacian(WriteHeatEquation): def construct(self): equation = self.get_d3_equation() equation.to_edge(UP, buff=MED_SMALL_BUFF) parts = VGroup() plusses = VGroup() for char in "xyz": index = equation.index_of_part_by_tex( "{" + char + "}" ) part = equation[index - 6:index + 3] rect = SurroundingRectangle(part) rect.match_color(equation[index]) parts.add(part) part.rect = rect if char in "yz": plus = equation[index - 8] part.plus = plus plusses.add(plus) lp = equation.get_part_by_tex("(") rp = equation.get_part_by_tex(")") for part in parts: part.rp = rp.copy() part.rp.next_to(part, RIGHT, SMALL_BUFF) part.rp.align_to(lp, UP) rp.become(parts[0].rp) # Show new second derivatives self.add(*equation) self.remove(*plusses, *parts[1], *parts[2]) for part in parts[1:]: self.play( rp.become, part.rp, FadeIn(part, LEFT), Write(part.plus), ShowCreation(part.rect), ) self.play( FadeOut(part.rect), ) self.wait() # Show laplacian brace = Brace(parts, DOWN) laplacian = OldTex("\\nabla^2", "T") laplacian.next_to(brace, DOWN) laplacian_name = OldTexText( "``Laplacian''" ) laplacian_name.next_to(laplacian, DOWN) T_parts = VGroup(*[part[3] for part in parts]) non_T_parts = VGroup(*[ VGroup(*part[:3], *part[4:]) for part in parts ]) self.play(GrowFromCenter(brace)) self.play(Write(laplacian_name)) self.play( TransformFromCopy(non_T_parts, laplacian[0]) ) self.play( TransformFromCopy(T_parts, laplacian[1]) ) self.wait(3) class AskAboutActuallySolving(WriteHeatEquationTemplate): def construct(self): equation = self.get_d1_equation() equation.center() q1 = OldTexText("Solve for T?") q1.next_to(equation, UP, LARGE_BUFF) q2 = OldTexText("What does it \\emph{mean} to solve this?") q2.next_to(equation, UP, LARGE_BUFF) formula = OldTex( "T({x}, {t}) = \\sin\\big(a{x}\\big) e^{-\\alpha \\cdot a^2 {t}}", tex_to_color_map={ "{x}": GREEN, "{t}": YELLOW, } ) formula.next_to(equation, DOWN, LARGE_BUFF) q3 = OldTexText("Is this it?") arrow = Vector(LEFT, color=WHITE) arrow.next_to(formula, RIGHT) q3.next_to(arrow, RIGHT) self.add(equation) self.play(FadeInFromDown(q1)) self.wait() self.play( FadeInFromDown(q2), q1.shift, 1.5 * UP, ) self.play(FadeIn(formula, UP)) self.play( GrowArrow(arrow), FadeIn(q3, LEFT) ) self.wait() class PDEPatreonEndscreen(PatreonEndScreen): CONFIG = { "specific_patrons": [ "Juan Benet", "Vassili Philippov", "Burt Humburg", "Matt Russell", "Scott Gray", "soekul", "Tihan Seale", "Richard Barthel", "Ali Yahya", "dave nicponski", "Evan Phillips", "Graham", "Joseph Kelly", "Kaustuv DeBiswas", "LambdaLabs", "Lukas Biewald", "Mike Coleman", "Peter Mcinerney", "Quantopian", "Roy Larson", "Scott Walter, Ph.D.", "Yana Chernobilsky", "Yu Jun", "Jordan Scales", "D. Sivakumar", "Lukas -krtek.net- Novy", "John Shaughnessy", "Britt Selvitelle", "David Gow", "J", "Jonathan Wilson", "Joseph John Cox", "Magnus Dahlström", "Randy C. Will", "Ryan Atallah", "Luc Ritchie", "1stViewMaths", "Adrian Robinson", "Alexis Olson", "Andreas Benjamin Brössel", "Andrew Busey", "Ankalagon", "Antoine Bruguier", "Antonio Juarez", "Arjun Chakroborty", "Art Ianuzzi", "Awoo", "Bernd Sing", "Boris Veselinovich", "Brian Staroselsky", "Chad Hurst", "Charles Southerland", "Chris Connett", "Christian Kaiser", "Clark Gaebel", "Cooper Jones", "Danger Dai", "Dave B", "Dave Kester", "David B. Hill", "David Clark", "DeathByShrimp", "Delton Ding", "eaglle", "emptymachine", "Eric Younge", "Eryq Ouithaqueue", "Federico Lebron", "Giovanni Filippi", "Hal Hildebrand", "Hitoshi Yamauchi", "Isaac Jeffrey Lee", "j eduardo perez", "Jacob Magnuson", "Jameel Syed", "Jason Hise", "Jeff Linse", "Jeff Straathof", "John Griffith", "John Haley", "John V Wertheim", "Jonathan Eppele", "Kai-Siang Ang", "Kanan Gill", "L0j1k", "Lee Beck", "Lee Redden", "Linh Tran", "Ludwig Schubert", "Magister Mugit", "Mark B Bahu", "Mark Heising", "Martin Price", "Mathias Jansson", "Matt Langford", "Matt Roveto", "Matthew Bouchard", "Matthew Cocke", "Michael Faust", "Michael Hardel", "Mirik Gogri", "Mustafa Mahdi", "Márton Vaitkus", "Nero Li", "Nikita Lesnikov", "Omar Zrien", "Owen Campbell-Moore", "Peter Ehrnstrom", "RedAgent14", "rehmi post", "Richard Burgmann", "Richard Comish", "Ripta Pasay", "Rish Kundalia", "Robert Teed", "Roobie", "Ryan Williams", "Sachit Nagpal", "Solara570", "Stevie Metke", "Tal Einav", "Ted Suzman", "Thomas Tarler", "Tom Fleming", "Valeriy Skobelev", "Xavier Bernard", "Yavor Ivanov", "Yaw Etse", "YinYangBalance.Asia", "Zach Cardwell", ], }
from manim_imports_ext import * from _2019.diffyq.part1.shared_constructs import * from _2019.diffyq.part1.pendulum import Pendulum from _2019.diffyq.part1.pendulum import ThetaVsTAxes from _2019.diffyq.part1.phase_space import IntroduceVectorField from _2018.div_curl import PhaseSpaceOfPopulationModel from _2018.div_curl import ShowTwoPopulations # Scenes class VectorFieldTest(Scene): def construct(self): plane = NumberPlane( # axis_config={"unit_size": 2} ) mu_tracker = ValueTracker(1) field = VectorField( lambda p: pendulum_vector_field_func( plane.point_to_coords(p), mu=mu_tracker.get_value() ), delta_x=0.5, delta_y=0.5, max_magnitude=6, opacity=0.5, # length_func=lambda norm: norm, ) field.set_opacity(1) self.add(plane, field) return stream_lines = StreamLines( field.func, delta_x=0.5, delta_y=0.5, ) animated_stream_lines = AnimatedStreamLines( stream_lines, line_anim_class=ShowPassingFlashWithThinningStrokeWidth, ) self.add(plane, field, animated_stream_lines) self.wait(10) class ShowRect(Scene): CONFIG = { "height": 1, "width": 3, } def construct(self): rect = Rectangle( height=self.height, width=self.width, ) rect.set_stroke(YELLOW) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) class ShowSquare(ShowRect): CONFIG = { "height": 3, "width": 3, } class WhenChangeIsEasier(Scene): def construct(self): pass class AirResistanceBrace(Scene): def construct(self): brace = Brace(Line(ORIGIN, RIGHT), DOWN) word = OldTexText("Air resistance") word.next_to(brace, DOWN) self.play(GrowFromCenter(brace), FadeIn(word, UP)) self.wait() class PeriodFormula(Scene): def construct(self): formula = get_period_formula() formula.scale(2) q_mark = OldTex("?") q_mark.scale(3) q_mark.next_to(formula, RIGHT) self.add(formula, q_mark) class TourOfDifferentialEquations(MovingCameraScene): CONFIG = { "screen_rect_style": { "stroke_width": 2, "stroke_color": WHITE, "fill_opacity": 1, "fill_color": BLACK, }, "camera_config": {"background_color": GREY_E}, "zoomed_thumbnail_index": 0, } def construct(self): self.add_title() self.show_thumbnails() self.zoom_in_to_one_thumbnail() # self.show_words() def add_title(self): title = OldTexText( "A Tourist's Guide \\\\to Differential\\\\Equations" ) title.scale(1.5) title.to_corner(UR) self.add(title) def show_thumbnails(self): thumbnails = self.thumbnails = Group( Group(ScreenRectangle(**self.screen_rect_style)), Group(ScreenRectangle(**self.screen_rect_style)), Group(ScreenRectangle(**self.screen_rect_style)), Group(ScreenRectangle(**self.screen_rect_style)), Group(ScreenRectangle(**self.screen_rect_style)), ) n = len(thumbnails) thumbnails.set_height(1.5) line = self.line = CubicBezier( [-5, 3, 0], [3, 3, 0], [-3, -3, 0], [5, -3, 0], ) line.shift(MED_SMALL_BUFF * LEFT) for thumbnail, a in zip(thumbnails, np.linspace(0, 1, n)): thumbnail.move_to(line.point_from_proportion(a)) dots = OldTex("\\dots") dots.next_to(thumbnails[-1], RIGHT) self.add_phase_space_preview(thumbnails[0]) self.add_heat_preview(thumbnails[1]) self.add_fourier_series(thumbnails[2]) self.add_matrix_exponent(thumbnails[3]) self.add_laplace_symbol(thumbnails[4]) self.play( ShowCreation( line, rate_func=lambda t: np.clip(t * (n + 1) / n, 0, 1) ), LaggedStart(*[ GrowFromCenter( thumbnail, rate_func=squish_rate_func( smooth, 0, 0.7, ) ) for thumbnail in thumbnails ], lag_ratio=1), run_time=5 ) self.play(Write(dots)) self.wait() self.thumbnails = thumbnails def zoom_in_to_one_thumbnail(self): self.play( self.camera_frame.replace, self.thumbnails[self.zoomed_thumbnail_index], run_time=3, ) self.wait() def show_words(self): words = VGroup( OldTexText("Generalize"), OldTexText("Put in context"), OldTexText("Modify"), ) # words.arrange(DOWN, aligned_edge=LEFT, buff=LARGE_BUFF) words.scale(1.5) words.to_corner(UR) words.add_to_back(VectorizedPoint(words.get_center())) words.add(VectorizedPoint(words.get_center())) diffEq = OldTexText("Differential\\\\equations") diffEq.scale(1.5) diffEq.to_corner(DL, buff=LARGE_BUFF) for word1, word2 in zip(words, words[1:]): self.play( FadeInFromDown(word2), FadeOut(word1, UP), ) self.wait() self.play( ReplacementTransform( VGroup(self.thumbnails).copy().fade(1), diffEq, lag_ratio=0.01, ) ) self.wait() # def add_phase_space_preview(self, thumbnail): image = ImageMobject("LovePhaseSpace") image.replace(thumbnail) thumbnail.add(image) def add_heat_preview(self, thumbnail): image = ImageMobject("HeatSurfaceExample") image.replace(thumbnail) thumbnail.add(image) def add_matrix_exponent(self, thumbnail): matrix = IntegerMatrix( [[3, 1], [4, 1]], v_buff=MED_LARGE_BUFF, h_buff=MED_LARGE_BUFF, bracket_h_buff=SMALL_BUFF, bracket_v_buff=SMALL_BUFF, ) e = OldTex("e") t = OldTex("t") t.scale(1.5) t.next_to(matrix, RIGHT, SMALL_BUFF) e.scale(2) e.move_to(matrix.get_corner(DL), UR) group = VGroup(e, matrix, t) group.set_height(0.7 * thumbnail.get_height()) randy = Randolph(mode="confused", height=0.75) randy.next_to(group, LEFT, aligned_edge=DOWN) randy.look_at(matrix) group.add(randy) group.move_to(thumbnail) thumbnail.add(group) def add_fourier_series(self, thumbnail): colors = [BLUE, GREEN, YELLOW, RED, RED_E, PINK] waves = VGroup(*[ self.get_square_wave_approx(N, color) for N, color in enumerate(colors) ]) waves.set_stroke(width=1.5) waves.replace(thumbnail, stretch=True) waves.scale(0.8) waves.move_to(thumbnail) thumbnail.add(waves) def get_square_wave_approx(self, N, color): return FunctionGraph( lambda x: sum([ (1 / n) * np.sin(n * PI * x) for n in range(1, 2 * N + 3, 2) ]), x_min=0, x_max=2, color=color ) def add_laplace_symbol(self, thumbnail): mob = OldTex( "\\mathcal{L}\\left\\{f(t)\\right\\}" ) mob.set_width(0.8 * thumbnail.get_width()) mob.move_to(thumbnail) thumbnail.add(mob) class HeatEquationPreview(ExternallyAnimatedScene): pass class ShowHorizontalDashedLine(Scene): def construct(self): line = DashedLine(LEFT_SIDE, RIGHT_SIDE) self.play(ShowCreation(line)) self.wait() class RabbitFoxPopulations(ShowTwoPopulations): pass class RabbitFoxEquation(PhaseSpaceOfPopulationModel): def construct(self): equations = self.get_equations() self.add(equations) class ShowGravityAcceleration(Scene): CONFIG = { "flash": True, "add_ball_copies": True, } def construct(self): self.add_gravity_field() self.add_title() self.pulse_gravity_down() self.show_g_value() self.show_trajectory() self.combine_v_vects() self.show_g_symbol() def add_gravity_field(self): gravity_field = self.gravity_field = VectorField( lambda p: DOWN, # delta_x=2, # delta_y=2, ) gravity_field.set_opacity(0.5) gravity_field.sort( lambda p: -p[1], ) self.add(gravity_field) def add_title(self): title = self.title = OldTexText("Gravitational acceleration") title.scale(1.5) title.to_edge(UP) title.add_background_rectangle( buff=0.05, opacity=1, ) self.play(FadeInFromDown(title)) def pulse_gravity_down(self): field = self.gravity_field self.play(LaggedStart(*[ ApplyFunction( lambda v: v.set_opacity(1).scale(1.2), vector, rate_func=there_and_back, ) for vector in field ]), run_time=2, lag_ratio=0.001) self.add(self.title) def show_g_value(self): title = self.title g_eq = self.g_eq = OldTex( "-9.8", "{\\text{m/s}", "\\over", "\\text{s}}", **Lg_formula_config ) g_eq.add_background_rectangle_to_submobjects() g_eq.scale(2) g_eq.center() num, ms, per, s = g_eq self.add(num) self.wait(0.75) self.play( FadeIn(ms, 0.25 * DOWN, run_time=0.5) ) self.wait(0.25) self.play(LaggedStart( GrowFromPoint(per, per.get_left()), FadeIn(s, 0.5 * UP), lag_ratio=0.7, run_time=0.75 )) self.wait() self.play( g_eq.scale, 0.5, g_eq.next_to, title, DOWN, ) def show_trajectory(self): total_time = 6 ball = self.get_ball() p0 = 3 * DOWN + 5 * LEFT v0 = 2.8 * UP + 1.5 * RIGHT g = 0.9 * DOWN graph = ParametricCurve( lambda t: p0 + v0 * t + 0.5 * g * t**2, t_min=0, t_max=total_time, ) # graph.center().to_edge(DOWN) dashed_graph = DashedVMobject(graph, num_dashes=60) dashed_graph.set_stroke(WHITE, 1) ball.move_to(graph.get_start()) randy.add_updater( lambda m, dt: m.rotate(dt).move_to(ball) ) times = np.arange(0, total_time + 1) velocity_graph = ParametricCurve( lambda t: v0 + g * t, t_min=0, t_max=total_time, ) v_point = VectorizedPoint() v_point.move_to(velocity_graph.get_start()) def get_v_vect(): result = Vector( v_point.get_location(), color=RED, tip_length=0.2, ) result.scale(0.5, about_point=result.get_start()) result.shift(ball.get_center()) result.set_stroke(width=2, family=False) return result v_vect = always_redraw(get_v_vect) self.add(v_vect) flash_rect = FullScreenRectangle( stroke_width=0, fill_color=WHITE, fill_opacity=0.2, ) flash = FadeOut( flash_rect, rate_func=squish_rate_func(smooth, 0, 0.1) ) time_label = OldTexText("Time = ") time_label.shift(MED_SMALL_BUFF * LEFT) time_tracker = ValueTracker(0) time = DecimalNumber(0) time.next_to(time_label, RIGHT) time.add_updater(lambda d, dt: d.set_value( time_tracker.get_value() )) time_group = VGroup(time_label, time) time_group.center().to_edge(DOWN) self.add(time_group) ball_copies = VGroup() v_vect_copies = VGroup() self.add(dashed_graph, ball) for t1, t2 in zip(times, times[1:]): v_vect_copy = v_vect.copy() v_vect_copies.add(v_vect_copy) ball_copy = ball.copy() ball_copy.clear_updaters() ball_copies.add(ball_copy) if self.add_ball_copies: self.add(v_vect_copy) self.add(ball_copy, ball) dashed_graph.save_state() kw = { "rate_func": lambda alpha: interpolate( t1 / total_time, t2 / total_time, alpha ) } anims = [ ShowCreation(dashed_graph, **kw), MoveAlongPath(ball, graph, **kw), MoveAlongPath(v_point, velocity_graph, **kw), ApplyMethod( time_tracker.increment_value, 1, rate_func=linear ), ] if self.flash: anims.append(flash) self.play(*anims, run_time=1) dashed_graph.restore() randy.clear_updaters() self.play(FadeOut(time_group)) self.wait() self.v_vects = v_vect_copies def combine_v_vects(self): v_vects = self.v_vects.copy() v_vects.generate_target() new_center = 2 * DOWN + 2 * LEFT for vect in v_vects.target: vect.scale(1.5) vect.set_stroke(width=2) vect.shift(new_center - vect.get_start()) self.play(MoveToTarget(v_vects)) delta_vects = VGroup(*[ Arrow( v1.get_end(), v2.get_end(), buff=0.01, color=YELLOW, ).set_opacity(0.5) for v1, v2 in zip(v_vects, v_vects[1:]) ]) brace = Brace(Line(ORIGIN, UP), RIGHT) braces = VGroup(*[ brace.copy().match_height(arrow).next_to( arrow, RIGHT, buff=0.2 * SMALL_BUFF ) for arrow in delta_vects ]) amounts = VGroup(*[ OldTexText("9.8 m/s").scale(0.5).next_to( brace, RIGHT, SMALL_BUFF ) for brace in braces ]) self.play( FadeOut(self.gravity_field), FadeIn(delta_vects, lag_ratio=0.1), ) self.play( LaggedStartMap(GrowFromCenter, braces), LaggedStartMap(FadeInFrom, amounts, lambda m: (m, LEFT)), ) self.wait() def show_g_symbol(self): g = OldTex("g") brace = Brace(self.g_eq[0][2:], UP, buff=SMALL_BUFF) g.scale(1.5) g.next_to(brace, UP) g.set_color(YELLOW) self.play( FadeOut(self.title), GrowFromCenter(brace), FadeIn(g, UP), ) self.wait() # def get_ball(self): ball = Circle( stroke_width=1, stroke_color=WHITE, fill_color=GREY, fill_opacity=1, sheen_factor=1, sheen_direction=UL, radius=0.25, ) randy = Randolph(mode="pondering") randy.eyes.set_stroke(BLACK, 0.5) randy.match_height(ball) randy.scale(0.75) randy.move_to(ball) ball.add(randy) return ball class ShowSimpleTrajectory(ShowGravityAcceleration): CONFIG = { "flash": False, } def construct(self): self.show_trajectory() class SimpleProjectileEquation(ShowGravityAcceleration): CONFIG = { "y0": 0, "g": 9.8, "axes_config": { "x_min": 0, "x_max": 6, "x_axis_config": { "unit_size": 1.5, "tip_width": 0.15, }, "y_min": -30, "y_max": 35, "y_axis_config": { "unit_size": 0.1, "numbers_with_elongated_ticks": range( -30, 35, 10 ), "tick_size": 0.05, "numbers_to_show": range(-30, 31, 10), "tip_width": 0.15, }, "center_point": 2 * LEFT, } } def construct(self): self.add_axes() self.setup_trajectory() self.show_trajectory() self.show_equation() self.solve_for_velocity() self.solve_for_position() def add_axes(self): axes = self.axes = Axes(**self.axes_config) axes.set_stroke(width=2) axes.add_coordinates() t_label = OldTex("t") t_label.next_to(axes.x_axis.get_right(), UL) axes.add(t_label) self.add(axes) def setup_trajectory(self): axes = self.axes total_time = self.total_time = 5 ball = self.get_ball() offset_vector = 3 * LEFT g = self.g y0 = self.y0 v0 = 0.5 * g * total_time t_tracker = ValueTracker(0) get_t = t_tracker.get_value # Position def y_func(t): return -0.5 * g * t**2 + v0 * t + y0 graph_template = axes.get_graph(y_func, x_max=total_time) graph_template.set_stroke(width=2) traj_template = graph_template.copy() traj_template.stretch(0, 0) traj_template.move_to( axes.coords_to_point(0, 0), DOWN ) traj_template.shift(offset_vector) traj_template.set_stroke(width=0.5) graph = VMobject() graph.set_stroke(BLUE, 2) traj = VMobject() traj.set_stroke(WHITE, 0.5) graph.add_updater(lambda g: g.pointwise_become_partial( graph_template, 0, get_t() / total_time )) traj.add_updater(lambda t: t.pointwise_become_partial( traj_template, 0, get_t() / total_time )) def get_ball_point(): return axes.coords_to_point( 0, y_func(get_t()) ) + offset_vector f_always(ball.move_to, get_ball_point) h_line = always_redraw(lambda: DashedLine( get_ball_point(), axes.input_to_graph_point(get_t(), graph_template), stroke_width=1, )) y_label = OldTex("y", "(t)") y_label.set_color_by_tex("y", BLUE) y_label.add_updater( lambda m: m.next_to( graph.get_last_point(), UR, SMALL_BUFF, ) ) # Velocity def v_func(t): return -g * t + v0 def get_v_vect(): return Vector( axes.y_axis.unit_size * v_func(get_t()) * UP, color=RED, ) v_vect = always_redraw( lambda: get_v_vect().shift(get_ball_point()) ) v_brace = always_redraw(lambda: Brace(v_vect, LEFT)) dy_dt_label = OldTex( "{d", "y", "\\over dt}", "(t)", ) dy_dt_label.scale(0.8) dy_dt_label.set_color_by_tex("y", BLUE) y_dot_label = OldTex("\\dot y", "(t)") y_dot_label.set_color_by_tex("\\dot y", RED) for label in dy_dt_label, y_dot_label: label.add_updater(lambda m: m.next_to( v_brace, LEFT, SMALL_BUFF, )) graphed_v_vect = always_redraw( lambda: get_v_vect().shift( axes.coords_to_point(get_t(), 0) ) ) v_graph_template = axes.get_graph( v_func, x_max=total_time, ) v_graph = VMobject() v_graph.set_stroke(RED, 2) v_graph.add_updater(lambda m: m.pointwise_become_partial( v_graph_template, 0, get_t() / total_time, )) # Acceleration def get_a_vect(): return Vector( axes.y_axis.unit_size * g * DOWN ) a_vect = get_a_vect() a_vect.add_updater(lambda a: a.move_to( get_ball_point(), UP, )) a_brace = Brace(a_vect, RIGHT) always(a_brace.next_to, a_vect, RIGHT, SMALL_BUFF) d2y_dt2_label = OldTex( "d^2", "{y}", "\\over dt}", "(t)" ) d2y_dt2_label.scale(0.8) d2y_dt2_label.set_color_by_tex( "y", BLUE, ) y_ddot_label = OldTex("\\ddot y", "(t)") y_ddot_label.set_color_by_tex("\\ddot y", YELLOW) for label in d2y_dt2_label, y_ddot_label: label.add_updater(lambda m: m.next_to( a_brace, RIGHT, SMALL_BUFF )) a_graph = axes.get_graph( lambda t: -g, x_max=total_time, ) a_graph.set_stroke(YELLOW, 2) graphed_a_vect = get_a_vect() graphed_a_vect.add_updater(lambda a: a.move_to( axes.coords_to_point(get_t(), 0), UP, )) self.set_variables_as_attrs( t_tracker, graph, y_label, traj, h_line, v_vect, v_brace, dy_dt_label, y_dot_label, ball, graphed_v_vect, v_graph, a_vect, a_brace, d2y_dt2_label, y_ddot_label, a_graph, graphed_a_vect, ) def show_trajectory(self): self.add( self.h_line, self.traj, self.ball, self.graph, self.y_label, ) self.play_trajectory() self.wait() self.add( self.v_vect, self.v_brace, self.dy_dt_label, self.ball, self.graphed_v_vect, self.v_graph, ) self.play_trajectory() self.wait() self.add( self.a_vect, self.ball, self.a_brace, self.d2y_dt2_label, self.a_graph, self.graphed_a_vect, ) self.play_trajectory() self.wait() self.play( ReplacementTransform( self.dy_dt_label, self.y_dot_label, ), ShowCreationThenFadeAround( self.y_dot_label, ), ) self.play( ReplacementTransform( self.d2y_dt2_label, self.y_ddot_label, ), ShowCreationThenFadeAround( self.y_ddot_label, ), ) def show_equation(self): y_ddot = self.y_ddot_label new_y_ddot = y_ddot.deepcopy() new_y_ddot.clear_updaters() equation = VGroup( new_y_ddot, *Tex( "=", "-g", tex_to_color_map={"-g": YELLOW}, ), ) new_y_ddot.next_to(equation[1], LEFT, SMALL_BUFF) equation.move_to(self.axes) equation.to_edge(UP) self.play( TransformFromCopy(y_ddot, new_y_ddot), Write(equation[1:]), FadeOut(self.graph), FadeOut(self.y_label), FadeOut(self.h_line), FadeOut(self.v_graph), FadeOut(self.graphed_v_vect), FadeOut(self.graphed_a_vect), ) self.equation = equation def solve_for_velocity(self): axes = self.axes equation = self.equation v_graph = self.v_graph.deepcopy() v_graph.clear_updaters() v_start_point = v_graph.get_start() origin = axes.coords_to_point(0, 0) offset = v_start_point - origin v_graph.shift(-offset) tex_question, answer1, answer2 = derivs = [ OldTex( "{d", "(", *term, ")", "\\over", "dt}", "(t)", "=", "-g", tex_to_color_map={ "-g": YELLOW, "v_0": RED, "?": RED, } ) for term in [ ("?", "?", "?", "?"), ("-g", "t"), ("-g", "t", "+", "v_0",), ] ] for x in range(2): answer1.submobjects.insert( 4, VectorizedPoint(answer1[4].get_left()) ) for deriv in derivs: deriv.next_to(equation, DOWN, MED_LARGE_BUFF) question = OldTexText( "What function has slope $-g$?", tex_to_color_map={"$-g$": YELLOW}, ) question.next_to(tex_question, DOWN) question.set_stroke(BLACK, 5, background=True) question.add_background_rectangle() v0_dot = Dot(v_start_point, color=PINK) v0_label = OldTex("v_0") v0_label.set_color(RED) v0_label.next_to(v0_dot, UR, buff=0) y_dot_equation = OldTex( "{\\dot y}", "(t)", "=", "-g", "t", "+", "v_0", tex_to_color_map={ "{\\dot y}": RED, "-g": YELLOW, "v_0": RED, } ) y_dot_equation.to_corner(UR) self.play( FadeIn(tex_question, DOWN), FadeIn(question, UP) ) self.wait() self.add(v_graph, question) self.play( ReplacementTransform(tex_question, answer1), ShowCreation(v_graph), ) self.wait() self.play( ReplacementTransform(answer1, answer2), v_graph.shift, offset, ) self.play( FadeInFromLarge(v0_dot), FadeInFromDown(v0_label), ) self.wait() self.play( TransformFromCopy( answer2[2:6], y_dot_equation[3:], ), Write(y_dot_equation[:3]), equation.shift, LEFT, ) self.play( FadeOut(question), FadeOut(answer2), ) self.remove(v_graph) self.add(self.v_graph) self.y_dot_equation = y_dot_equation def solve_for_position(self): # Largely copied from above...not great equation = self.equation y_dot_equation = self.y_dot_equation graph = self.graph all_terms = [ ("?", "?", "?", "?"), ("-", "(1/2)", "g", "t^2", "+", "v_0", "t"), ("-", "(1/2)", "g", "t^2", "+", "v_0", "t", "+", "y_0"), ] tex_question, answer1, answer2 = derivs = [ OldTex( "{d", "(", *term, ")", "\\over", "dt}", "(t)", "=", "-g", "t", "+", "v_0", tex_to_color_map={ "g": YELLOW, "v_0": RED, "?": BLUE, "y_0": BLUE, } ) for term in all_terms ] answer1.scale(0.8) answer2.scale(0.8) for deriv, terms in zip(derivs, all_terms): for x in range(len(all_terms[-1]) - len(terms)): n = 2 + len(terms) deriv.submobjects.insert( n, VectorizedPoint(deriv[n].get_left()) ) deriv.next_to( VGroup(equation, y_dot_equation), DOWN, MED_LARGE_BUFF + SMALL_BUFF ) deriv.shift_onto_screen() deriv.add_background_rectangle_to_submobjects() y_equation = OldTex( "y", "(t)", "=", "-", "(1/2)", "g", "t^2", "+", "v_0", "t", "+", "y_0", tex_to_color_map={ "y": BLUE, "g": YELLOW, "v_0": RED, } ) y_equation.next_to( VGroup(equation, y_dot_equation), DOWN, MED_LARGE_BUFF, ) self.play( FadeIn(tex_question, DOWN), ) self.wait() self.add(graph, tex_question) self.play( ReplacementTransform(tex_question, answer1), ShowCreation(graph), ) self.add(graph, answer1) self.wait() self.play(ReplacementTransform(answer1, answer2)) self.add(graph, answer2) g_updaters = graph.updaters graph.clear_updaters() self.play( graph.shift, 2 * DOWN, rate_func=there_and_back, run_time=2, ) graph.add_updater(g_updaters[0]) self.wait() br = BackgroundRectangle(y_equation) self.play( FadeIn(br), ReplacementTransform( answer2[2:11], y_equation[3:] ), FadeIn(y_equation[:3]), FadeOut(answer2[:2]), FadeOut(answer2[11:]), ) self.play(ShowCreationThenFadeAround(y_equation)) self.play_trajectory() # def play_trajectory(self, *added_anims, **kwargs): self.t_tracker.set_value(0) self.play( ApplyMethod( self.t_tracker.set_value, 5, rate_func=linear, run_time=self.total_time, ), *added_anims, ) self.wait() class SimpleProjectileEquationVGraphFreedom(SimpleProjectileEquation): def construct(self): self.add_axes() self.setup_trajectory() self.clear() v_graph = self.v_graph self.t_tracker.set_value(5) v_graph.update() v_graph.clear_updaters() self.add(v_graph) self.play(v_graph.shift, 5 * DOWN, run_time=2) self.play(v_graph.shift, 5 * UP, run_time=2) class UniversalGravityLawSymbols(Scene): def construct(self): x1_tex = "\\vec{\\textbf{x}}_1" x2_tex = "\\vec{\\textbf{x}}_2" a1_tex = "\\vec{\\textbf{a}}_1" new_brown = interpolate_color(GREY_B, LIGHT_BROWN, 0.5) law = OldTex( "F_1", "=", "m_1", a1_tex, "=", "G", "m_1", "m_2", "\\left({", x2_tex, "-", x1_tex, "\\over", "||", x2_tex, "-", x1_tex, "||", "}\\right)", "\\left({", "1", "\\over", "||", x2_tex, "-", x1_tex, "||^2", "}\\right)", tex_to_color_map={ x1_tex: BLUE_C, "m_1": BLUE_C, x2_tex: new_brown, "m_2": new_brown, a1_tex: YELLOW, } ) law.to_edge(UP) force = law[:4] constants = law[4:8] unit_vect = law[8:19] inverse_square = law[19:] parts = VGroup( force, unit_vect, inverse_square ) words = VGroup( OldTexText("Force on\\\\mass 1"), OldTexText("Unit vector\\\\towards mass 2"), OldTexText("Inverse square\\\\law"), ) self.add(law) braces = VGroup() rects = VGroup() for part, word in zip(parts, words): brace = Brace(part, DOWN) word.scale(0.8) word.next_to(brace, DOWN) rect = SurroundingRectangle(part) rect.set_stroke(YELLOW, 1) braces.add(brace) rects.add(rect) self.play( ShowCreationThenFadeOut(rects[0]), GrowFromCenter(braces[0]), FadeIn(words[0], UP) ) self.wait() self.play( ShowCreationThenFadeOut(rects[1]), GrowFromCenter(braces[1]), FadeIn(words[1], UP) ) self.wait() self.play( ShowCreationThenFadeOut(rects[2]), TransformFromCopy(*braces[1:3]), FadeIn(words[2], UP), ) self.wait() # Position derivative v1_tex = "\\vec{\\textbf{v}}_1" kw = { "tex_to_color_map": { x1_tex: BLUE_C, v1_tex: RED, } } x_deriv = OldTex( "{d", x1_tex, "\\over", "dt}", "=", v1_tex, **kw ) x_deriv.to_corner(UL) v_deriv = OldTex( "{d", v1_tex, "\\over", "dt}", "=", **kw ) # Make way law.generate_target() lt = law.target lt.to_edge(RIGHT) lt[6].fade(1) lt[:6].align_to(lt[6], RIGHT) lt[:3].fade(1) v_deriv.next_to(lt[3], LEFT) self.play( FadeInFromDown(x_deriv), MoveToTarget(law), braces[1:].align_to, lt, RIGHT, MaintainPositionRelativeTo(words[1:], braces[1:]), FadeOut(words[0]), FadeOut(braces[0]), ) self.play(ShowCreationThenFadeAround(x_deriv)) self.play( TransformFromCopy( x_deriv.get_part_by_tex(v1_tex), v_deriv.get_part_by_tex(v1_tex), ), Write(VGroup(*filter( lambda m: m is not v_deriv.get_part_by_tex(v1_tex), v_deriv, ))) ) x_parts = law.get_parts_by_tex(x1_tex) self.play( TransformFromCopy( x_deriv.get_parts_by_tex(x1_tex), x_parts.copy(), remover=True, path_arc=30 * DEGREES, ) ) self.play( LaggedStartMap( ShowCreationThenFadeAround, x_parts ) ) self.wait() class ExampleTypicalODE(TeacherStudentsScene): def construct(self): examples = VGroup( OldTex( "{\\dot x}(t) = k{x}(t)", tex_to_color_map={ "{\\dot x}": BLUE, "{x}": BLUE, }, ), get_ode(), OldTex( "{\\partial T", "\\over", "\\partial t} = ", "{\\partial^2 T", "\\over", "\\partial x^2}", "+", "{\\partial^2 T", "\\over", "\\partial y^2}", "+", "{\\partial^2 T", "\\over", "\\partial z^2}", tex_to_color_map={ "T": RED, } ), ) examples[1].get_parts_by_tex("theta").set_color(GREEN) examples.arrange(DOWN, buff=MED_LARGE_BUFF) examples.to_edge(UP) self.play( FadeIn(examples[0], UP), self.teacher.change, "raise_right_hand", ) self.play( FadeIn(examples[1], UP), self.change_students( *3 * ["pondering"], look_at=examples, ), ) self.play( FadeIn(examples[2], UP) ) self.wait(5) class ShowDerivativeVideo(Scene): def construct(self): title = OldTexText("Essence of", "Calculus") title.scale(1.5) title.to_edge(UP) title2 = OldTexText("Essence of", "Linear Algebra") title2.scale(1.5) title2.move_to(title, DOWN) rect = ScreenRectangle(height=6) rect = rect.copy() rect.set_style( fill_opacity=1, fill_color=BLACK, stroke_width=0, ) rect.next_to(title, DOWN) animated_rect = AnimatedBoundary(rect) self.add(title, rect) self.add(animated_rect) self.wait(5) self.play(ReplacementTransform(title, title2)) self.wait(10) class SubtleAirCurrents(Scene): def construct(self): pass class DefineODE(Scene): CONFIG = { "pendulum_config": { "length": 2, "top_point": 5 * RIGHT + 2 * UP, "initial_theta": 150 * DEGREES, "mu": 0.3, }, "axes_config": { "y_axis_config": {"unit_size": 0.75}, "y_max": PI, "y_min": -PI, "x_max": 10, "x_axis_config": { "numbers_to_show": range(2, 10, 2), "unit_size": 1, } }, } def construct(self): self.add_graph() self.write_differential_equation() self.dont_know_the_value() self.show_value_slope_curvature() self.write_ode() self.show_second_order() self.show_higher_order_examples() self.show_changing_curvature_group() def add_graph(self): pendulum = Pendulum(**self.pendulum_config) axes = ThetaVsTAxes(**self.axes_config) axes.center() axes.to_corner(DL) graph = axes.get_live_drawn_graph(pendulum) pendulum.start_swinging() self.add(axes, pendulum, graph) self.pendulum = pendulum self.axes = axes self.graph = graph def write_differential_equation(self): de_word = OldTexText("Differential", "Equation") de_word.to_edge(UP, buff=MED_SMALL_BUFF) equation = get_ode() equation.next_to(de_word, DOWN) thetas = equation.get_parts_by_tex("\\theta") lines = VGroup(*[ Line(v, 1.2 * v) for v in compass_directions(25) ]) lines.replace(equation, stretch=True) lines.scale(1.5) lines.set_stroke(YELLOW) lines.shuffle() self.add(equation) self.wait(5) self.play( ShowPassingFlashWithThinningStrokeWidth( lines, lag_ratio=0.002, run_time=1.5, time_width=0.9, n_segments=5, ) ) self.play(FadeInFromDown(de_word)) self.wait(2) self.play( LaggedStartMap( ApplyMethod, thetas, lambda m: (m.shift, 0.25 * DOWN), rate_func=there_and_back, ) ) self.wait() self.de_word = de_word self.equation = equation def dont_know_the_value(self): graph = self.graph pendulum = self.pendulum q_marks = VGroup(*[ OldTex("?").move_to(graph.point_from_proportion(a)) for a in np.linspace(0, 1, 20) ]) q_marks.set_stroke(width=0, background=True) self.play( VFadeOut(graph), FadeOut(pendulum), LaggedStart(*[ UpdateFromAlphaFunc( q_mark, lambda m, a: m.set_height(0.5 * (1 + a)).set_fill( opacity=there_and_back(a) ), ) for q_mark in q_marks ], lag_ratio=0.01, run_time=2) ) self.remove(q_marks) def show_value_slope_curvature(self): axes = self.axes p = self.pendulum graph = axes.get_graph( lambda t: p.initial_theta * np.cos( np.sqrt(p.gravity / p.length) * t ) * np.exp(-p.mu * t / 2) ) tex_config = { "tex_to_color_map": { "{\\theta}": BLUE, "{\\dot\\theta}": RED, "{\\ddot\\theta}": YELLOW, }, "height": 0.5, } theta, d_theta, dd_theta = [ OldTex( "{" + s + "\\theta}(t)", **tex_config ) for s in ("", "\\dot", "\\ddot") ] t_tracker = ValueTracker(2.5) get_t = t_tracker.get_value def get_point(t): return graph.point_from_proportion(t / axes.x_max) def get_dot(): return Dot(get_point(get_t())).scale(0.5) def get_v_line(): point = get_point(get_t()) x_point = axes.x_axis.number_to_point( axes.x_axis.point_to_number(point) ) return DashedLine( x_point, point, dash_length=0.025, stroke_color=BLUE, stroke_width=2, ) def get_tangent_line(curve, alpha): line = Line( ORIGIN, 1.5 * RIGHT, color=RED, stroke_width=1.5, ) da = 0.0001 p0 = curve.point_from_proportion(alpha) p1 = curve.point_from_proportion(alpha - da) p2 = curve.point_from_proportion(alpha + da) angle = angle_of_vector(p2 - p1) line.rotate(angle) line.move_to(p0) return line def get_slope_line(): return get_tangent_line( graph, get_t() / axes.x_max ) def get_curve(): curve = VMobject() t = get_t() curve.set_points_smoothly([ get_point(t + a) for a in np.linspace(-0.5, 0.5, 11) ]) curve.set_stroke(YELLOW, 1) return curve v_line = always_redraw(get_v_line) dot = always_redraw(get_dot) slope_line = always_redraw(get_slope_line) curve = always_redraw(get_curve) theta.next_to(v_line, RIGHT, SMALL_BUFF) d_theta.next_to(slope_line.get_end(), UP, SMALL_BUFF) dd_theta.next_to(curve.get_end(), RIGHT, SMALL_BUFF) thetas = VGroup(theta, d_theta, dd_theta) words = VGroup( OldTexText("= Height").set_color(BLUE), OldTexText("= Slope").set_color(RED), OldTexText("= ``Curvature''").set_color(YELLOW), ) words.scale(0.75) for word, sym in zip(words, thetas): word.next_to(sym, RIGHT, buff=2 * SMALL_BUFF) sym.word = word self.play( ShowCreation(v_line), FadeInFromPoint(dot, v_line.get_start()), FadeIn(theta, DOWN), FadeIn(theta.word, DOWN), ) self.add(slope_line, dot) self.play( ShowCreation(slope_line), FadeIn(d_theta, LEFT), FadeIn(d_theta.word, LEFT), ) a_tracker = ValueTracker(0) curve_copy = curve.copy() changing_slope = always_redraw( lambda: get_tangent_line( curve_copy, a_tracker.get_value(), ).set_stroke( opacity=there_and_back(a_tracker.get_value()) ) ) self.add(curve, dot) self.play( ShowCreation(curve), FadeIn(dd_theta, LEFT), FadeIn(dd_theta.word, LEFT), ) self.add(changing_slope) self.play( a_tracker.set_value, 1, run_time=3, ) self.remove(changing_slope, a_tracker) self.t_tracker = t_tracker self.curvature_group = VGroup( v_line, slope_line, curve, dot ) self.curvature_group_labels = VGroup(thetas, words) self.fake_graph = graph def write_ode(self): equation = self.equation axes = self.axes de_word = self.de_word ts = equation.get_parts_by_tex("{t}") t_rects = VGroup(*map(SurroundingRectangle, ts)) # Rawr x_axis = axes.x_axis x_axis_line = Line( x_axis.get_start(), x_axis.get_end(), stroke_color=YELLOW, stroke_width=5, ) ordinary = OldTexText("Ordinary") de_word.generate_target() group = VGroup(ordinary, de_word.target) group.arrange(RIGHT) group.to_edge(UP) ordinary_underline = Line(LEFT, RIGHT) ordinary_underline.replace(ordinary, dim_to_match=0) ordinary_underline.next_to(ordinary, DOWN, SMALL_BUFF) ordinary_underline.set_color(YELLOW) self.play( ShowCreationThenFadeOut( t_rects, lag_ratio=0.8 ), ShowCreationThenFadeOut(x_axis_line) ) self.play( MoveToTarget(de_word), FadeIn(ordinary, RIGHT), GrowFromCenter(ordinary_underline) ) self.play(FadeOut(ordinary_underline)) self.wait() self.remove(ordinary, de_word) ode_word = self.ode_word = VGroup(*ordinary, *de_word) ode_initials = VGroup(*[word[0] for word in ode_word]) ode_initials.generate_target() ode_initials.target.scale(1.2) ode_initials.target.set_color(PINK) ode_initials.target.arrange( RIGHT, buff=0.5 * SMALL_BUFF, aligned_edge=DOWN ) ode_initials.target.to_edge(UP, buff=MED_SMALL_BUFF) ode_remaining_letters = VGroup(*it.chain(*[ word[1:] for word in ode_word ])) ode_remaining_letters.generate_target() for mob in ode_remaining_letters.target: mob.shift(0.2 * UP) mob.fade(1) self.play( MoveToTarget(ode_initials), MoveToTarget(ode_remaining_letters, lag_ratio=0.05), ) self.wait() self.ode_initials = ode_initials def show_second_order(self): so = OldTexText("Second order") so.scale(1.4) ode = self.ode_initials ode.generate_target() group = VGroup(so, ode.target) group.arrange(RIGHT, aligned_edge=DOWN) group.to_edge(UP, buff=MED_SMALL_BUFF) second_deriv = self.equation[:5] self.play( Write(so), MoveToTarget(ode), ) self.wait() self.play(FocusOn(second_deriv)) self.play( Indicate(second_deriv, color=YELLOW), ) self.wait() self.second_order_word = so def show_higher_order_examples(self): main_example = self.get_main_example() tex_config = {"tex_to_color_map": {"{x}": BLUE}} example3 = VGroup( OldTexText("Third order ODE"), OldTex( "\\dddot {x}(t) + \\dot {x}(t)^2 = 0", **tex_config, ) ) example4 = VGroup( OldTexText("Fourth order ODE"), OldTex( "\\ddddot {x}(t) +", "a\\dddot {x}(t) \\dot {x}(t) + ", "b \\ddot {x}(t) {x}(t)", "= 1", **tex_config, ) ) for example in [example3, example4]: example[0].scale(1.2) example.arrange(DOWN, buff=MED_LARGE_BUFF) example.to_edge(UP, buff=MED_SMALL_BUFF) self.play( FadeOut(main_example), FadeIn(example3), ) self.wait(2) self.play( FadeOut(example3), FadeIn(example4), ) self.wait(2) self.play( FadeOut(example4), FadeIn(main_example), ) self.wait(2) def get_main_example(self): return VGroup( self.second_order_word, self.ode_initials, self.equation ) def show_changing_curvature_group(self): t_tracker = self.t_tracker curvature_group = self.curvature_group labels = self.curvature_group_labels graph = VMobject() graph.pointwise_become_partial( self.fake_graph, t_tracker.get_value() / self.axes.x_max, 1, ) dashed_graph = DashedVMobject(graph, num_dashes=100) dashed_graph.set_stroke(GREEN, 1) self.play(FadeOut(labels)) self.add(dashed_graph, curvature_group) self.play( t_tracker.set_value, 10, ShowCreation(dashed_graph), run_time=15, rate_func=linear, ) self.wait() # Largely a copy of DefineODE, which is not great. # But what can you do? class SecondOrderEquationExample(DefineODE): def construct(self): self.add_graph() self.write_differential_equation() self.show_value_slope_curvature() self.show_higher_order_examples() self.show_changing_curvature_group() def add_graph(self): axes = self.axes = Axes( x_min=0, x_max=10.5, y_min=-2.5, y_max=2.5, ) axes.center() axes.to_edge(DOWN) x_t = OldTex("x", "(t)") x_t.set_color_by_tex("x", BLUE) t = OldTex("t") t.next_to(axes.x_axis.get_right(), UP) x_t.next_to(axes.y_axis.get_top(), UP) axes.add(t, x_t) axes.add_coordinates() self.add(axes) def write_differential_equation(self): de_word = OldTexText("Differential", "Equation") de_word.scale(1.25) de_word.to_edge(UP, buff=MED_SMALL_BUFF) so_word = OldTexText("Second Order") so_word.scale(1.25) de_word.generate_target() group = VGroup(so_word, de_word.target) group.arrange(RIGHT) group.to_edge(UP, buff=MED_SMALL_BUFF) so_word.align_to(de_word.target[0], DOWN) so_line = Line(LEFT, RIGHT, color=YELLOW) so_line.match_width(so_word) so_line.next_to(so_word, DOWN, buff=SMALL_BUFF) equation = OldTex( "{\\ddot x}(t)", "=", "-\\mu", "{\\dot x}(t)", "-", "\\omega", "{x}(t)", tex_to_color_map={ "{x}": BLUE, "{\\dot x}": RED, "{\\ddot x}": YELLOW, } ) equation.next_to(de_word, DOWN) dd_x_part = equation[:2] dd_x_rect = SurroundingRectangle(dd_x_part) self.add(de_word, equation) self.play( MoveToTarget(de_word), FadeIn(so_word, RIGHT), GrowFromCenter(so_line), ) self.play(ReplacementTransform(so_line, dd_x_rect)) self.play(FadeOut(dd_x_rect)) self.equation = equation self.title = VGroup(*so_word, *de_word) def show_value_slope_curvature(self): axes = self.axes graph = axes.get_graph( lambda t: -2.5 * np.cos(2 * t) * np.exp(-0.2 * t) ) tex_config = { "tex_to_color_map": { "{x}": BLUE, "{\\dot x}": RED, "{\\ddot x}": YELLOW, }, "height": 0.5, } x, d_x, dd_x = [ OldTex( "{" + s + "x}(t)", **tex_config ) for s in ("", "\\dot ", "\\ddot ") ] t_tracker = ValueTracker(1.25) get_t = t_tracker.get_value def get_point(t): return graph.point_from_proportion(t / axes.x_max) def get_dot(): return Dot(get_point(get_t())).scale(0.5) def get_v_line(): point = get_point(get_t()) x_point = axes.x_axis.number_to_point( axes.x_axis.point_to_number(point) ) return DashedLine( x_point, point, dash_length=0.025, stroke_color=BLUE, stroke_width=2, ) def get_tangent_line(curve, alpha): line = Line( ORIGIN, 1.5 * RIGHT, color=RED, stroke_width=1.5, ) da = 0.0001 p0 = curve.point_from_proportion(alpha) p1 = curve.point_from_proportion(alpha - da) p2 = curve.point_from_proportion(alpha + da) angle = angle_of_vector(p2 - p1) line.rotate(angle) line.move_to(p0) return line def get_slope_line(): return get_tangent_line( graph, get_t() / axes.x_max ) def get_curve(): curve = VMobject() t = get_t() curve.set_points_smoothly([ get_point(t + a) for a in np.linspace(-0.5, 0.5, 11) ]) curve.set_stroke(YELLOW, 1) return curve v_line = always_redraw(get_v_line) dot = always_redraw(get_dot) slope_line = always_redraw(get_slope_line) curve = always_redraw(get_curve) x.next_to(v_line, RIGHT, SMALL_BUFF) d_x.next_to(slope_line.get_end(), UP, SMALL_BUFF) dd_x.next_to(curve.get_end(), RIGHT, SMALL_BUFF) xs = VGroup(x, d_x, dd_x) words = VGroup( OldTexText("= Height").set_color(BLUE), OldTexText("= Slope").set_color(RED), OldTexText("= ``Curvature''").set_color(YELLOW), ) words.scale(0.75) for word, sym in zip(words, xs): word.next_to(sym, RIGHT, buff=2 * SMALL_BUFF) sym.word = word self.play( ShowCreation(v_line), FadeInFromPoint(dot, v_line.get_start()), FadeIn(x, DOWN), FadeIn(x.word, DOWN), ) self.add(slope_line, dot) self.play( ShowCreation(slope_line), FadeIn(d_x, LEFT), FadeIn(d_x.word, LEFT), ) a_tracker = ValueTracker(0) curve_copy = curve.copy() changing_slope = always_redraw( lambda: get_tangent_line( curve_copy, a_tracker.get_value(), ).set_stroke( opacity=there_and_back(a_tracker.get_value()) ) ) self.add(curve, dot) self.play( ShowCreation(curve), FadeIn(dd_x, LEFT), FadeIn(dd_x.word, LEFT), ) self.add(changing_slope) self.play( a_tracker.set_value, 1, run_time=3, ) self.remove(changing_slope, a_tracker) self.t_tracker = t_tracker self.curvature_group = VGroup( v_line, slope_line, curve, dot ) self.curvature_group_labels = VGroup(xs, words) self.fake_graph = graph def get_main_example(self): return VGroup( self.equation, self.title, ) # class VisualizeHeightSlopeCurvature(DefineODE): # CONFIG = { # "pendulum_config": { # "length": 2, # "top_point": 5 * RIGHT + 2 * UP, # "initial_theta": 175 * DEGREES, # "mu": 0.3, # }, # } # def construct(self): # self.add_graph() # self.show_value_slope_curvature() # self.show_changing_curvature_group() class ODEvsPDEinFrames(Scene): CONFIG = { "camera_config": {"background_color": GREY_E} } def construct(self): frames = VGroup(*[ ScreenRectangle( height=3.5, fill_opacity=1, fill_color=BLACK, stroke_width=0, ) for x in range(2) ]) frames.arrange(RIGHT, buff=LARGE_BUFF) frames.shift(0.5 * DOWN) animated_frames = VGroup(*[ AnimatedBoundary( frame, cycle_rate=0.2, max_stroke_width=1, ) for frame in frames ]) titles = VGroup( # OldTexText("ODEs"), # OldTexText("PDEs"), OldTexText("Ordinary", "Differential", "Equations"), OldTexText("Partial", "Differential", "Equations"), ) for title, frame in zip(titles, frames): title.arrange( DOWN, buff=MED_SMALL_BUFF, aligned_edge=LEFT ) title.next_to(frame, UP, MED_LARGE_BUFF) title.initials = VGroup(*[ part[0] for part in title ]) titles[0][1].shift(0.05 * UP) # ODE content ode = get_ode() ode.set_width(frames[0].get_width() - MED_LARGE_BUFF) ode.next_to(frames[0].get_top(), DOWN) ts = ode.get_parts_by_tex("{t}") one_input = OldTexText("One input") one_input.next_to(frames[0].get_bottom(), UP) o_arrows = VGroup(*[ Arrow( one_input.get_top(), t.get_bottom(), buff=0.2, color=WHITE, max_tip_length_to_length_ratio=0.075, path_arc=pa ) for t, pa in zip(ts, [-0.7, 0, 0.7]) ]) o_arrows.set_stroke(width=3) frames[0].add(ode, one_input, o_arrows) # PDE content pde = OldTex( """ \\frac{\\partial T}{\\partial t} {(x, y, t)} = \\frac{\\partial^2 T}{\\partial x^2} {(x, y, t)} + \\frac{\\partial^2 T}{\\partial y^2} {(x, y, t)} """, tex_to_color_map={"{(x, y, t)}": WHITE} ) pde.set_width(frames[1].get_width() - MED_LARGE_BUFF) pde.next_to(frames[1].get_top(), DOWN) inputs = pde.get_parts_by_tex("{(x, y, t)}") multi_input = OldTexText("Multiple inputs") multi_input.next_to(frames[1].get_bottom(), UP) p_arrows = VGroup(*[ Arrow( multi_input.get_top(), mob.get_bottom(), buff=0.2, color=WHITE, max_tip_length_to_length_ratio=0.075, path_arc=pa ) for mob, pa in zip(inputs, [-0.7, 0, 0.7]) ]) p_arrows.set_stroke(width=3) frames[1].add(pde, multi_input, p_arrows) self.add( frames[0], animated_frames[0], titles[0] ) self.play( Write(one_input), ShowCreation(o_arrows, lag_ratio=0.5) ) self.wait(2) self.play(titles[0].initials.set_color, BLUE) self.wait(7) # Transition self.play( TransformFromCopy(*titles), TransformFromCopy(*frames), ) self.play(VFadeIn(animated_frames[1])) self.wait() self.play(titles[1].initials.set_color, YELLOW) self.wait(30) class ReferencePiCollisionStateSpaces(Scene): CONFIG = { "camera_config": {"background_color": GREY_E} } def construct(self): title = OldTexText("The block collision puzzle") title.scale(1.5) title.to_edge(UP) self.add(title) frames = VGroup(*[ ScreenRectangle( height=3.5, fill_opacity=1, fill_color=BLACK, stroke_width=0, ) for x in range(2) ]) frames.arrange(RIGHT, buff=LARGE_BUFF) boundary = AnimatedBoundary(frames) self.add(frames, boundary) self.wait(15) class XComponentArrows(Scene): def construct(self): field = VectorField( lambda p: np.array([p[1], 0, 0]) ) field.set_opacity(0.75) for u in (1, -1): field.sort(lambda p: u * p[0]) self.play(LaggedStartMap( GrowArrow, field, lag_ratio=0.1, run_time=1 )) self.play(FadeOut(field)) class BreakingSecondOrderIntoTwoFirstOrder(IntroduceVectorField): def construct(self): ode = OldTex( "{\\ddot\\theta}", "(t)", "=", "-\\mu", "{\\dot\\theta}", "(t)" "-(g / L)\\sin\\big(", "{\\theta}", "(t)\\big)", tex_to_color_map={ "{\\ddot\\theta}": RED, "{\\dot\\theta}": YELLOW, "{\\theta}": BLUE, # "{t}": WHITE, } ) so_word = OldTexText("Second order ODE") sys_word = OldTexText("System of two first order ODEs") system1 = self.get_system("{\\theta}", "{\\dot\\theta}") system2 = self.get_system("{\\theta}", "{\\omega}") so_word.to_edge(UP) ode.next_to(so_word, DOWN) sys_word.move_to(ORIGIN) system1.next_to(sys_word, DOWN) system2.move_to(system1) theta_dots = VGroup(*filter( lambda m: ( isinstance(m, SingleStringTex) and "{\\dot\\theta}" == m.get_tex() ), system1.get_family(), )) self.add(ode) self.play(FadeIn(so_word, 0.5 * DOWN)) self.wait() self.play( TransformFromCopy( ode[3:], system1[3].get_entries()[1], ), TransformFromCopy(ode[2], system1[2]), TransformFromCopy( ode[:2], VGroup( system1[0], system1[1].get_entries()[1], ) ), ) self.play( FadeIn(system1[1].get_brackets()), FadeIn(system1[1].get_entries()[0]), FadeIn(system1[3].get_brackets()), FadeIn(system1[3].get_entries()[0]), ) self.play( FadeInFromDown(sys_word) ) self.wait() self.play(LaggedStartMap( ShowCreationThenFadeAround, theta_dots, surrounding_rectangle_config={ "color": PINK, } )) self.play(ReplacementTransform(system1, system2)) self.wait() def get_system(self, tex1, tex2): system = VGroup( OldTex("d \\over dt"), self.get_vector_symbol( tex1 + "(t)", tex2 + "(t)", ), OldTex("="), self.get_vector_symbol( tex2 + "(t)", "".join([ "-\\mu", tex2, "(t)", "-(g / L) \\sin\\big(", tex1, "(t)", "\\big)", ]) ) ) system.arrange(RIGHT) return system class FromODEToVectorField(Scene): def construct(self): matrix_config = { "bracket_v_buff": 2 * SMALL_BUFF, "element_to_mobject_config": { "tex_to_color_map": { "x": GREEN, "y": RED, "z": BLUE, }, } } vect = get_vector_symbol( "x(t)", "y(t)", "z(t)", **matrix_config, ) d_vect = get_vector_symbol( "\\sigma\\big(y(t) - x(t)\\big)", "x(t)\\big(\\rho - z(t)\\big) - y(t)", "x(t)y(t) - \\beta z(t)", **matrix_config ) equation = VGroup( OldTex("d \\over dt").scale(1.5), vect, OldTex("="), d_vect ) equation.scale(0.8) equation.arrange(RIGHT) equation.to_edge(UP) arrow = Vector(DOWN, color=YELLOW) arrow.next_to(equation, DOWN) self.add(equation) self.play(ShowCreation(arrow)) self.wait() class LorenzVectorField(ExternallyAnimatedScene): pass class ThreeBodiesInSpace(SpecialThreeDScene): CONFIG = { "masses": [1, 6, 3], "colors": [RED_E, GREEN_E, BLUE_E], "G": 0.5, "play_time": 60, } def construct(self): self.add_axes() self.add_bodies() self.add_trajectories() self.let_play() def add_axes(self): axes = self.axes = self.get_axes() axes.set_stroke(width=0.5) self.add(axes) # Orient self.set_camera_orientation( phi=70 * DEGREES, theta=-110 * DEGREES, ) self.begin_ambient_camera_rotation() def add_bodies(self): masses = self.masses colors = self.colors bodies = self.bodies = VGroup() velocity_vectors = VGroup() centers = self.get_initial_positions() for mass, color, center in zip(masses, colors, centers): body = self.get_sphere( checkerboard_colors=[ color, color ], color=color, stroke_width=0.1, ) body.set_opacity(0.75) body.mass = mass body.radius = 0.08 * np.sqrt(mass) body.set_width(2 * body.radius) body.point = center body.move_to(center) body.velocity = self.get_initial_velocity( center, centers, mass ) vect = self.get_velocity_vector_mob(body) bodies.add(body) velocity_vectors.add(vect) total_mass = np.sum([body.mass for body in bodies]) center_of_mass = reduce(op.add, [ body.mass * body.get_center() / total_mass for body in bodies ]) average_momentum = reduce(op.add, [ body.mass * body.velocity / total_mass for body in bodies ]) for body in bodies: body.shift(-center_of_mass) body.velocity -= average_momentum def get_initial_positions(self): return [ np.dot( 4 * (np.random.random(3) - 0.5), [RIGHT, UP, OUT] ) for x in range(len(self.masses)) ] def get_initial_velocity(self, center, centers, mass): to_others = [ center - center2 for center2 in centers ] velocity = 0.2 * mass * normalize(np.cross(*filter( lambda diff: get_norm(diff) > 0, to_others ))) return velocity def add_trajectories(self): def update_trajectory(traj, dt): new_point = traj.body.point if get_norm(new_point - traj.get_points()[-1]) > 0.01: traj.add_smooth_curve_to(new_point) for body in self.bodies: traj = VMobject() traj.body = body traj.start_new_path(body.point) traj.set_stroke(body.color, 1, opacity=0.75) traj.add_updater(update_trajectory) self.add(traj, body) def let_play(self): bodies = self.bodies bodies.add_updater(self.update_bodies) # Break it up to see partial files as # it's rendered self.add(bodies) for x in range(int(self.play_time)): self.wait() # def get_velocity_vector_mob(self, body): def draw_vector(): center = body.get_center() vect = Arrow( center, center + body.velocity, buff=0, color=RED, ) vect.set_shade_in_3d(True) return vect # length = vect.get_length() # if length > 2: # vect.scale( # 2 / length, # about_point=vect.get_start(), # ) return always_redraw(draw_vector) def update_bodies(self, bodies, dt): G = self.G num_mid_steps = 1000 for x in range(num_mid_steps): for body in bodies: acceleration = np.zeros(3) for body2 in bodies: if body2 is body: continue diff = body2.point - body.point m2 = body2.mass R = get_norm(diff) acceleration += G * m2 * diff / (R**3) body.point += body.velocity * dt / num_mid_steps body.velocity += acceleration * dt / num_mid_steps for body in bodies: body.move_to(body.point) return bodies class AltThreeBodiesInSpace(ThreeBodiesInSpace): CONFIG = { "random_seed": 6, "masses": [1, 2, 6], } class TwoBodiesInSpace(ThreeBodiesInSpace): CONFIG = { "colors": [GREY, BLUE], "masses": [6, 36], "play_time": 60, } def construct(self): self.add_axes() self.add_bodies() self.add_trajectories() self.add_velocity_vectors() self.add_force_vectors() self.let_play() def add_bodies(self): super().add_bodies() for body in self.bodies: body.point = 3 * normalize(body.get_center()) # body.point += 2 * IN # body.velocity += (4 / 60) * OUT body.move_to(body.point) def get_initial_positions(self): return [ np.dot( 6 * (np.random.random(3) - 0.5), [RIGHT, UP, ORIGIN] ) for x in range(len(self.masses)) ] def get_initial_velocity(self, center, centers, mass): return 0.75 * normalize(np.cross(center, OUT)) def add_velocity_vectors(self): vectors = VGroup(*[ self.get_velocity_vector(body) for body in self.bodies ]) self.velocity_vectors = vectors self.add(vectors) def get_velocity_vector(self, body): def create_vector(b): v = Vector( b.velocity, color=RED, max_stroke_width_to_length_ratio=3, ) v.set_stroke(width=3) v.shift( b.point + b.radius * normalize(b.velocity) - v.get_start(), ) v.set_shade_in_3d(True) return v return always_redraw(lambda: create_vector(body)) def add_force_vectors(self): vectors = VGroup(*[ self.get_force_vector(b1, b2) for (b1, b2) in (self.bodies, self.bodies[::-1]) ]) self.force_vectors = vectors self.add(vectors) def get_force_vector(self, body1, body2): def create_vector(b1, b2): r = b2.point - b1.point F = r / (get_norm(r)**3) v = Vector( 4 * F, color=YELLOW, max_stroke_width_to_length_ratio=3, ) v.set_stroke(width=3) v.shift( b1.point + b1.radius * normalize(F) - v.get_start(), ) v.set_shade_in_3d(True) return v return always_redraw(lambda: create_vector(body1, body2)) class TwoBodiesWithZPart(TwoBodiesInSpace): def add_bodies(self): super().add_bodies() for body in self.bodies: body.point += 3 * IN body.velocity += (6 / 60) * OUT class LoveExample(PiCreatureScene): def construct(self): self.show_hearts() self.add_love_trackers() self.break_down_your_rule() self.break_down_their_rule() def create_pi_creatures(self): you = You() you.shift(FRAME_WIDTH * LEFT / 4) you.to_edge(DOWN) tau = TauCreature(color=GREEN) tau.flip() tau.shift(FRAME_WIDTH * RIGHT / 4) tau.to_edge(DOWN) self.you = you self.tau = tau return (you, tau) def show_hearts(self): you, tau = self.you, self.tau hearts = VGroup() n_hearts = 20 for x in range(n_hearts): heart = SuitSymbol("hearts") heart.scale(0.5 + 2 * np.random.random()) heart.shift(np.random.random() * 4 * RIGHT) heart.shift(np.random.random() * 4 * UP) hearts.add(heart) hearts.move_to(2 * DOWN) hearts.add_updater(lambda m, dt: m.shift(2 * dt * UP)) self.add(hearts) self.play( LaggedStartMap( UpdateFromAlphaFunc, hearts, lambda heart: ( heart, lambda h, a: h.set_opacity( there_and_back(a) ).shift(0.02 * UP) ), lag_ratio=0.01, run_time=3, suspend_mobject_updating=False, ), ApplyMethod( you.change, 'hooray', tau.eyes, run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1) ), ApplyMethod( tau.change, 'hooray', you.eyes, run_time=2, rate_func=squish_rate_func(smooth, 0.5, 1) ), ) self.remove(hearts) self.wait() def add_love_trackers(self): self.init_ps_point() self.add_love_decimals() self.add_love_number_lines() self.tie_creature_state_to_ps_point() self.play(Rotating( self.ps_point, radians=-7 * TAU / 8, about_point=ORIGIN, run_time=10, rate_func=linear, )) self.wait() def break_down_your_rule(self): label1 = self.love_1_label label2 = self.love_2_label ps_point = self.ps_point up_arrow = Vector(UP, color=GREEN) down_arrow = Vector(DOWN, color=RED) for arrow in (up_arrow, down_arrow): arrow.next_to(label1, RIGHT) self.play(GrowArrow(up_arrow)) self.play( self.tau.love_eyes.scale, 1.25, self.tau.love_eyes.set_color, BLUE_C, rate_func=there_and_back, ) self.play( ps_point.shift, 6 * RIGHT, run_time=2, ) self.wait() ps_point.shift(13 * DOWN) self.play( FadeOut(up_arrow), GrowArrow(down_arrow), ) self.play( ps_point.shift, 11 * LEFT, run_time=3, ) self.wait() # Derivative equation = get_love_equation1() equation.shift(0.5 * UP) deriv, equals, a, h2 = equation self.play( Write(deriv[:-1]), Write(equals), Write(a), TransformFromCopy(label1[0], deriv.heart), TransformFromCopy(label2[0], h2), ) self.wait() self.play( equation.scale, 0.5, equation.to_corner, UL, FadeOut(down_arrow) ) def break_down_their_rule(self): label1 = self.love_1_label label2 = self.love_2_label ps_point = self.ps_point up_arrow = Vector(UP, color=GREEN) down_arrow = Vector(DOWN, color=RED) for arrow in (up_arrow, down_arrow): arrow.next_to(label2, RIGHT) # Derivative equation = get_love_equation2() equation.shift(0.5 * UP) deriv, equals, mb, h1 = equation self.play( Write(deriv[:-1]), Write(equals), Write(mb), TransformFromCopy(label1[0], h1), TransformFromCopy(label2[0], deriv.heart), ) self.play(GrowArrow(up_arrow)) self.play( ps_point.shift, 13 * UP, run_time=3, ) self.wait() self.play( ps_point.shift, 11 * RIGHT, ) self.play( FadeOut(up_arrow), GrowArrow(down_arrow), ) self.play( ps_point.shift, 13 * DOWN, run_time=3, ) self.wait() # def init_ps_point(self): self.ps_point = VectorizedPoint(np.array([5.0, 5.0, 0])) def get_love1(self): return self.ps_point.get_location()[0] def get_love2(self): return self.ps_point.get_location()[1] def set_loves(self, love1=None, love2=None): if love1 is not None: self.ps_point.set_x(love1) if love2 is not None: self.ps_point.set_x(love2) def add_love_decimals(self): self.love_1_label = self.add_love_decimal( 1, self.get_love1, self.you.get_color(), -3, ) self.love_2_label = self.add_love_decimal( 2, self.get_love2, self.tau.get_color(), 3, ) def add_love_decimal(self, index, value_func, color, x_coord): d = DecimalNumber(include_sign=True) d.add_updater(lambda d: d.set_value(value_func())) label = get_heart_var(index) label.move_to(x_coord * RIGHT) label.to_edge(UP) eq = OldTex("=") eq.next_to(label, RIGHT, SMALL_BUFF) eq.shift(SMALL_BUFF * UP) d.next_to(eq, RIGHT, SMALL_BUFF) self.add(label, eq, d) return VGroup(label, eq, d) def add_love_number_lines(self): nl1 = NumberLine( x_min=-8, x_max=8, unit_size=0.25, tick_frequency=2, number_scale_val=0.25, ) nl1.set_stroke(width=1) nl1.next_to(self.love_1_label, DOWN) nl1.add_numbers(*range(-6, 8, 2)) nl2 = nl1.copy() nl2.next_to(self.love_2_label, DOWN) dot1 = Dot(color=self.you.get_color()) dot1.add_updater(lambda d: d.move_to( nl1.number_to_point(self.get_love1()) )) dot2 = Dot(color=self.tau.get_color()) dot2.add_updater(lambda d: d.move_to( nl2.number_to_point(self.get_love2()) )) self.add(nl1, nl2, dot1, dot2) def get_love_eyes(self, eyes): hearts = VGroup() for eye in eyes: heart = SuitSymbol("hearts") heart.match_width(eye) heart.move_to(eye) heart.scale(1.25) heart.set_stroke(BLACK, 1) hearts.add(heart) hearts.add_updater( lambda m: m.move_to(eyes) ) return hearts def tie_creature_state_to_ps_point(self): # Quite a mess, but I'm coding in a rush here... you = self.you you_copy = you.copy() tau = self.tau tau_copy = tau.copy() you.love_eyes = self.get_love_eyes(you.eyes) tau.love_eyes = self.get_love_eyes(tau.eyes) self.add(you.love_eyes) self.add(tau.love_eyes) you_height = you.get_height() tau_height = tau.get_height() you_bottom = you.get_bottom() tau_bottom = tau.get_bottom() def update_you(y): love = self.get_love1() cutoff_values = [ -5, -3, -1, 1, 3, 5 ] modes = [ "angry", "sassy", "hesitant", "plain", "happy", "hooray", "surprised", ] if love < cutoff_values[0]: y.change(modes[0]) elif love >= cutoff_values[-1]: y.change(modes[-1]) else: i = 0 while cutoff_values[i] < love: i += 1 m1 = modes[i - 1] m2 = modes[i] y.change(m1) you_copy.change(m2) for mob in y, you_copy: mob.set_height(you_height) mob.move_to(you_bottom, DOWN) alpha = inverse_interpolate( cutoff_values[i - 1], cutoff_values[i], love, ) s_alpha = squish_rate_func(smooth, 0.25, 1)(alpha) if s_alpha > 0: y.align_data_and_family(you_copy) f1 = y.family_members_with_points() f2 = you_copy.family_members_with_points() for sm1, sm2 in zip(f1, f2): sm1.interpolate(sm1, sm2, s_alpha) y.look_at(tau.eyes) if love < -4: y.look_at(LEFT_SIDE) # y.move_to( # you_bottom + 0.025 * love * RIGHT, DOWN, # ) l_alpha = np.clip( inverse_interpolate(5, 5.5, love), 0, 1 ) y.eyes.set_opacity(1 - l_alpha) y.love_eyes.set_opacity(l_alpha) return y def update_tau(t): love = self.get_love2() cutoff_values = [ -5, -1.7, 1.7, 5 ] modes = [ "angry", "confused", "plain", "hooray", "hooray" ] if love < cutoff_values[0]: t.change(modes[0]) elif love >= cutoff_values[-1]: t.change(modes[-1]) else: i = 0 while cutoff_values[i] < love: i += 1 m1 = modes[i - 1] m2 = modes[i] t.change(m1) tau_copy.change(m2) for mob in t, tau_copy: mob.set_height(tau_height) mob.move_to(tau_bottom, DOWN) alpha = inverse_interpolate( cutoff_values[i - 1], cutoff_values[i], love, ) s_alpha = squish_rate_func(smooth, 0.25, 1)(alpha) if s_alpha > 0: t.align_data_and_family(tau_copy) f1 = t.family_members_with_points() f2 = tau_copy.family_members_with_points() for sm1, sm2 in zip(f1, f2): sm1.interpolate(sm1, sm2, s_alpha) # t.move_to( # tau_bottom + 0.025 * love * LEFT, DOWN, # ) t.look_at(you.eyes) if love < -4: t.look_at(RIGHT_SIDE) l_alpha = np.clip( inverse_interpolate(5, 5.5, love), 0, 1 ) t.eyes.set_opacity(1 - l_alpha) t.love_eyes.set_opacity(l_alpha) you.add_updater(update_you) tau.add_updater(update_tau) self.pi_creatures = VGroup() class ComparePhysicsToLove(Scene): def construct(self): ode = get_ode() ode.to_edge(UP) thetas = ode.get_parts_by_tex("theta") love = VGroup( get_love_equation1(), get_love_equation2(), ) love.scale(0.5) love.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) love.move_to(DOWN) hearts = VGroup(*filter( lambda sm: isinstance(sm, SuitSymbol), love.get_family() )) arrow = DoubleArrow(love.get_top(), ode.get_bottom()) self.play(FadeIn(ode, DOWN)) self.play(FadeIn(love, UP)) self.wait() self.play(LaggedStartMap( ShowCreationThenFadeAround, thetas, )) self.play(LaggedStartMap( ShowCreationThenFadeAround, hearts, )) self.wait() self.play(ShowCreation(arrow)) self.wait() class FramesComparingPhysicsToLove(Scene): CONFIG = { "camera_config": {"background_color": GREY_E} } def construct(self): ode = get_ode() ode.to_edge(UP) love = VGroup( get_love_equation1(), get_love_equation2(), ) love.scale(0.5) love.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) frames = VGroup(*[ ScreenRectangle( height=3.5, fill_color=BLACK, fill_opacity=1, stroke_width=0, ) for x in range(2) ]) frames.arrange(RIGHT, buff=LARGE_BUFF) frames.shift(DOWN) animated_frames = AnimatedBoundary(frames) ode.next_to(frames[0], UP) love.next_to(frames[1], UP) self.add(frames, animated_frames) self.add(ode, love) self.wait(15) class PassageOfTime(Scene): def construct(self): clock = Clock() clock[0].set_color(BLUE) clock.set_stroke(width=1) clock.scale(0.8) clock.to_corner(UL) passage = ClockPassesTime( clock, hours_passed=48, ) self.play(passage, run_time=10) class WriteODESolvingCode(ExternallyAnimatedScene): pass class InaccurateComputation(Scene): def construct(self): h_line = DashedLine(LEFT_SIDE, RIGHT_SIDE) h_line.to_edge(UP, buff=1.5) words = VGroup( OldTexText("Real number"), OldTexText("IEEE 754\\\\representation"), OldTexText("Error"), ) for i, word in zip([-1, 0, 1], words): word.next_to(h_line, UP) word.shift(i * FRAME_WIDTH * RIGHT / 3) lines = VGroup(*[ DashedLine(TOP, BOTTOM) for x in range(4) ]) lines.arrange(RIGHT) lines.stretch_to_fit_width(FRAME_WIDTH) self.add(h_line, lines[1:-1], words) numbers = VGroup( OldTex("\\pi").scale(2), OldTex("e^{\\sqrt{163}\\pi}").scale(1.5), ) numbers.set_color(YELLOW) numbers.set_stroke(width=0, background=True) bit_strings = VGroup( OldTex( "01000000", "01001001", "00001111", "11011011", ), OldTex( "01011100", "01101001", "00101110", "00011001", ) ) for mob in bit_strings: mob.arrange(DOWN, buff=SMALL_BUFF) for word in mob: for submob, bit in zip(word, word.get_tex()): if bit == "0": submob.set_color(GREY_B) errors = VGroup( OldTex( "\\approx 8.7422 \\times 10^{-8}" ), OldTex( "\\approx 5{,}289{,}803{,}032.00", ), ) errors.set_color(RED) content = VGroup(numbers, bit_strings, errors) for group, word in zip(content, words): group[1].shift(3 * DOWN) group.move_to(DOWN) group.match_x(word) self.play(*map(Write, numbers)) self.wait() self.play( TransformFromCopy(numbers, bit_strings), lag_ratio=0.01, run_time=2, ) self.wait() self.play(FadeIn(errors, 3 * LEFT)) self.wait() class NewSceneName(Scene): def construct(self): pass