Dataset Viewer
file_path
stringlengths 21
66
| content
stringlengths 0
219k
|
---|---|
videos_3b1b/README.md
|
This project contains the code used to generate the explanatory math videos found on [3Blue1Brown](https://www.3blue1brown.com/).
This almost entirely consists of scenes generated using the library [Manim](https://github.com/3b1b/manim). See also the community maintained version at [ManimCommunity](https://github.com/ManimCommunity/manim/).
Note, while the library Manim itself is open source and under the MIT license, the contents of this project are intended only to be used for 3Blue1Brown videos themselves.
Copyright © 2022 3Blue1Brown
|
videos_3b1b/stage_scenes.py
|
#!/usr/bin/env python
import inspect
import os
import sys
import importlib
from manimlib.config import get_module
from manimlib.extract_scene import is_child_scene
def get_sorted_scene_classes(module_name):
module = get_module(module_name)
if hasattr(module, "SCENES_IN_ORDER"):
return module.SCENES_IN_ORDER
# Otherwise, deduce from the order in which
# they're defined in a file
importlib.import_module(module.__name__)
line_to_scene = {}
name_scene_list = inspect.getmembers(
module,
lambda obj: is_child_scene(obj, module)
)
for name, scene_class in name_scene_list:
if inspect.getmodule(scene_class).__name__ != module.__name__:
continue
lines, line_no = inspect.getsourcelines(scene_class)
line_to_scene[line_no] = scene_class
return [
line_to_scene[index]
for index in sorted(line_to_scene.keys())
]
def stage_scenes(module_name):
scene_classes = get_sorted_scene_classes(module_name)
if len(scene_classes) == 0:
print("There are no rendered animations from this module")
return
# TODO, fix this
animation_dir = os.path.join(
os.path.expanduser('~'),
"Dropbox/3Blue1Brown/videos/2021/holomorphic_dynamics/videos"
)
#
files = os.listdir(animation_dir)
sorted_files = []
for scene_class in scene_classes:
scene_name = scene_class.__name__
clips = [f for f in files if f.startswith(scene_name + ".")]
for clip in clips:
sorted_files.append(os.path.join(animation_dir, clip))
# Partial movie file directory
# movie_dir = get_movie_output_directory(
# scene_class, **output_directory_kwargs
# )
# if os.path.exists(movie_dir):
# for extension in [".mov", ".mp4"]:
# int_files = get_sorted_integer_files(
# pmf_dir, extension=extension
# )
# for file in int_files:
# sorted_files.append(os.path.join(pmf_dir, file))
# else:
# animation_subdir = os.path.dirname(animation_dir)
count = 0
while True:
staged_scenes_dir = os.path.join(
animation_dir,
os.pardir,
"staged_scenes_{}".format(count)
)
if not os.path.exists(staged_scenes_dir):
os.makedirs(staged_scenes_dir)
break
# Otherwise, keep trying new names until
# there is a free one
count += 1
for count, f in reversed(list(enumerate(sorted_files))):
# Going in reversed order means that when finder
# sorts by date modified, it shows up in the
# correct order
symlink_name = os.path.join(
staged_scenes_dir,
"Scene_{:03}_{}".format(
count, f.split(os.sep)[-1]
)
)
os.symlink(f, symlink_name)
if __name__ == "__main__":
if len(sys.argv) < 2:
raise Exception("No module given.")
module_name = sys.argv[1]
stage_scenes(module_name)
|
videos_3b1b/manim_imports_ext.py
|
from manimlib import *
from manimlib.mobject.svg.old_tex_mobject import *
from custom.backdrops import *
from custom.banner import *
from custom.characters.pi_creature import *
from custom.characters.pi_creature_animations import *
from custom.characters.pi_creature_scene import *
from custom.deprecated import *
from custom.drawings import *
from custom.end_screen import *
from custom.filler import *
from custom.logo import *
from custom.opening_quote import *
|
videos_3b1b/custom_config.yml
|
directories:
mirror_module_path: True
removed_mirror_prefix: "/Users/grant/cs/videos/"
output: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos"
raster_images: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/images/raster"
vector_images: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/images/vector"
pi_creature_images: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/images/pi_creature/svg"
sounds: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/sounds"
data: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/data"
temporary_storage: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/manim_cache"
universal_import_line: "from manim_imports_ext import *"
# tex:
# executable: "xelatex -no-pdf"
# template_file: "ctex_template.tex"
# intermediate_filetype: "xdv"
style:
font: "CMU Serif"
text_alignment: "CENTER"
background_color: "#000000"
camera_resolutions:
default_resolution: "4k"
fps: 30
window_position: UR
window_monitor: 0
full_screen: False
embed_exception_mode: "Plain"
|
videos_3b1b/_2017/borsuk.py
|
from manim_imports_ext import *
from functools import reduce
class Jewel(VMobject):
CONFIG = {
"color" : WHITE,
"fill_opacity" : 0.75,
"stroke_width" : 0,
"height" : 0.5,
"num_equator_points" : 5,
"sun_vect" : OUT+LEFT+UP,
}
def init_points(self):
for vect in OUT, IN:
compass_vects = list(compass_directions(self.num_equator_points))
if vect is IN:
compass_vects.reverse()
for vect_pair in adjacent_pairs(compass_vects):
self.add(Polygon(vect, *vect_pair))
self.set_height(self.height)
self.rotate(-np.pi/2-np.pi/24, RIGHT)
self.rotate(-np.pi/12, UP)
self.submobjects.sort(
key=lambda m: -m1.get_center()[2]
)
return self
class Necklace(VMobject):
CONFIG = {
"width" : FRAME_WIDTH - 1,
"jewel_buff" : MED_SMALL_BUFF,
"chain_color" : GREY,
"default_colors" : [(4, BLUE), (6, WHITE), (4, GREEN)]
}
def __init__(self, *colors, **kwargs):
digest_config(self, kwargs, locals())
if len(colors) == 0:
self.colors = self.get_default_colors()
VMobject.__init__(self, **kwargs)
def get_default_colors(self):
result = list(it.chain(*[
num*[color]
for num, color in self.default_colors
]))
random.shuffle(result)
return result
def init_points(self):
jewels = VGroup(*[
Jewel(color = color)
for color in self.colors
])
jewels.arrange(buff = self.jewel_buff)
jewels.set_width(self.width)
jewels.center()
j_to_j_dist = (jewels[1].get_center()-jewels[0].get_center())[0]
chain = Line(
jewels[0].get_center() + j_to_j_dist*LEFT/2,
jewels[-1].get_center() + j_to_j_dist*RIGHT/2,
color = self.chain_color,
)
self.add(chain, *jewels)
self.chain = chain
self.jewels = jewels
################
class FromPreviousTopologyVideo(Scene):
def construct(self):
rect = Rectangle(height = 9, width = 16)
rect.set_height(FRAME_HEIGHT-2)
title = OldTexText("From original ``Who cares about topology'' video")
title.to_edge(UP)
rect.next_to(title, DOWN)
self.add(title)
self.play(ShowCreation(rect))
self.wait()
class CheckOutMathologer(PiCreatureScene):
CONFIG = {
"logo_height" : 1.5,
"screen_height" : 5,
"channel_name" : "Mathologer",
"logo_file" : "mathologer_logo",
"logo_color" : None,
}
def construct(self):
logo = self.get_logo()
name = OldTexText(self.channel_name)
name.next_to(logo, RIGHT)
rect = Rectangle(height = 9, width = 16)
rect.set_height(self.screen_height)
rect.next_to(logo, DOWN)
rect.to_edge(LEFT)
self.play(
self.get_logo_intro_animation(logo),
self.pi_creature.change_mode, "hooray",
)
self.play(
ShowCreation(rect),
Write(name)
)
self.wait(2)
self.change_mode("happy")
self.wait(2)
def get_logo(self):
logo = ImageMobject(self.logo_file)
logo.set_height(self.logo_height)
logo.to_corner(UP+LEFT)
if self.logo_color is not None:
logo.set_color(self.logo_color)
logo.stroke_width = 1
return logo
def get_logo_intro_animation(self, logo):
logo.save_state()
logo.shift(DOWN)
logo.set_color(BLACK)
return ApplyMethod(logo.restore)
class IntroduceStolenNecklaceProblem(ThreeDScene):
CONFIG = {
"jewel_colors" : [BLUE, GREEN, WHITE, RED],
"num_per_jewel" : [8, 10, 4, 6],
"num_shuffles" : 1,
"necklace_center" : UP,
"random_seed" : 2,
"forced_binary_choices" : (0, 1, 0, 1, 0),
}
def construct(self):
random.seed(self.random_seed)
self.add_thieves()
self.write_title()
self.introduce_necklace()
self.divvy_by_cutting_all()
self.divvy_with_n_cuts()
self.shuffle_jewels(self.necklace.jewels)
self.divvy_with_n_cuts()
def add_thieves(self):
thieves = VGroup(
Randolph(),
Mortimer()
)
thieves.arrange(RIGHT, buff = 4*LARGE_BUFF)
thieves.to_edge(DOWN)
thieves[0].make_eye_contact(thieves[1])
self.add(thieves)
self.thieves = thieves
def write_title(self):
title = OldTexText("Stolen necklace problem")
title.to_edge(UP)
self.play(
Write(title),
*[
ApplyMethod(pi.look_at, title)
for pi in self.thieves
]
)
self.title = title
def introduce_necklace(self):
necklace = self.get_necklace()
jewels = necklace.jewels
jewel_types = self.get_jewels_organized_by_type(jewels)
enumeration_labels = VGroup()
for jewel_type in jewel_types:
num_mob = OldTex(str(len(jewel_type)))
jewel_copy = jewel_type[0].copy().scale(2)
jewel_copy.next_to(num_mob)
label = VGroup(num_mob, jewel_copy)
enumeration_labels.add(label)
enumeration_labels.arrange(RIGHT, buff = LARGE_BUFF)
enumeration_labels.to_edge(UP)
self.play(
FadeIn(
necklace,
lag_ratio = 0.5,
run_time = 3
),
*it.chain(*[
[pi.change_mode, "conniving", pi.look_at, necklace]
for pi in self.thieves
])
)
self.play(*[
ApplyMethod(
jewel.rotate, np.pi/6, UP,
rate_func = there_and_back
)
for jewel in jewels
])
self.play(Blink(self.thieves[0]))
for jewel_type in jewel_types:
self.play(
jewel_type.shift, 0.2*UP,
rate_func = wiggle
)
self.wait()
for x in range(self.num_shuffles):
self.shuffle_jewels(jewels)
self.play(FadeOut(self.title))
for jewel_type, label in zip(jewel_types, enumeration_labels):
jewel_type.submobjects.sort(
key=lambda m: m1.get
)
jewel_type.save_state()
jewel_type.generate_target()
jewel_type.target.arrange()
jewel_type.target.scale(2)
jewel_type.target.move_to(2*UP)
self.play(
MoveToTarget(jewel_type),
Write(label)
)
self.play(jewel_type.restore)
self.play(Blink(self.thieves[1]))
self.enumeration_labels = enumeration_labels
self.jewel_types = jewel_types
def divvy_by_cutting_all(self):
enumeration_labels = self.enumeration_labels
necklace = self.necklace
jewel_types = self.jewel_types
thieves = self.thieves
both_half_labels = VGroup()
for thief, vect in zip(self.thieves, [LEFT, RIGHT]):
half_labels = VGroup()
for label in enumeration_labels:
tex, jewel = label
num = int(tex.get_tex())
half_label = VGroup(
OldTex(str(num/2)),
jewel.copy()
)
half_label.arrange()
half_labels.add(half_label)
half_labels.arrange(DOWN)
half_labels.set_height(thief.get_height())
half_labels.next_to(
thief, vect,
buff = MED_LARGE_BUFF,
aligned_edge = DOWN
)
both_half_labels.add(half_labels)
for half_labels in both_half_labels:
self.play(ReplacementTransform(
enumeration_labels.copy(),
half_labels
))
self.play(*[ApplyMethod(pi.change_mode, "pondering") for pi in thieves])
self.wait()
for type_index, jewel_type in enumerate(jewel_types):
jewel_type.save_state()
jewel_type_copy = jewel_type.copy()
n_jewels = len(jewel_type)
halves = [
VGroup(*jewel_type_copy[:n_jewels/2]),
VGroup(*jewel_type_copy[n_jewels/2:]),
]
for half, thief, vect in zip(halves, thieves, [RIGHT, LEFT]):
half.arrange(DOWN)
half.next_to(
thief, vect,
buff = SMALL_BUFF + type_index*half.get_width(),
aligned_edge = DOWN
)
self.play(
Transform(jewel_type, jewel_type_copy),
*[
ApplyMethod(thief.look_at, jewel_type_copy)
for thief in thieves
]
)
self.play(*it.chain(*[
[thief.change_mode, "happy", thief.look_at, necklace]
for thief in thieves
]))
self.wait()
self.play(*[
jewel_type.restore
for jewel_type in jewel_types
])
self.play(*it.chain(*[
[thief.change_mode, "confused", thief.look_at, necklace]
for thief in thieves
]))
def divvy_with_n_cuts(
self,
with_thieves = True,
highlight_groups = True,
show_matching_after_divvying = True,
):
necklace = self.necklace
jewel_types = self.jewel_types
jewels = sorted(
necklace.jewels,
lambda m1, m2 : cmp(m1.get_center()[0], m2.get_center()[0])
)
slice_indices, binary_choices = self.find_slice_indices(jewels, jewel_types)
subgroups = [
VGroup(*jewels[i1:i2])
for i1, i2 in zip(slice_indices, slice_indices[1:])
]
buff = (jewels[1].get_left()[0]-jewels[0].get_right()[0])/2
v_lines = VGroup(*[
DashedLine(UP, DOWN).next_to(group, RIGHT, buff = buff)
for group in subgroups[:-1]
])
strand_groups = [VGroup(), VGroup()]
for group, choice in zip(subgroups, binary_choices):
strand = Line(
group[0].get_center(), group[-1].get_center(),
color = necklace.chain.get_color()
)
strand.add(*group)
strand_groups[choice].add(strand)
self.add(strand)
self.play(ShowCreation(v_lines))
self.play(
FadeOut(necklace.chain),
*it.chain(*[
list(map(Animation, group))
for group in strand_groups
])
)
for group in strand_groups:
group.save_state()
self.play(
strand_groups[0].shift, UP/2.,
strand_groups[1].shift, DOWN/2.,
)
if with_thieves:
self.play(*it.chain(*[
[thief.change_mode, "happy", thief.look_at, self.necklace]
for thief in self.thieves
]))
self.play(Blink(self.thieves[1]))
else:
self.wait()
if highlight_groups:
for group in strand_groups:
box = Rectangle(
width = group.get_width()+2*SMALL_BUFF,
height = group.get_height()+2*SMALL_BUFF,
stroke_width = 0,
fill_color = YELLOW,
fill_opacity = 0.3,
)
box.move_to(group)
self.play(FadeIn(box))
self.wait()
self.play(FadeOut(box))
self.wait()
if show_matching_after_divvying:
for jewel_type in jewel_types:
self.play(
*[
ApplyMethod(jewel.scale, 1.5)
for jewel in jewel_type
],
rate_func = there_and_back,
run_time = 2
)
self.wait()
self.play(
FadeOut(v_lines),
FadeIn(necklace.chain),
*[
group.restore for group in strand_groups
]
)
self.remove(*strand_groups)
self.add(necklace)
########
def get_necklace(self, **kwargs):
colors = reduce(op.add, [
num*[color]
for num, color in zip(self.num_per_jewel, self.jewel_colors)
])
self.necklace = Necklace(*colors, **kwargs)
self.necklace.shift(self.necklace_center)
return self.necklace
def get_jewels_organized_by_type(self, jewels):
return [
VGroup(*[m for m in jewels if m.get_color() == color])
for color in map(Color, self.jewel_colors)
]
def shuffle_jewels(self, jewels, run_time = 2, path_arc = np.pi/2, **kwargs):
shuffled_indices = list(range(len(jewels)))
random.shuffle(shuffled_indices)
target_group = VGroup(*[
jewel.copy().move_to(jewels[shuffled_indices[i]])
for i, jewel in enumerate(jewels)
])
self.play(Transform(
jewels, target_group,
run_time = run_time,
path_arc = path_arc,
**kwargs
))
def find_slice_indices(self, jewels, jewel_types):
def jewel_to_type_number(jewel):
for i, jewel_type in enumerate(jewel_types):
if jewel in jewel_type:
return i
raise Exception("Not in any jewel_types")
type_numbers = list(map(jewel_to_type_number, jewels))
n_types = len(jewel_types)
for slice_indices in it.combinations(list(range(1, len(jewels))), n_types):
slice_indices = [0] + list(slice_indices) + [len(jewels)]
if self.forced_binary_choices is not None:
all_binary_choices = [self.forced_binary_choices]
else:
all_binary_choices = it.product(*[list(range(2))]*(n_types+1))
for binary_choices in all_binary_choices:
subsets = [
type_numbers[i1:i2]
for i1, i2 in zip(slice_indices, slice_indices[1:])
]
left_sets, right_sets = [
[
subset
for subset, index in zip(subsets, binary_choices)
if index == target_index
]
for target_index in range(2)
]
flat_left_set = np.array(list(it.chain(*left_sets)))
flat_right_set = np.array(list(it.chain(*right_sets)))
match_array = [
sum(flat_left_set == n) == sum(flat_right_set == n)
for n in range(n_types)
]
if np.all(match_array):
return slice_indices, binary_choices
raise Exception("No fair division found")
class ThingToProve(PiCreatureScene):
def construct(self):
arrow = Arrow(UP, DOWN)
top_words = OldTexText("$n$ jewel types")
top_words.next_to(arrow, UP)
bottom_words = OldTexText("""
Fair division possible
with $n$ cuts
""")
bottom_words.next_to(arrow, DOWN)
self.play(
Write(top_words, run_time = 2),
self.pi_creature.change_mode, "raise_right_hand"
)
self.play(ShowCreation(arrow))
self.play(
Write(bottom_words, run_time = 2),
self.pi_creature.change_mode, "pondering"
)
self.wait(3)
class FiveJewelCase(IntroduceStolenNecklaceProblem):
CONFIG = {
"jewel_colors" : [BLUE, GREEN, WHITE, RED, YELLOW],
"num_per_jewel" : [6, 4, 4, 2, 8],
"forced_binary_choices" : (0, 1, 0, 1, 0, 1),
}
def construct(self):
random.seed(self.random_seed)
self.add(self.get_necklace())
jewels = self.necklace.jewels
self.shuffle_jewels(jewels, run_time = 0)
self.jewel_types = self.get_jewels_organized_by_type(jewels)
self.add_title()
self.add_thieves()
for thief in self.thieves:
ApplyMethod(thief.change_mode, "pondering").update(1)
thief.look_at(self.necklace)
self.divvy_with_n_cuts()
def add_title(self):
n_cuts = len(self.jewel_colors)
title = OldTexText(
"%d jewel types, %d cuts"%(n_cuts, n_cuts)
)
title.to_edge(UP)
self.add(title)
class SixJewelCase(FiveJewelCase):
CONFIG = {
"jewel_colors" : [BLUE, GREEN, WHITE, RED, YELLOW, MAROON_B],
"num_per_jewel" : [6, 4, 4, 2, 2, 6],
"forced_binary_choices" : (0, 1, 0, 1, 0, 1, 0),
}
class DiscussApplicability(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
Minimize sharding,
allocate resources evenly
""")
self.play_student_changes(*["pondering"]*3)
self.wait(2)
class ThreeJewelCase(FiveJewelCase):
CONFIG = {
"jewel_colors" : [BLUE, GREEN, WHITE],
"num_per_jewel" : [6, 4, 8],
"forced_binary_choices" : (0, 1, 0, 1),
}
class RepeatedShuffling(IntroduceStolenNecklaceProblem):
CONFIG = {
"num_shuffles" : 5,
"random_seed" : 3,
"show_matching_after_divvying" : False,
}
def construct(self):
random.seed(self.random_seed)
self.add(self.get_necklace())
jewels = self.necklace.jewels
self.jewel_types = self.get_jewels_organized_by_type(jewels)
self.add_thieves()
for thief in self.thieves:
ApplyMethod(thief.change_mode, "pondering").update(1)
thief.look_at(self.necklace)
for x in range(self.num_shuffles):
self.shuffle_jewels(jewels)
self.divvy_with_n_cuts(
show_matching_after_divvying = False
)
class NowForTheTopology(TeacherStudentsScene):
def construct(self):
self.teacher_says("Now for the \\\\ topology")
self.play_student_changes(*["hooray"]*3)
self.wait(3)
class ExternallyAnimatedScene(Scene):
def construct(self):
raise Exception("Don't actually run this class.")
class SphereOntoPlaneIn3D(ExternallyAnimatedScene):
pass
class DiscontinuousSphereOntoPlaneIn3D(ExternallyAnimatedScene):
pass
class WriteWords(Scene):
CONFIG = {
"words" : "",
"color" : WHITE,
}
def construct(self):
words = OldTexText(self.words)
words.set_color(self.color)
words.set_width(FRAME_WIDTH-1)
words.to_edge(DOWN)
self.play(Write(words))
self.wait(2)
class WriteNotAllowed(WriteWords):
CONFIG = {
"words" : "Not allowed",
"color" : RED,
}
class NonAntipodalCollisionIn3D(ExternallyAnimatedScene):
pass
class AntipodalCollisionIn3D(ExternallyAnimatedScene):
pass
class WriteBorsukUlam(WriteWords):
CONFIG = {
"words" : "Borsuk-Ulam Theorem",
}
class WriteAntipodal(WriteWords):
CONFIG = {
"words" : "``Antipodal''",
"color" : MAROON_B,
}
class ProjectOntoEquatorIn3D(ExternallyAnimatedScene):
pass
class ProjectOntoEquatorWithPolesIn3D(ExternallyAnimatedScene):
pass
class ProjectAntipodalNonCollisionIn3D(ExternallyAnimatedScene):
pass
class ShearThenProjectnOntoEquatorPolesMissIn3D(ExternallyAnimatedScene):
pass
class ShearThenProjectnOntoEquatorAntipodalCollisionIn3D(ExternallyAnimatedScene):
pass
class ClassicExample(TeacherStudentsScene):
def construct(self):
self.teacher_says("The classic example...")
self.play_student_changes(*["happy"]*3)
self.wait(2)
class AntipodalEarthPoints(ExternallyAnimatedScene):
pass
class RotatingEarth(ExternallyAnimatedScene):
pass
class TemperaturePressurePlane(GraphScene):
CONFIG = {
"x_labeled_nums" : [],
"y_labeled_nums" : [],
"x_axis_label" : "Temperature",
"y_axis_label" : "Pressure",
"graph_origin" : 2.5*DOWN + 2*LEFT,
"corner_square_width" : 4,
"example_point_coords" : (2, 5),
}
def construct(self):
self.setup_axes()
self.draw_arrow()
self.add_example_coordinates()
self.wander_continuously()
def draw_arrow(self):
square = Square(
side_length = self.corner_square_width,
stroke_color = WHITE,
stroke_width = 0,
)
square.to_corner(UP+LEFT, buff = 0)
arrow = Arrow(
square.get_right(),
self.coords_to_point(*self.example_point_coords)
)
self.play(ShowCreation(arrow))
def add_example_coordinates(self):
dot = Dot(self.coords_to_point(*self.example_point_coords))
dot.set_color(YELLOW)
tex = OldTex("(25^\\circ\\text{C}, 101 \\text{ kPa})")
tex.next_to(dot, UP+RIGHT, buff = SMALL_BUFF)
self.play(ShowCreation(dot))
self.play(Write(tex))
self.wait()
self.play(FadeOut(tex))
def wander_continuously(self):
path = VMobject().set_points_smoothly([
ORIGIN, 2*UP+RIGHT, 2*DOWN+RIGHT,
5*RIGHT, 4*RIGHT+UP, 3*RIGHT+2*DOWN,
DOWN+LEFT, 2*RIGHT
])
point = self.coords_to_point(*self.example_point_coords)
path.shift(point)
path.set_color(GREEN)
self.play(ShowCreation(path, run_time = 10, rate_func=linear))
self.wait()
class AlternateSphereSquishing(ExternallyAnimatedScene):
pass
class AlternateAntipodalCollision(ExternallyAnimatedScene):
pass
class AskWhy(TeacherStudentsScene):
def construct(self):
self.student_says("But...why?")
self.play_student_changes("pondering", None, "thinking")
self.play(self.get_teacher().change_mode, "happy")
self.wait(3)
class PointOutVSauce(CheckOutMathologer):
CONFIG = {
"channel_name" : "",
"logo_file" : "Vsauce_logo",
"logo_height" : 1,
"logo_color" : GREY,
}
def get_logo(self):
logo = SVGMobject(file_name = self.logo_file)
logo.set_height(self.logo_height)
logo.to_corner(UP+LEFT)
logo.set_stroke(width = 0)
logo.set_fill(GREEN)
logo.sort()
return logo
def get_logo_intro_animation(self, logo):
return DrawBorderThenFill(
logo,
run_time = 2,
)
class WalkEquatorPostTransform(GraphScene):
CONFIG = {
"x_labeled_nums" : [],
"y_labeled_nums" : [],
"graph_origin" : 2.5*DOWN + 2*LEFT,
"curved_arrow_color" : WHITE,
"curved_arrow_radius" : 3,
"num_great_arcs" : 10,
}
def construct(self):
self.setup_axes()
self.add_curved_arrow()
self.great_arc_images = self.get_great_arc_images()
self.walk_equator()
self.walk_tilted_equator()
self.draw_transverse_curve()
self.walk_transverse_curve()
def add_curved_arrow(self):
arc = Arc(
start_angle = 2*np.pi/3, angle = -np.pi/2,
radius = self.curved_arrow_radius,
color = self.curved_arrow_color
)
arc.add_tip()
arc.move_to(self.coords_to_point(0, 7))
self.add(arc)
def walk_equator(self):
equator = self.great_arc_images[0]
dots = VGroup(Dot(), Dot())
dots.set_color(MAROON_B)
dot_movement = self.get_arc_walk_dot_movement(equator, dots)
dot_movement.update(0)
self.play(ShowCreation(equator, run_time = 3))
self.play(FadeIn(dots[0]))
dots[1].set_fill(opacity = 0)
self.play(dot_movement)
self.play(dots[1].set_fill, None, 1)
self.play(dot_movement)
self.play(dot_movement)
proportion = equator.collision_point_proportion
self.play(self.get_arc_walk_dot_movement(
equator, dots,
rate_func = lambda t : 2*proportion*smooth(t)
))
v_line = DashedLine(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN)
v_line.shift(dots.get_center()[0]*RIGHT)
self.play(ShowCreation(v_line))
self.wait()
self.play(FadeOut(v_line))
dots.save_state()
equator.save_state()
self.play(
equator.fade,
dots.fade
)
self.first_dots = dots
def walk_tilted_equator(self):
equator = self.great_arc_images[0]
tilted_eq = self.great_arc_images[1]
dots = VGroup(Dot(), Dot())
dots.set_color(MAROON_B)
dot_movement = self.get_arc_walk_dot_movement(tilted_eq, dots)
dot_movement.update(0)
self.play(ReplacementTransform(equator.copy(), tilted_eq))
self.wait()
self.play(FadeIn(dots))
self.play(dot_movement)
proportion = tilted_eq.collision_point_proportion
self.play(self.get_arc_walk_dot_movement(
tilted_eq, dots,
rate_func = lambda t : 2*proportion*smooth(t)
))
v_line = DashedLine(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN)
v_line.shift(dots.get_center()[0]*RIGHT)
self.play(ShowCreation(v_line))
self.wait()
self.play(FadeOut(v_line))
self.play(*list(map(FadeOut, [tilted_eq, dots])))
def draw_transverse_curve(self):
transverse_curve = self.get_transverse_curve(self.great_arc_images)
dots = self.first_dots
equator = self.great_arc_images[0]
self.play(dots.restore)
equator.restore()
self.great_arc_images.fade()
target_arcs = list(self.great_arc_images[1:])
target_dots = []
for arc in target_arcs:
new_dots = dots.copy()
for dot, point in zip(new_dots, arc.x_collision_points):
dot.move_to(point)
target_dots.append(new_dots)
alt_eq = equator.copy()
alt_eq.set_points(list(reversed(alt_eq.get_points())))
alt_dots = dots.copy()
alt_dots.submobjects.reverse()
target_arcs += [alt_eq, alt_eq.copy()]
target_dots += [alt_dots, alt_dots.copy()]
equator_transform = Succession(*[
Transform(equator, arc, rate_func=linear)
for arc in target_arcs
])
dots_transform = Succession(*[
Transform(dots, target, rate_func=linear)
for target in target_dots
])
self.play(
ShowCreation(transverse_curve, lag_ratio = 0),
equator_transform,
dots_transform,
run_time = 10,
rate_func=linear,
)
self.wait(2)
def walk_transverse_curve(self):
transverse_curve = self.get_transverse_curve(self.great_arc_images)
dots = self.first_dots
def dot_update(dots, alpha):
for dot, curve in zip(dots, transverse_curve):
dot.move_to(curve.point_from_proportion(alpha))
return dots
for x in range(2):
self.play(
UpdateFromAlphaFunc(dots, dot_update),
run_time = 4
)
self.play(
UpdateFromAlphaFunc(dots, dot_update),
run_time = 4,
rate_func = lambda t : 0.455*smooth(t)
)
self.play(
dots.set_color, YELLOW,
dots.scale, 1.2,
rate_func = there_and_back
)
self.wait()
#######
def get_arc_walk_dot_movement(self, arc, dots, **kwargs):
def dot_update(dots, alpha):
dots[0].move_to(arc.point_from_proportion(0.5*alpha))
dots[1].move_to(arc.point_from_proportion(0.5+0.5*alpha))
return dots
if "run_time" not in kwargs:
kwargs["run_time"] = 5
return UpdateFromAlphaFunc(dots, dot_update, **kwargs)
def sphere_to_plane(self, point):
x, y, z = point
return np.array([
x - 2*x*z + y + 1,
y+0.5*y*np.cos(z*np.pi),
0
])
def sphere_point(self, portion_around_equator, equator_tilt = 0):
theta = portion_around_equator*2*np.pi
point = np.cos(theta)*RIGHT + np.sin(theta)*UP
phi = equator_tilt*np.pi
return rotate_vector(point, phi, RIGHT)
def get_great_arc_images(self):
curves = VGroup(*[
ParametricCurve(
lambda t : self.sphere_point(t, s)
).apply_function(self.sphere_to_plane)
for s in np.arange(0, 1, 1./self.num_great_arcs)
# for s in [0]
])
curves.set_color(YELLOW)
curves[0].set_color(RED)
for curve in curves:
antipodal_x_diff = lambda x : \
curve.point_from_proportion(x+0.5)[0]-\
curve.point_from_proportion(x)[0]
last_x = 0
last_sign = np.sign(antipodal_x_diff(last_x))
for x in np.linspace(0, 0.5, 100):
sign = np.sign(antipodal_x_diff(x))
if sign != last_sign:
mean = np.mean([last_x, x])
curve.x_collision_points = [
curve.point_from_proportion(mean),
curve.point_from_proportion(mean+0.5),
]
curve.collision_point_proportion = mean
break
last_x = x
last_sign = sign
return curves
def get_transverse_curve(self, gerat_arc_images):
points = list(it.chain(*[
[
curve.x_collision_points[i]
for curve in gerat_arc_images
]
for i in (0, 1)
]))
full_curve = VMobject(close_new_points = True)
full_curve.set_points_smoothly(points + [points[0]])
full_curve.set_color(MAROON_B)
first_half = full_curve.copy().pointwise_become_partial(
full_curve, 0, 0.5
)
second_half = first_half.copy().rotate(np.pi, RIGHT)
broken_curve = VGroup(first_half, second_half)
return broken_curve
class WalkAroundEquatorPreimage(ExternallyAnimatedScene):
pass
class WalkTiltedEquatorPreimage(ExternallyAnimatedScene):
pass
class FormLoopTransverseToEquator(ExternallyAnimatedScene):
pass
class AntipodalWalkAroundTransverseLoop(ExternallyAnimatedScene):
pass
class MentionGenerality(TeacherStudentsScene, ThreeDScene):
def construct(self):
necklace = Necklace(width = FRAME_X_RADIUS)
necklace.shift(2*UP)
necklace.to_edge(RIGHT)
arrow = OldTex("\\Leftrightarrow")
arrow.scale(2)
arrow.next_to(necklace, LEFT)
q_marks = OldTex("???")
q_marks.next_to(arrow, UP)
arrow.add(q_marks)
formula = OldTex("f(\\textbf{x}) = f(-\\textbf{x})")
formula.next_to(self.get_students(), UP, buff = LARGE_BUFF)
formula.to_edge(LEFT, buff = LARGE_BUFF)
self.play(
self.teacher.change_mode, "raise_right_hand",
self.teacher.look_at, arrow
)
self.play(
FadeIn(necklace, run_time = 2, lag_ratio = 0.5),
Write(arrow),
*[
ApplyMethod(pi.look_at, arrow)
for pi in self.get_pi_creatures()
]
)
self.play_student_changes("pondering", "erm", "confused")
self.wait()
self.play(*[
ApplyMethod(pi.look_at, arrow)
for pi in self.get_pi_creatures()
])
self.play(Write(formula))
self.wait(3)
class SimpleSphere(ExternallyAnimatedScene):
pass
class PointsIn3D(Scene):
CONFIG = {
# "colors" : [RED, GREEN, BLUE],
"colors" : color_gradient([GREEN, BLUE], 3),
}
def construct(self):
sphere_def = OldTexText(
"\\doublespacing Sphere in 3D: All", "$(x_1, x_2, x_3)$\\\\",
"such that", "$x_1^2 + x_2^2 + x_3^2 = 1$",
alignment = "",
)
sphere_def.next_to(ORIGIN, DOWN)
for index, subindex_list in (1, [1, 2, 4, 5, 7, 8]), (3, [0, 2, 4, 6, 8, 10]):
colors = np.repeat(self.colors, 2)
for subindex, color in zip(subindex_list, colors):
sphere_def[index][subindex].set_color(color)
point_ex = OldTexText(
"For example, ",
"(", "0.41", ", ", "-0.58", ", ", "0.71", ")",
arg_separator = ""
)
for index, color in zip([2, 4, 6], self.colors):
point_ex[index].set_color(color)
point_ex.scale(0.8)
point_ex.next_to(
sphere_def[1], UP+RIGHT,
buff = 1.5*LARGE_BUFF
)
point_ex.shift_onto_screen()
arrow = Arrow(sphere_def[1].get_top(), point_ex.get_bottom())
self.play(Write(sphere_def[1]))
self.play(ShowCreation(arrow))
self.play(Write(point_ex))
self.wait()
self.play(
Animation(sphere_def[1].copy(), remover = True),
Write(sphere_def),
)
self.wait()
class AntipodalPairToBeGivenCoordinates(ExternallyAnimatedScene):
pass
class WritePointCoordinates(Scene):
CONFIG = {
"colors" : color_gradient([GREEN, BLUE], 3),
"corner" : DOWN+RIGHT,
}
def construct(self):
coords = self.get_coords()
arrow = Arrow(
-self.corner, self.corner,
stroke_width = 8,
color = MAROON_B
)
x_component = self.corner[0]*RIGHT
y_component = self.corner[1]*UP
arrow.next_to(
coords.get_edge_center(y_component),
y_component,
aligned_edge = -x_component,
buff = MED_SMALL_BUFF
)
group = VGroup(coords, arrow)
group.scale(2)
group.to_corner(self.corner)
self.play(FadeIn(coords))
self.play(ShowCreation(arrow))
self.wait()
def get_coords(self):
coords = OldTex(
"(", "0.41", ", ", "-0.58", ", ", "0.71", ")",
arg_separator = ""
)
for index, color in zip([1, 3, 5], self.colors):
coords[index].set_color(color)
return coords
class WriteAntipodalCoordinates(WritePointCoordinates):
CONFIG = {
"corner" : UP+LEFT,
"sign_color" : RED,
}
def get_coords(self):
coords = OldTex(
"(", "-", "0.41", ", ", "+", "0.58", ", ", "-", "0.71", ")",
arg_separator = ""
)
for index, color in zip([2, 5, 8], self.colors):
coords[index].set_color(color)
coords[index-1].set_color(self.sign_color)
return coords
class GeneralizeBorsukUlam(Scene):
CONFIG = {
"n_dims" : 3,
"boundary_colors" : [GREEN_B, BLUE],
"output_boundary_color" : [MAROON_B, YELLOW],
"negative_color" : RED,
}
def setup(self):
self.colors = color_gradient(self.boundary_colors, self.n_dims)
def construct(self):
sphere_set = self.get_sphere_set()
arrow = Arrow(LEFT, RIGHT)
f = OldTex("f")
output_space = self.get_output_space()
equation = self.get_equation()
sphere_set.to_corner(UP+LEFT)
arrow.next_to(sphere_set, RIGHT)
f.next_to(arrow, UP)
output_space.next_to(arrow, RIGHT)
equation.next_to(sphere_set, DOWN, buff = LARGE_BUFF)
equation.to_edge(RIGHT)
lhs = VGroup(*equation[:2])
eq = equation[2]
rhs = VGroup(*equation[3:])
self.play(FadeIn(sphere_set))
self.wait()
self.play(
ShowCreation(arrow),
Write(f)
)
self.play(Write(output_space))
self.wait()
self.play(FadeIn(lhs))
self.play(
ReplacementTransform(lhs.copy(), rhs),
Write(eq)
)
self.wait()
def get_condition(self):
squares = list(map(Tex, [
"x_%d^2"%d
for d in range(1, 1+self.n_dims)
]))
for square, color in zip(squares, self.colors):
square[0].set_color(color)
square[-1].set_color(color)
plusses = [Tex("+") for x in range(self.n_dims-1)]
plusses += [Tex("=1")]
condition = VGroup(*it.chain(*list(zip(squares, plusses))))
condition.arrange(RIGHT)
return condition
def get_tuple(self):
mid_parts = list(it.chain(*[
["x_%d"%d, ","]
for d in range(1, self.n_dims)
]))
tup = OldTex(*["("] + mid_parts + ["x_%d"%self.n_dims, ")"])
for index, color in zip(it.count(1, 2), self.colors):
tup[index].set_color(color)
return tup
def get_negative_tuple(self):
mid_parts = list(it.chain(*[
["-", "x_%d"%d, ","]
for d in range(1, self.n_dims)
]))
tup = OldTex(*["("] + mid_parts + ["-", "x_%d"%self.n_dims, ")"])
for index, color in zip(it.count(1, 3), self.colors):
tup[index].set_color(self.negative_color)
tup[index+1].set_color(color)
return tup
def get_output_space(self):
return OldTexText("%dD space"%(self.n_dims-1))
# n_dims = self.n_dims-1
# colors = color_gradient(self.output_boundary_color, n_dims)
# mid_parts = list(it.chain(*[
# ["y_%d"%d, ","]
# for d in range(1, n_dims)
# ]))
# tup = OldTex(*["("] + mid_parts + ["y_%d"%n_dims, ")"])
# for index, color in zip(it.count(1, 2), colors):
# tup[index].set_color(color)
# return tup
def get_equation(self):
tup = self.get_tuple()
neg_tup = self.get_negative_tuple()
f1, f2 = [Tex("f") for x in range(2)]
equals = OldTex("=")
equation = VGroup(f1, tup, equals, f2, neg_tup)
equation.arrange(RIGHT, buff = SMALL_BUFF)
return equation
def get_sphere_set(self):
tup = self.get_tuple()
such_that = OldTexText("such that")
such_that.next_to(tup, RIGHT)
condition = self.get_condition()
condition.next_to(
tup, DOWN,
buff = MED_LARGE_BUFF,
aligned_edge = LEFT
)
group = VGroup(tup, such_that, condition)
l_brace = Brace(group, LEFT)
r_brace = Brace(group, RIGHT)
group.add(l_brace, r_brace)
return group
# class FiveDBorsukUlam(GeneralizeBorsukUlam):
# CONFIG = {
# "n_dims" : 5,
# }
class MentionMakingNecklaceProblemContinuous(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
Translate this into
a continuous problem.
""")
self.play_student_changes("confused", "pondering", "erm")
self.wait(3)
class MakeTwoJewelCaseContinuous(IntroduceStolenNecklaceProblem):
CONFIG = {
"jewel_colors" : [BLUE, GREEN],
"num_per_jewel" : [8, 10],
"random_seed" : 2,
"forced_binary_choices" : (0, 1, 0),
"show_matching_after_divvying" : True,
"necklace_center" : ORIGIN,
"necklace_width" : FRAME_WIDTH - 3,
"random_seed" : 0,
"num_continuous_division_searches" : 4,
}
def construct(self):
random.seed(self.random_seed)
self.introduce_necklace()
self.divvy_with_n_cuts()
self.identify_necklace_with_unit_interval()
self.color_necklace()
self.find_continuous_fair_division()
self.show_continuous_fair_division()
self.set_color_continuous_groups()
self.mention_equivalence_to_discrete_case()
self.shift_divide_off_tick_marks()
def introduce_necklace(self):
self.get_necklace(
width = self.necklace_width,
)
self.play(FadeIn(
self.necklace,
lag_ratio = 0.5
))
self.shuffle_jewels(self.necklace.jewels)
jewel_types = self.get_jewels_organized_by_type(
self.necklace.jewels
)
self.wait()
self.count_jewel_types(jewel_types)
self.wait()
self.jewel_types = jewel_types
def count_jewel_types(self, jewel_types):
enumeration_labels = VGroup()
for jewel_type in jewel_types:
num_mob = OldTex(str(len(jewel_type)))
jewel_copy = jewel_type[0].copy()
# jewel_copy.set_height(num_mob.get_height())
jewel_copy.next_to(num_mob)
label = VGroup(num_mob, jewel_copy)
enumeration_labels.add(label)
enumeration_labels.arrange(RIGHT, buff = LARGE_BUFF)
enumeration_labels.to_edge(UP)
for jewel_type, label in zip(jewel_types, enumeration_labels):
jewel_type.sort()
jewel_type.save_state()
jewel_type.generate_target()
jewel_type.target.arrange()
jewel_type.target.move_to(2*UP)
self.play(
MoveToTarget(jewel_type),
Write(label)
)
self.play(jewel_type.restore)
def divvy_with_n_cuts(self):
IntroduceStolenNecklaceProblem.divvy_with_n_cuts(
self,
with_thieves = False,
highlight_groups = False,
show_matching_after_divvying = True,
)
def identify_necklace_with_unit_interval(self):
interval = UnitInterval(
tick_frequency = 1./sum(self.num_per_jewel),
tick_size = 0.2,
numbers_with_elongated_ticks = [],
)
interval.stretch_to_fit_width(self.necklace.get_width())
interval.move_to(self.necklace)
tick_marks = interval.tick_marks
tick_marks.set_stroke(WHITE, width = 2)
brace = Brace(interval)
brace_text = brace.get_text("Length = 1")
self.play(
GrowFromCenter(brace),
Write(brace_text)
)
self.wait()
self.play(
ShowCreation(interval.tick_marks),
)
self.wait()
self.tick_marks = interval.tick_marks
self.length_brace = VGroup(brace, brace_text)
def color_necklace(self):
example_index = len(self.necklace.jewels)/2
jewels = self.necklace.jewels
chain = self.necklace.chain
self.remove(self.necklace)
self.add(chain, jewels)
jewels.submobjects.sort(
key=lambda m: m.get_center()[0]
)
remaining_indices = list(range(len(jewels)))
remaining_indices.remove(example_index)
example_segment = self.color_necklace_by_indices(example_index)
remaining_segments = self.color_necklace_by_indices(*remaining_indices)
self.remove(chain)
segments = VGroup(example_segment[0], *remaining_segments)
segments.submobjects.sort(
key=lambda m: m.get_center()[0]
)
segment_types = VGroup(*[
VGroup(*[m for m in segments if m.get_color() == Color(color)])
for color in self.jewel_colors
])
for group in segment_types:
length_tex = OldTex("\\frac{%d}{%d}"%(
len(group),
len(jewels)
))
length_tex.next_to(group, UP)
length_tex.shift(UP)
self.play(
group.shift, UP,
Write(length_tex, run_time = 1),
)
self.wait()
self.play(
group.shift, DOWN,
FadeOut(length_tex)
)
self.play(FadeOut(self.length_brace))
self.segments = segments
def color_necklace_by_indices(self, *indices):
chain = self.necklace.chain
jewels = VGroup(*[
self.necklace.jewels[i]
for i in indices
])
n_jewels = len(self.necklace.jewels)
segments = VGroup(*[
Line(
chain.point_from_proportion(index/float(n_jewels)),
chain.point_from_proportion((index+1)/float(n_jewels)),
color = jewel.get_color()
)
for index, jewel in zip(indices, jewels)
])
for jewel in jewels:
jewel.save_state()
self.play(jewels.shift, jewels.get_height()*UP)
self.play(ReplacementTransform(
jewels, segments,
lag_ratio = 0.5,
run_time = 2
))
self.wait()
return segments
def find_continuous_fair_division(self):
chain = self.necklace.chain
n_jewels = len(self.necklace.jewels)
slice_indices, ignore = self.find_slice_indices(
self.necklace.jewels,
self.jewel_types
)
cut_proportions = [
sorted([random.random(), random.random()])
for x in range(self.num_continuous_division_searches)
]
cut_proportions.append([
float(i)/n_jewels
for i in slice_indices[1:-1]
])
cut_points = [
list(map(chain.point_from_proportion, pair))
for pair in cut_proportions
]
v_lines = VGroup(*[DashedLine(UP, DOWN) for x in range(2)])
for line, point in zip(v_lines, cut_points[0]):
line.move_to(point)
self.play(ShowCreation(v_lines))
self.wait()
for target_points in cut_points[1:]:
self.play(*[
ApplyMethod(line.move_to, point)
for line, point in zip(v_lines, target_points)
])
self.wait()
self.slice_indices = slice_indices
self.v_lines = v_lines
def show_continuous_fair_division(self):
slice_indices = self.slice_indices
groups = [
VGroup(
VGroup(*self.segments[i1:i2]),
VGroup(*self.tick_marks[i1:i2]),
)
for i1, i2 in zip(slice_indices, slice_indices[1:])
]
groups[-1].add(self.tick_marks[-1])
vects = [[UP, DOWN][i] for i in self.forced_binary_choices]
self.play(*[
ApplyMethod(group.shift, 0.5*vect)
for group, vect in zip(groups, vects)
])
self.wait()
self.groups = groups
def set_color_continuous_groups(self):
top_group = VGroup(self.groups[0], self.groups[2])
bottom_group = self.groups[1]
boxes = VGroup()
for group in top_group, bottom_group:
box = Rectangle(
width = FRAME_WIDTH-2,
height = group.get_height()+SMALL_BUFF,
stroke_width = 0,
fill_color = WHITE,
fill_opacity = 0.25,
)
box.shift(group.get_center()[1]*UP)
boxes.add(box)
weight_description = VGroup(*[
VGroup(
OldTex("\\frac{%d}{%d}"%(
len(jewel_type)/2, len(self.segments)
)),
Jewel(color = jewel_type[0].get_color())
).arrange()
for jewel_type in self.jewel_types
])
weight_description.arrange(buff = LARGE_BUFF)
weight_description.next_to(boxes, UP, aligned_edge = LEFT)
self.play(FadeIn(boxes))
self.play(Write(weight_description))
self.wait()
self.set_color_box = boxes
self.weight_description = weight_description
def mention_equivalence_to_discrete_case(self):
morty = Mortimer()
morty.flip()
morty.to_edge(DOWN)
morty.shift(LEFT)
self.play(FadeIn(morty))
self.play(PiCreatureSays(
morty,
"""This is equivalent to
the discrete case. """,
bubble_config = {
"height" : 3,
"direction" : LEFT,
}
))
self.play(Blink(morty))
self.wait()
self.play(*list(map(FadeOut, [
morty, morty.bubble, morty.bubble.content
])))
def shift_divide_off_tick_marks(self):
groups = self.groups
slice_indices = self.slice_indices
v_lines = self.v_lines
left_segment = groups[1][0][0]
left_tick = groups[1][1][0]
right_segment = groups[-1][0][0]
right_tick = groups[-1][1][0]
segment_width = left_segment.get_width()
for mob in left_segment, right_segment:
mob.parts = VGroup(
mob.copy().pointwise_become_partial(mob, 0, 0.5),
mob.copy().pointwise_become_partial(mob, 0.5, 1),
)
self.remove(mob)
self.add(mob.parts)
restorers = [left_segment.parts, left_tick, right_segment.parts, right_tick]
for mob in restorers:
mob.save_state()
emerald_segments = VGroup(*[
segment
for segment in list(groups[0][0])+list(groups[2][0])
if segment.get_color() == Color(self.jewel_colors[1])
if segment is not right_segment
])
emerald_segments.add(
left_segment.parts[0],
right_segment.parts[1],
)
emerald_segments.sort()
self.play(v_lines.shift, segment_width*RIGHT/2)
self.play(*[
ApplyMethod(mob.shift, vect)
for mob, vect in [
(left_segment.parts[0], UP),
(left_tick, UP),
(right_segment.parts[0], DOWN),
(right_tick, DOWN),
]
])
self.wait()
words = OldTexText("Cut part way through segment")
words.to_edge(RIGHT)
words.shift(2*UP)
arrow1 = Arrow(words.get_bottom(), left_segment.parts[0].get_right())
arrow2 = Arrow(words.get_bottom(), right_segment.parts[1].get_left())
VGroup(words, arrow1, arrow2).set_color(RED)
self.play(Write(words), ShowCreation(arrow1))
self.wait()
emerald_segments.save_state()
emerald_segments.generate_target()
emerald_segments.target.arrange()
emerald_segments.target.move_to(2*DOWN)
brace = Brace(emerald_segments.target, DOWN)
label = VGroup(
OldTex("5\\left( 1/18 \\right)"),
Jewel(color = self.jewel_colors[1])
).arrange()
label.next_to(brace, DOWN)
self.play(MoveToTarget(emerald_segments))
self.play(GrowFromCenter(brace))
self.play(Write(label))
self.wait()
broken_pair = VGroup(*emerald_segments[2:4])
broken_pair.save_state()
self.play(broken_pair.shift, 0.5*UP)
vect = broken_pair[1].get_left()-broken_pair[1].get_right()
self.play(
broken_pair[0].shift, -vect/2,
broken_pair[1].shift, vect/2,
)
self.wait()
self.play(broken_pair.space_out_submobjects)
self.play(broken_pair.restore)
self.wait()
self.play(
emerald_segments.restore,
*list(map(FadeOut, [brace, label]))
)
self.wait()
self.play(ShowCreation(arrow2))
self.wait()
self.play(*list(map(FadeOut, [words, arrow1, arrow2])))
for line in v_lines:
self.play(line.shift, segment_width*LEFT/2)
self.play(*[mob.restore for mob in restorers])
self.remove(left_segment.parts, right_segment.parts)
self.add(left_segment, right_segment)
class ThinkAboutTheChoices(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
Think about the choices
behind a division...
""")
self.play_student_changes(
*["pondering"]*3,
look_at = FRAME_X_RADIUS*RIGHT+FRAME_Y_RADIUS*DOWN
)
self.wait(3)
class ChoicesInNecklaceCutting(ReconfigurableScene):
CONFIG = {
"num_continuous_division_searches" : 4,
"denoms" : [6, 3, 2],
"necklace_center" : DOWN,
"thief_box_offset" : 1.2,
}
def construct(self):
self.add_necklace()
self.choose_places_to_cut()
self.show_three_numbers_adding_to_one()
self.make_binary_choice()
def add_necklace(self):
width, colors, num_per_color = [
MakeTwoJewelCaseContinuous.CONFIG[key]
for key in [
"necklace_width", "jewel_colors", "num_per_jewel"
]
]
color_list = list(it.chain(*[
num*[color]
for num, color in zip(num_per_color, colors)
]))
random.shuffle(color_list)
interval = UnitInterval(
tick_frequency = 1./sum(num_per_color),
tick_size = 0.2,
numbers_with_elongated_ticks = [],
)
interval.stretch_to_fit_width(width)
interval.shift(self.necklace_center)
tick_marks = interval.tick_marks
tick_marks.set_stroke(WHITE, width = 2)
segments = VGroup()
for l_tick, r_tick, color in zip(tick_marks, tick_marks[1:], color_list):
segment = Line(
l_tick.get_center(),
r_tick.get_center(),
color = color
)
segments.add(segment)
self.necklace = VGroup(segments, tick_marks)
self.add(self.necklace)
self.interval = interval
def choose_places_to_cut(self):
v_lines = VGroup(*[DashedLine(UP, DOWN) for x in range(2)])
final_num_pair = np.cumsum([1./d for d in self.denoms[:2]])
num_pairs = [
sorted([random.random(), random.random()])
for x in range(self.num_continuous_division_searches)
] + [final_num_pair]
point_pairs = [
list(map(self.interval.number_to_point, num_pair))
for num_pair in num_pairs
]
for line, point in zip(v_lines, point_pairs[0]):
line.move_to(point)
self.play(ShowCreation(v_lines))
for point_pair in point_pairs[1:]:
self.wait()
self.play(*[
ApplyMethod(line.move_to, point)
for line, point in zip(v_lines, point_pair)
])
self.wait()
self.division_points = list(it.chain(
[self.interval.get_left()],
point_pairs[-1],
[self.interval.get_right()]
))
self.v_lines = v_lines
def show_three_numbers_adding_to_one(self):
points = self.division_points
braces = [
Brace(Line(p1+SMALL_BUFF*RIGHT/2, p2+SMALL_BUFF*LEFT/2))
for p1, p2 in zip(points, points[1:])
]
for char, denom, brace in zip("abc", self.denoms, braces):
brace.label = brace.get_text("$%s$"%char)
brace.concrete_label = brace.get_text("$\\frac{1}{%d}$"%denom)
VGroup(
brace.label,
brace.concrete_label
).set_color(YELLOW)
words = OldTexText(
"1) Choose", "$a$, $b$, $c$", "so that", "$a+b+c = 1$"
)
words[1].set_color(YELLOW)
words[3].set_color(YELLOW)
words.to_corner(UP+LEFT)
self.play(*it.chain(*[
[GrowFromCenter(brace), Write(brace.label)]
for brace in braces
]))
self.play(Write(words))
self.wait(2)
self.play(*[
ReplacementTransform(brace.label, brace.concrete_label)
for brace in braces
])
self.wait()
self.wiggle_v_lines()
self.wait()
self.transition_to_alt_config(denoms = [3, 3, 3])
self.wait()
self.play(*list(map(FadeOut, list(braces) + [
brace.concrete_label for brace in braces
])))
self.choice_one_words = words
def make_binary_choice(self):
groups = self.get_groups()
boxes, labels = self.get_boxes_and_labels()
arrow_pairs, curr_arrows = self.get_choice_arrow_pairs(groups)
words = OldTexText("2) Make a binary choice for each segment")
words.next_to(
self.choice_one_words, DOWN,
buff = MED_LARGE_BUFF,
aligned_edge = LEFT
)
self.play(Write(words))
self.play(*list(map(FadeIn, [boxes, labels])))
for binary_choices in it.product(*[[0, 1]]*3):
self.play(*[
ApplyMethod(group.move_to, group.target_points[choice])
for group, choice in zip(groups, binary_choices)
] + [
Transform(
curr_arrow, arrow_pair[choice],
path_arc = np.pi
)
for curr_arrow, arrow_pair, choice in zip(
curr_arrows, arrow_pairs, binary_choices
)
])
self.wait()
######
def get_groups(self, indices = None):
segments, tick_marks = self.necklace
if indices is None:
n_segments = len(segments)
indices = [0, n_segments/6, n_segments/2, n_segments]
groups = [
VGroup(
VGroup(*segments[i1:i2]),
VGroup(*tick_marks[i1:i2]),
)
for i1, i2 in zip(indices, indices[1:])
]
for group, index in zip(groups, indices[1:]):
group[1].add(tick_marks[index].copy())
groups[-1][1].add(tick_marks[-1])
for group in groups:
group.target_points = [
group.get_center() + self.thief_box_offset*vect
for vect in (UP, DOWN)
]
return groups
def get_boxes_and_labels(self):
box = Rectangle(
height = self.necklace.get_height()+SMALL_BUFF,
width = self.necklace.get_width()+2*SMALL_BUFF,
stroke_width = 0,
fill_color = WHITE,
fill_opacity = 0.25
)
box.move_to(self.necklace)
boxes = VGroup(*[
box.copy().shift(self.thief_box_offset*vect)
for vect in (UP, DOWN)
])
labels = VGroup(*[
OldTexText(
"Thief %d"%(i+1)
).next_to(box, UP, aligned_edge = RIGHT)
for i, box in enumerate(boxes)
])
return boxes, labels
def get_choice_arrow_pairs(self, groups):
arrow = OldTex("\\uparrow")
arrow_pairs = [
[arrow.copy(), arrow.copy().rotate(np.pi)]
for group in groups
]
pre_arrow_points = [
VectorizedPoint(group.get_center())
for group in groups
]
for point, arrow_pair in zip(pre_arrow_points, arrow_pairs):
for arrow, color in zip(arrow_pair, [GREEN, RED]):
arrow.set_color(color)
arrow.move_to(point.get_center())
return arrow_pairs, pre_arrow_points
def wiggle_v_lines(self):
self.play(
*it.chain(*[
[
line.rotate, np.pi/12, vect,
line.set_color, RED
]
for line, vect in zip(self.v_lines, [OUT, IN])
]),
rate_func = wiggle
)
class CompareThisToSphereChoice(TeacherStudentsScene):
def construct(self):
self.teacher_says("""
Compare this to choosing
a point on the sphere.
""")
self.play_student_changes(
*["pondering"]*3,
look_at = FRAME_X_RADIUS*RIGHT+FRAME_Y_RADIUS*DOWN
)
self.wait(3)
class SimpleRotatingSphereWithPoint(ExternallyAnimatedScene):
pass
class ChoicesForSpherePoint(GeneralizeBorsukUlam):
def construct(self):
self.add_sphere_set()
self.initialize_words()
self.play(Write(self.choice_one_words))
self.wait()
self.show_example_choices()
self.show_binary_choices()
def get_tuple(self):
tup = OldTex("(x, y, z)")
for i, color in zip([1, 3, 5], self.colors):
tup[i].set_color(color)
return tup
def get_condition(self):
condition = OldTex("x^2+y^2+z^2 = 1")
for i, color in zip([0, 3, 6], self.colors):
VGroup(*condition[i:i+2]).set_color(color)
return condition
def add_sphere_set(self):
sphere_set = self.get_sphere_set()
sphere_set.scale(0.7)
sphere_set.to_edge(RIGHT)
sphere_set.shift(UP)
self.add(sphere_set)
self.sphere_set = sphere_set
def initialize_words(self):
choice_one_words = OldTexText(
"1) Choose", "$x^2$, $y^2$, $z^2$",
"so that", "$x^2+y^2+z^2 = 1$"
)
for i in 1, 3:
for j, color in zip([0, 3, 6], self.colors):
VGroup(*choice_one_words[i][j:j+2]).set_color(color)
choice_one_words.to_corner(UP+LEFT)
choice_two_words = OldTexText(
"2) Make a binary choice for each one"
)
choice_two_words.next_to(
choice_one_words, DOWN,
buff = MED_LARGE_BUFF,
aligned_edge = LEFT
)
self.choice_one_words = choice_one_words
self.choice_two_words = choice_two_words
def show_example_choices(self):
choices = VGroup(*[
OldTex(*tex).set_color(color)
for color, tex in zip(self.colors, [
("x", "^2 = ", "1/6"),
("y", "^2 = ", "1/3"),
("z", "^2 = ", "1/2"),
])
])
choices.arrange(
DOWN,
buff = LARGE_BUFF,
aligned_edge = LEFT
)
choices.set_height(FRAME_Y_RADIUS)
choices.to_edge(LEFT)
choices.shift(DOWN)
self.play(FadeIn(
choices,
run_time = 2,
lag_ratio = 0.5
))
self.wait()
self.choices = choices
def show_binary_choices(self):
for choice in self.choices:
var_tex = choice.expression_parts[0]
frac_tex = choice.expression_parts[2]
sqrts = VGroup(*[
OldTex(
var_tex + "=" + sign + \
"\\sqrt{%s}"%frac_tex)
for sign in ["+", "-"]
])
for sqrt in sqrts:
sqrt.scale(0.6)
sqrts.arrange(DOWN)
sqrts.next_to(choice, RIGHT, buff = LARGE_BUFF)
sqrts.set_color(choice.get_color())
arrows = VGroup(*[
Arrow(
choice.get_right(), sqrt.get_left(),
color = WHITE,
tip_length = 0.1,
buff = SMALL_BUFF
)
for sqrt in sqrts
])
self.play(ShowCreation(arrows))
self.play(FadeIn(sqrts, lag_ratio = 0.5))
self.play(Write(self.choice_two_words))
self.wait()
class NecklaceDivisionSphereAssociation(ChoicesInNecklaceCutting):
CONFIG = {
"xyz_colors" : color_gradient([GREEN_B, BLUE], 3),
"necklace_center" : DOWN,
"thief_box_offset" : 1.6,
"denoms" : [6, 3, 2],
}
def construct(self):
self.add_necklace()
self.add_sphere_point_label()
self.choose_places_to_cut()
self.add_braces()
self.add_boxes_and_labels()
self.show_binary_choice_association()
self.ask_about_antipodal_pairs()
def add_sphere_point_label(self):
label = OldTexText(
"$(x, y, z)$",
"such that",
"$x^2 + y^2 + z^2 = 1$"
)
for i, j_list in (0, [1, 3, 5]), (2, [0, 3, 6]):
for j, color in zip(j_list, self.xyz_colors):
label[i][j].set_color(color)
label.to_corner(UP+RIGHT)
ghost_sphere_point = VectorizedPoint()
ghost_sphere_point.to_corner(UP+LEFT, buff = LARGE_BUFF)
ghost_sphere_point.shift(2*RIGHT)
arrow = Arrow(
label.get_left(), ghost_sphere_point,
color = WHITE
)
self.add(label, arrow)
self.sphere_point_label = label
def add_braces(self):
points = self.division_points
braces = [
Brace(
Line(p1+SMALL_BUFF*RIGHT/2, p2+SMALL_BUFF*LEFT/2),
UP
)
for p1, p2 in zip(points, points[1:])
]
for char, brace, color, denom in zip("xyz", braces, self.xyz_colors, self.denoms):
brace.label = brace.get_text(
"$%s^2$"%char, "$= 1/%d$"%denom,
buff = SMALL_BUFF
)
brace.label.set_color(color)
if brace.label.get_right()[0] > brace.get_right()[0]:
brace.label.next_to(
brace, UP, buff = SMALL_BUFF,
aligned_edge = RIGHT
)
self.play(*it.chain(
list(map(GrowFromCenter, braces)),
[Write(brace.label) for brace in braces]
))
self.wait()
self.braces = braces
def add_boxes_and_labels(self):
boxes, labels = self.get_boxes_and_labels()
self.play(*list(map(FadeIn, [boxes, labels])))
self.wait()
def show_binary_choice_association(self):
groups = self.get_groups()
self.swapping_anims = []
final_choices = [1, 0, 1]
quads = list(zip(self.braces, self.denoms, groups, final_choices))
for brace, denom, group, final_choice in quads:
char = brace.label.args[0][1]
choices = [
OldTex(
char, "=", sign, "\\sqrt{\\frac{1}{%d}}"%denom
)
for sign in ("+", "-")
]
for choice, color in zip(choices, [GREEN, RED]):
# choice[0].set_color(brace.label.get_color())
choice[2].set_color(color)
choice.scale(0.8)
choice.move_to(group)
if choice.get_width() > 0.8*group.get_width():
choice.next_to(group.get_right(), LEFT, buff = MED_SMALL_BUFF)
original_choices = [m.copy() for m in choices]
self.play(
ReplacementTransform(
VGroup(brace.label[0], brace, brace.label[1]),
choices[0]
),
group.move_to, group.target_points[0]
)
self.wait()
self.play(
Transform(*choices),
group.move_to, group.target_points[1]
)
self.wait()
if final_choice == 0:
self.play(
Transform(choices[0], original_choices[0]),
group.move_to, group.target_points[0]
)
self.swapping_anims += [
Transform(choices[0], original_choices[1-final_choice]),
group.move_to, group.target_points[1-final_choice]
]
def ask_about_antipodal_pairs(self):
question = OldTexText("What do antipodal points signify?")
question.move_to(self.sphere_point_label, LEFT)
question.set_color(MAROON_B)
antipodal_tex = OldTex(
"(x, y, z) \\rightarrow (-x, -y, -z)"
)
antipodal_tex.next_to(question, DOWN, aligned_edge = LEFT)
self.play(FadeOut(self.sphere_point_label))
self.play(FadeIn(question))
self.wait()
self.play(Write(antipodal_tex))
self.wait()
self.wiggle_v_lines()
self.wait()
self.play(*self.swapping_anims)
self.wait()
class SimpleRotatingSphereWithAntipodes(ExternallyAnimatedScene):
pass
class TotalLengthOfEachJewelEquals(NecklaceDivisionSphereAssociation, ThreeDScene):
CONFIG = {
"random_seed" : 1,
"thief_box_offset" : 1.2,
}
def construct(self):
random.seed(self.random_seed)
self.add_necklace()
self.add_boxes_and_labels()
self.find_fair_division()
self.demonstrate_fair_division()
self.perform_antipodal_swap()
def find_fair_division(self):
segments, tick_marks = self.necklace
segments.sort()
segment_colors = [
segment.get_color()
for segment in segments
]
indices = self.get_fair_division_indices(segment_colors)
groups = self.get_groups(
[0] + list(np.array(indices)+1) + [len(segments)]
)
self.add(*groups)
binary_choice = [0, 1, 0]
v_lines = VGroup(*[DashedLine(UP, DOWN) for x in range(2)])
v_lines.move_to(self.necklace)
self.play(ShowCreation(v_lines))
self.play(*[
ApplyMethod(line.move_to, segments[index].get_right())
for line, index in zip(v_lines, indices)
])
self.wait()
self.play(*[
ApplyMethod(group.move_to, group.target_points[choice])
for group, choice in zip(groups, binary_choice)
])
self.wait()
self.groups = groups
self.v_lines = v_lines
def get_fair_division_indices(self, colors):
colors = np.array(list(colors))
color_types = list(map(Color, set([c.get_hex_l() for c in colors])))
type_to_count = dict([
(color, sum(colors == color))
for color in color_types
])
for i1, i2 in it.combinations(list(range(1, len(colors)-1)), 2):
bools = [
sum(colors[i1:i2] == color) == type_to_count[color]/2
for color in color_types
]
if np.all(bools):
return i1, i2
raise Exception("No fair division found")
def demonstrate_fair_division(self):
segments, tick_marks = self.necklace
color_types = list(map(Color, set([
segment.get_color().get_hex_l()
for segment in segments
])))
top_segments = VGroup(*it.chain(
self.groups[0][0],
self.groups[2][0],
))
bottom_segments = self.groups[1][0]
for color in color_types:
monochrome_groups = [
VGroup(*[segment for segment in segment_group if segment.get_color() == color])
for segment_group in (top_segments, bottom_segments)
]
labels = VGroup()
for i, group in enumerate(monochrome_groups):
group.save_state()
group.generate_target()
group.target.arrange(buff = SMALL_BUFF)
brace = Brace(group.target, UP)
label = VGroup(
OldTexText("Thief %d"%(i+1)),
Jewel(color = group[0].get_color())
)
label.arrange()
label.next_to(brace, UP)
full_group = VGroup(group.target, brace, label)
vect = LEFT if i == 0 else RIGHT
full_group.next_to(ORIGIN, vect, buff = MED_LARGE_BUFF)
full_group.to_edge(UP)
labels.add(VGroup(brace, label))
equals = OldTex("=")
equals.next_to(monochrome_groups[0].target, RIGHT)
labels[-1].add(equals)
for group, label in zip(monochrome_groups, labels):
self.play(
MoveToTarget(group),
FadeIn(label),
)
self.wait()
self.play(
FadeOut(labels),
*[group.restore for group in monochrome_groups]
)
self.wait()
def perform_antipodal_swap(self):
binary_choices_list = [(1, 0, 1), (0, 1, 0)]
for binary_choices in binary_choices_list:
self.play(*[
ApplyMethod(
group.move_to,
group.target_points[choice]
)
for group, choice in zip(self.groups, binary_choices)
])
self.wait()
class ExclaimBorsukUlam(TeacherStudentsScene):
def construct(self):
self.student_says(
"Borsuk-Ulam!",
target_mode = "hooray"
)
self.play(*[
ApplyMethod(pi.change_mode, "hooray")
for pi in self.get_pi_creatures()
])
self.wait(3)
class ShowFunctionDiagram(TotalLengthOfEachJewelEquals, ReconfigurableScene):
CONFIG = {
"necklace_center" : ORIGIN,
"camera_class" : ThreeDCamera,
"thief_box_offset" : 0.3,
"make_up_fair_division_indices" : False,
}
def construct(self):
self.add_necklace()
self.add_number_pair()
self.swap_necklace_allocation()
self.add_sphere_arrow()
def add_necklace(self):
random.seed(self.random_seed)
ChoicesInNecklaceCutting.add_necklace(self)
self.necklace.set_width(FRAME_X_RADIUS-1)
self.necklace.to_edge(UP, buff = LARGE_BUFF)
self.necklace.to_edge(LEFT, buff = SMALL_BUFF)
self.add(self.necklace)
self.find_fair_division()
def add_number_pair(self):
plane_classes = [
JewelPairPlane(
skip_animations = True,
thief_number = x
)
for x in (1, 2)
]
t1_plane, t2_plane = planes = VGroup(*[
VGroup(*plane_class.get_top_level_mobjects())
for plane_class in plane_classes
])
planes.set_width(FRAME_X_RADIUS)
planes.to_edge(RIGHT)
self.example_coords = plane_classes[0].example_coords[0]
arrow = Arrow(
self.necklace.get_corner(DOWN+RIGHT),
self.example_coords,
color = YELLOW
)
self.play(ShowCreation(arrow))
self.play(Write(t1_plane), Animation(arrow))
self.wait()
clean_state = VGroup(*self.mobjects).family_members_with_points()
self.clear()
self.add(*clean_state)
self.transition_to_alt_config(
make_up_fair_division_indices = True
)
self.wait()
t1_plane.save_state()
self.play(
Transform(*planes, path_arc = np.pi),
Animation(arrow)
)
self.wait(2)
self.play(
ApplyMethod(t1_plane.restore, path_arc = np.pi),
Animation(arrow)
)
self.wait()
def swap_necklace_allocation(self):
for choices in [(1, 0, 1), (0, 1, 0)]:
self.play(*[
ApplyMethod(group.move_to, group.target_points[i])
for group, i in zip(self.groups, choices)
])
self.wait()
def add_sphere_arrow(self):
up_down_arrow = OldTex("\\updownarrow")
up_down_arrow.scale(1.5)
up_down_arrow.set_color(YELLOW)
up_down_arrow.next_to(self.necklace, DOWN, buff = LARGE_BUFF)
to_plane_arrow = Arrow(
up_down_arrow.get_bottom() + DOWN+RIGHT,
self.example_coords,
color = YELLOW
)
self.play(Write(up_down_arrow))
self.wait()
self.play(ShowCreation(to_plane_arrow))
self.wait()
def get_fair_division_indices(self, *args):
if self.make_up_fair_division_indices:
return [9, 14]
else:
return TotalLengthOfEachJewelEquals.get_fair_division_indices(self, *args)
class JewelPairPlane(GraphScene):
CONFIG = {
"camera_class" : ThreeDCamera,
"x_labeled_nums" : [],
"y_labeled_nums" : [],
"thief_number" : 1,
"colors" : [BLUE, GREEN],
}
def construct(self):
self.setup_axes()
point = self.coords_to_point(4, 5)
dot = Dot(point, color = WHITE)
coord_pair = OldTex(
"\\big(",
"\\text{Thief %d }"%self.thief_number, "X", ",",
"\\text{Thief %d }"%self.thief_number, "X",
"\\big)"
)
# coord_pair.scale(1.5)
to_replace = [coord_pair[i] for i in [2, 5]]
for mob, color in zip(to_replace, self.colors):
jewel = Jewel(color = color)
jewel.replace(mob)
coord_pair.remove(mob)
coord_pair.add(jewel)
coord_pair.next_to(dot, UP+RIGHT, buff = 0)
self.example_coords = VGroup(dot, coord_pair)
self.add(self.example_coords)
class WhatThisMappingActuallyLooksLikeWords(Scene):
def construct(self):
words = OldTexText("What this mapping actually looks like")
words.set_width(FRAME_WIDTH-1)
words.to_edge(DOWN)
self.play(Write(words))
self.wait()
class WhatAboutGeneralCase(TeacherStudentsScene):
def construct(self):
self.student_says("""
What about when
there's more than 2 jewels?
""")
self.play_student_changes("confused", None, "sassy")
self.wait()
self.play(self.get_teacher().change_mode, "thinking")
self.wait()
self.teacher_says(
"""Use Borsuk-Ulam for
higher-dimensional spheres """,
target_mode = "hooray"
)
self.play_student_changes(*["confused"]*3)
self.wait(2)
class Simple3DSpace(ExternallyAnimatedScene):
pass
class FourDBorsukUlam(GeneralizeBorsukUlam, PiCreatureScene):
CONFIG = {
"n_dims" : 4,
"use_morty" : False,
}
def setup(self):
GeneralizeBorsukUlam.setup(self)
PiCreatureScene.setup(self)
self.pi_creature.to_corner(DOWN+LEFT, buff = MED_SMALL_BUFF)
def construct(self):
sphere_set = self.get_sphere_set()
arrow = Arrow(LEFT, RIGHT)
f = OldTex("f")
output_space = self.get_output_space()
equation = self.get_equation()
sphere_set.to_corner(UP+LEFT)
arrow.next_to(sphere_set, RIGHT)
f.next_to(arrow, UP)
output_space.next_to(arrow, RIGHT)
equation.next_to(sphere_set, DOWN, buff = LARGE_BUFF)
equation.to_edge(RIGHT)
lhs = VGroup(*equation[:2])
eq = equation[2]
rhs = VGroup(*equation[3:])
brace = Brace(Line(ORIGIN, 5*RIGHT))
brace.to_edge(RIGHT)
brace_text = brace.get_text("Triplets of numbers")
brace_text.shift_onto_screen()
self.play(FadeIn(sphere_set))
self.change_mode("confused")
self.wait()
self.play(
ShowCreation(arrow),
Write(f)
)
self.play(Write(output_space))
self.wait()
self.change_mode("maybe")
self.wait(2)
self.change_mode("pondering")
self.wait()
self.play(
GrowFromCenter(brace),
Write(brace_text)
)
self.wait()
self.play(*list(map(FadeOut, [brace, brace_text])))
self.wait()
self.play(
FadeIn(lhs),
self.pi_creature.change_mode, "raise_right_hand"
)
self.play(
ReplacementTransform(lhs.copy(), rhs),
Write(eq)
)
self.wait(2)
def get_sphere_set(self):
sphere_set = GeneralizeBorsukUlam.get_sphere_set(self)
brace = Brace(sphere_set)
text = brace.get_text("Hypersphere in 4D")
sphere_set.add(brace, text)
return sphere_set
class CircleToSphereToQMarks(Scene):
def construct(self):
pi_groups = VGroup()
modes = ["happy", "pondering", "pleading"]
shapes = [
Circle(color = BLUE, radius = 0.5),
VectorizedPoint(),
OldTex("???")
]
for d, mode, shape in zip(it.count(2), modes, shapes):
randy = Randolph(mode = mode)
randy.scale(0.7)
bubble = randy.get_bubble(
height = 3, width = 4,
direction = LEFT
)
bubble.pin_to(randy)
bubble.position_mobject_inside(shape)
title = OldTexText("%dD"%d)
title.next_to(randy, UP)
arrow = Arrow(LEFT, RIGHT)
arrow.next_to(randy.get_corner(UP+RIGHT))
pi_groups.add(VGroup(
randy, bubble, shape, title, arrow
))
pi_groups[-1].remove(pi_groups[-1][-1])
pi_groups.arrange(buff = -1)
for mob in pi_groups:
self.play(FadeIn(mob))
self.wait(2)
self.play(pi_groups[-1][0].change_mode, "thinking")
self.wait(2)
class BorsukPatreonThanks(PatreonThanks):
CONFIG = {
"specific_patrons" : [
"Ali Yahya",
"Meshal Alshammari",
"CrypticSwarm ",
"Ankit Agarwal",
"Yu Jun",
"Shelby Doolittle",
"Dave Nicponski",
"Damion Kistler",
"Juan Benet",
"Othman Alikhan",
"Justin Helps",
"Markus Persson",
"Dan Buchoff",
"Derek Dai",
"Joseph John Cox",
"Luc Ritchie",
"Guido Gambardella",
"Jerry Ling",
"Mark Govea",
"Vecht",
"Jonathan Eppele",
"Shimin Kuang",
"Rish Kundalia",
"Achille Brighton",
"Kirk Werklund",
"Ripta Pasay",
"Felipe Diniz",
]
}
class MortyLookingAtRectangle(Scene):
def construct(self):
morty = Mortimer()
morty.to_corner(DOWN+RIGHT)
url = OldTexText("www.thegreatcoursesplus.com/3blue1brown")
url.scale(0.75)
url.to_corner(UP+LEFT)
rect = Rectangle(height = 9, width = 16)
rect.set_height(5)
rect.next_to(url, DOWN)
rect.shift_onto_screen()
url.save_state()
url.next_to(morty.get_corner(UP+LEFT), UP)
url.shift_onto_screen()
self.add(morty)
self.play(
morty.change_mode, "raise_right_hand",
morty.look_at, url,
)
self.play(Write(url))
self.play(Blink(morty))
self.wait()
self.play(
url.restore,
morty.change_mode, "happy"
)
self.play(ShowCreation(rect))
self.wait()
self.play(Blink(morty))
for mode in ["pondering", "hooray", "happy", "pondering", "happy"]:
self.play(morty.change_mode, mode)
self.wait(2)
self.play(Blink(morty))
self.wait(2)
class RotatingThreeDSphereProjection(Scene):
CONFIG = {
"camera_class" : ThreeDCamera,
}
def construct(self):
sphere = VGroup(*[
Circle(radius = np.sin(t)).shift(np.cos(t)*OUT)
for t in np.linspace(0, np.pi, 20)
])
sphere.set_stroke(BLUE, width = 2)
# sphere.set_fill(BLUE, opacity = 0.1)
self.play(Rotating(
sphere, axis = RIGHT+OUT,
run_time = 10
))
self.repeat_frames(4)
class FourDSphereProjectTo4D(ExternallyAnimatedScene):
pass
class Test(Scene):
CONFIG = {
"camera_class" : ThreeDCamera,
}
def construct(self):
randy = Randolph()
necklace = Necklace()
necklace.insert_n_curves(20)
# necklace.apply_function(
# lambda (x, y, z) : x*RIGHT + (y + 0.1*x**2)*UP
# )
necklace.set_width(randy.get_width() + 1)
necklace.move_to(randy)
self.add(randy, necklace)
|
videos_3b1b/_2017/triples.py
|
import fractions
from manim_imports_ext import *
A_COLOR = BLUE
B_COLOR = GREEN
C_COLOR = YELLOW
SIDE_COLORS = [A_COLOR, B_COLOR, C_COLOR]
U_COLOR = GREEN
V_COLOR = RED
#revert_to_original_skipping_status
def complex_string_with_i(z):
if z.real == 0:
return str(int(z.imag)) + "i"
elif z.imag == 0:
return str(int(z.real))
return complex_string(z).replace("j", "i")
class IntroduceTriples(TeacherStudentsScene):
def construct(self):
title = OldTex("a", "^2", "+", "b", "^2", "=", "c", "^2")
for color, char in zip(SIDE_COLORS, "abc"):
title.set_color_by_tex(char, color)
title.to_corner(UP + RIGHT)
triples = [
(3, 4, 5),
(5, 12, 13),
(8, 15, 17),
(7, 24, 25),
]
self.add(title)
for a, b, c in triples:
triangle = Polygon(
ORIGIN, a*RIGHT, a*RIGHT+b*UP,
stroke_width = 0,
fill_color = WHITE,
fill_opacity = 0.5
)
hyp_line = Line(ORIGIN, a*RIGHT+b*UP)
elbow = VMobject()
elbow.set_points_as_corners([LEFT, LEFT+UP, UP])
elbow.set_width(0.2*triangle.get_width())
elbow.move_to(triangle, DOWN+RIGHT)
triangle.add(elbow)
square = Square(side_length = 1)
square_groups = VGroup()
for n, color in zip([a, b, c], SIDE_COLORS):
square_group = VGroup(*[
square.copy().shift(x*RIGHT + y*UP)
for x in range(n)
for y in range(n)
])
square_group.set_stroke(color, width = 3)
square_group.set_fill(color, opacity = 0.5)
square_groups.add(square_group)
a_square, b_square, c_square = square_groups
a_square.move_to(triangle.get_bottom(), UP)
b_square.move_to(triangle.get_right(), LEFT)
c_square.move_to(hyp_line.get_center(), DOWN)
c_square.rotate(
hyp_line.get_angle(),
about_point = hyp_line.get_center()
)
if c in [5, 13, 25]:
if c == 5:
keys = list(range(0, 5, 2))
elif c == 13:
keys = list(range(0, 13, 3))
elif c == 25:
keys = list(range(0, 25, 4))
i_list = [i for i in range(c**2) if (i%c) in keys and (i//c) in keys]
else:
i_list = list(range(a**2))
not_i_list = list(filter(
lambda i : i not in i_list,
list(range(c**2)),
))
c_square_parts = [
VGroup(*[c_square[i] for i in i_list]),
VGroup(*[c_square[i] for i in not_i_list]),
]
full_group = VGroup(triangle, square_groups)
full_group.set_height(4)
full_group.center()
full_group.to_edge(UP)
equation = OldTex(
str(a), "^2", "+", str(b), "^2", "=", str(c), "^2"
)
for num, color in zip([a, b, c], SIDE_COLORS):
equation.set_color_by_tex(str(num), color)
equation.next_to(title, DOWN, MED_LARGE_BUFF)
equation.shift_onto_screen()
self.play(
FadeIn(triangle),
self.teacher.change_mode, "raise_right_hand"
)
self.play(LaggedStartMap(FadeIn, a_square))
self.play_student_changes(
*["pondering"]*3,
look_at = triangle,
added_anims = [LaggedStartMap(FadeIn, b_square)]
)
self.play(self.teacher.change_mode, "happy")
for start, target in zip([a_square, b_square], c_square_parts):
mover = start.copy().set_fill(opacity = 0)
target.set_color(start.get_color())
self.play(ReplacementTransform(
mover, target,
run_time = 2,
path_arc = np.pi/2
))
self.play(Write(equation))
self.play(c_square.set_color, C_COLOR)
self.wait()
self.play(*list(map(FadeOut, [full_group, equation])))
class CompareToFermatsLastTheorem(TeacherStudentsScene):
def construct(self):
expressions = [
OldTex(
"a", "^%d"%d, "+", "b", "^%d"%d,
"=", "c", "^%d"%d
)
for d in range(2, 9)
]
for expression in expressions:
for char, color in zip("abc", SIDE_COLORS):
expression.set_color_by_tex(char, color)
expression.next_to(self.get_pi_creatures(), UP, buff = 1.3)
square_expression = expressions[0]
low_expression = expressions[1]
square_expression.to_edge(UP, buff = 1.3)
top_brace = Brace(square_expression, UP, buff = SMALL_BUFF)
top_text = top_brace.get_text(
"Abundant integer solutions", buff = SMALL_BUFF
)
low_brace = Brace(low_expression, DOWN, buff = SMALL_BUFF)
low_text = low_brace.get_text(
"No integer solutions", buff = SMALL_BUFF
)
low_text.set_color(RED)
self.add(square_expression, top_brace, top_text)
self.play_student_changes(*["pondering"]*3)
self.play(self.teacher.change, "happy", run_time = 0)
self.play(
ReplacementTransform(
square_expression.copy(),
low_expression
),
self.teacher.change_mode, "raise_right_hand",
*[
ApplyMethod(pi.change, "confused", expressions[1])
for pi in self.get_students()
]
)
self.wait()
self.play(Transform(low_expression, expressions[2]))
self.play(
GrowFromCenter(low_brace),
FadeIn(low_text),
)
self.play_student_changes(
"sassy", "angry", "erm",
look_at = low_expression,
added_anims = [Transform(low_expression, expressions[3])]
)
for expression in expressions[4:]:
self.play(Transform(low_expression, expression))
self.wait()
class WritePythagoreanTriple(Scene):
def construct(self):
words = OldTexText("``Pythagorean triple''")
words.set_width(FRAME_WIDTH - LARGE_BUFF)
words.to_corner(DOWN+LEFT)
self.play(Write(words))
self.wait(2)
class ShowManyTriples(Scene):
def construct(self):
triples = [
(u**2 - v**2, 2*u*v, u**2 + v**2)
for u in range(1, 15)
for v in range(1, u)
if fractions.gcd(u, v) == 1 and not (u%2 == v%2)
][:40]
triangles = VGroup()
titles = VGroup()
for i, (a, b, c) in enumerate(triples):
triangle = Polygon(ORIGIN, a*RIGHT, a*RIGHT+b*UP)
triangle.set_color(WHITE)
max_width = max_height = 4
triangle.set_height(max_height)
if triangle.get_width() > max_width:
triangle.set_width(max_width)
triangle.move_to(2*RIGHT)
num_strings = list(map(str, (a, b, c)))
labels = list(map(Tex, num_strings))
for label, color in zip(labels, SIDE_COLORS):
label.set_color(color)
labels[0].next_to(triangle, DOWN)
labels[1].next_to(triangle, RIGHT)
labels[2].next_to(triangle.get_center(), UP+LEFT)
triangle.add(*labels)
title = OldTex(
str(a), "^2", "+", str(b), "^2", "=", str(c), "^2"
)
for num, color in zip([a, b, c], SIDE_COLORS):
title.set_color_by_tex(str(num), color)
title.next_to(triangle, UP, LARGE_BUFF)
title.generate_target()
title.target.scale(0.5)
title.target.move_to(
(-FRAME_X_RADIUS + MED_LARGE_BUFF + 2.7*(i//8))*RIGHT + \
(FRAME_Y_RADIUS - MED_LARGE_BUFF - (i%8))*UP,
UP+LEFT
)
triangles.add(triangle)
titles.add(title)
triangle = triangles[0]
title = titles[0]
self.play(
Write(triangle),
Write(title),
run_time = 2,
)
self.wait()
self.play(MoveToTarget(title))
for i in range(1, 17):
new_triangle = triangles[i]
new_title = titles[i]
if i < 4:
self.play(
Transform(triangle, new_triangle),
FadeIn(new_title)
)
self.wait()
self.play(MoveToTarget(new_title))
else:
self.play(
Transform(triangle, new_triangle),
FadeIn(new_title.target)
)
self.wait()
self.play(FadeOut(triangle))
self.play(LaggedStartMap(
FadeIn,
VGroup(*[
title.target
for title in titles[17:]
]),
run_time = 5
))
self.wait(2)
class BabylonianTablets(Scene):
def construct(self):
title = OldTexText("Plimpton 322 Tablets \\\\ (1800 BC)")
title.to_corner(UP+LEFT)
ac_pairs = [
(119, 169),
(3367, 4825),
(4601, 6649),
(12709, 18541),
(65, 97),
(319, 481),
(2291, 3541),
(799, 1249),
(481, 769),
(4961, 8161),
(45, 75),
(1679, 2929),
(161, 289),
(1771, 3229),
(56, 106),
]
triples = VGroup()
for a, c in ac_pairs:
b = int(np.sqrt(c**2 - a**2))
tex = "%s^2 + %s^2 = %s^2"%tuple(
map("{:,}".format, [a, b, c])
)
tex = tex.replace(",", "{,}")
triple = OldTex(tex)
triples.add(triple)
triples.arrange(DOWN, aligned_edge = LEFT)
triples.set_height(FRAME_HEIGHT - LARGE_BUFF)
triples.to_edge(RIGHT)
self.add(title)
self.wait()
self.play(LaggedStartMap(FadeIn, triples, run_time = 5))
self.wait()
class AskAboutFavoriteProof(TeacherStudentsScene):
def construct(self):
self.student_says(
"What's you're \\\\ favorite proof?",
target_mode = "raise_right_hand"
)
self.play_student_changes("happy", "raise_right_hand", "happy")
self.teacher_thinks("", target_mode = "thinking")
self.wait()
self.zoom_in_on_thought_bubble()
class PythagoreanProof(Scene):
def construct(self):
self.add_title()
self.show_proof()
def add_title(self):
title = OldTex("a^2", "+", "b^2", "=", "c^2")
for color, char in zip(SIDE_COLORS, "abc"):
title.set_color_by_tex(char, color)
title.to_edge(UP)
self.add(title)
self.title = title
def show_proof(self):
triangle = Polygon(
ORIGIN, 5*RIGHT, 5*RIGHT+12*UP,
stroke_color = WHITE,
stroke_width = 2,
fill_color = WHITE,
fill_opacity = 0.5
)
triangle.set_height(3)
triangle.center()
side_labels = self.get_triangle_side_labels(triangle)
triangle_copy = triangle.copy()
squares = self.get_abc_squares(triangle)
a_square, b_square, c_square = squares
self.add(triangle, triangle_copy)
self.play(Write(side_labels))
self.wait()
self.play(*list(map(DrawBorderThenFill, squares)))
self.add_labels_to_squares(squares, side_labels)
self.wait()
self.play(
VGroup(triangle_copy, a_square, b_square).move_to,
4*LEFT+2*DOWN, DOWN,
VGroup(triangle, c_square).move_to,
4*RIGHT+2*DOWN, DOWN,
run_time = 2,
path_arc = np.pi/2,
)
self.wait()
self.add_new_triangles(
triangle,
self.get_added_triangles_to_c_square(triangle, c_square)
)
self.wait()
self.add_new_triangles(
triangle_copy,
self.get_added_triangles_to_ab_squares(triangle_copy, a_square)
)
self.wait()
big_squares = VGroup(*list(map(
self.get_big_square,
[triangle, triangle_copy]
)))
negative_space_words = OldTexText(
"Same negative \\\\ space"
)
negative_space_words.scale(0.75)
negative_space_words.shift(UP)
double_arrow = DoubleArrow(LEFT, RIGHT)
double_arrow.next_to(negative_space_words, DOWN)
self.play(
FadeIn(big_squares),
Write(negative_space_words),
ShowCreation(double_arrow),
*list(map(FadeOut, squares))
)
self.wait(2)
self.play(*it.chain(
list(map(FadeIn, squares)),
list(map(Animation, big_squares)),
))
self.wait(2)
def add_labels_to_squares(self, squares, side_labels):
for label, square in zip(side_labels, squares):
label.target = OldTex(label.get_tex() + "^2")
label.target.set_color(label.get_color())
# label.target.scale(0.7)
label.target.move_to(square)
square.add(label)
self.play(LaggedStartMap(MoveToTarget, side_labels))
def add_new_triangles(self, triangle, added_triangles):
brace = Brace(added_triangles, DOWN)
label = OldTex("a", "+", "b")
label.set_color_by_tex("a", A_COLOR)
label.set_color_by_tex("b", B_COLOR)
label.next_to(brace, DOWN)
self.play(ReplacementTransform(
VGroup(triangle.copy().set_fill(opacity = 0)),
added_triangles,
run_time = 2,
))
self.play(GrowFromCenter(brace))
self.play(Write(label))
triangle.added_triangles = added_triangles
def get_big_square(self, triangle):
square = Square(stroke_color = RED)
square.replace(
VGroup(triangle, triangle.added_triangles),
stretch = True
)
square.scale(1.01)
return square
#####
def get_triangle_side_labels(self, triangle):
a, b, c = list(map(Tex, "abc"))
for mob, color in zip([a, b, c], SIDE_COLORS):
mob.set_color(color)
a.next_to(triangle, DOWN)
b.next_to(triangle, RIGHT)
c.next_to(triangle.get_center(), LEFT)
return VGroup(a, b, c)
def get_abc_squares(self, triangle):
a_square, b_square, c_square = squares = [
Square(
stroke_color = color,
fill_color = color,
fill_opacity = 0.5,
)
for color in SIDE_COLORS
]
a_square.set_width(triangle.get_width())
a_square.move_to(triangle.get_bottom(), UP)
b_square.set_height(triangle.get_height())
b_square.move_to(triangle.get_right(), LEFT)
hyp_line = Line(
triangle.get_corner(UP+RIGHT),
triangle.get_corner(DOWN+LEFT),
)
c_square.set_width(hyp_line.get_length())
c_square.move_to(hyp_line.get_center(), UP)
c_square.rotate(
hyp_line.get_angle(),
about_point = hyp_line.get_center()
)
return a_square, b_square, c_square
def get_added_triangles_to_c_square(self, triangle, c_square):
return VGroup(*[
triangle.copy().rotate(i*np.pi/2, about_point = c_square.get_center())
for i in range(1, 4)
])
def get_added_triangles_to_ab_squares(self, triangle, a_square):
t1 = triangle.copy()
t1.rotate(np.pi)
group = VGroup(triangle, t1).copy()
group.rotate(-np.pi/2)
group.move_to(a_square.get_right(), LEFT)
t2, t3 = group
return VGroup(t1, t2, t3)
class ReframeOnLattice(PiCreatureScene):
CONFIG = {
"initial_plane_center" : 3*LEFT + DOWN,
"new_plane_center" : ORIGIN,
"initial_unit_size" : 0.5,
"new_unit_size" : 0.8,
"dot_radius" : 0.075,
"dot_color" : YELLOW,
}
def construct(self):
self.remove(self.pi_creature)
self.add_plane()
self.wander_over_lattice_points()
self.show_whole_distance_examples()
self.resize_plane()
self.show_root_example()
self.view_as_complex_number()
self.mention_squaring_it()
self.work_out_square_algebraically()
self.walk_through_square_geometrically()
def add_plane(self):
plane = ComplexPlane(
center_point = self.initial_plane_center,
unit_size = self.initial_unit_size,
stroke_width = 2,
secondary_line_ratio = 0,
)
plane.axes.set_stroke(width = 4)
plane.coordinate_labels = VGroup()
for x in range(-8, 20, 2):
if x == 0:
continue
label = OldTex(str(x))
label.scale(0.5)
label.add_background_rectangle(opacity = 1)
label.next_to(plane.coords_to_point(x, 0), DOWN, SMALL_BUFF)
plane.coordinate_labels.add(label)
self.add(plane, plane.coordinate_labels)
self.plane = plane
def wander_over_lattice_points(self):
initial_examples = [(5, 3), (6, 8), (2, 7)]
integer_distance_examples = [(3, 4), (12, 5), (15, 8)]
dot_tuple_groups = VGroup()
for x, y in initial_examples + integer_distance_examples:
dot = Dot(
self.plane.coords_to_point(x, y),
color = self.dot_color,
radius = self.dot_radius,
)
tuple_mob = OldTex("(", str(x), ",", str(y), ")")
tuple_mob.add_background_rectangle()
tuple_mob.next_to(dot, UP+RIGHT, buff = 0)
dot_tuple_groups.add(VGroup(dot, tuple_mob))
dot_tuple_group = dot_tuple_groups[0]
final_group = dot_tuple_groups[-len(integer_distance_examples)]
all_dots = self.get_all_plane_dots()
self.play(Write(dot_tuple_group, run_time = 2))
self.wait()
for new_group in dot_tuple_groups[1:len(initial_examples)]:
self.play(Transform(dot_tuple_group, new_group))
self.wait()
self.play(LaggedStartMap(
FadeIn, all_dots,
rate_func = there_and_back,
run_time = 3,
lag_ratio = 0.2,
))
self.wait()
self.play(ReplacementTransform(
dot_tuple_group, final_group
))
self.integer_distance_dot_tuple_groups = VGroup(
*dot_tuple_groups[len(initial_examples):]
)
def show_whole_distance_examples(self):
dot_tuple_groups = self.integer_distance_dot_tuple_groups
for dot_tuple_group in dot_tuple_groups:
dot, tuple_mob = dot_tuple_group
p0 = self.plane.get_center_point()
p1 = dot.get_center()
triangle = Polygon(
p0, p1[0]*RIGHT + p0[1]*UP, p1,
stroke_width = 0,
fill_color = BLUE,
fill_opacity = 0.75,
)
line = Line(p0, p1, color = dot.get_color())
a, b = self.plane.point_to_coords(p1)
c = int(np.sqrt(a**2 + b**2))
hyp_label = OldTex(str(c))
hyp_label.add_background_rectangle()
hyp_label.next_to(
triangle.get_center(), UP+LEFT, buff = SMALL_BUFF
)
line.add(hyp_label)
dot_tuple_group.triangle = triangle
dot_tuple_group.line = line
group = dot_tuple_groups[0]
self.play(Write(group.line))
self.play(FadeIn(group.triangle), Animation(group.line))
self.wait(2)
for new_group in dot_tuple_groups[1:]:
self.play(
Transform(group, new_group),
Transform(group.triangle, new_group.triangle),
Transform(group.line, new_group.line),
)
self.wait(2)
self.play(*list(map(FadeOut, [group, group.triangle, group.line])))
def resize_plane(self):
new_plane = ComplexPlane(
plane_center = self.new_plane_center,
unit_size = self.new_unit_size,
y_radius = 8,
x_radius = 11,
stroke_width = 2,
secondary_line_ratio = 0,
)
new_plane.axes.set_stroke(width = 4)
self.plane.generate_target()
self.plane.target.unit_size = self.new_unit_size
self.plane.target.plane_center = self.new_plane_center
self.plane.target.shift(
new_plane.coords_to_point(0, 0) - \
self.plane.target.coords_to_point(0, 0)
)
self.plane.target.scale(
self.new_unit_size / self.initial_unit_size
)
coordinate_labels = self.plane.coordinate_labels
for coord in coordinate_labels:
x = int(coord.get_tex())
coord.generate_target()
coord.target.scale(1.5)
coord.target.next_to(
new_plane.coords_to_point(x, 0),
DOWN, buff = SMALL_BUFF
)
self.play(
MoveToTarget(self.plane),
*list(map(MoveToTarget, self.plane.coordinate_labels)),
run_time = 2
)
self.remove(self.plane)
self.plane = new_plane
self.plane.coordinate_labels = coordinate_labels
self.add(self.plane, coordinate_labels)
self.wait()
def show_root_example(self):
x, y = (2, 1)
point = self.plane.coords_to_point(x, y)
dot = Dot(
point,
color = self.dot_color,
radius = self.dot_radius
)
tuple_label = OldTex(str((x, y)))
tuple_label.add_background_rectangle()
tuple_label.next_to(dot, RIGHT, SMALL_BUFF)
line = Line(self.plane.get_center_point(), point)
line.set_color(dot.get_color())
distance_labels = VGroup()
for tex in "2^2 + 1^2", "5":
pre_label = OldTex("\\sqrt{%s}"%tex)
rect = BackgroundRectangle(pre_label)
label = VGroup(
rect,
VGroup(*pre_label[:2]),
VGroup(*pre_label[2:]),
)
label.scale(0.8)
label.next_to(line.get_center(), UP, SMALL_BUFF)
label.rotate(
line.get_angle(),
about_point = line.get_center()
)
distance_labels.add(label)
self.play(
ShowCreation(line),
DrawBorderThenFill(
dot,
stroke_width = 3,
stroke_color = PINK
)
)
self.play(Write(tuple_label))
self.wait()
self.play(FadeIn(distance_labels[0]))
self.wait(2)
self.play(Transform(*distance_labels))
self.wait(2)
self.distance_label = distance_labels[0]
self.example_dot = dot
self.example_line = line
self.example_tuple_label = tuple_label
def view_as_complex_number(self):
imag_coords = VGroup()
for y in range(-4, 5, 2):
if y == 0:
continue
label = OldTex("%di"%y)
label.add_background_rectangle()
label.scale(0.75)
label.next_to(
self.plane.coords_to_point(0, y),
LEFT, SMALL_BUFF
)
imag_coords.add(label)
tuple_label = self.example_tuple_label
new_label = OldTex("2+i")
new_label.add_background_rectangle()
new_label.next_to(
self.example_dot,
DOWN+RIGHT, buff = 0,
)
self.play(Write(imag_coords))
self.wait()
self.play(FadeOut(tuple_label))
self.play(FadeIn(new_label))
self.wait(2)
self.example_label = new_label
self.plane.coordinate_labels.add(*imag_coords)
def mention_squaring_it(self):
morty = self.pi_creature
arrow = Arrow(
self.plane.coords_to_point(2, 1),
self.plane.coords_to_point(3, 4),
path_arc = np.pi/3,
color = MAROON_B
)
square_label = OldTex("z \\to z^2")
square_label.set_color(arrow.get_color())
square_label.add_background_rectangle()
square_label.next_to(
arrow.point_from_proportion(0.5),
RIGHT, buff = SMALL_BUFF
)
self.play(FadeIn(morty))
self.play(
PiCreatureSays(
morty, "Try squaring \\\\ it!",
target_mode = "hooray",
bubble_config = {"width" : 4, "height" : 3},
)
)
self.play(
ShowCreation(arrow),
Write(square_label)
)
self.wait()
self.play(RemovePiCreatureBubble(
morty, target_mode = "pondering",
look_at = self.example_label
))
def work_out_square_algebraically(self):
rect = Rectangle(
height = 3.5, width = 6.5,
stroke_width = 0,
fill_color = BLACK,
fill_opacity = 0.8
)
rect.to_corner(UP+LEFT, buff = 0)
top_line = OldTex("(2+i)", "(2+i)")
top_line.next_to(rect.get_top(), DOWN)
second_line = OldTex(
"2^2 + 2i + 2i + i^2"
)
second_line.next_to(top_line, DOWN, MED_LARGE_BUFF)
final_line = OldTex("3 + 4i")
final_line.next_to(second_line, DOWN, MED_LARGE_BUFF)
result_dot = Dot(
self.plane.coords_to_point(3, 4),
color = MAROON_B,
radius = self.dot_radius
)
self.play(
FadeIn(rect),
ReplacementTransform(
VGroup(self.example_label[1].copy()),
top_line
),
run_time = 2
)
self.wait()
#From top line to second line
index_alignment_lists = [
[(0, 1, 0), (1, 1, 1)],
[(0, 2, 2), (0, 1, 3), (1, 3, 4)],
[(0, 2, 5), (1, 1, 6), (0, 3, 7)],
[(0, 2, 8), (0, 3, 9), (1, 3, 10)],
]
for index_alignment in index_alignment_lists:
self.play(*[
ReplacementTransform(
top_line[i][j].copy(), second_line[k],
)
for i, j, k in index_alignment
])
self.wait(2)
#From second line to final line
index_alignment_lists = [
[(0, 0), (1, 0), (9, 0), (10, 0)],
[(2, 1), (3, 2), (4, 3), (6, 2), (7, 3)],
]
for index_alignment in index_alignment_lists:
self.play(*[
ReplacementTransform(
second_line[i].copy(), final_line[j],
run_time = 1.5
)
for i, j in index_alignment
])
self.wait()
#Move result to appropriate place
result_label = final_line.copy()
result_label.add_background_rectangle()
self.play(
result_label.next_to, result_dot, UP+RIGHT, SMALL_BUFF,
Animation(final_line),
run_time = 2,
)
self.play(DrawBorderThenFill(
result_dot,
stroke_width = 4,
stroke_color = PINK
))
self.wait(2)
def walk_through_square_geometrically(self):
line = self.example_line
dot = self.example_dot
example_label = self.example_label
distance_label = self.distance_label
alt_line = line.copy().set_color(RED)
arc = Arc(
angle = line.get_angle(),
radius = 0.7,
color = WHITE
)
double_arc = Arc(
angle = 2*line.get_angle(),
radius = 0.8,
color = RED,
)
theta = OldTex("\\theta")
two_theta = OldTex("2\\theta")
for tex_mob, arc_mob in (theta, arc), (two_theta, double_arc):
tex_mob.scale(0.75)
tex_mob.add_background_rectangle()
point = arc_mob.point_from_proportion(0.5)
tex_mob.move_to(point)
tex_mob.shift(tex_mob.get_width()*point/get_norm(point))
self.play(self.pi_creature.change, "happy", arc)
self.play(ShowCreation(alt_line))
self.play(ShowCreation(line))
self.remove(alt_line)
self.wait()
self.play(
ShowCreation(arc),
Write(theta)
)
self.wait()
self.play(Indicate(distance_label))
self.wait()
#Multiply full plane under everything
everything = VGroup(*self.get_top_level_mobjects())
everything.remove(self.plane)
self.plane.save_state()
ghost_plane = self.plane.copy().fade()
method_args_list = [
(self.plane.rotate, (line.get_angle(),)),
(self.plane.scale, (np.sqrt(5),)),
(self.plane.restore, ()),
]
for method, args in method_args_list:
self.play(
Animation(ghost_plane),
ApplyMethod(method, *args),
Animation(everything),
run_time = 1.5
)
self.wait()
#Multiply number by itself
ghost_arc = arc.copy().fade()
ghost_line = line.copy().fade()
ghots_dot = dot.copy().fade()
self.add(ghost_arc, ghost_line, ghots_dot)
self.play(
VGroup(
line, dot, distance_label,
).rotate, line.get_angle(),
Transform(arc, double_arc),
Transform(theta, two_theta),
)
self.wait()
five = distance_label[2]
distance_label.remove(five)
for mob in five, line, dot:
mob.generate_target()
line.target.scale(np.sqrt(5))
five.target.shift(line.target.get_center()-line.get_center())
dot.target.move_to(line.target.get_end())
self.play(
FadeOut(distance_label),
*list(map(MoveToTarget, [five, line, dot])),
run_time = 2
)
self.wait(2)
####
def get_all_plane_dots(self):
x_min, y_min = list(map(int, self.plane.point_to_coords(
FRAME_X_RADIUS*LEFT + FRAME_Y_RADIUS*DOWN
)))
x_max, y_max = list(map(int, self.plane.point_to_coords(
FRAME_X_RADIUS*RIGHT + FRAME_Y_RADIUS*UP
)))
result = VGroup(*[
Dot(
self.plane.coords_to_point(x, y),
radius = self.dot_radius,
color = self.dot_color,
)
for x in range(int(x_min), int(x_max)+1)
for y in range(int(y_min), int(y_max)+1)
])
result.sort(lambda p : np.dot(p, UP+RIGHT))
return result
def create_pi_creature(self):
morty = Mortimer().flip()
morty.to_corner(DOWN+LEFT, buff = MED_SMALL_BUFF)
return morty
class TimeToGetComplex(TeacherStudentsScene):
def construct(self):
self.teacher_says("Time to \\\\ get complex")
self.play_student_changes("angry", "sassy", "pleading")
self.wait(2)
class OneMoreExample(Scene):
CONFIG = {
"unit_size" : 0.5,
"plane_center" : 3*LEFT + 3*DOWN,
"dot_color" : YELLOW,
"x_label_range" : list(range(-6, 25, 3)),
"y_label_range" : list(range(3, 13, 3)),
}
def construct(self):
self.add_plane()
self.add_point()
self.square_algebraically()
self.plot_result()
self.show_triangle()
def add_plane(self):
plane = ComplexPlane(
unit_size = self.unit_size,
center_point = self.plane_center,
stroke_width = 2,
)
plane.axes.set_stroke(width = 4)
coordinate_labels = VGroup()
for x in self.x_label_range:
if x == 0:
continue
coord = OldTex(str(x))
coord.scale(0.75)
coord.next_to(plane.coords_to_point(x, 0), DOWN, SMALL_BUFF)
coord.add_background_rectangle()
coordinate_labels.add(coord)
for y in self.y_label_range:
if y == 0:
continue
coord = OldTex("%di"%y)
coord.scale(0.75)
coord.next_to(plane.coords_to_point(0, y), LEFT, SMALL_BUFF)
coord.add_background_rectangle()
coordinate_labels.add(coord)
self.add(plane, coordinate_labels)
self.plane = plane
self.plane.coordinate_labels = coordinate_labels
def add_point(self):
point = self.plane.coords_to_point(3, 2)
dot = Dot(point, color = self.dot_color)
line = Line(self.plane.get_center_point(), point)
line.set_color(dot.get_color())
number_label = OldTex("3+2i")
number_label.add_background_rectangle()
number_label.next_to(dot, RIGHT, SMALL_BUFF)
distance_labels = VGroup()
for tex in "3^2 + 2^2", "13":
pre_label = OldTex("\\sqrt{%s}"%tex)
label = VGroup(
BackgroundRectangle(pre_label),
VGroup(*pre_label[:2]),
VGroup(*pre_label[2:]),
)
label.scale(0.75)
label.next_to(line.get_center(), UP, SMALL_BUFF)
label.rotate(
line.get_angle(),
about_point = line.get_center()
)
distance_labels.add(label)
self.play(
FadeIn(number_label),
ShowCreation(line),
DrawBorderThenFill(dot)
)
self.play(Write(distance_labels[0]))
self.wait()
self.play(ReplacementTransform(*distance_labels))
self.wait()
self.distance_label = distance_labels[1]
self.line = line
self.dot = dot
self.number_label = number_label
def square_algebraically(self):
#Crazy hacky. To anyone looking at this, for God's
#sake, don't mimic this.
rect = Rectangle(
height = 3.5, width = 7,
stroke_color = WHITE,
stroke_width = 2,
fill_color = BLACK,
fill_opacity = 0.8
)
rect.to_corner(UP+RIGHT, buff = 0)
number = self.number_label[1].copy()
top_line = OldTex("(3+2i)", "(3+2i)")
for part in top_line:
for i, color in zip([1, 3], [BLUE, YELLOW]):
part[i].set_color(color)
second_line = OldTex(
"\\big( 3^2 + (2i)^2 \\big) + " + \
"\\big(3 \\cdot 2 + 2 \\cdot 3 \\big)i"
)
for i in 1, 12, 18:
second_line[i].set_color(BLUE)
for i in 5, 14, 16:
second_line[i].set_color(YELLOW)
second_line.scale(0.9)
final_line = OldTex("5 + 12i")
for i in 0, 2, 3:
final_line[i].set_color(GREEN)
lines = VGroup(top_line, second_line, final_line)
lines.arrange(DOWN, buff = MED_LARGE_BUFF)
lines.next_to(rect.get_top(), DOWN)
minus = OldTex("-").scale(0.9)
minus.move_to(second_line[3])
self.play(
FadeIn(rect),
Transform(VGroup(number), top_line),
run_time = 2
)
self.wait()
index_alignment_lists = [
[(0, 0, 0), (0, 1, 1), (1, 1, 2), (1, 5, 9)],
[
(0, 2, 3), (1, 3, 4), (0, 3, 5),
(0, 4, 6), (1, 4, 7), (1, 3, 8)
],
[
(0, 2, 10), (0, 0, 11), (0, 1, 12),
(1, 3, 13), (1, 3, 14), (1, 5, 19),
(0, 4, 20), (1, 4, 20),
],
[
(0, 2, 15), (0, 3, 16),
(1, 1, 17), (1, 1, 18),
],
]
for index_alignment in index_alignment_lists[:2]:
self.play(*[
ReplacementTransform(
top_line[i][j].copy(), second_line[k],
run_time = 1.5
)
for i, j, k in index_alignment
])
self.wait()
self.play(
Transform(second_line[3], minus),
FadeOut(VGroup(*[
second_line[i]
for i in (4, 6, 7)
])),
second_line[5].shift, 0.35*RIGHT,
)
self.play(VGroup(*second_line[:4]).shift, 0.55*RIGHT)
self.wait()
for index_alignment in index_alignment_lists[2:]:
self.play(*[
ReplacementTransform(
top_line[i][j].copy(), second_line[k],
run_time = 1.5
)
for i, j, k in index_alignment
])
self.wait()
self.play(FadeIn(final_line))
self.wait()
self.final_line = final_line
def plot_result(self):
result_label = self.final_line.copy()
result_label.add_background_rectangle()
point = self.plane.coords_to_point(5, 12)
dot = Dot(point, color = GREEN)
line = Line(self.plane.get_center_point(), point)
line.set_color(dot.get_color())
distance_label = OldTex("13")
distance_label.add_background_rectangle()
distance_label.next_to(line.get_center(), UP+LEFT, SMALL_BUFF)
self.play(
result_label.next_to, dot, UP+LEFT, SMALL_BUFF,
Animation(self.final_line),
DrawBorderThenFill(dot)
)
self.wait()
self.play(*[
ReplacementTransform(m1.copy(), m2)
for m1, m2 in [
(self.line, line),
(self.distance_label, distance_label)
]
])
self.wait()
def show_triangle(self):
triangle = Polygon(*[
self.plane.coords_to_point(x, y)
for x, y in [(0, 0), (5, 0), (5, 12)]
])
triangle.set_stroke(WHITE, 1)
triangle.set_fill(BLUE, opacity = 0.75)
self.play(
FadeIn(triangle),
Animation(VGroup(
self.line, self.dot,
self.number_label[1], *self.distance_label[1:]
)),
run_time = 2
)
self.wait(2)
class ThisIsMagic(TeacherStudentsScene):
def construct(self):
self.student_says(
"This is magic", target_mode = "hooray"
)
self.play(self.teacher.change, "happy")
self.wait(2)
class GeneralExample(OneMoreExample):
CONFIG = {
"number" : complex(4, 1),
"square_color" : MAROON_B,
"result_label_vect" : UP+LEFT,
}
def construct(self):
self.add_plane()
self.square_point()
def square_point(self):
z = self.number
z_point = self.plane.number_to_point(z)
zero_point = self.plane.number_to_point(0)
dot = Dot(z_point, color = self.dot_color)
line = Line(zero_point, z_point)
line.set_color(dot.get_color())
label = OldTex(complex_string_with_i(z))
label.add_background_rectangle()
label.next_to(dot, RIGHT, SMALL_BUFF)
square_point = self.plane.number_to_point(z**2)
square_dot = Dot(square_point, color = self.square_color)
square_line = Line(zero_point, square_point)
square_line.set_color(square_dot.get_color())
square_label = OldTex(complex_string_with_i(z**2))
square_label.add_background_rectangle()
square_label.next_to(square_dot, UP+RIGHT, SMALL_BUFF)
result_length_label = OldTex(str(int(abs(z**2))))
result_length_label.next_to(
square_line.get_center(), self.result_label_vect
)
result_length_label.add_background_rectangle()
arrow = Arrow(
z_point, square_point,
# buff = SMALL_BUFF,
path_arc = np.pi/2
)
arrow.set_color(WHITE)
z_to_z_squared = OldTex("z", "\\to", "z^2")
z_to_z_squared.set_color_by_tex("z", dot.get_color())
z_to_z_squared.set_color_by_tex("z^2", square_dot.get_color())
z_to_z_squared.next_to(
arrow.point_from_proportion(0.5),
RIGHT, MED_SMALL_BUFF
)
z_to_z_squared.add_to_back(
BackgroundRectangle(VGroup(
z_to_z_squared[2][0],
*z_to_z_squared[:-1]
)),
BackgroundRectangle(z_to_z_squared[2][1])
)
self.play(
Write(label),
ShowCreation(line),
DrawBorderThenFill(dot)
)
self.wait()
self.play(
ShowCreation(arrow),
FadeIn(z_to_z_squared),
Animation(label),
)
self.play(*[
ReplacementTransform(
start.copy(), target,
path_arc = np.pi/2,
run_time = 1.5
)
for start, target in [
(dot, square_dot),
(line, square_line),
(label, square_label),
]
])
self.wait()
self.play(Write(result_length_label))
self.wait()
self.example_dot = dot
self.example_label = label
self.example_line = line
self.square_dot = square_dot
self.square_label = square_label
self.square_line = square_line
self.z_to_z_squared = z_to_z_squared
self.z_to_z_squared_arrow = arrow
self.result_length_label = result_length_label
class BoringExample(GeneralExample):
CONFIG = {
"number" : complex(2, 2),
"result_label_vect" : RIGHT,
}
def construct(self):
self.add_plane()
self.square_point()
self.show_associated_triplet()
def show_associated_triplet(self):
arrow = Arrow(LEFT, RIGHT, color = GREEN)
arrow.next_to(self.square_label, RIGHT)
triple = OldTex("0^2 + 8^2 = 8^2")
for part, color in zip(triple[::3], SIDE_COLORS):
part.set_color(color)
triple.add_background_rectangle()
triple.next_to(arrow, RIGHT)
morty = Mortimer()
morty.next_to(self.plane.coords_to_point(12, 0), UP)
self.play(
ShowCreation(arrow),
FadeIn(morty)
)
self.play(
Write(triple),
morty.change, "raise_right_hand", triple
)
self.play(Blink(morty))
self.play(morty.change, "tired")
self.wait(2)
self.play(Blink(morty))
self.wait()
class FiveTwoExample(GeneralExample):
CONFIG = {
"number" : complex(5, 2),
"unit_size" : 0.25,
"x_label_range" : list(range(-10, 40, 5)),
"y_label_range" : list(range(0, 30, 5)),
}
class WriteGeneralFormula(GeneralExample):
CONFIG = {
"plane_center" : 2*RIGHT,
"x_label_range" : [],
"y_label_range" : [],
"unit_size" : 0.7,
"number" : complex(2, 1),
}
def construct(self):
self.add_plane()
self.show_squaring()
self.expand_square()
self.draw_triangle()
self.show_uv_to_triples()
def show_squaring(self):
self.force_skipping()
self.square_point()
dot = self.example_dot
old_label = self.example_label
line = self.example_line
square_dot = self.square_dot
old_square_label = self.square_label
square_line = self.square_line
z_to_z_squared = self.z_to_z_squared
arrow = self.z_to_z_squared_arrow
result_length_label = self.result_length_label
self.clear()
self.add(self.plane, self.plane.coordinate_labels)
self.revert_to_original_skipping_status()
label = OldTex("u+vi")
label.move_to(old_label, LEFT)
label.add_background_rectangle()
square_label = OldTex("(u+vi)^2")
square_label.move_to(old_square_label, LEFT)
square_label.add_background_rectangle()
self.add(label, dot, line)
self.play(
ShowCreation(arrow),
FadeIn(z_to_z_squared)
)
self.play(*[
ReplacementTransform(
start.copy(), target,
run_time = 1.5,
path_arc = np.pi/2
)
for start, target in [
(dot, square_dot),
(line, square_line),
(label, square_label),
]
])
self.example_label = label
self.square_label = square_label
def expand_square(self):
rect = Rectangle(
height = 2.5, width = 7,
stroke_width = 0,
fill_color = BLACK,
fill_opacity = 0.8,
)
rect.to_corner(UP+LEFT, buff = 0)
top_line = OldTex("(u+vi)(u+vi)")
for i in 1, 7:
top_line[i].set_color(U_COLOR)
top_line[i+2].set_color(V_COLOR)
top_line.next_to(rect.get_top(), DOWN)
second_line = OldTex(
"\\big(", "u^2 - v^2", "\\big)", "+",
"\\big(", "2uv", "\\big)", "i"
)
for i, j in (1, 0), (5, 1):
second_line[i][j].set_color(U_COLOR)
for i, j in (1, 3), (5, 2):
second_line[i][j].set_color(V_COLOR)
second_line.next_to(top_line, DOWN, MED_LARGE_BUFF)
real_part = second_line[1]
imag_part = second_line[5]
for part in real_part, imag_part:
part.add_to_back(BackgroundRectangle(part))
z = self.number**2
square_point = self.plane.number_to_point(z)
zero_point = self.plane.number_to_point(0)
real_part_point = self.plane.number_to_point(z.real)
real_part_line = Line(zero_point, real_part_point)
imag_part_line = Line(real_part_point, square_point)
for line in real_part_line, imag_part_line:
line.set_color(self.square_color)
self.play(*list(map(FadeIn, [rect, top_line, second_line])))
self.wait()
self.play(
real_part.copy().next_to, real_part_line.copy(),
DOWN, SMALL_BUFF,
ShowCreation(real_part_line)
)
self.wait()
self.play(
FadeOut(VGroup(
self.example_label, self.example_dot, self.example_line,
self.z_to_z_squared, self.z_to_z_squared_arrow
)),
imag_part.copy().next_to, imag_part_line.copy(),
RIGHT, SMALL_BUFF,
ShowCreation(imag_part_line)
)
self.wait()
self.corner_rect = rect
def draw_triangle(self):
hyp_length = OldTex("u", "^2", "+", "v", "^2")
hyp_length.set_color_by_tex("u", U_COLOR)
hyp_length.set_color_by_tex("v", V_COLOR)
hyp_length.add_background_rectangle()
line = self.square_line
hyp_length.next_to(line.get_center(), UP, SMALL_BUFF)
hyp_length.rotate(
line.get_angle(),
about_point = line.get_center()
)
triangle = Polygon(
ORIGIN, RIGHT, RIGHT+UP,
stroke_width = 0,
fill_color = MAROON_B,
fill_opacity = 0.5,
)
triangle.replace(line, stretch = True)
self.play(Write(hyp_length))
self.wait()
self.play(FadeIn(triangle))
self.wait()
def show_uv_to_triples(self):
rect = self.corner_rect.copy()
rect.stretch_to_fit_height(FRAME_HEIGHT)
rect.move_to(self.corner_rect.get_bottom(), UP)
h_line = Line(rect.get_left(), rect.get_right())
h_line.next_to(rect.get_top(), DOWN, LARGE_BUFF)
v_line = Line(rect.get_top(), rect.get_bottom())
v_line.shift(1.3*LEFT)
uv_title = OldTex("(u, v)")
triple_title = OldTex("(u^2 - v^2, 2uv, u^2 + v^2)")
uv_title.scale(0.75)
triple_title.scale(0.75)
uv_title.next_to(
h_line.point_from_proportion(1./6),
UP, SMALL_BUFF
)
triple_title.next_to(
h_line.point_from_proportion(2./3),
UP, SMALL_BUFF
)
pairs = [(2, 1), (3, 2), (4, 1), (4, 3), (5, 2), (5, 4)]
pair_mobs = VGroup()
triple_mobs = VGroup()
for u, v in pairs:
a, b, c = u**2 - v**2, 2*u*v, u**2 + v**2
pair_mob = OldTex("(", str(u), ",", str(v), ")")
pair_mob.set_color_by_tex(str(u), U_COLOR)
pair_mob.set_color_by_tex(str(v), V_COLOR)
triple_mob = OldTex("(%d, %d, %d)"%(a, b, c))
pair_mobs.add(pair_mob)
triple_mobs.add(triple_mob)
pair_mob.scale(0.75)
triple_mob.scale(0.75)
pair_mobs.arrange(DOWN)
pair_mobs.next_to(uv_title, DOWN, MED_LARGE_BUFF)
triple_mobs.arrange(DOWN)
triple_mobs.next_to(triple_title, DOWN, MED_LARGE_BUFF)
self.play(*list(map(FadeIn, [
rect, h_line, v_line,
uv_title, triple_title
])))
self.play(*[
LaggedStartMap(
FadeIn, mob,
run_time = 5,
lag_ratio = 0.2
)
for mob in (pair_mobs, triple_mobs)
])
class VisualizeZSquared(Scene):
CONFIG = {
"initial_unit_size" : 0.4,
"final_unit_size" : 0.1,
"plane_center" : 3*LEFT + 2*DOWN,
"x_label_range" : list(range(-12, 24, 4)),
"y_label_range" : list(range(-4, 24, 4)),
"dot_color" : YELLOW,
"square_color" : MAROON_B,
"big_dot_radius" : 0.075,
"dot_radius" : 0.05,
}
def construct(self):
self.force_skipping()
self.add_plane()
self.write_z_to_z_squared()
self.draw_arrows()
self.draw_dots()
self.add_colored_grid()
self.apply_transformation()
self.show_triangles()
self.zoom_out()
self.show_more_triangles()
def add_plane(self):
width = (FRAME_X_RADIUS+abs(self.plane_center[0]))/self.final_unit_size
height = (FRAME_Y_RADIUS+abs(self.plane_center[1]))/self.final_unit_size
background_plane = ComplexPlane(
x_radius = width,
y_radius = height,
stroke_width = 2,
stroke_color = BLUE_E,
secondary_line_ratio = 0,
)
background_plane.axes.set_stroke(width = 4)
background_plane.scale(self.initial_unit_size)
background_plane.shift(self.plane_center)
coordinate_labels = VGroup()
z_list = np.append(
self.x_label_range,
complex(0, 1)*np.array(self.y_label_range)
)
for z in z_list:
if z == 0:
continue
if z.imag == 0:
tex = str(int(z.real))
else:
tex = str(int(z.imag)) + "i"
label = OldTex(tex)
label.scale(0.75)
label.add_background_rectangle()
point = background_plane.number_to_point(z)
if z.imag == 0:
label.next_to(point, DOWN, SMALL_BUFF)
else:
label.next_to(point, LEFT, SMALL_BUFF)
coordinate_labels.add(label)
self.add(background_plane, coordinate_labels)
self.background_plane = background_plane
self.coordinate_labels = coordinate_labels
def write_z_to_z_squared(self):
z_to_z_squared = OldTex("z", "\\to", "z^2")
z_to_z_squared.set_color_by_tex("z", YELLOW)
z_to_z_squared.set_color_by_tex("z^2", MAROON_B)
z_to_z_squared.add_background_rectangle()
z_to_z_squared.to_edge(UP)
z_to_z_squared.shift(2*RIGHT)
self.play(Write(z_to_z_squared))
self.wait()
self.z_to_z_squared = z_to_z_squared
def draw_arrows(self):
z_list = [
complex(2, 1),
complex(3, 2),
complex(0, 1),
complex(-1, 0),
]
arrows = VGroup()
dots = VGroup()
for z in z_list:
z_point, square_point, mid_point = [
self.background_plane.number_to_point(z**p)
for p in (1, 2, 1.5)
]
angle = Line(mid_point, square_point).get_angle()
angle -= Line(z_point, mid_point).get_angle()
angle *= 2
arrow = Arrow(
z_point, square_point,
path_arc = angle,
color = WHITE,
tip_length = 0.15,
buff = SMALL_BUFF,
)
z_dot, square_dot = [
Dot(
point, color = color,
radius = self.big_dot_radius,
)
for point, color in [
(z_point, self.dot_color),
(square_point, self.square_color),
]
]
z_label = OldTex(complex_string_with_i(z))
square_label = OldTex(complex_string_with_i(z**2))
for label, point in (z_label, z_point), (square_label, square_point):
if abs(z) > 2:
vect = RIGHT
else:
vect = point - self.plane_center
vect /= get_norm(vect)
if abs(vect[1]) < 0.1:
vect[1] = -1
label.next_to(point, vect)
label.add_background_rectangle()
self.play(*list(map(FadeIn, [z_label, z_dot])))
self.wait()
self.play(ShowCreation(arrow))
self.play(ReplacementTransform(
z_dot.copy(), square_dot,
path_arc = angle
))
self.play(FadeIn(square_label))
self.wait()
self.play(
FadeOut(z_label),
FadeOut(square_label),
Animation(arrow)
)
arrows.add(arrow)
dots.add(z_dot, square_dot)
self.wait()
self.play(*list(map(FadeOut, [
dots, arrows, self.z_to_z_squared
])))
def draw_dots(self):
min_corner, max_corner = [
self.background_plane.point_to_coords(
u*FRAME_X_RADIUS*RIGHT + u*FRAME_Y_RADIUS*UP
)
for u in (-1, 1)
]
x_min, y_min = list(map(int, min_corner[:2]))
x_max, y_max = list(map(int, max_corner[:2]))
dots = VGroup(*[
Dot(
self.background_plane.coords_to_point(x, y),
color = self.dot_color,
radius = self.dot_radius,
)
for x in range(x_min, x_max+1)
for y in range(y_min, y_max+1)
])
dots.sort(lambda p : np.dot(p, UP+RIGHT))
self.add_foreground_mobject(self.coordinate_labels)
self.play(LaggedStartMap(
DrawBorderThenFill, dots,
stroke_width = 3,
stroke_color = PINK,
run_time = 3,
lag_ratio = 0.2
))
self.wait()
self.dots = dots
def add_colored_grid(self):
color_grid = self.get_color_grid()
self.play(
self.background_planes.set_stroke, None, 1,
LaggedStartMap(
FadeIn, color_grid,
run_time = 2
),
Animation(self.dots),
)
self.wait()
self.color_grid = color_grid
def apply_transformation(self):
for dot in self.dots:
dot.start_point = dot.get_center()
def update_dot(dot, alpha):
event = list(dot.start_point) + [alpha]
dot.move_to(self.homotopy(*event))
return dot
self.play(
Homotopy(self.homotopy, self.color_grid),
*[
UpdateFromAlphaFunc(dot, update_dot)
for dot in self.dots
],
run_time = 3
)
self.wait(2)
self.play(self.color_grid.set_stroke, None, 3)
self.wait()
scale_factor = self.big_dot_radius/self.dot_radius
self.play(LaggedStartMap(
ApplyMethod, self.dots,
lambda d : (d.scale, scale_factor),
rate_func = there_and_back,
run_time = 3
))
self.wait()
def show_triangles(self):
z_list = [
complex(u, v)**2
for u, v in [(2, 1), (3, 2), (4, 1)]
]
triangles = self.get_triangles(z_list)
triangle = triangles[0]
triangle.save_state()
triangle.scale(0.01, about_point = triangle.tip)
self.play(triangle.restore, run_time = 2)
self.wait(2)
for new_triangle in triangles[1:]:
self.play(Transform(triangle, new_triangle))
self.wait(2)
self.play(FadeOut(triangle))
def zoom_out(self):
self.remove_foreground_mobject(self.coordinate_labels)
movers = [
self.background_plane,
self.color_grid,
self.dots,
self.coordinate_labels,
]
scale_factor = self.final_unit_size/self.initial_unit_size
for mover in movers:
mover.generate_target()
mover.target.scale(
scale_factor,
about_point = self.plane_center
)
for dot in self.dots.target:
dot.scale(1./scale_factor)
self.background_plane.target.fade()
self.revert_to_original_skipping_status()
self.play(
*list(map(MoveToTarget, movers)),
run_time = 3
)
self.wait(2)
def show_more_triangles(self):
z_list = [
complex(u, v)**2
for u in range(4, 7)
for v in range(1, u)
]
triangles = self.get_triangles(z_list)
triangle = triangles[0]
self.play(FadeOut(triangle))
self.wait(2)
for new_triangle in triangles[1:]:
self.play(Transform(triangle, new_triangle))
self.wait(2)
###
def get_color_grid(self):
width = (FRAME_X_RADIUS+abs(self.plane_center[0]))/self.initial_unit_size
height = (FRAME_Y_RADIUS+abs(self.plane_center[1]))/self.initial_unit_size
color_grid = ComplexPlane(
x_radius = width,
y_radius = int(height),
secondary_line_ratio = 0,
stroke_width = 2,
)
color_grids.set_color_by_gradient(
*[GREEN, RED, MAROON_B, TEAL]*2
)
color_grid.remove(color_grid.axes[0])
for line in color_grid.family_members_with_points():
center = line.get_center()
if center[0] <= 0 and abs(center[1]) < 0.01:
line_copy = line.copy()
line.scale(0.499, about_point = line.get_start())
line_copy.scale(0.499, about_point = line_copy.get_end())
color_grid.add(line_copy)
color_grid.scale(self.initial_unit_size)
color_grid.shift(self.plane_center)
color_grid.prepare_for_nonlinear_transform()
return color_grid
def get_triangles(self, z_list):
triangles = VGroup()
for z in z_list:
point = self.background_plane.number_to_point(z)
line = Line(self.plane_center, point)
triangle = Polygon(
ORIGIN, RIGHT, RIGHT+UP,
stroke_color = BLUE,
stroke_width = 2,
fill_color = BLUE,
fill_opacity = 0.5,
)
triangle.replace(line, stretch = True)
a = int(z.real)
b = int(z.imag)
c = int(abs(z))
a_label, b_label, c_label = labels = [
OldTex(str(num))
for num in (a, b, c)
]
for label in b_label, c_label:
label.add_background_rectangle()
a_label.next_to(triangle.get_bottom(), UP, SMALL_BUFF)
b_label.next_to(triangle, RIGHT, SMALL_BUFF)
c_label.next_to(line.get_center(), UP+LEFT, SMALL_BUFF)
triangle.add(*labels)
triangle.tip = point
triangles.add(triangle)
return triangles
def homotopy(self, x, y, z, t):
z_complex = self.background_plane.point_to_number(np.array([x, y, z]))
result = z_complex**(1+t)
return self.background_plane.number_to_point(result)
class AskAboutHittingAllPoints(TeacherStudentsScene):
def construct(self):
self.student_says(
"Does this hit \\\\ all pythagorean triples?",
target_mode = "raise_left_hand"
)
self.wait()
self.teacher_says("No", target_mode = "sad")
self.play_student_changes(*["hesitant"]*3)
self.wait()
class PointsWeMiss(VisualizeZSquared):
CONFIG = {
"final_unit_size" : 0.4,
"plane_center" : 2*LEFT + 2*DOWN,
"dot_x_range" : list(range(-5, 6)),
"dot_y_range" : list(range(-4, 4)),
}
def construct(self):
self.add_plane()
self.add_transformed_color_grid()
self.add_dots()
self.show_missing_point()
self.show_second_missing_point()
self.mention_one_half_rule()
def add_transformed_color_grid(self):
color_grid = self.get_color_grid()
func = lambda p : self.homotopy(p[0], p[1], p[1], 1)
color_grid.apply_function(func)
color_grid.set_stroke(width = 4)
self.add(color_grid, self.coordinate_labels)
self.color_grid = color_grid
def add_dots(self):
z_list = [
complex(x, y)**2
for x in self.dot_x_range
for y in self.dot_y_range
]
dots = VGroup(*[
Dot(
self.background_plane.number_to_point(z),
color = self.dot_color,
radius = self.big_dot_radius,
)
for z in z_list
])
dots.sort(get_norm)
self.add(dots)
self.dots = dots
def show_missing_point(self):
z_list = [complex(6, 8), complex(9, 12), complex(3, 4)]
points = list(map(
self.background_plane.number_to_point,
z_list
))
dots = VGroup(*list(map(Dot, points)))
for dot in dots[:2]:
dot.set_stroke(RED, 4)
dot.set_fill(opacity = 0)
labels = VGroup(*[
OldTex(complex_string_with_i(z))
for z in z_list
])
labels.set_color(RED)
labels[2].set_color(GREEN)
rhss = VGroup()
for label, dot in zip(labels, dots):
label.add_background_rectangle()
label.next_to(dot, UP+RIGHT, SMALL_BUFF)
if label is labels[-1]:
rhs = OldTex("= (2+i)^2")
else:
rhs = OldTex("\\ne (u+vi)^2")
rhs.add_background_rectangle()
rhs.next_to(label, RIGHT)
rhss.add(rhs)
triangles = self.get_triangles(z_list)
self.play(FocusOn(dots[0]))
self.play(ShowCreation(dots[0]))
self.play(Write(labels[0]))
self.wait()
self.play(FadeIn(triangles[0]))
self.wait(2)
self.play(Write(rhss[0]))
self.wait(2)
groups = triangles, dots, labels, rhss
for i in 1, 2:
self.play(*[
Transform(group[0], group[i])
for group in groups
])
self.wait(3)
self.play(*[
FadeOut(group[0])
for group in groups
])
def show_second_missing_point(self):
z_list = [complex(4, 3), complex(8, 6)]
points = list(map(
self.background_plane.number_to_point,
z_list
))
dots = VGroup(*list(map(Dot, points)))
dots[0].set_stroke(RED, 4)
dots[0].set_fill(opacity = 0)
labels = VGroup(*[
OldTex(complex_string_with_i(z))
for z in z_list
])
labels[0].set_color(RED)
labels[1].set_color(GREEN)
rhss = VGroup()
for label, dot in zip(labels, dots):
label.add_background_rectangle()
label.next_to(dot, UP+RIGHT, SMALL_BUFF)
if label is labels[-1]:
rhs = OldTex("= (3+i)^2")
else:
rhs = OldTex("\\ne (u+vi)^2")
rhs.add_background_rectangle()
rhs.next_to(label, RIGHT)
rhss.add(rhs)
triangles = self.get_triangles(z_list)
groups = [dots, labels, rhss, triangles]
for group in groups:
group[0].save_state()
self.play(ShowCreation(dots[0]))
self.play(Write(VGroup(labels[0], rhss[0])))
self.play(FadeIn(triangles[0]))
self.wait(3)
self.play(*[Transform(*group) for group in groups])
self.wait(3)
self.play(*[group[0].restore for group in groups])
self.wait(2)
def mention_one_half_rule(self):
morty = Mortimer()
morty.flip()
morty.to_corner(DOWN+LEFT)
self.play(FadeIn(morty))
self.play(PiCreatureSays(
morty,
"Never need to scale \\\\ by less than $\\frac{1}{2}$"
))
self.play(Blink(morty))
self.wait(2)
class PointsWeMissAreMultiplesOfOnesWeHit(TeacherStudentsScene):
def construct(self):
words = OldTexText(
"Every point we",
"miss",
"is \\\\ a multiple of one we",
"hit"
)
words.set_color_by_tex("miss", RED)
words.set_color_by_tex("hit", GREEN)
self.teacher_says(words)
self.play_student_changes(*["pondering"]*3)
self.wait(2)
class DrawSingleRadialLine(PointsWeMiss):
def construct(self):
self.add_plane()
self.background_plane.set_stroke(width = 1)
self.add_transformed_color_grid()
self.color_grid.set_stroke(width = 1)
self.add_dots()
self.draw_line()
def draw_line(self):
point = self.background_plane.coords_to_point(3, 4)
dot = Dot(point, color = RED)
line = Line(
self.plane_center,
self.background_plane.coords_to_point(15, 20),
color = WHITE,
)
added_dots = VGroup(*[
Dot(self.background_plane.coords_to_point(3*k, 4*k))
for k in (2, 3, 5)
])
added_dots.set_color(GREEN)
self.play(GrowFromCenter(dot))
self.play(Indicate(dot))
self.play(ShowCreation(line), Animation(dot))
self.wait()
self.play(LaggedStartMap(
DrawBorderThenFill, added_dots,
stroke_color = PINK,
stroke_width = 4,
run_time = 3
))
self.wait()
class DrawRadialLines(PointsWeMiss):
CONFIG = {
"final_unit_size" : 0.2,
"dot_x_range" : list(range(-4, 10)),
"dot_y_range" : list(range(-4, 10)),
"x_label_range" : list(range(-12, 40, 4)),
"y_label_range" : list(range(-4, 32, 4)),
"big_dot_radius" : 0.05,
}
def construct(self):
self.add_plane()
self.add_transformed_color_grid()
self.resize_plane()
self.add_dots()
self.create_lines()
self.show_single_line()
self.show_all_lines()
self.show_triangles()
def resize_plane(self):
everything = VGroup(*self.get_top_level_mobjects())
everything.scale(
self.final_unit_size/self.initial_unit_size,
about_point = self.plane_center
)
self.background_plane.set_stroke(width = 1)
def create_lines(self):
coord_strings = set([])
reduced_coords_yet_to_be_reached = set([])
for dot in self.dots:
point = dot.get_center()
float_coords = self.background_plane.point_to_coords(point)
coords = np.round(float_coords).astype('int')
gcd = fractions.gcd(*coords)
reduced_coords = coords/abs(gcd)
if np.all(coords == [3, 4]):
first_dot = dot
dot.coords = coords
dot.reduced_coords = reduced_coords
coord_strings.add(str(coords))
reduced_coords_yet_to_be_reached.add(str(reduced_coords))
lines = VGroup()
for dot in [first_dot] + list(self.dots):
rc_str = str(dot.reduced_coords)
if rc_str not in reduced_coords_yet_to_be_reached:
continue
reduced_coords_yet_to_be_reached.remove(rc_str)
new_dots = VGroup()
for k in range(50):
new_coords = k*dot.reduced_coords
if str(new_coords) in coord_strings:
continue
coord_strings.add(str(new_coords))
point = self.background_plane.coords_to_point(*new_coords)
if abs(point[0]) > FRAME_X_RADIUS or abs(point[1]) > FRAME_Y_RADIUS:
continue
new_dot = Dot(
point, color = GREEN,
radius = self.big_dot_radius
)
new_dots.add(new_dot)
line = Line(self.plane_center, dot.get_center())
line.scale(
FRAME_WIDTH/line.get_length(),
about_point = self.plane_center
)
line.set_stroke(width = 1)
line.seed_dot = dot.copy()
line.new_dots = new_dots
lines.add(line)
self.lines = lines
def show_single_line(self):
line = self.lines[0]
dot = line.seed_dot
self.play(
dot.scale, 2,
dot.set_color, RED
)
self.play(ReplacementTransform(dot, line))
self.wait()
self.play(LaggedStartMap(
DrawBorderThenFill, line.new_dots,
stroke_width = 4,
stroke_color = PINK,
run_time = 3,
))
self.wait()
def show_all_lines(self):
seed_dots = VGroup(*[line.seed_dot for line in self.lines])
new_dots = VGroup(*[line.new_dots for line in self.lines])
for dot in seed_dots:
dot.generate_target()
dot.target.scale(1.5)
dot.target.set_color(RED)
self.play(LaggedStartMap(
MoveToTarget, seed_dots,
run_time = 2
))
self.play(ReplacementTransform(
seed_dots, self.lines,
run_time = 3,
lag_ratio = 0.5
))
self.play(LaggedStartMap(
DrawBorderThenFill, new_dots,
stroke_width = 4,
stroke_color = PINK,
run_time = 3,
))
self.wait()
self.new_dots = new_dots
def show_triangles(self):
z_list = [
complex(9, 12),
complex(7, 24),
complex(8, 15),
complex(21, 20),
complex(36, 15),
]
triangles = self.get_triangles(z_list)
triangle = triangles[0]
self.play(FadeIn(triangle))
self.wait(2)
for new_triangle in triangles[1:]:
self.play(Transform(triangle, new_triangle))
self.wait(2)
class RationalPointsOnUnitCircle(DrawRadialLines):
CONFIG = {
"initial_unit_size" : 1.2,
"final_unit_size" : 0.4,
"plane_center" : 1.5*DOWN
}
def construct(self):
self.add_plane()
self.show_rational_points_on_unit_circle()
self.divide_by_c_squared()
self.from_rational_point_to_triple()
def add_plane(self):
added_x_coords = list(range(-4, 6, 2))
added_y_coords = list(range(-2, 4, 2))
self.x_label_range += added_x_coords
self.y_label_range += added_y_coords
DrawRadialLines.add_plane(self)
def show_rational_points_on_unit_circle(self):
circle = self.get_unit_circle()
coord_list = [
(12, 5),
(8, 15),
(7, 24),
(3, 4),
]
groups = VGroup()
for x, y in coord_list:
norm = np.sqrt(x**2 + y**2)
point = self.background_plane.coords_to_point(
x/norm, y/norm
)
dot = Dot(point, color = YELLOW)
line = Line(self.plane_center, point)
line.set_color(dot.get_color())
label = OldTex(
"{"+str(x), "\\over", str(int(norm))+"}",
"+",
"{"+str(y), "\\over", str(int(norm))+"}",
"i"
)
label.next_to(dot, UP+RIGHT, buff = 0)
label.add_background_rectangle()
group = VGroup(line, dot, label)
group.coords = (x, y)
groups.add(group)
group = groups[0].copy()
self.add(circle, self.coordinate_labels)
self.play(FadeIn(group))
self.wait()
for new_group in groups[1:]:
self.play(Transform(group, new_group))
self.wait()
self.curr_example_point_group = group
self.next_rational_point_example = groups[0]
self.unit_circle = circle
def divide_by_c_squared(self):
top_line = OldTex(
"a", "^2", "+", "b", "^2", "=", "c", "^2 \\phantom{1}"
)
top_line.shift(FRAME_X_RADIUS*RIGHT/2)
top_line.to_corner(UP + LEFT)
top_line.shift(RIGHT)
top_rect = BackgroundRectangle(top_line)
second_line = OldTex(
"\\left(", "{a", "\\over", "c}", "\\right)", "^2",
"+",
"\\left(", "{b", "\\over", "c}", "\\right)", "^2",
"=", "1"
)
second_line.move_to(top_line, UP)
second_line.shift_onto_screen()
second_rect = BackgroundRectangle(second_line)
circle_label = OldTexText(
"All $x+yi$ where \\\\",
"$x^2 + y^2 = 1$"
)
circle_label.next_to(second_line, DOWN, MED_LARGE_BUFF)
circle_label.shift_onto_screen()
circle_label.set_color_by_tex("x^2", GREEN)
circle_label.add_background_rectangle()
circle_arrow = Arrow(
circle_label.get_bottom(),
self.unit_circle.point_from_proportion(0.45),
color = GREEN
)
self.play(FadeIn(top_rect), FadeIn(top_line))
self.wait()
self.play(*[
ReplacementTransform(top_rect, second_rect)
] + [
ReplacementTransform(
top_line.get_parts_by_tex(tex, substring = False),
second_line.get_parts_by_tex(tex),
run_time = 2,
path_arc = -np.pi/3
)
for tex in ("a", "b", "c", "^2", "+", "=")
] + [
ReplacementTransform(
top_line.get_parts_by_tex("1"),
second_line.get_parts_by_tex("1"),
run_time = 2
)
] + [
Write(
second_line.get_parts_by_tex(tex),
run_time = 2,
rate_func = squish_rate_func(smooth, 0, 0.5)
)
for tex in ("(", ")", "over",)
])
self.wait(2)
self.play(Write(circle_label))
self.play(ShowCreation(circle_arrow))
self.wait(2)
self.play(FadeOut(circle_arrow))
self.algebra = VGroup(
second_rect, second_line, circle_label,
)
def from_rational_point_to_triple(self):
rational_point_group = self.next_rational_point_example
scale_factor = self.final_unit_size/self.initial_unit_size
self.play(ReplacementTransform(
self.curr_example_point_group,
rational_point_group
))
self.wait(2)
self.play(*[
ApplyMethod(
mob.scale_about_point,
scale_factor,
self.plane_center
)
for mob in [
self.background_plane,
self.coordinate_labels,
self.unit_circle,
rational_point_group,
]
] + [
Animation(self.algebra),
])
#mimic_group
point = self.background_plane.coords_to_point(
*rational_point_group.coords
)
dot = Dot(point, color = YELLOW)
line = Line(self.plane_center, point)
line.set_color(dot.get_color())
x, y = rational_point_group.coords
label = OldTex(str(x), "+", str(y), "i")
label.next_to(dot, UP+RIGHT, buff = 0)
label.add_background_rectangle()
integer_point_group = VGroup(line, dot, label)
distance_label = OldTex(
str(int(np.sqrt(x**2 + y**2)))
)
distance_label.add_background_rectangle()
distance_label.next_to(line.get_center(), UP+LEFT, SMALL_BUFF)
self.play(ReplacementTransform(
rational_point_group,
integer_point_group
))
self.play(Write(distance_label))
self.wait(2)
###
def get_unit_circle(self):
template_line = Line(*[
self.background_plane.number_to_point(z)
for z in (-1, 1)
])
circle = Circle(color = GREEN)
circle.replace(template_line, dim_to_match = 0)
return circle
class ProjectPointsOntoUnitCircle(DrawRadialLines):
def construct(self):
###
self.force_skipping()
self.add_plane()
self.add_transformed_color_grid()
self.resize_plane()
self.add_dots()
self.create_lines()
self.show_all_lines()
self.revert_to_original_skipping_status()
###
self.add_unit_circle()
self.project_all_dots()
self.zoom_in()
self.draw_infinitely_many_lines()
def add_unit_circle(self):
template_line = Line(*[
self.background_plane.number_to_point(n)
for n in (-1, 1)
])
circle = Circle(color = BLUE)
circle.replace(template_line, dim_to_match = 0)
self.play(ShowCreation(circle))
self.unit_circle = circle
def project_all_dots(self):
dots = self.dots
dots.add(*self.new_dots)
dots.sort(
lambda p : get_norm(p - self.plane_center)
)
unit_length = self.unit_circle.get_width()/2.0
for dot in dots:
dot.generate_target()
point = dot.get_center()
vect = point-self.plane_center
if np.round(vect[0], 3) == 0 and abs(vect[1]) > 2*unit_length:
dot.target.set_fill(opacity = 0)
continue
distance = get_norm(vect)
dot.target.scale(
unit_length/distance,
about_point = self.plane_center
)
dot.target.set_width(0.01)
self.play(LaggedStartMap(
MoveToTarget, dots,
run_time = 3,
lag_ratio = 0.2
))
def zoom_in(self):
target_height = 5.0
scale_factor = target_height / self.unit_circle.get_height()
group = VGroup(
self.background_plane, self.coordinate_labels,
self.color_grid,
self.lines, self.unit_circle,
self.dots,
)
self.play(
group.shift, -self.plane_center,
group.scale, scale_factor,
run_time = 2
)
self.wait(2)
def draw_infinitely_many_lines(self):
lines = VGroup(*[
Line(ORIGIN, FRAME_WIDTH*vect)
for vect in compass_directions(1000)
])
self.play(LaggedStartMap(
ShowCreation, lines,
run_time = 3
))
self.play(FadeOut(lines))
self.wait()
class ICanOnlyDrawFinitely(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"I can only \\\\ draw finitely",
run_time = 2
)
self.wait(2)
class SupposeMissingPoint(PointsWeMiss):
def construct(self):
self.add_plane()
self.background_plane.set_stroke(width = 1)
self.draw_missing_triple()
self.project_onto_unit_circle()
def draw_missing_triple(self):
point = self.background_plane.coords_to_point(12, 5)
origin = self.plane_center
line = Line(origin, point, color = WHITE)
dot = Dot(point, color = YELLOW)
triangle = Polygon(ORIGIN, RIGHT, RIGHT+UP)
triangle.set_stroke(BLUE, 2)
triangle.set_fill(BLUE, 0.5)
triangle.replace(line, stretch = True)
a = OldTex("a")
a.next_to(triangle.get_bottom(), UP, SMALL_BUFF)
b = OldTex("b")
b.add_background_rectangle()
b.next_to(triangle, RIGHT, SMALL_BUFF)
c = OldTex("c")
c.add_background_rectangle()
c.next_to(line.get_center(), UP+LEFT, SMALL_BUFF)
triangle.add(a, b, c)
words = OldTexText(
"If we missed \\\\ a triple \\dots"
)
words.add_background_rectangle()
words.next_to(dot, UP+RIGHT)
words.shift_onto_screen()
self.add(triangle, line, dot)
self.play(Write(words))
self.wait()
self.words = words
self.triangle = triangle
self.line = line
self.dot = dot
def project_onto_unit_circle(self):
dot, line = self.dot, self.line
template_line = Line(*[
self.background_plane.number_to_point(n)
for n in (-1, 1)
])
circle = Circle(color = GREEN)
circle.replace(template_line, dim_to_match = 0)
z = self.background_plane.point_to_number(dot.get_center())
z_norm = abs(z)
unit_z = z/z_norm
new_point = self.background_plane.number_to_point(unit_z)
dot.generate_target()
dot.target.move_to(new_point)
line.generate_target()
line.target.scale(1./z_norm, about_point = self.plane_center)
rational_point_word = OldTex("(a/c) + (b/c)i")
rational_point_word.next_to(
self.background_plane.coords_to_point(0, 6), RIGHT
)
rational_point_word.add_background_rectangle()
arrow = Arrow(
rational_point_word.get_bottom(),
dot.target,
buff = SMALL_BUFF
)
self.play(ShowCreation(circle))
self.add(dot.copy().fade())
self.add(line.copy().set_stroke(GREY, 1))
self.play(*list(map(MoveToTarget, [dot, line])))
self.wait()
self.play(
Write(rational_point_word),
ShowCreation(arrow)
)
self.wait(2)
class ProofTime(TeacherStudentsScene):
def construct(self):
self.teacher_says("Proof time!", target_mode = "hooray")
self.play_student_changes(*["hooray"]*3)
self.wait(2)
class FinalProof(RationalPointsOnUnitCircle):
def construct(self):
self.add_plane()
self.draw_rational_point()
self.draw_line_from_example_point()
self.show_slope_is_rational()
self.show_all_rational_slopes()
self.square_example_point()
self.project_onto_circle()
self.show_same_slope()
self.write_v_over_u_slope()
def draw_rational_point(self):
circle = self.get_unit_circle()
coords = (3./5., 4./5.)
point = self.background_plane.coords_to_point(*coords)
dot = Dot(point, color = YELLOW)
label = OldTex(
"(a/c) + (b/c)i"
)
label.add_background_rectangle()
label.next_to(dot, UP+RIGHT, buff = 0)
self.add(circle)
self.play(
Write(label, run_time = 2),
DrawBorderThenFill(dot)
)
self.wait()
self.example_dot = dot
self.example_label = label
self.unit_circle = circle
def draw_line_from_example_point(self):
neg_one_point = self.background_plane.number_to_point(-1)
neg_one_dot = Dot(neg_one_point, color = RED)
line = Line(
neg_one_point, self.example_dot.get_center(),
color = RED
)
self.play(
ShowCreation(line, run_time = 2),
Animation(self.example_label)
)
self.play(DrawBorderThenFill(neg_one_dot))
self.wait()
self.neg_one_dot = neg_one_dot
self.secant_line = line
def show_slope_is_rational(self):
p0 = self.neg_one_dot.get_center()
p1 = self.example_dot.get_center()
p_mid = p1[0]*RIGHT + p0[1]*UP
h_line = Line(p0, p_mid, color = MAROON_B)
v_line = Line(p_mid, p1, color = MAROON_B)
run_brace = Brace(h_line, DOWN)
run_text = run_brace.get_text(
"Run = $1 + \\frac{a}{c}$"
)
run_text.add_background_rectangle()
rise_brace = Brace(v_line, RIGHT)
rise_text = rise_brace.get_text("Rise = $\\frac{b}{c}$")
rise_text.add_background_rectangle()
self.play(*list(map(ShowCreation, [h_line, v_line])))
self.wait()
self.play(
GrowFromCenter(rise_brace),
FadeIn(rise_text)
)
self.wait()
self.play(
GrowFromCenter(run_brace),
FadeIn(run_text)
)
self.wait(3)
self.play(*list(map(FadeOut, [
self.example_dot, self.example_label,
self.secant_line,
h_line, v_line,
run_brace, rise_brace,
run_text, rise_text,
])))
def show_all_rational_slopes(self):
lines = VGroup()
labels = VGroup()
for u in range(2, 7):
for v in range(1, u):
if fractions.gcd(u, v) != 1:
continue
z_squared = complex(u, v)**2
unit_z_squared = z_squared/abs(z_squared)
point = self.background_plane.number_to_point(unit_z_squared)
dot = Dot(point, color = YELLOW)
line = Line(
self.background_plane.number_to_point(-1),
point,
color = self.neg_one_dot.get_color()
)
line.add(dot)
label = OldTex(
"\\text{Slope = }",
str(v), "/", str(u)
)
label.add_background_rectangle()
label.next_to(
self.background_plane.coords_to_point(1, 1.5),
RIGHT
)
lines.add(line)
labels.add(label)
line = lines[0]
label = labels[0]
self.play(
ShowCreation(line),
FadeIn(label)
)
self.wait()
for new_line, new_label in zip(lines, labels)[1:]:
self.play(
Transform(line, new_line),
Transform(label, new_label),
)
self.wait()
self.play(*list(map(FadeOut, [line, label])))
def square_example_point(self):
z = complex(2, 1)
point = self.background_plane.number_to_point(z)
uv_dot = Dot(point, color = YELLOW)
uv_label = OldTex("u", "+", "v", "i")
uv_label.add_background_rectangle()
uv_label.next_to(uv_dot, DOWN+RIGHT, buff = 0)
uv_line = Line(
self.plane_center, point,
color = YELLOW
)
uv_arc = Arc(
angle = uv_line.get_angle(),
radius = 0.75
)
uv_arc.shift(self.plane_center)
theta = OldTex("\\theta")
theta.next_to(uv_arc, RIGHT, SMALL_BUFF, DOWN)
theta.scale(0.8)
square_point = self.background_plane.number_to_point(z**2)
square_dot = Dot(square_point, color = MAROON_B)
square_label = OldTex("(u+vi)^2")
square_label.add_background_rectangle()
square_label.next_to(square_dot, RIGHT)
square_line = Line(
self.plane_center, square_point,
color = MAROON_B
)
square_arc = Arc(
angle = square_line.get_angle(),
radius = 0.65
)
square_arc.shift(self.plane_center)
two_theta = OldTex("2\\theta")
two_theta.next_to(
self.background_plane.coords_to_point(0, 1),
UP+RIGHT, SMALL_BUFF,
)
two_theta_arrow = Arrow(
two_theta.get_right(),
square_arc.point_from_proportion(0.75),
tip_length = 0.15,
path_arc = -np.pi/2,
color = WHITE,
buff = SMALL_BUFF
)
self.two_theta_group = VGroup(two_theta, two_theta_arrow)
z_to_z_squared_arrow = Arrow(
point, square_point,
path_arc = np.pi/3,
color = WHITE
)
z_to_z_squared = OldTex("z", "\\to", "z^2")
z_to_z_squared.set_color_by_tex("z", YELLOW)
z_to_z_squared.set_color_by_tex("z^2", MAROON_B)
z_to_z_squared.add_background_rectangle()
z_to_z_squared.next_to(
z_to_z_squared_arrow.point_from_proportion(0.5),
RIGHT, SMALL_BUFF
)
self.play(
Write(uv_label),
DrawBorderThenFill(uv_dot)
)
self.play(ShowCreation(uv_line))
self.play(ShowCreation(uv_arc))
self.play(Write(theta))
self.wait()
self.play(
ShowCreation(z_to_z_squared_arrow),
FadeIn(z_to_z_squared)
)
self.play(*[
ReplacementTransform(
m1.copy(), m2,
path_arc = np.pi/3
)
for m1, m2 in [
(uv_dot, square_dot),
(uv_line, square_line),
(uv_label, square_label),
(uv_arc, square_arc),
]
])
self.wait()
self.play(
Write(two_theta),
ShowCreation(two_theta_arrow)
)
self.wait(2)
self.play(FadeOut(self.two_theta_group))
self.theta_group = VGroup(uv_arc, theta)
self.uv_line = uv_line
self.uv_dot = uv_dot
self.uv_label = uv_label
self.square_line = square_line
self.square_dot = square_dot
def project_onto_circle(self):
line = self.square_line.copy()
dot = self.square_dot.copy()
self.square_line.fade()
self.square_dot.fade()
radius = self.unit_circle.get_width()/2
line.generate_target()
line.target.scale(
radius / line.get_length(),
about_point = line.get_start()
)
dot.generate_target()
dot.target.move_to(line.target.get_end())
self.play(
MoveToTarget(line),
MoveToTarget(dot),
)
self.wait()
self.play(FadeIn(self.two_theta_group))
self.wait()
self.play(FadeOut(self.two_theta_group))
self.wait(6) ##circle geometry
self.rational_point_dot = dot
def show_same_slope(self):
line = Line(
self.neg_one_dot.get_center(),
self.rational_point_dot.get_center(),
color = self.neg_one_dot.get_color()
)
theta_group_copy = self.theta_group.copy()
same_slope_words = OldTexText("Same slope")
same_slope_words.add_background_rectangle()
same_slope_words.shift(4*LEFT + 0.33*UP)
line_copies = VGroup(
line.copy(),
self.uv_line.copy()
)
line_copies.generate_target()
line_copies.target.next_to(same_slope_words, DOWN)
self.play(ShowCreation(line))
self.wait()
self.play(
theta_group_copy.shift,
line.get_start() - self.uv_line.get_start()
)
self.wait()
self.play(
Write(same_slope_words),
MoveToTarget(line_copies)
)
self.wait()
self.same_slope_words = same_slope_words
def write_v_over_u_slope(self):
p0 = self.plane_center
p1 = self.uv_dot.get_center()
p_mid = p1[0]*RIGHT + p0[1]*UP
h_line = Line(p0, p_mid, color = YELLOW)
v_line = Line(p_mid, p1, color = YELLOW)
rhs = OldTex("=", "{v", "\\over", "u}")
rhs.next_to(self.same_slope_words, RIGHT)
rect = SurroundingRectangle(VGroup(*rhs[1:]))
morty = Mortimer().flip()
morty.scale(0.5)
morty.next_to(self.same_slope_words, UP, buff = 0)
self.play(ShowCreation(h_line))
self.play(ShowCreation(v_line))
self.wait()
self.play(*[
ReplacementTransform(
self.uv_label.get_part_by_tex(tex).copy(),
rhs.get_part_by_tex(tex),
run_time = 2
)
for tex in ("u", "v")
] + [
Write(rhs.get_part_by_tex(tex))
for tex in ("=", "over")
])
self.wait(2)
self.play(
ShowCreation(rect),
FadeIn(morty)
)
self.play(PiCreatureSays(
morty, "Free to choose!",
bubble_config = {"height" : 1.5, "width" : 3},
target_mode = "hooray",
look_at = rect
))
self.play(Blink(morty))
self.wait(2)
class BitOfCircleGeometry(Scene):
def construct(self):
circle = Circle(color = BLUE, radius = 3)
p0, p1, p2 = [
circle.point_from_proportion(alpha)
for alpha in (0, 0.15, 0.55)
]
O = circle.get_center()
O_dot = Dot(O, color = WHITE)
self.add(circle, O_dot)
groups = VGroup()
for point, tex, color in (O, "2", MAROON_B), (p2, "", RED):
line1 = Line(point, p0)
line2 = Line(point, p1)
dot1 = Dot(p0)
dot2 = Dot(p1)
angle = line1.get_angle()
arc = Arc(
angle = line2.get_angle()-line1.get_angle(),
start_angle = line1.get_angle(),
radius = 0.75,
color = WHITE
)
arc.set_stroke(YELLOW, 3)
arc.shift(point)
label = OldTex(tex + "\\theta")
label.next_to(
arc.point_from_proportion(0.9), RIGHT
)
group = VGroup(line1, line2, dot1, dot2)
group.set_color(color)
group.add(arc, label)
if len(groups) == 0:
self.play(*list(map(ShowCreation, [dot1, dot2])))
self.play(*list(map(ShowCreation, [line1, line2])))
self.play(ShowCreation(arc))
self.play(FadeIn(label))
groups.add(group)
self.wait(2)
self.play(ReplacementTransform(
groups[0].copy(), groups[1]
))
self.wait(2)
class PatreonThanksTriples(PatreonThanks):
CONFIG = {
"specific_patrons" : [
"Ali Yahya",
"Burt Humburg",
"CrypticSwarm",
"David Beyer",
"Erik Sundell",
"Yana Chernobilsky",
"Kaustuv DeBiswas",
"Kathryn Schmiedicke",
"Karan Bhargava",
"Ankit Agarwal",
"Yu Jun",
"Dave Nicponski",
"Damion Kistler",
"Juan Benet",
"Othman Alikhan",
"Markus Persson",
"Yoni Nazarathy",
"Joseph John Cox",
"Dan Buchoff",
"Luc Ritchie",
"Ankalagon",
"Eric Lavault",
"Tomohiro Furusawa",
"Boris Veselinovich",
"Julian Pulgarin",
"John Haley",
"Jeff Linse",
"Suraj Pratap",
"Cooper Jones",
"Ryan Dahl",
"Ahmad Bamieh",
"Mark Govea",
"Robert Teed",
"Jason Hise",
"Meshal Alshammari",
"Bernd Sing",
"Nils Schneider",
"James Thornton",
"Mustafa Mahdi",
"Mathew Bramson",
"Jerry Ling",
"Vecht",
"Shimin Kuang",
"Rish Kundalia",
"Achille Brighton",
"Ripta Pasay",
],
}
class Thumbnail(DrawRadialLines):
def construct(self):
self.force_skipping()
self.add_plane()
self.add_transformed_color_grid()
self.color_grid.set_stroke(width = 5)
self.resize_plane()
self.add_dots()
self.create_lines()
self.show_single_line()
self.show_all_lines()
rect = Rectangle(
height = 4.3, width = 4.2,
stroke_width = 3,
stroke_color = WHITE,
fill_color = BLACK,
fill_opacity = 1,
)
rect.to_corner(UP+RIGHT, buff = 0.01)
triples = VGroup(*list(map(Tex, [
"3^2 + 4^2 = 5^2",
"5^2 + 12^2 = 13^2",
"8^2 + 15^2 = 17^2",
"\\vdots"
])))
triples.arrange(DOWN, buff = MED_LARGE_BUFF)
triples.next_to(rect.get_top(), DOWN)
self.add(rect, triples)
class Poster(DrawRadialLines):
CONFIG = {
"final_unit_size" : 0.1,
"plane_center" : ORIGIN,
}
def construct(self):
self.force_skipping()
self.add_plane()
self.add_transformed_color_grid()
self.color_grid.set_stroke(width = 5)
self.resize_plane()
self.add_dots()
self.create_lines()
self.show_single_line()
self.show_all_lines()
for dot_group in self.dots, self.new_dots:
for dot in dot_group.family_members_with_points():
dot.scale(0.5)
self.remove(self.coordinate_labels)
# rect = Rectangle(
# height = 4.3, width = 4.2,
# stroke_width = 3,
# stroke_color = WHITE,
# fill_color = BLACK,
# fill_opacity = 1,
# )
# rect.to_corner(UP+RIGHT, buff = 0.01)
# triples = VGroup(*map(Tex, [
# "3^2 + 4^2 = 5^2",
# "5^2 + 12^2 = 13^2",
# "8^2 + 15^2 = 17^2",
# "\\vdots"
# ]))
# triples.arrange(DOWN, buff = MED_LARGE_BUFF)
# triples.next_to(rect.get_top(), DOWN)
# self.add(rect, triples)
|
videos_3b1b/_2017/gradient.py
| "from manim_imports_ext import *\n\n\n# Warning, this file uses ContinualChangingDecimal,\n# which h(...TRUNCATED) |
videos_3b1b/_2017/highD.py
| "from manim_imports_ext import *\n\n##########\n#force_skipping\n#revert_to_original_skipping_status(...TRUNCATED) |
videos_3b1b/_2017/qa_round_two.py
| "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom manim_imports_ext import *\nfrom _2017.efvgt(...TRUNCATED) |
videos_3b1b/_2017/efvgt.py
| "from manim_imports_ext import *\n\nADDER_COLOR = GREEN\nMULTIPLIER_COLOR = YELLOW\n\ndef normalize((...TRUNCATED) |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- -