file_path
stringclasses 1
value | content
stringlengths 0
219k
|
---|---|
from manim_imports_ext import *
Lg_formula_config = {
"tex_to_color_map": {
"\\theta_0": WHITE,
"{L}": BLUE,
"{g}": YELLOW,
},
}
class You(PiCreature):
CONFIG = {
"color": BLUE_C,
}
def get_ode():
tex_config = {
"tex_to_color_map": {
"{\\theta}": BLUE,
"{\\dot\\theta}": RED,
"{\\ddot\\theta}": YELLOW,
"{t}": WHITE,
"{\\mu}": WHITE,
}
}
ode = OldTex(
"{\\ddot\\theta}({t})", "=",
"-{\\mu} {\\dot\\theta}({t})",
"-{g \\over L} \\sin\\big({\\theta}({t})\\big)",
**tex_config,
)
return ode
def get_period_formula():
return OldTex(
"2\\pi", "\\sqrt{\\,", "L", "/", "g", "}",
tex_to_color_map={
"L": BLUE,
"g": YELLOW,
}
)
def pendulum_vector_field_func(point, mu=0.1, g=9.8, L=3):
theta, omega = point[:2]
return np.array([
omega,
-np.sqrt(g / L) * np.sin(theta) - mu * omega,
0,
])
def get_vector_symbol(*texs, **kwargs):
config = {
"include_background_rectangle": True,
"bracket_h_buff": SMALL_BUFF,
"bracket_v_buff": SMALL_BUFF,
"element_alignment_corner": ORIGIN,
}
config.update(kwargs)
array = [[tex] for tex in texs]
return Matrix(array, **config)
def get_heart_var(index):
heart = SuitSymbol("hearts")
if index == 1:
heart.set_color(BLUE_C)
elif index == 2:
heart.set_color(GREEN)
heart.set_height(0.7)
index = Integer(index)
index.move_to(heart.get_corner(DR))
heart.add(index)
return heart
def get_heart_var_deriv(index):
heart = get_heart_var(index)
filler_tex = "T"
deriv = OldTex("{d", filler_tex, "\\over", "dt}")
deriv.scale(2)
filler = deriv.get_part_by_tex(filler_tex)
heart.match_height(filler)
heart.move_to(filler)
heart.scale(1.5, about_edge=UL)
deriv.remove(filler)
deriv.add(heart)
deriv.heart = heart
return deriv
def get_love_equation1():
equation = VGroup(
get_heart_var_deriv(1),
OldTex("=").scale(2),
OldTex("a").scale(2),
get_heart_var(2)
)
equation.arrange(RIGHT)
equation[-1].shift(SMALL_BUFF * DL)
return equation
def get_love_equation2():
equation = VGroup(
get_heart_var_deriv(2),
OldTex("=").scale(2),
OldTex("-b").scale(2),
get_heart_var(1),
)
equation.arrange(RIGHT)
equation[-1].shift(SMALL_BUFF * DL)
return equation
|
|
from manim_imports_ext import *
from _2019.diffyq.part1.shared_constructs import *
from _2019.diffyq.part1.pendulum import Pendulum
# TODO: Arguably separate the part showing many
# configurations with the part showing just one.
class VisualizeStates(Scene):
CONFIG = {
"coordinate_plane_config": {
"y_line_frequency": PI / 2,
# "x_line_frequency": PI / 2,
"x_line_frequency": 1,
"y_axis_config": {
# "unit_size": 1.75,
"unit_size": 1,
},
"y_max": 4,
"faded_line_ratio": 4,
"background_line_style": {
"stroke_width": 1,
},
},
"little_pendulum_config": {
"length": 1,
"gravity": 4.9,
"weight_diameter": 0.3,
"include_theta_label": False,
"include_velocity_vector": True,
"angle_arc_config": {
"radius": 0.2,
},
"velocity_vector_config": {
"max_tip_length_to_length_ratio": 0.35,
"max_stroke_width_to_length_ratio": 6,
},
"velocity_vector_multiple": 0.25,
"max_velocity_vector_length_to_length_ratio": 0.8,
},
"big_pendulum_config": {
"length": 1.6,
"gravity": 4.9,
"damping": 0.2,
"weight_diameter": 0.3,
"include_velocity_vector": True,
"angle_arc_config": {
"radius": 0.5,
},
"initial_theta": 80 * DEGREES,
"omega": -1,
"set_theta_label_height_cap": True,
},
"n_thetas": 11,
"n_omegas": 7,
# "n_thetas": 5,
# "n_omegas": 3,
"initial_grid_wait_time": 15,
}
def construct(self):
self.initialize_plane()
simple = False
if simple:
self.add(self.plane)
else:
self.initialize_grid_of_states()
self.show_all_states_evolving()
self.show_grid_of_states_creation()
self.collapse_grid_into_points()
self.show_state_with_pair_of_numbers()
self.show_acceleration_dependence()
self.show_evolution_from_a_start_state()
def initialize_grid_of_states(self):
pendulums = VGroup()
rects = VGroup()
state_grid = VGroup()
thetas = self.get_initial_thetas()
omegas = self.get_initial_omegas()
for omega in omegas:
row = VGroup()
for theta in thetas:
rect = Rectangle(
height=3,
width=3,
stroke_color=WHITE,
stroke_width=2,
fill_color=GREY_E,
fill_opacity=1,
)
pendulum = Pendulum(
initial_theta=theta,
omega=omega,
top_point=rect.get_center(),
**self.little_pendulum_config,
)
pendulum.add_velocity_vector()
pendulums.add(pendulum)
rects.add(rect)
state = VGroup(rect, pendulum)
state.rect = rect
state.pendulum = pendulum
row.add(state)
row.arrange(RIGHT, buff=0)
state_grid.add(row)
state_grid.arrange(UP, buff=0)
state_grid.set_height(FRAME_HEIGHT)
state_grid.center()
state_grid.save_state(use_deepcopy=True)
self.state_grid = state_grid
self.pendulums = pendulums
def initialize_plane(self):
plane = self.plane = NumberPlane(
**self.coordinate_plane_config
)
plane.axis_labels = VGroup(
plane.get_x_axis_label(
"\\theta", RIGHT, UL, buff=SMALL_BUFF
),
plane.get_y_axis_label(
"\\dot \\theta", UP, DR, buff=SMALL_BUFF
).set_color(YELLOW),
)
for label in plane.axis_labels:
label.add_background_rectangle()
plane.add(plane.axis_labels)
plane.y_axis.add_numbers(direction=DL)
x_axis = plane.x_axis
label_texs = ["\\pi \\over 2", "\\pi", "3\\pi \\over 2", "\\tau"]
values = [PI / 2, PI, 3 * PI / 2, TAU]
x_axis.coordinate_labels = VGroup()
x_axis.add(x_axis.coordinate_labels)
for value, label_tex in zip(values, label_texs):
for u in [-1, 1]:
tex = label_tex
if u < 0:
tex = "-" + tex
label = OldTex(tex)
label.scale(0.5)
if label.get_height() > 0.4:
label.set_height(0.4)
point = x_axis.number_to_point(u * value)
label.next_to(point, DR, SMALL_BUFF)
x_axis.coordinate_labels.add(label)
return plane
def show_all_states_evolving(self):
state_grid = self.state_grid
pendulums = self.pendulums
for pendulum in pendulums:
pendulum.start_swinging()
self.add(state_grid)
self.wait(self.initial_grid_wait_time)
def show_grid_of_states_creation(self):
self.remove(self.state_grid)
self.initialize_grid_of_states() # Again
state_grid = self.state_grid
title = OldTexText("All states")
title.to_edge(UP, buff=MED_SMALL_BUFF)
self.all_states_title = title
state_grid.set_height(
FRAME_HEIGHT - title.get_height() - 2 * MED_SMALL_BUFF
)
state_grid.to_edge(DOWN, buff=0)
def place_at_top(state):
state.set_height(3)
state.center()
state.next_to(title, DOWN)
middle_row = state_grid[len(state_grid) // 2]
middle_row_copy = middle_row.deepcopy()
right_column_copy = VGroup(*[
row[-1] for row in state_grid
]).deepcopy()
for state in it.chain(middle_row_copy, right_column_copy):
place_at_top(state)
self.add(title)
self.play(
ShowIncreasingSubsets(middle_row),
ShowIncreasingSubsets(middle_row_copy),
run_time=2,
rate_func=linear,
)
self.wait()
self.play(
ShowIncreasingSubsets(state_grid),
ShowIncreasingSubsets(right_column_copy),
run_time=2,
rate_func=linear,
)
self.remove(middle_row_copy)
self.remove(middle_row)
self.add(state_grid)
self.remove(right_column_copy)
self.play(
ReplacementTransform(
right_column_copy[-1],
state_grid[-1][-1],
remover=True
)
)
self.wait()
def collapse_grid_into_points(self):
state_grid = self.state_grid
plane = self.plane
dots = VGroup()
for row in state_grid:
for state in row:
dot = Dot(
self.get_state_point(state.pendulum),
radius=0.05,
color=YELLOW,
background_stroke_width=3,
background_stroke_color=BLACK,
)
dot.state = state
dots.add(dot)
self.add(plane)
self.remove(state_grid)
flat_state_group = VGroup(*it.chain(*state_grid))
flat_dot_group = VGroup(*it.chain(*dots))
self.clear() # The nuclear option
self.play(
ShowCreation(plane),
FadeOut(self.all_states_title),
LaggedStart(*[
TransformFromCopy(m1, m2)
for m1, m2 in zip(flat_state_group, flat_dot_group)
], lag_ratio=0.1, run_time=4)
)
self.clear() # Again, not sure why I need this
self.add(plane, dots)
self.wait()
self.state_dots = dots
def show_state_with_pair_of_numbers(self):
axis_labels = self.plane.axis_labels
state = self.get_flexible_state_picture()
dot = self.get_state_controlling_dot(state)
h_line = always_redraw(
lambda: self.get_tracking_h_line(dot.get_center())
)
v_line = always_redraw(
lambda: self.get_tracking_v_line(dot.get_center())
)
self.add(dot)
anims = [GrowFromPoint(state, dot.get_center())]
if hasattr(self, "state_dots"):
anims.append(FadeOut(self.state_dots))
self.play(*anims)
for line, label in zip([h_line, v_line], axis_labels):
# self.add(line, dot)
self.play(
ShowCreation(line),
ShowCreationThenFadeAround(label),
run_time=1
)
for vect in LEFT, 3 * UP:
self.play(
ApplyMethod(
dot.shift, vect,
rate_func=there_and_back,
run_time=2,
)
)
self.wait()
for vect in 2 * LEFT, 3 * UP, 2 * RIGHT, 2 * DOWN:
self.play(dot.shift, vect, run_time=1.5)
self.wait()
self.state = state
self.state_dot = dot
self.h_line = h_line
self.v_line = v_line
def show_acceleration_dependence(self):
ode = get_ode()
thetas = ode.get_parts_by_tex("\\theta")
thetas[0].set_color(RED)
thetas[1].set_color(YELLOW)
ode.move_to(
FRAME_WIDTH * RIGHT / 4 +
FRAME_HEIGHT * UP / 4,
)
ode.add_background_rectangle_to_submobjects()
self.play(Write(ode))
self.wait()
self.play(FadeOut(ode))
def show_evolution_from_a_start_state(self):
state = self.state
dot = self.state_dot
self.play(
Rotating(
dot,
about_point=dot.get_center() + UR,
rate_func=smooth,
)
)
self.wait()
# Show initial trajectory
state.pendulum.clear_updaters(recurse=False)
self.tie_dot_position_to_state(dot, state)
state.pendulum.start_swinging()
trajectory = self.get_evolving_trajectory(dot)
self.add(trajectory)
for x in range(20):
self.wait()
# Talk through start
trajectory.suspend_updating()
state.pendulum.end_swinging()
dot.clear_updaters()
self.tie_state_to_dot_position(state, dot)
alphas = np.linspace(0, 0.1, 1000)
index = np.argmin([
trajectory.point_from_proportion(a)[1]
for a in alphas
])
alpha = alphas[index]
sub_traj = trajectory.copy()
sub_traj.suspend_updating()
sub_traj.pointwise_become_partial(trajectory, 0, alpha)
sub_traj.match_style(trajectory)
sub_traj.set_stroke(width=3)
self.wait()
self.play(dot.move_to, sub_traj.get_start())
self.wait()
self.play(
ShowCreation(sub_traj),
UpdateFromFunc(
dot, lambda d: d.move_to(sub_traj.get_end())
),
run_time=6,
)
self.wait()
# Comment on physical velocity vs. space position
v_vect = state.pendulum.velocity_vector
v_line_copy = self.v_line.copy()
v_line_copy.clear_updaters()
v_line_copy.set_stroke(PINK, 5)
td_label = self.plane.axis_labels[1]
y_axis_copy = self.plane.y_axis.copy()
y_axis_copy.submobjects = []
y_axis_copy.match_style(v_line_copy)
self.play(ShowCreationThenFadeAround(v_vect))
self.play(
ShowCreationThenFadeAround(td_label),
ShowCreationThenFadeOut(y_axis_copy)
)
self.play(ShowCreationThenFadeOut(v_line_copy))
self.wait()
# Abstract vs. physical
abstract = OldTexText("Abstract")
abstract.add_background_rectangle()
abstract.scale(2)
abstract.to_corner(UR)
physical = OldTexText("Physical")
physical.next_to(state.get_top(), DOWN)
self.play(
ApplyMethod(
self.plane.set_stroke, YELLOW, 0.5,
rate_func=there_and_back,
lag_ratio=0.2,
),
FadeInFromDown(abstract),
Animation(state),
)
self.wait()
self.play(FadeInFromDown(physical))
self.wait()
# Continue on spiral
sub_traj.resume_updating()
state.pendulum.clear_updaters(recurse=False)
state.pendulum.start_swinging()
dot.clear_updaters()
self.tie_dot_position_to_state(dot, state)
self.wait(20)
#
def get_initial_thetas(self):
angle = 3 * PI / 4
return np.linspace(-angle, angle, self.n_thetas)
def get_initial_omegas(self):
return np.linspace(-1.5, 1.5, self.n_omegas)
def get_state(self, pendulum):
return (pendulum.get_theta(), pendulum.get_omega())
def get_state_point(self, pendulum):
return self.plane.coords_to_point(
*self.get_state(pendulum)
)
def get_flexible_state_picture(self):
buff = MED_SMALL_BUFF
height = FRAME_HEIGHT / 2 - buff
rect = Square(
side_length=height,
stroke_color=WHITE,
stroke_width=2,
fill_color="#111111",
fill_opacity=1,
)
rect.to_corner(UL, buff=buff / 2)
pendulum = Pendulum(
top_point=rect.get_center(),
**self.big_pendulum_config
)
pendulum.fixed_point_tracker.add_updater(
lambda m: m.move_to(rect.get_center())
)
state = VGroup(rect, pendulum)
state.rect = rect
state.pendulum = pendulum
return state
def get_state_dot(self, state):
dot = Dot(color=PINK)
dot.move_to(self.get_state_point(state.pendulum))
return dot
def get_state_controlling_dot(self, state):
dot = self.get_state_dot(state)
self.tie_state_to_dot_position(state, dot)
return dot
def tie_state_to_dot_position(self, state, dot):
def update_pendulum(pend):
theta, omega = self.plane.point_to_coords(
dot.get_center()
)
pend.set_theta(theta)
pend.set_omega(omega)
return pend
state.pendulum.add_updater(update_pendulum)
state.pendulum.get_arc_angle_theta = \
lambda: self.plane.x_axis.point_to_number(dot.get_center())
return self
def tie_dot_position_to_state(self, dot, state):
dot.add_updater(lambda d: d.move_to(
self.get_state_point(state.pendulum)
))
return dot
def get_tracking_line(self, point, axis, color=WHITE):
number = axis.point_to_number(point)
axis_point = axis.number_to_point(number)
return DashedLine(
axis_point, point,
dash_length=0.025,
color=color,
)
def get_tracking_h_line(self, point):
return self.get_tracking_line(
point, self.plane.y_axis, WHITE,
)
def get_tracking_v_line(self, point):
return self.get_tracking_line(
point, self.plane.x_axis, YELLOW,
)
def get_evolving_trajectory(self, mobject):
trajectory = VMobject()
trajectory.start_new_path(mobject.get_center())
trajectory.set_stroke(RED, 1)
def update_trajectory(traj):
point = mobject.get_center()
if get_norm(trajectory.get_points()[-1] == point) > 0.05:
traj.add_smooth_curve_to(point)
trajectory.add_updater(update_trajectory)
return trajectory
class IntroduceVectorField(VisualizeStates):
CONFIG = {
"vector_field_config": {
"max_magnitude": 3,
# "delta_x": 2,
# "delta_y": 2,
},
"big_pendulum_config": {
"initial_theta": -80 * DEGREES,
"omega": 1,
}
}
def construct(self):
self.initialize_plane()
self.add_flexible_state()
self.initialize_vector_field()
self.add_equation()
self.preview_vector_field()
self.write_vector_derivative()
self.interpret_first_coordinate()
self.interpret_second_coordinate()
self.show_full_vector_field()
self.show_trajectory()
def initialize_plane(self):
super().initialize_plane()
self.add(self.plane)
def initialize_vector_field(self):
self.vector_field = VectorField(
self.vector_field_func,
**self.vector_field_config,
)
self.vector_field.sort(get_norm)
def add_flexible_state(self):
self.state = self.get_flexible_state_picture()
self.add(self.state)
def add_equation(self):
ode = get_ode()
ode.set_width(self.state.get_width() - MED_LARGE_BUFF)
ode.next_to(self.state.get_top(), DOWN, SMALL_BUFF)
thetas = ode.get_parts_by_tex("\\theta")
thetas[0].set_color(RED)
thetas[1].set_color(YELLOW)
ode_word = OldTexText("Differential equation")
ode_word.match_width(ode)
ode_word.next_to(ode, DOWN)
self.play(
FadeIn(ode, 0.5 * DOWN),
FadeIn(ode_word, 0.5 * UP),
)
self.ode = ode
self.ode_word = ode_word
def preview_vector_field(self):
vector_field = self.vector_field
growth = LaggedStartMap(
GrowArrow, vector_field,
run_time=3,
lag_ratio=0.01,
)
self.add(
growth.mobject,
vector_field,
self.state, self.ode, self.ode_word
)
self.play(growth)
self.wait()
self.play(FadeOut(vector_field))
self.remove(growth.mobject)
def write_vector_derivative(self):
state = self.state
plane = self.plane
dot = self.get_state_dot(state)
# Vector
vect = Arrow(
plane.coords_to_point(0, 0),
dot.get_center(),
buff=0,
color=dot.get_color()
)
vect_sym, d_vect_sym = [
self.get_vector_symbol(
"{" + a + "\\theta}(t)",
"{" + b + "\\theta}(t)",
)
for a, b in [("", "\\dot"), ("\\dot", "\\ddot")]
]
# vect_sym.get_entries()[1][0][1].set_color(YELLOW)
# d_vect_sym.get_entries()[0][0][1].set_color(YELLOW)
# d_vect_sym.get_entries()[1][0][1].set_color(RED)
vect_sym.next_to(vect.get_end(), UP, MED_LARGE_BUFF)
time_inputs = VGroup(*[
e[-1][-2] for e in vect_sym.get_entries()
])
# Derivative
ddt = OldTex("d \\over dt")
ddt.set_height(0.9 * vect_sym.get_height())
ddt.next_to(vect_sym, LEFT)
ddt.set_stroke(BLACK, 5, background=True)
equals = OldTex("=")
equals.add_background_rectangle()
equals.next_to(vect_sym, RIGHT, SMALL_BUFF)
d_vect_sym.next_to(equals, RIGHT, SMALL_BUFF)
# Little vector
angle_tracker = ValueTracker(0)
mag_tracker = ValueTracker(0.75)
d_vect = always_redraw(
lambda: Vector(
rotate_vector(
mag_tracker.get_value() * RIGHT,
angle_tracker.get_value(),
),
color=WHITE
).shift(dot.get_center()),
)
d_vect_magnitude_factor_tracker = ValueTracker(2)
real_d_vect = always_redraw(
lambda: self.vector_field.get_vector(
dot.get_center()
).scale(
d_vect_magnitude_factor_tracker.get_value(),
about_point=dot.get_center()
)
)
# Show vector
self.play(TransformFromCopy(state[1], vect))
self.play(FadeInFromDown(vect_sym))
self.wait()
self.play(ReplacementTransform(vect, dot))
self.wait()
self.play(LaggedStartMap(
ShowCreationThenFadeAround, time_inputs,
lag_ratio=0.1,
))
self.wait()
# Write Derivative
self.play(Write(ddt))
self.play(
plane.y_axis.numbers.fade, 1,
FadeIn(equals, LEFT),
TransformFromCopy(vect_sym, d_vect_sym)
)
self.wait()
# Show as little vector
equation_group = VGroup(
ddt, vect_sym, equals, d_vect_sym
)
self.play(
# equation_group.shift, 4 * DOWN,
equation_group.to_edge, RIGHT, LARGE_BUFF,
GrowArrow(d_vect),
)
self.wait()
self.play(angle_tracker.set_value, 120 * DEGREES)
self.play(mag_tracker.set_value, 1.5)
self.wait()
# Highlight new vector
self.play(
ShowCreationThenFadeAround(d_vect_sym),
FadeOut(d_vect)
)
self.wait()
self.play(
TransformFromCopy(d_vect_sym, real_d_vect),
dot.set_color, WHITE,
)
self.wait()
# Take a walk
trajectory = VMobject()
trajectory.start_new_path(dot.get_center())
dt = 0.01
for x in range(130):
p = trajectory.get_points()[-1]
dp_dt = self.vector_field_func(p)
trajectory.add_smooth_curve_to(p + dp_dt * dt)
self.tie_state_to_dot_position(state, dot)
self.play(
MoveAlongPath(dot, trajectory),
run_time=5,
rate_func=bezier([0, 0, 1, 1]),
)
self.state_dot = dot
self.d_vect = real_d_vect
self.equation_group = equation_group
self.d_vect_magnitude_factor_tracker = d_vect_magnitude_factor_tracker
def interpret_first_coordinate(self):
equation = self.equation_group
ddt, vect_sym, equals, d_vect_sym = equation
dot = self.state_dot
first_components_copy = VGroup(
vect_sym.get_entries()[0],
d_vect_sym.get_entries()[0],
).copy()
rect = SurroundingRectangle(first_components_copy)
rect.set_stroke(YELLOW, 2)
equation.save_state()
self.play(
ShowCreation(rect),
equation.fade, 0.5,
Animation(first_components_copy),
)
self.wait()
dot.save_state()
self.play(dot.shift, 2 * UP)
self.wait()
self.play(dot.shift, 6 * DOWN)
self.wait()
self.play(dot.restore)
self.wait()
self.play(
equation.restore,
FadeOut(rect),
)
self.remove(first_components_copy)
def interpret_second_coordinate(self):
equation = self.equation_group
ddt, vect_sym, equals, d_vect_sym = equation
second_components = VGroup(
vect_sym.get_entries()[1],
d_vect_sym.get_entries()[1],
)
rect = SurroundingRectangle(second_components)
rect.set_stroke(YELLOW, 2)
expanded_derivative = self.get_vector_symbol(
"{\\dot\\theta}(t)",
"-\\mu {\\dot\\theta}(t)" +
"-(g / L) \\sin\\big({\\theta}(t)\\big)",
)
expanded_derivative.move_to(d_vect_sym)
expanded_derivative.to_edge(RIGHT, MED_SMALL_BUFF)
equals2 = OldTex("=")
equals2.next_to(expanded_derivative, LEFT, SMALL_BUFF)
equation.save_state()
self.play(
ShowCreation(rect),
)
self.wait()
self.play(
FadeIn(expanded_derivative, LEFT),
FadeIn(equals2),
equation.next_to, equals2, LEFT, SMALL_BUFF,
MaintainPositionRelativeTo(rect, equation),
VFadeOut(rect),
)
self.wait()
self.full_equation = VGroup(
*equation, equals2, expanded_derivative,
)
def show_full_vector_field(self):
vector_field = self.vector_field
state = self.state
ode = self.ode
ode_word = self.ode_word
equation = self.full_equation
d_vect = self.d_vect
dot = self.state_dot
equation.generate_target()
equation.target.scale(0.7)
equation.target.to_edge(DOWN, LARGE_BUFF)
equation.target.to_edge(LEFT, MED_SMALL_BUFF)
equation_rect = BackgroundRectangle(equation.target)
growth = LaggedStartMap(
GrowArrow, vector_field,
run_time=3,
lag_ratio=0.01,
)
self.add(
growth.mobject,
state, ode, ode_word,
equation_rect, equation, dot,
d_vect,
)
self.play(
growth,
FadeIn(equation_rect),
MoveToTarget(equation),
self.d_vect_magnitude_factor_tracker.set_value, 1,
)
def show_trajectory(self):
state = self.state
dot = self.state_dot
state.pendulum.clear_updaters(recurse=False)
self.tie_dot_position_to_state(dot, state)
state.pendulum.start_swinging()
trajectory = self.get_evolving_trajectory(dot)
trajectory.set_stroke(WHITE, 3)
self.add(trajectory, dot)
self.wait(25)
#
def get_vector_symbol(self, tex1, tex2):
t2c = {
"{\\theta}": BLUE,
"{\\dot\\theta}": YELLOW,
"{\\omega}": YELLOW,
"{\\ddot\\theta}": RED,
}
return get_vector_symbol(
tex1, tex2,
element_to_mobject_config={
"tex_to_color_map": t2c,
}
).scale(0.9)
def vector_field_func(self, point):
x, y = self.plane.point_to_coords(point)
mu, g, L = [
self.big_pendulum_config.get(key)
for key in ["damping", "gravity", "length"]
]
return pendulum_vector_field_func(
x * RIGHT + y * UP,
mu=mu, g=g, L=L
)
def ask_about_change(self):
state = self.state
dot = self.get_state_dot(state)
d_vect = Vector(0.75 * RIGHT, color=WHITE)
d_vect.shift(dot.get_center())
q_mark = always_redraw(
lambda: OldTex("?").move_to(
d_vect.get_end() + 0.4 * rotate_vector(
d_vect.get_vector(), 90 * DEGREES,
),
)
)
self.play(TransformFromCopy(state[1], dot))
self.tie_state_to_dot_position(state, dot)
self.play(
GrowArrow(d_vect),
FadeInFromDown(q_mark)
)
for x in range(4):
angle = 90 * DEGREES
self.play(
Rotate(
d_vect, angle,
about_point=d_vect.get_start(),
)
)
self.play(
dot.shift,
0.3 * d_vect.get_vector(),
rate_func=there_and_back,
)
class ShowPendulumPhaseFlow(IntroduceVectorField):
CONFIG = {
"coordinate_plane_config": {
"x_axis_config": {
"unit_size": 0.8,
},
"x_max": 9,
"x_min": -9,
},
"flow_time": 20,
}
def construct(self):
self.initialize_plane()
self.initialize_vector_field()
plane = self.plane
field = self.vector_field
self.add(plane, field)
stream_lines = StreamLines(
field.func,
delta_x=0.3,
delta_y=0.3,
)
animated_stream_lines = AnimatedStreamLines(
stream_lines,
line_anim_class=ShowPassingFlashWithThinningStrokeWidth,
)
self.add(animated_stream_lines)
self.wait(self.flow_time)
class ShowHighVelocityCase(ShowPendulumPhaseFlow, MovingCameraScene):
CONFIG = {
"coordinate_plane_config": {
"x_max": 15,
"x_min": -15,
},
"vector_field_config": {
"x_max": 15,
},
"big_pendulum_config": {
"max_velocity_vector_length_to_length_ratio": 1,
},
"run_time": 25,
"initial_theta": 0,
"initial_theta_dot": 4,
"frame_shift_vect": TAU * RIGHT,
}
def setup(self):
MovingCameraScene.setup(self)
def construct(self):
self.initialize_plane_and_field()
self.add_flexible_state()
self.show_high_vector()
self.show_trajectory()
def initialize_plane_and_field(self):
self.initialize_plane()
self.add(self.plane)
self.initialize_vector_field()
self.add(self.vector_field)
def add_flexible_state(self):
super().add_flexible_state()
state = self.state
plane = self.plane
state.to_edge(DOWN, buff=SMALL_BUFF),
start_point = plane.coords_to_point(
self.initial_theta,
self.initial_theta_dot,
)
dot = self.get_state_controlling_dot(state)
dot.move_to(start_point)
state.update()
self.dot = dot
self.start_point = start_point
def show_high_vector(self):
field = self.vector_field
top_vectors = VGroup(*filter(
lambda a: np.all(a.get_center() > [-10, 1.5, -10]),
field
)).copy()
top_vectors.set_stroke(PINK, 3)
top_vectors.sort(lambda p: p[0])
self.play(
ShowCreationThenFadeOut(
top_vectors,
run_time=2,
lag_ratio=0.01,
)
)
def show_trajectory(self):
state = self.state
frame = self.camera_frame
dot = self.dot
start_point = self.start_point
traj = self.get_trajectory(start_point, self.run_time)
self.add(traj, dot)
anims = [
ShowCreation(
traj,
rate_func=linear,
),
UpdateFromFunc(
dot, lambda d: d.move_to(traj.get_points()[-1])
),
]
if get_norm(self.frame_shift_vect) > 0:
anims += [
ApplyMethod(
frame.shift, self.frame_shift_vect,
rate_func=squish_rate_func(
smooth, 0, 0.3,
)
),
MaintainPositionRelativeTo(state.rect, frame),
]
self.play(*anims, run_time=total_time)
def get_trajectory(self, start_point, time, dt=0.1, added_steps=100):
field = self.vector_field
traj = VMobject()
traj.start_new_path(start_point)
for x in range(int(time / dt)):
last_point = traj.get_points()[-1]
for y in range(added_steps):
dp_dt = field.func(last_point)
last_point += dp_dt * dt / added_steps
traj.add_smooth_curve_to(last_point)
traj.make_smooth()
traj.set_stroke(WHITE, 2)
return traj
class TweakMuInFormula(Scene):
def construct(self):
self.add(FullScreenFadeRectangle(
opacity=0.75,
))
ode = get_ode()
ode.to_edge(DOWN, buff=LARGE_BUFF)
mu = ode.get_part_by_tex("\\mu")
lil_rect = SurroundingRectangle(mu, buff=0.5 * SMALL_BUFF)
lil_rect.stretch(1.2, 1, about_edge=DOWN)
lil_rect.set_stroke(PINK, 2)
interval = UnitInterval()
interval.add_numbers(
*np.arange(0, 1.2, 0.2)
)
interval.next_to(ode, UP, LARGE_BUFF)
big_rect_seed = SurroundingRectangle(interval, buff=MED_SMALL_BUFF)
big_rect_seed.stretch(1.5, 1, about_edge=DOWN)
big_rect_seed.stretch(1.2, 0)
big_rect = VGroup(*[
DashedLine(v1, v2)
for v1, v2 in adjacent_pairs(big_rect_seed.get_vertices())
])
big_rect.set_stroke(PINK, 2)
arrow = Arrow(
lil_rect.get_top(),
big_rect_seed.point_from_proportion(0.65),
buff=SMALL_BUFF,
)
arrow.match_color(lil_rect)
mu_tracker = ValueTracker(0.1)
get_mu = mu_tracker.get_value
triangle = Triangle(
start_angle=-90 * DEGREES,
stroke_width=0,
fill_opacity=1,
fill_color=WHITE,
)
triangle.set_height(0.2)
triangle.add_updater(lambda t: t.next_to(
interval.number_to_point(get_mu()),
UP, buff=0,
))
equation = VGroup(
OldTex("\\mu = "),
DecimalNumber(),
)
equation.add_updater(
lambda e: e.arrange(RIGHT).next_to(
triangle, UP, SMALL_BUFF,
).shift(0.4 * RIGHT)
)
equation[-1].add_updater(
lambda d: d.set_value(get_mu()).shift(0.05 * UL)
)
self.add(ode)
self.play(ShowCreation(lil_rect))
self.play(
GrowFromPoint(interval, mu.get_center()),
GrowFromPoint(triangle, mu.get_center()),
GrowFromPoint(equation, mu.get_center()),
TransformFromCopy(lil_rect, big_rect),
ShowCreation(arrow)
)
self.wait()
self.play(mu_tracker.set_value, 0.9, run_time=5)
self.wait()
class TweakMuInVectorField(ShowPendulumPhaseFlow):
def construct(self):
self.initialize_plane()
plane = self.plane
self.add(plane)
mu_tracker = ValueTracker(0.1)
get_mu = mu_tracker.get_value
def vector_field_func(p):
x, y = plane.point_to_coords(p)
mu = get_mu()
g = self.big_pendulum_config.get("gravity")
L = self.big_pendulum_config.get("length")
return pendulum_vector_field_func(
x * RIGHT + y * UP,
mu=mu, g=g, L=L
)
def get_vector_field():
return VectorField(
vector_field_func,
**self.vector_field_config,
)
field = always_redraw(get_vector_field)
self.add(field)
self.play(
mu_tracker.set_value, 0.9,
run_time=5,
)
field.suspend_updating()
stream_lines = StreamLines(
field.func,
delta_x=0.3,
delta_y=0.3,
)
animated_stream_lines = AnimatedStreamLines(
stream_lines,
line_anim_class=ShowPassingFlashWithThinningStrokeWidth,
)
self.add(animated_stream_lines)
self.wait(self.flow_time)
class HighAmplitudePendulum(ShowHighVelocityCase):
CONFIG = {
"big_pendulum_config": {
"damping": 0.02,
},
"initial_theta": 175 * DEGREES,
"initial_theta_dot": 0,
"frame_shift_vect": 0 * RIGHT,
}
def construct(self):
self.initialize_plane_and_field()
self.add_flexible_state()
self.show_trajectory()
class SpectrumOfStartingStates(ShowHighVelocityCase):
CONFIG = {
"run_time": 15,
}
def construct(self):
self.initialize_plane_and_field()
self.vector_field.set_opacity(0.5)
self.show_many_trajectories()
def show_many_trajectories(self):
plane = self.plane
delta_x = 0.5
delta_y = 0.5
n = 20
start_points = [
plane.coords_to_point(x, y)
for x in np.linspace(PI - delta_x, PI + delta_x, n)
for y in np.linspace(-delta_y, delta_y, n)
]
start_points.sort(
key=lambda p: np.dot(p, UL)
)
time = self.run_time
# Count points
dots = VGroup(*[
Dot(sp, radius=0.025)
for sp in start_points
])
dots.set_color_by_gradient(PINK, BLUE, YELLOW)
words = OldTexText(
"Spectrum of\\\\", "initial conditions"
)
words.set_stroke(BLACK, 5, background=True)
words.next_to(dots, UP)
self.play(
# ShowIncreasingSubsets(dots, run_time=2),
LaggedStartMap(
FadeInFromLarge, dots,
lambda m: (m, 10),
run_time=2
),
FadeInFromDown(words),
)
self.wait()
trajs = VGroup()
for sp in start_points:
trajs.add(
self.get_trajectory(
sp, time,
added_steps=10,
)
)
for traj, dot in zip(trajs, dots):
traj.set_stroke(dot.get_color(), 1)
def update_dots(ds):
for d, t in zip(ds, trajs):
d.move_to(t.get_points()[-1])
return ds
dots.add_updater(update_dots)
self.add(dots, trajs, words)
self.play(
ShowCreation(
trajs,
lag_ratio=0,
),
rate_func=linear,
run_time=time,
)
self.wait()
class AskAboutStability(ShowHighVelocityCase):
CONFIG = {
"initial_theta": 60 * DEGREES,
"initial_theta_dot": 1,
}
def construct(self):
self.initialize_plane_and_field()
self.add_flexible_state()
self.show_fixed_points()
self.label_fixed_points()
self.ask_about_stability()
self.show_nudges()
def show_fixed_points(self):
state1 = self.state
plane = self.plane
dot1 = self.dot
state2 = self.get_flexible_state_picture()
state2.to_corner(DR, buff=SMALL_BUFF)
dot2 = self.get_state_controlling_dot(state2)
dot2.set_color(BLUE)
fp1 = plane.coords_to_point(0, 0)
fp2 = plane.coords_to_point(PI, 0)
self.play(
dot1.move_to, fp1,
run_time=3,
)
self.wait()
self.play(FadeIn(state2))
self.play(
dot2.move_to, fp2,
path_arc=-30 * DEGREES,
run_time=2,
)
self.wait()
self.state1 = state1
self.state2 = state2
self.dot1 = dot1
self.dot2 = dot2
def label_fixed_points(self):
dots = VGroup(self.dot1, self.dot2)
label = OldTexText("Fixed points")
label.scale(1.5)
label.set_stroke(BLACK, 5, background=True)
label.next_to(dots, UP, buff=2)
label.shift(SMALL_BUFF * DOWN)
arrows = VGroup(*[
Arrow(
label.get_bottom(), dot.get_center(),
color=dot.get_color(),
)
for dot in dots
])
self.play(
self.vector_field.set_opacity, 0.5,
FadeInFromDown(label)
)
self.play(ShowCreation(arrows))
self.wait(2)
self.to_fade = VGroup(label, arrows)
def ask_about_stability(self):
question = OldTexText("Stable?")
question.scale(2)
question.shift(FRAME_WIDTH * RIGHT / 4)
question.to_edge(UP)
question.set_stroke(BLACK, 5, background=True)
self.play(Write(question))
self.play(FadeOut(self.to_fade))
def show_nudges(self):
dots = VGroup(self.dot1, self.dot2)
time = 20
self.play(*[
ApplyMethod(
dot.shift, 0.1 * UL,
rate_func=rush_from,
)
for dot in dots
])
trajs = VGroup()
for dot in dots:
traj = self.get_trajectory(
dot.get_center(),
time,
)
traj.set_stroke(dot.get_color(), 2)
trajs.add(traj)
def update_dots(ds):
for t, d in zip(trajs, ds):
d.move_to(t.get_points()[-1])
dots.add_updater(update_dots)
self.add(trajs, dots)
self.play(
ShowCreation(trajs, lag_ratio=0),
rate_func=linear,
run_time=time
)
self.wait()
class LovePhaseSpace(ShowHighVelocityCase):
CONFIG = {
"vector_field_config": {
"max_magnitude": 4,
# "delta_x": 2,
# "delta_y": 2,
},
"a": 0.5,
"b": 0.3,
"mu": 0.2,
}
def construct(self):
self.setup_plane()
self.add_equations()
self.show_vector_field()
self.show_example_trajectories()
self.add_resistance_term()
self.show_new_trajectories()
def setup_plane(self):
plane = self.plane = NumberPlane()
plane.add_coordinates()
self.add(plane)
h1, h2 = hearts = VGroup(*[
get_heart_var(i)
for i in (1, 2)
])
hearts.scale(0.5)
hearts.set_stroke(BLACK, 5, background=True)
h1.next_to(plane.x_axis.get_right(), UL, SMALL_BUFF)
h2.next_to(plane.y_axis.get_top(), DR, SMALL_BUFF)
for h in hearts:
h.shift_onto_screen(buff=MED_SMALL_BUFF)
plane.add(hearts)
self.axis_hearts = hearts
def add_equations(self):
equations = VGroup(
get_love_equation1(),
get_love_equation2(),
)
equations.scale(0.5)
equations.arrange(
DOWN,
aligned_edge=LEFT,
buff=MED_LARGE_BUFF
)
equations.to_corner(UL)
equations.add_background_rectangle_to_submobjects()
# for eq in equations:
# eq.add_background_rectangle_to_submobjects()
self.add(equations)
self.equations = equations
def show_vector_field(self):
field = VectorField(
lambda p: np.array([
self.a * p[1], -self.b * p[0], 0
]),
**self.vector_field_config
)
field.sort(get_norm)
x_range = np.arange(-7, 7.5, 0.5)
y_range = np.arange(-4, 4.5, 0.5)
x_axis_arrows = VGroup(*[
field.get_vector([x, 0, 0])
for x in x_range
])
y_axis_arrows = VGroup(*[
field.get_vector([0, y, 0])
for y in y_range
])
axis_arrows = VGroup(*x_axis_arrows, *y_axis_arrows)
axis_arrows.save_state()
for arrow in axis_arrows:
real_len = get_norm(field.func(arrow.get_start()))
arrow.scale(
0.5 * real_len / arrow.get_length(),
about_point=arrow.get_start()
)
self.play(
LaggedStartMap(GrowArrow, x_axis_arrows),
)
self.play(
LaggedStartMap(GrowArrow, y_axis_arrows),
)
self.wait()
self.add(field, self.equations, self.axis_hearts)
self.play(
axis_arrows.restore,
# axis_arrows.fade, 1,
ShowCreation(field),
run_time=3
)
self.remove(axis_arrows)
self.wait()
self.field = self.vector_field = field
def show_example_trajectories(self):
n_points = 20
total_time = 30
start_points = self.start_points = [
2.5 * np.random.random() * rotate_vector(
RIGHT,
TAU * np.random.random()
)
for x in range(n_points)
]
dots = VGroup(*[Dot(sp) for sp in start_points])
dots.set_color_by_gradient(BLUE, WHITE)
words = OldTexText("Possible initial\\\\", "conditions")
words.scale(1.5)
words.add_background_rectangle_to_submobjects()
words.set_stroke(BLACK, 5, background=True)
words.shift(FRAME_WIDTH * RIGHT / 4)
words.to_edge(UP)
self.possibility_words = words
self.play(
LaggedStartMap(
FadeInFromLarge, dots,
lambda m: (m, 5)
),
FadeInFromDown(words)
)
trajs = VGroup(*[
self.get_trajectory(
sp, total_time,
added_steps=10,
)
for sp in start_points
])
trajs.set_color_by_gradient(BLUE, WHITE)
dots.trajs = trajs
def update_dots(ds):
for d, t in zip(ds, ds.trajs):
d.move_to(t.get_points()[-1])
dots.add_updater(update_dots)
self.add(trajs, dots)
self.play(
ShowCreation(
trajs,
lag_ratio=0,
run_time=10,
rate_func=linear,
)
)
self.trajs = trajs
self.dots = dots
def add_resistance_term(self):
added_term = VGroup(
OldTex("-\\mu"),
get_heart_var(2).scale(0.5),
)
added_term.arrange(RIGHT, buff=SMALL_BUFF)
equation2 = self.equations[1]
equation2.generate_target()
br, deriv, eq, neg_b, h1 = equation2.target
added_term.next_to(eq, RIGHT, SMALL_BUFF)
added_term.align_to(h1, DOWN)
VGroup(neg_b, h1).next_to(
added_term, RIGHT, SMALL_BUFF,
aligned_edge=DOWN,
)
br.stretch(1.2, 0, about_edge=LEFT)
brace = Brace(added_term, DOWN, buff=SMALL_BUFF)
words = brace.get_text(
"``Resistance'' term"
)
words.set_stroke(BLACK, 5, background=True)
words.add_background_rectangle()
self.add(equation2, added_term)
self.play(
MoveToTarget(equation2),
FadeInFromDown(added_term),
GrowFromCenter(brace),
Write(words),
)
self.play(ShowCreationThenFadeAround(added_term))
equation2.add(added_term, brace, words)
def show_new_trajectories(self):
dots = self.dots
trajs = self.trajs
field = self.field
new_field = VectorField(
lambda p: np.array([
self.a * p[1],
-self.mu * p[1] - self.b * p[0],
0
]),
**self.vector_field_config
)
new_field.sort(get_norm)
field.generate_target()
for vect in field.target:
vect.become(new_field.get_vector(vect.get_start()))
self.play(*map(
FadeOut,
[trajs, dots, self.possibility_words]
))
self.play(MoveToTarget(field))
self.vector_field = new_field
total_time = 30
new_trajs = VGroup(*[
self.get_trajectory(
sp, total_time,
added_steps=10,
)
for sp in self.start_points
])
new_trajs.set_color_by_gradient(BLUE, WHITE)
dots.trajs = new_trajs
self.add(new_trajs, dots)
self.play(
ShowCreation(
new_trajs,
lag_ratio=0,
run_time=10,
rate_func=linear,
),
)
self.wait()
class TakeManyTinySteps(IntroduceVectorField):
CONFIG = {
"initial_theta": 60 * DEGREES,
"initial_theta_dot": 0,
"initial_theta_tex": "\\pi / 3",
"initial_theta_dot_tex": "0",
}
def construct(self):
self.initialize_plane_and_field()
self.take_many_time_steps()
def initialize_plane_and_field(self):
self.initialize_plane()
self.initialize_vector_field()
field = self.vector_field
field.set_opacity(0.35)
self.add(self.plane, field)
def take_many_time_steps(self):
self.setup_trackers()
delta_t_tracker = self.delta_t_tracker
get_delta_t = delta_t_tracker.get_value
time_tracker = self.time_tracker
get_t = time_tracker.get_value
traj = always_redraw(
lambda: self.get_time_step_trajectory(
get_delta_t(),
get_t(),
self.initial_theta,
self.initial_theta_dot,
)
)
vectors = always_redraw(
lambda: self.get_path_vectors(
get_delta_t(),
get_t(),
self.initial_theta,
self.initial_theta_dot,
)
)
# Labels
labels, init_labels = self.get_labels(get_t, get_delta_t)
t_label, dt_label = labels
theta_t_label = OldTex("\\theta(t)...\\text{ish}")
theta_t_label.scale(0.75)
theta_t_label.add_updater(lambda m: m.next_to(
vectors[-1].get_end(),
vectors[-1].get_vector(),
SMALL_BUFF,
))
self.add(traj, vectors, init_labels, labels)
time_tracker.set_value(0)
target_time = 10
self.play(
VFadeIn(theta_t_label),
ApplyMethod(
time_tracker.set_value, target_time,
run_time=5,
rate_func=linear,
)
)
self.wait()
t_label[-1].clear_updaters()
self.remove(theta_t_label)
target_delta_t = 0.01
self.play(
delta_t_tracker.set_value, target_delta_t,
run_time=7,
)
self.wait()
traj.clear_updaters()
vectors.clear_updaters()
# Show steps
count_tracker = ValueTracker(0)
count = Integer()
count.scale(1.5)
count.to_edge(LEFT)
count.shift(UP + MED_SMALL_BUFF * UR)
count.add_updater(lambda c: c.set_value(
count_tracker.get_value()
))
count_label = OldTexText("steps")
count_label.scale(1.5)
count_label.add_updater(
lambda m: m.next_to(
count[-1], RIGHT,
submobject_to_align=m[0][0],
aligned_edge=DOWN
)
)
scaled_vectors = vectors.copy()
scaled_vectors.clear_updaters()
for vector in scaled_vectors:
vector.scale(
1 / vector.get_length(),
about_point=vector.get_start()
)
vector.set_color(YELLOW)
def update_scaled_vectors(group):
group.set_opacity(0)
group[min(
int(count.get_value()),
len(group) - 1,
)].set_opacity(1)
scaled_vectors.add_updater(update_scaled_vectors)
self.add(count, count_label, scaled_vectors)
self.play(
ApplyMethod(
count_tracker.set_value,
int(target_time / target_delta_t),
rate_func=linear,
),
run_time=5,
)
self.play(FadeOut(scaled_vectors))
self.wait()
def setup_trackers(self):
self.delta_t_tracker = ValueTracker(0.5)
self.time_tracker = ValueTracker(10)
def get_labels(self, get_t, get_delta_t):
t_label, dt_label = labels = VGroup(*[
VGroup(
OldTex("{} = ".format(s)),
DecimalNumber(0)
).arrange(RIGHT, aligned_edge=DOWN)
for s in ("t", "{\\Delta t}")
])
dt_label[-1].add_updater(
lambda d: d.set_value(get_delta_t())
)
t_label[-1].add_updater(
lambda d: d.set_value(
int(np.ceil(get_t() / get_delta_t())) * get_delta_t()
)
)
init_labels = VGroup(
OldTex(
"\\theta_0", "=", self.initial_theta_tex,
tex_to_color_map={"\\theta": BLUE},
),
OldTex(
"{\\dot\\theta}_0 =", self.initial_theta_dot_tex,
tex_to_color_map={"{\\dot\\theta}": YELLOW},
),
)
for group in labels, init_labels:
for label in group:
label.scale(1.25)
label.add_background_rectangle()
group.arrange(DOWN)
group.shift(FRAME_WIDTH * RIGHT / 4)
labels.to_edge(UP)
init_labels.shift(2 * DOWN)
return labels, init_labels
#
def get_time_step_points(self, delta_t, total_time, theta_0, theta_dot_0):
plane = self.plane
field = self.vector_field
curr_point = plane.coords_to_point(
theta_0,
theta_dot_0,
)
points = [curr_point]
t = 0
while t < total_time:
new_point = curr_point + field.func(curr_point) * delta_t
points.append(new_point)
curr_point = new_point
t += delta_t
return points
def get_time_step_trajectory(self, delta_t, total_time, theta_0, theta_dot_0):
traj = VMobject()
traj.set_points_as_corners(
self.get_time_step_points(
delta_t, total_time,
theta_0, theta_dot_0,
)
)
traj.set_stroke(WHITE, 2)
return traj
def get_path_vectors(self, delta_t, total_time, theta_0, theta_dot_0):
corners = self.get_time_step_points(
delta_t, total_time,
theta_0, theta_dot_0,
)
result = VGroup()
for a1, a2 in zip(corners, corners[1:]):
vector = Arrow(
a1, a2, buff=0,
)
vector.match_style(
self.vector_field.get_vector(a1)
)
result.add(vector)
return result
class SetupToTakingManyTinySteps(TakeManyTinySteps):
CONFIG = {
}
def construct(self):
self.initialize_plane_and_field()
self.show_step()
def show_step(self):
self.setup_trackers()
get_delta_t = self.delta_t_tracker.get_value
get_t = self.time_tracker.get_value
labels, init_labels = self.get_labels(get_t, get_delta_t)
t_label, dt_label = labels
dt_part = dt_label[1][0][:-1].copy()
init_labels_rect = SurroundingRectangle(init_labels)
init_labels_rect.set_color(PINK)
field = self.vector_field
point = self.plane.coords_to_point(
self.initial_theta,
self.initial_theta_dot,
)
dot = Dot(point, color=init_labels_rect.get_color())
vector_value = field.func(point)
vector = field.get_vector(point)
vector.scale(
get_norm(vector_value) / vector.get_length(),
about_point=vector.get_start()
)
scaled_vector = vector.copy()
scaled_vector.scale(
get_delta_t(),
about_point=scaled_vector.get_start()
)
v_label = OldTex("\\vec{\\textbf{v}}")
v_label.set_stroke(BLACK, 5, background=True)
v_label.next_to(vector, LEFT, SMALL_BUFF)
real_field = field.copy()
for v in real_field:
p = v.get_start()
v.scale(
get_norm(field.func(p)) / v.get_length(),
about_point=p
)
self.add(init_labels)
self.play(ShowCreation(init_labels_rect))
self.play(ReplacementTransform(
init_labels_rect,
dot,
))
self.wait()
self.add(vector, dot)
self.play(
ShowCreation(vector),
FadeIn(v_label, RIGHT),
)
self.play(FadeInFromDown(dt_label))
self.wait()
#
v_label.generate_target()
dt_part.generate_target()
dt_part.target.next_to(scaled_vector, LEFT, SMALL_BUFF)
v_label.target.next_to(dt_part.target, LEFT, SMALL_BUFF)
rect = BackgroundRectangle(
VGroup(v_label.target, dt_part.target)
)
self.add(rect, v_label, dt_part)
self.play(
ReplacementTransform(vector, scaled_vector),
FadeIn(rect),
MoveToTarget(v_label),
MoveToTarget(dt_part),
)
self.add(scaled_vector, dot)
self.wait()
self.play(
LaggedStart(*[
Transform(
sm1, sm2,
rate_func=there_and_back_with_pause,
)
for sm1, sm2 in zip(field, real_field)
], lag_ratio=0.001, run_time=3)
)
self.wait()
class ShowClutterPrevention(SetupToTakingManyTinySteps):
def construct(self):
self.initialize_plane_and_field()
# Copied from above scene
field = self.vector_field
real_field = field.copy()
for v in real_field:
p = v.get_start()
v.scale(
get_norm(field.func(p)) / v.get_length(),
about_point=p
)
self.play(
LaggedStart(*[
Transform(
sm1, sm2,
rate_func=there_and_back_with_pause,
)
for sm1, sm2 in zip(field, real_field)
], lag_ratio=0.001, run_time=3)
)
self.wait()
class ManyStepsFromDifferentStartingPoints(TakeManyTinySteps):
CONFIG = {
"initial_thetas": np.linspace(0.1, PI - 0.1, 10),
"initial_theta_dot": 0,
}
def construct(self):
self.initialize_plane_and_field()
self.take_many_time_steps()
def take_many_time_steps(self):
delta_t_tracker = ValueTracker(0.2)
get_delta_t = delta_t_tracker.get_value
time_tracker = ValueTracker(10)
get_t = time_tracker.get_value
# traj = always_redraw(
# lambda: VGroup(*[
# self.get_time_step_trajectory(
# get_delta_t(),
# get_t(),
# theta,
# self.initial_theta_dot,
# )
# for theta in self.initial_thetas
# ])
# )
vectors = always_redraw(
lambda: VGroup(*[
self.get_path_vectors(
get_delta_t(),
get_t(),
theta,
self.initial_theta_dot,
)
for theta in self.initial_thetas
])
)
self.add(vectors)
time_tracker.set_value(0)
self.play(
time_tracker.set_value, 5,
run_time=5,
rate_func=linear,
)
class Thumbnail(IntroduceVectorField):
CONFIG = {
"vector_field_config": {
# "delta_x": 0.5,
# "delta_y": 0.5,
# "max_magnitude": 5,
# "length_func": lambda norm: 0.5 * sigmoid(norm),
"delta_x": 1,
"delta_y": 1,
"max_magnitude": 5,
"length_func": lambda norm: 0.9 * sigmoid(norm),
},
"big_pendulum_config": {
"damping": 0.4,
},
}
def construct(self):
self.initialize_plane()
self.plane.axes.set_stroke(width=0.5)
self.initialize_vector_field()
field = self.vector_field
field.set_stroke(width=5)
for vector in field:
vector.set_stroke(width=8)
vector.tip.set_stroke(width=0)
vector.tip.scale(1.5, about_point=vector.get_last_point())
vector.set_opacity(1)
title = OldTexText("Differential\\\\", "equations")
title.space_out_submobjects(0.8)
# title.scale(3)
title.set_width(FRAME_WIDTH - 3)
# title.to_edge(UP)
# title[1].to_edge(DOWN)
subtitle = OldTexText("Studying the unsolvable")
subtitle.set_width(FRAME_WIDTH - 1)
subtitle.set_color(WHITE)
subtitle.to_edge(DOWN, buff=1)
# title.center()
title.to_edge(UP, buff=1)
title.add(subtitle)
# title.set_stroke(BLACK, 15, background=True)
# title.add_background_rectangle_to_submobjects(opacity=0.5)
title.set_stroke(BLACK, 15, background=True)
subtitle.set_stroke(RED, 2, background=True)
# for part in title:
# part[0].set_fill(opacity=0.25)
# part[0].set_stroke(width=0)
black_parts = VGroup()
for mob in title.family_members_with_points():
for sp in mob.get_subpaths():
new_mob = VMobject()
new_mob.set_points(sp)
new_mob.set_fill(BLACK, 0.25)
new_mob.set_stroke(width=0)
black_parts.add(new_mob)
# for vect in field:
# for mob in title.family_members_with_points():
# for p in [vect.get_start(), vect.get_end()]:
# x, y = p[:2]
# x0, y0 = mob.get_corner(DL)[:2]
# x1, y1 = mob.get_corner(UR)[:2]
# if x0 < x < x1 and y0 < y < y1:
# vect.set_opacity(0.25)
# vect.tip.set_stroke(width=0)
self.add(self.plane)
self.add(field)
# self.add(black_parts)
# self.add(title)
self.add_line(self.plane)
def add_line(self, axes):
func = self.vector_field_func
line = VMobject()
line.start_new_path(axes.c2p(-TAU, 3.5))
dt = 0.1
t = 0
total_time = 40
while t < total_time:
t += dt
last_point = line.get_last_point()
new_point = last_point + dt * func(last_point)
if new_point[0] > FRAME_WIDTH / 2:
new_point = last_point + FRAME_WIDTH * LEFT
line.start_new_path(new_point)
else:
line.add_smooth_curve_to(new_point)
line.set_stroke(WHITE, 6)
line.make_smooth()
self.add(line)
|
|
from manim_imports_ext import *
from _2019.diffyq.part1.shared_constructs import *
class Pendulum(VGroup):
CONFIG = {
"length": 3,
"gravity": 9.8,
"weight_diameter": 0.5,
"initial_theta": 0.3,
"omega": 0,
"damping": 0.1,
"top_point": 2 * UP,
"rod_style": {
"stroke_width": 3,
"stroke_color": GREY_B,
"sheen_direction": UP,
"sheen_factor": 1,
},
"weight_style": {
"stroke_width": 0,
"fill_opacity": 1,
"fill_color": GREY_BROWN,
"sheen_direction": UL,
"sheen_factor": 0.5,
"background_stroke_color": BLACK,
"background_stroke_width": 3,
"background_stroke_opacity": 0.5,
},
"dashed_line_config": {
"num_dashes": 25,
"stroke_color": WHITE,
"stroke_width": 2,
},
"angle_arc_config": {
"radius": 1,
"stroke_color": WHITE,
"stroke_width": 2,
},
"velocity_vector_config": {
"color": RED,
},
"theta_label_height": 0.25,
"set_theta_label_height_cap": False,
"n_steps_per_frame": 100,
"include_theta_label": True,
"include_velocity_vector": False,
"velocity_vector_multiple": 0.5,
"max_velocity_vector_length_to_length_ratio": 0.5,
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.create_fixed_point()
self.create_rod()
self.create_weight()
self.rotating_group = VGroup(self.rod, self.weight)
self.create_dashed_line()
self.create_angle_arc()
if self.include_theta_label:
self.add_theta_label()
if self.include_velocity_vector:
self.add_velocity_vector()
self.set_theta(self.initial_theta)
self.update()
def create_fixed_point(self):
self.fixed_point_tracker = VectorizedPoint(self.top_point)
self.add(self.fixed_point_tracker)
return self
def create_rod(self):
rod = self.rod = Line(UP, DOWN)
rod.set_height(self.length)
rod.set_style(**self.rod_style)
rod.move_to(self.get_fixed_point(), UP)
self.add(rod)
def create_weight(self):
weight = self.weight = Circle()
weight.set_width(self.weight_diameter)
weight.set_style(**self.weight_style)
weight.move_to(self.rod.get_end())
self.add(weight)
def create_dashed_line(self):
line = self.dashed_line = DashedLine(
self.get_fixed_point(),
self.get_fixed_point() + self.length * DOWN,
**self.dashed_line_config
)
line.add_updater(
lambda l: l.move_to(self.get_fixed_point(), UP)
)
self.add_to_back(line)
def create_angle_arc(self):
self.angle_arc = always_redraw(lambda: Arc(
arc_center=self.get_fixed_point(),
start_angle=-90 * DEGREES,
angle=self.get_arc_angle_theta(),
**self.angle_arc_config,
))
self.add(self.angle_arc)
def get_arc_angle_theta(self):
# Might be changed in certain scenes
return self.get_theta()
def add_velocity_vector(self):
def make_vector():
omega = self.get_omega()
theta = self.get_theta()
mvlr = self.max_velocity_vector_length_to_length_ratio
max_len = mvlr * self.rod.get_length()
vvm = self.velocity_vector_multiple
multiple = np.clip(
vvm * omega, -max_len, max_len
)
vector = Vector(
multiple * RIGHT,
**self.velocity_vector_config,
)
vector.rotate(theta, about_point=ORIGIN)
vector.shift(self.rod.get_end())
return vector
self.velocity_vector = always_redraw(make_vector)
self.add(self.velocity_vector)
return self
def add_theta_label(self):
self.theta_label = always_redraw(self.get_label)
self.add(self.theta_label)
def get_label(self):
label = OldTex("\\theta")
label.set_height(self.theta_label_height)
if self.set_theta_label_height_cap:
max_height = self.angle_arc.get_width()
if label.get_height() > max_height:
label.set_height(max_height)
top = self.get_fixed_point()
arc_center = self.angle_arc.point_from_proportion(0.5)
vect = arc_center - top
norm = get_norm(vect)
vect = normalize(vect) * (norm + self.theta_label_height)
label.move_to(top + vect)
return label
#
def get_theta(self):
theta = self.rod.get_angle() - self.dashed_line.get_angle()
theta = (theta + PI) % TAU - PI
return theta
def set_theta(self, theta):
self.rotating_group.rotate(
theta - self.get_theta()
)
self.rotating_group.shift(
self.get_fixed_point() - self.rod.get_start(),
)
return self
def get_omega(self):
return self.omega
def set_omega(self, omega):
self.omega = omega
return self
def get_fixed_point(self):
return self.fixed_point_tracker.get_location()
#
def start_swinging(self):
self.add_updater(Pendulum.update_by_gravity)
def end_swinging(self):
self.remove_updater(Pendulum.update_by_gravity)
def update_by_gravity(self, dt):
theta = self.get_theta()
omega = self.get_omega()
nspf = self.n_steps_per_frame
for x in range(nspf):
d_theta = omega * dt / nspf
d_omega = op.add(
-self.damping * omega,
-(self.gravity / self.length) * np.sin(theta),
) * dt / nspf
theta += d_theta
omega += d_omega
self.set_theta(theta)
self.set_omega(omega)
return self
class GravityVector(Vector):
CONFIG = {
"color": YELLOW,
"length_multiple": 1 / 9.8,
# TODO, continually update the length based
# on the pendulum's gravity?
}
def __init__(self, pendulum, **kwargs):
super().__init__(DOWN, **kwargs)
self.pendulum = pendulum
self.scale(self.length_multiple * pendulum.gravity)
self.attach_to_pendulum(pendulum)
def attach_to_pendulum(self, pendulum):
self.add_updater(lambda m: m.shift(
pendulum.weight.get_center() - self.get_start(),
))
def add_component_lines(self):
self.component_lines = always_redraw(self.create_component_lines)
self.add(self.component_lines)
def create_component_lines(self):
theta = self.pendulum.get_theta()
x_new = rotate(RIGHT, theta)
base = self.get_start()
tip = self.get_end()
vect = tip - base
corner = base + x_new * np.dot(vect, x_new)
kw = {"dash_length": 0.025}
return VGroup(
DashedLine(base, corner, **kw),
DashedLine(corner, tip, **kw),
)
class ThetaValueDisplay(VGroup):
CONFIG = {
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
class ThetaVsTAxes(Axes):
CONFIG = {
"x_min": 0,
"x_max": 8,
"y_min": -PI / 2,
"y_max": PI / 2,
"y_axis_config": {
"tick_frequency": PI / 8,
"unit_size": 1.5,
},
"axis_config": {
"color": "#EEEEEE",
"stroke_width": 2,
"include_tip": False,
},
"graph_style": {
"stroke_color": GREEN,
"stroke_width": 3,
"fill_opacity": 0,
},
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_labels()
def add_axes(self):
self.axes = Axes(**self.axes_config)
self.add(self.axes)
def add_labels(self):
x_axis = self.get_x_axis()
y_axis = self.get_y_axis()
t_label = self.t_label = OldTex("t")
t_label.next_to(x_axis.get_right(), UP, MED_SMALL_BUFF)
x_axis.label = t_label
x_axis.add(t_label)
theta_label = self.theta_label = OldTex("\\theta(t)")
theta_label.next_to(y_axis.get_top(), UP, SMALL_BUFF)
y_axis.label = theta_label
y_axis.add(theta_label)
self.y_axis_label = theta_label
self.x_axis_label = t_label
x_axis.add_numbers()
y_axis.add(self.get_y_axis_coordinates(y_axis))
def get_y_axis_coordinates(self, y_axis):
texs = [
# "\\pi \\over 4",
# "\\pi \\over 2",
# "3 \\pi \\over 4",
# "\\pi",
"\\pi / 4",
"\\pi / 2",
"3 \\pi / 4",
"\\pi",
]
values = np.arange(1, 5) * PI / 4
labels = VGroup()
for pos_tex, pos_value in zip(texs, values):
neg_tex = "-" + pos_tex
neg_value = -1 * pos_value
for tex, value in (pos_tex, pos_value), (neg_tex, neg_value):
if value > self.y_max or value < self.y_min:
continue
symbol = OldTex(tex)
symbol.scale(0.5)
point = y_axis.number_to_point(value)
symbol.next_to(point, LEFT, MED_SMALL_BUFF)
labels.add(symbol)
return labels
def get_live_drawn_graph(self, pendulum,
t_max=None,
t_step=1.0 / 60,
**style):
style = merge_dicts_recursively(self.graph_style, style)
if t_max is None:
t_max = self.x_max
graph = VMobject()
graph.set_style(**style)
graph.all_coords = [(0, pendulum.get_theta())]
graph.time = 0
graph.time_of_last_addition = 0
def update_graph(graph, dt):
graph.time += dt
if graph.time > t_max:
graph.remove_updater(update_graph)
return
new_coords = (graph.time, pendulum.get_theta())
if graph.time - graph.time_of_last_addition >= t_step:
graph.all_coords.append(new_coords)
graph.time_of_last_addition = graph.time
points = [
self.coords_to_point(*coords)
for coords in [*graph.all_coords, new_coords]
]
graph.set_points_smoothly(points)
graph.add_updater(update_graph)
return graph
# Scenes
class IntroducePendulum(PiCreatureScene, MovingCameraScene):
CONFIG = {
"pendulum_config": {
"length": 3,
"top_point": 4 * RIGHT,
"weight_diameter": 0.35,
"gravity": 20,
},
"theta_vs_t_axes_config": {
"y_max": PI / 4,
"y_min": -PI / 4,
"y_axis_config": {
"tick_frequency": PI / 16,
"unit_size": 2,
"tip_length": 0.3,
},
"x_max": 12,
"axis_config": {
"stroke_width": 2,
}
},
}
def setup(self):
MovingCameraScene.setup(self)
PiCreatureScene.setup(self)
def construct(self):
self.add_pendulum()
# self.label_pi_creatures()
self.label_pendulum()
self.add_graph()
self.label_function()
self.show_graph_period()
self.show_length_and_gravity()
# self.tweak_length_and_gravity()
def create_pi_creatures(self):
randy = Randolph(color=BLUE_C)
morty = Mortimer(color=MAROON_E)
creatures = VGroup(randy, morty)
creatures.scale(0.5)
creatures.arrange(RIGHT, buff=2.5)
creatures.to_corner(DR)
return creatures
def add_pendulum(self):
pendulum = self.pendulum = Pendulum(**self.pendulum_config)
pendulum.start_swinging()
frame = self.camera_frame
frame.save_state()
frame.scale(0.5)
frame.move_to(pendulum.dashed_line)
self.add(pendulum, frame)
def label_pi_creatures(self):
randy, morty = self.pi_creatures
randy_label = OldTexText("Physics\\\\", "student")
morty_label = OldTexText("Physics\\\\", "teacher")
labels = VGroup(randy_label, morty_label)
labels.scale(0.5)
randy_label.next_to(randy, UP, LARGE_BUFF)
morty_label.next_to(morty, UP, LARGE_BUFF)
for label, pi in zip(labels, self.pi_creatures):
label.arrow = Arrow(
label.get_bottom(), pi.eyes.get_top()
)
label.arrow.set_color(WHITE)
label.arrow.set_stroke(width=5)
morty.labels = VGroup(
morty_label,
morty_label.arrow,
)
self.play(
FadeInFromDown(randy_label),
GrowArrow(randy_label.arrow),
randy.change, "hooray",
)
self.play(
Animation(self.pendulum.fixed_point_tracker),
TransformFromCopy(randy_label[0], morty_label[0]),
FadeIn(morty_label[1]),
GrowArrow(morty_label.arrow),
morty.change, "raise_right_hand",
)
self.wait(2)
def label_pendulum(self):
pendulum = self.pendulum
randy, morty = self.pi_creatures
label = pendulum.theta_label
rect = SurroundingRectangle(label, buff=0.5 * SMALL_BUFF)
rect.add_updater(lambda r: r.move_to(label))
for pi in randy, morty:
pi.add_updater(
lambda m: m.look_at(pendulum.weight)
)
self.play(randy.change, "pondering")
self.play(morty.change, "pondering")
self.wait(3)
randy.clear_updaters()
morty.clear_updaters()
self.play(
ShowCreationThenFadeOut(rect),
)
self.wait()
def add_graph(self):
axes = self.axes = ThetaVsTAxes(**self.theta_vs_t_axes_config)
axes.y_axis.label.next_to(axes.y_axis, UP, buff=0)
axes.to_corner(UL)
self.play(
Restore(
self.camera_frame,
rate_func=squish_rate_func(smooth, 0, 0.9),
),
DrawBorderThenFill(
axes,
rate_func=squish_rate_func(smooth, 0.5, 1),
lag_ratio=0.9,
),
Transform(
self.pendulum.theta_label.copy().clear_updaters(),
axes.y_axis.label.copy(),
remover=True,
rate_func=squish_rate_func(smooth, 0, 0.8),
),
run_time=3,
)
self.wait(1.5)
self.graph = axes.get_live_drawn_graph(self.pendulum)
self.add(self.graph)
def label_function(self):
hm_word = OldTexText("Simple harmonic motion")
hm_word.scale(1.25)
hm_word.to_edge(UP)
formula = OldTex(
"=\\theta_0 \\cos(\\sqrt{g / L} t)"
)
formula.next_to(
self.axes.y_axis_label, RIGHT, SMALL_BUFF
)
formula.set_stroke(width=0, background=True)
self.play(FadeIn(hm_word, DOWN))
self.wait()
self.play(
Write(formula),
hm_word.to_corner, UR
)
self.wait(4)
def show_graph_period(self):
pendulum = self.pendulum
axes = self.axes
period = self.period = TAU * np.sqrt(
pendulum.length / pendulum.gravity
)
amplitude = pendulum.initial_theta
line = Line(
axes.coords_to_point(0, amplitude),
axes.coords_to_point(period, amplitude),
)
line.shift(SMALL_BUFF * RIGHT)
brace = Brace(line, UP, buff=SMALL_BUFF)
brace.add_to_back(brace.copy().set_style(BLACK, 10))
formula = get_period_formula()
formula.next_to(brace, UP, SMALL_BUFF)
self.period_formula = formula
self.period_brace = brace
self.play(
GrowFromCenter(brace),
FadeInFromDown(formula),
)
self.wait(2)
def show_length_and_gravity(self):
formula = self.period_formula
L = formula.get_part_by_tex("L")
g = formula.get_part_by_tex("g")
rod = self.pendulum.rod
new_rod = rod.copy()
new_rod.set_stroke(BLUE, 7)
new_rod.add_updater(lambda r: r.put_start_and_end_on(
*rod.get_start_and_end()
))
g_vect = GravityVector(
self.pendulum,
length_multiple=0.5 / 9.8,
)
down_vectors = self.get_down_vectors()
down_vectors.set_color(YELLOW)
down_vectors.set_opacity(0.5)
self.play(
ShowCreationThenDestructionAround(L),
ShowCreation(new_rod),
)
self.play(FadeOut(new_rod))
self.play(
ShowCreationThenDestructionAround(g),
GrowArrow(g_vect),
)
self.play(self.get_down_vectors_animation(down_vectors))
self.wait(6)
self.gravity_vector = g_vect
def tweak_length_and_gravity(self):
pendulum = self.pendulum
axes = self.axes
graph = self.graph
brace = self.period_brace
formula = self.period_formula
g_vect = self.gravity_vector
randy, morty = self.pi_creatures
graph.clear_updaters()
period2 = self.period * np.sqrt(2)
period3 = self.period / np.sqrt(2)
amplitude = pendulum.initial_theta
graph2, graph3 = [
axes.get_graph(
lambda t: amplitude * np.cos(TAU * t / p),
color=RED,
)
for p in (period2, period3)
]
formula.add_updater(lambda m: m.next_to(
brace, UP, SMALL_BUFF
))
new_pendulum_config = dict(self.pendulum_config)
new_pendulum_config["length"] *= 2
new_pendulum_config["top_point"] += 3.5 * UP
# new_pendulum_config["initial_theta"] = pendulum.get_theta()
new_pendulum = Pendulum(**new_pendulum_config)
down_vectors = self.get_down_vectors()
self.play(randy.change, "happy")
self.play(
ReplacementTransform(pendulum, new_pendulum),
morty.change, "horrified",
morty.shift, 3 * RIGHT,
morty.labels.shift, 3 * RIGHT,
)
self.remove(morty, morty.labels)
g_vect.attach_to_pendulum(new_pendulum)
new_pendulum.start_swinging()
self.play(
ReplacementTransform(graph, graph2),
brace.stretch, np.sqrt(2), 0, {"about_edge": LEFT},
)
self.add(g_vect)
self.wait(3)
new_pendulum.gravity *= 4
g_vect.scale(2)
self.play(
FadeOut(graph2),
self.get_down_vectors_animation(down_vectors)
)
self.play(
FadeIn(graph3),
brace.stretch, 0.5, 0, {"about_edge": LEFT},
)
self.wait(6)
#
def get_down_vectors(self):
down_vectors = VGroup(*[
Vector(0.5 * DOWN)
for x in range(10 * 150)
])
down_vectors.arrange_in_grid(10, 150, buff=MED_SMALL_BUFF)
down_vectors.set_color_by_gradient(BLUE, RED)
# for vect in down_vectors:
# vect.shift(0.1 * np.random.random(3))
down_vectors.to_edge(RIGHT)
return down_vectors
def get_down_vectors_animation(self, down_vectors):
return LaggedStart(
*[
GrowArrow(v, rate_func=there_and_back)
for v in down_vectors
],
lag_ratio=0.0005,
run_time=2,
remover=True
)
class MultiplePendulumsOverlayed(Scene):
CONFIG = {
"initial_thetas": [
150 * DEGREES,
90 * DEGREES,
60 * DEGREES,
30 * DEGREES,
10 * DEGREES,
],
"weight_colors": [
PINK, RED, GREEN, BLUE, GREY,
],
"pendulum_config": {
"top_point": ORIGIN,
"length": 3,
},
}
def construct(self):
pendulums = VGroup(*[
Pendulum(
initial_theta=theta,
weight_style={
"fill_color": wc,
"fill_opacity": 0.5,
},
**self.pendulum_config,
)
for theta, wc in zip(
self.initial_thetas,
self.weight_colors,
)
])
for pendulum in pendulums:
pendulum.start_swinging()
pendulum.remove(pendulum.theta_label)
randy = Randolph(color=BLUE_C)
randy.to_corner(DL)
randy.add_updater(lambda r: r.look_at(pendulums[0].weight))
axes = ThetaVsTAxes(
x_max=20,
y_axis_config={
"unit_size": 0.5,
"tip_length": 0.3,
},
)
axes.to_corner(UL)
graphs = VGroup(*[
axes.get_live_drawn_graph(
pendulum,
stroke_color=pendulum.weight.get_color(),
stroke_width=1,
)
for pendulum in pendulums
])
self.add(pendulums)
self.add(axes, *graphs)
self.play(randy.change, "sassy")
self.wait(2)
self.play(Blink(randy))
self.wait(5)
self.play(randy.change, "angry")
self.play(Blink(randy))
self.wait(10)
class LowAnglePendulum(Scene):
CONFIG = {
"pendulum_config": {
"initial_theta": 20 * DEGREES,
"length": 2.0,
"damping": 0,
"top_point": ORIGIN,
},
"axes_config": {
"y_axis_config": {"unit_size": 0.75},
"x_axis_config": {
"unit_size": 0.5,
"numbers_to_show": range(2, 25, 2),
"number_scale_val": 0.5,
},
"x_max": 25,
"axis_config": {
"tip_length": 0.3,
"stroke_width": 2,
}
},
"axes_corner": UL,
}
def construct(self):
pendulum = Pendulum(**self.pendulum_config)
axes = ThetaVsTAxes(**self.axes_config)
axes.center()
axes.to_corner(self.axes_corner, buff=LARGE_BUFF)
graph = axes.get_live_drawn_graph(pendulum)
L = pendulum.length
g = pendulum.gravity
theta0 = pendulum.initial_theta
prediction = axes.get_graph(
lambda t: theta0 * np.cos(t * np.sqrt(g / L))
)
dashed_prediction = DashedVMobject(prediction, num_dashes=300)
dashed_prediction.set_stroke(WHITE, 1)
prediction_formula = OldTex(
"\\theta_0", "\\cos(\\sqrt{g / L} \\cdot t)"
)
prediction_formula.scale(0.75)
prediction_formula.next_to(
dashed_prediction, UP, SMALL_BUFF,
)
theta0 = prediction_formula.get_part_by_tex("\\theta_0")
theta0_brace = Brace(theta0, UP, buff=SMALL_BUFF)
theta0_brace.stretch(0.5, 1, about_edge=DOWN)
theta0_label = Integer(
pendulum.initial_theta * 180 / PI,
unit="^\\circ"
)
theta0_label.scale(0.75)
theta0_label.next_to(theta0_brace, UP, SMALL_BUFF)
group = VGroup(theta0_brace, theta0_label, prediction_formula)
group.shift_onto_screen(buff=MED_SMALL_BUFF)
self.add(axes, dashed_prediction, pendulum)
self.play(
ShowCreation(dashed_prediction, run_time=2),
FadeInFromDown(prediction_formula),
FadeInFromDown(theta0_brace),
FadeInFromDown(theta0_label),
)
self.play(
ShowCreationThenFadeAround(theta0_label),
ShowCreationThenFadeAround(pendulum.theta_label),
)
self.wait()
pendulum.start_swinging()
self.add(graph)
self.wait(30)
class ApproxWordsLowAnglePendulum(Scene):
def construct(self):
period = OldTex(
"\\text{Period}", "\\approx",
"2\\pi \\sqrt{\\,{L} / {g}}",
**Lg_formula_config
)
checkmark = OldTex("\\checkmark")
checkmark.set_color(GREEN)
checkmark.scale(2)
checkmark.next_to(period, RIGHT, MED_LARGE_BUFF)
self.add(period, checkmark)
class MediumAnglePendulum(LowAnglePendulum):
CONFIG = {
"pendulum_config": {
"initial_theta": 50 * DEGREES,
"n_steps_per_frame": 1000,
},
"axes_config": {
"y_axis_config": {"unit_size": 0.75},
"y_max": PI / 2,
"y_min": -PI / 2,
"axis_config": {
"tip_length": 0.3,
"stroke_width": 2,
}
},
"pendulum_shift_vect": 1 * RIGHT,
}
class MediumHighAnglePendulum(MediumAnglePendulum):
CONFIG = {
"pendulum_config": {
"initial_theta": 90 * DEGREES,
"n_steps_per_frame": 1000,
},
}
class HighAnglePendulum(LowAnglePendulum):
CONFIG = {
"pendulum_config": {
"initial_theta": 175 * DEGREES,
"n_steps_per_frame": 1000,
"top_point": 1.5 * DOWN,
"length": 2,
},
"axes_config": {
"y_axis_config": {"unit_size": 0.5},
"y_max": PI,
"y_min": -PI,
"axis_config": {
"tip_length": 0.3,
"stroke_width": 2,
}
},
"pendulum_shift_vect": 1 * RIGHT,
}
class VeryLowAnglePendulum(LowAnglePendulum):
CONFIG = {
"pendulum_config": {
"initial_theta": 10 * DEGREES,
"n_steps_per_frame": 1000,
"top_point": ORIGIN,
"length": 3,
},
"axes_config": {
"y_axis_config": {"unit_size": 2},
"y_max": PI / 4,
"y_min": -PI / 4,
"axis_config": {
"tip_length": 0.3,
"stroke_width": 2,
}
},
"pendulum_shift_vect": 1 * RIGHT,
}
class WherePendulumLeads(PiCreatureScene):
def construct(self):
pendulum = Pendulum(
top_point=UP,
length=3,
gravity=20,
)
pendulum.start_swinging()
l_title = OldTexText("Linearization")
l_title.scale(1.5)
l_title.to_corner(UL)
c_title = OldTexText("Chaos")
c_title.scale(1.5)
c_title.move_to(l_title)
c_title.move_to(
c_title.get_center() * np.array([-1, 1, 1])
)
get_theta = pendulum.get_theta
spring = always_redraw(
lambda: ParametricCurve(
lambda t: np.array([
np.cos(TAU * t) + (1.4 + get_theta()) * t,
np.sin(TAU * t) - 0.5,
0,
]),
t_min=-0.5,
t_max=7,
color=GREY,
sheen_factor=1,
sheen_direction=UL,
).scale(0.2).to_edge(LEFT, buff=0)
)
spring_rect = SurroundingRectangle(
spring, buff=MED_LARGE_BUFF,
stroke_width=0,
fill_color=BLACK,
fill_opacity=0,
)
weight = Dot(radius=0.25)
weight.add_updater(lambda m: m.move_to(
spring.get_points()[-1]
))
weight.set_color(BLUE)
weight.set_sheen(1, UL)
spring_system = VGroup(spring, weight)
linear_formula = OldTex(
"\\frac{d \\vec{\\textbf{x}}}{dt}="
"A\\vec{\\textbf{x}}"
)
linear_formula.next_to(spring, UP, LARGE_BUFF)
linear_formula.match_x(l_title)
randy = self.pi_creature
randy.set_height(2)
randy.center()
randy.to_edge(DOWN)
randy.shift(3 * LEFT)
q_marks = OldTex("???")
q_marks.next_to(randy, UP)
self.add(pendulum, randy)
self.play(
randy.change, "pondering", pendulum,
FadeInFromDown(q_marks, lag_ratio=0.3)
)
self.play(randy.look_at, pendulum)
self.wait(5)
self.play(
Animation(VectorizedPoint(pendulum.get_top())),
FadeOut(q_marks, UP, lag_ratio=0.3),
)
self.add(spring_system)
self.play(
FadeOut(spring_rect),
FadeIn(linear_formula, UP),
FadeInFromDown(l_title),
)
self.play(FadeInFromDown(c_title))
self.wait(8)
class LongDoublePendulum(ExternallyAnimatedScene):
pass
class AnalyzePendulumForce(MovingCameraScene):
CONFIG = {
"pendulum_config": {
"length": 5,
"top_point": 3.5 * UP,
"initial_theta": 60 * DEGREES,
"set_theta_label_height_cap": True,
},
"g_vect_config": {
"length_multiple": 0.25,
},
"tan_line_color": BLUE,
"perp_line_color": PINK,
}
def construct(self):
self.add_pendulum()
self.show_arc_length()
self.add_g_vect()
self.show_constraint()
self.break_g_vect_into_components()
self.show_angle_geometry()
self.show_gsin_formula()
self.show_sign()
self.show_acceleration_formula()
# self.ask_about_what_to_do()
# self.emphasize_theta()
# self.show_angular_velocity()
# self.show_angular_acceleration()
# self.circle_g_sin_formula()
def add_pendulum(self):
pendulum = Pendulum(**self.pendulum_config)
theta_tracker = ValueTracker(pendulum.get_theta())
pendulum.add_updater(lambda p: p.set_theta(
theta_tracker.get_value()
))
self.add(pendulum)
self.pendulum = pendulum
self.theta_tracker = theta_tracker
def show_arc_length(self):
pendulum = self.pendulum
angle = pendulum.get_theta()
height = pendulum.length
top = pendulum.get_fixed_point()
line = Line(UP, DOWN)
line.set_height(height)
line.move_to(top, UP)
arc = always_redraw(lambda: Arc(
start_angle=-90 * DEGREES,
angle=pendulum.get_theta(),
arc_center=pendulum.get_fixed_point(),
radius=pendulum.length,
stroke_color=GREEN,
))
brace = Brace(Line(ORIGIN, 5 * UP), RIGHT)
brace.point = VectorizedPoint(brace.get_right())
brace.add(brace.point)
brace.set_height(angle)
brace.move_to(ORIGIN, DL)
brace.apply_complex_function(np.exp)
brace.scale(height)
brace.rotate(-90 * DEGREES)
brace.move_to(arc)
brace.shift(MED_SMALL_BUFF * normalize(
arc.point_from_proportion(0.5) - top
))
x_sym = OldTex("x")
x_sym.set_color(GREEN)
x_sym.next_to(brace.point, DR, buff=SMALL_BUFF)
rhs = OldTex("=", "L", "\\theta")
rhs.set_color_by_tex("\\theta", BLUE)
rhs.next_to(x_sym, RIGHT)
rhs.shift(0.7 * SMALL_BUFF * UP)
line_L = OldTex("L")
line_L.next_to(
pendulum.rod.get_center(), UR, SMALL_BUFF,
)
self.play(
ShowCreation(arc),
Rotate(line, angle, about_point=top),
UpdateFromAlphaFunc(
line, lambda m, a: m.set_stroke(
width=2 * there_and_back(a)
)
),
GrowFromPoint(
brace, line.get_bottom(),
path_arc=angle
),
)
self.play(FadeIn(x_sym, UP))
self.wait()
# Show equation
line.set_stroke(BLUE, 5)
self.play(
ShowCreationThenFadeOut(line),
FadeInFromDown(line_L)
)
self.play(
TransformFromCopy(
line_L, rhs.get_part_by_tex("L")
),
Write(rhs.get_part_by_tex("="))
)
self.play(
TransformFromCopy(
pendulum.theta_label,
rhs.get_parts_by_tex("\\theta"),
)
)
self.add(rhs)
x_eq = VGroup(x_sym, rhs)
self.play(
FadeOut(brace),
x_eq.rotate, angle / 2,
x_eq.next_to, arc.point_from_proportion(0.5),
UL, {"buff": -MED_SMALL_BUFF}
)
self.x_eq = x_eq
self.arc = arc
self.line_L = line_L
def add_g_vect(self):
pendulum = self.pendulum
g_vect = self.g_vect = GravityVector(
pendulum, **self.g_vect_config,
)
g_word = self.g_word = OldTexText("Gravity")
g_word.rotate(-90 * DEGREES)
g_word.scale(0.75)
g_word.add_updater(lambda m: m.next_to(
g_vect, RIGHT, buff=-SMALL_BUFF,
))
self.play(
GrowArrow(g_vect),
FadeIn(g_word, UP, lag_ratio=0.1),
)
self.wait()
def show_constraint(self):
pendulum = self.pendulum
arcs = VGroup()
for u in [-1, 2, -1]:
d_theta = 40 * DEGREES * u
arc = Arc(
start_angle=pendulum.get_theta() - 90 * DEGREES,
angle=d_theta,
radius=pendulum.length,
arc_center=pendulum.get_fixed_point(),
stroke_width=2,
stroke_color=YELLOW,
stroke_opacity=0.5,
)
self.play(
self.theta_tracker.increment_value, d_theta,
ShowCreation(arc)
)
arcs.add(arc)
self.play(FadeOut(arcs))
def break_g_vect_into_components(self):
g_vect = self.g_vect
g_vect.component_lines = always_redraw(
g_vect.create_component_lines
)
tan_line, perp_line = g_vect.component_lines
g_vect.tangent = always_redraw(lambda: Arrow(
tan_line.get_start(),
tan_line.get_end(),
buff=0,
color=self.tan_line_color,
))
g_vect.perp = always_redraw(lambda: Arrow(
perp_line.get_start(),
perp_line.get_end(),
buff=0,
color=self.perp_line_color,
))
self.play(ShowCreation(g_vect.component_lines))
self.play(GrowArrow(g_vect.tangent))
self.wait()
self.play(GrowArrow(g_vect.perp))
self.wait()
def show_angle_geometry(self):
g_vect = self.g_vect
arc = Arc(
start_angle=90 * DEGREES,
angle=self.pendulum.get_theta(),
radius=0.5,
arc_center=g_vect.get_end(),
)
q_mark = OldTex("?")
q_mark.next_to(arc.get_center(), UL, SMALL_BUFF)
theta_label = OldTex("\\theta")
theta_label.move_to(q_mark)
self.add(g_vect)
self.play(
ShowCreation(arc),
Write(q_mark)
)
self.play(ShowCreationThenFadeAround(q_mark))
self.wait()
self.play(ShowCreationThenFadeAround(
self.pendulum.theta_label
))
self.play(
TransformFromCopy(
self.pendulum.theta_label,
theta_label,
),
FadeOut(q_mark)
)
self.wait()
self.play(WiggleOutThenIn(g_vect.tangent))
self.play(WiggleOutThenIn(
Line(
*g_vect.get_start_and_end(),
buff=0,
).add_tip().match_style(g_vect),
remover=True
))
self.wait()
self.play(
FadeOut(arc),
FadeOut(theta_label),
)
def show_gsin_formula(self):
g_vect = self.g_vect
g_word = self.g_word
g_word.clear_updaters()
g_term = self.g_term = OldTex("-g")
g_term.add_updater(lambda m: m.next_to(
g_vect,
RIGHT if self.pendulum.get_theta() >= 0 else LEFT,
SMALL_BUFF
))
def create_vect_label(vect, tex, direction):
label = OldTex(tex)
label.set_stroke(width=0, background=True)
label.add_background_rectangle()
label.scale(0.7)
max_width = 0.9 * vect.get_length()
if label.get_width() > max_width:
label.set_width(max_width)
angle = vect.get_angle()
angle = (angle + PI / 2) % PI - PI / 2
label.next_to(ORIGIN, direction, SMALL_BUFF)
label.rotate(angle, about_point=ORIGIN)
label.shift(vect.get_center())
return label
g_sin_label = always_redraw(lambda: create_vect_label(
g_vect.tangent, "-g\\sin(\\theta)", UP,
))
g_cos_label = always_redraw(lambda: create_vect_label(
g_vect.perp, "-g\\cos(\\theta)", DOWN,
))
self.play(
ReplacementTransform(g_word[0][0], g_term[0][1]),
FadeOut(g_word[0][1:]),
Write(g_term[0][0]),
)
self.add(g_term)
self.wait()
for label in g_sin_label, g_cos_label:
self.play(
GrowFromPoint(label[0], g_term.get_center()),
TransformFromCopy(g_term, label[1][:2]),
GrowFromPoint(label[1][2:], g_term.get_center()),
remover=True
)
self.add(label)
self.wait()
self.g_sin_label = g_sin_label
self.g_cos_label = g_cos_label
def show_sign(self):
get_theta = self.pendulum.get_theta
theta_decimal = DecimalNumber(include_sign=True)
theta_decimal.add_updater(lambda d: d.set_value(
get_theta()
))
theta_decimal.add_updater(lambda m: m.next_to(
self.pendulum.theta_label, DOWN
))
theta_decimal.add_updater(lambda m: m.set_color(
GREEN if get_theta() > 0 else RED
))
self.play(
FadeIn(theta_decimal, UP),
FadeOut(self.x_eq),
FadeOut(self.line_L),
)
self.set_theta(-60 * DEGREES, run_time=4)
self.set_theta(60 * DEGREES, run_time=4)
self.play(
FadeOut(theta_decimal),
FadeIn(self.x_eq),
)
def show_acceleration_formula(self):
x_eq = self.x_eq
g_sin_theta = self.g_sin_label
equation = OldTex(
"a", "=",
"\\ddot", "x",
"=",
"-", "g", "\\sin\\big(", "\\theta", "\\big)",
)
equation.to_edge(LEFT)
second_deriv = equation[2:4]
x_part = equation.get_part_by_tex("x")
x_part.set_color(GREEN)
a_eq = equation[:2]
eq2 = equation.get_parts_by_tex("=")[1]
rhs = equation[5:]
second_deriv_L_form = OldTex(
"L", "\\ddot", "\\theta"
)
second_deriv_L_form.move_to(second_deriv, DOWN)
eq3 = OldTex("=")
eq3.rotate(90 * DEGREES)
eq3.next_to(second_deriv_L_form, UP)
g_L_frac = OldTex(
"-", "{g", "\\over", "L}"
)
g_L_frac.move_to(rhs[:2], LEFT)
g_L_frac.shift(SMALL_BUFF * UP / 2)
mu_term = OldTex(
"-\\mu", "\\dot", "\\theta",
)
mu_term.next_to(g_L_frac, LEFT)
mu_term.shift(SMALL_BUFF * UP / 2)
mu_brace = Brace(mu_term, UP)
mu_word = mu_brace.get_text("Air resistance")
for mob in equation, second_deriv_L_form, mu_term:
mob.set_color_by_tex("\\theta", BLUE)
self.play(
TransformFromCopy(x_eq[0], x_part),
Write(equation[:3]),
)
self.wait()
self.play(
Write(eq2),
TransformFromCopy(g_sin_theta, rhs)
)
self.wait()
#
self.show_acceleration_at_different_angles()
#
self.play(
FadeInFromDown(second_deriv_L_form),
Write(eq3),
second_deriv.next_to, eq3, UP,
a_eq.shift, SMALL_BUFF * LEFT,
eq2.shift, SMALL_BUFF * RIGHT,
rhs.shift, SMALL_BUFF * RIGHT,
)
self.wait()
self.wait()
self.play(
FadeOut(a_eq),
FadeOut(second_deriv),
FadeOut(eq3),
ReplacementTransform(
second_deriv_L_form.get_part_by_tex("L"),
g_L_frac.get_part_by_tex("L"),
),
ReplacementTransform(
equation.get_part_by_tex("-"),
g_L_frac.get_part_by_tex("-"),
),
ReplacementTransform(
equation.get_part_by_tex("g"),
g_L_frac.get_part_by_tex("g"),
),
Write(g_L_frac.get_part_by_tex("\\over")),
rhs[2:].next_to, g_L_frac, RIGHT, {"buff": SMALL_BUFF},
)
self.wait()
self.play(
GrowFromCenter(mu_term),
VGroup(eq2, second_deriv_L_form[1:]).next_to,
mu_term, LEFT,
)
self.play(
GrowFromCenter(mu_brace),
FadeInFromDown(mu_word),
)
def show_acceleration_at_different_angles(self):
to_fade = VGroup(
self.g_cos_label,
self.g_vect.perp,
)
new_comp_line_sytle = {
"stroke_width": 0.5,
"stroke_opacity": 0.25,
}
self.play(
FadeOut(self.x_eq),
to_fade.set_opacity, 0.25,
self.g_vect.component_lines.set_style,
new_comp_line_sytle
)
self.g_vect.component_lines.add_updater(
lambda m: m.set_style(**new_comp_line_sytle)
)
for mob in to_fade:
mob.add_updater(lambda m: m.set_opacity(0.25))
self.set_theta(0)
self.wait(2)
self.set_theta(89.9 * DEGREES, run_time=3)
self.wait(2)
self.set_theta(
60 * DEGREES,
FadeIn(self.x_eq),
run_time=2,
)
self.wait()
def ask_about_what_to_do(self):
g_vect = self.g_vect
g_sin_label = self.g_sin_label
angle = g_vect.tangent.get_angle()
angle = (angle - PI) % TAU
randy = You()
randy.to_corner(DL)
bubble = randy.get_bubble(
height=2,
width=3.5,
)
g_sin_copy = g_sin_label.copy()
g_sin_copy.remove(g_sin_copy[0])
g_sin_copy.generate_target()
g_sin_copy.target.scale(1 / 0.75)
g_sin_copy.target.rotate(-angle)
a_eq = OldTex("a=")
thought_term = VGroup(a_eq, g_sin_copy.target)
thought_term.arrange(RIGHT, buff=SMALL_BUFF)
thought_term.move_to(bubble.get_bubble_center())
rect = SurroundingRectangle(g_sin_copy.target)
rect.rotate(angle)
rect.move_to(g_sin_label)
randy.save_state()
randy.fade(1)
self.play(randy.restore, randy.change, "pondering")
self.play(ShowCreationThenFadeOut(rect))
self.play(
ShowCreation(bubble),
Write(a_eq),
MoveToTarget(g_sin_copy),
randy.look_at, bubble,
)
thought_term.remove(g_sin_copy.target)
thought_term.add(g_sin_copy)
self.play(Blink(randy))
self.wait()
self.play(
ShowCreationThenDestruction(
thought_term.copy().set_style(
stroke_color=YELLOW,
stroke_width=2,
fill_opacity=0,
),
run_time=2,
lag_ratio=0.2,
),
randy.change, "confused", thought_term,
)
self.play(Blink(randy))
self.play(
FadeOut(randy),
FadeOut(bubble),
thought_term.next_to, self.pendulum, DOWN, LARGE_BUFF
)
self.accleration_equation = thought_term
def emphasize_theta(self):
pendulum = self.pendulum
self.play(FocusOn(pendulum.theta_label))
self.play(Indicate(pendulum.theta_label))
pendulum_copy = pendulum.deepcopy()
pendulum_copy.clear_updaters()
pendulum_copy.fade(1)
pendulum_copy.start_swinging()
def new_updater(p):
p.set_theta(pendulum_copy.get_theta())
pendulum.add_updater(new_updater)
self.add(pendulum_copy)
self.wait(5)
pendulum_copy.end_swinging()
self.remove(pendulum_copy)
pendulum.remove_updater(new_updater)
self.update_mobjects(0)
def show_angular_velocity(self):
pass
def show_angular_acceleration(self):
pass
def circle_g_sin_formula(self):
self.play(
ShowCreationThenFadeAround(
self.accleration_equation
)
)
#
def set_theta(self, value, *added_anims, **kwargs):
kwargs["run_time"] = kwargs.get("run_time", 2)
self.play(
self.theta_tracker.set_value, value,
*added_anims,
**kwargs,
)
class BuildUpEquation(Scene):
CONFIG = {
"tex_config": {
"tex_to_color_map": {
"{a}": YELLOW,
"{v}": RED,
"{x}": GREEN,
"\\theta": BLUE,
"{L}": WHITE,
}
}
}
def construct(self):
# self.add_center_line()
self.show_derivatives()
self.show_theta_double_dot_equation()
self.talk_about_sine_component()
self.add_air_resistance()
def add_center_line(self):
line = Line(UP, DOWN)
line.set_height(FRAME_HEIGHT)
line.set_stroke(WHITE, 1)
self.add(line)
def show_derivatives(self):
a_eq = OldTex(
"{a}", "=", "{d{v} \\over dt}",
**self.tex_config,
)
v_eq = OldTex(
"{v}", "=", "{d{x} \\over dt}",
**self.tex_config,
)
x_eq = OldTex(
"{x} = {L} \\theta",
**self.tex_config,
)
eqs = VGroup(a_eq, v_eq, x_eq)
eqs.arrange(DOWN, buff=LARGE_BUFF)
eqs.to_corner(UL)
v_rhs = OldTex(
"={L}{d\\theta \\over dt}",
"=", "{L}\\dot{\\theta}",
**self.tex_config,
)
v_rhs.next_to(v_eq, RIGHT, SMALL_BUFF)
v_rhs.shift(
UP * (v_eq[1].get_bottom()[1] - v_rhs[0].get_bottom()[1])
)
a_rhs = OldTex(
"={L}{d", "\\dot{\\theta}", "\\over dt}",
"=", "{L}\\ddot{\\theta}",
**self.tex_config,
)
a_rhs.next_to(a_eq, RIGHT, SMALL_BUFF)
a_rhs.shift(
UP * (a_eq[1].get_bottom()[1] - a_rhs[0].get_bottom()[1])
)
# a_eq
self.play(Write(a_eq))
self.wait()
# v_eq
self.play(
TransformFromCopy(
a_eq.get_part_by_tex("{v}"),
v_eq.get_part_by_tex("{v}"),
)
)
self.play(TransformFromCopy(v_eq[:1], v_eq[1:]))
self.wait()
# x_eq
self.play(
TransformFromCopy(
v_eq.get_part_by_tex("{x}"),
x_eq.get_part_by_tex("{x}"),
)
)
self.play(Write(x_eq[1:]))
self.wait()
for tex in "L", "\\theta":
self.play(ShowCreationThenFadeAround(
x_eq.get_part_by_tex(tex)
))
self.wait()
# v_rhs
self.play(*[
TransformFromCopy(
x_eq.get_part_by_tex(tex),
v_rhs.get_part_by_tex(tex),
)
for tex in ("=", "{L}", "\\theta")
])
self.play(
TransformFromCopy(v_eq[-3], v_rhs[2]),
TransformFromCopy(v_eq[-1], v_rhs[4]),
)
self.wait()
self.play(
Write(v_rhs[-5]),
TransformFromCopy(*v_rhs.get_parts_by_tex("{L}")),
TransformFromCopy(v_rhs[3:4], v_rhs[-3:])
)
self.wait()
self.play(ShowCreationThenFadeAround(v_rhs[2:4]))
self.play(ShowCreationThenFadeAround(v_rhs[4]))
self.wait()
# a_rhs
self.play(*[
TransformFromCopy(
v_rhs.get_parts_by_tex(tex)[-1],
a_rhs.get_part_by_tex(tex),
)
for tex in ("=", "{L}", "\\theta", "\\dot")
])
self.play(
TransformFromCopy(a_eq[-3], a_rhs[2]),
TransformFromCopy(a_eq[-1], a_rhs[6]),
)
self.wait()
self.play(
Write(a_rhs[-5]),
TransformFromCopy(*a_rhs.get_parts_by_tex("{L}")),
TransformFromCopy(a_rhs[3:4], a_rhs[-3:]),
)
self.wait()
self.equations = VGroup(
a_eq, v_eq, x_eq,
v_rhs, a_rhs,
)
def show_theta_double_dot_equation(self):
equations = self.equations
a_deriv = equations[0]
a_rhs = equations[-1][-5:].copy()
shift_vect = 1.5 * DOWN
equals = OldTex("=")
equals.rotate(90 * DEGREES)
equals.next_to(a_deriv[0], UP, MED_LARGE_BUFF)
g_sin_eq = OldTex(
"-", "g", "\\sin", "(", "\\theta", ")",
**self.tex_config,
)
g_sin_eq.next_to(
equals, UP,
buff=MED_LARGE_BUFF,
aligned_edge=LEFT,
)
g_sin_eq.to_edge(LEFT)
g_sin_eq.shift(shift_vect)
shift_vect += (
g_sin_eq[1].get_center() -
a_deriv[0].get_center()
)[0] * RIGHT
equals.shift(shift_vect)
a_rhs.shift(shift_vect)
self.play(
equations.shift, shift_vect,
Write(equals),
GrowFromPoint(
g_sin_eq, 2 * RIGHT + 3 * DOWN
)
)
self.wait()
self.play(
a_rhs.next_to, g_sin_eq, RIGHT,
a_rhs.shift, SMALL_BUFF * UP,
)
self.wait()
# Fade equations
self.play(
FadeOut(equals),
equations.shift, DOWN,
equations.fade, 0.5,
)
# Rotate sides
equals, L, ddot, theta, junk = a_rhs
L_dd_theta = VGroup(L, ddot, theta)
minus, g, sin, lp, theta2, rp = g_sin_eq
m2, g2, over, L2 = frac = OldTex("-", "{g", "\\over", "L}")
frac.next_to(equals, RIGHT)
self.play(
L_dd_theta.next_to, equals, LEFT,
L_dd_theta.shift, SMALL_BUFF * UP,
g_sin_eq.next_to, equals, RIGHT,
path_arc=PI / 2,
)
self.play(
ReplacementTransform(g, g2),
ReplacementTransform(minus, m2),
ReplacementTransform(L, L2),
Write(over),
g_sin_eq[2:].next_to, over, RIGHT, SMALL_BUFF,
)
self.wait()
# Surround
rect = SurroundingRectangle(VGroup(g_sin_eq, frac, ddot))
rect.stretch(1.1, 0)
dashed_rect = DashedVMobject(
rect, num_dashes=50, positive_space_ratio=1,
)
dashed_rect.shuffle()
dashed_rect.save_state()
dashed_rect.space_out_submobjects(1.1)
for piece in dashed_rect:
piece.rotate(90 * DEGREES)
dashed_rect.fade(1)
self.play(Restore(dashed_rect, lag_ratio=0.05))
dashed_rect.generate_target()
dashed_rect.target.space_out_submobjects(0.9)
dashed_rect.target.fade(1)
for piece in dashed_rect.target:
piece.rotate(90 * DEGREES)
self.play(MoveToTarget(
dashed_rect,
lag_ratio=0.05,
remover=True
))
self.wait()
self.main_equation = VGroup(
ddot, theta, equals,
m2, L2, over, g2,
sin, lp, theta2, rp,
)
def talk_about_sine_component(self):
main_equation = self.main_equation
gL_part = main_equation[4:7]
sin_part = main_equation[7:]
sin = sin_part[0]
morty = Mortimer(height=1.5)
morty.next_to(sin, DR, buff=LARGE_BUFF)
morty.add_updater(lambda m: m.look_at(sin))
self.play(ShowCreationThenFadeAround(gL_part))
self.wait()
self.play(ShowCreationThenFadeAround(sin_part))
self.wait()
self.play(FadeIn(morty))
sin.save_state()
self.play(
morty.change, "angry",
sin.next_to, morty, LEFT, {"aligned_edge": UP},
)
self.play(Blink(morty))
morty.clear_updaters()
self.play(
morty.change, "concerned_musician",
morty.look, DR,
)
self.play(Restore(sin))
self.play(FadeOut(morty))
self.wait()
# Emphasize theta as input
theta = sin_part[2]
arrow = Vector(0.5 * UP, color=WHITE)
arrow.next_to(theta, DOWN, SMALL_BUFF)
word = OldTexText("Input")
word.next_to(arrow, DOWN)
self.play(
FadeIn(word, UP),
GrowArrow(arrow)
)
self.play(
ShowCreationThenDestruction(
theta.copy().set_style(
fill_opacity=0,
stroke_width=2,
stroke_color=YELLOW,
),
lag_ratio=0.1,
)
)
self.play(FadeOut(arrow), FadeOut(word))
def add_air_resistance(self):
main_equation = self.main_equation
tdd_eq = main_equation[:3]
rhs = main_equation[3:]
new_term = OldTex(
"-", "\\mu", "\\dot{", "\\theta}",
)
new_term.set_color_by_tex("\\theta", BLUE)
new_term.move_to(main_equation)
new_term.shift(0.5 * SMALL_BUFF * UP)
new_term[0].align_to(rhs[0], UP)
brace = Brace(new_term, DOWN)
words = brace.get_text("Air resistance")
self.play(
FadeInFromDown(new_term),
tdd_eq.next_to, new_term, LEFT,
tdd_eq.align_to, tdd_eq, UP,
rhs.next_to, new_term, RIGHT,
rhs.align_to, rhs, UP,
)
self.play(
GrowFromCenter(brace),
Write(words)
)
self.wait()
class SimpleDampenedPendulum(Scene):
def construct(self):
pendulum = Pendulum(
top_point=ORIGIN,
initial_theta=150 * DEGREES,
mu=0.5,
)
self.add(pendulum)
pendulum.start_swinging()
self.wait(20)
class NewSceneName(Scene):
def construct(self):
pass
|
|
from manim_imports_ext import *
from _2019.diffyq.part1.shared_constructs import *
class SomeOfYouWatching(TeacherStudentsScene):
CONFIG = {
"camera_config": {
"background_color": GREY_E,
}
}
def construct(self):
screen = self.screen
screen.scale(1.25, about_edge=UL)
screen.set_fill(BLACK, 1)
self.add(screen)
self.teacher.change("raise_right_hand")
for student in self.students:
student.change("pondering", screen)
self.student_says(
"Well...yeah",
target_mode="tease"
)
self.wait(3)
class FormulasAreLies(PiCreatureScene):
def construct(self):
you = self.pi_creature
t2c = {
"{L}": BLUE,
"{g}": YELLOW,
"\\theta_0": WHITE,
"\\sqrt{\\,": WHITE,
}
kwargs = {"tex_to_color_map": t2c}
period_eq = OldTex(
"\\text{Period} = 2\\pi \\sqrt{\\,{L} / {g}}",
**kwargs
)
theta_eq = OldTex(
"\\theta(t) = \\theta_0 \\cos\\left("
"\\sqrt{\\,{L} / {g}} \\cdot t"
"\\right)",
**kwargs
)
equations = VGroup(theta_eq, period_eq)
equations.arrange(DOWN, buff=LARGE_BUFF)
for eq in period_eq, theta_eq:
i = eq.index_of_part_by_tex("\\sqrt")
eq.sqrt_part = eq[i:i + 4]
theta0 = theta_eq.get_part_by_tex("\\theta_0")
theta0_words = OldTexText("Starting angle")
theta0_words.next_to(theta0, UL)
theta0_words.shift(UP + 0.5 * RIGHT)
arrow = Arrow(
theta0_words.get_bottom(),
theta0,
color=WHITE,
tip_length=0.25,
)
bubble = SpeechBubble()
bubble.pin_to(you)
bubble.write("Lies!")
bubble.content.scale(2)
bubble.resize_to_content()
self.add(period_eq)
you.change("pondering", period_eq)
self.wait()
theta_eq.remove(*theta_eq.sqrt_part)
self.play(
TransformFromCopy(
period_eq.sqrt_part,
theta_eq.sqrt_part,
),
FadeIn(theta_eq)
)
theta_eq.add(*theta_eq.sqrt_part)
self.play(
FadeIn(theta0_words, LEFT),
GrowArrow(arrow),
)
self.wait()
self.play(you.change, "confused")
self.wait()
self.play(
you.change, "angry",
ShowCreation(bubble),
FadeInFromPoint(bubble.content, you.mouth),
equations.to_edge, LEFT,
FadeOut(arrow),
FadeOut(theta0_words),
)
self.wait()
def create_pi_creature(self):
return You().flip().to_corner(DR)
# class TourOfDifferentialEquations(Scene):
# def construct(self):
# pass
class SoWhatIsThetaThen(TeacherStudentsScene):
def construct(self):
ode = get_ode()
ode.to_corner(UL)
self.add(ode)
self.student_says(
"Okay, but then\\\\"
"what \\emph{is} $\\theta(t)$?"
)
self.wait()
self.play(self.teacher.change, "happy")
self.wait(2)
self.teacher_says(
"First, you must appreciate\\\\"
"a deep truth...",
added_anims=[self.change_students(
*3 * ["confused"]
)]
)
self.wait(4)
class ProveTeacherWrong(TeacherStudentsScene):
def construct(self):
tex_config = {
"tex_to_color_map": {
"{\\theta}": BLUE,
"{\\dot\\theta}": YELLOW,
"{\\ddot\\theta}": RED,
}
}
func = OldTex(
"{\\theta}(t)", "=",
"\\theta_0", "\\cos(\\sqrt{g / L} \\cdot t)",
**tex_config,
)
d_func = OldTex(
"{\\dot\\theta}(t)", "=",
"-\\left(\\sqrt{g / L}\\right)",
"\\theta_0", "\\sin(\\sqrt{g / L} \\cdot t)",
**tex_config,
)
dd_func = OldTex(
"{\\ddot\\theta}(t)", "=",
"-\\left(g / L\\right)",
"\\theta_0", "\\cos(\\sqrt{g / L} \\cdot t)",
**tex_config,
)
# ode = OldTex(
# "\\ddot {\\theta}({t})", "=",
# "-\\mu \\dot {\\theta}({t})",
# "-{g \\over L} \\sin\\big({\\theta}({t})\\big)",
# **tex_config,
# )
ode = get_ode()
arrows = [Tex("\\Downarrow") for x in range(2)]
VGroup(func, d_func, dd_func, ode, *arrows).scale(0.7)
teacher = self.teacher
you = self.students[2]
self.student_thinks(ode)
you.add_updater(lambda m: m.look_at(func))
self.teacher_holds_up(func)
self.wait()
group = VGroup(arrows[0], d_func, arrows[1], dd_func)
group.arrange(DOWN)
group.move_to(func, DOWN)
arrow = Arrow(
group.get_corner(UL),
ode.get_top(),
path_arc=PI / 2,
)
q_marks = VGroup(*[
OldTex("?").scale(1.5).next_to(
arrow.point_from_proportion(a),
UP
)
for a in np.linspace(0.2, 0.8, 5)
])
cycle_animation(VFadeInThenOut(
q_marks,
lag_ratio=0.2,
run_time=4,
rate_func=squish_rate_func(smooth, 0, 0.5)
))
self.play(
func.next_to, group, UP,
LaggedStartMap(
FadeInFrom, group,
lambda m: (m, UP)
),
teacher.change, "guilty",
you.change, "sassy",
)
rect = SurroundingRectangle(
VGroup(group, func)
)
dashed_rect = DashedVMobject(rect, num_dashes=75)
animated_rect = AnimatedBoundary(dashed_rect, cycle_rate=1)
self.wait()
self.add(animated_rect, q_marks)
self.play(
ShowCreation(arrow),
# FadeInFromDown(q_mark),
self.change_students("confused", "confused")
)
self.wait(4)
self.play_student_changes(
*3 * ["pondering"],
self.teacher.change, "maybe"
)
self.wait(8)
class PhysicistPhaseSpace(PiCreatureScene):
def construct(self):
physy = self.pi_creature
name = OldTexText("Physicist")
name.scale(1.5)
name.to_corner(DL, buff=MED_SMALL_BUFF)
physy.next_to(name, UP, SMALL_BUFF)
VGroup(name, physy).shift_onto_screen()
axes = Axes(
x_min=-1,
x_max=10,
y_min=-1,
y_max=7,
)
axes.set_height(6)
axes.next_to(physy, RIGHT)
axes.to_edge(UP)
axes.set_stroke(width=1)
x_label = OldTexText("Position")
x_label.next_to(axes.x_axis.get_right(), UP)
y_label = OldTexText("Momentum")
y_label.next_to(axes.y_axis.get_top(), RIGHT)
title = OldTexText("Phase space")
title.scale(1.5)
title.set_color(YELLOW)
title.move_to(axes)
self.add(name, physy)
self.play(
physy.change, "angry",
Write(axes),
FadeInFromDown(title)
)
self.wait(2)
self.play(
GrowFromPoint(x_label, physy.get_corner(UR)),
physy.change, "raise_right_hand",
axes.x_axis.get_right()
)
self.play(
GrowFromPoint(y_label, physy.get_corner(UR)),
physy.look_at, axes.y_axis.get_top(),
)
self.wait(3)
def create_pi_creature(self):
return PiCreature(color=GREY).to_corner(DL)
class AskAboutActuallySolving(TeacherStudentsScene):
def construct(self):
ode = get_ode()
ode.to_corner(UL)
self.add(ode)
morty = self.teacher
self.student_says(
"Yeah yeah, but how do\\\\"
"you actually \\emph{solve} it?",
index=1,
target_mode="sassy",
added_anims=[morty.change, "thinking"],
)
self.play_student_changes(
"confused", "sassy", "confused",
look_at=ode,
)
self.wait()
self.teacher_says(
"What do you mean\\\\ by ``solve''?",
target_mode="speaking",
added_anims=[self.change_students(
*3 * ["erm"]
)]
)
self.play(self.students[1].change, "angry")
self.wait(3)
class HungerForExactness(TeacherStudentsScene):
def construct(self):
students = self.students
you = students[2]
teacher = self.teacher
ode = get_ode()
ode.to_corner(UL)
left_part = ode[:5]
friction_part = ode[5:11]
self.add(ode)
proposed_solution = OldTex(
"\\theta_0\\cos((\\sqrt{g/L})t)e^{-\\mu t}"
)
proposed_solution.next_to(
you.get_corner(UL), UP, buff=0.7
)
proposed_solution_rect = SurroundingRectangle(
proposed_solution, buff=MED_SMALL_BUFF,
)
proposed_solution_rect.set_color(BLUE)
proposed_solution_rect.round_corners()
solution_p1 = OldTex(
"""
\\theta(t) = 2\\text{am}\\left(
\\frac{\\sqrt{2g + Lc_1} (t + c_2)}{2\\sqrt{L}},
\\frac{4g}{2g + Lc_1}
\\right)
""",
)
solution_p1.to_corner(UL)
solution_p2 = OldTex(
"c_1, c_2 = \\text{Constants depending on initial conditions}"
)
solution_p2.set_color(GREY_B)
solution_p2.scale(0.75)
solution_p3 = OldTex(
"""
\\text{am}(u, k) =
\\int_0^u \\text{dn}(v, k)\\,dv
"""
)
solution_p3.name = OldTexText(
"(Jacobi amplitude function)"
)
solution_p4 = OldTex(
"""
\\text{dn}(u, k) =
\\sqrt{1 - k^2 \\sin^2(\\phi)}
"""
)
solution_p4.name = OldTexText(
"(Jacobi elliptic function)"
)
solution_p5 = OldTexText("Where $\\phi$ satisfies")
solution_p6 = OldTex(
"""
u = \\int_0^\\phi \\frac{dt}{\\sqrt{1 - k^2 \\sin^2(t)}}
"""
)
solution = VGroup(
solution_p1,
solution_p2,
solution_p3,
solution_p4,
solution_p5,
solution_p6,
)
solution.arrange(DOWN)
solution.scale(0.7)
solution.to_corner(UL, buff=MED_SMALL_BUFF)
solution.set_stroke(width=0, background=True)
solution.remove(solution_p2)
solution_p1.add(solution_p2)
solution.remove(solution_p5)
solution_p6.add(solution_p5)
for part in [solution_p3, solution_p4]:
part.name.scale(0.7 * 0.7)
part.name.set_color(GREY_B)
part.name.next_to(part, RIGHT)
part.add(part.name)
self.student_says(
"Right, but like,\\\\"
"what \\emph{is} $\\theta(t)$?",
target_mode="sassy",
added_anims=[teacher.change, "guilty"],
)
self.wait()
self.play(
FadeInFromDown(proposed_solution),
RemovePiCreatureBubble(
you,
target_mode="raise_left_hand",
look_at=proposed_solution,
),
teacher.change, "pondering",
students[0].change, "pondering",
students[1].change, "hesitant",
)
self.play(ShowCreation(proposed_solution_rect))
self.play(
proposed_solution.shift, 3 * RIGHT,
proposed_solution_rect.shift, 3 * RIGHT,
you.change, "raise_right_hand", teacher.eyes,
)
self.wait(3)
self.play(
FadeOut(proposed_solution),
FadeOut(proposed_solution_rect),
ode.move_to, self.hold_up_spot, DOWN,
ode.shift, LEFT,
teacher.change, "raise_right_hand",
self.change_students(*3 * ["pondering"])
)
self.wait()
ode.save_state()
self.play(
left_part.move_to, friction_part, RIGHT,
left_part.match_y, left_part,
friction_part.to_corner, DR,
friction_part.fade, 0.5,
)
self.wait()
modes = ["erm", "sad", "sad", "horrified"]
for part, mode in zip(solution, modes):
self.play(
FadeIn(part, UP),
self.change_students(
*3 * [mode],
look_at=part,
)
)
self.wait()
self.wait(3)
self.play_student_changes("tired", "sad", "concerned_musician")
self.wait(4)
self.look_at(solution)
self.wait(5)
self.play(
FadeOut(solution, 2 * LEFT),
Restore(ode),
self.change_students(
"sick", "angry", "tired",
)
)
self.wait(3)
mystery = OldTex(
"\\theta(t) = ???",
tex_to_color_map={"\\theta": BLUE},
)
mystery.scale(2)
mystery.to_edge(UP)
mystery.set_stroke(width=0, background=True)
mystery_boundary = AnimatedBoundary(
mystery, stroke_width=1
)
self.play(
FadeInFromDown(mystery),
self.teacher.change, "pondering"
)
self.add(mystery_boundary, mystery)
self.play_all_student_changes("sad")
self.look_at(mystery)
self.wait(5)
# Define
self.student_says(
"Let $\\text{P}(\\mu, g, L; t)$ be a\\\\"
"function satisfying this ODE.",
index=0,
target_mode="speaking",
added_anims=[
FadeOut(mystery),
FadeOut(mystery_boundary),
ode.to_corner, UR
]
)
self.play_student_changes(
"hooray", "sassy", "sassy",
look_at=students[0].eyes.get_corner(UR),
)
self.wait(2)
class ItGetsWorse(TeacherStudentsScene):
def construct(self):
self.teacher_says("It gets\\\\worse")
self.play_student_changes(
"hesitant", "pleading", "erm"
)
self.wait(5)
|
|
from manim_imports_ext import *
from _2019.diffyq.part1.shared_constructs import *
class SmallAngleApproximationTex(Scene):
def construct(self):
approx = OldTex(
"\\sin", "(", "\\theta", ") \\approx \\theta",
tex_to_color_map={"\\theta": RED},
arg_separator="",
)
implies = OldTex("\\Downarrow")
period = OldTex(
"\\text{Period}", "\\approx",
"2\\pi \\sqrt{\\,{L} / {g}}",
**Lg_formula_config,
)
group = VGroup(approx, implies, period)
group.arrange(DOWN)
approx_brace = Brace(approx, UP, buff=SMALL_BUFF)
approx_words = OldTexText(
"For small $\\theta$",
tex_to_color_map={"$\\theta$": RED},
)
approx_words.scale(0.75)
approx_words.next_to(approx_brace, UP, SMALL_BUFF)
self.add(approx, approx_brace, approx_words)
self.play(
Write(implies),
FadeIn(period, LEFT)
)
self.wait()
class StrogatzQuote(Scene):
def construct(self):
quote = self.get_quote()
movers = VGroup(*quote[:-1].family_members_with_points())
for mover in movers:
mover.save_state()
disc = Circle(radius=0.05)
disc.set_stroke(width=0)
disc.set_fill(BLACK, 0)
disc.move_to(mover)
mover.become(disc)
self.play(
FadeIn(quote.author_part, LEFT),
LaggedStartMap(
# FadeInFromLarge,
# quote[:-1].family_members_with_points(),
Restore, movers,
lag_ratio=0.005,
run_time=2,
)
# FadeInFromDown(quote[:-1]),
# lag_ratio=0.01,
)
self.wait()
self.play(
Write(quote.law_part.copy().set_color(YELLOW)),
run_time=1,
)
self.wait()
self.play(
Write(quote.language_part.copy().set_color(BLUE)),
run_time=1.5,
)
self.wait(2)
def get_quote(self):
law_words = "laws of physics"
language_words = "language of differential equations"
author = "-Steven Strogatz"
quote = OldTexText(
"""
\\Large
``Since Newton, mankind has come to realize
that the laws of physics are always expressed
in the language of differential equations.''\\\\
""" + author,
alignment="",
arg_separator=" ",
isolate=[law_words, language_words, author]
)
quote.law_part = quote.get_part_by_tex(law_words)
quote.language_part = quote.get_part_by_tex(language_words)
quote.author_part = quote.get_part_by_tex(author)
quote.set_width(12)
quote.to_edge(UP)
quote[-2].shift(SMALL_BUFF * LEFT)
quote.author_part.shift(RIGHT + 0.5 * DOWN)
quote.author_part.scale(1.2, about_edge=UL)
return quote
class WriteInRadians(Scene):
def construct(self):
words = OldTexText("In radians")
words.set_color(YELLOW)
square = SurroundingRectangle(OldTex("\\theta"))
square.next_to(words, UP)
self.play(ShowCreation(square))
self.play(Write(words), FadeOut(square))
self.wait()
class XEqLThetaToCorner(Scene):
def construct(self):
equation = OldTex(
"x = L\\theta",
tex_to_color_map={
"x": GREEN,
"\\theta": BLUE,
}
)
equation.move_to(DOWN + 3 * RIGHT)
self.add(equation)
self.play(equation.to_corner, DL, {"buff": LARGE_BUFF})
self.wait()
class ComingUp(Scene):
CONFIG = {
"camera_config": {"background_color": GREY_E}
}
def construct(self):
frame = ScreenRectangle(
stroke_width=0,
fill_color=BLACK,
fill_opacity=1,
height=6
)
title = OldTexText("Coming up")
title.scale(1.5)
title.to_edge(UP)
frame.next_to(title, DOWN)
animated_frame = AnimatedBoundary(frame)
self.add(frame, title, animated_frame)
self.wait(10)
class InputLabel(Scene):
def construct(self):
label = OldTexText("Input")
label.scale(1.25)
arrow = Vector(UP)
arrow.next_to(label, UP)
self.play(
FadeIn(label, UP),
GrowArrow(arrow)
)
self.wait()
class ReallyHardToSolve(Scene):
def construct(self):
words = OldTexText(
"They're", "really\\\\",
"freaking", "hard\\\\",
"to", "solve\\\\",
)
words.set_height(6)
self.wait()
for word in words:
wait_time = 0.05 * len(word)
self.add(word)
self.wait(wait_time)
self.wait()
class ReasonForSolution(Scene):
def construct(self):
# Words
eq_word = OldTexText("Differential\\\\Equation")
s_word = OldTexText("Solution")
u_word = OldTexText("Understanding")
c_word = OldTexText("Computation")
cu_group = VGroup(u_word, c_word)
cu_group.arrange(DOWN, buff=2)
group = VGroup(eq_word, s_word, cu_group)
group.arrange(RIGHT, buff=2)
# words = VGroup(eq_word, s_word, u_word, c_word)
# Arrows
arrows = VGroup(
Arrow(eq_word.get_right(), s_word.get_left()),
Arrow(s_word.get_right(), u_word.get_left()),
Arrow(s_word.get_right(), c_word.get_left()),
)
arrows.set_color(GREY_B)
new_arrows = VGroup(
Arrow(
eq_word.get_corner(UR),
u_word.get_left(),
path_arc=-60 * DEGREES,
),
Arrow(
eq_word.get_corner(DR),
c_word.get_left(),
path_arc=60 * DEGREES,
),
)
new_arrows.set_color(BLUE)
# Define first examples
t2c = {
"{x}": BLUE,
"{\\dot x}": RED,
}
equation = OldTex(
"{\\dot x}(t) = k {x}(t)",
tex_to_color_map=t2c,
)
equation.next_to(eq_word, DOWN)
solution = OldTex(
"{x}(t) = x_0 e^{kt}",
tex_to_color_map=t2c,
)
solution.next_to(s_word, DOWN, MED_LARGE_BUFF)
equation.align_to(solution, DOWN)
axes = Axes(
x_min=-1,
x_max=5.5,
y_min=-1,
y_max=4.5,
y_axis_config={"unit_size": 0.5}
)
axes.set_stroke(width=2)
graph_line = axes.get_graph(
lambda x: np.exp(0.4 * x)
)
graph_line.set_stroke(width=2)
graph = VGroup(axes, graph_line)
graph.scale(0.5)
graph.next_to(u_word, UP)
computation = OldTex(
# "\\displaystyle "
"e^x = \\sum_{n=0}^\\infty "
"\\frac{x^n}{n!}"
)
computation.next_to(c_word, DOWN)
first_examples = VGroup(
equation, solution, graph, computation
)
# Second example
ode = get_ode()
ode.scale(0.75)
second_examples = VGroup(
ode,
OldTex("???").set_color(GREY_B),
ScreenRectangle(
height=2,
stroke_width=1,
),
)
for fe, se in zip(first_examples, second_examples):
se.move_to(fe, DOWN)
ode.shift(2 * SMALL_BUFF * DOWN)
ode.add_to_back(BackgroundRectangle(ode[-4:]))
self.add(eq_word)
self.add(equation)
self.play(
FadeIn(s_word, LEFT),
GrowArrow(arrows[0]),
TransformFromCopy(equation, solution)
)
self.wait()
self.play(
FadeIn(c_word, UL),
GrowArrow(arrows[2]),
FadeIn(computation, UP)
)
self.wait()
self.play(
FadeIn(u_word, DL),
GrowArrow(arrows[1]),
FadeInFromDown(graph)
)
self.wait(2)
self.play(
FadeOut(first_examples),
FadeIn(second_examples[:2])
)
self.wait()
self.play(
arrows.fade, 0.75,
s_word.fade, 0.75,
second_examples[1].fade, 0.75,
ShowCreation(new_arrows[0]),
FadeIn(second_examples[2])
)
self.play(
ShowCreation(new_arrows[1]),
Animation(second_examples),
)
self.wait()
class WritePhaseSpace(Scene):
def construct(self):
word = OldTexText("Phase space")
word.scale(2)
word.shift(FRAME_WIDTH * LEFT / 4)
word.to_edge(UP)
word.add_background_rectangle()
lines = VGroup(*[
Line(v, 1.3 * v)
for v in compass_directions(50)
])
lines.replace(word, stretch=True)
lines.scale(1.5)
lines.set_stroke(YELLOW)
lines.shuffle()
self.add(word)
self.play(
ShowPassingFlashWithThinningStrokeWidth(
lines,
lag_ratio=0.002,
run_time=1.5,
time_width=0.9,
n_segments=5,
)
)
self.wait()
class GleickQuote(Scene):
def construct(self):
quote = OldTexText(
"``[Phase space is] one of the most\\\\",
"powerful inventions", "of modern science.''\\\\",
)
quote.power_part = quote.get_part_by_tex("power")
book = ImageMobject("ChaosBookCover")
book.set_height(5)
book.next_to(ORIGIN, LEFT)
book.to_edge(DOWN)
gleick = ImageMobject("JamesGleick")
gleick.set_height(5)
gleick.next_to(ORIGIN, RIGHT)
gleick.to_edge(DOWN)
quote.to_edge(UP)
self.play(
FadeIn(book, RIGHT),
FadeIn(gleick, LEFT),
)
self.wait()
self.play(Write(quote))
self.play(Write(
quote.power_part.copy().set_color(BLUE),
run_time=1
))
self.wait()
class WritePhaseFlow(Scene):
def construct(self):
words = OldTexText("Phase flow")
words.scale(2)
words.shift(FRAME_WIDTH * LEFT / 4)
words.to_edge(UP)
words.add_background_rectangle()
self.play(Write(words))
self.wait()
class ShowSineValues(Scene):
def construct(self):
angle_tracker = ValueTracker(60 * DEGREES)
get_angle = angle_tracker.get_value
formula = always_redraw(
lambda: self.get_sine_formula(get_angle())
)
self.add(formula)
self.play(
angle_tracker.set_value, 0,
run_time=3,
)
self.wait()
self.play(
angle_tracker.set_value, 90 * DEGREES,
run_time=3,
)
self.wait()
def get_sine_formula(self, angle):
sin, lp, rp = OldTex(
"\\sin", "(", ") = "
)
input_part = Integer(
angle / DEGREES,
unit="^\\circ",
)
input_part.set_color(YELLOW)
output_part = DecimalNumber(
np.sin(input_part.get_value() * DEGREES),
num_decimal_places=3,
)
result = VGroup(
sin, lp, input_part, rp, output_part
)
result.arrange(RIGHT, buff=SMALL_BUFF)
sin.scale(1.1, about_edge=DOWN)
lp.align_to(rp, UP)
return result
class SetAsideSeekingSolution(Scene):
def construct(self):
ode = get_ode()
ode.to_edge(UP)
q1 = OldTexText("Find an exact solution")
q1.set_color(YELLOW)
q2 = OldTex(
"\\text{What is }", "\\theta", "(t)",
"\\text{'s personality?}",
tex_to_color_map={"\\theta": BLUE},
arg_separator="",
)
theta = q2.get_part_by_tex("\\theta")
for q in q1, q2:
q.scale(1.5)
q.next_to(ode, DOWN, MED_LARGE_BUFF)
eyes = Eyes(theta, height=0.1)
self.add(ode)
self.add(q1)
self.wait()
self.play(
q1.scale, 0.3,
q1.to_corner, UR, MED_SMALL_BUFF,
)
self.play(FadeIn(q2, DOWN))
self.play(
eyes.blink,
rate_func=lambda t: smooth(1 - t),
)
self.play(eyes.look_at, q2.get_left())
self.play(eyes.look_at, q2.get_right())
self.play(
eyes.blink,
rate_func=squish_rate_func(there_and_back)
)
self.wait()
self.play(
eyes.change_mode, "confused",
eyes.look_at, ode.get_left(),
)
self.play(
eyes.blink,
rate_func=squish_rate_func(there_and_back)
)
class ThreeBodyTitle(Scene):
def construct(self):
title = OldTexText("Three body problem")
title.scale(1.5)
title.to_edge(UP)
self.add(title)
class ThreeBodySymbols(Scene):
def construct(self):
self.init_coord_groups()
self.introduce_coord_groups()
self.count_coords()
def init_coord_groups(self):
kwargs = {
"bracket_v_buff": 2 * SMALL_BUFF
}
positions = VGroup(*[
get_vector_symbol(*[
"{}_{}".format(s, i)
for s in "xyz"
], **kwargs)
for i in range(1, 4)
])
velocities = VGroup(*[
get_vector_symbol(*[
"p^{}_{}".format(s, i)
for s in "xyz"
], **kwargs)
for i in range(1, 4)
])
groups = VGroup(positions, velocities)
colors = [GREEN, RED, BLUE]
for group in groups:
for matrix in group:
matrix.coords = matrix.get_entries()
for coord, color in zip(matrix.coords, colors):
coord.set_color(color)
group.arrange(RIGHT)
groups.arrange(DOWN, buff=LARGE_BUFF)
groups.to_edge(LEFT)
self.coord_groups = groups
def introduce_coord_groups(self):
groups = self.coord_groups
x_group, p_group = groups
x_word = OldTexText("Positions")
p_word = OldTexText("Momenta")
words = VGroup(x_word, p_word)
for word, group in zip(words, groups):
word.next_to(group, UP)
rect_groups = VGroup()
for group in groups:
rect_group = VGroup(*[
SurroundingRectangle(
VGroup(*[
tm.coords[i]
for tm in group
]),
color=WHITE,
stroke_width=2,
)
for i in range(3)
])
rect_groups.add(rect_group)
self.play(
*[
LaggedStartMap(
FadeInFrom, group,
lambda m: (m, UP),
run_time=1,
)
for group in groups
],
*map(FadeInFromDown, words),
)
for rect_group in rect_groups:
self.play(
ShowCreationThenFadeOut(
rect_group,
lag_ratio=0.5,
)
)
self.wait()
def count_coords(self):
coord_copies = VGroup()
for group in self.coord_groups:
for tex_mob in group:
for coord in tex_mob.coords:
coord_copy = coord.copy()
coord_copy.set_stroke(
WHITE, 2, background=True
)
coord_copies.add(coord_copy)
count = Integer()
count_word = OldTexText("18", "degrees \\\\ of freedom")[1]
count_group = VGroup(count, count_word)
count_group.arrange(
RIGHT,
aligned_edge=DOWN,
)
count_group.scale(1.5)
count_group.next_to(
self.coord_groups, RIGHT,
aligned_edge=DOWN,
)
count.add_updater(
lambda m: m.set_value(len(coord_copies))
)
count.add_updater(
lambda m: m.next_to(count_word[0][0], LEFT, aligned_edge=DOWN)
)
self.add(count_group)
self.play(
# ChangeDecimalToValue(count, len(coord_copies)),
ShowIncreasingSubsets(coord_copies),
run_time=1.5,
rate_func=linear,
)
self.play(FadeOut(coord_copies))
class ThreeBodyEquation(Scene):
def construct(self):
x1 = "\\vec{\\textbf{x}}_1"
x2 = "\\vec{\\textbf{x}}_2"
x3 = "\\vec{\\textbf{x}}_3"
kw = {
"tex_to_color_map": {
x1: RED,
x2: GREEN,
x3: BLUE,
}
}
equations = VGroup(*[
OldTex(
"{d^2", t1, "\\over dt^2}", "=",
"G", "\\left("
"{" + m2, "(", t2, "-", t1, ")"
"\\over"
"||", t2, "-", t1, "||^3}",
"+",
"{" + m3, "(", t3, "-", t1, ")"
"\\over"
"||", t3, "-", t1, "||^3}",
"\\right)",
**kw
)
for t1, t2, t3, m1, m2, m3 in [
(x1, x2, x3, "m_1", "m_2", "m_3"),
(x2, x3, x1, "m_2", "m_3", "m_1"),
(x3, x1, x2, "m_3", "m_1", "m_2"),
]
])
equations.arrange(DOWN, buff=LARGE_BUFF)
self.play(LaggedStartMap(
FadeInFrom, equations,
lambda m: (m, UP),
lag_ratio=0.2,
))
self.wait()
class JumpToThisPoint(Scene):
def construct(self):
dot = Dot(color=YELLOW)
dot.scale(0.5)
arrow = Vector(DR, color=WHITE)
arrow.next_to(dot, UL, SMALL_BUFF)
words = OldTexText(
"Jump directly to\\\\",
"this point?",
)
words.add_background_rectangle_to_submobjects()
words.next_to(arrow.get_start(), UP, SMALL_BUFF)
self.play(
FadeInFromLarge(dot, 20),
rate_func=rush_into,
)
self.play(
GrowArrow(arrow),
FadeInFromDown(words),
)
class ChaosTitle(Scene):
def construct(self):
title = OldTexText("Chaos theory")
title.scale(1.5)
title.to_edge(UP)
line = Line(LEFT, RIGHT)
line.set_width(FRAME_WIDTH - 1)
line.next_to(title, DOWN)
self.play(
Write(title),
ShowCreation(line),
)
self.wait()
class RevisitQuote(StrogatzQuote, PiCreatureScene):
def construct(self):
quote = self.get_quote()
quote.law_part.set_color(YELLOW)
quote.language_part.set_color(BLUE)
quote.set_stroke(BLACK, 6, background=True)
quote.scale(0.8, about_edge=UL)
new_langauge_part = OldTexText(
"\\Large Language of differential equations"
)
new_langauge_part.to_edge(UP)
new_langauge_part.match_style(quote.language_part)
randy = self.pi_creature
self.play(
FadeIn(quote[:-1], DOWN),
FadeIn(quote[-1:], LEFT),
randy.change, "raise_right_hand",
)
self.play(Blink(randy))
self.play(randy.change, "angry")
self.play(
Blink(randy),
VFadeOut(randy, run_time=3)
)
mover = VGroup(quote.language_part)
self.add(quote, mover)
self.play(
ReplacementTransform(
mover, new_langauge_part,
),
*[
FadeOut(part)
for part in quote
if part is not quote.language_part
],
run_time=2,
)
self.wait()
class EndScreen(PatreonEndScreen):
CONFIG = {
"specific_patrons": [
"Juan Benet",
"Vassili Philippov",
"Burt Humburg",
"Carlos Vergara Del Rio",
"Matt Russell",
"Scott Gray",
"soekul",
"Tihan Seale",
"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",
"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",
"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 Clark",
"DeathByShrimp",
"Delton Ding",
"eaglle",
"emptymachine",
"Eric Younge",
"Eryq Ouithaqueue",
"Federico Lebron",
"Giovanni Filippi",
"Hal Hildebrand",
"Herman Dieset",
"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 Redden",
"Linh Tran",
"Ludwig Schubert",
"Magister Mugit",
"Mark B Bahu",
"Mark Heising",
"Martin Price",
"Mathias Jansson",
"Matt Langford",
"Matt Roveto",
"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",
"Samuel D. Judge",
"Solara570",
"Stevie Metke",
"Tal Einav",
"Ted Suzman",
"Valeriy Skobelev",
"Xavier Bernard",
"Yavor Ivanov",
"Yaw Etse",
"YinYangBalance.Asia",
"Zach Cardwell",
]
}
|
|
from manim_imports_ext import *
T_COLOR = GREY_B
VELOCITY_COLOR = GREEN
POSITION_COLOR = BLUE
CONST_COLOR = YELLOW
tex_config = {
"tex_to_color_map": {
"{t}": T_COLOR,
"{0}": T_COLOR,
"e^": WHITE,
"=": WHITE,
}
}
class IntroductionOfExp(Scene):
def construct(self):
questions = VGroup(
OldTexText("What", "is", "$e^{t}$", "?"),
OldTexText("What", "properties", "does", "$e^{t}$", "have?"),
OldTexText(
"What", "property", "defines", "$e^{t}$", "?",
tex_to_color_map={"defines": BLUE}
),
)
questions.scale(2)
questions[0].next_to(questions[1], UP, LARGE_BUFF)
questions[2][-1].next_to(questions[2][-2], RIGHT, SMALL_BUFF)
questions.to_edge(UP)
for question in questions:
part = question.get_part_by_tex("e^{t}")
part[1].set_color(T_COLOR)
top_cross = Cross(questions[0])
deriv_ic = self.get_deriv_and_ic()
deriv_ic.save_state()
deriv_ic.scale(2 / 1.5)
deriv_ic.to_edge(DOWN, buff=LARGE_BUFF)
derivative, ic = deriv_ic
derivative.save_state()
derivative.set_x(0)
self.play(FadeInFromDown(questions[0]))
self.wait()
self.play(
ShowCreation(top_cross),
LaggedStart(
*[
TransformFromCopy(
questions[0].get_part_by_tex(tex),
questions[1].get_part_by_tex(tex),
)
for tex in ("What", "e^{t}")
],
*[
FadeIn(questions[1][i])
for i in [1, 2, 4]
]
)
)
self.wait()
self.play(
TransformFromCopy(
questions[1].get_part_by_tex("$e^{t}$"),
derivative[3:7],
),
FadeIn(derivative[:2]),
FadeIn(derivative.get_part_by_tex("=")),
)
self.play(
ReplacementTransform(
questions[1][0],
questions[2][0],
),
FadeOut(questions[1][1]),
FadeIn(questions[2][1]),
FadeOut(questions[1][2]),
FadeIn(questions[2][2]),
ReplacementTransform(
questions[1][3],
questions[2][3],
),
FadeOut(questions[1][4]),
FadeIn(questions[2][4]),
)
self.wait()
self.play(
TransformFromCopy(
derivative[3:7:3],
derivative[-5:],
path_arc=-60 * DEGREES,
),
)
self.wait()
self.play(
Restore(derivative),
FadeIn(ic, LEFT)
)
self.wait()
self.play(
FadeOut(questions[0]),
FadeOut(top_cross),
FadeOut(questions[2]),
Restore(deriv_ic),
)
self.wait()
def get_deriv_and_ic(self, const=None):
if const:
const_str = "{" + str(const) + "}"
mult_str = "\\cdot"
else:
const_str = "{}"
mult_str = "{}"
args = [
"{d \\over d{t}}",
"e^{",
const_str,
"{t}}",
"=",
const_str,
mult_str,
"e^{",
const_str,
"{t}}"
]
derivative = OldTex(
*args,
**tex_config
)
if const:
derivative.set_color_by_tex(const_str, CONST_COLOR)
ic = OldTex("e^{0} = 1", **tex_config)
group = VGroup(derivative, ic)
group.arrange(RIGHT, buff=LARGE_BUFF)
ic.align_to(derivative.get_part_by_tex("e^"), DOWN)
group.scale(1.5)
group.to_edge(UP)
return group
class IntroducePhysicalModel(IntroductionOfExp):
CONFIG = {
"number_line_config": {
"x_min": 0,
"x_max": 100,
"unit_size": 1.5,
"numbers_with_elongated_ticks": [0],
"numbers_to_show": list(range(0, 15)),
"label_direction": UP,
},
"number_line_y": -2,
"const": 1,
"const_str": "",
"num_decimal_places": 2,
"output_label_config": {
"show_ellipsis": True,
},
}
def construct(self):
self.setup_number_line()
self.setup_movers()
self.show_number_line()
self.show_formulas()
self.let_time_pass()
def setup_number_line(self):
nl = self.number_line = NumberLine(
**self.number_line_config,
)
nl.to_edge(LEFT)
nl.set_y(self.number_line_y)
nl.add_numbers()
def setup_movers(self):
self.setup_value_trackers()
self.setup_vectors()
self.setup_vector_labels()
self.setup_tip()
self.setup_tip_label()
self.setup_output_label()
def setup_value_trackers(self):
number_line = self.number_line
input_tracker = ValueTracker(0)
get_input = input_tracker.get_value
def complex_number_to_point(z):
zero = number_line.n2p(0)
unit = number_line.n2p(1) - zero
perp = rotate_vector(unit, TAU / 4)
z = complex(z)
return zero + unit * z.real + perp * z.imag
number_line.cn2p = complex_number_to_point
def get_output():
return np.exp(self.const * get_input())
def get_output_point():
return number_line.n2p(get_output())
output_tracker = ValueTracker(1)
output_tracker.add_updater(
lambda m: m.set_value(get_output())
)
self.get_input = get_input
self.get_output = get_output
self.get_output_point = get_output_point
self.add(
input_tracker,
output_tracker,
)
self.input_tracker = input_tracker
self.output_tracker = output_tracker
def setup_tip(self):
tip = ArrowTip(start_angle=-PI / 2)
tip.set_height(0.6)
tip.set_width(0.1, stretch=True)
tip.add_updater(lambda m: m.move_to(
self.get_output_point(), DOWN
))
# tip.set_color(WHITE)
tip.set_fill(GREY, 1)
self.tip = tip
def setup_tip_label(self):
tip = self.tip
const_str = self.const_str
ndp = self.num_decimal_places
args = ["e^{"]
if const_str:
args += [const_str, "\\cdot"]
args += ["0." + ndp * "0"]
tip_label = OldTex(*args, arg_separator="")
if const_str:
tip_label[1].set_color(CONST_COLOR)
template_decimal = tip_label[-1]
# parens = tip_label[-3::2]
template_decimal.set_opacity(0)
tip_label.add_updater(lambda m: m.next_to(
tip, UP,
buff=2 * SMALL_BUFF,
index_of_submobject_to_align=0
))
decimal = DecimalNumber(num_decimal_places=ndp)
decimal.set_color(T_COLOR)
decimal.match_height(template_decimal)
decimal.add_updater(lambda m: m.set_value(self.get_input()))
decimal.add_updater(
lambda m: m.move_to(template_decimal, LEFT)
)
tip_label.add(decimal)
self.tip_label = tip_label
def setup_output_label(self):
label = VGroup(
OldTex("="),
DecimalNumber(1, **self.output_label_config)
)
label.set_color(POSITION_COLOR)
label.add_updater(
lambda m: m[1].set_value(
self.get_output()
)
)
label.add_updater(
lambda m: m.arrange(RIGHT, buff=SMALL_BUFF)
)
label.add_updater(
lambda m: m.next_to(
self.tip_label, RIGHT,
buff=SMALL_BUFF,
aligned_edge=DOWN,
)
)
self.output_label = label
def setup_vectors(self):
number_line = self.number_line
position_vect = Vector(color=POSITION_COLOR)
velocity_vect = Vector(color=VELOCITY_COLOR)
position_vect.add_updater(
lambda m: m.put_start_and_end_on(
number_line.cn2p(0),
number_line.cn2p(self.get_output()),
)
)
def update_velocity_vect(vect):
vect.put_start_and_end_on(
number_line.cn2p(0),
number_line.cn2p(self.const * self.get_output())
)
vect.shift(
number_line.cn2p(self.get_output()) - number_line.n2p(0)
)
return vect
velocity_vect.add_updater(update_velocity_vect)
self.position_vect = position_vect
self.velocity_vect = velocity_vect
def setup_vector_labels(self):
position_vect = self.position_vect
velocity_vect = self.velocity_vect
max_width = 1.5
p_label = OldTexText("Position")
p_label.set_color(POSITION_COLOR)
p_label.vect = position_vect
v_label = OldTexText("Velocity")
v_label.set_color(VELOCITY_COLOR)
v_label.vect = velocity_vect
# for label in [p_label, v_label]:
# label.add_background_rectangle()
def update_label(label):
label.set_width(min(
max_width,
0.8 * label.vect.get_length(),
))
direction = normalize(label.vect.get_vector())
perp_direction = rotate_vector(direction, -TAU / 4)
label.next_to(
label.vect.get_center(),
np.round(perp_direction),
buff=MED_SMALL_BUFF,
)
p_label.add_updater(update_label)
v_label.add_updater(update_label)
self.position_label = p_label
self.velocity_label = v_label
def show_number_line(self):
number_line = self.number_line
self.play(
LaggedStartMap(
FadeIn,
number_line.numbers.copy(),
remover=True,
),
Write(number_line),
run_time=2
)
self.wait()
def show_formulas(self):
deriv, ic = self.get_deriv_and_ic()
eq_index = deriv.index_of_part_by_tex("=")
lhs = deriv[:eq_index - 1]
rhs = deriv[eq_index + 1:]
rhs_rect = SurroundingRectangle(rhs)
lhs_rect = SurroundingRectangle(lhs)
rects = VGroup(rhs_rect, lhs_rect)
rhs_rect.set_stroke(POSITION_COLOR, 2)
lhs_rect.set_stroke(VELOCITY_COLOR, 2)
rhs_word = OldTexText("Position")
lhs_word = OldTexText("Velocity")
words = VGroup(rhs_word, lhs_word)
for word, rect in zip(words, rects):
word.match_color(rect)
word.next_to(rect, DOWN)
self.add(deriv, ic)
self.play(
ShowCreation(rhs_rect),
FadeIn(rhs_word, UP),
ShowCreation(self.position_vect)
)
self.add(
self.tip,
self.number_line,
self.position_vect,
)
self.number_line.numbers.set_stroke(BLACK, 3, background=True)
self.play(
Transform(
rhs.copy(),
self.tip_label.copy().clear_updaters(),
remover=True,
),
GrowFromPoint(self.tip, rhs.get_bottom()),
TransformFromCopy(rhs_word, self.position_label),
)
self.add(self.tip_label)
self.wait()
self.play(
ShowCreation(lhs_rect),
FadeIn(lhs_word, UP),
)
self.wait()
self.play(
TransformFromCopy(
self.position_vect,
self.velocity_vect,
path_arc=PI,
)
)
self.play(
TransformFromCopy(
lhs_word,
self.velocity_label,
)
)
self.wait()
def let_time_pass(self):
# Sort of a quick and dirty implementation,
# not the best for reusability
rate = 0.25
t_tracker = self.input_tracker
t_tracker.add_updater(
lambda m, dt: m.increment_value(rate * dt)
)
nl = self.number_line
zero_point = nl.n2p(0)
nl_copy = nl.copy()
nl_copy.submobjects = []
nl_copy.stretch(100, 0, about_point=zero_point)
nl.add(nl_copy)
# For first zoom
xs1 = range(25, 100, 25)
nl.add(*[
nl.get_tick(x, size=1.5)
for x in xs1
])
nl.add_numbers(
*xs1,
buff=2,
height=5,
)
# For second zoom
xs2 = range(200, 1000, 200)
nl.add(*[
nl.get_tick(x, size=15)
for x in xs2
])
nl.add_numbers(
*xs2,
height=50,
buff=20,
)
# For third zoom
xs3 = range(2000, 10000, 2000)
nl.add(*[
nl.get_tick(x, size=150)
for x in xs3
])
nl.add_numbers(
*xs3,
height=300,
buff=200,
)
for n in nl.numbers:
n[1].scale(0.5)
self.add(self.tip)
self.add(self.output_label)
self.play(VFadeIn(self.output_label))
self.wait(5)
self.play(
nl.scale, 0.1, {"about_point": zero_point},
run_time=1,
)
self.wait(6)
self.play(
nl.scale, 0.1, {"about_point": zero_point},
run_time=1,
)
self.wait(8)
self.play(
nl.scale, 0.1, {"about_point": zero_point},
run_time=1,
)
self.wait(12)
class ConstantEquals2(IntroducePhysicalModel):
CONFIG = {
"const": 2,
"const_str": "2",
"const_text": "Double",
}
def construct(self):
self.setup_number_line()
self.setup_movers()
self.add_initial_objects()
self.point_out_chain_rule()
self.show_double_vector()
self.let_time_pass()
def add_initial_objects(self):
deriv, ic = self.get_deriv_and_ic(
const=self.const
)
self.deriv = deriv
self.ic = ic
self.add(ic)
self.add(self.tip)
self.add(self.number_line)
self.add(self.position_vect)
self.add(self.position_label)
self.add(self.tip_label)
def point_out_chain_rule(self):
deriv = self.deriv
eq = deriv.get_part_by_tex("=")
dot = deriv.get_part_by_tex("\\cdot")
eq_index = deriv.index_of_part(eq)
dot_index = deriv.index_of_part(dot)
v_part = deriv[:eq_index - 1]
c_part = deriv[eq_index + 1: dot_index]
p_part = deriv[dot_index + 1:]
parts = VGroup(v_part, c_part, p_part)
rects = VGroup(*map(SurroundingRectangle, parts))
words = VGroup(*map(TexText, [
"Velocity", self.const_text, "Position"
]))
colors = [VELOCITY_COLOR, CONST_COLOR, POSITION_COLOR]
for rect, word, color in zip(rects, words, colors):
rect.set_stroke(color, 2)
word.set_color(color)
word.next_to(rect, DOWN)
v_rect, c_rect, p_rect = rects
v_word, c_word, p_word = words
self.readjust_const_label(c_word, c_rect)
self.add(v_part, eq)
self.add(v_rect, v_word)
p_part.save_state()
p_part.replace(v_part[-4:])
c_part.save_state()
c_part.replace(p_part.saved_state[2])
self.play(ShowCreationThenFadeAround(
v_part[-2],
surrounding_rectangle_config={
"color": CONST_COLOR
},
))
self.wait()
self.play(
Restore(p_part, path_arc=-TAU / 6),
FadeIn(p_rect),
FadeIn(p_word),
)
self.play(
Restore(c_part, path_arc=TAU / 6),
FadeIn(dot)
)
self.play(
FadeIn(c_rect),
FadeIn(c_word),
)
self.wait()
self.v_word = v_word
def show_double_vector(self):
v_vect = self.velocity_vect
p_vect = self.position_vect
p_copy = p_vect.copy()
p_copy.clear_updaters()
p_copy.generate_target()
p_copy.target.shift(2 * UR)
times_2 = OldTex("\\times", "2")
times_2.set_color_by_tex("2", CONST_COLOR)
times_2.next_to(p_copy.target.get_end(), UP, MED_SMALL_BUFF)
self.play(
MoveToTarget(p_copy),
FadeIn(times_2),
)
self.play(
p_copy.scale, 2, {"about_edge": LEFT},
p_copy.match_color, v_vect,
)
self.play(FadeOut(times_2))
self.play(
ReplacementTransform(p_copy, v_vect),
TransformFromCopy(
self.v_word,
self.velocity_label,
)
)
self.wait()
def let_time_pass(self):
# Largely copying from the above scene.
# Note to self: If these are reused anymore,
# factor this out properly
rate = 0.25
t_tracker = self.input_tracker
t_tracker.add_updater(
lambda m, dt: m.increment_value(rate * dt)
)
nl = self.number_line
zero_point = nl.n2p(0)
nl_copy = nl.copy()
nl_copy.submobjects = []
nl_copy.stretch(1000, 0, about_point=zero_point)
nl.add(nl_copy)
# For first zoom
xs1 = range(25, 100, 25)
nl.add(*[
nl.get_tick(x, size=1.5)
for x in xs1
])
nl.add_numbers(
*xs1,
buff=2,
height=5,
)
# For second zoom
xs2 = range(200, 1000, 200)
nl.add(*[
nl.get_tick(x, size=15)
for x in xs2
])
nl.add_numbers(
*xs2,
buff=20,
height=50,
)
# For third zoom
xs3 = range(2000, 10000, 2000)
nl.add(*[
nl.get_tick(x, size=150)
for x in xs3
])
nl.add_numbers(
*xs3,
buff=200,
height=300,
)
for n in nl.numbers:
n[1].scale(0.5)
# For fourth zoom
xs3 = range(20000, 100000, 20000)
nl.add(*[
nl.get_tick(x, size=1500)
for x in xs3
])
nl.add_numbers(
*xs3,
buff=2000,
height=3000,
)
for n in nl.numbers:
n[2].scale(0.5)
self.add(self.tip)
self.add(self.output_label)
self.play(VFadeIn(self.output_label))
for x in range(4):
self.wait_until(
lambda: self.position_vect.get_end()[0] > 0
)
self.play(
nl.scale, 0.1, {"about_point": zero_point},
run_time=1,
)
self.wait(5)
#
def readjust_const_label(self, c_word, c_rect):
c_rect.stretch(1.2, 1, about_edge=DOWN)
c_word.next_to(c_rect, UP)
class NegativeConstant(ConstantEquals2):
CONFIG = {
"const": -0.5,
"const_str": "-0.5",
"const_text": "Flip and squish",
"number_line_config": {
"unit_size": 2.5,
}
}
def construct(self):
self.setup_number_line()
self.setup_movers()
self.add_initial_objects()
self.point_out_chain_rule()
self.show_vector_manipulation()
self.let_time_pass()
def show_vector_manipulation(self):
p_vect = self.position_vect
v_vect = self.velocity_vect
p_copy = p_vect.copy()
p_copy.clear_updaters()
p_copy.generate_target()
p_copy.target.shift(5 * RIGHT + 2 * UP)
times_neg1 = OldTex("\\times", "(\\cdot 1)")
temp_neg = times_neg1[1][-3]
neg = OldTex("-")
neg.set_width(0.2, stretch=True)
neg.move_to(temp_neg)
temp_neg.become(neg)
times_point5 = OldTex("\\times", "0.5")
terms = VGroup(times_neg1, times_point5)
for term in terms:
term[1].set_color(CONST_COLOR)
terms.arrange(LEFT, buff=SMALL_BUFF)
terms.next_to(p_copy.target.get_start(), UP)
v_vect.add_updater(
lambda m: m.shift(SMALL_BUFF * UP)
)
self.velocity_label.add_updater(
lambda m: m.next_to(
self.velocity_vect,
UP, buff=SMALL_BUFF,
)
)
v_vect_back = v_vect.copy()
v_vect_back.set_stroke(BLACK, 3)
self.play(
MoveToTarget(p_copy),
FadeIn(times_neg1),
)
self.play(
Rotate(
p_copy,
angle=PI,
about_point=p_copy.get_start(),
)
)
self.wait()
self.play(
p_copy.scale, 0.5,
{"about_point": p_copy.get_start()},
p_copy.match_color, v_vect,
FadeIn(times_point5)
)
self.wait()
self.play(
ReplacementTransform(p_copy, v_vect),
FadeOut(terms),
TransformFromCopy(
self.v_word,
self.velocity_label,
),
)
self.add(v_vect_back, v_vect)
self.add(self.velocity_label)
def let_time_pass(self):
nl = self.number_line
t_tracker = self.input_tracker
zero_point = nl.n2p(0)
scale_factor = 4.5
nl.generate_target(use_deepcopy=True)
nl.target.scale(scale_factor, about_point=zero_point)
for tick in [*nl.target.tick_marks, *nl.target.big_tick_marks]:
tick.scale(1 / scale_factor)
nl.target.tick_marks[1].scale(2)
for number in nl.target.numbers:
number.scale(1.5 / scale_factor, about_edge=DOWN)
number.align_to(zero_point + 0.3 * UP, DOWN)
new_ticks = VGroup(*[
nl.get_tick(x)
for x in np.arange(0.1, 1.5, 0.1)
])
self.play(
MoveToTarget(nl),
new_ticks.stretch, scale_factor, 0,
{"about_point": zero_point},
VFadeIn(new_ticks),
)
self.wait()
rate = 0.25
t_tracker.add_updater(
lambda m, dt: m.increment_value(rate * dt)
)
self.play(VFadeIn(self.output_label))
self.wait(20)
#
def readjust_const_label(self, c_word, c_rect):
super().readjust_const_label(c_word, c_rect)
c_word.shift(SMALL_BUFF * DOWN)
c_word.shift(MED_SMALL_BUFF * RIGHT)
class ImaginaryConstant(ConstantEquals2):
CONFIG = {
"const": complex(0, 1),
"const_str": "i",
"const_text": "Rotate $90^\\circ$",
"number_line_config": {
"x_min": -5,
"unit_size": 2.5,
},
"output_label_config": {
"show_ellipsis": False,
},
"plane_unit_size": 2.5,
}
def construct(self):
self.setup_number_line()
self.setup_movers()
self.add_initial_objects()
self.show_vector_manipulation()
self.transition_to_complex_plane()
self.show_vector_field()
self.show_circle()
def setup_number_line(self):
super().setup_number_line()
nl = self.number_line
nl.shift(nl.n2p(-5) - nl.n2p(0))
nl.shift(0.5 * DOWN)
shift_distance = (4 * nl.tick_size + nl.numbers.get_height() + SMALL_BUFF)
nl.numbers.shift(shift_distance * DOWN)
def add_initial_objects(self):
deriv, ic = self.get_deriv_and_ic("i")
VGroup(deriv, ic).shift(0.5 * DOWN)
ic.shift(RIGHT)
self.deriv = deriv
self.ic = ic
self.add(self.number_line)
self.add(self.position_vect)
self.add(self.position_label)
# self.tip_label.clear_updaters()
self.tip_label.shift_vect = VectorizedPoint(0.2 * UP)
self.tip_label.add_updater(
lambda m: m.next_to(
self.position_vect.get_end(), UP,
buff=0,
index_of_submobject_to_align=0,
).shift(m.shift_vect.get_location())
)
eq = deriv.get_part_by_tex("=")
dot = deriv.get_part_by_tex("\\cdot")
eq_index = deriv.index_of_part(eq)
dot_index = deriv.index_of_part(dot)
v_term = deriv[:eq_index - 1]
c_term = deriv[eq_index + 1: dot_index]
p_term = deriv[dot_index + 1:]
terms = VGroup(v_term, c_term, p_term)
rects = VGroup(*map(SurroundingRectangle, terms))
colors = [VELOCITY_COLOR, CONST_COLOR, POSITION_COLOR]
labels = VGroup(*map(
TexText,
["Velocity", self.const_text, "Position"]
))
for rect, color, label in zip(rects, colors, labels):
rect.set_stroke(color, 2)
label.set_color(color)
label.next_to(rect, DOWN)
v_label, c_label, p_label = labels
v_rect, c_rect, p_rect = rects
self.term_rects = rects
self.term_labels = labels
randy = Randolph()
randy.next_to(deriv, DOWN, LARGE_BUFF)
point = VectorizedPoint(p_term.get_center())
randy.add_updater(lambda r: r.look_at(point))
self.play(
FadeInFromDown(p_term),
VFadeIn(randy),
)
self.play(randy.change, "confused")
self.play(
ShowCreation(p_rect),
FadeIn(p_label, UP)
)
self.add(self.number_line, self.position_vect)
self.play(
Transform(
p_label.copy(),
self.tip_label.copy().clear_updaters(),
remover=True,
),
point.move_to, self.position_vect.get_end(),
FadeIn(ic),
)
self.add(self.tip_label)
self.play(Blink(randy))
self.play(FadeOut(randy))
# Velocity
self.play(
LaggedStartMap(FadeIn, [
v_term, eq, v_rect, v_label,
]),
run_time=1
)
c_term.save_state()
c_term.replace(p_term[2])
self.play(
Restore(c_term, path_arc=TAU / 4),
FadeIn(dot),
)
c_rect.stretch(1.2, 1, about_edge=DOWN)
c_label.next_to(c_rect, UP)
c_label.shift(0.5 * RIGHT)
self.c_rect = c_rect
self.c_label = c_label
self.v_label = v_label
def show_vector_manipulation(self):
p_vect = self.position_vect
v_vect = self.velocity_vect
p_copy = p_vect.copy()
p_copy.clear_updaters()
p_copy.generate_target()
p_copy.target.center()
p_copy.target.shift(1.5 * DOWN)
rot_p = p_copy.target.copy()
rot_p.rotate(TAU / 4, about_point=rot_p.get_start())
rot_p.match_style(v_vect)
arc = Arc(
angle=TAU / 4,
radius=0.5,
arc_center=p_copy.target.get_start(),
)
arc.add_tip(tip_length=0.1)
angle_label = OldTex("90^\\circ")
angle_label.scale(0.5)
angle_label.next_to(arc.point_from_proportion(0.5), UR, SMALL_BUFF)
times_i = OldTex("\\times", "i")
times_i.set_color_by_tex("i", CONST_COLOR)
times_i.next_to(p_copy.target, UP, buff=0)
rot_v_label = OldTexText("Velocity")
rot_v_label.set_color(VELOCITY_COLOR)
rot_v_label.add_background_rectangle()
rot_v_label.scale(0.8)
rot_v_label.curr_angle = 0
def update_rot_v_label(label):
label.rotate(-label.curr_angle)
label.next_to(ORIGIN, DOWN, 2 * SMALL_BUFF)
# angle = PI + self.velocity_vect.get_angle()
angle = 0
label.rotate(angle, about_point=ORIGIN)
label.curr_angle = angle
# label.shift(self.velocity_vect.get_center())
label.next_to(
self.velocity_vect.get_end(),
RIGHT,
buff=SMALL_BUFF
)
rot_v_label.add_updater(update_rot_v_label)
self.play(
MoveToTarget(p_copy),
FadeIn(times_i),
)
self.play(
FadeIn(self.c_rect),
FadeInFromDown(self.c_label),
)
self.play(
ShowCreation(arc),
FadeIn(angle_label),
ApplyMethod(
times_i.next_to, rot_p, RIGHT, {"buff": 0},
path_arc=TAU / 4,
),
TransformFromCopy(
p_copy, rot_p,
path_arc=-TAU / 4,
),
)
self.wait()
temp_rot_v_label = rot_v_label.copy()
temp_rot_v_label.clear_updaters()
temp_rot_v_label.replace(self.v_label, dim_to_match=0)
self.play(
TransformFromCopy(rot_p, v_vect),
TransformFromCopy(temp_rot_v_label, rot_v_label),
self.tip_label.shift_vect.move_to, 0.1 * UP + 0.2 * RIGHT,
)
self.play(FadeOut(VGroup(
p_copy, arc, angle_label,
times_i, rot_p,
)))
self.velocity_label = rot_v_label
def transition_to_complex_plane(self):
nl = self.number_line
background_rects = VGroup(*[
BackgroundRectangle(rect)
for rect in self.term_rects
])
self.ic.add_background_rectangle()
for label in self.term_labels:
label.add_background_rectangle()
corner_group = VGroup(
background_rects,
self.deriv,
self.term_rects,
self.term_labels,
self.ic,
)
corner_group.generate_target()
corner_group.target.to_corner(UL)
corner_group.target[-1].next_to(
corner_group.target, DOWN,
buff=0.75,
aligned_edge=LEFT
)
plane = ComplexPlane()
plane.unit_size = self.plane_unit_size
plane.scale(plane.unit_size)
plane.add_coordinates()
plane.shift(DOWN + 0.25 * RIGHT)
nl.generate_target(use_deepcopy=True)
nl.target.numbers.set_opacity(0)
nl.target.scale(
plane.unit_size / nl.unit_size
)
nl.target.shift(plane.n2p(0) - nl.target.n2p(0))
plane_title = OldTexText("Complex plane")
plane_title.set_stroke(BLACK, 3, background=True)
plane_title.scale(2)
plane_title.to_corner(UR)
self.add(
plane,
corner_group,
self.position_vect,
self.velocity_vect,
self.position_label,
self.velocity_label,
self.tip_label,
)
plane.save_state()
plane.set_opacity(0)
self.play(
VFadeIn(background_rects),
MoveToTarget(corner_group),
MoveToTarget(nl),
)
self.play(
Restore(plane, lag_ratio=0.01),
FadeInFromDown(plane_title)
)
self.play(FadeOut(nl))
self.play(FadeOut(plane_title))
self.wait()
self.plane = plane
self.corner_group = corner_group
def show_vector_field(self):
plane = self.plane
temp_faders = VGroup(
self.position_vect,
self.position_label,
self.velocity_vect,
self.velocity_label,
self.tip_label,
)
foreground = VGroup(
self.corner_group,
)
# Initial examples
n = 12
zs = [
np.exp(complex(0, k * TAU / n))
for k in range(n)
]
points = map(plane.n2p, zs)
vects = VGroup(*[
Arrow(
plane.n2p(0), point,
buff=0,
color=POSITION_COLOR,
)
for point in points
])
vects.set_opacity(0.75)
attached_vects = VGroup(*[
vect.copy().shift(vect.get_vector())
for vect in vects
])
attached_vects.set_color(VELOCITY_COLOR)
v_vects = VGroup(*[
av.copy().rotate(
90 * DEGREES,
about_point=av.get_start()
)
for av in attached_vects
])
self.play(
LaggedStartMap(GrowArrow, vects),
FadeOut(temp_faders),
)
self.wait()
self.play(
TransformFromCopy(
vects, attached_vects,
path_arc=20 * DEGREES,
)
)
self.play(
ReplacementTransform(
attached_vects,
v_vects,
path_arc=90 * DEGREES,
)
)
self.wait()
# Vector fields
zero_point = plane.n2p(0)
def func(p):
vect = p - zero_point
return rotate_vector(vect, 90 * DEGREES)
vf_config = {
# "x_min": plane.n2p(-3)[0],
# "x_max": plane.n2p(3)[0],
# "y_min": plane.c2p(0, -2)[1],
# "y_max": plane.c2p(0, 2)[1],
"max_magnitude": 8,
"opacity": 0.5,
}
vf0 = VectorField(
lambda p: np.array(p) - zero_point,
length_func=lambda x: x,
# opacity=0.5,
**vf_config,
)
vf1 = VectorField(
func,
length_func=lambda x: x,
# opacity=0.5,
**vf_config,
)
vf2 = VectorField(
func,
**vf_config,
)
for vf in [vf0, vf1, vf2]:
vf.submobjects.sort(
key=lambda m: get_norm(m.get_start())
)
self.play(
FadeIn(vf0, lag_ratio=0.01, run_time=3),
FadeOut(vects),
FadeOut(v_vects),
FadeOut(foreground),
)
self.play(
Transform(vf0, vf1, path_arc=90 * DEGREES)
)
self.play(
Transform(
vf0, vf2,
lag_ratio=0.001,
run_time=2,
),
)
self.play(
FadeIn(foreground)
)
self.play(FadeIn(temp_faders))
self.vector_field = vf0
self.foreground = foreground
def show_circle(self):
t_tracker = self.input_tracker
ic = self.ic
output_label = self.output_label
plane = self.plane
tip_label = self.tip_label
output_label.update(0)
# output_rect = BackgroundRectangle(output_label)
# output_rect.add_updater(
# lambda m: m.move_to(output_label)
# )
# output_rect.set_opacity(0)
output_label.set_stroke(BLACK, 5, background=True)
ic_rect = SurroundingRectangle(ic)
ic_rect.set_color(BLUE)
circle = Circle(
radius=get_norm(plane.n2p(1) - plane.n2p(0)),
stroke_color=TEAL,
)
circle.move_to(plane.n2p(0))
epii, eti = results = [
OldTex(
"e^{{i}" + s1 + "} = " + s2,
tex_to_color_map={
"{i}": CONST_COLOR,
"\\pi": T_COLOR,
"\\tau": T_COLOR,
"-1": POSITION_COLOR,
"1": POSITION_COLOR,
}
)
for s1, s2 in [("\\pi", "-1"), ("\\tau", "1")]
]
for result in results:
rect = SurroundingRectangle(result)
rect.set_stroke(WHITE, 1)
rect.set_fill(BLACK, 0.75)
result.add_to_back(rect)
# result.set_stroke(BLACK, 5, background=True)
result.scale(2)
result.to_corner(UR)
result.save_state()
result.fade(1)
eti.saved_state.next_to(epii, DOWN, buff=MED_LARGE_BUFF)
epii.move_to(plane.n2p(-1), LEFT)
eti.move_to(plane.n2p(1), LEFT)
self.play(ShowCreation(ic_rect))
self.play(FadeOut(ic_rect))
self.play(
Transform(
ic[-1].copy(),
output_label.deepcopy().clear_updaters(),
remover=True
),
FadeOut(self.position_label),
FadeOut(self.velocity_label),
)
self.add(output_label)
self.wait()
circle_copy = circle.copy()
circle_copy.save_state()
self.play(
ShowCreation(circle),
t_tracker.set_value, TAU,
run_time=TAU,
rate_func=linear,
)
self.wait()
self.play(
t_tracker.set_value, 0,
circle.set_stroke, {"width": 1},
)
self.wait()
self.add(circle_copy, self.tip_label, self.output_label)
self.play(
ApplyMethod(
t_tracker.set_value, PI,
rate_func=linear,
),
tip_label.shift_vect.move_to, 0.25 * UR,
ShowCreation(
circle_copy,
rate_func=lambda t: 0.5 * t,
),
run_time=PI,
)
self.wait()
self.play(Restore(epii, run_time=2))
self.wait()
circle_copy.restore()
self.play(
ApplyMethod(
t_tracker.set_value, TAU,
rate_func=linear,
),
tip_label.shift_vect.move_to, 0.1 * UR,
ShowCreation(
circle_copy,
rate_func=lambda t: 0.5 + 0.5 * t,
),
run_time=PI,
)
self.wait()
self.play(Restore(eti, run_time=2))
self.wait()
rate = 1
t_tracker.add_updater(
lambda m, dt: m.increment_value(rate * dt)
)
# self.play(VFadeOut(output_label))
self.wait(16)
class PiMinuteMark(Scene):
def construct(self):
text = OldTex(
"\\pi \\text{ minutes} \\approx \\text{3:08}"
)
rect = SurroundingRectangle(text)
rect.set_fill(BLACK, 1)
rect.set_stroke(WHITE, 2)
self.play(
FadeInFromDown(rect),
FadeInFromDown(text),
)
self.wait()
class ReferenceWhatItMeans(PiCreatureScene):
def construct(self):
randy = self.pi_creature
tex_config = {
"tex_to_color_map": {
"{i}": CONST_COLOR,
"\\pi": T_COLOR,
"-1": POSITION_COLOR,
},
}
epii = OldTex(
"e^{{i} \\pi} = -1",
**tex_config
)
epii.scale(2)
many_es = OldTex("e \\cdot e \\cdots e", "= -1", **tex_config)
many_es.scale(2)
brace = Brace(many_es[0], DOWN)
pi_i = OldTex("{i} \\pi \\text{ times}", **tex_config)
pi_i.next_to(brace, DOWN, SMALL_BUFF)
repeated_mult = VGroup(many_es, brace, pi_i)
# arrow = Vector(2 * RIGHT)
arrow = OldTex("\\Rightarrow")
arrow.scale(2)
group = VGroup(epii, arrow, repeated_mult)
group.arrange(
RIGHT, buff=LARGE_BUFF,
)
for mob in group[1:]:
mob.shift(
(epii[0].get_bottom() - mob[0].get_bottom())[1] * UP
)
group.to_edge(UP)
does_not_mean = OldTexText("Does \\emph{not}\\\\mean")
does_not_mean.set_color(RED)
does_not_mean.move_to(arrow)
# cross = Cross(repeated_mult)
nonsense = OldTexText(
"\\dots because that's "
"literal nonsense!"
)
nonsense.next_to(repeated_mult, DOWN)
nonsense.to_edge(RIGHT, buff=MED_SMALL_BUFF)
nonsense.set_color(RED)
down_arrow = OldTex("\\Downarrow")
down_arrow.scale(2)
down_arrow.stretch(1.5, 1)
down_arrow.set_color(GREEN)
down_arrow.next_to(epii, DOWN, LARGE_BUFF)
actually_means = OldTexText("It actually\\\\means")
actually_means.next_to(down_arrow, RIGHT)
actually_means.set_color(GREEN)
series = OldTex(
"{({i} \\pi )^0 \\over 0!} + ",
"{({i} \\pi )^1 \\over 1!} + ",
"{({i} \\pi )^2 \\over 2!} + ",
"{({i} \\pi )^3 \\over 3!} + ",
"{({i} \\pi )^4 \\over 4!} + ",
"\\cdots = -1",
**tex_config
)
series.set_width(FRAME_WIDTH - 1)
series.next_to(down_arrow, DOWN, LARGE_BUFF)
series.set_x(0)
self.add(epii)
self.play(
FadeIn(arrow, LEFT),
FadeIn(repeated_mult, 2 * LEFT),
randy.change, "maybe",
)
self.wait()
self.play(randy.change, "confused")
self.play(
FadeOut(arrow, DOWN),
FadeIn(does_not_mean, UP),
)
self.play(Write(nonsense))
self.play(randy.change, "angry")
# self.play(ShowCreation(cross))
self.wait()
self.play(
FadeOut(randy, DOWN),
FadeIn(down_arrow, UP),
FadeIn(actually_means, LEFT),
FadeIn(series, lag_ratio=0.1, run_time=2)
)
self.wait()
class VideoWrapper(Scene):
def construct(self):
fade_rect = FullScreenFadeRectangle()
fade_rect.set_fill(GREY_D, 1)
screen_rects = VGroup(
ScreenRectangle(),
ScreenRectangle(),
)
screen_rects.set_height(3)
screen_rects.set_fill(BLACK, 1)
screen_rects.set_stroke(width=0)
screen_rects.arrange(RIGHT, buff=LARGE_BUFF)
screen_rects.shift(1.25 * UP)
boundary = VGroup(*map(AnimatedBoundary, screen_rects))
titles = VGroup(
OldTexText("Want more?"),
OldTexText("Learn calculus"),
)
titles.scale(1.5)
for rect, title, in zip(screen_rects, titles):
title.next_to(rect, UP)
self.add(fade_rect)
self.add(screen_rects)
self.add(boundary[0])
self.play(FadeInFromDown(titles[0]))
self.add(boundary[1])
self.play(FadeInFromDown(titles[1]))
self.wait(18)
class Thumbnail(Scene):
def construct(self):
epii = OldTex(
"e^{ {i} \\pi} = -1",
tex_to_color_map={
"{i}": YELLOW,
"\\pi": BLUE,
"-1": GREY_A,
}
)
epii.set_width(8)
epii.to_edge(UP)
epii.set_stroke(BLACK, 50, background=True)
words = VGroup(
OldTexText("in"),
OldTexText(
"in",
"3.14", " minutes"
),
)
# words.set_width(FRAME_WIDTH - 4)
words.set_stroke(BLACK, 6, background=True)
words.set_width(FRAME_WIDTH - 2)
words.arrange(DOWN, buff=LARGE_BUFF)
words.next_to(epii, DOWN, LARGE_BUFF)
words[1].set_color_by_tex("3.14", YELLOW)
words.shift(-words[0].get_center())
words[0].set_opacity(0)
unit_size = 2.0
plane = ComplexPlane()
plane.scale(unit_size)
plane.shift(1.0 * DOWN)
plane.add_coordinate_labels([*range(-3, 4), complex(0, -1), complex(0, 1)])
circle = Circle(
radius=unit_size,
color=YELLOW,
)
circle.set_stroke(GREY_B, 3)
arc = Arc(0, PI, radius=unit_size)
arc.set_stroke(BLUE, 10)
circle = VGroup(arc.copy().set_stroke(BLACK, 20, background=True), circle, arc)
circle.move_to(plane.get_origin())
# half_circle = VMobject()
# half_circle.pointwise_become_partial(circle, 0, 0.5)
# half_circle.set_stroke(RED, 6)
p_vect = Arrow(
plane.n2p(0),
plane.n2p(1),
buff=0,
fill_color=GREY_A,
thickness=0.1
)
v_vect = Arrow(
plane.n2p(1),
plane.n2p(complex(1, 1)),
buff=0,
fill_color=YELLOW,
thickness=0.1
)
vects = VGroup(p_vect, v_vect)
self.add(plane)
self.add(circle)
self.add(vects)
self.add(epii)
# self.add(words)
self.embed()
|
|
from manim_imports_ext import *
from _2019.diffyq.part2.fourier_series import FourierOfTrebleClef
class FourierNameIntro(Scene):
def construct(self):
self.show_two_titles()
self.transition_to_image()
self.show_paper()
def show_two_titles(self):
lt = OldTexText("Fourier", "Series")
rt = OldTexText("Fourier", "Transform")
lt_variants = VGroup(
OldTexText("Complex", "Fourier Series"),
OldTexText("Discrete", "Fourier Series"),
)
rt_variants = VGroup(
OldTexText("Discrete", "Fourier Transform"),
OldTexText("Fast", "Fourier Transform"),
OldTexText("Quantum", "Fourier Transform"),
)
titles = VGroup(lt, rt)
titles.scale(1.5)
for title, vect in (lt, LEFT), (rt, RIGHT):
title.move_to(vect * FRAME_WIDTH / 4)
title.to_edge(UP)
for title, variants in (lt, lt_variants), (rt, rt_variants):
title.save_state()
title.target = title.copy()
title.target.scale(1 / 1.5, about_edge=RIGHT)
for variant in variants:
variant.move_to(title.target, UR)
variant[0].set_color(YELLOW)
v_line = Line(UP, DOWN)
v_line.set_height(FRAME_HEIGHT)
v_line.set_stroke(WHITE, 2)
self.play(
FadeIn(lt, RIGHT),
ShowCreation(v_line)
)
self.play(
FadeIn(rt, LEFT),
)
# Edit in images of circle animations
# and clips from FT video
# for title, variants in (rt, rt_variants), (lt, lt_variants):
for title, variants in [(rt, rt_variants)]:
# Maybe do it for left variant, maybe not...
self.play(
MoveToTarget(title),
FadeIn(variants[0][0], LEFT)
)
for v1, v2 in zip(variants, variants[1:]):
self.play(
FadeOut(v1[0], UP),
FadeIn(v2[0], DOWN),
run_time=0.5,
)
self.wait(0.5)
self.play(
Restore(title),
FadeOut(variants[-1][0])
)
self.wait()
self.titles = titles
self.v_line = v_line
def transition_to_image(self):
titles = self.titles
v_line = self.v_line
image = ImageMobject("Joseph Fourier")
image.set_height(5)
image.to_edge(LEFT)
frame = Rectangle()
frame.replace(image, stretch=True)
name = OldTexText("Joseph", "Fourier")
fourier_part = name.get_part_by_tex("Fourier")
fourier_part.set_color(YELLOW)
F_sym = fourier_part[0]
name.match_width(image)
name.next_to(image, DOWN)
self.play(
ReplacementTransform(v_line, frame),
FadeIn(image),
FadeIn(name[0]),
*[
ReplacementTransform(
title[0].deepcopy(),
name[1]
)
for title in titles
],
titles.scale, 0.65,
titles.arrange, DOWN,
titles.next_to, image, UP,
)
self.wait()
big_F = F_sym.copy()
big_F.set_fill(opacity=0)
big_F.set_stroke(WHITE, 2)
big_F.set_height(3)
big_F.move_to(midpoint(
image.get_right(),
RIGHT_SIDE,
))
big_F.shift(DOWN)
equivalence = VGroup(
fourier_part.copy().scale(1.25),
OldTex("\\Leftrightarrow").scale(1.5),
OldTexText("Break down into\\\\pure frequencies"),
)
equivalence.arrange(RIGHT)
equivalence.move_to(big_F)
equivalence.to_edge(UP)
self.play(
FadeIn(big_F),
TransformFromCopy(fourier_part, equivalence[0]),
Write(equivalence[1:]),
)
self.wait(3)
self.play(FadeOut(VGroup(big_F, equivalence)))
self.image = image
self.name = name
def show_paper(self):
image = self.image
paper = ImageMobject("Fourier paper")
paper.match_height(image)
paper.next_to(image, RIGHT, MED_LARGE_BUFF)
date = OldTex("1822")
date.next_to(paper, DOWN)
date_rect = SurroundingRectangle(date)
date_rect.scale(0.3)
date_rect.set_color(RED)
date_rect.shift(1.37 * UP + 0.08 * LEFT)
date_arrow = Arrow(
date_rect.get_bottom(),
date.get_top(),
buff=SMALL_BUFF,
color=date_rect.get_color(),
)
heat_rect = SurroundingRectangle(
OldTexText("CHALEUR")
)
heat_rect.set_color(RED)
heat_rect.scale(0.6)
heat_rect.move_to(
paper.get_top() +
1.22 * DOWN + 0.37 * RIGHT
)
heat_word = OldTexText("Heat")
heat_word.scale(1.5)
heat_word.next_to(paper, UP)
heat_word.shift(paper.get_width() * RIGHT)
heat_arrow = Arrow(
heat_rect.get_top(),
heat_word.get_left(),
buff=0.1,
path_arc=-60 * DEGREES,
color=heat_rect.get_color(),
)
self.play(FadeIn(paper, LEFT))
self.play(
ShowCreation(date_rect),
)
self.play(
GrowFromPoint(date, date_arrow.get_start()),
ShowCreation(date_arrow),
)
self.wait(3)
# Insert animation of circles/sine waves
# approximating a square wave
self.play(
ShowCreation(heat_rect),
)
self.play(
GrowFromPoint(heat_word, heat_arrow.get_start()),
ShowCreation(heat_arrow),
)
self.wait(3)
class ManyCousinsOfFourierThings(Scene):
def construct(self):
series_variants = VGroup(
OldTexText("Complex", "Fourier Series"),
OldTexText("Discrete", "Fourier Series"),
)
transform_variants = VGroup(
OldTexText("Discrete", "Fourier Transform"),
OldTexText("Fast", "Fourier Transform"),
OldTexText("Quantum", "Fourier Transform"),
)
groups = VGroup(series_variants, transform_variants)
for group, vect in zip(groups, [LEFT, RIGHT]):
group.scale(0.7)
group.arrange(DOWN, aligned_edge=LEFT)
group.move_to(
vect * FRAME_WIDTH / 4
)
group.set_color(YELLOW)
self.play(*[
LaggedStartMap(FadeIn, group)
for group in groups
])
self.play(*[
LaggedStartMap(FadeOut, group)
for group in groups
])
class FourierSeriesIllustraiton(Scene):
CONFIG = {
"n_range": range(1, 31, 2),
"axes_config": {
"axis_config": {
"include_tip": False,
},
"x_axis_config": {
"tick_frequency": 1 / 4,
"unit_size": 4,
},
"x_min": 0,
"x_max": 1,
"y_min": -1,
"y_max": 1,
},
"colors": [BLUE, GREEN, RED, YELLOW, PINK],
}
def construct(self):
aaa_group = self.get_axes_arrow_axes()
aaa_group.shift(2 * UP)
aaa_group.shift_onto_screen()
axes1, arrow, axes2 = aaa_group
axes2.add(self.get_target_func_graph(axes2))
sine_graphs = self.get_sine_graphs(axes1)
partial_sums = self.get_partial_sums(axes1, sine_graphs)
sum_tex = self.get_sum_tex()
sum_tex.next_to(axes1, DOWN, LARGE_BUFF)
sum_tex.shift(RIGHT)
eq = OldTex("=")
target_func_tex = self.get_target_func_tex()
target_func_tex.next_to(axes2, DOWN)
target_func_tex.match_y(sum_tex)
eq.move_to(midpoint(
target_func_tex.get_left(),
sum_tex.get_right()
))
range_words = OldTexText(
"For $0 \\le x \\le 1$"
)
range_words.next_to(
VGroup(sum_tex, target_func_tex),
DOWN,
)
rects = it.chain(
[
SurroundingRectangle(piece)
for piece in self.get_sum_tex_pieces(sum_tex)
],
it.cycle([None])
)
self.add(axes1, arrow, axes2)
self.add(sum_tex, eq, target_func_tex)
self.add(range_words)
curr_partial_sum = axes1.get_graph(lambda x: 0)
curr_partial_sum.set_stroke(width=1)
for sine_graph, partial_sum, rect in zip(sine_graphs, partial_sums, rects):
anims1 = [
ShowCreation(sine_graph)
]
partial_sum.set_stroke(BLACK, 4, background=True)
anims2 = [
curr_partial_sum.set_stroke,
{"width": 1, "opacity": 0.5},
curr_partial_sum.set_stroke,
{"width": 0, "background": True},
ReplacementTransform(
sine_graph, partial_sum,
remover=True
),
]
if rect:
rect.match_style(sine_graph)
anims1.append(ShowCreation(rect))
anims2.append(FadeOut(rect))
self.play(*anims1)
self.play(*anims2)
curr_partial_sum = partial_sum
def get_axes_arrow_axes(self):
axes1 = Axes(**self.axes_config)
axes1.x_axis.add_numbers(
0.5, 1,
num_decimal_places=1
)
axes1.y_axis.add_numbers(
-1, 1,
direction=LEFT,
num_decimal_places=1,
)
axes2 = axes1.deepcopy()
arrow = Arrow(LEFT, RIGHT, color=WHITE)
group = VGroup(axes1, arrow, axes2)
group.arrange(RIGHT, buff=MED_LARGE_BUFF)
return group
def get_sine_graphs(self, axes):
sine_graphs = VGroup(*[
axes.get_graph(self.generate_nth_func(n))
for n in self.n_range
])
sine_graphs.set_stroke(width=3)
for graph, color in zip(sine_graphs, it.cycle(self.colors)):
graph.set_color(color)
return sine_graphs
def get_partial_sums(self, axes, sine_graphs):
partial_sums = VGroup(*[
axes.get_graph(self.generate_kth_partial_sum_func(k + 1))
for k in range(len(self.n_range))
])
partial_sums.match_style(sine_graphs)
return partial_sums
def get_sum_tex(self):
return OldTex(
"\\frac{4}{\\pi} \\left(",
"\\frac{\\cos(\\pi x)}{1}",
"-\\frac{\\cos(3\\pi x)}{3}",
"+\\frac{\\cos(5\\pi x)}{5}",
"- \\cdots \\right)"
).scale(0.75)
def get_sum_tex_pieces(self, sum_tex):
return sum_tex[1:4]
def get_target_func_tex(self):
step_tex = OldTex(
"""
1 \\quad \\text{if $x < 0.5$} \\\\
0 \\quad \\text{if $x = 0.5$} \\\\
-1 \\quad \\text{if $x > 0.5$} \\\\
"""
)
lb = Brace(step_tex, LEFT, buff=SMALL_BUFF)
step_tex.add(lb)
return step_tex
def get_target_func_graph(self, axes):
step_func = axes.get_graph(
lambda x: (1 if x < 0.5 else -1),
discontinuities=[0.5],
color=YELLOW,
stroke_width=3,
)
dot = Dot(axes.c2p(0.5, 0), color=step_func.get_color())
dot.scale(0.5)
step_func.add(dot)
return step_func
# def generate_nth_func(self, n):
# return lambda x: (4 / n / PI) * np.sin(TAU * n * x)
def generate_nth_func(self, n):
return lambda x: np.prod([
(4 / PI),
(1 / n) * (-1)**((n - 1) / 2),
np.cos(PI * n * x)
])
def generate_kth_partial_sum_func(self, k):
return lambda x: np.sum([
self.generate_nth_func(n)(x)
for n in self.n_range[:k]
])
class FourierSeriesOfLineIllustration(FourierSeriesIllustraiton):
CONFIG = {
"n_range": range(1, 31, 2),
"axes_config": {
"y_axis_config": {
"unit_size": 2,
"tick_frequency": 0.25,
"numbers_with_elongated_ticks": [-1, 1],
}
}
}
def get_sum_tex(self):
return OldTex(
"\\frac{8}{\\pi^2} \\left(",
"\\frac{\\cos(\\pi x)}{1^2}",
"+\\frac{\\cos(3\\pi x)}{3^2}",
"+\\frac{\\cos(5\\pi x)}{5^2}",
"+ \\cdots \\right)"
).scale(0.75)
# def get_sum_tex_pieces(self, sum_tex):
# return sum_tex[1:4]
def get_target_func_tex(self):
result = OldTex("1 - 2x")
result.scale(1.5)
point = VectorizedPoint()
point.next_to(result, RIGHT, 1.5 * LARGE_BUFF)
# result.add(point)
return result
def get_target_func_graph(self, axes):
return axes.get_graph(
lambda x: 1 - 2 * x,
color=YELLOW,
stroke_width=3,
)
# def generate_nth_func(self, n):
# return lambda x: (4 / n / PI) * np.sin(TAU * n * x)
def generate_nth_func(self, n):
return lambda x: np.prod([
(8 / PI**2),
(1 / n**2),
np.cos(PI * n * x)
])
class CircleAnimationOfF(FourierOfTrebleClef):
CONFIG = {
"height": 3,
"n_circles": 200,
"run_time": 10,
"arrow_config": {
"tip_length": 0.1,
"stroke_width": 2,
}
}
def get_shape(self):
path = VMobject()
shape = OldTexText("F")
for sp in shape.family_members_with_points():
path.append_points(sp.get_points())
return path
class ExponentialDecay(PiCreatureScene):
def construct(self):
k = 0.2
mk_tex = "-0.2"
mk_tex_color = GREEN
t2c = {mk_tex: mk_tex_color}
# Pi creature
randy = self.pi_creature
randy.flip()
randy.set_height(2.5)
randy.move_to(3 * RIGHT)
randy.to_edge(DOWN)
bubble = ThoughtBubble(
direction=LEFT,
height=3.5,
width=3,
)
bubble.pin_to(randy)
bubble.set_fill(GREY_E)
exp = OldTex(
"Ce^{", mk_tex, "t}",
tex_to_color_map=t2c,
)
exp.move_to(bubble.get_bubble_center())
# Setup axes
axes = Axes(
x_min=0,
x_max=13,
y_min=-4,
y_max=4,
)
axes.set_stroke(width=2)
axes.set_color(GREY_B)
axes.scale(0.9)
axes.to_edge(LEFT, buff=LARGE_BUFF)
axes.x_axis.add_numbers()
axes.y_axis.add_numbers()
axes.y_axis.add_numbers(0)
axes.x_axis.add(
OldTexText("Time").next_to(
axes.x_axis.get_end(), DR,
)
)
axes.y_axis.add(
OldTex("f").next_to(
axes.y_axis.get_corner(UR), RIGHT,
).set_color(YELLOW)
)
axes.x_axis.set_opacity(0)
# Value trackers
y_tracker = ValueTracker(3)
x_tracker = ValueTracker(0)
dydt_tracker = ValueTracker()
dxdt_tracker = ValueTracker(0)
self.add(
y_tracker, x_tracker,
dydt_tracker, dxdt_tracker,
)
get_y = y_tracker.get_value
get_x = x_tracker.get_value
get_dydt = dydt_tracker.get_value
get_dxdt = dxdt_tracker.get_value
dydt_tracker.add_updater(lambda m: m.set_value(
- k * get_y()
))
y_tracker.add_updater(lambda m, dt: m.increment_value(
dt * get_dydt()
))
x_tracker.add_updater(lambda m, dt: m.increment_value(
dt * get_dxdt()
))
# Tip/decimal
tip = ArrowTip(color=YELLOW)
tip.set_width(0.25)
tip.add_updater(lambda m: m.move_to(
axes.c2p(get_x(), get_y()), LEFT
))
decimal = DecimalNumber()
decimal.add_updater(lambda d: d.set_value(get_y()))
decimal.add_updater(lambda d: d.next_to(
tip, RIGHT,
SMALL_BUFF,
))
# Rate of change arrow
arrow = Vector(
DOWN, color=RED,
max_stroke_width_to_length_ratio=50,
max_tip_length_to_length_ratio=0.2,
)
arrow.set_stroke(width=4)
arrow.add_updater(lambda m: m.scale(
2.5 * abs(get_dydt()) / m.get_length()
))
arrow.add_updater(lambda m: m.move_to(
tip.get_left(), UP
))
# Graph
graph = TracedPath(tip.get_left)
# Equation
ode = OldTex(
"{d{f} \\over dt}(t)",
"=", mk_tex, "\\cdot {f}(t)",
tex_to_color_map={
"{f}": YELLOW,
"=": WHITE,
mk_tex: mk_tex_color
}
)
ode.to_edge(UP)
dfdt = ode[:3]
ft = ode[-2:]
self.add(axes)
self.add(tip)
self.add(decimal)
self.add(arrow)
self.add(randy)
self.add(ode)
# Show rate of change dependent on itself
rect = SurroundingRectangle(dfdt)
self.play(ShowCreation(rect))
self.wait()
self.play(
Transform(
rect,
SurroundingRectangle(ft)
)
)
self.wait(3)
# Show graph over time
self.play(
DrawBorderThenFill(bubble),
Write(exp),
FadeOut(rect),
randy.change, "thinking",
)
axes.x_axis.set_opacity(1)
self.play(
y_tracker.set_value, 3,
ShowCreation(axes.x_axis),
)
dxdt_tracker.set_value(1)
self.add(graph)
randy.add_updater(lambda r: r.look_at(tip))
self.wait(4)
# Show derivative of exponential
eq = OldTex("=")
eq.next_to(ode.get_part_by_tex("="), DOWN, LARGE_BUFF)
exp.generate_target()
exp.target.next_to(eq, LEFT)
d_dt = OldTex("{d \\over dt}")
d_dt.next_to(exp.target, LEFT)
const = OldTex(mk_tex)
const.set_color(mk_tex_color)
dot = OldTex("\\cdot")
const.next_to(eq, RIGHT)
dot.next_to(const, RIGHT, 2 * SMALL_BUFF)
exp_copy = exp.copy()
exp_copy.next_to(dot, RIGHT, 2 * SMALL_BUFF)
VGroup(const, dot, eq).align_to(exp_copy, DOWN)
self.play(
MoveToTarget(exp),
FadeOut(bubble),
FadeIn(d_dt),
FadeIn(eq),
)
self.wait(2)
self.play(
ApplyMethod(
exp[1].copy().replace,
const[0],
)
)
self.wait()
rect = SurroundingRectangle(exp)
rect.set_stroke(BLUE, 2)
self.play(FadeIn(rect))
self.play(
Write(dot),
TransformFromCopy(exp, exp_copy),
rect.move_to, exp_copy
)
self.play(FadeOut(rect))
self.wait(5)
class InvestmentGrowth(Scene):
CONFIG = {
"output_tex": "{M}",
"output_color": GREEN,
"initial_value": 1,
"initial_value_tex": "{M_0}",
"k": 0.05,
"k_tex": "0.05",
"total_time": 43,
"time_rate": 3,
}
def construct(self):
# Axes
axes = Axes(
x_min=0,
x_max=self.total_time,
y_min=0,
y_max=6,
x_axis_config={
"unit_size": 0.3,
"tick_size": 0.05,
"numbers_with_elongated_ticks": range(
0, self.total_time, 5
)
}
)
axes.to_corner(DL, buff=LARGE_BUFF)
time_label = OldTexText("Time")
time_label.next_to(
axes.x_axis.get_right(),
UP, MED_LARGE_BUFF
)
time_label.shift_onto_screen()
axes.x_axis.add(time_label)
money_label = OldTex(self.output_tex)
money_label.set_color(self.output_color)
money_label.next_to(
axes.y_axis.get_top(),
UP,
)
axes.y_axis.add(money_label)
# Graph
graph = axes.get_graph(
lambda x: self.initial_value * np.exp(self.k * x)
)
graph.set_color(self.output_color)
full_graph = graph.copy()
time_tracker = self.get_time_tracker()
graph.add_updater(lambda m: m.pointwise_become_partial(
full_graph, 0,
np.clip(
time_tracker.get_value() / self.total_time,
0, 1,
)
))
# Equation
tex_kwargs = {
"tex_to_color_map": {
self.output_tex: self.output_color,
self.initial_value_tex: BLUE,
}
}
ode = OldTex(
"{d",
"\\over dt}",
self.output_tex,
"(t)",
"=", self.k_tex,
"\\cdot", self.output_tex, "(t)",
**tex_kwargs
)
ode.to_edge(UP)
exp = OldTex(
self.output_tex,
"(t) =", self.initial_value_tex,
"e^{", self.k_tex, "t}",
**tex_kwargs
)
exp.next_to(ode, DOWN, LARGE_BUFF)
M0_part = exp.get_part_by_tex(self.initial_value_tex)
exp_part = exp[-3:]
M0_label = M0_part.copy()
M0_label.next_to(
axes.c2p(0, self.initial_value),
LEFT
)
M0_part.set_opacity(0)
exp_part.save_state()
exp_part.align_to(M0_part, LEFT)
self.add(axes)
self.add(graph)
self.add(time_tracker)
self.play(FadeInFromDown(ode))
self.wait(6)
self.play(FadeIn(exp, UP))
self.wait(2)
self.play(
Restore(exp_part),
M0_part.set_opacity, 1,
)
self.play(TransformFromCopy(
M0_part, M0_label
))
self.wait(5)
def get_time_tracker(self):
time_tracker = ValueTracker(0)
time_tracker.add_updater(
lambda m, dt: m.increment_value(
self.time_rate * dt
)
)
return time_tracker
class GrowingPileOfMoney(InvestmentGrowth):
CONFIG = {
"total_time": 60
}
def construct(self):
initial_count = 5
k = self.k
total_time = self.total_time
time_tracker = self.get_time_tracker()
final_count = initial_count * np.exp(k * total_time)
dollar_signs = VGroup(*[
OldTex("\\$")
for x in range(int(final_count))
])
dollar_signs.set_color(GREEN)
for ds in dollar_signs:
ds.shift(
3 * np.random.random(3)
)
dollar_signs.center()
dollar_signs.sort(get_norm)
dollar_signs.set_stroke(BLACK, 3, background=True)
def update_dollar_signs(group):
t = time_tracker.get_value()
count = initial_count * np.exp(k * t)
alpha = count / final_count
n, sa = integer_interpolate(0, len(dollar_signs), alpha)
group.set_opacity(1)
group[n:].set_opacity(0)
group[n].set_opacity(sa)
dollar_signs.add_updater(update_dollar_signs)
self.add(time_tracker)
self.add(dollar_signs)
self.wait(20)
class CarbonDecayCurve(InvestmentGrowth):
CONFIG = {
"output_tex": "{^{14}C}",
"output_color": GOLD,
"initial_value": 4,
"initial_value_tex": "{^{14}C_0}",
"k": -0.1,
"k_tex": "-k",
"time_rate": 6,
}
class CarbonDecayingInMammoth(Scene):
def construct(self):
mammoth = SVGMobject("Mammoth")
mammoth.set_color(
interpolate_color(GREY_BROWN, WHITE, 0.25)
)
mammoth.set_height(4)
body = mammoth[9]
atoms = VGroup(*[
self.get_atom(body)
for n in range(600)
])
p_decay = 0.2
def update_atoms(group, dt):
for atom in group:
if np.random.random() < dt * p_decay:
group.remove(atom)
return group
atoms.add_updater(update_atoms)
self.add(mammoth)
self.add(atoms)
self.wait(20)
def get_atom(self, body):
atom = Dot(color=GOLD)
atom.set_height(0.05)
dl = body.get_corner(DL)
ur = body.get_corner(UR)
wn = 0
while wn == 0:
point = np.array([
interpolate(dl[0], ur[0], np.random.random()),
interpolate(dl[1], ur[1], np.random.random()),
0
])
wn = get_winding_number([
body.point_from_proportion(a) - point
for a in np.linspace(0, 1, 300)
])
wn = int(np.round(wn))
atom.move_to(point)
return atom
class BoundaryConditionInterlude(Scene):
def construct(self):
background = FullScreenFadeRectangle(
fill_color=GREY_D
)
storyline = self.get_main_storyline()
storyline.generate_target()
v_shift = 2 * DOWN
storyline.target.shift(v_shift)
im_to_im = storyline[1].get_center() - storyline[0].get_center()
bc_image = self.get_labeled_image(
"Boundary\\\\conditions",
"boundary_condition_thumbnail"
)
bc_image.next_to(storyline[1], UP)
new_arrow0 = Arrow(
storyline.arrows[0].get_start() + v_shift,
bc_image.get_left() + SMALL_BUFF * LEFT,
path_arc=-90 * DEGREES,
buff=0,
)
new_mid_arrow = Arrow(
bc_image.get_bottom(),
storyline[1].get_top() + v_shift,
buff=SMALL_BUFF,
path_arc=60 * DEGREES,
)
# BC detour
self.add(background)
self.add(storyline[0])
for im1, im2, arrow in zip(storyline, storyline[1:], storyline.arrows):
self.add(im2, im1)
self.play(
FadeIn(im2, -im_to_im),
ShowCreation(arrow),
)
self.wait()
self.play(
GrowFromCenter(bc_image),
MoveToTarget(storyline),
Transform(
storyline.arrows[0],
new_arrow0,
),
MaintainPositionRelativeTo(
storyline.arrows[1],
storyline,
),
)
self.play(ShowCreation(new_mid_arrow))
self.wait()
# From BC to next step
rect1 = bc_image[2].copy()
rect2 = storyline[1][2].copy()
rect3 = storyline[2][2].copy()
for rect in rect1, rect2, rect3:
rect.set_stroke(YELLOW, 3)
self.play(FadeIn(rect1))
kw = {"path_arc": 60 * DEGREES}
self.play(
LaggedStart(
Transform(rect1, rect2, **kw),
# TransformFromCopy(rect1, rect3, **kw),
lag_ratio=0.4,
)
)
self.play(
FadeOut(rect1),
# FadeOut(rect3),
)
# Reorganize images
im1, im3, im4 = storyline
im2 = bc_image
l_group = Group(im1, im2)
r_group = Group(im3, im4)
for group in l_group, r_group:
group.generate_target()
group.target.arrange(DOWN, buff=LARGE_BUFF)
group.target.center()
l_group.target.to_edge(LEFT)
r_group.target.move_to(
FRAME_WIDTH * RIGHT / 4
)
brace = Brace(r_group.target, LEFT)
nv_text = brace.get_text("Next\\\\video")
nv_text.scale(1.5, about_edge=RIGHT)
nv_text.set_color(YELLOW)
brace.set_color(YELLOW)
arrows = VGroup(
storyline.arrows,
new_mid_arrow,
)
self.play(
LaggedStart(
MoveToTarget(l_group),
MoveToTarget(r_group),
lag_ratio=0.3,
),
FadeOut(arrows),
)
self.play(
GrowFromCenter(brace),
FadeIn(nv_text, RIGHT)
)
self.wait()
def get_main_storyline(self):
images = Group(
self.get_sine_curve_image(),
self.get_linearity_image(),
self.get_fourier_series_image(),
)
for image in images:
image.set_height(3)
images.arrange(RIGHT, buff=1)
images.set_width(FRAME_WIDTH - 1)
arrows = VGroup()
for im1, im2 in zip(images, images[1:]):
arrow = Arrow(
im1.get_top(),
im2.get_top(),
color=WHITE,
buff=MED_SMALL_BUFF,
path_arc=-120 * DEGREES,
rectangular_stem_width=0.025,
)
arrow.scale(0.7, about_edge=DOWN)
arrows.add(arrow)
images.arrows = arrows
return images
def get_sine_curve_image(self):
return self.get_labeled_image(
"Sine curves",
"sine_curve_temp_graph",
)
def get_linearity_image(self):
return self.get_labeled_image(
"Linearity",
"linearity_thumbnail",
)
def get_fourier_series_image(self):
return self.get_labeled_image(
"Fourier series",
"fourier_series_thumbnail",
)
def get_labeled_image(self, text, image_file):
rect = ScreenRectangle(height=2)
border = rect.copy()
rect.set_fill(BLACK, 1)
rect.set_stroke(WHITE, 0)
border.set_stroke(WHITE, 2)
text_mob = OldTexText(text)
text_mob.set_stroke(BLACK, 5, background=True)
text_mob.next_to(rect.get_top(), DOWN, SMALL_BUFF)
image = ImageMobject(image_file)
image.replace(rect, dim_to_match=1)
image.scale(0.8, about_edge=DOWN)
return Group(rect, image, border, text_mob)
class GiantCross(Scene):
def construct(self):
rect = FullScreenFadeRectangle()
cross = Cross(rect)
cross.set_stroke(RED, 25)
words = OldTexText("This wouldn't\\\\happen!")
words.scale(2)
words.set_color(RED)
words.to_edge(UP)
self.play(
FadeInFromDown(words),
ShowCreation(cross),
)
self.wait()
class EndScreen(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",
"Charles Southerland",
"Chris Connett",
"Christian Kaiser",
"Clark Gaebel",
"Cooper Jones",
"Danger Dai",
"Daniel Pang",
"Dave B",
"Dave Kester",
"David B. Hill",
"David Clark",
"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 Hartmann",
"Jacob Magnuson",
"Jameel Syed",
"Jason Hise",
"Jeff Linse",
"Jeff Straathof",
"John C. Vesey",
"John Griffith",
"John Haley",
"John V Wertheim",
"Jonathan Eppele",
"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",
"Peter Ehrnstrom",
"RedAgent14",
"rehmi post",
"Richard Comish",
"Ripta Pasay",
"Rish Kundalia",
"Robert Teed",
"Roobie",
"Ryan Williams",
"Sebastian Garcia",
"Solara570",
"Stephan Arlinghaus",
"Steven Siddals",
"Stevie Metke",
"Tal Einav",
"Ted Suzman",
"Thomas Tarler",
"Tianyu Ge",
"Tom Fleming",
"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.part2.wordy_scenes import *
class IveHeardOfThis(TeacherStudentsScene):
def construct(self):
point = VectorizedPoint()
point.move_to(3 * RIGHT + 2 * UP)
self.student_says(
"I've heard\\\\", "of this!",
index=1,
target_mode="hooray",
bubble_config={
"height": 3,
"width": 3,
"direction": RIGHT,
},
run_time=1,
)
self.play_student_changes(
"thinking", "hooray", "thinking",
look_at=point,
added_anims=[self.teacher.change, "happy"]
)
self.wait(3)
self.student_says(
"But who\\\\", "cares?",
index=1,
target_mode="maybe",
bubble_config={
"direction": RIGHT,
"width": 3,
"height": 3,
},
run_time=1,
)
self.play_student_changes(
"pondering", "maybe", "pondering",
look_at=point,
added_anims=[self.teacher.change, "guilty"]
)
self.wait(5)
class InFouriersShoes(PiCreatureScene, WriteHeatEquationTemplate):
def construct(self):
randy = self.pi_creature
fourier = ImageMobject("Joseph Fourier")
fourier.set_height(4)
fourier.next_to(randy, RIGHT, LARGE_BUFF)
fourier.align_to(randy, DOWN)
equation = self.get_d1_equation()
equation.next_to(fourier, UP, MED_LARGE_BUFF)
decades = list(range(1740, 2040, 20))
time_line = NumberLine(
x_min=decades[0],
x_max=decades[-1],
tick_frequency=1,
tick_size=0.05,
longer_tick_multiple=4,
unit_size=0.2,
numbers_with_elongated_ticks=decades,
numbers_to_show=decades,
decimal_number_config={
"group_with_commas": False,
},
stroke_width=2,
)
time_line.add_numbers()
time_line.move_to(ORIGIN, RIGHT)
time_line.to_edge(UP)
triangle = ArrowTip(start_angle=-90 * DEGREES)
triangle.set_height(0.25)
triangle.move_to(time_line.n2p(2019), DOWN)
triangle.set_color(WHITE)
self.play(FadeIn(fourier, 2 * LEFT))
self.play(randy.change, "pondering")
self.wait()
self.play(
DrawBorderThenFill(triangle, run_time=1),
FadeInFromDown(equation),
FadeIn(time_line),
)
self.play(
Animation(triangle),
ApplyMethod(
time_line.shift,
time_line.n2p(2019) - time_line.n2p(1822),
run_time=5
),
)
self.wait()
class SineCurveIsUnrealistic(TeacherStudentsScene):
def construct(self):
self.student_says(
"But that would\\\\never happen!",
index=1,
bubble_config={
"direction": RIGHT,
"height": 3,
"width": 4,
},
target_mode="angry"
)
self.play_student_changes(
"guilty", "angry", "hesitant",
added_anims=[
self.teacher.change, "tease"
]
)
self.wait(3)
self.play(
RemovePiCreatureBubble(self.students[1]),
self.teacher.change, "raise_right_hand"
)
self.play_all_student_changes(
"pondering",
look_at=3 * UP,
)
self.wait(5)
class IfOnly(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"If only!",
target_mode="angry"
)
self.play_all_student_changes(
"confused",
look_at=self.screen
)
self.wait(3)
class SoWeGotNowhere(TeacherStudentsScene):
def construct(self):
self.student_says(
"So we've gotten\\\\nowhere!",
target_mode="angry",
added_anims=[
self.teacher.change, "guilty"
]
)
self.play_all_student_changes("angry")
self.wait()
text = OldTex(
"&\\text{Actually,}\\\\",
"&\\sin\\left({x}\\right)"
"e^{-\\alpha {t}}\\\\",
"&\\text{isn't far off.}",
tex_to_color_map={
"{x}": GREEN,
"{t}": YELLOW,
}
)
text.scale(0.8)
self.teacher_says(
text,
content_introduction_class=FadeIn,
bubble_config={
"width": 4,
"height": 3.5,
}
)
self.play_all_student_changes(
"pondering",
look_at=self.screen
)
self.wait(3)
|
|
from scipy import integrate
from manim_imports_ext import *
from _2019.diffyq.part2.heat_equation import *
class TemperatureGraphScene(SpecialThreeDScene):
CONFIG = {
"axes_config": {
"x_min": 0,
"x_max": TAU,
"y_min": 0,
"y_max": 10,
"z_min": -3,
"z_max": 3,
"x_axis_config": {
"tick_frequency": TAU / 8,
"include_tip": False,
},
"num_axis_pieces": 1,
},
"default_graph_style": {
"stroke_width": 2,
"stroke_color": WHITE,
"background_image_file": "VerticalTempGradient",
},
"default_surface_config": {
"fill_opacity": 0.1,
"checkerboard_colors": [GREY_B],
"stroke_width": 0.5,
"stroke_color": WHITE,
"stroke_opacity": 0.5,
},
"temp_text": "Temperature",
}
def get_three_d_axes(self, include_labels=True, include_numbers=False, **kwargs):
config = dict(self.axes_config)
config.update(kwargs)
axes = ThreeDAxes(**config)
axes.set_stroke(width=2)
if include_numbers:
self.add_axes_numbers(axes)
if include_labels:
self.add_axes_labels(axes)
# Adjust axis orientation
axes.x_axis.rotate(
90 * DEGREES, RIGHT,
about_point=axes.c2p(0, 0, 0),
)
axes.y_axis.rotate(
90 * DEGREES, UP,
about_point=axes.c2p(0, 0, 0),
)
# Add xy-plane
input_plane = self.get_surface(
axes, lambda x, t: 0
)
input_plane.set_style(
fill_opacity=0.5,
fill_color=BLUE_B,
stroke_width=0.5,
stroke_color=WHITE,
)
axes.input_plane = input_plane
return axes
def add_axes_numbers(self, axes):
x_axis = axes.x_axis
y_axis = axes.y_axis
tex_vals = [
("\\pi \\over 2", TAU / 4),
("\\pi", TAU / 2),
("3\\pi \\over 2", 3 * TAU / 4),
("2\\pi", TAU)
]
x_labels = VGroup()
for tex, val in tex_vals:
label = OldTex(tex)
label.scale(0.5)
label.next_to(x_axis.n2p(val), DOWN)
x_labels.add(label)
x_axis.add(x_labels)
x_axis.numbers = x_labels
y_axis.add_numbers()
for number in y_axis.numbers:
number.rotate(90 * DEGREES)
return axes
def add_axes_labels(self, axes):
x_label = OldTex("x")
x_label.next_to(axes.x_axis.get_end(), RIGHT)
axes.x_axis.label = x_label
t_label = OldTexText("Time")
t_label.rotate(90 * DEGREES, OUT)
t_label.next_to(axes.y_axis.get_end(), UP)
axes.y_axis.label = t_label
temp_label = OldTexText(self.temp_text)
temp_label.rotate(90 * DEGREES, RIGHT)
temp_label.next_to(axes.z_axis.get_zenith(), RIGHT)
axes.z_axis.label = temp_label
for axis in axes:
axis.add(axis.label)
return axes
def get_time_slice_graph(self, axes, func, t, **kwargs):
config = dict()
config.update(self.default_graph_style)
config.update({
"t_min": axes.x_min,
"t_max": axes.x_max,
})
config.update(kwargs)
return ParametricCurve(
lambda x: axes.c2p(
x, t, func(x, t)
),
**config,
)
def get_initial_state_graph(self, axes, func, **kwargs):
return self.get_time_slice_graph(
axes,
lambda x, t: func(x),
t=0,
**kwargs
)
def get_surface(self, axes, func, **kwargs):
config = {
"u_min": axes.y_min,
"u_max": axes.y_max,
"v_min": axes.x_min,
"v_max": axes.x_max,
"resolution": (
(axes.y_max - axes.y_min) // axes.y_axis.tick_frequency,
(axes.x_max - axes.x_min) // axes.x_axis.tick_frequency,
),
}
config.update(self.default_surface_config)
config.update(kwargs)
return ParametricSurface(
lambda t, x: axes.c2p(
x, t, func(x, t)
),
**config
)
def orient_three_d_mobject(self, mobject,
phi=85 * DEGREES,
theta=-80 * DEGREES):
mobject.rotate(-90 * DEGREES - theta, OUT)
mobject.rotate(phi, LEFT)
return mobject
def get_rod_length(self):
return self.axes_config["x_max"]
def get_const_time_plane(self, axes):
t_tracker = ValueTracker(0)
plane = Polygon(
*[
axes.c2p(x, 0, z)
for x, z in [
(axes.x_min, axes.z_min),
(axes.x_max, axes.z_min),
(axes.x_max, axes.z_max),
(axes.x_min, axes.z_max),
]
],
stroke_width=0,
fill_color=WHITE,
fill_opacity=0.2
)
plane.add_updater(lambda m: m.shift(
axes.c2p(
axes.x_min,
t_tracker.get_value(),
axes.z_min,
) - plane.get_points()[0]
))
plane.t_tracker = t_tracker
return plane
class SimpleCosExpGraph(TemperatureGraphScene):
def construct(self):
axes = self.get_three_d_axes()
cos_graph = self.get_cos_graph(axes)
cos_exp_surface = self.get_cos_exp_surface(axes)
self.set_camera_orientation(
phi=80 * DEGREES,
theta=-80 * DEGREES,
)
self.camera.frame_center.shift(3 * RIGHT)
self.begin_ambient_camera_rotation(rate=0.01)
self.add(axes)
self.play(ShowCreation(cos_graph))
self.play(UpdateFromAlphaFunc(
cos_exp_surface,
lambda m, a: m.become(
self.get_cos_exp_surface(axes, v_max=a * 10)
),
run_time=3
))
self.add(cos_graph.copy())
t_tracker = ValueTracker(0)
get_t = t_tracker.get_value
cos_graph.add_updater(
lambda m: m.become(self.get_time_slice_graph(
axes,
lambda x: self.cos_exp(x, get_t()),
t=get_t()
))
)
plane = Rectangle(
stroke_width=0,
fill_color=WHITE,
fill_opacity=0.1,
)
plane.rotate(90 * DEGREES, RIGHT)
plane.match_width(axes.x_axis)
plane.match_depth(axes.z_axis, stretch=True)
plane.move_to(axes.c2p(0, 0, 0), LEFT)
self.add(plane, cos_graph)
self.play(
ApplyMethod(
t_tracker.set_value, 10,
run_time=10,
rate_func=linear,
),
ApplyMethod(
plane.shift, 10 * UP,
run_time=10,
rate_func=linear,
),
VFadeIn(plane),
)
self.wait(10)
#
def cos_exp(self, x, t, A=2, omega=1.5, k=0.1):
return A * np.cos(omega * x) * np.exp(-k * (omega**2) * t)
def get_cos_graph(self, axes, **config):
return self.get_initial_state_graph(
axes,
lambda x: self.cos_exp(x, 0),
**config
)
def get_cos_exp_surface(self, axes, **config):
return self.get_surface(
axes,
lambda x, t: self.cos_exp(x, t),
**config
)
class AddMultipleSolutions(SimpleCosExpGraph):
CONFIG = {
"axes_config": {
"x_axis_config": {
"unit_size": 0.7,
},
}
}
def construct(self):
axes1, axes2, axes3 = all_axes = VGroup(*[
self.get_three_d_axes(
include_labels=False,
)
for x in range(3)
])
all_axes.scale(0.5)
self.orient_three_d_mobject(all_axes)
As = [1.5, 1.5]
omegas = [1.5, 2.5]
ks = [0.1, 0.1]
quads = [
(axes1, [As[0]], [omegas[0]], [ks[0]]),
(axes2, [As[1]], [omegas[1]], [ks[1]]),
(axes3, As, omegas, ks),
]
for axes, As, omegas, ks in quads:
graph = self.get_initial_state_graph(
axes,
lambda x: np.sum([
self.cos_exp(x, 0, A, omega, k)
for A, omega, k in zip(As, omegas, ks)
])
)
surface = self.get_surface(
axes,
lambda x, t: np.sum([
self.cos_exp(x, t, A, omega, k)
for A, omega, k in zip(As, omegas, ks)
])
)
surface.sort(lambda p: -p[2])
axes.add(surface, graph)
axes.graph = graph
axes.surface = surface
self.set_camera_orientation(distance=100)
plus = OldTex("+").scale(2)
equals = OldTex("=").scale(2)
group = VGroup(
axes1, plus, axes2, equals, axes3,
)
group.arrange(RIGHT, buff=SMALL_BUFF)
for axes in all_axes:
checkmark = OldTex("\\checkmark")
checkmark.set_color(GREEN)
checkmark.scale(2)
checkmark.next_to(axes, UP)
checkmark.shift(0.7 * DOWN)
axes.checkmark = checkmark
self.add(axes1, axes2)
self.play(
LaggedStart(
Write(axes1.surface),
Write(axes2.surface),
),
LaggedStart(
FadeIn(axes1.checkmark, DOWN),
FadeIn(axes2.checkmark, DOWN),
),
lag_ratio=0.2,
run_time=1,
)
self.wait()
self.play(Write(plus))
self.play(
Transform(
axes1.copy().set_fill(opacity=0),
axes3
),
Transform(
axes2.copy().set_fill(opacity=0),
axes3
),
FadeIn(equals, LEFT)
)
self.play(
FadeIn(axes3.checkmark, DOWN),
)
self.wait()
class BreakDownAFunction(SimpleCosExpGraph):
CONFIG = {
"axes_config": {
"z_axis_config": {
"unit_size": 0.75,
"include_tip": False,
},
"z_min": -2,
"y_max": 20,
},
"low_axes_config": {
"z_min": -3,
"z_axis_config": {"unit_size": 1}
},
"n_low_axes": 4,
"k": 0.2,
}
def construct(self):
self.set_camera_orientation(distance=100)
self.set_axes()
self.setup_graphs()
self.show_break_down()
self.show_solutions_for_waves()
def set_axes(self):
top_axes = self.get_three_d_axes()
top_axes.z_axis.label.next_to(
top_axes.z_axis.get_end(), OUT, SMALL_BUFF
)
top_axes.y_axis.set_opacity(0)
self.orient_three_d_mobject(top_axes)
top_axes.y_axis.label.rotate(-10 * DEGREES, UP)
top_axes.scale(0.75)
top_axes.center()
top_axes.to_edge(UP)
low_axes = self.get_three_d_axes(**self.low_axes_config)
low_axes.y_axis.set_opacity(0)
for axis in low_axes:
axis.label.fade(1)
# low_axes.add(low_axes.input_plane)
# low_axes.input_plane.set_opacity(0)
self.orient_three_d_mobject(low_axes)
low_axes_group = VGroup(*[
low_axes.deepcopy()
for x in range(self.n_low_axes)
])
low_axes_group.arrange(
RIGHT, buff=low_axes.get_width() / 3
)
low_axes_group.set_width(FRAME_WIDTH - 2.5)
low_axes_group.next_to(top_axes, DOWN, LARGE_BUFF)
low_axes_group.to_edge(LEFT)
self.top_axes = top_axes
self.low_axes_group = low_axes_group
def setup_graphs(self):
top_axes = self.top_axes
low_axes_group = self.low_axes_group
top_graph = self.get_initial_state_graph(
top_axes,
self.initial_func,
discontinuities=self.get_initial_func_discontinuities(),
color=YELLOW,
)
top_graph.set_stroke(width=4)
fourier_terms = self.get_fourier_cosine_terms(
self.initial_func
)
low_graphs = VGroup(*[
self.get_initial_state_graph(
axes,
lambda x: A * np.cos(n * x / 2)
)
for n, axes, A in zip(
it.count(),
low_axes_group,
fourier_terms
)
])
k = self.k
low_surfaces = VGroup(*[
self.get_surface(
axes,
lambda x, t: np.prod([
A,
np.cos(n * x / 2),
np.exp(-k * (n / 2)**2 * t)
])
)
for n, axes, A in zip(
it.count(),
low_axes_group,
fourier_terms
)
])
top_surface = self.get_surface(
top_axes,
lambda x, t: np.sum([
np.prod([
A,
np.cos(n * x / 2),
np.exp(-k * (n / 2)**2 * t)
])
for n, A in zip(
it.count(),
fourier_terms
)
])
)
self.top_graph = top_graph
self.low_graphs = low_graphs
self.low_surfaces = low_surfaces
self.top_surface = top_surface
def show_break_down(self):
top_axes = self.top_axes
low_axes_group = self.low_axes_group
top_graph = self.top_graph
low_graphs = self.low_graphs
plusses = VGroup(*[
OldTex("+").next_to(
axes.x_axis.get_end(),
RIGHT, MED_SMALL_BUFF
)
for axes in low_axes_group
])
dots = OldTex("\\cdots")
dots.next_to(plusses, RIGHT, MED_SMALL_BUFF)
arrow = Arrow(
dots.get_right(),
top_graph.get_end() + 1.4 * DOWN + 1.7 * RIGHT,
path_arc=90 * DEGREES,
)
top_words = OldTexText("Arbitrary\\\\function")
top_words.next_to(top_axes, LEFT, MED_LARGE_BUFF)
top_words.set_color(YELLOW)
top_arrow = Arrow(
top_words.get_right(),
top_graph.point_from_proportion(0.3)
)
low_words = OldTexText("Sine curves")
low_words.set_color(BLUE)
low_words.next_to(low_axes_group, DOWN, MED_LARGE_BUFF)
self.add(top_axes)
self.play(ShowCreation(top_graph))
self.play(
FadeIn(top_words, RIGHT),
ShowCreation(top_arrow)
)
self.wait()
self.play(
LaggedStartMap(FadeIn, low_axes_group),
FadeIn(low_words, UP),
LaggedStartMap(FadeInFromDown, [*plusses, dots]),
*[
TransformFromCopy(top_graph, low_graph)
for low_graph in low_graphs
],
)
self.play(ShowCreation(arrow))
self.wait()
def show_solutions_for_waves(self):
low_axes_group = self.low_axes_group
top_axes = self.top_axes
low_graphs = self.low_graphs
low_surfaces = self.low_surfaces
top_surface = self.top_surface
top_graph = self.top_graph
for surface in [top_surface, *low_surfaces]:
surface.sort(lambda p: -p[2])
anims1 = []
anims2 = [
ApplyMethod(
top_axes.y_axis.set_opacity, 1,
),
]
for axes, surface, graph in zip(low_axes_group, low_surfaces, low_graphs):
axes.y_axis.set_opacity(1)
axes.y_axis.label.fade(1)
anims1 += [
ShowCreation(axes.y_axis),
Write(surface, run_time=2),
]
anims2.append(AnimationGroup(
TransformFromCopy(graph, top_graph.copy()),
Transform(
surface.copy().set_fill(opacity=0),
top_surface,
)
))
self.play(*anims1)
self.wait()
self.play(LaggedStart(*anims2, run_time=2))
self.wait()
checkmark = OldTex("\\checkmark")
checkmark.set_color(GREEN)
low_checkmarks = VGroup(*[
checkmark.copy().next_to(
surface.get_top(), UP, SMALL_BUFF
)
for surface in low_surfaces
])
top_checkmark = checkmark.copy()
top_checkmark.scale(1.5)
top_checkmark.move_to(top_axes.get_corner(UR))
self.play(LaggedStartMap(FadeInFromDown, low_checkmarks))
self.wait()
self.play(*[
TransformFromCopy(low_checkmark, top_checkmark.copy())
for low_checkmark in low_checkmarks
])
self.wait()
#
def initial_func(self, x):
# return 3 * np.exp(-(x - PI)**2)
x1 = TAU / 4 - 1
x2 = TAU / 4 + 1
x3 = 3 * TAU / 4 - 1.6
x4 = 3 * TAU / 4 + 0.3
T0 = -2
T1 = 2
T2 = 1
if x < x1:
return T0
elif x < x2:
alpha = inverse_interpolate(x1, x2, x)
return bezier([T0, T0, T1, T1])(alpha)
elif x < x3:
return T1
elif x < x4:
alpha = inverse_interpolate(x3, x4, x)
return bezier([T1, T1, T2, T2])(alpha)
else:
return T2
def get_initial_func_discontinuities(self):
# return [TAU / 4, 3 * TAU / 4]
return []
def get_fourier_cosine_terms(self, func, n_terms=40):
result = [
integrate.quad(
lambda x: (1 / PI) * func(x) * np.cos(n * x / 2),
0, TAU
)[0]
for n in range(n_terms)
]
result[0] = result[0] / 2
return result
class OceanOfPossibilities(TemperatureGraphScene):
CONFIG = {
"axes_config": {
"z_min": 0,
"z_max": 4,
},
"k": 0.2,
"default_surface_config": {
# "resolution": (32, 20),
# "resolution": (8, 5),
}
}
def construct(self):
self.setup_camera()
self.setup_axes()
self.setup_surface()
self.show_solution()
self.reference_boundary_conditions()
self.reference_initial_condition()
self.ambiently_change_solution()
def setup_camera(self):
self.set_camera_orientation(
phi=80 * DEGREES,
theta=-80 * DEGREES,
)
self.begin_ambient_camera_rotation(rate=0.01)
def setup_axes(self):
axes = self.get_three_d_axes(include_numbers=True)
axes.add(axes.input_plane)
axes.scale(0.8)
axes.center()
axes.shift(OUT + RIGHT)
self.add(axes)
self.axes = axes
def setup_surface(self):
axes = self.axes
k = self.k
# Parameters for surface function
initial_As = [2] + [
0.8 * random.choice([-1, 1]) / n
for n in range(1, 20)
]
A_trackers = Group(*[
ValueTracker(A)
for A in initial_As
])
def get_As():
return [At.get_value() for At in A_trackers]
omegas = [n / 2 for n in range(0, 10)]
def func(x, t):
return np.sum([
np.prod([
A * np.cos(omega * x),
np.exp(-k * omega**2 * t)
])
for A, omega in zip(get_As(), omegas)
])
# Surface and graph
surface = always_redraw(
lambda: self.get_surface(axes, func)
)
t_tracker = ValueTracker(0)
graph = always_redraw(
lambda: self.get_time_slice_graph(
axes, func, t_tracker.get_value(),
)
)
surface.suspend_updating()
graph.suspend_updating()
self.surface_func = func
self.surface = surface
self.graph = graph
self.t_tracker = t_tracker
self.A_trackers = A_trackers
self.omegas = omegas
def show_solution(self):
axes = self.axes
surface = self.surface
graph = self.graph
t_tracker = self.t_tracker
get_t = t_tracker.get_value
opacity_tracker = ValueTracker(0)
plane = always_redraw(lambda: Polygon(
*[
axes.c2p(x, get_t(), T)
for x, T in [
(0, 0), (TAU, 0), (TAU, 4), (0, 4)
]
],
stroke_width=0,
fill_color=WHITE,
fill_opacity=opacity_tracker.get_value(),
))
self.add(surface, plane, graph)
graph.resume_updating()
self.play(
opacity_tracker.set_value, 0.2,
ApplyMethod(
t_tracker.set_value, 1,
rate_func=linear
),
run_time=1
)
self.play(
ApplyMethod(
t_tracker.set_value, 10,
rate_func=linear,
run_time=9
)
)
self.wait()
self.plane = plane
def reference_boundary_conditions(self):
axes = self.axes
t_numbers = axes.y_axis.numbers
lines = VGroup(*[
Line(
axes.c2p(x, 0, 0),
axes.c2p(x, axes.y_max, 0),
stroke_width=3,
stroke_color=MAROON_B,
)
for x in [0, axes.x_max]
])
surface_boundary_lines = always_redraw(lambda: VGroup(*[
ParametricCurve(
lambda t: axes.c2p(
x, t,
self.surface_func(x, t)
),
t_max=axes.y_max
).match_style(self.graph)
for x in [0, axes.x_max]
]))
# surface_boundary_lines.suspend_updating()
words = VGroup()
for line in lines:
word = OldTexText("Boundary")
word.set_stroke(BLACK, 3, background=True)
word.scale(1.5)
word.match_color(line)
word.rotate(90 * DEGREES, RIGHT)
word.rotate(90 * DEGREES, OUT)
word.next_to(line, OUT, SMALL_BUFF)
words.add(word)
self.stop_ambient_camera_rotation()
self.move_camera(
theta=-45 * DEGREES,
added_anims=[
LaggedStartMap(ShowCreation, lines),
LaggedStartMap(
FadeInFrom, words,
lambda m: (m, IN)
),
FadeOut(t_numbers),
]
)
self.play(
LaggedStart(*[
TransformFromCopy(l1, l2)
for l1, l2 in zip(lines, surface_boundary_lines)
])
)
self.add(surface_boundary_lines)
self.wait()
self.move_camera(
theta=-70 * DEGREES,
)
self.surface_boundary_lines = surface_boundary_lines
def reference_initial_condition(self):
plane = self.plane
t_tracker = self.t_tracker
self.play(
t_tracker.set_value, 0,
run_time=2
)
plane.clear_updaters()
self.play(FadeOut(plane))
def ambiently_change_solution(self):
A_trackers = self.A_trackers
def generate_A_updater(A, rate):
def update(m, dt):
m.total_time += dt
m.set_value(
2 * A * np.sin(rate * m.total_time + PI / 6)
)
return update
rates = [0, 0.2] + [
0.5 + 0.5 * np.random.random()
for x in range(len(A_trackers) - 2)
]
for tracker, rate in zip(A_trackers, rates):
tracker.total_time = 0
tracker.add_updater(generate_A_updater(
tracker.get_value(),
rate
))
self.add(*A_trackers)
self.surface_boundary_lines.resume_updating()
self.surface.resume_updating()
self.graph.resume_updating()
self.begin_ambient_camera_rotation(rate=0.01)
self.wait(30)
class AnalyzeSineCurve(TemperatureGraphScene):
CONFIG = {
"origin_point": 3 * LEFT,
"axes_config": {
"z_min": -1.5,
"z_max": 1.5,
"z_axis_config": {
"unit_size": 2,
"tick_frequency": 0.5,
}
},
"tex_to_color_map": {
"{x}": GREEN,
"T": YELLOW,
"=": WHITE,
"0": WHITE,
"\\Delta t": WHITE,
"\\sin": WHITE,
"{t}": PINK,
}
}
def construct(self):
self.setup_axes()
self.ask_about_sine_curve()
self.show_sine_wave_on_axes()
self.reference_curvature()
self.show_derivatives()
self.show_curvature_matching_height()
self.show_time_step_scalings()
self.smooth_evolution()
def setup_axes(self):
axes = self.get_three_d_axes()
axes.rotate(90 * DEGREES, LEFT)
axes.shift(self.origin_point - axes.c2p(0, 0, 0))
y_axis = axes.y_axis
y_axis.fade(1)
z_axis = axes.z_axis
z_axis.label.next_to(z_axis.get_end(), UP, SMALL_BUFF)
self.add_axes_numbers(axes)
y_axis.remove(y_axis.numbers)
axes.z_axis.add_numbers(
*range(-1, 2),
direction=LEFT,
)
self.axes = axes
def ask_about_sine_curve(self):
curve = FunctionGraph(
lambda t: np.sin(t),
x_min=0,
x_max=TAU,
)
curve.move_to(DR)
curve.set_width(5)
curve.set_color(YELLOW)
question = OldTexText("What's so special?")
question.scale(1.5)
question.to_edge(UP)
question.shift(2 * LEFT)
arrow = Arrow(
question.get_bottom(),
curve.point_from_proportion(0.25)
)
self.play(
ShowCreation(curve),
Write(question, run_time=1),
GrowArrow(arrow),
)
self.wait()
self.quick_sine_curve = curve
self.question_group = VGroup(question, arrow)
def show_sine_wave_on_axes(self):
axes = self.axes
graph = self.get_initial_state_graph(
axes, lambda x: np.sin(x)
)
graph.set_stroke(width=4)
graph_label = OldTex(
"T({x}, 0) = \\sin\\left({x}\\right)",
tex_to_color_map=self.tex_to_color_map,
)
graph_label.next_to(
graph.point_from_proportion(0.25), UR,
buff=SMALL_BUFF,
)
v_line, x_tracker = self.get_v_line_with_x_tracker(graph)
xs = VGroup(
*graph_label.get_parts_by_tex("x"),
axes.x_axis.label,
)
self.play(
Write(axes),
self.quick_sine_curve.become, graph,
FadeOut(self.question_group, UP),
)
self.play(
FadeInFromDown(graph_label),
FadeIn(graph),
)
self.remove(self.quick_sine_curve)
self.add(v_line)
self.play(
ApplyMethod(
x_tracker.set_value, TAU,
rate_func=lambda t: smooth(t, 3),
run_time=5,
),
LaggedStartMap(
ShowCreationThenFadeAround, xs,
run_time=3,
lag_ratio=0.2,
)
)
self.remove(v_line, x_tracker)
self.wait()
self.graph = graph
self.graph_label = graph_label
self.v_line = v_line
self.x_tracker = x_tracker
def reference_curvature(self):
curve_segment, curve_x_tracker = \
self.get_curve_segment_with_x_tracker(self.graph)
self.add(curve_segment)
self.play(
curve_x_tracker.set_value, TAU,
run_time=5,
rate_func=lambda t: smooth(t, 3),
)
self.play(FadeOut(curve_segment))
self.curve_segment = curve_segment
self.curve_x_tracker = curve_x_tracker
def show_derivatives(self):
deriv1 = OldTex(
"{\\partial T \\over \\partial {x}}({x}, 0)",
"= \\cos\\left({x}\\right)",
tex_to_color_map=self.tex_to_color_map,
)
deriv2 = OldTex(
"{\\partial^2 T \\over \\partial {x}^2}({x}, 0)",
"= -\\sin\\left({x}\\right)",
tex_to_color_map=self.tex_to_color_map,
)
deriv1.to_corner(UR)
deriv2.next_to(
deriv1, DOWN,
buff=0.75,
aligned_edge=LEFT,
)
VGroup(deriv1, deriv2).shift(1.4 * RIGHT)
self.play(
Animation(Group(*self.get_mobjects())),
FadeIn(deriv1, LEFT),
self.camera.frame_center.shift, 2 * RIGHT,
)
self.wait()
self.play(
FadeIn(deriv2, UP)
)
self.wait()
self.deriv1 = deriv1
self.deriv2 = deriv2
def show_curvature_matching_height(self):
axes = self.axes
graph = self.graph
curve_segment = self.curve_segment
curve_x_tracker = self.curve_x_tracker
d2_graph = self.get_initial_state_graph(
axes, lambda x: -np.sin(x),
)
dashed_d2_graph = DashedVMobject(d2_graph, num_dashes=50)
dashed_d2_graph.color_using_background_image(None)
dashed_d2_graph.set_stroke(RED, 2)
vector, x_tracker = self.get_v_line_with_x_tracker(
d2_graph,
line_creator=lambda p1, p2: Arrow(
p1, p2, color=RED, buff=0
)
)
lil_vectors = self.get_many_lil_vectors(graph)
lil_vector = always_redraw(
lambda: self.get_lil_vector(
graph, x_tracker.get_value()
)
)
d2_rect = SurroundingRectangle(
self.deriv2[-5:],
color=RED,
)
self.play(ShowCreation(d2_rect))
self.add(vector)
self.add(lil_vector)
self.add(curve_segment)
curve_x_tracker.set_value(0)
self.play(
ShowCreation(dashed_d2_graph),
x_tracker.set_value, TAU,
curve_x_tracker.set_value, TAU,
ShowIncreasingSubsets(lil_vectors[1:]),
run_time=8,
rate_func=linear,
)
self.remove(vector)
self.remove(lil_vector)
self.add(lil_vectors)
self.play(
FadeOut(curve_segment),
FadeOut(d2_rect),
)
self.lil_vectors = lil_vectors
self.dashed_d2_graph = dashed_d2_graph
def show_time_step_scalings(self):
axes = self.axes
graph_label = self.graph_label
dashed_d2_graph = self.dashed_d2_graph
lil_vectors = self.lil_vectors
graph = self.graph
factor = 0.9
new_label = OldTex(
"T({x}, \\Delta t) = c \\cdot \\sin\\left({x}\\right)",
tex_to_color_map=self.tex_to_color_map,
)
final_label = OldTex(
"T({x}, {t}) = (\\text{something}) \\cdot \\sin\\left({x}\\right)",
tex_to_color_map=self.tex_to_color_map,
)
for label in (new_label, final_label):
label.shift(
graph_label.get_part_by_tex("=").get_center() -
label.get_part_by_tex("=").get_center()
)
final_label.shift(1.5 * LEFT)
h_lines = VGroup(
DashedLine(axes.c2p(0, 0, 1), axes.c2p(TAU, 0, 1)),
DashedLine(axes.c2p(0, 0, -1), axes.c2p(TAU, 0, -1)),
)
lil_vectors.add_updater(lambda m: m.become(
self.get_many_lil_vectors(graph)
))
i = 4
self.play(
ReplacementTransform(
graph_label[:i], new_label[:i],
),
ReplacementTransform(
graph_label[i + 1:i + 3],
new_label[i + 1:i + 3],
),
FadeOut(graph_label[i], UP),
FadeIn(new_label[i], DOWN),
)
self.play(
ReplacementTransform(
graph_label[i + 3:],
new_label[i + 4:]
),
FadeInFromDown(new_label[i + 3])
)
self.play(
FadeOut(dashed_d2_graph),
FadeIn(h_lines),
)
self.play(
graph.stretch, factor, 1,
h_lines.stretch, factor, 1,
)
self.wait()
# Repeat
last_coef = None
last_exp = None
delta_T = new_label.get_part_by_tex("\\Delta t")
c = new_label.get_part_by_tex("c")[0]
prefix = new_label[:4]
prefix.generate_target()
for x in range(5):
coef = Integer(x + 2)
exp = coef.copy().scale(0.7)
coef.next_to(
delta_T, LEFT, SMALL_BUFF,
aligned_edge=DOWN,
)
exp.move_to(c.get_corner(UR), DL)
anims1 = [FadeIn(coef, 0.25 * DOWN)]
anims2 = [FadeIn(exp, 0.25 * DOWN)]
if last_coef:
anims1.append(
FadeOut(last_coef, 0.25 * UP)
)
anims2.append(
FadeOut(last_exp, 0.25 * UP)
)
last_coef = coef
last_exp = exp
prefix.target.next_to(coef, LEFT, SMALL_BUFF)
prefix.target.match_y(prefix)
anims1.append(MoveToTarget(prefix))
self.play(*anims1)
self.play(
graph.stretch, factor, 1,
h_lines.stretch, factor, 1,
*anims2,
)
self.play(
ReplacementTransform(
new_label[:4],
final_label[:4],
),
ReplacementTransform(
VGroup(last_coef, delta_T),
final_label.get_part_by_tex("{t}"),
),
ReplacementTransform(
last_exp,
final_label.get_part_by_tex("something"),
),
FadeOut(new_label.get_part_by_tex("\\cdot"), UP),
ReplacementTransform(
new_label[-4:],
final_label[-4:],
),
ReplacementTransform(
new_label.get_part_by_tex("="),
final_label.get_part_by_tex("="),
),
ReplacementTransform(
new_label.get_part_by_tex(")"),
final_label.get_part_by_tex(")"),
),
)
final_label.add_background_rectangle(opacity=1)
self.add(final_label)
self.wait()
group = VGroup(graph, h_lines)
group.add_updater(lambda m, dt: m.stretch(
(1 - 0.1 * dt), 1
))
self.add(group)
self.wait(10)
def smooth_evolution(self):
pass
#
def get_rod(self, temp_func):
pass
def get_v_line_with_x_tracker(self, graph, line_creator=DashedLine):
axes = self.axes
x_min = axes.x_axis.p2n(graph.get_start())
x_max = axes.x_axis.p2n(graph.get_end())
x_tracker = ValueTracker(x_min)
get_x = x_tracker.get_value
v_line = always_redraw(lambda: line_creator(
axes.c2p(get_x(), 0, 0),
graph.point_from_proportion(
inverse_interpolate(
x_min, x_max, get_x()
)
),
))
return v_line, x_tracker
def get_curve_segment_with_x_tracker(self, graph, delta_x=0.5):
axes = self.axes
x_min = axes.x_axis.p2n(graph.get_start())
x_max = axes.x_axis.p2n(graph.get_end())
x_tracker = ValueTracker(x_min)
get_x = x_tracker.get_value
def x2a(x):
return inverse_interpolate(x_min, x_max, x)
curve = VMobject(
stroke_color=WHITE,
stroke_width=5
)
curve.add_updater(lambda m: m.pointwise_become_partial(
graph,
max(x2a(get_x() - delta_x), 0),
min(x2a(get_x() + delta_x), 1),
))
return curve, x_tracker
def get_lil_vector(self, graph, x):
x_axis = self.axes.x_axis
point = graph.point_from_proportion(x / TAU)
x_axis_point = x_axis.n2p(x_axis.p2n(point))
return Arrow(
point,
interpolate(
point, x_axis_point, 0.5,
),
buff=0,
color=RED
)
def get_many_lil_vectors(self, graph, n=13):
return VGroup(*[
self.get_lil_vector(graph, x)
for x in np.linspace(0, TAU, n)
])
class SineWaveScaledByExp(TemperatureGraphScene):
CONFIG = {
"axes_config": {
"z_min": -1.5,
"z_max": 1.5,
"z_axis_config": {
"unit_size": 2,
"tick_frequency": 0.5,
"label_direction": LEFT,
},
"y_axis_config": {
"label_direction": RIGHT,
},
},
"k": 0.3,
}
def construct(self):
self.setup_axes()
self.setup_camera()
self.show_sine_wave()
self.show_decay_surface()
self.linger_at_end()
def setup_axes(self):
axes = self.get_three_d_axes()
# Add number labels
self.add_axes_numbers(axes)
for axis in [axes.x_axis, axes.y_axis]:
axis.numbers.rotate(
90 * DEGREES,
axis=axis.get_vector(),
about_point=axis.point_from_proportion(0.5)
)
axis.numbers.set_shade_in_3d(True)
axes.z_axis.add_numbers(*range(-1, 2))
for number in axes.z_axis.numbers:
number.rotate(90 * DEGREES, RIGHT)
axes.z_axis.label.next_to(
axes.z_axis.get_end(), OUT,
)
# Input plane
axes.input_plane.set_opacity(0.25)
self.add(axes.input_plane)
# Shift into place
# axes.shift(5 * LEFT)
self.axes = axes
self.add(axes)
def setup_camera(self):
self.set_camera_orientation(
phi=80 * DEGREES,
theta=-80 * DEGREES,
distance=50,
)
self.camera.frame.move_to(2 * RIGHT)
def show_sine_wave(self):
time_tracker = ValueTracker(0)
graph = always_redraw(
lambda: self.get_time_slice_graph(
self.axes,
self.sin_exp,
t=time_tracker.get_value(),
)
)
graph.suspend_updating()
graph_label = OldTex("\\sin(x)")
graph_label.set_color(BLUE)
graph_label.rotate(90 * DEGREES, RIGHT)
graph_label.next_to(
graph.point_from_proportion(0.25),
OUT,
SMALL_BUFF,
)
self.play(
ShowCreation(graph),
FadeIn(graph_label, IN)
)
self.wait()
graph.resume_updating()
self.time_tracker = time_tracker
self.graph = graph
def show_decay_surface(self):
time_tracker = self.time_tracker
axes = self.axes
plane = Rectangle()
plane.rotate(90 * DEGREES, RIGHT)
plane.set_stroke(width=0)
plane.set_fill(WHITE, 0.2)
plane.match_depth(axes.z_axis)
plane.match_width(axes.x_axis, stretch=True)
plane.add_updater(
lambda p: p.move_to(axes.c2p(
0,
time_tracker.get_value(),
0,
), LEFT)
)
time_slices = VGroup(*[
self.get_time_slice_graph(
self.axes,
self.sin_exp,
t=t,
)
for t in range(0, 10)
])
surface_t_tracker = ValueTracker(0)
surface = always_redraw(
lambda: self.get_surface(
self.axes,
self.sin_exp,
v_max=surface_t_tracker.get_value(),
).set_stroke(opacity=0)
)
exp_graph = ParametricCurve(
lambda t: axes.c2p(
PI / 2,
t,
self.sin_exp(PI / 2, t)
),
t_min=axes.y_min,
t_max=axes.y_max,
)
exp_graph.set_stroke(RED, 3)
exp_graph.set_shade_in_3d(True)
exp_label = OldTex("e^{-\\alpha t}")
exp_label.scale(1.5)
exp_label.set_color(RED)
exp_label.rotate(90 * DEGREES, RIGHT)
exp_label.rotate(90 * DEGREES, OUT)
exp_label.next_to(
exp_graph.point_from_proportion(0.3),
OUT + UP,
)
self.move_camera(
theta=-25 * DEGREES,
)
self.add(surface)
self.add(plane)
self.play(
surface_t_tracker.set_value, axes.y_max,
time_tracker.set_value, axes.y_max,
ShowIncreasingSubsets(
time_slices,
int_func=np.ceil,
),
run_time=5,
rate_func=linear,
)
surface.clear_updaters()
self.play(
ShowCreation(exp_graph),
FadeOut(plane),
FadeIn(exp_label, IN),
time_slices.set_stroke, {"width": 1},
)
def linger_at_end(self):
self.wait()
self.begin_ambient_camera_rotation(rate=-0.02)
self.wait(20)
#
def sin_exp(self, x, t):
return np.sin(x) * np.exp(-self.k * t)
class BoundaryConditionReference(ShowEvolvingTempGraphWithArrows):
def construct(self):
self.setup_axes()
self.setup_graph()
rod = self.get_rod(0, 10)
self.color_rod_by_graph(rod)
boundary_points = [
rod.get_right(),
rod.get_left(),
]
boundary_dots = VGroup(*[
Dot(point, radius=0.2)
for point in boundary_points
])
boundary_arrows = VGroup(*[
Vector(2 * DOWN).next_to(dot, UP)
for dot in boundary_dots
])
boundary_arrows.set_stroke(YELLOW, 10)
words = OldTexText(
"Different rules\\\\",
"at the boundary",
)
words.scale(1.5)
words.to_edge(UP)
# self.add(self.axes)
# self.add(self.graph)
self.add(rod)
self.play(FadeInFromDown(words))
self.play(
LaggedStartMap(GrowArrow, boundary_arrows),
LaggedStartMap(GrowFromCenter, boundary_dots),
lag_ratio=0.3,
run_time=1,
)
self.wait()
class SimulateRealSineCurve(ShowEvolvingTempGraphWithArrows):
CONFIG = {
"axes_config": {
"x_min": 0,
"x_max": TAU,
"x_axis_config": {
"unit_size": 1.5,
"include_tip": False,
"tick_frequency": PI / 4,
},
"y_min": -1.5,
"y_max": 1.5,
"y_axis_config": {
"tick_frequency": 0.5,
"unit_size": 2,
},
},
"graph_x_min": 0,
"graph_x_max": TAU,
"arrow_xs": np.linspace(0, TAU, 13),
"rod_opacity": 0.5,
"wait_time": 30,
"alpha": 0.5,
}
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_labels_to_axes(self):
x_axis = self.axes.x_axis
x_axis.add(*[
OldTex(tex).scale(0.5).next_to(
x_axis.n2p(n),
DOWN,
buff=MED_SMALL_BUFF
)
for tex, n in [
("\\tau \\over 4", TAU / 4),
("\\tau \\over 2", TAU / 2),
("3 \\tau \\over 4", 3 * TAU / 4),
("\\tau", TAU),
]
])
def add_axes(self):
super().add_axes()
self.add_labels_to_axes()
def add_rod(self):
super().add_rod()
self.rod.set_opacity(self.rod_opacity)
self.rod.set_stroke(width=0)
def initial_function(self, x):
return np.sin(x)
def y_to_color(self, y):
return temperature_to_color(0.8 * y)
class StraightLine3DGraph(TemperatureGraphScene):
CONFIG = {
"axes_config": {
"z_min": 0,
"z_max": 10,
"z_axis_config": {
'unit_size': 0.5,
}
},
"c": 1.2,
}
def construct(self):
axes = self.get_three_d_axes()
axes.add(axes.input_plane)
axes.move_to(2 * IN + UP, IN)
surface = self.get_surface(
axes, self.func,
)
initial_graph = self.get_initial_state_graph(
axes, lambda x: self.func(x, 0)
)
plane = self.get_const_time_plane(axes)
initial_graph.add_updater(
lambda m: m.move_to(plane, IN)
)
self.set_camera_orientation(
phi=80 * DEGREES,
theta=-100 * DEGREES,
)
self.begin_ambient_camera_rotation()
self.add(axes)
self.add(initial_graph)
self.play(
TransformFromCopy(initial_graph, surface)
)
self.add(surface, initial_graph)
self.wait()
self.play(
FadeIn(plane),
ApplyMethod(
plane.t_tracker.set_value, 10,
rate_func=linear,
run_time=10,
)
)
self.play(FadeOut(plane))
self.wait(15)
def func(self, x, t):
return self.c * x
class SimulateLinearGraph(SimulateRealSineCurve):
CONFIG = {
"axes_config": {
"y_min": 0,
"y_max": 3,
"y_axis_config": {
"tick_frequency": 0.5,
"unit_size": 2,
},
},
"arrow_scale_factor": 2,
"alpha": 1,
"wait_time": 40,
"step_size": 0.02,
}
# def let_play(self):
# pass
def add_labels_to_axes(self):
pass
def y_to_color(self, y):
return temperature_to_color(0.8 * (y - 1.5))
def initial_function(self, x):
axes = self.axes
y_max = axes.y_max
x_max = axes.x_max
slope = y_max / x_max
return slope * x
class EmphasizeBoundaryPoints(SimulateLinearGraph):
CONFIG = {
"wait_time": 30,
}
def let_play(self):
rod = self.rod
self.graph.update(0.01)
self.arrows.update()
to_update = VGroup(
self.graph,
self.arrows,
self.time_label,
)
for mob in to_update:
mob.suspend_updating()
dots = VGroup(
Dot(rod.get_left()),
Dot(rod.get_right()),
)
for dot in dots:
dot.set_height(0.2)
dot.set_color(YELLOW)
words = OldTexText(
"Different rules\\\\"
"at the boundary"
)
words.next_to(rod, UP)
arrows = VGroup(*[
Arrow(
words.get_corner(corner),
dot.get_top(),
path_arc=u * 60 * DEGREES,
)
for corner, dot, u in zip(
[LEFT, RIGHT], dots, [1, -1]
)
])
self.add(words)
self.play(
LaggedStartMap(
FadeInFromLarge, dots,
scale_factor=5,
),
LaggedStartMap(
ShowCreation, arrows,
),
lag_ratio=0.4
)
self.wait()
for mob in to_update:
mob.resume_updating()
super().let_play()
class FlatEdgesContinuousEvolution(ShowEvolvingTempGraphWithArrows):
CONFIG = {
"wait_time": 30,
"freq_amplitude_pairs": [
(1, 0.5),
(2, 1),
(3, 0.5),
(4, 0.3),
],
}
def construct(self):
self.add_axes()
self.add_graph()
self.add_clock()
self.add_rod()
self.initialize_updaters()
self.add_boundary_lines()
self.let_play()
def add_boundary_lines(self):
lines = VGroup(*[
Line(LEFT, RIGHT)
for x in range(2)
])
lines.set_width(1.5)
lines.set_stroke(WHITE, 5, opacity=0.5)
lines.add_updater(self.update_lines)
turn_animation_into_updater(
ShowCreation(lines, run_time=2)
)
self.add(lines)
def update_lines(self, lines):
graph = self.graph
lines[0].move_to(graph.get_start())
lines[1].move_to(graph.get_end())
def initial_function(self, x):
return ShowEvolvingTempGraphWithArrows.initial_function(self, x)
class MoreAccurateTempFlowWithArrows(ShowEvolvingTempGraphWithArrows):
CONFIG = {
"arrow_scale_factor": 1,
"max_magnitude": 1,
"freq_amplitude_pairs": [
(1, 0.5),
(2, 1),
(3, 0.5),
(4, 0.3),
],
}
def setup_axes(self):
super().setup_axes()
y_axis = self.axes.y_axis
y_axis.remove(y_axis.label)
class SlopeToHeatFlow(FlatEdgesContinuousEvolution):
CONFIG = {
"wait_time": 20,
"xs": [1.75, 5.25, 7.8],
"axes_config": {
"x_min": 0,
"x_max": 10,
"x_axis_config": {
"include_tip": False,
}
},
"n_arrows": 10,
"random_seed": 1,
}
def construct(self):
self.add_axes()
self.add_graph()
self.add_rod()
#
self.show_slope_labels()
self.show_heat_flow()
def show_slope_labels(self):
axes = self.axes
# axes.x_axis.add_numbers()
graph = self.graph
xs = self.xs
lines = VGroup(*[
TangentLine(
graph,
inverse_interpolate(
axes.x_min,
axes.x_max,
x
),
length=2,
stroke_opacity=0.75,
)
for x in xs
])
slope_words = VGroup()
for line in lines:
slope = line.get_slope()
word = OldTexText(
"Slope =",
"${:.2}$".format(slope)
)
if slope > 0:
word[1].set_color(GREEN)
else:
word[1].set_color(RED)
word.set_width(line.get_length())
word.next_to(ORIGIN, UP, SMALL_BUFF)
word.rotate(
line.get_angle(),
about_point=ORIGIN,
)
word.shift(line.get_center())
slope_words.add(word)
self.play(
LaggedStartMap(ShowCreation, lines),
LaggedStartMap(Write, slope_words),
lag_ratio=0.5,
run_time=1,
)
self.wait()
self.lines = lines
self.slope_words = slope_words
def show_heat_flow(self):
axes = self.axes
xs = self.xs
slope_words = self.slope_words
tan_lines = self.lines
slopes = map(Line.get_slope, self.lines)
flow_rates = [-s for s in slopes]
points = list(map(axes.x_axis.n2p, xs))
v_lines = VGroup(*[
Line(
line.get_center(), point,
stroke_width=1,
)
for point, line in zip(points, tan_lines)
])
flow_words = VGroup(*[
OldTexText("Heat flow").next_to(
point, DOWN
).scale(0.8)
for point in points
])
flow_mobjects = VGroup(*[
self.get_flow(x, flow_rate)
for x, flow_rate in zip(xs, flow_rates)
])
self.add(flow_mobjects)
self.wait()
self.play(
LaggedStart(*[
TransformFromCopy(
sw[0], fw[0]
)
for sw, fw in zip(slope_words, flow_words)
]),
LaggedStartMap(ShowCreation, v_lines),
lag_ratio=0.4,
run_time=2,
)
self.wait(self.wait_time)
def get_flow(self, x, flow_rate):
return VGroup(*[
self.get_single_flow_arrow(
x, flow_rate,
t_offset=to
)
for to in np.linspace(0, 5, self.n_arrows)
])
def get_single_flow_arrow(self, x, flow_rate, t_offset):
axes = self.axes
point = axes.x_axis.n2p(x)
h_shift = 0.5
v_shift = 0.4 * np.random.random() + 0.1
arrow = Vector(0.5 * RIGHT * np.sign(flow_rate))
arrow.move_to(point)
arrow.shift(v_shift * UP)
lp = arrow.get_center() + h_shift * LEFT
rp = arrow.get_center() + h_shift * RIGHT
lc = self.rod_point_to_color(lp)
rc = self.rod_point_to_color(rp)
run_time = 3 / flow_rate
animation = UpdateFromAlphaFunc(
arrow,
lambda m, a: m.move_to(
interpolate(lp, rp, a)
).set_color(
interpolate_color(lc, rc, a)
).set_opacity(there_and_back(a)),
run_time=run_time,
)
result = cycle_animation(animation)
animation.total_time += t_offset
return result
class CloserLookAtStraightLine(SimulateLinearGraph):
def construct(self):
self.add_axes()
self.add_graph()
self.add_clock()
self.add_rod()
# self.initialize_updaters()
#
self.show_t_eq_0_state()
self.show_t_gt_0_state()
def show_t_eq_0_state(self):
t_eq = OldTex("t", "=", "0")
t_eq.next_to(self.time_label, DOWN)
circles = VGroup(*[
Circle(
radius=0.25,
stroke_color=YELLOW,
)
for x in range(2)
])
circles.add_updater(self.attach_to_endpoints)
self.play(Write(t_eq))
self.play(ShowCreation(circles))
self.wait()
self.play(FadeOut(circles))
self.circles = circles
self.t_eq = t_eq
def show_t_gt_0_state(self):
# circles = self.circles
t_eq = self.t_eq
t_ineq = OldTex("t", ">", "0")
t_ineq.move_to(t_eq)
slope_lines = VGroup(*[
Line(LEFT, RIGHT)
for x in range(2)
])
slope_lines.set_opacity(0.5)
slope_lines.add_updater(self.attach_to_endpoints)
self.remove(t_eq)
self.add(t_ineq)
self.initialize_updaters()
self.run_clock(0.1)
for mob in self.mobjects:
mob.suspend_updating()
self.wait()
self.add(slope_lines)
self.add(self.clock, self.time_label, t_ineq)
self.play(ShowCreation(slope_lines))
for mob in self.mobjects:
mob.resume_updating()
self.run_clock(self.wait_time)
#
def attach_to_endpoints(self, mobs):
points = [
self.graph.get_start(),
self.graph.get_end(),
]
for mob, point in zip(mobs, points):
mob.move_to(point)
return mobs
class ManipulateSinExpSurface(TemperatureGraphScene):
CONFIG = {
"axes_config": {
"z_max": 1.25,
"z_min": -1.25,
"z_axis_config": {
"unit_size": 2.5,
"tick_frequency": 0.5,
},
"x_axis_config": {
# "unit_size": 1.5,
"unit_size": 1.0,
"tick_frequency": 1,
},
"x_max": 10,
"y_max": 15,
},
"alpha": 0.2,
"tex_mobject_config": {
"tex_to_color_map": {
"{x}": GREEN,
"{t}": YELLOW,
"\\omega": MAROON_B,
"^2": WHITE,
},
},
"graph_config": {},
"initial_phi": -90 * DEGREES,
"initial_omega": 1,
}
def construct(self):
self.setup_axes()
self.add_sine_wave()
self.shift_sine_to_cosine()
self.show_derivatives_of_cos()
self.show_cos_exp_surface()
self.change_frequency()
self.talk_through_omega()
self.show_cos_omega_derivatives()
self.show_rebalanced_exp()
def setup_axes(self):
axes = self.get_three_d_axes(include_numbers=True)
axes.x_axis.remove(axes.x_axis.numbers)
L = OldTex("L")
L.rotate(90 * DEGREES, RIGHT)
L.next_to(axes.x_axis.get_end(), IN)
axes.x_axis.label = L
axes.x_axis.add(L)
axes.shift(5 * LEFT + 0.5 * IN)
axes.z_axis.label[0].remove(
*axes.z_axis.label[0][1:]
)
axes.z_axis.label.next_to(
axes.z_axis.get_end(), OUT
)
axes.z_axis.add_numbers(
*np.arange(-1, 1.5, 0.5),
direction=LEFT,
num_decimal_places=1
)
for number in axes.z_axis.numbers:
number.rotate(90 * DEGREES, RIGHT)
self.set_camera_orientation(
phi=90 * DEGREES,
theta=-90 * DEGREES,
distance=100,
)
self.add(axes)
self.remove(axes.y_axis)
self.axes = axes
def add_sine_wave(self):
self.initialize_parameter_trackers()
graph = self.get_graph()
sin_label = OldTex(
"\\sin\\left({x}\\right)",
**self.tex_mobject_config,
)
sin_label.shift(2 * LEFT + 2.75 * UP)
self.add_fixed_in_frame_mobjects(sin_label)
graph.suspend_updating()
self.play(
ShowCreation(graph),
Write(sin_label),
)
graph.resume_updating()
self.wait()
self.sin_label = sin_label
self.graph = graph
def shift_sine_to_cosine(self):
graph = self.graph
sin_label = self.sin_label
sin_cross = Cross(sin_label)
sin_cross.add_updater(
lambda m: m.move_to(sin_label)
)
cos_label = OldTex(
"\\cos\\left({x}\\right)",
**self.tex_mobject_config,
)
cos_label.move_to(sin_label, LEFT)
cos_label.shift(LEFT)
# cos_label.shift(
# axes.c2p(0, 0) - axes.c2p(PI / 2, 0),
# )
left_tangent = Line(ORIGIN, RIGHT)
left_tangent.set_stroke(WHITE, 5)
self.add_fixed_in_frame_mobjects(cos_label)
self.play(
ApplyMethod(
self.phi_tracker.set_value, 0,
),
FadeOut(sin_label, LEFT),
FadeIn(cos_label, RIGHT),
run_time=2,
)
left_tangent.move_to(graph.get_start(), LEFT)
self.play(ShowCreation(left_tangent))
self.play(FadeOut(left_tangent))
self.cos_label = cos_label
def show_derivatives_of_cos(self):
cos_label = self.cos_label
cos_exp_label = OldTex(
"\\cos\\left({x}\\right)",
"e^{-\\alpha {t}}",
**self.tex_mobject_config
)
cos_exp_label.move_to(cos_label, LEFT)
ddx_group, ddx_exp_group = [
self.get_ddx_computation_group(
label,
*[
OldTex(
s + "\\left({x}\\right)" + exp,
**self.tex_mobject_config,
)
for s in ["-\\sin", "-\\cos"]
]
)
for label, exp in [
(cos_label, ""),
(cos_exp_label, "e^{-\\alpha {t}}"),
]
]
self.add_fixed_in_frame_mobjects(ddx_group)
self.play(FadeIn(ddx_group))
self.wait()
# Cos exp
transforms = [
ReplacementTransform(
cos_label, cos_exp_label,
),
ReplacementTransform(
ddx_group, ddx_exp_group,
),
]
for trans in transforms:
trans.begin()
self.add_fixed_in_frame_mobjects(trans.mobject)
self.play(*transforms)
self.add_fixed_in_frame_mobjects(
cos_exp_label, ddx_exp_group
)
self.remove_fixed_in_frame_mobjects(
cos_label,
*[
trans.mobject
for trans in transforms
]
)
self.cos_exp_label = cos_exp_label
self.ddx_exp_group = ddx_exp_group
def show_cos_exp_surface(self):
axes = self.axes
surface = self.get_cos_exp_surface()
self.add(surface)
surface.max_t_tracker.set_value(0)
self.move_camera(
phi=85 * DEGREES,
theta=-80 * DEGREES,
added_anims=[
ApplyMethod(
surface.max_t_tracker.set_value,
axes.y_max,
run_time=4,
),
Write(axes.y_axis),
]
)
self.wait()
self.surface = surface
def change_frequency(self):
cos_exp_label = self.cos_exp_label
ddx_exp_group = self.ddx_exp_group
omega_tracker = self.omega_tracker
cos_omega = OldTex(
"\\cos\\left(",
"\\omega", "\\cdot", "{x}",
"\\right)",
**self.tex_mobject_config
)
cos_omega.move_to(cos_exp_label, LEFT)
omega = cos_omega.get_part_by_tex("\\omega")
brace = Brace(omega, UP, buff=SMALL_BUFF)
omega_decimal = always_redraw(
lambda: DecimalNumber(
omega_tracker.get_value(),
color=omega.get_color(),
).next_to(brace, UP, SMALL_BUFF)
)
self.add_fixed_in_frame_mobjects(
cos_omega,
brace,
omega_decimal,
)
self.play(
self.camera.phi_tracker.set_value, 90 * DEGREES,
self.camera.theta_tracker.set_value, -90 * DEGREES,
FadeOut(self.surface),
FadeOut(self.axes.y_axis),
FadeOut(cos_exp_label),
FadeOut(ddx_exp_group),
FadeIn(cos_omega),
GrowFromCenter(brace),
FadeInFromDown(omega_decimal)
)
for n in [2, 6, 1, 4]:
freq = n * PI / self.axes.x_max
self.play(
omega_tracker.set_value, freq,
run_time=2
)
self.wait()
self.wait()
self.cos_omega = cos_omega
self.omega_brace = brace
def talk_through_omega(self):
axes = self.axes
x_tracker = ValueTracker(0)
get_x = x_tracker.get_value
v_line = always_redraw(lambda: DashedLine(
axes.c2p(get_x(), 0, 0),
axes.c2p(get_x(), 0, self.func(get_x(), 0)),
))
x = self.cos_omega.get_part_by_tex("{x}")
brace = Brace(x, DOWN)
x_decimal = always_redraw(
lambda: DecimalNumber(
get_x(),
color=x.get_color()
).next_to(brace, DOWN, SMALL_BUFF)
)
self.add(v_line)
self.add_fixed_in_frame_mobjects(brace, x_decimal)
self.play(
x_tracker.set_value, 5,
run_time=5,
rate_func=linear,
)
self.play(
FadeOut(v_line),
FadeOut(brace),
FadeOut(x_decimal),
)
self.remove_fixed_in_frame_mobjects(
brace, x_decimal
)
def show_cos_omega_derivatives(self):
cos_omega = self.cos_omega
ddx_omega_group = self.get_ddx_computation_group(
cos_omega,
*[
OldTex(
s + "\\left(\\omega \\cdot {x}\\right)",
**self.tex_mobject_config,
)
for s in ["-\\omega \\sin", "-\\omega^2 \\cos"]
]
)
omega_squared = ddx_omega_group[-1][1:3]
rect = SurroundingRectangle(omega_squared)
self.add_fixed_in_frame_mobjects(ddx_omega_group)
self.play(FadeIn(ddx_omega_group))
self.wait()
self.add_fixed_in_frame_mobjects(rect)
self.play(ShowCreationThenFadeOut(rect))
self.wait()
self.ddx_omega_group = ddx_omega_group
def show_rebalanced_exp(self):
cos_omega = self.cos_omega
ddx_omega_group = self.ddx_omega_group
cos_exp = OldTex(
"\\cos\\left(",
"\\omega", "\\cdot", "{x}",
"\\right)",
"e^{-\\alpha \\omega^2 {t}}",
**self.tex_mobject_config
)
cos_exp.move_to(cos_omega, DL)
self.add_fixed_in_frame_mobjects(cos_exp)
self.play(
FadeOut(cos_omega),
FadeOut(ddx_omega_group),
FadeIn(cos_exp),
)
self.remove_fixed_in_frame_mobjects(
cos_omega,
ddx_omega_group,
)
self.play(
FadeIn(self.surface),
FadeIn(self.axes.y_axis),
VGroup(
cos_exp,
self.omega_brace,
).shift, 4 * RIGHT,
self.camera.phi_tracker.set_value, 80 * DEGREES,
self.camera.theta_tracker.set_value, -80 * DEGREES,
)
self.wait()
self.play(
self.omega_tracker.set_value, TAU / 10,
run_time=6,
)
#
def initialize_parameter_trackers(self):
self.phi_tracker = ValueTracker(
self.initial_phi
)
self.omega_tracker = ValueTracker(
self.initial_omega
)
self.t_tracker = ValueTracker(0)
def get_graph(self):
return always_redraw(
lambda: self.get_time_slice_graph(
self.axes, self.func,
t=self.t_tracker.get_value(),
**self.graph_config
)
)
def get_cos_exp_surface(self):
max_t_tracker = ValueTracker(self.axes.y_max)
surface = always_redraw(
lambda: self.get_surface(
self.axes,
self.func,
v_max=max_t_tracker.get_value(),
)
)
surface.max_t_tracker = max_t_tracker
return surface
def func(self, x, t):
phi = self.phi_tracker.get_value()
omega = self.omega_tracker.get_value()
alpha = self.alpha
return op.mul(
np.cos(omega * (x + phi)),
np.exp(-alpha * (omega**2) * t)
)
def get_ddx_computation_group(self, f, df, ddf):
arrows = VGroup(*[
Vector(0.5 * RIGHT) for x in range(2)
])
group = VGroup(
arrows[0], df, arrows[1], ddf
)
group.arrange(RIGHT)
group.next_to(f, RIGHT)
for arrow in arrows:
label = OldTex(
"\\partial \\over \\partial {x}",
**self.tex_mobject_config,
)
label.scale(0.5)
label.next_to(arrow, UP, SMALL_BUFF)
arrow.add(label)
group.arrows = arrows
group.funcs = VGroup(df, ddf)
return group
class ShowFreq1CosExpDecay(ManipulateSinExpSurface):
CONFIG = {
"freq": 1,
"alpha": 0.2,
}
def construct(self):
self.setup_axes()
self.add_back_y_axis()
self.initialize_parameter_trackers()
self.phi_tracker.set_value(0)
self.omega_tracker.set_value(
self.freq * TAU / 10,
)
#
self.show_decay()
def add_back_y_axis(self):
axes = self.axes
self.add(axes.y_axis)
self.remove(axes.y_axis.numbers)
self.remove(axes.y_axis.label)
def show_decay(self):
axes = self.axes
t_tracker = self.t_tracker
t_max = self.axes.y_max
graph = always_redraw(
lambda: self.get_time_slice_graph(
axes,
self.func,
t=t_tracker.get_value(),
stroke_width=5,
)
)
surface = self.get_surface(
self.axes, self.func,
)
plane = self.get_const_time_plane(axes)
self.add(surface, plane, graph)
self.set_camera_orientation(
phi=80 * DEGREES,
theta=-85 * DEGREES,
)
self.begin_ambient_camera_rotation(rate=0.01)
self.play(
t_tracker.set_value, t_max,
plane.t_tracker.set_value, t_max,
run_time=t_max,
rate_func=linear,
)
class ShowFreq2CosExpDecay(ShowFreq1CosExpDecay):
CONFIG = {
"freq": 2,
}
class ShowFreq4CosExpDecay(ShowFreq1CosExpDecay):
CONFIG = {
"freq": 4,
}
class ShowHarmonics(SimulateRealSineCurve):
CONFIG = {
"rod_opacity": 0.75,
"initial_omega": 1.27,
"default_n_rod_pieces": 32,
}
def construct(self):
self.add_axes()
self.add_graph()
self.add_rod()
self.rod.add_updater(self.color_rod_by_graph)
#
self.show_formula()
def add_graph(self):
omega_tracker = ValueTracker(self.initial_omega)
get_omega = omega_tracker.get_value
graph = always_redraw(
lambda: self.axes.get_graph(
lambda x: np.cos(get_omega() * x),
x_min=self.graph_x_min,
x_max=self.graph_x_max,
step_size=self.step_size,
discontinuities=[5],
).color_using_background_image("VerticalTempGradient")
)
self.add(graph)
self.graph = graph
self.omega_tracker = omega_tracker
def show_formula(self):
rod = self.rod
graph = self.graph
axes = self.axes
omega_tracker = self.omega_tracker
L = TAU
formula = OldTex(
"=", "\\cos\\left(",
"2(\\pi / L)", "\\cdot", "{x}",
"\\right)",
tex_to_color_map={
"{x}": GREEN,
}
)
formula.next_to(
self.axes.y_axis.label, RIGHT, SMALL_BUFF
)
omega_part = formula.get_part_by_tex("\\pi")
omega_brace = Brace(omega_part, DOWN)
omega = OldTex("\\omega")
omega.set_color(MAROON_B)
omega.next_to(omega_brace, DOWN, SMALL_BUFF)
formula.remove(omega_part)
pi_over_L = OldTex("(\\pi / L)")
pi_over_L.move_to(omega_part)
pi_over_L.match_color(omega)
self.add(formula)
self.add(omega_brace)
self.add(omega)
self.remove(graph)
self.play(GrowFromEdge(rod, LEFT))
self.play(
ShowCreationThenFadeAround(axes.x_axis.label)
)
self.wait()
self.play(FadeIn(graph))
self.play(FadeInFromDown(pi_over_L))
self.play(
omega_tracker.set_value, PI / L,
run_time=2
)
self.wait()
# Show x
x_tracker = ValueTracker(0)
tip = ArrowTip(
start_angle=-90 * DEGREES,
color=WHITE,
)
tip.add_updater(lambda m: m.move_to(
axes.x_axis.n2p(x_tracker.get_value()),
DOWN,
))
x_sym = OldTex("x")
x_sym.set_color(GREEN)
x_sym.add_background_rectangle(buff=SMALL_BUFF)
x_sym.add_updater(lambda m: m.next_to(tip, UP, SMALL_BUFF))
self.play(
Write(tip),
Write(x_sym),
)
self.play(
x_tracker.set_value, L,
run_time=3,
)
self.wait()
self.play(TransformFromCopy(
x_sym, formula.get_part_by_tex("{x}")
))
self.play(
FadeOut(tip),
FadeOut(x_sym),
)
# Harmonics
pi_over_L.generate_target()
n_sym = Integer(2)
n_sym.match_color(pi_over_L)
group = VGroup(n_sym, pi_over_L.target)
group.arrange(RIGHT, buff=SMALL_BUFF)
group.move_to(pi_over_L)
self.play(
MoveToTarget(pi_over_L),
FadeInFromDown(n_sym),
ApplyMethod(
omega_tracker.set_value, 2 * PI / L,
run_time=2,
)
)
self.wait()
for n in [*range(3, 9), 0]:
new_n_sym = Integer(n)
new_n_sym.move_to(n_sym, DR)
new_n_sym.match_style(n_sym)
self.play(
FadeOut(n_sym, UP),
FadeIn(new_n_sym, DOWN),
omega_tracker.set_value, n * PI / L,
)
self.wait()
n_sym = new_n_sym
#
def add_labels_to_axes(self):
x_axis = self.axes.x_axis
L = OldTex("L")
L.next_to(x_axis.get_end(), DOWN)
x_axis.add(L)
x_axis.label = L
class ShowHarmonicSurfaces(ManipulateSinExpSurface):
CONFIG = {
"alpha": 0.2,
"initial_phi": 0,
"initial_omega": PI / 10,
"n_iterations": 8,
"default_surface_config": {
"resolution": (40, 30),
"surface_piece_config": {
"stroke_width": 0.5,
}
}
}
def construct(self):
self.setup_axes()
self.initialize_parameter_trackers()
self.add_surface()
self.add_graph()
self.show_all_harmonic_surfaces()
def setup_axes(self):
super().setup_axes()
self.add(self.axes.y_axis)
self.set_camera_orientation(
phi=82 * DEGREES,
theta=-80 * DEGREES,
)
def add_surface(self):
self.surface = self.get_cos_exp_surface()
self.add(self.surface)
def add_graph(self):
self.graph = self.get_graph()
self.add(self.graph)
def show_all_harmonic_surfaces(self):
omega_tracker = self.omega_tracker
formula = self.get_formula(str(1))
L = self.axes.x_max
self.begin_ambient_camera_rotation(rate=0.01)
self.add_fixed_in_frame_mobjects(formula)
self.wait(2)
for n in range(2, self.n_iterations):
if n > 5:
n_str = "n"
else:
n_str = str(n)
new_formula = self.get_formula(n_str)
self.play(
Transform(formula, new_formula),
ApplyMethod(
omega_tracker.set_value,
n * PI / L
),
)
self.wait(3)
#
def get_formula(self, n_str):
n_str = "{" + n_str + "}"
result = OldTex(
"\\cos\\left(",
n_str, "(", "\\pi / L", ")", "{x}"
"\\right)"
"e^{-\\alpha (", n_str, "\\pi / L", ")^2",
"{t}}",
tex_to_color_map={
"{x}": GREEN,
"{t}": YELLOW,
"\\pi / L": MAROON_B,
n_str: MAROON_B,
}
)
result.to_edge(UP)
return result
class Thumbnail(ShowHarmonicSurfaces):
CONFIG = {
"default_surface_config": {
"resolution": (40, 30),
# "resolution": (10, 10),
},
"graph_config": {
"stroke_width": 8,
},
}
def construct(self):
self.setup_axes()
self.initialize_parameter_trackers()
self.add_surface()
self.add_graph()
#
self.omega_tracker.set_value(3 * PI / 10)
self.set_camera_orientation(
theta=-70 * DEGREES,
)
axes = self.axes
for axis in [axes.y_axis, axes.z_axis]:
axis.numbers.set_opacity(0)
axis.remove(*axis.numbers)
axes.x_axis.label.set_opacity(0)
axes.z_axis.label.set_opacity(0)
for n in range(2, 16, 2):
new_graph = self.get_time_slice_graph(
axes, self.func, t=n,
**self.graph_config
)
new_graph.set_shade_in_3d(True)
new_graph.set_stroke(
width=8 / np.sqrt(n),
# opacity=1 / n**(1 / 4),
)
self.add(new_graph)
words = OldTexText(
"Sine waves + Linearity + Fourier = Solution"
)
words.set_width(FRAME_WIDTH - 1)
words.to_edge(DOWN)
words.shift(2 * DOWN)
self.add_fixed_in_frame_mobjects(words)
self.camera.frame_center.shift(DOWN)
self.update_mobjects(0)
self.surface.set_stroke(width=0.1)
self.surface.set_fill(opacity=0.2)
|
|
from manim_imports_ext import *
from _2019.diffyq.part2.wordy_scenes import *
class ThreeMainObservations(Scene):
def construct(self):
fourier = ImageMobject("Joseph Fourier")
name = OldTexText("Joseph Fourier")
name.match_width(fourier)
name.next_to(fourier, DOWN, SMALL_BUFF)
fourier.add(name)
fourier.set_height(5)
fourier.to_corner(DR)
fourier.shift(LEFT)
bubble = ThoughtBubble(
direction=RIGHT,
height=3,
width=4,
)
bubble.move_tip_to(fourier.get_corner(UL) + 0.5 * DR)
observations = VGroup(
OldTexText(
"1)",
"Sine = Nice",
),
OldTexText(
"2)",
"Linearity"
),
OldTexText(
"3)",
"Fourier series"
),
)
# heart = SuitSymbol("hearts")
# heart.replace(observations[0][2])
# observations[0][2].become(heart)
# observations[0][1].add(happiness)
# observations[2][2].align_to(
# observations[2][1], LEFT,
# )
observations.arrange(
DOWN,
aligned_edge=LEFT,
buff=2 * LARGE_BUFF,
)
observations.set_height(FRAME_HEIGHT - 2)
observations.to_corner(UL, buff=LARGE_BUFF)
self.add(fourier)
self.play(ShowCreation(bubble))
self.wait()
self.play(LaggedStart(*[
TransformFromCopy(bubble, observation[0])
for observation in observations
], lag_ratio=0.2))
self.play(
FadeOut(fourier),
FadeOut(bubble),
)
self.wait()
for obs in observations:
self.play(FadeIn(obs[1], LEFT))
self.wait()
class LastChapterWrapper(Scene):
def construct(self):
full_rect = FullScreenFadeRectangle(
fill_color=GREY_D,
fill_opacity=1,
)
rect = ScreenRectangle(height=6)
rect.set_stroke(WHITE, 2)
rect.set_fill(BLACK, 1)
title = OldTexText("Last chapter")
title.scale(2)
title.to_edge(UP)
rect.next_to(title, DOWN)
self.add(full_rect)
self.play(
FadeIn(rect),
Write(title, run_time=2),
)
self.wait()
class ThreeConstraints(WriteHeatEquationTemplate):
def construct(self):
self.cross_out_solving()
self.show_three_conditions()
def cross_out_solving(self):
equation = self.get_d1_equation()
words = OldTexText("Solve this equation")
words.to_edge(UP)
equation.next_to(words, DOWN)
cross = Cross(words)
self.add(words, equation)
self.wait()
self.play(ShowCreation(cross))
self.wait()
self.equation = equation
self.to_remove = VGroup(words, cross)
def show_three_conditions(self):
equation = self.equation
to_remove = self.to_remove
title = OldTex(
"\\text{Constraints }"
"T({x}, {t})"
"\\text{ must satisfy:}",
**self.tex_mobject_config
)
title.to_edge(UP)
items = VGroup(
OldTexText("1)", "The PDE"),
OldTexText("2)", "Boundary condition"),
OldTexText("3)", "Initial condition"),
)
items.scale(0.7)
items.arrange(RIGHT, buff=LARGE_BUFF)
items.set_width(FRAME_WIDTH - 2)
items.next_to(title, DOWN, LARGE_BUFF)
items[1].set_color(MAROON_B)
items[2].set_color(RED)
bc_paren = OldTexText("(Explained soon)")
bc_paren.scale(0.7)
bc_paren.next_to(items[1], DOWN)
self.play(
FadeInFromDown(title),
FadeOut(to_remove, UP),
equation.scale, 0.6,
equation.next_to, items[0], DOWN,
equation.shift_onto_screen,
LaggedStartMap(FadeIn, [
items[0],
items[1][0],
items[2][0],
])
)
self.wait()
self.play(Write(items[1][1]))
bc_paren.match_y(equation)
self.play(FadeIn(bc_paren, UP))
self.wait(2)
self.play(Write(items[2][1]))
self.wait(2)
self.title = title
self.items = items
self.pde = equation
self.bc_paren = bc_paren
class RectAroundEquation(WriteHeatEquationTemplate):
def construct(self):
eq = self.get_d1_equation()
self.play(ShowCreationThenFadeAround(eq))
class BorderRect(Scene):
def construct(self):
rect = FullScreenFadeRectangle()
rect.set_stroke(WHITE, 3)
rect.set_fill(opacity=0)
self.add(rect)
class SeekIdealized(Scene):
def construct(self):
phrases = VGroup(*[
OldTexText(
"Seek", text, "problems",
tex_to_color_map={
"realistic": GREEN,
"{idealized}": YELLOW,
"over-idealized": YELLOW,
"general": BLUE,
}
)
for text in [
"realistic",
"{idealized}",
"over-idealized",
"general",
]
])
phrases.scale(2)
words = VGroup()
for phrase in phrases:
phrase.center()
word = phrase[1]
words.add(word)
phrase.remove(word)
arrow = Vector(DOWN)
arrow.set_stroke(WHITE, 6)
arrow.next_to(words[3], UP)
low_arrow = arrow.copy()
low_arrow.next_to(words[3], DOWN)
solutions = OldTexText("solutions")
solutions.scale(2)
solutions.move_to(phrases[3][1], UL)
models = OldTexText("models")
models.scale(2)
models.next_to(
words[0], RIGHT, buff=0.35,
aligned_edge=DOWN
)
phrases.center()
phrase = phrases[0]
self.add(phrase)
self.add(words[0])
self.wait()
words[0].save_state()
self.play(
words[0].to_edge, DOWN,
words[0].set_opacity, 0.5,
Transform(phrase, phrases[1]),
FadeIn(words[1], UP)
)
self.wait()
# self.play(
# words[1].move_to, words[2], RIGHT,
# FadeIn(words[2]),
# Transform(phrase, phrases[2])
# )
# self.wait()
self.play(
words[1].next_to, arrow, UP,
ShowCreation(arrow),
MaintainPositionRelativeTo(
phrase, words[1]
),
FadeIn(solutions, LEFT),
FadeIn(words[3]),
)
self.wait()
words[0].generate_target()
words[0].target.next_to(low_arrow, DOWN)
words[0].target.set_opacity(1)
models.shift(
words[0].target.get_center() -
words[0].saved_state.get_center()
)
self.play(
MoveToTarget(words[0]),
ShowCreation(low_arrow),
FadeIn(models, LEFT)
)
self.wait()
class SecondDerivativeOfSine(Scene):
def construct(self):
equation = OldTex(
"{d^2 \\over d{x}^2}",
"\\cos\\left({x}\\right) =",
"-\\cos\\left({x}\\right)",
tex_to_color_map={
"{x}": GREEN,
}
)
self.add(equation)
class EquationAboveSineAnalysis(WriteHeatEquationTemplate):
def construct(self):
equation = self.get_d1_equation()
equation.to_edge(UP)
equation.shift(2 * LEFT)
eq_index = equation.index_of_part_by_tex("=")
lhs = equation[:eq_index]
eq = equation[eq_index]
rhs = equation[eq_index + 1:]
t_terms = equation.get_parts_by_tex("{t}")[1:]
t_terms.save_state()
zeros = VGroup(*[
OldTex("0").replace(t, dim_to_match=1)
for t in t_terms
])
zeros.align_to(t_terms, DOWN)
new_rhs = OldTex(
"=", "-\\alpha \\cdot {T}", "({x}, 0)",
**self.tex_mobject_config
)
# new_rhs.move_to(equation.get_right())
# new_rhs.next_to(equation, DOWN, MED_LARGE_BUFF)
# new_rhs.align_to(eq, LEFT)
new_rhs.next_to(equation, RIGHT)
new_rhs.shift(SMALL_BUFF * DOWN)
self.add(equation)
self.play(ShowCreationThenFadeAround(rhs))
self.wait()
self.play(
FadeOut(t_terms, UP),
FadeIn(zeros, DOWN),
)
t_terms.fade(1)
self.wait()
self.play(
# VGroup(equation, zeros).next_to,
# new_rhs, LEFT,
FadeIn(new_rhs),
)
self.wait()
self.play(
VGroup(
lhs[6:],
eq,
rhs,
new_rhs[0],
new_rhs[-3:],
zeros,
).fade, 0.5,
)
self.play(ShowCreationThenFadeAround(lhs[:6]))
self.play(ShowCreationThenFadeAround(new_rhs[1:-3]))
self.wait()
class ExpVideoWrapper(Scene):
def construct(self):
self.add(FullScreenFadeRectangle(
fill_color=GREY_E,
fill_opacity=1,
))
screen = ImageMobject("eoc_chapter5_thumbnail")
screen.set_height(6)
rect = SurroundingRectangle(screen, buff=0)
rect.set_stroke(WHITE, 2)
screen.add(rect)
title = OldTexText("Need a refresher?")
title.scale(1.5)
title.to_edge(UP)
screen.next_to(title, DOWN)
screen.center()
self.play(
# FadeIn(title, LEFT),
FadeIn(screen, DOWN),
)
self.wait()
class ShowSinExpDerivatives(WriteHeatEquationTemplate):
CONFIG = {
"tex_mobject_config": {
"tex_to_color_map": {
"{0}": WHITE,
"\\partial": WHITE,
"=": WHITE,
}
}
}
def construct(self):
pde = self.get_d1_equation_without_inputs()
pde.to_edge(UP)
pde.generate_target()
new_rhs = OldTex(
"=- \\alpha \\cdot T",
**self.tex_mobject_config,
)
new_rhs.next_to(pde, RIGHT)
new_rhs.align_to(pde.get_part_by_tex("alpha"), DOWN)
equation1 = OldTex(
"T({x}, {0}) = \\sin\\left({x}\\right)",
**self.tex_mobject_config
)
equation2 = OldTex(
"T({x}, {t}) = \\sin\\left({x}\\right)",
"e^{-\\alpha{t}}",
**self.tex_mobject_config
)
for eq in equation1, equation2:
eq.next_to(pde, DOWN, MED_LARGE_BUFF)
eq2_part1 = equation2[:len(equation1)]
eq2_part2 = equation2[len(equation1):]
# Rectangles
exp_rect = SurroundingRectangle(eq2_part2)
exp_rect.set_stroke(RED, 3)
sin_rect = SurroundingRectangle(
eq2_part1[-3:]
)
sin_rect.set_color(BLUE)
VGroup(pde.target, new_rhs).center().to_edge(UP)
# Show proposed solution
self.add(pde)
self.add(equation1)
self.wait()
self.play(
MoveToTarget(pde),
FadeIn(new_rhs, LEFT)
)
self.wait()
self.play(
ReplacementTransform(equation1, eq2_part1),
FadeIn(eq2_part2),
)
self.play(ShowCreation(exp_rect))
self.wait()
self.play(FadeOut(exp_rect))
# Take partial derivatives wrt x
q_mark = OldTex("?")
q_mark.next_to(pde.get_part_by_tex("="), UP)
q_mark.set_color(RED)
arrow1 = Vector(3 * DOWN + 1 * RIGHT, color=WHITE)
arrow1.scale(1.2 / arrow1.get_length())
arrow1.next_to(
eq2_part2.get_corner(DL),
DOWN, MED_LARGE_BUFF
)
ddx_label1 = OldTex(
"\\partial \\over \\partial {x}",
**self.tex_mobject_config,
)
ddx_label1.scale(0.7)
ddx_label1.next_to(
arrow1.point_from_proportion(0.8),
UR, SMALL_BUFF
)
pde_ddx = VGroup(
*pde.get_parts_by_tex("\\partial")[2:],
pde.get_parts_by_tex("\\over")[1],
pde.get_part_by_tex("{x}"),
)
pde_ddx_rect = SurroundingRectangle(pde_ddx)
pde_ddx_rect.set_color(GREEN)
eq2_part2_rect = SurroundingRectangle(eq2_part2)
dx = OldTex(
"\\cos\\left({x}\\right)", "e^{-\\alpha {t}}",
**self.tex_mobject_config
)
ddx = OldTex(
"-\\sin\\left({x}\\right)", "e^{-\\alpha {t}}",
**self.tex_mobject_config
)
dx.next_to(arrow1, DOWN)
dx.align_to(eq2_part2, RIGHT)
x_shift = arrow1.get_end()[0] - arrow1.get_start()[0]
x_shift *= 2
dx.shift(x_shift * RIGHT)
arrow2 = arrow1.copy()
arrow2.next_to(dx, DOWN)
arrow2.shift(MED_SMALL_BUFF * RIGHT)
dx_arrows = VGroup(arrow1, arrow2)
ddx_label2 = ddx_label1.copy()
ddx_label2.shift(
arrow2.get_center() - arrow1.get_center()
)
ddx.next_to(arrow2, DOWN)
ddx.align_to(eq2_part2, RIGHT)
ddx.shift(2 * x_shift * RIGHT)
rhs = equation2[-6:]
self.play(
FadeInFromDown(q_mark)
)
self.play(
ShowCreation(pde_ddx_rect)
)
self.wait()
self.play(
LaggedStart(
GrowArrow(arrow1),
GrowArrow(arrow2),
),
TransformFromCopy(
pde_ddx[0], ddx_label1
),
TransformFromCopy(
pde_ddx[0], ddx_label2
),
)
self.wait()
self.play(
TransformFromCopy(rhs, dx)
)
self.wait()
self.play(
FadeIn(eq2_part2_rect)
)
self.play(
Transform(
eq2_part2_rect,
SurroundingRectangle(dx[-3:])
)
)
self.play(
FadeOut(eq2_part2_rect)
)
self.wait()
self.play(
TransformFromCopy(dx, ddx)
)
self.play(
FadeIn(
SurroundingRectangle(ddx).match_style(
pde_ddx_rect
)
)
)
self.wait()
# Take partial derivative wrt t
pde_ddt = pde[:pde.index_of_part_by_tex("=") - 1]
pde_ddt_rect = SurroundingRectangle(pde_ddt)
dt_arrow = Arrow(
arrow1.get_start(),
arrow2.get_end() + RIGHT,
buff=0
)
dt_arrow.flip(UP)
dt_arrow.next_to(dx_arrows, LEFT, MED_LARGE_BUFF)
dt_label = OldTex(
"\\partial \\over \\partial {t}",
**self.tex_mobject_config,
)
dt_label.scale(1)
dt_label.next_to(
dt_arrow.get_center(), UL,
SMALL_BUFF,
)
rhs_copy = rhs.copy()
rhs_copy.next_to(dt_arrow.get_end(), DOWN)
rhs_copy.shift(MED_LARGE_BUFF * LEFT)
rhs_copy.match_y(ddx)
minus_alpha_in_exp = rhs_copy[-3][1:].copy()
minus_alpha_in_exp.set_color(RED)
minus_alpha = OldTex("-\\alpha")
minus_alpha.next_to(rhs_copy, LEFT)
minus_alpha.align_to(rhs_copy[0][0], DOWN)
dot = OldTex("\\cdot")
dot.move_to(midpoint(
minus_alpha.get_right(),
rhs_copy.get_left(),
))
self.play(
TransformFromCopy(
pde_ddx_rect,
pde_ddt_rect,
)
)
self.play(
GrowArrow(dt_arrow),
TransformFromCopy(
pde_ddt,
dt_label,
)
)
self.wait()
self.play(TransformFromCopy(rhs, rhs_copy))
self.play(FadeIn(minus_alpha_in_exp))
self.play(
ApplyMethod(
minus_alpha_in_exp.replace, minus_alpha,
path_arc=TAU / 4
),
FadeIn(dot),
)
self.play(
FadeIn(minus_alpha),
FadeOut(minus_alpha_in_exp),
)
self.wait()
rhs_copy.add(minus_alpha, dot)
self.play(
FadeIn(SurroundingRectangle(rhs_copy))
)
self.wait()
#
checkmark = OldTex("\\checkmark")
checkmark.set_color(GREEN)
checkmark.move_to(q_mark, DOWN)
self.play(
FadeInFromDown(checkmark),
FadeOut(q_mark, UP)
)
self.wait()
class DerivativesOfLinearFunction(WriteHeatEquationTemplate):
CONFIG = {
"tex_mobject_config": {
"tex_to_color_map": {
"{c}": WHITE,
}
}
}
def construct(self):
func = OldTex(
"T({x}, {t}) = {c} \\cdot {x}",
**self.tex_mobject_config
)
dx_T = OldTex("{c}", **self.tex_mobject_config)
ddx_T = OldTex("0")
dt_T = OldTex("0")
for mob in func, dx_T, ddx_T, dt_T:
mob.scale(1.5)
func.generate_target()
arrows = VGroup(*[
Vector(1.5 * RIGHT, color=WHITE)
for x in range(3)
])
dx_arrows = arrows[:2]
dt_arrow = arrows[2]
dt_arrow.rotate(-TAU / 4)
dx_group = VGroup(
func.target,
dx_arrows[0],
dx_T,
dx_arrows[1],
ddx_T,
)
dx_group.arrange(RIGHT)
for arrow, char, vect in zip(arrows, "xxt", [UP, UP, RIGHT]):
label = OldTex(
"\\partial \\over \\partial {%s}" % char,
**self.tex_mobject_config
)
label.scale(0.7)
label.next_to(arrow.get_center(), vect)
arrow.add(label)
dt_arrow.shift(
func.target[-3:].get_bottom() + MED_SMALL_BUFF * DOWN -
dt_arrow.get_start(),
)
dt_T.next_to(dt_arrow.get_end(), DOWN)
self.play(FadeInFromDown(func))
self.wait()
self.play(
MoveToTarget(func),
LaggedStartMap(Write, dx_arrows),
run_time=1,
)
self.play(
TransformFromCopy(func[-3:], dx_T),
path_arc=-TAU / 4,
)
self.play(
TransformFromCopy(dx_T, ddx_T),
path_arc=-TAU / 4,
)
self.wait()
# dt
self.play(Write(dt_arrow))
self.play(
TransformFromCopy(func[-3:], dt_T)
)
self.wait()
class FlatAtBoundaryWords(Scene):
def construct(self):
words = self.get_bc_words()
self.play(Write(words))
self.wait()
def get_bc_words(self):
return OldTexText(
"Flat at boundary\\\\"
"for all", "${t}$", "$> 0$",
)
class WriteOutBoundaryCondition(FlatAtBoundaryWords, ThreeConstraints, MovingCameraScene):
def construct(self):
self.force_skipping()
ThreeConstraints.construct(self)
self.revert_to_original_skipping_status()
self.add_ic()
self.write_bc_words()
self.write_bc_equation()
def add_ic(self):
image = ImageMobject("temp_initial_condition_example")
image.set_width(3)
border = SurroundingRectangle(image, buff=SMALL_BUFF)
border.shift(SMALL_BUFF * UP)
border.set_stroke(WHITE, 2)
group = Group(image, border)
group.next_to(self.items[2], DOWN)
self.add(group)
def write_bc_words(self):
bc_paren = self.bc_paren
bc_words = self.get_bc_words()
bc_words.match_width(self.items[1][1])
bc_words.move_to(bc_paren, UP)
bc_words.set_color_by_tex("{t}", YELLOW)
self.play(ShowCreationThenFadeAround(
VGroup(self.items[0], self.pde)
))
self.play(
FadeOut(bc_paren, UP),
FadeIn(bc_words, DOWN),
)
self.wait()
self.bc_words = bc_words
def write_bc_equation(self):
bc_words = self.bc_words
equation = OldTex(
"{\\partial {T} \\over \\partial {x}}(0, {t}) = ",
"{\\partial {T} \\over \\partial {x}}(L, {t}) = ",
"0",
**self.tex_mobject_config,
)
equation.next_to(bc_words, DOWN, MED_LARGE_BUFF)
self.play(
self.camera_frame.shift, 0.8 * DOWN,
)
self.play(FadeIn(equation, UP))
self.wait()
class HeatEquationFrame(WriteHeatEquationTemplate):
def construct(self):
equation = self.get_d1_equation()
equation.to_edge(UP, buff=MED_SMALL_BUFF)
ddx = equation[-11:]
dt = equation[:11]
full_rect = FullScreenFadeRectangle(
fill_color=GREY_D,
fill_opacity=1,
)
smaller_rect = ScreenRectangle(
height=6,
fill_color=BLACK,
fill_opacity=1,
stroke_color=WHITE,
stroke_width=2,
)
smaller_rect.next_to(equation, DOWN)
self.add(full_rect)
self.add(smaller_rect)
self.add(equation)
self.wait()
self.play(ShowCreationThenFadeAround(
ddx,
surrounding_rectangle_config={
"stroke_color": GREEN,
}
))
self.wait()
self.play(ShowCreationThenFadeAround(dt))
self.wait()
class CompareFreqDecays1to2(Scene):
CONFIG = {
"freqs": [1, 2]
}
def construct(self):
background = FullScreenFadeRectangle(
fill_color=GREY_E,
fill_opacity=1,
)
screens = VGroup(*[
ScreenRectangle(
height=4,
fill_color=BLACK,
fill_opacity=1,
stroke_width=1,
stroke_color=WHITE,
)
for x in range(2)
])
screens.arrange(RIGHT)
screens.set_width(FRAME_WIDTH - 1)
formulas = VGroup(*[
self.get_formula(freq)
for freq in self.freqs
])
for formula, screen in zip(formulas, screens):
formula.next_to(screen, UP)
self.add(background)
self.add(screens)
self.add(formulas)
self.wait()
def get_formula(self, freq):
f_str = str(freq)
return OldTex(
"\\cos\\left(%s \\cdot {x}\\right)" % f_str,
"e^{-\\alpha \\cdot %s^2 \\cdot {t}}" % f_str,
tex_to_color_map={
"{x}": GREEN,
"{t}": YELLOW,
f_str: MAROON_B,
}
)
class CompareFreqDecays1to4(CompareFreqDecays1to2):
CONFIG = {
"freqs": [1, 4],
}
class CompareFreqDecays2to4(CompareFreqDecays1to2):
CONFIG = {
"freqs": [2, 4],
}
class WorryAboutGenerality(TeacherStudentsScene, WriteHeatEquationTemplate):
def construct(self):
eq = self.get_d1_equation()
diffyq = self.get_diffyq_set()
is_in = OldTex("\\in")
is_in.scale(2)
group = VGroup(eq, is_in, diffyq)
group.arrange(RIGHT, buff=MED_LARGE_BUFF)
group.to_edge(UP)
arrow = Vector(DOWN)
arrow.set_stroke(WHITE, 5)
arrow.next_to(eq, DOWN)
themes = OldTexText("Frequent themes")
themes.scale(1.5)
themes.next_to(arrow, DOWN)
self.play(
self.change_students(
"sad", "tired", "pleading"
),
self.teacher.change, "raise_right_hand",
FadeInFromDown(eq)
)
self.play(Write(group[1:]))
self.wait(2)
self.play(
ShowCreation(arrow),
self.change_students(*3 * ["pondering"]),
)
self.play(
FadeIn(themes, UP),
self.change_students(*3 * ["thinking"]),
self.teacher.change, "happy"
)
self.wait(4)
# def get_d1_equation(self):
# result = super().get_d1_equation()
# lp, rp = parens = OldTex("(", ")")
# parens.match_height(result)
# lp.next_to(result, LEFT, SMALL_BUFF)
# rp.next_to(result, RIGHT, SMALL_BUFF)
# result.add_to_back(lp)
# result.add(rp)
# return result
def get_diffyq_set(self):
words = OldTexText(
"Differential\\\\equations"
)
words.scale(1.5)
words.set_color(BLUE)
lb = Brace(words, LEFT)
rb = Brace(words, RIGHT)
return VGroup(lb, words, rb)
|
|
from manim_imports_ext import *
from _2019.diffyq.part2.heat_equation import *
class ShowNewRuleAtDiscreteBoundary(DiscreteSetup):
CONFIG = {
"axes_config": {
"x_min": 0,
"stroke_width": 1,
"x_axis_config": {
"include_tip": False,
},
},
"freq_amplitude_pairs": [
(1, 0.5),
(2, 1),
(3, 0.5),
(4, 0.3),
],
"v_line_class": DashedLine,
"v_line_config": {
},
"step_size": 1,
"wait_time": 15,
"alpha": 0.25,
}
def construct(self):
self.add_axes()
self.set_points()
self.show_boundary_point_influenced_by_neighbor()
self.add_clock()
self.let_evolve()
def set_points(self):
axes = self.axes
for mob in axes.family_members_with_points():
if isinstance(mob, Line):
mob.set_stroke(width=1)
step_size = self.step_size
xs = np.arange(
axes.x_min,
axes.x_max + step_size,
step_size
)
dots = self.dots = self.get_dots(axes, xs)
self.v_lines = self.get_v_lines(dots)
self.rod_pieces = self.get_rod_pieces(dots)
# rod_pieces
self.add(self.dots)
self.add(self.v_lines)
self.add(self.rod_pieces)
def show_boundary_point_influenced_by_neighbor(self):
dots = self.dots
ld = dots[0]
ld_in = dots[1]
rd = dots[-1]
rd_in = dots[-2]
v_len = 0.75
l_arrow = Vector(v_len * LEFT)
l_arrow.move_to(ld.get_left(), RIGHT)
r_arrow = Vector(v_len * RIGHT)
r_arrow.move_to(rd.get_right(), LEFT)
arrows = VGroup(l_arrow, r_arrow)
q_marks = VGroup(*[
OldTex("?").scale(1.5).next_to(
arrow, arrow.get_vector()
)
for arrow in arrows
])
arrows.set_color(YELLOW)
q_marks.set_color(YELLOW)
blocking_rects = VGroup(*[
BackgroundRectangle(VGroup(
*dots[i:-i],
*self.rod_pieces[i:-i]
))
for i in [1, 2]
])
for rect in blocking_rects:
rect.stretch(1.1, dim=1, about_edge=UP)
self.play(FadeIn(blocking_rects[0]))
self.play(
LaggedStartMap(ShowCreation, arrows),
LaggedStart(*[
FadeIn(q_mark, -arrow.get_vector())
for q_mark, arrow in zip(q_marks, arrows)
]),
run_time=1.5
)
self.wait()
# Point to inward neighbor
new_arrows = VGroup(*[
Arrow(
d1.get_center(),
VGroup(d1, d2).get_center(),
buff=0,
).match_style(l_arrow)
for d1, d2 in [(ld, ld_in), (rd, rd_in)]
])
new_arrows.match_style(arrows)
l_brace = Brace(VGroup(ld, ld_in), DOWN)
r_brace = Brace(VGroup(rd, rd_in), DOWN)
braces = VGroup(l_brace, r_brace)
for brace in braces:
brace.align_to(
self.axes.x_axis.get_center(), UP
)
brace.shift(SMALL_BUFF * DOWN)
brace.add(brace.get_tex("\\Delta x"))
self.play(
ReplacementTransform(arrows, new_arrows),
FadeOut(q_marks),
ReplacementTransform(*blocking_rects)
)
self.wait()
self.play(FadeIn(braces, UP))
self.wait()
self.play(
FadeOut(new_arrows),
FadeOut(blocking_rects[1]),
FadeOut(braces),
)
def add_clock(self):
super().add_clock()
self.time_label.add_updater(
lambda d, dt: d.increment_value(dt)
)
VGroup(
self.clock,
self.time_label
).shift(2 * LEFT)
def let_evolve(self):
dots = self.dots
dots.add_updater(self.update_dots)
wait_time = self.wait_time
self.play(
ClockPassesTime(
self.clock,
run_time=wait_time,
hours_passed=wait_time,
),
)
#
def get_dots(self, axes, xs):
dots = VGroup(*[
Dot(axes.c2p(x, self.temp_func(x, 0)))
for x in xs
])
max_width = 0.8 * self.step_size
for dot in dots:
dot.add_updater(self.update_dot_color)
if dot.get_width() > max_width:
dot.set_width(max_width)
return dots
def get_v_lines(self, dots):
return always_redraw(lambda: VGroup(*[
self.get_v_line(dot)
for dot in dots
]))
def get_v_line(self, dot):
x_axis = self.axes.x_axis
bottom = dot.get_bottom()
x = x_axis.p2n(bottom)
proj_point = x_axis.n2p(x)
return self.v_line_class(
proj_point, bottom,
**self.v_line_config,
)
def get_rod_pieces(self, dots):
axis = self.axes.x_axis
factor = 1 - np.exp(-(0.8 / self.step_size)**2)
width = factor * self.step_size
pieces = VGroup()
for dot in dots:
piece = Line(ORIGIN, width * RIGHT)
piece.set_stroke(width=5)
piece.move_to(dot)
piece.set_y(axis.get_center()[1])
piece.dot = dot
piece.add_updater(
lambda p: p.match_color(p.dot)
)
pieces.add(piece)
return pieces
def update_dot_color(self, dot):
y = self.axes.y_axis.p2n(dot.get_center())
dot.set_color(self.y_to_color(y))
def update_dots(self, dots, dt):
for ds in zip(dots, dots[1:], dots[2:]):
points = [d.get_center() for d in ds]
x0, x1, x2 = [p[0] for p in points]
dx = x1 - x0
y0, y1, y2 = [p[1] for p in points]
self.update_dot(
dot=ds[1],
dt=dt,
mean_diff=0.5 * (y2 - 2 * y1 + y0) / dx
)
if ds[0] is dots[0]:
self.update_dot(
dot=ds[0],
dt=dt,
mean_diff=(y1 - y0) / dx
)
elif ds[-1] is dots[-1]:
self.update_dot(
dot=ds[-1],
dt=dt,
mean_diff=(y1 - y2) / dx
)
def update_dot(self, dot, dt, mean_diff):
dot.shift(mean_diff * self.alpha * dt * UP)
class DiscreteEvolutionPoint25(ShowNewRuleAtDiscreteBoundary):
CONFIG = {
"step_size": 0.25,
"alpha": 0.5,
"wait_time": 30,
}
def construct(self):
self.add_axes()
self.set_points()
self.add_clock()
self.let_evolve()
class DiscreteEvolutionPoint1(DiscreteEvolutionPoint25):
CONFIG = {
"step_size": 0.1,
"v_line_config": {
"stroke_width": 1,
},
"wait_time": 30,
}
class FlatEdgesForDiscreteEvolution(DiscreteEvolutionPoint1):
CONFIG = {
"wait_time": 20,
"step_size": 0.1,
}
def let_evolve(self):
lines = VGroup(*[
Line(LEFT, RIGHT)
for x in range(2)
])
lines.set_width(1.5)
lines.set_stroke(WHITE, 5, opacity=0.5)
lines.add_updater(self.update_lines)
turn_animation_into_updater(
ShowCreation(lines, run_time=2)
)
self.add(lines)
super().let_evolve()
def update_lines(self, lines):
dots = self.dots
for line, dot in zip(lines, [dots[0], dots[-1]]):
line.move_to(dot)
class FlatEdgesForDiscreteEvolutionTinySteps(FlatEdgesForDiscreteEvolution):
CONFIG = {
"step_size": 0.025,
"wait_time": 10,
"v_line_class": Line,
"v_line_config": {
"stroke_opacity": 0.5,
}
}
|
|
from manim_imports_ext import *
class SideGigToFullTime(Scene):
def construct(self):
morty = Mortimer()
morty.next_to(ORIGIN, DOWN)
self.add(morty)
self.side_project(morty)
self.income(morty)
self.full_time(morty)
def side_project(self, morty):
rect = PictureInPictureFrame()
rect.next_to(morty, UP+LEFT)
side_project = OldTexText("Side project")
side_project.next_to(rect, UP)
dollar_sign = OldTex("\\$")
cross = VGroup(*[
Line(vect, -vect, color = RED)
for vect in (UP+RIGHT, UP+LEFT)
])
cross.set_height(dollar_sign.get_height())
no_money = VGroup(dollar_sign, cross)
no_money.next_to(rect, DOWN)
self.play(
morty.change_mode, "raise_right_hand",
morty.look_at, rect
)
self.play(
Write(side_project),
ShowCreation(rect)
)
self.wait()
self.play(Blink(morty))
self.wait()
self.play(Write(dollar_sign))
self.play(ShowCreation(cross))
self.screen_title = side_project
self.cross = cross
def income(self, morty):
dollar_signs = VGroup(*[
OldTex("\\$")
for x in range(10)
])
dollar_signs.arrange(RIGHT, buff = LARGE_BUFF)
dollar_signs.set_color(BLACK)
dollar_signs.next_to(morty.eyes, RIGHT, buff = 2*LARGE_BUFF)
self.play(
morty.change_mode, "happy",
morty.look_at, dollar_signs,
dollar_signs.shift, LEFT,
dollar_signs.set_color, GREEN
)
for x in range(5):
last_sign = dollar_signs[0]
dollar_signs.remove(last_sign)
self.play(
FadeOut(last_sign),
dollar_signs.shift, LEFT
)
random.shuffle(dollar_signs.submobjects)
self.play(
ApplyMethod(
dollar_signs.shift,
(FRAME_Y_RADIUS+1)*DOWN,
lag_ratio = 0.5
),
morty.change_mode, "guilty",
morty.look, DOWN+RIGHT
)
self.play(Blink(morty))
def full_time(self, morty):
new_title = OldTexText("Full time")
new_title.move_to(self.screen_title)
q_mark = OldTex("?")
q_mark.next_to(self.cross)
q_mark.set_color(GREEN)
self.play(morty.look_at, q_mark)
self.play(Transform(self.screen_title, new_title))
self.play(
Transform(self.cross, q_mark),
morty.change_mode, "confused"
)
self.play(Blink(morty))
self.wait()
self.play(
morty.change_mode, "happy",
morty.look, UP+RIGHT
)
self.play(Blink(morty))
self.wait()
class TakesTime(Scene):
def construct(self):
rect = PictureInPictureFrame(height = 4)
rect.to_edge(RIGHT, buff = LARGE_BUFF)
clock = Clock()
clock.hour_hand.set_color(BLUE_C)
clock.minute_hand.set_color(BLUE_D)
clock.next_to(rect, LEFT, buff = LARGE_BUFF)
self.add(rect)
self.play(ShowCreation(clock))
for x in range(3):
self.play(ClockPassesTime(clock))
class GrowingToDoList(Scene):
def construct(self):
morty = Mortimer()
morty.flip()
morty.next_to(ORIGIN, DOWN+LEFT)
title = OldTexText("3blue1brown to-do list")
title.next_to(ORIGIN, RIGHT)
title.to_edge(UP)
underline = Line(title.get_left(), title.get_right())
underline.next_to(title, DOWN)
lines = VGroup(*list(map(TexText, [
"That one on topology",
"Something with quaternions",
"Solving puzzles with binary counting",
"Tatoos on math",
"Laplace stuffs",
"The role of memorization in math",
"Strangeness of the axiom of choice",
"Tensors",
"Different view of $e^{\\pi i}$",
"Quadratic reciprocity",
"Fourier stuffs",
"$1+2+3+\\cdots = -\\frac{1}{12}$",
"Understanding entropy",
])))
lines.scale(0.65)
lines.arrange(DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT)
lines.set_color_by_gradient(BLUE_C, YELLOW)
lines.next_to(title, DOWN, buff = LARGE_BUFF/2.)
lines.to_edge(RIGHT)
self.play(
Write(title),
morty.look_at, title
)
self.play(
Write(lines[0]),
morty.change_mode, "erm",
run_time = 1
)
for line in lines[1:3]:
self.play(
Write(line),
morty.look_at, line,
run_time = 1
)
self.play(
morty.change_mode, "pleading",
morty.look_at, lines,
Write(
VGroup(*lines[3:]),
)
)
class TwoTypesOfVideos(Scene):
def construct(self):
morty = Mortimer().shift(2*DOWN)
stand_alone = OldTexText("Standalone videos")
stand_alone.shift(FRAME_X_RADIUS*LEFT/2)
stand_alone.to_edge(UP)
series = OldTexText("Series")
series.shift(FRAME_X_RADIUS*RIGHT/2)
series.to_edge(UP)
box = Rectangle(width = 16, height = 9, color = WHITE)
box.set_height(3)
box.next_to(stand_alone, DOWN)
series_list = VGroup(*[
OldTexText("Essence of %s"%s)
for s in [
"linear algebra",
"calculus",
"probability",
"real analysis",
"complex analysis",
"ODEs",
]
])
series_list.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF)
series_list.set_width(FRAME_X_RADIUS-2)
series_list.next_to(series, DOWN, buff = MED_SMALL_BUFF)
series_list.to_edge(RIGHT)
fridays = OldTexText("Every other friday")
when_done = OldTexText("When series is done")
for words, vect in (fridays, LEFT), (when_done, RIGHT):
words.set_color(YELLOW)
words.next_to(
morty, vect,
buff = MED_SMALL_BUFF,
aligned_edge = UP
)
unless = OldTexText("""
Unless you're
a patron \\dots
""")
unless.next_to(when_done, DOWN, buff = MED_SMALL_BUFF)
self.add(morty)
self.play(Blink(morty))
self.play(
morty.change_mode, "raise_right_hand",
morty.look_at, stand_alone,
Write(stand_alone, run_time = 2),
)
self.play(
morty.change_mode, "raise_left_hand",
morty.look_at, series,
Write(series, run_time = 2),
)
self.play(Blink(morty))
self.wait()
self.play(
morty.change_mode, "raise_right_hand",
morty.look_at, box,
ShowCreation(box)
)
for x in range(3):
self.wait(2)
self.play(Blink(morty))
self.play(
morty.change_mode, "raise_left_hand",
morty.look_at, series
)
for i, words in enumerate(series_list):
self.play(Write(words), run_time = 1)
self.play(Blink(morty))
self.wait()
self.play(series_list[1].set_color, BLUE)
self.wait(2)
self.play(Blink(morty))
self.wait()
pairs = [
(fridays, "speaking"),
(when_done, "wave_2") ,
(unless, "surprised"),
]
for words, mode in pairs:
self.play(
Write(words),
morty.change_mode, mode,
morty.look_at, words
)
self.wait()
class ClassWatching(TeacherStudentsScene):
def construct(self):
rect = PictureInPictureFrame(height = 4)
rect.next_to(self.get_teacher(), UP, buff = LARGE_BUFF/2.)
rect.to_edge(RIGHT)
self.add(rect)
for pi in self.get_students():
pi.look_at(rect)
self.random_blink(5)
self.play_student_changes(
"raise_left_hand",
"raise_right_hand",
"sassy",
)
self.play(self.get_teacher().change_mode, "pondering")
self.random_blink(3)
class RandolphWatching(Scene):
def construct(self):
randy = Randolph()
randy.shift(2*LEFT)
randy.look(RIGHT)
self.add(randy)
self.wait()
self.play(Blink(randy))
self.wait()
self.play(
randy.change_mode, "pondering",
randy.look, RIGHT
)
self.play(Blink(randy))
self.wait()
class RandolphWatchingWithLaptop(Scene):
pass
class GrowRonaksSierpinski(Scene):
CONFIG = {
"colors" : [BLUE, YELLOW, BLUE_C, BLUE_E],
"dot_radius" : 0.08,
"n_layers" : 64,
}
def construct(self):
sierp = self.get_ronaks_sierpinski(self.n_layers)
dots = self.get_dots(self.n_layers)
self.triangle = VGroup(sierp, dots)
self.triangle.scale(1.5)
self.triangle.shift(3*UP)
sierp_layers = sierp.submobjects
dot_layers = dots.submobjects
last_dot_layer = dot_layers[0]
self.play(ShowCreation(last_dot_layer))
run_time = 1
for n, sierp_layer, dot_layer in zip(it.count(1), sierp_layers, dot_layers[1:]):
self.play(
ShowCreation(sierp_layer, lag_ratio=1),
Animation(last_dot_layer),
run_time = run_time
)
self.play(ShowCreation(
dot_layer,
run_time = run_time,
lag_ratio=1,
))
# if n == 2:
# dot = dot_layer[1]
# words = OldTexText("Stop growth at pink")
# words.next_to(dot, DOWN, 2)
# arrow = Arrow(words, dot)
# self.play(
# Write(words),
# ShowCreation(arrow)
# )
# self.wait()
# self.play(*map(FadeOut, [words, arrow]))
log2 = np.log2(n)
if n > 2 and log2-np.round(log2) == 0 and n < self.n_layers:
self.wait()
self.rescale()
run_time /= 1.3
last_dot_layer = dot_layer
def rescale(self):
shown_mobs = VGroup(*self.get_mobjects())
shown_mobs_copy = shown_mobs.copy()
self.remove(shown_mobs)
self.add(shown_mobs_copy)
top = shown_mobs.get_top()
self.triangle.scale(0.5)
self.triangle.move_to(top, aligned_edge = UP)
self.play(Transform(shown_mobs_copy, shown_mobs))
self.remove(shown_mobs_copy)
self.add(shown_mobs)
def get_pascal_point(self, n, k):
return n*rotate_vector(RIGHT, -2*np.pi/3) + k*RIGHT
def get_lines_at_layer(self, n):
lines = VGroup()
for k in range(n+1):
if choose(n, k)%2 == 1:
p1 = self.get_pascal_point(n, k)
p2 = self.get_pascal_point(n+1, k)
p3 = self.get_pascal_point(n+1, k+1)
lines.add(Line(p1, p2), Line(p1, p3))
return lines
def get_dot_layer(self, n):
dots = VGroup()
for k in range(n+1):
p = self.get_pascal_point(n, k)
dot = Dot(p, radius = self.dot_radius)
if choose(n, k)%2 == 0:
if choose(n-1, k)%2 == 0:
continue
dot.set_color(PINK)
else:
dot.set_color(WHITE)
dots.add(dot)
return dots
def get_ronaks_sierpinski(self, n_layers):
ronaks_sierpinski = VGroup()
for n in range(n_layers):
ronaks_sierpinski.add(self.get_lines_at_layer(n))
ronaks_sierpinski.set_color_by_gradient(*self.colors)
ronaks_sierpinski.set_stroke(width = 0)##TODO
return ronaks_sierpinski
def get_dots(self, n_layers):
dots = VGroup()
for n in range(n_layers+1):
dots.add(self.get_dot_layer(n))
return dots
class PatreonLogo(Scene):
def construct(self):
words1 = OldTexText(
"Support future\\\\",
"3blue1brown videos"
)
words2 = OldTexText(
"Early access to\\\\",
"``Essence of'' series"
)
for words in words1, words2:
words.scale(2)
words.to_edge(DOWN)
self.play(Write(words1))
self.wait(2)
self.play(Transform(words1, words2))
self.wait(2)
class PatreonLogin(Scene):
pass
class PythagoreanTransformation(Scene):
def construct(self):
tri1 = VGroup(
Line(ORIGIN, 2*RIGHT, color = BLUE),
Line(2*RIGHT, 3*UP, color = YELLOW),
Line(3*UP, ORIGIN, color = MAROON_B),
)
tri1.shift(2.5*(DOWN+LEFT))
tri2, tri3, tri4 = copies = [
tri1.copy().rotate(-i*np.pi/2)
for i in range(1, 4)
]
a = OldTex("a").next_to(tri1[0], DOWN, buff = MED_SMALL_BUFF)
b = OldTex("b").next_to(tri1[2], LEFT, buff = MED_SMALL_BUFF)
c = OldTex("c").next_to(tri1[1].get_center(), UP+RIGHT)
c_square = Polygon(*[
tri[1].get_end()
for tri in [tri1] + copies
])
c_square.set_stroke(width = 0)
c_square.set_fill(color = YELLOW, opacity = 0.5)
c_square_tex = OldTex("c^2")
big_square = Polygon(*[
tri[0].get_start()
for tri in [tri1] + copies
])
big_square.set_color(WHITE)
a_square = Square(side_length = 2)
a_square.shift(1.5*(LEFT+UP))
a_square.set_stroke(width = 0)
a_square.set_fill(color = BLUE, opacity = 0.5)
a_square_tex = OldTex("a^2")
a_square_tex.move_to(a_square)
b_square = Square(side_length = 3)
b_square.move_to(
a_square.get_corner(DOWN+RIGHT),
aligned_edge = UP+LEFT
)
b_square.set_stroke(width = 0)
b_square.set_fill(color = MAROON_B, opacity = 0.5)
b_square_tex = OldTex("b^2")
b_square_tex.move_to(b_square)
self.play(ShowCreation(tri1, run_time = 2))
self.play(*list(map(Write, [a, b, c])))
self.wait()
self.play(
FadeIn(c_square),
Animation(c)
)
self.play(Transform(c, c_square_tex))
self.wait(2)
mover = tri1.copy()
for copy in copies:
self.play(Transform(
mover, copy,
path_arc = -np.pi/2
))
self.add(copy)
self.remove(mover)
self.add(big_square, *[tri1]+copies)
self.wait(2)
self.play(*list(map(FadeOut, [a, b, c, c_square])))
self.play(
tri3.shift,
tri1.get_corner(UP+LEFT) -\
tri3.get_corner(UP+LEFT)
)
self.play(tri2.shift, 2*RIGHT)
self.play(tri4.shift, 3*UP)
self.wait()
self.play(FadeIn(a_square))
self.play(FadeIn(b_square))
self.play(Write(a_square_tex))
self.play(Write(b_square_tex))
self.wait(2)
class KindWordsOnEoLA(TeacherStudentsScene):
def construct(self):
rect = Rectangle(width = 16, height = 9, color = WHITE)
rect.set_height(4)
title = OldTexText("Essence of linear algebra")
title.to_edge(UP)
rect.next_to(title, DOWN)
self.play(
Write(title),
ShowCreation(rect),
*[
ApplyMethod(pi.look_at, rect)
for pi in self.get_pi_creatures()
],
run_time = 2
)
self.random_blink()
self.play_student_changes(*["hooray"]*3)
self.random_blink()
self.play(self.get_teacher().change_mode, "happy")
self.random_blink()
class MakeALotOfPiCreaturesHappy(Scene):
def construct(self):
width = 7
height = 4
pis = VGroup(*[
VGroup(*[
Randolph()
for x in range(7)
]).arrange(RIGHT, buff = MED_LARGE_BUFF)
for x in range(4)
]).arrange(DOWN, buff = MED_LARGE_BUFF)
pi_list = list(it.chain(*[
layer.submobjects
for layer in pis.submobjects
]))
random.shuffle(pi_list)
colors = color_gradient([BLUE_D, GREY_BROWN], len(pi_list))
for pi, color in zip(pi_list, colors):
pi.set_color(color)
pis = VGroup(*pi_list)
pis.set_height(6)
self.add(pis)
pis.generate_target()
self.wait()
for pi, color in zip(pis.target, colors):
pi.change_mode("hooray")
# pi.scale(1)
pi.set_color(color)
self.play(
MoveToTarget(
pis,
run_time = 2,
lag_ratio = 0.5,
)
)
for x in range(10):
pi = random.choice(pi_list)
self.play(Blink(pi))
class IntegrationByParts(Scene):
def construct(self):
rect = Rectangle(width = 5, height = 3)
# f = lambda t : 4*np.sin(t*np.pi/2)
f = lambda t : 4*t
g = lambda t : 3*smooth(t)
curve = ParametricCurve(lambda t : f(t)*RIGHT + g(t)*DOWN)
curve.set_color(YELLOW)
curve.center()
rect = Rectangle()
rect.replace(curve, stretch = True)
regions = []
for vect, color in (UP+RIGHT, BLUE), (DOWN+LEFT, GREEN):
region = curve.copy()
region.add_line_to(rect.get_corner(vect))
region.set_stroke(width = 0)
region.set_fill(color = color, opacity = 0.5)
regions.append(region)
upper_right, lower_left = regions
v_lines, h_lines = VGroup(), VGroup()
for alpha in np.linspace(0, 1, 30):
point = curve.point_from_proportion(alpha)
top_point = curve.get_points()[0][1]*UP + point[0]*RIGHT
left_point = curve.get_points()[0][0]*RIGHT + point[1]*UP
v_lines.add(Line(top_point, point))
h_lines.add(Line(left_point, point))
v_lines.set_color(BLUE_E)
h_lines.set_color(GREEN_E)
equation = OldTex(
"\\int_0^1 g\\,df",
"+\\int_0^1 f\\,dg",
"= \\big(fg \\big)_0^1"
)
equation.to_edge(UP)
equation.set_color_by_tex(
"\\int_0^1 g\\,df",
upper_right.get_color()
)
equation.set_color_by_tex(
"+\\int_0^1 f\\,dg",
lower_left.get_color()
)
left_brace = Brace(rect, LEFT)
down_brace = Brace(rect, DOWN)
g_T = left_brace.get_text("$g(t)\\big|_0^1$")
f_T = down_brace.get_text("$f(t)\\big|_0^1$")
self.draw_curve(curve)
self.play(ShowCreation(rect))
self.play(*list(map(Write, [down_brace, left_brace, f_T, g_T])))
self.wait()
self.play(FadeIn(upper_right))
self.play(
ShowCreation(
v_lines,
run_time = 2
),
Animation(curve),
Animation(rect)
)
self.play(Write(equation[0]))
self.wait()
self.play(FadeIn(lower_left))
self.play(
ShowCreation(
h_lines,
run_time = 2
),
Animation(curve),
Animation(rect)
)
self.play(Write(equation[1]))
self.wait()
self.play(Write(equation[2]))
self.wait()
def draw_curve(self, curve):
lp, lnum, comma, rnum, rp = coords = OldTex(
"\\big(f(", "t", "), g(", "t", ")\\big)"
)
coords.set_color_by_tex("0.00", BLACK)
dot = Dot(radius = 0.1)
dot.move_to(curve.get_points()[0])
coords.next_to(dot, UP+RIGHT)
self.play(
ShowCreation(curve),
UpdateFromFunc(
dot,
lambda d : d.move_to(curve.get_points()[-1])
),
MaintainPositionRelativeTo(coords, dot),
run_time = 5,
rate_func=linear
)
self.wait()
self.play(*list(map(FadeOut, [coords, dot])))
class EndScreen(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"""
See you every
other friday!
""",
target_mode = "hooray"
)
self.play_student_changes(*["happy"]*3)
self.random_blink()
|
|
from manim_imports_ext import *
class CountingScene(Scene):
CONFIG = {
"base" : 10,
"power_colors" : [YELLOW, MAROON_B, RED, GREEN, BLUE, PURPLE_D],
"counting_dot_starting_position" : (FRAME_X_RADIUS-1)*RIGHT + (FRAME_Y_RADIUS-1)*UP,
"count_dot_starting_radius" : 0.5,
"dot_configuration_height" : 2,
"ones_configuration_location" : UP+2*RIGHT,
"num_scale_factor" : 2,
"num_start_location" : 2*DOWN,
}
def setup(self):
self.dots = VGroup()
self.number = 0
self.number_mob = VGroup(OldTex(str(self.number)))
self.number_mob.scale(self.num_scale_factor)
self.number_mob.shift(self.num_start_location)
self.digit_width = self.number_mob.get_width()
self.initialize_configurations()
self.arrows = VGroup()
self.add(self.number_mob)
def get_template_configuration(self):
#This should probably be replaced for non-base-10 counting scenes
down_right = (0.5)*RIGHT + (np.sqrt(3)/2)*DOWN
result = []
for down_right_steps in range(5):
for left_steps in range(down_right_steps):
result.append(
down_right_steps*down_right + left_steps*LEFT
)
return reversed(result[:self.base])
def get_dot_template(self):
#This should be replaced for non-base-10 counting scenes
down_right = (0.5)*RIGHT + (np.sqrt(3)/2)*DOWN
dots = VGroup(*[
Dot(
point,
radius = 0.25,
fill_opacity = 0,
stroke_width = 2,
stroke_color = WHITE,
)
for point in self.get_template_configuration()
])
dots[-1].set_stroke(width = 0)
dots.set_height(self.dot_configuration_height)
return dots
def initialize_configurations(self):
self.dot_templates = []
self.dot_template_iterators = []
self.curr_configurations = []
def add_configuration(self):
new_template = self.get_dot_template()
new_template.move_to(self.ones_configuration_location)
left_vect = (new_template.get_width()+LARGE_BUFF)*LEFT
new_template.shift(
left_vect*len(self.dot_templates)
)
self.dot_templates.append(new_template)
self.dot_template_iterators.append(
it.cycle(new_template)
)
self.curr_configurations.append(VGroup())
def count(self, max_val, run_time_per_anim = 1):
for x in range(max_val):
self.increment(run_time_per_anim)
def increment(self, run_time_per_anim = 1, added_anims = [], total_run_time = None):
run_all_at_once = (total_run_time is not None)
if run_all_at_once:
num_rollovers = self.get_num_rollovers()
run_time_per_anim = float(total_run_time)/(num_rollovers+1)
moving_dot = Dot(
self.counting_dot_starting_position,
radius = self.count_dot_starting_radius,
color = self.power_colors[0],
)
moving_dot.generate_target()
moving_dot.set_fill(opacity = 0)
continue_rolling_over = True
place = 0
self.number += 1
added_anims = list(added_anims) #Silly python objects...
added_anims += self.get_new_configuration_animations()
while continue_rolling_over:
moving_dot.target.replace(
next(self.dot_template_iterators[place])
)
if run_all_at_once:
denom = float(num_rollovers+1)
start_t = place/denom
def get_modified_rate_func(anim):
return lambda t : anim.original_rate_func(
start_t + t/denom
)
for anim in added_anims:
if not hasattr(anim, "original_rate_func"):
anim.original_rate_func = anim.rate_func
anim.rate_func = get_modified_rate_func(anim)
self.play(
MoveToTarget(moving_dot),
*added_anims,
run_time = run_time_per_anim
)
self.curr_configurations[place].add(moving_dot)
if not run_all_at_once:
added_anims = []
if len(self.curr_configurations[place].split()) == self.base:
full_configuration = self.curr_configurations[place]
self.curr_configurations[place] = VGroup()
place += 1
center = full_configuration.get_center_of_mass()
radius = 0.6*max(
full_configuration.get_width(),
full_configuration.get_height(),
)
circle = Circle(
radius = radius,
stroke_width = 0,
fill_color = self.power_colors[place],
fill_opacity = 0.5,
)
circle.move_to(center)
moving_dot = VGroup(circle, full_configuration)
moving_dot.generate_target()
moving_dot[0].set_fill(opacity = 0)
else:
continue_rolling_over = False
self.play(*self.get_digit_increment_animations())
def get_new_configuration_animations(self):
if self.is_perfect_power():
self.add_configuration()
return [FadeIn(self.dot_templates[-1])]
else:
return []
def get_digit_increment_animations(self):
result = []
new_number_mob = self.get_number_mob(self.number)
new_number_mob.move_to(self.number_mob, RIGHT)
if self.is_perfect_power():
place = len(new_number_mob.split())-1
arrow = Arrow(
new_number_mob[place].get_top(),
self.dot_templates[place].get_bottom(),
color = self.power_colors[place]
)
self.arrows.add(arrow)
result.append(ShowCreation(arrow))
result.append(Transform(
self.number_mob, new_number_mob,
lag_ratio = 0.5
))
return result
def get_number_mob(self, num):
result = VGroup()
place = 0
while num > 0:
digit = OldTex(str(num % self.base))
if place >= len(self.power_colors):
self.power_colors += self.power_colors
digit.set_color(self.power_colors[place])
digit.scale(self.num_scale_factor)
digit.move_to(result, RIGHT)
digit.shift(place*(self.digit_width+SMALL_BUFF)*LEFT)
result.add(digit)
num /= self.base
place += 1
return result
def is_perfect_power(self):
number = self.number
while number > 1:
if number%self.base != 0:
return False
number /= self.base
return True
def get_num_rollovers(self):
next_number = self.number + 1
result = 0
while next_number%self.base == 0:
result += 1
next_number /= self.base
return result
class BinaryCountingScene(CountingScene):
CONFIG = {
"base" : 2,
"dot_configuration_height" : 1,
"ones_configuration_location" : UP+5*RIGHT
}
def get_template_configuration(self):
return [ORIGIN, UP]
class CountInDecimal(CountingScene):
def construct(self):
for x in range(11):
self.increment()
for x in range(85):
self.increment(0.25)
for x in range(20):
self.increment()
class CountInTernary(CountingScene):
CONFIG = {
"base" : 3,
"dot_configuration_height" : 1,
"ones_configuration_location" : UP+4*RIGHT
}
def construct(self):
self.count(27)
# def get_template_configuration(self):
# return [ORIGIN, UP]
class CountTo27InTernary(CountInTernary):
def construct(self):
for x in range(27):
self.increment()
self.wait()
class CountInBinaryTo256(BinaryCountingScene):
def construct(self):
self.count(256, 0.25)
class TowersOfHanoiScene(Scene):
CONFIG = {
"disk_start_and_end_colors" : [BLUE_E, BLUE_A],
"num_disks" : 5,
"peg_width" : 0.25,
"peg_height" : 2.5,
"peg_spacing" : 4,
"include_peg_labels" : True,
"middle_peg_bottom" : 0.5*DOWN,
"disk_height" : 0.4,
"disk_min_width" : 1,
"disk_max_width" : 3,
"default_disk_run_time_off_peg" : 1,
"default_disk_run_time_on_peg" : 2,
}
def setup(self):
self.add_pegs()
self.add_disks()
def add_pegs(self):
peg = Rectangle(
height = self.peg_height,
width = self.peg_width,
stroke_width = 0,
fill_color = GREY_BROWN,
fill_opacity = 1,
)
peg.move_to(self.middle_peg_bottom, DOWN)
self.pegs = VGroup(*[
peg.copy().shift(vect)
for vect in (self.peg_spacing*LEFT, ORIGIN, self.peg_spacing*RIGHT)
])
self.add(self.pegs)
if self.include_peg_labels:
self.peg_labels = VGroup(*[
OldTex(char).next_to(peg, DOWN)
for char, peg in zip("ABC", self.pegs)
])
self.add(self.peg_labels)
def add_disks(self):
self.disks = VGroup(*[
Rectangle(
height = self.disk_height,
width = width,
fill_color = color,
fill_opacity = 0.8,
stroke_width = 0,
)
for width, color in zip(
np.linspace(
self.disk_min_width,
self.disk_max_width,
self.num_disks
),
color_gradient(
self.disk_start_and_end_colors,
self.num_disks
)
)
])
for number, disk in enumerate(self.disks):
label = OldTex(str(number))
label.set_color(BLACK)
label.set_height(self.disk_height/2)
label.move_to(disk)
disk.add(label)
disk.label = label
self.reset_disks(run_time = 0)
self.add(self.disks)
def reset_disks(self, **kwargs):
self.disks.generate_target()
self.disks.target.arrange(DOWN, buff = 0)
self.disks.target.move_to(self.pegs[0], DOWN)
self.play(
MoveToTarget(self.disks),
**kwargs
)
self.disk_tracker = [
set(range(self.num_disks)),
set([]),
set([])
]
def disk_index_to_peg_index(self, disk_index):
for index, disk_set in enumerate(self.disk_tracker):
if disk_index in disk_set:
return index
raise Exception("Somehow this disk wasn't accounted for...")
def min_disk_index_on_peg(self, peg_index):
disk_index_set = self.disk_tracker[peg_index]
if disk_index_set:
return min(self.disk_tracker[peg_index])
else:
return self.num_disks
def bottom_point_for_next_disk(self, peg_index):
min_disk_index = self.min_disk_index_on_peg(peg_index)
if min_disk_index >= self.num_disks:
return self.pegs[peg_index].get_bottom()
else:
return self.disks[min_disk_index].get_top()
def get_next_disk_0_peg(self):
curr_peg_index = self.disk_index_to_peg_index(0)
return (curr_peg_index+1)%3
def get_available_peg(self, disk_index):
if disk_index == 0:
return self.get_next_disk_0_peg()
for index in range(len(list(self.pegs))):
if self.min_disk_index_on_peg(index) > disk_index:
return index
raise Exception("Tower's of Honoi rule broken: No available disks")
def set_disk_config(self, peg_indices):
assert(len(peg_indices) == self.num_disks)
self.disk_tracker = [set([]) for x in range(3)]
for n, peg_index in enumerate(peg_indices):
disk_index = self.num_disks - n - 1
disk = self.disks[disk_index]
peg = self.pegs[peg_index]
disk.move_to(peg.get_bottom(), DOWN)
n_disks_here = len(self.disk_tracker[peg_index])
disk.shift(disk.get_height()*n_disks_here*UP)
self.disk_tracker[peg_index].add(disk_index)
def move_disk(self, disk_index, **kwargs):
next_peg_index = self.get_available_peg(disk_index)
self.move_disk_to_peg(disk_index, next_peg_index, **kwargs)
def move_subtower_to_peg(self, num_disks, next_peg_index, **kwargs):
disk_indices = list(range(num_disks))
peg_indices = list(map(self.disk_index_to_peg_index, disk_indices))
if len(set(peg_indices)) != 1:
warnings.warn("These disks don't make up a tower right now")
self.move_disks_to_peg(disk_indices, next_peg_index, **kwargs)
def move_disk_to_peg(self, disk_index, next_peg_index, **kwargs):
self.move_disks_to_peg([disk_index], next_peg_index, **kwargs)
def move_disks_to_peg(self, disk_indices, next_peg_index, run_time = None, stay_on_peg = True, added_anims = []):
if run_time is None:
if stay_on_peg is True:
run_time = self.default_disk_run_time_on_peg
else:
run_time = self.default_disk_run_time_off_peg
disks = VGroup(*[self.disks[index] for index in disk_indices])
max_disk_index = max(disk_indices)
next_peg = self.pegs[next_peg_index]
curr_peg_index = self.disk_index_to_peg_index(max_disk_index)
curr_peg = self.pegs[curr_peg_index]
if self.min_disk_index_on_peg(curr_peg_index) != max_disk_index:
warnings.warn("Tower's of Hanoi rule broken: disk has crap on top of it")
target_bottom_point = self.bottom_point_for_next_disk(next_peg_index)
path_arc = np.sign(curr_peg_index-next_peg_index)*np.pi/3
if stay_on_peg:
self.play(
Succession(
ApplyMethod(disks.next_to, curr_peg, UP, 0),
ApplyMethod(disks.next_to, next_peg, UP, 0, path_arc = path_arc),
ApplyMethod(disks.move_to, target_bottom_point, DOWN),
),
*added_anims,
run_time = run_time,
rate_func = lambda t : smooth(t, 2)
)
else:
self.play(
ApplyMethod(disks.move_to, target_bottom_point, DOWN),
*added_anims,
path_arc = path_arc*2,
run_time = run_time,
rate_func = lambda t : smooth(t, 2)
)
for disk_index in disk_indices:
self.disk_tracker[curr_peg_index].remove(disk_index)
self.disk_tracker[next_peg_index].add(disk_index)
class ConstrainedTowersOfHanoiScene(TowersOfHanoiScene):
def get_next_disk_0_peg(self):
if not hasattr(self, "total_disk_0_movements"):
self.total_disk_0_movements = 0
curr_peg_index = self.disk_index_to_peg_index(0)
if (self.total_disk_0_movements/2)%2 == 0:
result = curr_peg_index + 1
else:
result = curr_peg_index - 1
self.total_disk_0_movements += 1
return result
def get_ruler_sequence(order = 4):
if order == -1:
return []
else:
smaller = get_ruler_sequence(order - 1)
return smaller + [order] + smaller
def get_ternary_ruler_sequence(order = 4):
if order == -1:
return []
else:
smaller = get_ternary_ruler_sequence(order-1)
return smaller+[order]+smaller+[order]+smaller
class SolveHanoi(TowersOfHanoiScene):
def construct(self):
self.wait()
for x in get_ruler_sequence(self.num_disks-1):
self.move_disk(x, stay_on_peg = False)
self.wait()
class SolveConstrainedHanoi(ConstrainedTowersOfHanoiScene):
def construct(self):
self.wait()
for x in get_ternary_ruler_sequence(self.num_disks-1):
self.move_disk(x, run_time = 0.5, stay_on_peg = False)
self.wait()
class Keith(PiCreature):
CONFIG = {
"color" : GREEN_D
}
def get_binary_tex_mobs(num_list):
result = VGroup()
zero_width = OldTex("0").get_width()
nudge = zero_width + SMALL_BUFF
for num in num_list:
bin_string = bin(num)[2:]#Strip off the "0b" prefix
bits = VGroup(*list(map(Tex, bin_string)))
for n, bit in enumerate(bits):
bit.shift(n*nudge*RIGHT)
bits.move_to(ORIGIN, RIGHT)
result.add(bits)
return result
def get_base_b_tex_mob(number, base, n_digits):
assert(number < base**n_digits)
curr_digit = n_digits - 1
zero = OldTex("0")
zero_width = zero.get_width()
zero_height = zero.get_height()
result = VGroup()
for place in range(n_digits):
remainder = number%base
digit_mob = OldTex(str(remainder))
digit_mob.set_height(zero_height)
digit_mob.shift(place*(zero_width+SMALL_BUFF)*LEFT)
result.add(digit_mob)
number = (number - remainder)/base
return result.center()
def get_binary_tex_mob(number, n_bits = 4):
return get_base_b_tex_mob(number, 2, n_bits)
def get_ternary_tex_mob(number, n_trits = 4):
return get_base_b_tex_mob(number, 3, n_trits)
####################
class IntroduceKeith(Scene):
def construct(self):
morty = Mortimer(mode = "happy")
keith = Keith(mode = "dance_kick")
keith_image = ImageMobject("keith_schwarz", invert = False)
# keith_image = Rectangle()
keith_image.set_height(FRAME_HEIGHT - 2)
keith_image.next_to(ORIGIN, LEFT)
keith.move_to(keith_image, DOWN+RIGHT)
morty.next_to(keith, buff = LARGE_BUFF, aligned_edge = DOWN)
morty.make_eye_contact(keith)
randy = Randolph().next_to(keith, LEFT, LARGE_BUFF, aligned_edge = DOWN)
randy.shift_onto_screen()
bubble = keith.get_bubble(SpeechBubble, width = 7)
bubble.write("01101011 $\\Rightarrow$ Towers of Hanoi")
zero_width = bubble.content[0].get_width()
one_width = bubble.content[1].get_width()
for mob in bubble.content[:8]:
if abs(mob.get_width() - zero_width) < 0.01:
mob.set_color(GREEN)
else:
mob.set_color(YELLOW)
bubble.resize_to_content()
bubble.pin_to(keith)
VGroup(bubble, bubble.content).shift(DOWN)
randy.bubble = randy.get_bubble(SpeechBubble, height = 3)
randy.bubble.write("Wait, what's \\\\ Towers of Hanoi?")
title = OldTexText("Keith Schwarz (Computer scientist)")
title.to_edge(UP)
self.add(keith_image, morty)
self.play(Write(title))
self.play(FadeIn(keith, run_time = 2))
self.play(FadeOut(keith_image), Animation(keith))
self.play(Blink(morty))
self.play(
keith.change_mode, "speaking",
keith.set_height, morty.get_height(),
keith.next_to, morty, LEFT, LARGE_BUFF,
run_time = 1.5
)
self.play(
ShowCreation(bubble),
Write(bubble.content)
)
self.play(
morty.change_mode, "pondering",
morty.look_at, bubble
)
self.play(Blink(keith))
self.wait()
original_content = bubble.content
bubble.write("I'm usually meh \\\\ on puzzles")
self.play(
keith.change_mode, "hesitant",
Transform(original_content, bubble.content),
)
self.play(
morty.change_mode, "happy",
morty.look_at, keith.eyes
)
self.play(Blink(keith))
bubble.write("But \\emph{analyzing} puzzles!")
VGroup(*bubble.content[3:12]).set_color(YELLOW)
self.play(
keith.change_mode, "hooray",
Transform(original_content, bubble.content)
)
self.play(Blink(morty))
self.wait()
self.play(FadeIn(randy))
self.play(
randy.change_mode, "confused",
randy.look_at, keith.eyes,
keith.change_mode, "plain",
keith.look_at, randy.eyes,
morty.change_mode, "plain",
morty.look_at, randy.eyes,
FadeOut(bubble),
FadeOut(original_content),
ShowCreation(randy.bubble),
Write(randy.bubble.content)
)
self.play(Blink(keith))
self.play(
keith.change_mode, "hooray",
keith.look_at, randy.eyes
)
self.wait()
class IntroduceTowersOfHanoi(TowersOfHanoiScene):
def construct(self):
self.clear()
self.add_title()
self.show_setup()
self.note_disk_labels()
self.show_more_disk_possibility()
self.move_full_tower()
self.move_single_disk()
self.cannot_move_disk_onto_smaller_disk()
def add_title(self):
title = OldTexText("Towers of Hanoi")
title.to_edge(UP)
self.add(title)
self.title = title
def show_setup(self):
self.pegs.save_state()
bottom = self.pegs.get_bottom()
self.pegs.stretch_to_fit_height(0)
self.pegs.move_to(bottom)
self.play(
ApplyMethod(
self.pegs.restore,
lag_ratio = 0.5,
run_time = 2
),
Write(self.peg_labels)
)
self.wait()
self.bring_in_disks()
self.wait()
def bring_in_disks(self):
peg = self.pegs[0]
disk_groups = VGroup()
for disk in self.disks:
top = Circle(radius = disk.get_width()/2)
inner = Circle(radius = self.peg_width/2)
inner.flip()
top.add_subpath(inner.points)
top.set_stroke(width = 0)
top.set_fill(disk.get_color())
top.rotate(np.pi/2, RIGHT)
top.move_to(disk, UP)
bottom = top.copy()
bottom.move_to(disk, DOWN)
group = VGroup(disk, top, bottom)
group.truly_original_state = group.copy()
group.next_to(peg, UP, 0)
group.rotate(-np.pi/24, RIGHT)
group.save_state()
group.rotate(-11*np.pi/24, RIGHT)
disk.set_fill(opacity = 0)
disk_groups.add(group)
disk_groups.arrange()
disk_groups.next_to(self.peg_labels, DOWN)
self.play(FadeIn(
disk_groups,
run_time = 2,
lag_ratio = 0.5
))
for group in reversed(list(disk_groups)):
self.play(group.restore)
self.play(Transform(group, group.truly_original_state))
self.remove(disk_groups)
self.add(self.disks)
def note_disk_labels(self):
labels = [disk.label for disk in self.disks]
last = VGroup().save_state()
for label in labels:
label.save_state()
self.play(
label.scale, 2,
label.set_color, YELLOW,
last.restore,
run_time = 0.5
)
last = label
self.play(last.restore)
self.wait()
def show_more_disk_possibility(self):
original_num_disks = self.num_disks
original_disk_height = self.disk_height
original_disks = self.disks
original_disks_copy = original_disks.copy()
#Hacky
self.num_disks = 10
self.disk_height = 0.3
self.add_disks()
new_disks = self.disks
self.disks = original_disks
self.remove(new_disks)
self.play(Transform(self.disks, new_disks))
self.wait()
self.play(Transform(self.disks, original_disks_copy))
self.remove(self.disks)
self.disks = original_disks_copy
self.add(self.disks)
self.wait()
self.num_disks = original_num_disks
self.disk_height = original_disk_height
def move_full_tower(self):
self.move_subtower_to_peg(self.num_disks, 1, run_time = 2)
self.wait()
self.reset_disks(run_time = 1, lag_ratio = 0.5)
self.wait()
def move_single_disk(self):
for x in 0, 1, 0:
self.move_disk(x)
self.wait()
def cannot_move_disk_onto_smaller_disk(self):
also_not_allowed = OldTexText("Not allowed")
also_not_allowed.to_edge(UP)
also_not_allowed.set_color(RED)
cross = OldTex("\\times")
cross.set_fill(RED, opacity = 0.5)
disk = self.disks[2]
disk.save_state()
self.move_disks_to_peg([2], 2, added_anims = [
Transform(self.title, also_not_allowed, run_time = 1)
])
cross.replace(disk)
self.play(FadeIn(cross))
self.wait()
self.play(
FadeOut(cross),
FadeOut(self.title),
disk.restore
)
self.wait()
class ExampleFirstMoves(TowersOfHanoiScene):
def construct(self):
ruler_sequence = get_ruler_sequence(4)
cross = OldTex("\\times")
cross.set_fill(RED, 0.7)
self.wait()
self.play(
self.disks[0].set_fill, YELLOW,
self.disks[0].label.set_color, BLACK
)
self.wait()
self.move_disk(0)
self.wait()
self.play(
self.disks[1].set_fill, YELLOW_D,
self.disks[1].label.set_color, BLACK
)
self.move_disk_to_peg(1, 1)
cross.replace(self.disks[1])
self.play(FadeIn(cross))
self.wait()
self.move_disk_to_peg(1, 2, added_anims = [FadeOut(cross)])
self.wait()
for x in ruler_sequence[2:9]:
self.move_disk(x)
for x in ruler_sequence[9:]:
self.move_disk(x, run_time = 0.5, stay_on_peg = False)
self.wait()
class KeithShowingBinary(Scene):
def construct(self):
keith = Keith()
morty = Mortimer()
morty.to_corner(DOWN+RIGHT)
keith.next_to(morty, LEFT, buff = 2*LARGE_BUFF)
randy = Randolph()
randy.next_to(keith, LEFT, buff = 2*LARGE_BUFF)
randy.bubble = randy.get_bubble(SpeechBubble)
randy.bubble.set_fill(BLACK, opacity = 1)
randy.bubble.write("Hold on...how does \\\\ binary work again?")
binary_tex_mobs = get_binary_tex_mobs(list(range(16)))
binary_tex_mobs.shift(keith.get_corner(UP+LEFT))
binary_tex_mobs.shift(0.5*(UP+RIGHT))
bits_list = binary_tex_mobs.split()
bits = bits_list.pop(0)
def get_bit_flip():
return Transform(
bits, bits_list.pop(0),
rate_func = squish_rate_func(smooth, 0, 0.7)
)
self.play(
keith.change_mode, "wave_1",
keith.look_at, bits,
morty.look_at, bits,
Write(bits)
)
for x in range(2):
self.play(get_bit_flip())
self.play(
morty.change_mode, "pondering",
morty.look_at, bits,
get_bit_flip()
)
while bits_list:
added_anims = []
if random.random() < 0.2:
if random.random() < 0.5:
added_anims.append(Blink(keith))
else:
added_anims.append(Blink(morty))
self.play(get_bit_flip(), *added_anims)
self.wait()
self.play(
FadeIn(randy),
morty.change_mode, "plain",
morty.look_at, randy.eyes,
keith.change_mode, "plain",
keith.look_at, randy.eyes,
)
self.play(
randy.change_mode, "confused",
ShowCreation(randy.bubble),
Write(randy.bubble.content)
)
self.play(Blink(randy))
self.wait()
self.play(morty.change_mode, "hooray")
self.play(Blink(morty))
self.wait()
class FocusOnRhythm(Scene):
def construct(self):
title = OldTexText("Focus on rhythm")
title.scale(1.5)
letters = list(reversed(title[-6:]))
self.play(Write(title, run_time = 1))
sequence = get_ruler_sequence(5)
for x in sequence:
movers = VGroup(*letters[:x+1])
self.play(
movers.shift, 0.2*DOWN,
rate_func = there_and_back,
run_time = 0.25
)
class IntroduceBase10(Scene):
def construct(self):
self.expand_example_number()
self.list_digits()
def expand_example_number(self):
title = OldTexText("``Base 10''")
title.to_edge(UP)
number = OldTex("137")
number.next_to(title, DOWN)
number.shift(2*LEFT)
colors = [RED, MAROON_B, YELLOW]
expansion = OldTex(
"1(100) + ",
"3(10) + ",
"7"
)
expansion.next_to(number, DOWN, buff = LARGE_BUFF, aligned_edge = RIGHT)
arrows = VGroup()
number.generate_target()
for color, digit, term in zip(colors, number.target, expansion):
digit.set_color(color)
term.set_color(color)
arrow = Arrow(digit, term.get_top())
arrow.set_color(color)
arrows.add(arrow)
expansion.save_state()
for digit, term in zip(number, expansion):
Transform(term, digit).update(1)
self.play(
MoveToTarget(number),
ShowCreation(arrows),
ApplyMethod(
expansion.restore, lag_ratio = 0.5),
run_time = 2
)
self.play(Write(title))
self.wait()
self.title = title
def list_digits(self):
digits = OldTexText("""
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
""")
digits.next_to(self.title, DOWN, buff = LARGE_BUFF)
digits.shift(2*RIGHT)
self.play(Write(digits))
self.wait()
class RhythmOfDecimalCounting(CountingScene):
CONFIG = {
"ones_configuration_location" : 2*UP+2*RIGHT,
"num_start_location" : DOWN
}
def construct(self):
for x in range(10):
self.increment()
brace = Brace(self.number_mob)
two_digits = brace.get_text("Two digits")
one_brace = Brace(self.number_mob[-1])
tens_place = one_brace.get_text("Ten's place")
ten_group = self.curr_configurations[1][0]
self.play(
GrowFromCenter(brace),
Write(two_digits, run_time = 1)
)
self.wait(2)
self.play(
Transform(brace, one_brace),
Transform(two_digits, tens_place)
)
self.wait()
ten_group.save_state()
self.play(
ten_group.scale, 7,
ten_group.shift, 2*(DOWN+LEFT),
)
self.wait()
self.play(
ten_group.restore,
*list(map(FadeOut, [brace, two_digits]))
)
for x in range(89):
self.increment(run_time_per_anim = 0.25)
self.increment(run_time_per_anim = 1)
self.wait()
hundred_group = self.curr_configurations[2][0]
hundred_group.save_state()
self.play(
hundred_group.scale, 14,
hundred_group.to_corner, DOWN+LEFT
)
self.wait()
self.play(hundred_group.restore)
self.wait()
groups = [
VGroup(*pair)
for pair in zip(self.dot_templates, self.curr_configurations)
]
self.play(
groups[2].to_edge, RIGHT,
MaintainPositionRelativeTo(groups[1], groups[2]),
MaintainPositionRelativeTo(groups[0], groups[2]),
self.number_mob.to_edge, RIGHT, LARGE_BUFF,
FadeOut(self.arrows)
)
class DecimalCountingAtHundredsScale(CountingScene):
CONFIG = {
"power_colors" : [RED, GREEN, BLUE, PURPLE_D],
"counting_dot_starting_position" : (FRAME_X_RADIUS+1)*RIGHT + (FRAME_Y_RADIUS-2)*UP,
"ones_configuration_location" : 2*UP+5.7*RIGHT,
"num_start_location" : DOWN + 3*RIGHT
}
def construct(self):
added_zeros = OldTex("00")
added_zeros.scale(self.num_scale_factor)
added_zeros.next_to(self.number_mob, RIGHT, SMALL_BUFF, aligned_edge = DOWN)
added_zeros.set_color_by_gradient(MAROON_B, YELLOW)
self.add(added_zeros)
self.increment(run_time_per_anim = 0)
VGroup(self.number_mob, added_zeros).to_edge(RIGHT, buff = LARGE_BUFF)
VGroup(self.dot_templates[0], self.curr_configurations[0]).to_edge(RIGHT)
Transform(
self.arrows[0],
Arrow(self.number_mob, self.dot_templates[0], color = self.power_colors[0])
).update(1)
for x in range(10):
this_range = list(range(8)) if x == 0 else list(range(9))
for y in this_range:
self.increment(run_time_per_anim = 0.25)
self.increment(run_time_per_anim = 1)
class IntroduceBinaryCounting(BinaryCountingScene):
CONFIG = {
"ones_configuration_location" : UP+5*RIGHT,
"num_start_location" : DOWN+2*RIGHT
}
def construct(self):
self.introduce_name()
self.initial_counting()
self.show_self_similarity()
def introduce_name(self):
title = OldTexText("Binary (base 2):", "0, 1")
title.to_edge(UP)
self.add(title)
self.number_mob.set_fill(opacity = 0)
brace = Brace(title[1], buff = SMALL_BUFF)
bits = OldTexText("bi", "ts", arg_separator = "")
bits.submobjects.insert(1, VectorizedPoint(bits.get_center()))
binary_digits = OldTexText("bi", "nary digi", "ts", arg_separator = "")
for mob in bits, binary_digits:
mob.next_to(brace, DOWN, buff = SMALL_BUFF)
VGroup(brace, bits, binary_digits).set_color(BLUE)
binary_digits[1].set_color(BLUE_E)
self.play(
GrowFromCenter(brace),
Write(bits)
)
self.wait()
bits.save_state()
self.play(Transform(bits, binary_digits))
self.wait()
self.play(bits.restore)
self.wait()
def initial_counting(self):
randy = Randolph().to_corner(DOWN+LEFT)
bubble = randy.get_bubble(ThoughtBubble, height = 3.4, width = 5)
bubble.write(
"Not ten, not ten \\\\",
"\\quad not ten, not ten..."
)
self.play(self.number_mob.set_fill, self.power_colors[0], 1)
self.increment()
self.wait()
self.start_dot = self.curr_configurations[0][0]
##Up to 10
self.increment()
brace = Brace(self.number_mob[1])
twos_place = brace.get_text("Two's place")
self.play(
GrowFromCenter(brace),
Write(twos_place)
)
self.play(
FadeIn(randy),
ShowCreation(bubble)
)
self.play(
randy.change_mode, "hesitant",
randy.look_at, self.number_mob,
Write(bubble.content)
)
self.wait()
curr_content = bubble.content
bubble.write("$1 \\! \\cdot \\! 2+$", "$0$")
bubble.content[0][0].set_color(self.power_colors[1])
self.play(
Transform(curr_content, bubble.content),
randy.change_mode, "pondering",
randy.look_at, self.number_mob
)
self.remove(curr_content)
self.add(bubble.content)
#Up to 11
zero = bubble.content[-1]
zero.set_color(self.power_colors[0])
one = OldTex("1").replace(zero, dim_to_match = 1)
one.set_color(zero.get_color())
self.play(Blink(randy))
self.increment(added_anims = [Transform(zero, one)])
self.wait()
#Up to 100
curr_content = bubble.content
bubble.write(
"$1 \\!\\cdot\\! 4 + $",
"$0 \\!\\cdot\\! 2 + $",
"$0$",
)
colors = reversed(self.power_colors[:3])
for piece, color in zip(bubble.content.submobjects, colors):
piece[0].set_color(color)
self.increment(added_anims = [Transform(curr_content, bubble.content)])
four_brace = Brace(self.number_mob[-1])
fours_place = four_brace.get_text("Four's place")
self.play(
Transform(brace, four_brace),
Transform(twos_place, fours_place),
)
self.play(Blink(randy))
self.play(*list(map(FadeOut, [bubble, curr_content])))
#Up to 1000
for x in range(4):
self.increment()
brace.target = Brace(self.number_mob[-1])
twos_place.target = brace.get_text("Eight's place")
self.play(
randy.change_mode, "happy",
randy.look_at, self.number_mob,
*list(map(MoveToTarget, [brace, twos_place]))
)
for x in range(8):
self.increment(total_run_time = 1)
self.wait()
for x in range(8):
self.increment(total_run_time = 1.5)
def show_self_similarity(self):
cover_rect = Rectangle()
cover_rect.set_width(FRAME_WIDTH)
cover_rect.set_height(FRAME_HEIGHT)
cover_rect.set_stroke(width = 0)
cover_rect.set_fill(BLACK, opacity = 0.85)
big_dot = self.curr_configurations[-1][0].copy()
self.play(
FadeIn(cover_rect),
Animation(big_dot)
)
self.play(
big_dot.center,
big_dot.set_height, FRAME_HEIGHT-2,
big_dot.to_edge, LEFT,
run_time = 5
)
class BinaryCountingAtEveryScale(Scene):
CONFIG = {
"num_bits" : 4,
"show_title" : False,
}
def construct(self):
title = OldTexText("Count to %d (which is %s in binary)"%(
2**self.num_bits-1, bin(2**self.num_bits-1)[2:]
))
title.to_edge(UP)
if self.show_title:
self.add(title)
bit_mobs = [
get_binary_tex_mob(n, self.num_bits)
for n in range(2**self.num_bits)
]
curr_bits = bit_mobs[0]
lower_brace = Brace(VGroup(*curr_bits[1:]))
do_a_thing = lower_brace.get_text("Do a thing")
VGroup(lower_brace, do_a_thing).set_color(YELLOW)
upper_brace = Brace(curr_bits, UP)
roll_over = upper_brace.get_text("Roll over")
VGroup(upper_brace, roll_over).set_color(MAROON_B)
again = OldTexText("again")
again.next_to(do_a_thing, RIGHT, 2*SMALL_BUFF)
again.set_color(YELLOW)
self.add(curr_bits, lower_brace, do_a_thing)
def get_run_through(mobs):
return Succession(*[
Transform(
curr_bits, mob,
rate_func = squish_rate_func(smooth, 0, 0.5)
)
for mob in mobs
], run_time = 1)
for bit_mob in bit_mobs:
curr_bits.align_data_and_family(bit_mob)
bit_mob.set_color(YELLOW)
bit_mob[0].set_color(MAROON_B)
self.play(get_run_through(bit_mobs[1:2**(self.num_bits-1)]))
self.play(*list(map(FadeIn, [upper_brace, roll_over])))
self.play(Transform(
VGroup(*reversed(list(curr_bits))),
VGroup(*reversed(list(bit_mobs[2**(self.num_bits-1)]))),
lag_ratio = 0.5,
))
self.wait()
self.play(
get_run_through(bit_mobs[2**(self.num_bits-1)+1:]),
Write(again)
)
self.wait()
class BinaryCountingAtSmallestScale(BinaryCountingAtEveryScale):
CONFIG = {
"num_bits" : 2,
"show_title" : True,
}
class BinaryCountingAtMediumScale(BinaryCountingAtEveryScale):
CONFIG = {
"num_bits" : 4,
"show_title" : True,
}
class BinaryCountingAtLargeScale(BinaryCountingAtEveryScale):
CONFIG = {
"num_bits" : 8,
"show_title" : True,
}
class IntroduceSolveByCounting(TowersOfHanoiScene):
CONFIG = {
"num_disks" : 4
}
def construct(self):
self.initialize_bit_mobs()
for disk in self.disks:
disk.original_fill_color = disk.get_color()
braces = [
Brace(VGroup(*self.curr_bit_mob[:n]))
for n in range(1, self.num_disks+1)
]
word_list = [
brace.get_text(text)
for brace, text in zip(braces, [
"Only flip last bit",
"Roll over once",
"Roll over twice",
"Roll over three times",
])
]
brace = braces[0].copy()
words = word_list[0].copy()
##First increment
self.play(self.get_increment_animation())
self.play(
GrowFromCenter(brace),
Write(words, run_time = 1)
)
disk = self.disks[0]
last_bit = self.curr_bit_mob[0]
last_bit.save_state()
self.play(
disk.set_fill, YELLOW,
disk[1].set_fill, BLACK,
last_bit.set_fill, YELLOW,
)
self.wait()
self.move_disk(0, run_time = 2)
self.play(
last_bit.restore,
disk.set_fill, disk.original_fill_color,
self.disks[0][1].set_fill, BLACK
)
##Second increment
self.play(
self.get_increment_animation(),
Transform(words, word_list[1]),
Transform(brace, braces[1]),
)
disk = self.disks[1]
twos_bit = self.curr_bit_mob[1]
twos_bit.save_state()
self.play(
disk.set_fill, MAROON_B,
disk[1].set_fill, BLACK,
twos_bit.set_fill, MAROON_B,
)
self.move_disk(1, run_time = 2)
self.wait()
self.move_disk_to_peg(1, 1, stay_on_peg = False)
cross = OldTex("\\times")
cross.replace(disk)
cross.set_fill(RED, opacity = 0.5)
self.play(FadeIn(cross))
self.wait()
self.move_disk_to_peg(
1, 2, stay_on_peg = False,
added_anims = [FadeOut(cross)]
)
self.play(
disk.set_fill, disk.original_fill_color,
disk[1].set_fill, BLACK,
twos_bit.restore,
Transform(brace, braces[0]),
Transform(words, word_list[0]),
)
self.move_disk(
0,
added_anims = [self.get_increment_animation()],
run_time = 2
)
self.wait()
##Fourth increment
self.play(
Transform(brace, braces[2]),
Transform(words, word_list[2]),
)
self.play(self.get_increment_animation())
disk = self.disks[2]
fours_bit = self.curr_bit_mob[2]
fours_bit.save_state()
self.play(
disk.set_fill, RED,
disk[1].set_fill, BLACK,
fours_bit.set_fill, RED
)
self.move_disk(2, run_time = 2)
self.play(
disk.set_fill, disk.original_fill_color,
disk[1].set_fill, BLACK,
fours_bit.restore,
FadeOut(brace),
FadeOut(words)
)
self.wait()
for disk_index in 0, 1, 0:
self.play(self.get_increment_animation())
self.move_disk(disk_index)
self.wait()
##Eighth incremement
brace = braces[3]
words = word_list[3]
self.play(
self.get_increment_animation(),
GrowFromCenter(brace),
Write(words, run_time = 1)
)
disk = self.disks[3]
eights_bit = self.curr_bit_mob[3]
eights_bit.save_state()
self.play(
disk.set_fill, GREEN,
disk[1].set_fill, BLACK,
eights_bit.set_fill, GREEN
)
self.move_disk(3, run_time = 2)
self.play(
disk.set_fill, disk.original_fill_color,
disk[1].set_fill, BLACK,
eights_bit.restore,
)
self.play(*list(map(FadeOut, [brace, words])))
for disk_index in get_ruler_sequence(2):
self.play(self.get_increment_animation())
self.move_disk(disk_index, stay_on_peg = False)
self.wait()
def initialize_bit_mobs(self):
bit_mobs = VGroup(*[
get_binary_tex_mob(n, self.num_disks)
for n in range(2**(self.num_disks))
])
bit_mobs.scale(2)
self.bit_mobs_iter = it.cycle(bit_mobs)
self.curr_bit_mob = next(self.bit_mobs_iter)
for bit_mob in bit_mobs:
bit_mob.align_data_and_family(self.curr_bit_mob)
for bit, disk in zip(bit_mob, reversed(list(self.disks))):
bit.set_color(disk.get_color())
bit_mobs.next_to(self.peg_labels, DOWN)
self.add(self.curr_bit_mob)
def get_increment_animation(self):
return Succession(
Transform(
self.curr_bit_mob, next(self.bit_mobs_iter),
lag_ratio = 0.5,
path_arc = -np.pi/3
),
Animation(self.curr_bit_mob)
)
class SolveSixDisksByCounting(IntroduceSolveByCounting):
CONFIG = {
"num_disks" : 6,
"stay_on_peg" : False,
"run_time_per_move" : 0.5,
}
def construct(self):
self.initialize_bit_mobs()
for disk_index in get_ruler_sequence(self.num_disks-1):
self.play(
self.get_increment_animation(),
run_time = self.run_time_per_move,
)
self.move_disk(
disk_index,
stay_on_peg = self.stay_on_peg,
run_time = self.run_time_per_move,
)
self.wait()
class RecursionTime(Scene):
def construct(self):
keith = Keith().shift(2*DOWN+3*LEFT)
morty = Mortimer().shift(2*DOWN+3*RIGHT)
keith.make_eye_contact(morty)
keith_kick = keith.copy().change_mode("dance_kick")
keith_kick.scale(1.3)
keith_kick.shift(0.5*LEFT)
keith_kick.look_at(morty.eyes)
keith_hooray = keith.copy().change_mode("hooray")
self.add(keith, morty)
bubble = keith.get_bubble(SpeechBubble, height = 2)
bubble.write("Recursion time!!!")
VGroup(bubble, bubble.content).shift(UP)
self.play(
Transform(keith, keith_kick),
morty.change_mode, "happy",
ShowCreation(bubble),
Write(bubble.content, run_time = 1)
)
self.play(
morty.change_mode, "hooray",
Transform(keith, keith_hooray),
bubble.content.set_color_by_gradient, BLUE_A, BLUE_E
)
self.play(Blink(morty))
self.wait()
class RecursiveSolution(TowersOfHanoiScene):
CONFIG = {
"num_disks" : 4,
"middle_peg_bottom" : 2*DOWN,
}
def construct(self):
# VGroup(*self.get_mobjects()).shift(1.5*DOWN)
big_disk = self.disks[-1]
self.eyes = Eyes(big_disk)
title = OldTexText("Move 4-tower")
sub_steps = OldTexText(
"Move 3-tower,",
"Move disk 3,",
"Move 3-tower",
)
sub_steps[1].set_color(GREEN)
sub_step_brace = Brace(sub_steps, UP)
sub_sub_steps = OldTexText(
"Move 2-tower,",
"Move disk 2,",
"Move 2-tower",
)
sub_sub_steps[1].set_color(RED)
sub_sub_steps_brace = Brace(sub_sub_steps, UP)
steps = VGroup(
title, sub_step_brace, sub_steps,
sub_sub_steps_brace, sub_sub_steps
)
steps.arrange(DOWN)
steps.scale(0.7)
steps.to_edge(UP)
VGroup(sub_sub_steps_brace, sub_sub_steps).next_to(sub_steps[-1], DOWN)
self.add(title)
##Big disk is frustrated
self.play(
FadeIn(self.eyes),
big_disk.set_fill, GREEN,
big_disk.label.set_fill, BLACK,
)
big_disk.add(self.eyes)
self.blink()
self.wait()
self.change_mode("angry")
for x in range(2):
self.wait()
self.shake(big_disk)
self.blink()
self.wait()
self.change_mode("plain")
self.look_at(self.peg_labels[2])
self.look_at(self.disks[0])
self.blink()
#Subtower move
self.move_subtower_to_peg(3, 1, run_time = 2, added_anims = [
self.eyes.look_at_anim(self.pegs[1]),
FadeIn(sub_step_brace),
Write(sub_steps[0], run_time = 1)
])
self.wait()
self.move_disk_to_peg(0, 0, run_time = 2, added_anims = [
self.eyes.look_at_anim(self.pegs[0].get_top())
])
self.shake(big_disk)
self.move_disk_to_peg(0, 2, run_time = 2, added_anims = [
self.eyes.look_at_anim(self.pegs[2].get_bottom())
])
self.change_mode("angry")
self.move_disk_to_peg(0, 1, run_time = 2, added_anims = [
self.eyes.look_at_anim(self.disks[1].get_top())
])
self.blink()
#Final moves for big case
self.move_disk(3, run_time = 2, added_anims = [
Write(sub_steps[1])
])
self.look_at(self.disks[1])
self.blink()
bubble = SpeechBubble()
bubble.write("I'm set!")
bubble.resize_to_content()
bubble.pin_to(big_disk)
bubble.add_content(bubble.content)
bubble.set_fill(BLACK, opacity = 0.7)
self.play(
ShowCreation(bubble),
Write(bubble.content)
)
self.wait()
self.blink()
self.play(*list(map(FadeOut, [bubble, bubble.content])))
big_disk.remove(self.eyes)
self.move_subtower_to_peg(3, 2, run_time = 2, added_anims = [
self.eyes.look_at_anim(self.pegs[2].get_top()),
Write(sub_steps[2])
])
self.play(FadeOut(self.eyes))
self.wait()
#Highlight subproblem
self.play(
VGroup(*self.disks[:3]).move_to, self.pegs[1], DOWN
)
self.disk_tracker = [set([]), set([0, 1, 2]), set([3])]
arc = Arc(-5*np.pi/6, start_angle = 5*np.pi/6)
arc.add_tip()
arc.set_color(YELLOW)
arc.set_width(
VGroup(*self.pegs[1:]).get_width()*0.8
)
arc.next_to(self.disks[0], UP+RIGHT, buff = SMALL_BUFF)
q_mark = OldTexText("?")
q_mark.next_to(arc, UP)
self.play(
ShowCreation(arc),
Write(q_mark),
sub_steps[-1].set_color, YELLOW
)
self.wait()
self.play(
GrowFromCenter(sub_sub_steps_brace),
*list(map(FadeOut, [arc, q_mark]))
)
#Disk 2 frustration
big_disk = self.disks[2]
self.eyes.move_to(big_disk.get_top(), DOWN)
self.play(
FadeIn(self.eyes),
big_disk.set_fill, RED,
big_disk.label.set_fill, BLACK
)
big_disk.add(self.eyes)
self.change_mode("sad")
self.look_at(self.pegs[1].get_top())
self.shake(big_disk)
self.blink()
#Move sub-sub-tower
self.move_subtower_to_peg(2, 0, run_time = 2, added_anims = [
self.eyes.look_at_anim(self.pegs[0].get_bottom()),
Write(sub_sub_steps[0])
])
self.blink()
self.move_disk_to_peg(2, 2, run_time = 2, added_anims = [
Write(sub_sub_steps[1])
])
self.look_at(self.disks[0])
big_disk.remove(self.eyes)
self.move_subtower_to_peg(2, 2, run_time = 2, added_anims = [
self.eyes.look_at_anim(self.pegs[2].get_top()),
Write(sub_sub_steps[2])
])
self.blink()
self.look_at(self.disks[-1])
#Move eyes
self.play(FadeOut(self.eyes))
self.eyes.move_to(self.disks[1].get_top(), DOWN)
self.play(FadeIn(self.eyes))
self.blink()
self.play(FadeOut(self.eyes))
self.eyes.move_to(self.disks[3].get_top(), DOWN)
self.play(FadeIn(self.eyes))
#Show process one last time
big_disk = self.disks[3]
big_disk.add(self.eyes)
self.move_subtower_to_peg(3, 1, run_time = 2, added_anims = [
self.eyes.look_at_anim(self.pegs[0])
])
self.move_disk_to_peg(3, 0, run_time = 2)
big_disk.remove(self.eyes)
self.move_subtower_to_peg(3, 0, run_time = 2, added_anims = [
self.eyes.look_at_anim(self.pegs[0].get_top())
])
self.blink()
def shake(self, mobject, direction = UP, added_anims = []):
self.play(
mobject.shift, 0.2*direction, rate_func = wiggle,
*added_anims
)
def blink(self):
self.play(self.eyes.blink_anim())
def look_at(self, point_or_mobject):
self.play(self.eyes.look_at_anim(point_or_mobject))
def change_mode(self, mode):
self.play(self.eyes.change_mode_anim(mode))
class KeithSaysBigToSmall(Scene):
def construct(self):
keith = Keith()
keith.shift(2.5*DOWN + 3*LEFT)
bubble = keith.get_bubble(SpeechBubble, height = 4.5)
bubble.write("""
Big problem
$\\Downarrow$
Smaller problem
""")
self.add(keith)
self.play(Blink(keith))
self.play(
keith.change_mode, "speaking",
ShowCreation(bubble),
Write(bubble.content)
)
self.wait()
self.play(Blink(keith))
self.wait()
class CodeThisUp(Scene):
def construct(self):
keith = Keith()
keith.shift(2*DOWN+3*LEFT)
morty = Mortimer()
morty.shift(2*DOWN+3*RIGHT)
keith.make_eye_contact(morty)
point = 2*UP+3*RIGHT
bubble = keith.get_bubble(SpeechBubble, width = 4.5, height = 3)
bubble.write("This is the \\\\ most efficient")
self.add(morty, keith)
self.play(
keith.change_mode, "speaking",
keith.look_at, point
)
self.play(
morty.change_mode, "pondering",
morty.look_at, point
)
self.play(Blink(keith))
self.wait(2)
self.play(Blink(morty))
self.wait()
self.play(
keith.change_mode, "hooray",
keith.look_at, morty.eyes
)
self.play(Blink(keith))
self.wait()
self.play(
keith.change_mode, "speaking",
keith.look_at, morty.eyes,
ShowCreation(bubble),
Write(bubble.content),
morty.change_mode, "happy",
morty.look_at, keith.eyes,
)
self.wait()
self.play(Blink(morty))
self.wait()
class HanoiSolutionCode(Scene):
def construct(self):
pass
class NoRoomForInefficiency(Scene):
def construct(self):
morty = Mortimer().flip()
morty.shift(2.5*DOWN+3*LEFT)
bubble = morty.get_bubble(SpeechBubble, width = 4)
bubble.write("No room for \\\\ inefficiency")
VGroup(morty, bubble, bubble.content).to_corner(DOWN+RIGHT)
self.add(morty)
self.play(
morty.change_mode, "speaking",
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(morty))
self.wait()
class WhyDoesBinaryAchieveThis(Scene):
def construct(self):
keith = Keith()
keith.shift(2*DOWN+3*LEFT)
morty = Mortimer()
morty.shift(2*DOWN+3*RIGHT)
keith.make_eye_contact(morty)
bubble = morty.get_bubble(SpeechBubble, width = 5, height = 3)
bubble.write("""
Why does counting
in binary work?
""")
self.add(morty, keith)
self.play(
morty.change_mode, "confused",
morty.look_at, keith.eyes,
ShowCreation(bubble),
Write(bubble.content)
)
self.play(keith.change_mode, "happy")
self.wait()
self.play(Blink(morty))
self.wait()
class BothAreSelfSimilar(Scene):
def construct(self):
morty = Mortimer().flip()
morty.shift(2.5*DOWN+3*LEFT)
bubble = morty.get_bubble(SpeechBubble)
bubble.write("Both are self-similar")
self.add(morty)
self.play(
morty.change_mode, "hooray",
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(morty))
self.wait()
class LargeScaleHanoiDecomposition(TowersOfHanoiScene):
CONFIG = {
"num_disks" : 8,
"peg_height" : 3.5,
"middle_peg_bottom" : 2*DOWN,
"disk_max_width" : 4,
}
def construct(self):
self.move_subtower_to_peg(7, 1, stay_on_peg = False)
self.wait()
self.move_disk(7, stay_on_peg = False)
self.wait()
self.move_subtower_to_peg(7, 2, stay_on_peg = False)
self.wait()
class SolveTwoDisksByCounting(SolveSixDisksByCounting):
CONFIG = {
"num_disks" : 2,
"stay_on_peg" : False,
"run_time_per_move" : 1,
"disk_max_width" : 1.5,
}
def construct(self):
self.initialize_bit_mobs()
for disk_index in 0, 1, 0:
self.play(self.get_increment_animation())
self.move_disk(
disk_index,
stay_on_peg = False,
)
self.wait()
class ShowFourDiskFourBitsParallel(IntroduceSolveByCounting):
CONFIG = {
"num_disks" : 4,
"subtask_run_time" : 1,
}
def construct(self):
self.initialize_bit_mobs()
self.counting_subtask()
self.wait()
self.disk_subtask()
self.wait()
self.play(self.get_increment_animation())
self.move_disk(
self.num_disks-1,
stay_on_peg = False,
)
self.wait()
self.counting_subtask()
self.wait()
self.disk_subtask()
self.wait()
def disk_subtask(self):
sequence = get_ruler_sequence(self.num_disks-2)
run_time = float(self.subtask_run_time)/len(sequence)
for disk_index in get_ruler_sequence(self.num_disks-2):
self.move_disk(
disk_index,
run_time = run_time,
stay_on_peg = False,
)
# curr_peg = self.disk_index_to_peg_index(0)
# self.move_subtower_to_peg(self.num_disks-1, curr_peg+1)
def counting_subtask(self):
num_tasks = 2**(self.num_disks-1)-1
run_time = float(self.subtask_run_time)/num_tasks
# for x in range(num_tasks):
# self.play(
# self.get_increment_animation(),
# run_time = run_time
# )
self.play(
Succession(*[
self.get_increment_animation()
for x in range(num_tasks)
]),
rate_func=linear,
run_time = self.subtask_run_time
)
def get_increment_animation(self):
return Transform(
self.curr_bit_mob, next(self.bit_mobs_iter),
path_arc = -np.pi/3,
)
class ShowThreeDiskThreeBitsParallel(ShowFourDiskFourBitsParallel):
CONFIG = {
"num_disks" : 3,
"subtask_run_time" : 1
}
class ShowFiveDiskFiveBitsParallel(ShowFourDiskFourBitsParallel):
CONFIG = {
"num_disks" : 5,
"subtask_run_time" : 2
}
class ShowSixDiskSixBitsParallel(ShowFourDiskFourBitsParallel):
CONFIG = {
"num_disks" : 6,
"subtask_run_time" : 2
}
class CoolRight(Scene):
def construct(self):
morty = Mortimer()
morty.shift(2*DOWN)
bubble = SpeechBubble()
bubble.write("Cool! right?")
bubble.resize_to_content()
bubble.pin_to(morty)
self.play(
morty.change_mode, "surprised",
morty.look, OUT,
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(morty))
self.wait()
curr_content = bubble.content
bubble.write("It gets \\\\ better...")
self.play(
Transform(curr_content, bubble.content),
morty.change_mode, "hooray",
morty.look, OUT
)
self.wait()
self.play(Blink(morty))
self.wait()
############ Part 2 ############
class MentionLastVideo(Scene):
def construct(self):
keith = Keith()
keith.shift(2*DOWN+3*LEFT)
morty = Mortimer()
morty.shift(2*DOWN+3*RIGHT)
keith.make_eye_contact(morty)
point = 2*UP
name = OldTexText("""
Keith Schwarz
(Computer Scientist)
""")
name.to_corner(UP+LEFT)
arrow = Arrow(name.get_bottom(), keith.get_top())
self.add(morty, keith)
self.play(
keith.change_mode, "raise_right_hand",
keith.look_at, point,
morty.change_mode, "pondering",
morty.look_at, point
)
self.play(Blink(keith))
self.play(Write(name))
self.play(ShowCreation(arrow))
self.play(Blink(morty))
self.wait(2)
self.play(
morty.change_mode, "confused",
morty.look_at, point
)
self.play(Blink(keith))
self.wait(2)
self.play(
morty.change_mode, "surprised"
)
self.wait()
class IntroduceConstrainedTowersOfHanoi(ConstrainedTowersOfHanoiScene):
CONFIG = {
"middle_peg_bottom" : 2*DOWN,
}
def construct(self):
title = OldTexText("Constrained", "Towers of Hanoi")
title.set_color_by_tex("Constrained", YELLOW)
title.to_edge(UP)
self.play(Write(title))
self.add_arcs()
self.disks.save_state()
for index in 0, 0, 1, 0:
self.move_disk(index)
self.wait()
self.wait()
self.play(self.disks.restore)
self.disk_tracker = [set(range(self.num_disks)), set([]), set([])]
self.wait()
self.move_disk_to_peg(0, 1)
self.move_disk_to_peg(1, 2)
self.play(ShowCreation(self.big_curved_arrow))
cross = OldTex("\\times")
cross.scale(2)
cross.set_fill(RED)
cross.move_to(self.big_curved_arrow.get_top())
big_cross = cross.copy()
big_cross.replace(self.disks[1])
big_cross.set_fill(opacity = 0.5)
self.play(FadeIn(cross))
self.play(FadeIn(big_cross))
self.wait()
def add_arcs(self):
arc = Arc(start_angle = np.pi/6, angle = 2*np.pi/3)
curved_arrow1 = VGroup(arc, arc.copy().flip())
curved_arrow2 = curved_arrow1.copy()
curved_arrows = [curved_arrow1, curved_arrow2]
for curved_arrow in curved_arrows:
for arc in curved_arrow:
arc.add_tip(tip_length = 0.15)
arc.set_color(YELLOW)
peg_sets = (self.pegs[:2], self.pegs[1:])
for curved_arrow, pegs in zip(curved_arrows, peg_sets):
peg_group = VGroup(*pegs)
curved_arrow.set_width(0.7*peg_group.get_width())
curved_arrow.next_to(peg_group, UP)
self.play(ShowCreation(curved_arrow1))
self.play(ShowCreation(curved_arrow2))
self.wait()
big_curved_arrow = Arc(start_angle = 5*np.pi/6, angle = -2*np.pi/3)
big_curved_arrow.set_width(0.9*self.pegs.get_width())
big_curved_arrow.next_to(self.pegs, UP)
big_curved_arrow.add_tip(tip_length = 0.4)
big_curved_arrow.set_color(WHITE)
self.big_curved_arrow = big_curved_arrow
class StillRecruse(Scene):
def construct(self):
keith = Keith()
keith.shift(2*DOWN+3*LEFT)
morty = Mortimer()
morty.shift(2*DOWN+3*RIGHT)
keith.make_eye_contact(morty)
point = 2*UP+3*RIGHT
bubble = keith.get_bubble(SpeechBubble, width = 4.5, height = 3)
bubble.write("You can still\\\\ use recursion")
self.add(morty, keith)
self.play(
keith.change_mode, "speaking",
ShowCreation(bubble),
Write(bubble.content)
)
self.play(morty.change_mode, "hooray")
self.play(Blink(keith))
self.wait()
self.play(Blink(morty))
self.wait()
class RecursiveSolutionToConstrained(RecursiveSolution):
CONFIG = {
"middle_peg_bottom" : 2*DOWN,
"num_disks" : 4,
}
def construct(self):
big_disk = self.disks[-1]
self.eyes = Eyes(big_disk)
#Define steps breakdown text
title = OldTexText("Move 4-tower")
subdivisions = [
OldTexText(
"\\tiny Move %d-tower,"%d,
"Move disk %d,"%d,
"\\, Move %d-tower, \\,"%d,
"Move disk %d,"%d,
"Move %d-tower"%d,
).set_color_by_tex("Move disk %d,"%d, color)
for d, color in [(3, GREEN), (2, RED), (1, BLUE_C)]
]
sub_steps, sub_sub_steps = subdivisions[:2]
for steps in subdivisions:
steps.set_width(FRAME_WIDTH-1)
subdivisions.append(
OldTexText("\\tiny Move disk 0, Move disk 0").set_color(BLUE)
)
braces = [
Brace(steps, UP)
for steps in subdivisions
]
sub_steps_brace, sub_sub_steps_brace = braces[:2]
steps = VGroup(title, *it.chain(*list(zip(
braces, subdivisions
))))
steps.arrange(DOWN)
steps.to_edge(UP)
steps_to_fade = VGroup(
title, sub_steps_brace,
*list(sub_steps[:2]) + list(sub_steps[3:])
)
self.add(title)
#Initially move big disk
self.play(
FadeIn(self.eyes),
big_disk.set_fill, GREEN,
big_disk.label.set_fill, BLACK
)
big_disk.add(self.eyes)
big_disk.save_state()
self.blink()
self.look_at(self.pegs[2])
self.move_disk_to_peg(self.num_disks-1, 2, stay_on_peg = False)
self.look_at(self.pegs[0])
self.blink()
self.play(big_disk.restore, path_arc = np.pi/3)
self.disk_tracker = [set(range(self.num_disks)), set([]), set([])]
self.look_at(self.pegs[0].get_top())
self.change_mode("angry")
self.shake(big_disk)
self.wait()
#Talk about tower blocking
tower = VGroup(*self.disks[:self.num_disks-1])
blocking = OldTexText("Still\\\\", "Blocking")
blocking.set_color(RED)
blocking.to_edge(LEFT)
blocking.shift(2*UP)
arrow = Arrow(blocking.get_bottom(), tower.get_top(), buff = SMALL_BUFF)
new_arrow = Arrow(blocking.get_bottom(), self.pegs[1], buff = SMALL_BUFF)
VGroup(arrow, new_arrow).set_color(RED)
self.play(
Write(blocking[1]),
ShowCreation(arrow)
)
self.shake(tower, RIGHT, added_anims = [Animation(big_disk)])
self.blink()
self.shake(big_disk)
self.wait()
self.move_subtower_to_peg(self.num_disks-1, 1, added_anims = [
Transform(arrow, new_arrow),
self.eyes.look_at_anim(self.pegs[1])
])
self.play(Write(blocking[0]))
self.shake(big_disk, RIGHT)
self.wait()
self.blink()
self.wait()
self.play(FadeIn(sub_steps_brace))
self.move_subtower_to_peg(self.num_disks-1, 2, added_anims = [
FadeOut(blocking),
FadeOut(arrow),
self.eyes.change_mode_anim("plain", thing_to_look_at = self.pegs[2]),
Write(sub_steps[0], run_time = 1),
])
self.blink()
#Proceed through actual process
self.move_disk_to_peg(self.num_disks-1, 1, added_anims = [
Write(sub_steps[1], run_time = 1),
])
self.wait()
self.move_subtower_to_peg(self.num_disks-1, 0, added_anims = [
self.eyes.look_at_anim(self.pegs[0]),
Write(sub_steps[2], run_time = 1),
])
self.blink()
self.move_disk_to_peg(self.num_disks-1, 2, added_anims = [
Write(sub_steps[3], run_time = 1),
])
self.wait()
big_disk.remove(self.eyes)
self.move_subtower_to_peg(self.num_disks-1, 2, added_anims = [
self.eyes.look_at_anim(self.pegs[2].get_top()),
Write(sub_steps[4], run_time = 1),
])
self.blink()
self.play(FadeOut(self.eyes))
#Ask about subproblem
sub_sub_steps_brace.set_color(WHITE)
self.move_subtower_to_peg(self.num_disks-1, 0, added_anims = [
steps_to_fade.fade, 0.7,
sub_steps[2].set_color, WHITE,
sub_steps[2].scale, 1.2,
FadeIn(sub_sub_steps_brace)
])
num_disks = self.num_disks-1
big_disk = self.disks[num_disks-1]
self.eyes.move_to(big_disk.get_top(), DOWN)
self.play(
FadeIn(self.eyes),
big_disk.set_fill, RED,
big_disk.label.set_fill, BLACK,
)
big_disk.add(self.eyes)
self.blink()
#Solve subproblem
self.move_subtower_to_peg(num_disks-1, 2, added_anims = [
self.eyes.look_at_anim(self.pegs[2]),
Write(sub_sub_steps[0], run_time = 1)
])
self.blink()
self.move_disk_to_peg(num_disks-1, 1, added_anims = [
Write(sub_sub_steps[1], run_time = 1)
])
self.wait()
self.move_subtower_to_peg(num_disks-1, 0, added_anims = [
self.eyes.look_at_anim(self.pegs[0]),
Write(sub_sub_steps[2], run_time = 1)
])
self.blink()
self.move_disk_to_peg(num_disks-1, 2, added_anims = [
Write(sub_sub_steps[3], run_time = 1)
])
self.wait()
big_disk.remove(self.eyes)
self.move_subtower_to_peg(num_disks-1, 2, added_anims = [
self.eyes.look_at_anim(self.pegs[2].get_top()),
Write(sub_sub_steps[4], run_time = 1)
])
self.wait()
#Show smallest subdivisions
smaller_subdivision = VGroup(
*list(subdivisions[2:]) + \
list(braces[2:])
)
last_subdivisions = [VGroup(braces[-1], subdivisions[-1])]
for vect in LEFT, RIGHT:
group = last_subdivisions[0].copy()
group.to_edge(vect)
steps.add(group)
smaller_subdivision.add(group)
last_subdivisions.append(group)
smaller_subdivision.set_fill(opacity = 0)
self.play(
steps.shift,
(FRAME_Y_RADIUS-sub_sub_steps.get_top()[1]-MED_SMALL_BUFF)*UP,
self.eyes.look_at_anim(steps)
)
self.play(ApplyMethod(
VGroup(VGroup(braces[-2], subdivisions[-2])).set_fill, None, 1,
run_time = 3,
lag_ratio = 0.5,
))
self.blink()
for mob in last_subdivisions:
self.play(
ApplyMethod(mob.set_fill, None, 1),
self.eyes.look_at_anim(mob)
)
self.blink()
self.play(FadeOut(self.eyes))
self.wait()
#final movements
movements = [
(0, 1),
(0, 0),
(1, 1),
(0, 1),
(0, 2),
(1, 0),
(0, 1),
(0, 0),
]
for disk_index, peg_index in movements:
self.move_disk_to_peg(
disk_index, peg_index,
stay_on_peg = False
)
self.wait()
class SimpleConstrainedBreakdown(TowersOfHanoiScene):
CONFIG = {
"num_disks" : 4
}
def construct(self):
self.move_subtower_to_peg(self.num_disks-1, 2)
self.wait()
self.move_disk(self.num_disks-1)
self.wait()
self.move_subtower_to_peg(self.num_disks-1, 0)
self.wait()
self.move_disk(self.num_disks-1)
self.wait()
self.move_subtower_to_peg(self.num_disks-1, 2)
self.wait()
class SolveConstrainedByCounting(ConstrainedTowersOfHanoiScene):
CONFIG = {
"num_disks" : 5,
"ternary_mob_scale_factor" : 2,
}
def construct(self):
ternary_mobs = VGroup()
for num in range(3**self.num_disks):
ternary_mob = get_ternary_tex_mob(num, self.num_disks)
ternary_mob.scale(self.ternary_mob_scale_factor)
ternary_mob.set_color_by_gradient(*self.disk_start_and_end_colors)
ternary_mobs.add(ternary_mob)
ternary_mobs.next_to(self.peg_labels, DOWN)
self.ternary_mob_iter = it.cycle(ternary_mobs)
self.curr_ternary_mob = next(self.ternary_mob_iter)
self.add(self.curr_ternary_mob)
for index in get_ternary_ruler_sequence(self.num_disks-1):
self.move_disk(index, stay_on_peg = False, added_anims = [
self.increment_animation()
])
def increment_animation(self):
return Succession(
Transform(
self.curr_ternary_mob, next(self.ternary_mob_iter),
lag_ratio = 0.5,
path_arc = np.pi/6,
),
Animation(self.curr_ternary_mob),
)
class CompareNumberSystems(Scene):
def construct(self):
base_ten = OldTexText("Base ten")
base_ten.to_corner(UP+LEFT).shift(RIGHT)
binary = OldTexText("Binary")
binary.to_corner(UP+RIGHT).shift(LEFT)
ternary = OldTexText("Ternary")
ternary.to_edge(UP)
ternary.set_color(YELLOW)
titles = [base_ten, binary, ternary]
zero_to_nine = OldTexText("""
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
""")
zero_to_nine.next_to(base_ten, DOWN, buff = LARGE_BUFF)
zero_one = OldTexText("0, 1")
zero_one.next_to(binary, DOWN, buff = LARGE_BUFF)
zero_one_two = OldTexText("0, 1, 2")
zero_one_two.next_to(ternary, DOWN, buff = LARGE_BUFF)
zero_one_two.set_color_by_gradient(BLUE, GREEN)
symbols = [zero_to_nine, zero_one, zero_one_two]
names = ["Digits", "Bits", "Trits?"]
for mob, text in zip(symbols, names):
mob.brace = Brace(mob)
mob.name = mob.brace.get_text(text)
zero_one_two.name.set_color_by_gradient(BLUE, GREEN)
dots = OldTex("\\dots")
dots.next_to(zero_one.name, RIGHT, aligned_edge = DOWN, buff = SMALL_BUFF)
keith = Keith()
keith.shift(2*DOWN+3*LEFT)
keith.look_at(zero_one_two)
morty = Mortimer()
morty.shift(2*DOWN+3*RIGHT)
for title, symbol in zip(titles, symbols):
self.play(FadeIn(title))
added_anims = []
if title is not ternary:
added_anims += [
FadeIn(symbol.brace),
FadeIn(symbol.name)
]
self.play(Write(symbol, run_time = 2), *added_anims)
self.wait()
self.play(FadeIn(keith))
self.play(keith.change_mode, "confused")
self.play(keith.look_at, zero_to_nine)
self.play(keith.look_at, zero_one)
self.play(
GrowFromCenter(zero_one_two.brace),
Write(zero_one_two.name),
keith.look_at, zero_one_two,
)
self.play(keith.change_mode, "sassy")
self.play(Blink(keith))
self.play(FadeIn(morty))
self.play(
morty.change_mode, "sassy",
morty.look_at, zero_one_two
)
self.play(Blink(morty))
self.wait()
self.play(
morty.shrug,
morty.look_at, keith.eyes,
keith.shrug,
keith.look_at, morty.eyes
)
self.wait()
self.play(
morty.change_mode, "hesitant",
morty.look_at, zero_one.name,
keith.change_mode, "erm",
keith.look_at, zero_one.name
)
self.play(Blink(morty))
self.play(Write(dots, run_time = 3))
self.wait()
class IntroduceTernaryCounting(CountingScene):
CONFIG = {
"base" : 3,
"counting_dot_starting_position" : (FRAME_X_RADIUS-1)*RIGHT + (FRAME_Y_RADIUS-1)*UP,
"count_dot_starting_radius" : 0.5,
"dot_configuration_height" : 1,
"ones_configuration_location" : UP+2*RIGHT,
"num_scale_factor" : 2,
"num_start_location" : DOWN+RIGHT,
}
def construct(self):
for x in range(2):
self.increment()
self.wait()
self.increment()
brace = Brace(self.number_mob[-1])
threes_place = brace.get_text("Three's place")
self.play(
GrowFromCenter(brace),
Write(threes_place)
)
self.wait()
for x in range(6):
self.increment()
self.wait()
new_brace = Brace(self.number_mob[-1])
nines_place = new_brace.get_text("Nine's place")
self.play(
Transform(brace, new_brace),
Transform(threes_place, nines_place),
)
self.wait()
for x in range(9):
self.increment()
class TernaryCountingSelfSimilarPattern(Scene):
CONFIG = {
"num_trits" : 3,
"colors" : CountingScene.CONFIG["power_colors"][:3],
}
def construct(self):
colors = self.colors
title = OldTexText("Count to " + "2"*self.num_trits)
for i, color in enumerate(colors):
title[-i-1].set_color(color)
steps = VGroup(*list(map(TexText, [
"Count to %s,"%("2"*(self.num_trits-1)),
"Roll over,",
"Count to %s,"%("2"*(self.num_trits-1)),
"Roll over,",
"Count to %s,"%("2"*(self.num_trits-1)),
])))
steps.arrange(RIGHT)
for step in steps[::2]:
for i, color in enumerate(colors[:-1]):
step[-i-2].set_color(color)
VGroup(*steps[1::2]).set_color(colors[-1])
steps.set_width(FRAME_WIDTH-1)
brace = Brace(steps, UP)
word_group = VGroup(title, brace, steps)
word_group.arrange(DOWN)
word_group.to_edge(UP)
ternary_mobs = VGroup(*[
get_ternary_tex_mob(n, n_trits = self.num_trits)
for n in range(3**self.num_trits)
])
ternary_mobs.scale(2)
ternary_mob_iter = it.cycle(ternary_mobs)
curr_ternary_mob = next(ternary_mob_iter)
for trits in ternary_mobs:
trits.align_data_and_family(curr_ternary_mob)
for trit, color in zip(trits, colors):
trit.set_color(color)
def get_increment():
return Transform(
curr_ternary_mob, next(ternary_mob_iter),
lag_ratio = 0.5,
path_arc = -np.pi/3
)
self.add(curr_ternary_mob, title)
self.play(GrowFromCenter(brace))
for i, step in enumerate(steps):
self.play(Write(step, run_time = 1))
if i%2 == 0:
self.play(
Succession(*[
get_increment()
for x in range(3**(self.num_trits-1)-1)
]),
run_time = 1
)
else:
self.play(get_increment())
self.wait()
class TernaryCountingSelfSimilarPatternFiveTrits(TernaryCountingSelfSimilarPattern):
CONFIG = {
"num_trits" : 5,
"colors" : color_gradient([YELLOW, PINK, RED], 5),
}
class CountInTernary(IntroduceTernaryCounting):
def construct(self):
for x in range(9):
self.increment()
self.wait()
class SolveConstrainedWithTernaryCounting(ConstrainedTowersOfHanoiScene):
CONFIG = {
"num_disks" : 4,
}
def construct(self):
for x in range(3**self.num_disks-1):
self.increment(run_time = 0.75)
self.wait()
def setup(self):
ConstrainedTowersOfHanoiScene.setup(self)
ternary_mobs = VGroup(*[
get_ternary_tex_mob(x)
for x in range(3**self.num_disks)
])
ternary_mobs.scale(2)
ternary_mobs.next_to(self.peg_labels, DOWN)
for trits in ternary_mobs:
trits.align_data_and_family(ternary_mobs[0])
trits.set_color_by_gradient(*self.disk_start_and_end_colors)
self.ternary_mob_iter = it.cycle(ternary_mobs)
self.curr_ternary_mob = self.ternary_mob_iter.next().copy()
self.disk_index_iter = it.cycle(
get_ternary_ruler_sequence(self.num_disks-1)
)
self.ternary_mobs = ternary_mobs
def increment(self, run_time = 1, stay_on_peg = False):
self.increment_number(run_time)
self.move_next_disk(run_time, stay_on_peg)
def increment_number(self, run_time = 1):
self.play(Transform(
self.curr_ternary_mob, next(self.ternary_mob_iter),
path_arc = -np.pi/3,
lag_ratio = 0.5,
run_time = run_time,
))
def move_next_disk(self, run_time = None, stay_on_peg = False):
self.move_disk(
next(self.disk_index_iter),
run_time = run_time,
stay_on_peg = stay_on_peg
)
class DescribeSolutionByCountingToConstrained(SolveConstrainedWithTernaryCounting):
def construct(self):
braces = [
Brace(VGroup(*self.curr_ternary_mob[:n+1]))
for n in range(self.num_disks)
]
words = [
brace.get_text(text)
for brace, text in zip(braces, [
"Only flip last trit",
"Roll over once",
"Roll over twice",
"Roll over three times",
])
]
#Count 1, 2
color = YELLOW
brace = braces[0]
word = words[0]
words[0].set_color(color)
self.increment_number()
self.play(
FadeIn(brace),
Write(word, run_time = 1),
self.curr_ternary_mob[0].set_color, color
)
self.wait()
self.play(
self.disks[0].set_fill, color,
self.disks[0].label.set_fill, BLACK,
)
self.move_next_disk(stay_on_peg = True)
self.wait()
self.ternary_mobs[2][0].set_color(color)
self.increment_number()
self.move_next_disk(stay_on_peg = True)
self.wait()
#Count 10
color = MAROON_B
words[1].set_color(color)
self.increment_number()
self.play(
Transform(brace, braces[1]),
Transform(word, words[1]),
self.curr_ternary_mob[1].set_color, color
)
self.wait()
self.play(
self.disks[1].set_fill, color,
self.disks[1].label.set_fill, BLACK,
)
self.move_next_disk(stay_on_peg = True)
self.wait()
self.play(*list(map(FadeOut, [brace, word])))
#Count up to 22
for x in range(5):
self.increment()
self.wait()
#Count to 100
color = RED
words[2].set_color(color)
self.wait()
self.increment_number()
self.play(
FadeIn(braces[2]),
Write(words[2], run_time = 1),
self.curr_ternary_mob[2].set_fill, color,
self.disks[2].set_fill, color,
self.disks[2].label.set_fill, BLACK,
)
self.wait()
self.move_next_disk(stay_on_peg = True)
self.wait()
self.play(*list(map(FadeOut, [braces[2], words[2]])))
for x in range(20):
self.increment()
class Describe2222(Scene):
def construct(self):
ternary_mob = OldTex("2222").scale(1.5)
brace = Brace(ternary_mob)
description = brace.get_text("$3^4 - 1 = 80$")
VGroup(ternary_mob, brace, description).scale(1.5)
self.add(ternary_mob)
self.wait()
self.play(GrowFromCenter(brace))
self.play(Write(description))
self.wait()
class KeithAsksAboutConfigurations(Scene):
def construct(self):
keith = Keith().shift(2*DOWN+3*LEFT)
morty = Mortimer().shift(2*DOWN+3*RIGHT)
keith.make_eye_contact(morty)
bubble = keith.get_bubble(SpeechBubble)
bubble.write("Think about how many \\\\ configurations there are.")
self.add(keith, morty)
self.play(Blink(keith))
self.play(
keith.change_mode, "speaking",
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(morty))
self.play(morty.change_mode, "pondering")
self.wait()
class AskAboutConfigurations(SolveConstrainedWithTernaryCounting):
def construct(self):
question = OldTexText("How many configurations?")
question.scale(1.5)
question.to_edge(UP)
self.add(question)
for x in range(15):
self.remove(self.curr_ternary_mob)
self.wait(2)
for y in range(7):
self.increment(run_time = 0)
class AnswerConfigurationsCount(TowersOfHanoiScene):
CONFIG = {
"middle_peg_bottom" : 2.5*DOWN,
"num_disks" : 4,
"peg_height" : 1.5,
}
def construct(self):
answer = OldTexText("$3^4 = 81$ configurations")
answer.to_edge(UP)
self.add(answer)
parentheticals = self.get_parentheticals(answer)
self.prepare_disks()
for parens, disk in zip(parentheticals, reversed(list(self.disks))):
VGroup(parens, parens.brace, parens.three).set_color(disk.get_color())
self.play(
Write(parens, run_time = 1),
FadeIn(disk)
)
self.play(
ApplyMethod(
disk.next_to, self.pegs[2], UP,
run_time = 2
),
GrowFromCenter(parens.brace),
Write(parens.three, run_time = 1)
)
x_diff = disk.saved_state.get_center()[0]-disk.get_center()[0]
self.play(
disk.shift, x_diff*RIGHT
)
self.play(disk.restore)
self.wait()
def get_parentheticals(self, top_mob):
parentheticals = VGroup(*reversed([
OldTex("""
\\left(
\\begin{array}{c}
\\text{Choices for} \\\\
\\text{disk %d}
\\end{array}
\\right)
"""%d)
for d in range(self.num_disks)
]))
parentheticals.arrange()
parentheticals.set_width(FRAME_WIDTH-1)
parentheticals.next_to(top_mob, DOWN)
for parens in parentheticals:
brace = Brace(parens)
three = brace.get_text("$3$")
parens.brace = brace
parens.three = three
return parentheticals
def prepare_disks(self):
configuration = [1, 2, 1, 0]
for n, peg_index in enumerate(configuration):
disk_index = self.num_disks-n-1
disk = self.disks[disk_index]
top = Circle(radius = disk.get_width()/2)
inner = Circle(radius = self.peg_width/2)
inner.flip()
top.add_subpath(inner.points)
top.set_stroke(width = 0)
top.set_fill(disk.get_color())
top.rotate(np.pi/2, RIGHT)
top.move_to(disk, UP)
bottom = top.copy()
bottom.move_to(disk, DOWN)
disk.remove(disk.label)
disk.add(top, bottom, disk.label)
self.move_disk_to_peg(disk_index, peg_index, run_time = 0)
if disk_index == 0:
disk.move_to(self.pegs[peg_index].get_bottom(), DOWN)
for disk in self.disks:
disk.save_state()
disk.rotate(np.pi/30, RIGHT)
disk.next_to(self.pegs[0], UP)
self.remove(self.disks)
class ThisIsMostEfficientText(Scene):
def construct(self):
text = OldTexText("This is the most efficient solution")
text.set_width(FRAME_WIDTH - 1)
text.to_edge(DOWN)
self.play(Write(text))
self.wait(2)
class RepeatingConfiguraiton(Scene):
def construct(self):
dots = VGroup(*[Dot() for x in range(10)])
arrows = VGroup(*[Arrow(LEFT, RIGHT) for x in range(9)])
arrows.add(VGroup())
arrows.scale(0.5)
group = VGroup(*it.chain(*list(zip(dots, arrows))))
group.arrange()
title = OldTexText("Same state twice")
title.shift(3*UP)
special_dots = VGroup(dots[2], dots[6])
special_arrows = VGroup(*[
Arrow(title.get_bottom(), dot, color = RED)
for dot in special_dots
])
mid_mobs = VGroup(*group[5:14])
mid_arrow = Arrow(dots[2], dots[7], tip_length = 0.125)
more_efficient = OldTexText("More efficient")
more_efficient.next_to(mid_arrow, UP)
self.play(ShowCreation(group, run_time = 2))
self.play(Write(title))
self.play(
ShowCreation(special_arrows),
special_dots.set_color, RED
)
self.wait()
self.play(
mid_mobs.shift, 2*DOWN,
FadeOut(special_arrows)
)
self.play(
ShowCreation(mid_arrow),
Write(more_efficient)
)
self.wait()
class ShowSomeGraph(Scene):
def construct(self):
title = OldTexText("Graphs")
title.scale(2)
title.to_edge(UP)
nodes = VGroup(*list(map(Dot, [
2*LEFT,
UP,
DOWN,
2*RIGHT,
2*RIGHT+2*UP,
2*RIGHT+2*DOWN,
4*RIGHT+2*UP,
])))
edge_pairs = [
(0, 1),
(0, 2),
(1, 3),
(2, 3),
(3, 4),
(3, 5),
(4, 6),
]
edges = VGroup()
for i, j in edge_pairs:
edges.add(Line(
nodes[i].get_center(),
nodes[j].get_center(),
))
self.play(Write(title))
for mob in nodes, edges:
mob.set_color_by_gradient(YELLOW, MAROON_B)
self.play(ShowCreation(
mob,
lag_ratio = 0.5,
run_time = 2,
))
self.wait()
class SierpinskiGraphScene(Scene):
CONFIG = {
"num_disks" : 3,
"towers_config" : {
"num_disks" : 3,
"peg_height" : 1.5,
"peg_spacing" : 2,
"include_peg_labels" : False,
"disk_min_width" : 1,
"disk_max_width" : 2,
},
"preliminary_node_radius" : 1,
"center_to_island_length" : 2.0,
"include_towers" : True,
"start_color" : RED,
"end_color" : GREEN,
"graph_stroke_width" : 2,
}
def setup(self):
self.initialize_nodes()
self.add(self.nodes)
self.initialize_edges()
self.add(self.edges)
def initialize_nodes(self):
circles = self.get_node_circles(self.num_disks)
circles.set_color_by_gradient(self.start_color, self.end_color)
circles.set_fill(BLACK, opacity = 0.7)
circles.set_stroke(width = self.graph_stroke_width)
self.nodes = VGroup()
for circle in circles.get_family():
if not isinstance(circle, Circle):
continue
node = VGroup()
node.add(circle)
node.circle = circle
self.nodes.add(node)
if self.include_towers:
self.add_towers_to_nodes()
self.nodes.set_height(FRAME_HEIGHT-2)
self.nodes.to_edge(UP)
def get_node_circles(self, order = 3):
if order == 0:
return Circle(radius = self.preliminary_node_radius)
islands = [self.get_node_circles(order-1) for x in range(3)]
for island, angle in (islands[0], np.pi/6), (islands[2], 5*np.pi/6):
island.rotate(
np.pi,
rotate_vector(RIGHT, angle),
about_point = island.get_center_of_mass()
)
for n, island in enumerate(islands):
vect = rotate_vector(RIGHT, -5*np.pi/6-n*2*np.pi/3)
island.scale(0.5)
island.shift(vect)
return VGroup(*islands)
def add_towers_to_nodes(self):
towers_scene = ConstrainedTowersOfHanoiScene(**self.towers_config)
tower_scene_group = VGroup(*towers_scene.get_mobjects())
ruler_sequence = get_ternary_ruler_sequence(self.num_disks-1)
self.disks = VGroup(*[VGroup() for x in range(self.num_disks)])
for disk_index, node in zip(ruler_sequence+[0], self.nodes):
towers = tower_scene_group.copy()
for mob in towers:
if hasattr(mob, "label"):
self.disks[int(mob.label.tex_string)].add(mob)
towers.set_width(0.85*node.get_width())
towers.move_to(node)
node.towers = towers
node.add(towers)
towers_scene.move_disk(disk_index, run_time = 0)
def distance_between_nodes(self, i, j):
return get_norm(
self.nodes[i].get_center()-\
self.nodes[j].get_center()
)
def initialize_edges(self):
edges = VGroup()
self.edge_dict = {}
min_distance = self.distance_between_nodes(0, 1)
min_distance *= 1.1 ##Just a little buff to be sure
node_radius = self.nodes[0].get_width()/2
for i, j in it.combinations(list(range(3**self.num_disks)), 2):
center1 = self.nodes[i].get_center()
center2 = self.nodes[j].get_center()
vect = center1-center2
distance = get_norm(center1 - center2)
if distance < min_distance:
edge = Line(
center1 - (vect/distance)*node_radius,
center2 + (vect/distance)*node_radius,
color = self.nodes[i].circle.get_stroke_color(),
stroke_width = self.graph_stroke_width,
)
edges.add(edge)
self.edge_dict[self.node_indices_to_key(i, j)] = edge
self.edges = edges
def node_indices_to_key(self, i, j):
return ",".join(map(str, sorted([i, j])))
def node_indices_to_edge(self, i, j):
key = self.node_indices_to_key(i, j)
if key not in self.edge_dict:
warnings.warn("(%d, %d) is not an edge"%(i, j))
return VGroup()
return self.edge_dict[key]
def zoom_into_node(self, node_index, order = 0):
start_index = node_index - node_index%(3**order)
node_indices = [start_index + r for r in range(3**order)]
self.zoom_into_nodes(node_indices)
def zoom_into_nodes(self, node_indices):
nodes = VGroup(*[
self.nodes[index].circle
for index in node_indices
])
everything = VGroup(*self.get_mobjects())
if nodes.get_width()/nodes.get_height() > FRAME_X_RADIUS/FRAME_Y_RADIUS:
scale_factor = (FRAME_WIDTH-2)/nodes.get_width()
else:
scale_factor = (FRAME_HEIGHT-2)/nodes.get_height()
self.play(
everything.shift, -nodes.get_center(),
everything.scale, scale_factor
)
self.remove(everything)
self.add(*everything)
self.wait()
class IntroduceGraphStructure(SierpinskiGraphScene):
CONFIG = {
"include_towers" : True,
"graph_stroke_width" : 3,
"num_disks" : 3,
}
def construct(self):
self.remove(self.nodes, self.edges)
self.introduce_nodes()
self.define_edges()
self.tour_structure()
def introduce_nodes(self):
self.play(FadeIn(
self.nodes,
run_time = 3,
lag_ratio = 0.5,
))
vect = LEFT
for index in 3, 21, 8, 17, 10, 13:
node = self.nodes[index]
node.save_state()
self.play(
node.set_height, FRAME_HEIGHT-2,
node.next_to, ORIGIN, vect
)
self.wait()
self.play(node.restore)
node.saved_state = None
vect = -vect
def define_edges(self):
nodes = [self.nodes[i] for i in (12, 14)]
for node, vect in zip(nodes, [LEFT, RIGHT]):
node.save_state()
node.generate_target()
node.target.set_height(5)
node.target.center()
node.target.to_edge(vect)
arc = Arc(angle = -2*np.pi/3, start_angle = 5*np.pi/6)
if vect is RIGHT:
arc.flip()
arc.set_width(0.8*node.target.towers.get_width())
arc.next_to(node.target.towers, UP)
arc.add_tip()
arc.set_color(YELLOW)
node.arc = arc
self.play(*list(map(MoveToTarget, nodes)))
edge = Line(
nodes[0].get_right(), nodes[1].get_left(),
color = YELLOW,
stroke_width = 6,
)
edge.target = self.node_indices_to_edge(12, 14)
self.play(ShowCreation(edge))
self.wait()
for node in nodes:
self.play(ShowCreation(node.arc))
self.wait()
self.play(*[
FadeOut(node.arc)
for node in nodes
])
self.play(
MoveToTarget(edge),
*[node.restore for node in nodes]
)
self.wait()
self.play(ShowCreation(self.edges, run_time = 3))
self.wait()
def tour_structure(self):
for n in range(3):
self.zoom_into_node(n)
self.zoom_into_node(0, 1)
self.play(
self.disks[0].set_color, YELLOW,
*[
ApplyMethod(disk.label.set_color, BLACK)
for disk in self.disks[0]
]
)
self.wait()
self.zoom_into_node(0, 3)
self.zoom_into_node(15, 1)
self.wait()
self.zoom_into_node(20, 1)
self.wait()
class DescribeTriforcePattern(SierpinskiGraphScene):
CONFIG = {
"index_pairs" : [(7, 1), (2, 3), (5, 6)],
"scale" : 2,
"disk_color" : MAROON_B,
"include_towers" : True,
"first_connect_0_and_2_islands" : True, #Dumb that I have to do this
}
def construct(self):
index_pair = self.index_pairs[0]
self.zoom_into_node(index_pair[0], self.scale)
self.play(
self.disks[self.scale-1].set_color, self.disk_color,
*[
ApplyMethod(disk.label.set_color, BLACK)
for disk in self.disks[self.scale-1]
]
)
nodes = [self.nodes[i] for i in index_pair]
for node, vect in zip(nodes, [LEFT, RIGHT]):
node.save_state()
node.generate_target()
node.target.set_height(6)
node.target.center().next_to(ORIGIN, vect)
self.play(*list(map(MoveToTarget, nodes)))
self.wait()
self.play(*[node.restore for node in nodes])
bold_edges = [
self.node_indices_to_edge(*pair).copy().set_stroke(self.disk_color, 6)
for pair in self.index_pairs
]
self.play(ShowCreation(bold_edges[0]))
self.wait()
self.play(*list(map(ShowCreation, bold_edges[1:])))
self.wait()
power_of_three = 3**(self.scale-1)
index_sets = [
list(range(0, power_of_three)),
list(range(power_of_three, 2*power_of_three)),
list(range(2*power_of_three, 3*power_of_three)),
]
if self.first_connect_0_and_2_islands:
index_sets = [index_sets[0], index_sets[2], index_sets[1]]
islands = [
VGroup(*[self.nodes[i] for i in index_set])
for index_set in index_sets
]
def wiggle_island(island):
return ApplyMethod(
island.rotate, np.pi/12,
run_time = 1,
rate_func = wiggle
)
self.play(*list(map(wiggle_island, islands[:2])))
self.wait()
self.play(wiggle_island(islands[2]))
self.wait()
for index_set in index_sets:
self.zoom_into_nodes(index_set)
self.zoom_into_nodes(list(it.chain(*index_sets)))
self.wait()
class TriforcePatternWord(Scene):
def construct(self):
word = OldTexText("Triforce \\\\ pattern")
word.scale(2)
word.to_corner(DOWN+RIGHT)
self.play(Write(word))
self.wait(2)
class DescribeOrderTwoPattern(DescribeTriforcePattern):
CONFIG = {
"index_pairs" : [(8, 9), (17, 18), (4, 22)],
"scale" : 3,
"disk_color" : RED,
"first_connect_0_and_2_islands" : False,
}
class BiggerTowers(SierpinskiGraphScene):
CONFIG = {
"num_disks" : 6,
"include_towers" : False
}
def construct(self):
for order in range(3, 7):
self.zoom_into_node(0, order)
class ShowPathThroughGraph(SierpinskiGraphScene):
CONFIG = {
"include_towers" : True
}
def construct(self):
arrows = VGroup(*[
Arrow(
n1.get_center(),
n2.get_center(),
tip_length = 0.15,
buff = 0.15
)
for n1, n2 in zip(self.nodes, self.nodes[1:])
])
self.wait()
self.play(ShowCreation(
arrows,
rate_func=linear,
run_time = 5
))
self.wait(2)
for index in range(9):
self.zoom_into_node(index)
class MentionFinalAnimation(Scene):
def construct(self):
morty = Mortimer()
morty.shift(2*DOWN+3*RIGHT)
bubble = morty.get_bubble(SpeechBubble, width = 6)
bubble.write("Before the final\\\\ animation...")
self.add(morty)
self.wait()
self.play(
morty.change_mode, "speaking",
morty.look_at, bubble.content,
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(morty))
self.wait(2)
self.play(Blink(morty))
self.wait(2)
class PatreonThanks(Scene):
CONFIG = {
"specific_patrons" : [
"CrypticSwarm",
"Ali Yahya",
"Juan Batiz-Benet",
"Yu Jun",
"Othman Alikhan",
"Joseph John Cox",
"Luc Ritchie",
"Einar Johansen",
"Rish Kundalia",
"Achille Brighton",
"Kirk Werklund",
"Ripta Pasay",
"Felipe Diniz",
]
}
def construct(self):
morty = Mortimer()
morty.next_to(ORIGIN, DOWN)
n_patrons = len(self.specific_patrons)
special_thanks = OldTexText("Special thanks to:")
special_thanks.set_color(YELLOW)
special_thanks.shift(3*UP)
left_patrons = VGroup(*list(map(TexText,
self.specific_patrons[:n_patrons/2]
)))
right_patrons = VGroup(*list(map(TexText,
self.specific_patrons[n_patrons/2:]
)))
for patrons, vect in (left_patrons, LEFT), (right_patrons, RIGHT):
patrons.arrange(DOWN, aligned_edge = LEFT)
patrons.next_to(special_thanks, DOWN)
patrons.to_edge(vect, buff = LARGE_BUFF)
self.play(morty.change_mode, "gracious")
self.play(Write(special_thanks, run_time = 1))
self.play(
Write(left_patrons),
morty.look_at, left_patrons
)
self.play(
Write(right_patrons),
morty.look_at, right_patrons
)
self.play(Blink(morty))
for patrons in left_patrons, right_patrons:
for index in 0, -1:
self.play(morty.look_at, patrons[index])
self.wait()
class MortyLookingAtRectangle(Scene):
def construct(self):
morty = Mortimer()
morty.to_corner(DOWN+RIGHT)
url = OldTexText("www.desmos.com/careers")
url.to_corner(UP+LEFT)
rect = Rectangle(height = 9, width = 16)
rect.set_height(5)
rect.next_to(url, DOWN)
rect.shift_onto_screen()
url.save_state()
url.next_to(morty.get_corner(UP+LEFT), UP)
self.play(morty.change_mode, "raise_right_hand")
self.play(Write(url))
self.play(Blink(morty))
self.wait()
self.play(
url.restore,
morty.change_mode, "happy"
)
self.play(ShowCreation(rect))
self.wait()
self.play(Blink(morty))
self.wait()
class ShowSierpinskiCurvesOfIncreasingOrder(Scene):
CONFIG = {
"sierpinski_graph_scene_config" :{
"include_towers" : False
},
"min_order" : 2,
"max_order" : 7,
"path_stroke_width" : 7,
}
def construct(self):
graph_scenes = [
SierpinskiGraphScene(
num_disks = order,
**self.sierpinski_graph_scene_config
)
for order in range(self.min_order, self.max_order+1)
]
paths = [self.get_path(scene) for scene in graph_scenes]
graphs = []
for scene in graph_scenes:
graphs.append(scene.nodes)
for graph in graphs:
graph.set_fill(opacity = 0)
graph, path = graphs[0], paths[0]
self.add(graph)
self.wait()
self.play(ShowCreation(path, run_time = 3, rate_func=linear))
self.wait()
self.play(graph.fade, 0.5, Animation(path))
for other_graph in graphs[1:]:
other_graph.fade(0.5)
self.wait()
for new_graph, new_path in zip(graphs[1:], paths[1:]):
self.play(
Transform(graph, new_graph),
Transform(path, new_path),
run_time = 2
)
self.wait()
self.path = path
def get_path(self, graph_scene):
path = VGroup()
nodes = graph_scene.nodes
for n1, n2, n3 in zip(nodes, nodes[1:], nodes[2:]):
segment = VMobject()
segment.set_points_as_corners([
n1.get_center(),
n2.get_center(),
n3.get_center(),
])
path.add(segment)
path.set_color_by_gradient(
graph_scene.start_color,
graph_scene.end_color,
)
path.set_stroke(
width = self.path_stroke_width - graph_scene.num_disks/2
)
return path
class Part1Thumbnail(Scene):
CONFIG = {
"part_number" : 1,
"sierpinski_order" : 5
}
def construct(self):
toh_scene = TowersOfHanoiScene(
peg_spacing = 2,
part_number = 1,
)
toh_scene.remove(toh_scene.peg_labels)
toh_scene.pegs[2].set_fill(opacity = 0.5)
toh = VGroup(*toh_scene.get_mobjects())
toh.scale(2)
toh.to_edge(DOWN)
self.add(toh)
sierpinski_scene = ShowSierpinskiCurvesOfIncreasingOrder(
min_order = self.sierpinski_order,
max_order = self.sierpinski_order,
skip_animations = True,
)
sierpinski_scene.path.set_stroke(width = 10)
sierpinski = VGroup(*sierpinski_scene.get_mobjects())
sierpinski.scale(0.9)
sierpinski.to_corner(DOWN+RIGHT)
self.add(sierpinski)
binary = OldTex("01011")
binary.set_color_by_tex("0", GREEN)
binary.set_color_by_tex("1", BLUE)
binary.set_color_by_gradient(GREEN, RED)
binary.add_background_rectangle()
binary.background_rectangle.set_fill(opacity = 0.5)
# binary.set_fill(opacity = 0.5)
binary.scale(4)
binary.to_corner(UP+LEFT)
self.add(binary)
part = OldTexText("Part %d"%self.part_number)
part.scale(4)
part.to_corner(UP+RIGHT)
part.add_background_rectangle()
self.add(part)
class Part2Thumbnail(Part1Thumbnail):
CONFIG = {
"part_number" : 2
}
|
|
from manim_imports_ext import *
class FractalCreation(Scene):
CONFIG = {
"fractal_class" : PentagonalFractal,
"max_order" : 5,
"transform_kwargs" : {
"path_arc" : np.pi/6,
"lag_ratio" : 0.5,
"run_time" : 2,
},
"fractal_kwargs" : {},
}
def construct(self):
fractal = self.fractal_class(order = 0, **self.fractal_kwargs)
self.play(FadeIn(fractal))
for order in range(1, self.max_order+1):
new_fractal = self.fractal_class(
order = order,
**self.fractal_kwargs
)
fractal.align_data_and_family(new_fractal)
self.play(Transform(
fractal, new_fractal,
**self.transform_kwargs
))
self.wait()
self.wait()
self.fractal = fractal
class PentagonalFractalCreation(FractalCreation):
pass
class DiamondFractalCreation(FractalCreation):
CONFIG = {
"fractal_class" : DiamondFractal,
"max_order" : 6,
"fractal_kwargs" : {"height" : 6}
}
class PiCreatureFractalCreation(FractalCreation):
CONFIG = {
"fractal_class" : PiCreatureFractal,
"max_order" : 6,
"fractal_kwargs" : {"height" : 6},
"transform_kwargs" : {
"lag_ratio" : 0,
"run_time" : 2,
},
}
def construct(self):
FractalCreation.construct(self)
fractal = self.fractal
smallest_pi = fractal[0][0]
zoom_factor = 0.1/smallest_pi.get_height()
fractal.generate_target()
fractal.target.shift(-smallest_pi.get_corner(UP+LEFT))
fractal.target.scale(zoom_factor)
self.play(MoveToTarget(fractal, run_time = 10))
self.wait()
class QuadraticKochFractalCreation(FractalCreation):
CONFIG = {
"fractal_class" : QuadraticKoch,
"max_order" : 5,
"fractal_kwargs" : {"radius" : 10},
# "transform_kwargs" : {
# "lag_ratio" : 0,
# "run_time" : 2,
# },
}
class KochSnowFlakeFractalCreation(FractalCreation):
CONFIG = {
"fractal_class" : KochSnowFlake,
"max_order" : 6,
"fractal_kwargs" : {
"radius" : 6,
"num_submobjects" : 100,
},
"transform_kwargs" : {
"lag_ratio" : 0.5,
"path_arc" : np.pi/6,
"run_time" : 2,
},
}
class WonkyHexagonFractalCreation(FractalCreation):
CONFIG = {
"fractal_class" : WonkyHexagonFractal,
"max_order" : 5,
"fractal_kwargs" : {"height" : 6},
}
class SierpinskiFractalCreation(FractalCreation):
CONFIG = {
"fractal_class" : Sierpinski,
"max_order" : 6,
"fractal_kwargs" : {"height" : 6},
"transform_kwargs" : {
"path_arc" : 0,
},
}
class CircularFractalCreation(FractalCreation):
CONFIG = {
"fractal_class" : CircularFractal,
"max_order" : 5,
"fractal_kwargs" : {"height" : 6},
}
|
|
from manim_imports_ext import *
class ClosedLoopScene(Scene):
CONFIG = {
"loop_anchor_points" : [
3*RIGHT,
2*RIGHT+UP,
3*RIGHT + 3*UP,
UP,
2*UP+LEFT,
2*LEFT + 2*UP,
3*LEFT,
2*LEFT+DOWN,
3*LEFT+2*DOWN,
2*DOWN+RIGHT,
LEFT+DOWN,
],
"square_vertices" : [
2*RIGHT+UP,
2*UP+LEFT,
2*LEFT+DOWN,
2*DOWN+RIGHT
],
"rect_vertices" : [
0*RIGHT + 1*UP,
-1*RIGHT + 2*UP,
-3*RIGHT + 0*UP,
-2*RIGHT + -1*UP,
],
"dot_color" : YELLOW,
"connecting_lines_color" : BLUE,
"pair_colors" : [MAROON_B, PURPLE_B],
}
def setup(self):
self.dots = VGroup()
self.connecting_lines = VGroup()
self.add_loop()
def add_loop(self):
self.loop = self.get_default_loop()
self.add(self.loop)
def get_default_loop(self):
loop = VMobject()
loop.set_points_smoothly(
self.loop_anchor_points + [self.loop_anchor_points[0]]
)
return loop
def get_square(self):
return Polygon(*self.square_vertices)
def get_rect_vertex_dots(self, square = False):
if square:
vertices = self.square_vertices
else:
vertices = self.rect_vertices
dots = VGroup(*[Dot(v) for v in vertices])
dots.set_color(self.dot_color)
return dots
def get_rect_alphas(self, square = False):
#Inefficient and silly, but whatever.
dots = self.get_rect_vertex_dots(square = square)
return self.get_dot_alphas(dots)
def add_dot(self, dot):
self.add_dots(dot)
def add_dots(self, *dots):
self.dots.add(*dots)
self.add(self.dots)
def add_rect_dots(self, square = False):
self.add_dots(*self.get_rect_vertex_dots(square = square))
def add_dots_at_alphas(self, *alphas):
self.add_dots(*[
Dot(
self.loop.point_from_proportion(alpha),
color = self.dot_color
)
for alpha in alphas
])
def add_connecting_lines(self, cyclic = False):
if cyclic:
pairs = adjacent_pairs(self.dots)
else:
n_pairs = len(list(self.dots))/2
pairs = list(zip(self.dots[:n_pairs], self.dots[n_pairs:]))
for d1, d2 in pairs:
line = Line(d1.get_center(), d2.get_center())
line.start_dot = d1
line.end_dot = d2
line.update_anim = UpdateFromFunc(
line,
lambda l : l.put_start_and_end_on(
l.start_dot.get_center(),
l.end_dot.get_center()
)
)
line.set_color(d1.get_color())
self.connecting_lines.add(line)
if cyclic:
self.connecting_lines.set_color(self.connecting_lines_color)
self.connecting_lines.set_stroke(width = 6)
self.add(self.connecting_lines, self.dots)
def get_line_anims(self):
return [
line.update_anim
for line in self.connecting_lines
] + [Animation(self.dots)]
def get_dot_alphas(self, dots = None, precision = 0.005):
if dots == None:
dots = self.dots
alphas = []
alpha_range = np.arange(0, 1, precision)
loop_points = np.array(list(map(self.loop.point_from_proportion, alpha_range)))
for dot in dots:
vects = loop_points - dot.get_center()
norms = np.apply_along_axis(get_norm, 1, vects)
index = np.argmin(norms)
alphas.append(alpha_range[index])
return alphas
def let_dots_wonder(self, run_time = 5, random_seed = None, added_anims = []):
if random_seed is not None:
np.random.seed(random_seed)
start_alphas = self.get_dot_alphas()
alpha_rates = 0.05 + 0.1*np.random.random(len(list(self.dots)))
def generate_rate_func(start, rate):
return lambda t : (start + t*rate*run_time)%1
anims = [
MoveAlongPath(
dot,
self.loop,
rate_func = generate_rate_func(start, rate)
)
for dot, start, rate in zip(self.dots, start_alphas, alpha_rates)
]
anims += self.get_line_anims()
anims += added_anims
self.play(*anims, run_time = run_time)
def move_dots_to_alphas(self, alphas, run_time = 3):
assert(len(alphas) == len(list(self.dots)))
start_alphas = self.get_dot_alphas()
def generate_rate_func(start_alpha, alpha):
return lambda t : interpolate(start_alpha, alpha, smooth(t))
anims = [
MoveAlongPath(
dot, self.loop,
rate_func = generate_rate_func(sa, a),
run_time = run_time,
)
for dot, sa, a in zip(self.dots, start_alphas, alphas)
]
anims += self.get_line_anims()
self.play(*anims)
def transform_loop(self, target_loop, added_anims = [], **kwargs):
alphas = self.get_dot_alphas()
dot_anims = []
for dot, alpha in zip(self.dots, alphas):
dot.generate_target()
dot.target.move_to(target_loop.point_from_proportion(alpha))
dot_anims.append(MoveToTarget(dot))
self.play(
Transform(self.loop, target_loop),
*dot_anims + self.get_line_anims() + added_anims,
**kwargs
)
def set_color_dots_by_pair(self):
n_pairs = len(list(self.dots))/2
for d1, d2, c in zip(self.dots[:n_pairs], self.dots[n_pairs:], self.pair_colors):
VGroup(d1, d2).set_color(c)
def find_square(self):
alpha_quads = list(it.combinations(
np.arange(0, 1, 0.02) , 4
))
quads = np.array([
[
self.loop.point_from_proportion(alpha)
for alpha in quad
]
for quad in alpha_quads
])
scores = self.square_scores(quads)
index = np.argmin(scores)
return quads[index]
def square_scores(self, all_quads):
midpoint_diffs = np.apply_along_axis(
get_norm, 1,
0.5*(all_quads[:,0] + all_quads[:,2]) - 0.5*(all_quads[:,1] + all_quads[:,3])
)
vects1 = all_quads[:,0] - all_quads[:,2]
vects2 = all_quads[:,1] - all_quads[:,3]
distances1 = np.apply_along_axis(get_norm, 1, vects1)
distances2 = np.apply_along_axis(get_norm, 1, vects2)
distance_diffs = np.abs(distances1 - distances2)
midpoint_diffs /= distances1
distance_diffs /= distances2
buffed_d1s = np.repeat(distances1, 3).reshape(vects1.shape)
buffed_d2s = np.repeat(distances2, 3).reshape(vects2.shape)
unit_v1s = vects1/buffed_d1s
unit_v2s = vects2/buffed_d2s
dots = np.abs(unit_v1s[:,0]*unit_v2s[:,0] + unit_v1s[:,1]*unit_v2s[:,1] + unit_v1s[:,2]*unit_v2s[:,2])
return midpoint_diffs + distance_diffs + dots
#############################
class Introduction(TeacherStudentsScene):
def construct(self):
self.play(self.get_teacher().change_mode, "hooray")
self.random_blink()
self.teacher_says("")
for pi in self.get_students():
pi.generate_target()
pi.target.change_mode("happy")
pi.target.look_at(self.get_teacher().bubble)
self.play(*list(map(MoveToTarget, self.get_students())))
self.random_blink(3)
self.teacher_says(
"Here's why \\\\ I'm excited...",
target_mode = "hooray"
)
for pi in self.get_students():
pi.target.look_at(self.get_teacher().eyes)
self.play(*list(map(MoveToTarget, self.get_students())))
self.wait()
class WhenIWasAKid(TeacherStudentsScene):
def construct(self):
children = self.get_children()
speaker = self.get_speaker()
self.prepare_everyone(children, speaker)
self.state_excitement(children, speaker)
self.students = children
self.teacher = speaker
self.run_class()
self.grow_up()
def state_excitement(self, children, speaker):
self.teacher_says(
"""
Here's why
I'm excited!
""",
target_mode = "hooray"
)
self.play_student_changes(*["happy"]*3)
self.wait()
speaker.look_at(children)
me = children[-1]
self.play(
FadeOut(self.get_students()),
FadeOut(self.get_teacher().bubble),
FadeOut(self.get_teacher().bubble.content),
Transform(self.get_teacher(), me)
)
self.remove(self.get_teacher())
self.add(me)
self.play(*list(map(FadeIn, children[:-1] + [speaker])))
self.random_blink()
def run_class(self):
children = self.students
speaker = self.teacher
title = OldTexText("Topology")
title.to_edge(UP)
pi1, pi2, pi3, me = children
self.random_blink()
self.teacher_says(
"""
Math! Excitement!
You are the future!
""",
target_mode = "hooray"
)
self.play(
pi1.look_at, pi2.eyes,
pi1.change_mode, "erm",
pi2.look_at, pi1.eyes,
pi2.change_mode, "surprised",
)
self.play(
pi3.look_at, me.eyes,
pi3.change_mode, "sassy",
me.look_at, pi3.eyes,
)
self.random_blink(2)
self.play(
self.teacher.change_mode, "speaking",
FadeOut(self.teacher.bubble),
FadeOut(self.teacher.bubble.content),
)
self.play(Write(title))
self.random_blink()
self.play(pi1.change_mode, "raise_right_hand")
self.random_blink()
self.play(
pi2.change_mode, "confused",
pi3.change_mode, "happy",
pi2.look_at, pi3.eyes,
pi3.look_at, pi2.eyes,
)
self.random_blink()
self.play(me.change_mode, "pondering")
self.wait()
self.random_blink(2)
self.play(pi1.change_mode, "raise_left_hand")
self.wait()
self.play(pi2.change_mode, "erm")
self.random_blink()
self.student_says(
"How is this math?",
index = -1,
target_mode = "pleading",
width = 5,
height = 3,
direction = RIGHT
)
self.play(
pi1.change_mode, "pondering",
pi2.change_mode, "pondering",
pi3.change_mode, "pondering",
)
self.play(speaker.change_mode, "pondering")
self.random_blink()
def grow_up(self):
me = self.students[-1]
self.students.remove(me)
morty = Mortimer(mode = "pondering")
morty.flip()
morty.move_to(me, aligned_edge = DOWN)
morty.to_edge(LEFT)
morty.look(RIGHT)
self.play(
Transform(me, morty),
*list(map(FadeOut, [
self.students, self.teacher,
me.bubble, me.bubble.content
]))
)
self.remove(me)
self.add(morty)
self.play(Blink(morty))
self.wait()
self.play(morty.change_mode, "hooray")
self.wait()
def prepare_everyone(self, children, speaker):
self.everyone = list(children) + [speaker]
for pi in self.everyone:
pi.bubble = None
def get_children(self):
colors = [MAROON_E, YELLOW_D, PINK, GREY_BROWN]
children = VGroup(*[
BabyPiCreature(color = color)
for color in colors
])
children.arrange(RIGHT)
children.to_edge(DOWN, buff = LARGE_BUFF)
children.to_edge(LEFT)
return children
def get_speaker(self):
speaker = Mathematician(mode = "happy")
speaker.flip()
speaker.to_edge(DOWN, buff = LARGE_BUFF)
speaker.to_edge(RIGHT)
return speaker
def get_pi_creatures(self):
if hasattr(self, "everyone"):
return self.everyone
else:
return TeacherStudentsScene.get_pi_creatures(self)
class FormingTheMobiusStrip(Scene):
def construct(self):
pass
class DrawLineOnMobiusStrip(Scene):
def construct(self):
pass
class MugIntoTorus(Scene):
def construct(self):
pass
class DefineInscribedSquareProblem(ClosedLoopScene):
def construct(self):
self.draw_loop()
self.cycle_through_shapes()
self.ask_about_rectangles()
def draw_loop(self):
self.title = OldTexText("Inscribed", "square", "problem")
self.title.to_edge(UP)
#Draw loop
self.remove(self.loop)
self.play(Write(self.title))
self.wait()
self.play(ShowCreation(
self.loop,
run_time = 5,
rate_func=linear
))
self.wait()
self.add_rect_dots(square = True)
self.play(ShowCreation(self.dots, run_time = 2))
self.wait()
self.add_connecting_lines(cyclic = True)
self.play(
ShowCreation(
self.connecting_lines,
lag_ratio = 0,
run_time = 2
),
Animation(self.dots)
)
self.wait(2)
def cycle_through_shapes(self):
circle = Circle(radius = 2.5, color = WHITE)
ellipse = circle.copy()
ellipse.stretch(1.5, 0)
ellipse.stretch(0.7, 1)
ellipse.rotate(-np.pi/2)
ellipse.set_height(4)
pi_loop = OldTex("\\pi")[0]
pi_loop.set_fill(opacity = 0)
pi_loop.set_stroke(
color = WHITE,
width = DEFAULT_STROKE_WIDTH
)
pi_loop.set_height(4)
randy = Randolph()
randy.look(DOWN)
randy.set_width(pi_loop.get_width())
randy.move_to(pi_loop, aligned_edge = DOWN)
randy.body.set_fill(opacity = 0)
randy.mouth.set_stroke(width = 0)
self.transform_loop(circle)
self.remove(self.loop)
self.loop = circle
self.add(self.loop, self.connecting_lines, self.dots)
self.wait()
odd_eigths = np.linspace(1./8, 7./8, 4)
self.move_dots_to_alphas(odd_eigths)
self.wait()
for nudge in 0.1, -0.1, 0:
self.move_dots_to_alphas(odd_eigths+nudge)
self.wait()
self.transform_loop(ellipse)
self.wait()
nudge = 0.055
self.move_dots_to_alphas(
odd_eigths + [nudge, -nudge, nudge, -nudge]
)
self.wait(2)
self.transform_loop(pi_loop)
self.let_dots_wonder()
randy_anims = [
FadeIn(randy),
Animation(randy),
Blink(randy),
Animation(randy),
Blink(randy),
Animation(randy),
Blink(randy, rate_func = smooth)
]
for anim in randy_anims:
self.let_dots_wonder(
run_time = 1.5,
random_seed = 0,
added_anims = [anim]
)
self.remove(randy)
self.transform_loop(self.get_default_loop())
def ask_about_rectangles(self):
morty = Mortimer()
morty.next_to(ORIGIN, DOWN)
morty.to_edge(RIGHT)
new_title = OldTexText("Inscribed", "rectangle", "problem")
new_title.set_color_by_tex("rectangle", YELLOW)
new_title.to_edge(UP)
rect_dots = self.get_rect_vertex_dots()
rect_alphas = self.get_dot_alphas(rect_dots)
self.play(FadeIn(morty))
self.play(morty.change_mode, "speaking")
self.play(Transform(self.title, new_title))
self.move_dots_to_alphas(rect_alphas)
self.wait()
self.play(morty.change_mode, "hooray")
self.play(Blink(morty))
self.wait()
self.play(FadeOut(self.connecting_lines))
self.connecting_lines = VGroup()
self.play(morty.change_mode, "plain")
dot_pairs = [
VGroup(self.dots[i], self.dots[j])
for i, j in [(0, 2), (1, 3)]
]
pair_colors = MAROON_B, PURPLE_B
diag_lines = [
Line(d1.get_center(), d2.get_center(), color = c)
for (d1, d2), c in zip(dot_pairs, pair_colors)
]
for pair, line in zip(dot_pairs, diag_lines):
self.play(
FadeIn(line),
pair.set_color, line.get_color(),
)
class RectangleProperties(Scene):
def construct(self):
rect = Rectangle(color = BLUE)
vertex_dots = VGroup(*[
Dot(anchor, color = YELLOW)
for anchor in rect.get_anchors_and_handles()[0]
])
dot_pairs = [
VGroup(vertex_dots[i], vertex_dots[j])
for i, j in [(0, 2), (1, 3)]
]
colors = [MAROON_B, PURPLE_B]
diag_lines = [
Line(d1.get_center(), d2.get_center(), color = c)
for (d1, d2), c in zip(dot_pairs, colors)
]
braces = [Brace(rect).next_to(ORIGIN, DOWN) for x in range(2)]
for brace, line in zip(braces, diag_lines):
brace.stretch_to_fit_width(line.get_length())
brace.rotate(line.get_angle())
a, b, c, d = labels = VGroup(*[
OldTex(s).next_to(dot, dot.get_center(), buff = SMALL_BUFF)
for s, dot in zip("abcd", vertex_dots)
])
midpoint = Dot(ORIGIN, color = RED)
self.play(ShowCreation(rect))
self.wait()
self.play(
ShowCreation(vertex_dots),
Write(labels)
)
self.wait()
mob_lists = [
(a, c, dot_pairs[0]),
(b, d, dot_pairs[1]),
]
for color, mob_list in zip(colors, mob_lists):
self.play(*[
ApplyMethod(mob.set_color, color)
for mob in mob_list
])
self.wait()
for line, brace in zip(diag_lines, braces):
self.play(
ShowCreation(line),
GrowFromCenter(brace)
)
self.wait()
self.play(FadeOut(brace))
self.play(FadeIn(midpoint))
self.wait()
class PairOfPairBecomeRectangle(Scene):
def construct(self):
dots = VGroup(
Dot(4*RIGHT+0.5*DOWN, color = MAROON_B),
Dot(5*RIGHT+3*UP, color = MAROON_B),
Dot(LEFT+0.1*DOWN, color = PURPLE_B),
Dot(2*LEFT+UP, color = PURPLE_B)
)
labels = VGroup()
for dot, char in zip(dots, "acbd"):
label = OldTex(char)
y_coord = dot.get_center()[1]
label.next_to(dot, np.sign(dot.get_center()[1])*UP)
label.set_color(dot.get_color())
labels.add(label)
lines = [
Line(
dots[i].get_center(),
dots[j].get_center(),
color = dots[i].get_color()
)
for i, j in [(0, 1), (2, 3)]
]
groups = [
VGroup(dots[0], dots[1], labels[0], labels[1], lines[0]),
VGroup(dots[2], dots[3], labels[2], labels[3], lines[1]),
]
midpoint = Dot(LEFT, color = RED)
words = VGroup(*list(map(TexText, [
"Common midpoint",
"Same distance apart",
"$\\Downarrow$",
"Rectangle",
])))
words.arrange(DOWN)
words.to_edge(RIGHT)
words[-1].set_color(BLUE)
self.play(
ShowCreation(dots),
Write(labels)
)
self.play(*list(map(ShowCreation, lines)))
self.wait()
self.play(*[
ApplyMethod(
group.shift,
-group[-1].get_center()+midpoint.get_center()
)
for group in groups
])
self.play(
ShowCreation(midpoint),
Write(words[0])
)
factor = lines[0].get_length()/lines[1].get_length()
grower = groups[1].copy()
new_line = grower[-1]
new_line.scale(factor)
grower[0].move_to(new_line.get_start())
grower[2].next_to(grower[0], DOWN)
grower[1].move_to(new_line.get_end())
grower[3].next_to(grower[1], UP)
self.play(Transform(groups[1], grower))
self.play(Write(words[1]))
self.wait()
rectangle = Polygon(*[
dots[i].get_center()
for i in (0, 2, 1, 3)
])
rectangle.set_color(BLUE)
self.play(
ShowCreation(rectangle),
Animation(dots)
)
self.play(*list(map(Write, words[2:])))
self.wait()
class SearchForRectangleOnLoop(ClosedLoopScene):
def construct(self):
self.add_dots_at_alphas(*np.linspace(0.2, 0.8, 4))
self.set_color_dots_by_pair()
rect_alphas = self.get_rect_alphas()
self.play(ShowCreation(self.dots))
self.add_connecting_lines()
self.play(ShowCreation(self.connecting_lines))
self.let_dots_wonder(2)
self.move_dots_to_alphas(rect_alphas)
midpoint = Dot(
center_of_mass([d.get_center() for d in self.dots]),
color = RED
)
self.play(ShowCreation(midpoint))
self.wait()
angles = [line.get_angle() for line in self.connecting_lines]
angle_mean = np.mean(angles)
self.play(
*[
ApplyMethod(line.rotate, angle_mean-angle)
for line, angle in zip(self.connecting_lines, angles)
] + [Animation(midpoint)],
rate_func = there_and_back
)
self.add(self.connecting_lines.copy(), midpoint)
self.connecting_lines = VGroup()
self.wait()
self.add_connecting_lines(cyclic = True)
self.play(
ShowCreation(self.connecting_lines),
Animation(self.dots)
)
self.wait()
class DeclareFunction(ClosedLoopScene):
def construct(self):
self.add_dots_at_alphas(0.2, 0.8)
self.set_color_dots_by_pair()
self.add_connecting_lines()
VGroup(
self.loop, self.dots, self.connecting_lines
).scale(0.7).to_edge(LEFT).shift(DOWN)
arrow = Arrow(LEFT, RIGHT).next_to(self.loop)
self.add(arrow)
self.add_tex()
self.let_dots_wonder(10)
def add_tex(self):
tex = OldTex("f", "(A, B)", "=", "(x, y, z)")
tex.to_edge(UP)
tex.shift(LEFT)
ab_brace = Brace(tex[1])
xyz_brace = Brace(tex[-1], RIGHT)
ab_brace.add(ab_brace.get_text("Pair of points on the loop"))
xyz_brace.add(xyz_brace.get_text("Point in 3d space"))
ab_brace.set_color_by_gradient(MAROON_B, PURPLE_B)
xyz_brace.set_color(BLUE)
self.add(tex)
self.play(Write(ab_brace))
self.wait()
self.play(Write(xyz_brace))
self.wait()
class DefinePairTo3dFunction(Scene):
def construct(self):
pass
class LabelMidpoint(Scene):
def construct(self):
words = OldTexText("Midpoint $M$")
words.set_color(RED)
words.scale(2)
self.play(Write(words, run_time = 1))
self.wait()
class LabelDistance(Scene):
def construct(self):
words = OldTexText("Distance $d$")
words.set_color(MAROON_B)
words.scale(2)
self.play(Write(words, run_time = 1))
self.wait()
class DrawingOneLineOfTheSurface(Scene):
def construct(self):
pass
class FunctionSurface(Scene):
def construct(self):
pass
class PointPairApprocahingEachother3D(Scene):
def construct(self):
pass
class InputPairToFunction(Scene):
def construct(self):
tex = OldTex("f(X, X)", "=X")
tex.set_color_by_tex("=X", BLUE)
tex.scale(2)
self.play(Write(tex[0]))
self.wait(2)
self.play(Write(tex[1]))
self.wait(2)
class WigglePairUnderSurface(Scene):
def construct(self):
pass
class WriteContinuous(Scene):
def construct(self):
self.play(Write(OldTexText("Continuous").scale(2)))
self.wait(2)
class DistinctPairCollisionOnSurface(Scene):
def construct(self):
pass
class PairsOfPointsOnLoop(ClosedLoopScene):
def construct(self):
self.add_dots_at_alphas(0.2, 0.5)
self.dots.set_color(MAROON_B)
self.add_connecting_lines()
self.let_dots_wonder(run_time = 10)
class PairOfRealsToPlane(Scene):
def construct(self):
r1, r2 = numbers = -3, 2
colors = GREEN, RED
dot1, dot2 = dots = VGroup(*[Dot(color = c) for c in colors])
for dot, number in zip(dots, numbers):
dot.move_to(number*RIGHT)
pair_label = OldTex("(", str(r1), ",", str(r2), ")")
for number, color in zip(numbers, colors):
pair_label.set_color_by_tex(str(number), color)
pair_label.next_to(dots, UP, buff = 2)
arrows = VGroup(*[
Arrow(pair_label[i], dot, color = dot.get_color())
for i, dot in zip([1, 3], dots)
])
two_d_point = Dot(r1*RIGHT + r2*UP, color = YELLOW)
pair_label.add_background_rectangle()
x_axis = NumberLine(color = BLUE)
y_axis = NumberLine(color = BLUE)
plane = NumberPlane().fade()
self.add(x_axis, y_axis, dots, pair_label)
self.play(ShowCreation(arrows, run_time = 2))
self.wait()
self.play(
pair_label.next_to, two_d_point, UP+LEFT, SMALL_BUFF,
Rotate(y_axis, np.pi/2),
Rotate(dot2, np.pi/2),
FadeOut(arrows)
)
lines = VGroup(*[
DashedLine(dot, two_d_point, color = dot.get_color())
for dot in dots
])
self.play(*list(map(ShowCreation, lines)))
self.play(ShowCreation(two_d_point))
everything = VGroup(*self.get_mobjects())
self.play(
FadeIn(plane),
Animation(everything),
Animation(dot2)
)
self.wait()
class SeekSurfaceForPairs(ClosedLoopScene):
def construct(self):
self.loop.to_edge(LEFT)
self.add_dots_at_alphas(0.2, 0.3)
self.set_color_dots_by_pair()
self.add_connecting_lines()
arrow = Arrow(LEFT, RIGHT).next_to(self.loop)
words = OldTexText("Some 2d surface")
words.next_to(arrow, RIGHT)
anims = [
ShowCreation(arrow),
Write(words)
]
for anim in anims:
self.let_dots_wonder(
random_seed = 1,
added_anims = [anim],
run_time = anim.run_time
)
self.let_dots_wonder(random_seed = 1, run_time = 10)
class AskAbouPairType(TeacherStudentsScene):
def construct(self):
self.student_says("""
Do you mean ordered
or unordered pairs?
""")
self.play(*[
ApplyMethod(self.get_students()[i].change_mode, "confused")
for i in (0, 2)
])
self.random_blink(3)
class DefineOrderedPair(ClosedLoopScene):
def construct(self):
title = OldTexText("Ordered pairs")
title.to_edge(UP)
subtitle = OldTex(
"(", "a", ",", "b", ")",
"\\ne",
"(", "b", ",", "a", ")"
)
labels_start = VGroup(subtitle[1], subtitle[3])
labels_end = VGroup(subtitle[9], subtitle[7])
subtitle.next_to(title, DOWN)
colors = GREEN, RED
for char, color in zip("ab", colors):
subtitle.set_color_by_tex(char, color)
self.loop.next_to(subtitle, DOWN)
self.add(title, subtitle)
self.add_dots_at_alphas(0.5, 0.6)
dots = self.dots
for dot, color, char in zip(dots, colors, "ab"):
dot.set_color(color)
label = OldTex(char)
label.set_color(color)
label.next_to(dot, RIGHT, buff = SMALL_BUFF)
dot.label = label
self.dots[1].label.shift(0.3*UP)
first = OldTexText("First")
first.next_to(self.dots[0], UP+2*LEFT, LARGE_BUFF)
arrow = Arrow(first.get_bottom(), self.dots[0], color = GREEN)
self.wait()
self.play(*[
Transform(label.copy(), dot.label)
for label, dot in zip(labels_start, dots)
])
self.remove(*self.get_mobjects_from_last_animation())
self.add(*[d.label for d in dots])
self.wait()
self.play(
Write(first),
ShowCreation(arrow)
)
self.wait()
class DefineUnorderedPair(ClosedLoopScene):
def construct(self):
title = OldTexText("Unordered pairs")
title.to_edge(UP)
subtitle = OldTex(
"\\{a,b\\}",
"=",
"\\{b,a\\}",
)
subtitle.next_to(title, DOWN)
for char in "ab":
subtitle.set_color_by_tex(char, PURPLE_B)
self.loop.next_to(subtitle, DOWN)
self.add(title, subtitle)
self.add_dots_at_alphas(0.5, 0.6)
dots = self.dots
dots.set_color(PURPLE_B)
labels = VGroup(*[subtitle[i].copy() for i in (0, 2)])
for label, vect in zip(labels, [LEFT, RIGHT]):
label.next_to(dots, vect, LARGE_BUFF)
arrows = [
Arrow(*pair, color = PURPLE_B)
for pair in it.product(labels, dots)
]
arrow_pairs = [VGroup(*arrows[:2]), VGroup(*arrows[2:])]
for label, arrow_pair in zip(labels, arrow_pairs):
self.play(*list(map(FadeIn, [label, arrow_pair])))
self.wait()
for x in range(2):
self.play(
dots[0].move_to, dots[1],
dots[1].move_to, dots[0],
path_arc = np.pi/2
)
self.wait()
class BeginWithOrdered(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
One must know order
before he can ignore it.
""")
self.random_blink(3)
class DeformToInterval(ClosedLoopScene):
def construct(self):
interval = UnitInterval(color = WHITE)
interval.shift(2*DOWN)
numbers = interval.get_number_mobjects(0, 1)
line = Line(interval.get_left(), interval.get_right())
line.insert_n_curves(self.loop.get_num_curves())
line.make_smooth()
self.loop.scale(0.7)
self.loop.to_edge(UP)
original_loop = self.loop.copy()
cut_loop = self.loop.copy()
cut_loop.get_points()[0] += 0.3*(UP+RIGHT)
cut_loop.get_points()[-1] += 0.3*(DOWN+RIGHT)
#Unwrap loop
self.transform_loop(cut_loop, path_arc = np.pi)
self.wait()
self.transform_loop(
line,
run_time = 3,
path_arc = np.pi/2
)
self.wait()
self.play(ShowCreation(interval))
self.play(Write(numbers))
self.wait()
#Follow points
self.loop = original_loop.copy()
self.play(FadeIn(self.loop))
self.add(original_loop)
self.add_dots_at_alphas(*np.linspace(0, 1, 20))
self.dots.set_color_by_gradient(BLUE, MAROON_C, BLUE)
dot_at_1 = self.dots[-1]
dot_at_1.generate_target()
dot_at_1.target.move_to(interval.get_right())
dots_copy = self.dots.copy()
fading_dots = VGroup(*list(self.dots)+list(dots_copy))
end_dots = VGroup(
self.dots[0], self.dots[-1],
dots_copy[0], dots_copy[-1]
)
fading_dots.remove(*end_dots)
self.play(Write(self.dots))
self.add(dots_copy)
self.wait()
self.transform_loop(
line,
added_anims = [MoveToTarget(dot_at_1)],
run_time = 3
)
self.wait()
self.loop = original_loop
self.dots = dots_copy
dot_at_1 = self.dots[-1]
dot_at_1.target.move_to(cut_loop.get_points()[-1])
self.transform_loop(
cut_loop,
added_anims = [MoveToTarget(dot_at_1)]
)
self.wait()
fading_dots.generate_target()
fading_dots.target.set_fill(opacity = 0.3)
self.play(MoveToTarget(fading_dots))
self.play(
end_dots.shift, 0.2*UP,
rate_func = wiggle
)
self.wait()
class RepresentPairInUnitSquare(ClosedLoopScene):
def construct(self):
interval = UnitInterval(color = WHITE)
interval.shift(2.5*DOWN)
interval.shift(LEFT)
numbers = interval.get_number_mobjects(0, 1)
line = Line(interval.get_left(), interval.get_right())
line.insert_n_curves(self.loop.get_num_curves())
line.make_smooth()
vert_interval = interval.copy()
square = Square()
square.set_width(interval.get_width())
square.set_stroke(width = 0)
square.set_fill(color = BLUE, opacity = 0.3)
square.move_to(
interval.get_left(),
aligned_edge = DOWN+LEFT
)
right_words = VGroup(*[
OldTexText("Pair of\\\\ loop points"),
OldTex("\\Downarrow"),
OldTexText("Point in \\\\ unit square")
])
right_words.arrange(DOWN)
right_words.to_edge(RIGHT)
dot_coords = (0.3, 0.7)
self.loop.scale(0.7)
self.loop.to_edge(UP)
self.add_dots_at_alphas(*dot_coords)
self.dots.set_color_by_gradient(GREEN, RED)
self.play(
Write(self.dots),
Write(right_words[0])
)
self.wait()
self.transform_loop(line)
self.play(
ShowCreation(interval),
Write(numbers),
Animation(self.dots)
)
self.wait()
self.play(*[
Rotate(mob, np.pi/2, about_point = interval.get_left())
for mob in (vert_interval, self.dots[1])
])
#Find interior point
point = self.dots[0].get_center()[0]*RIGHT
point += self.dots[1].get_center()[1]*UP
inner_dot = Dot(point, color = YELLOW)
dashed_lines = VGroup(*[
DashedLine(dot, inner_dot, color = dot.get_color())
for dot in self.dots
])
self.play(ShowCreation(dashed_lines))
self.play(ShowCreation(inner_dot))
self.play(
FadeIn(square),
Animation(self.dots),
*list(map(Write, right_words[1:]))
)
self.wait()
#Shift point in square
movers = list(dashed_lines)+list(self.dots)+[inner_dot]
for mob in movers:
mob.generate_target()
shift_vals = [
RIGHT+DOWN,
LEFT+DOWN,
LEFT+2*UP,
3*DOWN,
2*RIGHT+UP,
RIGHT+UP,
3*LEFT+3*DOWN
]
for shift_val in shift_vals:
inner_dot.target.shift(shift_val)
self.dots[0].target.shift(shift_val[0]*RIGHT)
self.dots[1].target.shift(shift_val[1]*UP)
for line, dot in zip(dashed_lines, self.dots):
line.target.put_start_and_end_on(
dot.target.get_center(),
inner_dot.target.get_center()
)
self.play(*list(map(MoveToTarget, movers)))
self.wait()
self.play(*list(map(FadeOut, [dashed_lines, self.dots])))
class EdgesOfSquare(Scene):
def construct(self):
square = self.add_square()
x_edges, y_edges = self.get_edges(square)
label_groups = self.get_coordinate_labels(square)
arrow_groups = self.get_arrows(x_edges, y_edges)
for edge in list(x_edges) + list(y_edges):
self.play(ShowCreation(edge))
self.wait()
for label_group in label_groups:
for label in label_group[:3]:
self.play(FadeIn(label))
self.wait()
self.play(Write(VGroup(*label_group[3:])))
self.wait()
self.play(FadeOut(VGroup(*label_groups)))
for arrows in arrow_groups:
self.play(ShowCreation(arrows, run_time = 2))
self.wait()
self.play(*[
ApplyMethod(
n.next_to,
square.get_corner(vect+LEFT),
LEFT,
MED_SMALL_BUFF,
path_arc = np.pi/2
)
for n, vect in zip(self.numbers, [DOWN, UP])
])
self.wait()
def add_square(self):
interval = UnitInterval(color = WHITE)
interval.shift(2.5*DOWN)
bottom_left = interval.get_left()
for tick in interval.tick_marks:
height = tick.get_height()
tick.scale(0.5)
tick.shift(height*DOWN/4.)
self.numbers = interval.get_number_mobjects(0, 1)
vert_interval = interval.copy()
vert_interval.rotate(np.pi, axis = UP+RIGHT, about_point = bottom_left)
square = Square()
square.set_width(interval.get_width())
square.set_stroke(width = 0)
square.set_fill(color = BLUE, opacity = 0.3)
square.move_to(
bottom_left,
aligned_edge = DOWN+LEFT
)
self.add(interval, self.numbers, vert_interval, square)
return square
def get_edges(self, square):
y_edges = VGroup(*[
Line(
square.get_corner(vect+LEFT),
square.get_corner(vect+RIGHT),
)
for vect in (DOWN, UP)
])
y_edges.set_color(BLUE)
x_edges = VGroup(*[
Line(
square.get_corner(vect+DOWN),
square.get_corner(vect+UP),
)
for vect in (LEFT, RIGHT)
])
x_edges.set_color(MAROON_B)
return x_edges, y_edges
def get_coordinate_labels(self, square):
alpha_range = np.arange(0, 1.1, 0.1)
dot_groups = [
VGroup(*[
Dot(interpolate(
square.get_corner(DOWN+vect),
square.get_corner(UP+vect),
alpha
))
for alpha in alpha_range
])
for vect in (LEFT, RIGHT)
]
for group in dot_groups:
group.set_color_by_gradient(YELLOW, PURPLE_B)
label_groups = [
VGroup(*[
OldTex("(%s, %s)"%(a, b)).scale(0.7)
for b in alpha_range
])
for a in (0, 1)
]
for dot_group, label_group in zip(dot_groups, label_groups):
for dot, label in zip(dot_group, label_group):
label[1].set_color(MAROON_B)
label.next_to(dot, RIGHT*np.sign(dot.get_center()[0]))
label.add(dot)
return label_groups
def get_arrows(self, x_edges, y_edges):
alpha_range = np.linspace(0, 1, 4)
return [
VGroup(*[
VGroup(*[
Arrow(
edge.point_from_proportion(a1),
edge.point_from_proportion(a2),
buff = 0
)
for a1, a2 in zip(alpha_range, alpha_range[1:])
])
for edge in edges
]).set_color(edges.get_color())
for edges in (x_edges, y_edges)
]
class EndpointsGluedTogether(ClosedLoopScene):
def construct(self):
interval = UnitInterval(color = WHITE)
interval.shift(2*DOWN)
numbers = interval.get_number_mobjects(0, 1)
line = Line(interval.get_left(), interval.get_right())
line.insert_n_curves(self.loop.get_num_curves())
line.make_smooth()
self.loop.scale(0.7)
self.loop.to_edge(UP)
original_loop = self.loop
self.remove(original_loop)
self.loop = line
dots = VGroup(*[
Dot(line.get_bounding_box_point(vect))
for vect in (LEFT, RIGHT)
])
dots.set_color(BLUE)
self.add(interval, dots)
self.play(dots.rotate, np.pi/20, rate_func = wiggle)
self.wait()
self.transform_loop(
original_loop,
added_anims = [
ApplyMethod(dot.move_to, original_loop.get_points()[0])
for dot in dots
],
run_time = 3
)
self.wait()
class WrapUpToTorus(Scene):
def construct(self):
pass
class TorusPlaneAnalogy(ClosedLoopScene):
def construct(self):
top_arrow = DoubleArrow(LEFT, RIGHT)
top_arrow.to_edge(UP, buff = 2*LARGE_BUFF)
single_pointed_top_arrow = Arrow(LEFT, RIGHT)
single_pointed_top_arrow.to_edge(UP, buff = 2*LARGE_BUFF)
low_arrow = DoubleArrow(LEFT, RIGHT).shift(2*DOWN)
self.loop.scale(0.5)
self.loop.next_to(top_arrow, RIGHT)
self.loop.shift_onto_screen()
self.add_dots_at_alphas(0.3, 0.5)
self.dots.set_color_by_gradient(GREEN, RED)
plane = NumberPlane()
plane.scale(0.3).next_to(low_arrow, LEFT)
number_line = NumberLine()
number_line.scale(0.3)
number_line.next_to(low_arrow, RIGHT)
number_line.add(
Dot(number_line.number_to_point(3), color = GREEN),
Dot(number_line.number_to_point(-2), color = RED),
)
self.wait()
self.play(ShowCreation(single_pointed_top_arrow))
self.wait()
self.play(ShowCreation(top_arrow))
self.wait()
self.play(ShowCreation(plane))
self.play(ShowCreation(low_arrow))
self.play(ShowCreation(number_line))
self.wait()
class WigglingPairOfPoints(ClosedLoopScene):
def construct(self):
alpha_pairs = [
(0.4, 0.6),
(0.42, 0.62),
]
self.add_dots_at_alphas(*alpha_pairs[-1])
self.add_connecting_lines()
self.dots.set_color_by_gradient(GREEN, RED)
self.connecting_lines.set_color(YELLOW)
for x, pair in zip(list(range(20)), it.cycle(alpha_pairs)):
self.move_dots_to_alphas(pair, run_time = 0.3)
class WigglingTorusPoint(Scene):
def construct(self):
pass
class WhatAboutUnordered(TeacherStudentsScene):
def construct(self):
self.student_says(
"What about \\\\ unordered pairs?"
)
self.play(self.get_teacher().change_mode, "pondering")
self.random_blink(2)
class TrivialPairCollision(ClosedLoopScene):
def construct(self):
self.loop.to_edge(RIGHT)
self.add_dots_at_alphas(0.35, 0.55)
self.dots.set_color_by_gradient(BLUE, YELLOW)
a, b = self.dots
a_label = OldTex("a").next_to(a, RIGHT)
a_label.set_color(a.get_color())
b_label = OldTex("b").next_to(b, LEFT)
b_label.set_color(b.get_color())
line = Line(
a.get_corner(DOWN+LEFT),
b.get_corner(UP+RIGHT),
color = MAROON_B
)
midpoint = Dot(self.dots.get_center(), color = RED)
randy = Randolph(mode = "pondering")
randy.next_to(self.loop, LEFT, aligned_edge = DOWN)
randy.look_at(b)
self.add(randy)
for label in a_label, b_label:
self.play(
Write(label, run_time = 1),
randy.look_at, label
)
self.play(Blink(randy))
self.wait()
swappers = [a, b, a_label, b_label]
for mob in swappers:
mob.save_state()
self.play(
a.move_to, b,
b.move_to, a,
a_label.next_to, b, LEFT,
b_label.next_to, a, RIGHT,
randy.look_at, a,
path_arc = np.pi
)
self.play(ShowCreation(midpoint))
self.play(ShowCreation(line), Animation(midpoint))
self.play(randy.change_mode, "erm", randy.look_at, b)
self.play(
randy.look_at, a,
*[m.restore for m in swappers],
path_arc = -np.pi
)
self.play(Blink(randy))
self.wait()
class NotHelpful(Scene):
def construct(self):
morty = Mortimer()
morty.next_to(ORIGIN, DOWN)
bubble = morty.get_bubble(SpeechBubble, width = 4, height = 3)
bubble.write("Not helpful!")
self.add(morty)
self.play(
FadeIn(bubble),
FadeIn(bubble.content),
morty.change_mode, "angry",
morty.look, OUT
)
self.play(Blink(morty))
self.wait()
class FoldUnitSquare(EdgesOfSquare):
def construct(self):
self.add_triangles()
self.add_arrows()
self.show_points_to_glue()
self.perform_fold()
self.show_singleton_pairs()
self.ask_about_gluing()
self.clarify_edge_gluing()
def add_triangles(self):
square = self.add_square()
triangles = VGroup(*[
Polygon(*[square.get_corner(vect) for vect in vects])
for vects in [
(DOWN+LEFT, UP+RIGHT, UP+LEFT),
(DOWN+LEFT, UP+RIGHT, DOWN+RIGHT),
]
])
triangles.set_stroke(width = 0)
triangles.set_fill(
color = square.get_color(),
opacity = square.get_fill_opacity()
)
self.remove(square)
self.square = square
self.add(triangles)
self.triangles = triangles
def add_arrows(self):
start_arrows = VGroup()
end_arrows = VGroup()
colors = MAROON_B, BLUE
for a in 0, 1:
for color in colors:
b_range = np.linspace(0, 1, 4)
for b1, b2 in zip(b_range, b_range[1:]):
arrow = Arrow(
self.get_point_from_coords(a, b1),
self.get_point_from_coords(a, b2),
buff = 0,
color = color
)
if color is BLUE:
arrow.rotate(
-np.pi/2,
about_point = self.square.get_center()
)
if (a is 0):
start_arrows.add(arrow)
else:
end_arrows.add(arrow)
self.add(start_arrows, end_arrows)
self.start_arrows = start_arrows
self.end_arrows = VGroup(*list(end_arrows[3:])+list(end_arrows[:3])).copy()
self.end_arrows.set_color(
color_gradient([MAROON_B, BLUE], 3)[1]
)
def show_points_to_glue(self):
colors = YELLOW, MAROON_B, PINK
pairs = [(0.2, 0.3), (0.5, 0.7), (0.25, 0.6)]
unit = self.square.get_width()
start_dots = VGroup()
end_dots = VGroup()
for (x, y), color in zip(pairs, colors):
old_x_line, old_y_line = None, None
for (a, b) in (x, y), (y, x):
point = self.get_point_from_coords(a, b)
dot = Dot(point)
dot.set_color(color)
if color == colors[-1]:
s = "(x, y)" if a < b else "(y, x)"
label = OldTex(s)
else:
label = OldTex("(%.01f, %.01f)"%(a, b))
vect = UP+RIGHT if a < b else DOWN+RIGHT
label.next_to(dot, vect, buff = SMALL_BUFF)
self.play(*list(map(FadeIn, [dot, label])))
x_line = Line(point+a*unit*LEFT, point)
y_line = Line(point+b*unit*DOWN, point)
x_line.set_color(GREEN)
y_line.set_color(RED)
if old_x_line is None:
self.play(ShowCreation(x_line), Animation(dot))
self.play(ShowCreation(y_line), Animation(dot))
old_x_line, old_y_line = y_line, x_line
else:
self.play(Transform(old_x_line, x_line), Animation(dot))
self.play(Transform(old_y_line, y_line), Animation(dot))
self.remove(old_x_line, old_y_line)
self.add(x_line, y_line, dot)
self.wait(2)
self.play(FadeOut(label))
if a < b:
start_dots.add(dot)
else:
end_dots.add(dot)
self.play(*list(map(FadeOut, [x_line, y_line])))
self.start_dots, self.end_dots = start_dots, end_dots
def perform_fold(self):
diag_line = DashedLine(
self.square.get_corner(DOWN+LEFT),
self.square.get_corner(UP+RIGHT),
color = RED
)
self.play(ShowCreation(diag_line))
self.wait()
self.play(
Transform(*self.triangles),
Transform(self.start_dots, self.end_dots),
Transform(self.start_arrows, self.end_arrows),
)
self.wait()
self.diag_line = diag_line
def show_singleton_pairs(self):
xs = [0.7, 0.4, 0.5]
old_label = None
old_dot = None
for x in xs:
point = self.get_point_from_coords(x, x)
dot = Dot(point)
if x is xs[-1]:
label = OldTex("(x, x)")
else:
label = OldTex("(%.1f, %.1f)"%(x, x))
label.next_to(dot, UP+LEFT, buff = SMALL_BUFF)
VGroup(dot, label).set_color(RED)
if old_label is None:
self.play(
ShowCreation(dot),
Write(label)
)
old_label = label
old_dot = dot
else:
self.play(
Transform(old_dot, dot),
Transform(old_label, label),
)
self.wait()
#Some strange bug necesitating this
self.remove(old_label)
self.add(label)
def ask_about_gluing(self):
keepers = VGroup(
self.triangles[0],
self.start_arrows,
self.diag_line
).copy()
faders = VGroup(*self.get_mobjects())
randy = Randolph()
randy.next_to(ORIGIN, DOWN)
bubble = randy.get_bubble(height = 4, width = 6)
bubble.write("How do you \\\\ glue those arrows?")
self.play(
FadeOut(faders),
Animation(keepers)
)
self.play(
keepers.scale, 0.6,
keepers.shift, 4*RIGHT + UP,
FadeIn(randy)
)
self.play(
randy.change_mode, "pondering",
randy.look_at, keepers,
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(randy))
self.wait()
self.randy = randy
def clarify_edge_gluing(self):
dots = VGroup(*[
Dot(self.get_point_from_coords(*coords), radius = 0.1)
for coords in [
(0.1, 0),
(1, 0.1),
(0.9, 0),
(1, 0.9),
]
])
dots.scale(0.6)
dots.shift(4*RIGHT + UP)
for dot in dots[:2]:
dot.set_color(YELLOW)
self.play(
ShowCreation(dot),
self.randy.look_at, dot
)
self.wait()
for dot in dots[2:]:
dot.set_color(MAROON_B)
self.play(
ShowCreation(dot),
self.randy.look_at, dot
)
self.play(Blink(self.randy))
self.wait()
def get_point_from_coords(self, x, y):
left, right, bottom, top = [
self.triangles.get_edge_center(vect)
for vect in (LEFT, RIGHT, DOWN, UP)
]
x_point = interpolate(left, right, x)
y_point = interpolate(bottom, top, y)
return x_point[0]*RIGHT + y_point[1]*UP
class PrepareForMobiusStrip(Scene):
def construct(self):
self.add_triangles()
self.perform_cut()
self.rearrange_pieces()
def add_triangles(self):
triangles = VGroup(
Polygon(
DOWN+LEFT,
DOWN+RIGHT,
ORIGIN,
),
Polygon(
DOWN+RIGHT,
UP+RIGHT,
ORIGIN,
),
)
triangles.set_fill(color = BLUE, opacity = 0.6)
triangles.set_stroke(width = 0)
triangles.center()
triangles.scale(2)
arrows_color = color_gradient([PINK, BLUE], 3)[1]
for tri in triangles:
anchors = tri.get_anchors_and_handles()[0]
alpha_range = np.linspace(0, 1, 4)
arrows = VGroup(*[
Arrow(
interpolate(anchors[0], anchors[1], a),
interpolate(anchors[0], anchors[1], b),
buff = 0,
color = arrows_color
)
for a, b in zip(alpha_range, alpha_range[1:])
])
tri.original_arrows = arrows
tri.add(arrows)
i, j, k = (0, 2, 1) if tri is triangles[0] else (1, 2, 0)
dashed_line = DashedLine(
anchors[i], anchors[j],
color = RED
)
tri.add(dashed_line)
#Add but don't draw cut_arrows
start, end = anchors[j], anchors[k]
cut_arrows = VGroup(*[
Arrow(
interpolate(start, end, a),
interpolate(start, end, b),
buff = 0,
color = YELLOW
)
for a, b in zip(alpha_range, alpha_range[1:])
])
tri.cut_arrows = cut_arrows
self.add(triangles)
self.triangles = triangles
def perform_cut(self):
tri1, tri2 = self.triangles
self.play(ShowCreation(tri1.cut_arrows))
for tri in self.triangles:
tri.add(tri.cut_arrows)
self.wait()
self.play(
tri1.shift, (DOWN+LEFT)/2.,
tri2.shift, (UP+RIGHT)/2.,
)
self.wait()
def rearrange_pieces(self):
tri1, tri2 = self.triangles
self.play(
tri1.rotate, np.pi, UP+RIGHT,
tri1.next_to, ORIGIN, RIGHT,
tri2.next_to, ORIGIN, LEFT,
)
self.wait()
self.play(*[
ApplyMethod(tri.shift, tri.get_points()[0][0]*LEFT)
for tri in self.triangles
])
self.play(*[
FadeOut(tri.original_arrows)
for tri in self.triangles
])
for tri in self.triangles:
tri.remove(tri.original_arrows)
self.wait()
# self.play(*[
# ApplyMethod(tri.rotate, -np.pi/4)
# for tri in self.triangles
# ])
# self.wait()
class FoldToMobius(Scene):
def construct(self):
pass
class MobiusPlaneAnalogy(ClosedLoopScene):
def construct(self):
top_arrow = Arrow(LEFT, RIGHT)
top_arrow.to_edge(UP, buff = 2*LARGE_BUFF)
low_arrow = Arrow(LEFT, RIGHT).shift(2*DOWN)
self.loop.scale(0.5)
self.loop.next_to(top_arrow, RIGHT)
self.loop.shift_onto_screen()
self.add_dots_at_alphas(0.3, 0.5)
self.dots.set_color(PURPLE_B)
plane = NumberPlane()
plane.scale(0.3).next_to(low_arrow, LEFT)
number_line = NumberLine()
number_line.scale(0.3)
number_line.next_to(low_arrow, RIGHT)
number_line.add(
Dot(number_line.number_to_point(3), color = GREEN),
Dot(number_line.number_to_point(-2), color = RED),
)
self.wait()
self.play(ShowCreation(top_arrow))
self.wait()
self.play(ShowCreation(plane))
self.play(ShowCreation(low_arrow))
self.play(ShowCreation(number_line))
self.wait()
class DrawRightArrow(Scene):
CONFIG = {
"tex" : "\\Rightarrow"
}
def construct(self):
arrow = OldTex(self.tex)
arrow.scale(4)
self.play(Write(arrow))
self.wait()
class DrawLeftrightArrow(DrawRightArrow):
CONFIG = {
"tex" : "\\Leftrightarrow"
}
class MobiusToPairToSurface(ClosedLoopScene):
def construct(self):
self.loop.scale(0.5)
self.loop.next_to(ORIGIN, RIGHT)
self.loop.to_edge(UP)
self.add_dots_at_alphas(0.4, 0.6)
self.dots.set_color(MAROON_B)
self.add_connecting_lines()
strip_dot = Dot().next_to(self.loop, LEFT, buff = 2*LARGE_BUFF)
surface_dot = Dot().next_to(self.loop, DOWN, buff = 2*LARGE_BUFF)
top_arrow = Arrow(strip_dot, self.loop)
right_arrow = Arrow(self.loop, surface_dot)
diag_arrow = Arrow(strip_dot, surface_dot)
randy = self.randy = Randolph(mode = "pondering")
randy.next_to(ORIGIN, DOWN+LEFT)
self.look_at(strip_dot)
self.play(
ShowCreation(top_arrow),
randy.look_at, self.loop
)
self.wait()
self.look_at(strip_dot, surface_dot)
self.play(ShowCreation(diag_arrow))
self.play(Blink(randy))
self.look_at(strip_dot, self.loop)
self.wait()
self.play(
ShowCreation(right_arrow),
randy.look_at, surface_dot
)
self.play(Blink(randy))
self.play(randy.change_mode, "happy")
self.play(Blink(randy))
self.wait()
def look_at(self, *things):
for thing in things:
self.play(self.randy.look_at, thing)
class MapMobiusStripOntoSurface(Scene):
def construct(self):
pass
class StripMustIntersectItself(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"""
The strip must
intersect itself
during this process
""",
width = 4
)
dot = Dot(2*UP + 4*LEFT)
for student in self.get_students():
student.generate_target()
student.target.change_mode("pondering")
student.target.look_at(dot)
self.play(*list(map(MoveToTarget, self.get_students())))
self.random_blink(4)
class PairOfMobiusPointsLandOnEachother(Scene):
def construct(self):
pass
class ThatsTheProof(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"""
Bada boom
bada bang!
""",
target_mode = "hooray",
width = 4
)
self.play_student_changes(*["hooray"]*3)
self.random_blink()
self.play_student_changes(
"confused", "sassy", "erm"
)
self.teacher_says(
"""
If you trust
the mobius strip
fact...
""",
target_mode = "guilty",
width = 4,
)
self.random_blink()
class TryItYourself(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
It's actually an
edifying exercise.
""")
self.random_blink()
self.play_student_changes(*["pondering"]*3)
self.random_blink(2)
pi = self.get_students()[1]
bubble = pi.get_bubble(
"thought",
width = 4, height = 4,
direction = RIGHT
)
bubble.set_fill(BLACK, opacity = 1)
bubble.write("Orientation seem\\\\ to matter...")
self.play(
FadeIn(bubble),
Write(bubble.content)
)
self.random_blink(3)
class OneMoreAnimation(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
One more animation,
but first...
""")
self.play_student_changes(*["happy"]*3)
self.random_blink()
class PatreonThanks(Scene):
CONFIG = {
"specific_patrons" : [
"Loo Yu Jun",
"Tom",
"Othman Alikhan",
"Juan Batiz-Benet",
"Markus Persson",
"Joseph John Cox",
"Achille Brighton",
"Kirk Werklund",
"Luc Ritchie",
"Ripta Pasay",
"PatrickJMT ",
"Felipe Diniz",
]
}
def construct(self):
morty = Mortimer()
morty.next_to(ORIGIN, DOWN)
n_patrons = len(self.specific_patrons)
special_thanks = OldTexText("Special thanks to:")
special_thanks.set_color(YELLOW)
special_thanks.shift(2*UP)
left_patrons = VGroup(*list(map(TexText,
self.specific_patrons[:n_patrons/2]
)))
right_patrons = VGroup(*list(map(TexText,
self.specific_patrons[n_patrons/2:]
)))
for patrons, vect in (left_patrons, LEFT), (right_patrons, RIGHT):
patrons.arrange(DOWN, aligned_edge = LEFT)
patrons.next_to(special_thanks, DOWN)
patrons.to_edge(vect, buff = LARGE_BUFF)
self.play(morty.change_mode, "gracious")
self.play(Write(special_thanks, run_time = 1))
self.play(
Write(left_patrons),
morty.look_at, left_patrons
)
self.play(
Write(right_patrons),
morty.look_at, right_patrons
)
self.play(Blink(morty))
for patrons in left_patrons, right_patrons:
for index in 0, -1:
self.play(morty.look_at, patrons[index])
self.wait()
class CreditTWo(Scene):
def construct(self):
morty = Mortimer()
morty.next_to(ORIGIN, DOWN)
morty.to_edge(RIGHT)
brother = PiCreature(color = GOLD_E)
brother.next_to(morty, LEFT)
brother.look_at(morty.eyes)
headphones = Headphones(height = 1)
headphones.move_to(morty.eyes, aligned_edge = DOWN)
headphones.shift(0.1*DOWN)
url = OldTexText("www.audible.com/3b1b")
url.to_corner(UP+RIGHT, buff = LARGE_BUFF)
self.add(morty)
self.play(Blink(morty))
self.play(
FadeIn(headphones),
Write(url),
Animation(morty)
)
self.play(morty.change_mode, "happy")
self.wait()
self.play(Blink(morty))
self.wait()
self.play(
FadeIn(brother),
morty.look_at, brother.eyes
)
self.play(brother.change_mode, "surprised")
self.play(Blink(brother))
self.wait()
self.play(
morty.look, LEFT,
brother.change_mode, "happy",
brother.look, LEFT
)
self.play(Blink(morty))
self.wait()
class CreditThree(Scene):
def construct(self):
logo_dot = Dot().to_edge(UP).shift(3*RIGHT)
randy = Randolph()
randy.next_to(ORIGIN, DOWN)
randy.to_edge(LEFT)
randy.look(RIGHT)
self.add(randy)
bubble = randy.get_bubble(width = 2, height = 2)
domains = VGroup(*list(map(TexText, [
"visualnumbertheory.com",
"buymywidgets.com",
"learnwhatilearn.com",
])))
domains.arrange(DOWN, aligned_edge = LEFT)
domains.next_to(randy, UP, buff = LARGE_BUFF)
domains.shift_onto_screen()
promo_code = OldTexText("Promo code: TOPOLOGY")
promo_code.shift(3*RIGHT)
self.add(promo_code)
whois = OldTexText("Free WHOIS privacy")
whois.next_to(promo_code, DOWN, buff = LARGE_BUFF)
self.play(Blink(randy))
self.play(
randy.change_mode, "happy",
randy.look_at, logo_dot
)
self.wait()
self.play(
ShowCreation(bubble),
randy.change_mode, "pondering",
run_time = 2
)
self.play(Blink(randy))
self.play(
Transform(bubble, VectorizedPoint(randy.get_corner(UP+LEFT))),
randy.change_mode, "sad"
)
self.wait()
self.play(
Write(domains, run_time = 5),
randy.look_at, domains
)
self.wait()
self.play(Blink(randy))
self.play(
randy.change_mode, "hooray",
randy.look_at, logo_dot,
FadeOut(domains)
)
self.wait()
self.play(
Write(whois),
randy.change_mode, "confused",
randy.look_at, whois
)
self.wait(2)
self.play(randy.change_mode, "sassy")
self.wait(2)
self.play(
randy.change_mode, "happy",
randy.look_at, logo_dot
)
self.play(Blink(randy))
self.wait()
class ShiftingLoopPairSurface(Scene):
def construct(self):
pass
class ThumbnailImage(ClosedLoopScene):
def construct(self):
self.add_rect_dots(square = True)
for dot in self.dots:
dot.scale(1.5)
self.add_connecting_lines(cyclic = True)
self.connecting_lines.set_stroke(width = 10)
self.loop.add(self.connecting_lines, self.dots)
title = OldTexText("Unsolved")
title.scale(2.5)
title.to_edge(UP)
title.set_color_by_gradient(YELLOW, MAROON_B)
self.add(title)
self.loop.next_to(title, DOWN, buff = MED_SMALL_BUFF)
self.loop.shift(2*LEFT)
|
|
from manim_imports_ext import *
import mpmath
mpmath.mp.dps = 7
def zeta(z):
max_norm = FRAME_X_RADIUS
try:
return np.complex(mpmath.zeta(z))
except:
return np.complex(max_norm, 0)
def d_zeta(z):
epsilon = 0.01
return (zeta(z + epsilon) - zeta(z))/epsilon
class ComplexTransformationScene(Scene):
def construct(self):
pass
class ZetaTransformationScene(ComplexTransformationScene):
CONFIG = {
"anchor_density" : 35,
"min_added_anchors" : 10,
"max_added_anchors" : 300,
"num_anchors_to_add_per_line" : 75,
"post_transformation_stroke_width" : 2,
"default_apply_complex_function_kwargs" : {
"run_time" : 5,
},
"x_min" : 1,
"x_max" : int(FRAME_X_RADIUS+2),
"extra_lines_x_min" : -2,
"extra_lines_x_max" : 4,
"extra_lines_y_min" : -2,
"extra_lines_y_max" : 2,
}
def prepare_for_transformation(self, mob):
for line in mob.family_members_with_points():
#Find point of line cloest to 1 on C
if not isinstance(line, Line):
line.insert_n_curves(self.min_added_anchors)
continue
p1 = line.get_start()+LEFT
p2 = line.get_end()+LEFT
t = (-np.dot(p1, p2-p1))/(get_norm(p2-p1)**2)
closest_to_one = interpolate(
line.get_start(), line.get_end(), t
)
#See how big this line will become
diameter = abs(zeta(complex(*closest_to_one[:2])))
target_num_curves = np.clip(
int(self.anchor_density*np.pi*diameter),
self.min_added_anchors,
self.max_added_anchors,
)
num_curves = line.get_num_curves()
if num_curves < target_num_curves:
line.insert_n_curves(target_num_curves-num_curves)
line.make_smooth()
def add_extra_plane_lines_for_zeta(self, animate = False, **kwargs):
dense_grid = self.get_dense_grid(**kwargs)
if animate:
self.play(ShowCreation(dense_grid))
self.plane.add(dense_grid)
self.add(self.plane)
def get_dense_grid(self, step_size = 1./16):
epsilon = 0.1
x_range = np.arange(
max(self.x_min, self.extra_lines_x_min),
min(self.x_max, self.extra_lines_x_max),
step_size
)
y_range = np.arange(
max(self.y_min, self.extra_lines_y_min),
min(self.y_max, self.extra_lines_y_max),
step_size
)
vert_lines = VGroup(*[
Line(
self.y_min*UP,
self.y_max*UP,
).shift(x*RIGHT)
for x in x_range
if abs(x-1) > epsilon
])
vert_lines.set_color_by_gradient(
self.vert_start_color, self.vert_end_color
)
horiz_lines = VGroup(*[
Line(
self.x_min*RIGHT,
self.x_max*RIGHT,
).shift(y*UP)
for y in y_range
if abs(y) > epsilon
])
horiz_lines.set_color_by_gradient(
self.horiz_start_color, self.horiz_end_color
)
dense_grid = VGroup(horiz_lines, vert_lines)
dense_grid.set_stroke(width = 1)
return dense_grid
def add_reflected_plane(self, animate = False):
reflected_plane = self.get_reflected_plane()
if animate:
self.play(ShowCreation(reflected_plane, run_time = 5))
self.plane.add(reflected_plane)
self.add(self.plane)
def get_reflected_plane(self):
reflected_plane = self.plane.copy()
reflected_plane.rotate(np.pi, UP, about_point = RIGHT)
for mob in reflected_plane.family_members_with_points():
mob.set_color(
Color(rgb = 1-0.5*color_to_rgb(mob.get_color()))
)
self.prepare_for_transformation(reflected_plane)
reflected_plane.submobjects = list(reversed(
reflected_plane.family_members_with_points()
))
return reflected_plane
def apply_zeta_function(self, **kwargs):
transform_kwargs = dict(self.default_apply_complex_function_kwargs)
transform_kwargs.update(kwargs)
self.apply_complex_function(zeta, **kwargs)
class TestZetaOnHalfPlane(ZetaTransformationScene):
CONFIG = {
"anchor_density" : 15,
}
def construct(self):
self.add_transformable_plane()
self.add_extra_plane_lines_for_zeta()
self.prepare_for_transformation(self.plane)
print(sum([
mob.get_num_points()
for mob in self.plane.family_members_with_points()
]))
print(len(self.plane.family_members_with_points()))
self.apply_zeta_function()
self.wait()
class TestZetaOnFullPlane(ZetaTransformationScene):
def construct(self):
self.add_transformable_plane(animate = True)
self.add_extra_plane_lines_for_zeta(animate = True)
self.add_reflected_plane(animate = True)
self.apply_zeta_function()
class TestZetaOnLine(ZetaTransformationScene):
def construct(self):
line = Line(UP+20*LEFT, UP+20*RIGHT)
self.add_transformable_plane()
self.plane.submobjects = [line]
self.apply_zeta_function()
self.wait(2)
self.play(ShowCreation(line, run_time = 10))
self.wait(3)
######################
class IntroduceZeta(ZetaTransformationScene):
CONFIG = {
"default_apply_complex_function_kwargs" : {
"run_time" : 8,
}
}
def construct(self):
title = OldTexText("Riemann zeta function")
title.add_background_rectangle()
title.to_corner(UP+LEFT)
func_mob = VGroup(
OldTex("\\zeta(s) = "),
OldTex("\\sum_{n=1}^\\infty \\frac{1}{n^s}")
)
func_mob.arrange(RIGHT, buff = 0)
for submob in func_mob:
submob.add_background_rectangle()
func_mob.next_to(title, DOWN)
randy = Randolph().flip()
randy.to_corner(DOWN+RIGHT)
self.add_foreground_mobjects(title, func_mob)
self.add_transformable_plane()
self.add_extra_plane_lines_for_zeta()
self.play(ShowCreation(self.plane, run_time = 2))
reflected_plane = self.get_reflected_plane()
self.play(ShowCreation(reflected_plane, run_time = 2))
self.plane.add(reflected_plane)
self.wait()
self.apply_zeta_function()
self.wait(2)
self.play(FadeIn(randy))
self.play(
randy.change_mode, "confused",
randy.look_at, func_mob,
)
self.play(Blink(randy))
self.wait()
class WhyPeopleMayKnowIt(TeacherStudentsScene):
def construct(self):
title = OldTexText("Riemann zeta function")
title.to_corner(UP+LEFT)
func_mob = OldTex(
"\\zeta(s) = \\sum_{n=1}^\\infty \\frac{1}{n^s}"
)
func_mob.next_to(title, DOWN, aligned_edge = LEFT)
self.add(title, func_mob)
mercenary_thought = VGroup(
OldTex("\\$1{,}000{,}000").set_color_by_gradient(GREEN_B, GREEN_D),
OldTex("\\zeta(s) = 0")
)
mercenary_thought.arrange(DOWN)
divergent_sum = VGroup(
OldTex("1+2+3+4+\\cdots = -\\frac{1}{12}"),
OldTex("\\zeta(-1) = -\\frac{1}{12}")
)
divergent_sum.arrange(DOWN)
divergent_sum[0].set_color_by_gradient(YELLOW, MAROON_B)
divergent_sum[1].set_color(BLACK)
#Thoughts
self.play(*it.chain(*[
[pi.change_mode, "pondering", pi.look_at, func_mob]
for pi in self.get_pi_creatures()
]))
self.random_blink()
self.student_thinks(
mercenary_thought, index = 2,
target_mode = "surprised",
)
student = self.get_students()[2]
self.random_blink()
self.wait(2)
self.student_thinks(
divergent_sum, index = 1,
added_anims = [student.change_mode, "plain"]
)
student = self.get_students()[1]
self.play(
student.change_mode, "confused",
student.look_at, divergent_sum,
)
self.random_blink()
self.play(*it.chain(*[
[pi.change_mode, "confused", pi.look_at, divergent_sum]
for pi in self.get_pi_creatures()
]))
self.wait()
self.random_blink()
divergent_sum[1].set_color(WHITE)
self.play(Write(divergent_sum[1]))
self.random_blink()
self.wait()
#Ask about continuation
self.student_says(
OldTexText("Can you explain \\\\" , "``analytic continuation''?"),
index = 1,
target_mode = "raise_right_hand"
)
self.play_student_changes(
"raise_left_hand",
"raise_right_hand",
"raise_left_hand",
)
self.play(
self.get_teacher().change_mode, "happy",
self.get_teacher().look_at, student.eyes,
)
self.random_blink()
self.wait(2)
self.random_blink()
self.wait()
class ComplexValuedFunctions(ComplexTransformationScene):
def construct(self):
title = OldTexText("Complex-valued function")
title.scale(1.5)
title.add_background_rectangle()
title.to_edge(UP)
self.add(title)
z_in = Dot(UP+RIGHT, color = YELLOW)
z_out = Dot(4*RIGHT + 2*UP, color = MAROON_B)
arrow = Arrow(z_in, z_out, buff = 0.1)
arrow.set_color(WHITE)
z = OldTex("z").next_to(z_in, DOWN+LEFT, buff = SMALL_BUFF)
z.set_color(z_in.get_color())
f_z = OldTex("f(z)").next_to(z_out, UP+RIGHT, buff = SMALL_BUFF)
f_z.set_color(z_out.get_color())
self.add(z_in, z)
self.wait()
self.play(ShowCreation(arrow))
self.play(
ShowCreation(z_out),
Write(f_z)
)
self.wait(2)
class PreviewZetaAndContinuation(ZetaTransformationScene):
CONFIG = {
"default_apply_complex_function_kwargs" : {
"run_time" : 4,
}
}
def construct(self):
self.add_transformable_plane()
self.add_extra_plane_lines_for_zeta()
reflected_plane = self.get_reflected_plane()
titles = [
OldTexText(
"What does", "%s"%s,
"look like?",
alignment = "",
)
for s in [
"$\\displaystyle \\sum_{n=1}^\\infty \\frac{1}{n^s}$",
"analytic continuation"
]
]
for mob in titles:
mob[1].set_color(YELLOW)
mob.to_corner(UP+LEFT, buff = 0.7)
mob.add_background_rectangle()
self.remove(self.plane)
self.play(Write(titles[0], run_time = 2))
self.add_foreground_mobjects(titles[0])
self.play(FadeIn(self.plane))
self.apply_zeta_function()
reflected_plane.apply_complex_function(zeta)
reflected_plane.make_smooth()
reflected_plane.set_stroke(width = 2)
self.wait()
self.play(Transform(*titles))
self.wait()
self.play(ShowCreation(
reflected_plane,
lag_ratio = 0,
run_time = 2
))
self.wait()
class AssumeKnowledgeOfComplexNumbers(ComplexTransformationScene):
def construct(self):
z = complex(5, 2)
dot = Dot(z.real*RIGHT + z.imag*UP, color = YELLOW)
line = Line(ORIGIN, dot.get_center(), color = dot.get_color())
x_line = Line(ORIGIN, z.real*RIGHT, color = GREEN_B)
y_line = Line(ORIGIN, z.imag*UP, color = RED)
y_line.shift(z.real*RIGHT)
complex_number_label = OldTex(
"%d+%di"%(int(z.real), int(z.imag))
)
complex_number_label[0].set_color(x_line.get_color())
complex_number_label[2].set_color(y_line.get_color())
complex_number_label.next_to(dot, UP)
text = VGroup(
OldTexText("Assumed knowledge:"),
OldTexText("1) What complex numbers are."),
OldTexText("2) How to work with them."),
OldTexText("3) Maybe derivatives?"),
)
text.arrange(DOWN, aligned_edge = LEFT)
for words in text:
words.add_background_rectangle()
text[0].shift(LEFT)
text[-1].set_color(PINK)
text.to_corner(UP+LEFT)
self.play(Write(text[0]))
self.wait()
self.play(FadeIn(text[1]))
self.play(
ShowCreation(x_line),
ShowCreation(y_line),
ShowCreation(VGroup(line, dot)),
Write(complex_number_label),
)
self.play(Write(text[2]))
self.wait(2)
self.play(Write(text[3]))
self.wait()
self.play(text[3].fade)
class DefineForRealS(PiCreatureScene):
def construct(self):
zeta_def, s_group = self.get_definition("s")
self.initial_definition(zeta_def)
self.plug_in_two(zeta_def)
self.plug_in_three_and_four(zeta_def)
self.plug_in_negative_values(zeta_def)
def initial_definition(self, zeta_def):
zeta_s, sum_terms, brace, sigma = zeta_def
self.say("Let's define $\\zeta(s)$")
self.blink()
pre_zeta_s = VGroup(
*self.pi_creature.bubble.content.copy()[-4:]
)
pre_zeta_s.add(VectorizedPoint(pre_zeta_s.get_right()))
self.play(
Transform(pre_zeta_s, zeta_s),
*self.get_bubble_fade_anims()
)
self.remove(pre_zeta_s)
self.add(zeta_s)
self.wait()
for count, term in enumerate(sum_terms):
self.play(FadeIn(term), run_time = 0.5)
if count%2 == 0:
self.wait()
self.play(
GrowFromCenter(brace),
Write(sigma),
self.pi_creature.change_mode, "pondering"
)
self.wait()
def plug_in_two(self, zeta_def):
two_def = self.get_definition("2")[0]
number_line = NumberLine(
x_min = 0,
x_max = 3,
tick_frequency = 0.25,
numbers_with_elongated_ticks = list(range(4)),
unit_size = 3,
)
number_line.add_numbers()
number_line.next_to(self.pi_creature, LEFT)
number_line.to_edge(LEFT)
self.number_line = number_line
lines, braces, dots, pi_dot = self.get_sum_lines(2)
fracs = VGroup(*[
OldTex("\\frac{1}{%d}"%((d+1)**2)).scale(0.7)
for d, brace in enumerate(braces)
])
for frac, brace, line in zip(fracs, braces, lines):
frac.set_color(line.get_color())
frac.next_to(brace, UP, buff = SMALL_BUFF)
if frac is fracs[-1]:
frac.shift(0.5*RIGHT + 0.2*UP)
arrow = Arrow(
frac.get_bottom(), brace.get_top(),
tip_length = 0.1,
buff = 0.1
)
arrow.set_color(line.get_color())
frac.add(arrow)
pi_term = OldTex("= \\frac{\\pi^2}{6}")
pi_term.next_to(zeta_def[1], RIGHT)
pi_arrow = Arrow(
pi_term[-1].get_bottom(), pi_dot,
color = pi_dot.get_color()
)
approx = OldTex("\\approx 1.645")
approx.next_to(pi_term)
self.play(Transform(zeta_def, two_def))
self.wait()
self.play(ShowCreation(number_line))
for frac, brace, line in zip(fracs, braces, lines):
self.play(
Write(frac),
GrowFromCenter(brace),
ShowCreation(line),
run_time = 0.7
)
self.wait(0.7)
self.wait()
self.play(
ShowCreation(VGroup(*lines[4:])),
Write(dots)
)
self.wait()
self.play(
Write(pi_term),
ShowCreation(VGroup(pi_arrow, pi_dot)),
self.pi_creature.change_mode, "hooray"
)
self.wait()
self.play(
Write(approx),
self.pi_creature.change_mode, "happy"
)
self.wait(3)
self.play(*list(map(FadeOut, [
fracs, pi_arrow, pi_dot, approx,
])))
self.lines = lines
self.braces = braces
self.dots = dots
self.final_dot = pi_dot
self.final_sum = pi_term
def plug_in_three_and_four(self, zeta_def):
final_sums = ["1.202\\dots", "\\frac{\\pi^4}{90}"]
sum_terms, brace, sigma = zeta_def[1:]
for exponent, final_sum in zip([3, 4], final_sums):
self.transition_to_new_input(zeta_def, exponent, final_sum)
self.wait()
arrow = Arrow(sum_terms.get_left(), sum_terms.get_right())
arrow.next_to(sum_terms, DOWN)
smaller_words = OldTexText("Getting smaller")
smaller_words.next_to(arrow, DOWN)
self.arrow, self.smaller_words = arrow, smaller_words
self.wait()
self.play(
ShowCreation(arrow),
Write(smaller_words)
)
self.change_mode("happy")
self.wait(2)
def plug_in_negative_values(self, zeta_def):
zeta_s, sum_terms, brace, sigma = zeta_def
arrow = self.arrow
smaller_words = self.smaller_words
bigger_words = OldTexText("Getting \\emph{bigger}?")
bigger_words.move_to(self.smaller_words)
#plug in -1
self.transition_to_new_input(zeta_def, -1, "-\\frac{1}{12}")
self.play(
Transform(self.smaller_words, bigger_words),
self.pi_creature.change_mode, "confused"
)
new_sum_terms = OldTex(
list("1+2+3+4+") + ["\\cdots"]
)
new_sum_terms.move_to(sum_terms, LEFT)
arrow.target = arrow.copy().next_to(new_sum_terms, DOWN)
arrow.target.stretch_to_fit_width(new_sum_terms.get_width())
bigger_words.next_to(arrow.target, DOWN)
new_brace = Brace(new_sum_terms, UP)
self.play(
Transform(sum_terms, new_sum_terms),
Transform(brace, new_brace),
sigma.next_to, new_brace, UP,
MoveToTarget(arrow),
Transform(smaller_words, bigger_words),
self.final_sum.next_to, new_sum_terms, RIGHT
)
self.wait(3)
#plug in -2
new_sum_terms = OldTex(
list("1+4+9+16+") + ["\\cdots"]
)
new_sum_terms.move_to(sum_terms, LEFT)
new_zeta_def, ignore = self.get_definition("-2")
zeta_minus_two, ignore, ignore, new_sigma = new_zeta_def
new_sigma.next_to(brace, UP)
new_final_sum = OldTex("=0")
new_final_sum.next_to(new_sum_terms)
lines, braces, dots, final_dot = self.get_sum_lines(-2)
self.play(
Transform(zeta_s, zeta_minus_two),
Transform(sum_terms, new_sum_terms),
Transform(sigma, new_sigma),
Transform(self.final_sum, new_final_sum),
Transform(self.lines, lines),
Transform(self.braces, braces),
)
self.wait()
self.change_mode("pleading")
self.wait(2)
def get_definition(self, input_string, input_color = YELLOW):
inputs = VGroup()
num_shown_terms = 4
n_input_chars = len(input_string)
zeta_s_eq = OldTex("\\zeta(%s) = "%input_string)
zeta_s_eq.to_edge(LEFT, buff = LARGE_BUFF)
zeta_s_eq.shift(0.5*UP)
inputs.add(*zeta_s_eq[2:2+n_input_chars])
sum_terms = OldTex(*it.chain(*list(zip(
[
"\\frac{1}{%d^{%s}}"%(d, input_string)
for d in range(1, 1+num_shown_terms)
],
it.cycle(["+"])
))))
sum_terms.add(OldTex("\\cdots").next_to(sum_terms))
sum_terms.next_to(zeta_s_eq, RIGHT)
for x in range(num_shown_terms):
inputs.add(*sum_terms[2*x][-n_input_chars:])
brace = Brace(sum_terms, UP)
sigma = OldTex(
"\\sum_{n=1}^\\infty \\frac{1}{n^{%s}}"%input_string
)
sigma.next_to(brace, UP)
inputs.add(*sigma[-n_input_chars:])
inputs.set_color(input_color)
group = VGroup(zeta_s_eq, sum_terms, brace, sigma)
return group, inputs
def get_sum_lines(self, exponent, line_thickness = 6):
num_lines = 100 if exponent > 0 else 6
powers = [0] + [x**(-exponent) for x in range(1, num_lines)]
power_sums = np.cumsum(powers)
lines = VGroup(*[
Line(
self.number_line.number_to_point(s1),
self.number_line.number_to_point(s2),
)
for s1, s2 in zip(power_sums, power_sums[1:])
])
lines.set_stroke(width = line_thickness)
# VGroup(*lines[:4]).set_color_by_gradient(RED, GREEN_B)
# VGroup(*lines[4:]).set_color_by_gradient(GREEN_B, MAROON_B)
VGroup(*lines[::2]).set_color(MAROON_B)
VGroup(*lines[1::2]).set_color(RED)
braces = VGroup(*[
Brace(line, UP)
for line in lines[:4]
])
dots = OldTex("...")
dots.stretch_to_fit_width(
0.8 * VGroup(*lines[4:]).get_width()
)
dots.next_to(braces, RIGHT, buff = SMALL_BUFF)
final_dot = Dot(
self.number_line.number_to_point(power_sums[-1]),
color = GREEN_B
)
return lines, braces, dots, final_dot
def transition_to_new_input(self, zeta_def, exponent, final_sum):
new_zeta_def = self.get_definition(str(exponent))[0]
lines, braces, dots, final_dot = self.get_sum_lines(exponent)
final_sum = OldTex("=" + final_sum)
final_sum.next_to(new_zeta_def[1][-1])
final_sum.shift(SMALL_BUFF*UP)
self.play(
Transform(zeta_def, new_zeta_def),
Transform(self.lines, lines),
Transform(self.braces, braces),
Transform(self.dots, dots),
Transform(self.final_dot, final_dot),
Transform(self.final_sum, final_sum),
self.pi_creature.change_mode, "pondering"
)
class ReadIntoZetaFunction(Scene):
CONFIG = {
"statement" : "$\\zeta(-1) = -\\frac{1}{12}$",
"target_mode" : "frustrated",
}
def construct(self):
randy = Randolph(mode = "pondering")
randy.shift(3*LEFT+DOWN)
paper = Rectangle(width = 4, height = 5)
paper.next_to(randy, RIGHT, aligned_edge = DOWN)
paper.set_color(WHITE)
max_width = 0.8*paper.get_width()
title = OldTexText("$\\zeta(s)$ manual")
title.next_to(paper.get_top(), DOWN)
title.set_color(YELLOW)
paper.add(title)
paragraph_lines = VGroup(
Line(LEFT, RIGHT),
Line(LEFT, RIGHT).shift(0.2*DOWN),
Line(LEFT, ORIGIN).shift(0.4*DOWN)
)
paragraph_lines.set_width(max_width)
paragraph_lines.next_to(title, DOWN, MED_LARGE_BUFF)
paper.add(paragraph_lines)
max_height = 1.5*paragraph_lines.get_height()
statement = OldTexText(self.statement)
if statement.get_width() > max_width:
statement.set_width(max_width)
if statement.get_height() > max_height:
statement.set_height(max_height)
statement.next_to(paragraph_lines, DOWN)
statement.set_color(GREEN_B)
paper.add(paragraph_lines.copy().next_to(statement, DOWN, MED_LARGE_BUFF))
randy.look_at(statement)
self.add(randy, paper)
self.play(Write(statement))
self.play(
randy.change_mode, self.target_mode,
randy.look_at, title
)
self.play(Blink(randy))
self.play(randy.look_at, statement)
self.wait()
class ReadIntoZetaFunctionTrivialZero(ReadIntoZetaFunction):
CONFIG = {
"statement" : "$\\zeta(-2n) = 0$"
}
class ReadIntoZetaFunctionAnalyticContinuation(ReadIntoZetaFunction):
CONFIG = {
"statement" : "...analytic \\\\ continuation...",
"target_mode" : "confused",
}
class IgnoreNegatives(TeacherStudentsScene):
def construct(self):
definition = OldTex("""
\\zeta(s) = \\sum_{n=1}^{\\infty} \\frac{1}{n^s}
""")
VGroup(definition[2], definition[-1]).set_color(YELLOW)
definition.to_corner(UP+LEFT)
self.add(definition)
brace = Brace(definition, DOWN)
only_s_gt_1 = brace.get_text("""
Only defined
for $s > 1$
""")
only_s_gt_1[-3].set_color(YELLOW)
self.play_student_changes(*["confused"]*3)
words = OldTexText(
"Ignore $s \\le 1$ \\dots \\\\",
"For now."
)
words[0][6].set_color(YELLOW)
words[1].set_color(BLACK)
self.teacher_says(words)
self.play(words[1].set_color, WHITE)
self.play_student_changes(*["happy"]*3)
self.play(
GrowFromCenter(brace),
Write(only_s_gt_1),
*it.chain(*[
[pi.look_at, definition]
for pi in self.get_pi_creatures()
])
)
self.random_blink(3)
class RiemannFatherOfComplex(ComplexTransformationScene):
def construct(self):
name = OldTexText(
"Bernhard Riemann $\\rightarrow$ Complex analysis"
)
name.to_corner(UP+LEFT)
name.shift(0.25*DOWN)
name.add_background_rectangle()
# photo = Square()
photo = ImageMobject("Riemann", invert = False)
photo.set_width(5)
photo.next_to(name, DOWN, aligned_edge = LEFT)
self.add(photo)
self.play(Write(name))
self.wait()
input_dot = Dot(2*RIGHT+UP, color = YELLOW)
arc = Arc(-2*np.pi/3)
arc.rotate(-np.pi)
arc.add_tip()
arc.shift(input_dot.get_top()-arc.get_points()[0]+SMALL_BUFF*UP)
output_dot = Dot(
arc.get_points()[-1] + SMALL_BUFF*(2*RIGHT+DOWN),
color = MAROON_B
)
for dot, tex in (input_dot, "z"), (output_dot, "f(z)"):
dot.label = OldTex(tex)
dot.label.add_background_rectangle()
dot.label.next_to(dot, DOWN+RIGHT, buff = SMALL_BUFF)
dot.label.set_color(dot.get_color())
self.play(
ShowCreation(input_dot),
Write(input_dot.label)
)
self.play(ShowCreation(arc))
self.play(
ShowCreation(output_dot),
Write(output_dot.label)
)
self.wait()
class FromRealToComplex(ComplexTransformationScene):
CONFIG = {
"plane_config" : {
"space_unit_to_x_unit" : 2,
"space_unit_to_y_unit" : 2,
},
"background_label_scale_val" : 0.7,
"output_color" : GREEN_B,
"num_lines_in_spiril_sum" : 1000,
}
def construct(self):
self.handle_background()
self.show_real_to_real()
self.transition_to_complex()
self.single_out_complex_exponent()
##Fade to several scenes defined below
self.show_s_equals_two_lines()
self.transition_to_spiril_sum()
self.vary_complex_input()
self.show_domain_of_convergence()
self.ask_about_visualizing_all()
def handle_background(self):
self.remove(self.background)
#Oh yeah, this is great practice...
self.background[-1].remove(*self.background[-1][-3:])
def show_real_to_real(self):
zeta = self.get_zeta_definition("2", "\\frac{\\pi^2}{6}")
number_line = NumberLine(
unit_size = 2,
tick_frequency = 0.5,
numbers_with_elongated_ticks = list(range(-2, 3))
)
number_line.add_numbers()
input_dot = Dot(number_line.number_to_point(2))
input_dot.set_color(YELLOW)
output_dot = Dot(number_line.number_to_point(np.pi**2/6))
output_dot.set_color(self.output_color)
arc = Arc(
2*np.pi/3, start_angle = np.pi/6,
)
arc.stretch_to_fit_width(
(input_dot.get_center()-output_dot.get_center())[0]
)
arc.stretch_to_fit_height(0.5)
arc.next_to(input_dot.get_center(), UP, aligned_edge = RIGHT)
arc.add_tip()
two = zeta[1][2].copy()
sum_term = zeta[-1]
self.add(number_line, *zeta[:-1])
self.wait()
self.play(Transform(two, input_dot))
self.remove(two)
self.add(input_dot)
self.play(ShowCreation(arc))
self.play(ShowCreation(output_dot))
self.play(Transform(output_dot.copy(), sum_term))
self.remove(*self.get_mobjects_from_last_animation())
self.add(sum_term)
self.wait(2)
self.play(
ShowCreation(
self.background,
run_time = 2
),
FadeOut(VGroup(arc, output_dot, number_line)),
Animation(zeta),
Animation(input_dot)
)
self.wait(2)
self.zeta = zeta
self.input_dot = input_dot
def transition_to_complex(self):
complex_zeta = self.get_zeta_definition("2+i", "???")
input_dot = self.input_dot
input_dot.generate_target()
input_dot.target.move_to(
self.background.num_pair_to_point((2, 1))
)
input_label = OldTex("2+i")
input_label.set_color(YELLOW)
input_label.next_to(input_dot.target, DOWN+RIGHT, buff = SMALL_BUFF)
input_label.add_background_rectangle()
input_label.save_state()
input_label.replace(VGroup(*complex_zeta[1][2:5]))
input_label.background_rectangle.scale(0.01)
self.input_label = input_label
self.play(Transform(self.zeta, complex_zeta))
self.wait()
self.play(
input_label.restore,
MoveToTarget(input_dot)
)
self.wait(2)
def single_out_complex_exponent(self):
frac_scale_factor = 1.2
randy = Randolph()
randy.to_corner()
bubble = randy.get_bubble(height = 4)
bubble.set_fill(BLACK, opacity = 1)
frac = VGroup(
VectorizedPoint(self.zeta[2][3].get_left()),
self.zeta[2][3],
VectorizedPoint(self.zeta[2][3].get_right()),
self.zeta[2][4],
).copy()
frac.generate_target()
frac.target.scale(frac_scale_factor)
bubble.add_content(frac.target)
new_frac = OldTex(
"\\Big(", "\\frac{1}{2}", "\\Big)", "^{2+i}"
)
new_frac[-1].set_color(YELLOW)
new_frac.scale(frac_scale_factor)
new_frac.move_to(frac.target)
new_frac.shift(LEFT+0.2*UP)
words = OldTexText("Not repeated \\\\", " multiplication")
words.scale(0.8)
words.set_color(RED)
words.next_to(new_frac, RIGHT)
new_words = OldTexText("Not \\emph{super} \\\\", "crucial to know...")
new_words.replace(words)
new_words.scale(1.3)
self.play(FadeIn(randy))
self.play(
randy.change_mode, "confused",
randy.look_at, bubble,
ShowCreation(bubble),
MoveToTarget(frac)
)
self.play(Blink(randy))
self.play(Transform(frac, new_frac))
self.play(Write(words))
for x in range(2):
self.wait(2)
self.play(Blink(randy))
self.play(
Transform(words, new_words),
randy.change_mode, "maybe"
)
self.wait()
self.play(Blink(randy))
self.play(randy.change_mode, "happy")
self.wait()
self.play(*list(map(FadeOut, [randy, bubble, frac, words])))
def show_s_equals_two_lines(self):
self.input_label.save_state()
zeta = self.get_zeta_definition("2", "\\frac{\\pi^2}{6}")
lines, output_dot = self.get_sum_lines(2)
sum_terms = self.zeta[2][:-1:3]
dots_copy = zeta[2][-1].copy()
pi_copy = zeta[3].copy()
def transform_and_replace(m1, m2):
self.play(Transform(m1, m2))
self.remove(m1)
self.add(m2)
self.play(
self.input_dot.shift, 2*DOWN,
self.input_label.fade, 0.7,
)
self.play(Transform(self.zeta, zeta))
for term, line in zip(sum_terms, lines):
line.save_state()
line.next_to(term, DOWN)
term_copy = term.copy()
transform_and_replace(term_copy, line)
self.play(line.restore)
later_lines = VGroup(*lines[4:])
transform_and_replace(dots_copy, later_lines)
self.wait()
transform_and_replace(pi_copy, output_dot)
self.wait()
self.lines = lines
self.output_dot = output_dot
def transition_to_spiril_sum(self):
zeta = self.get_zeta_definition("2+i", "1.15 - 0.44i")
zeta.set_width(FRAME_WIDTH-1)
zeta.to_corner(UP+LEFT)
lines, output_dot = self.get_sum_lines(complex(2, 1))
self.play(
self.input_dot.shift, 2*UP,
self.input_label.restore,
)
self.wait()
self.play(Transform(self.zeta, zeta))
self.wait()
self.play(
Transform(self.lines, lines),
Transform(self.output_dot, output_dot),
run_time = 2,
path_arc = -np.pi/6,
)
self.wait()
def vary_complex_input(self):
zeta = self.get_zeta_definition("s", "")
zeta[3].set_color(BLACK)
self.play(Transform(self.zeta, zeta))
self.play(FadeOut(self.input_label))
self.wait(2)
inputs = [
complex(1.5, 1.8),
complex(1.5, -1),
complex(3, -1),
complex(1.5, 1.8),
complex(1.5, -1.8),
complex(1.4, -1.8),
complex(1.5, 0),
complex(2, 1),
]
for s in inputs:
input_point = self.z_to_point(s)
lines, output_dot = self.get_sum_lines(s)
self.play(
self.input_dot.move_to, input_point,
Transform(self.lines, lines),
Transform(self.output_dot, output_dot),
run_time = 2
)
self.wait()
self.wait()
def show_domain_of_convergence(self, opacity = 0.2):
domain = Rectangle(
width = FRAME_X_RADIUS-2,
height = FRAME_HEIGHT,
stroke_width = 0,
fill_color = YELLOW,
fill_opacity = opacity,
)
domain.to_edge(RIGHT, buff = 0)
anti_domain = Rectangle(
width = FRAME_X_RADIUS+2,
height = FRAME_HEIGHT,
stroke_width = 0,
fill_color = RED,
fill_opacity = opacity,
)
anti_domain.to_edge(LEFT, buff = 0)
domain_words = OldTexText("""
$\\zeta(s)$ happily
converges and
makes sense
""")
domain_words.to_corner(UP+RIGHT, buff = MED_LARGE_BUFF)
anti_domain_words = OldTexText("""
Not so much...
""")
anti_domain_words.next_to(ORIGIN, LEFT, buff = LARGE_BUFF)
anti_domain_words.shift(1.5*DOWN)
self.play(FadeIn(domain))
self.play(Write(domain_words))
self.wait()
self.play(FadeIn(anti_domain))
self.play(Write(anti_domain_words))
self.wait(2)
self.play(*list(map(FadeOut, [
anti_domain, anti_domain_words,
])))
self.domain_words = domain_words
def ask_about_visualizing_all(self):
morty = Mortimer().flip()
morty.scale(0.7)
morty.to_corner(DOWN+LEFT)
bubble = morty.get_bubble(SpeechBubble, height = 4)
bubble.set_fill(BLACK, opacity = 0.5)
bubble.write("""
How can we visualize
this for all inputs?
""")
self.play(FadeIn(morty))
self.play(
morty.change_mode, "speaking",
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(morty))
self.wait(3)
self.play(
morty.change_mode, "pondering",
morty.look_at, self.input_dot,
*list(map(FadeOut, [
bubble, bubble.content, self.domain_words
]))
)
arrow = Arrow(self.input_dot, self.output_dot, buff = SMALL_BUFF)
arrow.set_color(WHITE)
self.play(ShowCreation(arrow))
self.play(Blink(morty))
self.wait()
def get_zeta_definition(self, input_string, output_string, input_color = YELLOW):
inputs = VGroup()
num_shown_terms = 4
n_input_chars = len(input_string)
zeta_s_eq = OldTex("\\zeta(%s) = "%input_string)
zeta_s_eq.to_edge(LEFT, buff = LARGE_BUFF)
zeta_s_eq.shift(0.5*UP)
inputs.add(*zeta_s_eq[2:2+n_input_chars])
raw_sum_terms = OldTex(*[
"\\frac{1}{%d^{%s}} + "%(d, input_string)
for d in range(1, 1+num_shown_terms)
])
sum_terms = VGroup(*it.chain(*[
[
VGroup(*term[:3]),
VGroup(*term[3:-1]),
term[-1],
]
for term in raw_sum_terms
]))
sum_terms.add(OldTex("\\cdots").next_to(sum_terms[-1]))
sum_terms.next_to(zeta_s_eq, RIGHT)
for x in range(num_shown_terms):
inputs.add(*sum_terms[3*x+1])
output = OldTex("= \\," + output_string)
output.next_to(sum_terms, RIGHT)
output.set_color(self.output_color)
inputs.set_color(input_color)
group = VGroup(zeta_s_eq, sum_terms, output)
group.to_edge(UP)
group.add_to_back(BackgroundRectangle(group))
return group
def get_sum_lines(self, exponent, line_thickness = 6):
powers = [0] + [
x**(-exponent)
for x in range(1, self.num_lines_in_spiril_sum)
]
power_sums = np.cumsum(powers)
lines = VGroup(*[
Line(*list(map(self.z_to_point, z_pair)))
for z_pair in zip(power_sums, power_sums[1:])
])
widths = np.linspace(line_thickness, 0, len(list(lines)))
for line, width in zip(lines, widths):
line.set_stroke(width = width)
VGroup(*lines[::2]).set_color(MAROON_B)
VGroup(*lines[1::2]).set_color(RED)
final_dot = Dot(
# self.z_to_point(power_sums[-1]),
self.z_to_point(zeta(exponent)),
color = self.output_color
)
return lines, final_dot
class TerritoryOfExponents(ComplexTransformationScene):
def construct(self):
self.add_title()
familiar_territory = OldTexText("Familiar territory")
familiar_territory.set_color(YELLOW)
familiar_territory.next_to(ORIGIN, UP+RIGHT)
familiar_territory.shift(2*UP)
real_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
real_line.set_color(YELLOW)
arrow1 = Arrow(familiar_territory.get_bottom(), real_line.get_left())
arrow2 = Arrow(familiar_territory.get_bottom(), real_line.get_right())
VGroup(arrow1, arrow2).set_color(WHITE)
extended_realm = OldTexText("Extended realm")
extended_realm.move_to(familiar_territory)
full_plane = Rectangle(
width = FRAME_WIDTH,
height = FRAME_HEIGHT,
fill_color = YELLOW,
fill_opacity = 0.3
)
self.add(familiar_territory)
self.play(ShowCreation(arrow1))
self.play(
Transform(arrow1, arrow2),
ShowCreation(real_line)
)
self.play(FadeOut(arrow1))
self.play(
FadeIn(full_plane),
Transform(familiar_territory, extended_realm),
Animation(real_line)
)
def add_title(self):
exponent = OldTex(
"\\left(\\frac{1}{2}\\right)^s"
)
exponent[-1].set_color(YELLOW)
exponent.next_to(ORIGIN, LEFT, MED_LARGE_BUFF).to_edge(UP)
self.add_foreground_mobjects(exponent)
class ComplexExponentiation(Scene):
def construct(self):
self.extract_pure_imaginary_part()
self.add_on_planes()
self.show_imaginary_powers()
def extract_pure_imaginary_part(self):
original = OldTex(
"\\left(\\frac{1}{2}\\right)", "^{2+i}"
)
split = OldTex(
"\\left(\\frac{1}{2}\\right)", "^{2}",
"\\left(\\frac{1}{2}\\right)", "^{i}",
)
VGroup(original[-1], split[1], split[3]).set_color(YELLOW)
VGroup(original, split).shift(UP)
real_part = VGroup(*split[:2])
imag_part = VGroup(*split[2:])
brace = Brace(real_part)
we_understand = brace.get_text(
"We understand this"
)
VGroup(brace, we_understand).set_color(GREEN_B)
self.add(original)
self.wait()
self.play(*[
Transform(*pair)
for pair in [
(original[0], split[0]),
(original[1][0], split[1]),
(original[0].copy(), split[2]),
(VGroup(*original[1][1:]), split[3]),
]
])
self.remove(*self.get_mobjects_from_last_animation())
self.add(real_part, imag_part)
self.wait()
self.play(
GrowFromCenter(brace),
FadeIn(we_understand),
real_part.set_color, GREEN_B
)
self.wait()
self.play(
imag_part.move_to, imag_part.get_left(),
*list(map(FadeOut, [brace, we_understand, real_part]))
)
self.wait()
self.imag_exponent = imag_part
def add_on_planes(self):
left_plane = NumberPlane(x_radius = (FRAME_X_RADIUS-1)/2)
left_plane.to_edge(LEFT, buff = 0)
imag_line = Line(DOWN, UP).scale(FRAME_Y_RADIUS)
imag_line.set_color(YELLOW).fade(0.3)
imag_line.move_to(left_plane.get_center())
left_plane.add(imag_line)
left_title = OldTexText("Input space")
left_title.add_background_rectangle()
left_title.set_color(YELLOW)
left_title.next_to(left_plane.get_top(), DOWN)
right_plane = NumberPlane(x_radius = (FRAME_X_RADIUS-1)/2)
right_plane.to_edge(RIGHT, buff = 0)
unit_circle = Circle()
unit_circle.set_color(MAROON_B).fade(0.3)
unit_circle.shift(right_plane.get_center())
right_plane.add(unit_circle)
right_title = OldTexText("Output space")
right_title.add_background_rectangle()
right_title.set_color(MAROON_B)
right_title.next_to(right_plane.get_top(), DOWN)
for plane in left_plane, right_plane:
labels = VGroup()
for x in range(-2, 3):
label = OldTex(str(x))
label.move_to(plane.num_pair_to_point((x, 0)))
labels.add(label)
for y in range(-3, 4):
if y == 0:
continue
label = OldTex(str(y) + "i")
label.move_to(plane.num_pair_to_point((0, y)))
labels.add(label)
for label in labels:
label.scale(0.5)
label.next_to(
label.get_center(), DOWN+RIGHT,
buff = SMALL_BUFF
)
plane.add(labels)
arrow = Arrow(LEFT, RIGHT)
self.play(
ShowCreation(left_plane),
Write(left_title),
run_time = 3
)
self.play(
ShowCreation(right_plane),
Write(right_title),
run_time = 3
)
self.play(ShowCreation(arrow))
self.wait()
self.left_plane = left_plane
self.right_plane = right_plane
def show_imaginary_powers(self):
i = complex(0, 1)
input_dot = Dot(self.z_to_point(i))
input_dot.set_color(YELLOW)
output_dot = Dot(self.z_to_point(0.5**(i), is_input = False))
output_dot.set_color(MAROON_B)
output_dot.save_state()
output_dot.move_to(input_dot)
output_dot.set_color(input_dot.get_color())
curr_base = 0.5
def output_dot_update(ouput_dot):
y = input_dot.get_center()[1]
output_dot.move_to(self.z_to_point(
curr_base**complex(0, y), is_input = False
))
return output_dot
def walk_up_and_down():
for vect in 3*DOWN, 5*UP, 5*DOWN, 2*UP:
self.play(
input_dot.shift, vect,
UpdateFromFunc(output_dot, output_dot_update),
run_time = 3
)
exp = self.imag_exponent[-1]
new_exp = OldTex("ti")
new_exp.set_color(exp.get_color())
new_exp.set_height(exp.get_height())
new_exp.move_to(exp, LEFT)
nine = OldTex("9")
nine.set_color(BLUE)
denom = self.imag_exponent[0][3]
denom.save_state()
nine.replace(denom)
self.play(Transform(exp, new_exp))
self.play(input_dot.shift, 2*UP)
self.play(input_dot.shift, 2*DOWN)
self.wait()
self.play(output_dot.restore)
self.wait()
walk_up_and_down()
self.wait()
curr_base = 1./9
self.play(Transform(denom, nine))
walk_up_and_down()
self.wait()
def z_to_point(self, z, is_input = True):
if is_input:
plane = self.left_plane
else:
plane = self.right_plane
return plane.num_pair_to_point((z.real, z.imag))
class SizeAndRotationBreakdown(Scene):
def construct(self):
original = OldTex(
"\\left(\\frac{1}{2}\\right)", "^{2+i}"
)
split = OldTex(
"\\left(\\frac{1}{2}\\right)", "^{2}",
"\\left(\\frac{1}{2}\\right)", "^{i}",
)
VGroup(original[-1], split[1], split[3]).set_color(YELLOW)
VGroup(original, split).shift(UP)
real_part = VGroup(*split[:2])
imag_part = VGroup(*split[2:])
size_brace = Brace(real_part)
size = size_brace.get_text("Size")
rotation_brace = Brace(imag_part, UP)
rotation = rotation_brace.get_text("Rotation")
self.add(original)
self.wait()
self.play(*[
Transform(*pair)
for pair in [
(original[0], split[0]),
(original[1][0], split[1]),
(original[0].copy(), split[2]),
(VGroup(*original[1][1:]), split[3]),
]
])
self.play(
GrowFromCenter(size_brace),
Write(size)
)
self.play(
GrowFromCenter(rotation_brace),
Write(rotation)
)
self.wait()
class SeeLinksInDescription(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
See links in the
description for more.
""")
self.play(*it.chain(*[
[pi.change_mode, "hooray", pi.look, DOWN]
for pi in self.get_students()
]))
self.random_blink(3)
class ShowMultiplicationOfRealAndImaginaryExponentialParts(FromRealToComplex):
def construct(self):
self.break_up_exponent()
self.show_multiplication()
def break_up_exponent(self):
original = OldTex(
"\\left(\\frac{1}{2}\\right)", "^{2+i}"
)
split = OldTex(
"\\left(\\frac{1}{2}\\right)", "^{2}",
"\\left(\\frac{1}{2}\\right)", "^{i}",
)
VGroup(original[-1], split[1], split[3]).set_color(YELLOW)
VGroup(original, split).to_corner(UP+LEFT)
rect = BackgroundRectangle(split)
real_part = VGroup(*split[:2])
imag_part = VGroup(*split[2:])
self.add(rect, original)
self.wait()
self.play(*[
Transform(*pair)
for pair in [
(original[0], split[0]),
(original[1][0], split[1]),
(original[0].copy(), split[2]),
(VGroup(*original[1][1:]), split[3]),
]
])
self.remove(*self.get_mobjects_from_last_animation())
self.add(real_part, imag_part)
self.wait()
self.real_part = real_part
self.imag_part = imag_part
def show_multiplication(self):
real_part = self.real_part.copy()
imag_part = self.imag_part.copy()
for part in real_part, imag_part:
part.add_to_back(BackgroundRectangle(part))
fourth_point = self.z_to_point(0.25)
fourth_line = Line(ORIGIN, fourth_point)
brace = Brace(fourth_line, UP, buff = SMALL_BUFF)
fourth_dot = Dot(fourth_point)
fourth_group = VGroup(fourth_line, brace, fourth_dot)
fourth_group.set_color(RED)
circle = Circle(radius = 2, color = MAROON_B)
circle.fade(0.3)
imag_power_point = self.z_to_point(0.5**complex(0, 1))
imag_power_dot = Dot(imag_power_point)
imag_power_line = Line(ORIGIN, imag_power_point)
VGroup(imag_power_dot, imag_power_line).set_color(MAROON_B)
full_power_tex = OldTex(
"\\left(\\frac{1}{2}\\right)", "^{2+i}"
)
full_power_tex[-1].set_color(YELLOW)
full_power_tex.add_background_rectangle()
full_power_tex.scale(0.7)
full_power_tex.next_to(
0.5*self.z_to_point(0.5**complex(2, 1)),
UP+RIGHT
)
self.play(
real_part.scale, 0.7,
real_part.next_to, brace, UP, SMALL_BUFF, LEFT,
ShowCreation(fourth_dot)
)
self.play(
GrowFromCenter(brace),
ShowCreation(fourth_line),
)
self.wait()
self.play(
imag_part.scale, 0.7,
imag_part.next_to, imag_power_dot, DOWN+RIGHT, SMALL_BUFF,
ShowCreation(imag_power_dot)
)
self.play(ShowCreation(circle), Animation(imag_power_dot))
self.play(ShowCreation(imag_power_line))
self.wait(2)
self.play(
fourth_group.rotate, imag_power_line.get_angle()
)
real_part.generate_target()
imag_part.generate_target()
real_part.target.next_to(brace, UP+RIGHT, buff = 0)
imag_part.target.next_to(real_part.target, buff = 0)
self.play(*list(map(MoveToTarget, [real_part, imag_part])))
self.wait()
class ComplexFunctionsAsTransformations(ComplexTransformationScene):
def construct(self):
self.add_title()
input_dots, output_dots, arrows = self.get_dots()
self.play(FadeIn(
input_dots,
run_time = 2,
lag_ratio = 0.5
))
for in_dot, out_dot, arrow in zip(input_dots, output_dots, arrows):
self.play(
Transform(in_dot.copy(), out_dot),
ShowCreation(arrow)
)
self.wait()
self.wait()
def add_title(self):
title = OldTexText("Complex functions as transformations")
title.add_background_rectangle()
title.to_edge(UP)
self.add(title)
def get_dots(self):
input_points = [
RIGHT+2*UP,
4*RIGHT+DOWN,
2*LEFT+2*UP,
LEFT+DOWN,
6*LEFT+DOWN,
]
output_nudges = [
DOWN+RIGHT,
2*UP+RIGHT,
2*RIGHT+2*DOWN,
2*RIGHT+DOWN,
RIGHT+2*UP,
]
input_dots = VGroup(*list(map(Dot, input_points)))
input_dots.set_color(YELLOW)
output_dots = VGroup(*[
Dot(ip + on)
for ip, on in zip(input_points, output_nudges)
])
output_dots.set_color(MAROON_B)
arrows = VGroup(*[
Arrow(in_dot, out_dot, buff = 0.1, color = WHITE)
for in_dot, out_dot, in zip(input_dots, output_dots)
])
for i, dot in enumerate(input_dots):
label = OldTex("s_%d"%i)
label.set_color(dot.get_color())
label.next_to(dot, DOWN+LEFT, buff = SMALL_BUFF)
dot.add(label)
for i, dot in enumerate(output_dots):
label = OldTex("f(s_%d)"%i)
label.set_color(dot.get_color())
label.next_to(dot, UP+RIGHT, buff = SMALL_BUFF)
dot.add(label)
return input_dots, output_dots, arrows
class VisualizingSSquared(ComplexTransformationScene):
CONFIG = {
"num_anchors_to_add_per_line" : 100,
"horiz_end_color" : GOLD,
"y_min" : 0,
}
def construct(self):
self.add_title()
self.plug_in_specific_values()
self.show_transformation()
self.comment_on_two_dimensions()
def add_title(self):
title = OldTex("f(", "s", ") = ", "s", "^2")
title.set_color_by_tex("s", YELLOW)
title.add_background_rectangle()
title.scale(1.5)
title.to_corner(UP+LEFT)
self.play(Write(title))
self.add_foreground_mobject(title)
self.wait()
self.title = title
def plug_in_specific_values(self):
inputs = list(map(complex, [2, -1, complex(0, 1)]))
input_dots = VGroup(*[
Dot(self.z_to_point(z), color = YELLOW)
for z in inputs
])
output_dots = VGroup(*[
Dot(self.z_to_point(z**2), color = BLUE)
for z in inputs
])
arrows = VGroup()
VGroup(*[
ParametricCurve(
lambda t : self.z_to_point(z**(1.1+0.8*t))
)
for z in inputs
])
for z, dot in zip(inputs, input_dots):
path = ParametricCurve(
lambda t : self.z_to_point(z**(1+t))
)
dot.path = path
arrow = ParametricCurve(
lambda t : self.z_to_point(z**(1.1+0.8*t))
)
stand_in_arrow = Arrow(
arrow.get_points()[-2], arrow.get_points()[-1],
tip_length = 0.2
)
arrow.add(stand_in_arrow.tip)
arrows.add(arrow)
arrows.set_color(WHITE)
for input_dot, output_dot, arrow in zip(input_dots, output_dots, arrows):
input_dot.save_state()
input_dot.move_to(self.title[1][1])
input_dot.set_fill(opacity = 0)
self.play(input_dot.restore)
self.wait()
self.play(ShowCreation(arrow))
self.play(ShowCreation(output_dot))
self.wait()
self.add_foreground_mobjects(arrows, output_dots, input_dots)
self.input_dots = input_dots
self.output_dots = output_dots
def add_transformable_plane(self, **kwargs):
ComplexTransformationScene.add_transformable_plane(self, **kwargs)
self.plane.next_to(ORIGIN, UP, buff = 0.01)
self.plane.add(self.plane.copy().rotate(np.pi, RIGHT))
self.plane.add(
Line(ORIGIN, FRAME_X_RADIUS*RIGHT, color = self.horiz_end_color),
Line(ORIGIN, FRAME_X_RADIUS*LEFT, color = self.horiz_end_color),
)
self.add(self.plane)
def show_transformation(self):
self.add_transformable_plane()
self.play(ShowCreation(self.plane, run_time = 3))
self.wait()
self.apply_complex_homotopy(
lambda z, t : z**(1+t),
added_anims = [
MoveAlongPath(dot, dot.path, run_time = 5)
for dot in self.input_dots
],
run_time = 5
)
self.wait(2)
def comment_on_two_dimensions(self):
morty = Mortimer().flip()
morty.scale(0.7)
morty.to_corner(DOWN+LEFT)
bubble = morty.get_bubble(SpeechBubble, height = 2, width = 4)
bubble.set_fill(BLACK, opacity = 0.9)
bubble.write("""
It all happens
in two dimensions!
""")
self.foreground_mobjects = []
self.play(FadeIn(morty))
self.play(
morty.change_mode, "hooray",
ShowCreation(bubble),
Write(bubble.content),
)
self.play(Blink(morty))
self.wait(2)
class ShowZetaOnHalfPlane(ZetaTransformationScene):
CONFIG = {
"x_min" : 1,
"x_max" : int(FRAME_X_RADIUS+2),
}
def construct(self):
self.add_title()
self.initial_transformation()
self.react_to_transformation()
self.show_cutoff()
self.set_color_i_line()
self.show_continuation()
self.emphsize_sum_doesnt_make_sense()
def add_title(self):
zeta = OldTex(
"\\zeta(", "s", ")=",
*[
"\\frac{1}{%d^s} + "%d
for d in range(1, 5)
] + ["\\cdots"]
)
zeta[1].set_color(YELLOW)
for mob in zeta[3:3+4]:
mob[-2].set_color(YELLOW)
zeta.add_background_rectangle()
zeta.scale(0.8)
zeta.to_corner(UP+LEFT)
self.add_foreground_mobjects(zeta)
self.zeta = zeta
def initial_transformation(self):
self.add_transformable_plane()
self.wait()
self.add_extra_plane_lines_for_zeta(animate = True)
self.wait(2)
self.plane.save_state()
self.apply_zeta_function()
self.wait(2)
def react_to_transformation(self):
morty = Mortimer().flip()
morty.to_corner(DOWN+LEFT)
bubble = morty.get_bubble(SpeechBubble)
bubble.set_fill(BLACK, 0.5)
bubble.write("\\emph{Damn}!")
bubble.resize_to_content()
bubble.pin_to(morty)
self.play(FadeIn(morty))
self.play(
morty.change_mode, "surprised",
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(morty))
self.play(morty.look_at, self.plane.get_top())
self.wait()
self.play(
morty.look_at, self.plane.get_bottom(),
*list(map(FadeOut, [bubble, bubble.content]))
)
self.play(Blink(morty))
self.play(FadeOut(morty))
def show_cutoff(self):
words = OldTexText("Such an abrupt stop...")
words.add_background_rectangle()
words.next_to(ORIGIN, UP+LEFT)
words.shift(LEFT+UP)
line = Line(*list(map(self.z_to_point, [
complex(np.euler_gamma, u*FRAME_Y_RADIUS)
for u in (1, -1)
])))
line.set_color(YELLOW)
arrows = [
Arrow(words.get_right(), point)
for point in line.get_start_and_end()
]
self.play(Write(words, run_time = 2))
self.play(ShowCreation(arrows[0]))
self.play(
Transform(*arrows),
ShowCreation(line),
run_time = 2
)
self.play(FadeOut(arrows[0]))
self.wait(2)
self.play(*list(map(FadeOut, [words, line])))
def set_color_i_line(self):
right_i_lines, left_i_lines = [
VGroup(*[
Line(
vert_vect+RIGHT,
vert_vect+(FRAME_X_RADIUS+1)*horiz_vect
)
for vert_vect in (UP, DOWN)
])
for horiz_vect in (RIGHT, LEFT)
]
right_i_lines.set_color(YELLOW)
left_i_lines.set_color(BLUE)
for lines in right_i_lines, left_i_lines:
self.prepare_for_transformation(lines)
self.restore_mobjects(self.plane)
self.plane.add(*right_i_lines)
colored_plane = self.plane.copy()
right_i_lines.set_stroke(width = 0)
self.play(
self.plane.set_stroke, GREY, 1,
)
right_i_lines.set_stroke(YELLOW, width = 3)
self.play(ShowCreation(right_i_lines))
self.plane.save_state()
self.wait(2)
self.apply_zeta_function()
self.wait(2)
left_i_lines.save_state()
left_i_lines.apply_complex_function(zeta)
self.play(ShowCreation(left_i_lines, run_time = 5))
self.wait()
self.restore_mobjects(self.plane, left_i_lines)
self.play(Transform(self.plane, colored_plane))
self.wait()
self.left_i_lines = left_i_lines
def show_continuation(self):
reflected_plane = self.get_reflected_plane()
self.play(ShowCreation(reflected_plane, run_time = 2))
self.plane.add(reflected_plane)
self.remove(self.left_i_lines)
self.wait()
self.apply_zeta_function()
self.wait(2)
self.play(ShowCreation(
reflected_plane,
run_time = 6,
rate_func = lambda t : 1-there_and_back(t)
))
self.wait(2)
def emphsize_sum_doesnt_make_sense(self):
brace = Brace(VGroup(*self.zeta[1][3:]))
words = brace.get_text("""
Still fails to converge
when Re$(s) < 1$
""", buff = SMALL_BUFF)
words.add_background_rectangle()
words.scale(0.8)
divergent_sum = OldTex("1+2+3+4+\\cdots")
divergent_sum.next_to(ORIGIN, UP)
divergent_sum.to_edge(LEFT)
divergent_sum.add_background_rectangle()
self.play(
GrowFromCenter(brace),
Write(words)
)
self.wait(2)
self.play(Write(divergent_sum))
self.wait(2)
def restore_mobjects(self, *mobjects):
self.play(*it.chain(*[
[m.restore, m.make_smooth]
for m in mobjects
]), run_time = 2)
for m in mobjects:
self.remove(m)
m.restore()
self.add(m)
class ShowConditionalDefinition(Scene):
def construct(self):
zeta = OldTex("\\zeta(s)=")
zeta[2].set_color(YELLOW)
sigma = OldTex("\\sum_{n=1}^\\infty \\frac{1}{n^s}")
sigma[-1].set_color(YELLOW)
something_else = OldTexText("Something else...")
conditions = VGroup(*[
OldTexText("if Re$(s) %s 1$"%s)
for s in (">", "\\le")
])
definitions = VGroup(sigma, something_else)
definitions.arrange(DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT)
conditions.arrange(DOWN, buff = LARGE_BUFF)
definitions.shift(2*LEFT+2*UP)
conditions.next_to(definitions, RIGHT, buff = LARGE_BUFF, aligned_edge = DOWN)
brace = Brace(definitions, LEFT)
zeta.next_to(brace, LEFT)
sigma.save_state()
sigma.next_to(zeta)
self.add(zeta, sigma)
self.wait()
self.play(
sigma.restore,
GrowFromCenter(brace),
FadeIn(something_else)
)
self.play(Write(conditions))
self.wait()
underbrace = Brace(something_else)
question = underbrace.get_text("""
What to put here?
""")
VGroup(underbrace, question).set_color(GREEN_B)
self.play(
GrowFromCenter(underbrace),
Write(question),
something_else.set_color, GREEN_B
)
self.wait(2)
class SquiggleOnExtensions(ZetaTransformationScene):
CONFIG = {
"x_min" : 1,
"x_max" : int(FRAME_X_RADIUS+2),
}
def construct(self):
self.show_negative_one()
self.cycle_through_options()
self.lock_into_place()
def show_negative_one(self):
self.add_transformable_plane()
thin_plane = self.plane.copy()
thin_plane.add(self.get_reflected_plane())
self.remove(self.plane)
self.add_extra_plane_lines_for_zeta()
reflected_plane = self.get_reflected_plane()
self.plane.add(reflected_plane)
self.remove(self.plane)
self.add(thin_plane)
dot = self.note_point(-1, "-1")
self.play(
ShowCreation(self.plane, run_time = 2),
Animation(dot),
run_time = 2
)
self.remove(thin_plane)
self.apply_zeta_function(added_anims = [
ApplyMethod(
dot.move_to, self.z_to_point(-1./12),
run_time = 5
)
])
dot_to_remove = self.note_point(-1./12, "-\\frac{1}{12}")
self.remove(dot_to_remove)
self.left_plane = reflected_plane
self.dot = dot
def note_point(self, z, label_tex):
dot = Dot(self.z_to_point(z))
dot.set_color(YELLOW)
label = OldTex(label_tex)
label.add_background_rectangle()
label.next_to(dot, UP+LEFT, buff = SMALL_BUFF)
label.shift(LEFT)
arrow = Arrow(label.get_right(), dot, buff = SMALL_BUFF)
self.play(Write(label, run_time = 1))
self.play(*list(map(ShowCreation, [arrow, dot])))
self.wait()
self.play(*list(map(FadeOut, [arrow, label])))
return dot
def cycle_through_options(self):
gamma = np.euler_gamma
def shear(point):
x, y, z = point
return np.array([
x,
y+0.25*(1-x)**2,
0
])
def mixed_scalar_func(point):
x, y, z = point
scalar = 1 + (gamma-x)/(gamma+FRAME_X_RADIUS)
return np.array([
(scalar**2)*x,
(scalar**3)*y,
0
])
def alt_mixed_scalar_func(point):
x, y, z = point
scalar = 1 + (gamma-x)/(gamma+FRAME_X_RADIUS)
return np.array([
(scalar**5)*x,
(scalar**2)*y,
0
])
def sinusoidal_func(point):
x, y, z = point
freq = np.pi/gamma
return np.array([
x-0.2*np.sin(x*freq)*np.sin(y),
y-0.2*np.sin(x*freq)*np.sin(y),
0
])
funcs = [
shear,
mixed_scalar_func,
alt_mixed_scalar_func,
sinusoidal_func,
]
for mob in self.left_plane.family_members_with_points():
if np.all(np.abs(mob.get_points()[:,1]) < 0.1):
self.left_plane.remove(mob)
new_left_planes = [
self.left_plane.copy().apply_function(func)
for func in funcs
]
new_dots = [
self.dot.copy().move_to(func(self.dot.get_center()))
for func in funcs
]
self.left_plane.save_state()
for plane, dot in zip(new_left_planes, new_dots):
self.play(
Transform(self.left_plane, plane),
Transform(self.dot, dot),
run_time = 3
)
self.wait()
self.play(FadeOut(self.dot))
#Squiggle on example
self.wait()
self.play(FadeOut(self.left_plane))
self.play(ShowCreation(
self.left_plane,
run_time = 5,
rate_func=linear
))
self.wait()
def lock_into_place(self):
words = OldTexText(
"""Only one extension
has a """,
"\\emph{derivative}",
"everywhere",
alignment = ""
)
words.to_corner(UP+LEFT)
words.set_color_by_tex("\\emph{derivative}", YELLOW)
words.add_background_rectangle()
self.play(Write(words))
self.add_foreground_mobjects(words)
self.play(self.left_plane.restore)
self.wait()
class DontKnowDerivatives(TeacherStudentsScene):
def construct(self):
self.student_says(
"""
You said we don't
need derivatives!
""",
target_mode = "pleading"
)
self.random_blink(2)
self.student_says(
"""
I get $\\frac{df}{dx}$, just not
for complex functions
""",
target_mode = "confused",
index = 2
)
self.random_blink(2)
self.teacher_says(
"""
Luckily, there's a purely
geometric intuition here.
""",
target_mode = "hooray"
)
self.play_student_changes(*["happy"]*3)
self.random_blink(3)
class IntroduceAnglePreservation(VisualizingSSquared):
CONFIG = {
"num_anchors_to_add_per_line" : 50,
"use_homotopy" : True,
}
def construct(self):
self.add_title()
self.show_initial_transformation()
self.talk_about_derivative()
self.cycle_through_line_pairs()
self.note_grid_lines()
self.name_analytic()
def add_title(self):
title = OldTex("f(", "s", ")=", "s", "^2")
title.set_color_by_tex("s", YELLOW)
title.scale(1.5)
title.to_corner(UP+LEFT)
title.add_background_rectangle()
self.title = title
self.add_transformable_plane()
self.play(Write(title))
self.add_foreground_mobjects(title)
self.wait()
def show_initial_transformation(self):
self.apply_function()
self.wait(2)
self.reset()
def talk_about_derivative(self):
randy = Randolph().scale(0.8)
randy.to_corner(DOWN+LEFT)
morty = Mortimer()
morty.to_corner(DOWN+RIGHT)
randy.make_eye_contact(morty)
for pi, words in (randy, "$f'(s) = 2s$"), (morty, "Here's some \\\\ related geometry..."):
pi.bubble = pi.get_bubble(SpeechBubble)
pi.bubble.set_fill(BLACK, opacity = 0.7)
pi.bubble.write(words)
pi.bubble.resize_to_content()
pi.bubble.pin_to(pi)
for index in 3, 7:
randy.bubble.content[index].set_color(YELLOW)
self.play(*list(map(FadeIn, [randy, morty])))
self.play(
randy.change_mode, "speaking",
ShowCreation(randy.bubble),
Write(randy.bubble.content)
)
self.play(Blink(morty))
self.wait()
self.play(
morty.change_mode, "speaking",
randy.change_mode, "pondering",
ShowCreation(morty.bubble),
Write(morty.bubble.content),
)
self.play(Blink(randy))
self.wait()
self.play(*list(map(FadeOut, [
randy, morty,
randy.bubble, randy.bubble.content,
morty.bubble, morty.bubble.content,
])))
def cycle_through_line_pairs(self):
line_pairs = [
(
Line(3*DOWN+3*RIGHT, 2*UP),
Line(DOWN+RIGHT, 3*UP+4*RIGHT)
),
(
Line(RIGHT+3.5*DOWN, RIGHT+2.5*UP),
Line(3*LEFT+0.5*UP, 3*RIGHT+0.5*UP),
),
(
Line(4*RIGHT+4*DOWN, RIGHT+2*UP),
Line(4*DOWN+RIGHT, 2*UP+2*RIGHT)
),
]
for lines in line_pairs:
self.show_angle_preservation_between_lines(*lines)
self.reset()
def note_grid_lines(self):
intersection_inputs = [
complex(x, y)
for x in np.arange(-5, 5, 0.5)
for y in np.arange(0, 3, 0.5)
if not (x <= 0 and y == 0)
]
brackets = VGroup(*list(map(
self.get_right_angle_bracket,
intersection_inputs
)))
self.apply_function()
self.wait()
self.play(
ShowCreation(brackets, run_time = 5),
Animation(self.plane)
)
self.wait()
def name_analytic(self):
equiv = OldTexText("``Analytic'' $\\Leftrightarrow$ Angle-preserving")
kind_of = OldTexText("...kind of")
for text in equiv, kind_of:
text.scale(1.2)
text.add_background_rectangle()
equiv.set_color(YELLOW)
kind_of.set_color(RED)
kind_of.next_to(equiv, RIGHT)
VGroup(equiv, kind_of).next_to(ORIGIN, UP, buff = 1)
self.play(Write(equiv))
self.wait(2)
self.play(Write(kind_of, run_time = 1))
self.wait(2)
def reset(self, faded = True):
self.play(FadeOut(self.plane))
self.add_transformable_plane()
if faded:
self.plane.fade()
self.play(FadeIn(self.plane))
def apply_function(self, **kwargs):
if self.use_homotopy:
self.apply_complex_homotopy(
lambda z, t : z**(1+t),
run_time = 5,
**kwargs
)
else:
self.apply_complex_function(
lambda z : z**2,
**kwargs
)
def show_angle_preservation_between_lines(self, *lines):
R2_endpoints = [
[l.get_start()[:2], l.get_end()[:2]]
for l in lines
]
R2_intersection_point = intersection(*R2_endpoints)
intersection_point = np.array(list(R2_intersection_point) + [0])
angle1, angle2 = [l.get_angle() for l in lines]
arc = Arc(
start_angle = angle1,
angle = angle2-angle1,
radius = 0.4,
color = YELLOW
)
arc.shift(intersection_point)
arc.insert_n_curves(10)
arc.generate_target()
input_z = complex(*arc.get_center()[:2])
scale_factor = abs(2*input_z)
arc.target.scale_about_point(1./scale_factor, intersection_point)
arc.target.apply_complex_function(lambda z : z**2)
angle_tex = OldTex(
"%d^\\circ"%abs(int((angle2-angle1)*180/np.pi))
)
angle_tex.set_color(arc.get_color())
angle_tex.add_background_rectangle()
self.put_angle_tex_next_to_arc(angle_tex, arc)
angle_arrow = Arrow(
angle_tex, arc,
color = arc.get_color(),
buff = 0.1,
)
angle_group = VGroup(angle_tex, angle_arrow)
self.play(*list(map(ShowCreation, lines)))
self.play(
Write(angle_tex),
ShowCreation(angle_arrow),
ShowCreation(arc)
)
self.wait()
self.play(FadeOut(angle_group))
self.plane.add(*lines)
self.apply_function(added_anims = [
MoveToTarget(arc, run_time = 5)
])
self.put_angle_tex_next_to_arc(angle_tex, arc)
arrow = Arrow(angle_tex, arc, buff = 0.1)
arrow.set_color(arc.get_color())
self.play(
Write(angle_tex),
ShowCreation(arrow)
)
self.wait(2)
self.play(*list(map(FadeOut, [arc, angle_tex, arrow])))
def put_angle_tex_next_to_arc(self, angle_tex, arc):
vect = arc.point_from_proportion(0.5)-interpolate(
arc.get_points()[0], arc.get_points()[-1], 0.5
)
unit_vect = vect/get_norm(vect)
angle_tex.move_to(arc.get_center() + 1.7*unit_vect)
def get_right_angle_bracket(self, input_z):
output_z = input_z**2
derivative = 2*input_z
rotation = np.log(derivative).imag
brackets = VGroup(
Line(RIGHT, RIGHT+UP),
Line(RIGHT+UP, UP)
)
brackets.scale(0.15)
brackets.set_stroke(width = 2)
brackets.set_color(YELLOW)
brackets.shift(0.02*UP) ##Why???
brackets.rotate(rotation, about_point = ORIGIN)
brackets.shift(self.z_to_point(output_z))
return brackets
class AngleAtZeroDerivativePoints(IntroduceAnglePreservation):
CONFIG = {
"use_homotopy" : True
}
def construct(self):
self.add_title()
self.is_before_transformation = True
self.add_transformable_plane()
self.plane.fade()
line = Line(3*LEFT+0.5*UP, 3*RIGHT+0.5*DOWN)
self.show_angle_preservation_between_lines(
line, line.copy().rotate(np.pi/5)
)
self.wait()
def add_title(self):
title = OldTex("f(", "s", ")=", "s", "^2")
title.set_color_by_tex("s", YELLOW)
title.scale(1.5)
title.to_corner(UP+LEFT)
title.add_background_rectangle()
derivative = OldTex("f'(0) = 0")
derivative.set_color(RED)
derivative.scale(1.2)
derivative.add_background_rectangle()
derivative.next_to(title, DOWN)
self.add_foreground_mobjects(title, derivative)
def put_angle_tex_next_to_arc(self, angle_tex, arc):
IntroduceAnglePreservation.put_angle_tex_next_to_arc(
self, angle_tex, arc
)
if not self.is_before_transformation:
two_dot = OldTex("2 \\times ")
two_dot.set_color(angle_tex.get_color())
two_dot.next_to(angle_tex, LEFT, buff = SMALL_BUFF)
two_dot.add_background_rectangle()
center = angle_tex.get_center()
angle_tex.add_to_back(two_dot)
angle_tex.move_to(center)
else:
self.is_before_transformation = False
class AnglePreservationAtAnyPairOfPoints(IntroduceAnglePreservation):
def construct(self):
self.add_transformable_plane()
self.plane.fade()
line_pairs = self.get_line_pairs()
line_pair = line_pairs[0]
for target_pair in line_pairs[1:]:
self.play(Transform(
line_pair, target_pair,
run_time = 2,
path_arc = np.pi
))
self.wait()
self.show_angle_preservation_between_lines(*line_pair)
self.show_example_analytic_functions()
def get_line_pairs(self):
return list(it.starmap(VGroup, [
(
Line(3*DOWN, 3*LEFT+2*UP),
Line(2*LEFT+DOWN, 3*UP+RIGHT)
),
(
Line(2*RIGHT+DOWN, 3*LEFT+2*UP),
Line(LEFT+3*DOWN, 4*RIGHT+3*UP),
),
(
Line(LEFT+3*DOWN, LEFT+3*UP),
Line(5*LEFT+UP, 3*RIGHT+UP)
),
(
Line(4*RIGHT+3*DOWN, RIGHT+2*UP),
Line(3*DOWN+RIGHT, 2*UP+2*RIGHT)
),
]))
def show_example_analytic_functions(self):
words = OldTexText("Examples of analytic functions:")
words.shift(2*UP)
words.set_color(YELLOW)
words.add_background_rectangle()
words.next_to(UP, UP).to_edge(LEFT)
functions = OldTexText(
"$e^x$, ",
"$\\sin(x)$, ",
"any polynomial, "
"$\\log(x)$, ",
"\\dots",
)
functions.next_to(ORIGIN, UP).to_edge(LEFT)
for function in functions:
function.add_to_back(BackgroundRectangle(function))
self.play(Write(words))
for function in functions:
self.play(FadeIn(function))
self.wait()
class NoteZetaFunctionAnalyticOnRightHalf(ZetaTransformationScene):
CONFIG = {
"anchor_density" : 35,
}
def construct(self):
self.add_title()
self.add_transformable_plane(animate = False)
self.add_extra_plane_lines_for_zeta(animate = True)
self.apply_zeta_function()
self.note_right_angles()
def add_title(self):
title = OldTex(
"\\zeta(s) = \\sum_{n=1}^\\infty \\frac{1}{n^s}"
)
title[2].set_color(YELLOW)
title[-1].set_color(YELLOW)
title.add_background_rectangle()
title.to_corner(UP+LEFT)
self.add_foreground_mobjects(title)
def note_right_angles(self):
intersection_inputs = [
complex(x, y)
for x in np.arange(1+2./16, 1.4, 1./16)
for y in np.arange(-0.5, 0.5, 1./16)
if abs(y) > 1./16
]
brackets = VGroup(*list(map(
self.get_right_angle_bracket,
intersection_inputs
)))
self.play(ShowCreation(brackets, run_time = 3))
self.wait()
def get_right_angle_bracket(self, input_z):
output_z = zeta(input_z)
derivative = d_zeta(input_z)
rotation = np.log(derivative).imag
brackets = VGroup(
Line(RIGHT, RIGHT+UP),
Line(RIGHT+UP, UP)
)
brackets.scale(0.1)
brackets.set_stroke(width = 2)
brackets.set_color(YELLOW)
brackets.rotate(rotation, about_point = ORIGIN)
brackets.shift(self.z_to_point(output_z))
return brackets
class InfiniteContinuousJigsawPuzzle(ZetaTransformationScene):
CONFIG = {
"anchor_density" : 35,
}
def construct(self):
self.set_stage()
self.add_title()
self.show_jigsaw()
self.name_analytic_continuation()
def set_stage(self):
self.plane = self.get_dense_grid()
left_plane = self.get_reflected_plane()
self.plane.add(left_plane)
self.apply_zeta_function(run_time = 0)
self.remove(left_plane)
lines_per_piece = 5
pieces = [
VGroup(*left_plane[lines_per_piece*i:lines_per_piece*(i+1)])
for i in range(len(list(left_plane))/lines_per_piece)
]
random.shuffle(pieces)
self.pieces = pieces
def add_title(self):
title = OldTexText("Infinite ", "continuous ", "jigsaw puzzle")
title.scale(1.5)
title.to_edge(UP)
for word in title:
word.add_to_back(BackgroundRectangle(word))
self.play(FadeIn(word))
self.wait()
self.add_foreground_mobjects(title)
self.title = title
def show_jigsaw(self):
for piece in self.pieces:
self.play(FadeIn(piece, run_time = 0.5))
self.wait()
def name_analytic_continuation(self):
words = OldTexText("``Analytic continuation''")
words.set_color(YELLOW)
words.scale(1.5)
words.next_to(self.title, DOWN, buff = LARGE_BUFF)
words.add_background_rectangle()
self.play(Write(words))
self.wait()
class ThatsHowZetaIsDefined(TeacherStudentsScene):
def construct(self):
self.add_zeta_definition()
self.teacher_says("""
So that's how
$\\zeta(s)$ is defined
""")
self.play_student_changes(*["hooray"]*3)
self.random_blink(2)
def add_zeta_definition(self):
zeta = OldTex(
"\\zeta(s) = \\sum_{n=1}^\\infty \\frac{1}{n^s}"
)
VGroup(zeta[2], zeta[-1]).set_color(YELLOW)
zeta.to_corner(UP+LEFT)
self.add(zeta)
class ManyIntersectingLinesPreZeta(ZetaTransformationScene):
CONFIG = {
"apply_zeta" : False,
"lines_center" : RIGHT,
"nudge_size" : 0.9,
"function" : zeta,
"angle" : np.pi/5,
"arc_scale_factor" : 0.3,
"shift_directions" : [LEFT, RIGHT],
}
def construct(self):
self.establish_plane()
self.add_title()
line = Line(DOWN+2*LEFT, UP+2*RIGHT)
lines = VGroup(line, line.copy().rotate(self.angle))
arc = Arc(start_angle = line.get_angle(), angle = self.angle)
arc.scale(self.arc_scale_factor)
arc.set_color(YELLOW)
lines.add(arc)
# lines.set_stroke(WHITE, width = 5)
lines.shift(self.lines_center + self.nudge_size*RIGHT)
if self.apply_zeta:
self.apply_zeta_function(run_time = 0)
lines.set_stroke(width = 0)
added_anims = self.get_modified_line_anims(lines)
for vect in self.shift_directions:
self.play(
ApplyMethod(lines.shift, 2*self.nudge_size*vect, path_arc = np.pi),
*added_anims,
run_time = 3
)
def establish_plane(self):
self.add_transformable_plane()
self.add_extra_plane_lines_for_zeta()
self.add_reflected_plane()
self.plane.fade()
def add_title(self):
if self.apply_zeta:
title = OldTexText("After \\\\ transformation")
else:
title = OldTexText("Before \\\\ transformation")
title.add_background_rectangle()
title.to_edge(UP)
self.add_foreground_mobjects(title)
def get_modified_line_anims(self, lines):
return []
class ManyIntersectingLinesPostZeta(ManyIntersectingLinesPreZeta):
CONFIG = {
"apply_zeta" : True,
# "anchor_density" : 5
}
def get_modified_line_anims(self, lines):
n_inserted_points = 30
new_lines = lines.copy()
new_lines.set_stroke(width = 5)
def update_new_lines(lines_to_update):
transformed = lines.copy()
self.prepare_for_transformation(transformed)
transformed.apply_complex_function(self.function)
transformed.make_smooth()
transformed.set_stroke(width = 5)
for start, end in zip(lines_to_update, transformed):
if start.get_num_points() > 0:
start.points = np.array(end.points)
return [UpdateFromFunc(new_lines, update_new_lines)]
class ManyIntersectingLinesPreSSquared(ManyIntersectingLinesPreZeta):
CONFIG = {
"x_min" : -int(FRAME_X_RADIUS),
"apply_zeta" : False,
"lines_center" : ORIGIN,
"nudge_size" : 0.9,
"function" : lambda z : z**2,
"shift_directions" : [LEFT, RIGHT, UP, DOWN, DOWN+LEFT, UP+RIGHT],
}
def establish_plane(self):
self.add_transformable_plane()
self.plane.fade()
def apply_zeta_function(self, **kwargs):
self.apply_complex_function(self.function, **kwargs)
class ManyIntersectingLinesPostSSquared(ManyIntersectingLinesPreSSquared):
CONFIG = {
"apply_zeta" : True,
}
def get_modified_line_anims(self, lines):
n_inserted_points = 30
new_lines = lines.copy()
new_lines.set_stroke(width = 5)
def update_new_lines(lines_to_update):
transformed = lines.copy()
self.prepare_for_transformation(transformed)
transformed.apply_complex_function(self.function)
transformed.make_smooth()
transformed.set_stroke(width = 5)
for start, end in zip(lines_to_update, transformed):
if start.get_num_points() > 0:
start.points = np.array(end.points)
return [UpdateFromFunc(new_lines, update_new_lines)]
class ButWhatIsTheExensions(TeacherStudentsScene):
def construct(self):
self.student_says(
"""
But what exactly \\emph{is}
that continuation?
""",
target_mode = "sassy"
)
self.play_student_changes("confused", "sassy", "confused")
self.random_blink(2)
self.teacher_says("""
You're $\\$1{,}000{,}000$ richer
if you can answer
that fully
""", target_mode = "shruggie")
self.play_student_changes(*["pondering"]*3)
self.random_blink(3)
class MathematiciansLookingAtFunctionEquation(Scene):
def construct(self):
equation = OldTex(
"\\zeta(s)",
"= 2^s \\pi ^{s-1}",
"\\sin\\left(\\frac{\\pi s}{2}\\right)",
"\\Gamma(1-s)",
"\\zeta(1-s)",
)
equation.shift(UP)
mathy = Mathematician().to_corner(DOWN+LEFT)
mathys = VGroup(mathy)
for x in range(2):
mathys.add(Mathematician().next_to(mathys))
for mathy in mathys:
mathy.change_mode("pondering")
mathy.look_at(equation)
self.add(mathys)
self.play(Write(VGroup(*equation[:-1])))
self.play(Transform(
equation[0].copy(),
equation[-1],
path_arc = -np.pi/3,
run_time = 2
))
for mathy in mathys:
self.play(Blink(mathy))
self.wait()
class DiscussZeros(ZetaTransformationScene):
def construct(self):
self.establish_plane()
self.ask_about_zeros()
self.show_trivial_zeros()
self.show_critical_strip()
self.transform_bit_of_critical_line()
self.extend_transformed_critical_line()
def establish_plane(self):
self.add_transformable_plane()
self.add_extra_plane_lines_for_zeta()
self.add_reflected_plane()
self.plane.fade()
def ask_about_zeros(self):
dots = VGroup(*[
Dot(
(2+np.sin(12*alpha))*\
rotate_vector(RIGHT, alpha+nudge)
)
for alpha in np.arange(3*np.pi/20, 2*np.pi, 2*np.pi/5)
for nudge in [random.random()*np.pi/6]
])
dots.set_color(YELLOW)
q_marks = VGroup(*[
OldTex("?").next_to(dot, UP)
for dot in dots
])
arrows = VGroup(*[
Arrow(dot, ORIGIN, buff = 0.2, tip_length = 0.1)
for dot in dots
])
question = OldTexText("Which numbers go to $0$?")
question.add_background_rectangle()
question.to_edge(UP)
for mob in dots, arrows, q_marks:
self.play(ShowCreation(mob))
self.play(Write(question))
self.wait(2)
dots.generate_target()
for i, dot in enumerate(dots.target):
dot.move_to(2*(i+1)*LEFT)
self.play(
FadeOut(arrows),
FadeOut(q_marks),
FadeOut(question),
MoveToTarget(dots),
)
self.wait()
self.dots = dots
def show_trivial_zeros(self):
trivial_zero_words = OldTexText("``Trivial'' zeros")
trivial_zero_words.next_to(ORIGIN, UP)
trivial_zero_words.to_edge(LEFT)
randy = Randolph().flip()
randy.to_corner(DOWN+RIGHT)
bubble = randy.get_bubble()
bubble.set_fill(BLACK, opacity = 0.8)
bubble.write("$1^1 + 2^2 + 3^2 + \\cdots = 0$")
bubble.resize_to_content()
bubble.pin_to(randy)
self.plane.save_state()
self.dots.save_state()
for dot in self.dots.target:
dot.move_to(ORIGIN)
self.apply_zeta_function(
added_anims = [MoveToTarget(self.dots, run_time = 3)],
run_time = 3
)
self.wait(3)
self.play(
self.plane.restore,
self.plane.make_smooth,
self.dots.restore,
run_time = 2
)
self.remove(*self.get_mobjects_from_last_animation())
self.plane.restore()
self.dots.restore()
self.add(self.plane, self.dots)
self.play(Write(trivial_zero_words))
self.wait()
self.play(FadeIn(randy))
self.play(
randy.change_mode, "confused",
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(randy))
self.wait()
self.play(Blink(randy))
self.play(*list(map(FadeOut, [
randy, bubble, bubble.content, trivial_zero_words
])))
def show_critical_strip(self):
strip = Rectangle(
height = FRAME_HEIGHT,
width = 1
)
strip.next_to(ORIGIN, RIGHT, buff = 0)
strip.set_stroke(width = 0)
strip.set_fill(YELLOW, opacity = 0.3)
name = OldTexText("Critical strip")
name.add_background_rectangle()
name.next_to(ORIGIN, LEFT)
name.to_edge(UP)
arrow = Arrow(name.get_bottom(), 0.5*RIGHT+UP)
primes = OldTex("2, 3, 5, 7, 11, 13, 17, \\dots")
primes.to_corner(UP+RIGHT)
# photo = Square()
photo = ImageMobject("Riemann", invert = False)
photo.set_width(5)
photo.to_corner(UP+LEFT)
new_dots = VGroup(*[
Dot(0.5*RIGHT + y*UP)
for y in np.linspace(-2.5, 3.2, 5)
])
new_dots.set_color(YELLOW)
critical_line = Line(
0.5*RIGHT+FRAME_Y_RADIUS*DOWN,
0.5*RIGHT+FRAME_Y_RADIUS*UP,
color = YELLOW
)
self.give_dots_wandering_anims()
self.play(FadeIn(strip), *self.get_dot_wandering_anims())
self.play(
Write(name, run_time = 1),
ShowCreation(arrow),
*self.get_dot_wandering_anims()
)
self.play(*self.get_dot_wandering_anims())
self.play(
FadeIn(primes),
*self.get_dot_wandering_anims()
)
for x in range(7):
self.play(*self.get_dot_wandering_anims())
self.play(
GrowFromCenter(photo),
FadeOut(name),
FadeOut(arrow),
*self.get_dot_wandering_anims()
)
self.play(Transform(self.dots, new_dots))
self.play(ShowCreation(critical_line))
self.wait(3)
self.play(
photo.shift, 7*LEFT,
*list(map(FadeOut, [
primes, self.dots, strip
]))
)
self.remove(photo)
self.critical_line = critical_line
def give_dots_wandering_anims(self):
def func(t):
result = (np.sin(6*2*np.pi*t) + 1)*RIGHT/2
result += 3*np.cos(2*2*np.pi*t)*UP
return result
self.wandering_path = ParametricCurve(func)
for i, dot in enumerate(self.dots):
dot.target = dot.copy()
q_mark = OldTex("?")
q_mark.next_to(dot.target, UP)
dot.target.add(q_mark)
dot.target.move_to(self.wandering_path.point_from_proportion(
(float(2+2*i)/(4*len(list(self.dots))))%1
))
self.dot_anim_count = 0
def get_dot_wandering_anims(self):
self.dot_anim_count += 1
if self.dot_anim_count == 1:
return list(map(MoveToTarget, self.dots))
denom = 4*(len(list(self.dots)))
def get_rate_func(index):
return lambda t : (float(self.dot_anim_count + 2*index + t)/denom)%1
return [
MoveAlongPath(
dot, self.wandering_path,
rate_func = get_rate_func(i)
)
for i, dot in enumerate(self.dots)
]
def transform_bit_of_critical_line(self):
self.play(
self.plane.scale, 0.8,
self.critical_line.scale, 0.8,
rate_func = there_and_back,
run_time = 2
)
self.wait()
self.play(
self.plane.set_stroke, GREY, 1,
Animation(self.critical_line)
)
self.plane.add(self.critical_line)
self.apply_zeta_function()
self.wait(2)
self.play(
self.plane.fade,
Animation(self.critical_line)
)
def extend_transformed_critical_line(self):
def func(t):
z = zeta(complex(0.5, t))
return z.real*RIGHT + z.imag*UP
full_line = VGroup(*[
ParametricCurve(func, t_min = t0, t_max = t0+1)
for t0 in range(100)
])
full_line.set_color_by_gradient(
YELLOW, BLUE, GREEN, RED, YELLOW, BLUE, GREEN, RED,
)
self.play(ShowCreation(full_line, run_time = 20, rate_func=linear))
self.wait()
class AskAboutRelationToPrimes(TeacherStudentsScene):
def construct(self):
self.student_says("""
Whoa! Where the heck
do primes come in here?
""", target_mode = "confused")
self.random_blink(3)
self.teacher_says("""
Perhaps in a
different video.
""", target_mode = "hesitant")
self.random_blink(3)
class HighlightCriticalLineAgain(DiscussZeros):
def construct(self):
self.establish_plane()
title = OldTex("\\zeta(", "s", ") = 0")
title.set_color_by_tex("s", YELLOW)
title.add_background_rectangle()
title.to_corner(UP+LEFT)
self.add(title)
strip = Rectangle(
height = FRAME_HEIGHT,
width = 1
)
strip.next_to(ORIGIN, RIGHT, buff = 0)
strip.set_stroke(width = 0)
strip.set_fill(YELLOW, opacity = 0.3)
line = Line(
0.5*RIGHT+FRAME_Y_RADIUS*UP,
0.5*RIGHT+FRAME_Y_RADIUS*DOWN,
color = YELLOW
)
randy = Randolph().to_corner(DOWN+LEFT)
million = OldTex("\\$1{,}000{,}000")
million.set_color(GREEN_B)
million.next_to(ORIGIN, UP+LEFT)
million.shift(2*LEFT)
arrow1 = Arrow(million.get_right(), line.get_top())
arrow2 = Arrow(million.get_right(), line.get_bottom())
self.add(randy, strip)
self.play(Write(million))
self.play(
randy.change_mode, "pondering",
randy.look_at, line.get_top(),
ShowCreation(arrow1),
run_time = 3
)
self.play(
randy.look_at, line.get_bottom(),
ShowCreation(line),
Transform(arrow1, arrow2)
)
self.play(FadeOut(arrow1))
self.play(Blink(randy))
self.wait()
self.play(randy.look_at, line.get_center())
self.play(randy.change_mode, "confused")
self.play(Blink(randy))
self.wait()
self.play(randy.change_mode, "pondering")
self.wait()
class DiscussSumOfNaturals(Scene):
def construct(self):
title = OldTex(
"\\zeta(s) = \\sum_{n=1}^\\infty \\frac{1}{n^s}"
)
VGroup(title[2], title[-1]).set_color(YELLOW)
title.to_corner(UP+LEFT)
neg_twelfth, eq, zeta_neg_1, sum_naturals = equation = OldTex(
"-\\frac{1}{12}",
"=",
"\\zeta(-1)",
"= 1 + 2 + 3 + 4 + \\cdots"
)
neg_twelfth.set_color(GREEN_B)
VGroup(*zeta_neg_1[2:4]).set_color(YELLOW)
q_mark = OldTex("?").next_to(sum_naturals[0], UP)
q_mark.set_color(RED)
randy = Randolph()
randy.to_corner(DOWN+LEFT)
analytic_continuation = OldTexText("Analytic continuation")
analytic_continuation.next_to(title, RIGHT, 3*LARGE_BUFF)
sum_to_zeta = Arrow(title.get_corner(DOWN+RIGHT), zeta_neg_1)
sum_to_ac = Arrow(title.get_right(), analytic_continuation)
ac_to_zeta = Arrow(analytic_continuation.get_bottom(), zeta_neg_1.get_top())
cross = OldTex("\\times")
cross.scale(2)
cross.set_color(RED)
cross.rotate(np.pi/6)
cross.move_to(sum_to_zeta.get_center())
brace = Brace(VGroup(zeta_neg_1, sum_naturals))
words = OldTexText(
"If not equal, at least connected",
"\\\\(see links in description)"
)
words.next_to(brace, DOWN)
self.add(neg_twelfth, eq, zeta_neg_1, randy, title)
self.wait()
self.play(
Write(sum_naturals),
Write(q_mark),
randy.change_mode, "confused"
)
self.play(Blink(randy))
self.wait()
self.play(randy.change_mode, "angry")
self.play(
ShowCreation(sum_to_zeta),
Write(cross)
)
self.play(Blink(randy))
self.wait()
self.play(
Transform(sum_to_zeta, sum_to_ac),
FadeOut(cross),
Write(analytic_continuation),
randy.change_mode, "pondering",
randy.look_at, analytic_continuation,
)
self.play(ShowCreation(ac_to_zeta))
self.play(Blink(randy))
self.wait()
self.play(
GrowFromCenter(brace),
Write(words[0]),
randy.look_at, words[0],
)
self.wait()
self.play(FadeIn(words[1]))
self.play(Blink(randy))
self.wait()
class InventingMathPreview(Scene):
def construct(self):
rect = Rectangle(height = 9, width = 16)
rect.set_height(4)
title = OldTexText("What does it feel like to invent math?")
title.next_to(rect, UP)
sum_tex = OldTex("1+2+4+8+\\cdots = -1")
sum_tex.set_width(rect.get_width()-1)
self.play(
ShowCreation(rect),
Write(title)
)
self.play(Write(sum_tex))
self.wait()
class FinalAnimationTease(Scene):
def construct(self):
morty = Mortimer().shift(2*(DOWN+RIGHT))
bubble = morty.get_bubble(SpeechBubble)
bubble.write("""
Want to know what
$\\zeta'(s)$ looks like?
""")
self.add(morty)
self.play(
morty.change_mode, "hooray",
morty.look_at, bubble.content,
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(morty))
self.wait()
class PatreonThanks(Scene):
CONFIG = {
"specific_patrons" : [
"CrypticSwarm",
"Ali Yahya",
"Damion Kistler",
"Juan Batiz-Benet",
"Yu Jun",
"Othman Alikhan",
"Markus Persson",
"Joseph John Cox",
"Luc Ritchie",
"Shimin Kuang",
"Einar Johansen",
"Rish Kundalia",
"Achille Brighton",
"Kirk Werklund",
"Ripta Pasay",
"Felipe Diniz",
]
}
def construct(self):
morty = Mortimer()
morty.next_to(ORIGIN, DOWN)
n_patrons = len(self.specific_patrons)
special_thanks = OldTexText("Special thanks to:")
special_thanks.set_color(YELLOW)
special_thanks.shift(3*UP)
patreon_logo = ImageMobject("patreon", invert = False)
patreon_logo.set_height(1.5)
patreon_logo.next_to(special_thanks, DOWN)
left_patrons = VGroup(*list(map(TexText,
self.specific_patrons[:n_patrons/2]
)))
right_patrons = VGroup(*list(map(TexText,
self.specific_patrons[n_patrons/2:]
)))
for patrons, vect in (left_patrons, LEFT), (right_patrons, RIGHT):
patrons.arrange(DOWN, aligned_edge = LEFT)
patrons.next_to(special_thanks, DOWN)
patrons.to_edge(vect, buff = LARGE_BUFF)
self.add(patreon_logo)
self.play(morty.change_mode, "gracious")
self.play(Write(special_thanks, run_time = 1))
self.play(
Write(left_patrons),
morty.look_at, left_patrons
)
self.play(
Write(right_patrons),
morty.look_at, right_patrons
)
self.play(Blink(morty))
for patrons in left_patrons, right_patrons:
for index in 0, -1:
self.play(morty.look_at, patrons[index])
self.wait()
class CreditTwo(Scene):
def construct(self):
morty = Mortimer()
morty.next_to(ORIGIN, DOWN)
morty.to_edge(RIGHT)
brother = PiCreature(color = GOLD_E)
brother.next_to(morty, LEFT)
brother.look_at(morty.eyes)
headphones = Headphones(height = 1)
headphones.move_to(morty.eyes, aligned_edge = DOWN)
headphones.shift(0.1*DOWN)
url = OldTexText("www.audible.com/3blue1brown")
url.to_corner(UP+RIGHT, buff = LARGE_BUFF)
self.add(morty)
self.play(Blink(morty))
self.play(
FadeIn(headphones),
Write(url),
Animation(morty)
)
self.play(morty.change_mode, "happy")
for x in range(4):
self.wait()
self.play(Blink(morty))
self.wait()
self.play(
FadeIn(brother),
morty.look_at, brother.eyes
)
self.play(brother.change_mode, "surprised")
self.play(Blink(brother))
self.wait()
self.play(
morty.look, LEFT,
brother.change_mode, "happy",
brother.look, LEFT
)
for x in range(10):
self.play(Blink(morty))
self.wait()
self.play(Blink(brother))
self.wait()
class FinalAnimation(ZetaTransformationScene):
CONFIG = {
"min_added_anchors" : 100,
}
def construct(self):
self.add_transformable_plane()
self.add_extra_plane_lines_for_zeta()
self.add_reflected_plane()
title = OldTex("s", "\\to \\frac{d\\zeta}{ds}(", "s", ")")
title.set_color_by_tex("s", YELLOW)
title.add_background_rectangle()
title.scale(1.5)
title.to_corner(UP+LEFT)
self.play(Write(title))
self.add_foreground_mobjects(title)
self.wait()
self.apply_complex_function(d_zeta, run_time = 8)
self.wait()
class Thumbnail(ZetaTransformationScene):
CONFIG = {
"anchor_density" : 35
}
def construct(self):
self.y_min = -4
self.y_max = 4
self.x_min = 1
self.x_max = int(FRAME_X_RADIUS+2)
self.add_transformable_plane()
self.add_extra_plane_lines_for_zeta()
self.add_reflected_plane()
# self.apply_zeta_function()
self.plane.set_stroke(width = 4)
div_sum = OldTex("-\\frac{1}{12} = ", "1+2+3+4+\\cdots")
div_sum.set_width(FRAME_WIDTH-1)
div_sum.to_edge(DOWN)
div_sum.set_color(YELLOW)
div_sum.set_background_stroke(width=8)
# for mob in div_sum.submobjects:
# mob.add_to_back(BackgroundRectangle(mob))
zeta = OldTex("\\zeta(s)")
zeta.set_height(FRAME_Y_RADIUS-1)
zeta.to_corner(UP+LEFT)
million = OldTex("\\$1{,}000{,}000")
million.set_width(FRAME_X_RADIUS+1)
million.to_edge(UP+RIGHT)
million.set_color(GREEN_B)
million.set_background_stroke(width=8)
self.add(div_sum, million, zeta)
class ZetaThumbnail(Scene):
def construct(self):
plane = ComplexPlane(
x_range=(-5, 5), y_range=(-3, 3),
background_line_style={
"stroke_width": 2,
"stroke_opacity": 0.75,
}
)
plane.set_height(FRAME_HEIGHT)
plane.scale(3 / 2.5)
plane.add_coordinate_labels(font_size=12)
# self.add(plane)
lines = VGroup(
*(
Line(plane.c2p(-7, y), plane.c2p(7, y))
for y in np.arange(-2, 2, 0.1)
if y != 0
),
*(
Line(plane.c2p(x, -4), plane.c2p(x, 4))
for x in np.arange(-2, 2, 0.1)
if x != 0
),
)
lines.insert_n_curves(200)
lines.apply_function(lambda p: plane.n2p(zeta(plane.p2n(p))))
lines.make_smooth()
lines.set_stroke(GREY_B, 1, opacity=0.5)
# self.add(lines)
c_line = Line(plane.c2p(0.5, 0), plane.c2p(0.5, 35))
c_line.insert_n_curves(1000)
c_line.apply_function(lambda p: plane.n2p(zeta(plane.p2n(p))))
c_line.make_smooth()
c_line.set_stroke([TEAL, YELLOW], width=[7, 3])
shadow = VGroup()
for w in np.linspace(25, 0, 50):
cc = c_line.copy()
cc.set_stroke(BLACK, width=w, opacity=0.025)
shadow.add(cc)
self.add(shadow)
self.add(c_line)
sym = OldTex("\\zeta\\left(s\\right)")
sym.set_height(1.5)
sym.move_to(FRAME_WIDTH * LEFT / 4 + FRAME_HEIGHT * UP / 4)
shadow = VGroup()
for w in np.linspace(50, 0, 50):
sc = sym.copy()
sc.set_fill(opacity=0)
sc.set_stroke(BLACK, width=w, opacity=0.05)
shadow.add(sc)
# self.add(shadow)
# self.add(sym)
class ZetaPartialSums(ZetaTransformationScene):
CONFIG = {
"anchor_density" : 35,
"num_partial_sums" : 12,
}
def construct(self):
self.add_transformable_plane()
self.add_extra_plane_lines_for_zeta()
self.prepare_for_transformation(self.plane)
N_list = [2**k for k in range(self.num_partial_sums)]
sigma = OldTex(
"\\sum_{n = 1}^N \\frac{1}{n^s}"
)
sigmas = []
for N in N_list + ["\\infty"]:
tex = OldTex(str(N))
tex.set_color(YELLOW)
new_sigma = sigma.copy()
top = new_sigma[0]
tex.move_to(top, DOWN)
new_sigma.remove(top)
new_sigma.add(tex)
new_sigma.to_corner(UP+LEFT)
sigmas.append(new_sigma)
def get_partial_sum_func(n_terms):
return lambda s : sum([1./(n**s) for n in range(1, n_terms+1)])
interim_planes = [
self.plane.copy().apply_complex_function(
get_partial_sum_func(N)
)
for N in N_list
]
interim_planes.append(self.plane.copy().apply_complex_function(zeta))
symbol = VGroup(OldTex("s"))
symbol.scale(2)
symbol.set_color(YELLOW)
symbol.to_corner(UP+LEFT)
for plane, sigma in zip(interim_planes, sigmas):
self.play(
Transform(self.plane, plane),
Transform(symbol, sigma)
)
self.wait()
|
|
from manim_imports_ext import *
import displayer as disp
from hilbert.curves import \
TransformOverIncreasingOrders, FlowSnake, HilbertCurve, \
SnakeCurve, Sierpinski
from hilbert.section1 import get_mathy_and_bubble
class SectionThree(Scene):
def construct(self):
self.add(OldTexText("A few words on the usefulness of infinite math"))
self.wait()
class InfiniteResultsFiniteWorld(Scene):
def construct(self):
left_words = OldTexText("Infinite result")
right_words = OldTexText("Finite world")
for words in left_words, right_words:
words.scale(0.8)
left_formula = OldTex(
"\\sum_{n = 0}^{\\infty} 2^n = -1"
)
right_formula = OldTex("111\\cdots111")
for formula in left_formula, right_formula:
formula.add(
Brace(formula, UP),
)
formula.ingest_submobjects()
right_overwords = OldTexText(
"\\substack{\
\\text{How computers} \\\\ \
\\text{represent $-1$}\
}"
).scale(1.5)
left_mobs = [left_words, left_formula]
right_mobs = [right_words, right_formula]
for mob in left_mobs:
mob.to_edge(RIGHT, buff = 1)
mob.shift(FRAME_X_RADIUS*LEFT)
for mob in right_mobs:
mob.to_edge(LEFT, buff = 1)
mob.shift(FRAME_X_RADIUS*RIGHT)
arrow = Arrow(left_words, right_words)
right_overwords.next_to(right_formula, UP)
self.play(ShimmerIn(left_words))
self.play(ShowCreation(arrow))
self.play(ShimmerIn(right_words))
self.wait()
self.play(
ShimmerIn(left_formula),
ApplyMethod(left_words.next_to, left_formula, UP)
)
self.wait()
self.play(
ShimmerIn(right_formula),
Transform(right_words, right_overwords)
)
self.wait()
self.finite_analog(
Mobject(left_formula, left_words),
arrow,
Mobject(right_formula, right_words)
)
def finite_analog(self, left_mob, arrow, right_mob):
self.clear()
self.add(left_mob, arrow, right_mob)
ex = OldTexText("\\times")
ex.set_color(RED)
# ex.shift(arrow.get_center())
middle = OldTex(
"\\sum_{n=0}^N 2^n \\equiv -1 \\mod 2^{N+1}"
)
finite_analog = OldTexText("Finite analog")
finite_analog.scale(0.8)
brace = Brace(middle, UP)
finite_analog.next_to(brace, UP)
new_left = left_mob.copy().to_edge(LEFT)
new_right = right_mob.copy().to_edge(RIGHT)
left_arrow, right_arrow = [
Arrow(
mob1.get_right()[0]*RIGHT,
mob2.get_left()[0]*RIGHT,
buff = 0
)
for mob1, mob2 in [
(new_left, middle),
(middle, new_right)
]
]
for mob in ex, middle:
mob.sort_points(get_norm)
self.play(GrowFromCenter(ex))
self.wait()
self.play(
Transform(left_mob, new_left),
Transform(arrow.copy(), left_arrow),
DelayByOrder(Transform(ex, middle)),
Transform(arrow, right_arrow),
Transform(right_mob, new_right)
)
self.play(
GrowFromCenter(brace),
ShimmerIn(finite_analog)
)
self.wait()
self.equivalence(
left_mob,
left_arrow,
Mobject(middle, brace, finite_analog)
)
def equivalence(self, left_mob, arrow, right_mob):
self.clear()
self.add(left_mob, arrow, right_mob)
words = OldTexText("is equivalent to")
words.shift(0.25*LEFT)
words.set_color(BLUE)
new_left = left_mob.copy().shift(RIGHT)
new_right = right_mob.copy()
new_right.shift(
(words.get_right()[0]-\
right_mob.get_left()[0]+\
0.5
)*RIGHT
)
for mob in arrow, words:
mob.sort_points(get_norm)
self.play(
ApplyMethod(left_mob.shift, RIGHT),
Transform(arrow, words),
ApplyMethod(right_mob.to_edge, RIGHT)
)
self.wait()
class HilbertCurvesStayStable(Scene):
def construct(self):
scale_factor = 0.9
grid = Grid(4, 4, stroke_width = 1)
curve = HilbertCurve(order = 2)
for mob in grid, curve:
mob.scale(scale_factor)
words = OldTexText("""
Sequence of curves is stable
$\\leftrightarrow$ existence of limit curve
""", size = "\\normal")
words.scale(1.25)
words.to_edge(UP)
self.add(curve, grid)
self.wait()
for n in range(3, 7):
if n == 5:
self.play(ShimmerIn(words))
new_grid = Grid(2**n, 2**n, stroke_width = 1)
new_curve = HilbertCurve(order = n)
for mob in new_grid, new_curve:
mob.scale(scale_factor)
self.play(
ShowCreation(new_grid),
Animation(curve)
)
self.remove(grid)
grid = new_grid
self.play(Transform(curve, new_curve))
self.wait()
class InfiniteObjectsEncapsulateFiniteObjects(Scene):
def get_triangles(self):
triangle = Polygon(
LEFT/np.sqrt(3),
UP,
RIGHT/np.sqrt(3),
color = GREEN
)
triangles = Mobject(
triangle.copy().scale(0.5).shift(LEFT),
triangle,
triangle.copy().scale(0.3).shift(0.5*UP+RIGHT)
)
triangles.center()
return triangles
def construct(self):
words =[
OldTexText(text, size = "\\large")
for text in [
"Truths about infinite objects",
" encapsulate ",
"facts about finite objects"
]
]
words[0].set_color(RED)
words[1].next_to(words[0])
words[2].set_color(GREEN).next_to(words[1])
Mobject(*words).center().to_edge(UP)
infinite_objects = [
OldTex(
"\\sum_{n=0}^\\infty",
size = "\\normal"
).set_color(RED_E),
Sierpinski(order = 8).scale(0.3),
OldTexText(
"$\\exists$ something infinite $\\dots$"
).set_color(RED_B)
]
finite_objects = [
OldTex(
"\\sum_{n=0}^N",
size = "\\normal"
).set_color(GREEN_E),
self.get_triangles(),
OldTexText(
"$\\forall$ finite somethings $\\dots$"
).set_color(GREEN_B)
]
for infinite, finite, n in zip(infinite_objects, finite_objects, it.count(1, 2)):
infinite.next_to(words[0], DOWN, buff = n)
finite.next_to(words[2], DOWN, buff = n)
self.play(ShimmerIn(words[0]))
self.wait()
self.play(ShimmerIn(infinite_objects[0]))
self.play(ShowCreation(infinite_objects[1]))
self.play(ShimmerIn(infinite_objects[2]))
self.wait()
self.play(ShimmerIn(words[1]), ShimmerIn(words[2]))
self.play(ShimmerIn(finite_objects[0]))
self.play(ShowCreation(finite_objects[1]))
self.play(ShimmerIn(finite_objects[2]))
self.wait()
class StatementRemovedFromReality(Scene):
def construct(self):
mathy, bubble = get_mathy_and_bubble()
bubble.stretch_to_fit_width(4)
mathy.to_corner(DOWN+LEFT)
bubble.pin_to(mathy)
bubble.shift(LEFT)
morty = Mortimer()
morty.to_corner(DOWN+RIGHT)
morty_bubble = SpeechBubble()
morty_bubble.stretch_to_fit_width(4)
morty_bubble.pin_to(morty)
bubble.write("""
Did you know a curve \\\\
can fill all space?
""")
morty_bubble.write("Who cares?")
self.add(mathy, morty)
for bub, buddy in [(bubble, mathy), (morty_bubble, morty)]:
self.play(Transform(
Point(bub.get_tip()),
bub
))
self.play(ShimmerIn(bub.content))
self.play(ApplyMethod(
buddy.blink,
rate_func = squish_rate_func(there_and_back)
))
|
|
from manim_imports_ext import *
import displayer as disp
from hilbert.curves import \
TransformOverIncreasingOrders, FlowSnake, HilbertCurve, \
SnakeCurve, PeanoCurve
from hilbert.section1 import get_mathy_and_bubble
from scipy.spatial.distance import cdist
def get_time_line():
length = 2.6*FRAME_WIDTH
year_range = 400
time_line = NumberLine(
numerical_radius = year_range/2,
unit_length_to_spatial_width = length/year_range,
tick_frequency = 10,
leftmost_tick = 1720,
number_at_center = 1870,
numbers_with_elongated_ticks = list(range(1700, 2100, 100))
)
time_line.sort_points(lambda p : p[0])
time_line.set_color_by_gradient(
PeanoCurve.CONFIG["start_color"],
PeanoCurve.CONFIG["end_color"]
)
time_line.add_numbers(
2020, *list(range(1800, 2050, 50))
)
return time_line
class SectionTwo(Scene):
def construct(self):
self.add(OldTexText("Section 2: Filling space"))
self.wait()
class HilbertCurveIsPerfect(Scene):
def construct(self):
curve = HilbertCurve(order = 6)
curve.set_color(WHITE)
colored_curve = curve.copy()
colored_curve.thin_out(3)
lion = ImageMobject("lion", invert = False)
lion.replace(curve, stretch = True)
sparce_lion = lion.copy()
sparce_lion.thin_out(100)
distance_matrix = cdist(colored_curve.points, sparce_lion.points)
closest_point_indices = np.apply_along_axis(
np.argmin, 1, distance_matrix
)
colored_curve.rgbas = sparce_lion.rgbas[closest_point_indices]
line = Line(5*LEFT, 5*RIGHT)
Mobject.align_data_and_family(line, colored_curve)
line.rgbas = colored_curve.rgbas
self.add(lion)
self.play(ShowCreation(curve, run_time = 3))
self.play(
FadeOut(lion),
Transform(curve, colored_curve),
run_time = 3
)
self.wait()
self.play(Transform(curve, line, run_time = 5))
self.wait()
class AskMathematicianFriend(Scene):
def construct(self):
mathy, bubble = get_mathy_and_bubble()
bubble.sort_points(lambda p : np.dot(p, UP+RIGHT))
self.add(mathy)
self.wait()
self.play(ApplyMethod(
mathy.blink,
rate_func = squish_rate_func(there_and_back)
))
self.wait()
self.play(ShowCreation(bubble))
self.wait()
self.play(
ApplyMethod(mathy.shift, 3*(DOWN+LEFT)),
ApplyPointwiseFunction(
lambda p : 15*p/get_norm(p),
bubble
),
run_time = 3
)
class TimeLineAboutSpaceFilling(Scene):
def construct(self):
curve = PeanoCurve(order = 5)
curve.stretch_to_fit_width(FRAME_WIDTH)
curve.stretch_to_fit_height(FRAME_HEIGHT)
curve_start = curve.copy()
curve_start.apply_over_attr_arrays(
lambda arr : arr[:200]
)
time_line = get_time_line()
time_line.shift(-time_line.number_to_point(2000))
self.add(time_line)
self.play(ApplyMethod(
time_line.shift,
-time_line.number_to_point(1900),
run_time = 3
))
brace = Brace(
Mobject(
Point(time_line.number_to_point(1865)),
Point(time_line.number_to_point(1888)),
),
UP
)
words = OldTexText("""
Cantor drives himself (and the \\\\
mathematical community at large) \\\\
crazy with research on infinity.
""")
words.next_to(brace, UP)
self.play(
GrowFromCenter(brace),
ShimmerIn(words)
)
self.wait()
self.play(
Transform(time_line, curve_start),
FadeOut(brace),
FadeOut(words)
)
self.play(ShowCreation(
curve,
run_time = 5,
rate_func=linear
))
self.wait()
class NotPixelatedSpace(Scene):
def construct(self):
grid = Grid(64, 64)
space_region = Region()
space_mobject = MobjectFromRegion(space_region, GREY_D)
curve = PeanoCurve(order = 5).replace(space_mobject)
line = Line(5*LEFT, 5*RIGHT)
line.set_color_by_gradient(curve.start_color, curve.end_color)
for mob in grid, space_mobject:
mob.sort_points(get_norm)
infinitely = OldTexText("Infinitely")
detailed = OldTexText("detailed")
extending = OldTexText("extending")
detailed.next_to(infinitely, RIGHT)
extending.next_to(infinitely, RIGHT)
Mobject(extending, infinitely, detailed).center()
arrows = Mobject(*[
Arrow(2*p, 4*p)
for theta in np.arange(np.pi/6, 2*np.pi, np.pi/3)
for p in [rotate_vector(RIGHT, theta)]
])
self.add(grid)
self.wait()
self.play(Transform(grid, space_mobject, run_time = 5))
self.remove(grid)
self.set_color_region(space_region, GREY_D)
self.wait()
self.add(infinitely, detailed)
self.wait()
self.play(DelayByOrder(Transform(detailed, extending)))
self.play(ShowCreation(arrows))
self.wait()
self.clear()
self.set_color_region(space_region, GREY_D)
self.play(ShowCreation(line))
self.play(Transform(line, curve, run_time = 5))
class HistoryOfDiscover(Scene):
def construct(self):
time_line = get_time_line()
time_line.shift(-time_line.number_to_point(1900))
hilbert_curve = HilbertCurve(order = 3)
peano_curve = PeanoCurve(order = 2)
for curve in hilbert_curve, peano_curve:
curve.scale(0.5)
hilbert_curve.to_corner(DOWN+RIGHT)
peano_curve.to_corner(UP+LEFT)
squares = Mobject(*[
Square(side_length=3, color=WHITE).replace(curve)
for curve in (hilbert_curve, peano_curve)
])
self.add(time_line)
self.wait()
for year, curve, vect, text in [
(1890, peano_curve, UP, "Peano Curve"),
(1891, hilbert_curve, DOWN, "Hilbert Curve"),
]:
point = time_line.number_to_point(year)
point[1] = 0.2
arrow = Arrow(point+2*vect, point, buff = 0.1)
arrow.set_color_by_gradient(curve.start_color, curve.end_color)
year_mob = OldTex(str(year))
year_mob.next_to(arrow, vect)
words = OldTexText(text)
words.next_to(year_mob, vect)
self.play(
ShowCreation(arrow),
ShimmerIn(year_mob),
ShimmerIn(words)
)
self.play(ShowCreation(curve))
self.wait()
self.play(ShowCreation(squares))
self.wait()
self.play(ApplyMethod(
Mobject(*self.mobjects).shift, 20*(DOWN+RIGHT)
))
class DefinitionOfCurve(Scene):
def construct(self):
start_words = OldTexText([
"``", "Space Filling", "Curve ''",
]).to_edge(TOP, buff = 0.25)
quote, space_filling, curve_quote = start_words.copy().split()
curve_quote.shift(
space_filling.get_left()-\
curve_quote.get_left()
)
space_filling = Point(space_filling.get_center())
end_words = Mobject(*[
quote, space_filling, curve_quote
]).center().to_edge(TOP, buff = 0.25)
space_filling_fractal = OldTexText("""
``Space Filling Fractal''
""").to_edge(UP)
curve = HilbertCurve(order = 2).shift(DOWN)
fine_curve = HilbertCurve(order = 8)
fine_curve.replace(curve)
dots = Mobject(*[
Dot(
curve.get_points()[n*curve.get_num_points()/15],
color = YELLOW_C
)
for n in range(1, 15)
if n not in [4, 11]
])
start_words.shift(2*(UP+LEFT))
self.play(
ApplyMethod(start_words.shift, 2*(DOWN+RIGHT))
)
self.wait()
self.play(Transform(start_words, end_words))
self.wait()
self.play(ShowCreation(curve))
self.wait()
self.play(ShowCreation(
dots,
run_time = 3,
))
self.wait()
self.clear()
self.play(ShowCreation(fine_curve, run_time = 5))
self.wait()
self.play(ShimmerIn(space_filling_fractal))
self.wait()
class PseudoHilbertCurvesDontFillSpace(Scene):
def construct(self):
curve = HilbertCurve(order = 1)
grid = Grid(2, 2, stroke_width=1)
self.add(grid, curve)
for order in range(2, 6):
self.wait()
new_grid = Grid(2**order, 2**order, stroke_width=1)
self.play(
ShowCreation(new_grid),
Animation(curve)
)
self.remove(grid)
grid = new_grid
self.play(Transform(
curve, HilbertCurve(order = order)
))
square = Square(side_length = 6, color = WHITE)
square.corner = Mobject1D()
square.corner.add_line(3*DOWN, ORIGIN)
square.corner.add_line(ORIGIN, 3*RIGHT)
square.digest_mobject_attrs()
square.scale(2**(-5))
square.corner.set_color(
Color(rgb = curve.rgbas[curve.get_num_points()/3])
)
square.shift(
grid.get_corner(UP+LEFT)-\
square.get_corner(UP+LEFT)
)
self.wait()
self.play(
FadeOut(grid),
FadeOut(curve),
FadeIn(square)
)
self.play(
ApplyMethod(square.replace, grid)
)
self.wait()
class HilbertCurveIsLimit(Scene):
def construct(self):
mathy, bubble = get_mathy_and_bubble()
bubble.write(
"A Hilbert curve is the \\\\ limit of all these \\dots"
)
self.add(mathy, bubble)
self.play(ShimmerIn(bubble.content))
self.wait()
class DefiningCurves(Scene):
def construct(self):
words = OldTexText(
["One does not simply define the limit \\\\ \
of a sequence of","curves","\\dots"]
)
top_words = OldTexText([
"curves", "are functions"
]).to_edge(UP)
curves1 = words.split()[1]
curves2 = top_words.split()[0]
words.ingest_submobjects()
number = OldTex("0.27")
pair = OldTex("(0.53, 0.02)")
pair.next_to(number, buff = 2)
arrow = Arrow(number, pair)
Mobject(number, arrow, pair).center().shift(UP)
number_line = UnitInterval()
number_line.stretch_to_fit_width(5)
number_line.to_edge(LEFT).shift(DOWN)
grid = Grid(4, 4).scale(0.4)
grid.next_to(number_line, buff = 2)
low_arrow = Arrow(number_line, grid)
self.play(ShimmerIn(words))
self.wait()
self.play(
FadeOut(words),
ApplyMethod(curves1.replace, curves2),
ShimmerIn(top_words.split()[1])
)
self.wait()
self.play(FadeIn(number))
self.play(ShowCreation(arrow))
self.play(FadeIn(pair))
self.wait()
self.play(ShowCreation(number_line))
self.play(ShowCreation(low_arrow))
self.play(ShowCreation(grid))
self.wait()
class PseudoHilbertCurveAsFunctionExample(Scene):
args_list = [(2,), (3,)]
# For subclasses to turn args in the above
# list into stings which can be appended to the name
@staticmethod
def args_to_string(order):
return "Order%d"%order
@staticmethod
def string_to_args(order_str):
return int(order_str)
def construct(self, order):
if order == 2:
result_tex = "(0.125, 0.75)"
elif order == 3:
result_tex = "(0.0758, 0.6875)"
phc, arg, result = OldTex([
"\\text{PHC}_%d"%order,
"(0.3)",
"= %s"%result_tex
]).to_edge(UP).split()
function = OldTexText("Function", size = "\\normal")
function.shift(phc.get_center()+DOWN+2*LEFT)
function_arrow = Arrow(function, phc)
line = Line(5*LEFT, 5*RIGHT)
curve = HilbertCurve(order = order)
line.match_colors(curve)
grid = Grid(2**order, 2**order)
grid.fade()
for mob in curve, grid:
mob.scale(0.7)
index = int(0.3*line.get_num_points())
dot1 = Dot(line.get_points()[index])
arrow1 = Arrow(arg, dot1, buff = 0.1)
dot2 = Dot(curve.get_points()[index])
arrow2 = Arrow(result.get_bottom(), dot2, buff = 0.1)
self.add(phc)
self.play(
ShimmerIn(function),
ShowCreation(function_arrow)
)
self.wait()
self.remove(function_arrow, function)
self.play(ShowCreation(line))
self.wait()
self.play(
ShimmerIn(arg),
ShowCreation(arrow1),
ShowCreation(dot1)
)
self.wait()
self.remove(arrow1)
self.play(
FadeIn(grid),
Transform(line, curve),
Transform(dot1, dot2),
run_time = 2
)
self.wait()
self.play(
ShimmerIn(result),
ShowCreation(arrow2)
)
self.wait()
class ContinuityRequired(Scene):
def construct(self):
words = OldTexText([
"A function must be",
"\\emph{continuous}",
"if it is to represent a curve."
])
words.split()[1].set_color(YELLOW_C)
self.add(words)
self.wait()
class FormalDefinitionOfContinuity(Scene):
def construct(self):
self.setup()
self.label_spaces()
self.move_dot()
self.label_jump()
self.draw_circles()
self.vary_circle_sizes()
self.discontinuous_point()
def setup(self):
self.input_color = YELLOW_C
self.output_color = RED
def spiril(t):
theta = 2*np.pi*t
return t*np.cos(theta)*RIGHT+t*np.sin(theta)*UP
self.spiril1 = ParametricCurve(
lambda t : 1.5*RIGHT + DOWN + 2*spiril(t),
density = 5*DEFAULT_POINT_DENSITY_1D,
)
self.spiril2 = ParametricCurve(
lambda t : 5.5*RIGHT + UP - 2*spiril(1-t),
density = 5*DEFAULT_POINT_DENSITY_1D,
)
Mobject.align_data_and_family(self.spiril1, self.spiril2)
self.output = Mobject(self.spiril1, self.spiril2)
self.output.ingest_submobjects()
self.output.set_color(GREEN_A)
self.interval = UnitInterval()
self.interval.set_width(FRAME_X_RADIUS-1)
self.interval.to_edge(LEFT)
self.input_dot = Dot(color = self.input_color)
self.output_dot = self.input_dot.copy().set_color(self.output_color)
left, right = self.interval.get_left(), self.interval.get_right()
self.input_homotopy = lambda x_y_z_t : (x_y_z_t[0], x_y_z_t[1], x_y_z_t[3]) + interpolate(left, right, x_y_z_t[3])
output_size = self.output.get_num_points()-1
output_points = self.output.points
self.output_homotopy = lambda x_y_z_t1 : (x_y_z_t1[0], x_y_z_t1[1], x_y_z_t1[2]) + output_points[int(x_y_z_t1[3]*output_size)]
def get_circles_and_points(self, min_input, max_input):
input_left, input_right = [
self.interval.number_to_point(num)
for num in (min_input, max_input)
]
input_circle = Circle(
radius = get_norm(input_left-input_right)/2,
color = WHITE
)
input_circle.shift((input_left+input_right)/2)
input_points = Line(
input_left, input_right,
color = self.input_color
)
output_points = Mobject(color = self.output_color)
n = self.output.get_num_points()
output_points.add_points(
self.output.get_points()[int(min_input*n):int(max_input*n)]
)
output_center = output_points.get_points()[int(0.5*output_points.get_num_points())]
max_distance = get_norm(output_center-output_points.get_points()[-1])
output_circle = Circle(
radius = max_distance,
color = WHITE
)
output_circle.shift(output_center)
return (
input_circle,
input_points,
output_circle,
output_points
)
def label_spaces(self):
input_space = OldTexText("Input Space")
input_space.to_edge(UP)
input_space.shift(LEFT*FRAME_X_RADIUS/2)
output_space = OldTexText("Output Space")
output_space.to_edge(UP)
output_space.shift(RIGHT*FRAME_X_RADIUS/2)
line = Line(
UP*FRAME_Y_RADIUS, DOWN*FRAME_Y_RADIUS,
color = WHITE
)
self.play(
ShimmerIn(input_space),
ShimmerIn(output_space),
ShowCreation(line),
ShowCreation(self.interval),
)
self.wait()
def move_dot(self):
kwargs = {
"rate_func" : None,
"run_time" : 3
}
self.play(
Homotopy(self.input_homotopy, self.input_dot, **kwargs),
Homotopy(self.output_homotopy, self.output_dot, **kwargs),
ShowCreation(self.output, **kwargs)
)
self.wait()
def label_jump(self):
jump_points = Mobject(
Point(self.spiril1.get_points()[-1]),
Point(self.spiril2.get_points()[0])
)
self.brace = Brace(jump_points, RIGHT)
self.jump = OldTexText("Jump")
self.jump.next_to(self.brace, RIGHT)
self.play(
GrowFromCenter(self.brace),
ShimmerIn(self.jump)
)
self.wait()
self.remove(self.brace, self.jump)
def draw_circles(self):
input_value = 0.45
input_radius = 0.04
for dot in self.input_dot, self.output_dot:
dot.center()
kwargs = {
"rate_func" : lambda t : interpolate(1, input_value, smooth(t))
}
self.play(
Homotopy(self.input_homotopy, self.input_dot, **kwargs),
Homotopy(self.output_homotopy, self.output_dot, **kwargs)
)
A, B = list(map(Mobject.get_center, [self.input_dot, self.output_dot]))
A_text = OldTexText("A")
A_text.shift(A+2*(LEFT+UP))
A_arrow = Arrow(
A_text, self.input_dot,
color = self.input_color
)
B_text = OldTexText("B")
B_text.shift(B+2*RIGHT+DOWN)
B_arrow = Arrow(
B_text, self.output_dot,
color = self.output_color
)
tup = self.get_circles_and_points(
input_value-input_radius,
input_value+input_radius
)
input_circle, input_points, output_circle, output_points = tup
for text, arrow in [(A_text, A_arrow), (B_text, B_arrow)]:
self.play(
ShimmerIn(text),
ShowCreation(arrow)
)
self.wait()
self.remove(A_text, A_arrow, B_text, B_arrow)
self.play(ShowCreation(input_circle))
self.wait()
self.play(ShowCreation(input_points))
self.wait()
input_points_copy = input_points.copy()
self.play(
Transform(input_points_copy, output_points),
run_time = 2
)
self.wait()
self.play(ShowCreation(output_circle))
self.wait()
self.wait()
self.remove(*[
input_circle, input_points,
output_circle, input_points_copy
])
def vary_circle_sizes(self):
input_value = 0.45
radius = 0.04
vary_circles = VaryCircles(
self, input_value, radius,
run_time = 5,
)
self.play(vary_circles)
self.wait()
text = OldTexText("Function is ``Continuous at A''")
text.shift(2*UP).to_edge(LEFT)
arrow = Arrow(text, self.input_dot)
self.play(
ShimmerIn(text),
ShowCreation(arrow)
)
self.wait()
self.remove(vary_circles.mobject, text, arrow)
def discontinuous_point(self):
point_description = OldTexText(
"Point where the function jumps"
)
point_description.shift(3*RIGHT)
discontinuous_at_A = OldTexText(
"``Discontinuous at A''",
size = "\\Large"
)
discontinuous_at_A.shift(2*UP).to_edge(LEFT)
text = OldTexText("""
Circle around ouput \\\\
points can never \\\\
be smaller than \\\\
the jump
""")
text.scale(0.75)
text.shift(3.5*RIGHT)
input_value = 0.5
input_radius = 0.04
vary_circles = VaryCircles(
self, input_value, input_radius,
run_time = 5,
)
for dot in self.input_dot, self.output_dot:
dot.center()
kwargs = {
"rate_func" : lambda t : interpolate(0.45, input_value, smooth(t))
}
self.play(
Homotopy(self.input_homotopy, self.input_dot, **kwargs),
Homotopy(self.output_homotopy, self.output_dot, **kwargs)
)
discontinuous_arrow = Arrow(discontinuous_at_A, self.input_dot)
arrow = Arrow(
point_description, self.output_dot,
buff = 0.05,
color = self.output_color
)
self.play(
ShimmerIn(point_description),
ShowCreation(arrow)
)
self.wait()
self.remove(point_description, arrow)
tup = self.get_circles_and_points(
input_value-input_radius,
input_value+input_radius
)
input_circle, input_points, output_circle, output_points = tup
input_points_copy = input_points.copy()
self.play(ShowCreation(input_circle))
self.play(ShowCreation(input_points))
self.play(
Transform(input_points_copy, output_points),
run_time = 2
)
self.play(ShowCreation(output_circle))
self.wait()
self.play(ShimmerIn(text))
self.remove(input_circle, input_points, output_circle, input_points_copy)
self.play(vary_circles)
self.wait()
self.play(
ShimmerIn(discontinuous_at_A),
ShowCreation(discontinuous_arrow)
)
self.wait(3)
self.remove(vary_circles.mobject, discontinuous_at_A, discontinuous_arrow)
def continuous_point(self):
pass
class VaryCircles(Animation):
def __init__(self, scene, input_value, radius, **kwargs):
digest_locals(self)
Animation.__init__(self, Mobject(), **kwargs)
def interpolate_mobject(self, alpha):
radius = self.radius + 0.9*self.radius*np.sin(1.5*np.pi*alpha)
self.mobject = Mobject(*self.scene.get_circles_and_points(
self.input_value-radius,
self.input_value+radius
)).ingest_submobjects()
class FunctionIsContinuousText(Scene):
def construct(self):
all_points = OldTexText("$f$ is continuous at every input point")
continuous = OldTexText("$f$ is continuous")
all_points.shift(UP)
continuous.shift(DOWN)
arrow = Arrow(all_points, continuous)
self.play(ShimmerIn(all_points))
self.play(ShowCreation(arrow))
self.play(ShimmerIn(continuous))
self.wait()
class DefineActualHilbertCurveText(Scene):
def construct(self):
self.add(OldTexText("""
Finally define a Hilbert Curve\\dots
"""))
self.wait()
class ReliesOnWonderfulProperty(Scene):
def construct(self):
self.add(OldTexText("""
\\dots which relies on a certain property
of Pseudo-Hilbert-curves.
"""))
self.wait()
class WonderfulPropertyOfPseudoHilbertCurves(Scene):
def construct(self):
val = 0.3
text = OldTexText([
"PHC", "$_n", "(", "%3.1f"%val, ")$",
" has a ", "limit point ", "as $n \\to \\infty$"
])
func_parts = text.copy().split()[:5]
Mobject(*func_parts).center().to_edge(UP)
num_str, val_str = func_parts[1], func_parts[3]
curve = UnitInterval()
curve.sort_points(lambda p : p[0])
dot = Dot().shift(curve.number_to_point(val))
arrow = Arrow(val_str, dot, buff = 0.1)
curve.add_numbers(0, 1)
self.play(ShowCreation(curve))
self.play(
ShimmerIn(val_str),
ShowCreation(arrow),
ShowCreation(dot)
)
self.wait()
self.play(
FadeOut(arrow),
*[
FadeIn(func_parts[i])
for i in (0, 1, 2, 4)
]
)
for num in range(2,9):
new_curve = HilbertCurve(order = num)
new_curve.scale(0.8)
new_dot = Dot(new_curve.get_points()[int(val*new_curve.get_num_points())])
new_num_str = OldTex(str(num)).replace(num_str)
self.play(
Transform(curve, new_curve),
Transform(dot, new_dot),
Transform(num_str, new_num_str)
)
self.wait()
text.to_edge(UP)
text_parts = text.split()
for index in 1, -1:
text_parts[index].set_color()
starters = Mobject(*func_parts + [
Point(mob.get_center(), stroke_width=1)
for mob in text_parts[5:]
])
self.play(Transform(starters, text))
arrow = Arrow(text_parts[-2].get_bottom(), dot, buff = 0.1)
self.play(ShowCreation(arrow))
self.wait()
class FollowManyPoints(Scene):
def construct(self):
text = OldTexText([
"PHC", "_n", "(", "x", ")$",
" has a limit point ", "as $n \\to \\infty$",
"\\\\ for all $x$"
])
parts = text.split()
parts[-1].next_to(Mobject(*parts[:-1]), DOWN)
parts[-1].set_color(BLUE)
parts[3].set_color(BLUE)
parts[1].set_color()
parts[-2].set_color()
text.to_edge(UP)
curve = UnitInterval()
curve.sort_points(lambda p : p[0])
vals = np.arange(0.1, 1, 0.1)
dots = Mobject(*[
Dot(curve.number_to_point(val))
for val in vals
])
curve.add_numbers(0, 1)
starter_dots = dots.copy().ingest_submobjects()
starter_dots.shift(2*UP)
self.add(curve, text)
self.wait()
self.play(DelayByOrder(ApplyMethod(starter_dots.shift, 2*DOWN)))
self.wait()
self.remove(starter_dots)
self.add(dots)
for num in range(1, 10):
new_curve = HilbertCurve(order = num)
new_curve.scale(0.8)
new_dots = Mobject(*[
Dot(new_curve.get_points()[int(val*new_curve.get_num_points())])
for val in vals
])
self.play(
Transform(curve, new_curve),
Transform(dots, new_dots),
)
# self.wait()
class FormalDefinitionOfHilbertCurve(Scene):
def construct(self):
val = 0.7
text = OldTex([
"\\text{HC}(", "x", ")",
"=\\lim_{n \\to \\infty}\\text{PHC}_n(", "x", ")"
])
text.to_edge(UP)
x1 = text.split()[1]
x2 = text.split()[-2]
x2.set_color(BLUE)
explanation = OldTexText("Actual Hilbert curve function")
exp_arrow = Arrow(explanation, text.split()[0])
curve = UnitInterval()
dot = Dot(curve.number_to_point(val))
x_arrow = Arrow(x1.get_bottom(), dot, buff = 0)
curve.sort_points(lambda p : p[0])
curve.add_numbers(0, 1)
self.add(*text.split()[:3])
self.play(
ShimmerIn(explanation),
ShowCreation(exp_arrow)
)
self.wait()
self.remove(explanation, exp_arrow)
self.play(ShowCreation(curve))
self.play(
ApplyMethod(x1.set_color, BLUE),
ShowCreation(x_arrow),
ShowCreation(dot)
)
self.wait()
self.remove(x_arrow)
limit = Mobject(*text.split()[3:]).ingest_submobjects()
limit.stroke_width = 1
self.play(ShimmerIn(limit))
for num in range(1, 9):
new_curve = HilbertCurve(order = num)
new_curve.scale(0.8)
new_dot = Dot(new_curve.get_points()[int(val*new_curve.get_num_points())])
self.play(
Transform(curve, new_curve),
Transform(dot, new_dot),
)
class CouldNotDefineForSnakeCurve(Scene):
def construct(self):
self.add(OldTexText("""
You could not define a limit curve from
snake curves.
"""))
self.wait()
class ThreeThingsToProve(Scene):
def construct(self):
definition = OldTex([
"\\text{HC}(", "x", ")",
"=\\lim_{n \\to \\infty}\\text{PHC}_n(", "x", ")"
])
definition.to_edge(UP)
definition.split()[1].set_color(BLUE)
definition.split()[-2].set_color(BLUE)
intro = OldTexText("Three things need to be proven")
prove_that = OldTexText("Prove that HC is $\\dots$")
prove_that.scale(0.7)
prove_that.to_edge(LEFT)
items = OldTexText([
"\\begin{enumerate}",
"\\item Well-defined: ",
"Points on Pseudo-Hilbert-curves really do converge",
"\\item A Curve: ",
"HC is continuous",
"\\item Space-filling: ",
"Each point in the unit square is an output of HC",
"\\end{enumerate}",
]).split()
items[1].set_color(GREEN)
items[3].set_color(YELLOW_C)
items[5].set_color(MAROON)
Mobject(*items).to_edge(RIGHT)
self.add(definition)
self.play(ShimmerIn(intro))
self.wait()
self.play(Transform(intro, prove_that))
for item in items[1:-1]:
self.play(ShimmerIn(item))
self.wait()
class TilingSpace(Scene):
def construct(self):
coords_set = [ORIGIN]
for n in range(int(FRAME_WIDTH)):
for vect in UP, RIGHT:
for k in range(n):
new_coords = coords_set[-1]+((-1)**n)*vect
coords_set.append(new_coords)
square = Square(side_length = 1, color = WHITE)
squares = Mobject(*[
square.copy().shift(coords)
for coords in coords_set
]).ingest_submobjects()
self.play(
DelayByOrder(FadeIn(squares)),
run_time = 3
)
curve = HilbertCurve(order = 6).scale(1./6)
all_curves = Mobject(*[
curve.copy().shift(coords)
for coords in coords_set
]).ingest_submobjects()
all_curves.thin_out(10)
self.play(ShowCreation(
all_curves,
rate_func=linear,
run_time = 15
))
class ColorIntervals(Scene):
def construct(self):
number_line = NumberLine(
numerical_radius = 5,
number_at_center = 5,
leftmost_tick = 0,
density = 2*DEFAULT_POINT_DENSITY_1D
)
number_line.shift(2*RIGHT)
number_line.add_numbers()
number_line.scale(2)
brace = Brace(Mobject(
*number_line.submobjects[:2]
))
self.add(number_line)
for n in range(0, 10, 2):
if n == 0:
brace_anim = GrowFromCenter(brace)
else:
brace_anim = ApplyMethod(brace.shift, 2*RIGHT)
self.play(
ApplyMethod(
number_line.set_color,
RED,
lambda p : p[0] > n-6.2 and p[0] < n-4 and p[1] > -0.4
),
brace_anim
)
|
|
from manim_imports_ext import *
import displayer as disp
from hilbert.curves import \
TransformOverIncreasingOrders, FlowSnake, HilbertCurve, \
SnakeCurve
from constants import *
def get_grid():
return Grid(64, 64)
def get_freq_line():
return UnitInterval().shift(2*DOWN) ##Change?
def get_mathy_and_bubble():
mathy = Mathematician()
mathy.to_edge(DOWN).shift(4*LEFT)
bubble = SpeechBubble(initial_width = 8)
bubble.pin_to(mathy)
return mathy, bubble
class AboutSpaceFillingCurves(TransformOverIncreasingOrders):
@staticmethod
def args_to_string():
return ""
@staticmethod
def string_to_args(arg_str):
return ()
def construct(self):
self.bubble = ThoughtBubble().ingest_submobjects()
self.bubble.scale(1.5)
TransformOverIncreasingOrders.construct(self, FlowSnake, 7)
self.play(Transform(self.curve, self.bubble))
self.show_infinite_objects()
self.pose_question()
self.wait()
def show_infinite_objects(self):
sigma, summand, equals, result = OldTex([
"\\sum_{n = 1}^{\\infty}",
"\\dfrac{1}{n^2}",
"=",
"\\dfrac{\pi^2}{6}"
]).split()
alt_summand = OldTex("n").replace(summand)
alt_result = OldTex("-\\dfrac{1}{12}").replace(result)
rationals, other_equals, naturals = OldTex([
"|\\mathds{Q}|",
"=",
"|\\mathds{N}|"
]).scale(2).split()
infinity = OldTex("\\infty").scale(2)
local_mobjects = list(filter(
lambda m : isinstance(m, Mobject),
list(locals().values()),
))
for mob in local_mobjects:
mob.sort_points(get_norm)
self.play(ShimmerIn(infinity))
self.wait()
self.play(
ShimmerIn(summand),
ShimmerIn(equals),
ShimmerIn(result),
DelayByOrder(Transform(infinity, sigma))
)
self.wait()
self.play(
Transform(summand, alt_summand),
Transform(result, alt_result),
)
self.wait()
self.remove(infinity)
self.play(*[
CounterclockwiseTransform(
Mobject(summand, equals, result, sigma),
Mobject(rationals, other_equals, naturals)
)
])
self.wait()
self.clear()
self.add(self.bubble)
def pose_question(self):
infinity, rightarrow, N = OldTex([
"\\infty", "\\rightarrow", "N"
]).scale(2).split()
question_mark = OldTexText("?").scale(2)
self.add(question_mark)
self.wait()
self.play(*[
ShimmerIn(mob)
for mob in (infinity, rightarrow, N)
] + [
ApplyMethod(question_mark.next_to, rightarrow, UP),
])
self.wait()
class PostponePhilosophizing(Scene):
def construct(self):
abstract, arrow, concrete = OldTexText([
"Abstract", " $\\rightarrow$ ", "Concrete"
]).scale(2).split()
self.add(abstract, arrow, concrete)
self.wait()
self.play(*[
ApplyMethod(
word1.replace, word2,
path_func = path_along_arc(np.pi/2)
)
for word1, word2 in it.permutations([abstract, concrete])
])
self.wait()
class GrowHilbertWithName(Scene):
def construct(self):
curve = HilbertCurve(order = 1)
words = OldTexText("``Hilbert Curve''")
words.to_edge(UP, buff = 0.2)
self.play(
ShimmerIn(words),
Transform(curve, HilbertCurve(order = 2)),
run_time = 2
)
for n in range(3, 8):
self.play(
Transform(curve, HilbertCurve(order = n)),
run_time = 5. /n
)
class SectionOne(Scene):
def construct(self):
self.add(OldTexText("Section 1: Seeing with your ears"))
self.wait()
class WriteSomeSoftware(Scene):
pass #Done viea screen capture, written here for organization
class ImageToSound(Scene):
def construct(self):
string = Vibrate(color = BLUE_D, run_time = 5)
picture = ImageMobject("lion", invert = False)
picture.scale(0.8)
picture_copy = picture.copy()
picture.sort_points(get_norm)
string.mobject.sort_points(lambda p : -get_norm(p))
self.add(picture)
self.wait()
self.play(Transform(
picture, string.mobject,
run_time = 3,
rate_func = rush_into
))
self.remove(picture)
self.play(string)
for mob in picture_copy, string.mobject:
mob.sort_points(lambda p : get_norm(p)%1)
self.play(Transform(
string.mobject, picture_copy,
run_time = 5,
rate_func = rush_from
))
class LinksInDescription(Scene):
def construct(self):
text = OldTexText("""
See links in the description for more on
sight via sound.
""")
self.play(ShimmerIn(text))
self.play(ShowCreation(Arrow(text, 3*DOWN)))
self.wait(2)
class ImageDataIsTwoDimensional(Scene):
def construct(self):
image = ImageMobject("lion", invert = False)
image.scale(0.5)
image.shift(2*LEFT)
self.add(image)
for vect, num in zip([DOWN, RIGHT], [1, 2]):
brace = Brace(image, vect)
words_mob = OldTexText("Dimension %d"%num)
words_mob.next_to(image, vect, buff = 1)
self.play(
Transform(Point(brace.get_center()), brace),
ShimmerIn(words_mob),
run_time = 2
)
self.wait()
class SoundDataIsOneDimensional(Scene):
def construct(self):
overtones = 5
floor = 2*DOWN
main_string = Vibrate(color = BLUE_D)
component_strings = [
Vibrate(
num_periods = k+1,
overtones = 1,
color = color,
center = 2*DOWN + UP*k
)
for k, color in zip(
list(range(overtones)),
Color(BLUE_E).range_to(WHITE, overtones)
)
]
dots = [
Dot(
string.mobject.get_center(),
color = string.mobject.get_color()
)
for string in component_strings
]
freq_line = get_freq_line()
freq_line.shift(floor)
freq_line.sort_points(get_norm)
brace = Brace(freq_line, UP)
words = OldTexText("Range of frequency values")
words.next_to(brace, UP)
self.play(*[
TransformAnimations(
main_string.copy(),
string,
run_time = 5
)
for string in component_strings
])
self.clear()
self.play(*[
TransformAnimations(
string,
Animation(dot)
)
for string, dot in zip(component_strings, dots)
])
self.clear()
self.play(
ShowCreation(freq_line),
GrowFromCenter(brace),
ShimmerIn(words),
*[
Transform(
dot,
dot.copy().scale(2).rotate(-np.pi/2).shift(floor),
path_func = path_along_arc(np.pi/3)
)
for dot in dots
]
)
self.wait(0.5)
class GridOfPixels(Scene):
def construct(self):
low_res = ImageMobject("low_resolution_lion", invert = False)
high_res = ImageMobject("Lion", invert = False)
grid = get_grid().scale(0.8)
for mob in low_res, high_res:
mob.replace(grid, stretch = True)
side_brace = Brace(low_res, LEFT)
top_brace = Brace(low_res, UP)
top_words = OldTexText("256 Px", size = "\\normal")
side_words = top_words.copy().rotate(np.pi/2)
top_words.next_to(top_brace, UP)
side_words.next_to(side_brace, LEFT)
self.add(high_res)
self.wait()
self.play(DelayByOrder(Transform(high_res, low_res)))
self.wait()
self.play(
GrowFromCenter(top_brace),
GrowFromCenter(side_brace),
ShimmerIn(top_words),
ShimmerIn(side_words)
)
self.wait()
for mob in grid, high_res:
mob.sort_points(get_norm)
self.play(DelayByOrder(Transform(high_res, grid)))
self.wait()
class ShowFrequencySpace(Scene):
def construct(self):
freq_line = get_freq_line()
self.add(freq_line)
self.wait()
for tex, vect in zip(["20 Hz", "20{,}000 Hz"], [LEFT, RIGHT]):
tex_mob = OldTexText(tex)
tex_mob.to_edge(vect)
tex_mob.shift(UP)
arrow = Arrow(tex_mob, freq_line.get_edge_center(vect))
self.play(
ShimmerIn(tex_mob),
ShowCreation(arrow)
)
self.wait()
class AssociatePixelWithFrequency(Scene):
def construct(self):
big_grid_dim = 20.
small_grid_dim = 6.
big_grid = Grid(64, 64, height = big_grid_dim, width = big_grid_dim)
big_grid.to_corner(UP+RIGHT, buff = 2)
small_grid = big_grid.copy()
small_grid.scale(small_grid_dim/big_grid_dim)
small_grid.center()
pixel = MobjectFromRegion(
region_from_polygon_vertices(*0.2*np.array([
RIGHT+DOWN,
RIGHT+UP,
LEFT+UP,
LEFT+DOWN
]))
)
pixel.set_color(WHITE)
pixel_width = big_grid.width/big_grid.columns
pixel.set_width(pixel_width)
pixel.to_corner(UP+RIGHT, buff = 2)
pixel.shift(5*pixel_width*(2*LEFT+DOWN))
freq_line = get_freq_line()
dot = Dot()
dot.shift(freq_line.get_center() + 2*RIGHT)
string = Line(LEFT, RIGHT, color = GREEN)
arrow = Arrow(dot, string.get_center())
vibration_config = {
"overtones" : 1,
"spatial_period" : 2,
}
vibration, loud_vibration, quiet_vibration = [
Vibrate(string.copy(), amplitude = a, **vibration_config)
for a in [0.5, 1., 0.25]
]
self.add(small_grid)
self.wait()
self.play(
Transform(small_grid, big_grid)
)
self.play(FadeIn(pixel))
self.wait()
self.play(
FadeOut(small_grid),
ShowCreation(freq_line)
)
self.remove(small_grid)
self.play(
Transform(pixel, dot),
)
self.wait()
self.play(ShowCreation(arrow))
self.play(loud_vibration)
self.play(
TransformAnimations(loud_vibration, quiet_vibration),
ApplyMethod(dot.fade, 0.9)
)
self.clear()
self.add(freq_line, dot, arrow)
self.play(quiet_vibration)
class ListenToAllPixels(Scene):
def construct(self):
grid = get_grid()
grid.sort_points(get_norm)
freq_line = get_freq_line()
freq_line.sort_points(lambda p : p[0])
red, blue = Color(RED), Color(BLUE)
freq_line.set_color_by_gradient(red, blue)
colors = [
Color(rgb = interpolate(
np.array(red.rgb),
np.array(blue.rgb),
alpha
))
for alpha in np.arange(4)/3.
]
string = Line(3*LEFT, 3*RIGHT, color = colors[1])
vibration = Vibrate(string)
vibration_copy = vibration.copy()
vibration_copy.mobject.stroke_width = 1
sub_vibrations = [
Vibrate(
string.copy().shift((n-1)*UP).set_color(colors[n]),
overtones = 1,
spatial_period = 6./(n+1),
temporal_period = 1./(n+1),
amplitude = 0.5/(n+1)
)
for n in range(4)
]
words = OldTex("&\\vdots \\\\ \\text{thousands }& \\text{of frequencies} \\\\ &\\vdots")
words.to_edge(UP, buff = 0.1)
self.add(grid)
self.wait()
self.play(DelayByOrder(ApplyMethod(
grid.set_color_by_gradient, red, blue
)))
self.play(Transform(grid, freq_line))
self.wait()
self.play(
ShimmerIn(
words,
rate_func = squish_rate_func(smooth, 0, 0.2)
),
*sub_vibrations,
run_time = 5
)
self.play(
*[
TransformAnimations(
sub_vib, vibration
)
for sub_vib in sub_vibrations
]+[FadeOut(words)]
)
self.clear()
self.add(freq_line)
self.play(vibration)
class LayAsideSpeculation(Scene):
def construct(self):
words = OldTexText("Would this actually work?")
grid = get_grid()
grid.set_width(6)
grid.to_edge(LEFT)
freq_line = get_freq_line()
freq_line.set_width(6)
freq_line.center().to_edge(RIGHT)
mapping = Mobject(
grid, freq_line, Arrow(grid, freq_line)
)
mapping.ingest_submobjects()
lower_left = Point().to_corner(DOWN+LEFT, buff = 0)
lower_right = Point().to_corner(DOWN+RIGHT, buff = 0)
self.add(words)
self.wait()
self.play(
Transform(words, lower_right),
Transform(lower_left, mapping)
)
self.wait()
class RandomMapping(Scene):
def construct(self):
grid = get_grid()
grid.set_width(6)
grid.to_edge(LEFT)
freq_line = get_freq_line()
freq_line.set_width(6)
freq_line.center().to_edge(RIGHT)
# for mob in grid, freq_line:
# indices = np.arange(mob.get_num_points())
# random.shuffle(indices)
# mob.points = mob.get_points()[indices]
stars = Stars(stroke_width = grid.stroke_width)
self.add(grid)
targets = [stars, freq_line]
alphas = [not_quite_there(rush_into), rush_from]
for target, rate_func in zip(targets, alphas):
self.play(Transform(
grid, target,
run_time = 3,
rate_func = rate_func,
path_func = path_along_arc(-np.pi/2)
))
self.wait()
class DataScrambledAnyway(Scene):
def construct(self):
self.add(OldTexText("Data is scrambled anyway, right?"))
self.wait()
class LeverageExistingIntuitions(Scene):
def construct(self):
self.add(OldTexText("Leverage existing intuitions"))
self.wait()
class ThinkInTermsOfReverseMapping(Scene):
def construct(self):
grid = get_grid()
grid.set_width(6)
grid.to_edge(LEFT)
freq_line = get_freq_line()
freq_line.set_width(6)
freq_line.center().to_edge(RIGHT)
arrow = Arrow(grid, freq_line)
color1, color2 = YELLOW_C, RED
square_length = 0.01
dot1 = Dot(color = color1)
dot1.shift(3*RIGHT)
dot2 = Dot(color = color2)
dot2.shift(3.1*RIGHT)
arrow1 = Arrow(2*RIGHT+UP, dot1, color = color1, buff = 0.1)
arrow2 = Arrow(4*RIGHT+UP, dot2, color = color2, buff = 0.1)
dot3, arrow3 = [
mob.copy().shift(5*LEFT+UP)
for mob in (dot1, arrow1)
]
dot4, arrow4 = [
mob.copy().shift(5*LEFT+0.9*UP)
for mob in (dot2, arrow2)
]
self.add(grid, freq_line, arrow)
self.wait()
self.play(ApplyMethod(
arrow.rotate, np.pi,
path_func = clockwise_path()
))
self.wait()
self.play(ShowCreation(arrow1))
self.add(dot1)
self.play(ShowCreation(arrow2))
self.add(dot2)
self.wait()
self.remove(arrow1, arrow2)
self.play(
Transform(dot1, dot3),
Transform(dot2, dot4)
)
self.play(
ApplyMethod(grid.fade, 0.8),
Animation(Mobject(dot3, dot4))
)
self.play(ShowCreation(arrow3))
self.play(ShowCreation(arrow4))
self.wait()
class WeaveLineThroughPixels(Scene):
@staticmethod
def args_to_string(order):
return str(order)
@staticmethod
def string_to_args(order_str):
return int(order_str)
def construct(self, order):
start_color, end_color = RED, GREEN
curve = HilbertCurve(order = order)
line = Line(5*LEFT, 5*RIGHT)
for mob in curve, line:
mob.set_color_by_gradient(start_color, end_color)
freq_line = get_freq_line()
freq_line.replace(line, stretch = True)
unit = 6./(2**order) #sidelength of pixel
up = unit*UP
right = unit*RIGHT
lower_left = 3*(LEFT+DOWN)
squares = Mobject(*[
Square(
side_length = unit,
color = WHITE
).shift(x*right+y*up)
for x, y in it.product(list(range(2**order)), list(range(2**order)))
])
squares.center()
targets = Mobject()
for square in squares.submobjects:
center = square.get_center()
distances = np.apply_along_axis(
lambda p : get_norm(p-center),
1,
curve.points
)
index_along_curve = np.argmin(distances)
fraction_along_curve = index_along_curve/float(curve.get_num_points())
target = square.copy().center().scale(0.8/(2**order))
line_index = int(fraction_along_curve*line.get_num_points())
target.shift(line.get_points()[line_index])
targets.add(target)
self.add(squares)
self.play(ShowCreation(
curve,
run_time = 5,
rate_func=linear
))
self.wait()
self.play(
Transform(curve, line),
Transform(squares, targets),
run_time = 3
)
self.wait()
self.play(ShowCreation(freq_line))
self.wait()
class WellPlayedGameOfSnake(Scene):
def construct(self):
grid = Grid(16, 16).fade()
snake_curve = SnakeCurve(order = 4)
words = OldTexText("``Snake Curve''")
words.next_to(grid, UP)
self.add(grid)
self.play(ShowCreation(
snake_curve,
run_time = 7,
rate_func=linear
))
self.wait()
self.play(ShimmerIn(words))
self.wait()
class TellMathematicianFriend(Scene):
def construct(self):
mathy, bubble = get_mathy_and_bubble()
squiggle_mouth = mathy.mouth.copy()
squiggle_mouth.apply_function(
lambda x_y_z : (x_y_z[0], x_y_z[1]+0.02*np.sin(50*x_y_z[0]), x_y_z[2])
)
bubble.ingest_submobjects()
bubble.write("Why not use a Hilbert curve \\textinterrobang ")
words1 = bubble.content
bubble.write("So, it's not one curve but an infinite family of curves \\dots")
words2 = bubble.content
bubble.write("Well, no, it \\emph{is} just one thing, but I need \\\\ \
to tell you about a certain infinite family first.")
words3 = bubble.content
description = OldTexText("Mathematician friend", size = "\\small")
description.next_to(mathy, buff = 2)
arrow = Arrow(description, mathy)
self.add(mathy)
self.play(
ShowCreation(arrow),
ShimmerIn(description)
)
self.wait()
point = Point(bubble.get_tip())
self.play(
Transform(point, bubble),
)
self.remove(point)
self.add(bubble)
self.play(ShimmerIn(words1))
self.wait()
self.remove(description, arrow)
self.play(
Transform(mathy.mouth, squiggle_mouth),
ApplyMethod(mathy.arm.wag, 0.2*RIGHT, LEFT),
)
self.remove(words1)
self.add(words2)
self.wait(2)
self.remove(words2)
self.add(words3)
self.wait(2)
self.play(
ApplyPointwiseFunction(
lambda p : 15*p/get_norm(p),
bubble
),
ApplyMethod(mathy.shift, 5*(DOWN+LEFT)),
FadeOut(words3),
run_time = 3
)
class Order1PseudoHilbertCurve(Scene):
def construct(self):
words, s = OldTexText(["Pseudo-Hilbert Curve", "s"]).split()
pre_words = OldTexText("Order 1")
pre_words.next_to(words, LEFT, buff = 0.5)
s.next_to(words, RIGHT, buff = 0.05, aligned_edge = DOWN)
cluster = Mobject(pre_words, words, s)
cluster.center()
cluster.scale(0.7)
cluster.to_edge(UP, buff = 0.3)
cluster.set_color(GREEN)
grid1 = Grid(1, 1)
grid2 = Grid(2, 2)
curve = HilbertCurve(order = 1)
self.add(words, s)
self.wait()
self.play(Transform(
s, pre_words,
path_func = path_along_arc(-np.pi/3)
))
self.wait()
self.play(ShowCreation(grid1))
self.wait()
self.play(ShowCreation(grid2))
self.wait()
kwargs = {
"run_time" : 5,
"rate_func" : None
}
self.play(ShowCreation(curve, **kwargs))
self.wait()
class Order2PseudoHilbertCurve(Scene):
def construct(self):
words = OldTexText("Order 2 Pseudo-Hilbert Curve")
words.to_edge(UP, buff = 0.3)
words.set_color(GREEN)
grid2 = Grid(2, 2)
grid4 = Grid(4, 4, stroke_width = 2)
# order_1_curve = HilbertCurve(order = 1)
# squaggle_curve = order_1_curve.copy().apply_function(
# lambda (x, y, z) : (x + np.cos(3*y), y + np.sin(3*x), z)
# )
# squaggle_curve.show()
mini_curves = [
HilbertCurve(order = 1).scale(0.5).shift(1.5*vect)
for vect in [
LEFT+DOWN,
LEFT+UP,
RIGHT+UP,
RIGHT+DOWN
]
]
last_curve = mini_curves[0]
naive_curve = Mobject(last_curve)
for mini_curve in mini_curves[1:]:
line = Line(last_curve.get_points()[-1], mini_curve.get_points()[0])
naive_curve.add(line, mini_curve)
last_curve = mini_curve
naive_curve.ingest_submobjects()
naive_curve.set_color_by_gradient(RED, GREEN)
order_2_curve = HilbertCurve(order = 2)
self.add(words, grid2)
self.wait()
self.play(ShowCreation(grid4))
self.play(*[
ShowCreation(mini_curve)
for mini_curve in mini_curves
])
self.wait()
self.play(ShowCreation(naive_curve, run_time = 5))
self.remove(*mini_curves)
self.wait()
self.play(Transform(naive_curve, order_2_curve))
self.wait()
class Order3PseudoHilbertCurve(Scene):
def construct(self):
words = OldTexText("Order 3 Pseudo-Hilbert Curve")
words.set_color(GREEN)
words.to_edge(UP)
grid4 = Mobject(
Grid(2, 2),
Grid(4, 4, stroke_width = 2)
)
grid8 = Grid(8, 8, stroke_width = 1)
order_3_curve = HilbertCurve(order = 3)
mini_curves = [
HilbertCurve(order = 2).scale(0.5).shift(1.5*vect)
for vect in [
LEFT+DOWN,
LEFT+UP,
RIGHT+UP,
RIGHT+DOWN
]
]
self.add(words, grid4)
self.wait()
self.play(ShowCreation(grid8))
self.wait()
self.play(*list(map(GrowFromCenter, mini_curves)))
self.wait()
self.clear()
self.add(words, grid8, *mini_curves)
self.play(*[
ApplyMethod(curve.rotate, np.pi, axis)
for curve, axis in [
(mini_curves[0], UP+RIGHT),
(mini_curves[3], UP+LEFT)
]
])
self.play(ShowCreation(order_3_curve, run_time = 5))
self.wait()
class GrowToOrder8PseudoHilbertCurve(Scene):
def construct(self):
self.curve = HilbertCurve(order = 1)
self.add(self.curve)
self.wait()
while self.curve.order < 8:
self.increase_order()
def increase_order(self):
mini_curves = [
self.curve.copy().scale(0.5).shift(1.5*vect)
for vect in [
LEFT+DOWN,
LEFT+UP,
RIGHT+UP,
RIGHT+DOWN
]
]
self.remove(self.curve)
self.play(
Transform(self.curve.copy(), mini_curves[0])
)
self.play(*[
GrowFromCenter(mini_curve)
for mini_curve in mini_curves[1:]
])
self.wait()
self.clear()
self.add(*mini_curves)
self.play(*[
ApplyMethod(curve.rotate, np.pi, axis)
for curve, axis in [
(mini_curves[0], UP+RIGHT),
(mini_curves[3], UP+LEFT)
]
])
self.curve = HilbertCurve(order = self.curve.order+1)
self.play(ShowCreation(self.curve, run_time = 2))
self.remove(*mini_curves)
self.wait()
class UseOrder8(Scene):
def construct(self):
mathy, bubble = get_mathy_and_bubble()
bubble.write("For a 256x256 pixel array...")
words = OldTexText("Order 8 Pseudo-Hilbert Curve")
words.set_color(GREEN)
words.to_edge(UP, buff = 0.3)
curve = HilbertCurve(order = 8)
self.add(mathy, bubble)
self.play(ShimmerIn(bubble.content))
self.wait()
self.clear()
self.add(words)
self.play(ShowCreation(
curve, run_time = 7, rate_func=linear
))
self.wait()
class HilbertBetterThanSnakeQ(Scene):
def construct(self):
hilbert_curves, snake_curves = [
[
CurveClass(order = n)
for n in range(2, 7)
]
for CurveClass in (HilbertCurve, SnakeCurve)
]
for curve in hilbert_curves+snake_curves:
curve.scale(0.8)
for curve in hilbert_curves:
curve.to_edge(LEFT)
for curve in snake_curves:
curve.to_edge(RIGHT)
greater_than = OldTex(">")
question_mark = OldTexText("?")
question_mark.next_to(greater_than, UP)
self.add(greater_than, question_mark)
hilbert_curve = hilbert_curves[0]
snake_curve = snake_curves[0]
for new_hc, new_sc in zip(hilbert_curves[1:], snake_curves[1:]):
self.play(*[
Transform(hilbert_curve, new_hc),
Transform(snake_curve, new_sc)
])
self.wait()
class ImagineItWorks(Scene):
def construct(self):
self.add(OldTexText("Imagine your project succeeds..."))
self.wait()
class RandyWithHeadphones(Scene):
def construct(self):
headphones = ImageMobject("Headphones.png")
headphones.scale(0.1)
headphones.stretch(2, 0)
headphones.shift(1.2*UP+0.05*LEFT)
headphones.set_color(GREY)
randy = Randolph()
self.add(randy, headphones)
self.wait(2)
self.play(ApplyMethod(randy.blink))
self.wait(4)
class IncreaseResolution(Scene):
def construct(self):
grids = [
Grid(
2**order, 2**order,
stroke_width = 1
).shift(0.3*DOWN)
for order in (6, 7)
]
grid = grids[0]
side_brace = Brace(grid, LEFT)
top_brace = Brace(grid, UP)
top_words = OldTexText("256")
new_top_words = OldTexText("512")
side_words = top_words.copy()
new_side_words = new_top_words.copy()
for words in top_words, new_top_words:
words.next_to(top_brace, UP, buff = 0.1)
for words in side_words, new_side_words:
words.next_to(side_brace, LEFT)
self.add(grid)
self.play(
GrowFromCenter(side_brace),
GrowFromCenter(top_brace),
ShimmerIn(top_words),
ShimmerIn(side_words)
)
self.wait()
self.play(
DelayByOrder(Transform(*grids)),
Transform(top_words, new_top_words),
Transform(side_words, new_side_words)
)
self.wait()
class IncreasingResolutionWithSnakeCurve(Scene):
def construct(self):
start_curve = SnakeCurve(order = 6)
end_curve = SnakeCurve(order = 7)
start_dots, end_dots = [
Mobject(*[
Dot(
curve.get_points()[int(x*curve.get_num_points())],
color = color
)
for x, color in [
(0.202, GREEN),
(0.48, BLUE),
(0.7, RED)
]
])
for curve in (start_curve, end_curve)
]
self.add(start_curve)
self.wait()
self.play(
ShowCreation(start_dots, run_time = 2),
ApplyMethod(start_curve.fade)
)
end_curve.fade()
self.play(
Transform(start_curve, end_curve),
Transform(start_dots, end_dots)
)
self.wait()
class TrackSpecificCurvePoint(Scene):
CURVE_CLASS = None #Fillin
def construct(self):
line = get_freq_line().center()
line.sort_points(lambda p : p[0])
curves = [
self.CURVE_CLASS(order = order)
for order in range(3, 10)
]
alpha = 0.48
dot = Dot(UP)
start_dot = Dot(0.1*LEFT)
dots = [
Dot(curve.get_points()[alpha*curve.get_num_points()])
for curve in curves
]
self.play(ShowCreation(line))
self.play(Transform(dot, start_dot))
self.wait()
for new_dot, curve in zip(dots, curves):
self.play(
Transform(line, curve),
Transform(dot, new_dot)
)
self.wait()
class TrackSpecificSnakeCurvePoint(TrackSpecificCurvePoint):
CURVE_CLASS = SnakeCurve
class NeedToRelearn(Scene):
def construct(self):
top_words = OldTexText("Different pixel-frequency association")
bottom_words = OldTexText("Need to relearn sight-via-sound")
top_words.shift(UP)
bottom_words.shift(DOWN)
arrow = Arrow(top_words, bottom_words)
self.play(ShimmerIn(top_words))
self.wait()
self.play(ShowCreation(arrow))
self.play(ShimmerIn(bottom_words))
self.wait()
class TrackSpecificHilbertCurvePoint(TrackSpecificCurvePoint):
CURVE_CLASS = HilbertCurve
|
|
from manim_imports_ext import *
from from_3b1b.old.hilbert.curves import *
class Intro(TransformOverIncreasingOrders):
@staticmethod
def args_to_string(*args):
return ""
@staticmethod
def string_to_args(string):
raise Exception("string_to_args Not Implemented!")
def construct(self):
words1 = OldTexText(
"If you watched my video about Hilbert's space-filling curve\\dots"
)
words2 = OldTexText(
"\\dots you might be curious to see what a few other space-filling curves look like."
)
words2.scale(0.8)
for words in words1, words2:
words.to_edge(UP, buff = 0.2)
self.setup(HilbertCurve)
self.play(ShimmerIn(words1))
for x in range(4):
self.increase_order()
self.remove(words1)
self.increase_order(
ShimmerIn(words2)
)
for x in range(4):
self.increase_order()
class BringInPeano(Intro):
def construct(self):
words1 = OldTexText("""
For each one, see if you can figure out what
the pattern of construction is.
""")
words2 = OldTexText("""
This one is the Peano curve.
""")
words3 = OldTexText("""
It is the original space-filling curve.
""")
self.setup(PeanoCurve)
self.play(ShimmerIn(words1))
self.wait(5)
self.remove(words1)
self.add(words2.to_edge(UP))
for x in range(3):
self.increase_order()
self.remove(words2)
self.increase_order(ShimmerIn(words3.to_edge(UP)))
for x in range(2):
self.increase_order()
class FillOtherShapes(Intro):
def construct(self):
words1 = OldTexText("""
But of course, there's no reason we should limit
ourselves to filling in squares.
""")
words2 = OldTexText("""
Here's a simple triangle-filling curve I defined
in a style reflective of a Hilbert curve.
""")
words1.to_edge(UP)
words2.scale(0.8).to_edge(UP, buff = 0.2)
self.setup(TriangleFillingCurve)
self.play(ShimmerIn(words1))
for x in range(3):
self.increase_order()
self.remove(words1)
self.add(words2)
for x in range(5):
self.increase_order()
class SmallerFlowSnake(FlowSnake):
CONFIG = {
"radius" : 4
}
class MostDelightfulName(Intro):
def construct(self):
words1 = OldTexText("""
This one has the most delightful name,
thanks to mathematician/programmer Bill Gosper:
""")
words2 = OldTexText("``Flow Snake''")
words3 = OldTexText("""
What makes this one particularly interesting
is that the boundary itself is a fractal.
""")
for words in words1, words2, words3:
words.to_edge(UP)
self.setup(SmallerFlowSnake)
self.play(ShimmerIn(words1))
for x in range(3):
self.increase_order()
self.remove(words1)
self.add(words2)
for x in range(3):
self.increase_order()
self.remove(words2)
self.play(ShimmerIn(words3))
class SurpriseFractal(Intro):
def construct(self):
words = OldTexText("""
It might come as a surprise how some well-known
fractals can be described with curves.
""")
words.to_edge(UP)
self.setup(Sierpinski)
self.add(OldTexText("Speaking of other fractals\\dots"))
self.wait(3)
self.clear()
self.play(ShimmerIn(words))
for x in range(9):
self.increase_order()
class IntroduceKoch(Intro):
def construct(self):
words = list(map(TexText, [
"This is another famous fractal.",
"The ``Koch Snowflake''",
"Let's finish things off by seeing how to turn \
this into a space-filling curve"
]))
for text in words:
text.to_edge(UP)
self.setup(KochCurve)
self.add(words[0])
for x in range(3):
self.increase_order()
self.remove(words[0])
self.add(words[1])
for x in range(4):
self.increase_order()
self.remove(words[1])
self.add(words[2])
self.wait(6)
class StraightKoch(KochCurve):
CONFIG = {
"axiom" : "A"
}
class SharperKoch(StraightKoch):
CONFIG = {
"angle" : 0.9*np.pi/2,
}
class DullerKoch(StraightKoch):
CONFIG = {
"angle" : np.pi/6,
}
class SpaceFillingKoch(StraightKoch):
CONFIG = {
"angle" : np.pi/2,
}
class FromKochToSpaceFilling(Scene):
def construct(self):
self.max_order = 7
self.revisit_koch()
self.show_angles()
self.show_change_side_by_side()
def revisit_koch(self):
words = list(map(TexText, [
"First, look at how one section of this curve is made.",
"This pattern of four lines is the ``seed''",
"With each iteration, every straight line is \
replaced with an appropriately small copy of the seed",
]))
for text in words:
text.to_edge(UP)
self.add(words[0])
curve = StraightKoch(order = self.max_order)
self.play(Transform(
curve,
StraightKoch(order = 1),
run_time = 5
))
self.remove(words[0])
self.add(words[1])
self.wait(4)
self.remove(words[1])
self.add(words[2])
self.wait(3)
for order in range(2, self.max_order):
self.play(Transform(
curve,
StraightKoch(order = order)
))
if order == 2:
self.wait(2)
elif order == 3:
self.wait()
self.clear()
def show_angles(self):
words = OldTexText("""
Let's see what happens as we change
the angle in this seed
""")
words.to_edge(UP)
koch, sharper_koch, duller_koch = curves = [
CurveClass(order = 1)
for CurveClass in (StraightKoch, SharperKoch, DullerKoch)
]
arcs = [
Arc(
2*(np.pi/2 - curve.angle),
radius = r,
start_angle = np.pi+curve.angle
).shift(curve.get_points()[curve.get_num_points()/2])
for curve, r in zip(curves, [0.6, 0.7, 0.4])
]
theta = OldTex("\\theta")
theta.shift(arcs[0].get_center()+2.5*DOWN)
arrow = Arrow(theta, arcs[0])
self.add(words, koch)
self.play(ShowCreation(arcs[0]))
self.play(
ShowCreation(arrow),
ShimmerIn(theta)
)
self.wait(2)
self.remove(theta, arrow)
self.play(
Transform(koch, duller_koch),
Transform(arcs[0], arcs[2]),
)
self.play(
Transform(koch, sharper_koch),
Transform(arcs[0], arcs[1]),
)
self.clear()
def show_change_side_by_side(self):
seed = OldTexText("Seed")
seed.shift(3*LEFT+2*DOWN)
fractal = OldTexText("Fractal")
fractal.shift(3*RIGHT+2*DOWN)
words = list(map(TexText, [
"A sharper angle results in a richer curve",
"A more obtuse angle gives a sparser curve",
"And as the angle approaches 0\\dots",
"We have a new space-filling curve."
]))
for text in words:
text.to_edge(UP)
sharper, duller, space_filling = [
CurveClass(order = 1).shift(3*LEFT)
for CurveClass in (SharperKoch, DullerKoch, SpaceFillingKoch)
]
shaper_f, duller_f, space_filling_f = [
CurveClass(order = self.max_order).shift(3*RIGHT)
for CurveClass in (SharperKoch, DullerKoch, SpaceFillingKoch)
]
self.add(words[0])
left_curve = SharperKoch(order = 1)
right_curve = SharperKoch(order = 1)
self.play(
Transform(left_curve, sharper),
ApplyMethod(right_curve.shift, 3*RIGHT),
)
self.play(
Transform(
right_curve,
SharperKoch(order = 2).shift(3*RIGHT)
),
ShimmerIn(seed),
ShimmerIn(fractal)
)
for order in range(3, self.max_order):
self.play(Transform(
right_curve,
SharperKoch(order = order).shift(3*RIGHT)
))
self.remove(words[0])
self.add(words[1])
kwargs = {
"run_time" : 4,
}
self.play(
Transform(left_curve, duller, **kwargs),
Transform(right_curve, duller_f, **kwargs)
)
self.wait()
kwargs["run_time"] = 7
kwargs["rate_func"] = None
self.remove(words[1])
self.add(words[2])
self.play(
Transform(left_curve, space_filling, **kwargs),
Transform(right_curve, space_filling_f, **kwargs)
)
self.remove(words[2])
self.add(words[3])
self.wait()
|
|
from manim_imports_ext import *
from from_3b1b.old.brachistochrone.curves import *
class RollAlongVector(Animation):
CONFIG = {
"rotation_vector" : OUT,
}
def __init__(self, mobject, vector, **kwargs):
radius = mobject.get_width()/2
radians = get_norm(vector)/radius
last_alpha = 0
digest_config(self, kwargs, locals())
Animation.__init__(self, mobject, **kwargs)
def interpolate_mobject(self, alpha):
d_alpha = alpha - self.last_alpha
self.last_alpha = alpha
self.mobject.rotate(
d_alpha*self.radians,
self.rotation_vector
)
self.mobject.shift(d_alpha*self.vector)
class CycloidScene(Scene):
CONFIG = {
"point_a" : 6*LEFT+3*UP,
"radius" : 2,
"end_theta" : 2*np.pi
}
def construct(self):
self.generate_cycloid()
self.generate_circle()
self.generate_ceiling()
def grow_parts(self):
self.play(*[
ShowCreation(mob)
for mob in (self.circle, self.ceiling)
])
def generate_cycloid(self):
self.cycloid = Cycloid(
point_a = self.point_a,
radius = self.radius,
end_theta = self.end_theta
)
def generate_circle(self, **kwargs):
self.circle = Circle(radius = self.radius, **kwargs)
self.circle.shift(self.point_a - self.circle.get_top())
radial_line = Line(
self.circle.get_center(), self.point_a
)
self.circle.add(radial_line)
def generate_ceiling(self):
self.ceiling = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT)
self.ceiling.shift(self.cycloid.get_top()[1]*UP)
def draw_cycloid(self, run_time = 3, *anims, **kwargs):
kwargs["run_time"] = run_time
self.play(
RollAlongVector(
self.circle,
self.cycloid.get_points()[-1]-self.cycloid.get_points()[0],
**kwargs
),
ShowCreation(self.cycloid, **kwargs),
*anims
)
def roll_back(self, run_time = 3, *anims, **kwargs):
kwargs["run_time"] = run_time
self.play(
RollAlongVector(
self.circle,
self.cycloid.get_points()[0]-self.cycloid.get_points()[- 1],
rotation_vector = IN,
**kwargs
),
ShowCreation(
self.cycloid,
rate_func = lambda t : smooth(1-t),
**kwargs
),
*anims
)
self.generate_cycloid()
class IntroduceCycloid(CycloidScene):
def construct(self):
CycloidScene.construct(self)
equation = OldTex([
"\\dfrac{\\sin(\\theta)}{\\sqrt{y}}",
"= \\text{constant}"
])
sin_sqrt, const = equation.split()
new_eq = equation.copy()
new_eq.to_edge(UP, buff = 1.3)
cycloid_word = OldTexText("Cycloid")
arrow = Arrow(2*UP, cycloid_word)
arrow.reverse_points()
q_mark = OldTexText("?")
self.play(*list(map(ShimmerIn, equation.split())))
self.wait()
self.play(
ApplyMethod(equation.shift, 2.2*UP),
ShowCreation(arrow)
)
q_mark.next_to(sin_sqrt)
self.play(ShimmerIn(cycloid_word))
self.wait()
self.grow_parts()
self.draw_cycloid()
self.wait()
extra_terms = [const, arrow, cycloid_word]
self.play(*[
Transform(mob, q_mark)
for mob in extra_terms
])
self.remove(*extra_terms)
self.roll_back()
q_marks, arrows = self.get_q_marks_and_arrows(sin_sqrt)
self.draw_cycloid(3,
ShowCreation(q_marks),
ShowCreation(arrows)
)
self.wait()
def get_q_marks_and_arrows(self, mob, n_marks = 10):
circle = Circle().replace(mob)
q_marks, arrows = result = [Mobject(), Mobject()]
for x in range(n_marks):
index = (x+0.5)*self.cycloid.get_num_points()/n_marks
q_point = self.cycloid.get_points()[index]
vect = q_point-mob.get_center()
start_point = circle.get_boundary_point(vect)
arrow = Arrow(
start_point, q_point,
color = BLUE_E
)
q_marks.add(OldTexText("?").shift(q_point))
arrows.add(arrow)
for mob in result:
mob.ingest_submobjects()
return result
class LeviSolution(CycloidScene):
CONFIG = {
"cycloid_fraction" : 0.25,
}
def construct(self):
CycloidScene.construct(self)
self.add(self.ceiling)
self.init_points()
methods = [
self.draw_cycloid,
self.roll_into_position,
self.draw_p_and_c,
self.show_pendulum,
self.show_diameter,
self.show_theta,
self.show_similar_triangles,
self.show_sin_thetas,
self.show_y,
self.rearrange,
]
for method in methods:
method()
self.wait()
def init_points(self):
index = int(self.cycloid_fraction*self.cycloid.get_num_points())
p_point = self.cycloid.get_points()[index]
p_dot = Dot(p_point)
p_label = OldTex("P")
p_label.next_to(p_dot, DOWN+LEFT)
c_point = self.point_a + self.cycloid_fraction*self.radius*2*np.pi*RIGHT
c_dot = Dot(c_point)
c_label = OldTex("C")
c_label.next_to(c_dot, UP)
digest_locals(self)
def roll_into_position(self):
self.play(RollAlongVector(
self.circle,
(1-self.cycloid_fraction)*self.radius*2*np.pi*LEFT,
rotation_vector = IN,
run_time = 2
))
def draw_p_and_c(self):
radial_line = self.circle.submobjects[0] ##Hacky
self.play(Transform(radial_line, self.p_dot))
self.remove(radial_line)
self.add(self.p_dot)
self.play(ShimmerIn(self.p_label))
self.wait()
self.play(Transform(self.ceiling.copy(), self.c_dot))
self.play(ShimmerIn(self.c_label))
def show_pendulum(self, arc_angle = np.pi, arc_color = GREEN):
words = OldTexText(": Instantaneous center of rotation")
words.next_to(self.c_label)
line = Line(self.p_point, self.c_point)
line_angle = line.get_angle()+np.pi
line_length = line.get_length()
line.add(self.p_dot.copy())
line.get_center = lambda : self.c_point
tangent_line = Line(3*LEFT, 3*RIGHT)
tangent_line.rotate(line_angle-np.pi/2)
tangent_line.shift(self.p_point)
tangent_line.set_color(arc_color)
right_angle_symbol = Mobject(
Line(UP, UP+RIGHT),
Line(UP+RIGHT, RIGHT)
)
right_angle_symbol.scale(0.3)
right_angle_symbol.rotate(tangent_line.get_angle()+np.pi)
right_angle_symbol.shift(self.p_point)
self.play(ShowCreation(line))
self.play(ShimmerIn(words))
self.wait()
pairs = [
(line_angle, arc_angle/2),
(line_angle+arc_angle/2, -arc_angle),
(line_angle-arc_angle/2, arc_angle/2),
]
arcs = []
for start, angle in pairs:
arc = Arc(
angle = angle,
radius = line_length,
start_angle = start,
color = GREEN
)
arc.shift(self.c_point)
self.play(
ShowCreation(arc),
ApplyMethod(
line.rotate,
angle,
path_func = path_along_arc(angle)
),
run_time = 2
)
arcs.append(arc)
self.wait()
self.play(Transform(arcs[1], tangent_line))
self.add(tangent_line)
self.play(ShowCreation(right_angle_symbol))
self.wait()
self.tangent_line = tangent_line
self.right_angle_symbol = right_angle_symbol
self.pc_line = line
self.remove(words, *arcs)
def show_diameter(self):
exceptions = [
self.circle,
self.tangent_line,
self.pc_line,
self.right_angle_symbol
]
everything = set(self.mobjects).difference(exceptions)
everything_copy = Mobject(*everything).copy()
light_everything = everything_copy.copy()
dark_everything = everything_copy.copy()
dark_everything.fade(0.8)
bottom_point = np.array(self.c_point)
bottom_point += 2*self.radius*DOWN
diameter = Line(bottom_point, self.c_point)
brace = Brace(diameter, RIGHT)
diameter_word = OldTexText("Diameter")
d_mob = OldTex("D")
diameter_word.next_to(brace)
d_mob.next_to(diameter)
self.remove(*everything)
self.play(Transform(everything_copy, dark_everything))
self.wait()
self.play(ShowCreation(diameter))
self.play(GrowFromCenter(brace))
self.play(ShimmerIn(diameter_word))
self.wait()
self.play(*[
Transform(mob, d_mob)
for mob in (brace, diameter_word)
])
self.remove(brace, diameter_word)
self.add(d_mob)
self.play(Transform(everything_copy, light_everything))
self.remove(everything_copy)
self.add(*everything)
self.d_mob = d_mob
self.bottom_point = bottom_point
def show_theta(self, radius = 1):
arc = Arc(
angle = self.tangent_line.get_angle()-np.pi/2,
radius = radius,
start_angle = np.pi/2
)
theta = OldTex("\\theta")
theta.shift(1.5*arc.get_center())
Mobject(arc, theta).shift(self.bottom_point)
self.play(
ShowCreation(arc),
ShimmerIn(theta)
)
self.arc = arc
self.theta = theta
def show_similar_triangles(self):
y_point = np.array(self.p_point)
y_point[1] = self.point_a[1]
new_arc = Arc(
angle = self.tangent_line.get_angle()-np.pi/2,
radius = 0.5,
start_angle = np.pi
)
new_arc.shift(self.c_point)
new_theta = self.theta.copy()
new_theta.next_to(new_arc, LEFT)
new_theta.shift(0.1*DOWN)
kwargs = {
"stroke_width" : 2*DEFAULT_STROKE_WIDTH,
}
triangle1 = Polygon(
self.p_point, self.c_point, self.bottom_point,
color = MAROON,
**kwargs
)
triangle2 = Polygon(
y_point, self.p_point, self.c_point,
color = WHITE,
**kwargs
)
y_line = Line(self.p_point, y_point)
self.play(
Transform(self.arc.copy(), new_arc),
Transform(self.theta.copy(), new_theta),
run_time = 3
)
self.wait()
self.play(FadeIn(triangle1))
self.wait()
self.play(Transform(triangle1, triangle2))
self.play(ApplyMethod(triangle1.set_color, MAROON))
self.wait()
self.remove(triangle1)
self.add(y_line)
self.y_line = y_line
def show_sin_thetas(self):
pc = Line(self.p_point, self.c_point)
mob = Mobject(self.theta, self.d_mob).copy()
mob.ingest_submobjects()
triplets = [
(pc, "D\\sin(\\theta)", 0.5),
(self.y_line, "D\\sin^2(\\theta)", 0.7),
]
for line, tex, scale in triplets:
trig_mob = OldTex(tex)
trig_mob.set_width(
scale*line.get_length()
)
trig_mob.shift(-1.2*trig_mob.get_top())
trig_mob.rotate(line.get_angle())
trig_mob.shift(line.get_center())
if line is self.y_line:
trig_mob.shift(0.1*UP)
self.play(Transform(mob, trig_mob))
self.add(trig_mob)
self.wait()
self.remove(mob)
self.d_sin_squared_theta = trig_mob
def show_y(self):
y_equals = OldTex(["y", "="])
y_equals.shift(2*UP)
y_expression = OldTex([
"D ", "\\sin", "^2", "(\\theta)"
])
y_expression.next_to(y_equals)
y_expression.shift(0.05*UP+0.1*RIGHT)
temp_expr = self.d_sin_squared_theta.copy()
temp_expr.rotate(-np.pi/2)
temp_expr.replace(y_expression)
y_mob = OldTex("y")
y_mob.next_to(self.y_line, RIGHT)
y_mob.shift(0.2*UP)
self.play(
Transform(self.d_sin_squared_theta, temp_expr),
ShimmerIn(y_mob),
ShowCreation(y_equals)
)
self.remove(self.d_sin_squared_theta)
self.add(y_expression)
self.y_equals = y_equals
self.y_expression = y_expression
def rearrange(self):
sqrt_nudge = 0.2*LEFT
y, equals = self.y_equals.split()
d, sin, squared, theta = self.y_expression.split()
y_sqrt = OldTex("\\sqrt{\\phantom{y}}")
d_sqrt = y_sqrt.copy()
y_sqrt.shift(y.get_center()+sqrt_nudge)
d_sqrt.shift(d.get_center()+sqrt_nudge)
self.play(
ShimmerIn(y_sqrt),
ShimmerIn(d_sqrt),
ApplyMethod(squared.shift, 4*UP),
ApplyMethod(theta.shift, 1.5* squared.get_width()*LEFT)
)
self.wait()
y_sqrt.add(y)
d_sqrt.add(d)
sin.add(theta)
sin_over = OldTex("\\dfrac{\\phantom{\\sin(\\theta)}}{\\quad}")
sin_over.next_to(sin, DOWN, 0.15)
new_eq = equals.copy()
new_eq.next_to(sin_over, LEFT)
one_over = OldTex("\\dfrac{1}{\\quad}")
one_over.next_to(new_eq, LEFT)
one_over.shift(
(sin_over.get_bottom()[1]-one_over.get_bottom()[1])*UP
)
self.play(
Transform(equals, new_eq),
ShimmerIn(sin_over),
ShimmerIn(one_over),
ApplyMethod(
d_sqrt.next_to, one_over, DOWN,
path_func = path_along_arc(-np.pi)
),
ApplyMethod(
y_sqrt.next_to, sin_over, DOWN,
path_func = path_along_arc(-np.pi)
),
run_time = 2
)
self.wait()
brace = Brace(d_sqrt, DOWN)
constant = OldTexText("Constant")
constant.next_to(brace, DOWN)
self.play(
GrowFromCenter(brace),
ShimmerIn(constant)
)
class EquationsForCycloid(CycloidScene):
def construct(self):
CycloidScene.construct(self)
equations = OldTex([
"x(t) = Rt - R\\sin(t)",
"y(t) = -R + R\\cos(t)"
])
top, bottom = equations.split()
bottom.next_to(top, DOWN)
equations.center()
equations.to_edge(UP, buff = 1.3)
self.play(ShimmerIn(equations))
self.grow_parts()
self.draw_cycloid(rate_func=linear, run_time = 5)
self.wait()
class SlidingObject(CycloidScene, PathSlidingScene):
CONFIG = {
"show_time" : False,
"wait_and_add" : False
}
args_list = [(True,), (False,)]
@staticmethod
def args_to_string(with_words):
return "WithWords" if with_words else "WithoutWords"
@staticmethod
def string_to_args(string):
return string == "WithWords"
def construct(self, with_words):
CycloidScene.construct(self)
randy = Randolph()
randy.scale(RANDY_SCALE_FACTOR)
randy.shift(-randy.get_bottom())
central_randy = randy.copy()
start_randy = self.adjust_mobject_to_index(
randy.copy(), 1, self.cycloid.points
)
if with_words:
words1 = OldTexText("Trajectory due to gravity")
arrow = OldTex("\\leftrightarrow")
words2 = OldTexText("Trajectory due \\emph{constantly} rotating wheel")
words1.next_to(arrow, LEFT)
words2.next_to(arrow, RIGHT)
words = Mobject(words1, arrow, words2)
words.set_width(FRAME_WIDTH-1)
words.to_edge(UP, buff = 0.2)
words.to_edge(LEFT)
self.play(ShowCreation(self.cycloid.copy()))
self.slide(randy, self.cycloid)
self.add(self.slider)
self.wait()
self.grow_parts()
self.draw_cycloid()
self.wait()
self.play(Transform(self.slider, start_randy))
self.wait()
self.roll_back()
self.wait()
if with_words:
self.play(*list(map(ShimmerIn, [words1, arrow, words2])))
self.wait()
self.remove(self.circle)
start_time = len(self.frames)*self.frame_duration
self.remove(self.slider)
self.slide(central_randy, self.cycloid)
end_time = len(self.frames)*self.frame_duration
self.play_over_time_range(
start_time,
end_time,
RollAlongVector(
self.circle,
self.cycloid.get_points()[-1]-self.cycloid.get_points()[0],
run_time = end_time-start_time,
rate_func=linear
)
)
self.add(self.circle, self.slider)
self.wait()
class RotateWheel(CycloidScene):
def construct(self):
CycloidScene.construct(self)
self.circle.center()
self.play(Rotating(
self.circle,
axis = OUT,
run_time = 5,
rate_func = smooth
))
|
|
from manim_imports_ext import *
RANDY_SCALE_FACTOR = 0.3
class Cycloid(ParametricCurve):
CONFIG = {
"point_a" : 6*LEFT+3*UP,
"radius" : 2,
"end_theta" : 3*np.pi/2,
"density" : 5*DEFAULT_POINT_DENSITY_1D,
"color" : YELLOW
}
def __init__(self, **kwargs):
digest_config(self, kwargs)
ParametricCurve.__init__(self, self.pos_func, **kwargs)
def pos_func(self, t):
T = t*self.end_theta
return self.point_a + self.radius * np.array([
T - np.sin(T),
np.cos(T) - 1,
0
])
class LoopTheLoop(ParametricCurve):
CONFIG = {
"color" : YELLOW_D,
"density" : 10*DEFAULT_POINT_DENSITY_1D
}
def __init__(self, **kwargs):
digest_config(self, kwargs)
def func(t):
t = (6*np.pi/2)*(t-0.5)
return (t/2-np.sin(t))*RIGHT + \
(np.cos(t)+(t**2)/10)*UP
ParametricCurve.__init__(self, func, **kwargs)
class SlideWordDownCycloid(Animation):
CONFIG = {
"rate_func" : None,
"run_time" : 8
}
def __init__(self, word, **kwargs):
self.path = Cycloid(end_theta = np.pi)
word_mob = OldTexText(list(word))
end_word = word_mob.copy()
end_word.shift(-end_word.get_bottom())
end_word.shift(self.path.get_corner(DOWN+RIGHT))
end_word.shift(3*RIGHT)
self.end_letters = end_word.split()
for letter in word_mob.split():
letter.center()
letter.angle = 0
unit_interval = np.arange(0, 1, 1./len(word))
self.start_times = 0.5*(1-(unit_interval))
Animation.__init__(self, word_mob, **kwargs)
def interpolate_mobject(self, alpha):
virtual_times = 2*(alpha - self.start_times)
cut_offs = [
0.1,
0.3,
0.7,
]
for letter, time, end_letter in zip(
self.mobject.split(), virtual_times, self.end_letters
):
time = max(time, 0)
time = min(time, 1)
if time < cut_offs[0]:
brightness = time/cut_offs[0]
letter.rgbas = brightness*np.ones(letter.rgbas.shape)
position = self.path.get_points()[0]
angle = 0
elif time < cut_offs[1]:
alpha = (time-cut_offs[0])/(cut_offs[1]-cut_offs[0])
angle = -rush_into(alpha)*np.pi/2
position = self.path.get_points()[0]
elif time < cut_offs[2]:
alpha = (time-cut_offs[1])/(cut_offs[2]-cut_offs[1])
index = int(alpha*self.path.get_num_points())
position = self.path.get_points()[index]
try:
angle = angle_of_vector(
self.path.get_points()[index+1] - \
self.path.get_points()[index]
)
except:
angle = letter.angle
else:
alpha = (time-cut_offs[2])/(1-cut_offs[2])
start = self.path.get_points()[-1]
end = end_letter.get_bottom()
position = interpolate(start, end, rush_from(alpha))
angle = 0
letter.shift(position-letter.get_bottom())
letter.rotate(angle-letter.angle)
letter.angle = angle
class BrachistochroneWordSliding(Scene):
def construct(self):
anim = SlideWordDownCycloid("Brachistochrone")
anim.path.set_color_by_gradient(WHITE, BLUE_E)
self.play(ShowCreation(anim.path))
self.play(anim)
self.wait()
self.play(
FadeOut(anim.path),
ApplyMethod(anim.mobject.center)
)
class PathSlidingScene(Scene):
CONFIG = {
"gravity" : 3,
"delta_t" : 0.05,
"wait_and_add" : True,
"show_time" : True,
}
def slide(self, mobject, path, roll = False, ceiling = None):
points = path.points
time_slices = self.get_time_slices(points, ceiling = ceiling)
curr_t = 0
last_index = 0
curr_index = 1
if self.show_time:
self.t_equals = OldTex("t = ")
self.t_equals.shift(3.5*UP+4*RIGHT)
self.add(self.t_equals)
while curr_index < len(points):
self.slider = mobject.copy()
self.adjust_mobject_to_index(
self.slider, curr_index, points
)
if roll:
distance = get_norm(
points[curr_index] - points[last_index]
)
self.roll(mobject, distance)
self.add(self.slider)
if self.show_time:
self.write_time(curr_t)
self.wait(self.frame_duration)
self.remove(self.slider)
curr_t += self.delta_t
last_index = curr_index
while time_slices[curr_index] < curr_t:
curr_index += 1
if curr_index == len(points):
break
if self.wait_and_add:
self.add(self.slider)
self.wait()
else:
return self.slider
def get_time_slices(self, points, ceiling = None):
dt_list = np.zeros(len(points))
ds_list = np.apply_along_axis(
get_norm,
1,
points[1:]-points[:-1]
)
if ceiling is None:
ceiling = points[0, 1]
delta_y_list = np.abs(ceiling - points[1:,1])
delta_y_list += 0.001*(delta_y_list == 0)
v_list = self.gravity*np.sqrt(delta_y_list)
dt_list[1:] = ds_list / v_list
return np.cumsum(dt_list)
def adjust_mobject_to_index(self, mobject, index, points):
point_a, point_b = points[index-1], points[index]
while np.all(point_a == point_b):
index += 1
point_b = points[index]
theta = angle_of_vector(point_b - point_a)
mobject.rotate(theta)
mobject.shift(points[index])
self.midslide_action(point_a, theta)
return mobject
def midslide_action(self, point, angle):
pass
def write_time(self, time):
if hasattr(self, "time_mob"):
self.remove(self.time_mob)
digits = list(map(Tex, "%.2f"%time))
digits[0].next_to(self.t_equals, buff = 0.1)
for left, right in zip(digits, digits[1:]):
right.next_to(left, buff = 0.1, aligned_edge = DOWN)
self.time_mob = Mobject(*digits)
self.add(self.time_mob)
def roll(self, mobject, arc_length):
radius = mobject.get_width()/2
theta = arc_length / radius
mobject.rotate(-theta)
def add_cycloid_end_points(self):
cycloid = Cycloid()
point_a = Dot(cycloid.get_points()[0])
point_b = Dot(cycloid.get_points()[-1])
A = OldTex("A").next_to(point_a, LEFT)
B = OldTex("B").next_to(point_b, RIGHT)
self.add(point_a, point_b, A, B)
digest_locals(self)
class TryManyPaths(PathSlidingScene):
def construct(self):
randy = Randolph()
randy.shift(-randy.get_bottom())
self.slider = randy.copy()
randy.scale(RANDY_SCALE_FACTOR)
paths = self.get_paths()
point_a = Dot(paths[0].get_points()[0])
point_b = Dot(paths[0].get_points()[-1])
A = OldTex("A").next_to(point_a, LEFT)
B = OldTex("B").next_to(point_b, RIGHT)
for point, tex in [(point_a, A), (point_b, B)]:
self.play(ShowCreation(point))
self.play(ShimmerIn(tex))
self.wait()
curr_path = None
for path in paths:
new_slider = self.adjust_mobject_to_index(
randy.copy(), 1, path.points
)
if curr_path is None:
curr_path = path
self.play(ShowCreation(curr_path))
else:
self.play(Transform(curr_path, path))
self.play(Transform(self.slider, new_slider))
self.wait()
self.remove(self.slider)
self.slide(randy, curr_path)
self.clear()
self.add(point_a, point_b, A, B, curr_path)
text = self.get_text()
text.to_edge(UP)
self.play(ShimmerIn(text))
for path in paths:
self.play(Transform(
curr_path, path,
path_func = path_along_arc(np.pi/2),
run_time = 3
))
def get_text(self):
return OldTexText("Which path is fastest?")
def get_paths(self):
sharp_corner = Mobject(
Line(3*UP+LEFT, LEFT),
Arc(angle = np.pi/2, start_angle = np.pi),
Line(DOWN, DOWN+3*RIGHT)
).ingest_submobjects().set_color(GREEN)
paths = [
Arc(
angle = np.pi/2,
radius = 3,
start_angle = 4
),
LoopTheLoop(),
Line(7*LEFT, 7*RIGHT, color = RED_D),
sharp_corner,
FunctionGraph(
lambda x : 0.05*(x**2)+0.1*np.sin(2*x)
),
FunctionGraph(
lambda x : x**2,
x_min = -3,
x_max = 2,
density = 3*DEFAULT_POINT_DENSITY_1D
)
]
cycloid = Cycloid()
self.align_paths(paths, cycloid)
return paths + [cycloid]
def align_paths(self, paths, target_path):
start = target_path.get_points()[0]
end = target_path.get_points()[-1]
for path in paths:
path.put_start_and_end_on(start, end)
class RollingRandolph(PathSlidingScene):
def construct(self):
randy = Randolph()
randy.scale(RANDY_SCALE_FACTOR)
randy.shift(-randy.get_bottom())
self.add_cycloid_end_points()
self.slide(randy, self.cycloid, roll = True)
class NotTheCircle(PathSlidingScene):
def construct(self):
self.add_cycloid_end_points()
start = self.point_a.get_center()
end = self.point_b.get_center()
angle = 2*np.pi/3
path = Arc(angle, radius = 3)
path.set_color_by_gradient(RED_D, WHITE)
radius = Line(ORIGIN, path.get_points()[0])
randy = Randolph()
randy.scale(RANDY_SCALE_FACTOR)
randy.shift(-randy.get_bottom())
randy_copy = randy.copy()
words = OldTexText("Circular paths are good, \\\\ but still not the best")
words.shift(UP)
self.play(
ShowCreation(path),
ApplyMethod(
radius.rotate,
angle,
path_func = path_along_arc(angle)
)
)
self.play(FadeOut(radius))
self.play(
ApplyMethod(
path.put_start_and_end_on, start, end,
path_func = path_along_arc(-angle)
),
run_time = 3
)
self.adjust_mobject_to_index(randy_copy, 1, path.points)
self.play(FadeIn(randy_copy))
self.remove(randy_copy)
self.slide(randy, path)
self.play(ShimmerIn(words))
self.wait()
class TransitionAwayFromSlide(PathSlidingScene):
def construct(self):
randy = Randolph()
randy.scale(RANDY_SCALE_FACTOR)
randy.shift(-randy.get_bottom())
self.add_cycloid_end_points()
arrow = Arrow(ORIGIN, 2*RIGHT)
arrows = Mobject(*[
arrow.copy().shift(vect)
for vect in (3*LEFT, ORIGIN, 3*RIGHT)
])
arrows.shift(FRAME_WIDTH*RIGHT)
self.add(arrows)
self.add(self.cycloid)
self.slide(randy, self.cycloid)
everything = Mobject(*self.mobjects)
self.play(ApplyMethod(
everything.shift, 4*FRAME_X_RADIUS*LEFT,
run_time = 2,
rate_func = rush_into
))
class MinimalPotentialEnergy(Scene):
def construct(self):
horiz_radius = 5
vert_radius = 3
vert_axis = NumberLine(numerical_radius = vert_radius)
vert_axis.rotate(np.pi/2)
vert_axis.shift(horiz_radius*LEFT)
horiz_axis = NumberLine(
numerical_radius = 5,
numbers_with_elongated_ticks = []
)
axes = Mobject(horiz_axis, vert_axis)
graph = FunctionGraph(
lambda x : 0.4*(x-2)*(x+2)+3,
x_min = -2,
x_max = 2,
density = 3*DEFAULT_POINT_DENSITY_1D
)
graph.stretch_to_fit_width(2*horiz_radius)
graph.set_color(YELLOW)
min_point = Dot(graph.get_bottom())
nature_finds = OldTexText("Nature finds this point")
nature_finds.scale(0.5)
nature_finds.set_color(GREEN)
nature_finds.shift(2*RIGHT+3*UP)
arrow = Arrow(
nature_finds.get_bottom(), min_point,
color = GREEN
)
side_words_start = OldTexText("Parameter describing")
top_words, last_side_words = [
list(map(TexText, pair))
for pair in [
("Light's travel time", "Potential energy"),
("path", "mechanical state")
]
]
for word in top_words + last_side_words + [side_words_start]:
word.scale(0.7)
side_words_start.next_to(horiz_axis, DOWN)
side_words_start.to_edge(RIGHT)
for words in top_words:
words.next_to(vert_axis, UP)
words.to_edge(LEFT)
for words in last_side_words:
words.next_to(side_words_start, DOWN)
for words in top_words[1], last_side_words[1]:
words.set_color(RED)
self.add(
axes, top_words[0], side_words_start,
last_side_words[0]
)
self.play(ShowCreation(graph))
self.play(
ShimmerIn(nature_finds),
ShowCreation(arrow),
ShowCreation(min_point)
)
self.wait()
self.play(
FadeOut(top_words[0]),
FadeOut(last_side_words[0]),
GrowFromCenter(top_words[1]),
GrowFromCenter(last_side_words[1])
)
self.wait(3)
class WhatGovernsSpeed(PathSlidingScene):
CONFIG = {
"num_pieces" : 6,
"wait_and_add" : False,
"show_time" : False,
}
def construct(self):
randy = Randolph()
randy.scale(RANDY_SCALE_FACTOR)
randy.shift(-randy.get_bottom())
self.add_cycloid_end_points()
points = self.cycloid.points
ceiling = points[0, 1]
n = len(points)
broken_points = [
points[k*n/self.num_pieces:(k+1)*n/self.num_pieces]
for k in range(self.num_pieces)
]
words = OldTexText("""
What determines the speed\\\\
at each point?
""")
words.to_edge(UP)
self.add(self.cycloid)
sliders, vectors = [], []
for points in broken_points:
path = Mobject().add_points(points)
vect = points[-1] - points[-2]
magnitude = np.sqrt(ceiling - points[-1, 1])
vect = magnitude*vect/get_norm(vect)
slider = self.slide(randy, path, ceiling = ceiling)
vector = Vector(slider.get_center(), vect)
self.add(slider, vector)
sliders.append(slider)
vectors.append(vector)
self.wait()
self.play(ShimmerIn(words))
self.wait(3)
slider = sliders.pop(1)
vector = vectors.pop(1)
faders = sliders+vectors+[words]
self.play(*list(map(FadeOut, faders)))
self.remove(*faders)
self.show_geometry(slider, vector)
def show_geometry(self, slider, vector):
point_a = self.point_a.get_center()
horiz_line = Line(point_a, point_a + 6*RIGHT)
ceil_point = point_a
ceil_point[0] = slider.get_center()[0]
vert_brace = Brace(
Mobject(Point(ceil_point), Point(slider.get_center())),
RIGHT,
buff = 0.5
)
vect_brace = Brace(slider)
vect_brace.stretch_to_fit_width(vector.get_length())
vect_brace.rotate(np.arctan(vector.get_slope()))
vect_brace.center().shift(vector.get_center())
nudge = 0.2*(DOWN+LEFT)
vect_brace.shift(nudge)
y_mob = OldTex("y")
y_mob.next_to(vert_brace)
sqrt_y = OldTex("k\\sqrt{y}")
sqrt_y.scale(0.5)
sqrt_y.shift(vect_brace.get_center())
sqrt_y.shift(3*nudge)
self.play(ShowCreation(horiz_line))
self.play(
GrowFromCenter(vert_brace),
ShimmerIn(y_mob)
)
self.play(
GrowFromCenter(vect_brace),
ShimmerIn(sqrt_y)
)
self.wait(3)
self.solve_energy()
def solve_energy(self):
loss_in_potential = OldTexText("Loss in potential: ")
loss_in_potential.shift(2*UP)
potential = OldTex("m g y".split())
potential.next_to(loss_in_potential)
kinetic = OldTex([
"\\dfrac{1}{2}","m","v","^2","="
])
kinetic.next_to(potential, LEFT)
nudge = 0.1*UP
kinetic.shift(nudge)
loss_in_potential.shift(nudge)
ms = Mobject(kinetic.split()[1], potential.split()[0])
two = OldTex("2")
two.shift(ms.split()[1].get_center())
half = kinetic.split()[0]
sqrt = OldTex("\\sqrt{\\phantom{2mg}}")
sqrt.shift(potential.get_center())
nudge = 0.2*LEFT
sqrt.shift(nudge)
squared = kinetic.split()[3]
equals = kinetic.split()[-1]
new_eq = equals.copy().next_to(kinetic.split()[2])
self.play(
Transform(
Point(loss_in_potential.get_left()),
loss_in_potential
),
*list(map(GrowFromCenter, potential.split()))
)
self.wait(2)
self.play(
FadeOut(loss_in_potential),
GrowFromCenter(kinetic)
)
self.wait(2)
self.play(ApplyMethod(ms.shift, 5*UP))
self.wait()
self.play(Transform(
half, two,
path_func = counterclockwise_path()
))
self.wait()
self.play(
Transform(
squared, sqrt,
path_func = clockwise_path()
),
Transform(equals, new_eq)
)
self.wait(2)
class ThetaTInsteadOfXY(Scene):
def construct(self):
cycloid = Cycloid()
index = cycloid.get_num_points()/3
point = cycloid.get_points()[index]
vect = cycloid.get_points()[index+1]-point
vect /= get_norm(vect)
vect *= 3
vect_mob = Vector(point, vect)
dot = Dot(point)
xy = OldTex("\\big( x(t), y(t) \\big)")
xy.next_to(dot, UP+RIGHT, buff = 0.1)
vert_line = Line(2*DOWN, 2*UP)
vert_line.shift(point)
angle = vect_mob.get_angle() + np.pi/2
arc = Arc(angle, radius = 1, start_angle = -np.pi/2)
arc.shift(point)
theta = OldTex("\\theta(t)")
theta.next_to(arc, DOWN, buff = 0.1, aligned_edge = LEFT)
theta.shift(0.2*RIGHT)
self.play(ShowCreation(cycloid))
self.play(ShowCreation(dot))
self.play(ShimmerIn(xy))
self.wait()
self.play(
FadeOut(xy),
ShowCreation(vect_mob)
)
self.play(
ShowCreation(arc),
ShowCreation(vert_line),
ShimmerIn(theta)
)
self.wait()
class DefineCurveWithKnob(PathSlidingScene):
def construct(self):
self.knob = Circle(color = BLUE_D)
self.knob.add_line(UP, DOWN)
self.knob.to_corner(UP+RIGHT)
self.knob.shift(0.5*DOWN)
self.last_angle = np.pi/2
arrow = Vector(ORIGIN, RIGHT)
arrow.next_to(self.knob, LEFT)
words = OldTexText("Turn this knob over time to define the curve")
words.next_to(arrow, LEFT)
self.path = self.get_path()
self.path.shift(1.5*DOWN)
self.path.show()
self.path.set_color(BLACK)
randy = Randolph()
randy.scale(RANDY_SCALE_FACTOR)
randy.shift(-randy.get_bottom())
self.play(ShimmerIn(words))
self.play(ShowCreation(arrow))
self.play(ShowCreation(self.knob))
self.wait()
self.add(self.path)
self.slide(randy, self.path)
self.wait()
def get_path(self):
return Cycloid(end_theta = 2*np.pi)
def midslide_action(self, point, angle):
d_angle = angle-self.last_angle
self.knob.rotate(d_angle)
self.last_angle = angle
self.path.set_color(BLUE_D, lambda p : p[0] < point[0])
class WonkyDefineCurveWithKnob(DefineCurveWithKnob):
def get_path(self):
return ParametricCurve(
lambda t : t*RIGHT + (-0.2*t-np.sin(2*np.pi*t/6))*UP,
start = -7,
end = 10
)
class SlowDefineCurveWithKnob(DefineCurveWithKnob):
def get_path(self):
return ParametricCurve(
lambda t : t*RIGHT + (np.exp(-(t+2)**2)-0.2*np.exp(t-2)),
start = -4,
end = 4
)
class BumpyDefineCurveWithKnob(DefineCurveWithKnob):
def get_path(self):
result = FunctionGraph(
lambda x : 0.05*(x**2)+0.1*np.sin(2*x)
)
result.rotate(-np.pi/20)
result.scale(0.7)
result.shift(DOWN)
return result
|
|
import numpy as np
import itertools as it
from manim_imports_ext import *
from from_3b1b.old.brachistochrone.curves import Cycloid
class MultilayeredGlass(PhotonScene, ZoomedScene):
CONFIG = {
"num_discrete_layers" : 5,
"num_variables" : 3,
"top_color" : BLUE_E,
"bottom_color" : BLUE_A,
"zoomed_canvas_frame_shape" : (5, 5),
"square_color" : GREEN_B,
}
def construct(self):
self.cycloid = Cycloid(end_theta = np.pi)
self.cycloid.set_color(YELLOW)
self.top = self.cycloid.get_top()[1]
self.bottom = self.cycloid.get_bottom()[1]-1
self.generate_layers()
self.generate_discrete_path()
photon_run = self.photon_run_along_path(
self.discrete_path,
run_time = 1,
rate_func = rush_into
)
self.continuous_to_smooth()
self.add(*self.layers)
self.show_layer_variables()
self.play(photon_run)
self.play(ShowCreation(self.discrete_path))
self.isolate_bend_points()
self.clear()
self.add(*self.layers)
self.show_main_equation()
self.ask_continuous_question()
def continuous_to_smooth(self):
self.add(*self.layers)
continuous = self.get_continuous_background()
self.add(continuous)
self.wait()
self.play(ShowCreation(
continuous,
rate_func = lambda t : smooth(1-t)
))
self.remove(continuous)
self.wait()
def get_continuous_background(self):
glass = FilledRectangle(
height = self.top-self.bottom,
width = FRAME_WIDTH,
)
glass.sort_points(lambda p : -p[1])
glass.shift((self.top-glass.get_top()[1])*UP)
glass.set_color_by_gradient(self.top_color, self.bottom_color)
return glass
def generate_layer_info(self):
self.layer_thickness = float(self.top-self.bottom)/self.num_discrete_layers
self.layer_tops = np.arange(
self.top, self.bottom, -self.layer_thickness
)
top_rgb, bottom_rgb = [
np.array(Color(color).get_rgb())
for color in (self.top_color, self.bottom_color)
]
epsilon = 1./(self.num_discrete_layers-1)
self.layer_colors = [
Color(rgb = interpolate(top_rgb, bottom_rgb, alpha))
for alpha in np.arange(0, 1+epsilon, epsilon)
]
def generate_layers(self):
self.generate_layer_info()
def create_region(top, color):
return Region(
lambda x, y : (y < top) & (y > top-self.layer_thickness),
color = color
)
self.layers = [
create_region(top, color)
for top, color in zip(self.layer_tops, self.layer_colors)
]
def generate_discrete_path(self):
points = self.cycloid.points
tops = list(self.layer_tops)
tops.append(tops[-1]-self.layer_thickness)
indices = [
np.argmin(np.abs(points[:, 1]-top))
for top in tops
]
self.bend_points = points[indices[1:-1]]
self.path_angles = []
self.discrete_path = Mobject1D(
color = YELLOW,
density = 3*DEFAULT_POINT_DENSITY_1D
)
for start, end in zip(indices, indices[1:]):
start_point, end_point = points[start], points[end]
self.discrete_path.add_line(
start_point, end_point
)
self.path_angles.append(
angle_of_vector(start_point-end_point)-np.pi/2
)
self.discrete_path.add_line(
points[end], FRAME_X_RADIUS*RIGHT+(self.layer_tops[-1]-1)*UP
)
def show_layer_variables(self):
layer_top_pairs = list(zip(
self.layer_tops[:self.num_variables],
self.layer_tops[1:]
))
v_equations = []
start_ys = []
end_ys = []
center_paths = []
braces = []
for (top1, top2), x in zip(layer_top_pairs, it.count(1)):
eq_mob = OldTex(
["v_%d"%x, "=", "\sqrt{\phantom{y_1}}"],
size = "\\Large"
)
midpoint = UP*(top1+top2)/2
eq_mob.shift(midpoint)
v_eq = eq_mob.split()
center_paths.append(Line(
midpoint+FRAME_X_RADIUS*LEFT,
midpoint+FRAME_X_RADIUS*RIGHT
))
brace_endpoints = Mobject(
Point(self.top*UP+x*RIGHT),
Point(top2*UP+x*RIGHT)
)
brace = Brace(brace_endpoints, RIGHT)
start_y = OldTex("y_%d"%x, size = "\\Large")
end_y = start_y.copy()
start_y.next_to(brace, RIGHT)
end_y.shift(v_eq[-1].get_center())
end_y.shift(0.2*RIGHT)
v_equations.append(v_eq)
start_ys.append(start_y)
end_ys.append(end_y)
braces.append(brace)
for v_eq, path, time in zip(v_equations, center_paths, [2, 1, 0.5]):
photon_run = self.photon_run_along_path(
path,
rate_func=linear
)
self.play(
ShimmerIn(v_eq[0]),
photon_run,
run_time = time
)
self.wait()
for start_y, brace in zip(start_ys, braces):
self.add(start_y)
self.play(GrowFromCenter(brace))
self.wait()
quads = list(zip(v_equations, start_ys, end_ys, braces))
self.equations = []
for v_eq, start_y, end_y, brace in quads:
self.remove(brace)
self.play(
ShowCreation(v_eq[1]),
ShowCreation(v_eq[2]),
Transform(start_y, end_y)
)
v_eq.append(start_y)
self.equations.append(Mobject(*v_eq))
def isolate_bend_points(self):
arc_radius = 0.1
self.activate_zooming()
little_square = self.get_zoomed_camera_mobject()
for index in range(3):
bend_point = self.bend_points[index]
line = Line(
bend_point+DOWN,
bend_point+UP,
color = WHITE,
density = self.zoom_factor*DEFAULT_POINT_DENSITY_1D
)
angle_arcs = []
for i, rotation in [(index, np.pi/2), (index+1, -np.pi/2)]:
arc = Arc(angle = self.path_angles[i])
arc.scale(arc_radius)
arc.rotate(rotation)
arc.shift(bend_point)
angle_arcs.append(arc)
thetas = []
for i in [index+1, index+2]:
theta = OldTex("\\theta_%d"%i)
theta.scale(0.5/self.zoom_factor)
vert = UP if i == index+1 else DOWN
horiz = rotate_vector(vert, np.pi/2)
theta.next_to(
Point(bend_point),
horiz,
buff = 0.01
)
theta.shift(1.5*arc_radius*vert)
thetas.append(theta)
figure_marks = [line] + angle_arcs + thetas
self.play(ApplyMethod(
little_square.shift,
bend_point - little_square.get_center(),
run_time = 2
))
self.play(*list(map(ShowCreation, figure_marks)))
self.wait()
equation_frame = little_square.copy()
equation_frame.scale(0.5)
equation_frame.shift(
little_square.get_corner(UP+RIGHT) - \
equation_frame.get_corner(UP+RIGHT)
)
equation_frame.scale(0.9)
self.show_snells(index+1, equation_frame)
self.remove(*figure_marks)
self.disactivate_zooming()
def show_snells(self, index, frame):
left_text, right_text = [
"\\dfrac{\\sin(\\theta_%d)}{\\phantom{\\sqrt{y_1}}}"%x
for x in (index, index+1)
]
left, equals, right = OldTex(
[left_text, "=", right_text]
).split()
vs = []
sqrt_ys = []
for x, numerator in [(index, left), (index+1, right)]:
v, sqrt_y = [
OldTex(
text, size = "\\Large"
).next_to(numerator, DOWN)
for text in ("v_%d"%x, "\\sqrt{y_%d}"%x)
]
vs.append(v)
sqrt_ys.append(sqrt_y)
start, end = [
Mobject(
left.copy(), mobs[0], equals.copy(), right.copy(), mobs[1]
).replace(frame)
for mobs in (vs, sqrt_ys)
]
self.add(start)
self.wait(2)
self.play(Transform(
start, end,
path_func = counterclockwise_path()
))
self.wait(2)
self.remove(start, end)
def show_main_equation(self):
self.equation = OldTex("""
\\dfrac{\\sin(\\theta)}{\\sqrt{y}} =
\\text{constant}
""")
self.equation.shift(LEFT)
self.equation.shift(
(self.layer_tops[0]-self.equation.get_top())*UP
)
self.add(self.equation)
self.wait()
def ask_continuous_question(self):
continuous = self.get_continuous_background()
line = Line(
UP, DOWN,
density = self.zoom_factor*DEFAULT_POINT_DENSITY_1D
)
theta = OldTex("\\theta")
theta.scale(0.5/self.zoom_factor)
self.play(
ShowCreation(continuous),
Animation(self.equation)
)
self.remove(*self.layers)
self.play(ShowCreation(self.cycloid))
self.activate_zooming()
little_square = self.get_zoomed_camera_mobject()
self.add(line)
indices = np.arange(
0, self.cycloid.get_num_points()-1, 10
)
for index in indices:
point = self.cycloid.get_points()[index]
next_point = self.cycloid.get_points()[index+1]
angle = angle_of_vector(point - next_point)
for mob in little_square, line:
mob.shift(point - mob.get_center())
arc = Arc(angle-np.pi/2, start_angle = np.pi/2)
arc.scale(0.1)
arc.shift(point)
self.add(arc)
if angle > np.pi/2 + np.pi/6:
vect_angle = interpolate(np.pi/2, angle, 0.5)
vect = rotate_vector(RIGHT, vect_angle)
theta.center()
theta.shift(point)
theta.shift(0.15*vect)
self.add(theta)
self.wait(self.frame_duration)
self.remove(arc) |
|
import numpy as np
import itertools as it
from manim_imports_ext import *
from from_3b1b.old.brachistochrone.curves import \
Cycloid, PathSlidingScene, RANDY_SCALE_FACTOR, TryManyPaths
class Lens(Arc):
CONFIG = {
"radius" : 2,
"angle" : np.pi/2,
"color" : BLUE_B,
}
def __init__(self, **kwargs):
digest_config(self, kwargs)
Arc.__init__(self, self.angle, **kwargs)
def init_points(self):
Arc.init_points(self)
self.rotate(-np.pi/4)
self.shift(-self.get_left())
self.add_points(self.copy().rotate(np.pi).points)
class PhotonScene(Scene):
def wavify(self, mobject):
result = mobject.copy()
result.ingest_submobjects()
tangent_vectors = result.get_points()[1:]-result.get_points()[:-1]
lengths = np.apply_along_axis(
get_norm, 1, tangent_vectors
)
thick_lengths = lengths.repeat(3).reshape((len(lengths), 3))
unit_tangent_vectors = tangent_vectors/thick_lengths
rot_matrix = np.transpose(rotation_matrix(np.pi/2, OUT))
normal_vectors = np.dot(unit_tangent_vectors, rot_matrix)
# total_length = np.sum(lengths)
times = np.cumsum(lengths)
nudge_sizes = 0.1*np.sin(2*np.pi*times)
thick_nudge_sizes = nudge_sizes.repeat(3).reshape((len(nudge_sizes), 3))
nudges = thick_nudge_sizes*normal_vectors
result.get_points()[1:] += nudges
return result
def photon_run_along_path(self, path, color = YELLOW, **kwargs):
if "rate_func" not in kwargs:
kwargs["rate_func"] = None
photon = self.wavify(path)
photon.set_color(color)
return ShowPassingFlash(photon, **kwargs)
class SimplePhoton(PhotonScene):
def construct(self):
text = OldTexText("Light")
text.to_edge(UP)
self.play(ShimmerIn(text))
self.play(self.photon_run_along_path(
Cycloid(), rate_func=linear
))
self.wait()
class MultipathPhotonScene(PhotonScene):
CONFIG = {
"num_paths" : 5
}
def run_along_paths(self, **kwargs):
paths = self.get_paths()
colors = Color(YELLOW).range_to(WHITE, len(paths))
for path, color in zip(paths, colors):
path.set_color(color)
photon_runs = [
self.photon_run_along_path(path)
for path in paths
]
for photon_run, path in zip(photon_runs, paths):
self.play(
photon_run,
ShowCreation(
path,
rate_func = lambda t : 0.9*smooth(t)
),
**kwargs
)
self.wait()
def generate_paths(self):
raise Exception("Not Implemented")
class PhotonThroughLens(MultipathPhotonScene):
def construct(self):
self.lens = Lens()
self.add(self.lens)
self.run_along_paths()
def get_paths(self):
interval_values = np.arange(self.num_paths).astype('float')
interval_values /= (self.num_paths-1.)
first_contact = [
self.lens.point_from_proportion(0.4*v+0.55)
for v in reversed(interval_values)
]
second_contact = [
self.lens.point_from_proportion(0.3*v + 0.1)
for v in interval_values
]
focal_point = 2*RIGHT
return [
Mobject(
Line(FRAME_X_RADIUS*LEFT + fc[1]*UP, fc),
Line(fc, sc),
Line(sc, focal_point),
Line(focal_point, 6*focal_point-5*sc)
).ingest_submobjects()
for fc, sc in zip(first_contact, second_contact)
]
class TransitionToOptics(PhotonThroughLens):
def construct(self):
optics = OldTexText("Optics")
optics.to_edge(UP)
self.add(optics)
self.has_started = False
PhotonThroughLens.construct(self)
def play(self, *args, **kwargs):
if not self.has_started:
self.has_started = True
everything = Mobject(*self.mobjects)
vect = FRAME_WIDTH*RIGHT
everything.shift(vect)
self.play(ApplyMethod(
everything.shift, -vect,
rate_func = rush_from
))
Scene.play(self, *args, **kwargs)
class PhotonOffMirror(MultipathPhotonScene):
def construct(self):
self.mirror = Line(*FRAME_Y_RADIUS*np.array([DOWN, UP]))
self.mirror.set_color(GREY)
self.add(self.mirror)
self.run_along_paths()
def get_paths(self):
interval_values = np.arange(self.num_paths).astype('float')
interval_values /= (self.num_paths-1)
anchor_points = [
self.mirror.point_from_proportion(0.6*v+0.3)
for v in interval_values
]
start_point = 5*LEFT+3*UP
end_points = []
for point in anchor_points:
vect = start_point-point
vect[1] *= -1
end_points.append(point+2*vect)
return [
Mobject(
Line(start_point, anchor_point),
Line(anchor_point, end_point)
).ingest_submobjects()
for anchor_point, end_point in zip(anchor_points, end_points)
]
class PhotonsInWater(MultipathPhotonScene):
def construct(self):
water = Region(lambda x, y : y < 0, color = BLUE_E)
self.add(water)
self.run_along_paths()
def get_paths(self):
x, y = -3, 3
start_point = x*RIGHT + y*UP
angles = np.arange(np.pi/18, np.pi/3, np.pi/18)
midpoints = y*np.arctan(angles)
end_points = midpoints + FRAME_Y_RADIUS*np.arctan(2*angles)
return [
Mobject(
Line(start_point, [midpoint, 0, 0]),
Line([midpoint, 0, 0], [end_point, -FRAME_Y_RADIUS, 0])
).ingest_submobjects()
for midpoint, end_point in zip(midpoints, end_points)
]
class ShowMultiplePathsScene(PhotonScene):
def construct(self):
text = OldTexText("Which path minimizes travel time?")
text.to_edge(UP)
self.generate_start_and_end_points()
point_a = Dot(self.start_point)
point_b = Dot(self.end_point)
A = OldTexText("A").next_to(point_a, UP)
B = OldTexText("B").next_to(point_b, DOWN)
paths = self.get_paths()
for point, letter in [(point_a, A), (point_b, B)]:
self.play(
ShowCreation(point),
ShimmerIn(letter)
)
self.play(ShimmerIn(text))
curr_path = paths[0].copy()
curr_path_copy = curr_path.copy().ingest_submobjects()
self.play(
self.photon_run_along_path(curr_path),
ShowCreation(curr_path_copy, rate_func = rush_into)
)
self.remove(curr_path_copy)
for path in paths[1:] + [paths[0]]:
self.play(Transform(curr_path, path, run_time = 4))
self.wait()
self.path = curr_path.ingest_submobjects()
def generate_start_and_end_points(self):
raise Exception("Not Implemented")
def get_paths(self):
raise Exception("Not implemented")
class ShowMultiplePathsThroughLens(ShowMultiplePathsScene):
def construct(self):
self.lens = Lens()
self.add(self.lens)
ShowMultiplePathsScene.construct(self)
def generate_start_and_end_points(self):
self.start_point = 3*LEFT + UP
self.end_point = 2*RIGHT
def get_paths(self):
alphas = [0.25, 0.4, 0.58, 0.75]
lower_right, upper_right, upper_left, lower_left = list(map(
self.lens.point_from_proportion, alphas
))
return [
Mobject(
Line(self.start_point, a),
Line(a, b),
Line(b, self.end_point)
).set_color(color)
for (a, b), color in zip(
[
(upper_left, upper_right),
(upper_left, lower_right),
(lower_left, lower_right),
(lower_left, upper_right),
],
Color(YELLOW).range_to(WHITE, 4)
)
]
class ShowMultiplePathsOffMirror(ShowMultiplePathsScene):
def construct(self):
mirror = Line(*FRAME_Y_RADIUS*np.array([DOWN, UP]))
mirror.set_color(GREY)
self.add(mirror)
ShowMultiplePathsScene.construct(self)
def generate_start_and_end_points(self):
self.start_point = 4*LEFT + 2*UP
self.end_point = 4*LEFT + 2*DOWN
def get_paths(self):
return [
Mobject(
Line(self.start_point, midpoint),
Line(midpoint, self.end_point)
).set_color(color)
for midpoint, color in zip(
[2*UP, 2*DOWN],
Color(YELLOW).range_to(WHITE, 2)
)
]
class ShowMultiplePathsInWater(ShowMultiplePathsScene):
def construct(self):
glass = Region(lambda x, y : y < 0, color = BLUE_E)
self.generate_start_and_end_points()
straight = Line(self.start_point, self.end_point)
slow = OldTexText("Slow")
slow.rotate(np.arctan(straight.get_slope()))
slow.shift(straight.get_points()[int(0.7*straight.get_num_points())])
slow.shift(0.5*DOWN)
too_long = OldTexText("Too long")
too_long.shift(UP)
air = OldTexText("Air").shift(2*UP)
water = OldTexText("Water").shift(2*DOWN)
self.add(glass)
self.play(GrowFromCenter(air))
self.play(GrowFromCenter(water))
self.wait()
self.remove(air, water)
ShowMultiplePathsScene.construct(self)
self.play(
Transform(self.path, straight)
)
self.wait()
self.play(GrowFromCenter(slow))
self.wait()
self.remove(slow)
self.leftmost.ingest_submobjects()
self.play(Transform(self.path, self.leftmost, run_time = 3))
self.wait()
self.play(ShimmerIn(too_long))
self.wait()
def generate_start_and_end_points(self):
self.start_point = 3*LEFT + 2*UP
self.end_point = 3*RIGHT + 2*DOWN
def get_paths(self):
self.leftmost, self.rightmost = result = [
Mobject(
Line(self.start_point, midpoint),
Line(midpoint, self.end_point)
).set_color(color)
for midpoint, color in zip(
[3*LEFT, 3*RIGHT],
Color(YELLOW).range_to(WHITE, 2)
)
]
return result
class StraightLinesFastestInConstantMedium(PhotonScene):
def construct(self):
kwargs = {"size" : "\\Large"}
left = OldTexText("Speed of light is constant", **kwargs)
arrow = OldTex("\\Rightarrow", **kwargs)
right = OldTexText("Staight path is fastest", **kwargs)
left.next_to(arrow, LEFT)
right.next_to(arrow, RIGHT)
squaggle, line = self.get_paths()
self.play(*list(map(ShimmerIn, [left, arrow, right])))
self.play(ShowCreation(squaggle))
self.play(self.photon_run_along_path(
squaggle, run_time = 2, rate_func=linear
))
self.play(Transform(
squaggle, line,
path_func = path_along_arc(np.pi)
))
self.play(self.photon_run_along_path(line, rate_func=linear))
self.wait()
def get_paths(self):
squaggle = ParametricCurve(
lambda t : (0.5*t+np.cos(t))*RIGHT+np.sin(t)*UP,
start = -np.pi,
end = 2*np.pi
)
squaggle.shift(2*UP)
start, end = squaggle.get_points()[0], squaggle.get_points()[-1]
line = Line(start, end)
result = [squaggle, line]
for mob in result:
mob.set_color(BLUE_D)
return result
class PhtonBendsInWater(PhotonScene, ZoomedScene):
def construct(self):
glass = Region(lambda x, y : y < 0, color = BLUE_E)
kwargs = {
"density" : self.zoom_factor*DEFAULT_POINT_DENSITY_1D
}
top_line = Line(FRAME_Y_RADIUS*UP+2*LEFT, ORIGIN, **kwargs)
extension = Line(ORIGIN, FRAME_Y_RADIUS*DOWN+2*RIGHT, **kwargs)
bottom_line = Line(ORIGIN, FRAME_Y_RADIUS*DOWN+RIGHT, **kwargs)
path1 = Mobject(top_line, extension)
path2 = Mobject(top_line, bottom_line)
for mob in path1, path2:
mob.ingest_submobjects()
extension.set_color(RED)
theta1 = np.arctan(bottom_line.get_slope())
theta2 = np.arctan(extension.get_slope())
arc = Arc(theta2-theta1, start_angle = theta1, radius = 2)
question_mark = OldTexText("$\\theta$?")
question_mark.shift(arc.get_center()+0.5*DOWN+0.25*RIGHT)
wave = self.wavify(path2)
wave.set_color(YELLOW)
wave.scale(0.5)
self.add(glass)
self.play(ShowCreation(path1))
self.play(Transform(path1, path2))
self.wait()
# self.activate_zooming()
self.wait()
self.play(ShowPassingFlash(
wave, run_time = 3, rate_func=linear
))
self.wait()
self.play(ShowCreation(extension))
self.play(
ShowCreation(arc),
ShimmerIn(question_mark)
)
class LightIsFasterInAirThanWater(ShowMultiplePathsInWater):
def construct(self):
glass = Region(lambda x, y : y < 0, color = BLUE_E)
equation = OldTex("v_{\\text{air}} > v_{\\text{water}}")
equation.to_edge(UP)
path = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT)
path1 = path.copy().shift(2*UP)
path2 = path.copy().shift(2*DOWN)
self.add(glass)
self.play(ShimmerIn(equation))
self.wait()
photon_runs = []
photon_runs.append(self.photon_run_along_path(
path1, rate_func = lambda t : min(1, 1.2*t)
))
photon_runs.append(self.photon_run_along_path(path2))
self.play(*photon_runs, **{"run_time" : 2})
self.wait()
class GeometryOfGlassSituation(ShowMultiplePathsInWater):
def construct(self):
glass = Region(lambda x, y : y < 0, color = BLUE_E)
self.generate_start_and_end_points()
left = self.start_point[0]*RIGHT
right = self.end_point[0]*RIGHT
start_x = interpolate(left, right, 0.2)
end_x = interpolate(left, right, 1.0)
left_line = Line(self.start_point, left, color = RED_D)
right_line = Line(self.end_point, right, color = RED_D)
h_1, h_2 = list(map(Tex, ["h_1", "h_2"]))
h_1.next_to(left_line, LEFT)
h_2.next_to(right_line, RIGHT)
point_a = Dot(self.start_point)
point_b = Dot(self.end_point)
A = OldTexText("A").next_to(point_a, UP)
B = OldTexText("B").next_to(point_b, DOWN)
x = start_x
left_brace = Brace(Mobject(Point(left), Point(x)))
right_brace = Brace(Mobject(Point(x), Point(right)), UP)
x_mob = OldTex("x")
x_mob.next_to(left_brace, DOWN)
w_minus_x = OldTex("w-x")
w_minus_x.next_to(right_brace, UP)
top_line = Line(self.start_point, x)
bottom_line = Line(x, self.end_point)
top_dist = OldTex("\\sqrt{h_1^2+x^2}")
top_dist.scale(0.5)
a = 0.3
n = top_line.get_num_points()
point = top_line.get_points()[int(a*n)]
top_dist.next_to(Point(point), RIGHT, buff = 0.3)
bottom_dist = OldTex("\\sqrt{h_2^2+(w-x)^2}")
bottom_dist.scale(0.5)
n = bottom_line.get_num_points()
point = bottom_line.get_points()[int((1-a)*n)]
bottom_dist.next_to(Point(point), LEFT, buff = 1)
end_top_line = Line(self.start_point, end_x)
end_bottom_line = Line(end_x, self.end_point)
end_brace = Brace(Mobject(Point(left), Point(end_x)))
end_x_mob = OldTex("x").next_to(end_brace, DOWN)
axes = Mobject(
NumberLine(),
NumberLine().rotate(np.pi/2).shift(7*LEFT)
)
graph = FunctionGraph(
lambda x : 0.4*(x+1)*(x-3)+4,
x_min = -2,
x_max = 4
)
graph.set_color(YELLOW)
Mobject(axes, graph).scale(0.2).to_corner(UP+RIGHT, buff = 1)
axes.add(OldTex("x", size = "\\small").next_to(axes, RIGHT))
axes.add(OldTexText("Travel time", size = "\\small").next_to(
axes, UP
))
new_graph = graph.copy()
midpoint = new_graph.get_points()[new_graph.get_num_points()/2]
new_graph.filter_out(lambda p : p[0] < midpoint[0])
new_graph.reverse_points()
pairs_for_end_transform = [
(mob, mob.copy())
for mob in (top_line, bottom_line, left_brace, x_mob)
]
self.add(glass, point_a, point_b, A, B)
line = Mobject(top_line, bottom_line).ingest_submobjects()
self.play(ShowCreation(line))
self.wait()
self.play(
GrowFromCenter(left_brace),
GrowFromCenter(x_mob)
)
self.play(
GrowFromCenter(right_brace),
GrowFromCenter(w_minus_x)
)
self.play(ShowCreation(left_line), ShimmerIn(h_1))
self.play(ShowCreation(right_line), GrowFromCenter(h_2))
self.play(ShimmerIn(top_dist))
self.play(GrowFromCenter(bottom_dist))
self.wait(3)
self.clear()
self.add(glass, point_a, point_b, A, B,
top_line, bottom_line, left_brace, x_mob)
self.play(ShowCreation(axes))
kwargs = {
"run_time" : 4,
}
self.play(*[
Transform(*pair, **kwargs)
for pair in [
(top_line, end_top_line),
(bottom_line, end_bottom_line),
(left_brace, end_brace),
(x_mob, end_x_mob)
]
]+[ShowCreation(graph, **kwargs)])
self.wait()
self.show_derivatives(graph)
line = self.show_derivatives(new_graph)
self.add(line)
self.play(*[
Transform(*pair, rate_func = lambda x : 0.3*smooth(x))
for pair in pairs_for_end_transform
])
self.wait()
def show_derivatives(self, graph, run_time = 2):
step = self.frame_duration/run_time
for a in smooth(np.arange(0, 1-step, step)):
index = int(a*graph.get_num_points())
p1, p2 = graph.get_points()[index], graph.get_points()[index+1]
line = Line(LEFT, RIGHT)
line.rotate(angle_of_vector(p2-p1))
line.shift(p1)
self.add(line)
self.wait(self.frame_duration)
self.remove(line)
return line
class Spring(Line):
CONFIG = {
"num_loops" : 5,
"loop_radius" : 0.3,
"color" : GREY
}
def init_points(self):
## self.start, self.end
length = get_norm(self.end-self.start)
angle = angle_of_vector(self.end-self.start)
micro_radius = self.loop_radius/length
m = 2*np.pi*(self.num_loops+0.5)
def loop(t):
return micro_radius*(
RIGHT + np.cos(m*t)*LEFT + np.sin(m*t)*UP
)
new_epsilon = self.epsilon/(m*micro_radius)/length
self.add_points([
t*RIGHT + loop(t)
for t in np.arange(0, 1, new_epsilon)
])
self.scale(length/(1+2*micro_radius))
self.rotate(angle)
self.shift(self.start)
class SpringSetup(ShowMultiplePathsInWater):
def construct(self):
self.ring_shift_val = 6*RIGHT
self.slide_kwargs = {
"rate_func" : there_and_back,
"run_time" : 5
}
self.setup_background()
rod = Region(
lambda x, y : (abs(x) < 5) & (abs(y) < 0.05),
color = GOLD_E
)
ring = Arc(
angle = 11*np.pi/6,
start_angle = -11*np.pi/12,
radius = 0.2,
color = YELLOW
)
ring.shift(-self.ring_shift_val/2)
self.generate_springs(ring)
self.add_rod_and_ring(rod, ring)
self.slide_ring(ring)
self.wait()
self.add_springs()
self.add_force_definitions()
self.slide_system(ring)
self.show_horizontal_component(ring)
self.show_angles(ring)
self.show_equation()
def setup_background(self):
glass = Region(lambda x, y : y < 0, color = BLUE_E)
self.generate_start_and_end_points()
point_a = Dot(self.start_point)
point_b = Dot(self.end_point)
A = OldTexText("A").next_to(point_a, UP)
B = OldTexText("B").next_to(point_b, DOWN)
self.add(glass, point_a, point_b, A, B)
def generate_springs(self, ring):
self.start_springs, self.end_springs = [
Mobject(
Spring(self.start_point, r.get_top()),
Spring(self.end_point, r.get_bottom())
)
for r in (ring, ring.copy().shift(self.ring_shift_val))
]
def add_rod_and_ring(self, rod, ring):
rod_word = OldTexText("Rod")
rod_word.next_to(Point(), UP)
ring_word = OldTexText("Ring")
ring_word.next_to(ring, UP)
self.wait()
self.add(rod)
self.play(ShimmerIn(rod_word))
self.wait()
self.remove(rod_word)
self.play(ShowCreation(ring))
self.play(ShimmerIn(ring_word))
self.wait()
self.remove(ring_word)
def slide_ring(self, ring):
self.play(ApplyMethod(
ring.shift, self.ring_shift_val,
**self.slide_kwargs
))
def add_springs(self):
colors = iter([BLACK, BLUE_E])
for spring in self.start_springs.split():
circle = Circle(color = next(colors))
circle.reverse_points()
circle.scale(spring.loop_radius)
circle.shift(spring.get_points()[0])
self.play(Transform(circle, spring))
self.remove(circle)
self.add(spring)
self.wait()
def add_force_definitions(self):
top_force = OldTex("F_1 = \\dfrac{1}{v_{\\text{air}}}")
bottom_force = OldTex("F_2 = \\dfrac{1}{v_{\\text{water}}}")
top_spring, bottom_spring = self.start_springs.split()
top_force.next_to(top_spring)
bottom_force.next_to(bottom_spring, DOWN, buff = -0.5)
words = OldTexText("""
The force in a real spring is
proportional to that spring's length
""")
words.to_corner(UP+RIGHT)
for force in top_force, bottom_force:
self.play(GrowFromCenter(force))
self.wait()
self.play(ShimmerIn(words))
self.wait(3)
self.remove(top_force, bottom_force, words)
def slide_system(self, ring):
equilibrium_slide_kwargs = dict(self.slide_kwargs)
def jiggle_to_equilibrium(t):
return 0.7*(1+((1-t)**2)*(-np.cos(10*np.pi*t)))
equilibrium_slide_kwargs = {
"rate_func" : jiggle_to_equilibrium,
"run_time" : 3
}
start = Mobject(ring, self.start_springs)
end = Mobject(
ring.copy().shift(self.ring_shift_val),
self.end_springs
)
for kwargs in self.slide_kwargs, equilibrium_slide_kwargs:
self.play(Transform(start, end, **kwargs))
self.wait()
def show_horizontal_component(self, ring):
v_right = Vector(ring.get_top(), RIGHT)
v_left = Vector(ring.get_bottom(), LEFT)
self.play(*list(map(ShowCreation, [v_right, v_left])))
self.wait()
self.remove(v_right, v_left)
def show_angles(self, ring):
ring_center = ring.get_center()
lines, arcs, thetas = [], [], []
counter = it.count(1)
for point in self.start_point, self.end_point:
line = Line(point, ring_center, color = GREY)
angle = np.pi/2-np.abs(np.arctan(line.get_slope()))
arc = Arc(angle, radius = 0.5).rotate(np.pi/2)
if point is self.end_point:
arc.rotate(np.pi)
theta = OldTex("\\theta_%d"%next(counter))
theta.scale(0.5)
theta.shift(2*arc.get_center())
arc.shift(ring_center)
theta.shift(ring_center)
lines.append(line)
arcs.append(arc)
thetas.append(theta)
vert_line = Line(2*UP, 2*DOWN)
vert_line.shift(ring_center)
top_spring, bottom_spring = self.start_springs.split()
self.play(
Transform(ring, Point(ring_center)),
Transform(top_spring, lines[0]),
Transform(bottom_spring, lines[1])
)
self.play(ShowCreation(vert_line))
anims = []
for arc, theta in zip(arcs, thetas):
anims += [
ShowCreation(arc),
GrowFromCenter(theta)
]
self.play(*anims)
self.wait()
def show_equation(self):
equation = OldTex([
"\\left(\\dfrac{1}{\\phantom{v_air}}\\right)",
"\\sin(\\theta_1)",
"=",
"\\left(\\dfrac{1}{\\phantom{v_water}}\\right)",
"\\sin(\\theta_2)"
])
equation.to_corner(UP+RIGHT)
frac1, sin1, equals, frac2, sin2 = equation.split()
v_air, v_water = [
OldTex("v_{\\text{%s}}"%s, size = "\\Large")
for s in ("air", "water")
]
v_air.next_to(Point(frac1.get_center()), DOWN)
v_water.next_to(Point(frac2.get_center()), DOWN)
frac1.add(v_air)
frac2.add(v_water)
f1, f2 = [
OldTex("F_%d"%d, size = "\\Large")
for d in (1, 2)
]
f1.next_to(sin1, LEFT)
f2.next_to(equals, RIGHT)
sin2_start = sin2.copy().next_to(f2, RIGHT)
bar1 = OldTex("\\dfrac{\\qquad}{\\qquad}")
bar2 = bar1.copy()
bar1.next_to(sin1, DOWN)
bar2.next_to(sin2, DOWN)
v_air_copy = v_air.copy().next_to(bar1, DOWN)
v_water_copy = v_water.copy().next_to(bar2, DOWN)
bars = Mobject(bar1, bar2)
new_eq = equals.copy().center().shift(bars.get_center())
snells = OldTexText("Snell's Law")
snells.set_color(YELLOW)
snells.shift(new_eq.get_center()[0]*RIGHT)
snells.shift(UP)
anims = []
for mob in f1, sin1, equals, f2, sin2_start:
anims.append(ShimmerIn(mob))
self.play(*anims)
self.wait()
for f, frac in (f1, frac1), (f2, frac2):
target = frac.copy().ingest_submobjects()
also = []
if f is f2:
also.append(Transform(sin2_start, sin2))
sin2 = sin2_start
self.play(Transform(f, target), *also)
self.remove(f)
self.add(frac)
self.wait()
self.play(
FadeOut(frac1),
FadeOut(frac2),
Transform(v_air, v_air_copy),
Transform(v_water, v_water_copy),
ShowCreation(bars),
Transform(equals, new_eq)
)
self.wait()
frac1 = Mobject(sin1, bar1, v_air)
frac2 = Mobject(sin2, bar2, v_water)
for frac, vect in (frac1, LEFT), (frac2, RIGHT):
self.play(ApplyMethod(
frac.next_to, equals, vect
))
self.wait()
self.play(ShimmerIn(snells))
self.wait()
class WhatGovernsTheSpeedOfLight(PhotonScene, PathSlidingScene):
def construct(self):
randy = Randolph()
randy.scale(RANDY_SCALE_FACTOR)
randy.shift(-randy.get_bottom())
self.add_cycloid_end_points()
self.add(self.cycloid)
self.slide(randy, self.cycloid)
self.play(self.photon_run_along_path(self.cycloid))
self.wait()
class WhichPathWouldLightTake(PhotonScene, TryManyPaths):
def construct(self):
words = OldTexText(
["Which path ", "would \\emph{light} take", "?"]
)
words.split()[1].set_color(YELLOW)
words.to_corner(UP+RIGHT)
self.add_cycloid_end_points()
anims = [
self.photon_run_along_path(
path,
rate_func = smooth
)
for path in self.get_paths()
]
self.play(anims[0], ShimmerIn(words))
for anim in anims[1:]:
self.play(anim)
class StateSnellsLaw(PhotonScene):
def construct(self):
point_a = 3*LEFT+3*UP
point_b = 1.5*RIGHT+3*DOWN
midpoint = ORIGIN
lines, arcs, thetas = [], [], []
counter = it.count(1)
for point in point_a, point_b:
line = Line(point, midpoint, color = RED_D)
angle = np.pi/2-np.abs(np.arctan(line.get_slope()))
arc = Arc(angle, radius = 0.5).rotate(np.pi/2)
if point is point_b:
arc.rotate(np.pi)
line.reverse_points()
theta = OldTex("\\theta_%d"%next(counter))
theta.scale(0.5)
theta.shift(2*arc.get_center())
arc.shift(midpoint)
theta.shift(midpoint)
lines.append(line)
arcs.append(arc)
thetas.append(theta)
vert_line = Line(2*UP, 2*DOWN)
vert_line.shift(midpoint)
path = Mobject(*lines).ingest_submobjects()
glass = Region(lambda x, y : y < 0, color = BLUE_E)
self.add(glass)
equation = OldTex([
"\\dfrac{\\sin(\\theta_1)}{v_{\\text{air}}}",
"=",
"\\dfrac{\\sin(\\theta_2)}{v_{\\text{water}}}",
])
equation.to_corner(UP+RIGHT)
exp1, equals, exp2 = equation.split()
snells_law = OldTexText("Snell's Law:")
snells_law.set_color(YELLOW)
snells_law.to_edge(UP)
self.play(ShimmerIn(snells_law))
self.wait()
self.play(ShowCreation(path))
self.play(self.photon_run_along_path(path))
self.wait()
self.play(ShowCreation(vert_line))
self.play(*list(map(ShowCreation, arcs)))
self.play(*list(map(GrowFromCenter, thetas)))
self.wait()
self.play(ShimmerIn(exp1))
self.wait()
self.play(*list(map(ShimmerIn, [equals, exp2])))
self.wait()
|
|
import numpy as np
import itertools as it
import operator as op
import sys
import inspect
from PIL import Image
import cv2
import random
from scipy.spatial.distance import cdist
from scipy import ndimage
from manim_imports_ext import *
DEFAULT_GAUSS_BLUR_CONFIG = {
"ksize" : (5, 5),
"sigmaX" : 6,
"sigmaY" : 6,
}
DEFAULT_CANNY_CONFIG = {
"threshold1" : 50,
"threshold2" : 100,
}
DEFAULT_BLUR_RADIUS = 0.5
DEFAULT_CONNECTED_COMPONENT_THRESHOLD = 25
def reverse_colors(nparray):
return nparray[:,:,[2, 1, 0]]
def show(nparray):
Image.fromarray(reverse_colors(nparray)).show()
def thicken(nparray):
height, width = nparray.shape
nparray = nparray.reshape((height, width, 1))
return np.repeat(nparray, 3, 2)
def sort_by_color(mob):
indices = np.argsort(np.apply_along_axis(
lambda p : -get_norm(p),
1,
mob.rgbas
))
mob.rgbas = mob.rgbas[indices]
mob.points = mob.get_points()[indices]
def get_image_array(name):
image_files = os.listdir(IMAGE_DIR)
possibilities = [s for s in image_files if s.startswith(name)]
for possibility in possibilities:
try:
path = os.path.join(IMAGE_DIR, possibility)
image = Image.open(path)
image = image.convert('RGB')
return np.array(image)
except:
pass
raise Exception("Image for %s not found"%name)
def get_edges(image_array):
blurred = cv2.GaussianBlur(
image_array,
**DEFAULT_GAUSS_BLUR_CONFIG
)
edges = cv2.Canny(
blurred,
**DEFAULT_CANNY_CONFIG
)
return edges
def nearest_neighbor_align(mobject1, mobject2):
distance_matrix = cdist(mobject1.points, mobject2.points)
closest_point_indices = np.apply_along_axis(
np.argmin, 0, distance_matrix
)
new_mob1 = Mobject()
new_mob2 = Mobject()
for n in range(mobject1.get_num_points()):
indices = (closest_point_indices == n)
new_mob1.add_points(
[mobject1.get_points()[n]]*sum(indices)
)
new_mob2.add_points(
mobject2.get_points()[indices],
rgbas = mobject2.rgbas[indices]
)
return new_mob1, new_mob2
def get_connected_components(image_array,
blur_radius = DEFAULT_BLUR_RADIUS,
threshold = DEFAULT_CONNECTED_COMPONENT_THRESHOLD):
blurred_image = ndimage.gaussian_filter(image_array, blur_radius)
labels, component_count = ndimage.label(blurred_image > threshold)
return [
image_array * (labels == count)
for count in range(1, component_count+1)
]
def color_region(bw_region, colored_image):
return thicken(bw_region > 0) * colored_image
class TracePicture(Scene):
args_list = [
("Newton",),
("Mark_Levi",),
("Steven_Strogatz",),
("Pierre_de_Fermat",),
("Galileo_Galilei",),
("Jacob_Bernoulli",),
("Johann_Bernoulli2",),
("Old_Newton",)
]
@staticmethod
def args_to_string(name):
return name
@staticmethod
def string_to_args(name):
return name
def construct(self, name):
run_time = 20
scale_factor = 0.8
image_array = get_image_array(name)
edge_mobject = self.get_edge_mobject(image_array)
full_picture = MobjectFromPixelArray(image_array)
for mob in edge_mobject, full_picture:
# mob.stroke_width = 4
mob.scale(scale_factor)
mob.show()
self.play(
DelayByOrder(FadeIn(
full_picture,
run_time = run_time,
rate_func = squish_rate_func(smooth, 0.7, 1)
)),
ShowCreation(
edge_mobject,
run_time = run_time,
rate_func=linear
)
)
self.remove(edge_mobject)
self.wait()
def get_edge_mobject(self, image_array):
edged_image = get_edges(image_array)
individual_edges = get_connected_components(edged_image)
colored_edges = [
color_region(edge, image_array)
for edge in individual_edges
]
colored_edge_mobject_list = [
MobjectFromPixelArray(colored_edge)
for colored_edge in colored_edges
]
random.shuffle(colored_edge_mobject_list)
edge_mobject = Mobject(*colored_edge_mobject_list)
edge_mobject.ingest_submobjects()
return edge_mobject
class JohannThinksHeIsBetter(Scene):
def construct(self):
names = [
"Johann_Bernoulli2",
"Jacob_Bernoulli",
"Gottfried_Wilhelm_von_Leibniz",
"Newton"
]
guys = [
ImageMobject(name, invert = False)
for name in names
]
johann = guys[0]
johann.scale(0.8)
pensive_johann = johann.copy()
pensive_johann.scale(0.25)
pensive_johann.to_corner(DOWN+LEFT)
comparitive_johann = johann.copy()
template = Square(side_length = 2)
comparitive_johann.replace(template)
comparitive_johann.shift(UP+LEFT)
greater_than = OldTex(">")
greater_than.next_to(comparitive_johann)
for guy, name in zip(guys, names)[1:]:
guy.replace(template)
guy.next_to(greater_than)
name_mob = OldTexText(name.replace("_", " "))
name_mob.scale(0.5)
name_mob.next_to(guy, DOWN)
guy.name_mob = name_mob
guy.sort_points(lambda p : np.dot(p, DOWN+RIGHT))
bubble = ThoughtBubble(initial_width = 12)
bubble.stretch_to_fit_height(6)
bubble.ingest_submobjects()
bubble.pin_to(pensive_johann)
bubble.shift(DOWN)
point = Point(johann.get_corner(UP+RIGHT))
upper_point = Point(comparitive_johann.get_corner(UP+RIGHT))
lightbulb = ImageMobject("Lightbulb", invert = False)
lightbulb.scale(0.1)
lightbulb.sort_points(get_norm)
lightbulb.next_to(upper_point, RIGHT)
self.add(johann)
self.wait()
self.play(
Transform(johann, pensive_johann),
Transform(point, bubble),
run_time = 2
)
self.remove(point)
self.add(bubble)
weakling = guys[1]
self.play(
FadeIn(comparitive_johann),
ShowCreation(greater_than),
FadeIn(weakling)
)
self.wait(2)
for guy in guys[2:]:
self.play(DelayByOrder(Transform(
weakling, upper_point
)))
self.play(
FadeIn(guy),
ShimmerIn(guy.name_mob)
)
self.wait(3)
self.remove(guy.name_mob)
weakling = guy
self.play(FadeOut(weakling), FadeOut(greater_than))
self.play(ShowCreation(lightbulb))
self.wait()
self.play(FadeOut(comparitive_johann), FadeOut(lightbulb))
self.play(ApplyMethod(
Mobject(johann, bubble).scale, 10,
run_time = 3
))
class NewtonVsJohann(Scene):
def construct(self):
newton, johann = [
ImageMobject(name, invert = False).scale(0.5)
for name in ("Newton", "Johann_Bernoulli2")
]
greater_than = OldTex(">")
newton.next_to(greater_than, RIGHT)
johann.next_to(greater_than, LEFT)
self.add(johann, greater_than, newton)
for i in range(2):
kwargs = {
"path_func" : counterclockwise_path(),
"run_time" : 2
}
self.play(
ApplyMethod(newton.replace, johann, **kwargs),
ApplyMethod(johann.replace, newton, **kwargs),
)
self.wait()
class JohannThinksOfFermat(Scene):
def construct(self):
johann, fermat = [
ImageMobject(name, invert = False)
for name in ("Johann_Bernoulli2", "Pierre_de_Fermat")
]
johann.scale(0.2)
johann.to_corner(DOWN+LEFT)
bubble = ThoughtBubble(initial_width = 12)
bubble.stretch_to_fit_height(6)
bubble.pin_to(johann)
bubble.shift(DOWN)
bubble.add_content(fermat)
fermat.scale(0.4)
self.add(johann, bubble)
self.wait()
self.play(FadeIn(fermat))
self.wait()
class MathematiciansOfEurope(Scene):
def construct(self):
europe = ImageMobject("Europe", use_cache = False)
self.add(europe)
self.freeze_background()
mathematicians = [
("Newton", [-1.75, -0.75, 0]),
("Jacob_Bernoulli",[-0.75, -1.75, 0]),
("Ehrenfried_von_Tschirnhaus",[0.5, -0.5, 0]),
("Gottfried_Wilhelm_von_Leibniz",[0.2, -1.75, 0]),
("Guillaume_de_L'Hopital", [-1.75, -1.25, 0]),
]
for name, point in mathematicians:
man = ImageMobject(name, invert = False)
if name == "Newton":
name = "Isaac_Newton"
name_mob = OldTexText(name.replace("_", " "))
name_mob.to_corner(UP+LEFT, buff=0.75)
self.add(name_mob)
man.set_height(4)
mobject = Point(man.get_corner(UP+LEFT))
self.play(Transform(mobject, man))
man.scale(0.2)
man.shift(point)
self.play(Transform(mobject, man))
self.remove(name_mob)
class OldNewtonIsDispleased(Scene):
def construct(self):
old_newton = ImageMobject("Old_Newton", invert = False)
old_newton.scale(0.8)
self.add(old_newton)
self.freeze_background()
words = OldTexText("Note the displeasure")
words.to_corner(UP+RIGHT)
face_point = 1.8*UP+0.5*LEFT
arrow = Arrow(words.get_bottom(), face_point)
self.play(ShimmerIn(words))
self.play(ShowCreation(arrow))
self.wait()
class NewtonConsideredEveryoneBeneathHim(Scene):
def construct(self):
mathematicians = [
ImageMobject(name, invert = False)
for name in [
"Old_Newton",
"Johann_Bernoulli2",
"Jacob_Bernoulli",
"Ehrenfried_von_Tschirnhaus",
"Gottfried_Wilhelm_von_Leibniz",
"Guillaume_de_L'Hopital",
]
]
newton = mathematicians.pop(0)
newton.scale(0.8)
new_newton = newton.copy()
new_newton.set_height(3)
new_newton.to_edge(UP)
for man in mathematicians:
man.set_width(1.7)
johann = mathematicians.pop(0)
johann.next_to(new_newton, DOWN)
last_left, last_right = johann, johann
for man, count in zip(mathematicians, it.count()):
if count%2 == 0:
man.next_to(last_left, LEFT)
last_left = man
else:
man.next_to(last_right, RIGHT)
last_right = man
self.play(
Transform(newton, new_newton),
GrowFromCenter(johann)
)
self.wait()
self.play(FadeIn(Mobject(*mathematicians)))
self.wait()
|
|
import numpy as np
import itertools as it
from manim_imports_ext import *
from from_3b1b.old.brachistochrone.curves import Cycloid
class PhysicalIntuition(Scene):
def construct(self):
n_terms = 4
def func(xxx_todo_changeme):
(x, y, ignore) = xxx_todo_changeme
z = complex(x, y)
if (np.abs(x%1 - 0.5)<0.01 and y < 0.01) or np.abs(z)<0.01:
return ORIGIN
out_z = 1./(2*np.tan(np.pi*z)*(z**2))
return out_z.real*RIGHT - out_z.imag*UP
arrows = Mobject(*[
Arrow(ORIGIN, np.sqrt(2)*point)
for point in compass_directions(4, RIGHT+UP)
])
arrows.set_color(YELLOW)
arrows.ingest_submobjects()
all_arrows = Mobject(*[
arrows.copy().scale(0.3/(x)).shift(x*RIGHT)
for x in range(1, n_terms+2)
])
terms = OldTex([
"\\dfrac{1}{%d^2} + "%(x+1)
for x in range(n_terms)
]+["\\cdots"])
terms.shift(2*UP)
plane = NumberPlane(color = BLUE_E)
axes = Mobject(NumberLine(), NumberLine().rotate(np.pi/2))
axes.set_color(WHITE)
for term in terms.split():
self.play(ShimmerIn(term, run_time = 0.5))
self.wait()
self.play(ShowCreation(plane), ShowCreation(axes))
self.play(*[
Transform(*pair)
for pair in zip(terms.split(), all_arrows.split())
])
self.play(PhaseFlow(
func, plane,
run_time = 5,
virtual_time = 8
))
class TimeLine(Scene):
def construct(self):
dated_events = [
{
"date" : 1696,
"text": "Johann Bernoulli poses Brachistochrone problem",
"picture" : "Johann_Bernoulli2"
},
{
"date" : 1662,
"text" : "Fermat states his principle of least time",
"picture" : "Pierre_de_Fermat"
}
]
speical_dates = [2016] + [
obj["date"] for obj in dated_events
]
centuries = list(range(1600, 2100, 100))
timeline = NumberLine(
numerical_radius = 300,
number_at_center = 1800,
unit_length_to_spatial_width = FRAME_X_RADIUS/100,
tick_frequency = 10,
numbers_with_elongated_ticks = centuries
)
timeline.add_numbers(*centuries)
centers = [
Point(timeline.number_to_point(year))
for year in speical_dates
]
timeline.add(*centers)
timeline.shift(-centers[0].get_center())
self.add(timeline)
self.wait()
run_times = iter([3, 1])
for point, event in zip(centers[1:], dated_events):
self.play(ApplyMethod(
timeline.shift, -point.get_center(),
run_time = next(run_times)
))
picture = ImageMobject(event["picture"], invert = False)
picture.set_width(2)
picture.to_corner(UP+RIGHT)
event_mob = OldTexText(event["text"])
event_mob.shift(2*LEFT+2*UP)
date_mob = OldTex(str(event["date"]))
date_mob.scale(0.5)
date_mob.shift(0.6*UP)
line = Line(event_mob.get_bottom(), 0.2*UP)
self.play(
ShimmerIn(event_mob),
ShowCreation(line),
ShimmerIn(date_mob)
)
self.play(FadeIn(picture))
self.wait(3)
self.play(*list(map(FadeOut, [event_mob, date_mob, line, picture])))
class StayedUpAllNight(Scene):
def construct(self):
clock = Circle(radius = 2, color = WHITE)
clock.add(Dot(ORIGIN))
ticks = Mobject(*[
Line(1.8*vect, 2*vect, color = GREY)
for vect in compass_directions(12)
])
clock.add(ticks)
hour_hand = Line(ORIGIN, UP)
minute_hand = Line(ORIGIN, 1.5*UP)
clock.add(hour_hand, minute_hand)
clock.to_corner(UP+RIGHT)
hour_hand.get_center = lambda : clock.get_center()
minute_hand.get_center = lambda : clock.get_center()
solution = ImageMobject(
"Newton_brachistochrone_solution2",
use_cache = False
)
solution.stroke_width = 3
solution.set_color(GREY)
solution.set_width(5)
solution.to_corner(UP+RIGHT)
newton = ImageMobject("Old_Newton", invert = False)
newton.scale(0.8)
phil_trans = OldTexText("Philosophical Transactions")
rect = Rectangle(height = 6, width = 4.5, color = WHITE)
rect.to_corner(UP+RIGHT)
rect.shift(DOWN)
phil_trans.set_width(0.8*rect.get_width())
phil_trans.next_to(Point(rect.get_top()), DOWN)
new_solution = solution.copy()
new_solution.set_width(phil_trans.get_width())
new_solution.next_to(phil_trans, DOWN, buff = 1)
not_newton = OldTexText("-Totally not by Newton")
not_newton.set_width(2.5)
not_newton.next_to(new_solution, DOWN, aligned_edge = RIGHT)
phil_trans.add(rect)
newton_complaint = OldTexText([
"``I do not love to be",
" \\emph{dunned} ",
"and teased by foreigners''"
], size = "\\small")
newton_complaint.to_edge(UP, buff = 0.2)
dunned = newton_complaint.split()[1]
dunned.set_color()
dunned_def = OldTexText("(old timey term for making \\\\ demands on someone)")
dunned_def.scale(0.7)
dunned_def.next_to(phil_trans, LEFT)
dunned_def.shift(2*UP)
dunned_arrow = Arrow(dunned_def, dunned)
johann = ImageMobject("Johann_Bernoulli2", invert = False)
johann.scale(0.4)
johann.to_edge(LEFT)
johann.shift(DOWN)
johann_quote = OldTexText("``I recognize the lion by his claw''")
johann_quote.next_to(johann, UP, aligned_edge = LEFT)
self.play(ApplyMethod(newton.to_edge, LEFT))
self.play(ShowCreation(clock))
kwargs = {
"axis" : OUT,
"rate_func" : smooth
}
self.play(
Rotating(hour_hand, radians = -2*np.pi, **kwargs),
Rotating(minute_hand, radians = -12*2*np.pi, **kwargs),
run_time = 5
)
self.wait()
self.clear()
self.add(newton)
clock.ingest_submobjects()
self.play(Transform(clock, solution))
self.remove(clock)
self.add(solution)
self.wait()
self.play(
FadeIn(phil_trans),
Transform(solution, new_solution)
)
self.wait()
self.play(ShimmerIn(not_newton))
phil_trans.add(solution, not_newton)
self.wait()
self.play(*list(map(ShimmerIn, newton_complaint.split())))
self.wait()
self.play(
ShimmerIn(dunned_def),
ShowCreation(dunned_arrow)
)
self.wait()
self.remove(dunned_def, dunned_arrow)
self.play(FadeOut(newton_complaint))
self.remove(newton_complaint)
self.play(
FadeOut(newton),
GrowFromCenter(johann)
)
self.remove(newton)
self.wait()
self.play(ShimmerIn(johann_quote))
self.wait()
class ThetaTGraph(Scene):
def construct(self):
t_axis = NumberLine()
theta_axis = NumberLine().rotate(np.pi/2)
theta_mob = OldTex("\\theta(t)")
t_mob = OldTex("t")
theta_mob.next_to(theta_axis, RIGHT)
theta_mob.to_edge(UP)
t_mob.next_to(t_axis, UP)
t_mob.to_edge(RIGHT)
graph = ParametricCurve(
lambda t : 4*t*RIGHT + 2*smooth(t)*UP
)
line = Line(graph.get_points()[0], graph.get_points()[-1], color = WHITE)
q_mark = OldTexText("?")
q_mark.next_to(Point(graph.get_center()), LEFT)
stars = Stars(color = BLACK)
stars.scale(0.1).shift(q_mark.get_center())
squiggle = ParametricCurve(
lambda t : t*RIGHT + 0.2*t*(5-t)*(np.sin(t)**2)*UP,
start = 0,
end = 5
)
self.play(
ShowCreation(t_axis),
ShowCreation(theta_axis),
ShimmerIn(theta_mob),
ShimmerIn(t_mob)
)
self.play(
ShimmerIn(q_mark),
ShowCreation(graph)
)
self.wait()
self.play(
Transform(q_mark, stars),
Transform(graph, line)
)
self.wait()
self.play(Transform(graph, squiggle))
self.wait()
class SolutionsToTheBrachistochrone(Scene):
def construct(self):
r_range = np.arange(0.5, 2, 0.25)
cycloids = Mobject(*[
Cycloid(radius = r, end_theta=2*np.pi)
for r in r_range
])
lower_left = 2*DOWN+6*LEFT
lines = Mobject(*[
Line(
lower_left,
lower_left+5*r*np.cos(np.arctan(r))*RIGHT+2*r*np.sin(np.arctan(r))*UP
)
for r in r_range
])
nl = NumberLine(numbers_with_elongated_ticks = [])
x_axis = nl.copy().shift(3*UP)
y_axis = nl.copy().rotate(np.pi/2).shift(6*LEFT)
t_axis = nl.copy().shift(2*DOWN)
x_label = OldTex("x")
x_label.next_to(x_axis, DOWN)
x_label.to_edge(RIGHT)
y_label = OldTex("y")
y_label.next_to(y_axis, RIGHT)
y_label.shift(2*DOWN)
t_label = OldTex("t")
t_label.next_to(t_axis, UP)
t_label.to_edge(RIGHT)
theta_label = OldTex("\\theta")
theta_label.next_to(y_axis, RIGHT)
theta_label.to_edge(UP)
words = OldTexText("Boundary conditions?")
words.next_to(lines, RIGHT)
words.shift(2*UP)
self.play(ShowCreation(x_axis), ShimmerIn(x_label))
self.play(ShowCreation(y_axis), ShimmerIn(y_label))
self.play(ShowCreation(cycloids))
self.wait()
self.play(
Transform(cycloids, lines),
Transform(x_axis, t_axis),
Transform(x_label, t_label),
Transform(y_label, theta_label),
run_time = 2
)
self.wait()
self.play(ShimmerIn(words))
self.wait()
class VideoLayout(Scene):
def construct(self):
left, right = 5*LEFT, 5*RIGHT
top_words = OldTexText("The next 15 minutes of your life:")
top_words.to_edge(UP)
line = Line(left, right, color = BLUE_D)
for a in np.arange(0, 4./3, 1./3):
vect = interpolate(left, right, a)
line.add_line(vect+0.2*DOWN, vect+0.2*UP)
left_brace = Brace(
Mobject(
Point(left),
Point(interpolate(left, right, 2./3))
),
DOWN
)
right_brace = Brace(
Mobject(
Point(interpolate(left, right, 2./3)),
Point(right)
),
UP
)
left_brace.words = list(map(TexText, [
"Problem statement",
"History",
"Johann Bernoulli's cleverness"
]))
curr = left_brace
right_brace.words = list(map(TexText, [
"Challenge",
"Mark Levi's cleverness",
]))
for brace in left_brace, right_brace:
curr = brace
direction = DOWN if brace is left_brace else UP
for word in brace.words:
word.next_to(curr, direction)
curr = word
right_brace.words.reverse()
self.play(ShimmerIn(top_words))
self.play(ShowCreation(line))
for brace in left_brace, right_brace:
self.play(GrowFromCenter(brace))
self.wait()
for word in brace.words:
self.play(ShimmerIn(word))
self.wait()
class ShortestPathProblem(Scene):
def construct(self):
point_a, point_b = 3*LEFT, 3*RIGHT
dots = []
for point, char in [(point_a, "A"), (point_b, "B")]:
dot = Dot(point)
letter = OldTex(char)
letter.next_to(dot, UP+LEFT)
dot.add(letter)
dots.append(dot)
path = ParametricCurve(
lambda t : (t/2 + np.cos(t))*RIGHT + np.sin(t)*UP,
start = -2*np.pi,
end = 2*np.pi
)
path.scale(6/(2*np.pi))
path.shift(point_a - path.get_points()[0])
path.set_color(RED)
line = Line(point_a, point_b)
words = OldTexText("Shortest path from $A$ to $B$")
words.to_edge(UP)
self.play(
ShimmerIn(words),
*list(map(GrowFromCenter, dots))
)
self.play(ShowCreation(path))
self.play(Transform(
path, line,
path_func = path_along_arc(np.pi)
))
self.wait()
class MathBetterThanTalking(Scene):
def construct(self):
mathy = Mathematician()
mathy.to_corner(DOWN+LEFT)
bubble = ThoughtBubble()
bubble.pin_to(mathy)
bubble.write("Math $>$ Talking about math")
self.add(mathy)
self.play(ShowCreation(bubble))
self.play(ShimmerIn(bubble.content))
self.wait()
self.play(ApplyMethod(
mathy.blink,
rate_func = squish_rate_func(there_and_back, 0.4, 0.6)
))
class DetailsOfProofBox(Scene):
def construct(self):
rect = Rectangle(height = 4, width = 6, color = WHITE)
words = OldTexText("Details of proof")
words.to_edge(UP)
self.play(
ShowCreation(rect),
ShimmerIn(words)
)
self.wait()
class TalkedAboutSnellsLaw(Scene):
def construct(self):
randy = Randolph()
randy.to_corner(DOWN+LEFT)
morty = Mortimer()
morty.to_edge(DOWN+RIGHT)
randy.bubble = SpeechBubble().pin_to(randy)
morty.bubble = SpeechBubble().pin_to(morty)
phrases = [
"Let's talk about Snell's law",
"I love Snell's law",
"It's like running from \\\\ a beach into the ocean",
"It's like two constant \\\\ tension springs",
]
self.add(randy, morty)
talkers = it.cycle([randy, morty])
for talker, phrase in zip(talkers, phrases):
talker.bubble.write(phrase)
self.play(
FadeIn(talker.bubble),
ShimmerIn(talker.bubble.content)
)
self.play(ApplyMethod(
talker.blink,
rate_func = squish_rate_func(there_and_back)
))
self.wait()
self.remove(talker.bubble, talker.bubble.content)
class YetAnotherMarkLevi(Scene):
def construct(self):
words = OldTexText("Yet another bit of Mark Levi cleverness")
words.to_edge(UP)
levi = ImageMobject("Mark_Levi", invert = False)
levi.set_width(6)
levi.show()
self.add(levi)
self.play(ShimmerIn(words))
self.wait(2)
|
|
import numpy as np
import itertools as it
import os
from manim_imports_ext import *
from from_3b1b.old.brachistochrone.drawing_images import sort_by_color
class Intro(Scene):
def construct(self):
logo = ImageMobject("LogoGeneration", invert = False)
name_mob = OldTexText("3Blue1Brown").center()
name_mob.set_color("grey")
name_mob.shift(2*DOWN)
self.add(name_mob, logo)
new_text = OldTexText(["with ", "Steven Strogatz"])
new_text.next_to(name_mob, DOWN)
self.play(*[
ShimmerIn(part)
for part in new_text.split()
])
self.wait()
with_word, steve = new_text.split()
steve_copy = steve.copy().center().to_edge(UP)
# logo.sort_points(lambda p : -get_norm(p))
sort_by_color(logo)
self.play(
Transform(steve, steve_copy),
DelayByOrder(Transform(logo, Point())),
FadeOut(with_word),
FadeOut(name_mob),
run_time = 3
)
class IntroduceSteve(Scene):
def construct(self):
name = OldTexText("Steven Strogatz")
name.to_edge(UP)
contributions = OldTexText("Frequent Contributions")
contributions.scale(0.5).to_edge(RIGHT).shift(2*UP)
books_word = OldTexText("Books")
books_word.scale(0.5).to_edge(LEFT).shift(2*UP)
radio_lab, sci_fri, cornell, book2, book3, book4 = [
ImageMobject(filename, invert = False, filter_color = WHITE)
for filename in [
"radio_lab",
"science_friday",
"cornell",
"strogatz_book2",
"strogatz_book3",
"strogatz_book4",
]
]
book1 = ImageMobject("strogatz_book1", invert = False)
nyt = ImageMobject("new_york_times")
logos = [radio_lab, nyt, sci_fri]
books = [book1, book2, book3, book4]
sample_size = Square(side_length = 2)
last = contributions
for image in logos:
image.replace(sample_size)
image.next_to(last, DOWN)
last = image
sci_fri.scale(0.9)
shift_val = 0
sample_size.scale(0.75)
for book in books:
book.replace(sample_size)
book.next_to(books_word, DOWN)
book.shift(shift_val*(RIGHT+DOWN))
shift_val += 0.5
sample_size.scale(2)
cornell.replace(sample_size)
cornell.next_to(name, DOWN)
self.add(name)
self.play(FadeIn(cornell))
self.play(ShimmerIn(books_word))
for book in books:
book.shift(5*LEFT)
self.play(ApplyMethod(book.shift, 5*RIGHT))
self.play(ShimmerIn(contributions))
for logo in logos:
self.play(FadeIn(logo))
self.wait()
class ShowTweets(Scene):
def construct(self):
tweets = [
ImageMobject("tweet%d"%x, invert = False)
for x in range(1, 4)
]
for tweet in tweets:
tweet.scale(0.4)
tweets[0].to_corner(UP+LEFT)
tweets[1].next_to(tweets[0], RIGHT, aligned_edge = UP)
tweets[2].next_to(tweets[1], DOWN)
self.play(GrowFromCenter(tweets[0]))
for x in 1, 2:
self.play(
Transform(Point(tweets[x-1].get_center()), tweets[x]),
Animation(tweets[x-1])
)
self.wait()
class LetsBeHonest(Scene):
def construct(self):
self.play(ShimmerIn(OldTexText("""
Let's be honest about who benefits
from this collaboration...
""")))
self.wait()
class WhatIsTheBrachistochrone(Scene):
def construct(self):
self.play(ShimmerIn(OldTexText("""
So \\dots what is the Brachistochrone?
""")))
self.wait()
class DisectBrachistochroneWord(Scene):
def construct(self):
word = OldTexText(["Bra", "chis", "to", "chrone"])
original_word = word.copy()
dots = []
for part in word.split():
if dots:
part.next_to(dots[-1], buff = 0.06)
dot = OldTex("\\cdot")
dot.next_to(part, buff = 0.06)
dots.append(dot)
dots = Mobject(*dots[:-1])
dots.shift(0.1*DOWN)
Mobject(word, dots).center()
overbrace1 = Brace(Mobject(*word.split()[:-1]), UP)
overbrace2 = Brace(word.split()[-1], UP)
shortest = OldTexText("Shortest")
shortest.next_to(overbrace1, UP)
shortest.set_color(YELLOW)
time = OldTexText("Time")
time.next_to(overbrace2, UP)
time.set_color(YELLOW)
chrono_example = OldTexText("""
As in ``Chronological'' \\\\
or ``Synchronize''
""")
chrono_example.scale(0.5)
chrono_example.to_edge(RIGHT)
chrono_example.shift(2*UP)
chrono_example.set_color(BLUE_D)
chrono_arrow = Arrow(
word.get_right(),
chrono_example.get_bottom(),
color = BLUE_D
)
brachy_example = OldTexText("As in . . . brachydactyly?")
brachy_example.scale(0.5)
brachy_example.to_edge(LEFT)
brachy_example.shift(2*DOWN)
brachy_example.set_color(GREEN)
brachy_arrow = Arrow(
word.get_left(),
brachy_example.get_top(),
color = GREEN
)
pronunciation = OldTexText(["/br", "e", "kist","e","kr$\\bar{o}$n/"])
pronunciation.split()[1].rotate(np.pi)
pronunciation.split()[3].rotate(np.pi)
pronunciation.scale(0.7)
pronunciation.shift(DOWN)
latin = OldTexText(list("Latin"))
greek = OldTexText(list("Greek"))
for mob in latin, greek:
mob.to_edge(LEFT)
question_mark = OldTexText("?").next_to(greek, buff = 0.1)
stars = Stars().set_color(BLACK)
stars.scale(0.5).shift(question_mark.get_center())
self.play(Transform(original_word, word), ShowCreation(dots))
self.play(ShimmerIn(pronunciation))
self.wait()
self.play(
GrowFromCenter(overbrace1),
GrowFromCenter(overbrace2)
)
self.wait()
self.play(ShimmerIn(latin))
self.play(FadeIn(question_mark))
self.play(Transform(
latin, greek,
path_func = counterclockwise_path()
))
self.wait()
self.play(Transform(question_mark, stars))
self.remove(stars)
self.wait()
self.play(ShimmerIn(shortest))
self.play(ShimmerIn(time))
for ex, ar in [(chrono_example, chrono_arrow), (brachy_example, brachy_arrow)]:
self.play(
ShowCreation(ar),
ShimmerIn(ex)
)
self.wait()
class OneSolutionTwoInsights(Scene):
def construct(self):
one_solution = OldTexText(["One ", "solution"])
two_insights = OldTexText(["Two ", " insights"])
two, insights = two_insights.split()
johann = ImageMobject("Johann_Bernoulli2", invert = False)
mark = ImageMobject("Mark_Levi", invert = False)
for mob in johann, mark:
mob.scale(0.4)
johann.next_to(insights, LEFT)
mark.next_to(johann, RIGHT)
name = OldTexText("Mark Levi").to_edge(UP)
self.play(*list(map(ShimmerIn, one_solution.split())))
self.wait()
for pair in zip(one_solution.split(), two_insights.split()):
self.play(Transform(*pair, path_func = path_along_arc(np.pi)))
self.wait()
self.clear()
self.add(two, insights)
for word, man in [(two, johann), (insights, mark)]:
self.play(
Transform(word, Point(word.get_left())),
GrowFromCenter(man)
)
self.wait()
self.clear()
self.play(ApplyMethod(mark.center))
self.play(ShimmerIn(name))
self.wait()
class CircleOfIdeas(Scene):
def construct(self):
words = list(map(TexText, [
"optics", "calculus", "mechanics", "geometry", "history"
]))
words[0].set_color(YELLOW)
words[1].set_color(BLUE_D)
words[2].set_color(GREY)
words[3].set_color(GREEN)
words[4].set_color(MAROON)
brachistochrone = OldTexText("Brachistochrone")
displayed_words = []
for word in words:
anims = self.get_spinning_anims(displayed_words)
word.shift(3*RIGHT)
point = Point()
anims.append(Transform(point, word))
self.play(*anims)
self.remove(point)
self.add(word)
displayed_words.append(word)
self.play(*self.get_spinning_anims(displayed_words))
self.play(*[
Transform(
word, word.copy().set_color(BLACK).center().scale(0.1),
path_func = path_along_arc(np.pi),
rate_func=linear,
run_time = 2
)
for word in displayed_words
]+[
GrowFromCenter(brachistochrone)
])
self.wait()
def get_spinning_anims(self, words, angle = np.pi/6):
anims = []
for word in words:
old_center = word.get_center()
new_center = rotate_vector(old_center, angle)
vect = new_center-old_center
anims.append(ApplyMethod(
word.shift, vect,
path_func = path_along_arc(angle),
rate_func=linear
))
return anims
class FermatsPrincipleStatement(Scene):
def construct(self):
words = OldTexText([
"Fermat's principle:",
"""
If a beam of light travels
from point $A$ to $B$, it does so along the
fastest path possible.
"""
])
words.split()[0].set_color(BLUE)
everything = MobjectFromRegion(Region())
everything.scale(0.9)
angles = np.apply_along_axis(
angle_of_vector, 1, everything.points
)
norms = np.apply_along_axis(
get_norm, 1, everything.points
)
norms -= np.min(norms)
norms /= np.max(norms)
alphas = 0.25 + 0.75 * norms * (1 + np.sin(12*angles))/2
everything.rgbas = alphas.repeat(3).reshape((len(alphas), 3))
Mobject(everything, words).show()
everything.sort_points(get_norm)
self.add(words)
self.play(
DelayByOrder(FadeIn(everything, run_time = 3)),
Animation(words)
)
self.play(
ApplyMethod(everything.set_color, WHITE),
)
self.wait()
class VideoProgression(Scene):
def construct(self):
spacing = 2*UP
brachy, optics, light_in_two, snells, multi = words = [
OldTexText(text)
for text in [
"Brachistochrone",
"Optics",
"Light in two media",
"Snell's Law",
"Multilayered glass",
]
]
for mob in light_in_two, snells:
mob.shift(-spacing)
arrow1 = Arrow(brachy, optics)
arrow2 = Arrow(optics, snells)
point = Point(DOWN)
self.play(ShimmerIn(brachy))
self.wait()
self.play(
ApplyMethod(brachy.shift, spacing),
Transform(point, optics)
)
optics = point
arrow1 = Arrow(optics, brachy)
self.play(ShowCreation(arrow1))
self.wait()
arrow2 = Arrow(light_in_two, optics)
self.play(
ShowCreation(arrow2),
ShimmerIn(light_in_two)
)
self.wait()
self.play(
FadeOut(light_in_two),
GrowFromCenter(snells),
DelayByOrder(
ApplyMethod(arrow2.set_color, BLUE_D)
)
)
self.wait()
self.play(
FadeOut(optics),
GrowFromCenter(multi),
DelayByOrder(
ApplyMethod(arrow1.set_color, BLUE_D)
)
)
self.wait()
class BalanceCompetingFactors(Scene):
args_list = [
("Short", "Steep"),
("Minimal time \\\\ in water", "Short path")
]
@staticmethod
def args_to_string(*words):
return "".join([word.split(" ")[0] for word in words])
def construct(self, *words):
factor1, factor2 = [
OldTexText("Factor %d"%x).set_color(c)
for x, c in [
(1, RED_D),
(2, BLUE_D)
]
]
real_factor1, real_factor2 = list(map(TexText, words))
for word in factor1, factor2, real_factor1, real_factor2:
word.shift(0.2*UP-word.get_bottom())
for f1 in factor1, real_factor1:
f1.set_color(RED_D)
f1.shift(2*LEFT)
for f2 in factor2, real_factor2:
f2.set_color(BLUE_D)
f2.shift(2*RIGHT)
line = Line(
factor1.get_left(),
factor2.get_right()
)
line.center()
self.balancers = Mobject(factor1, factor2, line)
self.hidden_balancers = Mobject(real_factor1, real_factor2)
triangle = Polygon(RIGHT, np.sqrt(3)*UP, LEFT)
triangle.next_to(line, DOWN, buff = 0)
self.add(triangle, self.balancers)
self.rotate(1)
self.rotate(-2)
self.wait()
self.play(Transform(
factor1, real_factor1,
path_func = path_along_arc(np.pi/4)
))
self.rotate(2)
self.wait()
self.play(Transform(
factor2, real_factor2,
path_func = path_along_arc(np.pi/4)
))
self.rotate(-2)
self.wait()
self.rotate(1)
def rotate(self, factor):
angle = np.pi/11
self.play(Rotate(
self.balancers,
factor*angle,
run_time = abs(factor)
))
self.hidden_balancers.rotate(factor*angle)
class Challenge(Scene):
def construct(self):
self.add(OldTexText("""
Can you find a new solution to the
Brachistochrone problem by finding
an intuitive reason that time-minimizing
curves look like straight lines in
$t$-$\\theta$ space?
"""))
self.wait()
class Section1(Scene):
def construct(self):
self.add(OldTexText("Section 1: Johann Bernoulli's insight"))
self.wait()
class Section2(Scene):
def construct(self):
self.add(OldTexText(
"Section 2: Mark Levi's insight, and a challenge",
size = "\\large"
))
self.wait()
class NarratorInterjection(Scene):
def construct(self):
words1 = OldTex("<\\text{Narrator interjection}>")
words2 = OldTex("<\\!/\\text{Narrator interjection}>")
self.add(words1)
self.wait()
self.clear()
self.add(words2)
self.wait()
class ThisCouldBeTheEnd(Scene):
def construct(self):
words = OldTexText([
"This could be the end\\dots",
"but\\dots"
])
for part in words.split():
self.play(ShimmerIn(part))
self.wait()
class MyOwnChallenge(Scene):
def construct(self):
self.add(OldTexText("My own challenge:"))
self.wait()
class WarmupChallenge(Scene):
def construct(self):
self.add(OldTexText("\\large Warm-up challenge: Confirm this for yourself"))
self.wait()
class FindAnotherSolution(Scene):
def construct(self):
self.add(OldTexText("Find another brachistochrone solution\\dots"))
self.wait()
class ProofOfSnellsLaw(Scene):
def construct(self):
self.add(OldTexText("Proof of Snell's law:"))
self.wait()
class CondensedVersion(Scene):
def construct(self):
snells = OldTexText("Snell's")
snells.shift(-snells.get_left())
snells.to_edge(UP)
for vect in [RIGHT, RIGHT, LEFT, DOWN, DOWN, DOWN]:
snells.add(snells.copy().next_to(snells, vect))
snells.ingest_submobjects()
snells.show()
condensed = OldTexText("condensed")
self.add(snells)
self.wait()
self.play(DelayByOrder(
Transform(snells, condensed, run_time = 2)
))
self.wait()
|
|
import numpy as np
import itertools as it
from manim_imports_ext import *
from from_3b1b.old.brachistochrone.light import PhotonScene
from from_3b1b.old.brachistochrone.curves import *
class MultilayeredScene(Scene):
CONFIG = {
"n_layers" : 5,
"top_color" : BLUE_E,
"bottom_color" : BLUE_A,
"total_glass_height" : 5,
"top" : 3*UP,
"RectClass" : Rectangle #FilledRectangle
}
def get_layers(self, n_layers = None):
if n_layers is None:
n_layers = self.n_layers
width = FRAME_WIDTH
height = float(self.total_glass_height)/n_layers
rgb_pair = [
np.array(Color(color).get_rgb())
for color in (self.top_color, self.bottom_color)
]
rgb_range = [
interpolate(*rgb_pair+[x])
for x in np.arange(0, 1, 1./n_layers)
]
tops = [
self.top + x*height*DOWN
for x in range(n_layers)
]
color = Color()
result = []
for top, rgb in zip(tops, rgb_range):
color.set_rgb(rgb)
rect = self.RectClass(
height = height,
width = width,
color = color
)
rect.shift(top-rect.get_top())
result.append(rect)
return result
def add_layers(self):
self.layers = self.get_layers()
self.add(*self.layers)
self.freeze_background()
def get_bottom(self):
return self.top + self.total_glass_height*DOWN
def get_continuous_glass(self):
result = self.RectClass(
width = FRAME_WIDTH,
height = self.total_glass_height,
)
result.sort_points(lambda p : -p[1])
result.set_color_by_gradient(self.top_color, self.bottom_color)
result.shift(self.top-result.get_top())
return result
class TwoToMany(MultilayeredScene):
CONFIG = {
"RectClass" : FilledRectangle
}
def construct(self):
glass = self.get_glass()
layers = self.get_layers()
self.add(glass)
self.wait()
self.play(*[
FadeIn(
layer,
rate_func = squish_rate_func(smooth, x, 1)
)
for layer, x in zip(layers[1:], it.count(0, 0.2))
]+[
Transform(glass, layers[0])
])
self.wait()
def get_glass(self):
return self.RectClass(
height = FRAME_Y_RADIUS,
width = FRAME_WIDTH,
color = BLUE_E
).shift(FRAME_Y_RADIUS*DOWN/2)
class RaceLightInLayers(MultilayeredScene, PhotonScene):
CONFIG = {
"RectClass" : FilledRectangle
}
def construct(self):
self.add_layers()
line = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT)
lines = [
line.copy().shift(layer.get_center())
for layer in self.layers
]
def rate_maker(x):
return lambda t : min(x*x*t, 1)
min_rate, max_rate = 1., 2.
rates = np.arange(min_rate, max_rate, (max_rate-min_rate)/self.n_layers)
self.play(*[
self.photon_run_along_path(
line,
rate_func = rate_maker(rate),
run_time = 2
)
for line, rate in zip(lines, rates)
])
class ShowDiscretePath(MultilayeredScene, PhotonScene):
CONFIG = {
"RectClass" : FilledRectangle
}
def construct(self):
self.add_layers()
self.cycloid = Cycloid(end_theta = np.pi)
self.generate_discrete_path()
self.play(ShowCreation(self.discrete_path))
self.wait()
self.play(self.photon_run_along_path(
self.discrete_path,
rate_func = rush_into,
run_time = 3
))
self.wait()
def generate_discrete_path(self):
points = self.cycloid.points
tops = [mob.get_top()[1] for mob in self.layers]
tops.append(tops[-1]-self.layers[0].get_height())
indices = [
np.argmin(np.abs(points[:, 1]-top))
for top in tops
]
self.bend_points = points[indices[1:-1]]
self.path_angles = []
self.discrete_path = Mobject1D(
color = WHITE,
density = 3*DEFAULT_POINT_DENSITY_1D
)
for start, end in zip(indices, indices[1:]):
start_point, end_point = points[start], points[end]
self.discrete_path.add_line(
start_point, end_point
)
self.path_angles.append(
angle_of_vector(start_point-end_point)-np.pi/2
)
self.discrete_path.add_line(
points[end], FRAME_X_RADIUS*RIGHT+(tops[-1]-0.5)*UP
)
class NLayers(MultilayeredScene):
CONFIG = {
"RectClass" : FilledRectangle
}
def construct(self):
self.add_layers()
brace = Brace(
Mobject(
Point(self.top),
Point(self.get_bottom())
),
RIGHT
)
n_layers = OldTexText("$n$ layers")
n_layers.next_to(brace)
self.wait()
self.add(brace)
self.show_frame()
self.play(
GrowFromCenter(brace),
GrowFromCenter(n_layers)
)
self.wait()
class ShowLayerVariables(MultilayeredScene, PhotonScene):
CONFIG = {
"RectClass" : FilledRectangle
}
def construct(self):
self.add_layers()
v_equations = []
start_ys = []
end_ys = []
center_paths = []
braces = []
for layer, x in zip(self.layers[:3], it.count(1)):
eq_mob = OldTex(
["v_%d"%x, "=", "\sqrt{\phantom{y_1}}"],
size = "\\Large"
)
eq_mob.shift(layer.get_center()+2*LEFT)
v_eq = eq_mob.split()
v_eq[0].set_color(layer.get_color())
path = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT)
path.shift(layer.get_center())
brace_endpoints = Mobject(
Point(self.top),
Point(layer.get_bottom())
)
brace = Brace(brace_endpoints, RIGHT)
brace.shift(x*RIGHT)
start_y = OldTex("y_%d"%x, size = "\\Large")
end_y = start_y.copy()
start_y.next_to(brace, RIGHT)
end_y.shift(v_eq[-1].get_center())
nudge = 0.2*RIGHT
end_y.shift(nudge)
v_equations.append(v_eq)
start_ys.append(start_y)
end_ys.append(end_y)
center_paths.append(path)
braces.append(brace)
for v_eq, path, time in zip(v_equations, center_paths, [2, 1, 0.5]):
photon_run = self.photon_run_along_path(
path,
rate_func=linear
)
self.play(
FadeToColor(v_eq[0], WHITE),
photon_run,
run_time = time
)
self.wait()
starts = [0, 0.3, 0.6]
self.play(*it.chain(*[
[
GrowFromCenter(
mob,
rate_func=squish_rate_func(smooth, start, 1)
)
for mob, start in zip(mobs, starts)
]
for mobs in (start_ys, braces)
]))
self.wait()
triplets = list(zip(v_equations, start_ys, end_ys))
anims = []
for v_eq, start_y, end_y in triplets:
anims += [
ShowCreation(v_eq[1]),
ShowCreation(v_eq[2]),
Transform(start_y.copy(), end_y)
]
self.play(*anims)
self.wait()
class LimitingProcess(MultilayeredScene):
CONFIG = {
"RectClass" : FilledRectangle
}
def construct(self):
num_iterations = 3
layer_sets = [
self.get_layers((2**x)*self.n_layers)
for x in range(num_iterations)
]
glass_sets = [
Mobject(*[
Mobject(
*layer_sets[x][(2**x)*index:(2**x)*(index+1)]
)
for index in range(self.n_layers)
]).ingest_submobjects()
for x in range(num_iterations)
]
glass_sets.append(self.get_continuous_glass())
for glass_set in glass_sets:
glass_set.sort_points(lambda p : p[1])
curr_set = glass_sets[0]
self.add(curr_set)
for layer_set in glass_sets[1:]:
self.wait()
self.play(Transform(curr_set, layer_set))
self.wait()
class ShowLightAndSlidingObject(MultilayeredScene, TryManyPaths, PhotonScene):
CONFIG = {
"show_time" : False,
"wait_and_add" : False,
"RectClass" : FilledRectangle
}
def construct(self):
glass = self.get_continuous_glass()
self.play(ApplyMethod(glass.fade, 0.8))
self.freeze_background()
paths = self.get_paths()
for path in paths:
if path.get_height() > self.total_glass_height:
path.stretch(0.7, 1)
path.shift(self.top - path.get_top())
path.rgbas[:,2] = 0
loop = paths.pop(1) ##Bad!
randy = Randolph()
randy.scale(RANDY_SCALE_FACTOR)
randy.shift(-randy.get_bottom())
photon_run = self.photon_run_along_path(
loop,
rate_func = lambda t : smooth(1.2*t, 2),
run_time = 4.1
)
text = self.get_text().to_edge(UP, buff = 0.2)
self.play(ShowCreation(loop))
self.wait()
self.play(photon_run)
self.remove(photon_run.mobject)
randy = self.slide(randy, loop)
self.add(randy)
self.wait()
self.remove(randy)
self.play(ShimmerIn(text))
for path in paths:
self.play(Transform(
loop, path,
path_func = path_along_arc(np.pi/2),
run_time = 2
))
class ContinuouslyObeyingSnellsLaw(MultilayeredScene):
CONFIG = {
"arc_radius" : 0.5,
"RectClass" : FilledRectangle
}
def construct(self):
glass = self.get_continuous_glass()
self.add(glass)
self.freeze_background()
cycloid = Cycloid(end_theta = np.pi)
cycloid.set_color(YELLOW)
chopped_cycloid = cycloid.copy()
n = cycloid.get_num_points()
chopped_cycloid.filter_out(lambda p : p[1] > 1 and p[0] < 0)
chopped_cycloid.reverse_points()
self.play(ShowCreation(cycloid))
ref_mob = self.snells_law_at_every_point(cycloid, chopped_cycloid)
self.show_equation(chopped_cycloid, ref_mob)
def snells_law_at_every_point(self, cycloid, chopped_cycloid):
square = Square(side_length = 0.2, color = WHITE)
words = OldTexText(["Snell's law ", "everywhere"])
snells, rest = words.split()
colon = OldTexText(":")
words.next_to(square)
words.shift(0.3*UP)
combo = Mobject(square, words)
combo.get_center = lambda : square.get_center()
new_snells = snells.copy().center().to_edge(UP, buff = 1.5)
colon.next_to(new_snells)
colon.shift(0.05*DOWN)
self.play(MoveAlongPath(
combo, cycloid,
run_time = 5
))
self.play(MoveAlongPath(
combo, chopped_cycloid,
run_time = 4
))
dot = Dot(combo.get_center())
self.play(Transform(square, dot))
self.play(
Transform(snells, new_snells),
Transform(rest, colon)
)
self.wait()
return colon
def get_marks(self, point1, point2):
vert_line = Line(2*DOWN, 2*UP)
tangent_line = vert_line.copy()
theta = OldTex("\\theta")
theta.scale(0.5)
angle = angle_of_vector(point1 - point2)
tangent_line.rotate(
angle - tangent_line.get_angle()
)
angle_from_vert = angle - np.pi/2
for mob in vert_line, tangent_line:
mob.shift(point1 - mob.get_center())
arc = Arc(angle_from_vert, start_angle = np.pi/2)
arc.scale(self.arc_radius)
arc.shift(point1)
vect_angle = angle_from_vert/2 + np.pi/2
vect = rotate_vector(RIGHT, vect_angle)
theta.center()
theta.shift(point1)
theta.shift(1.5*self.arc_radius*vect)
return arc, theta, vert_line, tangent_line
def show_equation(self, chopped_cycloid, ref_mob):
point2, point1 = chopped_cycloid.get_points()[-2:]
arc, theta, vert_line, tangent_line = self.get_marks(
point1, point2
)
equation = OldTex([
"\\sin(\\theta)",
"\\over \\sqrt{y}",
])
sin, sqrt_y = equation.split()
equation.next_to(ref_mob)
const = OldTex(" = \\text{constant}")
const.next_to(equation)
ceil_point = np.array(point1)
ceil_point[1] = self.top[1]
brace = Brace(
Mobject(Point(point1), Point(ceil_point)),
RIGHT
)
y_mob = OldTex("y").next_to(brace)
self.play(
GrowFromCenter(sin),
ShowCreation(arc),
GrowFromCenter(theta)
)
self.play(ShowCreation(vert_line))
self.play(ShowCreation(tangent_line))
self.wait()
self.play(
GrowFromCenter(sqrt_y),
GrowFromCenter(brace),
GrowFromCenter(y_mob)
)
self.wait()
self.play(Transform(
Point(const.get_left()), const
))
self.wait()
|
|
from manim_imports_ext import *
from _2016.triangle_of_power.triangle import TOP, OPERATION_COLORS
class DontLearnFromSymbols(Scene):
def construct(self):
randy = Randolph().to_corner()
bubble = randy.get_bubble()
bubble.content_scale_factor = 0.6
bubble.add_content(TOP(2, 3, 8).scale(0.7))
equation = VMobject(
TOP(2, "x"),
OldTex("\\times"),
TOP(2, "y"),
OldTex("="),
TOP(2, "x+y")
)
equation.arrange()
q_marks = OldTexText("???")
q_marks.set_color(YELLOW)
q_marks.next_to(randy, UP)
self.add(randy)
self.play(FadeIn(bubble))
self.wait()
top = bubble.content
bubble.add_content(equation)
self.play(
FadeOut(top),
ApplyMethod(randy.change_mode, "sassy"),
Write(bubble.content),
Write(q_marks),
run_time = 1
)
self.wait(3)
class NotationReflectsMath(Scene):
def construct(self):
top_expr = OldTexText("Notation $\\Leftrightarrow$ Math")
top_expr.shift(2*UP)
better_questions = OldTexText("Better questions")
arrow = Arrow(top_expr, better_questions)
self.play(Write(top_expr))
self.play(
ShowCreationPerSubmobject(
arrow,
rate_func = lambda t : min(smooth(3*t), 1)
),
Write(better_questions),
run_time = 3
)
self.wait(2)
class AsymmetriesInTheMath(Scene):
def construct(self):
assyms_of_top = VMobject(
OldTexText("Asymmetries of "),
TOP("a", "b", "c", radius = 0.75).set_color(BLUE)
).arrange()
assyms_of_top.to_edge(UP)
assyms_of_math = OldTexText("""
Asymmetries of
$\\underbrace{a \\cdot a \\cdots a}_{\\text{$b$ times}} = c$
""")
VMobject(*assyms_of_math.split()[13:]).set_color(YELLOW)
assyms_of_math.next_to(assyms_of_top, DOWN, buff = 2)
rad = OldTex("\\sqrt{\\quad}").to_edge(LEFT).shift(UP)
rad.set_color(RED)
log = OldTex("\\log").next_to(rad, DOWN)
log.set_color(RED)
self.play(FadeIn(assyms_of_top))
self.wait()
self.play(FadeIn(assyms_of_math))
self.wait()
self.play(Write(VMobject(rad, log)))
self.wait()
class AddedVsOplussed(Scene):
def construct(self):
top = TOP()
left_times = top.put_in_vertex(0, OldTex("\\times"))
left_dot = top.put_in_vertex(0, Dot())
right_times = top.put_in_vertex(2, OldTex("\\times"))
right_dot = top.put_in_vertex(2, Dot())
plus = top.put_in_vertex(1, OldTex("+"))
oplus = top.put_in_vertex(1, OldTex("\\oplus"))
left_times.set_color(YELLOW)
right_times.set_color(YELLOW)
plus.set_color(GREEN)
oplus.set_color(BLUE)
self.add(top, left_dot, plus, right_times)
self.wait()
self.play(
Transform(
VMobject(left_dot, plus, right_times),
VMobject(right_dot, oplus, left_times),
path_arc = np.pi/2
)
)
self.wait()
class ReciprocalTop(Scene):
def construct(self):
top = TOP()
start_two = top.put_on_vertex(2, 2)
end_two = top.put_on_vertex(0, 2)
x = top.put_on_vertex(1, "x")
one_over_x = top.put_on_vertex(1, "\\dfrac{1}{x}")
x.set_color(GREEN)
one_over_x.set_color(BLUE)
start_two.set_color(YELLOW)
end_two.set_color(YELLOW)
self.add(top, start_two, x)
self.wait()
self.play(
Transform(
VMobject(start_two, x),
VMobject(end_two, one_over_x)
),
ApplyMethod(top.rotate, np.pi, UP, path_arc = np.pi/7)
)
self.wait()
class NotSymbolicPatterns(Scene):
def construct(self):
randy = Randolph()
symbolic_patterns = OldTexText("Symbolic patterns")
symbolic_patterns.to_edge(RIGHT).shift(UP)
line = Line(LEFT, RIGHT, color = RED, stroke_width = 7)
line.replace(symbolic_patterns)
substantive_reasoning = OldTexText("Substantive reasoning")
substantive_reasoning.to_edge(RIGHT).shift(DOWN)
self.add(randy, symbolic_patterns)
self.wait()
self.play(ShowCreation(line))
self.play(
Write(substantive_reasoning),
ApplyMethod(randy.change_mode, "pondering_looking_left"),
run_time = 1
)
self.wait(2)
self.play(
ApplyMethod(line.shift, 10*DOWN),
ApplyMethod(substantive_reasoning.shift, 10*DOWN),
ApplyMethod(randy.change_mode, "sad"),
run_time = 1
)
self.wait(2)
class ChangeWeCanBelieveIn(Scene):
def construct(self):
words = OldTexText("Change we can believe in")
change = VMobject(*words.split()[:6])
top = TOP(radius = 0.75)
top.shift(change.get_right()-top.get_right())
self.play(Write(words))
self.play(
FadeOut(change),
GrowFromCenter(top)
)
self.wait(3)
class TriangleOfPowerIsBetter(Scene):
def construct(self):
top = TOP("x", "y", "z", radius = 0.75)
top.set_color(BLUE)
alts = VMobject(*list(map(Tex, [
"x^y", "\\log_x(z)", "\\sqrt[y]{z}"
])))
for mob, color in zip(alts.split(), OPERATION_COLORS):
mob.set_color(color)
alts.arrange(DOWN)
greater_than = OldTex(">")
top.next_to(greater_than, LEFT)
alts.next_to(greater_than, RIGHT)
self.play(Write(VMobject(top, greater_than, alts)))
self.wait()
class InYourOwnNotes(Scene):
def construct(self):
anims = [
self.get_log_anim(3*LEFT),
self.get_exp_anim(3*RIGHT),
]
for anim in anims:
self.add(anim.mobject)
self.wait(2)
self.play(*anims)
self.wait(2)
def get_log_anim(self, center):
O_log_n = OldTex(["O(", "\\log(n)", ")"])
O_log_n.shift(center)
log_n = O_log_n.split()[1]
#super hacky
g = log_n.split()[2]
for mob in g.submobjects:
mob.is_subpath = False
mob.set_fill(BLACK, 1.0)
log_n.add(mob)
g.submobjects = []
#end hack
top = TOP(2, None, "n", radius = 0.75)
top.set_width(log_n.get_width())
top.shift(log_n.get_center())
new_O_log_n = O_log_n.copy()
new_O_log_n.submobjects[1] = top
return Transform(O_log_n, new_O_log_n)
def get_exp_anim(self, center):
epii = OldTex("e^{\\pi i} = -1")
epii.shift(center)
top = TOP("e", "\\pi i", "-1", radius = 0.75)
top.shift(center)
e, pi, i, equals, minus, one = epii.split()
##hacky
loop = e.submobjects[0]
loop.is_subpath = False
loop.set_fill(BLACK, 1.0)
e.submobjects = []
##
start = VMobject(
equals,
VMobject(e, loop),
VMobject(pi, i),
VMobject(minus, one)
)
return Transform(start, top)
class Qwerty(Scene):
def construct(self):
qwerty = VMobject(
OldTexText(list("QWERTYUIOP")),
OldTexText(list("ASDFGHJKL")),
OldTexText(list("ZXCVBNM")),
)
qwerty.arrange(DOWN)
dvorak = VMobject(
OldTexText(list("PYFGCRL")),
OldTexText(list("AOEUIDHTNS")),
OldTexText(list("QJKXBMWVZ")),
)
dvorak.arrange(DOWN)
d1, d2, d3 = dvorak.split()
d1.shift(0.9*RIGHT)
d3.shift(0.95*RIGHT)
self.add(qwerty)
self.wait(2)
self.play(Transform(qwerty, dvorak))
self.wait(2)
class ShowLog(Scene):
def construct(self):
equation = VMobject(*[
TOP(2, None, "x"),
OldTex("+"),
TOP(2, None, "y"),
OldTex("="),
TOP(2, None, "xy")
]).arrange()
old_eq = OldTex("\\log_2(x) + \\log_2(y) = \\log_2(xy)")
old_eq.to_edge(UP)
self.play(FadeIn(equation))
self.wait(3)
self.play(FadeIn(old_eq))
self.wait(2)
class NoOneWillActuallyDoThis(Scene):
def construct(self):
randy = Randolph().to_corner()
bubble = SpeechBubble().pin_to(randy)
words = OldTexText("No one will actually do this...")
tau_v_pi = OldTex("\\tau > \\pi").scale(2)
morty = Mortimer("speaking").to_corner(DOWN+RIGHT)
morty_bubble = SpeechBubble(
direction = RIGHT,
height = 4
)
morty_bubble.pin_to(morty)
final_words = OldTexText("If this war is won, it will \\\\ not be won with that attitude")
lil_thought_bubble = ThoughtBubble(height = 3, width = 5)
lil_thought_bubble.set_fill(BLACK, 1.0)
lil_thought_bubble.pin_to(randy)
lil_thought_bubble.write("Okay buddy, calm down, it's notation \\\\ we're talking about not war.")
lil_thought_bubble.show()
self.add(randy)
self.play(
ApplyMethod(randy.change_mode, "sassy"),
ShowCreation(bubble)
)
bubble.add_content(words)
self.play(Write(words), run_time = 2)
self.play(Blink(randy))
bubble.add_content(tau_v_pi)
self.play(
FadeOut(words),
GrowFromCenter(tau_v_pi),
ApplyMethod(randy.change_mode, "speaking")
)
self.remove(words)
self.play(Blink(randy))
self.wait(2)
self.play(
FadeOut(bubble),
FadeIn(morty),
ShowCreation(morty_bubble),
ApplyMethod(randy.change_mode, "plain")
)
morty_bubble.add_content(final_words)
self.play(Write(final_words))
self.wait()
self.play(Blink(morty))
self.wait(2)
self.play(ShowCreation(lil_thought_bubble))
|
|
from manim_imports_ext import *
class TrigAnimation(Animation):
CONFIG = {
"rate_func" : None,
"run_time" : 5,
"sin_color" : BLUE,
"cos_color" : RED,
"tan_color" : GREEN
}
def __init__(self, **kwargs):
digest_config(self, kwargs)
x_axis = NumberLine(
x_min = -3,
x_max = 3,
color = BLUE_E
)
y_axis = x_axis.copy().rotate(np.pi/2)
circle = Circle(color = WHITE)
self.trig_lines = [
Line(ORIGIN, RIGHT, color = color)
for color in (self.sin_color, self.cos_color, self.tan_color)
]
mobject = VMobject(
x_axis, y_axis, circle,
*self.trig_lines
)
mobject.to_edge(RIGHT)
self.center = mobject.get_center()
Animation.__init__(self, mobject, **kwargs)
def interpolate_mobject(self, alpha):
theta = 2*np.pi*alpha
circle_point = np.cos(theta)*RIGHT+np.sin(theta)*UP+self.center
points = [
circle_point[0]*RIGHT,
circle_point[1]*UP+self.center,
(
np.sign(np.cos(theta))*np.sqrt(
np.tan(theta)**2 - np.sin(theta)**2
) + np.cos(theta)
)*RIGHT + self.center,
]
for line, point in zip(self.trig_lines, points):
line.set_points_as_corners([circle_point, point])
class Notation(Scene):
def construct(self):
self.introduce_notation()
self.shift_to_good_and_back()
self.shift_to_visuals()
self.swipe_left()
def introduce_notation(self):
notation = OldTexText("Notation")
notation.to_edge(UP)
self.sum1 = OldTex("\\sum_{n=1}^\\infty \\dfrac{1}{n}")
self.prod1 = OldTex("\\prod_{p\\text{ prime}}\\left(1-p^{-s}\\right)")
self.trigs1 = OldTex([
["\\sin", "(x)"],
["\\cos", "(x)"],
["\\tan", "(x)"],
], next_to_direction = DOWN)
self.func1 = OldTex("f(x) = y")
symbols = [self.sum1, self.prod1, self.trigs1, self.func1]
for sym, vect in zip(symbols, compass_directions(4, UP+LEFT)):
sym.scale(0.5)
vect[0] *= 2
sym.shift(vect)
self.symbols = VMobject(*symbols)
self.play(Write(notation))
self.play(Write(self.symbols))
self.wait()
self.add(notation, self.symbols)
def shift_to_good_and_back(self):
sum2 = self.sum1.copy()
sigma = sum2.submobjects[1]
plus = OldTex("+").replace(sigma)
sum2.submobjects[1] = plus
prod2 = self.prod1.copy()
pi = prod2.submobjects[0]
times = OldTex("\\times").replace(pi)
prod2.submobjects[0] = times
new_sin, new_cos, new_tan = [
VMobject().set_points_as_corners(
corners
).replace(trig_part.split()[0])
for corners, trig_part in zip(
[
[RIGHT, RIGHT+UP, LEFT],
[RIGHT+UP, LEFT, RIGHT],
[RIGHT+UP, RIGHT, LEFT],
],
self.trigs1.split()
)
]
x1, x2, x3 = [
trig_part.split()[1]
for trig_part in self.trigs1.split()
]
trigs2 = VMobject(
VMobject(new_sin, x1),
VMobject(new_cos, x2),
VMobject(new_tan, x3),
)
x, arrow, y = OldTex("x \\rightarrow y").split()
f = OldTex("f")
f.next_to(arrow, UP)
func2 = VMobject(f, VMobject(), x, VMobject(), arrow, y)
func2.scale(0.5)
func2.shift(self.func1.get_center())
good_symbols = VMobject(sum2, prod2, trigs2, func2)
bad_symbols = self.symbols.copy()
self.play(Transform(
self.symbols, good_symbols,
path_arc = np.pi
))
self.wait(3)
self.play(Transform(
self.symbols, bad_symbols,
path_arc = np.pi
))
self.wait()
def shift_to_visuals(self):
sigma, prod, trig, func = self.symbols.split()
new_trig = trig.copy()
sin, cos, tan = [
trig_part.split()[0]
for trig_part in new_trig.split()
]
trig_anim = TrigAnimation()
sin.set_color(trig_anim.sin_color)
cos.set_color(trig_anim.cos_color)
tan.set_color(trig_anim.tan_color)
new_trig.to_corner(UP+RIGHT)
sum_lines = self.get_harmonic_sum_lines()
self.play(
Transform(trig, new_trig),
*it.starmap(ApplyMethod, [
(sigma.to_corner, UP+LEFT),
(prod.shift, 15*LEFT),
(func.shift, 5*UP),
])
)
sum_lines.next_to(sigma, DOWN)
self.remove(prod, func)
self.play(
trig_anim,
Write(sum_lines)
)
self.play(trig_anim)
self.wait()
def get_harmonic_sum_lines(self):
result = VMobject()
for n in range(1, 8):
big_line = NumberLine(
x_min = 0,
x_max = 1.01,
tick_frequency = 1./n,
numbers_with_elongated_ticks = [],
color = WHITE
)
little_line = Line(
big_line.number_to_point(0),
big_line.number_to_point(1./n),
color = RED
)
big_line.add(little_line)
big_line.shift(0.5*n*DOWN)
result.add(big_line)
return result
def swipe_left(self):
everyone = VMobject(*self.mobjects)
self.play(ApplyMethod(everyone.shift, 20*LEFT))
class ButDots(Scene):
def construct(self):
but = OldTexText("but")
dots = OldTex("\\dots")
dots.next_to(but, aligned_edge = DOWN)
but.shift(20*RIGHT)
self.play(ApplyMethod(but.shift, 20*LEFT))
self.play(Write(dots, run_time = 5))
self.wait()
class ThreesomeOfNotation(Scene):
def construct(self):
exp = OldTex("x^y = z")
log = OldTex("\\log_x(z) = y")
rad = OldTex("\\sqrt[y]{z} = x")
exp.to_edge(LEFT).shift(2*UP)
rad.to_edge(RIGHT).shift(2*DOWN)
x1, y1, eq, z1 = exp.split()
l, o, g, x2, p, z2, p, eq, y2 = log.split()
y3, r, r, z3, eq, x3 = rad.split()
vars1 = VMobject(x1, y1, z1).copy()
vars2 = VMobject(x2, y2, z2)
vars3 = VMobject(x3, y3, z3)
self.play(Write(exp))
self.play(Transform(vars1, vars2, path_arc = -np.pi))
self.play(Write(log))
self.play(Transform(vars1, vars3, path_arc = -np.pi))
self.play(Write(rad))
self.wait()
words = OldTexText("Artificially unrelated")
words.to_corner(UP+RIGHT)
words.set_color(YELLOW)
self.play(Write(words))
self.wait()
class TwoThreeEightExample(Scene):
def construct(self):
start = OldTex("2 \\cdot 2 \\cdot 2 = 8")
two1, dot1, two2, dot2, two3, eq, eight = start.split()
brace = Brace(VMobject(two1, two3), DOWN)
three = OldTex("3").next_to(brace, DOWN, buff = 0.2)
rogue_two = two1.copy()
self.add(two1)
self.play(
Transform(rogue_two, two2),
Write(dot1),
run_time = 0.5
)
self.add(two2)
self.play(
Transform(rogue_two, two3),
Write(dot2),
run_time = 0.5
)
self.add(two3)
self.remove(rogue_two)
self.play(
Write(eq), Write(eight),
GrowFromCenter(brace),
Write(three),
run_time = 1
)
self.wait()
exp = OldTex("2^3")
exp.next_to(eq, LEFT)
exp.shift(0.2*UP)
base_two, exp_three = exp.split()
self.play(
Transform(
VMobject(two1, dot1, two2, dot2, brace, three),
exp_three,
path_arc = -np.pi/2
),
Transform(two3, base_two)
)
self.clear()
self.add(base_two, exp_three, eq, eight)
self.wait(3)
rad_three, rad1, rad2, rad_eight, rad_eq, rad_two = \
OldTex("\\sqrt[3]{8} = 2").split()
self.play(*[
Transform(*pair, path_arc = np.pi/2)
for pair in [
(exp_three, rad_three),
(VMobject(), rad1),
(VMobject(), rad2),
(eight, rad_eight),
(eq, rad_eq),
(base_two, rad_two)
]
])
self.wait()
self.play(ApplyMethod(
VMobject(rad1, rad2).set_color, RED,
rate_func = there_and_back,
run_time = 2
))
self.remove(rad1, rad2)
self.wait()
l, o, g, log_two, p1, log_eight, p2, log_eq, log_three = \
OldTex("\\log_2(8) = 3").split()
self.clear()
self.play(*[
Transform(*pair, path_arc = np.pi/2)
for pair in [
(rad1, l),
(rad2, o),
(rad2.copy(), g),
(rad_two, log_two),
(VMobject(), p1),
(rad_eight, log_eight),
(VMobject(), p2),
(rad_eq, log_eq),
(rad_three, log_three)
]
])
self.wait()
self.play(ApplyMethod(
VMobject(l, o, g).set_color, RED,
rate_func = there_and_back,
run_time = 2
))
self.wait()
class WhatTheHell(Scene):
def construct(self):
randy = Randolph()
randy.to_corner(DOWN+LEFT)
exp, rad, log = list(map(Tex,[
"2^3 = 8",
"\\sqrt[3]{8} = 2",
"\\log_2(8) = 3",
]))
# exp.set_color(BLUE_D)
# rad.set_color(RED_D)
# log.set_color(GREEN_D)
arrow1 = DoubleArrow(DOWN, UP)
arrow2 = arrow1.copy()
last = exp
for mob in arrow1, rad, arrow2, log:
mob.next_to(last, DOWN)
last = mob
q_marks = VMobject(*[
OldTex("?!").next_to(arrow, RIGHT)
for arrow in (arrow1, arrow2)
])
q_marks.set_color(RED_D)
everyone = VMobject(exp, rad, log, arrow1, arrow2, q_marks)
everyone.scale(0.7)
everyone.to_corner(UP+RIGHT)
phrases = [
OldTexText(
["Communicate with", words]
).next_to(mob, LEFT, buff = 1)
for words, mob in [
("position", exp),
("a new symbol", rad),
("a word", log)
]
]
for phrase, color in zip(phrases, [BLUE, RED, GREEN]):
phrase.split()[1].set_color(color)
self.play(ApplyMethod(randy.change_mode, "angry"))
self.play(FadeIn(VMobject(exp, rad, log)))
self.play(
ShowCreationPerSubmobject(arrow1),
ShowCreationPerSubmobject(arrow2)
)
self.play(Write(q_marks))
self.wait()
self.remove(randy)
self.play(Write(VMobject(*phrases)))
self.wait()
class Countermathematical(Scene):
def construct(self):
counterintuitive = OldTexText("Counterintuitive")
mathematical = OldTexText("mathematical")
intuitive = VMobject(*counterintuitive.split()[7:])
mathematical.shift(intuitive.get_left()-mathematical.get_left())
self.add(counterintuitive)
self.wait()
self.play(Transform(intuitive, mathematical))
self.wait()
class PascalsCollision(Scene):
def construct(self):
pascals_triangle = PascalsTriangle()
pascals_triangle.scale(0.5)
final_triangle = PascalsTriangle()
final_triangle.fill_with_n_choose_k()
pascals_triangle.to_corner(UP+LEFT)
final_triangle.scale(0.7)
final_triangle.to_edge(UP)
equation = OldTex([
"{n \\choose k}",
" = \\dfrac{n!}{(n-k)!k!}"
])
equation.scale(0.5)
equation.to_corner(UP+RIGHT)
n_choose_k, formula = equation.split()
words = OldTexText("Seemingly unrelated")
words.shift(2*DOWN)
to_remove = VMobject(*words.split()[:-7])
self.add(pascals_triangle, n_choose_k, formula)
self.play(Write(words))
self.wait()
self.play(
Transform(pascals_triangle, final_triangle),
Transform(n_choose_k, final_triangle),
FadeOut(formula),
ApplyMethod(to_remove.shift, 5*DOWN)
)
self.wait()
class LogarithmProperties(Scene):
def construct(self):
randy = Randolph()
randy.to_corner()
bubble = ThoughtBubble().pin_to(randy)
props = [
OldTex("\\log_a(x) = \\dfrac{\\log_b(a)}{\\log_b(x)}"),
OldTex("\\log_a(x) = \\dfrac{\\log_b(x)}{\\log_b(a)}"),
OldTex("\\log_a(x) = \\log_b(x) - \\log_b(a)"),
OldTex("\\log_a(x) = \\log_b(x) + \\log_b(a)"),
OldTex("\\log_a(x) = \\dfrac{\\log_b(x)}{\\log_b(a)}"),
]
bubble.add_content(props[0])
words = OldTexText("What was it again?")
words.set_color(YELLOW)
words.scale(0.5)
words.next_to(props[0], UP)
self.play(
ApplyMethod(randy.change_mode, "confused"),
ShowCreation(bubble),
Write(words)
)
self.show_frame()
for i, prop in enumerate(props[1:]):
self.play(ApplyMethod(bubble.add_content, prop))
if i%2 == 0:
self.play(Blink(randy))
else:
self.wait()
class HaveToShare(Scene):
def construct(self):
words = list(map(TexText, [
"Lovely", "Symmetrical", "Utterly Reasonable"
]))
for w1, w2 in zip(words, words[1:]):
w2.next_to(w1, DOWN)
VMobject(*words).center()
left_dot, top_dot, bottom_dot = [
Dot(point, radius = 0.1)
for point in (ORIGIN, RIGHT+0.5*UP, RIGHT+0.5*DOWN)
]
line1, line2 = [
Line(left_dot.get_center(), dot.get_center(), buff = 0)
for dot in (top_dot, bottom_dot)
]
share = VMobject(left_dot, top_dot, bottom_dot, line1, line2)
share.next_to(words[1], RIGHT, buff = 1)
share.set_color(RED)
for word in words:
self.play(FadeIn(word))
self.wait()
self.play(Write(share, run_time = 1))
self.wait()
|
|
import numbers
from manim_imports_ext import *
from functools import reduce
OPERATION_COLORS = [YELLOW, GREEN, BLUE_B]
def get_equation(index, x = 2, y = 3, z = 8, expression_only = False):
assert(index in [0, 1, 2])
if index == 0:
tex1 = "\\sqrt[%d]{%d}"%(y, z),
tex2 = " = %d"%x
elif index == 1:
tex1 = "\\log_%d(%d)"%(x, z),
tex2 = " = %d"%y
elif index == 2:
tex1 = "%d^%d"%(x, y),
tex2 = " = %d"%z
if expression_only:
tex = tex1
else:
tex = tex1+tex2
return OldTex(tex).set_color(OPERATION_COLORS[index])
def get_inverse_rules():
return list(map(Tex, [
"x^{\\log_x(z)} = z",
"\\log_x\\left(x^y \\right) = y",
"\\sqrt[y]{x^y} = x",
"\\left(\\sqrt[y]{z}\\right)^y = z",
"\\sqrt[\\log_x(z)]{z} = x",
"\\log_{\\sqrt[y]{z}}(z) = y",
]))
def get_top_inverse_rules():
result = []
pairs = [#Careful of order here!
(0, 2),
(0, 1),
(1, 0),
(1, 2),
(2, 0),
(2, 1),
]
for i, j in pairs:
top = get_top_inverse(i, j)
char = ["x", "y", "z"][j]
eq = OldTex("= %s"%char)
eq.scale(2)
eq.next_to(top, RIGHT)
diff = eq.get_center() - top.triangle.get_center()
eq.shift(diff[1]*UP)
result.append(VMobject(top, eq))
return result
def get_top_inverse(i, j):
args = [None]*3
k = set([0, 1, 2]).difference([i, j]).pop()
args[i] = ["x", "y", "z"][i]
big_top = TOP(*args)
args[j] = ["x", "y", "z"][j]
lil_top = TOP(*args, triangle_height_to_number_height = 1.5)
big_top.set_value(k, lil_top)
return big_top
class TOP(VMobject):
CONFIG = {
"triangle_height_to_number_height" : 3,
"offset_multiple" : 1.5,
"radius" : 1.5,
}
def __init__(self, x = None, y = None, z = None, **kwargs):
digest_config(self, kwargs, locals())
VMobject.__init__(self, **kwargs)
def init_points(self):
vertices = [
self.radius*rotate_vector(RIGHT, 7*np.pi/6 - i*2*np.pi/3)
for i in range(3)
]
self.triangle = Polygon(
*vertices,
color = WHITE,
stroke_width = 5
)
self.values = [VMobject()]*3
self.set_values(self.x, self.y, self.z)
def set_values(self, x, y, z):
for i, mob in enumerate([x, y, z]):
self.set_value(i, mob)
def set_value(self, index, value):
self.values[index] = self.put_on_vertex(index, value)
self.reset_submobjects()
def put_on_vertex(self, index, value):
assert(index in [0, 1, 2])
if value is None:
value = VectorizedPoint()
if isinstance(value, numbers.Number):
value = str(value)
if isinstance(value, str):
value = OldTex(value)
if isinstance(value, TOP):
return self.put_top_on_vertix(index, value)
self.rescale_corner_mobject(value)
value.center()
if index == 0:
offset = -value.get_corner(UP+RIGHT)
elif index == 1:
offset = -value.get_bottom()
elif index == 2:
offset = -value.get_corner(UP+LEFT)
value.shift(self.offset_multiple*offset)
anchors = self.triangle.get_anchors_and_handles()[0]
value.shift(anchors[index])
return value
def put_top_on_vertix(self, index, top):
top.set_height(2*self.get_value_height())
vertices = np.array(top.get_vertices())
vertices[index] = 0
start = reduce(op.add, vertices)/2
end = self.triangle.get_anchors_and_handles()[0][index]
top.shift(end-start)
return top
def put_in_vertex(self, index, mobject):
self.rescale_corner_mobject(mobject)
mobject.center()
mobject.shift(interpolate(
self.get_center(),
self.get_vertices()[index],
0.7
))
return mobject
def get_surrounding_circle(self, color = YELLOW):
return Circle(
radius = 1.7*self.radius,
color = color
).shift(
self.triangle.get_center(),
(self.triangle.get_height()/6)*DOWN
)
def rescale_corner_mobject(self, mobject):
mobject.set_height(self.get_value_height())
return self
def get_value_height(self):
return self.triangle.get_height()/self.triangle_height_to_number_height
def get_center(self):
return center_of_mass(self.get_vertices())
def get_vertices(self):
return self.triangle.get_anchors_and_handles()[0][:3]
def reset_submobjects(self):
self.submobjects = [self.triangle] + self.values
return self
class IntroduceNotation(Scene):
def construct(self):
top = TOP()
equation = OldTex("2^3 = 8")
equation.to_corner(UP+LEFT)
two, three, eight = [
top.put_on_vertex(i, num)
for i, num in enumerate([2, 3, 8])
]
self.play(FadeIn(equation))
self.wait()
self.play(ShowCreation(top))
for num in two, three, eight:
self.play(ShowCreation(num), run_time=2)
self.wait()
class ShowRule(Scene):
args_list = [(0,), (1,), (2,)]
@staticmethod
def args_to_string(index):
return str(index)
@staticmethod
def string_to_args(index_string):
result = int(index_string)
assert(result in [0, 1, 2])
return result
def construct(self, index):
equation = get_equation(index)
equation.to_corner(UP+LEFT)
top = TOP(2, 3, 8)
new_top = top.copy()
equals = OldTex("=").scale(1.5)
new_top.next_to(equals, LEFT, buff = 1)
new_top.values[index].next_to(equals, RIGHT, buff = 1)
circle = Circle(
radius = 1.7*top.radius,
color = OPERATION_COLORS[index]
)
self.add(equation, top)
self.wait()
self.play(
Transform(top, new_top),
ShowCreation(equals)
)
circle.shift(new_top.triangle.get_center_of_mass())
new_circle = circle.copy()
new_top.put_on_vertex(index, new_circle)
self.wait()
self.play(ShowCreation(circle))
self.wait()
self.play(
Transform(circle, new_circle),
ApplyMethod(new_top.values[index].set_color, circle.color)
)
self.wait()
class AllThree(Scene):
def construct(self):
tops = []
equations = []
args = (2, 3, 8)
for i in 2, 1, 0:
new_args = list(args)
new_args[i] = None
top = TOP(*new_args, triangle_height_to_number_height = 2)
# top.set_color(OPERATION_COLORS[i])
top.shift(i*4.5*LEFT)
equation = get_equation(i, expression_only = True)
equation.scale(3)
equation.next_to(top, DOWN, buff = 0.7)
tops.append(top)
equations.append(equation)
VMobject(*tops+equations).center()
# name = OldTexText("Triangle of Power")
# name.to_edge(UP)
for top, eq in zip(tops, equations):
self.play(FadeIn(top), FadeIn(eq))
self.wait(3)
# self.play(Write(name))
self.wait()
class SixDifferentInverses(Scene):
def construct(self):
rules = get_inverse_rules()
vects = it.starmap(op.add, it.product(
[3*UP, 0.5*UP, 2*DOWN], [2*LEFT, 2*RIGHT]
))
for rule, vect in zip(rules, vects):
rule.shift(vect)
general_idea = OldTex("f(f^{-1}(a)) = a")
self.play(Write(VMobject(*rules)))
self.wait()
for s, color in (rules[:4], GREEN), (rules[4:], RED):
mob = VMobject(*s)
self.play(ApplyMethod(mob.set_color, color))
self.wait()
self.play(ApplyMethod(mob.set_color, WHITE))
self.play(
ApplyMethod(VMobject(*rules[::2]).to_edge, LEFT),
ApplyMethod(VMobject(*rules[1::2]).to_edge, RIGHT),
GrowFromCenter(general_idea)
)
self.wait()
top_rules = get_top_inverse_rules()
for rule, top_rule in zip(rules, top_rules):
top_rule.set_height(1.5)
top_rule.center()
top_rule.shift(rule.get_center())
self.play(*list(map(FadeOut, rules)))
self.remove(*rules)
self.play(*list(map(GrowFromCenter, top_rules)))
self.wait()
self.remove(general_idea)
rules = get_inverse_rules()
original = None
for i, (top_rule, rule) in enumerate(zip(top_rules, rules)):
rule.center().to_edge(UP)
rule.set_color(GREEN if i < 4 else RED)
self.add(rule)
new_top_rule = top_rule.copy().center().scale(1.5)
anims = [Transform(top_rule, new_top_rule)]
if original is not None:
anims.append(FadeIn(original))
original = top_rule.copy()
self.play(*anims)
self.wait()
self.animate_top_rule(top_rule)
self.remove(rule)
def animate_top_rule(self, top_rule):
lil_top, lil_symbol, symbol_index = None, None, None
big_top = top_rule.submobjects[0]
equals, right_symbol = top_rule.submobjects[1].split()
for i, value in enumerate(big_top.values):
if isinstance(value, TOP):
lil_top = value
elif isinstance(value, Tex):
symbol_index = i
else:
lil_symbol_index = i
lil_symbol = lil_top.values[lil_symbol_index]
assert(lil_top is not None and lil_symbol is not None)
cancel_parts = [
VMobject(top.triangle, top.values[symbol_index])
for top in (lil_top, big_top)
]
new_symbol = lil_symbol.copy()
new_symbol.replace(right_symbol)
vect = equals.get_center() - right_symbol.get_center()
new_symbol.shift(2*vect[0]*RIGHT)
self.play(
Transform(*cancel_parts, rate_func = rush_into)
)
self.play(
FadeOut(VMobject(*cancel_parts)),
Transform(lil_symbol, new_symbol, rate_func = rush_from)
)
self.wait()
self.remove(lil_symbol, top_rule, VMobject(*cancel_parts))
class SixSixSix(Scene):
def construct(self):
randy = Randolph(mode = "pondering").to_corner()
bubble = ThoughtBubble().pin_to(randy)
rules = get_inverse_rules()
sixes = OldTex(["6", "6", "6"], next_to_buff = 1)
sixes.to_corner(UP+RIGHT)
sixes = sixes.split()
speech_bubble = SpeechBubble()
speech_bubble.pin_to(randy)
speech_bubble.write("I'll just study art!")
self.add(randy)
self.play(ShowCreation(bubble))
bubble.add_content(VectorizedPoint())
for i, rule in enumerate(rules):
if i%2 == 0:
anim = ShowCreation(sixes[i/2])
else:
anim = Blink(randy)
self.play(
ApplyMethod(bubble.add_content, rule),
anim
)
self.wait()
self.wait()
words = speech_bubble.content
equation = bubble.content
speech_bubble.clear()
bubble.clear()
self.play(
ApplyMethod(randy.change_mode, "angry"),
Transform(bubble, speech_bubble),
Transform(equation, words),
FadeOut(VMobject(*sixes))
)
self.wait()
class AdditiveProperty(Scene):
def construct(self):
exp_rule, log_rule = self.write_old_style_rules()
t_exp_rule, t_log_rule = self.get_new_style_rules()
self.play(
ApplyMethod(exp_rule.to_edge, UP),
ApplyMethod(log_rule.to_edge, DOWN, 1.5)
)
t_exp_rule.next_to(exp_rule, DOWN)
t_exp_rule.set_color(GREEN)
t_log_rule.next_to(log_rule, UP)
t_log_rule.set_color(RED)
self.play(
FadeIn(t_exp_rule),
FadeIn(t_log_rule),
ApplyMethod(exp_rule.set_color, GREEN),
ApplyMethod(log_rule.set_color, RED),
)
self.wait()
all_tops = [m for m in t_exp_rule.split()+t_log_rule.split() if isinstance(m, TOP)]
self.put_in_circles(all_tops)
self.set_color_appropriate_parts(t_exp_rule, t_log_rule)
def write_old_style_rules(self):
start = OldTex("a^x a^y = a^{x+y}")
end = OldTex("\\log_a(xy) = \\log_a(x) + \\log_a(y)")
start.shift(UP)
end.shift(DOWN)
a1, x1, a2, y1, eq1, a3, p1, x2, y2 = start.split()
a4, x3, y3, eq2, a5, x4, p2, a6, y4 = np.array(end.split())[
[3, 5, 6, 8, 12, 14, 16, 20, 22]
]
start_copy = start.copy()
self.play(Write(start_copy))
self.wait()
self.play(Transform(
VMobject(a1, x1, a2, y1, eq1, a3, p1, x2, a3.copy(), y2),
VMobject(a4, x3, a4.copy(), y3, eq2, a5, p2, x4, a6, y4)
))
self.play(Write(end))
self.clear()
self.add(start_copy, end)
self.wait()
return start_copy, end
def get_new_style_rules(self):
upper_mobs = [
TOP("a", "x", "R"), Dot(),
TOP("a", "y", "R"), OldTex("="),
TOP("a", "x+y")
]
lower_mobs = [
TOP("a", None, "xy"), OldTex("="),
TOP("a", None, "x"), OldTex("+"),
TOP("a", None, "y"),
]
for mob in upper_mobs + lower_mobs:
if isinstance(mob, TOP):
mob.scale(0.5)
for group in upper_mobs, lower_mobs:
for m1, m2 in zip(group, group[1:]):
m2.next_to(m1)
for top in upper_mobs[0], upper_mobs[2]:
top.set_value(2, None)
upper_mobs = VMobject(*upper_mobs).center().shift(2*UP)
lower_mobs = VMobject(*lower_mobs).center().shift(2*DOWN)
return upper_mobs, lower_mobs
def put_in_circles(self, tops):
anims = []
for top in tops:
for i, value in enumerate(top.values):
if isinstance(value, VectorizedPoint):
index = i
circle = top.put_on_vertex(index, Circle(color = WHITE))
anims.append(
Transform(top.copy().set_color(YELLOW), circle)
)
self.add(*[anim.mobject for anim in anims])
self.wait()
self.play(*anims)
self.wait()
def set_color_appropriate_parts(self, t_exp_rule, t_log_rule):
#Horribly hacky
circle1 = t_exp_rule.split()[0].put_on_vertex(
2, Circle()
)
top_dot = t_exp_rule.split()[1]
circle2 = t_exp_rule.split()[2].put_on_vertex(
2, Circle()
)
top_plus = t_exp_rule.split()[4].values[1]
bottom_times = t_log_rule.split()[0].values[2]
circle3 = t_log_rule.split()[2].put_on_vertex(
1, Circle()
)
bottom_plus = t_log_rule.split()[3]
circle4 = t_log_rule.split()[4].put_on_vertex(
1, Circle()
)
mob_lists = [
[circle1, top_dot, circle2],
[top_plus],
[bottom_times],
[circle3, bottom_plus, circle4]
]
for mobs in mob_lists:
copies = VMobject(*mobs).copy()
self.play(ApplyMethod(
copies.set_color, YELLOW,
run_time = 0.5
))
self.play(ApplyMethod(
copies.scale, 1.2,
rate_func = there_and_back
))
self.wait()
self.remove(copies)
class DrawInsideTriangle(Scene):
def construct(self):
top = TOP()
top.scale(2)
dot = top.put_in_vertex(0, Dot())
plus = top.put_in_vertex(1, OldTex("+"))
times = top.put_in_vertex(2, OldTex("\\times"))
plus.set_color(GREEN)
times.set_color(YELLOW)
self.add(top)
self.wait()
for mob in dot, plus, times:
self.play(Write(mob, run_time = 1))
self.wait()
class ConstantOnTop(Scene):
def construct(self):
top = TOP()
dot = top.put_in_vertex(1, Dot())
times1 = top.put_in_vertex(0, OldTex("\\times"))
times2 = top.put_in_vertex(2, OldTex("\\times"))
times1.set_color(YELLOW)
times2.set_color(YELLOW)
three = top.put_on_vertex(1, "3")
lower_left_x = top.put_on_vertex(0, "x")
lower_right_x = top.put_on_vertex(2, "x")
x_cubed = OldTex("x^3").to_edge(UP)
x_cubed.submobjects.reverse() #To align better
cube_root_x = OldTex("\\sqrt[3]{x}").to_edge(UP)
self.add(top)
self.play(ShowCreation(three))
self.play(
FadeIn(lower_left_x),
Write(x_cubed),
run_time = 1
)
self.wait()
self.play(*[
Transform(*pair, path_arc = np.pi)
for pair in [
(lower_left_x, lower_right_x),
(x_cubed, cube_root_x),
]
])
self.wait(2)
for mob in dot, times1, times2:
self.play(ShowCreation(mob))
self.wait()
def get_const_top_TOP(*args):
top = TOP(*args)
dot = top.put_in_vertex(1, Dot())
times1 = top.put_in_vertex(0, OldTex("\\times"))
times2 = top.put_in_vertex(2, OldTex("\\times"))
times1.set_color(YELLOW)
times2.set_color(YELLOW)
top.add(dot, times1, times2)
return top
class MultiplyWithConstantTop(Scene):
def construct(self):
top1 = get_const_top_TOP("x", "3")
top2 = get_const_top_TOP("y", "3")
top3 = get_const_top_TOP("xy", "3")
times = OldTex("\\times")
equals = OldTex("=")
top_exp_equation = VMobject(
top1, times, top2, equals, top3
)
top_exp_equation.arrange()
old_style_exp = OldTex("(x^3)(y^3) = (xy)^3")
old_style_exp.to_edge(UP)
old_style_exp.set_color(GREEN)
old_style_rad = OldTex("\\sqrt[3]{x} \\sqrt[3]{y} = \\sqrt[3]{xy}")
old_style_rad.to_edge(UP)
old_style_rad.set_color(RED)
self.add(top_exp_equation, old_style_exp)
self.wait(3)
old_tops = [top1, top2, top3]
new_tops = []
for top in old_tops:
new_top = top.copy()
new_top.put_on_vertex(2, new_top.values[0])
new_top.shift(0.5*LEFT)
new_tops.append(new_top)
self.play(
Transform(old_style_exp, old_style_rad),
Transform(
VMobject(*old_tops),
VMobject(*new_tops),
path_arc = np.pi/2
)
)
self.wait(3)
class RightStaysConstantQ(Scene):
def construct(self):
top1, top2, top3 = old_tops = [
TOP(None, s, "8")
for s in ("x", "y", OldTex("x?y"))
]
q_mark = OldTex("?").scale(2)
equation = VMobject(
top1, q_mark, top2, OldTex("="), top3
)
equation.arrange(buff = 0.7)
symbols_at_top = VMobject(*[
top.values[1]
for top in (top1, top2, top3)
])
symbols_at_lower_right = VMobject(*[
top.put_on_vertex(0, top.values[1].copy())
for top in (top1, top2, top3)
])
old_style_eq1 = OldTex("\\sqrt[x]{8} ? \\sqrt[y]{8} = \\sqrt[x?y]{8}")
old_style_eq1.set_color(BLUE)
old_style_eq2 = OldTex("\\log_x(8) ? \\log_y(8) = \\log_{x?y}(8)")
old_style_eq2.set_color(YELLOW)
for eq in old_style_eq1, old_style_eq2:
eq.to_edge(UP)
randy = Randolph()
randy.to_corner()
bubble = ThoughtBubble().pin_to(randy)
bubble.add_content(TOP(None, None, "8"))
self.add(randy, bubble)
self.play(ApplyMethod(randy.change_mode, "pondering"))
self.wait(3)
triangle = bubble.content.triangle
eight = bubble.content.values[2]
bubble.clear()
self.play(
Transform(triangle, equation),
FadeOut(eight),
ApplyPointwiseFunction(
lambda p : (p+2*DOWN)*15/get_norm(p+2*DOWN),
bubble
),
FadeIn(old_style_eq1),
ApplyMethod(randy.shift, 3*DOWN + 3*LEFT),
run_time = 2
)
self.remove(triangle)
self.add(equation)
self.wait(4)
self.play(
Transform(
symbols_at_top, symbols_at_lower_right,
path_arc = np.pi/2
),
Transform(old_style_eq1, old_style_eq2)
)
self.wait(2)
class AOplusB(Scene):
def construct(self):
self.add(OldTex(
"a \\oplus b = \\dfrac{1}{\\frac{1}{a} + \\frac{1}{b}}"
).scale(2))
self.wait()
class ConstantLowerRight(Scene):
def construct(self):
top = TOP()
times = top.put_in_vertex(0, OldTex("\\times"))
times.set_color(YELLOW)
oplus = top.put_in_vertex(1, OldTex("\\oplus"))
oplus.set_color(BLUE)
dot = top.put_in_vertex(2, Dot())
eight = top.put_on_vertex(2, OldTex("8"))
self.add(top)
self.play(ShowCreation(eight))
for mob in dot, oplus, times:
self.play(ShowCreation(mob))
self.wait()
top.add(eight)
top.add(times, oplus, dot)
top1, top2, top3 = tops = [
top.copy() for i in range(3)
]
big_oplus = OldTex("\\oplus").scale(2).set_color(BLUE)
equals = OldTex("=")
equation = VMobject(
top1, big_oplus, top2, equals, top3
)
equation.arrange()
top3.shift(0.5*RIGHT)
x, y, xy = [
t.put_on_vertex(0, s)
for t, s in zip(tops, ["x", "y", "xy"])
]
old_style_eq = OldTex(
"\\dfrac{1}{\\frac{1}{\\log_x(8)} + \\frac{1}{\\log_y(8)}} = \\log_{xy}(8)"
)
old_style_eq.to_edge(UP).set_color(RED)
triple_top_copy = VMobject(*[
top.copy() for i in range(3)
])
self.clear()
self.play(
Transform(triple_top_copy, VMobject(*tops)),
FadeIn(VMobject(x, y, xy, big_oplus, equals))
)
self.remove(triple_top_copy)
self.add(*tops)
self.play(Write(old_style_eq))
self.wait(3)
syms = VMobject(x, y, xy)
new_syms = VMobject(*[
t.put_on_vertex(1, s)
for t, s in zip(tops, ["x", "y", "x \\oplus y"])
])
new_old_style_eq = OldTex(
"\\sqrt[x]{8} \\sqrt[y]{8} = \\sqrt[X]{8}"
)
X = new_old_style_eq.split()[-4]
frac = OldTex("\\frac{1}{\\frac{1}{x} + \\frac{1}{y}}")
frac.replace(X)
frac_lower_right = frac.get_corner(DOWN+RIGHT)
frac.scale(2)
frac.shift(frac_lower_right - frac.get_corner(DOWN+RIGHT))
new_old_style_eq.submobjects[-4] = frac
new_old_style_eq.to_edge(UP)
new_old_style_eq.set_color(RED)
big_times = OldTex("\\times").set_color(YELLOW)
big_times.shift(big_oplus.get_center())
self.play(
Transform(old_style_eq, new_old_style_eq),
Transform(syms, new_syms, path_arc = np.pi/2),
Transform(big_oplus, big_times)
)
self.wait(4)
class TowerExponentFrame(Scene):
def construct(self):
words = OldTexText("""
Consider an expression like $3^{3^3}$. It's
ambiguous whether this means $27^3$ or $3^{27}$,
which is the difference between $19{,}683$ and
$7{,}625{,}597{,}484{,}987$. But with the triangle
of power, the difference is crystal clear:
""")
words.set_width(FRAME_WIDTH-1)
words.to_edge(UP)
top1 = TOP(TOP(3, 3), 3)
top2 = TOP(3, (TOP(3, 3)))
for top in top1, top2:
top.next_to(words, DOWN)
top1.shift(3*LEFT)
top2.shift(3*RIGHT)
self.add(words, top1, top2)
self.wait()
class ExponentialGrowth(Scene):
def construct(self):
words = OldTexText("""
Let's say you are studying a certain growth rate,
and you come across an expression like $T^a$. It
matters a lot whether you consider $T$ or $a$
to be the variable, since exponential growth and
polynomial growth have very different flavors. The
nice thing about having a triangle that you can write
inside is that you can clarify this kind of ambiguity
by writing a little dot next to the constant and
a ``$\\sim$'' next to the variable.
""")
words.scale(0.75)
words.to_edge(UP)
top = TOP("T", "a")
top.next_to(words, DOWN)
dot = top.put_in_vertex(0, OldTex("\\cdot"))
sim = top.put_in_vertex(1, OldTex("\\sim"))
self.add(words, top, dot, sim)
self.show_frame()
self.wait()
class GoExplore(Scene):
def construct(self):
explore = OldTexText("Go explore!")
by_the_way = OldTexText("by the way \\dots")
by_the_way.shift(20*RIGHT)
self.play(Write(explore))
self.wait(4)
self.play(
ApplyMethod(
VMobject(explore, by_the_way).shift,
20*LEFT
)
)
self.wait(3)
|
|
from manim_imports_ext import *
from _2016.eola.chapter1 import plane_wave_homotopy
from _2016.eola.chapter3 import ColumnsToBasisVectors
from _2016.eola.chapter5 import get_det_text
from _2016.eola.chapter9 import get_small_bubble
class OpeningQuote(Scene):
def construct(self):
words = OldTexText(
"``Last time, I asked: `What does",
"mathematics",
""" mean to you?', and some people answered: `The
manipulation of numbers, the manipulation of structures.'
And if I had asked what""",
"music",
"""means to you, would you have answered: `The
manipulation of notes?' '' """,
enforce_new_line_structure = False,
alignment = "",
)
words.set_color_by_tex("mathematics", BLUE)
words.set_color_by_tex("music", BLUE)
words.set_width(FRAME_WIDTH - 2)
words.to_edge(UP)
author = OldTexText("-Serge Lang")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = 0.5)
self.play(Write(words, run_time = 10))
self.wait()
self.play(FadeIn(author))
self.wait(3)
class StudentsFindThisConfusing(TeacherStudentsScene):
def construct(self):
title = OldTexText("Eigenvectors and Eigenvalues")
title.to_edge(UP)
students = self.get_students()
self.play(
Write(title),
*[
ApplyMethod(pi.look_at, title)
for pi in self.get_pi_creatures()
]
)
self.play(
self.get_teacher().look_at, students[-1].eyes,
students[0].change_mode, "confused",
students[1].change_mode, "tired",
students[2].change_mode, "sassy",
)
self.random_blink()
self.student_says(
"Why are we doing this?",
index = 0,
run_time = 2,
)
question1 = students[0].bubble.content.copy()
self.student_says(
"What does this actually mean?",
index = 2,
added_anims = [
question1.scale, 0.8,
question1.to_edge, LEFT,
question1.shift, DOWN,
]
)
question2 = students[2].bubble.content.copy()
question2.target = question2.copy()
question2.target.next_to(
question1, DOWN,
aligned_edge = LEFT,
buff = MED_SMALL_BUFF
)
equation = OldTex(
"\\det\\left( %s \\right)=0"%matrix_to_tex_string([
["a-\\lambda", "b"],
["c", "d-\\lambda"],
])
)
equation.set_color(YELLOW)
self.teacher_says(
equation,
added_anims = [MoveToTarget(question2)]
)
self.play_student_changes(*["confused"]*3)
self.random_blink(3)
class ShowComments(Scene):
pass #TODO
class EigenThingsArentAllThatBad(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"Eigen-things aren't \\\\ actually so bad",
target_mode = "hooray"
)
self.play_student_changes(
"pondering", "pondering", "erm"
)
self.random_blink(4)
class ManyPrerequisites(Scene):
def construct(self):
title = OldTexText("Many prerequisites")
title.to_edge(UP)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
h_line.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(h_line))
rect = Rectangle(height = 9, width = 16, color = BLUE)
rect.set_width(FRAME_X_RADIUS-2)
rects = [rect]+[rect.copy() for i in range(3)]
words = [
"Linear transformations",
"Determinants",
"Linear systems",
"Change of basis",
]
for rect, word in zip(rects, words):
word_mob = OldTexText(word)
word_mob.next_to(rect, UP, buff = MED_SMALL_BUFF)
rect.add(word_mob)
Matrix(np.array(rects).reshape((2, 2)))
rects = VGroup(*rects)
rects.set_height(FRAME_HEIGHT - 1.5)
rects.next_to(h_line, DOWN, buff = MED_SMALL_BUFF)
self.play(Write(rects[0]))
self.wait()
self.play(*list(map(FadeIn, rects[1:])))
self.wait()
class ExampleTranformationScene(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[3, 0], [1, 2]]
}
def setup(self):
LinearTransformationScene.setup(self)
self.add_matrix()
def add_matrix(self):
matrix = Matrix(self.t_matrix.T)
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(ORIGIN, LEFT, buff = MED_SMALL_BUFF)
matrix.to_edge(UP)
matrix.rect = BackgroundRectangle(matrix)
matrix.add_to_back(matrix.rect)
self.add_foreground_mobject(matrix)
self.matrix = matrix
def remove_matrix(self):
self.remove(self.matrix)
self.foreground_mobjects.remove(self.matrix)
class IntroduceExampleTransformation(ExampleTranformationScene):
def construct(self):
self.remove_matrix()
i_coords = Matrix(self.t_matrix[0])
j_coords = Matrix(self.t_matrix[1])
self.apply_transposed_matrix(self.t_matrix)
for coords, vect in (i_coords, self.i_hat), (j_coords, self.j_hat):
coords.set_color(vect.get_color())
coords.scale(0.8)
coords.rect = BackgroundRectangle(coords)
coords.add_to_back(coords.rect)
coords.next_to(vect.get_end(), RIGHT)
self.play(Write(coords))
self.wait()
i_coords_copy = i_coords.copy()
self.play(*[
Transform(*pair)
for pair in [
(i_coords_copy.rect, self.matrix.rect),
(i_coords_copy.get_brackets(), self.matrix.get_brackets()),
(
i_coords_copy.get_entries(),
VGroup(*self.matrix.get_mob_matrix()[:,0])
)
]
])
to_remove = self.get_mobjects_from_last_animation()
self.play(Transform(
j_coords.copy().get_entries(),
VGroup(*self.matrix.get_mob_matrix()[:,1])
))
to_remove += self.get_mobjects_from_last_animation()
self.wait()
self.remove(*to_remove)
self.add(self.matrix)
class VectorKnockedOffSpan(ExampleTranformationScene):
def construct(self):
vector = Vector([2, 1])
line = Line(vector.get_end()*-4, vector.get_end()*4, color = MAROON_B)
vector.scale(0.7)
top_words, off, span_label = all_words = OldTexText(
"\\centering Vector gets knocked", "\\\\ off", "Span"
)
all_words.shift(
line.point_from_proportion(0.75) - \
span_label.get_corner(DOWN+RIGHT) + \
MED_SMALL_BUFF*LEFT
)
for text in all_words:
text.add_to_back(BackgroundRectangle(text))
self.add_vector(vector)
self.wait()
self.play(
ShowCreation(line),
Write(span_label),
Animation(vector),
)
self.add_foreground_mobject(span_label)
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.play(Animation(span_label.copy()), Write(all_words))
self.wait()
class VectorRemainsOnSpan(ExampleTranformationScene):
def construct(self):
vector = Vector([1, -1])
v_end = vector.get_end()
line = Line(-4*v_end, 4*v_end, color = MAROON_B)
words = OldTexText("Vector remains on", "\\\\its own span")
words.next_to(ORIGIN, DOWN+LEFT)
for part in words:
part.add_to_back(BackgroundRectangle(part))
self.add_vector(vector)
self.play(ShowCreation(line), Animation(vector))
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.play(Write(words))
self.wait()
target_vectors = [
vector.copy().scale(scalar)
for scalar in (2, -2, 1)
]
for target, time in zip(target_vectors, [1, 2, 2]):
self.play(Transform(vector, target, run_time = time))
self.wait()
class IHatAsEigenVector(ExampleTranformationScene):
def construct(self):
self.set_color_first_column()
self.set_color_x_axis()
self.apply_transposed_matrix(self.t_matrix, path_arc = 0)
self.label_i_hat_landing_spot()
def set_color_first_column(self):
faders = VGroup(self.plane, self.i_hat, self.j_hat)
faders.save_state()
column1 = VGroup(*self.matrix.get_mob_matrix()[:,0])
self.play(faders.fade, 0.7, Animation(self.matrix))
self.play(column1.scale, 1.3, rate_func = there_and_back)
self.wait()
self.play(faders.restore, Animation(self.matrix))
self.wait()
def set_color_x_axis(self):
x_axis = self.plane.axes[0]
targets = [
self.i_hat.copy().scale(val)
for val in (-FRAME_X_RADIUS, FRAME_X_RADIUS, 1)
]
lines = [
Line(v1.get_end(), v2.get_end(), color = YELLOW)
for v1, v2 in adjacent_pairs([self.i_hat]+targets)
]
for target, line in zip(targets, lines):
self.play(
ShowCreation(line),
Transform(self.i_hat, target),
)
self.wait()
self.remove(*lines)
x_axis.set_color(YELLOW)
def label_i_hat_landing_spot(self):
array = Matrix(self.t_matrix[0])
array.set_color(X_COLOR)
array.rect = BackgroundRectangle(array)
array.add_to_back(array.rect)
brace = Brace(self.i_hat, buff = 0)
brace.put_at_tip(array)
self.play(GrowFromCenter(brace))
matrix = self.matrix.copy()
self.play(
Transform(matrix.rect, array.rect),
Transform(matrix.get_brackets(), array.get_brackets()),
Transform(
VGroup(*matrix.get_mob_matrix()[:,0]),
array.get_entries()
),
)
self.wait()
class AllXAxisVectorsAreEigenvectors(ExampleTranformationScene):
def construct(self):
vectors = VGroup(*[
self.add_vector(u*x*RIGHT, animate = False)
for x in reversed(list(range(1, int(FRAME_X_RADIUS)+1)))
for u in [-1, 1]
])
vectors.set_color_by_gradient(YELLOW, X_COLOR)
self.play(ShowCreation(vectors))
self.wait()
self.apply_transposed_matrix(self.t_matrix, path_arc = 0)
self.wait()
class SneakierEigenVector(ExampleTranformationScene):
def construct(self):
coords = [-1, 1]
vector = Vector(coords)
array = Matrix(coords)
array.scale(0.7)
array.set_color(vector.get_color())
array.add_to_back(BackgroundRectangle(array))
array.target = array.copy()
array.next_to(vector.get_end(), LEFT)
array.target.next_to(2*vector.get_end(), LEFT)
two_times = OldTex("2 \\cdot")
two_times.add_background_rectangle()
two_times.next_to(array.target, LEFT)
span_line = Line(-4*vector.get_end(), 4*vector.get_end())
span_line.set_color(MAROON_B)
self.matrix.shift(-2*self.matrix.get_center()[0]*RIGHT)
self.add_vector(vector)
self.play(Write(array))
self.play(
ShowCreation(span_line),
Animation(vector),
Animation(array),
)
self.wait()
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [
MoveToTarget(array),
Transform(VectorizedPoint(array.get_left()), two_times)
],
path_arc = 0,
)
self.wait()
class FullSneakyEigenspace(ExampleTranformationScene):
def construct(self):
self.matrix.shift(-2*self.matrix.get_center()[0]*RIGHT)
vectors = VGroup(*[
self.add_vector(u*x*(LEFT+UP), animate = False)
for x in reversed(np.arange(0.5, 5, 0.5))
for u in [-1, 1]
])
vectors.set_color_by_gradient(MAROON_B, YELLOW)
words = OldTexText("Stretch by 2")
words.add_background_rectangle()
words.next_to(ORIGIN, DOWN+LEFT, buff = MED_SMALL_BUFF)
words.shift(MED_SMALL_BUFF*LEFT)
words.rotate(vectors[0].get_angle())
words.start = words.copy()
words.start.scale(0.5)
words.start.set_fill(opacity = 0)
self.play(ShowCreation(vectors))
self.wait()
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [Transform(words.start, words)],
path_arc = 0
)
self.wait()
class NameEigenvectorsAndEigenvalues(ExampleTranformationScene):
CONFIG = {
"show_basis_vectors" : False
}
def construct(self):
self.remove(self.matrix)
self.foreground_mobjects.remove(self.matrix)
x_vectors = VGroup(*[
self.add_vector(u*x*RIGHT, animate = False)
for x in range(int(FRAME_X_RADIUS)+1, 0, -1)
for u in [-1, 1]
])
x_vectors.set_color_by_gradient(YELLOW, X_COLOR)
self.remove(x_vectors)
sneak_vectors = VGroup(*[
self.add_vector(u*x*(LEFT+UP), animate = False)
for x in np.arange(int(FRAME_Y_RADIUS), 0, -0.5)
for u in [-1, 1]
])
sneak_vectors.set_color_by_gradient(MAROON_B, YELLOW)
self.remove(sneak_vectors)
x_words = OldTexText("Stretched by 3")
sneak_words = OldTexText("Stretched by 2")
for words in x_words, sneak_words:
words.add_background_rectangle()
words.next_to(x_vectors, DOWN)
words.next_to(words.get_center(), LEFT, buff = 1.5)
eigen_word = OldTexText("Eigenvectors")
eigen_word.add_background_rectangle()
eigen_word.replace(words)
words.target = eigen_word
eigen_val_words = OldTexText(
"with eigenvalue ",
"%s"%words.get_tex()[-1]
)
eigen_val_words.add_background_rectangle()
eigen_val_words.next_to(words, DOWN, aligned_edge = RIGHT)
words.eigen_val_words = eigen_val_words
x_words.eigen_val_words.set_color(X_COLOR)
sneak_words.eigen_val_words.set_color(YELLOW)
VGroup(
sneak_words,
sneak_words.target,
sneak_words.eigen_val_words,
).rotate(sneak_vectors[0].get_angle())
non_eigen = Vector([1, 1], color = PINK)
non_eigen_span = Line(
-FRAME_Y_RADIUS*non_eigen.get_end(),
FRAME_Y_RADIUS*non_eigen.get_end(),
color = RED
)
non_eigen_words = OldTexText("""
Knocked off
its own span
""")
non_eigen_words.add_background_rectangle()
non_eigen_words.scale(0.7)
non_eigen_words.next_to(non_eigen.get_end(), RIGHT)
non_eigen_span.fade()
for vectors in x_vectors, sneak_vectors:
self.play(ShowCreation(vectors, run_time = 1))
self.wait()
for words in x_words, sneak_words:
self.play(Write(words, run_time = 1.5))
self.add_foreground_mobject(words)
self.wait()
self.play(ShowCreation(non_eigen))
self.play(
ShowCreation(non_eigen_span),
Write(non_eigen_words),
Animation(non_eigen)
)
self.add_vector(non_eigen, animate = False)
self.wait()
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [FadeOut(non_eigen_words)],
path_arc = 0,
)
self.wait(2)
self.play(*list(map(FadeOut, [non_eigen, non_eigen_span])))
self.play(*list(map(MoveToTarget, [x_words, sneak_words])))
self.wait()
for words in x_words, sneak_words:
self.play(Write(words.eigen_val_words), run_time = 2)
self.wait()
class CanEigenvaluesBeNegative(TeacherStudentsScene):
def construct(self):
self.student_says("Can eigenvalues be negative?")
self.random_blink()
self.teacher_says("But of course!", target_mode = "hooray")
self.random_blink()
class EigenvalueNegativeOneHalf(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[0.5, -1], [-1, 0.5]],
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 0
},
"include_background_plane" : False
}
def construct(self):
matrix = Matrix(self.t_matrix.T)
matrix.add_to_back(BackgroundRectangle(matrix))
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(ORIGIN, LEFT)
matrix.to_edge(UP)
self.add_foreground_mobject(matrix)
vector = self.add_vector([1, 1])
words = OldTexText("Eigenvector with \\\\ eigenvalue $-\\frac{1}{2}$")
words.add_background_rectangle()
words.next_to(vector.get_end(), RIGHT)
span = Line(
-FRAME_Y_RADIUS*vector.get_end(),
FRAME_Y_RADIUS*vector.get_end(),
color = MAROON_B
)
self.play(Write(words))
self.play(
ShowCreation(span),
Animation(vector),
Animation(words),
)
self.wait()
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [FadeOut(words)]
)
self.wait()
self.play(
Rotate(span, np.pi/12, rate_func = wiggle),
Animation(vector),
)
self.wait()
class ThreeDRotationTitle(Scene):
def construct(self):
title = OldTexText("3D Rotation")
title.scale(2)
self.play(Write(title))
self.wait()
class ThreeDShowRotation(Scene):
pass
class ThreeDShowRotationWithEigenvector(Scene):
pass
class EigenvectorToAxisOfRotation(Scene):
def construct(self):
words = [
OldTexText("Eigenvector"),
OldTexText("Axis of rotation"),
]
for word in words:
word.scale(2)
self.play(Write(words[0]))
self.wait()
self.play(Transform(*words))
self.wait()
class EigenvalueOne(Scene):
def construct(self):
text = OldTexText("Eigenvalue = $1$")
text.set_color(MAROON_B)
self.play(Write(text))
self.wait()
class ContrastMatrixUnderstandingWithEigenvalue(TeacherStudentsScene):
def construct(self):
axis_and_rotation = OldTexText(
"Rotate", "$30^\\circ$", "around",
"$%s$"%matrix_to_tex_string([2, 3, 1])
)
axis_and_rotation[1].set_color(BLUE)
axis_and_rotation[-1].set_color(MAROON_B)
matrix = Matrix([
[
"\\cos(\\theta)\\cos(\\phi)",
"-\\sin(\\phi)",
"\\cos(\\theta)\\sin(\\phi)",
],
[
"\\sin(\\theta)\\cos(\\phi)",
"\\cos(\\theta)",
"\\sin(\\theta)\\sin(\\phi)",
],
[
"-\\sin(\\phi)",
"0",
"\\cos(\\phi)"
]
])
matrix.scale(0.7)
for mob in axis_and_rotation, matrix:
mob.to_corner(UP+RIGHT)
everyone = self.get_pi_creatures()
self.play(
Write(axis_and_rotation),
*it.chain(*list(zip(
[pi.change_mode for pi in everyone],
["hooray"]*4,
[pi.look_at for pi in everyone],
[axis_and_rotation]*4,
))),
run_time = 2
)
self.random_blink(2)
self.play(
Transform(axis_and_rotation, matrix),
*it.chain(*list(zip(
[pi.change_mode for pi in everyone],
["confused"]*4,
[pi.look_at for pi in everyone],
[matrix]*4,
)))
)
self.random_blink(3)
class CommonPattern(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
This is a common pattern
in linear algebra.
""")
self.random_blink(2)
class DeduceTransformationFromMatrix(ColumnsToBasisVectors):
def construct(self):
self.setup()
self.move_matrix_columns([[3, 0], [1, 2]])
words = OldTexText("""
This gives too much weight
to our coordinate system
""")
words.add_background_rectangle()
words.next_to(ORIGIN, DOWN+LEFT, buff = MED_SMALL_BUFF)
words.shift_onto_screen()
self.play(Write(words))
self.wait()
class WordsOnComputation(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"I won't cover the full\\\\",
"details of computation...",
target_mode = "guilty"
)
self.play_student_changes("angry", "sassy", "angry")
self.random_blink()
self.teacher_says(
"...but I'll hit the \\\\",
"important parts"
)
self.play_student_changes(*["happy"]*3)
self.random_blink(3)
class SymbolicEigenvectors(Scene):
def construct(self):
self.introduce_terms()
self.contrast_multiplication_types()
self.rewrite_righthand_side()
self.reveal_as_linear_system()
self.bring_in_determinant()
def introduce_terms(self):
self.expression = OldTex(
"A", "\\vec{\\textbf{v}}", "=",
"\\lambda", "\\vec{\\textbf{v}}"
)
self.expression.scale(1.5)
self.expression.shift(UP+2*LEFT)
A, v1, equals, lamb, v2 = self.expression
vs = VGroup(v1, v2)
vs.set_color(YELLOW)
lamb.set_color(MAROON_B)
A_brace = Brace(A, UP, buff = 0)
A_text = OldTexText("Transformation \\\\ matrix")
A_text.next_to(A_brace, UP)
lamb_brace = Brace(lamb, UP, buff = 0)
lamb_text = OldTexText("Eigenvalue")
lamb_text.set_color(lamb.get_color())
lamb_text.next_to(lamb_brace, UP, aligned_edge = LEFT)
v_text = OldTexText("Eigenvector")
v_text.set_color(vs.get_color())
v_text.next_to(vs, DOWN, buff = 1.5*LARGE_BUFF)
v_arrows = VGroup(*[
Arrow(v_text.get_top(), v.get_bottom())
for v in vs
])
self.play(Write(self.expression))
self.wait()
self.play(
GrowFromCenter(A_brace),
Write(A_text)
)
self.wait()
self.play(
Write(v_text),
ShowCreation(v_arrows)
)
self.wait()
self.play(
GrowFromCenter(lamb_brace),
Write(lamb_text)
)
self.wait(2)
self.play(*list(map(FadeOut, [
A_brace, A_text,
lamb_brace, lamb_text,
v_text, v_arrows
])))
def contrast_multiplication_types(self):
A, v1, equals, lamb, v2 = self.expression
left_group = VGroup(A, v1)
left_group.brace = Brace(left_group, UP)
left_group.text = left_group.brace.get_text("Matrix-vector multiplication")
right_group = VGroup(lamb, v2)
right_group.brace = Brace(right_group, DOWN)
right_group.text = right_group.brace.get_text("Scalar multiplication")
right_group.text.set_color(lamb.get_color())
for group in left_group, right_group:
self.play(
GrowFromCenter(group.brace),
Write(group.text, run_time = 2)
)
self.play(group.scale, 1.2, rate_func = there_and_back)
self.wait()
morty = Mortimer().to_edge(DOWN)
morty.change_mode("speaking")
bubble = morty.get_bubble(SpeechBubble, width = 5, direction = LEFT)
VGroup(morty, bubble).to_edge(RIGHT)
solve_text = OldTexText(
"Solve for \\\\",
"$\\lambda$", "and", "$\\vec{\\textbf{v}}$"
)
solve_text.set_color_by_tex("$\\lambda$", lamb.get_color())
solve_text.set_color_by_tex("$\\vec{\\textbf{v}}$", v1.get_color())
bubble.add_content(solve_text)
self.play(
FadeIn(morty),
FadeIn(bubble),
Write(solve_text)
)
self.play(Blink(morty))
self.wait(2)
bubble.write("Fix different", "\\\\ multiplication", "types")
self.play(
Transform(solve_text, bubble.content),
morty.change_mode, "sassy"
)
self.play(Blink(morty))
self.wait()
self.play(*list(map(FadeOut, [
left_group.brace, left_group.text,
right_group.brace, right_group.text,
morty, bubble, solve_text
])))
def rewrite_righthand_side(self):
A, v1, equals, lamb, v2 = self.expression
lamb_copy = lamb.copy()
scaling_by = VGroup(
OldTexText("Scaling by "), lamb_copy
)
scaling_by.arrange()
arrow = OldTex("\\Updownarrow")
matrix_multiplication = OldTexText(
"Matrix multiplication by"
)
matrix = Matrix(np.identity(3, dtype = int))
corner_group = VGroup(
scaling_by, arrow, matrix_multiplication, matrix
)
corner_group.arrange(DOWN)
corner_group.to_corner(UP+RIGHT)
q_marks = VGroup(*[
OldTex("?").replace(entry)
for entry in matrix.get_entries()
])
q_marks.set_color_by_gradient(X_COLOR, Y_COLOR, Z_COLOR)
diag_entries = VGroup(*[
matrix.get_mob_matrix()[i,i]
for i in range(3)
])
diag_entries.save_state()
for entry in diag_entries:
new_lamb = OldTex("\\lambda")
new_lamb.move_to(entry)
new_lamb.set_color(lamb.get_color())
Transform(entry, new_lamb).update(1)
new_lamb = lamb.copy()
new_lamb.next_to(matrix, LEFT)
id_brace = Brace(matrix)
id_text = OldTex("I").scale(1.5)
id_text.next_to(id_brace, DOWN)
self.play(
Transform(lamb.copy(), lamb_copy),
Write(scaling_by)
)
self.remove(*self.get_mobjects_from_last_animation())
self.add(scaling_by)
self.play(Write(VGroup(
matrix_multiplication,
arrow,
matrix.get_brackets(),
q_marks,
), run_time = 2
))
self.wait()
self.play(Transform(
q_marks, matrix.get_entries(),
lag_ratio = 0.5,
run_time = 2
))
self.remove(q_marks)
self.add(*matrix.get_entries())
self.wait()
self.play(
Transform(diag_entries.copy(), new_lamb),
diag_entries.restore
)
self.remove(*self.get_mobjects_from_last_animation())
self.add(new_lamb, diag_entries)
self.play(
GrowFromCenter(id_brace),
Write(id_text)
)
self.wait()
id_text_copy = id_text.copy()
self.add(id_text_copy)
l_paren, r_paren = parens = OldTex("()").scale(1.5)
for mob in lamb, id_text, v2:
mob.target = mob.copy()
VGroup(
l_paren, lamb.target, id_text.target,
r_paren, v2.target
).arrange().next_to(equals).shift(SMALL_BUFF*UP)
self.play(
Write(parens),
*list(map(MoveToTarget, [lamb, id_text, v2]))
)
self.wait()
self.play(*list(map(FadeOut, [
corner_group, id_brace, id_text_copy, new_lamb
])))
self.expression = VGroup(
A, v1, equals,
VGroup(l_paren, lamb, id_text, r_paren),
v2
)
def reveal_as_linear_system(self):
A, v1, equals, lamb_group, v2 = self.expression
l_paren, lamb, I, r_paren = lamb_group
zero = OldTex("\\vec{\\textbf{0}}")
zero.scale(1.3)
zero.next_to(equals, RIGHT)
zero.shift(SMALL_BUFF*UP/2)
minus = OldTex("-").scale(1.5)
movers = A, v1, lamb_group, v2
for mob in movers:
mob.target = mob.copy()
VGroup(
A.target, v1.target, minus,
lamb_group.target, v2.target
).arrange().next_to(equals, LEFT)
self.play(
Write(zero),
Write(minus),
*list(map(MoveToTarget, movers)),
path_arc = np.pi/3
)
self.wait()
A.target.next_to(minus, LEFT)
l_paren.target = l_paren.copy()
l_paren.target.next_to(A.target, LEFT)
self.play(
MoveToTarget(A),
MoveToTarget(l_paren),
Transform(v1, v2, path_arc = np.pi/3)
)
self.remove(v1)
self.wait()
brace = Brace(VGroup(l_paren, r_paren))
brace.text = OldTexText("This matrix looks \\\\ something like")
brace.text.next_to(brace, DOWN)
brace.text.to_edge(LEFT)
matrix = Matrix([
["3-\\lambda", "1", "4"],
["1", "5-\\lambda", "9"],
["2", "6", "5-\\lambda"],
])
matrix.scale(0.7)
VGroup(
matrix.get_brackets()[1],
*matrix.get_mob_matrix()[:,2]
).shift(0.5*RIGHT)
matrix.next_to(brace.text, DOWN)
for entry in matrix.get_entries():
if len(entry.get_tex()) > 1:
entry[-1].set_color(lamb.get_color())
self.play(
GrowFromCenter(brace),
Write(brace.text),
Write(matrix)
)
self.wait()
vect_words = OldTexText(
"We want a nonzero solution for"
)
v_copy = v2.copy().next_to(vect_words)
vect_words.add(v_copy)
vect_words.to_corner(UP+LEFT)
arrow = Arrow(vect_words.get_bottom(), v2.get_top())
self.play(
Write(vect_words),
ShowCreation(arrow)
)
self.wait()
def bring_in_determinant(self):
randy = Randolph(mode = "speaking").to_edge(DOWN)
randy.flip()
randy.look_at(self.expression)
bubble = randy.get_bubble(SpeechBubble, direction = LEFT, width = 5)
words = OldTexText("We need")
equation = OldTex(
"\\det(A-", "\\lambda", "I)", "=0"
)
equation.set_color_by_tex("\\lambda", MAROON_B)
equation.next_to(words, DOWN)
words.add(equation)
bubble.add_content(words)
self.play(
FadeIn(randy),
ShowCreation(bubble),
Write(words)
)
self.play(Blink(randy))
self.wait()
everything = self.get_mobjects()
equation_copy = equation.copy()
self.play(
FadeOut(VGroup(*everything)),
Animation(equation_copy)
)
self.play(
equation_copy.center,
equation_copy.scale, 1.5
)
self.wait()
class NonZeroSolutionsVisually(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[1, 1], [2, 2]],
"v_coords" : [2, -1]
}
def construct(self):
equation = OldTex(
"(A-", "\\lambda", "I)", "\\vec{\\textbf{v}}",
"= \\vec{\\textbf{0}}"
)
equation_matrix = VGroup(*equation[:3])
equation.set_color_by_tex("\\lambda", MAROON_B)
equation.set_color_by_tex("\\vec{\\textbf{v}}", YELLOW)
equation.add_background_rectangle()
equation.next_to(ORIGIN, DOWN, buff = MED_SMALL_BUFF)
equation.to_edge(LEFT)
det_equation = OldTex(
"\\text{Squishification} \\Rightarrow",
"\\det", "(A-", "\\lambda", "I", ")", "=0"
)
det_equation_matrix = VGroup(*det_equation[2:2+4])
det_equation.set_color_by_tex("\\lambda", MAROON_B)
det_equation.next_to(equation, DOWN, buff = MED_SMALL_BUFF)
det_equation.to_edge(LEFT)
det_equation.add_background_rectangle()
self.add_foreground_mobject(equation)
v = self.add_vector(self.v_coords)
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
transform = Transform(
equation_matrix.copy(), det_equation_matrix
)
self.play(Write(det_equation), transform)
self.wait()
class TweakLambda(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[2, 1], [2, 3]],
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 1
},
}
def construct(self):
matrix = Matrix([
["2-0.00", "2"],
["1", "3-0.00"],
])
matrix.add_to_back(BackgroundRectangle(matrix))
matrix.next_to(ORIGIN, LEFT, buff = LARGE_BUFF)
matrix.to_edge(UP)
self.lambda_vals = []
for i in range(2):
entry = matrix.get_mob_matrix()[i,i]
place_holders = VGroup(*entry[2:])
entry.remove(*place_holders)
place_holders.set_color(MAROON_B)
self.lambda_vals.append(place_holders)
brace = Brace(matrix)
brace_text = OldTex("(A-", "\\lambda", "I)")
brace_text.set_color_by_tex("\\lambda", MAROON_B)
brace_text.next_to(brace, DOWN)
brace_text.add_background_rectangle()
det_text = get_det_text(matrix)
equals = OldTex("=").next_to(det_text)
det = DecimalNumber(np.linalg.det(self.t_matrix))
det.set_color(YELLOW)
det.next_to(equals)
det.rect = BackgroundRectangle(det)
self.det = det
self.matrix = VGroup(matrix, brace, brace_text)
self.add_foreground_mobject(
self.matrix, *self.lambda_vals
)
self.add_unit_square()
self.plane_mobjects = [
self.plane, self.square,
]
for mob in self.plane_mobjects:
mob.save_state()
self.apply_transposed_matrix(self.t_matrix)
self.play(
Write(det_text),
Write(equals),
ShowCreation(det.rect),
Write(det)
)
self.matrix.add(det_text, equals, det.rect)
self.wait()
self.range_lambda(0, 3, run_time = 5)
self.wait()
self.range_lambda(3, 0.5, run_time = 5)
self.wait()
self.range_lambda(0.5, 1.5, run_time = 3)
self.wait()
self.range_lambda(1.5, 1, run_time = 2)
self.wait()
def get_t_matrix(self, lambda_val):
return self.t_matrix - lambda_val*np.identity(2)
def range_lambda(self, start_val, end_val, run_time = 3):
alphas = np.linspace(0, 1, run_time/self.frame_duration)
matrix_transform = self.get_matrix_transformation(
self.get_t_matrix(end_val)
)
transformations = []
for mob in self.plane_mobjects:
mob.target = mob.copy().restore().apply_function(matrix_transform)
transformations.append(MoveToTarget(mob))
transformations += [
Transform(
self.i_hat,
Vector(matrix_transform(RIGHT), color = X_COLOR)
),
Transform(
self.j_hat,
Vector(matrix_transform(UP), color = Y_COLOR)
),
]
for alpha in alphas:
self.clear()
val = interpolate(start_val, end_val, alpha)
new_t_matrix = self.get_t_matrix(val)
for transformation in transformations:
transformation.update(alpha)
self.add(transformation.mobject)
self.add(self.matrix)
new_lambda_vals = []
for lambda_val in self.lambda_vals:
new_lambda = DecimalNumber(val)
new_lambda.move_to(lambda_val, aligned_edge = LEFT)
new_lambda.set_color(lambda_val.get_color())
new_lambda_vals.append(new_lambda)
self.lambda_vals = new_lambda_vals
self.add(*self.lambda_vals)
new_det = DecimalNumber(
np.linalg.det([
self.i_hat.get_end()[:2],
self.j_hat.get_end()[:2],
])
)
new_det.move_to(self.det, aligned_edge = LEFT)
new_det.set_color(self.det.get_color())
self.det = new_det
self.add(self.det)
self.wait(self.frame_duration)
class ShowEigenVectorAfterComputing(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[2, 1], [2, 3]],
"v_coords" : [2, -1],
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 1
},
}
def construct(self):
matrix = Matrix(self.t_matrix.T)
matrix.add_to_back(BackgroundRectangle(matrix))
matrix.next_to(ORIGIN, RIGHT)
matrix.shift(self.v_coords[0]*RIGHT)
self.add_foreground_mobject(matrix)
v_label = OldTex(
"\\vec{\\textbf{v}}",
"=",
"1",
"\\vec{\\textbf{v}}",
)
v_label.next_to(matrix, RIGHT)
v_label.set_color_by_tex("\\vec{\\textbf{v}}", YELLOW)
v_label.set_color_by_tex("1", MAROON_B)
v_label.add_background_rectangle()
v = self.add_vector(self.v_coords)
eigenvector = OldTexText("Eigenvector")
eigenvector.add_background_rectangle()
eigenvector.next_to(ORIGIN, DOWN+RIGHT)
eigenvector.rotate(v.get_angle())
self.play(Write(eigenvector))
self.add_foreground_mobject(eigenvector)
line = Line(v.get_end()*(-4), v.get_end()*4, color = MAROON_B)
self.play(Write(v_label))
self.add_foreground_mobject(v_label)
self.play(ShowCreation(line), Animation(v))
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
class LineOfReasoning(Scene):
def construct(self):
v_tex = "\\vec{\\textbf{v}}"
expressions = VGroup(*it.starmap(Tex, [
("A", v_tex, "=", "\\lambda", v_tex),
("A", v_tex, "-", "\\lambda", "I", v_tex, "=", "0"),
("(", "A", "-", "\\lambda", "I)", v_tex, "=", "0"),
("\\det(A-", "\\lambda", "I)", "=", "0")
]))
expressions.arrange(DOWN, buff = LARGE_BUFF/2.)
for expression in expressions:
for i, expression_part in enumerate(expression.expression_parts):
if expression_part == "=":
equals = expression[i]
expression.shift(equals.get_center()[0]*LEFT)
break
expression.set_color_by_tex(v_tex, YELLOW)
expression.set_color_by_tex("\\lambda", MAROON_B)
self.play(FadeIn(expression))
self.wait()
class IfYouDidntKnowDeterminants(TeacherStudentsScene):
def construct(self):
expression = OldTex("\\det(A-", "\\lambda", "I" ")=0")
expression.set_color_by_tex("\\lambda", MAROON_B)
expression.scale(1.3)
self.teacher_says(expression)
self.random_blink()
student = self.get_students()[0]
bubble = get_small_bubble(student)
bubble.write("Wait...why?")
self.play(
ShowCreation(bubble),
Write(bubble.content),
student.change_mode, "confused"
)
self.random_blink(4)
class RevisitExampleTransformation(ExampleTranformationScene):
def construct(self):
self.introduce_matrix()
seeking_eigenvalue = OldTexText("Seeking eigenvalue")
seeking_eigenvalue.add_background_rectangle()
lamb = OldTex("\\lambda")
lamb.set_color(MAROON_B)
words = VGroup(seeking_eigenvalue, lamb)
words.arrange()
words.next_to(self.matrix, DOWN, buff = LARGE_BUFF)
self.play(Write(words))
self.wait()
self.play(*self.get_lambda_to_diag_movements(lamb.copy()))
self.add_foreground_mobject(*self.get_mobjects_from_last_animation())
self.wait()
self.show_determinant(to_fade = words)
self.show_diagonally_altered_transform()
self.show_unaltered_transform()
def introduce_matrix(self):
self.matrix.shift(2*LEFT)
for mob in self.plane, self.i_hat, self.j_hat:
mob.save_state()
self.remove_matrix()
i_coords = Matrix(self.t_matrix[0])
j_coords = Matrix(self.t_matrix[1])
self.apply_transposed_matrix(self.t_matrix)
for coords, vect in (i_coords, self.i_hat), (j_coords, self.j_hat):
coords.set_color(vect.get_color())
coords.scale(0.8)
coords.rect = BackgroundRectangle(coords)
coords.add_to_back(coords.rect)
coords.next_to(
vect.get_end(),
RIGHT+DOWN if coords is i_coords else RIGHT
)
self.play(
Write(i_coords),
Write(j_coords),
)
self.wait()
self.play(*[
Transform(*pair)
for pair in [
(i_coords.rect, self.matrix.rect),
(i_coords.get_brackets(), self.matrix.get_brackets()),
(
i_coords.get_entries(),
VGroup(*self.matrix.get_mob_matrix()[:,0])
)
]
])
to_remove = self.get_mobjects_from_last_animation()
self.play(
FadeOut(j_coords.get_brackets()),
FadeOut(j_coords.rect),
Transform(
j_coords.get_entries(),
VGroup(*self.matrix.get_mob_matrix()[:,1])
),
)
to_remove += self.get_mobjects_from_last_animation()
self.wait()
self.remove(*to_remove)
self.add_foreground_mobject(self.matrix)
def get_lambda_to_diag_movements(self, lamb):
three, two = [self.matrix.get_mob_matrix()[i, i] for i in range(2)]
l_bracket, r_bracket = self.matrix.get_brackets()
rect = self.matrix.rect
lamb_copy = lamb.copy()
movers = [rect, three, two, l_bracket, r_bracket, lamb, lamb_copy]
for mover in movers:
mover.target = mover.copy()
minus1, minus2 = [Tex("-") for x in range(2)]
new_three = VGroup(three.target, minus1, lamb.target)
new_three.arrange()
new_three.move_to(three)
new_two = VGroup(two.target, minus2, lamb_copy.target)
new_two.arrange()
new_two.move_to(two)
l_bracket.target.next_to(VGroup(new_three, new_two), LEFT)
r_bracket.target.next_to(VGroup(new_three, new_two), RIGHT)
rect.target = BackgroundRectangle(
VGroup(l_bracket.target, r_bracket.target)
)
result = list(map(MoveToTarget, movers))
result += list(map(Write, [minus1, minus2]))
result += list(map(Animation, [
self.matrix.get_mob_matrix()[i, 1-i]
for i in range(2)
]))
self.diag_entries = [
VGroup(three, minus1, lamb),
VGroup(two, minus2, lamb_copy),
]
return result
def show_determinant(self, to_fade = None):
det_text = get_det_text(self.matrix)
equals = OldTex("=").next_to(det_text)
three_minus_lamb, two_minus_lamb = diag_entries = [
entry.copy() for entry in self.diag_entries
]
one = self.matrix.get_mob_matrix()[0, 1].copy()
zero = self.matrix.get_mob_matrix()[1, 0].copy()
for entry in diag_entries + [one, zero]:
entry.target = entry.copy()
lp1, rp1, lp2, rp2 = parens = OldTex("()()")
minus = OldTex("-")
cdot = OldTex("\\cdot")
VGroup(
lp1, three_minus_lamb.target, rp1,
lp2, two_minus_lamb.target, rp2,
minus, one.target, cdot, zero.target
).arrange().next_to(equals)
parens.add_background_rectangle()
new_rect = BackgroundRectangle(VGroup(minus, zero.target))
brace = Brace(new_rect, buff = 0)
brace_text = brace.get_text("Equals 0, so ", "ignore")
brace_text.add_background_rectangle()
brace.target = Brace(parens)
brace_text.target = brace.target.get_text(
"Quadratic polynomial in ", "$\\lambda$"
)
brace_text.target.set_color_by_tex("$\\lambda$", MAROON_B)
brace_text.target.add_background_rectangle()
equals_0 = OldTex("=0")
equals_0.next_to(parens, RIGHT)
equals_0.add_background_rectangle()
final_brace = Brace(VGroup(parens, equals_0))
final_text = OldTex(
"\\lambda", "=2", "\\text{ or }",
"\\lambda", "=3"
)
final_text.set_color_by_tex("\\lambda", MAROON_B)
final_text.next_to(final_brace, DOWN)
lambda_equals_two = VGroup(*final_text[:2]).copy()
lambda_equals_two.add_to_back(BackgroundRectangle(lambda_equals_two))
final_text.add_background_rectangle()
self.play(
Write(det_text),
Write(equals)
)
self.wait()
self.play(
Write(parens),
MoveToTarget(three_minus_lamb),
MoveToTarget(two_minus_lamb),
run_time = 2
)
self.wait()
self.play(
FadeIn(new_rect),
MoveToTarget(one),
MoveToTarget(zero),
Write(minus),
Write(cdot),
run_time = 2
)
self.play(
GrowFromCenter(brace),
Write(brace_text)
)
self.wait()
self.play(*it.chain(
list(map(MoveToTarget, [brace, brace_text])),
list(map(FadeOut, [one, zero, minus, cdot, new_rect]))
))
self.wait()
self.play(Write(equals_0))
self.wait()
self.play(
Transform(brace, final_brace),
Transform(brace_text, final_text)
)
self.wait()
faders = [
det_text, equals, parens,
three_minus_lamb, two_minus_lamb,
brace, brace_text, equals_0,
]
if to_fade is not None:
faders.append(to_fade)
self.play(*it.chain(
list(map(FadeOut, faders)),
[
lambda_equals_two.scale, 1.3,
lambda_equals_two.next_to, self.matrix, DOWN
]
))
self.add_foreground_mobject(lambda_equals_two)
self.lambda_equals_two = lambda_equals_two
self.wait()
def show_diagonally_altered_transform(self):
for entry in self.diag_entries:
lamb = entry[-1]
two = OldTex("2")
two.set_color(lamb.get_color())
two.move_to(lamb)
self.play(Transform(lamb, two))
self.play(*it.chain(
[mob.restore for mob in (self.plane, self.i_hat, self.j_hat)],
list(map(Animation, self.foreground_mobjects)),
))
xy_array = Matrix(["x", "y"])
xy_array.set_color(YELLOW)
zero_array = Matrix([0, 0])
for array in xy_array, zero_array:
array.set_height(self.matrix.get_height())
array.add_to_back(BackgroundRectangle(array))
xy_array.next_to(self.matrix)
equals = OldTex("=").next_to(xy_array)
equals.add_background_rectangle()
zero_array.next_to(equals)
self.play(*list(map(Write, [xy_array, equals, zero_array])))
self.wait()
vectors = VGroup(*[
self.add_vector(u*x*(LEFT+UP), animate = False)
for x in range(4, 0, -1)
for u in [-1, 1]
])
vectors.set_color_by_gradient(MAROON_B, YELLOW)
vectors.save_state()
self.play(
ShowCreation(
vectors,
lag_ratio = 0.5,
run_time = 2
),
*list(map(Animation, self.foreground_mobjects))
)
self.wait()
self.apply_transposed_matrix(
self.t_matrix - 2*np.identity(2)
)
self.wait()
self.play(*it.chain(
[mob.restore for mob in (self.plane, self.i_hat, self.j_hat, vectors)],
list(map(FadeOut, [xy_array, equals, zero_array])),
list(map(Animation, self.foreground_mobjects))
))
def show_unaltered_transform(self):
movers = []
faders = []
for entry in self.diag_entries:
mover = entry[0]
faders += list(entry[1:])
mover.target = mover.copy()
mover.target.move_to(entry)
movers.append(mover)
brace = Brace(self.matrix)
brace_text = brace.get_text("Unaltered matrix")
brace_text.add_background_rectangle()
self.lambda_equals_two.target = brace_text
movers.append(self.lambda_equals_two)
self.play(*it.chain(
list(map(MoveToTarget, movers)),
list(map(FadeOut, faders)),
[GrowFromCenter(brace)]
))
VGroup(*faders).set_fill(opacity = 0)
self.add_foreground_mobject(brace)
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
class ThereMightNotBeEigenvectors(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
There could be
\\emph{no} eigenvectors
""")
self.random_blink(3)
class Rotate90Degrees(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[0, 1], [-1, 0]],
"example_vector_coords" : None,
}
def setup(self):
LinearTransformationScene.setup(self)
matrix = Matrix(self.t_matrix.T)
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(ORIGIN, LEFT)
matrix.to_edge(UP)
matrix.rect = BackgroundRectangle(matrix)
matrix.add_to_back(matrix.rect)
self.add_foreground_mobject(matrix)
self.matrix = matrix
if self.example_vector_coords is not None:
v = self.add_vector(self.example_vector_coords, animate = False)
line = Line(v.get_end()*(-4), v.get_end()*4, color = MAROON_B)
self.play(ShowCreation(line), Animation(v))
self.add_foreground_mobject(line)
def construct(self):
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
class Rotate90DegreesWithVector(Rotate90Degrees):
CONFIG = {
"example_vector_coords" : [1, 2]
}
class SolveRotationEigenvalues(Rotate90Degrees):
def construct(self):
self.apply_transposed_matrix(self.t_matrix, run_time = 0)
self.wait()
diag_entries = [
self.matrix.get_mob_matrix()[i, i]
for i in range(2)
]
off_diag_entries = [
self.matrix.get_mob_matrix()[i, 1-i]
for i in range(2)
]
for entry in diag_entries:
minus_lambda = OldTex("-\\lambda")
minus_lambda.set_color(MAROON_B)
minus_lambda.move_to(entry)
self.play(Transform(entry, minus_lambda))
self.wait()
det_text = get_det_text(self.matrix)
equals = OldTex("=").next_to(det_text)
self.play(*list(map(Write, [det_text, equals])))
self.wait()
minus = OldTex("-")
for entries, sym in (diag_entries, equals), (off_diag_entries, minus):
lp1, rp1, lp2, rp2 = parens = OldTex("()()")
for entry in entries:
entry.target = entry.copy()
group = VGroup(
lp1, entries[0].target, rp1,
lp2, entries[1].target, rp2,
)
group.arrange()
group.next_to(sym)
parens.add_background_rectangle()
self.play(
Write(parens),
*[MoveToTarget(entry.copy()) for entry in entries],
run_time = 2
)
self.wait()
if entries == diag_entries:
minus.next_to(parens)
self.play(Write(minus))
polynomial = OldTex(
"=", "\\lambda^2", "+1=0"
)
polynomial.set_color_by_tex("\\lambda^2", MAROON_B)
polynomial.add_background_rectangle()
polynomial.next_to(equals, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT)
self.play(Write(polynomial))
self.wait()
result = OldTex(
"\\lambda", "= i", "\\text{ or }",
"\\lambda", "= -i"
)
result.set_color_by_tex("\\lambda", MAROON_B)
result.add_background_rectangle()
result.next_to(polynomial, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT)
self.play(Write(result))
self.wait()
interesting_tidbit = OldTexText("""
Interestingly, though, the fact that multiplication by i
in the complex plane looks like a 90 degree rotation is
related to the fact that i is an eigenvalue of this
transformation of 2d real vectors. The specifics of this
are a little beyond what I want to talk about today, but
note that that eigenvalues which are complex numbers
generally correspond to some kind of rotation in the
transformation.
""", alignment = "")
interesting_tidbit.add_background_rectangle()
interesting_tidbit.set_height(FRAME_Y_RADIUS-0.5)
interesting_tidbit.to_corner(DOWN+RIGHT)
self.play(FadeIn(interesting_tidbit))
self.wait()
class ShearExample(RevisitExampleTransformation):
CONFIG = {
"t_matrix" : [[1, 0], [1, 1]],
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_HEIGHT,
"secondary_line_ratio" : 1
},
}
def construct(self):
self.plane.fade()
self.introduce_matrix()
self.point_out_eigenvectors()
lamb = OldTex("\\lambda")
lamb.set_color(MAROON_B)
lamb.next_to(self.matrix, DOWN)
self.play(FadeIn(lamb))
self.play(*self.get_lambda_to_diag_movements(lamb))
self.add_foreground_mobject(*self.get_mobjects_from_last_animation())
self.wait()
self.show_determinant()
def point_out_eigenvectors(self):
vectors = VGroup(*[
self.add_vector(u*x*RIGHT, animate = False)
for x in range(int(FRAME_X_RADIUS)+1, 0, -1)
for u in [-1, 1]
])
vectors.set_color_by_gradient(YELLOW, X_COLOR)
words = VGroup(
OldTexText("Eigenvectors"),
OldTexText("with eigenvalue", "1")
)
for word in words:
word.set_color_by_tex("1", MAROON_B)
word.add_to_back(BackgroundRectangle(word))
words.arrange(DOWN, buff = MED_SMALL_BUFF)
words.next_to(ORIGIN, DOWN+RIGHT, buff = MED_SMALL_BUFF)
self.play(ShowCreation(vectors), run_time = 2)
self.play(Write(words))
self.wait()
def show_determinant(self):
det_text = get_det_text(self.matrix)
equals = OldTex("=").next_to(det_text)
three_minus_lamb, two_minus_lamb = diag_entries = [
entry.copy() for entry in self.diag_entries
]
one = self.matrix.get_mob_matrix()[0, 1].copy()
zero = self.matrix.get_mob_matrix()[1, 0].copy()
for entry in diag_entries + [one, zero]:
entry.target = entry.copy()
lp1, rp1, lp2, rp2 = parens = OldTex("()()")
minus = OldTex("-")
cdot = OldTex("\\cdot")
VGroup(
lp1, three_minus_lamb.target, rp1,
lp2, two_minus_lamb.target, rp2,
minus, one.target, cdot, zero.target
).arrange().next_to(equals)
parens.add_background_rectangle()
new_rect = BackgroundRectangle(VGroup(minus, zero.target))
brace = Brace(new_rect, buff = 0)
brace_text = brace.get_text("Equals 0, so ", "ignore")
brace_text.add_background_rectangle()
brace.target = Brace(parens)
brace_text.target = brace.target.get_text(
"Quadratic polynomial in ", "$\\lambda$"
)
brace_text.target.set_color_by_tex("$\\lambda$", MAROON_B)
brace_text.target.add_background_rectangle()
equals_0 = OldTex("=0")
equals_0.next_to(parens, RIGHT)
equals_0.add_background_rectangle()
final_brace = Brace(VGroup(parens, equals_0))
final_text = OldTex("\\lambda", "=1")
final_text.set_color_by_tex("\\lambda", MAROON_B)
final_text.next_to(final_brace, DOWN)
lambda_equals_two = VGroup(*final_text[:2]).copy()
lambda_equals_two.add_to_back(BackgroundRectangle(lambda_equals_two))
final_text.add_background_rectangle()
self.play(
Write(det_text),
Write(equals)
)
self.wait()
self.play(
Write(parens),
MoveToTarget(three_minus_lamb),
MoveToTarget(two_minus_lamb),
run_time = 2
)
self.wait()
self.play(
FadeIn(new_rect),
MoveToTarget(one),
MoveToTarget(zero),
Write(minus),
Write(cdot),
run_time = 2
)
self.play(
GrowFromCenter(brace),
Write(brace_text)
)
self.wait()
self.play(* list(map(FadeOut, [
one, zero, minus, cdot, new_rect, brace, brace_text
])))
self.wait()
self.play(Write(equals_0))
self.wait()
self.play(
FadeIn(final_brace),
FadeIn(final_text)
)
self.wait()
# faders = [
# det_text, equals, parens,
# three_minus_lamb, two_minus_lamb,
# brace, brace_text, equals_0,
# ]
# if to_fade is not None:
# faders.append(to_fade)
# self.play(*it.chain(
# map(FadeOut, faders),
# [
# lambda_equals_two.scale, 1.3,
# lambda_equals_two.next_to, self.matrix, DOWN
# ]
# ))
# self.add_foreground_mobject(lambda_equals_two)
# self.lambda_equals_two = lambda_equals_two
# self.wait()
class EigenvalueCanHaveMultipleEigenVectors(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
A single eigenvalue can
have more that a line
full of eigenvectors
""")
self.play_student_changes(*["pondering"]*3)
self.random_blink(2)
class ScalingExample(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[2, 0], [0, 2]]
}
def construct(self):
matrix = Matrix(self.t_matrix.T)
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.add_to_back(BackgroundRectangle(matrix))
matrix.next_to(ORIGIN, LEFT)
matrix.to_edge(UP)
words = OldTexText("Scale everything by 2")
words.add_background_rectangle()
words.next_to(matrix, RIGHT)
self.add_foreground_mobject(matrix, words)
for coords in [2, 1], [-2.5, -1], [1, -1]:
self.add_vector(coords, color = random_color())
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
class IntroduceEigenbasis(TeacherStudentsScene):
def construct(self):
words1, words2 = list(map(TexText, [
"Finish with ``eigenbasis.''",
"""Make sure you've
watched the last video"""
]))
words1.set_color(YELLOW)
self.teacher_says(words1)
self.play_student_changes(
"pondering", "raise_right_hand", "erm"
)
self.random_blink()
new_words = VGroup(words1.copy(), words2)
new_words.arrange(DOWN, buff = MED_SMALL_BUFF)
new_words.scale(0.8)
self.teacher.bubble.add_content(new_words)
self.play(
self.get_teacher().change_mode, "sassy",
Write(words2),
Transform(words1, new_words[0])
)
student = self.get_students()[0]
self.play(
student.change_mode, "guilty",
student.look, LEFT
)
self.random_blink(2)
class BasisVectorsAreEigenvectors(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[-1, 0], [0, 2]]
}
def construct(self):
matrix = Matrix(self.t_matrix.T)
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(ORIGIN, LEFT)
matrix.to_edge(UP)
words = OldTexText(
"What if both basis vectors \\\\",
"are eigenvectors?"
)
for word in words:
word.add_to_back(BackgroundRectangle(word))
words.to_corner(UP+RIGHT)
self.play(Write(words))
self.add_foreground_mobject(words)
self.wait()
self.apply_transposed_matrix([self.t_matrix[0], [0, 1]])
self.wait()
self.apply_transposed_matrix([[1, 0], self.t_matrix[1]])
self.wait()
i_coords = Matrix(self.t_matrix[0])
i_coords.next_to(self.i_hat.get_end(), DOWN+LEFT)
i_coords.set_color(X_COLOR)
j_coords = Matrix(self.t_matrix[1])
j_coords.next_to(self.j_hat.get_end(), RIGHT)
j_coords.set_color(Y_COLOR)
for array in matrix, i_coords, j_coords:
array.rect = BackgroundRectangle(array)
array.add_to_back(array.rect)
self.play(*list(map(Write, [i_coords, j_coords])))
self.wait()
self.play(
Transform(i_coords.rect, matrix.rect),
Transform(i_coords.get_brackets(), matrix.get_brackets()),
i_coords.get_entries().move_to, VGroup(
*matrix.get_mob_matrix()[:,0]
)
)
self.play(
FadeOut(j_coords.rect),
FadeOut(j_coords.get_brackets()),
j_coords.get_entries().move_to, VGroup(
*matrix.get_mob_matrix()[:,1]
)
)
self.remove(i_coords, j_coords)
self.add(matrix)
self.wait()
diag_entries = VGroup(*[
matrix.get_mob_matrix()[i, i]
for i in range(2)
])
off_diag_entries = VGroup(*[
matrix.get_mob_matrix()[1-i, i]
for i in range(2)
])
for entries in diag_entries, off_diag_entries:
self.play(
entries.scale, 1.3,
entries.set_color, YELLOW,
run_time = 2,
rate_func = there_and_back
)
self.wait()
class DefineDiagonalMatrix(Scene):
def construct(self):
n_dims = 4
numerical_matrix = np.identity(n_dims, dtype = 'int')
for x in range(n_dims):
numerical_matrix[x, x] = random.randint(-9, 9)
matrix = Matrix(numerical_matrix)
diag_entries = VGroup(*[
matrix.get_mob_matrix()[i,i]
for i in range(n_dims)
])
off_diag_entries = VGroup(*[
matrix.get_mob_matrix()[i, j]
for i in range(n_dims)
for j in range(n_dims)
if i != j
])
title = OldTexText("``Diagonal matrix''")
title.to_edge(UP)
self.add(matrix)
self.wait()
for entries in off_diag_entries, diag_entries:
self.play(
entries.scale, 1.1,
entries.set_color, YELLOW,
rate_func = there_and_back,
)
self.wait()
self.play(Write(title))
self.wait()
self.play(
matrix.set_column_colors,
X_COLOR, Y_COLOR, Z_COLOR, YELLOW
)
self.wait()
self.play(diag_entries.set_color, MAROON_B)
self.play(
diag_entries.scale, 1.1,
rate_func = there_and_back,
)
self.wait()
class RepeatedMultiplicationInAction(Scene):
def construct(self):
vector = Matrix(["x", "y"])
vector.set_color(YELLOW)
vector.scale(1.2)
vector.shift(RIGHT)
matrix, scalars = self.get_matrix(vector)
#First multiplication
for v_entry, scalar in zip(vector.get_entries(), scalars):
scalar.target = scalar.copy()
scalar.target.next_to(v_entry, LEFT)
l_bracket = vector.get_brackets()[0]
l_bracket.target = l_bracket.copy()
l_bracket.target.next_to(VGroup(*[
scalar.target for scalar in scalars
]), LEFT)
self.add(vector)
self.play(*list(map(FadeIn, [matrix]+scalars)))
self.wait()
self.play(
FadeOut(matrix),
*list(map(MoveToTarget, scalars + [l_bracket]))
)
self.wait()
#nth multiplications
for scalar in scalars:
scalar.exp = VectorizedPoint(scalar.get_corner(UP+RIGHT))
scalar.exp.shift(SMALL_BUFF*RIGHT/2.)
for new_exp in range(2, 6):
matrix, new_scalars = self.get_matrix(vector)
new_exp_mob = OldTex(str(new_exp)).scale(0.7)
movers = []
to_remove = []
for v_entry, scalar, new_scalar in zip(vector.get_entries(), scalars, new_scalars):
scalar.exp.target = new_exp_mob.copy()
scalar.exp.target.set_color(scalar.get_color())
scalar.exp.target.move_to(scalar.exp, aligned_edge = LEFT)
new_scalar.target = scalar.exp.target
scalar.target = scalar.copy()
VGroup(scalar.target, scalar.exp.target).next_to(
v_entry, LEFT, aligned_edge = DOWN
)
movers += [scalar, scalar.exp, new_scalar]
to_remove.append(new_scalar)
l_bracket.target.next_to(VGroup(*[
scalar.target for scalar in scalars
]), LEFT)
movers.append(l_bracket)
self.play(*list(map(FadeIn, [matrix]+new_scalars)))
self.wait()
self.play(
FadeOut(matrix),
*list(map(MoveToTarget, movers))
)
self.remove(*to_remove)
self.wait()
def get_matrix(self, vector):
matrix = Matrix([[3, 0], [0, 2]])
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(vector, LEFT)
scalars = [matrix.get_mob_matrix()[i, i] for i in range(2)]
matrix.remove(*scalars)
return matrix, scalars
class RepeatedMultilpicationOfMatrices(Scene):
CONFIG = {
"matrix" : [[3, 0], [0, 2]],
"diagonal" : True,
}
def construct(self):
vector = Matrix(["x", "y"])
vector.set_color(YELLOW)
matrix = Matrix(self.matrix)
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrices = VGroup(*[
matrix.copy(),
OldTex("\\dots\\dots"),
matrix.copy(),
matrix.copy(),
matrix.copy(),
])
last_matrix = matrices[-1]
group = VGroup(*list(matrices) + [vector])
group.arrange()
brace = Brace(matrices)
brace_text = brace.get_text("100", "times")
hundred = brace_text[0]
hundred_copy = hundred.copy()
self.add(vector)
for matrix in reversed(list(matrices)):
self.play(FadeIn(matrix))
self.wait()
self.play(
GrowFromCenter(brace),
Write(brace_text)
)
self.wait()
if self.diagonal:
last_matrix.target = last_matrix.copy()
for i, hund in enumerate([hundred, hundred_copy]):
entry = last_matrix.target.get_mob_matrix()[i, i]
hund.target = hund.copy()
hund.target.scale(0.5)
hund.target.next_to(entry, UP+RIGHT, buff = 0)
hund.target.set_color(entry.get_color())
VGroup(hund.target, entry).move_to(entry, aligned_edge = DOWN)
lb, rb = last_matrix.target.get_brackets()
lb.shift(SMALL_BUFF*LEFT)
rb.shift(SMALL_BUFF*RIGHT)
VGroup(
last_matrix.target, hundred.target, hundred_copy.target
).next_to(vector, LEFT)
self.play(*it.chain(
list(map(FadeOut, [brace, brace_text[1]] + list(matrices[:-1]))),
list(map(MoveToTarget, [hundred, hundred_copy, last_matrix]))
), run_time = 2)
self.wait()
else:
randy = Randolph().to_corner()
self.play(FadeIn(randy))
self.play(randy.change_mode, "angry")
self.play(Blink(randy))
self.wait()
self.play(Blink(randy))
self.wait()
class RepeatedMultilpicationOfNonDiagonalMatrices(RepeatedMultilpicationOfMatrices):
CONFIG = {
"matrix" : [[3, 4], [1, 1]],
"diagonal" : False,
}
class WhatAreTheOddsOfThat(TeacherStudentsScene):
def construct(self):
self.student_says("""
Sure, but what are the
odds of that happening?
""")
self.random_blink()
self.play_student_changes("pondering")
self.random_blink(3)
class LastVideo(Scene):
def construct(self):
title = OldTexText("Last chapter: Change of basis")
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN, buff = MED_SMALL_BUFF)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
class ChangeToEigenBasis(ExampleTranformationScene):
CONFIG = {
"show_basis_vectors" : False,
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_HEIGHT,
"secondary_line_ratio" : 0
},
}
def construct(self):
self.plane.fade()
self.introduce_eigenvectors()
self.write_change_of_basis_matrix()
self.ask_about_power()
def introduce_eigenvectors(self):
x_vectors, v_vectors = [
VGroup(*[
self.add_vector(u*x*vect, animate = False)
for x in range(num, 0, -1)
for u in [-1, 1]
])
for vect, num in [(RIGHT, 7), (UP+LEFT, 4)]
]
x_vectors.set_color_by_gradient(YELLOW, X_COLOR)
v_vectors.set_color_by_gradient(MAROON_B, YELLOW)
self.remove(x_vectors, v_vectors)
self.play(ShowCreation(x_vectors, run_time = 2))
self.play(ShowCreation(v_vectors, run_time = 2))
self.wait()
self.plane.save_state()
self.apply_transposed_matrix(
self.t_matrix,
rate_func = there_and_back,
path_arc = 0
)
x_vector = x_vectors[-1]
v_vector = v_vectors[-1]
x_vectors.remove(x_vector)
v_vectors.remove(v_vector)
words = OldTexText("Eigenvectors span space")
new_words = OldTexText("Use eigenvectors as basis")
for text in words, new_words:
text.add_background_rectangle()
text.next_to(ORIGIN, DOWN+LEFT, buff = MED_SMALL_BUFF)
# text.to_edge(RIGHT)
self.play(Write(words))
self.play(
FadeOut(x_vectors),
FadeOut(v_vectors),
Animation(x_vector),
Animation(v_vector),
)
self.wait()
self.play(Transform(words, new_words))
self.wait()
self.b1, self.b2 = x_vector, v_vector
self.moving_vectors = [self.b1, self.b2]
self.to_fade = [words]
def write_change_of_basis_matrix(self):
b1, b2 = self.b1, self.b2
for vect in b1, b2:
vect.coords = vector_coordinate_label(vect)
vect.coords.set_color(vect.get_color())
vect.entries = vect.coords.get_entries()
vect.entries.target = vect.entries.copy()
b1.coords.next_to(b1.get_end(), DOWN+RIGHT)
b2.coords.next_to(b2.get_end(), LEFT)
for vect in b1, b2:
self.play(Write(vect.coords))
self.wait()
cob_matrix = Matrix(np.array([
list(vect.entries.target)
for vect in (b1, b2)
]).T)
cob_matrix.rect = BackgroundRectangle(cob_matrix)
cob_matrix.add_to_back(cob_matrix.rect)
cob_matrix.set_height(self.matrix.get_height())
cob_matrix.next_to(self.matrix)
brace = Brace(cob_matrix)
brace_text = brace.get_text("Change of basis matrix")
brace_text.next_to(brace, DOWN, aligned_edge = LEFT)
brace_text.add_background_rectangle()
copies = [vect.coords.copy() for vect in (b1, b2)]
self.to_fade += copies
self.add(*copies)
self.play(
Transform(b1.coords.rect, cob_matrix.rect),
Transform(b1.coords.get_brackets(), cob_matrix.get_brackets()),
MoveToTarget(b1.entries)
)
to_remove = self.get_mobjects_from_last_animation()
self.play(MoveToTarget(b2.entries))
to_remove += self.get_mobjects_from_last_animation()
self.remove(*to_remove)
self.add(cob_matrix)
self.to_fade += [b2.coords]
self.play(
GrowFromCenter(brace),
Write(brace_text)
)
self.to_fade += [brace, brace_text]
self.wait()
inv_cob = cob_matrix.copy()
inv_cob.target = inv_cob.copy()
neg_1 = OldTex("-1")
neg_1.add_background_rectangle()
inv_cob.target.next_to(
self.matrix, LEFT, buff = neg_1.get_width()+2*SMALL_BUFF
)
neg_1.next_to(
inv_cob.target.get_corner(UP+RIGHT),
RIGHT,
)
self.play(
MoveToTarget(inv_cob, path_arc = -np.pi/2),
Write(neg_1)
)
self.wait()
self.add_foreground_mobject(cob_matrix, inv_cob, neg_1)
self.play(*list(map(FadeOut, self.to_fade)))
self.wait()
self.play(FadeOut(self.plane))
cob_transform = self.get_matrix_transformation([[1, 0], [-1, 1]])
ApplyMethod(self.plane.apply_function, cob_transform).update(1)
self.planes.set_color(BLUE_D)
self.plane.axes.set_color(WHITE)
self.play(
FadeIn(self.plane),
*list(map(Animation, self.foreground_mobjects+self.moving_vectors))
)
self.add(self.plane.copy().set_color(GREY).set_stroke(width = 2))
self.apply_transposed_matrix(self.t_matrix)
equals = OldTex("=").next_to(cob_matrix)
final_matrix = Matrix([[3, 0], [0, 2]])
final_matrix.add_to_back(BackgroundRectangle(final_matrix))
for i in range(2):
final_matrix.get_mob_matrix()[i, i].set_color(MAROON_B)
final_matrix.next_to(equals, RIGHT)
self.play(
Write(equals),
Write(final_matrix)
)
self.wait()
eigenbasis = OldTexText("``Eigenbasis''")
eigenbasis.add_background_rectangle()
eigenbasis.next_to(ORIGIN, DOWN)
self.play(Write(eigenbasis))
self.wait()
def ask_about_power(self):
morty = Mortimer()
morty.to_edge(DOWN).shift(LEFT)
bubble = morty.get_bubble(
"speech", height = 3, width = 5, direction = RIGHT
)
bubble.set_fill(BLACK, opacity = 1)
matrix_copy = self.matrix.copy().scale(0.7)
hundred = OldTex("100").scale(0.7)
hundred.next_to(matrix_copy.get_corner(UP+RIGHT), RIGHT)
compute = OldTexText("Compute")
compute.next_to(matrix_copy, LEFT, buff = MED_SMALL_BUFF)
words = VGroup(compute, matrix_copy, hundred)
bubble.add_content(words)
self.play(FadeIn(morty))
self.play(
morty.change_mode, "speaking",
ShowCreation(bubble),
Write(words)
)
for x in range(2):
self.play(Blink(morty))
self.wait(2)
class CannotDoWithWithAllTransformations(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
Not all matrices
can become diagonal
""")
self.play_student_changes(*["tired"]*3)
self.random_blink(2)
|
|
from manim_imports_ext import *
from _2016.eola.chapter1 import plane_wave_homotopy
class OpeningQuote(Scene):
def construct(self):
words = OldTexText("""
Mathematics requires a small dose, not of genius,
but of an imaginative freedom which, in a larger
dose, would be insanity.
""")
words.to_edge(UP)
for mob in words.submobjects[49:49+18]:
mob.set_color(GREEN)
author = OldTexText("-Angus K. Rodgers")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = 0.5)
self.play(FadeIn(words))
self.wait(3)
self.play(Write(author, run_time = 3))
self.wait()
class CoordinatesWereFamiliar(TeacherStudentsScene):
def construct(self):
self.setup()
self.student_says("I know this already")
self.random_blink()
self.teacher_says("Ah, but there is a subtlety")
self.random_blink()
self.wait()
class CoordinatesAsScalars(VectorScene):
CONFIG = {
"vector_coords" : [3, -2]
}
def construct(self):
self.lock_in_faded_grid()
vector = self.add_vector(self.vector_coords)
array, x_line, y_line = self.vector_to_coords(vector)
self.add(array)
self.wait()
new_array = self.general_idea_of_scalars(array, vector)
self.scale_basis_vectors(new_array)
self.show_symbolic_sum(new_array, vector)
def general_idea_of_scalars(self, array, vector):
starting_mobjects = self.get_mobjects()
title = OldTexText("Think of each coordinate as a scalar")
title.to_edge(UP)
x, y = array.get_mob_matrix().flatten()
new_x = x.copy().scale(2).set_color(X_COLOR)
new_x.move_to(3*LEFT+2*UP)
new_y = y.copy().scale(2).set_color(Y_COLOR)
new_y.move_to(3*RIGHT+2*UP)
i_hat, j_hat = self.get_basis_vectors()
new_i_hat = Vector(
self.vector_coords[0]*i_hat.get_end(),
color = X_COLOR
)
new_j_hat = Vector(
self.vector_coords[1]*j_hat.get_end(),
color = Y_COLOR
)
VMobject(i_hat, new_i_hat).shift(3*LEFT)
VMobject(j_hat, new_j_hat).shift(3*RIGHT)
new_array = Matrix([new_x.copy(), new_y.copy()])
new_array.scale(0.5)
new_array.shift(
-new_array.get_boundary_point(-vector.get_end()) + \
1.1*vector.get_end()
)
self.remove(*starting_mobjects)
self.play(
Transform(x, new_x),
Transform(y, new_y),
Write(title),
)
self.play(FadeIn(i_hat), FadeIn(j_hat))
self.wait()
self.play(
Transform(i_hat, new_i_hat),
Transform(j_hat, new_j_hat),
run_time = 3
)
self.wait()
starting_mobjects.remove(array)
new_x, new_y = new_array.get_mob_matrix().flatten()
self.play(
Transform(x, new_x),
Transform(y, new_y),
FadeOut(i_hat),
FadeOut(j_hat),
Write(new_array.get_brackets()),
FadeIn(VMobject(*starting_mobjects)),
FadeOut(title)
)
self.remove(x, y)
self.add(new_array)
return new_array
def scale_basis_vectors(self, new_array):
i_hat, j_hat = self.get_basis_vectors()
self.add_vector(i_hat)
i_hat_label = self.label_vector(
i_hat, "\\hat{\\imath}",
color = X_COLOR,
label_scale_factor = 1
)
self.add_vector(j_hat)
j_hat_label = self.label_vector(
j_hat, "\\hat{\\jmath}",
color = Y_COLOR,
label_scale_factor = 1
)
self.wait()
x, y = new_array.get_mob_matrix().flatten()
for coord, v, label, factor, shift_right in [
(x, i_hat, i_hat_label, self.vector_coords[0], False),
(y, j_hat, j_hat_label, self.vector_coords[1], True)
]:
faded_v = v.copy().fade(0.7)
scaled_v = Vector(factor*v.get_end(), color = v.get_color())
scaled_label = VMobject(coord.copy(), label.copy())
scaled_label.arrange(RIGHT, buff = 0.1)
scaled_label.move_to(label, DOWN+RIGHT)
scaled_label.shift((scaled_v.get_end()-v.get_end())/2)
coord_copy = coord.copy()
self.play(
Transform(v.copy(), faded_v),
Transform(v, scaled_v),
Transform(VMobject(coord_copy, label), scaled_label),
)
self.wait()
if shift_right:
group = VMobject(v, coord_copy, label)
self.play(ApplyMethod(
group.shift, self.vector_coords[0]*RIGHT
))
self.wait()
def show_symbolic_sum(self, new_array, vector):
new_mob = OldTex([
"(%d)\\hat{\\imath}"%self.vector_coords[0],
"+",
"(%d)\\hat{\\jmath}"%self.vector_coords[1]
])
new_mob.move_to(new_array)
new_mob.shift_onto_screen()
i_hat, plus, j_hat = new_mob.split()
i_hat.set_color(X_COLOR)
j_hat.set_color(Y_COLOR)
self.play(Transform(new_array, new_mob))
self.wait()
class CoordinatesAsScalarsExample2(CoordinatesAsScalars):
CONFIG = {
"vector_coords" : [-5, 2]
}
def construct(self):
self.lock_in_faded_grid()
basis_vectors = self.get_basis_vectors()
labels = self.get_basis_vector_labels()
self.add(*basis_vectors)
self.add(*labels)
text = OldTexText("""
$\\hat{\\imath}$ and $\\hat{\\jmath}$
are the ``basis vectors'' \\\\
of the $xy$ coordinate system
""")
text.set_width(FRAME_X_RADIUS-1)
text.to_corner(UP+RIGHT)
VMobject(*text.split()[:2]).set_color(X_COLOR)
VMobject(*text.split()[5:7]).set_color(Y_COLOR)
self.play(Write(text))
self.wait(2)
self.remove(*basis_vectors + labels)
CoordinatesAsScalars.construct(self)
class WhatIfWeChoseADifferentBasis(Scene):
def construct(self):
self.play(Write(
"What if we chose different basis vectors?",
run_time = 2
))
self.wait(2)
class ShowVaryingLinearCombinations(VectorScene):
CONFIG = {
"vector1" : [1, 2],
"vector2" : [3, -1],
"vector1_color" : MAROON_C,
"vector2_color" : BLUE,
"vector1_label" : "v",
"vector2_label" : "w",
"sum_color" : PINK,
"scalar_pairs" : [
(1.5, 0.6),
(0.7, 1.3),
(-1, -1.5),
(1, -1.13),
(1.25, 0.5),
(-0.8, 1.3),
],
"leave_sum_vector_copies" : False,
"start_with_non_sum_scaling" : True,
"finish_with_standard_basis_comparison" : True,
"finish_by_drawing_lines" : False,
}
def construct(self):
self.lock_in_faded_grid()
v1 = self.add_vector(self.vector1, color = self.vector1_color)
v2 = self.add_vector(self.vector2, color = self.vector2_color)
v1_label = self.label_vector(
v1, self.vector1_label, color = self.vector1_color,
buff_factor = 3
)
v2_label = self.label_vector(
v2, self.vector2_label, color = self.vector2_color,
buff_factor = 3
)
label_anims = [
MaintainPositionRelativeTo(label, v)
for v, label in [(v1, v1_label), (v2, v2_label)]
]
scalar_anims = self.get_scalar_anims(v1, v2, v1_label, v2_label)
self.last_scalar_pair = (1, 1)
if self.start_with_non_sum_scaling:
self.initial_scaling(v1, v2, label_anims, scalar_anims)
self.show_sum(v1, v2, label_anims, scalar_anims)
self.scale_with_sum(v1, v2, label_anims, scalar_anims)
if self.finish_with_standard_basis_comparison:
self.standard_basis_comparison(label_anims, scalar_anims)
if self.finish_by_drawing_lines:
self.draw_lines(v1, v2, label_anims, scalar_anims)
def get_scalar_anims(self, v1, v2, v1_label, v2_label):
def get_val_func(vect):
original_vect = np.array(vect.get_end()-vect.get_start())
square_norm = get_norm(original_vect)**2
return lambda a : np.dot(
original_vect, vect.get_end()-vect.get_start()
)/square_norm
return [
RangingValues(
tracked_mobject = label,
tracked_mobject_next_to_kwargs = {
"direction" : LEFT,
"buff" : 0.1
},
scale_factor = 0.75,
value_function = get_val_func(v)
)
for v, label in [(v1, v1_label), (v2, v2_label)]
]
def get_rate_func_pair(self):
return [
squish_rate_func(smooth, a, b)
for a, b in [(0, 0.7), (0.3, 1)]
]
def initial_scaling(self, v1, v2, label_anims, scalar_anims):
scalar_pair = self.scalar_pairs.pop(0)
anims = [
ApplyMethod(v.scale, s, rate_func = rf)
for v, s, rf in zip(
[v1, v2],
scalar_pair,
self.get_rate_func_pair()
)
]
anims += [
ApplyMethod(v.copy().fade, 0.7)
for v in (v1, v2)
]
anims += label_anims + scalar_anims
self.play(*anims, **{"run_time" : 2})
self.wait()
self.last_scalar_pair = scalar_pair
def show_sum(self, v1, v2, label_anims, scalar_anims):
self.play(
ApplyMethod(v2.shift, v1.get_end()),
*label_anims + scalar_anims
)
self.sum_vector = self.add_vector(
v2.get_end(), color = self.sum_color
)
self.wait()
def scale_with_sum(self, v1, v2, label_anims, scalar_anims):
v2_anim, sum_anim = self.get_sum_animations(v1, v2)
while self.scalar_pairs:
scalar_pair = self.scalar_pairs.pop(0)
anims = [
ApplyMethod(v.scale, s/s_old, rate_func = rf)
for v, s, s_old, rf in zip(
[v1, v2],
scalar_pair,
self.last_scalar_pair,
self.get_rate_func_pair()
)
]
anims += [v2_anim, sum_anim] + label_anims + scalar_anims
self.play(*anims, **{"run_time" : 2})
if self.leave_sum_vector_copies:
self.add(self.sum_vector.copy())
self.wait()
self.last_scalar_pair = scalar_pair
def get_sum_animations(self, v1, v2):
v2_anim = UpdateFromFunc(
v2, lambda m : m.shift(v1.get_end()-m.get_start())
)
sum_anim = UpdateFromFunc(
self.sum_vector,
lambda v : v.put_start_and_end_on(v1.get_start(), v2.get_end())
)
return v2_anim, sum_anim
def standard_basis_comparison(self, label_anims, scalar_anims):
everything = self.get_mobjects()
everything.remove(self.sum_vector)
everything = VMobject(*everything)
alt_coords = [a.mobject for a in scalar_anims]
array = Matrix([
mob.copy().set_color(color)
for mob, color in zip(
alt_coords,
[self.vector1_color, self.vector2_color]
)
])
array.scale(0.8)
array.to_edge(UP)
array.shift(RIGHT)
brackets = array.get_brackets()
anims = [
Transform(*pair)
for pair in zip(alt_coords, array.get_mob_matrix().flatten())
]
# anims += [
# FadeOut(a.mobject)
# for a in label_anims
# ]
self.play(*anims + [Write(brackets)])
self.wait()
self.remove(brackets, *alt_coords)
self.add(array)
self.play(
FadeOut(everything),
Animation(array),
)
self.add_axes(animate = True)
ij_array, x_line, y_line = self.vector_to_coords(
self.sum_vector, integer_labels = False
)
self.add(ij_array, x_line, y_line)
x, y = ij_array.get_mob_matrix().flatten()
self.play(
ApplyMethod(x.set_color, X_COLOR),
ApplyMethod(y.set_color, Y_COLOR),
)
neq = OldTex("\\neq")
neq.next_to(array)
self.play(
ApplyMethod(ij_array.next_to, neq),
Write(neq)
)
self.wait()
def draw_lines(self, v1, v2, label_anims, scalar_anims):
sum_anims = self.get_sum_animations(v1, v2)
aux_anims = list(sum_anims) + label_anims + scalar_anims
scale_factor = 2
for w1, w2 in (v2, v1), (v1, v2):
w1_vect = w1.get_end()-w1.get_start()
w2_vect = w2.get_end()-w2.get_start()
for num in scale_factor, -1, -1./scale_factor:
curr_tip = self.sum_vector.get_end()
line = Line(ORIGIN, curr_tip)
self.play(
ApplyMethod(w2.scale, num),
UpdateFromFunc(
line, lambda l : l.put_start_and_end_on(curr_tip, self.sum_vector.get_end())
),
*aux_anims
)
self.add(line, v2)
self.wait()
class AltShowVaryingLinearCombinations(ShowVaryingLinearCombinations):
CONFIG = {
"scalar_pairs" : [
(1.5, 0.3),
(0.64, 1.3),
(-1, -1.5),
(1, 1.13),
(1.25, 0.5),
(-0.8, 1.14),
],
"finish_with_standard_basis_comparison" : False
}
class NameLinearCombinations(Scene):
def construct(self):
v_color = MAROON_C
w_color = BLUE
words = OldTexText([
"``Linear combination'' of",
"$\\vec{\\textbf{v}}$",
"and",
"$\\vec{\\textbf{w}}$"
])
words.split()[1].set_color(v_color)
words.split()[3].set_color(w_color)
words.set_width(FRAME_WIDTH - 1)
words.to_edge(UP)
equation = OldTex([
"a", "\\vec{\\textbf{v}}", "+", "b", "\\vec{\\textbf{w}}"
])
equation.arrange(buff = 0.1, aligned_edge = DOWN)
equation.split()[1].set_color(v_color)
equation.split()[4].set_color(w_color)
a, b = np.array(equation.split())[[0, 3]]
equation.scale(2)
equation.next_to(words, DOWN, buff = 1)
scalars_word = OldTexText("Scalars")
scalars_word.scale(1.5)
scalars_word.next_to(equation, DOWN, buff = 2)
arrows = [
Arrow(scalars_word, letter)
for letter in (a, b)
]
self.add(equation)
self.play(Write(words))
self.play(
ShowCreation(VMobject(*arrows)),
Write(scalars_word)
)
self.wait(2)
class LinearCombinationsDrawLines(ShowVaryingLinearCombinations):
CONFIG = {
"scalar_pairs" : [
(1.5, 0.6),
(0.7, 1.3),
(1, 1),
],
"start_with_non_sum_scaling" : False,
"finish_with_standard_basis_comparison" : False,
"finish_by_drawing_lines" : True,
}
class LinearCombinationsWithSumCopies(ShowVaryingLinearCombinations):
CONFIG = {
"scalar_pairs" : [
(1.5, 0.6),
(0.7, 1.3),
(-1, -1.5),
(1, -1.13),
(1.25, 0.5),
(-0.8, 1.3),
(-0.9, 1.4),
(0.9, 2),
],
"leave_sum_vector_copies" : True,
"start_with_non_sum_scaling" : False,
"finish_with_standard_basis_comparison" : False,
"finish_by_drawing_lines" : False,
}
class LinearDependentVectors(ShowVaryingLinearCombinations):
CONFIG = {
"vector1" : [1, 2],
"vector2" : [0.5, 1],
"vector1_color" : MAROON_C,
"vector2_color" : BLUE,
"vector1_label" : "v",
"vector2_label" : "w",
"sum_color" : PINK,
"scalar_pairs" : [
(1.5, 0.6),
(0.7, 1.3),
(-1, -1.5),
(1.25, 0.5),
(-0.8, 1.3),
(-0.9, 1.4),
(0.9, 2),
],
"leave_sum_vector_copies" : False,
"start_with_non_sum_scaling" : False,
"finish_with_standard_basis_comparison" : False,
"finish_by_drawing_lines" : False,
}
def get_sum_animations(self, v1, v2):
v2_anim, sum_anim = ShowVaryingLinearCombinations.get_sum_animations(self, v1, v2)
self.remove(self.sum_vector)
return v2_anim, Animation(VMobject())
class WhenVectorsLineUp(LinearDependentVectors):
CONFIG = {
"vector1" : [3, 2],
"vector2" : [1.5, 1],
"scalar_pairs" : [
(1.5, 0.6),
(0.7, 1.3),
],
}
class AnimationUnderSpanDefinition(ShowVaryingLinearCombinations):
CONFIG = {
"scalar_pairs" : [
(1.5, 0.6),
(0.7, 1.3),
(-1, -1.5),
(1.25, 0.5),
(0.8, 1.3),
(0.93, -1.4),
(-2, -0.5),
],
"leave_sum_vector_copies" : True,
"start_with_non_sum_scaling" : False,
"finish_with_standard_basis_comparison" : False,
"finish_by_drawing_lines" : False,
}
class BothVectorsCouldBeZero(VectorScene):
def construct(self):
plane = self.add_plane()
plane.fade(0.7)
v1 = self.add_vector([1, 2], color = MAROON_C)
v2 = self.add_vector([3, -1], color = BLUE)
self.play(Transform(v1, Dot(ORIGIN)))
self.play(Transform(v2, Dot(ORIGIN)))
self.wait()
class DefineSpan(Scene):
def construct(self):
v_color = MAROON_C
w_color = BLUE
definition = OldTexText("""
The ``span'' of $\\vec{\\textbf{v}}$ and
$\\vec{\\textbf{w}}$ is the \\\\ set of all their
linear combinations.
""")
definition.set_width(FRAME_WIDTH-1)
definition.to_edge(UP)
def_mobs = np.array(definition.split())
VMobject(*def_mobs[4:4+4]).set_color(PINK)
VMobject(*def_mobs[11:11+2]).set_color(v_color)
VMobject(*def_mobs[16:16+2]).set_color(w_color)
VMobject(*def_mobs[-19:-1]).set_color(YELLOW)
equation = OldTex([
"a", "\\vec{\\textbf{v}}", "+", "b", "\\vec{\\textbf{w}}"
])
equation.arrange(buff = 0.1, aligned_edge = DOWN)
equation.split()[1].set_color(v_color)
equation.split()[4].set_color(w_color)
a, b = np.array(equation.split())[[0, 3]]
equation.scale(2)
equation.next_to(definition, DOWN, buff = 1)
vary_words = OldTexText(
"Let $a$ and $b$ vary \\\\ over all real numbers"
)
vary_words.scale(1.5)
vary_words.next_to(equation, DOWN, buff = 2)
arrows = [
Arrow(vary_words, letter)
for letter in (a, b)
]
self.play(Write(definition))
self.play(Write(equation))
self.wait()
self.play(
FadeIn(vary_words),
ShowCreation(VMobject(*arrows))
)
self.wait()
class VectorsVsPoints(Scene):
def construct(self):
self.play(Write("Vectors vs. Points"))
self.wait(2)
class VectorsToDotsScene(VectorScene):
CONFIG = {
"num_vectors" : 16,
"start_color" : PINK,
"end_color" : BLUE_E,
}
def construct(self):
self.lock_in_faded_grid()
vectors = self.get_vectors()
colors = Color(self.start_color).range_to(
self.end_color, len(vectors)
)
for vect, color in zip(vectors, colors):
vect.set_color(color)
prototype_vector = vectors[3*len(vectors)/4]
vector_group = VMobject(*vectors)
self.play(
ShowCreation(
vector_group,
run_time = 3
)
)
vectors.sort(key=lambda v: v.get_length())
self.add(*vectors)
def v_to_dot(vector):
return Dot(vector.get_end(), fill_color = vector.get_stroke_color())
self.wait()
vectors.remove(prototype_vector)
self.play(*list(map(FadeOut, vectors))+[Animation(prototype_vector)])
self.remove(vector_group)
self.add(prototype_vector)
self.wait()
self.play(Transform(prototype_vector, v_to_dot(prototype_vector)))
self.wait()
self.play(*list(map(FadeIn, vectors)) + [Animation(prototype_vector)])
rate_functions = [
squish_rate_func(smooth, float(x)/(len(vectors)+2), 1)
for x in range(len(vectors))
]
self.play(*[
Transform(v, v_to_dot(v), rate_func = rf, run_time = 2)
for v, rf in zip(vectors, rate_functions)
])
self.wait()
self.remove(prototype_vector)
self.play_final_animation(vectors, rate_functions)
self.wait()
def get_vectors(self):
raise Exception("Not implemented")
def play_final_animation(self, vectors, rate_functions):
raise Exception("Not implemented")
class VectorsOnALine(VectorsToDotsScene):
def get_vectors(self):
return [
Vector(a*np.array([1.5, 1]))
for a in np.linspace(
-FRAME_Y_RADIUS, FRAME_Y_RADIUS, self.num_vectors
)
]
def play_final_animation(self, vectors, rate_functions):
line_copies = [
Line(vectors[0].get_end(), vectors[-1].get_end())
for v in vectors
]
self.play(*[
Transform(v, mob, rate_func = rf, run_time = 2)
for v, mob, rf in zip(vectors, line_copies, rate_functions)
])
class VectorsInThePlane(VectorsToDotsScene):
CONFIG = {
"num_vectors" : 16,
"start_color" : PINK,
"end_color" : BLUE_E,
}
def get_vectors(self):
return [
Vector([x, y])
for x in np.arange(-int(FRAME_X_RADIUS)-0.5, int(FRAME_X_RADIUS)+0.5)
for y in np.arange(-int(FRAME_Y_RADIUS)-0.5, int(FRAME_Y_RADIUS)+0.5)
]
def play_final_animation(self, vectors, rate_functions):
h_line = Line(
FRAME_X_RADIUS*RIGHT, FRAME_X_RADIUS*LEFT,
stroke_width = 0.5,
color = BLUE_E
)
v_line = Line(
FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN,
stroke_width = 0.5,
color = BLUE_E
)
line_pairs = [
VMobject(h_line.copy().shift(y), v_line.copy().shift(x))
for v in vectors
for x, y, z in [v.get_center()]
]
plane = NumberPlane()
self.play(
ShowCreation(plane),
*[
Transform(v, p, rate_func = rf)
for v, p, rf in zip(vectors, line_pairs, rate_functions)
]
)
self.remove(*vectors)
self.wait()
class HowToThinkVectorsVsPoint(Scene):
def construct(self):
randy = Randolph().to_corner()
bubble = randy.get_bubble(height = 3.8)
text1 = OldTexText("Think of individual vectors as arrows")
text2 = OldTexText("Think of sets of vectors as points")
for text in text1, text2:
text.to_edge(UP)
single_vector = Vector([2, 1])
vector_group = VMobject(*[
Vector([x, 1])
for x in np.linspace(-2, 2, 5)
])
bubble.position_mobject_inside(single_vector)
bubble.position_mobject_inside(vector_group)
dots = VMobject(*[
Dot(v.get_end())
for v in vector_group.split()
])
self.add(randy)
self.play(
ApplyMethod(randy.change_mode, "pondering"),
ShowCreation(bubble)
)
self.play(FadeIn(text1))
self.play(ShowCreation(single_vector))
self.wait(3)
self.play(
Transform(text1, text2),
Transform(single_vector, vector_group)
)
self.remove(single_vector)
self.add(vector_group)
self.wait()
self.play(Transform(vector_group, dots))
self.wait()
class IntroduceThreeDSpan(Scene):
pass
class AskAboutThreeDSpan(Scene):
def construct(self):
self.play(Write("What does the span of two 3d vectors look like?"))
self.wait(2)
class ThreeDVectorSpan(Scene):
pass
class LinearCombinationOfThreeVectors(Scene):
pass
class VaryingLinearCombinationOfThreeVectors(Scene):
pass
class LinearCombinationOfThreeVectorsText(Scene):
def construct(self):
text = OldTexText("""
Linear combination of
$\\vec{\\textbf{v}}$,
$\\vec{\\textbf{w}}$, and
$\\vec{\\textbf{u}}$:
""")
VMobject(*text.split()[-12:-10]).set_color(MAROON_C)
VMobject(*text.split()[-9:-7]).set_color(BLUE)
VMobject(*text.split()[-3:-1]).set_color(RED_C)
VMobject(*text.split()[:17]).set_color(GREEN)
text.set_width(FRAME_WIDTH - 1)
text.to_edge(UP)
equation = OldTexText("""$
a\\vec{\\textbf{v}} +
b\\vec{\\textbf{w}} +
c\\vec{\\textbf{u}}
$""")
VMobject(*equation.split()[-10:-8]).set_color(MAROON_C)
VMobject(*equation.split()[-6:-4]).set_color(BLUE)
VMobject(*equation.split()[-2:]).set_color(RED_C)
a, b, c = np.array(equation.split())[[0, 4, 8]]
equation.scale(1.5)
equation.next_to(text, DOWN, buff = 1)
span_comment = OldTexText("For span, let these constants vary")
span_comment.scale(1.5)
span_comment.next_to(equation, DOWN, buff = 2)
VMobject(*span_comment.split()[3:7]).set_color(YELLOW)
arrows = VMobject(*[
Arrow(span_comment, var)
for var in (a, b, c)
])
self.play(Write(text))
self.play(Write(equation))
self.wait()
self.play(
ShowCreation(arrows),
Write(span_comment)
)
self.wait()
class ThirdVectorOnSpanOfFirstTwo(Scene):
pass
class ThirdVectorOutsideSpanOfFirstTwo(Scene):
pass
class SpanCasesWords(Scene):
def construct(self):
words1 = OldTexText("""
Case 1: $\\vec{\\textbf{u}}$ is in the span of
$\\vec{\\textbf{v}}$ and $\\vec{\\textbf{u}}$
""")
VMobject(*words1.split()[6:8]).set_color(RED_C)
VMobject(*words1.split()[-7:-5]).set_color(MAROON_C)
VMobject(*words1.split()[-2:]).set_color(BLUE)
words2 = OldTexText("""
Case 2: $\\vec{\\textbf{u}}$ is not in the span of
$\\vec{\\textbf{v}}$ and $\\vec{\\textbf{u}}$
""")
VMobject(*words2.split()[6:8]).set_color(RED_C)
VMobject(*words2.split()[-7:-5]).set_color(MAROON_C)
VMobject(*words2.split()[-2:]).set_color(BLUE)
VMobject(*words2.split()[10:13]).set_color(RED)
for words in words1, words2:
words.set_width(FRAME_WIDTH - 1)
self.play(Write(words1))
self.wait()
self.play(Transform(words1, words2))
self.wait()
class LinearDependentWords(Scene):
def construct(self):
words1 = OldTexText([
"$\\vec{\\textbf{v}}$",
"and",
"$\\vec{\\textbf{w}}$",
"are",
"``Linearly dependent'' ",
])
v, _and, w, are, rest = words1.split()
v.set_color(MAROON_C)
w.set_color(BLUE)
rest.set_color(YELLOW)
words2 = OldTexText([
"$\\vec{\\textbf{v}}$,",
"$\\vec{\\textbf{w}}$",
"and",
"$\\vec{\\textbf{u}}$",
"are",
"``Linearly dependent'' ",
])
v, w, _and, u, are, rest = words2.split()
v.set_color(MAROON_C)
w.set_color(BLUE)
u.set_color(RED_C)
rest.set_color(YELLOW)
for words in words1, words2:
words.set_width(FRAME_WIDTH - 1)
self.play(Write(words1))
self.wait()
self.play(Transform(words1, words2))
self.wait()
class LinearDependentEquations(Scene):
def construct(self):
title = OldTexText("``Linearly dependent'' ")
title.set_color(YELLOW)
title.scale(2)
title.to_edge(UP)
self.add(title)
equation1 = OldTex([
"\\vec{\\textbf{w}}",
"=",
"a",
"\\vec{\\textbf{v}}",
])
w, eq, a, v = equation1.split()
w.set_color(BLUE)
v.set_color(MAROON_C)
equation1.scale(2)
eq1_copy = equation1.copy()
low_words1 = OldTexText("For some value of $a$")
low_words1.scale(2)
low_words1.to_edge(DOWN)
arrow = Arrow(low_words1, a)
arrow_copy = arrow.copy()
equation2 = OldTex([
"\\vec{\\textbf{u}}",
"=",
"a",
"\\vec{\\textbf{v}}",
"+",
"b",
"\\vec{\\textbf{w}}",
])
u, eq, a, v, plus, b, w = equation2.split()
u.set_color(RED)
w.set_color(BLUE)
v.set_color(MAROON_C)
equation2.scale(2)
eq2_copy = equation2.copy()
low_words2 = OldTexText("For some values of a and b")
low_words2.scale(2)
low_words2.to_edge(DOWN)
arrows = VMobject(*[
Arrow(low_words2, var)
for var in (a, b)
])
self.play(Write(equation1))
self.play(
ShowCreation(arrow),
Write(low_words1)
)
self.wait()
self.play(
Transform(equation1, equation2),
Transform(low_words1, low_words2),
Transform(arrow, arrows)
)
self.wait(2)
new_title = OldTexText("``Linearly independent'' ")
new_title.set_color(GREEN)
new_title.replace(title)
for eq_copy in eq1_copy, eq2_copy:
neq = OldTex("\\neq")
neq.replace(eq_copy.submobjects[1])
eq_copy.submobjects[1] = neq
new_low_words1 = OldTexText(["For", "all", "values of a"])
new_low_words2 = OldTexText(["For", "all", "values of a and b"])
for low_words in new_low_words1, new_low_words2:
low_words.split()[1].set_color(GREEN)
low_words.scale(2)
low_words.to_edge(DOWN)
self.play(
Transform(title, new_title),
Transform(equation1, eq1_copy),
Transform(arrow, arrow_copy),
Transform(low_words1, new_low_words1)
)
self.wait()
self.play(
Transform(equation1, eq2_copy),
Transform(arrow, arrows),
Transform(low_words1, new_low_words2)
)
self.wait()
class AlternateDefOfLinearlyDependent(Scene):
def construct(self):
title1 = OldTexText([
"$\\vec{\\textbf{v}}$,",
"$\\vec{\\textbf{w}}$",
"and",
"$\\vec{\\textbf{u}}$",
"are",
"linearly dependent",
"if",
])
title2 = OldTexText([
"$\\vec{\\textbf{v}}$,",
"$\\vec{\\textbf{w}}$",
"and",
"$\\vec{\\textbf{u}}$",
"are",
"linearly independent",
"if",
])
for title in title1, title2:
v, w, _and, u, are, ld, _if = title.split()
v.set_color(MAROON_C)
w.set_color(BLUE)
u.set_color(RED_C)
title.to_edge(UP)
title1.split()[-2].set_color(YELLOW)
title2.split()[-2].set_color(GREEN)
subtitle = OldTexText("the only solution to")
subtitle.next_to(title2, DOWN, aligned_edge = LEFT)
self.add(title1)
equations = self.get_equations()
added_words1 = OldTexText(
"where at least one of $a$, $b$ and $c$ is not $0$"
)
added_words2 = OldTexText(
"is a = b = c = 0"
)
scalar_specification = OldTexText(
"For some choice of $a$ and $b$"
)
scalar_specification.shift(1.5*DOWN)
scalar_specification.add(*[
Arrow(scalar_specification, equations[0].split()[i])
for i in (2, 5)
])
brace = Brace(VMobject(*equations[2].split()[2:]))
brace_words = OldTexText("Linear combination")
brace_words.next_to(brace, DOWN)
equation = equations[0]
for added_words in added_words1, added_words2:
added_words.next_to(title, DOWN, buff = 3.5, aligned_edge = LEFT)
self.play(Write(equation))
for i, new_eq in enumerate(equations):
if i == 0:
self.play(FadeIn(scalar_specification))
self.wait(2)
self.play(FadeOut(scalar_specification))
elif i == 3:
self.play(
GrowFromCenter(brace),
Write(brace_words)
)
self.wait(3)
self.play(FadeOut(brace), FadeOut(brace_words))
self.play(Transform(
equation, new_eq,
path_arc = (np.pi/2 if i == 1 else 0)
))
self.wait(3)
self.play(Write(added_words1))
self.wait(2)
self.play(
Transform(title1, title2),
Write(subtitle),
Transform(added_words1, added_words2),
)
self.wait(3)
everything = VMobject(*self.get_mobjects())
self.play(ApplyFunction(
lambda m : m.scale(0.5).to_corner(UP+LEFT),
everything
))
self.wait()
def get_equations(self):
equation1 = OldTex([
"\\vec{\\textbf{u}}",
"=",
"a",
"\\vec{\\textbf{v}}",
"+",
"b",
"\\vec{\\textbf{w}}",
])
u = equation1.split()[0]
equation1.submobjects = list(it.chain(
[VectorizedPoint(u.get_center())],
equation1.submobjects[1:],
[VectorizedPoint(u.get_left())],
[u]
))
equation2 = OldTex([
"\\left[\\begin{array}{c} 0 \\\\ 0 \\\\ 0 \\end{array} \\right]",
"=",
"a",
"\\vec{\\textbf{v}}",
"+",
"b",
"\\vec{\\textbf{w}}",
"-",
"\\vec{\\textbf{u}}",
])
equation3 = OldTex([
"\\vec{\\textbf{0}}",
"=",
"a",
"\\vec{\\textbf{v}}",
"+",
"b",
"\\vec{\\textbf{w}}",
"-",
"\\vec{\\textbf{u}}",
])
equation4 = OldTex([
"\\vec{\\textbf{0}}",
"=",
"0",
"\\vec{\\textbf{v}}",
"+",
"0",
"\\vec{\\textbf{w}}",
"+0",
"\\vec{\\textbf{u}}",
])
equation5 = OldTex([
"\\vec{\\textbf{0}}",
"=",
"a",
"\\vec{\\textbf{v}}",
"+",
"b",
"\\vec{\\textbf{w}}",
"+(-1)",
"\\vec{\\textbf{u}}",
])
equation5.split()[-2].set_color(YELLOW)
equation6 = OldTex([
"\\vec{\\textbf{0}}",
"=",
"a",
"\\vec{\\textbf{v}}",
"+",
"b",
"\\vec{\\textbf{w}}",
"+c",
"\\vec{\\textbf{u}}",
])
result = [equation1, equation2, equation3, equation4, equation5, equation6]
for eq in result:
eq.split()[3].set_color(MAROON_C)
eq.split()[6].set_color(BLUE)
eq.split()[-1].set_color(RED_C)
eq.scale(1.5)
eq.shift(UP)
return result
class MathematiciansLikeToConfuse(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("""
We wouldn't want things to \\\\
be \\emph{understandable} would we?
""")
modes = "pondering", "sassy", "confused"
self.play(*[
ApplyMethod(student.change_mode, mode)
for student, mode in zip(self.get_students(), modes)
])
self.wait(2)
class CheckYourUnderstanding(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("Quiz time!")
self.random_blink()
self.wait()
self.random_blink()
class TechnicalDefinitionOfBasis(Scene):
def construct(self):
title = OldTexText("Technical definition of basis:")
title.to_edge(UP)
definition = OldTexText([
"The",
"basis",
"of a vector space is a set of",
"linearly independent",
"vectors that",
"span",
"the full space",
])
t, b, oavsiaso, li, vt, s, tfs = definition.split()
b.set_color(BLUE)
li.set_color(GREEN)
s.set_color(YELLOW)
definition.set_width(FRAME_WIDTH-1)
self.add(title)
self.play(Write(definition))
self.wait()
class NextVideo(Scene):
def construct(self):
title = OldTexText("Next video: Matrices as linear transformations")
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
|
|
from manim_imports_ext import *
from _2016.eola.chapter0 import UpcomingSeriesOfVidoes
import random
def plane_wave_homotopy(x, y, z, t):
norm = get_norm([x, y])
tau = interpolate(5, -5, t) + norm/FRAME_X_RADIUS
alpha = sigmoid(tau)
return [x, y + 0.5*np.sin(2*np.pi*alpha)-t*SMALL_BUFF/2, z]
class Physicist(PiCreature):
CONFIG = {
"color" : PINK,
}
class ComputerScientist(PiCreature):
CONFIG = {
"color" : PURPLE_E,
"flip_at_start" : True,
}
class OpeningQuote(Scene):
def construct(self):
words = OldTexText(
"``The introduction of numbers as \\\\ coordinates is an act of violence.''",
)
words.to_edge(UP)
for mob in words.submobjects[27:27+11]:
mob.set_color(GREEN)
author = OldTexText("-Hermann Weyl")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = 0.5)
self.play(FadeIn(words))
self.wait(1)
self.play(Write(author, run_time = 4))
self.wait()
class DifferentConceptions(Scene):
def construct(self):
physy = Physicist()
mathy = Mathematician(mode = "pondering")
compy = ComputerScientist()
creatures = [physy, compy, mathy]
physy.title = OldTexText("Physics student").to_corner(DOWN+LEFT)
compy.title = OldTexText("CS student").to_corner(DOWN+RIGHT)
mathy.title = OldTexText("Mathematician").to_edge(DOWN)
names = VMobject(physy.title, mathy.title, compy.title)
names.arrange(RIGHT, buff = 1)
names.to_corner(DOWN+LEFT)
for pi in creatures:
pi.next_to(pi.title, UP)
vector, symbol, coordinates = self.intro_vector()
for pi in creatures:
self.play(
Write(pi.title),
FadeIn(pi),
run_time = 1
)
self.wait(2)
self.remove(symbol, coordinates)
self.physics_conception(creatures, vector)
self.cs_conception(creatures)
self.handle_mathy(creatures)
def intro_vector(self):
plane = NumberPlane()
labels = VMobject(*plane.get_coordinate_labels())
vector = Vector(RIGHT+2*UP, color = YELLOW)
coordinates = vector_coordinate_label(vector)
symbol = OldTex("\\vec{\\textbf{v}}")
symbol.shift(0.5*(RIGHT+UP))
self.play(ShowCreation(
plane,
lag_ratio=1,
run_time = 3
))
self.play(ShowCreation(
vector,
))
self.play(
Write(labels),
Write(coordinates),
Write(symbol)
)
self.wait(2)
self.play(
FadeOut(plane),
FadeOut(labels),
ApplyMethod(vector.shift, 4*LEFT+UP),
ApplyMethod(coordinates.shift, 2.5*RIGHT+0.5*DOWN),
ApplyMethod(symbol.shift, 0.5*(UP+LEFT))
)
self.remove(plane, labels)
return vector, symbol, coordinates
def physics_conception(self, creatures, original_vector):
self.fade_all_but(creatures, 0)
physy, compy, mathy = creatures
vector = Vector(2*RIGHT)
vector.next_to(physy, UP+RIGHT)
brace = Brace(vector, DOWN)
length = OldTexText("Length")
length.next_to(brace, DOWN)
group = VMobject(vector, brace, length)
group.rotate(np.pi/6)
vector.get_center = lambda : vector.get_start()
direction = OldTexText("Direction")
direction.next_to(vector, RIGHT)
direction.shift(UP)
two_dimensional = OldTexText("Two-dimensional")
three_dimensional = OldTexText("Three-dimensional")
two_dimensional.to_corner(UP+RIGHT)
three_dimensional.to_corner(UP+RIGHT)
random_vectors = VMobject(*[
Vector(
random.uniform(-2, 2)*RIGHT + \
random.uniform(-2, 2)*UP
).shift(
random.uniform(0, 4)*RIGHT + \
random.uniform(-1, 2)*UP
).set_color(random_color())
for x in range(5)
])
self.play(
Transform(original_vector, vector),
ApplyMethod(physy.change_mode, "speaking")
)
self.remove(original_vector)
self.add(vector )
self.wait()
self.play(
GrowFromCenter(brace),
Write(length),
run_time = 1
)
self.wait()
self.remove(brace, length)
self.play(
Rotate(vector, np.pi/3, in_place = True),
Write(direction),
run_time = 1
)
for angle in -2*np.pi/3, np.pi/3:
self.play(Rotate(
vector, angle,
in_place = True,
run_time = 1
))
self.play(ApplyMethod(physy.change_mode, "plain"))
self.remove(direction)
for point in 2*UP, 4*RIGHT, ORIGIN:
self.play(ApplyMethod(vector.move_to, point))
self.wait()
self.play(
Write(two_dimensional),
ApplyMethod(physy.change_mode, "pondering"),
ShowCreation(random_vectors, lag_ratio = 0.5),
run_time = 1
)
self.wait(2)
self.remove(random_vectors, vector)
self.play(Transform(two_dimensional, three_dimensional))
self.wait(5)
self.remove(two_dimensional)
self.restore_creatures(creatures)
def cs_conception(self, creatures):
self.fade_all_but(creatures, 1)
physy, compy, mathy = creatures
title = OldTexText("Vectors $\\Leftrightarrow$ lists of numbers")
title.to_edge(UP)
vectors = VMobject(*list(map(matrix_to_mobject, [
[2, 1],
[5, 0, 0, -3],
[2.3, -7.1, 0.1],
])))
vectors.arrange(RIGHT, buff = 1)
vectors.to_edge(LEFT)
self.play(
ApplyMethod(compy.change_mode, "sassy"),
Write(title, run_time = 1)
)
self.play(Write(vectors))
self.wait()
self.play(ApplyMethod(compy.change_mode, "pondering"))
self.house_example(vectors, title)
self.restore_creatures(creatures)
def house_example(self, starter_mobject, title):
house = SVGMobject("house")
house.set_stroke(width = 0)
house.set_fill(BLUE_C, opacity = 1)
house.set_height(3)
house.center()
square_footage_words = OldTexText("Square footage:")
price_words = OldTexText("Price: ")
square_footage = OldTex("2{,}600\\text{ ft}^2")
price = OldTexText("\\$300{,}000")
house.to_edge(LEFT).shift(UP)
square_footage_words.next_to(house, RIGHT)
square_footage_words.shift(0.5*UP)
square_footage_words.set_color(RED)
price_words.next_to(square_footage_words, DOWN, aligned_edge = LEFT)
price_words.set_color(GREEN)
square_footage.next_to(square_footage_words)
square_footage.set_color(RED)
price.next_to(price_words)
price.set_color(GREEN)
vector = Matrix([square_footage.copy(), price.copy()])
vector.next_to(house, RIGHT).shift(0.25*UP)
new_square_footage, new_price = vector.get_mob_matrix().flatten()
not_equals = OldTex("\\ne")
not_equals.next_to(vector)
alt_vector = Matrix([
OldTexText("300{,}000\\text{ ft}^2").set_color(RED),
OldTexText("\\$2{,}600").set_color(GREEN)
])
alt_vector.next_to(not_equals)
brace = Brace(vector, RIGHT)
two_dimensional = OldTexText("2 dimensional")
two_dimensional.next_to(brace)
brackets = vector.get_brackets()
self.play(Transform(starter_mobject, house))
self.remove(starter_mobject)
self.add(house)
self.add(square_footage_words)
self.play(Write(square_footage, run_time = 2))
self.add(price_words)
self.play(Write(price, run_time = 2))
self.wait()
self.play(
FadeOut(square_footage_words), FadeOut(price_words),
Transform(square_footage, new_square_footage),
Transform(price, new_price),
Write(brackets),
run_time = 1
)
self.remove(square_footage_words, price_words)
self.wait()
self.play(
Write(not_equals),
Write(alt_vector),
run_time = 1
)
self.wait()
self.play(FadeOut(not_equals), FadeOut(alt_vector))
self.remove(not_equals, alt_vector)
self.wait()
self.play(
GrowFromCenter(brace),
Write(two_dimensional),
run_time = 1
)
self.wait()
everything = VMobject(
house, square_footage, price, brackets, brace,
two_dimensional, title
)
self.play(ApplyMethod(everything.shift, FRAME_WIDTH*LEFT))
self.remove(everything)
def handle_mathy(self, creatures):
self.fade_all_but(creatures, 2)
physy, compy, mathy = creatures
v_color = YELLOW
w_color = BLUE
sum_color = GREEN
v_arrow = Vector([1, 1])
w_arrow = Vector([2, 1])
w_arrow.shift(v_arrow.get_end())
sum_arrow = Vector(w_arrow.get_end())
arrows = VMobject(v_arrow, w_arrow, sum_arrow)
arrows.scale(0.7)
arrows.to_edge(LEFT, buff = 2)
v_array = matrix_to_mobject([3, -5])
w_array = matrix_to_mobject([2, 1])
sum_array = matrix_to_mobject(["3+2", "-5+1"])
arrays = VMobject(
v_array, OldTex("+"), w_array, OldTex("="), sum_array
)
arrays.arrange(RIGHT)
arrays.scale(0.75)
arrays.to_edge(RIGHT).shift(UP)
v_sym = OldTex("\\vec{\\textbf{v}}")
w_sym = OldTex("\\vec{\\textbf{w}}")
syms = VMobject(v_sym, OldTex("+"), w_sym)
syms.arrange(RIGHT)
syms.center().shift(2*UP)
statement = OldTexText("We'll ignore him \\\\ for now")
statement.set_color(PINK)
statement.set_width(arrays.get_width())
statement.next_to(arrays, DOWN, buff = 1.5)
circle = Circle()
circle.shift(syms.get_bottom())
VMobject(v_arrow, v_array, v_sym).set_color(v_color)
VMobject(w_arrow, w_array, w_sym).set_color(w_color)
VMobject(sum_arrow, sum_array).set_color(sum_color)
self.play(
Write(syms), Write(arrays),
ShowCreation(arrows),
ApplyMethod(mathy.change_mode, "pondering"),
run_time = 2
)
self.play(Blink(mathy))
self.add_scaling(arrows, syms, arrays)
self.play(Write(statement))
self.play(ApplyMethod(mathy.change_mode, "sad"))
self.wait()
self.play(
ShowCreation(circle),
ApplyMethod(mathy.change_mode, "plain")
)
self.wait()
def add_scaling(self, arrows, syms, arrays):
s_arrows = VMobject(
OldTex("2"), Vector([1, 1]).set_color(YELLOW),
OldTex("="), Vector([2, 2]).set_color(WHITE)
)
s_arrows.arrange(RIGHT)
s_arrows.scale(0.75)
s_arrows.next_to(arrows, DOWN)
s_arrays = VMobject(
OldTex("2"),
matrix_to_mobject([3, -5]).set_color(YELLOW),
OldTexText("="),
matrix_to_mobject(["2(3)", "2(-5)"])
)
s_arrays.arrange(RIGHT)
s_arrays.scale(0.75)
s_arrays.next_to(arrays, DOWN)
s_syms = OldTex(["2", "\\vec{\\textbf{v}}"])
s_syms.split()[-1].set_color(YELLOW)
s_syms.next_to(syms, DOWN)
self.play(
Write(s_arrows), Write(s_arrays), Write(s_syms),
run_time = 2
)
self.wait()
def fade_all_but(self, creatures, index):
self.play(*[
FadeOut(VMobject(pi, pi.title))
for pi in creatures[:index] + creatures[index+1:]
])
def restore_creatures(self, creatures):
self.play(*[
ApplyFunction(lambda m : m.change_mode("plain").set_color(m.color), pi)
for pi in creatures
] + [
ApplyMethod(pi.title.set_fill, WHITE, 1.0)
for pi in creatures
])
class ThreeDVectorField(Scene):
pass
class HelpsToHaveOneThought(Scene):
def construct(self):
morty = Mortimer()
morty.to_corner(DOWN+RIGHT)
morty.look(DOWN+LEFT)
new_morty = morty.copy().change_mode("speaking")
new_morty.look(DOWN+LEFT)
randys = VMobject(*[
Randolph(color = color).scale(0.8)
for color in (BLUE_D, BLUE_C, BLUE_E)
])
randys.arrange(RIGHT)
randys.to_corner(DOWN+LEFT)
randy = randys.split()[1]
speech_bubble = morty.get_bubble(SpeechBubble)
words = OldTexText("Think of some vector...")
speech_bubble.position_mobject_inside(words)
thought_bubble = randy.get_bubble()
arrow = Vector([2, 1]).scale(0.7)
or_word = OldTexText("or")
array = Matrix([2, 1]).scale(0.5)
q_mark = OldTexText("?")
thought = VMobject(arrow, or_word, array, q_mark)
thought.arrange(RIGHT, buff = 0.2)
thought_bubble.position_mobject_inside(thought)
thought_bubble.set_fill(BLACK, opacity = 1)
self.add(morty, randys)
self.play(
ShowCreation(speech_bubble),
Transform(morty, new_morty),
Write(words)
)
self.wait(2)
self.play(
FadeOut(speech_bubble),
FadeOut(words),
ApplyMethod(randy.change_mode, "pondering"),
ShowCreation(thought_bubble),
Write(thought)
)
self.wait(2)
class HowIWantYouToThinkAboutVectors(Scene):
def construct(self):
vector = Vector([-2, 3])
plane = NumberPlane()
axis_labels = plane.get_axis_labels()
other_vectors = VMobject(*list(map(Vector, [
[1, 2], [2, -1], [4, 0]
])))
colors = [GREEN_B, MAROON_B, PINK]
for v, color in zip(other_vectors.split(), colors):
v.set_color(color)
shift_val = 4*RIGHT+DOWN
dot = Dot(radius = 0.1)
dot.set_color(RED)
tail_word = OldTexText("Tail")
tail_word.shift(0.5*DOWN+2.5*LEFT)
line = Line(tail_word, dot)
self.play(ShowCreation(vector))
self.wait(2)
self.play(
ShowCreation(plane, lag_ratio=0.5),
Animation(vector)
)
self.play(Write(axis_labels, run_time = 1))
self.wait()
self.play(
GrowFromCenter(dot),
ShowCreation(line),
Write(tail_word, run_time = 1)
)
self.wait()
self.play(
FadeOut(tail_word),
ApplyMethod(VMobject(dot, line).scale, 0.01)
)
self.remove(tail_word, line, dot)
self.wait()
self.play(ApplyMethod(
vector.shift, shift_val,
path_arc = 3*np.pi/2,
run_time = 3
))
self.play(ApplyMethod(
vector.shift, -shift_val,
rate_func = rush_into,
run_time = 0.5
))
self.wait(3)
self.play(ShowCreation(
other_vectors,
run_time = 3
))
self.wait(3)
x_axis, y_axis = plane.get_axes().split()
x_label = axis_labels.split()[0]
x_axis = x_axis.copy()
x_label = x_label.copy()
everything = VMobject(*self.mobjects)
self.play(
FadeOut(everything),
Animation(x_axis), Animation(x_label)
)
class ListsOfNumbersAddOn(Scene):
def construct(self):
arrays = VMobject(*list(map(matrix_to_mobject, [
[-2, 3], [1, 2], [2, -1], [4, 0]
])))
arrays.arrange(buff = 0.4)
arrays.scale(2)
self.play(Write(arrays))
self.wait(2)
class CoordinateSystemWalkthrough(VectorScene):
def construct(self):
self.introduce_coordinate_plane()
self.show_vector_coordinates()
self.coords_to_vector([3, -1])
self.vector_to_coords([-2, -1.5], integer_labels = False)
def introduce_coordinate_plane(self):
plane = NumberPlane()
x_axis, y_axis = plane.get_axes().copy().split()
x_label, y_label = plane.get_axis_labels().split()
number_line = NumberLine(tick_frequency = 1)
x_tick_marks = number_line.get_tick_marks()
y_tick_marks = x_tick_marks.copy().rotate(np.pi/2)
tick_marks = VMobject(x_tick_marks, y_tick_marks)
tick_marks.set_color(WHITE)
plane_lines = [m for m in plane.get_family() if isinstance(m, Line)]
origin_words = OldTexText("Origin")
origin_words.shift(2*UP+2*LEFT)
dot = Dot(radius = 0.1).set_color(RED)
line = Line(origin_words.get_bottom(), dot.get_corner(UP+LEFT))
unit_brace = Brace(Line(RIGHT, 2*RIGHT))
one = OldTex("1").next_to(unit_brace, DOWN)
self.add(x_axis, x_label)
self.wait()
self.play(ShowCreation(y_axis))
self.play(Write(y_label, run_time = 1))
self.wait(2)
self.play(
Write(origin_words),
GrowFromCenter(dot),
ShowCreation(line),
run_time = 1
)
self.wait(2)
self.play(
FadeOut(VMobject(origin_words, dot, line))
)
self.remove(origin_words, dot, line)
self.wait()
self.play(
ShowCreation(tick_marks)
)
self.play(
GrowFromCenter(unit_brace),
Write(one, run_time = 1)
)
self.wait(2)
self.remove(unit_brace, one)
self.play(
*list(map(GrowFromCenter, plane_lines)) + [
Animation(x_axis), Animation(y_axis)
])
self.wait()
self.play(
FadeOut(plane),
Animation(VMobject(x_axis, y_axis, tick_marks))
)
self.remove(plane)
self.add(tick_marks)
def show_vector_coordinates(self):
starting_mobjects = list(self.mobjects)
vector = Vector([-2, 3])
x_line = Line(ORIGIN, -2*RIGHT)
y_line = Line(-2*RIGHT, -2*RIGHT+3*UP)
x_line.set_color(X_COLOR)
y_line.set_color(Y_COLOR)
array = vector_coordinate_label(vector)
x_label, y_label = array.get_mob_matrix().flatten()
x_label_copy = x_label.copy()
x_label_copy.set_color(X_COLOR)
y_label_copy = y_label.copy()
y_label_copy.set_color(Y_COLOR)
point = Dot(4*LEFT+2*UP)
point_word = OldTexText("(-4, 2) as \\\\ a point")
point_word.scale(0.7)
point_word.next_to(point, DOWN)
point.add(point_word)
self.play(ShowCreation(vector))
self.play(Write(array))
self.wait(2)
self.play(ApplyMethod(x_label_copy.next_to, x_line, DOWN))
self.play(ShowCreation(x_line))
self.wait(2)
self.play(ApplyMethod(y_label_copy.next_to, y_line, LEFT))
self.play(ShowCreation(y_line))
self.wait(2)
self.play(FadeIn(point))
self.wait()
self.play(ApplyFunction(
lambda m : m.scale(1.25).set_color(YELLOW),
array.get_brackets(),
rate_func = there_and_back
))
self.wait()
self.play(FadeOut(point))
self.remove(point)
self.wait()
self.clear()
self.add(*starting_mobjects)
class LabeledThreeDVector(Scene):
pass
class WriteZ(Scene):
def construct(self):
z = OldTex("z").set_color(Z_COLOR)
z.set_height(4)
self.play(Write(z, run_time = 2))
self.wait(3)
class Write3DVector(Scene):
def construct(self):
array = Matrix([2, 1, 3]).scale(2)
x, y, z = array.get_mob_matrix().flatten()
brackets = array.get_brackets()
x.set_color(X_COLOR)
y.set_color(Y_COLOR)
z.set_color(Z_COLOR)
self.add(brackets)
for mob in x, y, z:
self.play(Write(mob), run_time = 2)
self.wait()
class VectorAddition(VectorScene):
def construct(self):
self.add_plane()
vects = self.define_addition()
# vects = map(Vector, [[1, 2], [3, -1], [4, 1]])
self.ask_why(*vects)
self.answer_why(*vects)
def define_addition(self):
v1 = self.add_vector([1, 2])
v2 = self.add_vector([3, -1], color = MAROON_B)
l1 = self.label_vector(v1, "v")
l2 = self.label_vector(v2, "w")
self.wait()
self.play(ApplyMethod(v2.shift, v1.get_end()))
self.wait()
v_sum = self.add_vector(v2.get_end(), color = PINK)
sum_tex = "\\vec{\\textbf{v}} + \\vec{\\textbf{w}}"
self.label_vector(v_sum, sum_tex, rotate = True)
self.wait(3)
return v1, v2, v_sum
def ask_why(self, v1, v2, v_sum):
why = OldTexText("Why?")
why_not_this = OldTexText("Why not \\\\ this?")
new_v2 = v2.copy().shift(-v2.get_start())
new_v_sum = v_sum.copy()
alt_vect_sum = new_v2.get_end() - v1.get_end()
new_v_sum.shift(-new_v_sum.get_start())
new_v_sum.rotate(
angle_of_vector(alt_vect_sum) - new_v_sum.get_angle()
)
new_v_sum.scale(get_norm(alt_vect_sum)/new_v_sum.get_length())
new_v_sum.shift(v1.get_end())
new_v_sum.submobjects.reverse()#No idea why I have to do this
original_v_sum = v_sum.copy()
why.next_to(v2, RIGHT)
why_not_this.next_to(new_v_sum, RIGHT)
why_not_this.shift(0.5*UP)
self.play(Write(why, run_time = 1))
self.wait(2)
self.play(
Transform(v2, new_v2),
Transform(v_sum, new_v_sum),
Transform(why, why_not_this)
)
self.wait(2)
self.play(
FadeOut(why),
Transform(v_sum, original_v_sum)
)
self.remove(why)
self.wait()
def answer_why(self, v1, v2, v_sum):
randy = Randolph(color = PINK)
randy.shift(-randy.get_bottom())
self.remove(v1, v2, v_sum)
for v in v1, v2, v_sum:
self.add(v)
self.show_ghost_movement(v)
self.remove(v)
self.add(v1, v2 )
self.wait()
self.play(ApplyMethod(randy.scale, 0.3))
self.play(ApplyMethod(randy.shift, v1.get_end()))
self.wait()
self.play(ApplyMethod(v2.shift, v1.get_end()))
self.play(ApplyMethod(randy.move_to, v2.get_end()))
self.wait()
self.remove(randy)
randy.move_to(ORIGIN)
self.play(FadeIn(v_sum))
self.play(ApplyMethod(randy.shift, v_sum.get_end()))
self.wait()
class AddingNumbersOnNumberLine(Scene):
def construct(self):
number_line = NumberLine()
number_line.add_numbers()
two_vect = Vector([2, 0])
five_vect = Vector([5, 0], color = MAROON_B)
seven_vect = Vector([7, 0], color = PINK)
five_vect.shift(two_vect.get_end())
seven_vect.shift(0.5*DOWN)
vects = [two_vect, five_vect, seven_vect]
two, five, seven = list(map(Tex, ["2", "5", "7"]))
two.next_to(two_vect, UP)
five.next_to(five_vect, UP)
seven.next_to(seven_vect, DOWN)
nums = [two, five, seven]
sum_mob = OldTex("2 + 5").shift(3*UP)
self.play(ShowCreation(number_line))
self.wait()
self.play(Write(sum_mob, run_time = 2))
self.wait()
for vect, num in zip(vects, nums):
self.play(
ShowCreation(vect),
Write(num, run_time = 1)
)
self.wait()
class VectorAdditionNumerically(VectorScene):
def construct(self):
plus = OldTex("+")
equals = OldTex("=")
randy = Randolph()
randy.set_height(1)
randy.shift(-randy.get_bottom())
axes = self.add_axes()
x_axis, y_axis = axes.split()
v1 = self.add_vector([1, 2])
coords1, x_line1, y_line1 = self.vector_to_coords(v1, clean_up = False)
self.play(ApplyFunction(
lambda m : m.next_to(y_axis, RIGHT).to_edge(UP),
coords1
))
plus.next_to(coords1, RIGHT)
v2 = self.add_vector([3, -1], color = MAROON_B)
coords2, x_line2, y_line2 = self.vector_to_coords(v2, clean_up = False)
self.wait()
self.play(
ApplyMethod(coords2.next_to, plus, RIGHT),
Write(plus, run_time = 1),
*[
ApplyMethod(mob.shift, v1.get_end())
for mob in (v2, x_line2, y_line2)
]
)
equals.next_to(coords2, RIGHT)
self.wait()
self.play(FadeIn(randy))
for step in [RIGHT, 2*UP, 3*RIGHT, DOWN]:
self.play(ApplyMethod(randy.shift, step, run_time = 1.5))
self.wait()
self.play(ApplyMethod(randy.shift, -randy.get_bottom()))
self.play(ApplyMethod(x_line2.shift, 2*DOWN))
self.play(ApplyMethod(y_line1.shift, 3*RIGHT))
for step in [4*RIGHT, 2*UP, DOWN]:
self.play(ApplyMethod(randy.shift, step))
self.play(FadeOut(randy))
self.remove(randy)
one_brace = Brace(x_line1)
three_brace = Brace(x_line2)
one = OldTex("1").next_to(one_brace, DOWN)
three = OldTex("3").next_to(three_brace, DOWN)
self.play(
GrowFromCenter(one_brace),
GrowFromCenter(three_brace),
Write(one),
Write(three),
run_time = 1
)
self.wait()
two_brace = Brace(y_line1, RIGHT)
two = OldTex("2").next_to(two_brace, RIGHT)
new_y_line = Line(4*RIGHT, 4*RIGHT+UP, color = Y_COLOR)
two_minus_one_brace = Brace(new_y_line, RIGHT)
two_minus_one = OldTex("2+(-1)").next_to(two_minus_one_brace, RIGHT)
self.play(
GrowFromCenter(two_brace),
Write(two, run_time = 1)
)
self.wait()
self.play(
Transform(two_brace, two_minus_one_brace),
Transform(two, two_minus_one),
Transform(y_line1, new_y_line),
Transform(y_line2, new_y_line)
)
self.wait()
self.add_vector(v2.get_end(), color = PINK )
sum_coords = Matrix(["1+3", "2+(-1)"])
sum_coords.set_height(coords1.get_height())
sum_coords.next_to(equals, RIGHT)
brackets = sum_coords.get_brackets()
x1, y1 = coords1.get_mob_matrix().flatten()
x2, y2 = coords2.get_mob_matrix().flatten()
sum_x, sum_y = sum_coords.get_mob_matrix().flatten()
sum_x_start = VMobject(x1, x2).copy()
sum_y_start = VMobject(y1, y2).copy()
self.play(
Write(brackets),
Write(equals),
Transform(sum_x_start, sum_x),
run_time = 1
)
self.play(Transform(sum_y_start, sum_y))
self.wait(2)
starters = [x1, y1, x2, y2, sum_x_start, sum_y_start]
variables = list(map(Tex, [
"x_1", "y_1", "x_2", "y_2", "x_1+y_1", "x_2+y_2"
]))
for i, (var, starter) in enumerate(zip(variables, starters)):
if i%2 == 0:
var.set_color(X_COLOR)
else:
var.set_color(Y_COLOR)
var.scale(VECTOR_LABEL_SCALE_FACTOR)
var.move_to(starter)
self.play(
Transform(
VMobject(*starters[:4]),
VMobject(*variables[:4])
),
FadeOut(sum_x_start),
FadeOut(sum_y_start)
)
sum_x_end, sum_y_end = variables[-2:]
self.wait(2)
self.play(
Transform(VMobject(x1, x2).copy(), sum_x_end)
)
self.play(
Transform(VMobject(y1, y2).copy(), sum_y_end)
)
self.wait(3)
class MultiplicationByANumberIntro(Scene):
def construct(self):
v = OldTex("\\vec{\\textbf{v}}")
v.set_color(YELLOW)
nums = list(map(Tex, ["2", "\\dfrac{1}{3}", "-1.8"]))
for mob in [v] + nums:
mob.scale(1.5)
self.play(Write(v, run_time = 1))
last = None
for num in nums:
num.next_to(v, LEFT)
if last:
self.play(Transform(last, num))
else:
self.play(FadeIn(num))
last = num
self.wait()
class ShowScalarMultiplication(VectorScene):
def construct(self):
plane = self.add_plane()
v = self.add_vector([3, 1])
label = self.label_vector(v, "v", add_to_vector = False)
self.scale_vector(v, 2, label)
self.scale_vector(v, 1./3, label, factor_tex = "\\dfrac{1}{3}")
self.scale_vector(v, -1.8, label)
self.remove(label)
self.describe_scalars(v, plane)
def scale_vector(self, v, factor, v_label,
v_name = "v", factor_tex = None):
starting_mobjects = list(self.mobjects)
if factor_tex is None:
factor_tex = str(factor)
scaled_vector = self.add_vector(
factor*v.get_end(), animate = False
)
self.remove(scaled_vector)
label_tex = "%s\\vec{\\textbf{%s}}"%(factor_tex, v_name)
label = self.label_vector(
scaled_vector, label_tex, animate = False,
add_to_vector = False
)
self.remove(label)
factor_mob = OldTex(factor_tex)
if factor_mob.get_height() > 1:
factor_mob.set_height(0.9)
if factor_mob.get_width() > 1:
factor_mob.set_width(0.9)
factor_mob.shift(1.5*RIGHT+2.5*UP)
num_factor_parts = len(factor_mob.split())
factor_mob_parts_in_label = label.split()[:num_factor_parts]
label_remainder_parts = label.split()[num_factor_parts:]
factor_in_label = VMobject(*factor_mob_parts_in_label)
label_remainder = VMobject(*label_remainder_parts)
self.play(Write(factor_mob, run_time = 1))
self.wait()
self.play(
ApplyMethod(v.copy().set_color, GREY_D),
ApplyMethod(v_label.copy().set_color, GREY_D),
Transform(factor_mob, factor_in_label),
Transform(v.copy(), scaled_vector),
Transform(v_label.copy(), label_remainder),
)
self.wait(2)
self.clear()
self.add(*starting_mobjects)
def describe_scalars(self, v, plane):
axes = plane.get_axes()
long_v = Vector(2*v.get_end())
long_minus_v = Vector(-2*v.get_end())
original_v = v.copy()
scaling_word = OldTexText("``Scaling''").to_corner(UP+LEFT)
scaling_word.shift(2*RIGHT)
scalars = VMobject(*list(map(Tex, [
"2,", "\\dfrac{1}{3},", "-1.8,", "\\dots"
])))
scalars.arrange(RIGHT, buff = 0.4)
scalars.next_to(scaling_word, DOWN, aligned_edge = LEFT)
scalars_word = OldTexText("``Scalars''")
scalars_word.next_to(scalars, DOWN, aligned_edge = LEFT)
self.remove(plane)
self.add(axes)
self.play(
Write(scaling_word),
Transform(v, long_v),
run_time = 1.5
)
self.play(Transform(v, long_minus_v, run_time = 3))
self.play(Write(scalars))
self.wait()
self.play(Write(scalars_word))
self.play(Transform(v, original_v), run_time = 3)
self.wait(2)
class ScalingNumerically(VectorScene):
def construct(self):
two_dot = OldTex("2\\cdot")
equals = OldTex("=")
self.add_axes()
v = self.add_vector([3, 1])
v_coords, vx_line, vy_line = self.vector_to_coords(v, clean_up = False)
self.play(ApplyMethod(v_coords.to_edge, UP))
two_dot.next_to(v_coords, LEFT)
equals.next_to(v_coords, RIGHT)
two_v = self.add_vector([6, 2], animate = False)
self.remove(two_v)
self.play(
Transform(v.copy(), two_v),
Write(two_dot, run_time = 1)
)
two_v_coords, two_v_x_line, two_v_y_line = self.vector_to_coords(
two_v, clean_up = False
)
self.play(
ApplyMethod(two_v_coords.next_to, equals, RIGHT),
Write(equals, run_time = 1)
)
self.wait(2)
x, y = v_coords.get_mob_matrix().flatten()
two_v_elems = two_v_coords.get_mob_matrix().flatten()
x_sym, y_sym = list(map(Tex, ["x", "y"]))
two_x_sym, two_y_sym = list(map(Tex, ["2x", "2y"]))
VMobject(x_sym, two_x_sym).set_color(X_COLOR)
VMobject(y_sym, two_y_sym).set_color(Y_COLOR)
syms = [x_sym, y_sym, two_x_sym, two_y_sym]
VMobject(*syms).scale(VECTOR_LABEL_SCALE_FACTOR)
for sym, num in zip(syms, [x, y] + list(two_v_elems)):
sym.move_to(num)
self.play(
Transform(x, x_sym),
Transform(y, y_sym),
FadeOut(VMobject(*two_v_elems))
)
self.wait()
self.play(
Transform(
VMobject(two_dot.copy(), x.copy()),
two_x_sym
),
Transform(
VMobject(two_dot.copy(), y.copy() ),
two_y_sym
)
)
self.wait(2)
class FollowingVideos(UpcomingSeriesOfVidoes):
def construct(self):
v_sum = VMobject(
Vector([1, 1], color = YELLOW),
Vector([3, 1], color = BLUE).shift(RIGHT+UP),
Vector([4, 2], color = GREEN),
)
scalar_multiplication = VMobject(
OldTex("2 \\cdot "),
Vector([1, 1]),
OldTex("="),
Vector([2, 2], color = WHITE)
)
scalar_multiplication.arrange(RIGHT)
both = VMobject(v_sum, scalar_multiplication)
both.arrange(RIGHT, buff = 1)
both.shift(2*DOWN)
self.add(both)
UpcomingSeriesOfVidoes.construct(self)
last_video = self.mobjects[-1]
self.play(ApplyMethod(last_video.set_color, YELLOW))
self.wait()
everything = VMobject(*self.mobjects)
everything.remove(last_video)
big_last_video = last_video.copy()
big_last_video.center()
big_last_video.set_height(2.5*FRAME_Y_RADIUS)
big_last_video.set_fill(opacity = 0)
self.play(
ApplyMethod(everything.shift, FRAME_WIDTH*LEFT),
Transform(last_video, big_last_video),
run_time = 2
)
class ItDoesntMatterWhich(Scene):
def construct(self):
physy = Physicist()
compy = ComputerScientist()
physy.title = OldTexText("Physics student").to_corner(DOWN+LEFT)
compy.title = OldTexText("CS student").to_corner(DOWN+RIGHT)
for pi in physy, compy:
pi.next_to(pi.title, UP)
self.add(pi, pi.title)
compy_speech = compy.get_bubble(SpeechBubble)
physy_speech = physy.get_bubble(SpeechBubble)
arrow = Vector([2, 1])
array = matrix_to_mobject([2, 1])
goes_to = OldTex("\\Rightarrow")
physy_statement = VMobject(arrow, goes_to, array)
physy_statement.arrange(RIGHT)
compy_statement = physy_statement.copy()
compy_statement.arrange(LEFT)
physy_speech.position_mobject_inside(physy_statement)
compy_speech.position_mobject_inside(compy_statement)
new_arrow = Vector([2, 1])
x_line = Line(ORIGIN, 2*RIGHT, color = X_COLOR)
y_line = Line(2*RIGHT, 2*RIGHT+UP, color = Y_COLOR)
x_mob = OldTex("2").next_to(x_line, DOWN)
y_mob = OldTex("1").next_to(y_line, RIGHT)
new_arrow.add(x_line, y_line, x_mob, y_mob)
back_and_forth = VMobject(
new_arrow,
OldTex("\\Leftrightarrow"),
matrix_to_mobject([2, 1])
)
back_and_forth.arrange(LEFT).center()
self.wait()
self.play(
ApplyMethod(physy.change_mode, "speaking"),
ShowCreation(physy_speech),
Write(physy_statement),
run_time = 1
)
self.play(Blink(compy))
self.play(
ApplyMethod(physy.change_mode, "sassy"),
ApplyMethod(compy.change_mode, "speaking"),
FadeOut(physy_speech),
ShowCreation(compy_speech),
Transform(physy_statement, compy_statement, path_arc = np.pi)
)
self.wait(2)
self.play(
ApplyMethod(physy.change_mode, "pondering"),
ApplyMethod(compy.change_mode, "pondering"),
Transform(compy_speech, VectorizedPoint(compy_speech.get_tip())),
Transform(physy_statement, back_and_forth)
)
self.wait()
class DataAnalyst(Scene):
def construct(self):
plane = NumberPlane()
ellipse = ParametricCurve(
lambda x : 2*np.cos(x)*(UP+RIGHT) + np.sin(x)*(UP+LEFT),
color = PINK,
t_max = 2*np.pi
)
ellipse_points = [
ellipse.point_from_proportion(x)
for x in np.arange(0, 1, 1./20)
]
string_vects = [
matrix_to_mobject(("%.02f %.02f"%tuple(ep[:2])).split())
for ep in ellipse_points
]
string_vects_matrix = Matrix(
np.array(string_vects).reshape((4, 5))
)
string_vects = string_vects_matrix.get_mob_matrix().flatten()
string_vects = VMobject(*string_vects)
vects = VMobject(*list(map(Vector, ellipse_points)))
self.play(Write(string_vects))
self.wait(2)
self.play(
FadeIn(plane),
Transform(string_vects, vects)
)
self.remove(string_vects)
self.add(vects)
self.wait()
self.play(
ApplyMethod(plane.fade, 0.7),
ApplyMethod(vects.set_color, GREY_D),
ShowCreation(ellipse)
)
self.wait(3)
class ManipulateSpace(LinearTransformationScene):
CONFIG = {
"include_background_plane" : False,
"show_basis_vectors" : False,
}
def construct(self):
matrix_rule = OldTex("""
\\left[
\\begin{array}{c}
x \\\\ y
\\end{array}
\\right]
\\rightarrow
\\left[
\\begin{array}{c}
2x + y \\\\ y + 2x
\\end{array}
\\right]
""")
self.setup()
pi_creature = PiCreature(color = PINK).scale(0.5)
pi_creature.shift(-pi_creature.get_corner(DOWN+LEFT))
self.plane.prepare_for_nonlinear_transform()
self.play(ShowCreation(
self.plane,
run_time = 2
))
self.play(FadeIn(pi_creature))
self.play(Blink(pi_creature))
self.plane.add(pi_creature)
self.play(Homotopy(plane_wave_homotopy, self.plane, run_time = 3))
self.wait(2)
self.apply_matrix([[2, 1], [1, 2]])
self.wait()
self.play(
FadeOut(self.plane),
Write(matrix_rule),
run_time = 2
)
self.wait()
class CodingMathyAnimation(Scene):
pass
class NextVideo(Scene):
def construct(self):
title = OldTexText("Next video: Linear combinations, span, and bases")
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
|
|
from manim_imports_ext import *
from _2016.eola.chapter9 import Jennifer, You
class Chapter0(LinearTransformationScene):
CONFIG = {
"include_background_plane" : False,
"t_matrix" : [[3, 1], [2, -1]]
}
def construct(self):
self.setup()
self.plane.fade()
for mob in self.get_mobjects():
mob.set_stroke(width = 6)
self.apply_transposed_matrix(self.t_matrix, run_time = 0)
class Chapter1(Scene):
def construct(self):
arrow = Vector(2*UP+RIGHT)
vs = OldTexText("vs.")
array = Matrix([1, 2])
array.set_color(TEAL)
everyone = VMobject(arrow, vs, array)
everyone.arrange(RIGHT, buff = 0.5)
everyone.set_height(4)
self.add(everyone)
class Chapter2(LinearTransformationScene):
def construct(self):
self.lock_in_faded_grid()
vectors = VMobject(*[
Vector([x, y])
for x in np.arange(-int(FRAME_X_RADIUS)+0.5, int(FRAME_X_RADIUS)+0.5)
for y in np.arange(-int(FRAME_Y_RADIUS)+0.5, int(FRAME_Y_RADIUS)+0.5)
])
vectors.set_submobject_colors_by_gradient(PINK, BLUE_E)
words = OldTexText("Span")
words.scale(3)
words.to_edge(UP)
words.add_background_rectangle()
self.add(vectors, words)
class Chapter3(Chapter0):
CONFIG = {
"t_matrix" : [[3, 0], [2, -1]]
}
class Chapter4p1(Chapter0):
CONFIG = {
"t_matrix" : [[1, 0], [1, 1]]
}
class Chapter4p2(Chapter0):
CONFIG = {
"t_matrix" : [[1, 2], [-1, 1]]
}
class Chapter5(LinearTransformationScene):
def construct(self):
self.plane.fade()
self.add_unit_square()
self.plane.set_stroke(width = 6)
VMobject(self.i_hat, self.j_hat).set_stroke(width = 10)
self.square.set_fill(YELLOW, opacity = 0.7)
self.square.set_stroke(width = 0)
self.apply_transposed_matrix(self.t_matrix, run_time = 0)
class Chapter9(Scene):
def construct(self):
you = You()
jenny = Jennifer()
you.change_mode("erm")
jenny.change_mode("speaking")
you.shift(LEFT)
jenny.shift(2*RIGHT)
vector = Vector([3, 2])
vector.center().shift(2*DOWN)
vector.set_stroke(width = 8)
vector.tip.scale(2)
you.coords = Matrix([3, 2])
jenny.coords = Matrix(["5/3", "1/3"])
for pi in jenny, you:
pi.bubble = pi.get_bubble(SpeechBubble, width = 3, height = 3)
if pi is you:
pi.bubble.shift(MED_SMALL_BUFF*RIGHT)
else:
pi.coords.scale(0.8)
pi.bubble.shift(MED_SMALL_BUFF*LEFT)
pi.bubble.add_content(pi.coords)
pi.add(pi.bubble, pi.coords)
pi.look_at(vector)
self.add(you, jenny, vector)
class Chapter10(LinearTransformationScene):
CONFIG = {
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_HEIGHT,
"secondary_line_ratio" : 1
},
"include_background_plane" : False,
}
def construct(self):
v_tex = "\\vec{\\textbf{v}}"
eq = OldTex("A", v_tex, "=", "\\lambda", v_tex)
eq.set_color_by_tex(v_tex, YELLOW)
eq.set_color_by_tex("\\lambda", MAROON_B)
eq.scale(3)
eq.add_background_rectangle()
eq.shift(2*DOWN)
title = OldTexText(
"Eigen", "vectors \\\\",
"Eigen", "values"
, arg_separator = "")
title.scale(2.5)
title.to_edge(UP)
# title.set_color_by_tex("Eigen", MAROON_B)
title[0].set_color(YELLOW)
title[2].set_color(MAROON_B)
title.add_background_rectangle()
self.add_vector([-1, 1], color = YELLOW, animate = False)
self.apply_transposed_matrix([[3, 0], [1, 2]])
self.plane.fade()
self.remove(self.j_hat)
self.add(eq, title)
|
|
from manim_imports_ext import *
from _2016.eola.chapter1 import plane_wave_homotopy
V_COLOR = YELLOW
class Jennifer(PiCreature):
CONFIG = {
"color" : PINK,
"start_corner" : DOWN+LEFT,
}
class You(PiCreature):
CONFIG = {
"color" : BLUE_E,
"start_corner" : DOWN+RIGHT,
"flip_at_start" : True,
}
def get_small_bubble(pi_creature, height = 4, width = 3):
pi_center_x = pi_creature.get_center()[0]
kwargs = {
"height" : 4,
"bubble_center_adjustment_factor" : 1./6,
}
bubble = ThoughtBubble(**kwargs)
bubble.stretch_to_fit_width(3)##Canonical width
bubble.rotate(np.pi/4)
bubble.stretch_to_fit_width(width)
bubble.stretch_to_fit_height(height)
if pi_center_x < 0:
bubble.flip()
bubble.next_to(pi_creature, UP, buff = MED_SMALL_BUFF)
bubble.shift_onto_screen()
bubble.set_fill(BLACK, opacity = 0.8)
return bubble
class OpeningQuote(Scene):
def construct(self):
words = OldTexText(
"\\centering ``Mathematics is the art of giving the \\\\",
"same name ",
"to ",
"different things",
".''",
arg_separator = " "
)
words.set_color_by_tex("same name ", BLUE)
words.set_color_by_tex("different things", MAROON_B)
# words.set_width(FRAME_WIDTH - 2)
words.to_edge(UP)
author = OldTexText("-Henri Poincar\\'e.")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = 0.5)
self.play(FadeIn(words))
self.wait(2)
self.play(Write(author, run_time = 3))
self.wait(2)
class LinearCombinationScene(LinearTransformationScene):
CONFIG = {
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_X_RADIUS,
"y_radius" : FRAME_Y_RADIUS,
"secondary_line_ratio" : 1
},
}
def setup(self):
LinearTransformationScene.setup(self)
self.i_hat.label = self.get_vector_label(
self.i_hat, "\\hat{\\imath}", "right"
)
self.j_hat.label = self.get_vector_label(
self.j_hat, "\\hat{\\jmath}", "left"
)
def show_linear_combination(self, numerical_coords,
basis_vectors,
coord_mobs,
revert_to_original = True,
show_sum_vect = False,
sum_vect_color = V_COLOR,
):
for basis in basis_vectors:
if not hasattr(basis, "label"):
basis.label = VectorizedPoint()
direction = np.round(rotate_vector(
basis.get_end(), np.pi/2
))
basis.label.next_to(basis.get_center(), direction)
basis.save_state()
basis.label.save_state()
if coord_mobs is None:
coord_mobs = list(map(Tex, list(map(str, numerical_coords))))
VGroup(*coord_mobs).set_fill(opacity = 0)
for coord, basis in zip(coord_mobs, basis_vectors):
coord.next_to(basis.label, LEFT)
for coord, basis, scalar in zip(coord_mobs, basis_vectors, numerical_coords):
basis.target = basis.copy().scale(scalar)
basis.label.target = basis.label.copy()
coord.target = coord.copy()
new_label = VGroup(coord.target, basis.label.target)
new_label.arrange(aligned_edge = DOWN)
new_label.move_to(
basis.label,
aligned_edge = basis.get_center()-basis.label.get_center()
)
new_label.shift(
basis.target.get_center() - basis.get_center()
)
coord.target.next_to(basis.label.target, LEFT)
coord.target.set_fill(basis.get_color(), opacity = 1)
self.play(*list(map(MoveToTarget, [
coord, basis, basis.label
])))
self.wait()
self.play(*[
ApplyMethod(m.shift, basis_vectors[0].get_end())
for m in self.get_mobjects_from_last_animation()
])
if show_sum_vect:
sum_vect = Vector(
basis_vectors[1].get_end(),
color = sum_vect_color
)
self.play(ShowCreation(sum_vect))
self.wait(2)
if revert_to_original:
self.play(*it.chain(
[basis.restore for basis in basis_vectors],
[basis.label.restore for basis in basis_vectors],
[FadeOut(coord) for coord in coord_mobs],
[FadeOut(sum_vect) for x in [1] if show_sum_vect],
))
if show_sum_vect:
return sum_vect
class RemindOfCoordinates(LinearCombinationScene):
CONFIG = {
"vector_coords" : [3, 2]
}
def construct(self):
self.remove(self.i_hat, self.j_hat)
v = self.add_vector(self.vector_coords, color = V_COLOR)
coords = self.write_vector_coordinates(v)
self.show_standard_coord_meaning(*coords.get_entries().copy())
self.show_abstract_scalar_idea(*coords.get_entries().copy())
self.scale_basis_vectors(*coords.get_entries().copy())
self.list_implicit_assumptions(*coords.get_entries())
def show_standard_coord_meaning(self, x_coord, y_coord):
x, y = self.vector_coords
x_line = Line(ORIGIN, x*RIGHT, color = GREEN)
y_line = Line(ORIGIN, y*UP, color = RED)
y_line.shift(x_line.get_end())
for line, coord, direction in (x_line, x_coord, DOWN), (y_line, y_coord, LEFT):
self.play(
coord.set_color, line.get_color(),
coord.next_to, line.get_center(), direction,
ShowCreation(line),
)
self.wait()
self.wait()
self.play(*list(map(FadeOut, [x_coord, y_coord, x_line, y_line])))
def show_abstract_scalar_idea(self, x_coord, y_coord):
x_shift, y_shift = 4*LEFT, 4*RIGHT
to_save = x_coord, y_coord, self.i_hat, self.j_hat
for mob in to_save:
mob.save_state()
everything = VGroup(*self.get_mobjects())
words = OldTexText("Think of coordinates \\\\ as", "scalars")
words.set_color_by_tex("scalars", YELLOW)
words.to_edge(UP)
x, y = self.vector_coords
scaled_i = self.i_hat.copy().scale(x)
scaled_j = self.j_hat.copy().scale(y)
VGroup(self.i_hat, scaled_i).shift(x_shift)
VGroup(self.j_hat, scaled_j).shift(y_shift)
self.play(
FadeOut(everything),
x_coord.scale, 1.5,
x_coord.move_to, x_shift + 3*UP,
y_coord.scale, 1.5,
y_coord.move_to, y_shift + 3*UP,
Write(words)
)
self.play(*list(map(FadeIn, [self.i_hat, self.j_hat])))
self.wait()
self.play(Transform(self.i_hat, scaled_i))
self.play(Transform(self.j_hat, scaled_j))
self.wait()
self.play(
FadeOut(words),
FadeIn(everything),
*[mob.restore for mob in to_save]
)
self.wait()
def scale_basis_vectors(self, x_coord, y_coord):
self.play(*list(map(Write, [self.i_hat.label, self.j_hat.label])))
self.show_linear_combination(
self.vector_coords,
basis_vectors = [self.i_hat, self.j_hat],
coord_mobs = [x_coord, y_coord]
)
def list_implicit_assumptions(self, x_coord, y_coord):
everything = VGroup(*self.get_mobjects())
title = OldTexText("Implicit assumptions")
h_line = Line(title.get_left(), title.get_right())
h_line.set_color(YELLOW)
h_line.next_to(title, DOWN)
title.add(h_line)
ass1 = OldTexText("-First coordinate")
ass1 = VGroup(ass1, self.i_hat.copy())
ass1.arrange(buff = MED_SMALL_BUFF)
ass2 = OldTexText("-Second coordinate")
ass2 = VGroup(ass2, self.j_hat.copy())
ass2.arrange(buff = MED_SMALL_BUFF)
ass3 = OldTexText("-Unit of distance")
group = VGroup(title, ass1, ass2, ass3)
group.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF)
group.to_corner(UP+LEFT)
# VGroup(*group[1:]).shift(0.5*DOWN)
for words in group:
words.add_to_back(BackgroundRectangle(words))
self.play(Write(title))
self.wait()
self.play(
Write(ass1),
ApplyFunction(
lambda m : m.rotate(np.pi/6).set_color(X_COLOR),
x_coord,
rate_func = wiggle
)
)
self.wait()
self.play(
Write(ass2),
ApplyFunction(
lambda m : m.rotate(np.pi/6).set_color(Y_COLOR),
y_coord,
rate_func = wiggle
)
)
self.wait()
self.play(Write(ass3))
self.wait(2)
keepers = VGroup(*[
self.i_hat, self.j_hat,
self.i_hat.label, self.j_hat.label
])
self.play(
FadeOut(everything),
Animation(keepers.copy()),
Animation(group)
)
self.wait()
class NameCoordinateSystem(Scene):
def construct(self):
vector = Vector([3, 2])
coords = Matrix([3, 2])
arrow = OldTex("\\Rightarrow")
vector.next_to(arrow, RIGHT, buff = 0)
coords.next_to(arrow, LEFT, buff = MED_LARGE_BUFF)
group = VGroup(coords, arrow, vector)
group.shift(2*UP)
coordinate_system = OldTexText("``Coordinate system''")
coordinate_system.next_to(arrow, UP, buff = LARGE_BUFF)
i_hat, j_hat = Vector([1, 0]), Vector([0, 1])
i_hat.set_color(X_COLOR)
j_hat.set_color(Y_COLOR)
i_label = OldTex("\\hat{\\imath}")
i_label.set_color(X_COLOR)
i_label.next_to(i_hat, DOWN)
j_label = OldTex("\\hat{\\jmath}")
j_label.set_color(Y_COLOR)
j_label.next_to(j_hat, LEFT)
basis_group = VGroup(i_hat, j_hat, i_label, j_label)
basis_group.shift(DOWN)
basis_words = OldTexText("``Basis vectors''")
basis_words.shift(basis_group.get_bottom()[1]*UP+MED_SMALL_BUFF*DOWN)
self.play(Write(coords))
self.play(Write(arrow), ShowCreation(vector))
self.wait()
self.play(Write(coordinate_system))
self.wait(2)
self.play(Write(basis_group))
self.play(Write(basis_words))
self.wait()
class WhatAboutOtherBasis(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
\\centering What if we used
different basis vectors
""")
self.random_blink()
self.play_student_changes("pondering")
self.random_blink(2)
class JenniferScene(LinearCombinationScene):
CONFIG = {
"b1_coords" : [2, 1],
"b2_coords" : [-1, 1],
"foreground_plane_kwargs" : {
"x_radius" : FRAME_X_RADIUS,
"y_radius" : FRAME_X_RADIUS,
},
}
def setup(self):
LinearCombinationScene.setup(self)
self.remove(self.plane, self.i_hat, self.j_hat)
self.jenny = Jennifer()
self.you = You()
self.b1 = Vector(self.b1_coords, color = X_COLOR)
self.b2 = Vector(self.b2_coords, color = Y_COLOR)
for i, vect in enumerate([self.b1, self.b2]):
vect.label = OldTex("\\vec{\\textbf{b}}_%d"%(i+1))
vect.label.scale(0.7)
vect.label.add_background_rectangle()
vect.label.set_color(vect.get_color())
self.b1.label.next_to(
self.b1.get_end()*0.4, UP+LEFT, SMALL_BUFF/2
)
self.b2.label.next_to(
self.b2.get_end(), DOWN+LEFT, buff = SMALL_BUFF
)
self.basis_vectors = VGroup(
self.b1, self.b2, self.b1.label, self.b2.label
)
transform = self.get_matrix_transformation(self.cob_matrix().T)
self.jenny_plane = self.plane.copy()
self.jenny_plane.apply_function(transform)
def cob_matrix(self):
return np.array([self.b1_coords, self.b2_coords]).T
def inv_cob_matrix(self):
return np.linalg.inv(self.cob_matrix())
class IntroduceJennifer(JenniferScene):
CONFIG = {
"v_coords" : [3, 2]
}
def construct(self):
for plane in self.plane, self.jenny_plane:
plane.fade()
self.introduce_jenny()
self.add_basis_vectors()
self.show_v_from_both_perspectives()
self.how_we_label_her_basis()
def introduce_jenny(self):
jenny = self.jenny
name = OldTexText("Jennifer")
name.next_to(jenny, UP)
name.shift_onto_screen()
self.add(jenny)
self.play(
jenny.change_mode, "wave_1",
jenny.look, OUT,
Write(name)
)
self.play(
jenny.change_mode, "happy",
jenny.look, UP+RIGHT,
FadeOut(name)
)
self.wait()
def add_basis_vectors(self):
words = OldTexText("Alternate basis vectors")
words.shift(2.5*UP)
self.play(Write(words, run_time = 2))
for vect in self.b1, self.b2:
self.play(
ShowCreation(vect),
Write(vect.label)
)
self.wait()
self.play(FadeOut(words))
def show_v_from_both_perspectives(self):
v = Vector(self.v_coords)
jenny = self.jenny
you = self.you
you.coords = Matrix([3, 2])
jenny.coords = Matrix(["(5/3)", "(1/3)"])
for pi in you, jenny:
pi.bubble = get_small_bubble(pi)
pi.bubble.set_fill(BLACK, opacity = 0.7)
pi.bubble.add_content(pi.coords)
jenny.coords.scale(0.7)
new_coords = [-1, 2]
new_coords_mob = Matrix(new_coords)
new_coords_mob.set_height(jenny.coords.get_height())
new_coords_mob.move_to(jenny.coords)
for coords in you.coords, jenny.coords, new_coords_mob:
for entry in coords.get_entries():
entry.add_background_rectangle()
self.play(ShowCreation(v))
self.wait()
self.play(*it.chain(
list(map(FadeIn, [
self.plane, self.i_hat, self.j_hat,
self.i_hat.label, self.j_hat.label,
you
])),
list(map(Animation, [jenny, v])),
list(map(FadeOut, self.basis_vectors)),
))
self.play(
ShowCreation(you.bubble),
Write(you.coords)
)
self.play(you.change_mode, "speaking")
self.show_linear_combination(
self.v_coords,
basis_vectors = [self.i_hat, self.j_hat],
coord_mobs = you.coords.get_entries().copy(),
)
self.play(*it.chain(
list(map(FadeOut, [
self.plane, self.i_hat, self.j_hat,
self.i_hat.label, self.j_hat.label,
you.bubble, you.coords
])),
list(map(FadeIn, [self.jenny_plane, self.basis_vectors])),
list(map(Animation, [v, you, jenny])),
))
self.play(
ShowCreation(jenny.bubble),
Write(jenny.coords),
jenny.change_mode, "speaking",
)
self.play(you.change_mode, "erm")
self.show_linear_combination(
np.dot(self.inv_cob_matrix(), self.v_coords),
basis_vectors = [self.b1, self.b2],
coord_mobs = jenny.coords.get_entries().copy(),
)
self.play(
FadeOut(v),
jenny.change_mode, "plain"
)
self.play(
Transform(jenny.coords, new_coords_mob),
Blink(jenny),
)
self.hacked_show_linear_combination(
new_coords,
basis_vectors = [self.b1, self.b2],
coord_mobs = jenny.coords.get_entries().copy(),
show_sum_vect = True,
)
def hacked_show_linear_combination(
self, numerical_coords,
basis_vectors,
coord_mobs = None,
show_sum_vect = False,
sum_vect_color = V_COLOR,
):
for coord, basis, scalar in zip(coord_mobs, basis_vectors, numerical_coords):
basis.save_state()
basis.label.save_state()
basis.target = basis.copy().scale(scalar)
basis.label.target = basis.label.copy()
coord.target = coord.copy()
new_label = VGroup(coord.target, basis.label.target)
new_label.arrange(aligned_edge = DOWN)
new_label.move_to(
basis.label,
aligned_edge = basis.get_center()-basis.label.get_center()
)
new_label.shift(
basis.target.get_center() - basis.get_center()
)
coord.target.next_to(basis.label.target, LEFT)
coord.target.set_fill(basis.get_color(), opacity = 1)
self.play(*list(map(MoveToTarget, [
coord, basis, basis.label
])))
self.wait()
self.play(*[
ApplyMethod(m.shift, basis_vectors[0].get_end())
for m in self.get_mobjects_from_last_animation()
])
if show_sum_vect:
sum_vect = Vector(
basis_vectors[1].get_end(),
color = sum_vect_color
)
self.play(ShowCreation(sum_vect))
self.wait(2)
b1, b2 = basis_vectors
self.jenny_plane.save_state()
self.jenny.bubble.save_state()
self.jenny.coords.target = self.jenny.coords.copy()
self.you.bubble.add_content(self.jenny.coords.target)
x, y = numerical_coords
b1.target = self.i_hat.copy().scale(x)
b2.target = self.j_hat.copy().scale(y)
b2.target.shift(b1.target.get_end())
new_label1 = VGroup(coord_mobs[0], b1.label)
new_label2 = VGroup(coord_mobs[1], b2.label)
new_label1.target = new_label1.copy().next_to(b1.target, DOWN)
new_label2.target = new_label2.copy().next_to(b2.target, LEFT)
i_sym = OldTex("\\hat{\\imath}").add_background_rectangle()
j_sym = OldTex("\\hat{\\jmath}").add_background_rectangle()
i_sym.set_color(X_COLOR).move_to(new_label1.target[1], aligned_edge = LEFT)
j_sym.set_color(Y_COLOR).move_to(new_label2.target[1], aligned_edge = LEFT)
Transform(new_label1.target[1], i_sym).update(1)
Transform(new_label2.target[1], j_sym).update(1)
sum_vect.target = Vector(numerical_coords)
self.play(
Transform(self.jenny_plane, self.plane),
Transform(self.jenny.bubble, self.you.bubble),
self.you.change_mode, "speaking",
self.jenny.change_mode, "erm",
*list(map(MoveToTarget, [
self.jenny.coords,
b1, b2, new_label1, new_label2, sum_vect
]))
)
self.play(Blink(self.you))
self.wait()
self.play(*it.chain(
list(map(FadeOut, [
self.jenny.bubble, self.jenny.coords,
coord_mobs, sum_vect
])),
[
ApplyMethod(pi.change_mode, "plain")
for pi in (self.jenny, self.you)
],
[mob.restore for mob in (b1, b2, b1.label, b2.label)]
))
self.jenny.bubble.restore()
def how_we_label_her_basis(self):
you, jenny = self.you, self.jenny
b1_coords = Matrix(self.b1_coords)
b2_coords = Matrix(self.b2_coords)
for coords in b1_coords, b2_coords:
coords.add_to_back(BackgroundRectangle(coords))
coords.scale(0.7)
coords.add_to_back(BackgroundRectangle(coords))
you.bubble.add_content(coords)
coords.mover = coords.copy()
self.play(jenny.change_mode, "erm")
self.play(
ShowCreation(you.bubble),
Write(b1_coords),
you.change_mode, "speaking"
)
self.play(
b1_coords.mover.next_to, self.b1.get_end(), RIGHT,
b1_coords.mover.set_color, X_COLOR
)
self.play(Blink(you))
self.wait()
self.play(Transform(b1_coords, b2_coords))
self.play(
b2_coords.mover.next_to, self.b2.get_end(), LEFT,
b2_coords.mover.set_color, Y_COLOR
)
self.play(Blink(jenny))
for coords, array in (b1_coords, [1, 0]), (b2_coords, [0, 1]):
mover = coords.mover
array_mob = Matrix(array)
array_mob.set_color(mover.get_color())
array_mob.set_height(mover.get_height())
array_mob.move_to(mover)
array_mob.add_to_back(BackgroundRectangle(array_mob))
mover.target = array_mob
self.play(
self.jenny_plane.restore,
FadeOut(self.you.bubble),
FadeOut(b1_coords),
self.jenny.change_mode, "speaking",
self.you.change_mode, "confused",
*list(map(Animation, [
self.basis_vectors,
b1_coords.mover,
b2_coords.mover,
]))
)
self.play(MoveToTarget(b1_coords.mover))
self.play(MoveToTarget(b2_coords.mover))
self.play(Blink(self.jenny))
class SpeakingDifferentLanguages(JenniferScene):
def construct(self):
jenny, you = self.jenny, self.you
title = OldTexText("Different languages")
title.to_edge(UP)
vector = Vector([3, 2])
vector.center().shift(DOWN)
you.coords = Matrix([3, 2])
you.text = OldTexText("Looks to be")
jenny.coords = Matrix(["5/3", "1/3"])
jenny.text = OldTexText("Non, c'est")
for pi in jenny, you:
pi.bubble = pi.get_bubble(SpeechBubble, width = 4.5, height = 3.5)
if pi is you:
pi.bubble.shift(MED_SMALL_BUFF*RIGHT)
else:
pi.coords.scale(0.8)
pi.bubble.shift(MED_SMALL_BUFF*LEFT)
pi.coords.next_to(pi.text, buff = MED_SMALL_BUFF)
pi.coords.add(pi.text)
pi.bubble.add_content(pi.coords)
self.add(you, jenny)
self.play(Write(title))
self.play(
ShowCreation(vector),
you.look_at, vector,
jenny.look_at, vector,
)
for pi in you, jenny:
self.play(
pi.change_mode, "speaking" if pi is you else "sassy",
ShowCreation(pi.bubble),
Write(pi.coords)
)
self.play(Blink(pi))
self.wait()
class ShowGrid(LinearTransformationScene):
CONFIG = {
"include_background_plane" : False,
}
def construct(self):
self.remove(self.i_hat, self.j_hat)
self.wait()
self.plane.prepare_for_nonlinear_transform()
self.plane.save_state()
self.play(Homotopy(plane_wave_homotopy, self.plane))
self.play(self.plane.restore)
for vect in self.i_hat, self.j_hat:
self.play(ShowCreation(vect))
self.wait()
class GridIsAConstruct(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
\\centering
The grid is
just a construct
""")
self.play_student_changes(*["pondering"]*3)
self.random_blink(2)
class SpaceHasNoGrid(LinearTransformationScene):
CONFIG = {
"include_background_plane" : False
}
def construct(self):
words = OldTexText("Space has no grid")
words.to_edge(UP)
self.play(
Write(words),
FadeOut(self.plane),
*list(map(Animation, [self.i_hat, self.j_hat]))
)
self.wait()
class JennysGrid(JenniferScene):
def construct(self):
self.add(self.jenny)
self.jenny.shift(3*RIGHT)
bubble = self.jenny.get_bubble(SpeechBubble, width = 4)
bubble.flip()
bubble.set_fill(BLACK, opacity = 0.8)
bubble.to_edge(LEFT)
bubble.write("""
This grid is also
just a construct
""")
coords = [1.5, -3]
coords_mob = Matrix(coords)
coords_mob.add_background_to_entries()
bubble.position_mobject_inside(coords_mob)
for vect in self.b1, self.b2:
self.play(
ShowCreation(vect),
Write(vect.label)
)
self.wait()
self.play(
ShowCreation(
self.jenny_plane,
run_time = 3,
lag_ratio = 0.5
),
self.jenny.change_mode, "speaking",
self.jenny.look_at, ORIGIN,
ShowCreation(bubble),
Write(bubble.content),
Animation(self.basis_vectors)
)
self.play(Blink(self.jenny))
self.play(
FadeOut(bubble.content),
FadeIn(coords_mob)
)
self.show_linear_combination(
numerical_coords = coords,
basis_vectors = [self.b1, self.b2],
coord_mobs = coords_mob.get_entries().copy(),
show_sum_vect = True
)
class ShowOriginOfGrid(JenniferScene):
def construct(self):
for plane in self.plane, self.jenny_plane:
plane.fade(0.3)
self.add(self.jenny_plane)
self.jenny_plane.save_state()
origin_word = OldTexText("Origin")
origin_word.shift(2*RIGHT+2.5*UP)
origin_word.add_background_rectangle()
arrow = Arrow(origin_word, ORIGIN, color = RED)
origin_dot = Dot(ORIGIN, radius = 0.1, color = RED)
coords = Matrix([0, 0])
coords.add_to_back(BackgroundRectangle(coords))
coords.next_to(ORIGIN, DOWN+LEFT)
vector = Vector([3, -2], color = PINK)
self.play(
Write(origin_word),
ShowCreation(arrow)
)
self.play(ShowCreation(origin_dot))
self.wait()
self.play(
Transform(self.jenny_plane, self.plane),
*list(map(Animation, [origin_word, origin_dot, arrow]))
)
self.wait()
self.play(Write(coords))
self.wait()
self.play(FadeIn(vector))
self.wait()
self.play(Transform(vector, Mobject.scale(vector.copy(), 0)))
self.wait()
self.play(
self.jenny_plane.restore,
*list(map(Animation, [origin_word, origin_dot, arrow, coords]))
)
for vect in self.b1, self.b2:
self.play(
ShowCreation(vect),
Write(vect.label)
)
self.wait()
class AskAboutTranslation(TeacherStudentsScene):
def construct(self):
self.student_says(
"\\centering How do you translate \\\\ between coordinate systems?",
target_mode = "raise_right_hand"
)
self.random_blink(3)
class TranslateFromJenny(JenniferScene):
CONFIG = {
"coords" : [-1, 2]
}
def construct(self):
self.add_players()
self.ask_question()
self.establish_coordinates()
self.perform_arithmetic()
def add_players(self):
for plane in self.jenny_plane, self.plane:
plane.fade()
self.add(
self.jenny_plane,
self.jenny, self.you,
self.basis_vectors
)
self.jenny.coords = Matrix(self.coords)
self.you.coords = Matrix(["?", "?"])
self.you.coords.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR)
for pi in self.jenny, self.you:
pi.bubble = get_small_bubble(pi)
pi.bubble.set_fill(BLACK, opacity = 0.8)
pi.coords.scale(0.8)
pi.coords.add_background_to_entries()
pi.bubble.add_content(pi.coords)
def ask_question(self):
self.play(
self.jenny.change_mode, "pondering",
ShowCreation(self.jenny.bubble),
Write(self.jenny.coords)
)
coord_mobs = self.jenny.coords.get_entries().copy()
self.basis_vectors_copy = self.basis_vectors.copy()
self.basis_vectors_copy.fade(0.3)
self.add(self.basis_vectors_copy, self.basis_vectors)
sum_vect = self.show_linear_combination(
numerical_coords = self.coords,
basis_vectors = [self.b1, self.b2],
coord_mobs = coord_mobs,
revert_to_original = False,
show_sum_vect = True,
)
self.wait()
everything = self.get_mobjects()
for submob in self.jenny_plane.get_family():
everything.remove(submob)
self.play(
Transform(self.jenny_plane, self.plane),
*list(map(Animation, everything))
)
self.play(
self.you.change_mode, "confused",
ShowCreation(self.you.bubble),
Write(self.you.coords)
)
self.wait()
def establish_coordinates(self):
b1, b2 = self.basis_vectors_copy[:2]
b1_coords = Matrix(self.b1_coords).set_color(X_COLOR)
b2_coords = Matrix(self.b2_coords).set_color(Y_COLOR)
for coords in b1_coords, b2_coords:
coords.scale(0.7)
coords.add_to_back(BackgroundRectangle(coords))
b1_coords.next_to(b1.get_end(), RIGHT)
b2_coords.next_to(b2.get_end(), UP)
for coords in b1_coords, b2_coords:
self.play(Write(coords))
self.b1_coords_mob, self.b2_coords_mob = b1_coords, b2_coords
def perform_arithmetic(self):
jenny_x, jenny_y = self.jenny.coords.get_entries().copy()
equals, plus, equals2 = syms = list(map(Tex, list("=+=")))
result = Matrix([-4, 1])
result.set_height(self.you.coords.get_height())
for mob in syms + [self.you.coords, self.jenny.coords, result]:
mob.add_to_back(BackgroundRectangle(mob))
movers = [
self.you.coords, equals,
jenny_x, self.b1_coords_mob, plus,
jenny_y, self.b2_coords_mob,
equals2, result
]
for mover in movers:
mover.target = mover.copy()
mover_targets = VGroup(*[mover.target for mover in movers])
mover_targets.arrange()
mover_targets.to_edge(UP)
for mob in syms + [result]:
mob.move_to(mob.target)
mob.set_fill(BLACK, opacity = 0)
mover_sets = [
[jenny_x, self.b1_coords_mob],
[plus, jenny_y, self.b2_coords_mob],
[self.you.coords, equals],
]
for mover_set in mover_sets:
self.play(*list(map(MoveToTarget, mover_set)))
self.wait()
self.play(
MoveToTarget(equals2),
Transform(self.b1_coords_mob.copy(), result.target),
Transform(self.b2_coords_mob.copy(), result.target),
)
self.remove(*self.get_mobjects_from_last_animation())
result = result.target
self.add(equals2, result)
self.wait()
result_copy = result.copy()
self.you.bubble.add_content(result_copy)
self.play(
self.you.change_mode, "hooray",
Transform(result.copy(), result_copy)
)
self.play(Blink(self.you))
self.wait()
matrix = Matrix(np.array([self.b1_coords, self.b2_coords]).T)
matrix.set_column_colors(X_COLOR, Y_COLOR)
self.jenny.coords.target = self.jenny.coords.copy()
self.jenny.coords.target.next_to(equals, LEFT)
matrix.set_height(self.jenny.coords.get_height())
matrix.next_to(self.jenny.coords.target, LEFT)
matrix.add_to_back(BackgroundRectangle(matrix))
self.play(
FadeOut(self.jenny.bubble),
FadeOut(self.you.coords),
self.jenny.change_mode, "plain",
MoveToTarget(self.jenny.coords),
FadeIn(matrix)
)
self.wait()
class WatchChapter3(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
You've all watched
chapter 3, right?
""")
self.random_blink()
self.play(
self.get_students()[0].look, LEFT,
self.get_students()[1].change_mode, "happy",
self.get_students()[2].change_mode, "happy",
)
self.random_blink(2)
class TalkThroughChangeOfBasisMatrix(JenniferScene):
def construct(self):
self.add(self.plane, self.jenny, self.you)
self.plane.fade()
self.jenny_plane.fade()
for pi in self.jenny, self.you:
pi.bubble = get_small_bubble(pi)
matrix = Matrix(np.array([self.b1_coords, self.b2_coords]).T)
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(ORIGIN, RIGHT, buff = MED_SMALL_BUFF).to_edge(UP)
b1_coords = Matrix(self.b1_coords)
b1_coords.set_color(X_COLOR)
b1_coords.next_to(self.b1.get_end(), RIGHT)
b2_coords = Matrix(self.b2_coords)
b2_coords.set_color(Y_COLOR)
b2_coords.next_to(self.b2.get_end(), UP)
for coords in b1_coords, b2_coords:
coords.scale(0.7)
basis_coords_pair = VGroup(
Matrix([1, 0]).set_color(X_COLOR).scale(0.7),
OldTex(","),
Matrix([0, 1]).set_color(Y_COLOR).scale(0.7),
)
basis_coords_pair.arrange(aligned_edge = DOWN)
self.you.bubble.add_content(basis_coords_pair)
t_matrix1 = np.array([self.b1_coords, [0, 1]])
t_matrix2 = np.dot(
self.cob_matrix(),
np.linalg.inv(t_matrix1.T)
).T
for mob in matrix, b1_coords, b2_coords:
mob.rect = BackgroundRectangle(mob)
mob.add_to_back(mob.rect)
self.play(Write(matrix))
for vect in self.i_hat, self.j_hat:
self.play(
ShowCreation(vect),
Write(vect.label)
)
self.play(
self.you.change_mode, "pondering",
ShowCreation(self.you.bubble),
Write(basis_coords_pair)
)
self.play(Blink(self.you))
self.wait()
self.add_foreground_mobject(
self.jenny, self.you, self.you.bubble,
basis_coords_pair, matrix
)
matrix_copy = matrix.copy()
matrix_copy.rect.set_fill(opacity = 0)
self.apply_transposed_matrix(
t_matrix1,
added_anims = [
Transform(self.i_hat, self.b1),
Transform(self.i_hat.label, self.b1.label),
Transform(matrix_copy.rect, b1_coords.rect),
Transform(
matrix_copy.get_brackets(),
b1_coords.get_brackets(),
),
Transform(
VGroup(*matrix_copy.get_mob_matrix()[:,0]),
b1_coords.get_entries()
),
]
)
self.remove(matrix_copy)
self.add_foreground_mobject(b1_coords)
matrix_copy = matrix.copy()
matrix_copy.rect.set_fill(opacity = 0)
self.apply_transposed_matrix(
t_matrix2,
added_anims = [
Transform(self.j_hat, self.b2),
Transform(self.j_hat.label, self.b2.label),
Transform(matrix_copy.rect, b2_coords.rect),
Transform(
matrix_copy.get_brackets(),
b2_coords.get_brackets(),
),
Transform(
VGroup(*matrix_copy.get_mob_matrix()[:,1]),
b2_coords.get_entries()
),
]
)
self.remove(matrix_copy)
self.add_foreground_mobject(b2_coords)
basis_coords_pair.target = basis_coords_pair.copy()
self.jenny.bubble.add_content(basis_coords_pair.target)
self.wait()
self.play(
FadeOut(b1_coords),
FadeOut(b2_coords),
self.jenny.change_mode, "speaking",
Transform(self.you.bubble, self.jenny.bubble),
MoveToTarget(basis_coords_pair),
)
class ChangeOfBasisExample(JenniferScene):
CONFIG = {
"v_coords" : [-1, 2]
}
def construct(self):
self.add(
self.plane, self.i_hat, self.j_hat,
self.i_hat.label, self.j_hat.label,
)
self.j_hat.label.next_to(self.j_hat, RIGHT)
v = self.add_vector(self.v_coords)
v_coords = Matrix(self.v_coords)
v_coords.scale(0.8)
v_coords.add_to_back(BackgroundRectangle(v_coords))
v_coords.to_corner(UP+LEFT)
v_coords.add_background_to_entries()
for pi in self.you, self.jenny:
pi.change_mode("pondering")
pi.bubble = get_small_bubble(pi)
pi.bubble.add_content(v_coords.copy())
pi.add(pi.bubble, pi.bubble.content)
start_words = OldTexText("How", "we", "think of")
start_words.add_background_rectangle()
start_group = VGroup(start_words, v_coords)
start_group.arrange(buff = MED_SMALL_BUFF)
start_group.next_to(self.you, LEFT, buff = 0)
start_group.to_edge(UP)
end_words = OldTexText("How", "Jennifer", "thinks of")
end_words.add_background_rectangle()
end_words.move_to(start_words, aligned_edge = RIGHT)
self.play(
Write(start_group),
FadeIn(self.you),
)
self.add_foreground_mobject(start_group, self.you)
self.show_linear_combination(
numerical_coords = self.v_coords,
basis_vectors = [self.i_hat, self.j_hat],
coord_mobs = v_coords.get_entries().copy(),
)
self.play(*list(map(FadeOut, [self.i_hat.label, self.j_hat.label])))
self.apply_transposed_matrix(self.cob_matrix().T)
VGroup(self.i_hat, self.j_hat).fade()
self.add(self.b1, self.b2)
self.play(
Transform(start_words, end_words),
Transform(self.you, self.jenny),
*list(map(Write, [self.b1.label, self.b2.label]))
)
self.play(Blink(self.you))
self.show_linear_combination(
numerical_coords = self.v_coords,
basis_vectors = [self.b1, self.b2],
coord_mobs = v_coords.get_entries().copy(),
)
class FeelsBackwards(Scene):
def construct(self):
matrix = Matrix(np.array([
JenniferScene.CONFIG["b1_coords"],
JenniferScene.CONFIG["b2_coords"],
]).T)
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.shift(UP)
top_arrow = Arrow(matrix.get_left(), matrix.get_right())
bottom_arrow = top_arrow.copy().rotate(np.pi)
top_arrow.next_to(matrix, UP, buff = LARGE_BUFF)
bottom_arrow.next_to(matrix, DOWN, buff = LARGE_BUFF)
top_arrow.set_color(BLUE)
jenny_grid = OldTexText("Jennifer's grid").set_color(BLUE)
our_grid = OldTexText("Our grid").set_color(BLUE)
jenny_language = OldTexText("Jennifer's language")
our_language = OldTexText("Our language")
our_grid.next_to(top_arrow, LEFT)
jenny_grid.next_to(top_arrow, RIGHT)
jenny_language.next_to(bottom_arrow, RIGHT)
our_language.next_to(bottom_arrow, LEFT)
self.add(matrix)
self.play(Write(our_grid))
self.play(
ShowCreation(top_arrow),
Write(jenny_grid)
)
self.wait()
self.play(Write(jenny_language))
self.play(
ShowCreation(bottom_arrow),
Write(our_language)
)
self.wait()
##Swap things
inverse_word = OldTexText("Inverse")
inverse_word.next_to(matrix, LEFT, buff = MED_SMALL_BUFF)
inverse_exponent = OldTex("-1")
inverse_exponent.next_to(matrix.get_corner(UP+RIGHT), RIGHT)
self.play(*list(map(Write, [inverse_word, inverse_exponent])))
self.play(
Swap(jenny_grid, our_grid),
top_arrow.scale, 0.8,
top_arrow.shift, 0.8*RIGHT,
top_arrow.set_color, BLUE,
)
self.play(
Swap(jenny_language, our_language),
bottom_arrow.scale, 0.8,
bottom_arrow.shift, 0.8*RIGHT
)
self.wait()
class AskAboutOtherWayAround(TeacherStudentsScene):
def construct(self):
self.student_says("""
What about the
other way around?
""")
self.random_blink(3)
class RecallInverse(JenniferScene):
def construct(self):
numerical_t_matrix = np.array([self.b1_coords, self.b2_coords])
matrix = Matrix(numerical_t_matrix.T)
matrix.add_to_back(BackgroundRectangle(matrix))
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.to_corner(UP+LEFT, buff = MED_LARGE_BUFF)
# matrix.shift(MED_SMALL_BUFF*DOWN)
inverse_exponent = OldTex("-1")
inverse_exponent.next_to(matrix.get_corner(UP+RIGHT), RIGHT)
inverse_exponent.add_background_rectangle()
brace = Brace(VGroup(matrix, inverse_exponent))
inverse_word = brace.get_text("Inverse")
inverse_word.add_background_rectangle()
equals = OldTex("=")
equals.add_background_rectangle()
inv_matrix = Matrix([
["1/3", "1/3"],
["-1/3", "2/3"]
])
inv_matrix.set_height(matrix.get_height())
inv_matrix.add_to_back(BackgroundRectangle(inv_matrix))
equals.next_to(matrix, RIGHT, buff = 0.7)
inv_matrix.next_to(equals, RIGHT, buff = MED_SMALL_BUFF)
self.add_foreground_mobject(matrix)
self.apply_transposed_matrix(numerical_t_matrix)
self.play(
GrowFromCenter(brace),
Write(inverse_word),
Write(inverse_exponent)
)
self.add_foreground_mobject(*self.get_mobjects_from_last_animation())
self.wait()
self.apply_inverse_transpose(numerical_t_matrix)
self.wait()
self.play(
Write(equals),
Transform(matrix.copy(), inv_matrix)
)
self.remove(*self.get_mobjects_from_last_animation())
self.add_foreground_mobject(equals, inv_matrix)
self.wait()
for mob in self.plane, self.i_hat, self.j_hat:
self.add(mob.copy().fade(0.7))
self.apply_transposed_matrix(numerical_t_matrix)
self.play(FadeIn(self.jenny))
self.play(self.jenny.change_mode, "speaking")
#Little hacky now
inv_matrix.set_column_colors(X_COLOR)
self.play(*[
ApplyMethod(
mob.scale, 1.2,
rate_func = there_and_back
)
for mob in inv_matrix.get_mob_matrix()[:,0]
])
self.wait()
inv_matrix.set_column_colors(X_COLOR, Y_COLOR)
self.play(*[
ApplyMethod(
mob.scale, 1.2,
rate_func = there_and_back
)
for mob in inv_matrix.get_mob_matrix()[:,1]
])
self.wait()
class WorkOutInverseComputation(Scene):
def construct(self):
our_vector = Matrix([3, 2])
her_vector = Matrix(["5/3", "1/3"])
matrix = Matrix([["1/3", "1/3"], ["-1/3", "2/3"]])
our_vector.set_color(BLUE_D)
her_vector.set_color(MAROON_B)
equals = OldTex("=")
equation = VGroup(
matrix, our_vector, equals, her_vector
)
for mob in equation:
if isinstance(mob, Matrix):
mob.set_height(2)
equation.arrange()
matrix_brace = Brace(matrix, UP)
our_vector_brace = Brace(our_vector)
her_vector_brace = Brace(her_vector, UP)
matrix_text = matrix_brace.get_text("""
\\centering
Inverse
change of basis
matrix
""")
our_text = our_vector_brace.get_text("""
\\centering
Written in
our language
""")
our_text.set_color(our_vector.get_color())
her_text = her_vector_brace.get_text("""
\\centering
Same vector
in her language
""")
her_text.set_color(her_vector.get_color())
for text in our_text, her_text:
text.scale(0.7)
self.add(our_vector)
self.play(
GrowFromCenter(our_vector_brace),
Write(our_text)
)
self.wait()
self.play(
FadeIn(matrix),
GrowFromCenter(matrix_brace),
Write(matrix_text)
)
self.wait()
self.play(
Write(equals),
Write(her_vector)
)
self.play(
GrowFromCenter(her_vector_brace),
Write(her_text)
)
self.wait()
class SoThatsTranslation(TeacherStudentsScene):
def construct(self):
self.teacher_says("So that's translation")
self.random_blink(3)
class SummarizeTranslationProcess(Scene):
def construct(self):
self.define_matrix()
self.show_translation()
def define_matrix(self):
matrix = Matrix([[2, -1], [1, 1]])
matrix.set_column_colors(X_COLOR, Y_COLOR)
A, equals = list(map(Tex, list("A=")))
equation = VGroup(A, equals, matrix)
equation.arrange()
equation.to_corner(UP+LEFT)
equation.shift(RIGHT)
words = OldTexText("""
Jennifer's basis vectors,
written in our coordinates
""")
words.to_edge(LEFT)
mob_matrix = matrix.get_mob_matrix()
arrow1 = Arrow(words, mob_matrix[1, 0], color = X_COLOR)
arrow2 = Arrow(words, mob_matrix[1, 1], color = Y_COLOR)
self.add(A, equals, matrix)
self.play(
Write(words),
*list(map(ShowCreation, [arrow1, arrow2]))
)
self.A_copy = A.copy()
def show_translation(self):
our_vector = Matrix(["x_o", "y_o"])
her_vector = Matrix(["x_j", "y_j"])
for vector, color in (our_vector, BLUE_D), (her_vector, MAROON_B):
# vector.set_height(1.5)
vector.set_color(color)
A = OldTex("A")
A_inv = OldTex("A^{-1}")
equals = OldTex("=")
equation = VGroup(A, her_vector, equals, our_vector)
equation.arrange()
equation.to_edge(RIGHT)
equation.shift(0.5*UP)
A_inv.next_to(our_vector, LEFT)
her_words = OldTexText("Vector in her coordinates")
her_words.set_color(her_vector.get_color())
her_words.scale(0.8).to_corner(UP+RIGHT)
her_arrow = Arrow(
her_words, her_vector,
color = her_vector.get_color()
)
our_words = OldTexText("Same vector in\\\\ our coordinates")
our_words.set_color(our_vector.get_color())
our_words.scale(0.8).to_edge(RIGHT).shift(2*DOWN)
our_words.shift_onto_screen()
our_arrow = Arrow(
our_words.get_top(), our_vector.get_bottom(),
color = our_vector.get_color()
)
self.play(
Write(equation),
Transform(self.A_copy, A)
)
self.remove(self.A_copy)
self.play(
Write(her_words),
ShowCreation(her_arrow)
)
self.play(
Write(our_words),
ShowCreation(our_arrow)
)
self.wait(2)
self.play(
VGroup(her_vector, equals).next_to, A_inv, LEFT,
her_arrow.rotate, -np.pi/6,
her_arrow.shift, MED_SMALL_BUFF*LEFT,
Transform(A, A_inv, path_arc = np.pi)
)
self.wait()
class VectorsAreNotTheOnlyOnes(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
\\centering
Vectors aren't the
only thing with coordinates
""")
self.play_student_changes("pondering", "confused", "erm")
self.random_blink(3)
class Prerequisites(Scene):
def construct(self):
title = OldTexText("Prerequisites")
title.to_edge(UP)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
h_line.next_to(title, DOWN)
self.add(title, h_line)
prereqs = list(map(TexText, [
"Linear transformations",
"Matrix multiplication",
]))
for direction, words in zip([LEFT, RIGHT], prereqs):
rect = Rectangle(height = 9, width = 16)
rect.set_height(3.5)
rect.next_to(ORIGIN, direction, buff = MED_SMALL_BUFF)
rect.set_color(BLUE)
words.next_to(rect, UP, buff = MED_SMALL_BUFF)
self.play(
Write(words),
ShowCreation(rect)
)
self.wait()
class RotationExample(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[0, 1], [-1, 0]]
}
def construct(self):
words = OldTexText("$90^\\circ$ rotation")
words.scale(1.2)
words.add_background_rectangle()
words.to_edge(UP)
matrix = Matrix(self.t_matrix.T)
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.rect = BackgroundRectangle(matrix)
matrix.add_to_back(matrix.rect)
matrix.next_to(words, DOWN)
matrix.shift(2*RIGHT)
self.play(Write(words))
self.add_foreground_mobject(words)
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
self.play(
self.i_hat.rotate, np.pi/12,
self.j_hat.rotate, -np.pi/12,
rate_func = wiggle,
run_time = 2
)
self.wait()
i_coords, j_coords = coord_arrays = list(map(Matrix, self.t_matrix))
for coords, vect in zip(coord_arrays, [self.i_hat, self.j_hat]):
coords.scale(0.7)
coords.rect = BackgroundRectangle(coords)
coords.add_to_back(coords.rect)
coords.set_color(vect.get_color())
direction = UP if vect is self.j_hat else RIGHT
coords.next_to(vect.get_end(), direction, buff = MED_SMALL_BUFF)
self.play(Write(coords))
self.wait()
self.play(
Transform(i_coords.rect, matrix.rect),
Transform(i_coords.get_brackets(), matrix.get_brackets()),
Transform(
i_coords.get_entries(),
VGroup(*matrix.get_mob_matrix()[:, 0])
),
)
self.play(
FadeOut(j_coords.rect),
FadeOut(j_coords.get_brackets()),
Transform(
j_coords.get_entries(),
VGroup(*matrix.get_mob_matrix()[:, 1])
),
)
self.wait()
self.add_words(matrix)
def add_words(self, matrix):
follow_basis = OldTexText(
"Follow", "our choice",
"\\\\ of basis vectors"
)
follow_basis.set_color_by_tex("our choice", YELLOW)
follow_basis.add_background_rectangle()
follow_basis.next_to(
matrix, LEFT,
buff = MED_SMALL_BUFF,
)
record = OldTexText(
"Record using \\\\",
"our coordinates"
)
record.set_color_by_tex("our coordinates", YELLOW)
record.add_background_rectangle()
record.next_to(
matrix, DOWN,
buff = MED_SMALL_BUFF,
aligned_edge = LEFT
)
self.play(Write(follow_basis))
self.wait()
self.play(Write(record))
self.wait()
class JennyWatchesRotation(JenniferScene):
def construct(self):
jenny = self.jenny
self.add(self.jenny_plane.copy().fade())
self.add(self.jenny_plane)
self.add(jenny)
for vect in self.b1, self.b2:
self.add_vector(vect)
matrix = Matrix([["?", "?"], ["?", "?"]])
matrix.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR)
jenny.bubble = get_small_bubble(jenny)
jenny.bubble.add_content(matrix)
matrix.scale(0.8)
self.play(
jenny.change_mode, "sassy",
ShowCreation(jenny.bubble),
Write(matrix)
)
self.play(*it.chain(
[
Rotate(mob, np.pi/2, run_time = 3)
for mob in (self.jenny_plane, self.b1, self.b2)
],
list(map(Animation, [jenny, jenny.bubble, matrix]))
))
self.play(jenny.change_mode, "pondering")
self.play(Blink(jenny))
self.wait()
class AksAboutTranslatingColumns(TeacherStudentsScene):
def construct(self):
matrix = Matrix([[0, -1], [1, 0]])
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.scale(0.7)
words = OldTexText("Translate columns of")
matrix.next_to(words, DOWN)
words.add(matrix)
self.student_says(words, index = 0)
self.random_blink(2)
student = self.get_students()[0]
bubble = get_small_bubble(student)
bubble.set_fill(opacity = 0)
matrix.target = matrix.copy()
bubble.add_content(matrix.target)
self.play(
Transform(student.bubble, bubble),
FadeOut(student.bubble.content),
MoveToTarget(matrix.copy()),
student.change_mode, "pondering",
)
self.remove(student.bubble)
student.bubble = None
self.add(bubble, matrix.target)
self.random_blink()
words = OldTexText(
"\\centering Those columns still \\\\ represent ",
"our basis", ", not ", "hers",
arg_separator = ""
)
words.set_color_by_tex("our basis", BLUE)
words.set_color_by_tex("hers", MAROON_B)
self.teacher_says(words)
self.play_student_changes("erm", "pondering", "pondering")
self.random_blink()
class HowToTranslateAMatrix(Scene):
def construct(self):
self.add_title()
arrays = VGroup(*list(map(Matrix, [
[["1/3", "-2/3"], ["5/3", "-1/3"]],
[-1, 2],
[[2, -1], [1, 1]],
[[0, -1], [1, 0]],
[[2, -1], [1, 1]],
])))
result, her_vector, cob_matrix, transform, inv_cob = arrays
neg_1 = OldTex("-1")
neg_1.next_to(inv_cob.get_corner(UP+RIGHT), RIGHT)
inv_cob.add(neg_1)
arrays.arrange(LEFT)
arrays.to_edge(LEFT, buff = LARGE_BUFF/2.)
for array in arrays:
array.brace = Brace(array)
array.top_brace = Brace(VGroup(array, her_vector), UP)
for array in cob_matrix, inv_cob:
submobs = array.split()
submobs.sort(key=lambda m: m.get_center()[0])
array.submobjects = submobs
her_vector.set_color(MAROON_B)
cob_matrix.set_color_by_gradient(BLUE, MAROON_B)
transform.set_column_colors(X_COLOR, Y_COLOR)
transform.get_brackets().set_color(BLUE)
inv_cob.set_color_by_gradient(MAROON_B, BLUE)
result.set_column_colors(X_COLOR, Y_COLOR)
result.get_brackets().set_color(MAROON_B)
final_top_brace = Brace(VGroup(cob_matrix, inv_cob), UP)
brace_text_pairs = [
(her_vector.brace, ("Vector in \\\\", "Jennifer's language")),
(her_vector.top_brace, ("",)),
(cob_matrix.brace, ("Change of basis \\\\", "matrix")),
(cob_matrix.top_brace, ("Same vector \\\\", "in", "our", "language")),
(transform.brace, ("Transformation matrix \\\\", "in", "our", "language")),
(transform.top_brace, ("Transformed vector \\\\", "in", "our", "language")),
(inv_cob.brace, ("Inverse \\\\", "change of basis \\\\", "matrix")),
(inv_cob.top_brace, ("Transformed vector \\\\", "in", "her", "language")),
(final_top_brace, ("Transformation matrix \\\\", "in", "her", "language"))
]
for brace, text_args in brace_text_pairs:
text_args = list(text_args)
text_args[0] = "\\centering " + text_args[0]
text = OldTexText(*text_args)
text.set_color_by_tex("our", BLUE)
text.set_color_by_tex("her", MAROON_B)
brace.put_at_tip(text)
brace.text = text
brace = her_vector.brace
bottom_words = her_vector.brace.text
top_brace = cob_matrix.top_brace
top_words = cob_matrix.top_brace.text
def introduce(array):
self.play(
Write(array),
Transform(brace, array.brace),
Transform(bottom_words, array.brace.text)
)
self.wait()
def echo_introduce(array):
self.play(
Transform(top_brace, array.top_brace),
Transform(top_words, array.top_brace.text)
)
self.wait()
self.play(Write(her_vector))
self.play(
GrowFromCenter(brace),
Write(bottom_words)
)
self.wait()
introduce(cob_matrix)
self.play(
GrowFromCenter(top_brace),
Write(top_words)
)
self.wait()
introduce(transform)
echo_introduce(transform)
introduce(inv_cob),
echo_introduce(inv_cob)
#Genearlize to single matrix
v = OldTex("\\vec{\\textbf{v}}")
v.set_color(her_vector.get_color())
v.move_to(her_vector, aligned_edge = LEFT)
self.play(
Transform(her_vector, v),
FadeOut(bottom_words),
FadeOut(brace),
)
self.wait()
self.play(
Transform(top_brace, final_top_brace),
Transform(top_brace.text, final_top_brace.text),
)
self.wait()
equals = OldTex("=")
equals.replace(v)
result.next_to(equals, RIGHT)
self.play(
Transform(her_vector, equals),
Write(result)
)
self.wait(2)
everything = VGroup(*self.get_mobjects())
self.play(
FadeOut(everything),
result.to_corner, UP+LEFT
)
self.add(result)
self.wait()
def add_title(self):
title = OldTexText("How to translate a matrix")
title.to_edge(UP)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
h_line.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(h_line))
self.wait()
class JennyWatchesRotationWithMatrixAndVector(JenniferScene):
def construct(self):
self.add(self.jenny_plane.copy().fade(0.8))
self.add(self.jenny_plane, self.jenny, self.b1, self.b2)
matrix = Matrix([["1/3", "-2/3"], ["5/3", "-1/3"]])
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.to_corner(UP+LEFT)
vector_coords = [1, 2]
vector_array = Matrix(vector_coords)
vector_array.set_color(YELLOW)
vector_array.next_to(matrix, RIGHT)
result = Matrix([-1, 1])
equals = OldTex("=")
equals.next_to(vector_array)
result.next_to(equals)
for array in matrix, vector_array, result:
array.add_to_back(BackgroundRectangle(array))
vector = Vector(np.dot(self.cob_matrix(), vector_coords))
self.add(matrix)
self.play(Write(vector_array))
self.play(ShowCreation(vector))
self.play(Blink(self.jenny))
self.play(*it.chain(
[
Rotate(mob, np.pi/2, run_time = 3)
for mob in (self.jenny_plane, self.b1, self.b2, vector)
],
list(map(Animation, [self.jenny, matrix, vector_array])),
))
self.play(
self.jenny.change_mode, "pondering",
Write(equals),
Write(result)
)
self.play(Blink(self.jenny))
self.wait()
class MathematicalEmpathy(TeacherStudentsScene):
def construct(self):
words = OldTexText(
"\\centering An expression like",
"$A^{-1} M A$",
"\\\\ suggests a mathematical \\\\",
"sort of empathy"
)
A1, neg, one, M, A2 = words[1]
As = VGroup(A1, neg, one, A2)
VGroup(As, M).set_color(YELLOW)
self.teacher_says(words)
self.random_blink()
for mob, color in (M, BLUE), (As, MAROON_B):
self.play(mob.set_color, color)
self.play(mob.scale, 1.2, rate_func = there_and_back)
self.random_blink(2)
class NextVideo(Scene):
def construct(self):
title = OldTexText("""
Next video: Eigenvectors and eigenvalues
""")
title.to_edge(UP, buff = MED_SMALL_BUFF)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
|
|
from manim_imports_ext import *
from ka_playgrounds.circuits import Resistor, Source, LongResistor
class OpeningQuote(Scene):
def construct(self):
words = OldTexText(
"To ask the",
"right question\\\\",
"is harder than to answer it."
)
words.to_edge(UP)
words[1].set_color(BLUE)
author = OldTexText("-Georg Cantor")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = 0.5)
self.play(FadeIn(words))
self.wait(2)
self.play(Write(author, run_time = 3))
self.wait()
class ListTerms(Scene):
def construct(self):
title = OldTexText("Under the light of linear transformations")
title.set_color(YELLOW)
title.to_edge(UP)
randy = Randolph().to_corner()
words = VMobject(*list(map(TexText, [
"Inverse matrices",
"Column space",
"Rank",
"Null space",
])))
words.arrange(DOWN, aligned_edge = LEFT)
words.next_to(title, DOWN, aligned_edge = LEFT)
words.shift(RIGHT)
self.add(title, randy)
for i, word in enumerate(words.split()):
self.play(Write(word), run_time = 1)
if i%2 == 0:
self.play(Blink(randy))
else:
self.wait()
self.wait()
class NoComputations(TeacherStudentsScene):
def construct(self):
self.setup()
self.student_says(
"Will you cover \\\\ computations?",
target_mode = "raise_left_hand"
)
self.random_blink()
self.teacher_says(
"Well...uh...no",
target_mode = "guilty",
)
self.play(*[
ApplyMethod(student.change_mode, mode)
for student, mode in zip(
self.get_students(),
["dejected", "confused", "angry"]
)
])
self.random_blink()
self.wait()
new_words = self.teacher.bubble.position_mobject_inside(
OldTexText([
"Search",
"``Gaussian elimination'' \\\\",
"and",
"``Row echelon form''",
])
)
new_words.split()[1].set_color(YELLOW)
new_words.split()[3].set_color(GREEN)
self.play(
Transform(self.teacher.bubble.content, new_words),
self.teacher.change_mode, "speaking"
)
self.play(*[
ApplyMethod(student.change_mode, "pondering")
for student in self.get_students()
])
self.random_blink()
class PuntToSoftware(Scene):
def construct(self):
self.play(Write("Let the computers do the computing"))
class UsefulnessOfMatrices(Scene):
def construct(self):
title = OldTexText("Usefulness of matrices")
title.set_color(YELLOW)
title.to_edge(UP)
self.add(title)
self.wait(3) #Play some 3d linear transform over this
equations = OldTex("""
6x - 3y + 2z &= 7 \\\\
x + 2y + 5z &= 0 \\\\
2x - 8y - z &= -2 \\\\
""")
equations.to_edge(RIGHT, buff = 2)
syms = VMobject(*np.array(equations.split())[[1, 4, 7]])
new_syms = VMobject(*[
m.copy().set_color(c)
for m, c in zip(syms.split(), [X_COLOR, Y_COLOR, Z_COLOR])
])
new_syms.arrange(RIGHT, buff = 0.5)
new_syms.next_to(equations, LEFT, buff = 3)
sym_brace = Brace(new_syms, DOWN)
unknowns = sym_brace.get_text("Unknown variables")
eq_brace = Brace(equations, DOWN)
eq_words = eq_brace.get_text("Equations")
self.play(Write(equations))
self.wait()
self.play(Transform(syms.copy(), new_syms, path_arc = np.pi/2))
for brace, words in (sym_brace, unknowns), (eq_brace, eq_words):
self.play(
GrowFromCenter(brace),
Write(words)
)
self.wait()
class CircuitDiagram(Scene):
def construct(self):
self.add(OldTexText("Voltages").to_edge(UP))
source = Source()
p1, p2 = source.get_top(), source.get_bottom()
r1 = Resistor(p1, p1+2*RIGHT)
r2 = LongResistor(p1+2*RIGHT, p2+2*RIGHT)
r3 = Resistor(p1+2*RIGHT, p1+2*2*RIGHT)
l1 = Line(p1+2*2*RIGHT, p2+2*2*RIGHT)
l2 = Line(p2+2*2*RIGHT, p2)
circuit = VMobject(source, r1, r2, r3, l1, l2)
circuit.center()
v1 = OldTex("v_1").next_to(r1, UP)
v2 = OldTex("v_2").next_to(r2, RIGHT)
v3 = OldTex("v_3").next_to(r3, UP)
unknowns = VMobject(v1, v2, v3)
unknowns.set_color(BLUE)
self.play(ShowCreation(circuit))
self.wait()
self.play(Write(unknowns))
self.wait()
class StockLine(VMobject):
CONFIG = {
"num_points" : 15,
"step_range" : 2
}
def init_points(self):
points = [ORIGIN]
for x in range(self.num_points):
step_size = self.step_range*(random.random() - 0.5)
points.append(points[-1] + 0.5*RIGHT + step_size*UP)
self.set_points_as_corners(points)
class StockPrices(Scene):
def construct(self):
self.add(OldTexText("Stock prices").to_edge(UP))
x_axis = Line(ORIGIN, FRAME_X_RADIUS*RIGHT)
y_axis = Line(ORIGIN, FRAME_Y_RADIUS*UP)
everyone = VMobject(x_axis, y_axis)
stock_lines = []
for color in TEAL, PINK, YELLOW, RED, BLUE:
sl = StockLine(color = color)
sl.move_to(y_axis.get_center(), aligned_edge = LEFT)
everyone.add(sl)
stock_lines.append(sl)
everyone.center()
self.add(x_axis, y_axis)
self.play(ShowCreation(
VMobject(*stock_lines),
run_time = 3,
lag_ratio = 0.5
))
self.wait()
class MachineLearningNetwork(Scene):
def construct(self):
self.add(OldTexText("Machine learning parameters").to_edge(UP))
layers = []
for i, num_nodes in enumerate([3, 4, 4, 1]):
layer = VMobject(*[
Circle(radius = 0.5, color = YELLOW)
for x in range(num_nodes)
])
for j, mob in enumerate(layer.split()):
sym = OldTex("x_{%d, %d}"%(i, j))
sym.move_to(mob)
mob.add(sym)
layer.arrange(DOWN, buff = 0.5)
layer.center()
layers.append(layer)
VMobject(*layers).arrange(RIGHT, buff = 1.5)
lines = VMobject()
for l_layer, r_layer in zip(layers, layers[1:]):
for l_node, r_node in it.product(l_layer.split(), r_layer.split()):
lines.add(Line(l_node, r_node))
lines.set_submobject_colors_by_gradient(BLUE_E, BLUE_A)
for mob in VMobject(*layers), lines:
self.play(Write(mob), run_time = 2)
self.wait()
class ComplicatedSystem(Scene):
def construct(self):
system = OldTex("""
\\begin{align*}
\\dfrac{1}{1-e^{2x-3y+4z}} &= 1 \\\\ \\\\
\\sin(xy) + z^2 &= \\sqrt{y} \\\\ \\\\
x^2 + y^2 &= e^{-z}
\\end{align*}
""")
system.to_edge(UP)
randy = Randolph().to_corner(DOWN+LEFT)
self.add(randy)
self.play(Write(system, run_time = 1))
self.play(randy.change_mode, "sassy")
self.play(Blink(randy))
self.wait()
class SystemOfEquations(Scene):
def construct(self):
equations = self.get_equations()
self.show_linearity_rules(equations)
self.describe_organization(equations)
self.factor_into_matrix(equations)
def get_equations(self):
matrix = Matrix([
[2, 5, 3],
[4, 0, 8],
[1, 3, 0]
])
mob_matrix = matrix.get_mob_matrix()
rhs = list(map(Tex, list(map(str, [-3, 0, 2]))))
variables = list(map(Tex, list("xyz")))
for v, color in zip(variables, [X_COLOR, Y_COLOR, Z_COLOR]):
v.set_color(color)
equations = VMobject()
for row in mob_matrix:
equation = VMobject(*it.chain(*list(zip(
row,
[v.copy() for v in variables],
list(map(Tex, list("++=")))
))))
equation.arrange(
RIGHT, buff = 0.1,
aligned_edge = DOWN
)
equation.split()[4].shift(0.1*DOWN)
equation.split()[-1].next_to(equation.split()[-2], RIGHT)
equations.add(equation)
equations.arrange(DOWN, aligned_edge = RIGHT)
for eq, rhs_elem in zip(equations.split(), rhs):
rhs_elem.next_to(eq, RIGHT)
eq.add(rhs_elem)
equations.center()
self.play(Write(equations))
self.add(equations)
return equations
def show_linearity_rules(self, equations):
top_equation = equations.split()[0]
other_equations = VMobject(*equations.split()[1:])
other_equations.save_state()
scaled_vars = VMobject(*[
VMobject(*top_equation.split()[3*i:3*i+2])
for i in range(3)
])
scaled_vars.save_state()
isolated_scaled_vars = scaled_vars.copy()
isolated_scaled_vars.scale(1.5)
isolated_scaled_vars.next_to(top_equation, UP)
scalars = VMobject(*[m.split()[0] for m in scaled_vars.split()])
plusses = np.array(top_equation.split())[[2, 5]]
self.play(other_equations.fade, 0.7)
self.play(Transform(scaled_vars, isolated_scaled_vars))
self.play(scalars.set_color, YELLOW, lag_ratio = 0.5)
self.play(*[
ApplyMethod(m.scale, 1.2, rate_func = there_and_back)
for m in scalars.split()
])
self.wait()
self.remove(scalars)
self.play(scaled_vars.restore)
self.play(*[
ApplyMethod(p.scale, 1.5, rate_func = there_and_back)
for p in plusses
])
self.wait()
self.show_nonlinearity_examples()
self.play(other_equations.restore)
def show_nonlinearity_examples(self):
squared = OldTex("x^2")
squared.split()[0].set_color(X_COLOR)
sine = OldTex("\\sin(x)")
sine.split()[-2].set_color(X_COLOR)
product = OldTex("xy")
product.split()[0].set_color(X_COLOR)
product.split()[1].set_color(Y_COLOR)
words = OldTexText("Not allowed!")
words.set_color(RED)
words.to_corner(UP+LEFT, buff = 1)
arrow = Vector(RIGHT, color = RED)
arrow.next_to(words, RIGHT)
for mob in squared, sine, product:
mob.scale(1.7)
mob.next_to(arrow.get_end(), RIGHT, buff = 0.5)
circle_slash = Circle(color = RED)
line = Line(LEFT, RIGHT, color = RED)
line.rotate(np.pi/4)
circle_slash.add(line)
circle_slash.next_to(arrow, RIGHT)
def draw_circle_slash(mob):
circle_slash.replace(mob)
circle_slash.scale(1.4)
self.play(ShowCreation(circle_slash), run_time = 0.5)
self.wait(0.5)
self.play(FadeOut(circle_slash), run_time = 0.5)
self.play(
Write(squared),
Write(words, run_time = 1),
ShowCreation(arrow),
)
draw_circle_slash(squared)
for mob in sine, product:
self.play(Transform(squared, mob))
draw_circle_slash(mob)
self.play(*list(map(FadeOut, [words, arrow, squared])))
self.wait()
def describe_organization(self, equations):
variables = VMobject(*it.chain(*[
eq.split()[:-2]
for eq in equations.split()
]))
variables.words = "Throw variables on the left"
constants = VMobject(*[
eq.split()[-1]
for eq in equations.split()
])
constants.words = "Lingering constants on the right"
xs, ys, zs = [
VMobject(*[
eq.split()[i]
for eq in equations.split()
])
for i in (1, 4, 7)
]
ys.words = "Vertically align variables"
colors = [PINK, YELLOW, BLUE_B, BLUE_C, BLUE_D]
for mob, color in zip([variables, constants, xs, ys, zs], colors):
mob.square = Square(color = color)
mob.square.replace(mob, stretch = True)
mob.square.scale(1.1)
if hasattr(mob, "words"):
mob.words = OldTexText(mob.words)
mob.words.set_color(color)
mob.words.next_to(mob.square, UP)
ys.square.add(xs.square, zs.square)
zero_circles = VMobject(*[
Circle().replace(mob).scale(1.3)
for mob in [
VMobject(*equations.split()[i].split()[j:j+2])
for i, j in [(1, 3), (2, 6)]
]
])
zero_circles.set_color(PINK)
zero_circles.words = OldTexText("Add zeros as needed")
zero_circles.words.set_color(zero_circles.get_color())
zero_circles.words.next_to(equations, UP)
for mob in variables, constants, ys:
self.play(
FadeIn(mob.square),
FadeIn(mob.words)
)
self.wait()
self.play(*list(map(FadeOut, [mob.square, mob.words])))
self.play(
ShowCreation(zero_circles),
Write(zero_circles.words, run_time = 1)
)
self.wait()
self.play(*list(map(FadeOut, [zero_circles, zero_circles.words])))
self.wait()
title = OldTexText("``Linear system of equations''")
title.scale(1.5)
title.to_edge(UP)
self.play(Write(title))
self.wait()
self.play(FadeOut(title))
def factor_into_matrix(self, equations):
coefficients = np.array([
np.array(eq.split())[[0, 3, 6]]
for eq in equations.split()
])
variable_arrays = np.array([
np.array(eq.split())[[1, 4, 7]]
for eq in equations.split()
])
rhs_entries = np.array([
eq.split()[-1]
for eq in equations.split()
])
matrix = Matrix(copy.deepcopy(coefficients))
x_array = Matrix(copy.deepcopy(variable_arrays[0]))
v_array = Matrix(copy.deepcopy(rhs_entries))
equals = OldTex("=")
ax_equals_v = VMobject(matrix, x_array, equals, v_array)
ax_equals_v.arrange(RIGHT)
ax_equals_v.to_edge(RIGHT)
all_brackets = [
mob.get_brackets()
for mob in (matrix, x_array, v_array)
]
self.play(equations.to_edge, LEFT)
arrow = Vector(RIGHT, color = YELLOW)
arrow.next_to(ax_equals_v, LEFT)
self.play(ShowCreation(arrow))
self.play(*it.chain(*[
[
Transform(
m1.copy(), m2,
run_time = 2,
path_arc = -np.pi/2
)
for m1, m2 in zip(
start_array.flatten(),
matrix_mobject.get_entries().split()
)
]
for start_array, matrix_mobject in [
(coefficients, matrix),
(variable_arrays[0], x_array),
(variable_arrays[1], x_array),
(variable_arrays[2], x_array),
(rhs_entries, v_array)
]
]))
self.play(*[
Write(mob)
for mob in all_brackets + [equals]
])
self.wait()
self.label_matrix_product(matrix, x_array, v_array)
def label_matrix_product(self, matrix, x_array, v_array):
matrix.words = "Coefficients"
matrix.symbol = "A"
x_array.words = "Variables"
x_array.symbol = "\\vec{\\textbf{x}}"
v_array.words = "Constants"
v_array.symbol = "\\vec{\\textbf{v}}"
parts = matrix, x_array, v_array
for mob in parts:
mob.brace = Brace(mob, UP)
mob.words = mob.brace.get_text(mob.words)
mob.words.shift_onto_screen()
mob.symbol = OldTex(mob.symbol)
mob.brace.put_at_tip(mob.symbol)
x_array.words.set_submobject_colors_by_gradient(
X_COLOR, Y_COLOR, Z_COLOR
)
x_array.symbol.set_color(PINK)
v_array.symbol.set_color(YELLOW)
for mob in parts:
self.play(
GrowFromCenter(mob.brace),
FadeIn(mob.words)
)
self.wait()
self.play(*list(map(FadeOut, [mob.brace, mob.words])))
self.wait()
for mob in parts:
self.play(
FadeIn(mob.brace),
Write(mob.symbol)
)
compact_equation = VMobject(*[
mob.symbol for mob in parts
])
compact_equation.submobjects.insert(
2, OldTex("=").next_to(x_array, RIGHT)
)
compact_equation.target = compact_equation.copy()
compact_equation.target.arrange(buff = 0.1)
compact_equation.target.to_edge(UP)
self.play(Transform(
compact_equation.copy(),
compact_equation.target
))
self.wait()
class LinearSystemTransformationScene(LinearTransformationScene):
def setup(self):
LinearTransformationScene.setup(self)
equation = OldTex([
"A",
"\\vec{\\textbf{x}}",
"=",
"\\vec{\\textbf{v}}",
])
equation.scale(1.5)
equation.next_to(ORIGIN, LEFT).to_edge(UP)
equation.add_background_rectangle()
self.add_foreground_mobject(equation)
self.equation = equation
self.A, self.x, eq, self.v = equation.split()[1].split()
self.x.set_color(PINK)
self.v.set_color(YELLOW)
class MentionThatItsATransformation(LinearSystemTransformationScene):
CONFIG = {
"t_matrix" : np.array([[2, 1], [2, 3]])
}
def construct(self):
self.setup()
brace = Brace(self.A)
words = brace.get_text("Transformation")
words.add_background_rectangle()
self.play(GrowFromCenter(brace), Write(words, run_time = 1))
self.add_foreground_mobject(words, brace)
self.apply_transposed_matrix(self.t_matrix)
self.wait()
class LookForX(MentionThatItsATransformation):
CONFIG = {
"show_basis_vectors" : False
}
def construct(self):
self.setup()
v = [-4, - 1]
x = np.linalg.solve(self.t_matrix.T, v)
v = Vector(v, color = YELLOW)
x = Vector(x, color = PINK)
v_label = self.get_vector_label(v, "v", color = YELLOW)
x_label = self.get_vector_label(x, "x", color = PINK)
for label in x_label, v_label:
label.add_background_rectangle()
self.play(
ShowCreation(v),
Write(v_label)
)
self.add_foreground_mobject(v_label)
x = self.add_vector(x, animate = False)
self.play(
ShowCreation(x),
Write(x_label)
)
self.wait()
self.add(VMobject(x, x_label).copy().fade())
self.apply_transposed_matrix(self.t_matrix)
self.wait()
class ThinkAboutWhatsHappening(Scene):
def construct(self):
randy = Randolph()
randy.to_corner()
bubble = randy.get_bubble(height = 5)
bubble.add_content(OldTex("""
3x + 1y + 4z &= 1 \\\\
5x + 9y + 2z &= 6 \\\\
5x + 3y + 5z &= 8
"""))
self.play(randy.change_mode, "pondering")
self.play(ShowCreation(bubble))
self.play(Write(bubble.content, run_time = 2))
self.play(Blink(randy))
self.wait()
everything = VMobject(*self.get_mobjects())
self.play(
ApplyFunction(
lambda m : m.shift(2*DOWN).scale(5),
everything
),
bubble.content.set_color, BLACK,
run_time = 2
)
class SystemOfTwoEquationsTwoUnknowns(Scene):
def construct(self):
system = OldTex("""
2x + 2y &= -4 \\\\
1x + 3y &= -1
""")
system.to_edge(UP)
for indices, color in ((1, 9), X_COLOR), ((4, 12), Y_COLOR):
for i in indices:
system.split()[i].set_color(color)
matrix = Matrix([[2, 2], [1, 3]])
v = Matrix([-4, -1])
x = Matrix(["x", "y"])
x.get_entries().set_submobject_colors_by_gradient(X_COLOR, Y_COLOR)
matrix_system = VMobject(
matrix, x, OldTex("="), v
)
matrix_system.arrange(RIGHT)
matrix_system.next_to(system, DOWN, buff = 1)
matrix.label = "A"
matrix.label_color = WHITE
x.label = "\\vec{\\textbf{x}}"
x.label_color = PINK
v.label = "\\vec{\\textbf{v}}"
v.label_color = YELLOW
for mob in matrix, x, v:
brace = Brace(mob)
label = brace.get_text("$%s$"%mob.label)
label.set_color(mob.label_color)
brace.add(label)
mob.brace = brace
self.add(system)
self.play(Write(matrix_system))
self.wait()
for mob in matrix, v, x:
self.play(Write(mob.brace))
self.wait()
class ShowBijectivity(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"t_matrix" : np.array([[0, -1], [2, 1]])
}
def construct(self):
self.setup()
vectors = VMobject(*[
Vector([x, y])
for x, y in it.product(*[
np.arange(-int(val)+0.5, int(val)+0.5)
for val in (FRAME_X_RADIUS, FRAME_Y_RADIUS)
])
])
vectors.set_submobject_colors_by_gradient(BLUE_E, PINK)
dots = VMobject(*[
Dot(v.get_end(), color = v.get_color())
for v in vectors.split()
])
titles = [
OldTexText([
"Each vector lands on\\\\",
"exactly one vector"
]),
OldTexText([
"Every vector has \\\\",
"been landed on"
])
]
for title in titles:
title.to_edge(UP)
background = BackgroundRectangle(VMobject(*titles))
self.add_foreground_mobject(background, titles[0])
kwargs = {
"lag_ratio" : 0.5,
"run_time" : 2
}
anims = list(map(Animation, self.foreground_mobjects))
self.play(ShowCreation(vectors, **kwargs), *anims)
self.play(Transform(vectors, dots, **kwargs), *anims)
self.wait()
self.add_transformable_mobject(vectors)
self.apply_transposed_matrix(self.t_matrix)
self.wait()
self.play(Transform(*titles))
self.wait()
self.apply_transposed_matrix(
np.linalg.inv(self.t_matrix.T).T
)
self.wait()
class LabeledExample(LinearSystemTransformationScene):
CONFIG = {
"title" : "",
"t_matrix" : [[0, 0], [0, 0]],
"show_square" : False,
}
def setup(self):
LinearSystemTransformationScene.setup(self)
title = OldTexText(self.title)
title.next_to(self.equation, DOWN, buff = 1)
title.add_background_rectangle()
title.shift_onto_screen()
self.add_foreground_mobject(title)
self.title = title
if self.show_square:
self.add_unit_square()
def construct(self):
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
class SquishExmapleWithWords(LabeledExample):
CONFIG = {
"title" : "$A$ squishes things to a lower dimension",
"t_matrix" : [[-2, -1], [2, 1]]
}
class FullRankExmapleWithWords(LabeledExample):
CONFIG = {
"title" : "$A$ keeps things 2D",
"t_matrix" : [[3, 0], [2, 1]]
}
class SquishExmapleDet(SquishExmapleWithWords):
CONFIG = {
"title" : "$\\det(A) = 0$",
"show_square" : True,
}
class FullRankExmapleDet(FullRankExmapleWithWords):
CONFIG = {
"title" : "$\\det(A) \\ne 0$",
"show_square" : True,
}
class StartWithNonzeroDetCase(TeacherStudentsScene):
def construct(self):
words = OldTexText(
"Let's start with \\\\",
"the", "$\\det(A) \\ne 0$", "case"
)
words[2].set_color(TEAL)
self.teacher_says(words)
self.random_blink()
self.play(
random.choice(self.get_students()).change_mode,
"happy"
)
self.wait()
class DeclareNewTransformation(TeacherStudentsScene):
def construct(self):
words = OldTexText(
"Playing a transformation in\\\\",
"reverse gives a", "new transformation"
)
words[-1].set_color(GREEN)
self.teacher_says(words)
self.play_student_changes("pondering", "sassy")
self.random_blink()
class PlayInReverse(FullRankExmapleDet):
CONFIG = {
"show_basis_vectors" : False
}
def construct(self):
FullRankExmapleDet.construct(self)
v = self.add_vector([-4, -1], color = YELLOW)
v_label = self.label_vector(v, "v", color = YELLOW)
self.add(v.copy())
self.apply_inverse_transpose(self.t_matrix)
self.play(v.set_color, PINK)
self.label_vector(v, "x", color = PINK)
self.wait()
class DescribeInverse(LinearTransformationScene):
CONFIG = {
"show_actual_inverse" : False,
"matrix_label" : "$A$",
"inv_label" : "$A^{-1}$",
}
def construct(self):
title = OldTexText("Transformation:")
new_title = OldTexText("Inverse transformation:")
matrix = Matrix(self.t_matrix.T)
if not self.show_actual_inverse:
inv_matrix = matrix.copy()
neg_1 = OldTex("-1")
neg_1.move_to(
inv_matrix.get_corner(UP+RIGHT),
aligned_edge = LEFT
)
neg_1.shift(0.1*RIGHT)
inv_matrix.add(neg_1)
matrix.add(VectorizedPoint(matrix.get_corner(UP+RIGHT)))
else:
inv_matrix = Matrix(np.linalg.inv(self.t_matrix.T).astype('int'))
matrix.label = self.matrix_label
inv_matrix.label = self.inv_label
for m, text in (matrix, title), (inv_matrix, new_title):
m.add_to_back(BackgroundRectangle(m))
text.add_background_rectangle()
m.next_to(text, RIGHT)
brace = Brace(m)
label_mob = brace.get_text(m.label)
label_mob.add_background_rectangle()
m.add(brace, label_mob)
text.add(m)
if text.get_width() > FRAME_WIDTH-1:
text.set_width(FRAME_WIDTH-1)
text.center().to_corner(UP+RIGHT)
matrix.set_color(PINK)
inv_matrix.set_color(YELLOW)
self.add_foreground_mobject(title)
self.apply_transposed_matrix(self.t_matrix)
self.wait()
self.play(Transform(title, new_title))
self.apply_inverse_transpose(self.t_matrix)
self.wait()
class ClockwiseCounterclockwise(DescribeInverse):
CONFIG = {
"t_matrix" : [[0, 1], [-1, 0]],
"show_actual_inverse" : True,
"matrix_label" : "$90^\\circ$ Couterclockwise",
"inv_label" : "$90^\\circ$ Clockwise",
}
class ShearInverseShear(DescribeInverse):
CONFIG = {
"t_matrix" : [[1, 0], [1, 1]],
"show_actual_inverse" : True,
"matrix_label" : "Rightward shear",
"inv_label" : "Leftward shear",
}
class MultiplyToIdentity(LinearTransformationScene):
def construct(self):
self.setup()
lhs = OldTex("A^{-1}", "A", "=")
lhs.scale(1.5)
A_inv, A, eq = lhs.split()
identity = Matrix([[1, 0], [0, 1]])
identity.set_column_colors(X_COLOR, Y_COLOR)
identity.next_to(eq, RIGHT)
VMobject(lhs, identity).center().to_corner(UP+RIGHT)
for mob in A, A_inv, eq:
mob.add_to_back(BackgroundRectangle(mob))
identity.background = BackgroundRectangle(identity)
col1 = VMobject(*identity.get_mob_matrix()[:,0])
col2 = VMobject(*identity.get_mob_matrix()[:,1])
A.text = "Transformation"
A_inv.text = "Inverse transformation"
product = VMobject(A, A_inv)
product.text = "Matrix multiplication"
identity.text = "The transformation \\\\ that does nothing"
for mob in A, A_inv, product, identity:
mob.brace = Brace(mob)
mob.text = mob.brace.get_text(mob.text)
mob.text.shift_onto_screen()
mob.text.add_background_rectangle()
self.add_foreground_mobject(A, A_inv)
brace, text = A.brace, A.text
self.play(GrowFromCenter(brace), Write(text), run_time = 1)
self.add_foreground_mobject(brace, text)
self.apply_transposed_matrix(self.t_matrix)
self.play(
Transform(brace, A_inv.brace),
Transform(text, A_inv.text),
)
self.apply_inverse_transpose(self.t_matrix)
self.wait()
self.play(
Transform(brace, product.brace),
Transform(text, product.text)
)
self.wait()
self.play(
Write(identity.background),
Write(identity.get_brackets()),
Write(eq),
Transform(brace, identity.brace),
Transform(text, identity.text)
)
self.wait()
self.play(Write(col1))
self.wait()
self.play(Write(col2))
self.wait()
class ThereAreComputationMethods(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
There are methods
to compute $A^{-1}$
""")
self.random_blink()
self.wait()
class TwoDInverseFormula(Scene):
def construct(self):
title = OldTexText("If you're curious...")
title.set_color(YELLOW)
title.to_edge(UP)
morty = Mortimer().to_corner(DOWN+RIGHT)
self.add(title, morty)
matrix = [["a", "b"], ["c", "d"]]
scaled_inv = [["d", "-b"], ["-c", "a"]]
formula = OldTex("""
%s^{-1} = \\dfrac{1}{ad-bc} %s
"""%(
matrix_to_tex_string(matrix),
matrix_to_tex_string(scaled_inv)
))
self.play(Write(formula))
self.play(morty.change_mode, "confused")
self.play(Blink(morty))
class SymbolicInversion(Scene):
def construct(self):
vec = lambda s : "\\vec{\\textbf{%s}}"%s
words = OldTexText("Once you have this:")
words.to_edge(UP, buff = 2)
inv = OldTex("A^{-1}")
inv.set_color(GREEN)
inv.next_to(words.split()[-1], RIGHT, aligned_edge = DOWN)
inv2 = inv.copy()
start = OldTex("A", vec("x"), "=", vec("v"))
interim = OldTex("A^{-1}", "A", vec("x"), "=", "A^{-1}", vec("v"))
end = OldTex(vec("x"), "=", "A^{-1}", vec("v"))
A, x, eq, v = start.split()
x.set_color(PINK)
v.set_color(YELLOW)
interim_mobs = [inv, A, x, eq, inv2, v]
for i, mob in enumerate(interim_mobs):
mob.interim = mob.copy().move_to(interim.split()[i])
self.add(start)
self.play(Write(words), FadeIn(inv), run_time = 1)
self.wait()
self.play(
FadeOut(words),
*[Transform(m, m.interim) for m in interim_mobs]
)
self.wait()
product = VMobject(A, inv)
product.brace = Brace(product)
product.words = product.brace.get_text(
"The ``do nothing'' matrix"
)
product.words.set_color(BLUE)
self.play(
GrowFromCenter(product.brace),
Write(product.words, run_time = 1),
product.set_color, BLUE
)
self.wait()
self.play(*[
ApplyMethod(m.set_color, BLACK)
for m in (product, product.brace, product.words)
])
self.wait()
self.play(ApplyFunction(
lambda m : m.center().to_edge(UP),
VMobject(x, eq, inv2, v)
))
self.wait()
class PlayInReverseWithSolution(PlayInReverse):
CONFIG = {
"t_matrix" : [[2, 1], [2, 3]]
}
def setup(self):
LinearTransformationScene.setup(self)
equation = OldTex([
"\\vec{\\textbf{x}}",
"=",
"A^{-1}",
"\\vec{\\textbf{v}}",
])
equation.to_edge(UP)
equation.add_background_rectangle()
self.add_foreground_mobject(equation)
self.equation = equation
self.x, eq, self.inv, self.v = equation.split()[1].split()
self.x.set_color(PINK)
self.v.set_color(YELLOW)
self.inv.set_color(GREEN)
class OneUniqueSolution(Scene):
def construct(self):
system = OldTex("""
\\begin{align*}
ax + cy &= e \\\\
bx + dy &= f
\\end{align*}
""")
VMobject(*np.array(system.split())[[1, 8]]).set_color(X_COLOR)
VMobject(*np.array(system.split())[[4, 11]]).set_color(Y_COLOR)
brace = Brace(system, UP)
brace.set_color(YELLOW)
words = brace.get_text("One unique solution \\dots", "probably")
words.set_color(YELLOW)
words.split()[1].set_color(GREEN)
self.add(system)
self.wait()
self.play(
GrowFromCenter(brace),
Write(words.split()[0])
)
self.wait()
self.play(Write(words.split()[1], run_time = 1))
self.wait()
class ThreeDTransformXToV(Scene):
pass
class ThreeDTransformAndReverse(Scene):
pass
class DetNEZeroRule(Scene):
def construct(self):
text = OldTex("\\det(A) \\ne 0")
text.shift(2*UP)
A_inv = OldTexText("$A^{-1}$ exists")
A_inv.shift(DOWN)
arrow = Arrow(text, A_inv)
self.play(Write(text))
self.wait()
self.play(ShowCreation(arrow))
self.play(Write(A_inv, run_time = 1))
self.wait()
class ThreeDInverseRule(Scene):
def construct(self):
form = OldTex("A^{-1} A = ")
form.scale(2)
matrix = Matrix(np.identity(3, 'int'))
matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR)
matrix.next_to(form, RIGHT)
self.add(form)
self.play(Write(matrix))
self.wait()
class ThreeDApplyReverseToV(Scene):
pass
class InversesDontAlwaysExist(TeacherStudentsScene):
def construct(self):
self.teacher_says("$A^{-1}$ doesn't always exist")
self.random_blink()
self.wait()
self.random_blink()
class InvertNonInvertable(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[2, 1], [-2, -1]]
}
def setup(self):
LinearTransformationScene.setup(self)
det_text = OldTex("\\det(A) = 0")
det_text.scale(1.5)
det_text.to_corner(UP+LEFT)
det_text.add_background_rectangle()
self.add_foreground_mobject(det_text)
def construct(self):
no_func = OldTexText("No function does this")
no_func.shift(2*UP)
no_func.set_color(RED)
no_func.add_background_rectangle()
grid = VMobject(self.plane, self.i_hat, self.j_hat)
grid.save_state()
self.apply_transposed_matrix(self.t_matrix, path_arc = 0)
self.wait()
self.play(Write(no_func, run_time = 1))
self.add_foreground_mobject(no_func)
self.play(
grid.restore,
*list(map(Animation, self.foreground_mobjects)),
run_time = 3
)
self.wait()
class OneInputMultipleOutputs(InvertNonInvertable):
def construct(self):
input_vectors = VMobject(*[
Vector([x+2, x]) for x in np.arange(-4, 4.5, 0.5)
])
input_vectors.set_submobject_colors_by_gradient(PINK, YELLOW)
output_vector = Vector([4, 2], color = YELLOW)
grid = VMobject(self.plane, self.i_hat, self.j_hat)
grid.save_state()
self.apply_transposed_matrix(self.t_matrix, path_arc = 0)
self.play(ShowCreation(output_vector))
single_input = OldTexText("Single vector")
single_input.add_background_rectangle()
single_input.next_to(output_vector.get_end(), UP)
single_input.set_color(YELLOW)
self.play(Write(single_input))
self.wait()
self.remove(single_input, output_vector)
self.play(
grid.restore,
*[
Transform(output_vector.copy(), input_vector)
for input_vector in input_vectors.split()
] + list(map(Animation, self.foreground_mobjects)),
run_time = 3
)
multiple_outputs = OldTexText(
"Must map to \\\\",
"multiple vectors"
)
multiple_outputs.split()[1].set_submobject_colors_by_gradient(YELLOW, PINK)
multiple_outputs.next_to(ORIGIN, DOWN).to_edge(RIGHT)
multiple_outputs.add_background_rectangle()
self.play(Write(multiple_outputs, run_time = 2))
self.wait()
class SolutionsCanStillExist(TeacherStudentsScene):
def construct(self):
words = OldTexText("""
Solutions can still
exist when""", "$\\det(A) = 0$"
)
words[1].set_color(TEAL)
self.teacher_says(words)
self.random_blink(2)
class ShowVInAndOutOfColumnSpace(LinearSystemTransformationScene):
CONFIG = {
"t_matrix" : [[2, 1], [-2, -1]]
}
def construct(self):
v_out = Vector([1, -1])
v_in = Vector([-4, -2])
v_out.words = "No solution exists"
v_in.words = "Solutions exist"
v_in.words_color = YELLOW
v_out.words_color = RED
self.apply_transposed_matrix(self.t_matrix, path_arc = 0)
self.wait()
for v in v_in, v_out:
self.add_vector(v, animate = True)
words = OldTexText(v.words)
words.set_color(v.words_color)
words.next_to(v.get_end(), DOWN+RIGHT)
words.add_background_rectangle()
self.play(Write(words), run_time = 2)
self.wait()
class NotAllSquishesAreCreatedEqual(TeacherStudentsScene):
def construct(self):
self.student_says("""
Some squishes feel
...squishier
""")
self.random_blink(2)
class PrepareForRank(Scene):
def construct(self):
new_term, rank = words = OldTexText(
"New terminology: ",
"rank"
)
rank.set_color(TEAL)
self.play(Write(words))
self.wait()
class DefineRank(Scene):
def construct(self):
rank = OldTexText("``Rank''")
rank.set_color(TEAL)
arrow = DoubleArrow(LEFT, RIGHT)
dims = OldTexText(
"Number of\\\\", "dimensions \\\\",
"in the output"
)
dims[1].set_color(rank.get_color())
rank.next_to(arrow, LEFT)
dims.next_to(arrow, RIGHT)
self.play(Write(rank))
self.play(
ShowCreation(arrow),
*list(map(Write, dims))
)
self.wait()
class DefineColumnSpace(Scene):
def construct(self):
left_words = OldTexText(
"Set of all possible\\\\",
"outputs",
"$A\\vec{\\textbf{v}}$",
)
left_words[1].set_color(TEAL)
VMobject(*left_words[-1][1:]).set_color(YELLOW)
arrow = DoubleArrow(LEFT, RIGHT).to_edge(UP)
right_words = OldTexText("``Column space''", "of $A$")
right_words[0].set_color(left_words[1].get_color())
everyone = VMobject(left_words, arrow, right_words)
everyone.arrange(RIGHT)
everyone.to_edge(UP)
self.play(Write(left_words))
self.wait()
self.play(
ShowCreation(arrow),
Write(right_words)
)
self.wait()
class ColumnsRepresentBasisVectors(Scene):
def construct(self):
matrix = Matrix([[3, 1], [4, 1]])
matrix.shift(UP)
i_hat_words, j_hat_words = [
OldTexText("Where $\\hat{\\%smath}$ lands"%char)
for char in ("i", "j")
]
i_hat_words.set_color(X_COLOR)
i_hat_words.next_to(ORIGIN, LEFT).to_edge(UP)
j_hat_words.set_color(Y_COLOR)
j_hat_words.next_to(ORIGIN, RIGHT).to_edge(UP)
self.add(matrix)
self.wait()
for i, words in enumerate([i_hat_words, j_hat_words]):
arrow = Arrow(
words.get_bottom(),
matrix.get_mob_matrix()[0,i].get_top(),
color = words.get_color()
)
self.play(
Write(words, run_time = 1),
ShowCreation(arrow),
*[
ApplyMethod(m.set_color, words.get_color())
for m in matrix.get_mob_matrix()[:,i]
]
)
self.wait()
class ThreeDOntoPlane(Scene):
pass
class ThreeDOntoLine(Scene):
pass
class ThreeDOntoPoint(Scene):
pass
class TowDColumnsDontSpan(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[2, 1], [-2, -1]]
}
def construct(self):
matrix = Matrix(self.t_matrix.T)
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.add_to_back(BackgroundRectangle(matrix))
self.add_foreground_mobject(matrix)
brace = Brace(matrix)
words = VMobject(
OldTexText("Span", "of columns"),
OldTex("\\Updownarrow"),
OldTexText("``Column space''")
)
words.arrange(DOWN, buff = 0.1)
words.next_to(brace, DOWN)
words[0][0].set_color(PINK)
words[2].set_color(TEAL)
words[0].add_background_rectangle()
words[2].add_background_rectangle()
VMobject(matrix, brace, words).to_corner(UP+LEFT)
self.apply_transposed_matrix(self.t_matrix, path_arc = 0)
self.play(
GrowFromCenter(brace),
Write(words, run_time = 2)
)
self.wait()
self.play(ApplyFunction(
lambda m : m.scale(-1).shift(self.i_hat.get_end()),
self.j_hat
))
bases = [self.i_hat, self.j_hat]
for mob in bases:
mob.original = mob.copy()
for x in range(8):
for mob in bases:
mob.target = mob.original.copy()
mob.target.set_stroke(width = 6)
target_len = random.uniform(0.5, 1.5)
target_len *= random.choice([-1, 1])
mob.target.scale(target_len)
self.j_hat.target.shift(
-self.j_hat.target.get_start()+ \
self.i_hat.target.get_end()
)
self.play(Transform(
VMobject(*bases),
VMobject(*[m.target for m in bases]),
run_time = 2
))
class FullRankWords(Scene):
def construct(self):
self.play(Write(OldTexText("Full rank").scale(2)))
class ThreeDColumnsDontSpan(Scene):
def construct(self):
matrix = Matrix(np.array([
[1, 1, 0],
[0, 1, 1],
[-1, -2, -1],
]).T)
matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR)
brace = Brace(matrix)
words = brace.get_text(
"Columns don't",
"span \\\\",
"full output space"
)
words[1].set_color(PINK)
self.add(matrix)
self.play(
GrowFromCenter(brace),
Write(words, run_time = 2)
)
self.wait()
class NameColumnSpace(Scene):
def construct(self):
matrix = Matrix(np.array([
[1, 1, 0],
[0, 1, 1],
[-1, -2, -1],
]).T)
matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR)
matrix.to_corner(UP+LEFT)
cols = list(matrix.copy().get_mob_matrix().T)
col_arrays = list(map(Matrix, cols))
span_text = OldTex(
"\\text{Span}",
"\\Big(",
matrix_to_tex_string([1, 2, 3]),
",",
matrix_to_tex_string([1, 2, 3]),
",",
matrix_to_tex_string([1, 2, 3]),
"\\big)"
)
for i in 1, -1:
span_text[i].stretch(1.5, 1)
span_text[i].do_in_place(
span_text[i].set_height,
span_text.get_height()
)
for col_array, index in zip(col_arrays, [2, 4, 6]):
col_array.replace(span_text[index], dim_to_match = 1)
span_text.submobjects[index] = col_array
span_text.arrange(RIGHT, buff = 0.2)
arrow = DoubleArrow(LEFT, RIGHT)
column_space = OldTexText("``Column space''")
for mob in column_space, arrow:
mob.set_color(TEAL)
text = VMobject(span_text, arrow, column_space)
text.arrange(RIGHT)
text.next_to(matrix, DOWN, buff = 1, aligned_edge = LEFT)
self.add(matrix)
self.wait()
self.play(*[
Transform(
VMobject(*matrix.copy().get_mob_matrix()[:,i]),
col_arrays[i].get_entries()
)
for i in range(3)
])
self.play(
Write(span_text),
*list(map(Animation, self.get_mobjects_from_last_animation()))
)
self.play(
ShowCreation(arrow),
Write(column_space)
)
self.wait()
self.play(FadeOut(matrix))
self.clear()
self.add(text)
words = OldTexText(
"To solve",
"$A\\vec{\\textbf{x}} = \\vec{\\textbf{v}}$,\\\\",
"$\\vec{\\textbf{v}}$",
"must be in \\\\ the",
"column space."
)
VMobject(*words[1][1:3]).set_color(PINK)
VMobject(*words[1][4:6]).set_color(YELLOW)
words[2].set_color(YELLOW)
words[4].set_color(TEAL)
words.to_corner(UP+LEFT)
self.play(Write(words))
self.wait(2)
self.play(FadeOut(words))
brace = Brace(column_space, UP)
rank_words = brace.get_text(
"Number of dimensions \\\\ is called",
"``rank''"
)
rank_words[1].set_color(MAROON)
self.play(
GrowFromCenter(brace),
Write(rank_words)
)
self.wait()
self.cycle_through_span_possibilities(span_text)
def cycle_through_span_possibilities(self, span_text):
span_text.save_state()
two_d_span = span_text.copy()
for index, arr, c in (2, [1, 1], X_COLOR), (4, [0, 1], Y_COLOR):
col = Matrix(arr)
col.replace(two_d_span[index])
two_d_span.submobjects[index] = col
col.get_entries().set_color(c)
for index in 5, 6:
two_d_span[index].scale(0)
two_d_span.arrange(RIGHT, buff = 0.2)
two_d_span[-1].next_to(two_d_span[4], RIGHT, buff = 0.2)
two_d_span.move_to(span_text, aligned_edge = RIGHT)
mob_matrix = np.array([
two_d_span[i].get_entries().split()
for i in (2, 4)
])
self.play(Transform(span_text, two_d_span))
#horrible hack
span_text.shift(10*DOWN)
span_text = span_text.copy().restore()
###
self.add(two_d_span)
self.wait()
self.replace_number_matrix(mob_matrix, [[1, 1], [1, 1]])
self.wait()
self.replace_number_matrix(mob_matrix, [[0, 0], [0, 0]])
self.wait()
self.play(Transform(two_d_span, span_text))
self.wait()
self.remove(two_d_span)
self.add(span_text)
mob_matrix = np.array([
span_text[i].get_entries().split()
for i in (2, 4, 6)
])
self.replace_number_matrix(mob_matrix, [[1, 1, 0], [0, 1, 1], [1, 0, 1]])
self.wait()
self.replace_number_matrix(mob_matrix, [[1, 1, 0], [0, 1, 1], [-1, -2, -1]])
self.wait()
self.replace_number_matrix(mob_matrix, [[1, 1, 0], [2, 2, 0], [3, 3, 0]])
self.wait()
self.replace_number_matrix(mob_matrix, np.zeros((3, 3)).astype('int'))
self.wait()
def replace_number_matrix(self, matrix, new_numbers):
starters = matrix.flatten()
targets = list(map(Tex, list(map(str, np.array(new_numbers).flatten()))))
for start, target in zip(starters, targets):
target.move_to(start)
target.set_color(start.get_color())
self.play(*[
Transform(*pair, path_arc = np.pi)
for pair in zip(starters, targets)
])
class IHatShear(LinearTransformationScene):
CONFIG = {
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 0
},
}
def construct(self):
self.apply_transposed_matrix([[1, 1], [0, 1]])
self.wait()
class DiagonalDegenerate(LinearTransformationScene):
def construct(self):
self.apply_transposed_matrix([[1, 1], [1, 1]])
class ZeroMatirx(LinearTransformationScene):
def construct(self):
origin = Dot(ORIGIN)
self.play(Transform(
VMobject(self.plane, self.i_hat, self.j_hat),
origin,
run_time = 3
))
self.wait()
class RankNumber(Scene):
CONFIG = {
"number" : 3,
"color" : BLUE
}
def construct(self):
words = OldTexText("Rank", "%d"%self.number)
words[1].set_color(self.color)
self.add(words)
class RankNumber2(RankNumber):
CONFIG = {
"number" : 2,
"color" : RED,
}
class RankNumber1(RankNumber):
CONFIG = {
"number" : 1,
"color" : GREEN
}
class RankNumber0(RankNumber):
CONFIG = {
"number" : 0,
"color" : GREY
}
class NameFullRank(Scene):
def construct(self):
matrix = Matrix([[2, 5, 1], [3, 1, 4], [-4, 0, 0]])
matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR)
matrix.to_edge(UP)
brace = Brace(matrix)
top_words = brace.get_text(
"When", "rank", "$=$", "number of columns",
)
top_words[1].set_color(MAROON)
low_words = OldTexText(
"matrix is", "``full rank''"
)
low_words[1].set_color(MAROON)
low_words.next_to(top_words, DOWN)
VMobject(matrix, brace, top_words, low_words).to_corner(UP+LEFT)
self.add(matrix)
self.play(
GrowFromCenter(brace),
Write(top_words)
)
self.wait()
self.play(Write(low_words))
self.wait()
class OriginIsAlwaysInColumnSpace(LinearTransformationScene):
def construct(self):
vector = Matrix([0, 0]).set_color(YELLOW)
words = OldTexText("is always in the", "column space")
words[1].set_color(TEAL)
words.next_to(vector, RIGHT)
vector.add_to_back(BackgroundRectangle(vector))
words.add_background_rectangle()
VMobject(vector, words).center().to_edge(UP)
arrow = Arrow(vector.get_bottom(), ORIGIN)
dot = Dot(ORIGIN, color = YELLOW)
self.play(Write(vector), Write(words))
self.play(ShowCreation(arrow))
self.play(ShowCreation(dot, run_time = 0.5))
self.add_foreground_mobject(vector, words, arrow, dot)
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
self.apply_transposed_matrix([[1./3, -1./2], [-1./3, 1./2]])
self.wait()
class FullRankCase(LinearTransformationScene):
CONFIG = {
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 0
},
}
def construct(self):
t_matrices = [
[[2, 1], [-3, 2]],
[[1./2, 1], [1./3, -1./2]]
]
vector = Matrix([0, 0]).set_color(YELLOW)
title = VMobject(
OldTexText("Only"), vector,
OldTexText("lands on"), vector.copy()
)
title.arrange(buff = 0.2)
title.to_edge(UP)
for mob in title:
mob.add_to_back(BackgroundRectangle(mob))
arrow = Arrow(vector.get_bottom(), ORIGIN)
dot = Dot(ORIGIN, color = YELLOW)
words_on = False
for t_matrix in t_matrices:
self.apply_transposed_matrix(t_matrix)
if not words_on:
self.play(Write(title))
self.play(ShowCreation(arrow))
self.play(ShowCreation(dot, run_time = 0.5))
self.add_foreground_mobject(title, arrow, dot)
words_on = True
self.apply_inverse_transpose(t_matrix)
self.wait()
class NameNullSpace(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"t_matrix" : [[1, -1], [-1, 1]]
}
def construct(self):
vectors = self.get_vectors()
dot = Dot(ORIGIN, color = YELLOW)
line = Line(vectors[0].get_end(), vectors[-1].get_end())
line.set_color(YELLOW)
null_space_label = OldTexText("``Null space''")
kernel_label = OldTexText("``Kernel''")
null_space_label.move_to(vectors[13].get_end(), aligned_edge = UP+LEFT)
kernel_label.next_to(null_space_label, DOWN)
for mob in null_space_label, kernel_label:
mob.set_color(YELLOW)
mob.add_background_rectangle()
self.play(ShowCreation(vectors, run_time = 3))
self.wait()
vectors.save_state()
self.plane.save_state()
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [Transform(vectors, dot)],
path_arc = 0
)
self.wait()
self.play(
vectors.restore,
self.plane.restore,
*list(map(Animation, self.foreground_mobjects)),
run_time = 2
)
self.play(Transform(
vectors, line,
run_time = 2,
lag_ratio = 0.5
))
self.wait()
for label in null_space_label, kernel_label:
self.play(Write(label))
self.wait()
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [
Transform(vectors, dot),
ApplyMethod(null_space_label.scale, 0),
ApplyMethod(kernel_label.scale, 0),
],
path_arc = 0
)
self.wait()
def get_vectors(self, offset = 0):
vect = np.array(UP+RIGHT)
vectors = VMobject(*[
Vector(a*vect + offset)
for a in np.linspace(-5, 5, 18)
])
vectors.set_submobject_colors_by_gradient(PINK, YELLOW)
return vectors
class ThreeDNullSpaceIsLine(Scene):
pass
class ThreeDNullSpaceIsPlane(Scene):
pass
class NullSpaceSolveForVEqualsZero(NameNullSpace):
def construct(self):
vec = lambda s : "\\vec{\\textbf{%s}}"%s
equation = OldTex("A", vec("x"), "=", vec("v"))
A, x, eq, v = equation
x.set_color(PINK)
v.set_color(YELLOW)
zero_vector = Matrix([0, 0])
zero_vector.set_color(YELLOW)
zero_vector.scale(0.7)
zero_vector.move_to(v, aligned_edge = LEFT)
VMobject(equation, zero_vector).next_to(ORIGIN, LEFT).to_edge(UP)
zero_vector_rect = BackgroundRectangle(zero_vector)
equation.add_background_rectangle()
self.play(Write(equation))
self.wait()
self.play(
ShowCreation(zero_vector_rect),
Transform(v, zero_vector)
)
self.wait()
self.add_foreground_mobject(zero_vector_rect, equation)
NameNullSpace.construct(self)
class OffsetNullSpace(NameNullSpace):
def construct(self):
x = Vector([-2, 1], color = RED)
vectors = self.get_vectors()
offset_vectors = self.get_vectors(offset = x.get_end())
dots = VMobject(*[
Dot(v.get_end(), color = v.get_color())
for v in offset_vectors
])
dot = Dot(
self.get_matrix_transformation(self.t_matrix)(x.get_end()),
color = RED
)
circle = Circle(color = YELLOW).replace(dot)
circle.scale(5)
words = OldTexText("""
All vectors still land
on the same spot
""")
words.set_color(YELLOW)
words.add_background_rectangle()
words.next_to(circle)
x_copies = VMobject(*[
x.copy().shift(v.get_end())
for v in vectors
])
self.play(FadeIn(vectors))
self.wait()
self.add_vector(x, animate = True)
self.wait()
x_copy = VMobject(x.copy())
self.play(Transform(x_copy, x_copies))
self.play(
Transform(vectors, offset_vectors),
*[
Transform(v, VectorizedPoint(v.get_end()))
for v in x_copy
]
)
self.remove(x_copy)
self.wait()
self.play(Transform(vectors, dots))
self.wait()
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [Transform(vectors, dot)]
)
self.wait()
self.play(
ShowCreation(circle),
Write(words)
)
self.wait()
class ShowAdditivityProperty(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"t_matrix" : [[1, 0.5], [-1, 1]],
"include_background_plane" : False,
}
def construct(self):
v = Vector([2, -1])
w = Vector([1, 2])
v.set_color(YELLOW)
w.set_color(MAROON_B)
sum_vect = Vector(v.get_end()+w.get_end(), color = PINK)
form = OldTex(
"A(",
"\\vec{\\textbf{v}}",
"+",
"\\vec{\\textbf{w}}",
")",
"=A",
"\\vec{\\textbf{v}}",
"+A",
"\\vec{\\textbf{w}}",
)
form.to_corner(UP+RIGHT)
VMobject(form[1], form[6]).set_color(YELLOW)
VMobject(form[3], form[8]).set_color(MAROON_B)
initial_sum = VMobject(*form[1:4])
transformer = VMobject(form[0], form[4])
final_sum = VMobject(*form[5:])
form_rect = BackgroundRectangle(form)
self.add(form_rect)
self.add_vector(v, animate = True)
self.add_vector(w, animate = True)
w_copy = w.copy()
self.play(w_copy.shift, v.get_end())
self.add_vector(sum_vect, animate = True)
self.play(
Write(initial_sum),
FadeOut(w_copy)
)
self.add_foreground_mobject(form_rect, initial_sum)
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [Write(transformer)]
)
self.wait()
self.play(w.copy().shift, v.get_end())
self.play(Write(final_sum))
self.wait()
class AddJustOneNullSpaceVector(NameNullSpace):
def construct(self):
vectors = self.get_vectors()
self.add(vectors)
null_vector = vectors[int(0.7*len(vectors.split()))]
vectors.remove(null_vector)
null_vector.label = "$\\vec{\\textbf{n}}$"
x = Vector([-1, 1], color = RED)
x.label = "$\\vec{\\textbf{x}}$"
sum_vect = Vector(
x.get_end() + null_vector.get_end(),
color = PINK
)
for v in x, null_vector:
v.label = OldTexText(v.label)
v.label.set_color(v.get_color())
v.label.next_to(v.get_end(), UP)
v.label.add_background_rectangle()
dot = Dot(ORIGIN, color = null_vector.get_color())
form = OldTex(
"A(",
"\\vec{\\textbf{x}}",
"+",
"\\vec{\\textbf{n}}",
")",
"=A",
"\\vec{\\textbf{x}}",
"+A",
"\\vec{\\textbf{n}}",
)
form.to_corner(UP+RIGHT)
VMobject(form[1], form[6]).set_color(x.get_color())
VMobject(form[3], form[8]).set_color(null_vector.get_color())
initial_sum = VMobject(*form[1:4])
transformer = VMobject(form[0], form[4])
final_sum = VMobject(*form[5:])
brace = Brace(VMobject(*form[-2:]))
brace.add(brace.get_text("+0").add_background_rectangle())
form_rect = BackgroundRectangle(form)
sum_vect.label = initial_sum.copy()
sum_vect.label.next_to(sum_vect.get_end(), UP)
self.add_vector(x, animate = True)
self.play(Write(x.label))
self.wait()
self.play(
FadeOut(vectors),
Animation(null_vector)
)
self.play(Write(null_vector.label))
self.wait()
x_copy = x.copy()
self.play(x_copy.shift, null_vector.get_end())
self.add_vector(sum_vect, animate = True)
self.play(
FadeOut(x_copy),
Write(sum_vect.label)
)
self.wait()
self.play(
ShowCreation(form_rect),
sum_vect.label.replace, initial_sum
)
self.add_foreground_mobject(form_rect, sum_vect.label)
self.remove(x.label, null_vector.label)
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [
Transform(null_vector, dot),
Write(transformer)
]
)
self.play(Write(final_sum))
self.wait()
self.play(Write(brace))
self.wait()
words = OldTexText(
"$\\vec{\\textbf{x}}$",
"and the",
"$\\vec{\\textbf{x}} + \\vec{\\textbf{n}}$\\\\",
"land on the same spot"
)
words[0].set_color(x.get_color())
VMobject(*words[2][:2]).set_color(x.get_color())
VMobject(*words[2][3:]).set_color(null_vector.get_color())
words.next_to(brace, DOWN)
words.to_edge(RIGHT)
self.play(Write(words))
self.wait()
class NullSpaceOffsetRule(Scene):
def construct(self):
vec = lambda s : "\\vec{\\textbf{%s}}"%s
equation = OldTex("A", vec("x"), "=", vec("v"))
A, x, equals, v = equation
x.set_color(PINK)
v.set_color(YELLOW)
A_text = OldTexText(
"When $A$ is not", "full rank"
)
A_text[1].set_color(MAROON_C)
A_text.next_to(A, UP+LEFT, buff = 1)
A_text.shift_onto_screen()
A_arrow = Arrow(A_text.get_bottom(), A, color = WHITE)
v_text = OldTexText(
"If", "$%s$"%vec("v"), "is in the",
"column space", "of $A$"
)
v_text[1].set_color(YELLOW)
v_text[3].set_color(TEAL)
v_text.next_to(v, DOWN+RIGHT, buff = 1)
v_text.shift_onto_screen()
v_arrow = Arrow(v_text.get_top(), v, color = YELLOW)
self.add(equation)
self.play(Write(A_text, run_time = 2))
self.play(ShowCreation(A_arrow))
self.wait()
self.play(Write(v_text, run_time = 2))
self.play(ShowCreation(v_arrow))
self.wait()
class MuchLeftToLearn(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"That's the high \\\\",
"level overview"
)
self.random_blink()
self.wait()
self.teacher_says(
"There is still \\\\",
"much to learn"
)
for pi in self.get_students():
target_mode = random.choice([
"raise_right_hand", "raise_left_hand"
])
self.play(pi.change_mode, target_mode)
self.random_blink()
self.wait()
class NotToLearnItAllNow(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
The goal is not to
learn it all now
""")
self.random_blink()
self.wait()
self.random_blink()
class NextVideo(Scene):
def construct(self):
title = OldTexText("""
Next video: Nonsquare matrices
""")
title.set_width(FRAME_WIDTH - 2)
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
class WhatAboutNonsquareMatrices(TeacherStudentsScene):
def construct(self):
self.student_says(
"What about \\\\ nonsquare matrices?",
target_mode = "raise_right_hand"
)
self.play(self.get_students()[0].change_mode, "confused")
self.random_blink(6)
|
|
from manim_imports_ext import *
from _2016.eola.chapter1 import plane_wave_homotopy
from _2016.eola.chapter3 import ColumnsToBasisVectors
from _2016.eola.chapter5 import NameDeterminant, Blob
from _2016.eola.chapter9 import get_small_bubble
from _2016.eola.chapter10 import ExampleTranformationScene
class Student(PiCreature):
CONFIG = {
"name" : "Student"
}
def get_name(self):
text = OldTexText(self.name)
text.add_background_rectangle()
text.next_to(self, DOWN)
return text
class PhysicsStudent(Student):
CONFIG = {
"color" : PINK,
"name" : "Physics student"
}
class CSStudent(Student):
CONFIG = {
"color" : PURPLE_E,
"flip_at_start" : True,
"name" : "CS Student"
}
class OpeningQuote(Scene):
def construct(self):
words = OldTexText(
"``Such",
"axioms,",
"together with other unmotivated definitions,",
"serve mathematicians mainly by making it",
"difficult for the uninitiated",
"to master their subject, thereby elevating its authority.''",
enforce_new_line_structure = False,
alignment = "",
)
words.set_color_by_tex("axioms,", BLUE)
words.set_color_by_tex("difficult for the uninitiated", RED)
words.set_width(FRAME_WIDTH - 2)
words.to_edge(UP)
author = OldTexText("-Vladmir Arnold")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = MED_LARGE_BUFF)
self.play(Write(words, run_time = 8))
self.wait()
self.play(FadeIn(author))
self.wait(3)
class RevisitOriginalQuestion(TeacherStudentsScene):
def construct(self):
self.teacher_says("Let's revisit ", "\\\\ an old question")
self.random_blink()
question = OldTexText("What are ", "vectors", "?", arg_separator = "")
question.set_color_by_tex("vectors", YELLOW)
self.teacher_says(
question,
added_anims = [
ApplyMethod(self.get_students()[i].change_mode, mode)
for i, mode in enumerate([
"pondering", "raise_right_hand", "erm"
])
]
)
self.random_blink(2)
class WhatIsA2DVector(LinearTransformationScene):
CONFIG = {
"v_coords" : [1, 2],
"show_basis_vectors" : False,
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_HEIGHT,
"secondary_line_ratio" : 1
},
}
def construct(self):
self.plane.fade()
self.introduce_vector_and_space()
self.bring_in_students()
def introduce_vector_and_space(self):
v = Vector(self.v_coords)
coords = Matrix(self.v_coords)
coords.add_to_back(BackgroundRectangle(coords))
coords.next_to(v.get_end(), RIGHT)
two_d_vector = OldTexText(
"``Two-dimensional ", "vector", "''",
arg_separator = ""
)
two_d_vector.set_color_by_tex("vector", YELLOW)
two_d_vector.add_background_rectangle()
two_d_vector.to_edge(UP)
self.play(
Write(two_d_vector),
ShowCreation(v),
Write(coords),
run_time = 2
)
self.wait()
self.v, self.coords = v, coords
def bring_in_students(self):
everything = self.get_mobjects()
v, coords = self.v, self.coords
physics_student = PhysicsStudent()
cs_student = CSStudent()
students = [physics_student, cs_student]
for student, vect in zip(students, [LEFT, RIGHT]):
student.change_mode("confused")
student.to_corner(DOWN+vect, buff = MED_LARGE_BUFF)
student.look_at(v)
student.bubble = get_small_bubble(
student, height = 4, width = 4,
)
self.play(*list(map(FadeIn, students)))
self.play(Blink(physics_student))
self.wait()
for student, vect in zip(students, [RIGHT, LEFT]):
for mob in v, coords:
mob.target = mob.copy()
mob.target.scale(0.7)
arrow = OldTex("\\Rightarrow")
group = VGroup(v.target, arrow, coords.target)
group.arrange(vect)
student.bubble.add_content(group)
student.v, student.coords = v.copy(), coords.copy()
student.arrow = arrow
self.play(
student.change_mode, "pondering",
ShowCreation(student.bubble),
Write(arrow),
Transform(student.v, v.target),
Transform(student.coords, coords.target),
)
self.play(Blink(student))
self.wait()
anims = []
for student in students:
v, coords = student.v, student.coords
v.target = v.copy()
coords.target = coords.copy()
group = VGroup(v.target, coords.target)
group.arrange(DOWN)
group.set_height(coords.get_height())
group.next_to(student.arrow, RIGHT)
student.q_marks = OldTex("???")
student.q_marks.set_color_by_gradient(BLUE, YELLOW)
student.q_marks.next_to(student.arrow, LEFT)
anims += [
Write(student.q_marks),
MoveToTarget(v),
MoveToTarget(coords),
student.change_mode, "erm",
student.look_at, student.bubble
]
cs_student.v.save_state()
cs_student.coords.save_state()
self.play(*anims)
for student in students:
self.play(Blink(student))
self.wait()
self.play(*it.chain(
list(map(FadeOut, everything + [
physics_student.bubble,
physics_student.v,
physics_student.coords,
physics_student.arrow,
physics_student.q_marks,
cs_student.q_marks,
])),
[ApplyMethod(s.change_mode, "plain") for s in students],
list(map(Animation, [cs_student.bubble, cs_student.arrow])),
[mob.restore for mob in (cs_student.v, cs_student.coords)],
))
bubble = cs_student.get_bubble(SpeechBubble, width = 4, height = 3)
bubble.set_fill(BLACK, opacity = 1)
bubble.next_to(cs_student, UP+LEFT)
bubble.write("Consider higher \\\\ dimensions")
self.play(
cs_student.change_mode, "speaking",
ShowCreation(bubble),
Write(bubble.content)
)
self.play(Blink(physics_student))
self.wait()
class HigherDimensionalVectorsNumerically(Scene):
def construct(self):
words = VGroup(*list(map(TexText, [
"4D vector",
"5D vector",
"100D vector",
])))
words.arrange(RIGHT, buff = LARGE_BUFF*2)
words.to_edge(UP)
vectors = VGroup(*list(map(Matrix, [
[3, 1, 4, 1],
[5, 9, 2, 6, 5],
[3, 5, 8, "\\vdots", 0, 8, 6]
])))
colors = [YELLOW, MAROON_B, GREEN]
for word, vector, color in zip(words, vectors, colors):
vector.shift(word.get_center()[0]*RIGHT)
word.set_color(color)
vector.set_color(color)
for word in words:
self.play(FadeIn(word))
self.play(Write(vectors))
self.wait()
for index, dim, direction in (0, 4, RIGHT), (2, 100, LEFT):
v = vectors[index]
v.target = v.copy()
brace = Brace(v, direction)
brace.move_to(v)
v.target.next_to(brace, -direction)
text = brace.get_text("%d numbers"%dim)
self.play(
MoveToTarget(v),
GrowFromCenter(brace),
Write(text)
)
entries = v.get_entries()
num_entries = len(list(entries))
self.play(*[
Transform(
entries[i],
entries[i].copy().scale(1.2).set_color(WHITE),
rate_func = squish_rate_func(
there_and_back,
i/(2.*num_entries),
i/(2.*num_entries)+0.5
),
run_time = 2
)
for i in range(num_entries)
])
self.wait()
class HyperCube(VMobject):
CONFIG = {
"color" : BLUE_C,
"color2" : BLUE_D,
"dims" : 4,
}
def init_points(self):
corners = np.array(list(map(np.array, it.product(*[(-1, 1)]*self.dims))))
def project(four_d_array):
result = four_d_array[:3]
w = four_d_array[self.dims-1]
scalar = interpolate(0.8, 1.2 ,(w+1)/2.)
return scalar*result
for a1, a2 in it.combinations(corners, 2):
if sum(a1==a2) != self.dims-1:
continue
self.add(Line(project(a1), project(a2)))
self.pose_at_angle()
self.set_color_by_gradient(self.color, self.color2)
class AskAbout4DPhysicsStudent(Scene):
def construct(self):
physy = PhysicsStudent().to_edge(DOWN).shift(2*LEFT)
compy = CSStudent().to_edge(DOWN).shift(2*RIGHT)
for pi1, pi2 in (physy, compy), (compy, physy):
pi1.look_at(pi2.eyes)
physy.bubble = physy.get_bubble(SpeechBubble, width = 5, height = 4.5)
line = Line(LEFT, RIGHT, color = BLUE_B)
square = Square(color = BLUE_C)
square.scale(0.5)
cube = HyperCube(color = BLUE_D, dims = 3)
hyper_cube = HyperCube()
thought_mobs = []
for i, mob in enumerate([line, square, cube, hyper_cube]):
mob.set_height(2)
tex = OldTex("%dD"%(i+1))
tex.next_to(mob, UP)
group = VGroup(mob, tex)
thought_mobs.append(group)
group.shift(
physy.bubble.get_top() -\
tex.get_top() + MED_SMALL_BUFF*DOWN
)
line.shift(DOWN)
curr_mob = thought_mobs[0]
self.add(compy, physy)
self.play(
compy.change_mode, "confused",
physy.change_mode, "hooray",
ShowCreation(physy.bubble),
Write(curr_mob, run_time = 1),
)
self.play(Blink(compy))
for i, mob in enumerate(thought_mobs[1:]):
self.play(Transform(curr_mob, mob))
self.remove(curr_mob)
curr_mob = mob
self.add(curr_mob)
if i%2 == 1:
self.play(Blink(physy))
else:
self.wait()
self.play(Blink(compy))
self.wait()
class ManyCoordinateSystems(LinearTransformationScene):
CONFIG = {
"v_coords" : [2, 1],
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 1
},
}
def construct(self):
self.title = OldTexText("Many possible coordinate systems")
self.title.add_background_rectangle()
self.title.to_edge(UP)
self.add_foreground_mobject(self.title)
self.v = Vector(self.v_coords)
self.play(ShowCreation(self.v))
self.add_foreground_mobject(self.v)
t_matrices = [
[[0.5, 0.5], [-0.5, 0.5]],
[[1, -1], [-3, -1]],
[[-1, 2], [-0.5, -1]],
]
movers = [self.plane, self.i_hat, self.j_hat]
for mover in movers:
mover.save_state()
for t_matrix in t_matrices:
self.animate_coordinates()
self.play(*it.chain(
list(map(FadeOut, movers)),
list(map(Animation, self.foreground_mobjects))
))
for mover in movers:
mover.restore()
self.apply_transposed_matrix(t_matrix, run_time = 0)
self.play(*it.chain(
list(map(FadeIn, movers)),
list(map(Animation, self.foreground_mobjects))
))
self.animate_coordinates()
def animate_coordinates(self):
self.i_hat.save_state()
self.j_hat.save_state()
cob_matrix = np.array([
self.i_hat.get_end()[:2],
self.j_hat.get_end()[:2]
]).T
inv_cob = np.linalg.inv(cob_matrix)
coords = np.dot(inv_cob, self.v_coords)
array = Matrix(list(map(DecimalNumber, coords)))
array.get_entries()[0].set_color(X_COLOR)
array.get_entries()[1].set_color(Y_COLOR)
array.add_to_back(BackgroundRectangle(array))
for entry in array.get_entries():
entry.add_to_back(BackgroundRectangle(entry))
array.next_to(self.title, DOWN)
self.i_hat.target = self.i_hat.copy().scale(coords[0])
self.j_hat.target = self.j_hat.copy().scale(coords[1])
coord1, coord2 = array.get_entries().copy()
for coord, vect in (coord1, self.i_hat), (coord2, self.j_hat):
coord.target = coord.copy().next_to(
vect.target.get_end()/2,
rotate_vector(vect.get_end(), -np.pi/2)
)
self.play(Write(array, run_time = 1))
self.wait()
self.play(*list(map(MoveToTarget, [self.i_hat, coord1])))
self.play(*list(map(MoveToTarget, [self.j_hat, coord2])))
self.play(VGroup(self.j_hat, coord2).shift, self.i_hat.get_end())
self.wait(2)
self.play(
self.i_hat.restore,
self.j_hat.restore,
*list(map(FadeOut, [array, coord1, coord2]))
)
class DeterminantAndEigenvectorDontCare(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[3, 1], [1, 2]],
"include_background_plane" : False,
"show_basis_vectors" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_HEIGHT,
"secondary_line_ratio" : 1
},
}
def construct(self):
words = OldTexText(
"Determinant",
"and",
"eigenvectors",
"don't \\\\ care about the coordinate system"
)
words.set_color_by_tex("Determinant", YELLOW)
words.set_color_by_tex("eigenvectors", MAROON_B)
words.add_background_rectangle()
words.to_edge(UP)
dark_yellow = Color(rgb = interpolate(
color_to_rgb(YELLOW),
color_to_rgb(BLACK),
0.5
))
blob = Blob(
stroke_color = YELLOW,
fill_color = dark_yellow,
fill_opacity = 1,
)
blob.shift(2*LEFT+UP)
det_label = OldTex("A")
det_label = VGroup(
VectorizedPoint(det_label.get_left()).set_color(WHITE),
det_label
)
det_label_target = OldTex("\\det(M)\\cdot", "A")
det_label.move_to(blob)
eigenvectors = VGroup(*self.get_eigenvectors())
self.add_foreground_mobject(words)
self.wait()
self.play(
FadeIn(blob),
Write(det_label)
)
self.play(
ShowCreation(
eigenvectors,
run_time = 2,
),
Animation(words)
)
self.wait()
self.add_transformable_mobject(blob)
self.add_moving_mobject(det_label, det_label_target)
for vector in eigenvectors:
self.add_vector(vector, animate = False)
self.remove(self.plane)
non_plane_mobs = self.get_mobjects()
self.add(self.plane, *non_plane_mobs)
cob_matrices = [
None,
[[1, -1], [-3, -1]],
[[-1, 2], [-0.5, -1]],
]
def special_rate_func(t):
if t < 0.3:
return smooth(t/0.3)
if t > 0.7:
return smooth((1-t)/0.3)
return 1
for cob_matrix in cob_matrices:
if cob_matrix is not None:
self.play(
FadeOut(self.plane),
*list(map(Animation, non_plane_mobs))
)
transform = self.get_matrix_transformation(cob_matrix)
self.plane.apply_function(transform)
self.play(
FadeIn(self.plane),
*list(map(Animation, non_plane_mobs))
)
self.wait()
self.apply_transposed_matrix(
self.t_matrix,
rate_func = special_rate_func,
run_time = 8
)
def get_eigenvectors(self):
vals, (eig_matrix) = np.linalg.eig(self.t_matrix.T)
v1, v2 = eig_matrix.T
result = []
for v in v1, v2:
vectors = VGroup(*[
Vector(u*x*v)
for x in range(7, 0, -1)
for u in [-1, 1]
])
vectors.set_color_by_gradient(MAROON_A, MAROON_C)
result += list(vectors)
return result
class WhatIsSpace(Scene):
def construct(self):
physy = PhysicsStudent()
compy = CSStudent()
physy.to_edge(DOWN).shift(4*LEFT)
compy.to_edge(DOWN).shift(4*RIGHT)
physy.make_eye_contact(compy)
physy.bubble = get_small_bubble(physy)
vector = Vector([1, 2])
physy.bubble.add_content(vector)
compy.bubble = compy.get_bubble(SpeechBubble, width = 6, height = 4)
compy.bubble.set_fill(BLACK, opacity = 1)
compy.bubble.write("What exactly do\\\\ you mean by ``space''?")
self.add(compy, physy)
self.play(
physy.change_mode, "pondering",
ShowCreation(physy.bubble),
ShowCreation(vector)
)
self.play(
compy.change_mode, "sassy",
ShowCreation(compy.bubble),
Write(compy.bubble.content)
)
self.play(Blink(physy))
self.wait()
self.play(Blink(compy))
self.wait()
class OtherVectorishThings(TeacherStudentsScene):
def construct(self):
words = OldTexText(
"There are other\\\\",
"vectorish",
"things..."
)
words.set_color_by_tex("vectorish", YELLOW)
self.teacher_says(words)
self.play_student_changes(
"pondering", "raise_right_hand", "erm"
)
self.random_blink(2)
words = OldTexText("...like", "functions")
words.set_color_by_tex("functions", PINK)
self.teacher_says(words)
self.play_student_changes(*["pondering"]*3)
self.random_blink(2)
self.teacher_thinks("")
self.zoom_in_on_thought_bubble(self.get_teacher().bubble)
class FunctionGraphScene(Scene):
CONFIG = {
"graph_colors" : [RED, YELLOW, PINK],
"default_functions" : [
lambda x : (x**3 - 9*x)/20.,
lambda x : -(x**2)/8.+1
],
"default_names" : ["f", "g", "h"],
"x_min" : -4,
"x_max" : 4,
"line_to_line_buff" : 0.03
}
def setup(self):
self.axes = Axes(
x_min = self.x_min,
x_max = self.x_max,
)
self.add(self.axes)
self.graphs = []
def get_function_graph(self, func = None, animate = True,
add = True, **kwargs):
index = len(self.graphs)
if func is None:
func = self.default_functions[
index%len(self.default_functions)
]
default_color = self.graph_colors[index%len(self.graph_colors)]
kwargs["color"] = kwargs.get("color", default_color)
kwargs["x_min"] = kwargs.get("x_min", self.x_min)
kwargs["x_max"] = kwargs.get("x_max", self.x_max)
graph = FunctionGraph(func, **kwargs)
if animate:
self.play(ShowCreation(graph))
if add:
self.add(graph)
self.graphs.append(graph)
return graph
def get_index(self, function_graph):
if function_graph not in self.graphs:
self.graphs.append(function_graph)
return self.graphs.index(function_graph)
def get_output_lines(self, function_graph, num_steps = None, nudge = True):
index = self.get_index(function_graph)
num_steps = num_steps or function_graph.num_steps
lines = VGroup()
nudge_size = index*self.line_to_line_buff
x_min, x_max = function_graph.x_min, function_graph.x_max
for x in np.linspace(x_min, x_max, num_steps):
if nudge:
x += nudge_size
y = function_graph.function(x)
lines.add(Line(x*RIGHT, x*RIGHT+y*UP))
lines.set_color(function_graph.get_color())
return lines
def add_lines(self, output_lines):
self.play(ShowCreation(
output_lines,
lag_ratio = 0.5,
run_time = 2
))
def label_graph(self, function_graph, name = None, animate = True):
index = self.get_index(function_graph)
name = name or self.default_names[index%len(self.default_names)]
label = OldTex("%s(x)"%name)
label.next_to(function_graph.point_from_proportion(1), RIGHT)
label.shift_onto_screen()
label.set_color(function_graph.get_color())
if animate:
self.play(Write(label))
else:
self.add(label)
return label
class AddTwoFunctions(FunctionGraphScene):
def construct(self):
f_graph = self.get_function_graph()
g_graph = self.get_function_graph()
def sum_func(x):
return f_graph.get_function()(x)+g_graph.get_function()(x)
sum_graph = self.get_function_graph(sum_func, animate = False)
self.remove(sum_graph)
f_label = self.label_graph(f_graph)
g_label = self.label_graph(g_graph)
f_lines = self.get_output_lines(f_graph)
g_lines = self.get_output_lines(g_graph)
sum_lines = self.get_output_lines(sum_graph, nudge = False)
curr_x_point = f_lines[0].get_start()
sum_def = self.get_sum_definition(DecimalNumber(curr_x_point[0]))
# sum_def.set_width(FRAME_X_RADIUS-1)
sum_def.to_corner(UP+LEFT)
arrow = Arrow(sum_def[2].get_bottom(), curr_x_point, color = WHITE)
prefix = sum_def[0]
suffix = VGroup(*sum_def[1:])
rect = BackgroundRectangle(sum_def)
brace = Brace(prefix)
brace.add(brace.get_text("New function").shift_onto_screen())
self.play(
Write(prefix, run_time = 2),
FadeIn(brace)
)
self.wait()
for lines in f_lines, g_lines:
self.add_lines(lines)
self.play(*list(map(FadeOut, [f_graph, g_graph])))
self.wait()
self.play(FadeOut(brace))
fg_group = VGroup(*list(f_label)+list(g_label))
self.play(
FadeIn(rect),
Animation(prefix),
Transform(fg_group, suffix),
)
self.remove(prefix, fg_group)
self.add(sum_def)
self.play(ShowCreation(arrow))
self.show_line_addition(f_lines[0], g_lines[0], sum_lines[0])
self.wait()
curr_x_point = f_lines[1].get_start()
new_sum_def = self.get_sum_definition(DecimalNumber(curr_x_point[0]))
new_sum_def.to_corner(UP+LEFT)
new_arrow = Arrow(sum_def[2].get_bottom(), curr_x_point, color = WHITE)
self.play(
Transform(sum_def, new_sum_def),
Transform(arrow, new_arrow),
)
self.show_line_addition(f_lines[1], g_lines[1], sum_lines[1])
self.wait()
final_sum_def = self.get_sum_definition(OldTex("x"))
final_sum_def.to_corner(UP+LEFT)
self.play(
FadeOut(rect),
Transform(sum_def, final_sum_def),
FadeOut(arrow)
)
self.show_line_addition(*it.starmap(VGroup, [
f_lines[2:], g_lines[2:], sum_lines[2:]
]))
self.play(ShowCreation(sum_graph))
def get_sum_definition(self, input_mob):
result = VGroup(*it.chain(
OldTex("(f+g)", "("),
[input_mob.copy()],
OldTex(")", "=", "f("),
[input_mob.copy()],
OldTex(")", "+", "g("),
[input_mob.copy()],
OldTex(")")
))
result.arrange()
result[0].set_color(self.graph_colors[2])
VGroup(result[5], result[7]).set_color(self.graph_colors[0])
VGroup(result[9], result[11]).set_color(self.graph_colors[1])
return result
def show_line_addition(self, f_lines, g_lines, sum_lines):
g_lines.target = g_lines.copy()
dots = VGroup()
dots.target = VGroup()
for f_line, g_line in zip(f_lines, g_lines.target):
align_perfectly = f_line.get_end()[1]*g_line.get_end()[1] > 0
dot = Dot(g_line.get_end(), radius = 0.07)
g_line.shift(f_line.get_end()-g_line.get_start())
dot.target = Dot(g_line.get_end())
if not align_perfectly:
g_line.shift(self.line_to_line_buff*RIGHT)
dots.add(dot)
dots.target.add(dot.target)
for group in dots, dots.target:
group.set_color(sum_lines[0].get_color())
self.play(ShowCreation(dots))
if len(list(g_lines)) == 1:
kwargs = {}
else:
kwargs = {
"lag_ratio" : 0.5,
"run_time" : 3
}
self.play(*[
MoveToTarget(mob, **kwargs)
for mob in (g_lines, dots)
])
# self.play(
# *[mob.fade for mob in g_lines, f_lines]+[
# Animation(dots)
# ])
self.wait()
class AddVectorsCoordinateByCoordinate(Scene):
def construct(self):
v1 = Matrix(["x_1", "y_1", "z_1"])
v2 = Matrix(["x_2", "y_2", "z_2"])
v_sum = Matrix(["x_1 + x_2", "y_1 + y_2", "z_1 + z_2"])
for v in v1, v2, v_sum:
v.get_entries()[0].set_color(X_COLOR)
v.get_entries()[1].set_color(Y_COLOR)
v.get_entries()[2].set_color(Z_COLOR)
plus, equals = OldTex("+=")
VGroup(v1, plus, v2, equals, v_sum).arrange()
self.add(v1, plus, v2)
self.wait()
self.play(
Write(equals),
Write(v_sum.get_brackets())
)
self.play(
Transform(v1.get_entries().copy(), v_sum.get_entries()),
Transform(v2.get_entries().copy(), v_sum.get_entries()),
)
self.wait()
class ScaleFunction(FunctionGraphScene):
def construct(self):
graph = self.get_function_graph(
lambda x : self.default_functions[0](x),
animate = False
)
scaled_graph = self.get_function_graph(
lambda x : graph.get_function()(x)*2,
animate = False, add = False
)
graph_lines = self.get_output_lines(graph)
scaled_lines = self.get_output_lines(scaled_graph, nudge = False)
f_label = self.label_graph(graph, "f", animate = False)
two_f_label = self.label_graph(scaled_graph, "(2f)", animate = False)
self.remove(two_f_label)
title = OldTex("(2f)", "(x) = 2", "f", "(x)")
title.set_color_by_tex("(2f)", scaled_graph.get_color())
title.set_color_by_tex("f", graph.get_color())
title.next_to(ORIGIN, LEFT, buff = MED_SMALL_BUFF)
title.to_edge(UP)
self.add(title)
self.add_lines(graph_lines)
self.wait()
self.play(Transform(graph_lines, scaled_lines))
self.play(ShowCreation(scaled_graph))
self.play(Write(two_f_label))
self.play(FadeOut(graph_lines))
self.wait()
class ScaleVectorByCoordinates(Scene):
def construct(self):
two, dot, equals = OldTex("2 \\cdot =")
v1 = Matrix(list("xyz"))
v1.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR, Z_COLOR)
v2 = v1.copy()
two_targets = VGroup(*[
two.copy().next_to(entry, LEFT)
for entry in v2.get_entries()
])
v2.get_brackets()[0].next_to(two_targets, LEFT)
v2.add(two_targets)
VGroup(two, dot, v1, equals, v2).arrange()
self.add(two, dot, v1)
self.play(
Write(equals),
Write(v2.get_brackets())
)
self.play(
Transform(two.copy(), two_targets),
Transform(v1.get_entries().copy(), v2.get_entries())
)
self.wait()
class ShowSlopes(Animation):
CONFIG = {
"line_color" : YELLOW,
"dx" : 0.01,
"rate_func" : None,
"run_time" : 5
}
def __init__(self, graph, **kwargs):
digest_config(self, kwargs, locals())
line = Line(LEFT, RIGHT, color = self.line_color)
line.save_state()
Animation.__init__(self, line, **kwargs)
def interpolate_mobject(self, alpha):
f = self.graph.point_from_proportion
low, high = list(map(f, np.clip([alpha-self.dx, alpha+self.dx], 0, 1)))
slope = (high[1]-low[1])/(high[0]-low[0])
self.mobject.restore()
self.mobject.rotate(np.arctan(slope))
self.mobject.move_to(f(alpha))
class FromVectorsToFunctions(VectorScene):
def construct(self):
self.show_vector_addition_and_scaling()
self.bring_in_functions()
self.show_derivative()
def show_vector_addition_and_scaling(self):
self.plane = self.add_plane()
self.plane.fade()
words1 = OldTexText("Vector", "addition")
words2 = OldTexText("Vector", "scaling")
for words in words1, words2:
words.add_background_rectangle()
words.next_to(ORIGIN, RIGHT).to_edge(UP)
self.add(words1)
v = self.add_vector([2, -1], color = MAROON_B)
w = self.add_vector([3, 2], color = YELLOW)
w.save_state()
self.play(w.shift, v.get_end())
vw_sum = self.add_vector(w.get_end(), color = PINK)
self.wait()
self.play(
Transform(words1, words2),
FadeOut(vw_sum),
w.restore
)
self.add(
v.copy().fade(),
w.copy().fade()
)
self.play(v.scale, 2)
self.play(w.scale, -0.5)
self.wait()
def bring_in_functions(self):
everything = VGroup(*self.get_mobjects())
axes = Axes()
axes.shift(FRAME_WIDTH*LEFT)
fg_scene_config = FunctionGraphScene.CONFIG
graph = FunctionGraph(fg_scene_config["default_functions"][0])
graph.set_color(MAROON_B)
func_tex = OldTex("\\frac{1}{9}x^3 - x")
func_tex.set_color(graph.get_color())
func_tex.shift(5.5*RIGHT+2*UP)
words = VGroup(*[
OldTexText(words).add_background_rectangle()
for words in [
"Linear transformations",
"Null space",
"Dot products",
"Eigen-everything",
]
])
words.set_color_by_gradient(BLUE_B, BLUE_D)
words.arrange(DOWN, aligned_edge = LEFT)
words.to_corner(UP+LEFT)
self.play(FadeIn(
words,
lag_ratio = 0.5,
run_time = 3
))
self.wait()
self.play(*[
ApplyMethod(mob.shift, FRAME_WIDTH*RIGHT)
for mob in (axes, everything)
] + [Animation(words)]
)
self.play(ShowCreation(graph), Animation(words))
self.play(Write(func_tex, run_time = 2))
self.wait(2)
top_word = words[0]
words.remove(top_word)
self.play(
FadeOut(words),
top_word.shift, top_word.get_center()[0]*LEFT
)
self.wait()
self.func_tex = func_tex
self.graph = graph
def show_derivative(self):
func_tex, graph = self.func_tex, self.graph
new_graph = FunctionGraph(lambda x : (x**2)/3.-1)
new_graph.set_color(YELLOW)
func_tex.generate_target()
lp, rp = parens = OldTex("()")
parens.set_height(func_tex.get_height())
L, equals = OldTex("L=")
deriv = OldTex("\\frac{d}{dx}")
new_func = OldTex("\\frac{1}{3}x^2 - 1")
new_func.set_color(YELLOW)
group = VGroup(
L, lp, func_tex.target, rp,
equals, new_func
)
group.arrange()
group.shift(2*UP).to_edge(LEFT, buff = MED_LARGE_BUFF)
rect = BackgroundRectangle(group)
group.add_to_back(rect)
deriv.move_to(L, aligned_edge = RIGHT)
self.play(
MoveToTarget(func_tex),
*list(map(Write, [L, lp, rp, equals, new_func]))
)
self.remove(func_tex)
self.add(func_tex.target)
self.wait()
faded_graph = graph.copy().fade()
self.add(faded_graph)
self.play(
Transform(graph, new_graph, run_time = 2),
Animation(group)
)
self.wait()
self.play(Transform(L, deriv))
self.play(ShowSlopes(faded_graph))
self.wait()
class TransformationsAndOperators(TeacherStudentsScene):
def construct(self):
self.student_says("""
Are these the same
as ``linear operators''?
""", index = 0)
self.random_blink()
teacher = self.get_teacher()
bubble = teacher.get_bubble(SpeechBubble, height = 2, width = 2)
bubble.set_fill(BLACK, opacity = 1)
bubble.write("Yup!")
self.play(
teacher.change_mode, "hooray",
ShowCreation(bubble),
Write(bubble.content, run_time = 1)
)
self.random_blink(2)
class ManyFunctions(FunctionGraphScene):
def construct(self):
randy = Randolph().to_corner(DOWN+LEFT)
self.add(randy)
for i in range(100):
if i < 3:
run_time = 1
self.wait()
elif i < 10:
run_time = 0.4
else:
run_time = 0.2
added_anims = []
if i == 3:
added_anims = [randy.change_mode, "confused"]
if i == 10:
added_anims = [randy.change_mode, "pleading"]
self.add_random_function(
run_time = run_time,
added_anims = added_anims
)
def add_random_function(self, run_time = 1, added_anims = []):
coefs = np.random.randint(-3, 3, np.random.randint(3, 8))
def func(x):
return sum([c*x**(i) for i, c, in enumerate(coefs)])
graph = self.get_function_graph(func, animate = False)
if graph.get_height() > FRAME_HEIGHT:
graph.stretch_to_fit_height(FRAME_HEIGHT)
graph.shift(graph.point_from_proportion(0.5)[1]*DOWN)
graph.shift(interpolate(-3, 3, random.random())*UP)
graph.set_color(random_bright_color())
self.play(
ShowCreation(graph, run_time = run_time),
*added_anims
)
class WhatDoesLinearMean(TeacherStudentsScene):
def construct(self):
words = OldTexText("""
What does it mean for
a transformation of functions
to be """, "linear", "?",
arg_separator = ""
)
words.set_color_by_tex("linear", BLUE)
self.student_says(words)
self.play_student_changes("pondering")
self.random_blink(4)
class FormalDefinitionOfLinear(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"include_background_plane" : False,
"t_matrix" : [[1, 1], [-0.5, 1]],
"w_coords" : [1, 1],
"v_coords" : [1, -2],
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_HEIGHT,
"secondary_line_ratio" : 1
},
}
def construct(self):
self.plane.fade()
self.write_properties()
self.show_additive_property()
self.show_scaling_property()
self.add_words()
def write_properties(self):
title = OldTexText(
"Formal definition of linearity"
)
title.add_background_rectangle()
title.to_edge(UP)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
h_line.next_to(title, DOWN)
v_tex, w_tex = ["\\vec{\\textbf{%s}}"%s for s in "vw"]
tex_sets = [
[
("\\text{Additivity: }",),
("L(", v_tex, "+", w_tex, ")"),
("=", "L(", v_tex, ")", "+", "L(", w_tex, ")"),
],
[
("\\text{Scaling: }",),
("L(", "c", v_tex, ")"),
("=", "c", "L(", v_tex, ")"),
],
]
properties = VGroup()
for tex_set in tex_sets:
words = VGroup(*it.starmap(Tex, tex_set))
for word in words:
word.set_color_by_tex(v_tex, YELLOW)
word.set_color_by_tex(w_tex, MAROON_B)
word.set_color_by_tex("c", GREEN)
words.arrange()
words.lhs = words[1]
words.rhs = words[2]
words.add_to_back(BackgroundRectangle(words))
# words.scale(0.8)
properties.add(words)
properties.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF)
properties.next_to(h_line, DOWN, buff = MED_LARGE_BUFF).to_edge(LEFT)
self.play(Write(title), ShowCreation(h_line))
self.wait()
for words in properties:
self.play(Write(words))
self.wait()
self.add_foreground_mobject(title, h_line, *properties)
self.additivity, self.scaling = properties
def show_additive_property(self):
self.plane.save_state()
v = self.add_vector(self.v_coords)
v_label = self.add_transformable_label(v, "v", direction = "right")
w = self.add_vector(self.w_coords, color = MAROON_B)
w_label = self.add_transformable_label(w, "w", direction = "left")
w_group = VGroup(w, w_label)
w_group.save_state()
self.play(w_group.shift, v.get_end())
vw_sum = self.add_vector(w.get_end(), color = PINK)
v_label_copy, w_label_copy = v_label.copy(), w_label.copy()
v_label_copy.generate_target()
w_label_copy.generate_target()
plus = OldTex("+")
vw_label = VGroup(v_label_copy.target, plus, w_label_copy.target)
vw_label.arrange()
vw_label.next_to(vw_sum.get_end(), RIGHT)
self.play(
MoveToTarget(v_label_copy),
MoveToTarget(w_label_copy),
Write(plus)
)
vw_label_copy = vw_label.copy()
vw_label = VGroup(
VectorizedPoint(vw_label.get_left()),
vw_label,
VectorizedPoint(vw_label.get_right()),
)
self.remove(v_label_copy, w_label_copy, plus)
self.add(vw_label)
self.play(
w_group.restore,
)
vw_label.target = VGroup(
OldTex("L(").scale(0.8),
vw_label_copy,
OldTex(")").scale(0.8),
)
vw_label.target.arrange()
for mob in vw_label, vw_label.target:
mob.add_to_back(BackgroundRectangle(mob))
transform = self.get_matrix_transformation(self.t_matrix)
point = transform(vw_sum.get_end())
vw_label.target.next_to(point, UP)
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [MoveToTarget(vw_label)]
)
self.wait()
self.play(w_group.shift, v.get_end())
v_label_copy, w_label_copy = v_label.copy(), w_label.copy()
v_label_copy.generate_target()
w_label_copy.generate_target()
equals, plus = OldTex("=+")
rhs = VGroup(
equals, v_label_copy.target,
plus, w_label_copy.target
)
rhs.arrange()
rhs.next_to(vw_label, RIGHT)
rect = BackgroundRectangle(rhs)
self.play(*it.chain(
list(map(Write, [rect, equals, plus])),
list(map(MoveToTarget, [v_label_copy, w_label_copy])),
))
to_fade = [self.plane, v, v_label, w_group, vw_label, vw_sum]
to_fade += self.get_mobjects_from_last_animation()
self.wait()
self.play(*it.chain(
list(map(FadeOut, to_fade)),
list(map(Animation, self.foreground_mobjects))
))
self.plane.restore()
self.play(FadeIn(self.plane), *list(map(Animation, self.foreground_mobjects)))
self.transformable_mobjects = []
self.moving_vectors = []
self.transformable_labels = []
self.moving_mobjects = []
self.add_transformable_mobject(self.plane)
self.add(*self.foreground_mobjects)
def show_scaling_property(self):
v = self.add_vector([1, -1])
v_label = self.add_transformable_label(v, "v")
scaled_v = v.copy().scale(2)
scaled_v_label = OldTex("c\\vec{\\textbf{v}}")
scaled_v_label.set_color(YELLOW)
scaled_v_label[0].set_color(GREEN)
scaled_v_label.next_to(scaled_v.get_end(), RIGHT)
scaled_v_label.add_background_rectangle()
v_copy, v_label_copy = v.copy(), v_label.copy()
self.play(
Transform(v_copy, scaled_v),
Transform(v_label_copy, scaled_v_label),
)
self.remove(v_copy, v_label_copy)
self.add(scaled_v_label)
self.add_vector(scaled_v, animate = False)
self.wait()
transform = self.get_matrix_transformation(self.t_matrix)
point = transform(scaled_v.get_end())
scaled_v_label.target = OldTex("L(", "c", "\\vec{\\textbf{v}}", ")")
scaled_v_label.target.set_color_by_tex("c", GREEN)
scaled_v_label.target.set_color_by_tex("\\vec{\\textbf{v}}", YELLOW)
scaled_v_label.target.scale(0.8)
scaled_v_label.target.next_to(point, RIGHT)
scaled_v_label.target.add_background_rectangle()
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [MoveToTarget(scaled_v_label)]
)
self.wait()
scaled_v = v.copy().scale(2)
rhs = OldTex("=", "c", "L(", "\\vec{\\textbf{v}}", ")")
rhs.set_color_by_tex("c", GREEN)
rhs.set_color_by_tex("\\vec{\\textbf{v}}", YELLOW)
rhs.add_background_rectangle()
rhs.scale(0.8)
rhs.next_to(scaled_v_label, RIGHT)
v_copy = v.copy()
self.add(v_copy)
self.play(Transform(v, scaled_v))
self.play(Write(rhs))
self.wait()
faders = [
scaled_v_label, scaled_v, v_copy,
v, rhs
] + self.transformable_labels + self.moving_vectors
self.play(*list(map(FadeOut, faders)))
def add_words(self):
randy = Randolph().shift(LEFT).to_edge(DOWN)
bubble = randy.get_bubble(SpeechBubble, width = 6, height = 4)
bubble.set_fill(BLACK, opacity = 0.8)
bubble.shift(0.5*DOWN)
VGroup(randy, bubble).to_edge(RIGHT, buff = 0)
words = OldTexText(
"Linear transformations\\\\",
"preserve",
"addition and \\\\ scalar multiplication",
)
words.scale(0.9)
words.set_color_by_tex("preserve", YELLOW)
bubble.add_content(words)
self.play(FadeIn(randy))
self.play(
ShowCreation(bubble),
Write(words),
randy.change_mode, "speaking",
)
self.play(Blink(randy))
self.wait()
class CalcStudentsKnowThatDerivIsLinear(TeacherStudentsScene):
def construct(self):
words = OldTexText(
"""Calc students subconsciously
know that""",
"$\\dfrac{d}{dx}$",
"is linear"
)
words.set_color_by_tex("$\\dfrac{d}{dx}$", BLUE)
self.teacher_says(words)
self.play_student_changes(
"pondering", "confused", "erm"
)
self.random_blink(3)
class DerivativeIsLinear(Scene):
def construct(self):
self.add_title()
self.prepare_text()
self.show_additivity()
self.show_scaling()
def add_title(self):
title = OldTexText("Derivative is linear")
title.to_edge(UP)
self.add(title)
def prepare_text(self):
v_tex, w_tex = ["\\vec{\\textbf{%s}}"%s for s in "vw"]
additivity = OldTex(
"L(", v_tex, "+", w_tex, ")", "=",
"L(", v_tex, ")+L(", w_tex, ")"
)
scaling = OldTex(
"L(", "c", v_tex, ")=", "c", "L(", v_tex, ")"
)
for text in additivity, scaling:
text.set_color_by_tex(v_tex, YELLOW)
text.set_color_by_tex(w_tex, MAROON_B)
text.set_color_by_tex("c", GREEN)
deriv_tex = "\\dfrac{d}{dx}"
deriv_additivity = OldTex(
deriv_tex, "(", "x^3", "+", "x^2", ")", "=",
deriv_tex, "(", "x^3", ")", "+",
deriv_tex, "(", "x^2", ")"
)
deriv_scaling = OldTex(
deriv_tex, "(", "4", "x^3", ")", "=",
"4", deriv_tex, "(", "x^3", ")"
)
for text in deriv_additivity, deriv_scaling:
text.set_color_by_tex("x^3", YELLOW)
text.set_color_by_tex("x^2", MAROON_B)
text.set_color_by_tex("4", GREEN)
self.additivity = additivity
self.scaling = scaling
self.deriv_additivity = deriv_additivity
self.deriv_scaling = deriv_scaling
def show_additivity(self):
general, deriv = self.additivity, self.deriv_additivity
group = VGroup(general, deriv )
group.arrange(DOWN, buff = 1.5)
inner_sum = VGroup(*deriv[2:2+3])
outer_sum_deriv = VGroup(deriv[0], deriv[1], deriv[5])
inner_func1 = deriv[9]
outer_deriv1 = VGroup(deriv[7], deriv[8], deriv[10])
plus = deriv[11]
inner_func2 = deriv[14]
outer_deriv2 = VGroup(deriv[12], deriv[13], deriv[15])
self.play(FadeIn(group))
self.wait()
self.point_out(inner_sum)
self.point_out(outer_sum_deriv)
self.wait()
self.point_out(outer_deriv1, outer_deriv2)
self.point_out(inner_func1, inner_func2)
self.point_out(plus)
self.wait()
self.play(FadeOut(group))
def show_scaling(self):
general, deriv = self.scaling, self.deriv_scaling
group = VGroup(general, deriv)
group.arrange(DOWN, buff = 1.5)
inner_scaling = VGroup(*deriv[2:4])
lhs_deriv = VGroup(deriv[0], deriv[1], deriv[4])
rhs_deriv = VGroup(*deriv[7:])
outer_scaling = deriv[6]
self.play(FadeIn(group))
self.wait()
self.point_out(inner_scaling)
self.point_out(lhs_deriv)
self.wait()
self.point_out(rhs_deriv)
self.point_out(outer_scaling)
self.wait()
def point_out(self, *terms):
anims = []
for term in terms:
anims += [
term.scale, 1.2,
term.set_color, RED,
]
self.play(
*anims,
run_time = 1,
rate_func = there_and_back
)
class ProposeDerivativeAsMatrix(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"""
Let's describe the
derivative with
a matrix
""",
target_mode = "hooray"
)
self.random_blink()
self.play_student_changes("pondering", "confused", "erm")
self.random_blink(3)
class PolynomialsHaveArbitrarilyLargeDegree(Scene):
def construct(self):
polys = VGroup(*list(map(Tex, [
"x^{300} + 9x^2",
"4x^{4{,}000{,}000{,}000} + 1",
"3x^{\\left(10^{100}\\right)}",
"\\vdots"
])))
polys.set_color_by_gradient(BLUE_B, BLUE_D)
polys.arrange(DOWN, buff = MED_LARGE_BUFF)
polys.scale(1.3)
arrow = OldTex("\\Rightarrow").scale(1.5)
brace = Brace(
Line(UP, DOWN).scale(FRAME_Y_RADIUS).shift(FRAME_X_RADIUS*RIGHT),
LEFT
)
words = OldTexText("Infinitely many")
words.scale(1.5)
words.next_to(brace, LEFT)
arrow.next_to(words, LEFT)
polys.next_to(arrow, LEFT)
self.play(Write(polys))
self.wait()
self.play(
FadeIn(arrow),
Write(words),
GrowFromCenter(brace)
)
self.wait()
class GeneneralPolynomialCoordinates(Scene):
def construct(self):
poly = OldTex(
"a_n", "x^n", "+",
"a_{n-1}", "x^{n-1}", "+",
"\\cdots",
"a_1", "x", "+",
"a_0",
)
poly.set_color_by_tex("a_n", YELLOW)
poly.set_color_by_tex("a_{n-1}", MAROON_B)
poly.set_color_by_tex("a_1", RED)
poly.set_color_by_tex("a_0", GREEN)
poly.scale(1.3)
array = Matrix(
["a_0", "a_1", "\\vdots", "a_{n-1}", "a_n", "0", "\\vdots"]
)
array.get_entries()[0].set_color(GREEN)
array.get_entries()[1].set_color(RED)
array.get_entries()[3].set_color(MAROON_B)
array.get_entries()[4].set_color(YELLOW)
array.scale(1.2)
equals = OldTex("=").scale(1.3)
group = VGroup(poly, equals, array)
group.arrange()
group.to_edge(RIGHT)
pre_entries = VGroup(
poly[-1], poly[-4], poly[-5],
poly[3], poly[0],
VectorizedPoint(poly.get_left()),
VectorizedPoint(poly.get_left()),
)
self.add(poly, equals, array.get_brackets())
self.wait()
self.play(
Transform(pre_entries.copy(), array.get_entries())
)
self.wait()
class SimplePolynomialCoordinates(Scene):
def construct(self):
matrix = Matrix(["5", "3", "1", "0", "\\vdots"])
matrix.to_edge(LEFT)
self.play(Write(matrix))
self.wait()
class IntroducePolynomialSpace(Scene):
def construct(self):
self.add_title()
self.show_polynomial_cloud()
self.split_individual_polynomial()
self.list_basis_functions()
self.show_example_coordinates()
self.derivative_as_matrix()
def add_title(self):
title = OldTexText("Our current space: ", "All polynomials")
title.to_edge(UP)
title[1].set_color(BLUE)
self.play(Write(title))
self.wait()
self.title = title
def show_polynomial_cloud(self):
cloud = ThoughtBubble()[-1]
cloud.stretch_to_fit_height(6)
cloud.center()
polys = VGroup(
OldTex("x^2", "+", "3", "x", "+", "5"),
OldTex("4x^7-5x^2"),
OldTex("x^{100}+2x^{99}+3x^{98}"),
OldTex("3x-7"),
OldTex("x^{1{,}000{,}000{,}000}+1"),
OldTex("\\vdots"),
)
polys.set_color_by_gradient(BLUE_B, BLUE_D)
polys.arrange(DOWN, buff = MED_SMALL_BUFF)
polys.next_to(cloud.get_top(), DOWN, buff = MED_LARGE_BUFF)
self.play(ShowCreation(cloud))
for poly in polys:
self.play(Write(poly), run_time = 1)
self.wait()
self.poly1, self.poly2 = polys[0], polys[1]
polys.remove(self.poly1)
self.play(
FadeOut(cloud),
FadeOut(polys),
self.poly1.next_to, ORIGIN, LEFT,
self.poly1.set_color, WHITE
)
def split_individual_polynomial(self):
leading_coef = OldTex("1")
leading_coef.next_to(self.poly1[0], LEFT, aligned_edge = DOWN)
self.poly1.add_to_back(leading_coef)
one = OldTex("\\cdot", "1")
one.next_to(self.poly1[-1], RIGHT, aligned_edge = DOWN)
self.poly1.add(one)
for mob in leading_coef, one:
mob.set_color(BLACK)
brace = Brace(self.poly1)
brace.text = brace.get_text("Already written as \\\\ a linear combination")
index_to_color = {
0 : WHITE,
1 : Z_COLOR,
4 : Y_COLOR,
7 : X_COLOR,
}
self.play(
GrowFromCenter(brace),
Write(brace.text),
*[
ApplyMethod(self.poly1[index].set_color, color)
for index, color in list(index_to_color.items())
]
)
self.wait()
self.brace = brace
def list_basis_functions(self):
title = OldTexText("Basis functions")
title.next_to(self.title, DOWN, buff = MED_SMALL_BUFF)
title.to_edge(RIGHT)
h_line = Line(ORIGIN, RIGHT).scale(title.get_width())
h_line.next_to(title, DOWN)
x_cubed = OldTex("x^3")
x_cubed.set_color(MAROON_B)
x_cubed.to_corner(DOWN+RIGHT).shift(2*(DOWN+RIGHT))
basis_group = VGroup(
self.poly1[7][1],
self.poly1[4],
self.poly1[1],
x_cubed
).copy()
basis_group.generate_target()
basis_group.target.arrange(
DOWN, buff = 0.75*LARGE_BUFF, aligned_edge = LEFT
)
basis_group.target.to_edge(RIGHT, buff = MED_LARGE_BUFF)
dots = OldTex("\\vdots")
dots.next_to(basis_group.target, DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT)
basis_functions = [
OldTex("b_%d(x)"%i, "=")
for i in range(len(list(basis_group)))
]
for basis_func, term in zip(basis_functions, basis_group.target):
basis_func.set_color(term.get_color())
basis_func.next_to(term, LEFT)
for i in 2, 3:
basis_functions[i].shift(SMALL_BUFF*DOWN)
self.play(
FadeIn(title),
ShowCreation(h_line),
MoveToTarget(basis_group),
Write(dots)
)
for basis_func in basis_functions:
self.play(Write(basis_func, run_time = 1))
self.play(Write(dots))
self.wait()
self.basis = basis_group
self.basis_functions = basis_functions
def show_example_coordinates(self):
coords = Matrix(["5", "3", "1", "0", "0", "\\vdots"])
for i, color in enumerate([X_COLOR, Y_COLOR, Z_COLOR]):
coords[i].set_color(color)
self.poly1.generate_target()
equals = OldTex("=").next_to(coords, LEFT)
self.poly1.target.next_to(equals, LEFT)
entries = coords.get_entries()
entries.save_state()
entries.set_fill(opacity = 0)
self.play(
MoveToTarget(self.poly1),
Write(equals),
FadeOut(self.brace),
FadeOut(self.brace.text)
)
for entry, index in zip(entries, [6, 3, 0]):
entry.move_to(self.poly1[index])
self.play(Write(coords.get_brackets()))
self.play(
entries.restore,
lag_ratio = 0.5,
run_time = 3
)
self.wait()
target = self.poly1.copy()
terms = [
VGroup(*target[6:8]),
VGroup(target[5], *target[3:5]),
VGroup(target[2], *target[0:2]),
]
target[5].next_to(target[3], LEFT)
target[2].next_to(target[0], LEFT)
more_terms = [
OldTex("+0", "x^3").set_color_by_tex("x^3", MAROON_B),
OldTex("+0", "x^4").set_color_by_tex("x^4", YELLOW),
OldTex("\\vdots")
]
for entry, term in zip(entries, terms+more_terms):
term.next_to(entry, LEFT, buff = LARGE_BUFF)
more_terms[-1].shift(MED_SMALL_BUFF*LEFT)
self.play(Transform(self.poly1, target))
self.wait()
self.play(FadeIn(
VGroup(*more_terms),
lag_ratio = 0.5,
run_time = 2
))
self.wait()
self.play(*list(map(FadeOut, [self.poly1]+more_terms)))
self.poly2.next_to(equals, LEFT)
self.poly2.shift(MED_SMALL_BUFF*UP)
self.poly2.set_color(WHITE)
self.poly2[0].set_color(TEAL)
VGroup(*self.poly2[3:5]).set_color(Z_COLOR)
new_coords = Matrix(["0", "0", "-5", "0", "0", "0", "0", "4", "\\vdots"])
new_coords.get_entries()[2].set_color(Z_COLOR)
new_coords.get_entries()[7].set_color(TEAL)
new_coords.set_height(6)
new_coords.move_to(coords, aligned_edge = LEFT)
self.play(
Write(self.poly2),
Transform(coords, new_coords)
)
self.wait()
for i, mob in (2, VGroup(*self.poly2[3:5])), (7, self.poly2[0]):
self.play(
new_coords.get_entries()[i].scale, 1.3,
mob.scale, 1.3,
rate_func = there_and_back
)
self.remove(*self.get_mobjects_from_last_animation())
self.add(self.poly2)
self.wait()
self.play(*list(map(FadeOut, [self.poly2, coords, equals])))
def derivative_as_matrix(self):
matrix = Matrix([
[
str(j) if j == i+1 else "0"
for j in range(4)
] + ["\\cdots"]
for i in range(4)
] + [
["\\vdots"]*4 + ["\\ddots"]
])
matrix.shift(2*LEFT)
diag_entries = VGroup(*[
matrix.get_mob_matrix()[i, i+1]
for i in range(3)
])
##Horrible
last_col = VGroup(*matrix.get_mob_matrix()[:,-1])
last_col_top = last_col.get_top()
last_col.arrange(DOWN, buff = 0.83)
last_col.move_to(last_col_top, aligned_edge = UP+RIGHT)
##End horrible
matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR, MAROON_B)
deriv = OldTex("\\dfrac{d}{dx}")
equals = OldTex("=")
equals.next_to(matrix, LEFT)
deriv.next_to(equals, LEFT)
self.play(FadeIn(deriv), FadeIn(equals))
self.play(Write(matrix))
self.wait()
diag_entries.save_state()
diag_entries.generate_target()
diag_entries.target.scale(1.2)
diag_entries.target.set_color(YELLOW)
for anim in MoveToTarget(diag_entries), diag_entries.restore:
self.play(
anim,
lag_ratio = 0.5,
run_time = 1.5,
)
self.wait()
matrix.generate_target()
matrix.target.to_corner(DOWN+LEFT).shift(0.25*UP)
deriv.generate_target()
deriv.target.next_to(
matrix.target, UP,
buff = MED_SMALL_BUFF,
aligned_edge = LEFT
)
deriv.target.shift(0.25*RIGHT)
self.play(
FadeOut(equals),
*list(map(MoveToTarget, [matrix, deriv]))
)
poly = OldTex(
"(", "1", "x^3", "+",
"5", "x^2", "+",
"4", "x", "+",
"5", ")"
)
coefs = VGroup(*np.array(poly)[[10, 7, 4, 1]])
VGroup(*poly[1:3]).set_color(MAROON_B)
VGroup(*poly[4:6]).set_color(Z_COLOR)
VGroup(*poly[7:9]).set_color(Y_COLOR)
VGroup(*poly[10:11]).set_color(X_COLOR)
poly.next_to(deriv)
self.play(FadeIn(poly))
array = Matrix(list(coefs.copy()) + [Tex("\\vdots")])
array.next_to(matrix, RIGHT)
self.play(Write(array.get_brackets()))
to_remove = []
for coef, entry in zip(coefs, array.get_entries()):
self.play(Transform(coef.copy(), entry))
to_remove += self.get_mobjects_from_last_animation()
self.play(Write(array.get_entries()[-1]))
to_remove += self.get_mobjects_from_last_animation()
self.remove(*to_remove)
self.add(array)
eq1, eq2 = OldTex("="), OldTex("=")
eq1.next_to(poly)
eq2.next_to(array)
poly_result = OldTex(
"3", "x^2", "+",
"10", "x", "+",
"4"
)
poly_result.next_to(eq1)
brace = Brace(poly_result, buff = 0)
self.play(*list(map(Write, [eq1, eq2, brace])))
result_coefs = VGroup(*np.array(poly_result)[[6, 3, 0]])
VGroup(*poly_result[0:2]).set_color(MAROON_B)
VGroup(*poly_result[3:5]).set_color(Z_COLOR)
VGroup(*poly_result[6:]).set_color(Y_COLOR)
result_terms = [
VGroup(*poly_result[6:]),
VGroup(*poly_result[3:6]),
VGroup(*poly_result[0:3]),
]
relevant_entries = VGroup(*array.get_entries()[1:4])
dots = [Tex("\\cdot") for x in range(3)]
result_entries = []
for entry, diag_entry, dot in zip(relevant_entries, diag_entries, dots):
entry.generate_target()
diag_entry.generate_target()
group = VGroup(diag_entry.target, dot, entry.target)
group.arrange()
result_entries.append(group)
result_array = Matrix(
result_entries + [
OldTex("0"),
OldTex("\\vdots")
]
)
result_array.next_to(eq2)
rects = [
Rectangle(
color = YELLOW
).replace(
VGroup(*matrix.get_mob_matrix()[i,:]),
stretch = True
).stretch_in_place(1.1, 0).stretch_in_place(1.3, 1)
for i in range(3)
]
vert_rect = Rectangle(color = YELLOW)
vert_rect.replace(array.get_entries(), stretch = True)
vert_rect.stretch_in_place(1.1, 1)
vert_rect.stretch_in_place(1.5, 0)
tuples = list(zip(
relevant_entries,
diag_entries,
result_entries,
rects,
result_terms,
coefs[1:]
))
self.play(Write(result_array.get_brackets()))
for entry, diag_entry, result_entry, rect, result_term, coef in tuples:
self.play(FadeIn(rect), FadeIn(vert_rect))
self.wait()
self.play(
entry.scale, 1.2,
diag_entry.scale, 1.2,
)
diag_entry_target, dot, entry_target = result_entry
self.play(
Transform(entry.copy(), entry_target),
Transform(diag_entry.copy(), diag_entry_target),
entry.scale, 1/1.2,
diag_entry.scale, 1/1.2,
Write(dot)
)
self.wait()
self.play(Transform(coef.copy(), VGroup(result_term)))
self.wait()
self.play(FadeOut(rect), FadeOut(vert_rect))
self.play(*list(map(Write, result_array.get_entries()[3:])))
self.wait()
class MatrixVectorMultiplicationAndDerivative(TeacherStudentsScene):
def construct(self):
mv_mult = VGroup(
Matrix([[3, 1], [0, 2]]).set_column_colors(X_COLOR, Y_COLOR),
Matrix(["x", "y"]).set_column_colors(YELLOW)
)
mv_mult.arrange()
mv_mult.scale(0.75)
arrow = OldTex("\\Leftrightarrow")
deriv = OldTex("\\dfrac{df}{dx}")
group = VGroup(mv_mult, arrow, deriv)
group.arrange(buff = MED_SMALL_BUFF)
arrow.set_color(BLACK)
teacher = self.get_teacher()
bubble = teacher.get_bubble(SpeechBubble, height = 4)
bubble.add_content(group)
self.play(
teacher.change_mode, "speaking",
ShowCreation(bubble),
Write(group)
)
self.random_blink()
group.generate_target()
group.target.scale(0.8)
words = OldTexText("Linear transformations")
h_line = Line(ORIGIN, RIGHT).scale(words.get_width())
h_line.next_to(words, DOWN)
group.target.next_to(h_line, DOWN, buff = MED_SMALL_BUFF)
group.target[1].set_color(WHITE)
new_group = VGroup(words, h_line, group.target)
bubble.add_content(new_group)
self.play(
MoveToTarget(group),
ShowCreation(h_line),
Write(words),
self.get_teacher().change_mode, "hooray"
)
self.play_student_changes(*["pondering"]*3)
self.random_blink(3)
class CompareTermsInLinearAlgebraToFunction(Scene):
def construct(self):
l_title = OldTexText("Linear algebra \\\\ concepts")
r_title = OldTexText("Alternate names when \\\\ applied to functions")
for title, vect in (l_title, LEFT), (r_title, RIGHT):
title.to_edge(UP)
title.shift(vect*FRAME_X_RADIUS/2)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
h_line.shift(
VGroup(l_title, r_title).get_bottom()[1]*UP + SMALL_BUFF*DOWN
)
v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS)
VGroup(h_line, v_line).set_color(BLUE)
self.add(l_title, r_title)
self.play(*list(map(ShowCreation, [h_line, v_line])))
self.wait()
lin_alg_concepts = VGroup(*list(map(TexText, [
"Linear transformations",
"Dot products",
"Eigenvectors",
])))
function_concepts = VGroup(*list(map(TexText, [
"Linear operators",
"Inner products",
"Eigenfunctions",
])))
for concepts, vect in (lin_alg_concepts, LEFT), (function_concepts, RIGHT):
concepts.arrange(DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT)
concepts.next_to(h_line, DOWN, buff = LARGE_BUFF)
concepts.shift(vect*FRAME_X_RADIUS/2)
concepts.set_color_by_gradient(YELLOW_B, YELLOW_C)
for concept in concepts:
self.play(Write(concept, run_time = 1))
self.wait()
class BackToTheQuestion(TeacherStudentsScene):
def construct(self):
self.student_says(
"""
Wait...so how does
this relate to what vectors
really are?
""",
target_mode = "confused"
)
self.random_blink(2)
self.teacher_says(
"""
There are many different
vector-ish things
"""
)
self.random_blink(2)
class YouAsAMathematician(Scene):
def construct(self):
mathy = Mathematician()
mathy.to_corner(DOWN+LEFT)
words = OldTexText("You as a mathematician")
words.shift(2*UP)
arrow = Arrow(words.get_bottom(), mathy.get_corner(UP+RIGHT))
bubble = mathy.get_bubble()
equations = self.get_content()
bubble.add_content(equations)
self.add(mathy)
self.play(Write(words, run_time = 2))
self.play(
ShowCreation(arrow),
mathy.change_mode, "wave_1",
mathy.look, OUT
)
self.play(Blink(mathy))
self.wait()
self.play(
FadeOut(words),
FadeOut(arrow),
mathy.change_mode, "pondering",
ShowCreation(bubble),
)
self.play(Write(equations))
self.play(Blink(mathy))
self.wait()
bubble.write("Does this make any sense \\\\ for functions too?")
self.play(
equations.next_to, mathy.eyes, RIGHT, 2*LARGE_BUFF,
mathy.change_mode, "confused",
mathy.look, RIGHT,
Write(bubble.content)
)
self.wait()
self.play(Blink(mathy))
def get_content(self):
v_tex = "\\vec{\\textbf{v}}"
eigen_equation = OldTex("A", v_tex, "=", "\\lambda", v_tex)
v_ne_zero = OldTex(v_tex, "\\ne \\vec{\\textbf{0}}")
det_equation = OldTex("\\det(A-", "\\lambda", "I)=0")
arrow = OldTex("\\Rightarrow")
for tex in eigen_equation, v_ne_zero, det_equation:
tex.set_color_by_tex(v_tex, YELLOW)
tex.set_color_by_tex("\\lambda", MAROON_B)
lhs = VGroup(eigen_equation, v_ne_zero)
lhs.arrange(DOWN)
group = VGroup(lhs, arrow, det_equation)
group.arrange(buff = MED_SMALL_BUFF)
return group
class ShowVectorSpaces(Scene):
def construct(self):
title = OldTexText("Vector spaces")
title.to_edge(UP)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
h_line.next_to(title, DOWN)
v_lines = [
Line(
h_line.get_center(), FRAME_Y_RADIUS*DOWN
).shift(vect*FRAME_X_RADIUS/3.)
for vect in (LEFT, RIGHT)
]
vectors = self.get_vectors()
vectors.shift(LEFT*FRAME_X_RADIUS*(2./3))
arrays = self.get_arrays()
functions = self.get_functions()
functions.shift(RIGHT*FRAME_X_RADIUS*(2./3))
self.add(h_line, *v_lines)
self.play(ShowCreation(
vectors,
run_time = 3
))
self.play(Write(arrays))
self.play(Write(functions))
self.wait()
self.play(Write(title))
def get_vectors(self, n_vectors = 10):
vectors = VGroup(*[
Vector(RIGHT).scale(scalar).rotate(angle)
for scalar, angle in zip(
2*np.random.random(n_vectors)+0.5,
np.linspace(0, 6, n_vectors)
)
])
vectors.set_color_by_gradient(YELLOW, MAROON_B)
return vectors
def get_arrays(self):
arrays = VGroup(*[
VGroup(*[
Matrix(np.random.randint(-9, 9, 2))
for x in range(4)
])
for x in range(3)
])
for subgroup in arrays:
subgroup.arrange(DOWN, buff = MED_SMALL_BUFF)
arrays.arrange(RIGHT)
arrays.scale(0.7)
arrays.set_color_by_gradient(YELLOW, MAROON_B)
return arrays
def get_functions(self):
axes = Axes()
axes.scale(0.3)
functions = VGroup(*[
FunctionGraph(func, x_min = -4, x_max = 4)
for func in [
lambda x : x**3 - 9*x,
lambda x : x**3 - 4*x,
lambda x : x**2 - 1,
]
])
functions.stretch_to_fit_width(FRAME_X_RADIUS/2.)
functions.stretch_to_fit_height(6)
functions.set_color_by_gradient(YELLOW, MAROON_B)
functions.center()
return VGroup(axes, functions)
class ToolsOfLinearAlgebra(Scene):
def construct(self):
words = VGroup(*list(map(TexText, [
"Linear transformations",
"Null space",
"Eigenvectors",
"Dot products",
"$\\vdots$"
])))
words.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF)
words[-1].next_to(words[-2], DOWN)
self.play(FadeIn(
words,
lag_ratio = 0.5,
run_time = 3
))
self.wait()
class MathematicianSpeakingToAll(Scene):
def construct(self):
mathy = Mathematician().to_corner(DOWN+LEFT)
others = VGroup(*[
Randolph().flip().set_color(color)
for color in (BLUE_D, GREEN_E, GOLD_E, BLUE_C)
])
others.arrange()
others.scale(0.8)
others.to_corner(DOWN+RIGHT)
bubble = mathy.get_bubble(SpeechBubble)
bubble.write("""
I don't want to think
about all y'all's crazy
vector spaces
""")
self.add(mathy, others)
self.play(
ShowCreation(bubble),
Write(bubble.content),
mathy.change_mode, "sassy",
mathy.look_at, others
)
self.play(Blink(others[3]))
self.wait()
thought_bubble = mathy.get_bubble(ThoughtBubble)
self.play(
FadeOut(bubble.content),
Transform(bubble, thought_bubble),
mathy.change_mode, "speaking",
mathy.look_at, bubble,
*[ApplyMethod(pi.look_at, bubble) for pi in others]
)
vect = -bubble.get_bubble_center()
def func(point):
centered = point+vect
return 10*centered/get_norm(centered)
self.play(*[
ApplyPointwiseFunction(func, mob)
for mob in self.get_mobjects()
])
class ListAxioms(Scene):
def construct(self):
title = OldTexText("Rules for vectors addition and scaling")
title.to_edge(UP)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
h_line.next_to(title, DOWN)
self.add(title, h_line)
u_tex, v_tex, w_tex = ["\\vec{\\textbf{%s}}"%s for s in "uvw"]
axioms = VGroup(*it.starmap(Tex, [
(
"1. \\,",
u_tex, "+", "(", v_tex, "+", w_tex, ")=(",
u_tex, "+", v_tex, ")+", w_tex
),
( "2. \\,",
v_tex, "+", w_tex, "=", w_tex, "+", v_tex
),
(
"3. \\,",
"\\text{There is a vector }", "\\textbf{0}",
"\\text{ such that }", "\\textbf{0}+", v_tex,
"=", v_tex, "\\text{ for all }", v_tex
),
(
"4. \\,",
"\\text{For every vector }", v_tex,
"\\text{ there is a vector }", "-", v_tex,
"\\text{ so that }", v_tex, "+", "(-", v_tex, ")=\\textbf{0}"
),
( "5. \\,",
"a", "(", "b", v_tex, ")=(", "a", "b", ")", v_tex
),
(
"6. \\,",
"1", v_tex, "=", v_tex
),
(
"7. \\,",
"a", "(", v_tex, "+", w_tex, ")", "=",
"a", v_tex, "+", "a", w_tex
),
(
"8. \\,",
"(", "a", "+", "b", ")", v_tex, "=",
"a", v_tex, "+", "b", v_tex
),
]))
tex_color_pairs = [
(v_tex, YELLOW),
(w_tex, MAROON_B),
(u_tex, PINK),
("a", BLUE),
("b", GREEN)
]
for axiom in axioms:
for tex, color in tex_color_pairs:
axiom.set_color_by_tex(tex, color)
axioms.arrange(
DOWN, buff = MED_LARGE_BUFF,
aligned_edge = LEFT
)
axioms.set_width(FRAME_WIDTH-1)
axioms.next_to(h_line, DOWN, buff = MED_SMALL_BUFF)
self.play(FadeIn(
axioms,
lag_ratio = 0.5,
run_time = 5
))
self.wait()
axioms_word = OldTexText("``Axioms''")
axioms_word.set_color(YELLOW)
axioms_word.scale(2)
axioms_word.shift(FRAME_X_RADIUS*RIGHT/2, FRAME_Y_RADIUS*DOWN/2)
self.play(Write(axioms_word, run_time = 3))
self.wait()
class AxiomsAreInterface(Scene):
def construct(self):
mathy = Mathematician().to_edge(LEFT)
mathy.change_mode("pondering")
others = [
Randolph().flip().set_color(color)
for color in (BLUE_D, GREEN_E, GOLD_E, BLUE_C)
]
others = VGroup(
VGroup(*others[:2]),
VGroup(*others[2:]),
)
for group in others:
group.arrange(RIGHT)
others.arrange(DOWN)
others.scale(0.8)
others.to_edge(RIGHT)
VGroup(mathy, others).to_edge(DOWN)
double_arrow = DoubleArrow(mathy, others)
axioms, are, rules_of_nature = words = OldTexText(
"Axioms", "are", "rules of nature"
)
words.to_edge(UP)
axioms.set_color(YELLOW)
an_interface = OldTexText("an interface")
an_interface.next_to(rules_of_nature, DOWN)
red_line = Line(
rules_of_nature.get_left(),
rules_of_nature.get_right(),
color = RED
)
self.play(Write(words))
self.wait()
self.play(ShowCreation(red_line))
self.play(Transform(
rules_of_nature.copy(),
an_interface
))
self.wait()
self.play(FadeIn(mathy))
self.play(
ShowCreation(double_arrow),
FadeIn(others, lag_ratio = 0.5, run_time = 2)
)
self.play(axioms.copy().next_to, double_arrow, UP)
self.play(Blink(mathy))
self.wait()
class VectorSpaceOfPiCreatures(Scene):
def construct(self):
creatures = self.add_creatures()
self.show_sum(creatures)
def add_creatures(self):
creatures = VGroup(*[
VGroup(*[
PiCreature()
for x in range(4)
]).arrange(RIGHT, buff = 1.5)
for y in range(4)
]).arrange(DOWN, buff = 1.5)
creatures = VGroup(*it.chain(*creatures))
creatures.set_height(FRAME_HEIGHT-1)
for pi in creatures:
pi.change_mode(random.choice([
"pondering", "pondering",
"happy", "happy", "happy",
"confused",
"angry", "erm", "sassy", "hooray",
"speaking", "tired",
"plain", "plain"
]))
if random.random() < 0.5:
pi.flip()
pi.shift(0.5*(random.random()-0.5)*RIGHT)
pi.shift(0.5*(random.random()-0.5)*UP)
pi.set_color(random.choice([
BLUE_B, BLUE_C, BLUE_D, BLUE_E,
MAROON_B, MAROON_C, MAROON_D, MAROON_E,
GREY_BROWN, GREY_BROWN, GREY,
YELLOW_C, YELLOW_D, YELLOW_E
]))
pi.scale(random.random()+0.5)
self.play(FadeIn(
creatures,
lag_ratio = 0.5,
run_time = 3
))
self.wait()
return creatures
def show_sum(self, creatures):
def is_valid(pi1, pi2, pi3):
if len(set([pi.get_color() for pi in (pi1, pi2, pi3)])) < 3:
return False
if pi1.is_flipped()^pi2.is_flipped():
return False
return True
pi1, pi2, pi3 = pis = [random.choice(creatures) for x in range(3)]
while not is_valid(pi1, pi2, pi3):
pi1, pi2, pi3 = pis = [random.choice(creatures) for x in range(3)]
creatures.remove(*pis)
transform = Transform(pi1.copy(), pi2.copy())
transform.update(0.5)
sum_pi = transform.mobject
sum_pi.set_height(pi1.get_height()+pi2.get_height())
for pi in pis:
pi.generate_target()
plus, equals = OldTex("+=")
sum_equation = VGroup(
pi1.target, plus, pi2.target,
equals, sum_pi
)
sum_equation.arrange().center()
scaled_pi3 = pi3.copy().scale(2)
equals2 = OldTex("=")
two = OldTex("2 \\cdot")
scale_equation = VGroup(
two, pi3.target, equals2, scaled_pi3
)
scale_equation.arrange()
VGroup(sum_equation, scale_equation).arrange(
DOWN, buff = MED_SMALL_BUFF
)
self.play(FadeOut(creatures))
self.play(*it.chain(
list(map(MoveToTarget, [pi1, pi2, pi3])),
list(map(Write, [plus, equals, two, equals2])),
))
self.play(
Transform(pi1.copy(), sum_pi),
Transform(pi2.copy(), sum_pi),
Transform(pi3.copy(), scaled_pi3)
)
self.remove(*self.get_mobjects_from_last_animation())
self.add(sum_pi, scaled_pi3)
for pi in pi1, sum_pi, scaled_pi3, pi3:
self.play(Blink(pi))
class MathematicianDoesntHaveToThinkAboutThat(Scene):
def construct(self):
mathy = Mathematician().to_corner(DOWN+LEFT)
bubble = mathy.get_bubble(ThoughtBubble, height = 4)
words = OldTexText("I don't have to worry", "\\\\ about that madness!")
bubble.add_content(words)
new_words = OldTexText("So long as I", "\\\\ work abstractly")
bubble.add_content(new_words)
self.play(
mathy.change_mode, "hooray",
ShowCreation(bubble),
Write(words)
)
self.play(Blink(mathy))
self.wait()
self.play(
mathy.change_mode, "pondering",
Transform(words, new_words)
)
self.play(Blink(mathy))
self.wait()
class TextbooksAreAbstract(TeacherStudentsScene):
def construct(self):
self.student_says(
"""
All the textbooks I found
are pretty abstract.
""",
target_mode = "pleading"
)
self.random_blink(3)
self.teacher_says(
"""
For each new concept,
contemplate it for 2d space
with grid lines...
"""
)
self.play_student_changes("pondering")
self.random_blink(2)
self.teacher_says(
"...then in some different\\\\",
"context, like a function space"
)
self.play_student_changes(*["pondering"]*2)
self.random_blink()
self.teacher_says(
"Only then should you\\\\",
"think from the axioms",
target_mode = "surprised"
)
self.play_student_changes(*["pondering"]*3)
self.random_blink()
class LastAskWhatAreVectors(TeacherStudentsScene):
def construct(self):
self.student_says(
"So...what are vectors?",
target_mode = "erm"
)
self.random_blink()
self.teacher_says(
"""
The form they take
doesn't really matter
"""
)
self.random_blink()
class WhatIsThree(Scene):
def construct(self):
what_is, three, q_mark = words = OldTexText(
"What is ", "3", "?",
arg_separator = ""
)
words.scale(1.5)
self.play(Write(words))
self.wait()
self.play(
FadeOut(what_is),
FadeOut(q_mark),
three.center
)
triplets = [
VGroup(*[
PiCreature(color = color).scale(0.4)
for color in (BLUE_E, BLUE_C, BLUE_D)
]),
VGroup(*[HyperCube().scale(0.3) for x in range(3)]),
VGroup(*[Vector(RIGHT) for x in range(3)]),
OldTex("""
\\Big\\{
\\emptyset,
\\{\\emptyset\\},
\\{\\{\\emptyset\\}, \\emptyset\\}
\\Big\\}
""")
]
directions = [UP+LEFT, UP+RIGHT, DOWN+LEFT, DOWN+RIGHT]
for group, vect in zip(triplets, directions):
if isinstance(group, Tex):
pass
elif isinstance(group[0], Vector):
group.arrange(RIGHT)
group.set_color_by_gradient(YELLOW, MAROON_B)
else:
m1, m2, m3 = group
m2.next_to(m1, buff = MED_SMALL_BUFF)
m3.next_to(VGroup(m1, m2), DOWN, buff = MED_SMALL_BUFF)
group.next_to(three, vect, buff = LARGE_BUFF)
self.play(FadeIn(group))
self.wait()
self.play(*[
Transform(
trip, three,
lag_ratio = 0.5,
run_time = 2
)
for trip in triplets
])
class IStillRecommendConcrete(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
I still recommend
thinking concretely
""")
self.random_blink(2)
self.student_thinks("")
self.zoom_in_on_thought_bubble()
class AbstractionIsThePrice(Scene):
def construct(self):
words = OldTexText(
"Abstractness", "is the price\\\\"
"of", "generality"
)
words.set_color_by_tex("Abstractness", YELLOW)
words.set_color_by_tex("generality", BLUE)
self.play(Write(words))
self.wait()
class ThatsAWrap(TeacherStudentsScene):
def construct(self):
self.teacher_says("That's all for now!")
self.random_blink(2)
class GoodLuck(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"Good luck with \\\\ your future learning!",
target_mode = "hooray"
)
self.play_student_changes(*["happy"]*3)
self.random_blink(3)
|
|
from manim_imports_ext import *
from _2016.eola.chapter3 import MatrixVectorMultiplicationAbstract
class OpeningQuote(Scene):
def construct(self):
words = OldTexText([
"It is my experience that proofs involving",
"matrices",
"can be shortened by 50\\% if one",
"throws the matrices out."
])
words.set_width(FRAME_WIDTH - 2)
words.to_edge(UP)
words.split()[1].set_color(GREEN)
words.split()[3].set_color(BLUE)
author = OldTexText("-Emil Artin")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = 0.5)
self.play(FadeIn(words))
self.wait(2)
self.play(Write(author, run_time = 3))
self.wait()
class MatrixToBlank(Scene):
def construct(self):
matrix = Matrix([[3, 1], [0, 2]])
arrow = Arrow(LEFT, RIGHT)
matrix.to_edge(LEFT)
arrow.next_to(matrix, RIGHT)
matrix.add(arrow)
self.play(Write(matrix))
self.wait()
class ExampleTransformation(LinearTransformationScene):
def construct(self):
self.setup()
self.apply_transposed_matrix([[3, 0], [1, 2]])
self.wait(2)
class RecapTime(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("Quick recap time!")
self.random_blink()
self.wait()
student = self.get_students()[0]
everyone = self.get_mobjects()
everyone.remove(student)
everyone = VMobject(*everyone)
self.play(
ApplyMethod(everyone.fade, 0.7),
ApplyMethod(student.change_mode, "confused")
)
self.play(Blink(student))
self.wait()
self.play(ApplyFunction(
lambda m : m.change_mode("pondering").look(LEFT),
student
))
self.play(Blink(student))
self.wait()
class DeterminedByTwoBasisVectors(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False
}
def construct(self):
self.setup()
i_hat = self.add_vector([1, 0], color = X_COLOR)
self.add_transformable_label(
i_hat, "\\hat{\\imath}", "\\hat{\\imath}",
color = X_COLOR
)
j_hat = self.add_vector([0, 1], color = Y_COLOR)
self.add_transformable_label(
j_hat, "\\hat{\\jmath}", "\\hat{\\jmath}",
color = Y_COLOR
)
t_matrix = np.array([[2, 2], [-2, 1]])
matrix = t_matrix.transpose()
matrix1 = np.array(matrix)
matrix1[:,1] = [0, 1]
matrix2 = np.dot(matrix, np.linalg.inv(matrix1))
self.wait()
self.apply_transposed_matrix(matrix1.transpose())
self.apply_transposed_matrix(matrix2.transpose())
self.wait()
class FollowLinearCombination(LinearTransformationScene):
def construct(self):
vect_coords = [-1, 2]
t_matrix = np.array([[2, 2], [-2, 1]])
#Draw vectors
self.setup()
i_label = self.add_transformable_label(
self.i_hat, "\\hat{\\imath}", animate = False,
direction = "right", color = X_COLOR
)
j_label = self.add_transformable_label(
self.j_hat, "\\hat{\\jmath}", animate = False,
direction = "right", color = Y_COLOR
)
vect = self.add_vector(vect_coords)
vect_array = Matrix(["x", "y"], add_background_rectangles_to_entries = True)
v_equals = OldTex(["\\vec{\\textbf{v}}", "="])
v_equals.split()[0].set_color(YELLOW)
v_equals.next_to(vect_array, LEFT)
vect_array.add(v_equals)
vect_array.to_edge(UP, buff = 0.2)
background_rect = BackgroundRectangle(vect_array)
vect_array.get_entries().set_color(YELLOW)
self.play(ShowCreation(background_rect), Write(vect_array))
self.add_foreground_mobject(background_rect, vect_array)
#Show scaled vectors
x, y = vect_array.get_entries().split()
scaled_i_label = VMobject(x.copy(), i_label)
scaled_j_label = VMobject(y.copy(), j_label)
scaled_i = self.i_hat.copy().scale(vect_coords[0])
scaled_j = self.j_hat.copy().scale(vect_coords[1])
for mob in scaled_i, scaled_j:
mob.fade(0.3)
scaled_i_label_target = scaled_i_label.copy()
scaled_i_label_target.arrange(buff = 0.1)
scaled_i_label_target.next_to(scaled_i, DOWN)
scaled_j_label_target = scaled_j_label.copy()
scaled_j_label_target.arrange(buff = 0.1)
scaled_j_label_target.next_to(scaled_j, LEFT)
self.show_scaled_vectors(vect_array, vect_coords, i_label, j_label)
self.apply_transposed_matrix(t_matrix)
self.show_scaled_vectors(vect_array, vect_coords, i_label, j_label)
self.record_basis_coordinates(vect_array, vect)
def show_scaled_vectors(self, vect_array, vect_coords, i_label, j_label):
x, y = vect_array.get_entries().split()
scaled_i_label = VMobject(x.copy(), i_label.copy())
scaled_j_label = VMobject(y.copy(), j_label.copy())
scaled_i = self.i_hat.copy().scale(vect_coords[0])
scaled_j = self.j_hat.copy().scale(vect_coords[1])
for mob in scaled_i, scaled_j:
mob.fade(0.3)
scaled_i_label_target = scaled_i_label.copy()
scaled_i_label_target.arrange(buff = 0.1)
scaled_i_label_target.next_to(scaled_i.get_center(), DOWN)
scaled_j_label_target = scaled_j_label.copy()
scaled_j_label_target.arrange(buff = 0.1)
scaled_j_label_target.next_to(scaled_j.get_center(), LEFT)
self.play(
Transform(self.i_hat.copy(), scaled_i),
Transform(scaled_i_label, scaled_i_label_target)
)
scaled_i = self.get_mobjects_from_last_animation()[0]
self.play(
Transform(self.j_hat.copy(), scaled_j),
Transform(scaled_j_label, scaled_j_label_target)
)
scaled_j = self.get_mobjects_from_last_animation()[0]
self.play(*[
ApplyMethod(mob.shift, scaled_i.get_end())
for mob in (scaled_j, scaled_j_label)
])
self.wait()
self.play(*list(map(FadeOut, [
scaled_i, scaled_j, scaled_i_label, scaled_j_label,
])))
def record_basis_coordinates(self, vect_array, vect):
i_label = vector_coordinate_label(self.i_hat)
i_label.set_color(X_COLOR)
j_label = vector_coordinate_label(self.j_hat)
j_label.set_color(Y_COLOR)
for mob in i_label, j_label:
mob.scale(0.8)
background = BackgroundRectangle(mob)
self.play(ShowCreation(background), Write(mob))
self.wait()
x, y = vect_array.get_entries().split()
pre_formula = VMobject(
x, i_label, OldTex("+"),
y, j_label
)
post_formula = pre_formula.copy()
pre_formula.split()[2].fade(1)
post_formula.arrange(buff = 0.1)
post_formula.next_to(vect, DOWN)
background = BackgroundRectangle(post_formula)
everything = self.get_mobjects()
everything.remove(vect)
self.play(*[
ApplyMethod(m.fade) for m in everything
] + [
ShowCreation(background, run_time = 2, rate_func = squish_rate_func(smooth, 0.5, 1)),
Transform(pre_formula.copy(), post_formula, run_time = 2),
ApplyMethod(vect.set_stroke, width = 7)
])
self.wait()
class MatrixVectorMultiplicationCopy(MatrixVectorMultiplicationAbstract):
pass ## Here just for stage_animations.py purposes
class RecapOver(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("Recap over!")
class TwoSuccessiveTransformations(LinearTransformationScene):
CONFIG = {
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 0
},
}
def construct(self):
self.setup()
self.apply_transposed_matrix([[2, 1],[1, 2]])
self.apply_transposed_matrix([[-1, -0.5],[0, -0.5]])
self.wait()
class RotationThenShear(LinearTransformationScene):
CONFIG = {
"foreground_plane_kwargs" : {
"x_radius" : FRAME_X_RADIUS,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 0
},
}
def construct(self):
self.setup()
rot_words = OldTexText("$90^\\circ$ rotation counterclockwise")
shear_words = OldTexText("followed by a shear")
rot_words.set_color(YELLOW)
shear_words.set_color(PINK)
VMobject(rot_words, shear_words).arrange(DOWN).to_edge(UP)
for words in rot_words, shear_words:
words.add_background_rectangle()
self.play(Write(rot_words, run_time = 1))
self.add_foreground_mobject(rot_words)
self.apply_transposed_matrix([[0, 1], [-1, 0]])
self.play(Write(shear_words, run_time = 1))
self.add_foreground_mobject(shear_words)
self.apply_transposed_matrix([[1, 0], [1, 1]])
self.wait()
class IntroduceIdeaOfComposition(RotationThenShear):
def construct(self):
self.setup()
self.show_composition()
matrix = self.track_basis_vectors()
self.show_overall_effect(matrix)
def show_composition(self):
words = OldTexText([
"``Composition''",
"of a",
"rotation",
"and a",
"shear"
])
words.split()[0].set_submobject_colors_by_gradient(YELLOW, PINK, use_color_range_to = False)
words.split()[2].set_color(YELLOW)
words.split()[4].set_color(PINK)
words.add_background_rectangle()
words.to_edge(UP)
self.apply_transposed_matrix([[0, 1], [-1, 0]], run_time = 2)
self.apply_transposed_matrix([[1, 0], [1, 1]], run_time = 2)
self.play(
ApplyMethod(self.plane.fade),
Write(words),
Animation(self.i_hat),
Animation(self.j_hat),
)
self.wait()
def track_basis_vectors(self):
last_words = self.get_mobjects_from_last_animation()[1]
words = OldTexText([
"Record where",
"$\\hat{\\imath}$",
"and",
"$\\hat{\\jmath}$",
"land:"
])
rw, i_hat, a, j_hat, l = words.split()
i_hat.set_color(X_COLOR)
j_hat.set_color(Y_COLOR)
words.add_background_rectangle()
words.next_to(last_words, DOWN)
i_coords = vector_coordinate_label(self.i_hat)
j_coords = vector_coordinate_label(self.j_hat)
i_coords.set_color(X_COLOR)
j_coords.set_color(Y_COLOR)
i_background = BackgroundRectangle(i_coords)
j_background = BackgroundRectangle(j_coords)
matrix = Matrix(np.append(
i_coords.copy().get_mob_matrix(),
j_coords.copy().get_mob_matrix(),
axis = 1
))
matrix.next_to(words, RIGHT, aligned_edge = UP)
col1, col2 = [
VMobject(*matrix.get_mob_matrix()[:,i])
for i in (0, 1)
]
matrix_background = BackgroundRectangle(matrix)
self.play(Write(words))
self.wait()
self.play(ShowCreation(i_background), Write(i_coords), run_time = 2)
self.wait()
self.play(
Transform(i_background.copy(), matrix_background),
Transform(i_coords.copy().get_brackets(), matrix.get_brackets()),
ApplyMethod(i_coords.copy().get_entries().move_to, col1)
)
self.wait()
self.play(ShowCreation(j_background), Write(j_coords), run_time = 2)
self.wait()
self.play(
ApplyMethod(j_coords.copy().get_entries().move_to, col2)
)
self.wait()
matrix = VMobject(matrix_background, matrix)
return matrix
def show_overall_effect(self, matrix):
everything = self.get_mobjects()
everything = list_difference_update(
everything, matrix.get_family()
)
self.play(*list(map(FadeOut, everything)) + [Animation(matrix)])
new_matrix = matrix.copy()
new_matrix.center().to_edge(UP)
self.play(Transform(matrix, new_matrix))
self.wait()
self.remove(matrix)
self.setup()
everything = self.get_mobjects()
self.play(*list(map(FadeIn, everything)) + [Animation(matrix)])
func = self.get_matrix_transformation([[1, 1], [-1, 0]])
bases = VMobject(self.i_hat, self.j_hat)
new_bases = VMobject(*[
Vector(func(v.get_end()), color = v.get_color())
for v in bases.split()
])
self.play(
ApplyPointwiseFunction(func, self.plane),
Transform(bases, new_bases),
Animation(matrix),
run_time = 3
)
self.wait()
class PumpVectorThroughRotationThenShear(RotationThenShear):
def construct(self):
self.setup()
self.add_vector([2, 3])
self.apply_transposed_matrix([[0, 1], [-1, 0]], run_time = 2)
self.apply_transposed_matrix([[1, 0], [1, 1]], run_time = 2)
self.wait()
class ExplainWhyItsMatrixMultiplication(Scene):
def construct(self):
vect = Matrix(["x", "y"])
vect.get_entries().set_color(YELLOW)
rot_matrix = Matrix([[0, -1], [1, 0]])
rot_matrix.set_color(TEAL)
shear_matrix = Matrix([[1, 1], [0, 1]])
shear_matrix.set_color(PINK)
l_paren, r_paren = list(map(Tex, ["\\Big(", "\\Big)"]))
for p in l_paren, r_paren:
p.set_height(1.4*vect.get_height())
long_way = VMobject(
shear_matrix, l_paren, rot_matrix, vect, r_paren
)
long_way.arrange(buff = 0.1)
long_way.to_edge(LEFT).shift(UP)
equals = OldTex("=").next_to(long_way, RIGHT)
comp_matrix = Matrix([[1, -1], [1, 0]])
comp_matrix.set_column_colors(X_COLOR, Y_COLOR)
vect_copy = vect.copy()
short_way = VMobject(comp_matrix, vect_copy)
short_way.arrange(buff = 0.1)
short_way.next_to(equals, RIGHT)
pairs = [
(rot_matrix, "Rotation"),
(shear_matrix, "Shear"),
(comp_matrix, "Composition"),
]
for matrix, word in pairs:
brace = Brace(matrix)
text = OldTexText(word).next_to(brace, DOWN)
brace.set_color(matrix.get_color())
text.set_color(matrix.get_color())
matrix.add(brace, text)
comp_matrix.split()[-1].set_submobject_colors_by_gradient(TEAL, PINK)
self.add(vect)
groups = [
[rot_matrix],
[l_paren, r_paren, shear_matrix],
[equals, comp_matrix, vect_copy],
]
for group in groups:
self.play(*list(map(Write, group)))
self.wait()
self.play(*list(map(FadeOut, [l_paren, r_paren, vect, vect_copy])))
comp_matrix.add(equals)
matrices = VMobject(shear_matrix, rot_matrix, comp_matrix)
self.play(ApplyMethod(
matrices.arrange, buff = 0.1,
aligned_edge = UP
))
self.wait()
arrow = Arrow(rot_matrix.get_right(), shear_matrix.get_left())
arrow.shift((rot_matrix.get_top()[1]+0.2)*UP)
words = OldTexText("Read right to left")
words.submobjects.reverse()
words.next_to(arrow, UP)
functions = OldTex("f(g(x))")
functions.next_to(words, UP)
self.play(ShowCreation(arrow))
self.play(Write(words))
self.wait()
self.play(Write(functions))
self.wait()
class MoreComplicatedExampleVisually(LinearTransformationScene):
CONFIG = {
"t_matrix1" : [[1, 1], [-2, 0]],
"t_matrix2" : [[0, 1], [2, 0]],
}
def construct(self):
self.setup()
t_matrix1 = np.array(self.t_matrix1)
t_matrix2 = np.array(self.t_matrix2)
t_m1_inv = np.linalg.inv(t_matrix1.transpose()).transpose()
t_m2_inv = np.linalg.inv(t_matrix2.transpose()).transpose()
m1_mob, m2_mob, comp_matrix = self.get_matrices()
self.play(Write(m1_mob))
self.add_foreground_mobject(m1_mob)
self.wait()
self.apply_transposed_matrix(t_matrix1)
self.wait()
self.play(Write(m1_mob.label))
self.add_foreground_mobject(m1_mob.label)
self.wait()
self.apply_transposed_matrix(t_m1_inv, run_time = 0)
self.wait()
self.play(Write(m2_mob))
self.add_foreground_mobject(m2_mob)
self.wait()
self.apply_transposed_matrix(t_matrix2)
self.wait()
self.play(Write(m2_mob.label))
self.add_foreground_mobject(m2_mob.label)
self.wait()
self.apply_transposed_matrix(t_m2_inv, run_time = 0)
self.wait()
for matrix in t_matrix1, t_matrix2:
self.apply_transposed_matrix(matrix, run_time = 1)
self.play(Write(comp_matrix))
self.add_foreground_mobject(comp_matrix)
self.wait()
self.play(*list(map(FadeOut, [
self.background_plane,
self.plane,
self.i_hat,
self.j_hat,
])) + [
Animation(m) for m in self.foreground_mobjects
])
self.remove(self.i_hat, self.j_hat)
self.wait()
def get_matrices(self):
m1_mob = Matrix(np.array(self.t_matrix1).transpose())
m2_mob = Matrix(np.array(self.t_matrix2).transpose())
comp_matrix = Matrix([["?", "?"], ["?", "?"]])
m1_mob.set_color(YELLOW)
m2_mob.set_color(PINK)
comp_matrix.get_entries().set_submobject_colors_by_gradient(YELLOW, PINK)
equals = OldTex("=")
equals.next_to(comp_matrix, LEFT)
comp_matrix.add(equals)
m1_mob = VMobject(BackgroundRectangle(m1_mob), m1_mob)
m2_mob = VMobject(BackgroundRectangle(m2_mob), m2_mob)
comp_matrix = VMobject(BackgroundRectangle(comp_matrix), comp_matrix)
VMobject(
m2_mob, m1_mob, comp_matrix
).arrange(buff = 0.1).to_corner(UP+LEFT).shift(DOWN)
for i, mob in enumerate([m1_mob, m2_mob]):
brace = Brace(mob, UP)
text = OldTex("M_%d"%(i+1))
text.next_to(brace, UP)
brace.add_background_rectangle()
text.add_background_rectangle()
brace.add(text)
mob.label = brace
return m1_mob, m2_mob, comp_matrix
class MoreComplicatedExampleNumerically(MoreComplicatedExampleVisually):
def get_result(self):
return np.dot(self.t_matrix1, self.t_matrix2).transpose()
def construct(self):
m1_mob, m2_mob, comp_matrix = self.get_matrices()
self.add(m1_mob, m2_mob, m1_mob.label, m2_mob.label, comp_matrix)
result = self.get_result()
col1, col2 = [
VMobject(*m1_mob.split()[1].get_mob_matrix()[:,i])
for i in (0, 1)
]
col1.target_color = X_COLOR
col2.target_color = Y_COLOR
for col in col1, col2:
circle = Circle()
circle.stretch_to_fit_height(m1_mob.get_height())
circle.stretch_to_fit_width(m1_mob.get_width()/2.5)
circle.set_color(col.target_color)
circle.move_to(col)
col.circle = circle
triplets = [
(col1, "i", X_COLOR),
(col2, "j", Y_COLOR),
]
for i, (col, char, color) in enumerate(triplets):
self.add(col)
start_state = self.get_mobjects()
question = OldTexText(
"Where does $\\hat{\\%smath}$ go?"%char
)
question.split()[-4].set_color(color)
question.split()[-5].set_color(color)
question.scale(1.2)
question.shift(DOWN)
first = OldTexText("First here")
first.set_color(color)
first.shift(DOWN+LEFT)
first_arrow = Arrow(
first, col.circle.get_bottom(), color = color
)
second = OldTexText("Then to whatever this is")
second.set_color(color)
second.to_edge(RIGHT).shift(DOWN)
m2_copy = m2_mob.copy()
m2_target = m2_mob.copy()
m2_target.next_to(m2_mob, DOWN, buff = 1)
col_vect = Matrix(col.copy().split())
col_vect.set_color(color)
col_vect.next_to(m2_target, RIGHT, buff = 0.1)
second_arrow = Arrow(second, col_vect, color = color)
new_m2_copy = m2_mob.copy().split()[1]
intermediate = VMobject(
OldTex("="),
col_vect.copy().get_entries().split()[0],
Matrix(new_m2_copy.get_mob_matrix()[:,0]),
OldTex("+"),
col_vect.copy().get_entries().split()[1],
Matrix(new_m2_copy.get_mob_matrix()[:,1]),
OldTex("=")
)
intermediate.arrange(buff = 0.1)
intermediate.next_to(col_vect, RIGHT)
product = Matrix(result[:,i])
product.next_to(intermediate, RIGHT)
comp_col = VMobject(*comp_matrix.split()[1].get_mob_matrix()[:,i])
self.play(Write(question, run_time = 1 ))
self.wait()
self.play(
Transform(question, first),
ShowCreation(first_arrow),
ShowCreation(col.circle),
ApplyMethod(col.set_color, col.target_color)
)
self.wait()
self.play(
Transform(m2_copy, m2_target, run_time = 2),
ApplyMethod(col.copy().move_to, col_vect, run_time = 2),
Write(col_vect.get_brackets()),
Transform(first_arrow, second_arrow),
Transform(question, second),
)
self.wait()
self.play(*list(map(FadeOut, [question, first_arrow])))
self.play(Write(intermediate))
self.wait()
self.play(Write(product))
self.wait()
product_entries = product.get_entries()
self.play(
ApplyMethod(comp_col.set_color, BLACK),
ApplyMethod(product_entries.move_to, comp_col)
)
self.wait()
start_state.append(product_entries)
self.play(*[
FadeOut(mob)
for mob in self.get_mobjects()
if mob not in start_state
] + [
Animation(product_entries)
])
self.wait()
class GeneralMultiplication(MoreComplicatedExampleNumerically):
def get_result(self):
entries = list(map(Tex, [
"ae+bg", "af+bh", "ce+dg", "cf+dh"
]))
for mob in entries:
mob.split()[0].set_color(PINK)
mob.split()[3].set_color(PINK)
for mob in entries[0], entries[2]:
mob.split()[1].set_color(X_COLOR)
mob.split()[4].set_color(X_COLOR)
for mob in entries[1], entries[3]:
mob.split()[1].set_color(Y_COLOR)
mob.split()[4].set_color(Y_COLOR)
return np.array(entries).reshape((2, 2))
def get_matrices(self):
m1, m2, comp = MoreComplicatedExampleNumerically.get_matrices(self)
self.add(m1, m2, m1.label, m2.label, comp)
m1_entries = m1.split()[1].get_entries()
m2_entries = m2.split()[1].get_entries()
m2_entries_target = VMobject(*[
OldTex(char).move_to(entry).set_color(entry.get_color())
for entry, char in zip(m2_entries.split(), "abcd")
])
m1_entries_target = VMobject(*[
OldTex(char).move_to(entry).set_color(entry.get_color())
for entry, char in zip(m1_entries.split(), "efgh")
])
words = OldTexText("This method works generally")
self.play(Write(words, run_time = 2))
self.play(Transform(
m1_entries, m1_entries_target,
lag_ratio = 0.5
))
self.play(Transform(
m2_entries, m2_entries_target,
lag_ratio = 0.5
))
self.wait()
new_comp = Matrix(self.get_result())
new_comp.next_to(comp.split()[1].submobjects[-1], RIGHT)
new_comp.get_entries().set_color(BLACK)
self.play(
Transform(comp.split()[1].get_brackets(), new_comp.get_brackets()),
*[
ApplyMethod(q_mark.move_to, entry)
for q_mark, entry in zip(
comp.split()[1].get_entries().split(),
new_comp.get_entries().split()
)
]
)
self.wait()
self.play(FadeOut(words))
return m1, m2, comp
class MoreComplicatedExampleWithJustIHat(MoreComplicatedExampleVisually):
CONFIG = {
"show_basis_vectors" : False,
"v_coords" : [1, 0],
"v_color" : X_COLOR,
}
def construct(self):
self.setup()
self.add_vector(self.v_coords, self.v_color)
self.apply_transposed_matrix(self.t_matrix1)
self.wait()
self.apply_transposed_matrix(self.t_matrix2)
self.wait()
class MoreComplicatedExampleWithJustJHat(MoreComplicatedExampleWithJustIHat):
CONFIG = {
"v_coords" : [0, 1],
"v_color" : Y_COLOR,
}
class RoteMatrixMultiplication(NumericalMatrixMultiplication):
CONFIG = {
"left_matrix" : [[-3, 1], [2, 5]],
"right_matrix" : [[5, 3], [7, -3]]
}
class NeverForget(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("Never forget what \\\\ this represents!")
self.random_blink()
self.student_thinks("", index = 0)
def warp(point):
point += 2*DOWN+RIGHT
return 20*point/get_norm(point)
self.play(ApplyPointwiseFunction(
warp,
VMobject(*self.get_mobjects())
))
class AskAboutCommutativity(Scene):
def construct(self):
l_m1, l_m2, eq, r_m2, r_m1 = OldTex([
"M_1", "M_2", "=", "M_2", "M_1"
]).scale(1.5).split()
VMobject(l_m1, r_m1).set_color(YELLOW)
VMobject(l_m2, r_m2).set_color(PINK)
q_marks = OldTexText("???")
q_marks.set_color(TEAL)
q_marks.next_to(eq, UP)
neq = OldTex("\\neq")
neq.move_to(eq)
self.play(*list(map(Write, [l_m1, l_m2, eq])))
self.play(
Transform(l_m1.copy(), r_m1),
Transform(l_m2.copy(), r_m2),
path_arc = -np.pi,
run_time = 2
)
self.play(Write(q_marks))
self.wait()
self.play(Transform(
VMobject(eq, q_marks),
VMobject(neq),
lag_ratio = 0.5
))
self.wait()
class ShowShear(LinearTransformationScene):
CONFIG = {
"title" : "Shear",
"title_color" : PINK,
"t_matrix" : [[1, 0], [1, 1]]
}
def construct(self):
self.setup()
title = OldTexText(self.title)
title.scale(1.5).to_edge(UP)
title.set_color(self.title_color)
title.add_background_rectangle()
self.add_foreground_mobject(title)
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
class ShowRotation(ShowShear):
CONFIG = {
"title" : "$90^\\circ$ rotation",
"title_color" : YELLOW,
"t_matrix" : [[0, 1], [-1, 0]]
}
class FirstShearThenRotation(LinearTransformationScene):
CONFIG = {
"title" : "First shear then rotation",
"t_matrix1" : [[1, 0], [1, 1]],
"t_matrix2" : [[0, 1], [-1, 0]],
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 0
},
}
def construct(self):
self.setup()
title_parts = self.title.split(" ")
title = OldTexText(title_parts)
for i, part in enumerate(title_parts):
if part == "rotation":
title.split()[i].set_color(YELLOW)
elif part == "shear":
title.split()[i].set_color(PINK)
title.scale(1.5)
self.add_title(title)
self.apply_transposed_matrix(self.t_matrix1)
self.apply_transposed_matrix(self.t_matrix2)
self.i_hat.rotate(-0.01)##Laziness
self.wait()
self.write_vector_coordinates(self.i_hat, color = X_COLOR)
self.wait()
self.write_vector_coordinates(self.j_hat, color = Y_COLOR)
self.wait()
class RotationThenShear(FirstShearThenRotation):
CONFIG = {
"title" : "First rotation then shear",
"t_matrix1" : [[0, 1], [-1, 0]],
"t_matrix2" : [[1, 0], [1, 1]],
}
class NoticeTheLackOfComputations(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("""
Notice the lack
of computations!
""")
self.random_blink()
students = self.get_students()
random.shuffle(students)
unit = np.array([-0.5, 0.5])
self.play(*[
ApplyMethod(
pi.change_mode, "pondering",
rate_func = squish_rate_func(smooth, *np.clip(unit+0.5*i, 0, 1))
)
for i, pi in enumerate(students)
])
self.random_blink()
self.wait()
class AskAssociativityQuestion(Scene):
def construct(self):
morty = Mortimer()
morty.scale(0.8)
morty.to_corner(DOWN+RIGHT)
morty.shift(0.5*LEFT)
title = OldTexText("Associativity:")
title.to_corner(UP+LEFT)
lhs = OldTex(list("(AB)C"))
lp, a, b, rp, c = lhs.split()
rhs = VMobject(*[m.copy() for m in (a, lp, b, c, rp)])
point = VectorizedPoint()
start = VMobject(*[m.copy() for m in (point, a, b, point, c)])
for mob in lhs, rhs, start:
mob.arrange(buff = 0.1)
a, lp, b, c, rp = rhs.split()
rhs = VMobject(lp, a, b, rp, c)##Align order to lhs
eq = OldTex("=")
q_marks = OldTexText("???")
q_marks.set_submobject_colors_by_gradient(TEAL_B, TEAL_D)
q_marks.next_to(eq, UP)
lhs.next_to(eq, LEFT)
rhs.next_to(eq, RIGHT)
start.move_to(lhs)
self.add(morty, title)
self.wait()
self.play(Blink(morty))
self.play(Write(start))
self.wait()
self.play(Transform(start, lhs))
self.wait()
self.play(
Transform(lhs, rhs, path_arc = -np.pi),
Write(eq)
)
self.play(Write(q_marks))
self.play(Blink(morty))
self.play(morty.change_mode, "pondering")
lp, a, b, rp, c = start.split()
self.show_full_matrices(morty, a, b, c, title)
def show_full_matrices(self, morty, a, b, c, title):
everything = self.get_mobjects()
everything.remove(morty)
everything.remove(title)
everything = VMobject(*everything)
matrices = list(map(matrix_to_mobject, [
np.array(list(m)).reshape((2, 2))
for m in ("abcd", "efgh", "ijkl")
]))
VMobject(*matrices).arrange()
self.play(everything.to_edge, UP)
for letter, matrix in zip([a, b, c], matrices):
self.play(Transform(
letter.copy(), matrix,
lag_ratio = 0.5
))
self.remove(*self.get_mobjects_from_last_animation())
self.add(matrix)
self.wait()
self.move_matrix_parentheses(morty, matrices)
def move_matrix_parentheses(self, morty, matrices):
m1, m2, m3 = matrices
parens = OldTex(["(", ")"])
parens.set_height(1.2*m1.get_height())
lp, rp = parens.split()
state1 = VMobject(
VectorizedPoint(m1.get_left()),
m1, m2,
VectorizedPoint(m2.get_right()),
m3
)
state2 = VMobject(*[
m.copy() for m in (lp, m1, m2, rp, m3)
])
state3 = VMobject(*[
m.copy() for m in (m1, lp, m2, m3, rp)
])
for state in state2, state3:
state.arrange(RIGHT, buff = 0.1)
m1, lp, m2, m3, rp = state3.split()
state3 = VMobject(lp, m1, m2, rp, m3)
self.play(morty.change_mode, "angry")
for state in state2, state3:
self.play(Transform(state1, state))
self.wait()
self.play(morty.change_mode, "confused")
self.wait()
class ThreeSuccessiveTransformations(LinearTransformationScene):
CONFIG = {
"t_matrices" : [
[[2, 1], [1, 2]],
[[np.cos(-np.pi/6), np.sin(-np.pi/6)], [-np.sin(-np.pi/6), np.cos(-np.pi/6)]],
[[1, 0], [1, 1]]
],
"symbols_str" : "A(BC)",
"include_background_plane" : False,
}
def construct(self):
self.setup()
symbols = OldTex(list(self.symbols_str))
symbols.scale(1.5)
symbols.to_edge(UP)
a, b, c = None, None, None
for mob, letter in zip(symbols.split(), self.symbols_str):
if letter == "A":
a = mob
elif letter == "B":
b = mob
elif letter == "C":
c = mob
symbols.add_background_rectangle()
self.add_foreground_mobject(symbols)
brace = Brace(c, DOWN)
words = OldTexText("Apply this transformation")
words.add_background_rectangle()
words.next_to(brace, DOWN)
brace.add(words)
self.play(Write(brace, run_time = 1))
self.add_foreground_mobject(brace)
last = VectorizedPoint()
for t_matrix, sym in zip(self.t_matrices, [c, b, a]):
self.play(
brace.next_to, sym, DOWN,
sym.set_color, YELLOW,
last.set_color, WHITE
)
self.apply_transposed_matrix(t_matrix, run_time = 1)
last = sym
self.wait()
class ThreeSuccessiveTransformationsAltParens(ThreeSuccessiveTransformations):
CONFIG = {
"symbols_str" : "(AB)C"
}
class ThreeSuccessiveTransformationsSimple(ThreeSuccessiveTransformations):
CONFIG = {
"symbols_str" : "ABC"
}
class ExplanationTrumpsProof(Scene):
def construct(self):
greater = OldTex(">")
greater.shift(RIGHT)
explanation = OldTexText("Good explanation")
explanation.set_color(BLUE)
proof = OldTexText("Symbolic proof")
proof.set_color(LIGHT_BROWN)
explanation.next_to(greater, LEFT)
proof.next_to(greater, RIGHT)
explanation.get_center = lambda : explanation.get_right()
proof.get_center = lambda : proof.get_left()
self.play(
Write(explanation),
Write(greater),
Write(proof),
run_time = 1
)
self.play(
explanation.scale, 1.5,
proof.scale, 0.7
)
self.wait()
class GoPlay(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("Go play!", height = 3, width = 5)
self.play(*[
ApplyMethod(student.change_mode, "happy")
for student in self.get_students()
])
self.random_blink()
student = self.get_students()[-1]
bubble = ThoughtBubble(direction = RIGHT, width = 6, height = 5)
bubble.pin_to(student, allow_flipping = False)
bubble.make_green_screen()
self.play(
ShowCreation(bubble),
student.look, UP+LEFT,
)
self.play(student.change_mode, "pondering")
for x in range(3):
self.random_blink()
self.wait(2)
class NextVideo(Scene):
def construct(self):
title = OldTexText("""
Next video: Linear transformations in three dimensions
""")
title.set_width(FRAME_WIDTH - 2)
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
|
|
from manim_imports_ext import *
from _2016.eola.chapter5 import get_det_text, RightHandRule
U_COLOR = ORANGE
V_COLOR = YELLOW
W_COLOR = MAROON_B
P_COLOR = RED
def get_vect_tex(*strings):
result = ["\\vec{\\textbf{%s}}"%s for s in strings]
if len(result) == 1:
return result[0]
else:
return result
def get_perm_sign(*permutation):
identity = np.identity(len(permutation))
return np.linalg.det(identity[list(permutation)])
class OpeningQuote(Scene):
def construct(self):
words = OldTexText("``Every dimension is special.''")
words.to_edge(UP)
author = OldTexText("-Jeff Lagarias")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = 0.5)
self.play(FadeIn(words))
self.wait(1)
self.play(Write(author, run_time = 3))
self.wait()
class LastVideo(Scene):
def construct(self):
title = OldTexText("""
Last video: Dot products and duality
""")
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
class DoTheSameForCross(TeacherStudentsScene):
def construct(self):
words = OldTexText("Let's do the same \\\\ for", "cross products")
words.set_color_by_tex("cross products", YELLOW)
self.teacher_says(words, target_mode = "surprised")
self.random_blink(2)
self.play_student_changes("pondering")
self.random_blink()
class ListSteps(Scene):
CONFIG = {
"randy_corner" : DOWN+RIGHT
}
def construct(self):
title = OldTexText("Two part chapter")
title.to_edge(UP)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
h_line.next_to(title, DOWN)
randy = Randolph().flip().to_corner(DOWN+RIGHT)
randy.look(UP+LEFT)
step_1 = OldTexText("This video: Standard introduction")
step_2 = OldTexText("Next video: Deeper understanding with ", "linear transformations")
step_2.set_color_by_tex("linear transformations", BLUE)
steps = VGroup(step_1, step_2)
steps.arrange(DOWN, aligned_edge = LEFT, buff = LARGE_BUFF)
steps.next_to(randy, UP)
steps.to_edge(LEFT, buff = LARGE_BUFF)
self.add(title)
self.play(ShowCreation(h_line))
for step in steps:
self.play(Write(step))
self.wait()
for step in steps:
target = step.copy()
target.scale(1.1)
target.set_color(YELLOW)
target.set_color_by_tex("linear transformations", BLUE)
step.target = target
step.save_state()
self.play(FadeIn(randy))
self.play(Blink(randy))
self.play(
MoveToTarget(step_1),
step_2.fade,
randy.change_mode, "happy"
)
self.play(Blink(randy))
self.play(
Transform(step_1, step_1.copy().restore().fade()),
MoveToTarget(step_2),
randy.look, LEFT
)
self.play(randy.change_mode, "erm")
self.wait(2)
self.play(randy.change_mode, "pondering")
self.play(Blink(randy))
class SimpleDefine2dCrossProduct(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"v_coords" : [3, 2],
"w_coords" : [2, -1],
}
def construct(self):
self.add_vectors()
self.show_area()
self.write_area_words()
self.show_sign()
self.swap_v_and_w()
def add_vectors(self):
self.plane.fade()
v = self.add_vector(self.v_coords, color = V_COLOR)
w = self.add_vector(self.w_coords, color = W_COLOR)
for vect, name, direction in (v, "v", "left"), (w, "w", "right"):
color = vect.get_color()
vect.label = self.label_vector(
vect, name, color = color, direction = direction,
)
self.v, self.w = v, w
def show_area(self):
self.add_unit_square()
transform = self.get_matrix_transformation(np.array([
self.v_coords,
self.w_coords,
]))
self.square.apply_function(transform)
self.play(
ShowCreation(self.square),
*list(map(Animation, [self.v, self.w]))
)
self.wait()
self.play(FadeOut(self.square))
v_copy = self.v.copy()
w_copy = self.w.copy()
self.play(v_copy.shift, self.w.get_end())
self.play(w_copy.shift, self.v.get_end())
self.wait()
self.play(
FadeIn(self.square),
*list(map(Animation, [self.v, self.w, v_copy, w_copy]))
)
self.wait()
self.play(*list(map(FadeOut, [v_copy, w_copy])))
def write_area_words(self):
times = OldTex("\\times")
for vect in self.v, self.w:
vect.label.target = vect.label.copy()
vect.label.target.save_state()
cross = VGroup(self.v.label.target, times, self.w.label.target)
cross.arrange(aligned_edge = DOWN)
cross.scale(1.5)
cross.shift(2.5*UP).to_edge(LEFT)
cross_rect = BackgroundRectangle(cross)
equals = OldTex("=")
equals.add_background_rectangle()
equals.next_to(cross, buff = MED_SMALL_BUFF/2)
words = OldTexText("Area of parallelogram")
words.add_background_rectangle()
words.next_to(equals, buff = MED_SMALL_BUFF/2)
arrow = Arrow(
words.get_bottom(),
self.square.get_center(),
color = WHITE
)
self.play(
FadeIn(cross_rect),
Write(times),
*[
ApplyMethod(
vect.label.target.restore,
rate_func = lambda t : smooth(1-t)
)
for vect in (self.v, self.w)
]
)
self.wait()
self.play(ApplyFunction(
lambda m : m.scale(1.2).set_color(RED),
times,
rate_func = there_and_back
))
self.wait()
self.play(Write(words), Write(equals))
self.play(ShowCreation(arrow))
self.wait()
self.play(FadeOut(arrow))
self.area_words = words
self.cross = cross
def show_sign(self):
for vect, angle in (self.v, -np.pi/2), (self.w, np.pi/2):
vect.add(vect.label)
vect.save_state()
vect.target = vect.copy()
vect.target.rotate(angle)
vect.target.label.rotate(-angle)
vect.target.label.background_rectangle.set_fill(opacity = 0)
square = self.square
square.save_state()
self.add_unit_square(animate = False, opacity = 0.15)
transform = self.get_matrix_transformation([
self.v.target.get_end()[:2],
self.w.target.get_end()[:2],
])
self.square.apply_function(transform)
self.remove(self.square)
square.target = self.square
self.square = square
positive = OldTexText("Positive").set_color(GREEN)
negative = OldTexText("Negative").set_color(RED)
for word in positive, negative:
word.add_background_rectangle()
word.arrow = Arrow(
word.get_top(), word.get_top() + 1.5*UP,
color = word.get_color()
)
VGroup(word, word.arrow).next_to(
self.area_words, DOWN,
aligned_edge = LEFT,
buff = SMALL_BUFF
)
minus_sign = OldTex("-")
minus_sign.set_color(RED)
minus_sign.move_to(self.area_words, aligned_edge = LEFT)
self.area_words.target = self.area_words.copy()
self.area_words.target.next_to(minus_sign, RIGHT)
self.play(*list(map(MoveToTarget, [square, self.v, self.w])))
arc = self.get_arc(self.v, self.w, radius = 1.5)
arc.set_color(GREEN)
self.play(ShowCreation(arc))
self.wait()
self.play(Write(positive), ShowCreation(positive.arrow))
self.remove(arc)
self.play(
FadeOut(positive),
FadeOut(positive.arrow),
*[mob.restore for mob in (square, self.v, self.w)]
)
arc = self.get_arc(self.v, self.w, radius = 1.5)
arc.set_color(RED)
self.play(ShowCreation(arc))
self.play(
Write(negative),
ShowCreation(negative.arrow),
Write(minus_sign),
MoveToTarget(self.area_words)
)
self.wait()
self.play(*list(map(FadeOut, [negative, negative.arrow, arc])))
def swap_v_and_w(self):
new_cross = self.cross.copy()
new_cross.arrange(LEFT, aligned_edge = DOWN)
new_cross.move_to(self.area_words, aligned_edge = LEFT)
for vect in self.v, self.w:
vect.remove(vect.label)
self.play(
FadeOut(self.area_words),
Transform(self.cross.copy(), new_cross, path_arc = np.pi/2)
)
self.wait()
curr_matrix = np.array([self.v.get_end()[:2], self.w.get_end()[:2]])
new_matrix = np.array(list(reversed(curr_matrix)))
transform = self.get_matrix_transformation(
np.dot(new_matrix.T, np.linalg.inv(curr_matrix.T)).T
)
self.square.target = self.square.copy().apply_function(transform)
self.play(
MoveToTarget(self.square),
Transform(self.v, self.w),
Transform(self.w, self.v),
rate_func = there_and_back,
run_time = 3
)
self.wait()
def get_arc(self, v, w, radius = 2):
v_angle, w_angle = v.get_angle(), w.get_angle()
nudge = 0.05
arc = Arc(
(1-2*nudge)*(w_angle - v_angle),
start_angle = interpolate(v_angle, w_angle, nudge),
radius = radius,
stroke_width = 8,
)
arc.add_tip()
return arc
class CrossBasisVectors(LinearTransformationScene):
def construct(self):
self.plane.fade()
i_label = self.get_vector_label(
self.i_hat, "\\hat{\\imath}",
direction = "right",
color = X_COLOR,
)
j_label = self.get_vector_label(
self.j_hat, "\\hat{\\jmath}",
direction = "left",
color = Y_COLOR,
)
for label in i_label, j_label:
self.play(Write(label))
label.target = label.copy()
i_label.target.scale(1.5)
j_label.target.scale(1.2)
self.wait()
times = OldTex("\\times")
cross = VGroup(i_label.target, times, j_label.target)
cross.arrange()
cross.next_to(ORIGIN).shift(1.5*UP)
cross_rect = BackgroundRectangle(cross)
eq = OldTex("= + 1")
eq.add_background_rectangle()
eq.next_to(cross, RIGHT)
self.play(
ShowCreation(cross_rect),
MoveToTarget(i_label.copy()),
MoveToTarget(j_label.copy()),
Write(times),
)
self.play(Write(eq))
self.wait()
arc = self.get_arc(self.i_hat, self.j_hat, radius = 1)
# arc.set_color(GREEN)
self.play(ShowCreation(arc))
self.wait()
def get_arc(self, v, w, radius = 2):
v_angle, w_angle = v.get_angle(), w.get_angle()
nudge = 0.05
arc = Arc(
(1-2*nudge)*(w_angle - v_angle),
start_angle = interpolate(v_angle, w_angle, nudge),
radius = radius,
stroke_width = 8,
)
arc.add_tip()
return arc
class VisualExample(SimpleDefine2dCrossProduct):
CONFIG = {
"show_basis_vectors" : False,
"v_coords" : [3, 1],
"w_coords" : [1, -2],
}
def construct(self):
self.add_vectors()
# self.show_coords()
self.show_area()
self.write_area_words()
result = np.linalg.det([self.v_coords, self.w_coords])
val = OldTex(str(int(abs(result)))).scale(2)
val.move_to(self.square.get_center())
arc = self.get_arc(self.v, self.w, radius = 1)
arc.set_color(RED)
minus = OldTex("-").set_color(RED)
minus.scale(1.5)
minus.move_to(self.area_words, aligned_edge = LEFT)
self.play(ShowCreation(val))
self.wait()
self.play(ShowCreation(arc))
self.wait()
self.play(FadeOut(self.area_words))
self.play(
Transform(arc, minus),
val.next_to, minus, RIGHT
)
self.wait()
def show_coords(self):
for vect, edge in (self.v, DOWN), (self.w, UP):
color = vect.get_color()
vect.coord_array = vector_coordinate_label(
vect, color = color,
)
vect.coord_array.move_to(
vect.coord_array.get_center(),
aligned_edge = edge
)
self.play(Write(vect.coord_array, run_time = 1))
class HowDoYouCompute(TeacherStudentsScene):
def construct(self):
self.student_says(
"How do you \\\\ compute this?",
target_mode = "raise_left_hand"
)
self.random_blink(2)
class ContrastDotAndCross(Scene):
def construct(self):
self.add_t_chart()
self.add_dot_products()
self.add_cross_product()
self.add_2d_cross_product()
self.emphasize_output_type()
def add_t_chart(self):
for word, vect, color in ("Dot", LEFT, BLUE_C), ("Cross", RIGHT, YELLOW):
title = OldTexText("%s product"%word)
title.shift(vect*FRAME_X_RADIUS/2)
title.to_edge(UP)
title.set_color(color)
self.add(title)
v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS)
l_h_line = Line(LEFT, ORIGIN).scale(FRAME_X_RADIUS)
r_h_line = Line(ORIGIN, RIGHT).scale(FRAME_X_RADIUS)
r_h_line.next_to(title, DOWN)
l_h_line.next_to(r_h_line, LEFT, buff = 0)
self.add(v_line, l_h_line, r_h_line)
self.l_h_line, self.r_h_line = l_h_line, r_h_line
def add_dot_products(self, max_width = FRAME_X_RADIUS-1, dims = [2, 5]):
colors = [X_COLOR, Y_COLOR, Z_COLOR, MAROON_B, TEAL]
last_mob = self.l_h_line
dot_products = []
for dim in dims:
arrays = [
[random.randint(0, 9) for in_count in range(dim)]
for out_count in range(2)
]
m1, m2 = list(map(Matrix, arrays))
for matrix in m1, m2:
for entry, color in zip(matrix.get_entries(), colors):
entry.set_color(color)
entry.target = entry.copy()
syms = VGroup(*list(map(Tex, ["="] + ["+"]*(dim-1))))
def get_dot():
dot = OldTex("\\cdot")
syms.add(dot)
return dot
result = VGroup(*it.chain(*list(zip(
syms,
[
VGroup(
e1.target, get_dot(), e2.target
).arrange()
for e1, e2 in zip(m1.get_entries(), m2.get_entries())
]
))))
result.arrange(RIGHT)
dot_prod = VGroup(
m1, OldTex("\\cdot"), m2, result
)
dot_prod.arrange(RIGHT)
if dot_prod.get_width() > max_width:
dot_prod.set_width(max_width)
dot_prod.next_to(last_mob, DOWN, buff = MED_SMALL_BUFF)
last_mob = dot_prod
dot_prod.to_edge(LEFT)
dot_prod.remove(result)
dot_prod.syms = syms
dot_prod.entries = list(m1.get_entries())+list(m2.get_entries())
dot_products.append(dot_prod)
self.add(*dot_products)
for dot_prod in dot_products:
self.play(
Write(dot_prod.syms),
*[
Transform(
e.copy(), e.target,
path_arc = -np.pi/6
)
for e in dot_prod.entries
],
run_time = 2
)
self.wait()
def add_cross_product(self):
colors = [X_COLOR, Y_COLOR, Z_COLOR]
arrays = [
[random.randint(0, 9) for in_count in range(3)]
for out_count in range(2)
]
matrices = list(map(Matrix, arrays))
for matrix in matrices:
for entry, color in zip(matrix.get_entries(), colors):
entry.set_color(color)
m1, m2 = matrices
cross_product = VGroup(m1, OldTex("\\times"), m2)
cross_product.arrange()
index_to_cross_enty = {}
syms = VGroup()
movement_sets = []
for a, b, c in it.permutations(list(range(3))):
e1, e2 = m1.get_entries()[b], m2.get_entries()[c]
for e in e1, e2:
e.target = e.copy()
movement_sets.append([e1, e1.target, e2, e2.target])
dot = OldTex("\\cdot")
syms.add(dot)
cross_entry = VGroup(e1.target, dot, e2.target)
cross_entry.arrange()
if a not in index_to_cross_enty:
index_to_cross_enty[a] = []
index_to_cross_enty[a].append(cross_entry)
result_entries = []
for a in range(3):
prod1, prod2 = index_to_cross_enty[a]
if a == 1:
prod1, prod2 = prod2, prod1
prod2.arrange(LEFT)
minus = OldTex("-")
syms.add(minus)
entry = VGroup(prod1, minus, prod2)
entry.arrange(RIGHT)
result_entries.append(entry)
result = Matrix(result_entries)
full_cross_product = VGroup(
cross_product, OldTex("="), result
)
full_cross_product.arrange()
full_cross_product.scale(0.75)
full_cross_product.next_to(self.r_h_line, DOWN, buff = MED_SMALL_BUFF/2)
full_cross_product.remove(result)
self.play(
Write(full_cross_product),
)
movements = []
for e1, e1_target, e2, e2_target in movement_sets:
movements += [
e1.copy().move_to, e1_target,
e2.copy().move_to, e2_target,
]
brace = Brace(cross_product)
brace_text = brace.get_text("Only 3d")
self.play(
GrowFromCenter(brace),
Write(brace_text)
)
self.play(
Write(result.get_brackets()),
Write(syms),
*movements,
run_time = 2
)
self.wait()
self.cross_result = result
self.only_3d_text = brace_text
def add_2d_cross_product(self):
h_line = DashedLine(ORIGIN, FRAME_X_RADIUS*RIGHT)
h_line.next_to(self.only_3d_text, DOWN, buff = MED_SMALL_BUFF/2)
h_line.to_edge(RIGHT, buff = 0)
arrays = np.random.randint(0, 9, (2, 2))
m1, m2 = matrices = list(map(Matrix, arrays))
for m in matrices:
for e, color in zip(m.get_entries(), [X_COLOR, Y_COLOR]):
e.set_color(color)
cross_product = VGroup(m1, OldTex("\\times"), m2)
cross_product.arrange()
(x1, x2), (x3, x4) = tuple(m1.get_entries()), tuple(m2.get_entries())
entries = [x1, x2, x3, x4]
for entry in entries:
entry.target = entry.copy()
eq, dot1, minus, dot2 = syms = list(map(Tex,
["=", "\\cdot", "-", "\\cdot"]
))
result = VGroup(
eq, x1.target, dot1, x4.target,
minus, x3.target, dot2, x2.target,
)
result.arrange(RIGHT)
full_cross_product = VGroup(cross_product, result)
full_cross_product.arrange(RIGHT)
full_cross_product.next_to(h_line, DOWN, buff = MED_SMALL_BUFF/2)
self.play(ShowCreation(h_line))
self.play(Write(cross_product))
self.play(
Write(VGroup(*syms)),
*[
Transform(entry.copy(), entry.target)
for entry in entries
]
)
self.wait()
self.two_d_result = VGroup(*result[1:])
def emphasize_output_type(self):
three_d_brace = Brace(self.cross_result)
two_d_brace = Brace(self.two_d_result)
vector = three_d_brace.get_text("Vector")
number = two_d_brace.get_text("Number")
self.play(
GrowFromCenter(two_d_brace),
Write(number)
)
self.wait()
self.play(
GrowFromCenter(three_d_brace),
Write(vector)
)
self.wait()
class PrereqDeterminant(Scene):
def construct(self):
title = OldTexText("""
Prerequisite: Understanding determinants
""")
title.set_width(FRAME_WIDTH - 2)
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
class Define2dCrossProduct(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"v_coords" : [3, 1],
"w_coords" : [2, -1],
}
def construct(self):
self.initial_definition()
self.show_transformation()
self.transform_square()
self.show_orientation_rule()
def initial_definition(self):
self.plane.save_state()
self.plane.fade()
v = self.add_vector(self.v_coords, color = V_COLOR)
w = self.add_vector(self.w_coords, color = W_COLOR)
self.moving_vectors.remove(v)
self.moving_vectors.remove(w)
for vect, name, direction in (v, "v", "left"), (w, "w", "right"):
color = vect.get_color()
vect.label = self.label_vector(
vect, name, color = color, direction = direction,
)
vect.coord_array = vector_coordinate_label(
vect, color = color,
)
vect.coords = vect.coord_array.get_entries()
for vect, edge in (v, DOWN), (w, UP):
vect.coord_array.move_to(
vect.coord_array.get_center(),
aligned_edge = edge
)
self.play(Write(vect.coord_array, run_time = 1))
movers = [v.label, w.label, v.coords, w.coords]
for mover in movers:
mover.target = mover.copy()
times = OldTex("\\times")
cross_product = VGroup(
v.label.target, times, w.label.target
)
cross_product.arrange()
matrix = Matrix(np.array([
list(v.coords.target),
list(w.coords.target)
]).T)
det_text = get_det_text(matrix)
full_det = VGroup(det_text, matrix)
equals = OldTex("=")
equation = VGroup(cross_product, equals, full_det)
equation.arrange()
equation.to_corner(UP+LEFT)
matrix_background = BackgroundRectangle(matrix)
cross_background = BackgroundRectangle(cross_product)
disclaimer = OldTexText("$^*$ See ``Note on conventions'' in description")
disclaimer.scale(0.7)
disclaimer.set_color(RED)
disclaimer.next_to(
det_text.get_corner(UP+RIGHT), RIGHT, buff = 0
)
disclaimer.add_background_rectangle()
self.play(
FadeIn(cross_background),
Transform(v.label.copy(), v.label.target),
Transform(w.label.copy(), w.label.target),
Write(times),
)
self.wait()
self.play(
ShowCreation(matrix_background),
Write(matrix.get_brackets()),
run_time = 1
)
self.play(Transform(v.coords.copy(), v.coords.target))
self.play(Transform(w.coords.copy(), w.coords.target))
matrix.add_to_back(matrix_background)
self.wait()
self.play(
Write(equals),
Write(det_text),
Animation(matrix),
)
self.wait()
self.play(FadeIn(disclaimer))
self.wait()
self.play(FadeOut(disclaimer))
self.wait()
cross_product.add_to_back(cross_background)
cross_product.add(equals)
self.cross_product = cross_product
self.matrix = matrix
self.det_text = det_text
self.v, self.w = v, w
def show_transformation(self):
matrix = self.matrix.copy()
everything = self.get_mobjects()
everything.remove(self.plane)
everything.remove(self.background_plane)
self.play(
*list(map(FadeOut, everything)) + [
Animation(self.background_plane),
self.plane.restore,
Animation(matrix),
])
i_hat, j_hat = self.get_basis_vectors()
for vect in i_hat, j_hat:
vect.save_state()
basis_labels = self.get_basis_vector_labels()
self.play(
ShowCreation(i_hat),
ShowCreation(j_hat),
Write(basis_labels)
)
self.wait()
side_brace = Brace(matrix, RIGHT)
transform_words = side_brace.get_text("Linear transformation")
transform_words.add_background_rectangle()
col1, col2 = [
VGroup(*matrix.get_mob_matrix()[i,:])
for i in (0, 1)
]
both_words = []
for char, color, col in ("i", X_COLOR, col1), ("j", Y_COLOR, col2):
words = OldTexText("Where $\\hat\\%smath$ lands"%char)
words.set_color(color)
words.add_background_rectangle()
words.next_to(col, DOWN, buff = LARGE_BUFF)
words.arrow = Arrow(words.get_top(), col.get_bottom(), color = color)
both_words.append(words)
i_words, j_words = both_words
self.play(
GrowFromCenter(side_brace),
Write(transform_words)
)
self.play(
Write(i_words),
ShowCreation(i_words.arrow),
col1.set_color, X_COLOR
)
self.wait()
self.play(
Transform(i_words, j_words),
Transform(i_words.arrow, j_words.arrow),
col2.set_color, Y_COLOR
)
self.wait()
self.play(*list(map(FadeOut, [i_words, i_words.arrow, basis_labels])))
self.add_vector(i_hat, animate = False)
self.add_vector(j_hat, animate = False)
self.play(*list(map(FadeOut, [side_brace, transform_words])))
self.add_foreground_mobject(matrix)
self.apply_transposed_matrix([self.v_coords, self.w_coords])
self.wait()
self.play(
FadeOut(self.plane),
*list(map(Animation, [
self.background_plane,
matrix,
i_hat,
j_hat,
]))
)
self.play(
ShowCreation(self.v),
ShowCreation(self.w),
FadeIn(self.v.label),
FadeIn(self.w.label),
FadeIn(self.v.coord_array),
FadeIn(self.w.coord_array),
matrix.set_column_colors, V_COLOR, W_COLOR
)
self.wait()
self.i_hat, self.j_hat = i_hat, j_hat
self.matrix = matrix
def transform_square(self):
self.play(Write(self.det_text))
self.matrix.add(self.det_text)
vect_stuffs = VGroup(*it.chain(*[
[m, m.label, m.coord_array]
for m in (self.v, self.w)
]))
to_restore = [self.plane, self.i_hat, self.j_hat]
for mob in to_restore:
mob.fade(1)
self.play(*list(map(FadeOut, vect_stuffs)))
self.play(
*[m.restore for m in to_restore] + [
Animation(self.matrix)
]
)
self.add_unit_square(animate = True, opacity = 0.2)
self.square.save_state()
self.wait()
self.apply_transposed_matrix(
[self.v_coords, self.w_coords]
)
self.wait()
self.play(
FadeOut(self.plane),
Animation(self.matrix),
*list(map(FadeIn, vect_stuffs))
)
self.play(Write(self.cross_product))
det_text_brace = Brace(self.det_text)
area_words = det_text_brace.get_text("Area of this parallelogram")
area_words.add_background_rectangle()
area_arrow = Arrow(
area_words.get_bottom(),
self.square.get_center(),
color = WHITE
)
self.play(
GrowFromCenter(det_text_brace),
Write(area_words),
ShowCreation(area_arrow)
)
self.wait()
pm = VGroup(*list(map(Tex, ["+", "-"])))
pm.set_color_by_gradient(GREEN, RED)
pm.arrange(DOWN, buff = SMALL_BUFF)
pm.add_to_back(BackgroundRectangle(pm))
pm.next_to(area_words[0], LEFT, aligned_edge = DOWN)
self.play(
Transform(self.square.get_point_mobject(), pm),
path_arc = -np.pi/2
)
self.wait()
self.play(*list(map(FadeOut, [
area_arrow, self.v.coord_array, self.w.coord_array
])))
def show_orientation_rule(self):
self.remove(self.i_hat, self.j_hat)
for vect in self.v, self.w:
vect.add(vect.label)
vect.target = vect.copy()
angle = np.pi/3
self.v.target.rotate(-angle)
self.w.target.rotate(angle)
self.v.target.label.rotate(angle)
self.w.target.label.rotate(-angle)
for vect in self.v, self.w:
vect.target.label[0].set_fill(opacity = 0)
self.square.target = self.square.copy().restore()
transform = self.get_matrix_transformation([
self.v.target.get_end()[:2],
self.w.target.get_end()[:2],
])
self.square.target.apply_function(transform)
movers = VGroup(self.square, self.v, self.w)
movers.target = VGroup(*[m.target for m in movers])
movers.save_state()
self.remove(self.square)
self.play(Transform(movers, movers.target))
self.wait()
v_tex, w_tex = ["\\vec{\\textbf{%s}}"%s for s in ("v", "w")]
positive_words, negative_words = words_list = [
OldTex(v_tex, "\\times", w_tex, "\\text{ is }", word)
for word in ("\\text{positive}", "\\text{negative}")
]
for words in words_list:
words.set_color_by_tex(v_tex, V_COLOR)
words.set_color_by_tex(w_tex, W_COLOR)
words.set_color_by_tex("\\text{positive}", GREEN)
words.set_color_by_tex("\\text{negative}", RED)
words.add_background_rectangle()
words.next_to(self.square, UP)
arc = self.get_arc(self.v, self.w)
arc.set_color(GREEN)
self.play(
Write(positive_words),
ShowCreation(arc)
)
self.wait()
self.remove(arc)
self.play(movers.restore)
arc = self.get_arc(self.v, self.w)
arc.set_color(RED)
self.play(
Transform(positive_words, negative_words),
ShowCreation(arc)
)
self.wait()
anticommute = OldTex(
v_tex, "\\times", w_tex, "=-", w_tex, "\\times", v_tex
)
anticommute.shift(FRAME_X_RADIUS*RIGHT/2)
anticommute.to_edge(UP)
anticommute.set_color_by_tex(v_tex, V_COLOR)
anticommute.set_color_by_tex(w_tex, W_COLOR)
anticommute.add_background_rectangle()
for v1, v2 in (self.v, self.w), (self.w, self.v):
v1.label[0].set_fill(opacity = 0)
v1.target = v1.copy()
v1.target.label.rotate(v1.get_angle()-v2.get_angle())
v1.target.label.scale(v1.get_length()/v2.get_length())
v1.target.rotate(v2.get_angle()-v1.get_angle())
v1.target.scale(v2.get_length()/v1.get_length())
v1.target.label.move_to(v2.label)
self.play(
FadeOut(arc),
Transform(positive_words, anticommute)
)
self.play(
Transform(self.v, self.v.target),
Transform(self.w, self.w.target),
rate_func = there_and_back,
run_time = 2,
)
self.wait()
def get_arc(self, v, w, radius = 2):
v_angle, w_angle = v.get_angle(), w.get_angle()
nudge = 0.05
arc = Arc(
(1-2*nudge)*(w_angle - v_angle),
start_angle = interpolate(v_angle, w_angle, nudge),
radius = radius,
stroke_width = 8,
)
arc.add_tip()
return arc
class TwoDCrossProductExample(Define2dCrossProduct):
CONFIG = {
"v_coords" : [-3, 1],
"w_coords" : [2, 1],
}
def construct(self):
self.plane.fade()
v = Vector(self.v_coords, color = V_COLOR)
w = Vector(self.w_coords, color = W_COLOR)
v.coords = Matrix(self.v_coords)
w.coords = Matrix(self.w_coords)
v.coords.next_to(v.get_end(), LEFT)
w.coords.next_to(w.get_end(), RIGHT)
v.coords.set_color(v.get_color())
w.coords.set_color(w.get_color())
for coords in v.coords, w.coords:
coords.background_rectangle = BackgroundRectangle(coords)
coords.add_to_back(coords.background_rectangle)
v.label = self.get_vector_label(v, "v", "left", color = v.get_color())
w.label = self.get_vector_label(w, "w", "right", color = w.get_color())
matrix = Matrix(np.array([
list(v.coords.copy().get_entries()),
list(w.coords.copy().get_entries()),
]).T)
matrix_background = BackgroundRectangle(matrix)
col1, col2 = it.starmap(Group, matrix.get_mob_matrix().T)
det_text = get_det_text(matrix)
v_tex, w_tex = get_vect_tex("v", "w")
cross_product = OldTex(v_tex, "\\times", w_tex, "=")
cross_product.set_color_by_tex(v_tex, V_COLOR)
cross_product.set_color_by_tex(w_tex, W_COLOR)
cross_product.add_background_rectangle()
equation_start = VGroup(
cross_product,
VGroup(matrix_background, det_text, matrix)
)
equation_start.arrange()
equation_start.next_to(ORIGIN, DOWN).to_edge(LEFT)
for vect in v, w:
self.play(
ShowCreation(vect),
Write(vect.coords),
Write(vect.label)
)
self.wait()
self.play(
Transform(v.coords.background_rectangle, matrix_background),
Transform(w.coords.background_rectangle, matrix_background),
Transform(v.coords.get_entries(), col1),
Transform(w.coords.get_entries(), col2),
Transform(v.coords.get_brackets(), matrix.get_brackets()),
Transform(w.coords.get_brackets(), matrix.get_brackets()),
)
self.play(*list(map(Write, [det_text, cross_product])))
v1, v2 = v.coords.get_entries()
w1, w2 = w.coords.get_entries()
entries = v1, v2, w1, w2
for entry in entries:
entry.target = entry.copy()
det = np.linalg.det([self.v_coords, self.w_coords])
equals, dot1, minus, dot2, equals_result = syms = VGroup(*list(map(
Tex,
["=", "\\cdot", "-", "\\cdot", "=%d"%det]
)))
equation_end = VGroup(
equals, v1.target, dot1, w2.target,
minus, w1.target, dot2, v2.target, equals_result
)
equation_end.arrange()
equation_end.next_to(equation_start)
syms_rect = BackgroundRectangle(syms)
syms.add_to_back(syms_rect)
equation_end.add_to_back(syms_rect)
syms.remove(equals_result)
self.play(
Write(syms),
Transform(
VGroup(v1, w2).copy(), VGroup(v1.target, w2.target),
rate_func = squish_rate_func(smooth, 0, 1./3),
path_arc = np.pi/2
),
Transform(
VGroup(v2, w1).copy(), VGroup(v2.target, w1.target),
rate_func = squish_rate_func(smooth, 2./3, 1),
path_arc = np.pi/2
),
run_time = 3
)
self.wait()
self.play(Write(equals_result))
self.add_foreground_mobject(equation_start, equation_end)
self.show_transformation(v, w)
det_sym = OldTex(str(int(abs(det))))
det_sym.scale(1.5)
det_sym.next_to(v.get_end()+w.get_end(), DOWN+RIGHT, buff = MED_SMALL_BUFF/2)
arc = self.get_arc(v, w, radius = 1)
arc.set_color(RED)
self.play(Write(det_sym))
self.play(ShowCreation(arc))
self.wait()
def show_transformation(self, v, w):
i_hat, j_hat = self.get_basis_vectors()
self.play(*list(map(ShowCreation, [i_hat, j_hat])))
self.add_unit_square(animate = True, opacity = 0.2)
self.apply_transposed_matrix(
[v.get_end()[:2], w.get_end()[:2]],
added_anims = [
Transform(i_hat, v),
Transform(j_hat, w)
]
)
class PlayAround(TeacherStudentsScene):
def construct(self):
self.teacher_says(""" \\centering
Play with the idea if
you wish to understand it
""")
self.play_student_changes("pondering", "happy", "happy")
self.random_blink(2)
self.student_thinks("", index = 0)
self.zoom_in_on_thought_bubble()
class BiggerWhenPerpendicular(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
}
def construct(self):
self.lock_in_faded_grid()
self.add_unit_square(animate = False)
square = self.square
self.remove(square)
start_words = OldTexText("More perpendicular")
end_words = OldTexText("Similar direction")
arrow = OldTexText("\\Rightarrow")
v_tex, w_tex = get_vect_tex("v", "w")
cross_is = OldTex(v_tex, "\\times", w_tex, "\\text{ is }")
cross_is.set_color_by_tex(v_tex, V_COLOR)
cross_is.set_color_by_tex(w_tex, W_COLOR)
bigger = OldTexText("bigger")
smaller = OldTexText("smaller")
bigger.scale(1.5)
smaller.scale(0.75)
bigger.set_color(PINK)
smaller.set_color(TEAL)
group = VGroup(start_words, arrow, cross_is, bigger)
group.arrange()
group.to_edge(UP)
end_words.move_to(start_words, aligned_edge = RIGHT)
smaller.next_to(cross_is, buff = MED_SMALL_BUFF/2, aligned_edge = DOWN)
for mob in list(group) + [end_words, smaller]:
mob.add_background_rectangle()
v = Vector([2, 2], color = V_COLOR)
w = Vector([2, -2], color = W_COLOR)
v.target = v.copy().rotate(-np.pi/5)
w.target = w.copy().rotate(np.pi/5)
transforms = [
self.get_matrix_transformation([v1.get_end()[:2], v2.get_end()[:2]])
for v1, v2 in [(v, w), (v.target, w.target)]
]
start_square, end_square = [
square.copy().apply_function(transform)
for transform in transforms
]
for vect in v, w:
self.play(ShowCreation(vect))
group.remove(bigger)
self.play(
FadeIn(group),
ShowCreation(start_square),
*list(map(Animation, [v, w]))
)
self.play(GrowFromCenter(bigger))
self.wait()
self.play(
Transform(start_square, end_square),
Transform(v, v.target),
Transform(w, w.target),
)
self.play(
Transform(start_words, end_words),
Transform(bigger, smaller)
)
self.wait()
class ScalingRule(LinearTransformationScene):
CONFIG = {
"v_coords" : [2, -1],
"w_coords" : [1, 1],
"show_basis_vectors" : False
}
def construct(self):
self.lock_in_faded_grid()
self.add_unit_square(animate = False)
self.remove(self.square)
square = self.square
v = Vector(self.v_coords, color = V_COLOR)
w = Vector(self.w_coords, color = W_COLOR)
v.label = self.get_vector_label(v, "v", "right", color = V_COLOR)
w.label = self.get_vector_label(w, "w", "left", color = W_COLOR)
new_v = v.copy().scale(3)
new_v.label = self.get_vector_label(
new_v, "3\\vec{\\textbf{v}}", "right", color = V_COLOR
)
for vect in v, w, new_v:
vect.add(vect.label)
transform = self.get_matrix_transformation(
[self.v_coords, self.w_coords]
)
square.apply_function(transform)
new_squares = VGroup(*[
square.copy().shift(m*v.get_end())
for m in range(3)
])
v_tex, w_tex = get_vect_tex("v", "w")
cross_product = OldTex(v_tex, "\\times", w_tex)
rhs = OldTex("=3(", v_tex, "\\times", w_tex, ")")
three_v = OldTex("(3", v_tex, ")")
for tex_mob in cross_product, rhs, three_v:
tex_mob.set_color_by_tex(v_tex, V_COLOR)
tex_mob.set_color_by_tex(w_tex, W_COLOR)
equation = VGroup(cross_product, rhs)
equation.arrange()
equation.to_edge(UP)
v_tex_mob = cross_product[0]
three_v.move_to(v_tex_mob, aligned_edge = RIGHT)
for tex_mob in cross_product, rhs:
tex_mob.add_background_rectangle()
self.add(cross_product)
self.play(ShowCreation(v))
self.play(ShowCreation(w))
self.play(
ShowCreation(square),
*list(map(Animation, [v, w]))
)
self.wait()
self.play(
Transform(v, new_v),
Transform(v_tex_mob, three_v),
)
self.wait()
self.play(
Transform(square, new_squares),
*list(map(Animation, [v, w])),
path_arc = -np.pi/6
)
self.wait()
self.play(Write(rhs))
self.wait()
class TechnicallyNotTheDotProduct(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
That was technically
not the cross product
""")
self.play_student_changes("confused")
self.play_student_changes("confused", "angry")
self.play_student_changes("confused", "angry", "sassy")
self.random_blink(3)
class ThreeDShowParallelogramAndCrossProductVector(Scene):
pass
class WriteAreaOfParallelogram(Scene):
def construct(self):
words = OldTexText(
"Area of ", "parallelogram", " $=$ ", "$2.5$",
arg_separator = ""
)
words.set_color_by_tex("parallelogram", BLUE)
words.set_color_by_tex("$2.5$", BLUE)
result = words[-1]
words.remove(result)
self.play(Write(words))
self.wait()
self.play(Write(result, run_time = 1))
self.wait()
class WriteCrossProductProperties(Scene):
def construct(self):
v_tex, w_tex, p_tex = texs = get_vect_tex(*"vwp")
v_cash, w_cash, p_cash = ["$%s$"%tex for tex in texs]
cross_product = OldTex(v_tex, "\\times", w_tex, "=", p_tex)
cross_product.set_color_by_tex(v_tex, V_COLOR)
cross_product.set_color_by_tex(w_tex, W_COLOR)
cross_product.set_color_by_tex(p_tex, P_COLOR)
cross_product.to_edge(UP, buff = LARGE_BUFF)
p_mob = cross_product[-1]
brace = Brace(p_mob)
brace.do_in_place(brace.stretch, 2, 0)
vector = brace.get_text("vector")
vector.set_color(P_COLOR)
length_words = OldTexText(
"Length of ", p_cash, "\\\\ = ",
"(parallelogram's area)"
)
length_words.set_color_by_tex(p_cash, P_COLOR)
length_words.set_width(FRAME_X_RADIUS - 1)
length_words.set_color_by_tex("(parallelogram's area)", BLUE)
length_words.next_to(VGroup(cross_product, vector), DOWN, buff = LARGE_BUFF)
perpendicular = OldTexText(
"\\centering Perpendicular to",
v_cash, "and", w_cash
)
perpendicular.set_width(FRAME_X_RADIUS - 1)
perpendicular.set_color_by_tex(v_cash, V_COLOR)
perpendicular.set_color_by_tex(w_cash, W_COLOR)
perpendicular.next_to(length_words, DOWN, buff = LARGE_BUFF)
self.play(Write(cross_product))
self.play(
GrowFromCenter(brace),
Write(vector, run_time = 1)
)
self.wait()
self.play(Write(length_words, run_time = 1))
self.wait()
self.play(Write(perpendicular))
self.wait()
def get_cross_product_right_hand_rule_labels():
v_tex, w_tex = get_vect_tex(*"vw")
return [
v_tex, w_tex,
"%s \\times %s"%(v_tex, w_tex)
]
class CrossProductRightHandRule(RightHandRule):
CONFIG = {
"flip" : False,
"labels_tex" : get_cross_product_right_hand_rule_labels(),
"colors" : [U_COLOR, W_COLOR, P_COLOR],
}
class LabelingExampleVectors(Scene):
def construct(self):
v_tex, w_tex = texs = get_vect_tex(*"vw")
colors = [U_COLOR, W_COLOR, P_COLOR]
equations = [
OldTex(v_tex, "=%s"%matrix_to_tex_string([0, 0, 2])),
OldTex(w_tex, "=%s"%matrix_to_tex_string([0, 2, 0])),
OldTex(
v_tex, "\\times", w_tex,
"=%s"%matrix_to_tex_string([-4, 0, 0])
),
]
for eq, color in zip(equations, colors):
eq.set_color(color)
eq.scale(2)
area_words = OldTexText("Area", "=4")
area_words[0].set_color(BLUE)
area_words.scale(2)
for mob in equations[:2] + [area_words, equations[2]]:
self.fade_in_out(mob)
def fade_in_out(self, mob):
self.play(FadeIn(mob))
self.wait()
self.play(FadeOut(mob))
class ThreeDTwoPossiblePerpendicularVectors(Scene):
pass
class ThreeDCrossProductExample(Scene):
pass
class ShowCrossProductFormula(Scene):
def construct(self):
colors = [X_COLOR, Y_COLOR, Z_COLOR]
arrays = [
["%s_%d"%(s, i) for i in range(1, 4)]
for s in ("v", "w")
]
matrices = list(map(Matrix, arrays))
for matrix in matrices:
for entry, color in zip(matrix.get_entries(), colors):
entry.set_color(color)
m1, m2 = matrices
cross_product = VGroup(m1, OldTex("\\times"), m2)
cross_product.arrange()
cross_product.shift(2*LEFT)
entry_dicts = [{} for x in range(3)]
movement_sets = []
for a, b, c in it.permutations(list(range(3))):
sign = get_perm_sign(a, b, c)
e1, e2 = m1.get_entries()[b], m2.get_entries()[c]
for e in e1, e2:
e.target = e.copy()
dot = OldTex("\\cdot")
syms = VGroup(dot)
if sign < 0:
minus = OldTex("-")
syms.add(minus)
cross_entry = VGroup(minus, e2.target, dot, e1.target)
cross_entry.arrange()
entry_dicts[a]["negative"] = cross_entry
else:
cross_entry = VGroup(e1.target, dot, e2.target)
cross_entry.arrange()
entry_dicts[a]["positive"] = cross_entry
cross_entry.arrange()
movement_sets.append([
e1, e1.target,
e2, e2.target,
syms
])
result = Matrix([
VGroup(
entry_dict["positive"],
entry_dict["negative"],
).arrange()
for entry_dict in entry_dicts
])
equals = OldTex("=").next_to(cross_product)
result.next_to(equals)
self.play(FadeIn(cross_product))
self.play(
Write(equals),
Write(result.get_brackets())
)
self.wait()
movement_sets[2], movement_sets[3] = movement_sets[3], movement_sets[2]
for e1, e1_target, e2, e2_target, syms in movement_sets:
e1.save_state()
e2.save_state()
self.play(
e1.scale, 1.5,
e2.scale, 1.5,
)
self.play(
Transform(e1.copy(), e1_target),
Transform(e2.copy(), e2_target),
Write(syms),
e1.restore,
e2.restore,
path_arc = -np.pi/2
)
self.wait()
class ThisGetsWeird(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"This gets weird...",
target_mode = "sassy"
)
self.random_blink(2)
class DeterminantTrick(Scene):
def construct(self):
v_terms, w_terms = [
["%s_%d"%(s, d) for d in range(1, 4)]
for s in ("v", "w")
]
v = Matrix(v_terms)
w = Matrix(w_terms)
v.set_color(V_COLOR)
w.set_color(W_COLOR)
matrix = Matrix(np.array([
[
OldTex("\\hat{%s}"%s)
for s in ("\\imath", "\\jmath", "k")
],
list(v.get_entries().copy()),
list(w.get_entries().copy()),
]).T)
colors = [X_COLOR, Y_COLOR, Z_COLOR]
col1, col2, col3 = it.starmap(Group, matrix.get_mob_matrix().T)
i, j, k = col1
v1, v2, v3 = col2
w1, w2, w3 = col3
##Really should fix Matrix mobject...
j.shift(0.1*UP)
k.shift(0.2*UP)
VGroup(v2, w2).shift(0.1*DOWN)
VGroup(v3, w3).shift(0.2*DOWN)
##
for color, entry in zip(colors, col1):
entry.set_color(color)
det_text = get_det_text(matrix)
equals = OldTex("=")
equation = VGroup(
v, OldTex("\\times"), w,
equals, VGroup(det_text, matrix)
)
equation.arrange()
self.add(*equation[:-2])
self.wait()
self.play(Write(matrix.get_brackets()))
for col, vect in (col2, v), (col3, w):
col.save_state()
col.move_to(vect.get_entries())
self.play(
col.restore,
path_arc = -np.pi/2,
)
for entry in col1:
self.play(Write(entry))
self.wait()
self.play(*list(map(Write, [equals, det_text])))
self.wait()
disclaimer = OldTexText("$^*$ See ``Note on conventions'' in description")
disclaimer.scale(0.7)
disclaimer.set_color(RED)
disclaimer.next_to(equation, DOWN)
self.play(FadeIn(disclaimer))
self.wait()
self.play(FadeOut(disclaimer))
circle = Circle()
circle.stretch_to_fit_height(col1.get_height()+1)
circle.stretch_to_fit_width(col1.get_width()+1)
circle.move_to(col1)
randy = Randolph()
randy.scale(0.9)
randy.to_corner()
randy.to_edge(DOWN, buff = SMALL_BUFF)
self.play(FadeIn(randy))
self.play(
randy.change_mode, "confused",
ShowCreation(circle)
)
self.play(randy.look, RIGHT)
self.wait()
self.play(FadeOut(circle))
self.play(
equation.to_corner, UP+LEFT,
ApplyFunction(
lambda r : r.change_mode("plain").look(UP+RIGHT),
randy
)
)
quints = [
(i, v2, w3, v3, w2),
(j, v3, w1, v1, w3),
(k, v1, w2, v2, w1),
]
last_mob = None
paren_sets = []
for quint in quints:
for mob in quint:
mob.t = mob.copy()
mob.save_state()
basis = quint[0]
basis.t.scale(1/0.8)
lp, minus, rp = syms = VGroup(*list(map(Tex, "(-)")))
term = VGroup(
basis.t, lp,
quint[1].t, quint[2].t, minus,
quint[3].t, quint[4].t, rp
)
term.arrange()
if last_mob:
plus = OldTex("+")
syms.add(plus)
plus.next_to(term, LEFT, buff = MED_SMALL_BUFF/2)
term.add_to_back(plus)
term.next_to(last_mob, RIGHT, buff = MED_SMALL_BUFF/2)
else:
term.next_to(equation, DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT)
last_mob = term
self.play(*it.chain(*[
[mob.scale, 1.2]
for mob in quint
]))
self.wait()
self.play(*[
Transform(mob.copy(), mob.t)
for mob in quint
] + [
mob.restore for mob in quint
] + [
Write(syms)
],
run_time = 2
)
self.wait()
paren_sets.append(VGroup(lp, rp))
self.wait()
self.play(randy.change_mode, "pondering")
for parens in paren_sets:
brace = Brace(parens)
text = brace.get_text("Some number")
text.set_width(brace.get_width())
self.play(
GrowFromCenter(brace),
Write(text, run_time = 2)
)
self.wait()
class ThereIsAReason(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"\\centering Sure, it's a \\\\", "notational", "trick",
)
self.random_blink(2)
words = OldTexText(
"\\centering but there is a\\\\",
"reason", "for doing it"
)
words.set_color_by_tex("reason", YELLOW)
self.teacher_says(words, target_mode = "surprised")
self.play_student_changes(
"raise_right_hand", "confused", "raise_left_hand"
)
self.random_blink()
class RememberDuality(TeacherStudentsScene):
def construct(self):
words = OldTexText("Remember ", "duality", "?", arg_separator = "")
words[1].set_color_by_gradient(BLUE, YELLOW)
self.teacher_says(words, target_mode = "sassy")
self.random_blink(2)
class NextVideo(Scene):
def construct(self):
title = OldTexText("""
Next video: Cross products in the
light of linear transformations
""")
title.set_height(1.2)
title.to_edge(UP, buff = MED_SMALL_BUFF/2)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
class CrossAndDualWords(Scene):
def construct(self):
v_tex, w_tex, p_tex = get_vect_tex(*"vwp")
vector_word = OldTexText("Vector:")
transform_word = OldTexText("Dual transform:")
cross = OldTex(
p_tex, "=", v_tex, "\\times", w_tex
)
for tex, color in zip([v_tex, w_tex, p_tex], [U_COLOR, W_COLOR, P_COLOR]):
cross.set_color_by_tex(tex, color)
input_array_tex = matrix_to_tex_string(["x", "y", "z"])
func = OldTex("L\\left(%s\\right) = "%input_array_tex)
matrix = Matrix(np.array([
["x", "y", "z"],
["v_1", "v_2", "v_3"],
["w_1", "w_2", "w_3"],
]).T)
matrix.set_column_colors(WHITE, U_COLOR, W_COLOR)
det_text = get_det_text(matrix, background_rect = False)
det_text.add(matrix)
dot_with_cross = OldTex(
"%s \\cdot ( "%input_array_tex,
v_tex, "\\times", w_tex, ")"
)
dot_with_cross.set_color_by_tex(v_tex, U_COLOR)
dot_with_cross.set_color_by_tex(w_tex, W_COLOR)
transform = VGroup(func, det_text)
transform.arrange()
VGroup(transform, dot_with_cross).scale(0.7)
VGroup(vector_word, cross).arrange(
RIGHT, buff = MED_SMALL_BUFF
).center().shift(LEFT).to_edge(UP)
transform_word.next_to(vector_word, DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT)
transform.next_to(transform_word, DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT)
dot_with_cross.next_to(func, RIGHT)
self.add(vector_word)
self.play(Write(cross))
self.wait()
self.play(FadeIn(transform_word))
self.play(Write(transform))
self.wait()
self.play(Transform(det_text, dot_with_cross))
self.wait()
|
|
from manim_imports_ext import *
from ka_playgrounds.circuits import Resistor, Source, LongResistor
class OpeningQuote(Scene):
def construct(self):
words = OldTexText(
"``On this quiz, I asked you to find the determinant of a",
"2x3 matrix.",
"Some of you, to my great amusement, actually tried to do this.''"
)
words.set_width(FRAME_WIDTH - 2)
words.to_edge(UP)
words[1].set_color(GREEN)
author = OldTexText("-(Via mathprofessorquotes.com, no name listed)")
author.set_color(YELLOW)
author.scale(0.7)
author.next_to(words, DOWN, buff = 0.5)
self.play(FadeIn(words))
self.wait(2)
self.play(Write(author, run_time = 3))
self.wait()
class AnotherFootnote(TeacherStudentsScene):
def construct(self):
self.teacher.look(LEFT)
self.teacher_says(
"More footnotes!",
target_mode = "surprised",
run_time = 1
)
self.random_blink(2)
class ColumnsRepresentBasisVectors(Scene):
def construct(self):
matrix = Matrix([[3, 1], [4, 1], [5, 9]])
i_hat_words, j_hat_words = [
OldTexText("Where $\\hat{\\%smath}$ lands"%char)
for char in ("i", "j")
]
i_hat_words.set_color(X_COLOR)
i_hat_words.next_to(ORIGIN, LEFT).to_edge(UP)
j_hat_words.set_color(Y_COLOR)
j_hat_words.next_to(ORIGIN, RIGHT).to_edge(UP)
question = OldTexText("How to interpret?")
question.next_to(matrix, UP)
question.set_color(YELLOW)
self.add(matrix)
self.play(Write(question, run_time = 2))
self.wait()
self.play(FadeOut(question))
for i, words in enumerate([i_hat_words, j_hat_words]):
arrow = Arrow(
words.get_bottom(),
matrix.get_mob_matrix()[0,i].get_top(),
color = words.get_color()
)
self.play(
Write(words, run_time = 1),
ShowCreation(arrow),
*[
ApplyMethod(m.set_color, words.get_color())
for m in matrix.get_mob_matrix()[:,i]
]
)
self.wait(2)
self.put_in_thought_bubble()
def put_in_thought_bubble(self):
everything = VMobject(*self.get_mobjects())
randy = Randolph().to_corner()
bubble = randy.get_bubble()
self.play(FadeIn(randy))
self.play(
ApplyFunction(
lambda m : bubble.position_mobject_inside(
m.set_height(2.5)
),
everything
),
ShowCreation(bubble),
randy.change_mode, "pondering"
)
self.play(Blink(randy))
self.wait()
self.play(randy.change_mode, "surprised")
self.wait()
class Symbolic2To3DTransform(Scene):
def construct(self):
func = OldTex("L(", "\\vec{\\textbf{v}}", ")")
input_array = Matrix([2, 7])
input_array.set_color(YELLOW)
in_arrow = Arrow(LEFT, RIGHT, color = input_array.get_color())
func[1].set_color(input_array.get_color())
output_array = Matrix([1, 8, 2])
output_array.set_color(PINK)
out_arrow = Arrow(LEFT, RIGHT, color = output_array.get_color())
VMobject(
input_array, in_arrow, func, out_arrow, output_array
).arrange(RIGHT, buff = SMALL_BUFF)
input_brace = Brace(input_array, DOWN)
input_words = input_brace.get_text("2d input")
output_brace = Brace(output_array, UP)
output_words = output_brace.get_text("3d output")
input_words.set_color(input_array.get_color())
output_words.set_color(output_array.get_color())
self.add(func, input_array)
self.play(
GrowFromCenter(input_brace),
Write(input_words)
)
mover = input_array.copy()
self.play(
Transform(mover, Dot().move_to(func)),
ShowCreation(in_arrow),
rate_func = rush_into
)
self.play(
Transform(mover, output_array),
ShowCreation(out_arrow),
rate_func = rush_from
)
self.play(
GrowFromCenter(output_brace),
Write(output_words)
)
self.wait()
class PlaneStartState(LinearTransformationScene):
def construct(self):
self.add_title("Input space")
labels = self.get_basis_vector_labels()
self.play(*list(map(Write, labels)))
self.wait()
class OutputIn3dWords(Scene):
def construct(self):
words = OldTexText("Output in 3d")
words.scale(1.5)
self.play(Write(words))
self.wait()
class OutputIn3d(Scene):
pass
class ShowSideBySide2dTo3d(Scene):
pass
class AnimationLaziness(Scene):
def construct(self):
self.add(OldTexText("But there is some animation laziness..."))
class DescribeColumnsInSpecificTransformation(Scene):
def construct(self):
matrix = Matrix([
[2, 0],
[-1, 1],
[-2, 1],
])
matrix.set_column_colors(X_COLOR, Y_COLOR)
mob_matrix = matrix.get_mob_matrix()
i_col, j_col = [VMobject(*mob_matrix[:,i]) for i in (0, 1)]
for col, char, vect in zip([i_col, j_col], ["i", "j"], [UP, DOWN]):
color = col[0].get_color()
col.words = OldTexText("Where $\\hat\\%smath$ lands"%char)
col.words.next_to(matrix, vect, buff = LARGE_BUFF)
col.words.set_color(color)
col.arrow = Arrow(
col.words.get_edge_center(-vect),
col.get_edge_center(vect),
color = color
)
self.play(Write(matrix.get_brackets()))
self.wait()
for col in i_col, j_col:
self.play(
Write(col),
ShowCreation(col.arrow),
Write(col.words, run_time = 1)
)
self.wait()
class CountRowsAndColumns(Scene):
def construct(self):
matrix = Matrix([
[2, 0],
[-1, 1],
[-2, 1],
])
matrix.set_column_colors(X_COLOR, Y_COLOR)
rows_brace = Brace(matrix, LEFT)
rows_words = rows_brace.get_text("3", "rows")
rows_words.set_color(PINK)
cols_brace = Brace(matrix, UP)
cols_words = cols_brace.get_text("2", "columns")
cols_words.set_color(TEAL)
title = OldTex("3", "\\times", "2", "\\text{ matrix}")
title.to_edge(UP)
self.add(matrix)
self.play(
GrowFromCenter(rows_brace),
Write(rows_words, run_time = 2)
)
self.play(
GrowFromCenter(cols_brace),
Write(cols_words, run_time = 2)
)
self.wait()
self.play(
rows_words[0].copy().move_to, title[0],
cols_words[0].copy().move_to, title[2],
Write(VMobject(title[1], title[3]))
)
self.wait()
class WriteColumnSpaceDefinition(Scene):
def construct(self):
matrix = Matrix([
[2, 0],
[-1, 1],
[-2, 1],
])
matrix.set_column_colors(X_COLOR, Y_COLOR)
brace = Brace(matrix)
words = VMobject(
OldTexText("Span", "of columns"),
OldTex("\\Updownarrow"),
OldTexText("``Column space''")
)
words.arrange(DOWN, buff = 0.1)
words.next_to(brace, DOWN)
words[0][0].set_color(PINK)
words[2].set_color(TEAL)
words[0].add_background_rectangle()
words[2].add_background_rectangle()
VMobject(matrix, brace, words).center()
self.add(matrix)
self.play(
GrowFromCenter(brace),
Write(words, run_time = 2)
)
self.wait()
class MatrixInTheWild(Scene):
def construct(self):
randy = Randolph(color = PINK)
randy.look(LEFT)
randy.to_corner()
matrix = Matrix([
[3, 1],
[4, 1],
[5, 9],
])
matrix.next_to(randy, RIGHT, buff = LARGE_BUFF, aligned_edge = DOWN)
bubble = randy.get_bubble(height = 4)
bubble.make_green_screen()
VMobject(randy, bubble, matrix).to_corner(UP+LEFT, buff = MED_SMALL_BUFF)
self.add(randy)
self.play(Write(matrix))
self.play(randy.look, RIGHT, run_time = 0.5)
self.play(randy.change_mode, "sassy")
self.play(Blink(randy))
self.play(
ShowCreation(bubble),
randy.change_mode, "pondering"
)
# self.play(matrix.set_column_colors, X_COLOR, Y_COLOR)
self.wait()
for x in range(3):
self.play(Blink(randy))
self.wait(2)
new_matrix = Matrix([[3, 1, 4], [1, 5, 9]])
new_matrix.move_to(matrix, aligned_edge = UP+LEFT)
self.play(
Transform(matrix, new_matrix),
FadeOut(bubble)
)
self.remove(matrix)
matrix = new_matrix
self.add(matrix)
self.play(randy.look, DOWN+RIGHT, run_time = 0.5)
self.play(randy.change_mode, "confused")
self.wait()
self.play(Blink(randy))
self.wait()
top_brace = Brace(matrix, UP)
top_words = top_brace.get_text("3 basis vectors")
top_words.set_submobject_colors_by_gradient(GREEN, RED, BLUE)
side_brace = Brace(matrix, RIGHT)
side_words = side_brace.get_text("""
2 coordinates for
each landing spots
""")
side_words.set_color(YELLOW)
self.play(
GrowFromCenter(top_brace),
Write(top_words),
matrix.set_column_colors, X_COLOR, Y_COLOR, Z_COLOR
)
self.play(randy.change_mode, "happy")
self.play(
GrowFromCenter(side_brace),
Write(side_words, run_time = 2)
)
self.play(Blink(randy))
self.wait()
class ThreeDToTwoDInput(Scene):
pass
class ThreeDToTwoDInputWords(Scene):
def construct(self):
words = OldTexText("3d input")
words.scale(2)
self.play(Write(words))
self.wait()
class ThreeDToTwoDOutput(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"foreground_plane_kwargs" : {
"color" : GREY,
"x_radius" : FRAME_X_RADIUS,
"y_radius" : FRAME_Y_RADIUS,
"secondary_line_ratio" : 0
},
}
def construct(self):
title = OldTexText("Output in 2d")
title.to_edge(UP, buff = SMALL_BUFF)
subwords = OldTexText("""
(only showing basis vectors,
full 3d grid would be a mess)
""")
subwords.scale(0.75)
subwords.next_to(title, DOWN)
for words in title, subwords:
words.add_background_rectangle()
self.add(title)
i, j, k = it.starmap(self.add_vector, [
([3, 1], X_COLOR),
([1, 2], Y_COLOR),
([-2, -2], Z_COLOR)
])
pairs = [
(i, "L(\\hat\\imath)"),
(j, "L(\\hat\\jmath)"),
(k, "L(\\hat k)")
]
for v, tex in pairs:
self.label_vector(v, tex)
self.play(Write(subwords))
self.wait()
class ThreeDToTwoDSideBySide(Scene):
pass
class Symbolic2To1DTransform(Scene):
def construct(self):
func = OldTex("L(", "\\vec{\\textbf{v}}", ")")
input_array = Matrix([2, 7])
input_array.set_color(YELLOW)
in_arrow = Arrow(LEFT, RIGHT, color = input_array.get_color())
func[1].set_color(input_array.get_color())
output_array = Matrix([1.8])
output_array.set_color(PINK)
out_arrow = Arrow(LEFT, RIGHT, color = output_array.get_color())
VMobject(
input_array, in_arrow, func, out_arrow, output_array
).arrange(RIGHT, buff = SMALL_BUFF)
input_brace = Brace(input_array, DOWN)
input_words = input_brace.get_text("2d input")
output_brace = Brace(output_array, UP)
output_words = output_brace.get_text("1d output")
input_words.set_color(input_array.get_color())
output_words.set_color(output_array.get_color())
self.add(func, input_array)
self.play(
GrowFromCenter(input_brace),
Write(input_words)
)
mover = input_array.copy()
self.play(
Transform(mover, Dot().move_to(func)),
ShowCreation(in_arrow),
rate_func = rush_into,
run_time = 0.5
)
self.play(
Transform(mover, output_array),
ShowCreation(out_arrow),
rate_func = rush_from,
run_time = 0.5
)
self.play(
GrowFromCenter(output_brace),
Write(output_words)
)
self.wait()
class TwoDTo1DTransform(LinearTransformationScene):
CONFIG = {
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_X_RADIUS,
"y_radius" : FRAME_Y_RADIUS,
"secondary_line_ratio" : 1
},
"t_matrix" : [[1, 0], [2, 0]],
}
def construct(self):
line = NumberLine()
plane_words = OldTexText("2d space")
plane_words.next_to(self.j_hat, UP, buff = MED_SMALL_BUFF)
plane_words.add_background_rectangle()
line_words = OldTexText("1d space (number line)")
line_words.next_to(line, UP)
self.play(Write(plane_words))
self.wait()
self.remove(plane_words)
mobjects = self.get_mobjects()
self.play(
*list(map(FadeOut, mobjects)) + [ShowCreation(line)]
)
self.play(Write(line_words))
self.wait()
self.remove(line_words)
self.play(*list(map(FadeIn, mobjects)))
self.apply_transposed_matrix(self.t_matrix)
self.play(Write(VMobject(*line.get_number_mobjects())))
self.wait()
self.show_matrix()
def show_matrix(self):
for vect, char in zip([self.i_hat, self.j_hat], ["i", "j"]):
vect.words = OldTexText(
"$\\hat\\%smath$ lands on"%char,
str(int(vect.get_end()[0]))
)
direction = UP if vect is self.i_hat else DOWN
vect.words.next_to(vect.get_end(), direction, buff = LARGE_BUFF)
vect.words.set_color(vect.get_color())
matrix = Matrix([[1, 2]])
matrix_words = OldTexText("Transformation matrix: ")
matrix_group = VMobject(matrix_words, matrix)
matrix_group.arrange(buff = MED_SMALL_BUFF)
matrix_group.to_edge(UP)
entries = matrix.get_entries()
self.play(Write(matrix_words), Write(matrix.get_brackets()))
for i, vect in enumerate([self.i_hat, self.j_hat]):
self.play(vect.rotate, np.pi/12, rate_func = wiggle)
self.play(Write(vect.words))
self.wait()
self.play(vect.words[1].copy().move_to, entries[i])
self.wait()
class TwoDTo1DTransformWithDots(TwoDTo1DTransform):
def construct(self):
line = NumberLine()
self.add(line, *self.get_mobjects())
offset = LEFT+DOWN
vect = 2*RIGHT+UP
dots = VMobject(*[
Dot(offset + a*vect, radius = 0.075)
for a in np.linspace(-2, 3, 18)
])
dots.set_submobject_colors_by_gradient(YELLOW_B, YELLOW_C)
func = self.get_matrix_transformation(self.t_matrix)
new_dots = VMobject(*[
Dot(
func(dot.get_center()),
color = dot.get_color(),
radius = dot.radius
)
for dot in dots
])
words = OldTexText(
"Line of dots remains evenly spaced"
)
words.next_to(line, UP, buff = MED_SMALL_BUFF)
self.play(Write(dots))
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [Transform(dots, new_dots)]
)
self.play(Write(words))
self.wait()
class NextVideo(Scene):
def construct(self):
title = OldTexText("""
Next video: Dot products and duality
""")
title.set_width(FRAME_WIDTH - 2)
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
class DotProductPreview(VectorScene):
CONFIG = {
"v_coords" : [3, 1],
"w_coords" : [2, -1],
"v_color" : YELLOW,
"w_color" : MAROON_C,
}
def construct(self):
self.lock_in_faded_grid()
self.add_symbols()
self.add_vectors()
self.grow_number_line()
self.project_w()
self.show_scaling()
def add_symbols(self):
v = matrix_to_mobject(self.v_coords).set_color(self.v_color)
w = matrix_to_mobject(self.w_coords).set_color(self.w_color)
v.add_background_rectangle()
w.add_background_rectangle()
dot = OldTex("\\cdot")
eq = VMobject(v, dot, w)
eq.arrange(RIGHT, buff = SMALL_BUFF)
eq.to_corner(UP+LEFT)
self.play(Write(eq), run_time = 1)
def add_vectors(self):
self.v = Vector(self.v_coords, color = self.v_color)
self.w = Vector(self.w_coords, color = self.w_color)
self.play(ShowCreation(self.v))
self.play(ShowCreation(self.w))
def grow_number_line(self):
line = NumberLine(stroke_width = 2).add_numbers()
line.rotate(self.v.get_angle())
self.play(Write(line), Animation(self.v))
self.play(
line.set_color, self.v.get_color(),
Animation(self.v),
rate_func = there_and_back
)
self.wait()
def project_w(self):
dot_product = np.dot(self.v.get_end(), self.w.get_end())
v_norm, w_norm = [
get_norm(vect.get_end())
for vect in (self.v, self.w)
]
projected_w = Vector(
self.v.get_end()*dot_product/(v_norm**2),
color = self.w.get_color()
)
projection_line = Line(
self.w.get_end(), projected_w.get_end(),
color = GREY
)
self.play(ShowCreation(projection_line))
self.add(self.w.copy().fade())
self.play(Transform(self.w, projected_w))
self.wait()
def show_scaling(self):
dot_product = np.dot(self.v.get_end(), self.w.get_end())
start_brace, interim_brace, final_brace = braces = [
Brace(
Line(ORIGIN, norm*RIGHT),
UP
)
for norm in (1, self.v.get_length(), dot_product)
]
length_texs = list(it.starmap(Tex, [
("1",),
("\\text{Scale by }", "||\\vec{\\textbf{v}}||",),
("\\text{Length of}", "\\text{ scaled projection}",),
]))
length_texs[1][1].set_color(self.v_color)
length_texs[2][1].set_color(self.w_color)
for brace, tex_mob in zip(braces, length_texs):
tex_mob.add_background_rectangle()
brace.put_at_tip(tex_mob, buff = SMALL_BUFF)
brace.add(tex_mob)
brace.rotate(self.v.get_angle())
new_w = self.w.copy().scale(self.v.get_length())
self.play(Write(start_brace))
self.wait()
self.play(
Transform(start_brace, interim_brace),
Transform(self.w, new_w)
)
self.wait()
self.play(
Transform(start_brace, final_brace)
)
self.wait()
|
|
from manim_imports_ext import *
def curvy_squish(point):
x, y, z = point
return (x+np.cos(y))*RIGHT + (y+np.sin(x))*UP
class OpeningQuote(Scene):
def construct(self):
words = OldTexText([
"Unfortunately, no one can be told what the",
"Matrix",
"is. You have to",
"see it for yourself.",
])
words.set_width(FRAME_WIDTH - 2)
words.to_edge(UP)
words.split()[1].set_color(GREEN)
words.split()[3].set_color(BLUE)
author = OldTexText("-Morpheus")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = 0.5)
comment = OldTexText("""
(Surprisingly apt words on the importance
of understanding matrix operations visually.)
""")
comment.next_to(author, DOWN, buff = 1)
self.play(FadeIn(words))
self.wait(3)
self.play(Write(author, run_time = 3))
self.wait()
self.play(Write(comment))
self.wait()
class Introduction(TeacherStudentsScene):
def construct(self):
title = OldTexText(["Matrices as", "Linear transformations"])
title.to_edge(UP)
title.set_color(YELLOW)
linear_transformations = title.split()[1]
self.add(*title.split())
self.setup()
self.teacher_says("""
Listen up folks, this one is
particularly important
""", height = 3)
self.random_blink(2)
self.teacher_thinks("", height = 3)
self.remove(linear_transformations)
everything = VMobject(*self.get_mobjects())
def spread_out(p):
p = p + 2*DOWN
return (FRAME_X_RADIUS+FRAME_Y_RADIUS)*p/get_norm(p)
self.play(
ApplyPointwiseFunction(spread_out, everything),
ApplyFunction(
lambda m : m.center().to_edge(UP),
linear_transformations
)
)
class MatrixVectorMechanicalMultiplication(NumericalMatrixMultiplication):
CONFIG = {
"left_matrix" : [[1, -3], [2, 4]],
"right_matrix" : [[5], [7]]
}
class PostponeHigherDimensions(TeacherStudentsScene):
def construct(self):
self.setup()
self.student_says("What about 3 dimensions?")
self.random_blink()
self.teacher_says("All in due time,\\\\ young padawan")
self.random_blink()
class DescribeTransformation(Scene):
def construct(self):
self.add_title()
self.show_function()
def add_title(self):
title = OldTexText(["Linear", "transformation"])
title.to_edge(UP)
linear, transformation = title.split()
brace = Brace(transformation, DOWN)
function = OldTexText("function").next_to(brace, DOWN)
function.set_color(YELLOW)
self.play(Write(title))
self.wait()
self.play(
GrowFromCenter(brace),
Write(function),
ApplyMethod(linear.fade)
)
def show_function(self):
f_of_x = OldTex("f(x)")
L_of_v = OldTex("L(\\vec{\\textbf{v}})")
nums = [5, 2, -3]
num_inputs = VMobject(*list(map(Tex, list(map(str, nums)))))
num_outputs = VMobject(*[
OldTex(str(num**2))
for num in nums
])
for mob in num_inputs, num_outputs:
mob.arrange(DOWN, buff = 1)
num_inputs.next_to(f_of_x, LEFT, buff = 1)
num_outputs.next_to(f_of_x, RIGHT, buff = 1)
f_point = VectorizedPoint(f_of_x.get_center())
input_vect = Matrix([5, 7])
input_vect.next_to(L_of_v, LEFT, buff = 1)
output_vect = Matrix([2, -3])
output_vect.next_to(L_of_v, RIGHT, buff = 1)
vector_input_words = OldTexText("Vector input")
vector_input_words.set_color(MAROON_C)
vector_input_words.next_to(input_vect, DOWN)
vector_output_words = OldTexText("Vector output")
vector_output_words.set_color(BLUE)
vector_output_words.next_to(output_vect, DOWN)
self.play(Write(f_of_x, run_time = 1))
self.play(Write(num_inputs, run_time = 2))
self.wait()
for mob in f_point, num_outputs:
self.play(Transform(
num_inputs, mob,
lag_ratio = 0.5
))
self.wait()
self.play(
FadeOut(num_inputs),
Transform(f_of_x, L_of_v)
)
self.play(
Write(input_vect),
Write(vector_input_words)
)
self.wait()
for mob in f_point, output_vect:
self.play(Transform(
input_vect, mob,
lag_ratio = 0.5
))
self.play(Write(vector_output_words))
self.wait()
class WhyConfuseWithTerminology(TeacherStudentsScene):
def construct(self):
self.setup()
self.student_says("Why confuse us with \\\\ redundant terminology?")
other_students = [self.get_students()[i] for i in (0, 2)]
self.play(*[
ApplyMethod(student.change_mode, "confused")
for student in other_students
])
self.random_blink()
self.wait()
statement = OldTexText([
"The word",
"``transformation''",
"suggests \\\\ that you think using",
"movement",
])
statement.split()[1].set_color(BLUE)
statement.split()[-1].set_color(YELLOW)
self.teacher_says(statement, width = 10)
self.play(*[
ApplyMethod(student.change_mode, "happy")
for student in other_students
])
self.random_blink()
self.wait()
class ThinkinfOfFunctionsAsGraphs(VectorScene):
def construct(self):
axes = self.add_axes()
graph = FunctionGraph(lambda x : x**2, x_min = -2, x_max = 2)
name = OldTex("f(x) = x^2")
name.next_to(graph, RIGHT).to_edge(UP)
point = Dot(graph.point_from_proportion(0.8))
point_label = OldTex("(2, f(2))")
point_label.next_to(point.get_center(), DOWN+RIGHT, buff = 0.1)
self.play(ShowCreation(graph))
self.play(Write(name, run_time = 1))
self.play(
ShowCreation(point),
Write(point_label),
run_time = 1
)
self.wait()
def collapse_func(p):
return np.dot(p, [RIGHT, RIGHT, OUT]) + (FRAME_Y_RADIUS+1)*DOWN
self.play(
ApplyPointwiseFunction(collapse_func, axes),
ApplyPointwiseFunction(collapse_func, graph),
ApplyMethod(point.shift, 10*DOWN),
ApplyMethod(point_label.shift, 10*DOWN),
ApplyPointwiseFunction(collapse_func, name),
run_time = 2
)
self.clear()
words = OldTexText(["Instead think about", "\\emph{movement}"])
words.split()[-1].set_color(YELLOW)
self.play(Write(words))
self.wait()
class TransformJustOneVector(VectorScene):
def construct(self):
self.lock_in_faded_grid()
v1_coords = [-3, 1]
t_matrix = [[0, -1], [2, -1]]
v1 = Vector(v1_coords)
v2 = Vector(
np.dot(np.array(t_matrix).transpose(), v1_coords),
color = PINK
)
for v, word in (v1, "Input"), (v2, "Output"):
v.label = OldTexText("%s vector"%word)
v.label.next_to(v.get_end(), UP)
v.label.set_color(v.get_color())
self.play(ShowCreation(v))
self.play(Write(v.label))
self.wait()
self.remove(v2)
self.play(
Transform(
v1.copy(), v2,
path_arc = -np.pi/2, run_time = 3
),
ApplyMethod(v1.fade)
)
self.wait()
class TransformManyVectors(LinearTransformationScene):
CONFIG = {
"transposed_matrix" : [[2, 1], [1, 2]],
"use_dots" : False,
}
def construct(self):
self.lock_in_faded_grid()
vectors = VMobject(*[
Vector([x, y])
for x in np.arange(-int(FRAME_X_RADIUS)+0.5, int(FRAME_X_RADIUS)+0.5)
for y in np.arange(-int(FRAME_Y_RADIUS)+0.5, int(FRAME_Y_RADIUS)+0.5)
])
vectors.set_submobject_colors_by_gradient(PINK, YELLOW)
t_matrix = self.transposed_matrix
transformed_vectors = VMobject(*[
Vector(
np.dot(np.array(t_matrix).transpose(), v.get_end()[:2]),
color = v.get_color()
)
for v in vectors.split()
])
self.play(ShowCreation(vectors, lag_ratio = 0.5))
self.wait()
if self.use_dots:
self.play(Transform(
vectors, self.vectors_to_dots(vectors),
run_time = 3,
lag_ratio = 0.5
))
transformed_vectors = self.vectors_to_dots(transformed_vectors)
self.wait()
self.play(Transform(
vectors, transformed_vectors,
run_time = 3,
path_arc = -np.pi/2
))
self.wait()
if self.use_dots:
self.play(Transform(
vectors, self.dots_to_vectors(vectors),
run_time = 2,
lag_ratio = 0.5
))
self.wait()
def vectors_to_dots(self, vectors):
return VMobject(*[
Dot(v.get_end(), color = v.get_color())
for v in vectors.split()
])
def dots_to_vectors(self, dots):
return VMobject(*[
Vector(dot.get_center(), color = dot.get_color())
for dot in dots.split()
])
class TransformManyVectorsAsPoints(TransformManyVectors):
CONFIG = {
"use_dots" : True
}
class TransformInfiniteGrid(LinearTransformationScene):
CONFIG = {
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_HEIGHT,
},
"show_basis_vectors" : False
}
def construct(self):
self.setup()
self.play(ShowCreation(
self.plane, run_time = 3, lag_ratio = 0.5
))
self.wait()
self.apply_transposed_matrix([[2, 1], [1, 2]])
self.wait()
class TransformInfiniteGridWithBackground(TransformInfiniteGrid):
CONFIG = {
"include_background_plane" : True,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_HEIGHT,
"secondary_line_ratio" : 0
},
}
class ApplyComplexFunction(LinearTransformationScene):
CONFIG = {
"function" : lambda z : 0.5*z**2,
"show_basis_vectors" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_X_RADIUS,
"y_radius" : FRAME_Y_RADIUS,
"secondary_line_ratio" : 0
},
}
def construct(self):
self.setup()
self.plane.prepare_for_nonlinear_transform(100)
self.wait()
self.play(ApplyMethod(
self.plane.apply_complex_function, self.function,
run_time = 5,
path_arc = np.pi/2
))
self.wait()
class ExponentialTransformation(ApplyComplexFunction):
CONFIG = {
"function" : np.exp,
}
class CrazyTransformation(ApplyComplexFunction):
CONFIG = {
"function" : lambda z : np.sin(z)**2 + np.sinh(z)
}
class LookToWordLinear(Scene):
def construct(self):
title = OldTexText(["Linear ", "transformations"])
title.to_edge(UP)
faded_title = title.copy().fade()
linear, transformation = title.split()
faded_linear, faded_transformation = faded_title.split()
linear_brace = Brace(linear, DOWN)
transformation_brace = Brace(transformation, DOWN)
function = OldTexText("function")
function.set_color(YELLOW)
function.next_to(transformation_brace, DOWN)
new_sub_word = OldTexText("What does this mean?")
new_sub_word.set_color(BLUE)
new_sub_word.next_to(linear_brace, DOWN)
self.add(
faded_linear, transformation,
transformation_brace, function
)
self.wait()
self.play(
Transform(faded_linear, linear),
Transform(transformation, faded_transformation),
Transform(transformation_brace, linear_brace),
Transform(function, new_sub_word),
lag_ratio = 0.5
)
self.wait()
class IntroduceLinearTransformations(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
}
def construct(self):
self.setup()
self.wait()
self.apply_transposed_matrix([[2, 1], [1, 2]])
self.wait()
lines_rule = OldTexText("Lines remain lines")
lines_rule.shift(2*UP).to_edge(LEFT)
origin_rule = OldTexText("Origin remains fixed")
origin_rule.shift(2*UP).to_edge(RIGHT)
arrow = Arrow(origin_rule, ORIGIN)
dot = Dot(ORIGIN, radius = 0.1, color = RED)
for rule in lines_rule, origin_rule:
rule.add_background_rectangle()
self.play(
Write(lines_rule, run_time = 2),
)
self.wait()
self.play(
Write(origin_rule, run_time = 2),
ShowCreation(arrow),
GrowFromCenter(dot)
)
self.wait()
class ToThePedants(Scene):
def construct(self):
words = OldTexText([
"To the pedants:\\\\",
"""
Yeah yeah, I know that's not the formal definition
for linear transformations, as seen in textbooks,
but I'm building visual intuition here, and what
I've said is equivalent to the formal definition
(which I'll get to later in the series).
"""])
words.split()[0].set_color(RED)
words.to_edge(UP)
self.add(words)
self.wait()
class SimpleLinearTransformationScene(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"transposed_matrix" : [[2, 1], [1, 2]]
}
def construct(self):
self.setup()
self.wait()
self.apply_transposed_matrix(self.transposed_matrix)
self.wait()
class SimpleNonlinearTransformationScene(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"words" : "Not linear: some lines get curved"
}
def construct(self):
self.setup()
self.wait()
self.apply_nonlinear_transformation(self.func)
words = OldTexText(self.words)
words.to_corner(UP+RIGHT)
words.set_color(RED)
words.add_background_rectangle()
self.play(Write(words))
self.wait()
def func(self, point):
return curvy_squish(point)
class MovingOrigin(SimpleNonlinearTransformationScene):
CONFIG = {
"words" : "Not linear: Origin moves"
}
def setup(self):
LinearTransformationScene.setup(self)
dot = Dot(ORIGIN, color = RED)
self.add_transformable_mobject(dot)
def func(self, point):
matrix_transform = self.get_matrix_transformation([[2, 0], [1, 1]])
return matrix_transform(point) + 2*UP+3*LEFT
class SneakyNonlinearTransformation(SimpleNonlinearTransformationScene):
CONFIG = {
"words" : "\\dots"
}
def func(self, point):
x, y, z = point
new_x = np.sign(x)*FRAME_X_RADIUS*smooth(abs(x) / FRAME_X_RADIUS)
new_y = np.sign(y)*FRAME_Y_RADIUS*smooth(abs(y) / FRAME_Y_RADIUS)
return [new_x, new_y, 0]
class SneakyNonlinearTransformationExplained(SneakyNonlinearTransformation):
CONFIG = {
"words" : "Not linear: diagonal lines get curved"
}
def setup(self):
LinearTransformationScene.setup(self)
diag = Line(
FRAME_Y_RADIUS*LEFT+FRAME_Y_RADIUS*DOWN,
FRAME_Y_RADIUS*RIGHT + FRAME_Y_RADIUS*UP
)
diag.insert_n_curves(20)
diag.make_smooth()
diag.set_color(YELLOW)
self.play(ShowCreation(diag))
self.add_transformable_mobject(diag)
class GridLinesRemainParallel(SimpleLinearTransformationScene):
CONFIG = {
"transposed_matrix" : [
[3, 0],
[1, 2]
]
}
def construct(self):
SimpleLinearTransformationScene.construct(self)
text = OldTexText([
"Grid lines remain",
"parallel",
"and",
"evenly spaced",
])
glr, p, a, es = text.split()
p.set_color(YELLOW)
es.set_color(GREEN)
text.add_background_rectangle()
text.shift(-text.get_bottom())
self.play(Write(text))
self.wait()
class Rotation(SimpleLinearTransformationScene):
CONFIG = {
"angle" : np.pi/3,
}
def construct(self):
self.transposed_matrix = [
[np.cos(self.angle), np.sin(self.angle)],
[-np.sin(self.angle), np.cos(self.angle)]
]
SimpleLinearTransformationScene.construct(self)
class YetAnotherLinearTransformation(SimpleLinearTransformationScene):
CONFIG = {
"transposed_matrix" : [
[-1, 1],
[3, 2],
]
}
def construct(self):
SimpleLinearTransformationScene.construct(self)
words = OldTexText("""
How would you describe
one of these numerically?
"""
)
words.add_background_rectangle()
words.to_edge(UP)
words.set_color(GREEN)
formula = OldTex([
matrix_to_tex_string(["x_\\text{in}", "y_\\text{in}"]),
"\\rightarrow ???? \\rightarrow",
matrix_to_tex_string(["x_\\text{out}", "y_{\\text{out}}"])
])
formula.add_background_rectangle()
self.play(Write(words))
self.wait()
self.play(
ApplyMethod(self.plane.fade, 0.7),
ApplyMethod(self.background_plane.fade, 0.7),
Write(formula, run_time = 2),
Animation(words)
)
self.wait()
class FollowIHatJHat(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False
}
def construct(self):
self.setup()
i_hat = self.add_vector([1, 0], color = X_COLOR)
i_label = self.label_vector(
i_hat, "\\hat{\\imath}",
color = X_COLOR,
label_scale_factor = 1
)
j_hat = self.add_vector([0, 1], color = Y_COLOR)
j_label = self.label_vector(
j_hat, "\\hat{\\jmath}",
color = Y_COLOR,
label_scale_factor = 1
)
self.wait()
self.play(*list(map(FadeOut, [i_label, j_label])))
self.apply_transposed_matrix([[-1, 1], [-2, -1]])
self.wait()
class TrackBasisVectorsExample(LinearTransformationScene):
CONFIG = {
"transposed_matrix" : [[1, -2], [3, 0]],
"v_coords" : [-1, 2],
"v_coord_strings" : ["-1", "2"],
"result_coords_string" : """
=
\\left[ \\begin{array}{c}
-1(1) + 2(3) \\\\
-1(-2) + 2(0)
\\end{arary}\\right]
=
\\left[ \\begin{array}{c}
5 \\\\
2
\\end{arary}\\right]
"""
}
def construct(self):
self.setup()
self.label_bases()
self.introduce_vector()
self.wait()
self.apply_transposed_matrix(self.transposed_matrix)
self.wait()
self.show_linear_combination(clean_up = False)
self.write_linear_map_rule()
self.show_basis_vector_coords()
def label_bases(self):
triplets = [
(self.i_hat, "\\hat{\\imath}", X_COLOR),
(self.j_hat, "\\hat{\\jmath}", Y_COLOR),
]
label_mobs = []
for vect, label, color in triplets:
label_mobs.append(self.add_transformable_label(
vect, label, "\\text{Transformed } " + label,
color = color,
direction = "right",
))
self.i_label, self.j_label = label_mobs
def introduce_vector(self):
v = self.add_vector(self.v_coords)
coords = Matrix(self.v_coords)
coords.scale(VECTOR_LABEL_SCALE_FACTOR)
coords.next_to(v.get_end(), np.sign(self.v_coords[0])*RIGHT)
self.play(Write(coords, run_time = 1))
v_def = self.get_v_definition()
pre_def = VMobject(
VectorizedPoint(coords.get_center()),
VMobject(*[
mob.copy()
for mob in coords.get_mob_matrix().flatten()
])
)
self.play(Transform(
pre_def, v_def,
run_time = 2,
lag_ratio = 0
))
self.remove(pre_def)
self.add_foreground_mobject(v_def)
self.wait()
self.show_linear_combination()
self.remove(coords)
def show_linear_combination(self, clean_up = True):
i_hat_copy, j_hat_copy = [m.copy() for m in (self.i_hat, self.j_hat)]
self.play(ApplyFunction(
lambda m : m.scale(self.v_coords[0]).fade(0.3),
i_hat_copy
))
self.play(ApplyFunction(
lambda m : m.scale(self.v_coords[1]).fade(0.3),
j_hat_copy
))
self.play(ApplyMethod(j_hat_copy.shift, i_hat_copy.get_end()))
self.wait(2)
if clean_up:
self.play(FadeOut(i_hat_copy), FadeOut(j_hat_copy))
def get_v_definition(self):
v_def = OldTex([
"\\vec{\\textbf{v}}",
" = %s"%self.v_coord_strings[0],
"\\hat{\\imath}",
"+%s"%self.v_coord_strings[1],
"\\hat{\\jmath}",
])
v, equals_neg_1, i_hat, plus_2, j_hat = v_def.split()
v.set_color(YELLOW)
i_hat.set_color(X_COLOR)
j_hat.set_color(Y_COLOR)
v_def.add_background_rectangle()
v_def.to_corner(UP + LEFT)
self.v_def = v_def
return v_def
def write_linear_map_rule(self):
rule = OldTex([
"\\text{Transformed } \\vec{\\textbf{v}}",
" = %s"%self.v_coord_strings[0],
"(\\text{Transformed }\\hat{\\imath})",
"+%s"%self.v_coord_strings[1],
"(\\text{Transformed } \\hat{\\jmath})",
])
v, equals_neg_1, i_hat, plus_2, j_hat = rule.split()
v.set_color(YELLOW)
i_hat.set_color(X_COLOR)
j_hat.set_color(Y_COLOR)
rule.scale(0.85)
rule.next_to(self.v_def, DOWN, buff = 0.2)
rule.to_edge(LEFT)
rule.add_background_rectangle()
self.play(Write(rule, run_time = 2))
self.wait()
self.linear_map_rule = rule
def show_basis_vector_coords(self):
i_coords = matrix_to_mobject(self.transposed_matrix[0])
j_coords = matrix_to_mobject(self.transposed_matrix[1])
i_coords.set_color(X_COLOR)
j_coords.set_color(Y_COLOR)
for coords in i_coords, j_coords:
coords.add_background_rectangle()
coords.scale(0.7)
i_coords.next_to(self.i_hat.get_end(), RIGHT)
j_coords.next_to(self.j_hat.get_end(), RIGHT)
calculation = OldTex([
" = %s"%self.v_coord_strings[0],
matrix_to_tex_string(self.transposed_matrix[0]),
"+%s"%self.v_coord_strings[1],
matrix_to_tex_string(self.transposed_matrix[1]),
])
equals_neg_1, i_hat, plus_2, j_hat = calculation.split()
i_hat.set_color(X_COLOR)
j_hat.set_color(Y_COLOR)
calculation.scale(0.8)
calculation.next_to(self.linear_map_rule, DOWN)
calculation.to_edge(LEFT)
calculation.add_background_rectangle()
result = OldTex(self.result_coords_string)
result.scale(0.8)
result.add_background_rectangle()
result.next_to(calculation, DOWN)
result.to_edge(LEFT)
self.play(Write(i_coords, run_time = 1))
self.wait()
self.play(Write(j_coords, run_time = 1))
self.wait()
self.play(Write(calculation))
self.wait()
self.play(Write(result))
self.wait()
class WatchManyVectorsMove(TransformManyVectors):
def construct(self):
self.setup()
vectors = VMobject(*[
Vector([x, y])
for x in np.arange(-int(FRAME_X_RADIUS)+0.5, int(FRAME_X_RADIUS)+0.5)
for y in np.arange(-int(FRAME_Y_RADIUS)+0.5, int(FRAME_Y_RADIUS)+0.5)
])
vectors.set_submobject_colors_by_gradient(PINK, YELLOW)
dots = self.vectors_to_dots(vectors)
self.play(ShowCreation(dots, lag_ratio = 0.5))
self.play(Transform(
dots, vectors,
lag_ratio = 0.5,
run_time = 2
))
self.remove(dots)
for v in vectors.split():
self.add_vector(v, animate = False)
self.apply_transposed_matrix([[1, -2], [3, 0]])
self.wait()
self.play(
ApplyMethod(self.plane.fade),
FadeOut(vectors),
Animation(self.i_hat),
Animation(self.j_hat),
)
self.wait()
class NowWithoutWatching(Scene):
def construct(self):
text = OldTexText("Now without watching...")
text.to_edge(UP)
randy = Randolph(mode = "pondering")
self.add(randy)
self.play(Write(text, run_time = 1))
self.play(ApplyMethod(randy.blink))
self.wait(2)
class DeduceResultWithGeneralCoordinates(Scene):
def construct(self):
i_hat_to = OldTex("\\hat{\\imath} \\rightarrow")
j_hat_to = OldTex("\\hat{\\jmath} \\rightarrow")
i_coords = Matrix([1, -2])
j_coords = Matrix([3, 0])
i_coords.next_to(i_hat_to, RIGHT, buff = 0.1)
j_coords.next_to(j_hat_to, RIGHT, buff = 0.1)
i_group = VMobject(i_hat_to, i_coords)
j_group = VMobject(j_hat_to, j_coords)
i_group.set_color(X_COLOR)
j_group.set_color(Y_COLOR)
i_group.next_to(ORIGIN, LEFT, buff = 1).to_edge(UP)
j_group.next_to(ORIGIN, RIGHT, buff = 1).to_edge(UP)
vect = Matrix(["x", "y"])
x, y = vect.get_mob_matrix().flatten()
VMobject(x, y).set_color(YELLOW)
rto = OldTex("\\rightarrow")
equals = OldTex("=")
plus = OldTex("+")
row1 = OldTex("1x + 3y")
row2 = OldTex("-2x + 0y")
VMobject(
row1.split()[0], row2.split()[0], row2.split()[1]
).set_color(X_COLOR)
VMobject(
row1.split()[1], row1.split()[4], row2.split()[2], row2.split()[5]
).set_color(YELLOW)
VMobject(
row1.split()[3], row2.split()[4]
).set_color(Y_COLOR)
result = Matrix([row1, row2])
result.show()
vect_group = VMobject(
vect, rto,
x.copy(), i_coords.copy(), plus,
y.copy(), j_coords.copy(), equals,
result
)
vect_group.arrange(RIGHT, buff = 0.1)
self.add(i_group, j_group)
for mob in vect_group.split():
self.play(Write(mob))
self.wait()
class MatrixVectorMultiplication(LinearTransformationScene):
CONFIG = {
"abstract" : False
}
def construct(self):
self.setup()
matrix = self.build_to_matrix()
self.label_matrix(matrix)
vector, formula = self.multiply_by_vector(matrix)
self.reposition_matrix_and_vector(matrix, vector, formula)
def build_to_matrix(self):
self.wait()
self.apply_transposed_matrix([[3, -2], [2, 1]])
self.wait()
i_coords = vector_coordinate_label(self.i_hat)
j_coords = vector_coordinate_label(self.j_hat)
if self.abstract:
new_i_coords = Matrix(["a", "c"])
new_j_coords = Matrix(["b", "d"])
new_i_coords.move_to(i_coords)
new_j_coords.move_to(j_coords)
i_coords = new_i_coords
j_coords = new_j_coords
i_coords.set_color(X_COLOR)
j_coords.set_color(Y_COLOR)
i_brackets = i_coords.get_brackets()
j_brackets = j_coords.get_brackets()
for coords in i_coords, j_coords:
rect = BackgroundRectangle(coords)
coords.rect = rect
abstract_matrix = np.append(
i_coords.get_mob_matrix(),
j_coords.get_mob_matrix(),
axis = 1
)
concrete_matrix = Matrix(
copy.deepcopy(abstract_matrix),
add_background_rectangles_to_entries = True
)
concrete_matrix.to_edge(UP)
if self.abstract:
m = concrete_matrix.get_mob_matrix()[1, 0]
m.shift(m.get_height()*DOWN/2)
matrix_brackets = concrete_matrix.get_brackets()
self.play(ShowCreation(i_coords.rect), Write(i_coords))
self.play(ShowCreation(j_coords.rect), Write(j_coords))
self.wait()
self.remove(i_coords.rect, j_coords.rect)
self.play(
Transform(
VMobject(*abstract_matrix.flatten()),
VMobject(*concrete_matrix.get_mob_matrix().flatten()),
),
Transform(i_brackets, matrix_brackets),
Transform(j_brackets, matrix_brackets),
run_time = 2,
lag_ratio = 0
)
everything = VMobject(*self.get_mobjects())
self.play(
FadeOut(everything),
Animation(concrete_matrix)
)
return concrete_matrix
def label_matrix(self, matrix):
title = OldTexText("``2x2 Matrix''")
title.to_edge(UP+LEFT)
col_circles = []
for i, color in enumerate([X_COLOR, Y_COLOR]):
col = VMobject(*matrix.get_mob_matrix()[:,i])
col_circle = Circle(color = color)
col_circle.stretch_to_fit_width(matrix.get_width()/3)
col_circle.stretch_to_fit_height(matrix.get_height())
col_circle.move_to(col)
col_circles.append(col_circle)
i_circle, j_circle = col_circles
i_message = OldTexText("Where $\\hat{\\imath}$ lands")
j_message = OldTexText("Where $\\hat{\\jmath}$ lands")
i_message.set_color(X_COLOR)
j_message.set_color(Y_COLOR)
i_message.next_to(i_circle, DOWN, buff = 2, aligned_edge = RIGHT)
j_message.next_to(j_circle, DOWN, buff = 2, aligned_edge = LEFT)
i_arrow = Arrow(i_message, i_circle)
j_arrow = Arrow(j_message, j_circle)
self.play(Write(title))
self.wait()
self.play(ShowCreation(i_circle))
self.play(
Write(i_message, run_time = 1.5),
ShowCreation(i_arrow),
)
self.wait()
self.play(ShowCreation(j_circle))
self.play(
Write(j_message, run_time = 1.5),
ShowCreation(j_arrow)
)
self.wait()
self.play(*list(map(FadeOut, [
i_message, i_circle, i_arrow, j_message, j_circle, j_arrow
])))
def multiply_by_vector(self, matrix):
vector = Matrix(["x", "y"]) if self.abstract else Matrix([5, 7])
vector.set_height(matrix.get_height())
vector.next_to(matrix, buff = 2)
brace = Brace(vector, DOWN)
words = OldTexText("Any ol' vector")
words.next_to(brace, DOWN)
self.play(
Write(vector),
GrowFromCenter(brace),
Write(words),
run_time = 1
)
self.wait()
v1, v2 = vector.get_mob_matrix().flatten()
mob_matrix = matrix.copy().get_mob_matrix()
col1 = Matrix(mob_matrix[:,0])
col2 = Matrix(mob_matrix[:,1])
formula = VMobject(
v1.copy(), col1, OldTex("+"), v2.copy(), col2
)
formula.arrange(RIGHT, buff = 0.1)
formula.center()
formula_start = VMobject(
v1.copy(),
VMobject(*matrix.copy().get_mob_matrix()[:,0]),
VectorizedPoint(),
v2.copy(),
VMobject(*matrix.copy().get_mob_matrix()[:,1]),
)
self.play(
FadeOut(brace),
FadeOut(words),
Transform(
formula_start, formula,
run_time = 2,
lag_ratio = 0
)
)
self.wait()
self.show_result(formula)
return vector, formula
def show_result(self, formula):
if self.abstract:
row1 = ["a", "x", "+", "b", "y"]
row2 = ["c", "x", "+", "d", "y"]
else:
row1 = ["3", "(5)", "+", "2", "(7)"]
row2 = ["-2", "(5)", "+", "1", "(7)"]
row1 = VMobject(*list(map(Tex, row1)))
row2 = VMobject(*list(map(Tex, row2)))
for row in row1, row2:
row.arrange(RIGHT, buff = 0.1)
final_sum = Matrix([row1, row2])
row1, row2 = final_sum.get_mob_matrix().flatten()
row1.split()[0].set_color(X_COLOR)
row2.split()[0].set_color(X_COLOR)
row1.split()[3].set_color(Y_COLOR)
row2.split()[3].set_color(Y_COLOR)
equals = OldTex("=")
equals.next_to(formula, RIGHT)
final_sum.next_to(equals, RIGHT)
self.play(
Write(equals, run_time = 1),
Write(final_sum)
)
self.wait()
def reposition_matrix_and_vector(self, matrix, vector, formula):
start_state = VMobject(matrix, vector)
end_state = start_state.copy()
end_state.arrange(RIGHT, buff = 0.1)
equals = OldTex("=")
equals.next_to(formula, LEFT)
end_state.next_to(equals, LEFT)
brace = Brace(formula, DOWN)
brace_words = OldTexText("Where all the intuition is")
brace_words.next_to(brace, DOWN)
brace_words.set_color(YELLOW)
self.play(
Transform(
start_state, end_state,
lag_ratio = 0
),
Write(equals, run_time = 1)
)
self.wait()
self.play(
FadeIn(brace),
FadeIn(brace_words),
lag_ratio = 0.5
)
self.wait()
class MatrixVectorMultiplicationAbstract(MatrixVectorMultiplication):
CONFIG = {
"abstract" : True,
}
class ColumnsToBasisVectors(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[3, 1], [1, 2]]
}
def construct(self):
self.setup()
vector_coords = [-1, 2]
vector = self.move_matrix_columns(self.t_matrix, vector_coords)
self.scale_and_add(vector, vector_coords)
self.wait(3)
def move_matrix_columns(self, transposed_matrix, vector_coords = None):
matrix = np.array(transposed_matrix).transpose()
matrix_mob = Matrix(matrix)
matrix_mob.to_corner(UP+LEFT)
matrix_mob.add_background_to_entries()
col1 = VMobject(*matrix_mob.get_mob_matrix()[:,0])
col1.set_color(X_COLOR)
col2 = VMobject(*matrix_mob.get_mob_matrix()[:,1])
col2.set_color(Y_COLOR)
matrix_brackets = matrix_mob.get_brackets()
matrix_background = BackgroundRectangle(matrix_mob)
self.add_foreground_mobject(matrix_background, matrix_mob)
if vector_coords is not None:
vector = Matrix(vector_coords)
VMobject(*vector.get_mob_matrix().flatten()).set_color(YELLOW)
vector.set_height(matrix_mob.get_height())
vector.next_to(matrix_mob, RIGHT)
vector_background = BackgroundRectangle(vector)
self.add_foreground_mobject(vector_background, vector)
new_i = Vector(matrix[:,0])
new_j = Vector(matrix[:,1])
i_label = vector_coordinate_label(new_i).set_color(X_COLOR)
j_label = vector_coordinate_label(new_j).set_color(Y_COLOR)
i_coords = VMobject(*i_label.get_mob_matrix().flatten())
j_coords = VMobject(*j_label.get_mob_matrix().flatten())
i_brackets = i_label.get_brackets()
j_brackets = j_label.get_brackets()
i_label_background = BackgroundRectangle(i_label)
j_label_background = BackgroundRectangle(j_label)
i_coords_start = VMobject(
matrix_background.copy(),
col1.copy(),
matrix_brackets.copy()
)
i_coords_end = VMobject(
i_label_background,
i_coords,
i_brackets,
)
j_coords_start = VMobject(
matrix_background.copy(),
col2.copy(),
matrix_brackets.copy()
)
j_coords_end = VMobject(
j_label_background,
j_coords,
j_brackets,
)
transform_matrix1 = np.array(matrix)
transform_matrix1[:,1] = [0, 1]
transform_matrix2 = np.dot(
matrix,
np.linalg.inv(transform_matrix1)
)
self.wait()
self.apply_transposed_matrix(
transform_matrix1.transpose(),
added_anims = [Transform(i_coords_start, i_coords_end)],
path_arc = np.pi/2,
)
self.add_foreground_mobject(i_coords_start)
self.apply_transposed_matrix(
transform_matrix2.transpose(),
added_anims = [Transform(j_coords_start, j_coords_end) ],
path_arc = np.pi/2,
)
self.add_foreground_mobject(j_coords_start)
self.wait()
self.matrix = VGroup(matrix_background, matrix_mob)
self.i_coords = i_coords_start
self.j_coords = j_coords_start
return vector if vector_coords is not None else None
def scale_and_add(self, vector, vector_coords):
i_copy = self.i_hat.copy()
j_copy = self.j_hat.copy()
i_target = i_copy.copy().scale(vector_coords[0]).fade(0.3)
j_target = j_copy.copy().scale(vector_coords[1]).fade(0.3)
coord1, coord2 = vector.copy().get_mob_matrix().flatten()
coord1.add_background_rectangle()
coord2.add_background_rectangle()
self.play(
Transform(i_copy, i_target),
ApplyMethod(coord1.next_to, i_target.get_center(), DOWN)
)
self.play(
Transform(j_copy, j_target),
ApplyMethod(coord2.next_to, j_target.get_center(), LEFT)
)
j_copy.add(coord2)
self.play(ApplyMethod(j_copy.shift, i_copy.get_end()))
self.add_vector(j_copy.get_end())
self.wait()
class Describe90DegreeRotation(LinearTransformationScene):
CONFIG = {
"transposed_matrix" : [[0, 1], [-1, 0]],
"title" : "$90^\\circ$ rotation counterclockwise",
}
def construct(self):
self.setup()
title = OldTexText(self.title)
title.shift(DOWN)
title.add_background_rectangle()
matrix = Matrix(np.array(self.transposed_matrix).transpose())
matrix.to_corner(UP+LEFT)
matrix_background = BackgroundRectangle(matrix)
col1 = VMobject(*matrix.get_mob_matrix()[:,0])
col2 = VMobject(*matrix.get_mob_matrix()[:,1])
col1.set_color(X_COLOR)
col2.set_color(Y_COLOR)
self.add_foreground_mobject(matrix_background, matrix.get_brackets())
self.wait()
self.apply_transposed_matrix(self.transposed_matrix)
self.wait()
self.play(Write(title))
self.add_foreground_mobject(title)
for vect, color, col in [(self.i_hat, X_COLOR, col1), (self.j_hat, Y_COLOR, col2)]:
label = vector_coordinate_label(vect)
label.set_color(color)
background = BackgroundRectangle(label)
coords = VMobject(*label.get_mob_matrix().flatten())
brackets = label.get_brackets()
self.play(ShowCreation(background), Write(label))
self.wait()
self.play(
ShowCreation(background, rate_func = lambda t : smooth(1-t)),
ApplyMethod(coords.replace, col),
FadeOut(brackets),
)
self.remove(label)
self.add_foreground_mobject(coords)
self.wait()
self.show_vector(matrix)
def show_vector(self, matrix):
vector = Matrix(["x", "y"])
VMobject(*vector.get_mob_matrix().flatten()).set_color(YELLOW)
vector.set_height(matrix.get_height())
vector.next_to(matrix, RIGHT)
v_background = BackgroundRectangle(vector)
matrix = np.array(self.transposed_matrix).transpose()
inv = np.linalg.inv(matrix)
self.apply_transposed_matrix(inv.transpose(), run_time = 0.5)
self.add_vector([1, 2])
self.wait()
self.apply_transposed_matrix(self.transposed_matrix)
self.play(ShowCreation(v_background), Write(vector))
self.wait()
class DescribeShear(Describe90DegreeRotation):
CONFIG = {
"transposed_matrix" : [[1, 0], [1, 1]],
"title" : "``Shear''",
}
class OtherWayAround(Scene):
def construct(self):
self.play(Write("What about the other way around?"))
self.wait(2)
class DeduceTransformationFromMatrix(ColumnsToBasisVectors):
def construct(self):
self.setup()
self.move_matrix_columns([[1, 2], [3, 1]])
class LinearlyDependentColumns(ColumnsToBasisVectors):
def construct(self):
self.setup()
title = OldTexText("Linearly dependent")
subtitle = OldTexText("columns")
title.add_background_rectangle()
subtitle.add_background_rectangle()
subtitle.next_to(title, DOWN)
title.add(subtitle)
title.shift(UP).to_edge(LEFT)
title.set_color(YELLOW)
self.add_foreground_mobject(title)
self.move_matrix_columns([[2, 1], [-2, -1]])
class NextVideo(Scene):
def construct(self):
title = OldTexText("Next video: Matrix multiplication as composition")
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
class FinalSlide(Scene):
def construct(self):
text = OldTexText("""
\\footnotesize
Technically, the definition of ``linear'' is as follows:
A transformation L is linear if it satisfies these
two properties:
\\begin{align*}
L(\\vec{\\textbf{v}} + \\vec{\\textbf{w}})
&= L(\\vec{\\textbf{v}}) + L(\\vec{\\textbf{w}})
& & \\text{``Additivity''} \\\\
L(c\\vec{\\textbf{v}}) &= c L(\\vec{\\textbf{v}})
& & \\text{``Scaling''}
\\end{align*}
I'll talk about these properties later on, but I'm a big
believer in first understanding things visually.
Once you do, it becomes much more intuitive why these
two properties make sense. So for now, you can
feel fine thinking of linear transformations as those
which keep grid lines parallel and evenly spaced
(and which fix the origin in place), since this visual
definition is actually equivalent to the two properties
above.
""", enforce_new_line_structure = False)
text.set_height(FRAME_HEIGHT - 2)
text.to_edge(UP)
self.add(text)
self.wait()
### Old scenes
class RotateIHat(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False
}
def construct(self):
self.setup()
i_hat, j_hat = self.get_basis_vectors()
i_label, j_label = self.get_basis_vector_labels()
self.add_vector(i_hat)
self.play(Write(i_label, run_time = 1))
self.wait()
self.play(FadeOut(i_label))
self.apply_transposed_matrix([[0, 1], [-1, 0]])
self.wait()
self.play(Write(j_label, run_time = 1))
self.wait()
class TransformationsAreFunctions(Scene):
def construct(self):
title = OldTexText([
"""Linear transformations are a
special kind of""",
"function"
])
title_start, function = title.split()
function.set_color(YELLOW)
title.to_edge(UP)
equation = OldTex([
"L",
"(",
"\\vec{\\textbf{v}}",
") = ",
"\\vec{\\textbf{w}}",
])
L, lp, _input, equals, _output = equation.split()
L.set_color(YELLOW)
_input.set_color(MAROON_C)
_output.set_color(BLUE)
equation.scale(2)
equation.next_to(title, DOWN, buff = 1)
starting_vector = OldTexText("Starting vector")
starting_vector.shift(DOWN+3*LEFT)
starting_vector.set_color(MAROON_C)
ending_vector = OldTexText("The vector where it lands")
ending_vector.shift(DOWN).to_edge(RIGHT)
ending_vector.set_color(BLUE)
func_arrow = Arrow(function.get_bottom(), L.get_top(), color = YELLOW)
start_arrow = Arrow(starting_vector.get_top(), _input.get_bottom(), color = MAROON_C)
ending_arrow = Arrow(ending_vector, _output, color = BLUE)
self.add(title)
self.play(
Write(equation),
ShowCreation(func_arrow)
)
for v, a in [(starting_vector, start_arrow), (ending_vector, ending_arrow)]:
self.play(Write(v), ShowCreation(a), run_time = 1)
self.wait()
class UsedToThinkinfOfFunctionsAsGraphs(VectorScene):
def construct(self):
self.show_graph()
self.show_inputs_and_output()
def show_graph(self):
axes = self.add_axes()
graph = FunctionGraph(lambda x : x**2, x_min = -2, x_max = 2)
name = OldTex("f(x) = x^2")
name.next_to(graph, RIGHT).to_edge(UP)
point = Dot(graph.point_from_proportion(0.8))
point_label = OldTex("(x, x^2)")
point_label.next_to(point, DOWN+RIGHT, buff = 0.1)
self.play(ShowCreation(graph))
self.play(Write(name, run_time = 1))
self.play(
ShowCreation(point),
Write(point_label),
run_time = 1
)
self.wait()
def collapse_func(p):
return np.dot(p, [RIGHT, RIGHT, OUT]) + (FRAME_Y_RADIUS+1)*DOWN
self.play(
ApplyPointwiseFunction(
collapse_func, axes,
lag_ratio = 0,
),
ApplyPointwiseFunction(collapse_func, graph),
ApplyMethod(point.shift, 10*DOWN),
ApplyMethod(point_label.shift, 10*DOWN),
ApplyFunction(lambda m : m.center().to_edge(UP), name),
run_time = 1
)
self.clear()
self.add(name)
self.wait()
def show_inputs_and_output(self):
numbers = list(range(-3, 4))
inputs = VMobject(*list(map(Tex, list(map(str, numbers)))))
inputs.arrange(DOWN, buff = 0.5, aligned_edge = RIGHT)
arrows = VMobject(*[
Arrow(LEFT, RIGHT).next_to(mob)
for mob in inputs.split()
])
outputs = VMobject(*[
OldTex(str(num**2)).next_to(arrow)
for num, arrow in zip(numbers, arrows.split())
])
everyone = VMobject(inputs, arrows, outputs)
everyone.center().to_edge(UP, buff = 1.5)
self.play(Write(inputs, run_time = 1))
self.wait()
self.play(
Transform(inputs.copy(), outputs),
ShowCreation(arrows)
)
self.wait()
class TryingToVisualizeFourDimensions(Scene):
def construct(self):
randy = Randolph().to_corner()
bubble = randy.get_bubble()
formula = OldTex("""
L\\left(\\left[
\\begin{array}{c}
x \\\\
y
\\end{array}
\\right]\\right) =
\\left[
\\begin{array}{c}
2x + y \\\\
x + 2y
\\end{array}
\\right]
""")
formula.next_to(randy, RIGHT)
formula.split()[3].set_color(X_COLOR)
formula.split()[4].set_color(Y_COLOR)
VMobject(*formula.split()[9:9+4]).set_color(MAROON_C)
VMobject(*formula.split()[13:13+4]).set_color(BLUE)
thought = OldTexText("""
Do I imagine plotting
$(x, y, 2x+y, x+2y)$???
""")
thought.split()[-17].set_color(X_COLOR)
thought.split()[-15].set_color(Y_COLOR)
VMobject(*thought.split()[-13:-13+4]).set_color(MAROON_C)
VMobject(*thought.split()[-8:-8+4]).set_color(BLUE)
bubble.position_mobject_inside(thought)
thought.shift(0.2*UP)
self.add(randy)
self.play(
ApplyMethod(randy.look, DOWN+RIGHT),
Write(formula)
)
self.play(
ApplyMethod(randy.change_mode, "pondering"),
ShowCreation(bubble),
Write(thought)
)
self.play(Blink(randy))
self.wait()
self.remove(thought)
bubble.make_green_screen()
self.wait()
self.play(Blink(randy))
self.play(ApplyMethod(randy.change_mode, "confused"))
self.wait()
self.play(Blink(randy))
self.wait()
class ForgetAboutGraphs(Scene):
def construct(self):
self.play(Write("You must unlearn graphs"))
self.wait()
class ThinkAboutFunctionAsMovingVector(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"leave_ghost_vectors" : True,
}
def construct(self):
self.setup()
vector = self.add_vector([2, 1])
label = self.add_transformable_label(vector, "v")
self.wait()
self.apply_transposed_matrix([[1, 1], [-3, 1]])
self.wait()
class PrepareForFormalDefinition(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("Get ready for a formal definition!")
self.wait(3)
bubble = self.student_thinks("")
bubble.make_green_screen()
self.wait(3)
class AdditivityProperty(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"give_title" : True,
"transposed_matrix" : [[2, 0], [1, 1]],
"nonlinear_transformation" : None,
"vector_v" : [2, 1],
"vector_w" : [1, -2],
"proclaim_sum" : True,
}
def construct(self):
self.setup()
added_anims = []
if self.give_title:
title = OldTexText("""
First fundamental property of
linear transformations
""")
title.to_edge(UP)
title.set_color(YELLOW)
title.add_background_rectangle()
self.play(Write(title))
added_anims.append(Animation(title))
self.wait()
self.play(ApplyMethod(self.plane.fade), *added_anims)
v, w = self.draw_all_vectors()
self.apply_transformation(added_anims)
self.show_final_sum(v, w)
def draw_all_vectors(self):
v = self.add_vector(self.vector_v, color = MAROON_C)
v_label = self.add_transformable_label(v, "v")
w = self.add_vector(self.vector_w, color = GREEN)
w_label = self.add_transformable_label(w, "w")
new_w = w.copy().fade(0.4)
self.play(ApplyMethod(new_w.shift, v.get_end()))
sum_vect = self.add_vector(new_w.get_end(), color = PINK)
sum_label = self.add_transformable_label(
sum_vect,
"%s + %s"%(v_label.expression, w_label.expression),
rotate = True
)
self.play(FadeOut(new_w))
return v, w
def apply_transformation(self, added_anims):
if self.nonlinear_transformation:
self.apply_nonlinear_transformation(self.nonlinear_transformation)
else:
self.apply_transposed_matrix(
self.transposed_matrix,
added_anims = added_anims
)
self.wait()
def show_final_sum(self, v, w):
new_w = w.copy()
self.play(ApplyMethod(new_w.shift, v.get_end()))
self.wait()
if self.proclaim_sum:
text = OldTexText("It's still their sum!")
text.add_background_rectangle()
text.move_to(new_w.get_end(), aligned_edge = -new_w.get_end())
text.shift_onto_screen()
self.play(Write(text))
self.wait()
class NonlinearLacksAdditivity(AdditivityProperty):
CONFIG = {
"give_title" : False,
"nonlinear_transformation" : curvy_squish,
"vector_v" : [3, 2],
"vector_w" : [2, -3],
"proclaim_sum" : False,
}
class SecondAdditivityExample(AdditivityProperty):
CONFIG = {
"give_title" : False,
"transposed_matrix" : [[1, -1], [2, 1]],
"vector_v" : [-2, 2],
"vector_w" : [3, 0],
"proclaim_sum" : False,
}
class ShowGridCreation(Scene):
def construct(self):
plane = NumberPlane()
coords = VMobject(*plane.get_coordinate_labels())
self.play(ShowCreation(plane, run_time = 3))
self.play(Write(coords, run_time = 3))
self.wait()
class MoveAroundAllVectors(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
"focus_on_one_vector" : False,
"include_background_plane" : False,
}
def construct(self):
self.setup()
vectors = VMobject(*[
Vector([x, y])
for x in np.arange(-int(FRAME_X_RADIUS)+0.5, int(FRAME_X_RADIUS)+0.5)
for y in np.arange(-int(FRAME_Y_RADIUS)+0.5, int(FRAME_Y_RADIUS)+0.5)
])
vectors.set_submobject_colors_by_gradient(PINK, YELLOW)
dots = self.get_dots(vectors)
self.wait()
self.play(ShowCreation(dots))
self.wait()
self.play(Transform(dots, vectors))
self.wait()
self.remove(dots)
if self.focus_on_one_vector:
vector = vectors.split()[43]#yeah, great coding Grant
self.remove(vectors)
self.add_vector(vector)
self.play(*[
FadeOut(v)
for v in vectors.split()
if v is not vector
])
self.wait()
self.add(vector.copy().set_color(GREY_D))
else:
for vector in vectors.split():
self.add_vector(vector, animate = False)
self.apply_transposed_matrix([[3, 0], [1, 2]])
self.wait()
dots = self.get_dots(vectors)
self.play(Transform(vectors, dots))
self.wait()
def get_dots(self, vectors):
return VMobject(*[
Dot(v.get_end(), color = v.get_color())
for v in vectors.split()
])
class ReasonForThinkingAboutArrows(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False
}
def construct(self):
self.setup()
self.plane.fade()
v_color = MAROON_C
w_color = BLUE
v = self.add_vector([3, 1], color = v_color)
w = self.add_vector([1, -2], color = w_color)
vectors = VMobject(v, w)
self.to_and_from_dots(vectors)
self.scale_and_add(vectors)
self.apply_transposed_matrix([[1, 1], [-1, 0]])
self.scale_and_add(vectors)
def to_and_from_dots(self, vectors):
vectors_copy = vectors.copy()
dots = VMobject(*[
Dot(v.get_end(), color = v.get_color())
for v in vectors.split()
])
self.wait()
self.play(Transform(vectors, dots))
self.wait()
self.play(Transform(vectors, vectors_copy))
self.wait()
def scale_and_add(self, vectors):
vectors_copy = vectors.copy()
v, w, = vectors.split()
scaled_v = Vector(0.5*v.get_end(), color = v.get_color())
scaled_w = Vector(1.5*w.get_end(), color = w.get_color())
shifted_w = scaled_w.copy().shift(scaled_v.get_end())
sum_vect = Vector(shifted_w.get_end(), color = PINK)
self.play(
ApplyMethod(v.scale, 0.5),
ApplyMethod(w.scale, 1.5),
)
self.play(ApplyMethod(w.shift, v.get_end()))
self.add_vector(sum_vect)
self.wait()
self.play(Transform(
vectors, vectors_copy,
lag_ratio = 0
))
self.wait()
class LinearTransformationWithOneVector(LinearTransformationScene):
CONFIG = {
"show_basis_vectors" : False,
}
def construct(self):
self.setup()
v = self.add_vector([3, 1])
self.vector_to_coords(v)
self.apply_transposed_matrix([[-1, 1], [-2, -1]])
self.vector_to_coords(v)
|
|
from manim_imports_ext import *
from _2016.eola.footnote2 import TwoDTo1DTransformWithDots
V_COLOR = YELLOW
W_COLOR = MAROON_B
SUM_COLOR = PINK
def get_projection(vector_to_project, stable_vector):
v1, v2 = stable_vector, vector_to_project
return v1*np.dot(v1, v2)/(get_norm(v1)**2)
def get_vect_mob_projection(vector_to_project, stable_vector):
return Vector(
get_projection(
vector_to_project.get_end(),
stable_vector.get_end()
),
color = vector_to_project.get_color()
).fade()
class OpeningQuote(Scene):
def construct(self):
words = OldTexText(
"\\small Calvin:",
"You know, I don't think math is a science, I think it's a religion.",
"\\\\Hobbes:",
"A religion?",
"\\\\Calvin:" ,
"Yeah. All these equations are like miracles."
"You take two numbers and when you add them, "
"they magically become one NEW number! "
"No one can say how it happens. "
"You either believe it or you don't.",
)
words.set_width(FRAME_WIDTH - 1)
words.to_edge(UP)
words[0].set_color(YELLOW)
words[2].set_color("#fd9c2b")
words[4].set_color(YELLOW)
for i in range(3):
speaker, quote = words[2*i:2*i+2]
self.play(FadeIn(speaker, run_time = 0.5))
rt = max(1, len(quote.split())/18)
self.play(Write(
quote,
run_time = rt,
))
self.wait(2)
class TraditionalOrdering(RandolphScene):
def construct(self):
title = OldTexText("Traditional ordering:")
title.set_color(YELLOW)
title.scale(1.2)
title.to_corner(UP+LEFT)
topics = VMobject(*list(map(TexText, [
"Topic 1: Vectors",
"Topic 2: Dot products",
"\\vdots",
"(everything else)",
"\\vdots",
])))
topics.arrange(DOWN, aligned_edge = LEFT, buff = SMALL_BUFF)
# topics.next_to(title, DOWN+RIGHT)
self.play(
Write(title, run_time = 1),
FadeIn(
topics,
run_time = 3,
lag_ratio = 0.5
),
)
self.play(topics[1].set_color, PINK)
self.wait()
class ThisSeriesOrdering(RandolphScene):
def construct(self):
title = OldTexText("Essence of linear algebra")
self.randy.rotate(np.pi, UP)
title.scale(1.2).set_color(BLUE)
title.to_corner(UP+LEFT)
line = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT, color = WHITE)
line.next_to(title, DOWN, buff = SMALL_BUFF)
line.to_edge(LEFT, buff = 0)
chapters = VMobject(*[
OldTexText("\\small " + text)
for text in [
"Chapter 1: Vectors, what even are they?",
"Chapter 2: Linear combinations, span and bases",
"Chapter 3: Matrices as linear transformations",
"Chapter 4: Matrix multiplication as composition",
"Chapter 5: The determinant",
"Chapter 6: Inverse matrices, column space and null space",
"Chapter 7: Dot products and duality",
"Chapter 8: Cross products via transformations",
"Chapter 9: Change of basis",
"Chapter 10: Eigenvectors and eigenvalues",
"Chapter 11: Abstract vector spaces",
]
])
chapters.arrange(
DOWN, buff = SMALL_BUFF, aligned_edge = LEFT
)
chapters.set_height(1.5*FRAME_Y_RADIUS)
chapters.next_to(line, DOWN, buff = SMALL_BUFF)
chapters.to_edge(RIGHT)
self.add(title)
self.play(
ShowCreation(line),
)
self.play(
FadeIn(
chapters,
lag_ratio = 0.5,
run_time = 3
),
self.randy.change_mode, "sassy"
)
self.play(self.randy.look, UP+LEFT)
self.play(chapters[6].set_color, PINK)
self.wait(6)
class OneMustViewThroughTransformations(TeacherStudentsScene):
def construct(self):
words = OldTexText(
"Only with" , "transformations",
"\n can we truly understand",
)
words.set_color_by_tex("transformations", BLUE)
self.teacher_says(words)
self.play_student_changes(
"pondering",
"plain",
"raise_right_hand"
)
self.random_blink(2)
words = OldTexText(
"First, the ",
"standard view...",
arg_separator = "\n"
)
self.teacher_says(words)
self.random_blink(2)
class ShowNumericalDotProduct(Scene):
CONFIG = {
"v1" : [2, 7, 1],
"v2" : [8, 2, 8],
"write_dot_product_words" : True,
}
def construct(self):
v1 = Matrix(self.v1)
v2 = Matrix(self.v2)
inter_array_dot = OldTex("\\cdot").scale(1.5)
dot_product = VGroup(v1, inter_array_dot, v2)
dot_product.arrange(RIGHT, buff = MED_SMALL_BUFF/2)
dot_product.to_edge(LEFT)
pairs = list(zip(v1.get_entries(), v2.get_entries()))
for pair, color in zip(pairs, [X_COLOR, Y_COLOR, Z_COLOR, PINK]):
VGroup(*pair).set_color(color)
dot = OldTex("\\cdot")
products = VGroup(*[
VGroup(
p1.copy(), dot.copy(), p2.copy()
).arrange(RIGHT, buff = SMALL_BUFF)
for p1, p2 in pairs
])
products.arrange(DOWN, buff = LARGE_BUFF)
products.next_to(dot_product, RIGHT, buff = LARGE_BUFF)
products.target = products.copy()
plusses = ["+"]*(len(self.v1)-1)
symbols = VGroup(*list(map(Tex, ["="] + plusses)))
final_sum = VGroup(*it.chain(*list(zip(
symbols, products.target
))))
final_sum.arrange(RIGHT, buff = SMALL_BUFF)
final_sum.next_to(dot_product, RIGHT)
title = OldTexText("Two vectors of the same dimension")
title.to_edge(UP)
arrow = Arrow(DOWN, UP).next_to(inter_array_dot, DOWN)
dot_product_words = OldTexText("Dot product")
dot_product_words.set_color(YELLOW)
dot_product_words.next_to(arrow, DOWN)
dot_product_words.shift_onto_screen()
self.play(
Write(v1),
Write(v2),
FadeIn(inter_array_dot),
FadeIn(title)
)
self.wait()
if self.write_dot_product_words:
self.play(
inter_array_dot.set_color, YELLOW,
ShowCreation(arrow),
Write(dot_product_words, run_time = 2)
)
self.wait()
self.play(Transform(
VGroup(*it.starmap(Group, pairs)).copy(),
products,
path_arc = -np.pi/2,
run_time = 2
))
self.remove(*self.get_mobjects_from_last_animation())
self.add(products)
self.wait()
self.play(
Write(symbols),
Transform(products, products.target, path_arc = np.pi/2)
)
self.wait()
class TwoDDotProductExample(ShowNumericalDotProduct):
CONFIG = {
"v1" : [1, 2],
"v2" : [3, 4],
}
class FourDDotProductExample(ShowNumericalDotProduct):
CONFIG = {
"v1" : [6, 2, 8, 3],
"v2" : [1, 8, 5, 3],
"write_dot_product_words" : False,
}
class GeometricInterpretation(VectorScene):
CONFIG = {
"v_coords" : [4, 1],
"w_coords" : [2, -1],
"v_color" : V_COLOR,
"w_color" : W_COLOR,
"project_onto_v" : True,
}
def construct(self):
self.lock_in_faded_grid()
self.add_symbols()
self.add_vectors()
self.line()
self.project()
self.show_lengths()
self.handle_possible_negative()
def add_symbols(self):
v = matrix_to_mobject(self.v_coords).set_color(self.v_color)
w = matrix_to_mobject(self.w_coords).set_color(self.w_color)
v.add_background_rectangle()
w.add_background_rectangle()
dot = OldTex("\\cdot")
eq = VMobject(v, dot, w)
eq.arrange(RIGHT, buff = SMALL_BUFF)
eq.to_corner(UP+LEFT)
self.play(Write(eq), run_time = 1)
for array, char in zip([v, w], ["v", "w"]):
brace = Brace(array, DOWN)
label = brace.get_text("$\\vec{\\textbf{%s}}$"%char)
label.set_color(array.get_color())
self.play(
GrowFromCenter(brace),
Write(label),
run_time = 1
)
self.dot_product = eq
def add_vectors(self):
self.v = Vector(self.v_coords, color = self.v_color)
self.w = Vector(self.w_coords, color = self.w_color)
self.play(ShowCreation(self.v))
self.play(ShowCreation(self.w))
for vect, char, direction in zip(
[self.v, self.w], ["v", "w"], [DOWN+RIGHT, DOWN]
):
label = OldTex("\\vec{\\textbf{%s}}"%char)
label.next_to(vect.get_end(), direction)
label.set_color(vect.get_color())
self.play(Write(label, run_time = 1))
self.stable_vect = self.v if self.project_onto_v else self.w
self.proj_vect = self.w if self.project_onto_v else self.v
def line(self):
line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
line.rotate(self.stable_vect.get_angle())
self.play(ShowCreation(line), Animation(self.stable_vect))
self.wait()
def project(self):
dot_product = np.dot(self.v.get_end(), self.w.get_end())
v_norm, w_norm = [
get_norm(vect.get_end())
for vect in (self.v, self.w)
]
projected = Vector(
self.stable_vect.get_end()*dot_product/(
self.stable_vect.get_length()**2
),
color = self.proj_vect.get_color()
)
projection_line = Line(
self.proj_vect.get_end(), projected.get_end(),
color = GREY
)
self.play(ShowCreation(projection_line))
self.add(self.proj_vect.copy().fade())
self.play(Transform(self.proj_vect, projected))
self.wait()
def show_lengths(self):
stable_char = "v" if self.project_onto_v else "w"
proj_char = "w" if self.project_onto_v else "v"
product = OldTexText(
"=",
"(",
"Length of projected $\\vec{\\textbf{%s}}$"%proj_char,
")",
"(",
"Length of $\\vec{\\textbf{%s}}$"%stable_char,
")",
arg_separator = ""
)
product.scale(0.9)
product.next_to(self.dot_product, RIGHT)
proj_words = product[2]
proj_words.set_color(self.proj_vect.get_color())
stable_words = product[5]
stable_words.set_color(self.stable_vect.get_color())
product.remove(proj_words, stable_words)
for words in stable_words, proj_words:
words.add_to_back(BackgroundRectangle(words))
words.start = words.copy()
proj_brace, stable_brace = braces = [
Brace(Line(ORIGIN, vect.get_length()*RIGHT*sgn), UP)
for vect in (self.proj_vect, self.stable_vect)
for sgn in [np.sign(np.dot(vect.get_end(), self.stable_vect.get_end()))]
]
proj_brace.put_at_tip(proj_words.start)
proj_brace.words = proj_words.start
stable_brace.put_at_tip(stable_words.start)
stable_brace.words = stable_words.start
for brace in braces:
brace.rotate(self.stable_vect.get_angle())
brace.words.rotate(self.stable_vect.get_angle())
self.play(
GrowFromCenter(proj_brace),
Write(proj_words.start, run_time = 2)
)
self.wait()
self.play(
Transform(proj_words.start, proj_words),
FadeOut(proj_brace)
)
self.play(
GrowFromCenter(stable_brace),
Write(stable_words.start, run_time = 2),
Animation(self.stable_vect)
)
self.wait()
self.play(
Transform(stable_words.start, stable_words),
Write(product)
)
self.wait()
product.add(stable_words.start, proj_words.start)
self.product = product
def handle_possible_negative(self):
if np.dot(self.w.get_end(), self.v.get_end()) > 0:
return
neg = OldTex("-").set_color(RED)
neg.next_to(self.product[0], RIGHT)
words = OldTexText("Should be negative")
words.set_color(RED)
words.next_to(
VMobject(*self.product[2:]),
DOWN,
buff = LARGE_BUFF,
aligned_edge = LEFT
)
words.add_background_rectangle()
arrow = Arrow(words.get_left(), neg, color = RED)
self.play(
Write(neg),
ShowCreation(arrow),
VMobject(*self.product[1:]).next_to, neg,
Write(words)
)
self.wait()
class GeometricInterpretationNegative(GeometricInterpretation):
CONFIG = {
"v_coords" : [3, 1],
"w_coords" : [-1, -2],
"v_color" : YELLOW,
"w_color" : MAROON_B,
}
class ShowQualitativeDotProductValues(VectorScene):
def construct(self):
self.lock_in_faded_grid()
v_sym, dot, w_sym, comp, zero = ineq = OldTex(
"\\vec{\\textbf{v}}",
"\\cdot",
"\\vec{\\textbf{w}}",
">",
"0",
)
ineq.to_edge(UP)
ineq.add_background_rectangle()
comp.set_color(GREEN)
equals = OldTex("=").set_color(PINK).move_to(comp)
less_than = OldTex("<").set_color(RED).move_to(comp)
v_sym.set_color(V_COLOR)
w_sym.set_color(W_COLOR)
words = list(map(TexText, [
"Similar directions",
"Perpendicular",
"Opposing directions"
]))
for word, sym in zip(words, [comp, equals, less_than]):
word.add_background_rectangle()
word.next_to(sym, DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF)
word.set_color(sym.get_color())
v = Vector([1.5, 1.5], color = V_COLOR)
w = Vector([2, 2], color = W_COLOR)
w.rotate(-np.pi/6)
shadow = Vector(
v.get_end()*np.dot(v.get_end(), w.get_end())/(v.get_length()**2),
color = MAROON_E,
preserve_tip_size_when_scaling = False
)
shadow_opposite = shadow.copy().scale(-1)
line = Line(LEFT, RIGHT, color = WHITE)
line.scale(FRAME_X_RADIUS)
line.rotate(v.get_angle())
proj_line = Line(w.get_end(), shadow.get_end(), color = GREY)
word = words[0]
self.add(ineq)
for mob in v, w, line, proj_line:
self.play(
ShowCreation(mob),
Animation(v)
)
self.play(Transform(w.copy(), shadow))
self.remove(*self.get_mobjects_from_last_animation())
self.add(shadow)
self.play(FadeOut(proj_line))
self.play(Write(word, run_time = 1))
self.wait()
self.play(
Rotate(w, -np.pi/3),
shadow.scale, 0
)
self.play(
Transform(comp, equals),
Transform(word, words[1])
)
self.wait()
self.play(
Rotate(w, -np.pi/3),
Transform(shadow, shadow_opposite)
)
self.play(
Transform(comp, less_than),
Transform(word, words[2])
)
self.wait()
class AskAboutSymmetry(TeacherStudentsScene):
def construct(self):
v, w = "\\vec{\\textbf{v}}", "\\vec{\\textbf{w}}",
question = OldTex(
"\\text{Why does }",
v, "\\cdot", w, "=", w, "\\cdot", v,
"\\text{?}"
)
VMobject(question[1], question[7]).set_color(V_COLOR)
VMobject(question[3], question[5]).set_color(W_COLOR)
self.student_says(
question,
target_mode = "raise_left_hand"
)
self.play_student_changes("confused")
self.play(self.get_teacher().change_mode, "pondering")
self.play(self.get_teacher().look, RIGHT)
self.play(self.get_teacher().look, LEFT)
self.random_blink()
class GeometricInterpretationSwapVectors(GeometricInterpretation):
CONFIG = {
"project_onto_v" : False,
}
class SymmetricVAndW(VectorScene):
def construct(self):
self.lock_in_faded_grid()
v = Vector([3, 1], color = V_COLOR)
w = Vector([1, 3], color = W_COLOR)
for vect, char in zip([v, w], ["v", "w"]):
vect.label = OldTex("\\vec{\\textbf{%s}}"%char)
vect.label.set_color(vect.get_color())
vect.label.next_to(vect.get_end(), DOWN+RIGHT)
for v1, v2 in (v, w), (w, v):
v1.proj = get_vect_mob_projection(v1, v2)
v1.proj_line = Line(
v1.get_end(), v1.proj.get_end(), color = GREY
)
line_of_symmetry = DashedLine(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT)
line_of_symmetry.rotate(np.mean([v.get_angle(), w.get_angle()]))
line_of_symmetry_words = OldTexText("Line of symmetry")
line_of_symmetry_words.add_background_rectangle()
line_of_symmetry_words.next_to(ORIGIN, UP+LEFT)
line_of_symmetry_words.rotate(line_of_symmetry.get_angle())
for vect in v, w:
self.play(ShowCreation(vect))
self.play(Write(vect.label, run_time = 1))
self.wait()
angle = (v.get_angle()-w.get_angle())/2
self.play(
Rotate(w, angle),
Rotate(v, -angle),
rate_func = there_and_back,
run_time = 2
)
self.wait()
self.play(
ShowCreation(line_of_symmetry),
Write(line_of_symmetry_words, run_time = 1)
)
self.wait(0.5)
self.remove(line_of_symmetry_words)
self.play(*list(map(Uncreate, line_of_symmetry_words)))
for vect in w, v:
self.play(ShowCreation(vect.proj_line))
vect_copy = vect.copy()
self.play(Transform(vect_copy, vect.proj))
self.remove(vect_copy)
self.add(vect.proj)
self.wait()
self.play(*list(map(FadeOut,[
v.proj, v.proj_line, w.proj, w.proj_line
])))
self.show_doubling(v, w)
def show_doubling(self, v, w):
scalar = 2
new_v = v.copy().scale(scalar)
new_v.label = VMobject(OldTex("2"), v.label.copy())
new_v.label.arrange(aligned_edge = DOWN)
new_v.label.next_to(new_v.get_end(), DOWN+RIGHT)
new_v.proj = v.proj.copy().scale(scalar)
new_v.proj.fade()
new_v.proj_line = Line(
new_v.get_end(), new_v.proj.get_end(),
color = GREY
)
v_tex, w_tex = ["\\vec{\\textbf{%s}}"%c for c in ("v", "w")]
equation = OldTex(
"(", "2", v_tex, ")", "\\cdot", w_tex,
"=",
"2(", v_tex, "\\cdot", w_tex, ")"
)
equation.set_color_by_tex(v_tex, V_COLOR)
equation.set_color_by_tex(w_tex, W_COLOR)
equation.next_to(ORIGIN, DOWN).to_edge(RIGHT)
words = OldTexText("Symmetry is broken")
words.next_to(ORIGIN, LEFT)
words.to_edge(UP)
v.save_state()
v.proj.save_state()
v.proj_line.save_state()
self.play(Transform(*[
VGroup(mob, mob.label)
for mob in (v, new_v)
]), run_time = 2)
last_mob = self.get_mobjects_from_last_animation()[0]
self.remove(last_mob)
self.add(*last_mob)
Transform(
VGroup(v.proj, v.proj_line),
VGroup(new_v.proj, new_v.proj_line)
).update(1)##Hacky
self.play(Write(words))
self.wait()
two_v_parts = equation[1:3]
equation.remove(*two_v_parts)
for full_v, projector, stable in zip([False, True], [w, v], [v, w]):
self.play(
Transform(projector.copy(), projector.proj),
ShowCreation(projector.proj_line)
)
self.remove(self.get_mobjects_from_last_animation()[0])
self.add(projector.proj)
self.wait()
if equation not in self.get_mobjects():
self.play(
Write(equation),
Transform(new_v.label.copy(), VMobject(*two_v_parts))
)
self.wait()
v_parts = [v]
if full_v:
v_parts += [v.proj, v.proj_line]
self.play(
*[v_part.restore for v_part in v_parts],
rate_func = there_and_back,
run_time = 2
)
self.wait()
self.play(*list(map(FadeOut, [
projector.proj, projector.proj_line
])))
class LurkingQuestion(TeacherStudentsScene):
def construct(self):
# self.teacher_says("That's the standard intro")
# self.wait()
# self.student_says(
# """
# Wait, why are the
# two views connected?
# """,
# index = 2,
# target_mode = "raise_left_hand",
# width = 6,
# )
self.play_student_changes(
"raise_right_hand", "confused", "raise_left_hand"
)
self.random_blink(5)
answer = OldTexText("""
The most satisfactory
answer comes from""",
"duality"
)
answer[-1].set_color_by_gradient(BLUE, YELLOW)
self.teacher_says(answer)
self.random_blink(2)
self.teacher_thinks("")
everything = VMobject(*self.get_mobjects())
self.play(ApplyPointwiseFunction(
lambda p : 10*(p+2*DOWN)/get_norm(p+2*DOWN),
everything
))
class TwoDToOneDScene(LinearTransformationScene):
CONFIG = {
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_X_RADIUS,
"y_radius" : FRAME_Y_RADIUS,
"secondary_line_ratio" : 1
},
"t_matrix" : [[2, 0], [1, 0]]
}
def setup(self):
self.number_line = NumberLine()
self.add(self.number_line)
LinearTransformationScene.setup(self)
class Introduce2Dto1DLinearTransformations(TwoDToOneDScene):
def construct(self):
number_line_words = OldTexText("Number line")
number_line_words.next_to(self.number_line, UP, buff = MED_SMALL_BUFF)
numbers = VMobject(*self.number_line.get_number_mobjects())
self.remove(self.number_line)
self.apply_transposed_matrix(self.t_matrix)
self.play(
ShowCreation(number_line),
*[Animation(v) for v in (self.i_hat, self.j_hat)]
)
self.play(*list(map(Write, [numbers, number_line_words])))
self.wait()
class Symbolic2To1DTransform(Scene):
def construct(self):
func = OldTex("L(", "\\vec{\\textbf{v}}", ")")
input_array = Matrix([2, 7])
input_array.set_color(YELLOW)
in_arrow = Arrow(LEFT, RIGHT, color = input_array.get_color())
func[1].set_color(input_array.get_color())
output_array = Matrix([1.8])
output_array.set_color(PINK)
out_arrow = Arrow(LEFT, RIGHT, color = output_array.get_color())
VMobject(
input_array, in_arrow, func, out_arrow, output_array
).arrange(RIGHT, buff = SMALL_BUFF)
input_brace = Brace(input_array, DOWN)
input_words = input_brace.get_text("2d input")
output_brace = Brace(output_array, UP)
output_words = output_brace.get_text("1d output")
input_words.set_color(input_array.get_color())
output_words.set_color(output_array.get_color())
special_words = OldTexText("Linear", "functions are quite special")
special_words.set_color_by_tex("Linear", BLUE)
special_words.to_edge(UP)
self.add(func, input_array)
self.play(
GrowFromCenter(input_brace),
Write(input_words)
)
mover = input_array.copy()
self.play(
Transform(mover, Dot().move_to(func)),
ShowCreation(in_arrow),
rate_func = rush_into,
run_time = 0.5
)
self.play(
Transform(mover, output_array),
ShowCreation(out_arrow),
rate_func = rush_from,
run_time = 0.5
)
self.play(
GrowFromCenter(output_brace),
Write(output_words)
)
self.wait()
self.play(Write(special_words))
self.wait()
class RecommendChapter3(Scene):
def construct(self):
title = OldTexText("""
Definitely watch Chapter 3
if you haven't already
""")
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
class OkayToIgnoreFormalProperties(Scene):
def construct(self):
title = OldTexText("Formal linearity properties")
title.to_edge(UP)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
h_line.next_to(title, DOWN)
v_tex, w_tex = ["\\vec{\\textbf{%s}}"%s for s in ("v", "w")]
additivity = OldTex(
"L(", v_tex, "+", w_tex, ") = ",
"L(", v_tex, ") + L(", w_tex, ")",
)
scaling = OldTex(
"L(", "c", v_tex, ") =", "c", "L(", v_tex, ")",
)
for tex_mob in additivity, scaling:
tex_mob.set_color_by_tex(v_tex, V_COLOR)
tex_mob.set_color_by_tex(w_tex, W_COLOR)
tex_mob.set_color_by_tex("c", GREEN)
additivity.next_to(h_line, DOWN, buff = MED_SMALL_BUFF)
scaling.next_to(additivity, DOWN, buff = MED_SMALL_BUFF)
words = OldTexText("We'll ignore these")
words.set_color(RED)
arrow = Arrow(DOWN, UP, color = RED)
arrow.next_to(scaling, DOWN)
words.next_to(arrow, DOWN)
randy = Randolph().to_corner(DOWN+LEFT)
morty = Mortimer().to_corner(DOWN+RIGHT)
self.add(randy, morty, title)
self.play(ShowCreation(h_line))
for tex_mob in additivity, scaling:
self.play(Write(tex_mob, run_time = 2))
self.play(
FadeIn(words),
ShowCreation(arrow),
)
self.play(
randy.look, LEFT,
morty.look, RIGHT,
)
self.wait()
class FormalVsVisual(Scene):
def construct(self):
title = OldTexText("Linearity")
title.set_color(BLUE)
title.to_edge(UP)
line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
line.next_to(title, DOWN)
v_line = Line(line.get_center(), FRAME_Y_RADIUS*DOWN)
formal = OldTexText("Formal definition")
visual = OldTexText("Visual intuition")
formal.next_to(line, DOWN).shift(FRAME_X_RADIUS*LEFT/2)
visual.next_to(line, DOWN).shift(FRAME_X_RADIUS*RIGHT/2)
v_tex, w_tex = ["\\vec{\\textbf{%s}}"%c for c in ("v", "w")]
additivity = OldTex(
"L(", v_tex, "+", w_tex, ") = ",
"L(", v_tex, ")+", "L(", w_tex, ")"
)
additivity.set_color_by_tex(v_tex, V_COLOR)
additivity.set_color_by_tex(w_tex, W_COLOR)
scaling = OldTex(
"L(", "c", v_tex, ")=", "c", "L(", v_tex, ")"
)
scaling.set_color_by_tex(v_tex, V_COLOR)
scaling.set_color_by_tex("c", GREEN)
visual_statement = OldTexText("""
Line of dots evenly spaced
dots remains evenly spaced
""")
visual_statement.set_submobject_colors_by_gradient(YELLOW, MAROON_B)
properties = VMobject(additivity, scaling)
properties.arrange(DOWN, buff = MED_SMALL_BUFF)
for text, mob in (formal, properties), (visual, visual_statement):
mob.scale(0.75)
mob.next_to(text, DOWN, buff = MED_SMALL_BUFF)
self.add(title)
self.play(*list(map(ShowCreation, [line, v_line])))
for mob in formal, visual, additivity, scaling, visual_statement:
self.play(Write(mob, run_time = 2))
self.wait()
class AdditivityProperty(TwoDToOneDScene):
CONFIG = {
"show_basis_vectors" : False,
"sum_before" : True
}
def construct(self):
v = Vector([2, 1], color = V_COLOR)
w = Vector([-1, 1], color = W_COLOR)
L, sum_tex, r_paren = symbols = self.get_symbols()
symbols.shift(4*RIGHT+2*UP)
self.add_foreground_mobject(sum_tex)
self.play(ShowCreation(v))
self.play(ShowCreation(w))
if self.sum_before:
sum_vect = self.play_sum(v, w)
else:
self.add_vector(v, animate = False)
self.add_vector(w, animate = False)
self.apply_transposed_matrix(self.t_matrix)
if not self.sum_before:
sum_vect = self.play_sum(v, w)
symbols.target = symbols.copy().next_to(sum_vect, UP)
VGroup(L, r_paren).set_color(BLACK)
self.play(Transform(symbols, symbols.target))
self.wait()
def play_sum(self, v, w):
sum_vect = Vector(v.get_end()+w.get_end(), color = SUM_COLOR)
self.play(w.shift, v.get_end(), path_arc = np.pi/4)
self.play(ShowCreation(sum_vect))
for vect in v, w:
vect.target = vect.copy()
vect.target.set_fill(opacity = 0)
vect.target.set_stroke(width = 0)
sum_vect.target = sum_vect
self.play(*[
Transform(mob, mob.target)
for mob in (v, w, sum_vect)
])
self.add_vector(sum_vect, animate = False)
return sum_vect
def get_symbols(self):
v_tex, w_tex = ["\\vec{\\textbf{%s}}"%c for c in ("v", "w")]
if self.sum_before:
tex_mob = OldTex(
"L(", v_tex, "+", w_tex, ")"
)
result = VGroup(
tex_mob[0],
VGroup(*tex_mob[1:4]),
tex_mob[4]
)
else:
tex_mob = OldTex(
"L(", v_tex, ")", "+", "L(", w_tex, ")"
)
result = VGroup(
VectorizedPoint(tex_mob.get_left()),
tex_mob,
VectorizedPoint(tex_mob.get_right()),
)
tex_mob.set_color_by_tex(v_tex, V_COLOR)
tex_mob.set_color_by_tex(w_tex, W_COLOR)
result[1].add_to_back(BackgroundRectangle(result[1]))
return result
class AdditivityPropertyPart2(AdditivityProperty):
CONFIG = {
"sum_before" : False
}
class ScalingProperty(TwoDToOneDScene):
CONFIG = {
"show_basis_vectors" : False,
"scale_before" : True,
"scalar" : 2,
}
def construct(self):
v = Vector([-1, 1], color = V_COLOR)
self.play(ShowCreation(v))
if self.scale_before:
scaled_vect = self.show_scaling(v)
self.add_vector(v, animate = False)
self.apply_transposed_matrix(self.t_matrix)
if not self.scale_before:
scaled_vect = self.show_scaling(v)
self.wait()
self.write_symbols(scaled_vect)
def show_scaling(self, v):
self.add_vector(v.copy().fade(), animate = False)
self.play(v.scale, self.scalar)
return v
def write_symbols(self, scaled_vect):
v_tex = "\\vec{\\textbf{v}}"
if self.scale_before:
tex_mob = OldTex(
"L(", "c", v_tex, ")"
)
tex_mob.next_to(scaled_vect, UP)
else:
tex_mob = OldTex(
"c", "L(", v_tex, ")",
)
tex_mob.next_to(scaled_vect, DOWN)
tex_mob.set_color_by_tex(v_tex, V_COLOR)
tex_mob.set_color_by_tex("c", GREEN)
self.play(Write(tex_mob))
self.wait()
class ScalingPropertyPart2(ScalingProperty):
CONFIG = {
"scale_before" : False
}
class ThisTwoDTo1DTransformWithDots(TwoDTo1DTransformWithDots):
pass
class NonLinearFailsDotTest(TwoDTo1DTransformWithDots):
def construct(self):
line = NumberLine()
self.add(line, *self.get_mobjects())
offset = LEFT+DOWN
vect = 2*RIGHT+UP
dots = VMobject(*[
Dot(offset + a*vect, radius = 0.075)
for a in np.linspace(-2, 3, 18)
])
dots.set_submobject_colors_by_gradient(YELLOW_B, YELLOW_C)
func = lambda p : (p[0]**2 - p[1]**2)*RIGHT
new_dots = VMobject(*[
Dot(
func(dot.get_center()),
color = dot.get_color(),
radius = dot.radius
)
for dot in dots
])
words = OldTexText(
"Line of dots", "do not", "remain evenly spaced"
)
words.set_color_by_tex("do not", RED)
words.next_to(line, UP, buff = MED_SMALL_BUFF)
array_tex = matrix_to_tex_string(["x", "y"])
equation = OldTex(
"f", "\\left(%s \\right)"%array_tex, " = x^2 - y^2"
)
for part in equation:
part.add_to_back(BackgroundRectangle(part))
equation.to_corner(UP+LEFT)
self.add_foreground_mobject(equation)
self.play(Write(dots))
self.apply_nonlinear_transformation(
func,
added_anims = [Transform(dots, new_dots)]
)
self.play(Write(words))
self.wait()
class AlwaysfollowIHatJHat(TeacherStudentsScene):
def construct(self):
i_tex, j_tex = ["$\\hat{\\%smath}$"%c for c in ("i", "j")]
words = OldTexText(
"Always follow", i_tex, "and", j_tex
)
words.set_color_by_tex(i_tex, X_COLOR)
words.set_color_by_tex(j_tex, Y_COLOR)
self.teacher_says(words)
students = VMobject(*self.get_students())
ponderers = VMobject(*[
pi.copy().change_mode("pondering")
for pi in students
])
self.play(Transform(
students, ponderers,
lag_ratio = 0.5,
run_time = 2
))
self.random_blink(2)
class ShowMatrix(TwoDToOneDScene):
def construct(self):
self.apply_transposed_matrix(self.t_matrix)
self.play(Write(self.number_line.get_numbers()))
self.show_matrix()
def show_matrix(self):
for vect, char in zip([self.i_hat, self.j_hat], ["i", "j"]):
vect.words = OldTexText(
"$\\hat\\%smath$ lands on"%char,
str(int(vect.get_end()[0]))
)
direction = UP if vect is self.i_hat else DOWN
vect.words.next_to(vect.get_end(), direction, buff = LARGE_BUFF)
vect.words.set_color(vect.get_color())
matrix = Matrix([[1, 2]])
matrix_words = OldTexText("Transformation matrix: ")
matrix_group = VMobject(matrix_words, matrix)
matrix_group.arrange()
matrix_group.to_edge(UP)
entries = matrix.get_entries()
self.play(
Write(matrix_words),
Write(matrix.get_brackets()),
run_time = 1
)
for i, vect in enumerate([self.i_hat, self.j_hat]):
self.play(
Write(vect.words, run_time = 1),
ApplyMethod(vect.shift, 0.5*UP, rate_func = there_and_back)
)
self.wait()
self.play(vect.words[1].copy().move_to, entries[i])
self.wait()
class FollowVectorViaCoordinates(TwoDToOneDScene):
CONFIG = {
"t_matrix" : [[1, 0], [-2, 0]],
"v_coords" : [3, 3],
"written_v_coords" : ["x", "y"],
"concrete" : False,
}
def construct(self):
v = Vector(self.v_coords)
array = Matrix(self.v_coords if self.concrete else self.written_v_coords)
array.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR)
array.add_to_back(BackgroundRectangle(array))
v_label = OldTex("\\vec{\\textbf{v}}", "=")
v_label[0].set_color(YELLOW)
v_label.next_to(v.get_end(), RIGHT)
v_label.add_background_rectangle()
array.next_to(v_label, RIGHT)
bases = self.i_hat, self.j_hat
basis_labels = self.get_basis_vector_labels(direction = "right")
scaling_anim_tuples = self.get_scaling_anim_tuples(
basis_labels, array, [DOWN, RIGHT]
)
self.play(*list(map(Write, basis_labels)))
self.play(
ShowCreation(v),
Write(array),
Write(v_label)
)
self.add_foreground_mobject(v_label, array)
self.add_vector(v, animate = False)
self.wait()
to_fade = basis_labels
for i, anim_tuple in enumerate(scaling_anim_tuples):
self.play(*anim_tuple)
movers = self.get_mobjects_from_last_animation()
to_fade += movers[:-1]
if i == 1:
self.play(*[
ApplyMethod(m.shift, self.v_coords[0]*RIGHT)
for m in movers
])
self.wait()
self.play(
*list(map(FadeOut, to_fade)) + [
vect.restore
for vect in (self.i_hat, self.j_hat)
]
)
self.apply_transposed_matrix(self.t_matrix)
self.play(Write(self.number_line.get_numbers(), run_time = 1))
self.play(
self.i_hat.shift, 0.5*UP,
self.j_hat.shift, DOWN,
)
if self.concrete:
new_labels = [
OldTex("(%d)"%num)
for num in self.t_matrix[:,0]
]
else:
new_labels = [
OldTex("L(\\hat{\\%smath})"%char)
for char in ("i", "j")
]
new_labels[0].set_color(X_COLOR)
new_labels[1].set_color(Y_COLOR)
new_labels.append(
OldTex("L(\\vec{\\textbf{v}})").set_color(YELLOW)
)
for label, vect, direction in zip(new_labels, list(bases) + [v], [UP, DOWN, UP]):
label.next_to(vect, direction)
self.play(*list(map(Write, new_labels)))
self.wait()
scaling_anim_tuples = self.get_scaling_anim_tuples(
new_labels, array, [UP, DOWN]
)
for i, anim_tuple in enumerate(scaling_anim_tuples):
self.play(*anim_tuple)
movers = VMobject(*self.get_mobjects_from_last_animation())
self.wait()
self.play(movers.shift, self.i_hat.get_end()[0]*RIGHT)
self.wait()
if self.concrete:
final_label = OldTex(str(int(v.get_end()[0])))
final_label.move_to(new_labels[-1])
final_label.set_color(new_labels[-1].get_color())
self.play(Transform(new_labels[-1], final_label))
self.wait()
def get_scaling_anim_tuples(self, labels, array, directions):
scaling_anim_tuples = []
bases = self.i_hat, self.j_hat
quints = list(zip(
bases, self.v_coords, labels,
array.get_entries(), directions
))
for basis, scalar, label, entry, direction in quints:
basis.save_state()
basis.scaled = basis.copy().scale(scalar)
basis.scaled.shift(basis.get_start() - basis.scaled.get_start())
scaled_label = VMobject(entry.copy(), label.copy())
entry.target, label.target = scaled_label.split()
entry.target.next_to(label.target, LEFT)
scaled_label.next_to(
basis.scaled,
direction
)
scaling_anim_tuples.append((
ApplyMethod(label.move_to, label.target),
ApplyMethod(entry.copy().move_to, entry.target),
Transform(basis, basis.scaled),
))
return scaling_anim_tuples
class FollowVectorViaCoordinatesConcrete(FollowVectorViaCoordinates):
CONFIG = {
"v_coords" : [4, 3],
"concrete" : True
}
class TwoDOneDMatrixMultiplication(Scene):
CONFIG = {
"matrix" : [[1, -2]],
"vector" : [4, 3],
"order_left_to_right" : False,
}
def construct(self):
matrix = Matrix(self.matrix)
matrix.label = "Transform"
vector = Matrix(self.vector)
vector.label = "Vector"
matrix.next_to(vector, LEFT, buff = 0.2)
self.color_matrix_and_vector(matrix, vector)
for m, vect in zip([matrix, vector], [UP, DOWN]):
m.brace = Brace(m, vect)
m.label = m.brace.get_text(m.label)
matrix.label.set_color(BLUE)
vector.label.set_color(MAROON_B)
for m in vector, matrix:
self.play(Write(m))
self.play(
GrowFromCenter(m.brace),
Write(m.label),
run_time = 1
)
self.wait()
self.show_product(matrix, vector)
def show_product(self, matrix, vector):
starter_pairs = list(zip(vector.get_entries(), matrix.get_entries()))
pairs = [
VMobject(
e1.copy(), OldTex("\\cdot"), e2.copy()
).arrange(
LEFT if self.order_left_to_right else RIGHT,
)
for e1, e2 in starter_pairs
]
symbols = list(map(Tex, ["=", "+"]))
equation = VMobject(*it.chain(*list(zip(symbols, pairs))))
equation.arrange(align_using_submobjects = True)
equation.next_to(vector, RIGHT)
self.play(Write(VMobject(*symbols)))
for starter_pair, pair in zip(starter_pairs, pairs):
self.play(Transform(
VMobject(*starter_pair).copy(),
pair,
path_arc = -np.pi/2
))
self.wait()
def color_matrix_and_vector(self, matrix, vector):
for m in matrix, vector:
x, y = m.get_entries()
x.set_color(X_COLOR)
y.set_color(Y_COLOR)
class AssociationBetweenMatricesAndVectors(Scene):
CONFIG = {
"matrices" : [
[[2, 7]],
[[1, -2]]
]
}
def construct(self):
matrices_words = OldTexText("$1\\times 2$ matrices")
matrices_words.set_color(BLUE)
vectors_words = OldTexText("2d vectors")
vectors_words.set_color(YELLOW)
arrow = DoubleArrow(LEFT, RIGHT, color = WHITE)
VGroup(
matrices_words, arrow, vectors_words
).arrange(buff = MED_SMALL_BUFF)
matrices = VGroup(*list(map(Matrix, self.matrices)))
vectors = VGroup(*list(map(Matrix, [m[0] for m in self.matrices])))
for m in list(matrices) + list(vectors):
x, y = m.get_entries()
x.set_color(X_COLOR)
y.set_color(Y_COLOR)
matrices.words = matrices_words
vectors.words = vectors_words
for group in matrices, vectors:
for m, direction in zip(group, [UP, DOWN]):
m.next_to(group.words, direction, buff = MED_SMALL_BUFF)
self.play(*list(map(Write, [matrices_words, vectors_words])))
self.play(ShowCreation(arrow))
self.wait()
self.play(FadeIn(vectors))
vectors.save_state()
self.wait()
self.play(Transform(
vectors, matrices,
path_arc = np.pi/2,
lag_ratio = 0.5,
run_time = 2,
))
self.wait()
self.play(
vectors.restore,
path_arc = -np.pi/2,
lag_ratio = 0.5,
run_time = 2
)
self.wait()
class WhatAboutTheGeometricView(TeacherStudentsScene):
def construct(self):
self.student_says("""
What does this association
mean geometrically?
""",
target_mode = "raise_right_hand"
)
self.play_student_changes("pondering", "raise_right_hand", "pondering")
self.random_blink(2)
class SomeKindOfConnection(Scene):
CONFIG = {
"v_coords" : [2, 3]
}
def construct(self):
width = FRAME_X_RADIUS-1
plane = NumberPlane(x_radius = 4, y_radius = 6)
squish_plane = plane.copy()
i_hat = Vector([1, 0], color = X_COLOR)
j_hat = Vector([0, 1], color = Y_COLOR)
vect = Vector(self.v_coords, color = YELLOW)
plane.add(vect, i_hat, j_hat)
plane.set_width(FRAME_X_RADIUS)
plane.to_edge(LEFT, buff = 0)
plane.remove(vect, i_hat, j_hat)
squish_plane.apply_function(
lambda p : np.dot(p, [4, 1, 0])*RIGHT
)
squish_plane.add(Vector(self.v_coords[1]*RIGHT, color = Y_COLOR))
squish_plane.add(Vector(self.v_coords[0]*RIGHT, color = X_COLOR))
squish_plane.scale(width/(FRAME_WIDTH))
plane.add(j_hat, i_hat)
number_line = NumberLine().stretch_to_fit_width(width)
number_line.to_edge(RIGHT)
squish_plane.move_to(number_line)
numbers = number_line.get_numbers(*list(range(-6, 8, 2)))
v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS)
v_line.set_color(GREY)
v_line.set_stroke(width = 10)
matrix = Matrix([self.v_coords])
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(number_line, UP, buff = LARGE_BUFF)
v_coords = Matrix(self.v_coords)
v_coords.set_column_colors(YELLOW)
v_coords.scale(0.75)
v_coords.next_to(vect.get_end(), RIGHT)
for array in matrix, v_coords:
array.add_to_back(BackgroundRectangle(array))
self.play(*list(map(ShowCreation, [
plane, number_line, v_line
]))+[
Write(numbers, run_time = 2)
])
self.play(Write(matrix, run_time = 1))
mover = plane.copy()
interim = plane.copy().scale(0.8).move_to(number_line)
for target in interim, squish_plane:
self.play(
Transform(mover, target),
Animation(plane),
run_time = 1,
)
self.wait()
self.play(ShowCreation(vect))
self.play(Transform(matrix.copy(), v_coords))
self.wait()
class AnExampleWillClarify(TeacherStudentsScene):
def construct(self):
self.teacher_says("An example will clarify...")
self.play_student_changes(*["happy"]*3)
self.random_blink(3)
class ImagineYouDontKnowThis(Scene):
def construct(self):
words = OldTexText("Imagine you don't know this")
words.set_color(RED)
words.scale(1.5)
self.play(Write(words))
self.wait()
class ProjectOntoUnitVectorNumberline(VectorScene):
CONFIG = {
"randomize_dots" : True,
"animate_setup" : True,
"zoom_factor" : 1,
"u_hat_color" : YELLOW,
"tilt_angle" : np.pi/6,
}
def setup(self):
plane = self.add_plane()
plane.fade()
u_hat = Vector([1, 0], color = self.u_hat_color)
u_brace = Brace(u_hat, UP)
u_hat.rotate(self.tilt_angle)
u_hat.label = OldTex("\\hat{\\textbf{u}}")
u_hat.label.set_color(u_hat.get_color())
u_hat.label.next_to(u_hat.get_end(), UP+LEFT)
one = OldTex("1")
u_brace.put_at_tip(one)
u_brace.add(one)
u_brace.rotate(u_hat.get_angle())
one.rotate(-u_hat.get_angle())
number_line = NumberLine(x_min = -9, x_max = 9)
numbers = number_line.get_numbers()
VGroup(number_line, numbers).rotate(u_hat.get_angle())
if self.animate_setup:
self.play(
ShowCreation(number_line),
Write(numbers),
run_time = 3
)
self.wait()
self.play(ShowCreation(u_hat))
self.play(FadeIn(u_brace))
self.play(FadeOut(u_brace))
self.play(Write(u_hat.label))
self.wait()
else:
self.add(number_line, numbers, u_hat)
if self.zoom_factor != 1:
for mob in plane, u_hat:
mob.target = mob.copy().scale(self.zoom_factor)
number_line.target = number_line.copy()
number_line.target.rotate(-u_hat.get_angle())
number_line.target.stretch(self.zoom_factor, 0)
numbers.target = number_line.target.get_numbers()
number_line.target.rotate(u_hat.get_angle())
numbers.target.rotate(u_hat.get_angle())
self.play(*[
Transform(mob, mob.target)
for mob in self.get_mobjects()
])
self.wait()
self.number_line, self.numbers, self.u_hat = number_line, numbers, u_hat
def construct(self):
vectors = self.get_vectors(randomize = self.randomize_dots)
dots = self.get_dots(vectors)
proj_dots = self.get_proj_dots(dots)
proj_lines = self.get_proj_lines(dots, proj_dots)
self.wait()
self.play(FadeIn(vectors, lag_ratio = 0.5))
self.wait()
self.play(Transform(vectors, dots))
self.wait()
self.play(ShowCreation(proj_lines))
self.wait()
self.play(
self.number_line.set_stroke, None, 2,
Transform(vectors, proj_dots),
Transform(proj_lines, proj_dots),
Animation(self.u_hat),
lag_ratio = 0.5,
run_time = 2
)
self.wait()
def get_vectors(self, num_vectors = 10, randomize = True):
x_max = FRAME_X_RADIUS - 1
y_max = FRAME_Y_RADIUS - 1
x_vals = np.linspace(-x_max, x_max, num_vectors)
y_vals = np.linspace(y_max, -y_max, num_vectors)
if randomize:
random.shuffle(y_vals)
vectors = VGroup(*[
Vector(x*RIGHT + y*UP)
for x, y in zip(x_vals, y_vals)
])
vectors.set_color_by_gradient(PINK, MAROON_B)
return vectors
def get_dots(self, vectors):
return VGroup(*[
Dot(v.get_end(), color = v.get_color(), radius = 0.075)
for v in vectors
])
def get_proj_dots(self, dots):
return VGroup(*[
dot.copy().move_to(get_projection(
dot.get_center(), self.u_hat.get_end()
))
for dot in dots
])
def get_proj_lines(self, dots, proj_dots):
return VGroup(*[
DashedLine(
d1.get_center(), d2.get_center(),
buff = 0, color = d1.get_color(),
dash_length = 0.15
)
for d1, d2 in zip(dots, proj_dots)
])
class ProjectionFunctionSymbol(Scene):
def construct(self):
v_tex = "\\vec{\\textbf{v}}"
equation = OldTex(
"P(", v_tex, ")=",
"\\text{number }", v_tex, "\\text{ lands on}"
)
equation.set_color_by_tex(v_tex, YELLOW)
equation.shift(2*UP)
words = OldTexText(
"This projection function is", "linear"
)
words.set_color_by_tex("linear", BLUE)
arrow = Arrow(
words.get_top(), equation[0].get_bottom(),
color = BLUE
)
self.add(VGroup(*equation[:3]))
self.play(Write(VGroup(*equation[3:])))
self.wait()
self.play(Write(words), ShowCreation(arrow))
self.wait()
class ProjectLineOfDots(ProjectOntoUnitVectorNumberline):
CONFIG = {
"randomize_dots" : False,
"animate_setup" : False,
}
class ProjectSingleVectorOnUHat(ProjectOntoUnitVectorNumberline):
CONFIG = {
"animate_setup" : False
}
def construct(self):
v = Vector([-3, 1], color = PINK)
v.proj = get_vect_mob_projection(v, self.u_hat)
v.proj_line = DashedLine(v.get_end(), v.proj.get_end())
v.proj_line.set_color(v.get_color())
v_tex = "\\vec{\\textbf{v}}"
u_tex = self.u_hat.label.get_tex()
v.label = OldTex(v_tex)
v.label.set_color(v.get_color())
v.label.next_to(v.get_end(), LEFT)
dot_product = OldTex(v_tex, "\\cdot", u_tex)
dot_product.set_color_by_tex(v_tex, v.get_color())
dot_product.set_color_by_tex(u_tex, self.u_hat.get_color())
dot_product.next_to(ORIGIN, UP, buff = MED_SMALL_BUFF)
dot_product.rotate(self.tilt_angle)
dot_product.shift(v.proj.get_end())
dot_product.add_background_rectangle()
v.label.add_background_rectangle()
self.play(
ShowCreation(v),
Write(v.label),
)
self.wait()
self.play(
ShowCreation(v.proj_line),
Transform(v.copy(), v.proj)
)
self.wait()
self.play(
FadeOut(v),
FadeOut(v.proj_line),
FadeOut(v.label),
Write(dot_product)
)
self.wait()
class AskAboutProjectionMatrix(Scene):
def construct(self):
matrix = Matrix([["?", "?"]])
matrix.set_column_colors(X_COLOR, Y_COLOR)
words = OldTexText("Projection matrix:")
VMobject(words, matrix).arrange(buff = MED_SMALL_BUFF).shift(UP)
basis_words = [
OldTexText("Where", "$\\hat{\\%smath}$"%char, "lands")
for char in ("i", "j")
]
for b_words, q_mark, direction in zip(basis_words, matrix.get_entries(), [UP, DOWN]):
b_words.next_to(q_mark, direction, buff = 1.5)
b_words.arrow = Arrow(b_words, q_mark, color = q_mark.get_color())
b_words.set_color(q_mark.get_color())
self.play(
Write(words),
Write(matrix)
)
self.wait()
for b_words in basis_words:
self.play(
Write(b_words),
ShowCreation(b_words.arrow)
)
self.wait()
class ProjectBasisVectors(ProjectOntoUnitVectorNumberline):
CONFIG = {
"animate_setup" : False,
"zoom_factor" : 3,
"u_hat_color" : YELLOW,
"tilt_angle" : np.pi/5,
}
def construct(self):
basis_vectors = self.get_basis_vectors()
i_hat, j_hat = basis_vectors
for vect in basis_vectors:
vect.scale(self.zoom_factor)
dots = self.get_dots(basis_vectors)
proj_dots = self.get_proj_dots(dots)
proj_lines = self.get_proj_lines(dots, proj_dots)
for dot in proj_dots:
dot.scale(0.1)
proj_basis = VGroup(*[
get_vect_mob_projection(vector, self.u_hat)
for vector in basis_vectors
])
i_tex, j_tex = ["$\\hat{\\%smath}$"%char for char in ("i", "j")]
question = OldTexText(
"Where do", i_tex, "and", j_tex, "land?"
)
question.set_color_by_tex(i_tex, X_COLOR)
question.set_color_by_tex(j_tex, Y_COLOR)
question.add_background_rectangle()
matrix = Matrix([["u_x", "u_y"]])
VGroup(question, matrix).arrange(DOWN).to_corner(
UP+LEFT, buff = MED_SMALL_BUFF/2
)
matrix_rect = BackgroundRectangle(matrix)
i_label = OldTex(i_tex[1:-1])
j_label = OldTex(j_tex[1:-1])
u_label = OldTex("\\hat{\\textbf{u}}")
trips = list(zip(
(i_label, j_label, u_label),
(i_hat, j_hat, self.u_hat),
(DOWN+RIGHT, UP+LEFT, UP),
))
for label, vect, direction in trips:
label.set_color(vect.get_color())
label.scale(1.2)
label.next_to(vect.get_end(), direction, buff = MED_SMALL_BUFF/2)
self.play(Write(u_label, run_time = 1))
self.play(*list(map(ShowCreation, basis_vectors)))
self.play(*list(map(Write, [i_label, j_label])), run_time = 1)
self.play(ShowCreation(proj_lines))
self.play(
Write(question),
ShowCreation(matrix_rect),
Write(matrix.get_brackets()),
run_time = 2,
)
to_remove = [proj_lines]
quads = list(zip(basis_vectors, proj_basis, proj_lines, proj_dots))
for vect, proj_vect, proj_line, proj_dot in quads:
self.play(Transform(vect.copy(), proj_vect))
to_remove += self.get_mobjects_from_last_animation()
self.wait()
self.play(*list(map(FadeOut, to_remove)))
# self.show_u_coords(u_label)
u_x, u_y = [
OldTex("u_%s"%c).set_color(self.u_hat.get_color())
for c in ("x", "y")
]
matrix_x, matrix_y = matrix.get_entries()
self.remove(j_hat, j_label)
self.show_symmetry(i_hat, u_x, matrix_x)
self.add(j_hat, j_label)
self.remove(i_hat, i_label)
self.show_symmetry(j_hat, u_y, matrix_y)
# def show_u_coords(self, u_label):
# coords = Matrix(["u_x", "u_y"])
# x, y = coords.get_entries()
# x.set_color(X_COLOR)
# y.set_color(Y_COLOR)
# coords.add_to_back(BackgroundRectangle(coords))
# eq = OldTex("=")
# eq.next_to(u_label, RIGHT)
# coords.next_to(eq, RIGHT)
# self.play(*map(FadeIn, [eq, coords]))
# self.wait()
# self.u_coords = coords
def show_symmetry(self, vect, coord, coord_landing_spot):
starting_mobjects = list(self.get_mobjects())
line = DashedLine(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT)
words = OldTexText("Line of symmetry")
words.next_to(ORIGIN, UP+LEFT)
words.shift(LEFT)
words.add_background_rectangle()
angle = np.mean([vect.get_angle(), self.u_hat.get_angle()])
VGroup(line, words).rotate(angle)
self.play(ShowCreation(line))
if vect.get_end()[0] > 0.1:#is ihat
self.play(Write(words, run_time = 1))
vect.proj = get_vect_mob_projection(vect, self.u_hat)
self.u_hat.proj = get_vect_mob_projection(self.u_hat, vect)
for v in vect, self.u_hat:
v.proj_line = DashedLine(
v.get_end(), v.proj.get_end(),
color = v.get_color()
)
v.proj_line.fade()
v.tick = Line(0.1*DOWN, 0.1*UP, color = WHITE)
v.tick.rotate(v.proj.get_angle())
v.tick.shift(v.proj.get_end())
v.q_mark = OldTexText("?")
v.q_mark.next_to(v.tick, v.proj.get_end()-v.get_end())
self.play(ShowCreation(v.proj_line))
self.play(Transform(v.copy(), v.proj))
self.remove(*self.get_mobjects_from_last_animation())
self.add(v.proj)
self.wait()
for v in vect, self.u_hat:
self.play(
ShowCreation(v.tick),
Write(v.q_mark)
)
self.wait()
for v in self.u_hat, vect:
coord_copy = coord.copy().move_to(v.q_mark)
self.play(Transform(v.q_mark, coord_copy))
self.wait()
final_coord = coord_copy.copy()
self.play(final_coord.move_to, coord_landing_spot)
added_mobjects = [
mob
for mob in self.get_mobjects()
if mob not in starting_mobjects + [final_coord]
]
self.play(*list(map(FadeOut, added_mobjects)))
class ShowSingleProjection(ProjectBasisVectors):
CONFIG = {
"zoom_factor" : 1
}
def construct(self):
vector = Vector([5, - 1], color = MAROON_B)
proj = get_vect_mob_projection(vector, self.u_hat)
proj_line = DashedLine(
vector.get_end(), proj.get_end(),
color = vector.get_color()
)
coords = Matrix(["x", "y"])
coords.get_entries().set_color(vector.get_color())
coords.add_to_back(BackgroundRectangle(coords))
coords.next_to(vector.get_end(), RIGHT)
u_label = OldTex("\\hat{\\textbf{u}}")
u_label.next_to(self.u_hat.get_end(), UP)
u_label.add_background_rectangle()
self.add(u_label)
self.play(ShowCreation(vector))
self.play(Write(coords))
self.wait()
self.play(ShowCreation(proj_line))
self.play(
Transform(vector.copy(), proj),
Animation(self.u_hat)
)
self.wait()
class GeneralTwoDOneDMatrixMultiplication(TwoDOneDMatrixMultiplication):
CONFIG = {
"matrix" : [["u_x", "u_y"]],
"vector" : ["x", "y"],
"order_left_to_right" : True,
}
def construct(self):
TwoDOneDMatrixMultiplication.construct(self)
everything = VGroup(*self.get_mobjects())
to_fade = [m for m in everything if isinstance(m, Brace) or isinstance(m, TexText)]
u = Matrix(self.matrix[0])
v = Matrix(self.vector)
self.color_matrix_and_vector(u, v)
dot_product = VGroup(u, OldTex("\\cdot"), v)
dot_product.arrange()
dot_product.shift(2*RIGHT+DOWN)
words = VGroup(
OldTexText("Matrix-vector product"),
OldTex("\\Updownarrow"),
OldTexText("Dot product")
)
words[0].set_color(BLUE)
words[2].set_color(GREEN)
words.arrange(DOWN)
words.to_edge(LEFT)
self.play(
everything.to_corner, UP+RIGHT,
*list(map(FadeOut, to_fade))
)
self.remove(everything)
self.add(*everything)
self.remove(*to_fade)
self.play(Write(words, run_time = 2))
self.play(ShowCreation(dot_product))
self.show_product(u, v)
def color_matrix_and_vector(self, matrix, vector):
colors = [X_COLOR, Y_COLOR]
for coord, color in zip(matrix.get_entries(), colors):
coord[0].set_color(YELLOW)
coord[1].set_color(color)
vector.get_entries().set_color(MAROON_B)
class UHatIsTransformInDisguise(Scene):
def construct(self):
u_tex = "$\\hat{\\textbf{u}}$"
words = OldTexText(
u_tex,
"is secretly a \\\\",
"transform",
"in disguise",
)
words.set_color_by_tex(u_tex, YELLOW)
words.set_color_by_tex("transform", BLUE)
words.scale(2)
self.play(Write(words))
self.wait()
class AskAboutNonUnitVectors(TeacherStudentsScene):
def construct(self):
self.student_says(
"What about \\\\ non-unit vectors",
target_mode = "raise_left_hand"
)
self.random_blink(2)
class ScaleUpUHat(ProjectOntoUnitVectorNumberline) :
CONFIG = {
"animate_setup" : False,
"u_hat_color" : YELLOW,
"tilt_angle" : np.pi/6,
"scalar" : 3,
}
def construct(self):
self.scale_u_hat()
self.show_matrix()
self.transform_basis_vectors()
self.transform_some_vector()
def scale_u_hat(self):
self.u_hat.coords = Matrix(["u_x", "u_y"])
new_u = self.u_hat.copy().scale(self.scalar)
new_u.coords = Matrix([
"%du_x"%self.scalar,
"%du_y"%self.scalar,
])
for v in self.u_hat, new_u:
v.coords.get_entries().set_color(YELLOW)
v.coords.add_to_back(BackgroundRectangle(v.coords))
v.coords.next_to(v.get_end(), UP+LEFT)
self.play(Write(self.u_hat.coords))
self.play(
Transform(self.u_hat, new_u),
Transform(self.u_hat.coords, new_u.coords)
)
self.wait()
def show_matrix(self):
matrix = Matrix([list(self.u_hat.coords.get_entries().copy())])
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.add_to_back(BackgroundRectangle(matrix))
brace = Brace(matrix)
words = OldTexText(
"\\centering Associated\\\\",
"transformation"
)
words.set_color_by_tex("transformation", BLUE)
words.add_background_rectangle()
brace.put_at_tip(words)
VGroup(matrix, brace, words).to_corner(UP+LEFT)
self.play(Transform(
self.u_hat.coords, matrix
))
self.play(
GrowFromCenter(brace),
Write(words, run_time = 2)
)
self.wait()
self.matrix_words = words
def transform_basis_vectors(self):
start_state = list(self.get_mobjects())
bases = self.get_basis_vectors()
for b, char in zip(bases, ["x", "y"]):
b.proj = get_vect_mob_projection(b, self.u_hat)
b.proj_line = DashedLine(
b.get_end(), b.proj.get_end(),
dash_length = 0.05
)
b.proj.label = OldTex("u_%s"%char)
b.proj.label.set_color(b.get_color())
b.scaled_proj = b.proj.copy().scale(self.scalar)
b.scaled_proj.label = OldTex("3u_%s"%char)
b.scaled_proj.label.set_color(b.get_color())
for v, direction in zip([b.proj, b.scaled_proj], [UP, UP+LEFT]):
v.label.add_background_rectangle()
v.label.next_to(v.get_end(), direction)
self.play(*list(map(ShowCreation, bases)))
for b in bases:
mover = b.copy()
self.play(ShowCreation(b.proj_line))
self.play(Transform(mover, b.proj))
self.play(Write(b.proj.label))
self.wait()
self.play(
Transform(mover, b.scaled_proj),
Transform(b.proj.label, b.scaled_proj.label)
)
self.wait()
self.play(*list(map(FadeOut, [
mob
for mob in self.get_mobjects()
if mob not in start_state
])))
def transform_some_vector(self):
words = OldTexText(
"\\centering Project\\\\",
"then scale"
)
project, then_scale = words.split()
words.add_background_rectangle()
words.move_to(self.matrix_words, aligned_edge = UP)
v = Vector([3, -1], color = MAROON_B)
proj = get_vect_mob_projection(v, self.u_hat)
proj_line = DashedLine(
v.get_end(), proj.get_end(),
color = v.get_color()
)
mover = v.copy()
self.play(ShowCreation(v))
self.play(Transform(self.matrix_words, words))
self.play(ShowCreation(proj_line))
self.play(
Transform(mover, proj),
project.set_color, YELLOW
)
self.wait()
self.play(
mover.scale, self.scalar,
then_scale.set_color, YELLOW
)
self.wait()
class NoticeWhatHappenedHere(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
Notice what
happened here
""")
self.play_student_changes(*["pondering"]*3)
self.random_blink()
class AbstractNumericAssociation(AssociationBetweenMatricesAndVectors):
CONFIG = {
"matrices" : [
[["u_x", "u_y"]]
]
}
class TwoDOneDTransformationSeparateSpace(Scene):
CONFIG = {
"v_coords" : [4, 1]
}
def construct(self):
width = FRAME_X_RADIUS-1
plane = NumberPlane(x_radius = 6, y_radius = 7)
squish_plane = plane.copy()
i_hat = Vector([1, 0], color = X_COLOR)
j_hat = Vector([0, 1], color = Y_COLOR)
vect = Vector(self.v_coords, color = YELLOW)
plane.add(vect, i_hat, j_hat)
plane.set_width(FRAME_X_RADIUS)
plane.to_edge(LEFT, buff = 0)
plane.remove(vect, i_hat, j_hat)
squish_plane.apply_function(
lambda p : np.dot(p, [4, 1, 0])*RIGHT
)
squish_plane.add(Vector(self.v_coords[0]*RIGHT, color = X_COLOR))
squish_plane.add(Vector(self.v_coords[1]*RIGHT, color = Y_COLOR))
squish_plane.scale(width/(FRAME_WIDTH))
plane.add(i_hat, j_hat)
number_line = NumberLine().stretch_to_fit_width(width)
number_line.to_edge(RIGHT)
squish_plane.move_to(number_line)
numbers = number_line.get_numbers(*list(range(-6, 8, 2)))
v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS)
v_line.set_color(GREY)
v_line.set_stroke(width = 10)
matrix = Matrix([self.v_coords])
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(number_line, UP, buff = LARGE_BUFF)
v_coords = Matrix(self.v_coords)
v_coords.set_column_colors(YELLOW)
v_coords.scale(0.75)
v_coords.next_to(vect.get_end(), RIGHT)
for array in matrix, v_coords:
array.add_to_back(BackgroundRectangle(array))
start_words = OldTexText(
"\\centering Any time you have a \\\\",
"2d-to-1d linear transform..."
)
end_words = OldTexText(
"\\centering ...it's associated \\\\",
"with some vector",
)
for words in start_words, end_words:
words.add_background_rectangle()
words.scale(0.8)
start_words.next_to(ORIGIN, RIGHT, buff = MED_SMALL_BUFF).to_edge(UP)
end_words.next_to(ORIGIN, DOWN+LEFT, buff = MED_SMALL_BUFF/2)
self.play(*list(map(ShowCreation, [
plane, number_line, v_line
]))+[
Write(numbers, run_time = 2)
])
self.play(Write(start_words, run_time = 2))
self.play(Write(matrix, run_time = 1))
mover = plane.copy()
interim = plane.copy().scale(0.8).move_to(number_line)
for target in interim, squish_plane:
self.play(
Transform(mover, target),
Animation(plane),
Animation(start_words),
run_time = 1,
)
self.wait()
self.play(Transform(start_words.copy(), end_words))
self.play(ShowCreation(vect))
self.play(Transform(matrix.copy(), v_coords))
self.wait()
class IsntThisBeautiful(TeacherStudentsScene):
def construct(self):
self.teacher.look(DOWN+LEFT)
self.teacher_says(
"Isn't this", "beautiful",
target_mode = "surprised"
)
for student in self.get_students():
self.play(student.change_mode, "happy")
self.random_blink()
duality_words = OldTexText(
"It's called", "duality"
)
duality_words[1].set_color_by_gradient(BLUE, YELLOW)
self.teacher_says(duality_words)
self.random_blink()
class RememberGraphDuality(Scene):
def construct(self):
words = OldTexText("""
\\centering
Some of you may remember an
early video I did on graph duality
""")
words.to_edge(UP)
self.play(Write(words))
self.wait()
class LooseDualityDescription(Scene):
def construct(self):
duality = OldTexText("Duality")
duality.set_color_by_gradient(BLUE, YELLOW)
arrow = OldTex("\\Leftrightarrow")
words = OldTexText("Natural-but-surprising", "correspondence")
words[1].set_color_by_gradient(BLUE, YELLOW)
VGroup(duality, arrow, words).arrange(buff = MED_SMALL_BUFF)
self.add(duality)
self.play(Write(arrow))
self.play(Write(words))
self.wait()
class DualOfAVector(ScaleUpUHat):
pass #Exact copy
class DualOfATransform(TwoDOneDTransformationSeparateSpace):
pass #Exact copy
class UnderstandingProjection(ProjectOntoUnitVectorNumberline):
pass ##Copy
class ShowQualitativeDotProductValuesCopy(ShowQualitativeDotProductValues):
pass
class TranslateToTheWorldOfTransformations(TwoDOneDMatrixMultiplication):
CONFIG = {
"order_left_to_right" : True,
}
def construct(self):
v1, v2 = [
Matrix(["x_%d"%n, "y_%d"%n])
for n in (1, 2)
]
v1.set_column_colors(V_COLOR)
v2.set_column_colors(W_COLOR)
dot = OldTex("\\cdot")
matrix = Matrix([["x_1", "y_1"]])
matrix.set_column_colors(X_COLOR, Y_COLOR)
dot_product = VGroup(v1, dot, v2)
dot_product.arrange(RIGHT)
matrix.next_to(v2, LEFT)
brace = Brace(matrix, UP)
word = OldTexText("Transform")
word.set_width(brace.get_width())
brace.put_at_tip(word)
word.set_color(BLUE)
self.play(Write(dot_product))
self.wait()
self.play(
dot.set_fill, BLACK, 0,
Transform(v1, matrix),
)
self.play(
GrowFromCenter(brace),
Write(word)
)
self.wait()
self.show_product(v1, v2)
self.wait()
class NumericalAssociationSilliness(GeneralTwoDOneDMatrixMultiplication):
pass #copy
class YouMustKnowPersonality(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
You should learn a
vector's personality
""")
self.random_blink()
self.play_student_changes("pondering")
self.random_blink()
self.play_student_changes("pondering", "plain", "pondering")
self.random_blink()
class WhatTheVectorWantsToBe(Scene):
CONFIG = {
"v_coords" : [2, 4]
}
def construct(self):
width = FRAME_X_RADIUS-1
plane = NumberPlane(x_radius = 6, y_radius = 7)
squish_plane = plane.copy()
i_hat = Vector([1, 0], color = X_COLOR)
j_hat = Vector([0, 1], color = Y_COLOR)
vect = Vector(self.v_coords, color = YELLOW)
plane.add(vect, i_hat, j_hat)
plane.set_width(FRAME_X_RADIUS)
plane.to_edge(LEFT, buff = 0)
plane.remove(vect, i_hat, j_hat)
squish_plane.apply_function(
lambda p : np.dot(p, [4, 1, 0])*RIGHT
)
squish_plane.add(Vector(self.v_coords[1]*RIGHT, color = Y_COLOR))
squish_plane.add(Vector(self.v_coords[0]*RIGHT, color = X_COLOR))
squish_plane.scale(width/(FRAME_WIDTH))
plane.add(j_hat, i_hat)
number_line = NumberLine().stretch_to_fit_width(width)
number_line.to_edge(RIGHT)
squish_plane.move_to(number_line)
numbers = number_line.get_numbers(*list(range(-6, 8, 2)))
v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS)
v_line.set_color(GREY)
v_line.set_stroke(width = 10)
matrix = Matrix([self.v_coords])
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(number_line, UP, buff = LARGE_BUFF)
v_coords = Matrix(self.v_coords)
v_coords.set_column_colors(YELLOW)
v_coords.scale(0.75)
v_coords.next_to(vect.get_end(), RIGHT)
for array in matrix, v_coords:
array.add_to_back(BackgroundRectangle(array))
words = OldTexText(
"What the vector",
"\\\\ wants",
"to be"
)
words[1].set_color(BLUE)
words.next_to(matrix, UP, buff = MED_SMALL_BUFF)
self.add(plane, v_line, number_line, numbers)
self.play(ShowCreation(vect))
self.play(Write(v_coords))
self.wait()
self.play(
Transform(v_coords.copy(), matrix),
Write(words)
)
self.play(
Transform(plane.copy(), squish_plane, run_time = 3),
*list(map(Animation, [
words,
matrix,
plane,
vect,
v_coords
]))
)
self.wait()
class NextVideo(Scene):
def construct(self):
title = OldTexText("""
Next video: Cross products in the
light of linear transformations
""")
title.set_height(1.2)
title.to_edge(UP, buff = MED_SMALL_BUFF/2)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
VGroup(title, rect).show()
self.add(title)
self.play(ShowCreation(rect))
self.wait()
|
|
from manim_imports_ext import *
from _2016.eola.chapter3 import MatrixVectorMultiplicationAbstract
class Blob(Circle):
CONFIG = {
"stroke_color" : TEAL,
"fill_color" : BLUE_E,
"fill_opacity" : 1,
"random_seed" : 1,
"random_nudge_size" : 0.5,
"height" : 2,
}
def __init__(self, **kwargs):
Circle.__init__(self, **kwargs)
random.seed(self.random_seed)
self.apply_complex_function(
lambda z : z*(1+self.random_nudge_size*(random.random()-0.5))
)
self.set_height(self.height).center()
def probably_contains(self, point):
border_points = np.array(self.get_anchors_and_handles()[0])
distances = [get_norm(p-point) for p in border_points]
min3 = border_points[np.argsort(distances)[:3]]
center_direction = self.get_center() - point
in_center_direction = [np.dot(p-point, center_direction) > 0 for p in min3]
return sum(in_center_direction) <= 2
class RightHand(VMobject):
def __init__(self, **kwargs):
hand = SVGMobject("RightHandOutline")
self.inlines = VMobject(*hand.split()[:-4])
self.outline = VMobject(*hand.split()[-4:])
self.outline.set_stroke(color = WHITE, width = 5)
self.inlines.set_stroke(color = GREY_D, width = 3)
VMobject.__init__(self, self.outline, self.inlines)
self.center().set_height(3)
class OpeningQuote(Scene):
def construct(self):
words = OldTexText([
"``The purpose of computation is \\\\",
"insight",
", not ",
"numbers.",
"''",
], arg_separator = "")
# words.set_width(FRAME_WIDTH - 2)
words.to_edge(UP)
words.split()[1].set_color(BLUE)
words.split()[3].set_color(GREEN)
author = OldTexText("-Richard Hamming")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = 0.5)
self.play(FadeIn(words))
self.wait(2)
self.play(Write(author, run_time = 3))
self.wait()
class MovingForward(TeacherStudentsScene):
def construct(self):
self.setup()
student = self.get_students()[1]
bubble = student.get_bubble(direction = RIGHT, width = 5)
bubble.rotate(-np.pi/12)
bubble.next_to(student, UP, aligned_edge = RIGHT)
bubble.shift(0.5*LEFT)
bubble.make_green_screen()
self.teacher_says("""
Y'all know about linear
transformations, right?
""", width = 7)
self.play(
ShowCreation(bubble),
student.change_mode, "pondering"
)
self.wait(2)
class StretchingTransformation(LinearTransformationScene):
def construct(self):
self.setup()
self.add_title("Generally stretches space")
self.apply_transposed_matrix([[3, 1], [-1, 2]])
self.wait()
class SquishingTransformation(LinearTransformationScene):
CONFIG = {
"foreground_plane_kwargs" : {
"x_radius" : 3*FRAME_X_RADIUS,
"y_radius" : 3*FRAME_X_RADIUS,
"secondary_line_ratio" : 0
},
}
def construct(self):
self.setup()
self.add_title("Generally squishes space")
self.apply_transposed_matrix([[1./2, -0.5], [1, 1./3]])
self.wait()
class AskAboutStretching(LinearTransformationScene):
def construct(self):
self.setup()
words = OldTexText("""
Exactly how much are
things being stretched?
""")
words.add_background_rectangle()
words.to_corner(UP+RIGHT)
words.set_color(YELLOW)
self.apply_transposed_matrix(
[[2, 1], [-1, 3]],
added_anims = [Write(words)]
)
self.wait()
class AskAboutStretchingSpecifically(LinearTransformationScene):
def construct(self):
self.setup()
self.add_title(["How much are", "areas", "scaled?"])
hma, areas, scaled = self.title.split()[1].split()
areas.set_color(YELLOW)
blob = Blob().shift(UP+RIGHT)
label = OldTexText("Area")
label.set_color(YELLOW)
label = VMobject(VectorizedPoint(label.get_left()), label)
label.move_to(blob)
target_label = OldTex(["c \\cdot", "\\text{Area}"])
target_label.split()[1].set_color(YELLOW)
self.add_transformable_mobject(blob)
self.add_moving_mobject(label, target_label)
self.wait()
self.apply_transposed_matrix([[2, -1], [1, 1]])
arrow = Arrow(scaled, label.target.split()[0])
self.play(ShowCreation(arrow))
self.wait()
class BeautyNowUsesLater(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("Beauty now, uses later")
self.wait()
class DiagonalExample(LinearTransformationScene):
CONFIG = {
"show_square" : False,
"show_coordinates" : True,
"transposed_matrix" : [[3, 0], [0, 2]]
}
def construct(self):
self.setup()
matrix = Matrix(np.array(self.transposed_matrix).transpose())
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(ORIGIN, LEFT).to_edge(UP)
matrix_background = BackgroundRectangle(matrix)
self.play(ShowCreation(matrix_background), Write(matrix))
if self.show_square:
self.add_unit_square(animate = True)
self.add_foreground_mobject(matrix_background, matrix)
self.wait()
self.apply_transposed_matrix([self.transposed_matrix[0], [0, 1]])
self.apply_transposed_matrix([[1, 0], self.transposed_matrix[1]])
self.wait()
if self.show_square:
bottom_brace = Brace(self.i_hat, DOWN)
right_brace = Brace(self.square, RIGHT)
width = OldTex(str(self.transposed_matrix[0][0]))
height = OldTex(str(self.transposed_matrix[1][1]))
width.next_to(bottom_brace, DOWN)
height.next_to(right_brace, RIGHT)
for mob in bottom_brace, width, right_brace, height:
mob.add_background_rectangle()
self.play(Write(mob, run_time = 0.5))
self.wait()
width_target, height_target = width.copy(), height.copy()
det = np.linalg.det(self.transposed_matrix)
times, eq_det = list(map(Tex, ["\\times", "=%d"%det]))
words = OldTexText("New area $=$")
equation = VMobject(
words, width_target, times, height_target, eq_det
)
equation.arrange(RIGHT, buff = 0.2)
equation.next_to(self.square, UP, aligned_edge = LEFT)
equation.shift(0.5*RIGHT)
background_rect = BackgroundRectangle(equation)
self.play(
ShowCreation(background_rect),
Transform(width.copy(), width_target),
Transform(height.copy(), height_target),
*list(map(Write, [words, times, eq_det]))
)
self.wait()
class DiagonalExampleWithSquare(DiagonalExample):
CONFIG = {
"show_square" : True
}
class ShearExample(DiagonalExample):
CONFIG = {
"show_square" : False,
"show_coordinates" : True,
"transposed_matrix" : [[1, 0], [1, 1]]
}
class ShearExampleWithSquare(DiagonalExample):
CONFIG = {
"show_square" : True,
"show_coordinates" : True,
"show_coordinates" : False,
"transposed_matrix" : [[1, 0], [1, 1]]
}
class ThisSquareTellsEverything(LinearTransformationScene):
def construct(self):
self.setup()
self.add_unit_square()
words = OldTexText("""
This square gives you
everything you need.
""")
words.to_corner(UP+RIGHT)
words.set_color(YELLOW)
words.add_background_rectangle()
arrow = Arrow(
words.get_bottom(), self.square.get_right(),
color = WHITE
)
self.play(Write(words, run_time = 2))
self.play(ShowCreation(arrow))
self.add_foreground_mobject(words, arrow)
self.wait()
self.apply_transposed_matrix([[1.5, -0.5], [1, 1.5]])
self.wait()
class WhatHappensToOneSquareHappensToAll(LinearTransformationScene):
def construct(self):
self.setup()
self.add_unit_square()
pairs = [
(2*RIGHT+UP, 1),
(3*LEFT, 2),
(2*LEFT+DOWN, 0.5),
(3.5*RIGHT+2.5*UP, 1.5),
(RIGHT+2*DOWN, 0.25),
(3*LEFT+3*DOWN, 1),
]
squares = VMobject()
for position, side_length in pairs:
square = self.square.copy()
square.scale(side_length)
square.shift(position)
squares.add(square)
self.play(FadeIn(
squares, lag_ratio = 0.5,
run_time = 3
))
self.add_transformable_mobject(squares)
self.apply_transposed_matrix([[1, -1], [0.5, 1]])
self.wait()
class BreakBlobIntoGridSquares(LinearTransformationScene):
CONFIG = {
"square_size" : 0.5,
"blob_height" : 3,
}
def construct(self):
self.setup()
blob = Blob(
height = self.blob_height,
random_seed = 5,
random_nudge_size = 0.2,
)
blob.next_to(ORIGIN, UP+RIGHT)
self.add_transformable_mobject(blob)
arange = np.arange(
0, self.blob_height + self.square_size,
self.square_size
)
square = Square(side_length = self.square_size)
square.set_stroke(YELLOW, width = 2)
square.set_fill(YELLOW, opacity = 0.3)
squares = VMobject()
for x, y in it.product(*[arange]*2):
point = x*RIGHT + y*UP
if blob.probably_contains(point):
squares.add(square.copy().shift(point))
self.play(ShowCreation(
squares, lag_ratio = 0.5,
run_time = 2,
))
self.add_transformable_mobject(squares)
self.wait()
self.apply_transposed_matrix([[1, -1], [0.5, 1]])
self.wait()
class BreakBlobIntoGridSquaresGranular(BreakBlobIntoGridSquares):
CONFIG = {
"square_size" : 0.25
}
class BreakBlobIntoGridSquaresMoreGranular(BreakBlobIntoGridSquares):
CONFIG = {
"square_size" : 0.15
}
class BreakBlobIntoGridSquaresVeryGranular(BreakBlobIntoGridSquares):
CONFIG = {
"square_size" : 0.1
}
class NameDeterminant(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[3, 0], [2, 2]]
}
def construct(self):
self.setup()
self.plane.fade(0.3)
self.add_unit_square(color = YELLOW_E, opacity = 0.5)
self.add_title(
["The", "``determinant''", "of a transformation"],
scale_factor = 1
)
self.title.split()[1].split()[1].set_color(YELLOW)
matrix_background, matrix, det_text = self.get_matrix()
self.add_foreground_mobject(matrix_background, matrix)
A = OldTex("A")
area_label = VMobject(A.copy(), A.copy(), A)
area_label.move_to(self.square)
det = np.linalg.det(self.t_matrix)
if np.round(det) == det:
det = int(det)
area_label_target = VMobject(
OldTex(str(det)), OldTex("\\cdot"), A.copy()
)
if det < 1 and det > 0:
area_label_target.scale(det)
area_label_target.arrange(RIGHT, buff = 0.1)
self.add_moving_mobject(area_label, area_label_target)
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
det_mob_copy = area_label.split()[0].copy()
new_det_mob = det_mob_copy.copy().set_height(
det_text.split()[0].get_height()
)
new_det_mob.next_to(det_text, RIGHT, buff = 0.2)
new_det_mob.add_background_rectangle()
det_mob_copy.add_background_rectangle(opacity = 0)
self.play(Write(det_text))
self.play(Transform(det_mob_copy, new_det_mob))
self.wait()
def get_matrix(self):
matrix = Matrix(np.array(self.t_matrix).transpose())
matrix.set_column_colors(X_COLOR, Y_COLOR)
matrix.next_to(self.title, DOWN, buff = 0.5)
matrix.shift(2*LEFT)
matrix_background = BackgroundRectangle(matrix)
det_text = get_det_text(matrix, 0)
det_text.remove(det_text.split()[-1])
return matrix_background, matrix, det_text
class SecondDeterminantExample(NameDeterminant):
CONFIG = {
"t_matrix" : [[-1, -1], [1, -1]]
}
class DeterminantIsThree(NameDeterminant):
CONFIG = {
"t_matrix" : [[0, -1.5], [2, 1]]
}
class DeterminantIsOneHalf(NameDeterminant):
CONFIG = {
"t_matrix" : [[0.5, -0.5], [0.5, 0.5]],
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 0
},
}
class DeterminantIsZero(NameDeterminant):
CONFIG = {
"t_matrix" : [[4, 2], [2, 1]],
}
class SecondDeterminantIsZeroExamlpe(NameDeterminant):
CONFIG = {
"t_matrix" : [[0, 0], [0, 0]],
"show_basis_vectors" : False
}
class NextFewVideos(Scene):
def construct(self):
icon = SVGMobject("video_icon")
icon.center()
icon.set_width(FRAME_WIDTH/12.)
icon.set_stroke(color = WHITE, width = 0)
icon.set_fill(WHITE, opacity = 1)
icons = VMobject(*[icon.copy() for x in range(10)])
icons.set_submobject_colors_by_gradient(BLUE_A, BLUE_D)
icons.arrange(RIGHT)
icons.to_edge(LEFT)
self.play(
FadeIn(icons, lag_ratio = 0.5),
run_time = 3
)
self.wait()
class UnderstandingBeforeApplication(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("""
Just the visual
understanding for now
""")
self.random_blink()
self.wait()
class WhatIveSaidSoFar(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("""
What I've said so far
is not quite right...
""")
self.wait()
class NegativeDeterminant(Scene):
def construct(self):
numerical_matrix = [[1, 2], [3, 4]]
matrix = Matrix(numerical_matrix)
matrix.set_column_colors(X_COLOR, Y_COLOR)
det_text = get_det_text(matrix, np.linalg.det(numerical_matrix))
words = OldTexText("""
How can you scale area
by a negative number?
""")
words.set_color(YELLOW)
words.to_corner(UP+RIGHT)
det_num = det_text.split()[-1]
arrow = Arrow(words.get_bottom(), det_num)
self.add(matrix)
self.play(Write(det_text))
self.wait()
self.play(
Write(words, run_time = 2),
ShowCreation(arrow)
)
self.play(det_num.set_color, YELLOW)
self.wait()
class FlipSpaceOver(Scene):
def construct(self):
plane1 = NumberPlane(y_radius = FRAME_X_RADIUS)
plane2 = NumberPlane(
y_radius = FRAME_X_RADIUS,
color = RED_D, secondary_color = RED_E
)
axis = UP
for word, plane in ("Front", plane1), ("Back", plane2):
text = OldTexText(word)
if word == "Back":
text.rotate(np.pi, axis = axis)
text.scale(2)
text.next_to(ORIGIN, RIGHT).to_edge(UP)
text.add_background_rectangle()
plane.add(text)
self.play(ShowCreation(
plane1, lag_ratio = 0.5,
run_time = 1
))
self.wait()
self.play(Rotate(
plane1, axis = axis,
rate_func = lambda t : smooth(t/2),
run_time = 1.5,
path_arc = np.pi/2,
))
self.remove(plane1)
self.play(Rotate(
plane2, axis = axis,
rate_func = lambda t : smooth((t+1)/2),
run_time = 1.5,
path_arc = np.pi/2,
))
self.wait()
class RandyThinking(Scene):
def construct(self):
randy = Randolph().to_corner()
bubble = randy.get_bubble()
bubble.make_green_screen()
self.play(
randy.change_mode, "pondering",
ShowCreation(bubble)
)
self.wait()
self.play(Blink(randy))
self.wait(2)
self.play(Blink(randy))
class NegativeDeterminantTransformation(LinearTransformationScene):
CONFIG = {
"t_matrix" : [[1, 1], [2, -1]],
}
def construct(self):
self.setup()
self.add_title("Feels like flipping space")
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.wait()
class ThinkAboutFlippingPaper(Scene):
def construct(self):
pass
class NegativeDeterminantTransformation2(NegativeDeterminantTransformation):
CONFIG ={
"t_matrix" : [[-2, 1], [2, 1]]
}
class IHatJHatOrientation(NegativeDeterminantTransformation):
def construct(self):
self.setup()
i_label, j_label = self.get_basis_vector_labels()
self.add_transformable_label(self.i_hat, i_label, color = X_COLOR)
self.add_transformable_label(self.j_hat, j_label, color = Y_COLOR)
arc = Arc(start_angle = 0, angle = np.pi/2, color = YELLOW)
arc.shift(0.5*(RIGHT+UP)).scale(1/1.6)
arc.add_tip()
words1 = OldTexText([
"$\\hat{\\jmath}$",
"is to the",
"left",
"of",
"$\\hat{\\imath}$",
])
words1.split()[0].set_color(Y_COLOR)
words1.split()[2].set_color(YELLOW)
words1.split()[-1].set_color(X_COLOR)
words1.add_background_rectangle()
words1.next_to(arc, UP+RIGHT)
words2 = OldTexText([
"$L(\\hat{\\jmath})$",
"is to the \\\\",
"\\emph{right}",
"of",
"$L(\\hat{\\imath})$",
])
words2.split()[0].set_color(Y_COLOR)
words2.split()[2].set_color(YELLOW)
words2.split()[-1].set_color(X_COLOR)
words2.add_background_rectangle()
self.play(ShowCreation(arc))
self.play(Write(words1))
self.wait()
self.remove(words1, arc)
self.apply_transposed_matrix(self.t_matrix)
arc.submobjects = []
arc.apply_function(self.get_matrix_transformation(self.t_matrix))
arc.add_tip()
words2.next_to(arc, RIGHT)
self.play(
ShowCreation(arc),
Write(words2, run_time = 2),
)
self.wait()
title = OldTexText("Orientation has been reversed")
title.to_edge(UP)
title.add_background_rectangle()
self.play(Write(title, run_time = 1))
self.wait()
class WriteNegativeDeterminant(NegativeDeterminantTransformation):
def construct(self):
self.setup()
self.add_unit_square()
matrix = Matrix(np.array(self.t_matrix).transpose())
matrix.next_to(ORIGIN, LEFT)
matrix.to_edge(UP)
matrix.set_column_colors(X_COLOR, Y_COLOR)
det_text = get_det_text(
matrix, determinant = np.linalg.det(self.t_matrix)
)
three = VMobject(*det_text.split()[-1].split()[1:])
for mob in det_text.split():
if isinstance(mob, Tex):
mob.add_background_rectangle()
matrix_background = BackgroundRectangle(matrix)
self.play(
ShowCreation(matrix_background),
Write(matrix),
Write(det_text),
)
self.add_foreground_mobject(matrix_background, matrix, det_text)
self.wait()
self.apply_transposed_matrix(self.t_matrix)
self.play(three.copy().move_to, self.square)
self.wait()
class AltWriteNegativeDeterminant(WriteNegativeDeterminant):
CONFIG = {
"t_matrix" : [[2, -1], [1, -3]]
}
class WhyNegativeScaling(TeacherStudentsScene):
def construct(self):
self.setup()
self.student_says("""
Why does negative area
relate to orientation-flipping?
""")
other_students = np.array(self.get_students())[[0, 2]]
self.play(*[
ApplyMethod(student.change_mode, "confused")
for student in other_students
])
self.random_blink()
self.wait()
self.random_blink()
class SlowlyRotateIHat(LinearTransformationScene):
def construct(self):
self.setup()
self.add_unit_square()
self.apply_transposed_matrix(
[[-1, 0], [0, 1]],
path_arc = np.pi,
run_time = 30,
rate_func=linear,
)
class DeterminantGraphForRotatingIHat(Scene):
def construct(self):
t_axis = NumberLine(
numbers_with_elongated_ticks = [],
x_min = 0,
x_max = 10,
color = WHITE,
)
det_axis = NumberLine(
numbers_with_elongated_ticks = [],
x_min = -2,
x_max = 2,
color = WHITE
)
det_axis.rotate(np.pi/2)
t_axis.next_to(ORIGIN, RIGHT, buff = 0)
det_axis.move_to(t_axis.get_left())
axes = VMobject(det_axis, t_axis)
graph = FunctionGraph(np.cos, x_min = 0, x_max = np.pi)
graph.next_to(det_axis, RIGHT, buff = 0)
graph.set_color(YELLOW)
det_word = OldTexText("Det")
det_word.next_to(det_axis, RIGHT, aligned_edge = UP)
time_word = OldTexText("time")
time_word.next_to(t_axis, UP)
time_word.to_edge(RIGHT)
everything = VMobject(axes, det_word, time_word, graph)
everything.scale(1.5)
self.add(axes, det_word, time_word)
self.play(ShowCreation(
graph, rate_func=linear, run_time = 10
))
class WhatAboutThreeDimensions(TeacherStudentsScene):
def construct(self):
self.setup()
self.student_says("""
What about 3D
transformations?
""")
self.random_blink()
self.wait()
self.random_blink()
class Transforming3DCube(Scene):
def construct(self):
pass
class NameParallelepiped(Scene):
def construct(self):
word = OldTexText("``Parallelepiped''")
word.scale(2)
pp_part1 = VMobject(*word.split()[:len(word.split())/2])
pp_part2 = VMobject(*word.split()[len(word.split())/2:])
pp_part1.set_submobject_colors_by_gradient(X_COLOR, Y_COLOR)
pp_part2.set_submobject_colors_by_gradient(Y_COLOR, Z_COLOR)
self.play(Write(word))
self.wait(2)
class DeterminantIsVolumeOfParallelepiped(Scene):
def construct(self):
matrix = Matrix([[1, 0, 0.5], [0.5, 1, 0], [1, 0, 1]])
matrix.shift(3*LEFT)
matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR)
det_text = get_det_text(matrix)
eq = OldTex("=")
eq.next_to(det_text, RIGHT)
words = OldTexText([
"Volume of this\\\\",
"parallelepiped"
])
pp = words.split()[1]
pp_part1 = VMobject(*pp.split()[:len(pp.split())/2])
pp_part2 = VMobject(*pp.split()[len(pp.split())/2:])
pp_part1.set_submobject_colors_by_gradient(X_COLOR, Y_COLOR)
pp_part2.set_submobject_colors_by_gradient(Y_COLOR, Z_COLOR)
words.next_to(eq, RIGHT)
self.play(Write(matrix))
self.wait()
self.play(Write(det_text), Write(words), Write(eq))
self.wait()
class Degenerate3DTransformation(Scene):
def construct(self):
pass
class WriteZeroDeterminant(Scene):
def construct(self):
matrix = Matrix([[1, 0, 1], [0.5, 1, 1.5], [1, 0, 1]])
matrix.shift(2*LEFT)
matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR)
det_text = get_det_text(matrix, 0)
brace = Brace(matrix, DOWN)
words = OldTexText("""
Columns must be
linearly dependent
""")
words.set_color(YELLOW)
words.next_to(brace, DOWN)
self.play(Write(matrix))
self.wait()
self.play(Write(det_text))
self.wait()
self.play(
GrowFromCenter(brace),
Write(words, run_time = 2)
)
self.wait()
class AskAboutNegaive3DDeterminant(TeacherStudentsScene):
def construct(self):
self.setup()
self.student_says("""
What would det$(M) < 0$ mean?
""")
self.random_blink()
self.play(self.teacher.change_mode, "pondering")
self.wait()
self.random_blink()
class OrientationReversing3DTransformation(Scene):
def construct(self):
pass
class RightHandRule(Scene):
CONFIG = {
"flip" : False,
"labels_tex" : ["\\hat{\\imath}", "\\hat{\\jmath}", "\\hat{k}"],
"colors" : [X_COLOR, Y_COLOR, Z_COLOR],
}
def construct(self):
hand = RightHand()
v1 = Vector([-1.75, 0.5])
v2 = Vector([-1.4, -0.7])
v3 = Vector([0, 1.7])
vects = [v1, v2, v3]
if self.flip:
VMobject(hand, *vects).flip()
v1_label, v2_label, v3_label = [
OldTex(label_tex).scale(1.5)
for label_tex in self.labels_tex
]
v1_label.next_to(v1.get_end(), UP)
v2_label.next_to(v2.get_end(), DOWN)
v3_label.next_to(v3.get_end(), UP)
labels = [v1_label, v2_label, v3_label]
# self.add(NumberPlane())
self.play(
ShowCreation(hand.outline, run_time = 2, rate_func=linear),
FadeIn(hand.inlines)
)
self.wait()
for vect, label, color in zip(vects, labels, self.colors):
vect.set_color(color)
label.set_color(color)
vect.set_stroke(width = 8)
self.play(ShowCreation(vect))
self.play(Write(label))
self.wait()
class LeftHandRule(RightHandRule):
CONFIG = {
"flip" : True
}
class AskHowToCompute(TeacherStudentsScene):
def construct(self):
self.setup()
student = self.get_students()[1]
self.student_says("How do you \\\\ compute this?")
self.play(student.change_mode, "confused")
self.random_blink()
self.wait()
self.random_blink()
class TwoDDeterminantFormula(Scene):
def construct(self):
eq = OldTexText("=")
matrix = Matrix([["a", "b"], ["c", "d"]])
matrix.set_column_colors(X_COLOR, Y_COLOR)
ma, mb, mc, md = matrix.get_entries().split()
ma.shift(0.1*DOWN)
mc.shift(0.7*mc.get_height()*DOWN)
det_text = get_det_text(matrix)
VMobject(matrix, det_text).next_to(eq, LEFT)
formula = OldTex(list("ad-bc"))
formula.next_to(eq, RIGHT)
formula.shift(0.1*UP)
a, d, minus, b, c = formula.split()
VMobject(a, c).set_color(X_COLOR)
VMobject(b, d).set_color(Y_COLOR)
for mob in mb, mc, b, c:
if mob is c:
mob.zero = OldTex("\\cdot 0")
else:
mob.zero = OldTex("0")
mob.zero.move_to(mob, aligned_edge = DOWN+LEFT)
mob.zero.set_color(mob.get_color())
mob.original = mob.copy()
c.zero.shift(0.1*RIGHT)
self.add(matrix)
self.play(Write(det_text, run_time = 1))
self.play(Write(eq), Write(formula))
self.wait()
self.play(*[
Transform(m, m.zero)
for m in (mb, mc, b, c)
])
self.wait()
for pair in (mb, b), (mc, c):
self.play(*[
Transform(m, m.original)
for m in pair
])
self.wait()
class TwoDDeterminantFormulaIntuition(LinearTransformationScene):
def construct(self):
self.setup()
self.add_unit_square()
a, b, c, d = 3, 2, 3.5, 2
self.wait()
self.apply_transposed_matrix([[a, 0], [0, 1]])
i_brace = Brace(self.i_hat, DOWN)
width = OldTex("a").scale(1.5)
i_brace.put_at_tip(width)
width.set_color(X_COLOR)
width.add_background_rectangle()
self.play(GrowFromCenter(i_brace), Write(width))
self.wait()
self.apply_transposed_matrix([[1, 0], [0, d]])
side_brace = Brace(self.square, RIGHT)
height = OldTex("d").scale(1.5)
side_brace.put_at_tip(height)
height.set_color(Y_COLOR)
height.add_background_rectangle()
self.play(GrowFromCenter(side_brace), Write(height))
self.wait()
self.apply_transposed_matrix(
[[1, 0], [float(b)/d, 1]],
added_anims = [
ApplyMethod(m.shift, b*RIGHT)
for m in (side_brace, height)
]
)
self.wait()
self.play(*list(map(FadeOut, [i_brace, side_brace, width, height])))
matrix1 = np.dot(
[[a, b], [c, d]],
np.linalg.inv([[a, b], [0, d]])
)
matrix2 = np.dot(
[[a, b], [-c, d]],
np.linalg.inv([[a, b], [c, d]])
)
self.apply_transposed_matrix(matrix1.transpose(), path_arc = 0)
self.wait()
self.apply_transposed_matrix(matrix2.transpose(), path_arc = 0)
self.wait()
class FullFormulaExplanation(LinearTransformationScene):
def construct(self):
self.setup()
self.add_unit_square()
self.apply_transposed_matrix([[3, 1], [1, 2]], run_time = 0)
self.add_braces()
self.add_polygons()
self.show_formula()
def get_matrix(self):
matrix = Matrix([["a", "b"], ["c", "d"]])
matrix.set_column_colors(X_COLOR, Y_COLOR)
ma, mb, mc, md = matrix.get_entries().split()
ma.shift(0.1*DOWN)
mc.shift(0.7*mc.get_height()*DOWN)
matrix.shift(2*DOWN+4*LEFT)
return matrix
def add_polygons(self):
a = self.i_hat.get_end()[0]*RIGHT
b = self.j_hat.get_end()[0]*RIGHT
c = self.i_hat.get_end()[1]*UP
d = self.j_hat.get_end()[1]*UP
shapes_colors_and_tex = [
(Polygon(ORIGIN, a, a+c), MAROON, "ac/2"),
(Polygon(ORIGIN, d+b, d, d), TEAL, "\\dfrac{bd}{2}"),
(Polygon(a+c, a+b+c, a+b+c, a+b+c+d), TEAL, "\\dfrac{bd}{2}"),
(Polygon(b+d, a+b+c+d, b+c+d), MAROON, "ac/2"),
(Polygon(a, a+b, a+b+c, a+c), PINK, "bc"),
(Polygon(d, d+b, d+b+c, d+c), PINK, "bc"),
]
everyone = VMobject()
for shape, color, tex in shapes_colors_and_tex:
shape.set_stroke(width = 0)
shape.set_fill(color = color, opacity = 0.7)
tex_mob = OldTex(tex)
tex_mob.scale(0.7)
tex_mob.move_to(shape.get_center_of_mass())
everyone.add(shape, tex_mob)
self.play(FadeIn(
everyone,
lag_ratio = 0.5,
run_time = 1
))
def add_braces(self):
a = self.i_hat.get_end()[0]*RIGHT
b = self.j_hat.get_end()[0]*RIGHT
c = self.i_hat.get_end()[1]*UP
d = self.j_hat.get_end()[1]*UP
quads = [
(ORIGIN, a, DOWN, "a"),
(a, a+b, DOWN, "b"),
(a+b, a+b+c, RIGHT, "c"),
(a+b+c, a+b+c+d, RIGHT, "d"),
(a+b+c+d, b+c+d, UP, "a"),
(b+c+d, d+c, UP, "b"),
(d+c, d, LEFT, "c"),
(d, ORIGIN, LEFT, "d"),
]
everyone = VMobject()
for p1, p2, direction, char in quads:
line = Line(p1, p2)
brace = Brace(line, direction, buff = 0)
text = brace.get_text(char)
text.add_background_rectangle()
if char in ["a", "c"]:
text.set_color(X_COLOR)
else:
text.set_color(Y_COLOR)
everyone.add(brace, text)
self.play(Write(everyone), run_time = 1)
def show_formula(self):
matrix = self.get_matrix()
det_text = get_det_text(matrix)
f_str = "=(a+b)(c+d)-ac-bd-2bc=ad-bc"
formula = OldTex(f_str)
formula.next_to(det_text, RIGHT)
everyone = VMobject(det_text, matrix, formula)
everyone.set_width(FRAME_WIDTH - 1)
everyone.next_to(DOWN, DOWN)
background_rect = BackgroundRectangle(everyone)
self.play(
ShowCreation(background_rect),
Write(everyone)
)
self.wait()
class ThreeDDetFormula(Scene):
def construct(self):
matrix = Matrix([list("abc"), list("def"), list("ghi")])
matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR)
m1 = Matrix([["e", "f"], ["h", "i"]])
m1.set_column_colors(Y_COLOR, Z_COLOR)
m2 = Matrix([["d", "f"], ["g", "i"]])
m2.set_column_colors(X_COLOR, Z_COLOR)
m3 = Matrix([["d", "e"], ["g", "h"]])
m3.set_column_colors(X_COLOR, Y_COLOR)
for m in matrix, m1, m2, m3:
m.add(get_det_text(m))
a, b, c = matrix.get_entries().split()[:3]
parts = it.starmap(VMobject, [
[matrix],
[Tex("="), a.copy(), m1],
[Tex("-"), b.copy(), m2],
[Tex("+"), c.copy(), m3],
])
parts = list(parts)
for part in parts:
part.arrange(RIGHT, buff = 0.2)
parts[1].next_to(parts[0], RIGHT)
parts[2].next_to(parts[1], DOWN, aligned_edge = LEFT)
parts[3].next_to(parts[2], DOWN, aligned_edge = LEFT)
everyone = VMobject(*parts)
everyone.center().to_edge(UP)
for part in parts:
self.play(Write(part))
self.wait(2)
class QuizTime(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("Quiz time!")
self.random_blink()
self.wait()
self.random_blink()
class ProductProperty(Scene):
def construct(self):
lhs = OldTex([
"\\text{det}(",
"M_1",
"M_2",
")"
])
det, m1, m2, rp = lhs.split()
m1.set_color(TEAL)
m2.set_color(PINK)
rhs = OldTex([
"=\\text{det}(",
"M_1",
")\\text{det}(",
"M_2",
")"
])
rhs.split()[1].set_color(TEAL)
rhs.split()[3].set_color(PINK)
rhs.next_to(lhs, RIGHT)
formula = VMobject(lhs, rhs)
formula.center()
title = OldTexText("Explain in one sentence")
title.set_color(YELLOW)
title.next_to(formula, UP, buff = 0.5)
self.play(Write(m1))
self.play(Write(m2))
self.wait()
self.play(Write(det), Write(rp))
self.play(Write(rhs))
self.wait(2)
self.play(Write(title))
self.wait(2)
class NextVideo(Scene):
def construct(self):
title = OldTexText("""
Next video: Inverse matrices, column space and null space
""")
title.set_width(FRAME_WIDTH - 2)
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
|
|
from manim_imports_ext import *
from _2016.eola.chapter5 import get_det_text
from _2016.eola.chapter8 import *
class OpeningQuote(Scene):
def construct(self):
words = OldTexText(
"From [Grothendieck], I have also learned not",
"to take glory in the ",
"difficulty of a proof:",
"difficulty means we have not understood.",
"The idea is to be able to ",
"paint a landscape",
"in which the proof is obvious.",
arg_separator = " "
)
words.set_color_by_tex("difficulty of a proof:", RED)
words.set_color_by_tex("paint a landscape", GREEN)
words.set_width(FRAME_WIDTH - 2)
words.to_edge(UP)
author = OldTexText("-Pierre Deligne")
author.set_color(YELLOW)
author.next_to(words, DOWN, buff = 0.5)
self.play(FadeIn(words))
self.wait(4)
self.play(Write(author, run_time = 3))
self.wait()
class CrossProductSymbols(Scene):
def construct(self):
v_tex, w_tex, p_tex = get_vect_tex(*"vwp")
equation = OldTex(
v_tex, "\\times", w_tex, "=", p_tex
)
equation.set_color_by_tex(v_tex, V_COLOR)
equation.set_color_by_tex(w_tex, W_COLOR)
equation.set_color_by_tex(p_tex, P_COLOR)
brace = Brace(equation[-1])
brace.stretch_to_fit_width(0.7)
vector_text = brace.get_text("Vector")
vector_text.set_color(RED)
self.add(equation)
self.play(*list(map(Write, [brace, vector_text])))
self.wait()
class DeterminantTrickCopy(DeterminantTrick):
pass
class BruteForceVerification(Scene):
def construct(self):
v = Matrix(["v_1", "v_2", "v_3"])
w = Matrix(["w_1", "w_2", "w_3"])
v1, v2, v3 = v.get_entries()
w1, w2, w3 = w.get_entries()
v.set_color(V_COLOR)
w.set_color(W_COLOR)
def get_term(e1, e2, e3, e4):
group = VGroup(
e1.copy(), e2.copy(),
OldTex("-"),
e3.copy(), e4.copy(),
)
group.arrange()
return group
cross = Matrix(list(it.starmap(get_term, [
(v2, w3, v3, w2),
(v3, w1, v1, w3),
(v2, w3, v3, w2),
])))
cross_product = VGroup(
v.copy(), OldTex("\\times"), w.copy(),
OldTex("="), cross.copy()
)
cross_product.arrange()
cross_product.scale(0.75)
formula_word = OldTexText("Numerical formula")
computation_words = OldTexText("""
Facts you could (painfully)
verify computationally
""")
computation_words.scale(0.75)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS)
computation_words.to_edge(UP, buff = MED_SMALL_BUFF/2)
h_line.next_to(computation_words, DOWN)
formula_word.next_to(h_line, UP, buff = MED_SMALL_BUFF)
computation_words.shift(FRAME_X_RADIUS*RIGHT/2)
formula_word.shift(FRAME_X_RADIUS*LEFT/2)
cross_product.next_to(formula_word, DOWN, buff = LARGE_BUFF)
self.add(formula_word, computation_words)
self.play(
ShowCreation(h_line),
ShowCreation(v_line),
Write(cross_product)
)
v_tex, w_tex = get_vect_tex(*"vw")
v_dot, w_dot = [
OldTex(
tex, "\\cdot",
"(", v_tex, "\\times", w_tex, ")",
"= 0"
)
for tex in (v_tex, w_tex)
]
theta_def = OldTex(
"\\theta",
"= \\cos^{-1} \\big(", v_tex, "\\cdot", w_tex, "/",
"(||", v_tex, "||", "\\cdot", "||", w_tex, "||)", "\\big)"
)
length_check = OldTex(
"||", "(", v_tex, "\\times", w_tex, ")", "|| = ",
"(||", v_tex, "||)",
"(||", w_tex, "||)",
"\\sin(", "\\theta", ")"
)
last_point = h_line.get_center()+FRAME_X_RADIUS*RIGHT/2
max_width = FRAME_X_RADIUS-1
for mob in v_dot, w_dot, theta_def, length_check:
mob.set_color_by_tex(v_tex, V_COLOR)
mob.set_color_by_tex(w_tex, W_COLOR)
mob.set_color_by_tex("\\theta", GREEN)
mob.next_to(last_point, DOWN, buff = MED_SMALL_BUFF)
if mob.get_width() > max_width:
mob.set_width(max_width)
last_point = mob
self.play(FadeIn(mob))
self.wait()
class ButWeCanDoBetter(TeacherStudentsScene):
def construct(self):
self.teacher_says("But we can do \\\\ better than that")
self.play_student_changes(*["happy"]*3)
self.random_blink(3)
class Prerequisites(Scene):
def construct(self):
title = OldTexText("Prerequisites")
title.to_edge(UP)
title.set_color(YELLOW)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_width(FRAME_X_RADIUS - 1)
left_rect, right_rect = [
rect.copy().shift(DOWN/2).to_edge(edge)
for edge in (LEFT, RIGHT)
]
chapter5 = OldTexText("""
\\centering
Chapter 5
Determinants
""")
chapter7 = OldTexText("""
\\centering
Chapter 7:
Dot products and duality
""")
self.add(title)
for chapter, rect in (chapter5, left_rect), (chapter7, right_rect):
if chapter.get_width() > rect.get_width():
chapter.set_width(rect.get_width())
chapter.next_to(rect, UP)
self.play(
Write(chapter5),
ShowCreation(left_rect)
)
self.play(
Write(chapter7),
ShowCreation(right_rect)
)
self.wait()
class DualityReview(TeacherStudentsScene):
def construct(self):
words = OldTexText("Quick", "duality", "review")
words[1].set_color_by_gradient(BLUE, YELLOW)
self.teacher_says(words, target_mode = "surprised")
self.play_student_changes("pondering")
self.random_blink(2)
class DotProductToTransformSymbol(Scene):
CONFIG = {
"vect_coords" : [2, 1]
}
def construct(self):
v_mob = OldTex(get_vect_tex("v"))
v_mob.set_color(V_COLOR)
matrix = Matrix([self.vect_coords])
vector = Matrix(self.vect_coords)
matrix.set_column_colors(X_COLOR, Y_COLOR)
vector.set_column_colors(YELLOW)
_input = Matrix(["x", "y"])
_input.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR)
left_input, right_input = [_input.copy() for x in range(2)]
dot, equals = list(map(Tex, ["\\cdot", "="]))
equation = VGroup(
vector, dot, left_input, equals,
matrix, right_input
)
equation.arrange()
left_brace = Brace(VGroup(vector, left_input))
right_brace = Brace(matrix, UP)
left_words = left_brace.get_text("Dot product")
right_words = right_brace.get_text("Transform")
right_words.set_width(right_brace.get_width())
right_v_brace = Brace(right_input, UP)
right_v_mob = v_mob.copy()
right_v_brace.put_at_tip(right_v_mob)
right_input.add(right_v_brace, right_v_mob)
left_v_brace = Brace(left_input, UP)
left_v_mob = v_mob.copy()
left_v_brace.put_at_tip(left_v_mob)
left_input.add(left_v_brace, left_v_mob)
self.add(matrix, right_input)
self.play(
GrowFromCenter(right_brace),
Write(right_words, run_time = 1)
)
self.wait()
self.play(
Write(equals),
Write(dot),
Transform(matrix.copy(), vector),
Transform(right_input.copy(), left_input)
)
self.play(
GrowFromCenter(left_brace),
Write(left_words, run_time = 1)
)
self.wait()
class MathematicalWild(Scene):
def construct(self):
title = OldTexText("In the mathematical wild")
title.to_edge(UP)
self.add(title)
randy = Randolph()
randy.shift(DOWN)
bubble = ThoughtBubble(width = 5, height = 4)
bubble.write("""
\\centering
Some linear
transformation
to the number line
""")
bubble.content.set_color(BLUE)
bubble.content.shift(MED_SMALL_BUFF*UP/2)
bubble.remove(*bubble[:-1])
bubble.add(bubble.content)
bubble.next_to(randy.get_corner(UP+RIGHT), RIGHT)
vector = Vector([1, 2])
vector.move_to(randy.get_corner(UP+LEFT), aligned_edge = DOWN+LEFT)
dual_words = OldTexText("Dual vector")
dual_words.set_color_by_gradient(BLUE, YELLOW)
dual_words.next_to(vector, LEFT)
self.add(randy)
self.play(Blink(randy))
self.play(FadeIn(bubble))
self.play(randy.change_mode, "sassy")
self.play(Blink(randy))
self.wait()
self.play(randy.look, UP+LEFT)
self.play(
ShowCreation(vector),
randy.change_mode, "raise_right_hand"
)
self.wait()
self.play(Write(dual_words))
self.play(Blink(randy))
self.wait()
class ThreeStepPlan(Scene):
def construct(self):
title = OldTexText("The plan")
title.set_color(YELLOW)
title.to_edge(UP)
h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS)
h_line.next_to(title, DOWN)
v_tex, w_tex = get_vect_tex(*"vw")
v_text, w_text, cross_text = [
"$%s$"%s
for s in (v_tex, w_tex, v_tex + "\\times" + w_tex)
]
steps = [
OldTexText(
"1. Define a 3d-to-1d", "linear \\\\", "transformation",
"in terms of", v_text, "and", w_text
),
OldTexText(
"2. Find its", "dual vector"
),
OldTexText(
"3. Show that this dual is", cross_text
)
]
linear, transformation = steps[0][1:1+2]
steps[0].set_color_by_tex(v_text, V_COLOR)
steps[0].set_color_by_tex(w_text, W_COLOR)
steps[1][1].set_color_by_gradient(BLUE, YELLOW)
steps[2].set_color_by_tex(cross_text, P_COLOR)
VGroup(*steps).arrange(
DOWN, aligned_edge = LEFT, buff = LARGE_BUFF
).next_to(h_line, DOWN, buff = MED_SMALL_BUFF)
self.add(title)
self.play(ShowCreation(h_line))
for step in steps:
self.play(Write(step, run_time = 2))
self.wait()
linear_transformation = OldTexText("Linear", "transformation")
linear_transformation.next_to(h_line, DOWN, MED_SMALL_BUFF)
det = self.get_det()
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(3.5)
left_right_arrow = OldTex("\\Leftrightarrow")
left_right_arrow.shift(DOWN)
det.next_to(left_right_arrow, LEFT)
rect.next_to(left_right_arrow, RIGHT)
steps[0].remove(linear, transformation)
self.play(
Transform(
VGroup(linear, transformation),
linear_transformation
),
*list(map(FadeOut, steps))
)
self.wait()
self.play(Write(left_right_arrow))
self.play(Write(det))
self.play(ShowCreation(rect))
self.wait(0)
def get_det(self):
matrix = Matrix(np.array([
["\\hat{\\imath}", "\\hat{\\jmath}", "\\hat{k}"],
["v_%d"%d for d in range(1, 4)],
["w_%d"%d for d in range(1, 4)],
]).T)
matrix.set_column_colors(X_COLOR, V_COLOR, W_COLOR)
matrix.get_mob_matrix()[1, 0].set_color(Y_COLOR)
matrix.get_mob_matrix()[2, 0].set_color(Z_COLOR)
VGroup(*matrix.get_mob_matrix()[1, 1:]).shift(0.15*DOWN)
VGroup(*matrix.get_mob_matrix()[2, 1:]).shift(0.35*DOWN)
det_text = get_det_text(matrix)
det_text.add(matrix)
return det_text
class DefineDualTransform(Scene):
def construct(self):
self.add_title()
self.show_triple_cross_product()
self.write_function()
self.introduce_dual_vector()
self.expand_dot_product()
self.ask_question()
def add_title(self):
title = OldTexText("What a student might think")
title.not_real = OldTexText("Not the real cross product")
for mob in title, title.not_real:
mob.set_width(FRAME_X_RADIUS - 1)
mob.set_color(RED)
mob.to_edge(UP)
self.add(title)
self.title = title
def show_triple_cross_product(self):
colors = [WHITE, ORANGE, W_COLOR]
tex_mobs = list(map(Tex, get_vect_tex(*"uvw")))
u_tex, v_tex, w_tex = tex_mobs
arrays = [
Matrix(["%s_%d"%(s, d) for d in range(1, 4)])
for s in "uvw"
]
defs_equals = VGroup()
definitions = VGroup()
for array, tex_mob, color in zip(arrays, tex_mobs, colors):
array.set_column_colors(color)
tex_mob.set_color(color)
equals = OldTex("=")
definition = VGroup(tex_mob, equals, array)
definition.arrange(RIGHT)
definitions.add(definition)
defs_equals.add(equals)
definitions.arrange(buff = MED_SMALL_BUFF)
definitions.shift(2*DOWN)
mobs_with_targets = list(it.chain(
tex_mobs, *[a.get_entries() for a in arrays]
))
for mob in mobs_with_targets:
mob.target = mob.copy()
matrix = Matrix(np.array([
[e.target for e in array.get_entries()]
for array in arrays
]).T)
det_text = get_det_text(matrix, background_rect = False)
syms = times1, times2, equals = [
OldTex(sym)
for sym in ("\\times", "\\times", "=",)
]
triple_cross = VGroup(
u_tex.target, times1, v_tex.target, times2, w_tex.target, equals
)
triple_cross.arrange()
final_mobs = VGroup(triple_cross, VGroup(det_text, matrix))
final_mobs.arrange()
final_mobs.next_to(self.title, DOWN, buff = MED_SMALL_BUFF)
for mob in definitions, final_mobs:
mob.set_width(FRAME_X_RADIUS - 1)
for array in arrays:
brackets = array.get_brackets()
brackets.target = matrix.get_brackets()
mobs_with_targets.append(brackets)
for def_equals in defs_equals:
def_equals.target = equals
mobs_with_targets.append(def_equals)
self.play(FadeIn(
definitions,
run_time = 2,
lag_ratio = 0.5
))
self.wait(2)
self.play(*[
Transform(mob.copy(), mob.target)
for mob in tex_mobs
] + [
Write(times1),
Write(times2),
])
triple_cross.add(*self.get_mobjects_from_last_animation()[:3])
self.play(*[
Transform(mob.copy(), mob.target)
for mob in mobs_with_targets
if mob not in tex_mobs
])
u_entries = self.get_mobjects_from_last_animation()[:3]
v_entries = self.get_mobjects_from_last_animation()[3:6]
w_entries = self.get_mobjects_from_last_animation()[6:9]
self.play(Write(det_text))
self.wait(2)
self.det_text = det_text
self.definitions = definitions
self.u_entries = u_entries
self.v_entries = v_entries
self.w_entries = w_entries
self.matrix = matrix
self.triple_cross = triple_cross
self.v_tex, self.w_tex = v_tex, w_tex
self.equals = equals
def write_function(self):
brace = Brace(self.det_text, DOWN)
number_text = brace.get_text("Number")
self.play(Transform(self.title, self.title.not_real))
self.wait()
self.play(FadeOut(self.definitions))
self.play(
GrowFromCenter(brace),
Write(number_text)
)
self.wait()
x, y, z = variables = list(map(Tex, "xyz"))
for var, entry in zip(variables, self.u_entries):
var.scale(0.8)
var.move_to(entry)
entry.target = var
brace.target = Brace(z)
brace.target.stretch_to_fit_width(0.5)
number_text.target = brace.target.get_text("Variable")
v_brace = Brace(self.matrix.get_mob_matrix()[0, 1], UP)
w_brace = Brace(self.matrix.get_mob_matrix()[0, 2], UP)
for vect_brace, tex in (v_brace, self.v_tex), (w_brace, self.w_tex):
vect_brace.stretch_to_fit_width(brace.target.get_width())
new_tex = tex.copy()
vect_brace.put_at_tip(new_tex)
vect_brace.tex = new_tex
func_tex = OldTex(
"f\\left(%s\\right)"%matrix_to_tex_string(list("xyz"))
)
func_tex.scale(0.7)
func_input = Matrix(list("xyz"))
func_input_template = VGroup(*func_tex[3:-2])
func_input.set_height(func_input_template.get_height())
func_input.next_to(VGroup(*func_tex[:3]), RIGHT)
VGroup(*func_tex[-2:]).next_to(func_input, RIGHT)
func_tex[0].scale(1.5)
func_tex = VGroup(
VGroup(*[func_tex[i] for i in (0, 1, 2, -2, -1)]),
func_input
)
func_tex.next_to(self.equals, LEFT)
self.play(
FadeOut(self.title),
FadeOut(self.triple_cross),
*[
Transform(mob, mob.target)
for mob in [brace, number_text]
]
)
self.play(*[
Transform(mob, mob.target)
for mob in self.u_entries
])
self.play(*[
Write(VGroup(vect_brace, vect_brace.tex))
for vect_brace in (v_brace, w_brace)
])
self.wait()
self.play(Write(func_tex))
self.wait()
self.func_tex = func_tex
self.variables_text = VGroup(brace, number_text)
def introduce_dual_vector(self):
everything = VGroup(*self.get_mobjects())
colors = [X_COLOR, Y_COLOR, Z_COLOR]
q_marks = VGroup(*list(map(TexText, "???")))
q_marks.scale(2)
q_marks.set_color_by_gradient(*colors)
title = VGroup(OldTexText("This function is linear"))
title.set_color(GREEN)
title.to_edge(UP)
matrix = Matrix([list(q_marks.copy())])
matrix.set_height(self.func_tex.get_height()/2)
dual_vector = Matrix(list(q_marks))
dual_vector.set_height(self.func_tex.get_height())
dual_vector.get_brackets()[0].shift(0.2*LEFT)
dual_vector.get_entries().shift(0.1*LEFT)
dual_vector.scale(1.25)
dual_dot = VGroup(
dual_vector,
OldTex("\\cdot").next_to(dual_vector)
)
matrix_words = OldTexText("""
$1 \\times 3$ matrix encoding the
3d-to-1d linear transformation
""")
self.play(
Write(title, run_time = 2),
everything.shift, DOWN
)
self.remove(everything)
self.add(*everything)
self.wait()
func, func_input = self.func_tex
func_input.target = func_input.copy()
func_input.target.scale(1.2)
func_input.target.move_to(self.func_tex, aligned_edge = RIGHT)
matrix.next_to(func_input.target, LEFT)
dual_dot.next_to(func_input.target, LEFT)
matrix_words.next_to(matrix, DOWN, buff = 1.5)
matrix_words.shift_onto_screen()
matrix_arrow = Arrow(
matrix_words.get_top(),
matrix.get_bottom(),
color = WHITE
)
self.play(
Transform(func, matrix),
MoveToTarget(func_input),
FadeOut(self.variables_text),
)
self.wait()
self.play(
Write(matrix_words),
ShowCreation(matrix_arrow)
)
self.wait(2)
self.play(*list(map(FadeOut, [matrix_words, matrix_arrow])))
self.play(
Transform(func, dual_vector),
Write(dual_dot[1])
)
self.wait()
p_coords = VGroup(*list(map(Tex, [
"p_%d"%d for d in range(1, 4)
])))
p_coords.set_color(RED)
p_array = Matrix(list(p_coords))
p_array.set_height(dual_vector.get_height())
p_array.move_to(dual_vector, aligned_edge = RIGHT)
p_brace = Brace(p_array, UP)
p_tex = OldTex(get_vect_tex("p"))
p_tex.set_color(P_COLOR)
p_brace.put_at_tip(p_tex)
self.play(
GrowFromCenter(p_brace),
Write(p_tex)
)
self.play(Transform(
func, p_array,
run_time = 2,
lag_ratio = 0.5
))
self.remove(func)
self.add(p_array)
self.wait()
self.play(FadeOut(title))
self.wait()
self.p_array = p_array
self.input_array = func_input
def expand_dot_product(self):
everything = VGroup(*self.get_mobjects())
self.play(everything.to_edge, UP)
self.remove(everything)
self.add(*everything)
to_fade = VGroup()
p_entries = self.p_array.get_entries()
input_entries = self.input_array.get_entries()
dot_components = VGroup()
for p, x, i in zip(p_entries, input_entries, it.count()):
if i == 2:
x.sym = OldTex("=")
else:
x.sym = OldTex("+")
p.sym = OldTex("\\cdot")
p.target = p.copy().scale(2)
x.target = x.copy().scale(2)
component = VGroup(p.target, p.sym, x.target, x.sym)
component.arrange()
dot_components.add(component)
dot_components.arrange()
dot_components.next_to(ORIGIN, LEFT)
dot_components.shift(1.5*DOWN)
dot_arrow = Arrow(self.p_array.get_corner(DOWN+RIGHT), dot_components)
to_fade.add(dot_arrow)
self.play(ShowCreation(dot_arrow))
new_ps = VGroup()
for p, x in zip(p_entries, input_entries):
self.play(
MoveToTarget(p.copy()),
MoveToTarget(x.copy()),
Write(p.sym),
Write(x.sym)
)
mobs = self.get_mobjects_from_last_animation()
new_ps.add(mobs[0])
to_fade.add(*mobs[1:])
self.wait()
x, y, z = self.u_entries
v1, v2, v3 = self.v_entries
w1, w2, w3 = self.w_entries
cross_components = VGroup()
quints = [
(x, v2, w3, v3, w2),
(y, v3, w1, v1, w3),
(z, v1, w2, v2, w1),
]
quints = [
[m.copy() for m in quint]
for quint in quints
]
for i, quint in enumerate(quints):
sym_strings = ["(", "\\cdot", "-", "\\cdot", ")"]
if i < 2:
sym_strings[-1] += "+"
syms = list(map(Tex, sym_strings))
for mob, sym in zip(quint, syms):
mob.target = mob.copy()
mob.target.scale(1.5)
mob.sym = sym
quint_targets = [mob.target for mob in quint]
component = VGroup(*it.chain(*list(zip(quint_targets, syms))))
component.arrange()
cross_components.add(component)
to_fade.add(syms[0], syms[-1], quint[0])
cross_components.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF)
cross_components.next_to(dot_components, RIGHT)
for quint in quints:
self.play(*[
ApplyMethod(mob.set_color, YELLOW)
for mob in quint
])
self.wait(0.5)
self.play(*[
MoveToTarget(mob)
for mob in quint
] + [
Write(mob.sym)
for mob in quint
])
self.wait()
self.play(
ApplyFunction(
lambda m : m.arrange(
DOWN, buff = MED_SMALL_BUFF+SMALL_BUFF
).next_to(cross_components, LEFT),
new_ps
),
*list(map(FadeOut, to_fade))
)
self.play(*[
Write(OldTex("=").next_to(p, buff = 2*SMALL_BUFF))
for p in new_ps
])
equals = self.get_mobjects_from_last_animation()
self.wait(2)
everything = everything.copy()
self.play(
FadeOut(VGroup(*self.get_mobjects())),
Animation(everything)
)
self.clear()
self.add(everything)
def ask_question(self):
everything = VGroup(*self.get_mobjects())
p_tex = "$%s$"%get_vect_tex("p")
question = OldTexText(
"What vector",
p_tex,
"has \\\\ the property that"
)
question.to_edge(UP)
question.set_color(YELLOW)
question.set_color_by_tex(p_tex, P_COLOR)
everything.target = everything.copy()
everything.target.next_to(
question, DOWN, buff = MED_SMALL_BUFF
)
self.play(
MoveToTarget(everything),
Write(question)
)
self.wait()
class WhyAreWeDoingThis(TeacherStudentsScene):
def construct(self):
self.student_says(
"Um...why are \\\\ we doing this?",
target_mode = "confused"
)
self.random_blink()
self.play(self.get_teacher().change_mode, "erm")
self.play_student_changes("plain", "confused", "raise_left_hand")
self.random_blink()
self.play_student_changes("pondering", "confused", "raise_left_hand")
self.random_blink(5)
class ThreeDTripleCrossProduct(Scene):
pass #Simple parallelepiped
class ThreeDMovingVariableVector(Scene):
pass #white u moves around
class ThreeDMovingVariableVectorWithCrossShowing(Scene):
pass #white u moves around, red p is present
class NowForTheCoolPart(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"Now for the\\\\",
"cool part"
)
self.play_student_changes(*["happy"]*3)
self.random_blink(2)
self.teacher_says(
"Let's answer the same question,\\\\",
"but this time geometrically"
)
self.play_student_changes(*["pondering"]*3)
self.random_blink(2)
class ThreeDDotProductProjection(Scene):
pass #
class DotProductWords(Scene):
def construct(self):
p_tex = "$%s$"%get_vect_tex("p")
p_mob = OldTexText(p_tex)
p_mob.scale(1.5)
p_mob.set_color(P_COLOR)
input_array = Matrix(list("xyz"))
dot_product = VGroup(p_mob, Dot(radius = 0.07), input_array)
dot_product.arrange(buff = MED_SMALL_BUFF/2)
equals = OldTex("=")
dot_product.next_to(equals, LEFT)
words = VGroup(*it.starmap(TexText, [
("(Length of projection)",),
("(Length of ", p_tex, ")",)
]))
times = OldTex("\\times")
words[1].set_color_by_tex(p_tex, P_COLOR)
words[0].next_to(equals, RIGHT)
words[1].next_to(words[0], DOWN, aligned_edge = LEFT)
times.next_to(words[0], RIGHT)
everyone = VGroup(dot_product, equals, times, words)
everyone.center().set_width(FRAME_X_RADIUS - 1)
self.add(dot_product)
self.play(Write(equals))
self.play(Write(words[0]))
self.wait()
self.play(
Write(times),
Write(words[1])
)
self.wait()
class ThreeDProjectToPerpendicular(Scene):
pass #
class GeometricVolumeWords(Scene):
def construct(self):
v_tex, w_tex = [
"$%s$"%s
for s in get_vect_tex(*"vw")
]
words = VGroup(
OldTexText("(Area of", "parallelogram", ")$\\times$"),
OldTexText(
"(Component of $%s$"%matrix_to_tex_string(list("xyz")),
"perpendicular to", v_tex, "and", w_tex, ")"
)
)
words[0].set_color_by_tex("parallelogram", BLUE)
words[1].set_color_by_tex(v_tex, ORANGE)
words[1].set_color_by_tex(w_tex, W_COLOR)
words.arrange(RIGHT)
words.set_width(FRAME_WIDTH - 1)
words.to_edge(DOWN, buff = SMALL_BUFF)
for word in words:
self.play(Write(word))
self.wait()
class WriteXYZ(Scene):
def construct(self):
self.play(Write(Matrix(list("xyz"))))
self.wait()
class ThreeDDotProductWithCross(Scene):
pass
class CrossVectorEmphasisWords(Scene):
def construct(self):
v_tex, w_tex = ["$%s$"%s for s in get_vect_tex(*"vw")]
words = [
OldTexText("Perpendicular to", v_tex, "and", w_tex),
OldTexText("Length = (Area of ", "parallelogram", ")")
]
for word in words:
word.set_color_by_tex(v_tex, ORANGE)
word.set_color_by_tex(w_tex, W_COLOR)
word.set_color_by_tex("parallelogram", BLUE)
self.play(Write(word))
self.wait()
self.play(FadeOut(word))
class NextVideo(Scene):
def construct(self):
title = OldTexText("""
Next video: Change of basis
""")
title.to_edge(UP, buff = MED_SMALL_BUFF/2)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
class ChangeOfBasisPreview(LinearTransformationScene):
CONFIG = {
"include_background_plane" : False,
"foreground_plane_kwargs" : {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"secondary_line_ratio" : 0
},
"t_matrix" : [[2, 1], [-1, 1]],
"i_target_color" : YELLOW,
"j_target_color" : MAROON_B,
"sum_color" : PINK,
"vector" : [-1, 2],
}
def construct(self):
randy = Randolph()
pinky = Mortimer(color = PINK)
randy.to_corner(DOWN+LEFT)
pinky.to_corner(DOWN+RIGHT)
self.plane.fade()
self.add_foreground_mobject(randy, pinky)
coords = Matrix(self.vector)
coords.add_to_back(BackgroundRectangle(coords))
self.add_foreground_mobject(coords)
coords.move_to(
randy.get_corner(UP+RIGHT),
aligned_edge = DOWN+LEFT
)
coords.target = coords.copy()
coords.target.move_to(
pinky.get_corner(UP+LEFT),
aligned_edge = DOWN+RIGHT
)
self.play(
Write(coords),
randy.change_mode, "speaking"
)
self.scale_basis_vectors()
self.apply_transposed_matrix(
self.t_matrix,
added_anims = [
MoveToTarget(coords),
ApplyMethod(pinky.change_mode, "speaking"),
ApplyMethod(randy.change_mode, "plain"),
]
)
self.play(
randy.change_mode, "erm",
self.i_hat.set_color, self.i_target_color,
self.j_hat.set_color, self.j_target_color,
)
self.i_hat.color = self.i_target_color
self.j_hat.color = self.j_target_color
self.scale_basis_vectors()
def scale_basis_vectors(self):
for vect in self.i_hat, self.j_hat:
vect.save_state()
self.play(self.i_hat.scale, self.vector[0])
self.play(self.j_hat.scale, self.vector[1])
self.play(self.j_hat.shift, self.i_hat.get_end())
sum_vect = Vector(self.j_hat.get_end(), color = self.sum_color)
self.play(ShowCreation(sum_vect))
self.wait(2)
self.play(
FadeOut(sum_vect),
self.i_hat.restore,
self.j_hat.restore,
)
self.wait()
|
|
from manim_imports_ext import *
from functools import reduce
class OpeningQuote(Scene):
def construct(self):
words = OldTexText([
"Lisa:",
"Well, where's my dad?\\\\ \\\\",
"Frink:",
"""Well, it should be obvious to even the most
dimwitted individual who holds an advanced degree
in hyperbolic topology that Homer Simpson has stumbled
into...(dramatic pause)...""",
"the third dimension."
])
words.set_width(FRAME_WIDTH - 2)
words.to_edge(UP)
words.split()[0].set_color(YELLOW)
words.split()[2].set_color(YELLOW)
three_d = words.submobjects.pop()
three_d.set_color(BLUE)
self.play(FadeIn(words))
self.play(Write(three_d))
self.wait(2)
class QuickFootnote(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("Quick footnote here...")
self.random_blink()
self.play(
random.choice(self.get_students()).change_mode, "happy"
)
self.random_blink()
class PeakOutsideFlatland(TeacherStudentsScene):
def construct(self):
self.setup()
self.teacher_says("Peak outside flatland")
self.wait()
student = self.get_students()[0]
self.student_thinks(index = 0)
student.bubble.make_green_screen()
self.wait()
class SymbolicThreeDTransform(Scene):
CONFIG = {
"input_coords" : [2, 6, -1],
"output_coords" : [3, 2, 0],
"title" : "Three-dimensional transformation",
}
def construct(self):
in_vect = Matrix(self.input_coords)
out_vect = Matrix(self.output_coords)
in_vect.set_color(BLUE)
out_vect.set_color(GREEN)
func = OldTex("L(\\vec{\\textbf{v}})")
point = VectorizedPoint(func.get_center())
in_vect.next_to(func, LEFT, buff = 1)
out_vect.next_to(func, RIGHT, buff = 1)
in_words = OldTexText("Input")
in_words.next_to(in_vect, DOWN)
in_words.set_color(BLUE_C)
out_words = OldTexText("Output")
out_words.next_to(out_vect, DOWN)
out_words.set_color(GREEN_C)
title = OldTexText(self.title)
title.to_edge(UP)
self.add(title)
self.play(Write(func))
self.play(Write(in_vect), Write(in_words))
self.wait()
self.add(in_vect.copy())
self.play(Transform(in_vect, point, lag_ratio = 0.5))
self.play(Transform(in_vect, out_vect, lag_ratio = 0.5))
self.add(out_words)
self.wait()
class ThreeDLinearTransformExample(Scene):
pass
class SingleVectorToOutput(Scene):
pass
class InputWordOutputWord(Scene):
def construct(self):
self.add(OldTexText("Input").scale(2))
self.wait()
self.clear()
self.add(OldTexText("Output").scale(2))
self.wait()
class TransformOnlyBasisVectors(Scene):
pass
class IHatJHatKHatWritten(Scene):
def construct(self):
for char, color in zip(["\\imath", "\\jmath", "k"], [X_COLOR, Y_COLOR, Z_COLOR]):
sym = OldTex("{\\hat{%s}}"%char)
sym.scale(3)
sym.set_color(color)
self.play(Write(sym))
self.wait()
self.clear()
class PutTogether3x3Matrix(Scene):
CONFIG = {
"col1" : [1, 0, -1],
"col2" : [1, 1, 0],
"col3" : [1, 0, 1],
}
def construct(self):
i_to = OldTex("\\hat{\\imath} \\to").set_color(X_COLOR)
j_to = OldTex("\\hat{\\jmath} \\to").set_color(Y_COLOR)
k_to = OldTex("\\hat{k} \\to").set_color(Z_COLOR)
i_array = Matrix(self.col1)
j_array = Matrix(self.col2)
k_array = Matrix(self.col3)
everything = VMobject(
i_to, i_array, OldTex("=").set_color(BLACK),
j_to, j_array, OldTex("=").set_color(BLACK),
k_to, k_array, OldTex("=").set_color(BLACK),
)
everything.arrange(RIGHT, buff = 0.1)
everything.set_width(FRAME_WIDTH-1)
everything.to_edge(DOWN)
i_array.set_color(X_COLOR)
j_array.set_color(Y_COLOR)
k_array.set_color(Z_COLOR)
arrays = [i_array, j_array, k_array]
matrix = Matrix(reduce(
lambda a1, a2 : np.append(a1, a2, axis = 1),
[m.copy().get_mob_matrix() for m in arrays]
))
matrix.to_edge(DOWN)
start_entries = reduce(op.add, [a.get_entries().split() for a in arrays])
target_entries = matrix.get_mob_matrix().transpose().flatten()
start_l_bracket = i_array.get_brackets().split()[0]
start_r_bracket = k_array.get_brackets().split()[1]
start_brackets = VMobject(start_l_bracket, start_r_bracket)
target_bracketes = matrix.get_brackets()
for mob in everything.split():
self.play(Write(mob, run_time = 1))
self.wait()
self.play(
FadeOut(everything),
Transform(VMobject(*start_entries), VMobject(*target_entries)),
Transform(start_brackets, target_bracketes)
)
self.wait()
class RotateSpaceAboutYAxis(Scene):
pass
class RotateOnlyBasisVectorsAboutYAxis(Scene):
pass
class PutTogetherRotationMatrix(PutTogether3x3Matrix):
CONFIG = {
"col1" : [0, 0, -1],
"col2" : [0, 1, 0],
"col3" : [1, 0, 0]
}
class ScaleAndAddBeforeTransformation(Scene):
pass
class ShowVCoordinateMeaning(Scene):
CONFIG = {
"v_str" : "\\vec{\\textbf{v}}",
"i_str" : "\\hat{\\imath}",
"j_str" : "\\hat{\\jmath}",
"k_str" : "\\hat{k}",
"post_transform" : False,
}
def construct(self):
v = OldTex(self.v_str)
v.set_color(YELLOW)
eq = OldTex("=")
coords = Matrix(["x", "y", "z"])
eq2 = eq.copy()
if self.post_transform:
L, l_paren, r_paren = list(map(Tex, "L()"))
parens = VMobject(l_paren, r_paren)
parens.scale(2)
parens.stretch_to_fit_height(
coords.get_height()
)
VMobject(L, l_paren, coords, r_paren).arrange(buff = 0.1)
coords.submobjects = [L, l_paren] + coords.submobjects + [r_paren]
lin_comb = VMobject(*list(map(Tex, [
"x", self.i_str, "+",
"y", self.j_str, "+",
"z", self.k_str,
])))
lin_comb.arrange(
RIGHT, buff = 0.1,
aligned_edge = ORIGIN if self.post_transform else DOWN
)
lin_comb_parts = np.array(lin_comb.split())
new_x, new_y, new_z = lin_comb_parts[[0, 3, 6]]
i, j, k = lin_comb_parts[[1, 4, 7]]
plusses = lin_comb_parts[[2, 5]]
i.set_color(X_COLOR)
j.set_color(Y_COLOR)
k.set_color(Z_COLOR)
everything = VMobject(v, eq, coords, eq2, lin_comb)
everything.arrange(buff = 0.2)
everything.set_width(FRAME_WIDTH - 1)
everything.to_edge(DOWN)
if not self.post_transform:
lin_comb.shift(0.35*UP)
self.play(*list(map(Write, [v, eq, coords])))
self.wait()
self.play(
Transform(
coords.get_entries().copy(),
VMobject(new_x, new_y, new_z),
path_arc = -np.pi,
lag_ratio = 0.5
),
Write(VMobject(*[eq2, i, j, k] + list(plusses))),
run_time = 3
)
self.wait()
class ScaleAndAddAfterTransformation(Scene):
pass
class ShowVCoordinateMeaningAfterTransform(ShowVCoordinateMeaning):
CONFIG = {
"v_str" : "L(\\vec{\\textbf{v}})",
"i_str" : "L(\\hat{\\imath})",
"j_str" : "L(\\hat{\\jmath})",
"k_str" : "L(\\hat{k})",
"post_transform" : True,
}
class ShowMatrixVectorMultiplication(Scene):
def construct(self):
matrix = Matrix(np.arange(9).reshape((3, 3)))
vect = Matrix(list("xyz"))
vect.set_height(matrix.get_height())
col1, col2, col3 = columns = [
Matrix(col)
for col in matrix.copy().get_mob_matrix().transpose()
]
coords = x, y, z = [m.copy() for m in vect.get_entries().split()]
eq, plus1, plus2 = list(map(Tex, list("=++")))
everything = VMobject(
matrix, vect, eq,
x, col1, plus1,
y, col2, plus2,
z, col3
)
everything.arrange(buff = 0.1)
everything.set_width(FRAME_WIDTH-1)
result = VMobject(x, col1, plus1, y, col2, plus2, z, col3)
trips = [
(matrix, DOWN, "Transformation"),
(vect, UP, "Input vector"),
(result, DOWN, "Output vector"),
]
braces = []
for mob, direction, text in trips:
brace = Brace(mob, direction)
words = OldTexText(text)
words.next_to(brace, direction)
brace.add(words)
braces.append(brace)
matrix_brace, vect_brace, result_brace = braces
self.play(*list(map(Write, [matrix, vect])), run_time = 2)
self.play(Write(matrix_brace, run_time = 1))
self.play(Write(vect_brace, run_time = 1))
sexts = list(zip(
matrix.get_mob_matrix().transpose(),
columns,
vect.get_entries().split(),
coords,
[eq, plus1, plus2],
[X_COLOR, Y_COLOR, Z_COLOR]
))
for o_col, col, start_coord, coord, sym, color in sexts:
o_col = VMobject(*o_col)
self.play(
start_coord.set_color, YELLOW,
o_col.set_color, color
)
coord.set_color(YELLOW)
col.set_color(color)
self.play(
Write(col.get_brackets()),
Transform(
o_col.copy(), col.get_entries(),
path_arc = -np.pi
),
Transform(
start_coord.copy(), coord,
path_arc = -np.pi
),
Write(sym)
)
self.wait()
self.play(Write(result_brace, run_time = 1))
self.wait()
class ShowMatrixMultiplication(Scene):
def construct(self):
right = Matrix(np.arange(9).reshape((3, 3)))
left = Matrix(np.random.random_integers(-5, 5, (3, 3)))
VMobject(left, right).arrange(buff = 0.1)
right.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR)
left.set_color(PINK)
trips = [
(right, DOWN, "First transformation"),
(left, UP, "Second transformation"),
]
braces = []
for mob, direction, text in trips:
brace = Brace(mob, direction)
words = OldTexText(text)
words.next_to(brace, direction)
brace.add(words)
braces.append(brace)
right_brace, left_brace = braces
VMobject(*self.get_mobjects()).set_width(FRAME_WIDTH-1)
self.add(right, left)
self.play(Write(right_brace))
self.play(Write(left_brace))
self.wait()
class ApplyTwoSuccessiveTransforms(Scene):
pass
class ComputerGraphicsAndRobotics(Scene):
def construct(self):
mob = VMobject(
OldTexText("Computer graphics"),
OldTexText("Robotics")
)
mob.arrange(DOWN, buff = 1)
self.play(Write(mob, run_time = 1))
self.wait()
class ThreeDRotation(Scene):
pass
class ThreeDRotationBrokenUp(Scene):
pass
class SymbolicTwoDToThreeDTransform(SymbolicThreeDTransform):
CONFIG = {
"input_coords" : [2, 6],
"output_coords" : [3, 2, 0],
"title" : "Two dimensions to three dimensions",
}
class SymbolicThreeDToTwoDTransform(SymbolicThreeDTransform):
CONFIG = {
"input_coords" : [4, -3, 1],
"output_coords" : [8, 4],
"title" : "Three dimensions to two dimensions",
}
class QuestionsToPonder(Scene):
def construct(self):
title = OldTexText("Questions to ponder")
title.set_color(YELLOW).to_edge(UP)
self.add(title)
questions = VMobject(*list(map(TexText, [
"1. Can you visualize these transformations?",
"2. Can you represent them with matrices?",
"3. How many rows and columns?",
"4. When can you multiply these matrices?",
])))
questions.arrange(DOWN, buff = 1, aligned_edge = LEFT)
questions.to_edge(LEFT)
for question in questions.split():
self.play(Write(question, run_time = 1))
self.wait()
class NextVideo(Scene):
def construct(self):
title = OldTexText("""
Next video: The determinant
""")
title.set_width(FRAME_WIDTH - 2)
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
|
|
from manim_imports_ext import *
from once_useful_constructs import *
EXAMPLE_TRANFORM = [[0, 1], [-1, 1]]
TRANFORMED_VECTOR = [[1], [2]]
def matrix_multiplication():
return OldTex("""
\\left[
\\begin{array}{cc}
a & b \\\\
c & d
\\end{array}
\\right]
\\left[
\\begin{array}{cc}
e & f \\\\
g & h
\\end{array}
\\right]
=
\\left[
\\begin{array}{cc}
ae + bg & af + bh \\\\
ce + dg & cf + dh
\\end{array}
\\right]
""")
class OpeningQuote(Scene):
def construct(self):
words = OldTexText(
"""
``There is hardly any theory which is more elementary
than linear algebra, in spite of the fact that generations
of professors and textbook writers have obscured its
simplicity by preposterous calculations with matrices.''
""",
organize_left_to_right = False
)
words.set_width(2*(FRAME_X_RADIUS-1))
words.to_edge(UP)
for mob in words.submobjects[48:49+13]:
mob.set_color(GREEN)
author = OldTexText("-Jean Dieudonn\\'e")
author.set_color(YELLOW)
author.next_to(words, DOWN)
self.play(FadeIn(words))
self.wait(3)
self.play(Write(author, run_time = 5))
self.wait()
class VideoIcon(SVGMobject):
def __init__(self, **kwargs):
SVGMobject.__init__(self, "video_icon", **kwargs)
self.center()
self.set_width(FRAME_WIDTH/12.)
self.set_stroke(color = WHITE, width = 0)
self.set_fill(color = WHITE, opacity = 1)
class UpcomingSeriesOfVidoes(Scene):
def construct(self):
icons = [VideoIcon() for x in range(10)]
colors = Color(BLUE_A).range_to(BLUE_D, len(icons))
for icon, color in zip(icons, colors):
icon.set_fill(color, opacity = 1)
icons = VMobject(*icons)
icons.arrange(RIGHT)
icons.to_edge(LEFT)
icons.shift(UP)
icons = icons.split()
def rate_func_creator(offset):
return lambda a : min(max(2*(a-offset), 0), 1)
self.play(*[
FadeIn(
icon,
run_time = 5,
rate_func = rate_func_creator(offset)
)
for icon, offset in zip(icons, np.linspace(0, 0.5, len(icons)))
])
self.wait()
class AboutLinearAlgebra(Scene):
def construct(self):
self.show_dependencies()
self.to_thought_bubble()
def show_dependencies(self):
linalg = OldTexText("Linear Algebra")
subjects = list(map(TexText, [
"Computer science",
"Physics",
"Electrical engineering",
"Mechanical engineering",
"Statistics",
"\\vdots"
]))
prev = subjects[0]
for subject in subjects[1:]:
subject.next_to(prev, DOWN, aligned_edge = LEFT)
prev = subject
all_subs = VMobject(*subjects)
linalg.to_edge(LEFT)
all_subs.next_to(linalg, RIGHT, buff = 2)
arrows = VMobject(*[
Arrow(linalg, sub)
for sub in subjects
])
self.play(Write(linalg, run_time = 1))
self.wait()
self.play(
ShowCreation(arrows, lag_ratio = 0.5),
FadeIn(all_subs),
run_time = 2
)
self.wait()
self.linalg = linalg
def to_thought_bubble(self):
linalg = self.linalg
all_else = list(self.mobjects)
all_else.remove(linalg)
randy = Randolph()
randy.to_corner()
bubble = randy.get_bubble(width = 10)
new_linalg = bubble.position_mobject_inside(linalg.copy())
q_marks = OldTexText("???").next_to(randy, UP)
self.play(*list(map(FadeOut, all_else)))
self.remove(*all_else)
self.play(
Transform(linalg, new_linalg),
Write(bubble),
FadeIn(randy)
)
self.wait()
topics = [
self.get_matrix_multiplication(),
self.get_determinant(),
self.get_cross_product(),
self.get_eigenvalue(),
]
questions = [
self.get_matrix_multiplication_question(),
self.get_cross_product_question(),
self.get_eigen_question(),
]
for count, topic in enumerate(topics + questions):
bubble.position_mobject_inside(topic)
if count == len(topics):
self.play(FadeOut(linalg))
self.play(
ApplyMethod(randy.change_mode, "confused"),
Write(q_marks, run_time = 1)
)
linalg = VectorizedPoint(linalg.get_center())
if count > len(topics):
self.remove(linalg)
self.play(FadeIn(topic))
linalg = topic
else:
self.play(Transform(linalg, topic))
if count %3 == 0:
self.play(Blink(randy))
self.wait()
else:
self.wait(2)
def get_matrix_multiplication(self):
return matrix_multiplication()
def get_determinant(self):
return OldTex("""
\\text{Det}\\left(
\\begin{array}{cc}
a & b \\\\
c & d
\\end{array}
\\right)
=
ad - bc
""")
def get_cross_product(self):
return OldTex("""
\\vec{\\textbf{v}} \\times \\textbf{w} =
\\text{Det}\\left(
\\begin{array}{ccc}
\\hat{\imath} & \\hat{\jmath} & \\hat{k} \\\\
v_1 & v_2 & v_3 \\\\
w_1 & w_2 & w_3 \\\\
\\end{array}
\\right)
""")
def get_eigenvalue(self):
result = OldTex("\\text{Det}\\left(A - \\lambda I \\right) = 0")
result.submobjects[0][-5].set_color(YELLOW)
return result
def get_matrix_multiplication_question(self):
why = OldTexText("Why?").set_color(BLUE)
mult = self.get_matrix_multiplication()
why.next_to(mult, UP)
result = VMobject(why, mult)
result.get_center = lambda : mult.get_center()
return result
def get_cross_product_question(self):
cross = OldTex("\\vec{v} \\times \\vec{w}")
left_right_arrow = DoubleArrow(Point(LEFT), Point(RIGHT))
det = OldTexText("Det")
q_mark = OldTexText("?")
left_right_arrow.next_to(cross)
det.next_to(left_right_arrow)
q_mark.next_to(left_right_arrow, UP)
cross_question = VMobject(cross, left_right_arrow, q_mark, det)
cross_question.get_center = lambda : left_right_arrow.get_center()
return cross_question
def get_eigen_question(self):
result = OldTexText(
"What the heck \\\\ does ``eigen'' mean?",
)
for mob in result.submobjects[-11:-6]:
mob.set_color(YELLOW)
return result
class NumericVsGeometric(Scene):
def construct(self):
self.setup()
self.specifics_concepts()
self.clear_way_for_geometric()
self.list_geometric_benefits()
def setup(self):
numeric = OldTexText("Numeric operations")
geometric = OldTexText("Geometric intuition")
for mob in numeric, geometric:
mob.to_corner(UP+LEFT)
geometric.shift(FRAME_X_RADIUS*RIGHT)
hline = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT)
hline.next_to(numeric, DOWN)
hline.to_edge(LEFT, buff = 0)
vline = Line(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN)
for mob in hline, vline:
mob.set_color(GREEN)
self.play(ShowCreation(VMobject(hline, vline)))
digest_locals(self)
def specifics_concepts(self):
matrix_vector_product = OldTex(" ".join([
matrix_to_tex_string(EXAMPLE_TRANFORM),
matrix_to_tex_string(TRANFORMED_VECTOR),
"&=",
matrix_to_tex_string([
["1 \\cdot 1 + 0 \\cdot 2"],
["1 \\cdot 1 + (-1)\\cdot 2"]
]),
"\\\\ &=",
matrix_to_tex_string([[1], [-1]]),
]))
matrix_vector_product.set_width(FRAME_X_RADIUS-0.5)
matrix_vector_product.next_to(self.vline, LEFT)
self.play(
Write(self.numeric),
FadeIn(matrix_vector_product),
run_time = 2
)
self.wait()
self.play(Write(self.geometric, run_time = 2))
### Paste in linear transformation
self.wait()
digest_locals(self)
def clear_way_for_geometric(self):
new_line = Line(FRAME_Y_RADIUS*LEFT, FRAME_Y_RADIUS*RIGHT)
new_line.shift((FRAME_Y_RADIUS+1)*DOWN)
self.play(
Transform(self.vline, new_line),
Transform(self.hline, new_line),
ApplyMethod(self.numeric.shift, (FRAME_HEIGHT+1)*DOWN),
ApplyMethod(
self.matrix_vector_product.shift,
(FRAME_HEIGHT+1)*DOWN
),
ApplyMethod(self.geometric.to_edge, LEFT)
)
def list_geometric_benefits(self):
follow_words = OldTexText("is helpful for \\dots")
follow_words.next_to(self.geometric)
#Ugly hack
diff = follow_words.submobjects[0].get_bottom()[1] - \
self.geometric.submobjects[0].get_bottom()[1]
follow_words.shift(diff*DOWN)
randys = [
Randolph(mode = "speaking"),
Randolph(mode = "surprised"),
Randolph(mode = "pondering")
]
bulb = SVGMobject("light_bulb")
bulb.set_height(1)
bulb.set_color(YELLOW)
thoughts = [
matrix_to_mobject(EXAMPLE_TRANFORM),
bulb,
OldTexText("So therefore...").scale(0.5)
]
self.play(Write(follow_words, run_time = 1.5))
curr_randy = None
for randy, thought in zip(randys, thoughts):
randy.shift(DOWN)
thought.next_to(randy, UP+RIGHT, buff = 0)
if curr_randy:
self.play(
Transform(curr_randy, randy),
Transform(curr_thought, thought)
)
else:
self.play(
FadeIn(randy),
Write(thought, run_time = 1)
)
curr_randy = randy
curr_thought = thought
self.wait(1.5)
class ExampleTransformation(LinearTransformationScene):
def construct(self):
self.setup()
self.add_vector(np.array(TRANFORMED_VECTOR).flatten())
self.apply_matrix(EXAMPLE_TRANFORM)
self.wait()
class NumericToComputations(Scene):
def construct(self):
top = OldTexText("Numeric understanding")
arrow = Arrow(UP, DOWN)
bottom = OldTexText("Actual computations")
top.next_to(arrow, UP)
bottom.next_to(arrow, DOWN)
self.add(top)
self.play(ShowCreation(arrow))
self.play(FadeIn(bottom))
self.wait()
class LinAlgPyramid(Scene):
def construct(self):
rects = self.get_rects()
words = self.place_words_in_rects([
"Geometric understanding",
"Computations",
"Uses"
], rects)
for word, rect in zip(words, rects):
self.play(
Write(word),
ShowCreation(rect),
run_time = 1
)
self.wait()
self.play(*[
ApplyMethod(m.set_color, GREY_D)
for m in (words[0], rects[0])
])
self.wait()
self.list_applications(rects[-1])
def get_rects(self):
height = 1
rects = [
Rectangle(height = height, width = width)
for width in (8, 5, 2)
]
rects[0].shift(2*DOWN)
for i in 1, 2:
rects[i].next_to(rects[i-1], UP, buff = 0)
return rects
def place_words_in_rects(self, words, rects):
result = []
for word, rect in zip(words, rects):
tex_mob = OldTexText(word)
tex_mob.shift(rect.get_center())
result.append(tex_mob)
return result
def list_applications(self, top_mob):
subjects = [
OldTexText(word).to_corner(UP+RIGHT)
for word in [
"computer science",
"engineering",
"statistics",
"economics",
"pure math",
]
]
arrow = Arrow(top_mob, subjects[0].get_bottom(), color = RED)
self.play(ShowCreation(arrow))
curr_subject = None
for subject in subjects:
if curr_subject:
subject.shift(curr_subject.get_center()-subject.get_center())
self.play(Transform(curr_subject, subject, run_time = 0.5))
else:
curr_subject = subject
self.play(FadeIn(curr_subject, run_time = 0.5))
self.wait()
class IntimidatingProf(Scene):
def construct(self):
randy = Randolph().to_corner()
morty = Mortimer().to_corner(DOWN+RIGHT)
morty.shift(3*LEFT)
morty_name1 = OldTexText("Professor")
morty_name2 = OldTexText("Coworker")
for name in morty_name1, morty_name2:
name.to_edge(RIGHT)
name.shift(2*UP)
arrow = Arrow(morty_name1.get_bottom(), morty)
speech_bubble = SpeechBubble(height = 3).flip()
speech_bubble.pin_to(morty)
speech_bubble.shift(RIGHT)
speech_bubble.write("And of course $B^{-1}AB$ will \\\\ also have positive eigenvalues...")
thought_bubble = ThoughtBubble(width = 6, height = 5)
thought_bubble.next_to(morty, UP)
thought_bubble.to_edge(RIGHT, buff = -1)
thought_bubble.make_green_screen()
q_marks = OldTexText("???")
q_marks.next_to(randy, UP)
randy_bubble = randy.get_bubble()
randy_bubble.add_content(matrix_multiplication())
self.add(randy, morty)
self.play(
FadeIn(morty_name1),
ShowCreation(arrow)
)
self.play(Transform(morty_name1, morty_name2))
self.wait()
self.play(FadeOut(morty_name1), FadeOut(arrow))
self.play(
FadeIn(speech_bubble),
ApplyMethod(morty.change_mode, "speaking")
)
self.play(FadeIn(thought_bubble))
self.wait()
self.play(
ApplyMethod(randy.change_mode, "confused"),
Write(q_marks, run_time = 1)
)
self.play(FadeOut(VMobject(speech_bubble, thought_bubble)))
self.play(FadeIn(randy_bubble))
self.wait()
class ThoughtBubbleTransformation(LinearTransformationScene):
def construct(self):
self.setup()
rotation = rotation_about_z(np.pi/3)
self.apply_matrix(
np.linalg.inv(rotation),
path_arc = -np.pi/3,
)
self.apply_matrix(EXAMPLE_TRANFORM)
self.apply_matrix(
rotation,
path_arc = np.pi/3,
)
self.wait()
class SineApproximations(Scene):
def construct(self):
series = self.get_series()
one_approx = self.get_approx_series("1", 1)
one_approx.set_color(YELLOW)
pi_sixts_approx = self.get_approx_series("\\pi/6", np.pi/6)
pi_sixts_approx.set_color(RED)
words = OldTexText("(How calculators compute sine)")
words.set_color(GREEN)
series.to_edge(UP)
one_approx.next_to(series, DOWN, buff = 1.5)
pi_sixts_approx.next_to(one_approx, DOWN, buff = 1.5)
self.play(Write(series))
self.wait()
self.play(FadeIn(words))
self.wait(2)
self.play(FadeOut(words))
self.remove(words)
self.wait()
self.play(Write(one_approx))
self.play(Write(pi_sixts_approx))
self.wait()
def get_series(self):
return OldTex("""
\\sin(x) = x - \\dfrac{x^3}{3!} + \\dfrac{x^5}{5!}
+ \\cdots + (-1)^n \\dfrac{x^{2n+1}}{(2n+1)!} + \\cdots
""")
def get_approx_series(self, val_str, val):
#Default to 3 terms
approximation = val - (val**3)/6. + (val**5)/120.
return OldTex("""
\\sin(%s) \\approx
%s - \\dfrac{(%s)^3}{3!} + \\dfrac{(%s)^5}{5!} \\approx
%.04f
"""%(val_str, val_str, val_str, val_str, approximation))
class LooseConnectionToTriangles(Scene):
def construct(self):
sine = OldTex("\\sin(x)")
triangle = Polygon(ORIGIN, 2*RIGHT, 2*RIGHT+UP)
arrow = DoubleArrow(LEFT, RIGHT)
sine.next_to(arrow, LEFT)
triangle.next_to(arrow, RIGHT)
q_mark = OldTexText("?").scale(1.5)
q_mark.next_to(arrow, UP)
self.add(sine)
self.play(ShowCreation(arrow))
self.play(ShowCreation(triangle))
self.play(Write(q_mark))
self.wait()
class PhysicsExample(Scene):
def construct(self):
title = OldTexText("Physics")
title.to_corner(UP+LEFT)
parabola = FunctionGraph(
lambda x : (3-x)*(3+x)/4,
x_min = -4,
x_max = 4
)
self.play(Write(title))
self.projectile(parabola)
self.velocity_vector(parabola)
self.approximate_sine()
def projectile(self, parabola):
dot = Dot(radius = 0.15)
kwargs = {
"run_time" : 3,
"rate_func" : None
}
self.play(
MoveAlongPath(dot, parabola.copy(), **kwargs),
ShowCreation(parabola, **kwargs)
)
self.wait()
def velocity_vector(self, parabola):
alpha = 0.7
d_alpha = 0.01
vector_length = 3
p1 = parabola.point_from_proportion(alpha)
p2 = parabola.point_from_proportion(alpha + d_alpha)
vector = vector_length*(p2-p1)/get_norm(p2-p1)
v_mob = Vector(vector, color = YELLOW)
vx = Vector(vector[0]*RIGHT, color = GREEN_B)
vy = Vector(vector[1]*UP, color = RED)
v_mob.shift(p1)
vx.shift(p1)
vy.shift(vx.get_end())
arc = Arc(
angle_of_vector(vector),
radius = vector_length / 4.
)
arc.shift(p1)
theta = OldTex("\\theta").scale(0.75)
theta.next_to(arc, RIGHT, buff = 0.1)
v_label = OldTex("\\vec{v}")
v_label.shift(p1 + RIGHT*vector[0]/4 + UP*vector[1]/2)
v_label.set_color(v_mob.get_color())
vx_label = OldTex("||\\vec{v}|| \\cos(\\theta)")
vx_label.next_to(vx, UP)
vx_label.set_color(vx.get_color())
vy_label = OldTex("||\\vec{v}|| \\sin(\\theta)")
vy_label.next_to(vy, RIGHT)
vy_label.set_color(vy.get_color())
for v in v_mob, vx, vy:
self.play(
ShowCreation(v)
)
self.play(
ShowCreation(arc),
Write(theta, run_time = 1)
)
for label in v_label, vx_label, vy_label:
self.play(Write(label, run_time = 1))
self.wait()
def approximate_sine(self):
approx = OldTex("\\sin(\\theta) \\approx 0.7\\text{-ish}")
morty = Mortimer(mode = "speaking")
morty.flip()
morty.to_corner()
bubble = SpeechBubble(width = 4, height = 3)
bubble.set_fill(BLACK, opacity = 1)
bubble.pin_to(morty)
bubble.position_mobject_inside(approx)
self.play(
FadeIn(morty),
ShowCreation(bubble),
Write(approx),
run_time = 2
)
self.wait()
class LinearAlgebraIntuitions(Scene):
def construct(self):
title = OldTexText("Preview of core visual intuitions")
title.to_edge(UP)
h_line = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT)
h_line.next_to(title, DOWN)
h_line.set_color(BLUE_E)
intuitions = [
"Matrices transform space",
"Matrix multiplication corresponds to applying " +
"one transformation after another",
"The determinant gives the factor by which areas change",
]
self.play(
Write(title),
ShowCreation(h_line),
run_time = 2
)
for count, intuition in enumerate(intuitions, 3):
intuition += " (details coming in chapter %d)"%count
mob = OldTexText(intuition)
mob.scale(0.7)
mob.next_to(h_line, DOWN)
self.play(FadeIn(mob))
self.wait(4)
self.play(FadeOut(mob))
self.remove(mob)
self.wait()
class MatricesAre(Scene):
def construct(self):
matrix = matrix_to_mobject([[1, -1], [1, 2]])
matrix.set_height(6)
arrow = Arrow(LEFT, RIGHT, stroke_width = 8, preserve_tip_size_when_scaling = False)
arrow.scale(2)
arrow.to_edge(RIGHT)
matrix.next_to(arrow, LEFT)
self.play(Write(matrix, run_time = 1))
self.play(ShowCreation(arrow))
self.wait()
class ExampleTransformationForIntuitionList(LinearTransformationScene):
def construct(self):
self.setup()
self.apply_matrix([[1, -1], [1, 2]])
self.wait()
class MatrixMultiplicationIs(Scene):
def construct(self):
matrix1 = matrix_to_mobject([[1, -1], [1, 2]])
matrix1.set_color(BLUE)
matrix2 = matrix_to_mobject([[2, 1], [1, 2]])
matrix2.set_color(GREEN)
for m in matrix1, matrix2:
m.set_height(3)
arrow = Arrow(LEFT, RIGHT, stroke_width = 6, preserve_tip_size_when_scaling = False)
arrow.scale(2)
arrow.to_edge(RIGHT)
matrix1.next_to(arrow, LEFT)
matrix2.next_to(matrix1, LEFT)
brace1 = Brace(matrix1, UP)
apply_first = OldTexText("Apply first").next_to(brace1, UP)
brace2 = Brace(matrix2, DOWN)
apply_second = OldTexText("Apply second").next_to(brace2, DOWN)
self.play(
Write(matrix1),
ShowCreation(arrow),
GrowFromCenter(brace1),
Write(apply_first),
run_time = 1
)
self.wait()
self.play(
Write(matrix2),
GrowFromCenter(brace2),
Write(apply_second),
run_time = 1
)
self.wait()
class ComposedTransformsForIntuitionList(LinearTransformationScene):
def construct(self):
self.setup()
self.apply_matrix([[1, -1], [1, 2]])
self.wait()
self.apply_matrix([[2, 1], [1, 2]])
self.wait()
class DeterminantsAre(Scene):
def construct(self):
tex_mob = OldTex("""
\\text{Det}\\left(\\left[
\\begin{array}{cc}
1 & -1 \\\\
1 & 2
\\end{array}
\\right]\\right)
""")
tex_mob.set_height(4)
arrow = Arrow(LEFT, RIGHT, stroke_width = 8, preserve_tip_size_when_scaling = False)
arrow.scale(2)
arrow.to_edge(RIGHT)
tex_mob.next_to(arrow, LEFT)
self.play(
Write(tex_mob),
ShowCreation(arrow),
run_time = 1
)
class TransformationForDeterminant(LinearTransformationScene):
def construct(self):
self.setup()
square = Square(side_length = 1)
square.shift(-square.get_corner(DOWN+LEFT))
square.set_fill(YELLOW_A, 0.5)
self.add_transformable_mobject(square)
self.apply_matrix([[1, -1], [1, 2]])
class ProfessorsTry(Scene):
def construct(self):
morty = Mortimer()
morty.to_corner(DOWN+RIGHT)
morty.shift(3*LEFT)
speech_bubble = morty.get_bubble(SpeechBubble, height = 4, width = 8)
speech_bubble.shift(RIGHT)
words = OldTexText(
"It really is beautiful! I want you to \\\\" + \
"see it the way I do...",
)
speech_bubble.position_mobject_inside(words)
thought_bubble = ThoughtBubble(width = 4, height = 3.5)
thought_bubble.next_to(morty, UP)
thought_bubble.to_edge(RIGHT)
thought_bubble.make_green_screen()
randy = Randolph()
randy.scale(0.8)
randy.to_corner()
self.add(randy, morty)
self.play(
ApplyMethod(morty.change_mode, "speaking"),
FadeIn(speech_bubble),
FadeIn(words)
)
self.play(Blink(randy))
self.play(FadeIn(thought_bubble))
self.play(Blink(morty))
class ExampleMatrixMultiplication(NumericalMatrixMultiplication):
CONFIG = {
"left_matrix" : [[-3, 1], [2, 5]],
"right_matrix" : [[5, 3], [7, -3]]
}
class TableOfContents(Scene):
def construct(self):
title = OldTexText("Essence of Linear Algebra")
title.set_color(BLUE)
title.to_corner(UP+LEFT)
h_line = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT)
h_line.next_to(title, DOWN)
h_line.to_edge(LEFT, buff = 0)
chapters = VMobject(*list(map(TexText, [
"Chapter 1: Vectors, what even are they?",
"Chapter 2: Linear combinations, span and bases",
"Chapter 3: Matrices as linear transformations",
"Chapter 4: Matrix multiplication as composition",
"Chapter 5: The determinant",
"Chapter 6: Inverse matrices, column space and null space",
"Chapter 7: Dot products and cross products",
"Chapter 8: Change of basis",
"Chapter 9: Eigenvectors and eigenvalues",
"Chapter 10: Abstract vector spaces",
])))
chapters.arrange(DOWN)
chapters.scale(0.7)
chapters.next_to(h_line, DOWN)
self.play(
Write(title),
ShowCreation(h_line)
)
for chapter in chapters.split():
chapter.to_edge(LEFT, buff = 1)
self.play(FadeIn(chapter))
self.wait(2)
entry3 = chapters.split()[2]
added_words = OldTexText("(Personally, I'm most excited \\\\ to do this one)")
added_words.scale(0.5)
added_words.set_color(YELLOW)
added_words.next_to(h_line, DOWN)
added_words.to_edge(RIGHT)
arrow = Arrow(added_words.get_bottom(), entry3)
self.play(
ApplyMethod(entry3.set_color, YELLOW),
ShowCreation(arrow),
Write(added_words),
run_time = 1
)
self.wait()
removeable = VMobject(added_words, arrow, h_line, title)
self.play(FadeOut(removeable))
self.remove(removeable)
self.series_of_videos(chapters)
def series_of_videos(self, chapters):
icon = SVGMobject("video_icon")
icon.center()
icon.set_width(FRAME_WIDTH/12.)
icon.set_stroke(color = WHITE, width = 0)
icons = [icon.copy() for chapter in chapters.split()]
colors = Color(BLUE_A).range_to(BLUE_D, len(icons))
for icon, color in zip(icons, colors):
icon.set_fill(color, opacity = 1)
icons = VMobject(*icons)
icons.arrange(RIGHT)
icons.to_edge(LEFT)
icons.shift(UP)
randy = Randolph()
randy.to_corner()
bubble = randy.get_bubble()
new_icons = icons.copy().scale(0.2)
bubble.position_mobject_inside(new_icons)
self.play(Transform(
chapters, icons,
path_arc = np.pi/2,
))
self.clear()
self.add(icons)
self.play(FadeIn(randy))
self.play(Blink(randy))
self.wait()
self.play(
ShowCreation(bubble),
Transform(icons, new_icons)
)
self.remove(icons)
bubble.make_green_screen()
self.wait()
class ResourceForTeachers(Scene):
def construct(self):
morty = Mortimer(mode = "speaking")
morty.to_corner(DOWN + RIGHT)
bubble = morty.get_bubble(SpeechBubble)
bubble.write("I'm assuming you \\\\ know linear algebra\\dots")
words = bubble.content
bubble.clear()
randys = VMobject(*[
Randolph(color = c)
for c in (BLUE_D, BLUE_C, BLUE_E)
])
randys.arrange(RIGHT)
randys.scale(0.8)
randys.to_corner(DOWN+LEFT)
self.add(randys, morty)
self.play(FadeIn(bubble), Write(words), run_time = 3)
for randy in np.array(randys.split())[[2,0,1]]:
self.play(Blink(randy))
self.wait()
class AboutPacing(Scene):
def construct(self):
words = OldTexText("About pacing...")
dots = words.split()[-3:]
words.remove(*dots)
self.play(FadeIn(words))
self.play(Write(VMobject(*dots)))
self.wait()
class DifferingBackgrounds(Scene):
def construct(self):
words = list(map(TexText, [
"Just brushing up",
"Has yet to take the course",
"Supplementing course concurrently",
]))
students = VMobject(*[
Randolph(color = c)
for c in (BLUE_D, BLUE_C, BLUE_E)
])
modes = ["pondering", "speaking_looking_left", "sassy"]
students.arrange(RIGHT)
students.scale(0.8)
students.center().to_edge(DOWN)
last_word, last_arrow = None, None
for word, student, mode in zip(words, students.split(), modes):
word.shift(2*UP)
arrow = Arrow(word, student)
if last_word:
word_anim = Transform(last_word, word)
arrow_anim = Transform(last_arrow, arrow)
else:
word_anim = Write(word, run_time = 1)
arrow_anim = ShowCreation(arrow)
last_word = word
last_arrow = arrow
self.play(
word_anim, arrow_anim,
ApplyMethod(student.change_mode, mode)
)
self.play(Blink(student))
self.wait()
self.wait()
class PauseAndPonder(Scene):
def construct(self):
pause = OldTex("=").rotate(np.pi/2)
pause.stretch(0.5, 1)
pause.set_height(1.5)
bubble = ThoughtBubble().set_height(2)
pause.shift(LEFT)
bubble.next_to(pause, RIGHT, buff = 1)
self.play(FadeIn(pause))
self.play(ShowCreation(bubble))
self.wait()
class NextVideo(Scene):
def construct(self):
title = OldTexText("Next video: Vectors, what even are they?")
title.to_edge(UP)
rect = Rectangle(width = 16, height = 9, color = BLUE)
rect.set_height(6)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
|