Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

middle of massive restructure, everything still broken

Grant Sanderson2e074afb60d1
diff --git a/__init__.py b/__init__.py
index 7718a95cd..33c2412e9 100644
--- a/__init__.py
+++ b/__init__.py
@@ -1,10 +1,13 @@
from animation import *
-from mobject import *
from scene import *
-from scripts import *
+from topics import *
from constants import *
-from helpers import *
from displayer import *
+from extract_scene import *
+from helpers import *
+from image_mobject import *
+from mobject import *
+from old_proje import *
+from playground import *
from region import *
-from script_wrapper import *
-from tex_utils import *
\ No newline at end of file
+from tex_utils import *
diff --git a/animation/__init__.py b/animation/__init__.py
index 598695687..2ae2b51bf 100644
--- a/animation/__init__.py
+++ b/animation/__init__.py
@@ -1,3 +1,4 @@
from animation import *
-from transform import *
-from simple_animations import *
\ No newline at end of file
+from meta_animations import *
+from simple_animations import *
+from transform import *
\ No newline at end of file
diff --git a/animation/animation.py b/animation/animation.py
index ff13d6948..7bb31ac97 100644
--- a/animation/animation.py
+++ b/animation/animation.py
@@ -7,11 +7,10 @@ import os
import copy
import progressbar
import inspect
-from images2gif import writeGif
from helpers import *
-from constants import *
-from mobject import Mobject, Point
+from mobject import Mobject
+from topics.geometry import Point
class Animation(object):
DEFAULT_CONFIG = {
@@ -119,4 +118,3 @@ class Animation(object):
-
diff --git a/animation/meta_animations.py b/animation/meta_animations.py
new file mode 100644
index 000000000..f452f7554
--- /dev/null
+++ b/animation/meta_animations.py
@@ -0,0 +1,95 @@
+import numpy as np
+import itertools as it
+from copy import deepcopy
+
+from helpers import *
+from animation import Animation
+from transform import Transform
+
+
+class DelayByOrder(Animation):
+ """
+ Modifier of animation.
+
+ Warning: This will not work on all animation types, but
+ when it does, it will be pretty cool
+ """
+ DEFAULT_CONFIG = {
+ "max_power" : 5
+ }
+ def __init__(self, animation, **kwargs):
+ digest_config(self, DelayByOrder, kwargs, locals())
+ kwargs.update(dict([
+ (attr, getattr(animation, attr))
+ for attr in Animation.DEFAULT_CONFIG
+ ]))
+ self.num_mobject_points = animation.mobject.get_num_points()
+ Animation.__init__(self, animation.mobject, **kwargs)
+ self.name = self.__class__.__name__ + str(self.animation)
+
+ def update_mobject(self, alpha):
+ dim = self.mobject.DIM
+ alpha_array = np.array([
+ [alpha**power]*dim
+ for n in range(self.num_mobject_points)
+ for prop in [(n+1.0)/self.num_mobject_points]
+ for power in [1+prop*(self.max_power-1)]
+ ])
+ self.animation.update_mobject(alpha_array)
+
+
+
+class TransformAnimations(Transform):
+ DEFAULT_CONFIG = {
+ "alpha_func" : squish_alpha_func(smooth)
+ }
+ def __init__(self, start_anim, end_anim, **kwargs):
+ digest_config(self, TransformAnimations, kwargs, locals())
+ if "run_time" in kwargs:
+ self.run_time = kwargs.pop("run_time")
+ else:
+ self.run_time = max(start_anim.run_time, end_anim.run_time)
+ for anim in start_anim, end_anim:
+ anim.set_run_time(self.run_time)
+
+ if start_anim.starting_mobject.get_num_points() != end_anim.starting_mobject.get_num_points():
+ Mobject.align_data(start_anim.starting_mobject, end_anim.starting_mobject)
+ for anim in start_anim, end_anim:
+ if hasattr(anim, "ending_mobject"):
+ Mobject.align_data(anim.starting_mobject, anim.ending_mobject)
+
+ Transform.__init__(self, start_anim.mobject, end_anim.mobject, **kwargs)
+ #Rewire starting and ending mobjects
+ start_anim.mobject = self.starting_mobject
+ end_anim.mobject = self.ending_mobject
+
+ def update(self, alpha):
+ self.start_anim.update(alpha)
+ self.end_anim.update(alpha)
+ Transform.update(self, alpha)
+
+
+class Succession(Animation):
+ def __init__(self, *animations, **kwargs):
+ if "run_time" in kwargs:
+ run_time = kwargs.pop("run_time")
+ else:
+ run_time = sum([anim.run_time for anim in animations])
+ self.num_anims = len(animations)
+ self.anims = animations
+ mobject = animations[0].mobject
+ Animation.__init__(self, mobject, run_time = run_time, **kwargs)
+
+ def __str__(self):
+ return self.__class__.__name__ + \
+ "".join(map(str, self.anims))
+
+ def update(self, alpha):
+ scaled_alpha = alpha*self.num_anims
+ self.mobject = self.anims
+ for index in range(len(self.anims)):
+ self.anims[index].update(scaled_alpha - index)
+
+
+
+
diff --git a/animation/simple_animations.py b/animation/simple_animations.py
index e1f10fb7c..0c7c60698 100644
--- a/animation/simple_animations.py
+++ b/animation/simple_animations.py
@@ -2,42 +2,12 @@ import numpy as np
import itertools as it
from copy import deepcopy
-from animation import Animation
-from transform import Transform
-from mobject import *
-from constants import *
from helpers import *
+from animation import Animation
+from meta_animations import DelayByOrder
+from transform import Transform
-class DelayByOrder(Animation):
- """
- Modifier of animation.
-
- Warning: This will not work on all animation types, but
- when it does, it will be pretty cool
- """
- DEFAULT_CONFIG = {
- "max_power" : 5
- }
- def __init__(self, animation, **kwargs):
- digest_config(self, DelayByOrder, kwargs, locals())
- kwargs.update(dict([
- (attr, getattr(animation, attr))
- for attr in Animation.DEFAULT_CONFIG
- ]))
- self.num_mobject_points = animation.mobject.get_num_points()
- Animation.__init__(self, animation.mobject, **kwargs)
- self.name = self.__class__.__name__ + str(self.animation)
-
- def update_mobject(self, alpha):
- dim = self.mobject.DIM
- alpha_array = np.array([
- [alpha**power]*dim
- for n in range(self.num_mobject_points)
- for prop in [(n+1.0)/self.num_mobject_points]
- for power in [1+prop*(self.max_power-1)]
- ])
- self.animation.update_mobject(alpha_array)
class Rotating(Animation):
DEFAULT_CONFIG = {
@@ -55,17 +25,6 @@ class Rotating(Animation):
for axis in self.axes:
self.mobject.rotate(self.radians * alpha, axis)
-class RotationAsTransform(Rotating):
- DEFAULT_CONFIG = {
- "axes" : [OUT],
- "radians" : np.pi / 2,
- "run_time" : DEFAULT_ANIMATION_RUN_TIME,
- "alpha_func" : smooth,
- }
- def __init__(self, mobject, **kwargs):
- digest_config(self, RotationAsTransform, kwargs, locals())
- Rotating.__init__(self, mobject, **kwargs)
-
class FadeOut(Animation):
def update_mobject(self, alpha):
self.mobject.rgbs = self.starting_mobject.rgbs * (1 - alpha)
@@ -136,96 +95,6 @@ class Homotopy(Animation):
for x, y, z in self.starting_mobject.points
])
-class ComplexHomotopy(Homotopy):
- def __init__(self, complex_homotopy, **kwargs):
- """
- Complex Hootopy a function (z, t) to z'
- """
- def homotopy((x, y, z, t)):
- c = complex_homotopy((complex(x, y), t))
- return (c.real, c.imag, z)
- if len(args) > 0:
- args = list(args)
- mobject = args.pop(0)
- elif "mobject" in kwargs:
- mobject = kwargs["mobject"]
- else:
- mobject = Grid()
- Homotopy.__init__(self, homotopy, mobject, *args, **kwargs)
- self.name = "ComplexHomotopy" + \
- to_cammel_case(complex_homotopy.__name__)
-
-class Succession(Animation):
- def __init__(self, *animations, **kwargs):
- if "run_time" in kwargs:
- run_time = kwargs.pop("run_time")
- else:
- run_time = sum([anim.run_time for anim in animations])
- self.num_anims = len(animations)
- self.anims = animations
- mobject = animations[0].mobject
- Animation.__init__(self, mobject, run_time = run_time, **kwargs)
-
- def __str__(self):
- return self.__class__.__name__ + \
- "".join(map(str, self.anims))
-
- def update(self, alpha):
- scaled_alpha = alpha*self.num_anims
- self.mobject = self.anims
- for index in range(len(self.anims)):
- self.anims[index].update(scaled_alpha - index)
-
-####### Pi Creature Stuff #############
-
-class WalkPiCreature(Animation):
- def __init__(self, pi_creature, destination, *args, **kwargs):
- self.final = deepcopy(pi_creature).move_to(destination)
- self.middle = pi_creature.get_step_intermediate(self.final)
- Animation.__init__(self, pi_creature, *args, **kwargs)
-
- def update_mobject(self, alpha):
- if alpha < 0.5:
- Mobject.interpolate(
- self.starting_mobject,
- self.middle,
- self.mobject,
- 2*alpha
- )
- else:
- Mobject.interpolate(
- self.middle,
- self.final,
- self.mobject,
- 2*alpha - 1
- )
-
-
-class BlinkPiCreature(Transform):
- def __init__(self, pi_creature, *args, **kwargs):
- blinked = deepcopy(pi_creature).blink()
- Transform.__init__(
- self, pi_creature, blinked,
- alpha_func = squish_alpha_func(there_and_back),
- *args, **kwargs
- )
-
-
-class WaveArm(Transform):
- def __init__(self, pi_creature, *args, **kwargs):
- final = deepcopy(pi_creature)
- body_to_arm = pi_creature.arm.get_center()-pi_creature.get_center()
- if body_to_arm[0] < 0:
- wag_direction = LEFT
- else:
- wag_direction = RIGHT
- final.arm.wag(0.7*UP, wag_direction, 2.0)
- final.rewire_part_attributes(self_from_parts = True)
- Transform.__init__(
- self, pi_creature, final,
- alpha_func = there_and_back,
- *args, **kwargs
- )
diff --git a/animation/transform.py b/animation/transform.py
index 169cc5360..692ad3dcd 100644
--- a/animation/transform.py
+++ b/animation/transform.py
@@ -4,39 +4,12 @@ import inspect
import copy
import warnings
-from animation import Animation
-from mobject import Mobject, Point, ComplexPlane
-from constants import *
from helpers import *
-def straight_path(start_points, end_points, alpha):
- return (1-alpha)*start_points + alpha*end_points
-
-def path_along_arc(arc_angle):
- """
- If vect is vector from start to end, [vect[:,1], -vect[:,0]] is
- perpendicualr to vect in the left direction.
- """
- if arc_angle == 0:
- return straight_path
- def path(start_points, end_points, alpha):
- vects = end_points - start_points
- centers = start_points + 0.5*vects
- if arc_angle != np.pi:
- for i, b in [(0, -1), (1, 1)]:
- centers[:,i] += 0.5*b*vects[:,1-i]/np.tan(arc_angle/2)
- return centers + np.dot(
- start_points-centers,
- np.transpose(rotation_about_z(alpha*arc_angle))
- )
- return path
-
-def clockwise_path():
- return path_along_arc(np.pi)
-
-def counterclockwise_path():
- return path_along_arc(-np.pi)
-
+from animation import Animation
+from mobject import Mobject
+from topics.geometry import Point
+from topics.complex_numbers import ComplexPlane
class Transform(Animation):
DEFAULT_CONFIG = {
@@ -137,6 +110,12 @@ class ApplyMethod(Transform):
**kwargs
)
+class Rotate(ApplyMethod):
+ def __init__(self, mobject, angle = np.pi, **kwargs):
+ kwargs["interpolation_function"] = path_along_arc(angle)
+ ApplyMethod.__init__(self, mobject.rotate, angle, **kwargs)
+
+
class ApplyPointwiseFunction(ApplyMethod):
DEFAULT_CONFIG = {
"run_time" : DEFAULT_POINTWISE_FUNCTION_RUN_TIME
@@ -147,20 +126,6 @@ class ApplyPointwiseFunction(ApplyMethod):
self, mobject.apply_function, function, **kwargs
)
-
-class ComplexFunction(ApplyPointwiseFunction):
- def __init__(self, function, mobject = ComplexPlane, **kwargs):
- if "interpolation_function" not in kwargs:
- self.interpolation_function = path_along_arc(
- np.log(function(complex(1))).imag
- )
- ApplyPointwiseFunction.__init__(
- self,
- lambda (x, y, z) : complex_to_R3(function(complex(x, y))),
- instantiate(mobject),
- **kwargs
- )
-
class FadeToColor(ApplyMethod):
def __init__(self, mobject, color, **kwargs):
ApplyMethod.__init__(self, mobject.highlight, color, **kwargs)
@@ -200,35 +165,6 @@ class ApplyMatrix(Animation):
)
-class TransformAnimations(Transform):
- DEFAULT_CONFIG = {
- "alpha_func" : squish_alpha_func(smooth)
- }
- def __init__(self, start_anim, end_anim, **kwargs):
- digest_config(self, TransformAnimations, kwargs, locals())
- if "run_time" in kwargs:
- self.run_time = kwargs.pop("run_time")
- else:
- self.run_time = max(start_anim.run_time, end_anim.run_time)
- for anim in start_anim, end_anim:
- anim.set_run_time(self.run_time)
-
- if start_anim.starting_mobject.get_num_points() != end_anim.starting_mobject.get_num_points():
- Mobject.align_data(start_anim.starting_mobject, end_anim.starting_mobject)
- for anim in start_anim, end_anim:
- if hasattr(anim, "ending_mobject"):
- Mobject.align_data(anim.starting_mobject, anim.ending_mobject)
-
- Transform.__init__(self, start_anim.mobject, end_anim.mobject, **kwargs)
- #Rewire starting and ending mobjects
- start_anim.mobject = self.starting_mobject
- end_anim.mobject = self.ending_mobject
-
- def update(self, alpha):
- self.start_anim.update(alpha)
- self.end_anim.update(alpha)
- Transform.update(self, alpha)
-
diff --git a/displayer.py b/displayer.py
index 690e35ec8..8d9606b3d 100644
--- a/displayer.py
+++ b/displayer.py
@@ -8,8 +8,7 @@ import cv2
from colour import Color
import progressbar
-from mobject import *
-from constants import *
+from helpers import *
FFMPEG_BIN = "ffmpeg"
@@ -136,19 +135,6 @@ def get_file_path(name, extension):
os.makedirs(directory)
return file_path
-def write_to_gif(scene, name):
- #TODO, find better means of compression
- if not name.endswith(".gif"):
- name += ".gif"
- file_path = os.path.join(GIF_DIR, name)
- temppath = os.path.join(GIF_DIR, "Temp.gif")
- print "Writing " + name + "..."
- images = [Image.fromarray(frame) for frame in scene.frames]
- writeGif(temppath, images, scene.frame_duration)
- print "Compressing..."
- os.system("gifsicle -O " + temppath + " > " + file_path)
- os.system("rm " + temppath)
-
def write_to_movie(scene, name):
file_path = get_file_path(name, ".mp4")
print "Writing to %s"%file_path
diff --git a/script_wrapper.py b/extract_scene.py
similarity index 89%
rename from script_wrapper.py
rename to extract_scene.py
index cf7db0324..c909271bb 100644
--- a/script_wrapper.py
+++ b/extract_scene.py
@@ -1,13 +1,15 @@
+#!/usr/bin/env python
+
import sys
import getopt
import imp
import itertools as it
import inspect
import traceback
-from helpers import cammel_case_initials
-from scene import Scene
+import imp
-from constants import *
+from helpers import *
+from scene import Scene
HELP_MESSAGE = """
<script name> [<scene name or initials>] [<arg_string>]
@@ -35,6 +37,7 @@ def get_configuration(sys_argv):
print str(err)
sys.exit(2)
config = {
+ "module" : None,
"scene_name" : "",
"args_extension" : "",
"display_config" : PRODUCTION_QUALITY_DISPLAY_CONFIG,
@@ -70,9 +73,11 @@ def get_configuration(sys_argv):
config["write"] = True
if len(args) > 0:
- config["scene_name"] = args[0]
+ config["module"] = args[0]
if len(args) > 1:
- config["args_extension"] = " ".join(args[1:])
+ config["scene_name"] = args[1]
+ if len(args) > 2:
+ config["args_extension"] = " ".join(args[2:])
return config
def handle_scene(scene, **config):
@@ -120,7 +125,7 @@ def prompt_user_for_args(args_list, args_to_string):
print INVALID_NUMBER_MESSAGE
sys.exit()
-def get_args(SceneClass, config):
+def get_scene_args(SceneClass, config):
tuplify = lambda x : x if type(x) == tuple else (x,)
args_list = map(tuplify, SceneClass.args_list)
preset_extensions = [
@@ -146,11 +151,13 @@ def get_args(SceneClass, config):
else:
return [SceneClass.string_to_args(config["args_extension"])]
-def command_line_create_scene(movie_prefix = ""):
- script = sys.modules["__main__"]
- scene_names_to_classes = dict(inspect.getmembers(script, is_scene))
+def main():
config = get_configuration(sys.argv)
- config["movie_prefix"] = movie_prefix
+ module = imp.load_source(config["module_name"], ".")
+ scene_names_to_classes = dict(
+ inspect.getmembers(module, is_scene)
+ )
+ config["movie_prefix"] = config["module_name"].split(".py")[0]
if config["scene_name"] in scene_names_to_classes:
scene_classes = [scene_names_to_classes[config["scene_name"]] ]
elif config["scene_name"] == "" and config["write_all"]:
@@ -164,7 +171,7 @@ def command_line_create_scene(movie_prefix = ""):
"announce_construction" : True
}
for SceneClass in scene_classes:
- for args in get_args(SceneClass, config):
+ for args in get_scene_args(SceneClass, config):
scene_kwargs["construct_args"] = args
try:
handle_scene(SceneClass(**scene_kwargs), **config)
@@ -174,7 +181,8 @@ def command_line_create_scene(movie_prefix = ""):
print "\n\n"
-
+if __name__ == "__main__":
+ main()
diff --git a/helpers.py b/helpers.py
index 0ce0e318c..8382c7be3 100644
--- a/helpers.py
+++ b/helpers.py
@@ -93,6 +93,38 @@ def random_color():
color.set_rgb([1 - 0.5 * random() for x in range(3)])
return color
+
+################################################
+
+def straight_path(start_points, end_points, alpha):
+ return (1-alpha)*start_points + alpha*end_points
+
+def path_along_arc(arc_angle):
+ """
+ If vect is vector from start to end, [vect[:,1], -vect[:,0]] is
+ perpendicualr to vect in the left direction.
+ """
+ if arc_angle == 0:
+ return straight_path
+ def path(start_points, end_points, alpha):
+ vects = end_points - start_points
+ centers = start_points + 0.5*vects
+ if arc_angle != np.pi:
+ for i, b in [(0, -1), (1, 1)]:
+ centers[:,i] += 0.5*b*vects[:,1-i]/np.tan(arc_angle/2)
+ return centers + np.dot(
+ start_points-centers,
+ np.transpose(rotation_about_z(alpha*arc_angle))
+ )
+ return path
+
+def clockwise_path():
+ return path_along_arc(np.pi)
+
+def counterclockwise_path():
+ return path_along_arc(-np.pi)
+
+
################################################
def to_cammel_case(name):
diff --git a/mobject/image_mobject.py b/image_mobject.py
similarity index 88%
rename from mobject/image_mobject.py
rename to image_mobject.py
index af581e3f0..60ef2a924 100644
--- a/mobject/image_mobject.py
+++ b/image_mobject.py
@@ -4,8 +4,8 @@ import os
from PIL import Image
from random import random
-from tex_utils import *
-from mobject import *
+from tex_utils import tex_to_image
+from mobject import Mobject
class ImageMobject(Mobject):
"""
@@ -98,26 +98,6 @@ class ImageMobject(Mobject):
points *= 2 * SPACE_WIDTH / width
self.add_points(points, rgbs = rgbs)
-class Face(ImageMobject):
- DEFAULT_CONFIG = {
- "mode" : "simple",
- "scale_value" : 0.5
- }
- def __init__(self, **kwargs):
- """
- Mode can be "simple", "talking", "straight"
- """
- digest_config(self, Face, kwargs)
- ImageMobject.__init__(self, self.mode + "_face", **kwargs)
-
-class VideoIcon(ImageMobject):
- DEFAULT_CONFIG = {
- "scale_value" : 0.3
- }
- def __init__(self, **kwargs):
- digest_config(self, VideoIcon, kwargs)
- ImageMobject.__init__(self, "video_icon", **kwargs)
-
#TODO, Make both of these proper mobject classes
def text_mobject(text, size = None):
size = size or "\\Large" #TODO, auto-adjust?
diff --git a/images2gif.py b/images2gif.py
deleted file mode 100644
index ed54366af..000000000
--- a/images2gif.py
+++ /dev/null
@@ -1,845 +0,0 @@
-# -*- coding: utf-8 -*-
-# Copyright (c) 2010, Almar Klein, Ant1, Marius van Voorden
-#
-# This code is subject to the (new) BSD license:
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-# * Neither the name of the <organization> nor the
-# names of its contributors may be used to endorse or promote products
-# derived from this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
-# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-""" Module images2gif
-
-Provides functionality for reading and writing animated GIF images.
-Use writeGif to write a series of numpy arrays or PIL images as an
-animated GIF. Use readGif to read an animated gif as a series of numpy
-arrays.
-
-Acknowledgements
-----------------
-
-Many thanks to Ant1 for:
-* noting the use of "palette=PIL.Image.ADAPTIVE", which significantly
- improves the results.
-* the modifications to save each image with its own palette, or optionally
- the global palette (if its the same).
-
-Many thanks to Marius van Voorden for porting the NeuQuant quantization
-algorithm of Anthony Dekker to Python (See the NeuQuant class for its
-license).
-
-This code is based on gifmaker (in the scripts folder of the source
-distribution of PIL)
-
-Some implementation details are ased on gif file structure as provided
-by wikipedia.
-
-"""
-
-import os
-import progressbar
-
-try:
- import PIL
- from PIL import Image, ImageChops
- from PIL.GifImagePlugin import getheader, getdata
-except ImportError:
- PIL = None
-
-try:
- import numpy as np
-except ImportError:
- np = None
-
-try:
- from scipy.spatial import cKDTree
-except ImportError:
- cKDTree = None
-
-# getheader gives a 87a header and a color palette (two elements in a list).
-# getdata()[0] gives the Image Descriptor up to (including) "LZW min code size".
-# getdatas()[1:] is the image data itself in chuncks of 256 bytes (well
-# technically the first byte says how many bytes follow, after which that
-# amount (max 255) follows).
-
-def checkImages(images):
- """ checkImages(images)
- Check numpy images and correct intensity range etc.
- The same for all movie formats.
- """
- # Init results
- images2 = []
-
- for im in images:
- if PIL and isinstance(im, PIL.Image.Image):
- # We assume PIL images are allright
- images2.append(im)
-
- elif np and isinstance(im, np.ndarray):
- # Check and convert dtype
- if im.dtype == np.uint8:
- images2.append(im) # Ok
- elif im.dtype in [np.float32, np.float64]:
- im = im.copy()
- im[im<0] = 0
- im[im>1] = 1
- im *= 255
- images2.append( im.astype(np.uint8) )
- else:
- im = im.astype(np.uint8)
- images2.append(im)
- # Check size
- if im.ndim == 2:
- pass # ok
- elif im.ndim == 3:
- if im.shape[2] not in [3,4]:
- raise ValueError('This array can not represent an image.')
- else:
- raise ValueError('This array can not represent an image.')
- else:
- raise ValueError('Invalid image type: ' + str(type(im)))
-
- # Done
- return images2
-
-
-def intToBin(i):
- """ Integer to two bytes """
- # devide in two parts (bytes)
- i1 = i % 256
- i2 = int( i/256)
- # make string (little endian)
- return chr(i1) + chr(i2)
-
-
-def getheaderAnim(im):
- """ Animation header. To replace the getheader()[0] """
- bb = "GIF89a"
- bb += intToBin(im.size[0])
- bb += intToBin(im.size[1])
- bb += "\x87\x00\x00"
- return bb
-
-
-def getImageDescriptor(im):
- """ Used for the local color table properties per image.
- Otherwise global color table applies to all frames irrespective of
- wether additional colours comes in play that require a redefined palette
- Still a maximum of 256 color per frame, obviously.
-
- Written by Ant1 on 2010-08-22
- """
- bb = '\x2C' # Image separator,
- bb += intToBin( 0 ) # Left position
- bb += intToBin( 0 ) # Top position
- bb += intToBin( im.size[0] ) # image width
- bb += intToBin( im.size[1] ) # image height
- bb += '\x87' # packed field : local color table flag1, interlace0, sorted table0, reserved00, lct size111=7=2^(7+1)=256.
- # LZW minimum size code now comes later, begining of [image data] blocks
- return bb
-
-
-#def getAppExt(loops=float('inf')):
-#compile error commented by zcwang
-def getAppExt(loops=float(0)):
- """ Application extention. Part that specifies amount of loops.
- If loops is inf, it goes on infinitely.
- """
- if loops == 0:
- loops = 2**16-1
- #bb = "" # application extension should not be used
- # (the extension interprets zero loops
- # to mean an infinite number of loops)
- # Mmm, does not seem to work
- if True:
- bb = "\x21\xFF\x0B" # application extension
- bb += "NETSCAPE2.0"
- bb += "\x03\x01"
-# if loops == float('inf'):
- if loops == float(0):
- loops = 2**16-1
- bb += intToBin(loops)
- bb += '\x00' # end
- return bb
-
-
-def getGraphicsControlExt(duration=0.1):
- """ Graphics Control Extension. A sort of header at the start of
- each image. Specifies transparancy and duration. """
- bb = '\x21\xF9\x04'
- bb += '\x08' # no transparancy
- bb += intToBin( int(duration*100) ) # in 100th of seconds
- bb += '\x00' # no transparant color
- bb += '\x00' # end
- return bb
-
-
-def _writeGifToFile(fp, images, durations, loops):
- """ Given a set of images writes the bytes to the specified stream.
- """
- # Obtain palette for all images and count each occurance
- palettes, occur = [], []
- for im in images:
- palettes.append( getheader(im)[1] )
- for palette in palettes:
- occur.append( palettes.count( palette ) )
-
- # Select most-used palette as the global one (or first in case no max)
- globalPalette = palettes[ occur.index(max(occur)) ]
-
- # Init
- frames = 0
- firstFrame = True
-
-
- for im, palette in zip(images, palettes):
- if firstFrame:
- # Write header
-
- # Gather info
- header = getheaderAnim(im)
- appext = getAppExt(loops)
-
- # Write
- fp.write(header)
- fp.write(globalPalette)
- fp.write(appext)
-
- # Next frame is not the first
- firstFrame = False
-
- if True:
- # Write palette and image data
-
- # Gather info
- data = getdata(im)
- imdes, data = data[0], data[1:]
- graphext = getGraphicsControlExt(durations[frames])
- # Make image descriptor suitable for using 256 local color palette
- lid = getImageDescriptor(im)
-
- # Write local header
- if palette != globalPalette:
- # Use local color palette
- fp.write(graphext)
- fp.write(lid) # write suitable image descriptor
- fp.write(palette) # write local color table
- fp.write('\x08') # LZW minimum size code
- else:
- # Use global color palette
- fp.write(graphext)
- fp.write(imdes) # write suitable image descriptor
-
- # Write image data
- for d in data:
- fp.write(d)
-
- # Prepare for next round
- frames = frames + 1
-
- fp.write(";") # end gif
- return frames
-
-
-## Exposed functions
-
-def writeGif(filename, images, duration=0.1, repeat=True, dither=False, nq=0):
- """ writeGif(filename, images, duration=0.1, repeat=True, dither=False)
-
- Write an animated gif from the specified images.
-
- Parameters
- ----------
- filename : string
- The name of the file to write the image to.
- images : list
- Should be a list consisting of PIL images or numpy arrays.
- The latter should be between 0 and 255 for integer types, and
- between 0 and 1 for float types.
- duration : scalar or list of scalars
- The duration for all frames, or (if a list) for each frame.
- repeat : bool or integer
- The amount of loops. If True, loops infinitetely.
- dither : bool
- Whether to apply dithering
- nq : integer
- If nonzero, applies the NeuQuant quantization algorithm to create
- the color palette. This algorithm is superior, but slower than
- the standard PIL algorithm. The value of nq is the quality
- parameter. 1 represents the best quality. 10 is in general a
- good tradeoff between quality and speed.
-
- """
- progress_bar = progressbar.ProgressBar(maxval=len(images))
- progress_bar.start()
-
- # Check PIL
- if PIL is None:
- raise RuntimeError("Need PIL to write animated gif files.")
-
- # Check images
- images = checkImages(images)
-
- # Check loops
- if repeat is False:
- loops = 1
- elif repeat is True:
- loops = 0 # zero means infinite
- else:
- loops = int(repeat)
-
- # Convert to PIL images
- images2 = []
- for im in images:
- if isinstance(im, Image.Image):
- images2.append(im)
- elif np and isinstance(im, np.ndarray):
- if im.ndim==3 and im.shape[2]==3:
- im = Image.fromarray(im,'RGB')
- elif im.ndim==2:
- im = Image.fromarray(im,'L')
- images2.append(im)
-
- # Convert to paletted PIL images
- images, images2 = images2, []
- if nq >= 1:
- # NeuQuant algorithm
- for im in images:
- im = im.convert("RGBA") # NQ assumes RGBA
- NQ = NeuQuant(im, int(nq)) # Learn colors from image
- if dither:
- im = im.convert("RGB").quantize(palette=NQ.paletteImage())
- else:
- im = NQ.quantize(im) # Use to quantize the image itself
- images2.append(im)
- else:
- # Adaptive PIL algorithm
- AD = Image.ADAPTIVE
- count = 0
- for im in images:
- progress_bar.update(count)
- count += 1
- im = im.convert('P', palette=AD, dither=dither)
- images2.append(im)
-
- # Check duration
- if hasattr(duration, '__len__'):
- if len(duration) == len(images2):
- durations = [d for d in duration]
- else:
- raise ValueError("len(duration) doesn't match amount of images.")
- else:
- duration = [duration for im in images2]
-
- # Open file
- fp = open(filename, 'wb')
-
- # Write
- try:
- n = _writeGifToFile(fp, images2, duration, loops)
- finally:
- fp.close()
- progress_bar.finish()
-
-
-def readGif(filename, asNumpy=True):
- """ readGif(filename, asNumpy=True)
-
- Read images from an animated GIF file. Returns a list of numpy
- arrays, or, if asNumpy is false, a list if PIL images.
-
- """
-
- # Check PIL
- if PIL is None:
- raise RuntimeError("Need PIL to read animated gif files.")
-
- # Check Numpy
- if np is None:
- raise RuntimeError("Need Numpy to read animated gif files.")
-
- # Check whether it exists
- if not os.path.isfile(filename):
- raise IOError('File not found: '+str(filename))
-
- # Load file using PIL
- pilIm = PIL.Image.open(filename)
- pilIm.seek(0)
-
- # Read all images inside
- images = []
- try:
- while True:
- # Get image as numpy array
- tmp = pilIm.convert() # Make without palette
- a = np.asarray(tmp)
- if len(a.shape)==0:
- raise MemoryError("Too little memory to convert PIL image to array")
- # Store, and next
- images.append(a)
- pilIm.seek(pilIm.tell()+1)
- except EOFError:
- pass
-
- # Convert to normal PIL images if needed
- if not asNumpy:
- images2 = images
- images = []
- for im in images2:
- images.append( PIL.Image.fromarray(im) )
-
- # Done
- return images
-
-
-class NeuQuant:
- """ NeuQuant(image, samplefac=10, colors=256)
-
- samplefac should be an integer number of 1 or higher, 1
- being the highest quality, but the slowest performance.
- With avalue of 10, one tenth of all pixels are used during
- training. This value seems a nice tradeof between speed
- and quality.
-
- colors is the amount of colors to reduce the image to. This
- should best be a power of two.
-
- See also:
- http://members.ozemail.com.au/~dekker/NEUQUANT.HTML
-
- License of the NeuQuant Neural-Net Quantization Algorithm
- ---------------------------------------------------------
-
- Copyright (c) 1994 Anthony Dekker
- Ported to python by Marius van Voorden in 2010
-
- NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994.
- See "Kohonen neural networks for optimal colour quantization"
- in "network: Computation in Neural Systems" Vol. 5 (1994) pp 351-367.
- for a discussion of the algorithm.
- See also http://members.ozemail.com.au/~dekker/NEUQUANT.HTML
-
- Any party obtaining a copy of these files from the author, directly or
- indirectly, is granted, free of charge, a full and unrestricted irrevocable,
- world-wide, paid up, royalty-free, nonexclusive right and license to deal
- in this software and documentation files (the "Software"), including without
- limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
- and/or sell copies of the Software, and to permit persons who receive
- copies from any such party to do so, with the only requirement being
- that this copyright notice remain intact.
-
- """
-
- NCYCLES = None # Number of learning cycles
- NETSIZE = None # Number of colours used
- SPECIALS = None # Number of reserved colours used
- BGCOLOR = None # Reserved background colour
- CUTNETSIZE = None
- MAXNETPOS = None
-
- INITRAD = None # For 256 colours, radius starts at 32
- RADIUSBIASSHIFT = None
- RADIUSBIAS = None
- INITBIASRADIUS = None
- RADIUSDEC = None # Factor of 1/30 each cycle
-
- ALPHABIASSHIFT = None
- INITALPHA = None # biased by 10 bits
-
- GAMMA = None
- BETA = None
- BETAGAMMA = None
-
- network = None # The network itself
- colormap = None # The network itself
-
- netindex = None # For network lookup - really 256
-
- bias = None # Bias and freq arrays for learning
- freq = None
-
- pimage = None
-
- # Four primes near 500 - assume no image has a length so large
- # that it is divisible by all four primes
- PRIME1 = 499
- PRIME2 = 491
- PRIME3 = 487
- PRIME4 = 503
- MAXPRIME = PRIME4
-
- pixels = None
- samplefac = None
-
- a_s = None
-
-
- def setconstants(self, samplefac, colors):
- self.NCYCLES = 100 # Number of learning cycles
- self.NETSIZE = colors # Number of colours used
- self.SPECIALS = 3 # Number of reserved colours used
- self.BGCOLOR = self.SPECIALS-1 # Reserved background colour
- self.CUTNETSIZE = self.NETSIZE - self.SPECIALS
- self.MAXNETPOS = self.NETSIZE - 1
-
- self.INITRAD = self.NETSIZE/8 # For 256 colours, radius starts at 32
- self.RADIUSBIASSHIFT = 6
- self.RADIUSBIAS = 1 << self.RADIUSBIASSHIFT
- self.INITBIASRADIUS = self.INITRAD * self.RADIUSBIAS
- self.RADIUSDEC = 30 # Factor of 1/30 each cycle
-
- self.ALPHABIASSHIFT = 10 # Alpha starts at 1
- self.INITALPHA = 1 << self.ALPHABIASSHIFT # biased by 10 bits
-
- self.GAMMA = 1024.0
- self.BETA = 1.0/1024.0
- self.BETAGAMMA = self.BETA * self.GAMMA
-
- self.network = np.empty((self.NETSIZE, 3), dtype='float64') # The network itself
- self.colormap = np.empty((self.NETSIZE, 4), dtype='int32') # The network itself
-
- self.netindex = np.empty(256, dtype='int32') # For network lookup - really 256
-
- self.bias = np.empty(self.NETSIZE, dtype='float64') # Bias and freq arrays for learning
- self.freq = np.empty(self.NETSIZE, dtype='float64')
-
- self.pixels = None
- self.samplefac = samplefac
-
- self.a_s = {}
-
- def __init__(self, image, samplefac=10, colors=256):
-
- # Check Numpy
- if np is None:
- raise RuntimeError("Need Numpy for the NeuQuant algorithm.")
-
- # Check image
- if image.size[0] * image.size[1] < NeuQuant.MAXPRIME:
- raise IOError("Image is too small")
- assert image.mode == "RGBA"
-
- # Initialize
- self.setconstants(samplefac, colors)
- self.pixels = np.fromstring(image.tostring(), np.uint32)
- self.setUpArrays()
-
- self.learn()
- self.fix()
- self.inxbuild()
-
- def writeColourMap(self, rgb, outstream):
- for i in range(self.NETSIZE):
- bb = self.colormap[i,0];
- gg = self.colormap[i,1];
- rr = self.colormap[i,2];
- out.write(rr if rgb else bb)
- out.write(gg)
- out.write(bb if rgb else rr)
- return self.NETSIZE
-
- def setUpArrays(self):
- self.network[0,0] = 0.0 # Black
- self.network[0,1] = 0.0
- self.network[0,2] = 0.0
-
- self.network[1,0] = 255.0 # White
- self.network[1,1] = 255.0
- self.network[1,2] = 255.0
-
- # RESERVED self.BGCOLOR # Background
-
- for i in range(self.SPECIALS):
- self.freq[i] = 1.0 / self.NETSIZE
- self.bias[i] = 0.0
-
- for i in range(self.SPECIALS, self.NETSIZE):
- p = self.network[i]
- p[:] = (255.0 * (i-self.SPECIALS)) / self.CUTNETSIZE
-
- self.freq[i] = 1.0 / self.NETSIZE
- self.bias[i] = 0.0
-
- # Omitted: setPixels
-
- def altersingle(self, alpha, i, b, g, r):
- """Move neuron i towards biased (b,g,r) by factor alpha"""
- n = self.network[i] # Alter hit neuron
- n[0] -= (alpha*(n[0] - b))
- n[1] -= (alpha*(n[1] - g))
- n[2] -= (alpha*(n[2] - r))
-
- def geta(self, alpha, rad):
- try:
- return self.a_s[(alpha, rad)]
- except KeyError:
- length = rad*2-1
- mid = length/2
- q = np.array(range(mid-1,-1,-1)+range(-1,mid))
- a = alpha*(rad*rad - q*q)/(rad*rad)
- a[mid] = 0
- self.a_s[(alpha, rad)] = a
- return a
-
- def alterneigh(self, alpha, rad, i, b, g, r):
- if i-rad >= self.SPECIALS-1:
- lo = i-rad
- start = 0
- else:
- lo = self.SPECIALS-1
- start = (self.SPECIALS-1 - (i-rad))
-
- if i+rad <= self.NETSIZE:
- hi = i+rad
- end = rad*2-1
- else:
- hi = self.NETSIZE
- end = (self.NETSIZE - (i+rad))
-
- a = self.geta(alpha, rad)[start:end]
-
- p = self.network[lo+1:hi]
- p -= np.transpose(np.transpose(p - np.array([b, g, r])) * a)
-
- #def contest(self, b, g, r):
- # """ Search for biased BGR values
- # Finds closest neuron (min dist) and updates self.freq
- # finds best neuron (min dist-self.bias) and returns position
- # for frequently chosen neurons, self.freq[i] is high and self.bias[i] is negative
- # self.bias[i] = self.GAMMA*((1/self.NETSIZE)-self.freq[i])"""
- #
- # i, j = self.SPECIALS, self.NETSIZE
- # dists = abs(self.network[i:j] - np.array([b,g,r])).sum(1)
- # bestpos = i + np.argmin(dists)
- # biasdists = dists - self.bias[i:j]
- # bestbiaspos = i + np.argmin(biasdists)
- # self.freq[i:j] -= self.BETA * self.freq[i:j]
- # self.bias[i:j] += self.BETAGAMMA * self.freq[i:j]
- # self.freq[bestpos] += self.BETA
- # self.bias[bestpos] -= self.BETAGAMMA
- # return bestbiaspos
- def contest(self, b, g, r):
- """ Search for biased BGR values
- Finds closest neuron (min dist) and updates self.freq
- finds best neuron (min dist-self.bias) and returns position
- for frequently chosen neurons, self.freq[i] is high and self.bias[i] is negative
- self.bias[i] = self.GAMMA*((1/self.NETSIZE)-self.freq[i])"""
- i, j = self.SPECIALS, self.NETSIZE
- dists = abs(self.network[i:j] - np.array([b,g,r])).sum(1)
- bestpos = i + np.argmin(dists)
- biasdists = dists - self.bias[i:j]
- bestbiaspos = i + np.argmin(biasdists)
- self.freq[i:j] *= (1-self.BETA)
- self.bias[i:j] += self.BETAGAMMA * self.freq[i:j]
- self.freq[bestpos] += self.BETA
- self.bias[bestpos] -= self.BETAGAMMA
- return bestbiaspos
-
-
-
-
- def specialFind(self, b, g, r):
- for i in range(self.SPECIALS):
- n = self.network[i]
- if n[0] == b and n[1] == g and n[2] == r:
- return i
- return -1
-
- def learn(self):
- biasRadius = self.INITBIASRADIUS
- alphadec = 30 + ((self.samplefac-1)/3)
- lengthcount = self.pixels.size
- samplepixels = lengthcount / self.samplefac
- delta = samplepixels / self.NCYCLES
- alpha = self.INITALPHA
-
- i = 0;
- rad = biasRadius >> self.RADIUSBIASSHIFT
- if rad <= 1:
- rad = 0
-
- print "Beginning 1D learning: samplepixels =",samplepixels," rad =", rad
-
- step = 0
- pos = 0
- if lengthcount%NeuQuant.PRIME1 != 0:
- step = NeuQuant.PRIME1
- elif lengthcount%NeuQuant.PRIME2 != 0:
- step = NeuQuant.PRIME2
- elif lengthcount%NeuQuant.PRIME3 != 0:
- step = NeuQuant.PRIME3
- else:
- step = NeuQuant.PRIME4
-
- i = 0
- printed_string = ''
- while i < samplepixels:
- if i%100 == 99:
- tmp = '\b'*len(printed_string)
- printed_string = str((i+1)*100/samplepixels)+"%\n"
- print tmp + printed_string,
- p = self.pixels[pos]
- r = (p >> 16) & 0xff
- g = (p >> 8) & 0xff
- b = (p ) & 0xff
-
- if i == 0: # Remember background colour
- self.network[self.BGCOLOR] = [b, g, r]
-
- j = self.specialFind(b, g, r)
- if j < 0:
- j = self.contest(b, g, r)
-
- if j >= self.SPECIALS: # Don't learn for specials
- a = (1.0 * alpha) / self.INITALPHA
- self.altersingle(a, j, b, g, r)
- if rad > 0:
- self.alterneigh(a, rad, j, b, g, r)
-
- pos = (pos+step)%lengthcount
-
- i += 1
- if i%delta == 0:
- alpha -= alpha / alphadec
- biasRadius -= biasRadius / self.RADIUSDEC
- rad = biasRadius >> self.RADIUSBIASSHIFT
- if rad <= 1:
- rad = 0
- print "Finished 1D learning: final alpha =",(1.0*alpha)/self.INITALPHA,"!"
-
- def fix(self):
- for i in range(self.NETSIZE):
- for j in range(3):
- x = int(0.5 + self.network[i,j])
- x = max(0, x)
- x = min(255, x)
- self.colormap[i,j] = x
- self.colormap[i,3] = i
-
- def inxbuild(self):
- previouscol = 0
- startpos = 0
- for i in range(self.NETSIZE):
- p = self.colormap[i]
- q = None
- smallpos = i
- smallval = p[1] # Index on g
- # Find smallest in i..self.NETSIZE-1
- for j in range(i+1, self.NETSIZE):
- q = self.colormap[j]
- if q[1] < smallval: # Index on g
- smallpos = j
- smallval = q[1] # Index on g
-
- q = self.colormap[smallpos]
- # Swap p (i) and q (smallpos) entries
- if i != smallpos:
- p[:],q[:] = q, p.copy()
-
- # smallval entry is now in position i
- if smallval != previouscol:
- self.netindex[previouscol] = (startpos+i) >> 1
- for j in range(previouscol+1, smallval):
- self.netindex[j] = i
- previouscol = smallval
- startpos = i
- self.netindex[previouscol] = (startpos+self.MAXNETPOS) >> 1
- for j in range(previouscol+1, 256): # Really 256
- self.netindex[j] = self.MAXNETPOS
-
-
- def paletteImage(self):
- """ PIL weird interface for making a paletted image: create an image which
- already has the palette, and use that in Image.quantize. This function
- returns this palette image. """
- if self.pimage is None:
- palette = []
- for i in range(self.NETSIZE):
- palette.extend(self.colormap[i][:3])
-
- palette.extend([0]*(256-self.NETSIZE)*3)
-
- # a palette image to use for quant
- self.pimage = Image.new("P", (1, 1), 0)
- self.pimage.putpalette(palette)
- return self.pimage
-
-
- def quantize(self, image):
- """ Use a kdtree to quickly find the closest palette colors for the pixels """
- if cKDTree:
- return self.quantize_with_scipy(image)
- else:
- print 'Scipy not available, falling back to slower version.'
- return self.quantize_without_scipy(image)
-
-
- def quantize_with_scipy(self, image):
- w,h = image.size
- px = np.asarray(image).copy()
- px2 = px[:,:,:3].reshape((w*h,3))
-
- kdtree = cKDTree(self.colormap[:,:3],leafsize=10)
- result = kdtree.query(px2)
- colorindex = result[1]
- print "Distance:", (result[0].sum()/(w*h))
- px2[:] = self.colormap[colorindex,:3]
-
- return Image.fromarray(px).convert("RGB").quantize(palette=self.paletteImage())
-
-
- def quantize_without_scipy(self, image):
- """" This function can be used if no scipy is availabe.
- It's 7 times slower though.
- """
- w,h = image.size
- px = np.asarray(image).copy()
- memo = {}
- for j in range(w):
- for i in range(h):
- key = (px[i,j,0],px[i,j,1],px[i,j,2])
- try:
- val = memo[key]
- except KeyError:
- val = self.convert(key)
- memo[key] = val
- px[i,j,0],px[i,j,1],px[i,j,2] = val
- return Image.fromarray(px).convert("RGB").quantize(palette=self.paletteImage())
-
- def convert(self, (r, g, b)):
- i = self.inxsearch(r, g, b)
- return self.colormap[i,:3]
-
- def inxsearch(self, r, g, b):
- """Search for BGR values 0..255 and return colour index"""
- dists = (self.colormap[:,:3] - np.array([r,g,b]))
- a= np.argmin((dists*dists).sum(1))
- return a
-
-
-
-if __name__ == '__main__':
- im = np.zeros((200,200), dtype=np.uint8)
- im[10:30,:] = 100
- im[:,80:120] = 255
- im[-50:-40,:] = 50
-
- images = [im*1.0, im*0.8, im*0.6, im*0.4, im*0]
- writeGif('lala3.gif',images, duration=0.5, dither=0)
\ No newline at end of file
diff --git a/mobject/mobject.py b/mobject.py
similarity index 99%
rename from mobject/mobject.py
rename to mobject.py
index 3fb3eee4a..8a81699fd 100644
--- a/mobject/mobject.py
+++ b/mobject.py
@@ -8,10 +8,8 @@ from copy import deepcopy
from colour import Color
import inspect
-
-from constants import *
-from helpers import *
import displayer as disp
+from helpers import *
class Mobject(object):
diff --git a/mobject/__init__.py b/mobject/__init__.py
deleted file mode 100644
index c52e0b7e5..000000000
--- a/mobject/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from mobject import *
-from image_mobject import *
-from simple_mobjects import *
-from three_dimensional_mobjects import *
-from function_graphs import *
-from creatures import *
\ No newline at end of file
diff --git a/scripts/complex_actions.py b/old_projects/complex_multiplication_article.py
similarity index 66%
rename from scripts/complex_actions.py
rename to old_projects/complex_multiplication_article.py
index 0cf143bc5..65d054507 100644
--- a/scripts/complex_actions.py
+++ b/old_projects/complex_multiplication_article.py
@@ -11,129 +11,10 @@ from mobject import *
from constants import *
from region import *
from scene import Scene
-from script_wrapper import command_line_create_scene
-
-MOVIE_PREFIX = "complex_actions/"
+from topics.complex_numbers import *
DEFAULT_PLANE_CONFIG = {
"point_thickness" : 2*DEFAULT_POINT_THICKNESS
-}
-
-def complex_string(complex_num):
- return filter(lambda c : c not in "()", str(complex_num))
-
-class ComplexMultiplication(Scene):
- args_list = [
- complex(np.sqrt(3), 1),
- complex(1,-1)/3,
- complex(-2, 0),
- (complex(np.sqrt(3), 1), True),
- (complex(1,-1)/3, True),
- (complex(-2, 0), True),
- ]
- @staticmethod
- def args_to_string(multiplier, mark_one = False):
- num_str = complex_string(multiplier)
- arrow_str = "MarkOne" if mark_one else ""
- return num_str + arrow_str
-
- @staticmethod
- def string_to_args(arg_string):
- parts = arg_string.split()
- multiplier = complex(parts[0])
- mark_one = len(parts) > 1 and parts[1] == "MarkOne"
- return (multiplier, mark_one)
-
- def construct(self, multiplier, mark_one = False, **plane_config):
- norm = np.linalg.norm(multiplier)
- arg = np.log(multiplier).imag
- plane_config["faded_line_frequency"] = 0
- plane_config.update(DEFAULT_PLANE_CONFIG)
- if norm > 1 and "density" not in plane_config:
- plane_config["density"] = norm*DEFAULT_POINT_DENSITY_1D
- if "radius" not in plane_config:
- radius = SPACE_WIDTH
- if norm > 0 and norm < 1:
- radius /= norm
- else:
- radius = plane_config["radius"]
- plane_config["x_radius"] = plane_config["y_radius"] = radius
- plane = ComplexPlane(**plane_config)
- self.plane = plane
- self.add(plane)
- # plane.add_spider_web()
- self.anim_config = {
- "run_time" : 2.0,
- "interpolation_function" : path_along_arc(arg)
- }
-
- plane_config["faded_line_frequency"] = 0.5
- background = ComplexPlane(color = "grey", **plane_config)
- # background.add_spider_web()
- labels = background.get_coordinate_labels()
- self.paint_into_background(background, *labels)
- self.mobjects_to_move_without_molding = []
- if mark_one:
- self.draw_dot("1", 1, True)
- self.draw_dot("z", multiplier)
-
-
- self.mobjects_to_multiply = [plane]
-
- self.additional_animations = []
- self.multiplier = multiplier
- if self.__class__ == ComplexMultiplication:
- self.apply_multiplication()
-
- def draw_dot(self, tex_string, value, move_dot = False):
- dot = Dot(
- self.plane.number_to_point(value),
- radius = 0.1*self.plane.unit_to_spatial_width,
- color = BLUE if value == 1 else YELLOW
- )
- label = tex_mobject(tex_string)
- label.shift(dot.get_center()+1.5*UP+RIGHT)
- arrow = Arrow(label, dot)
- self.add(label)
- self.play(ShowCreation(arrow))
- self.play(ShowCreation(dot))
- self.dither()
-
- self.remove(label, arrow)
- if move_dot:
- self.mobjects_to_move_without_molding.append(dot)
- return dot
-
-
- def apply_multiplication(self):
- def func((x, y, z)):
- complex_num = self.multiplier*complex(x, y)
- return (complex_num.real, complex_num.imag, z)
- mobjects = self.mobjects_to_multiply
- mobjects += self.mobjects_to_move_without_molding
- mobjects += [anim.mobject for anim in self.additional_animations]
-
-
- self.add(*mobjects)
- full_multiplications = [
- ApplyMethod(mobject.apply_function, func, **self.anim_config)
- for mobject in self.mobjects_to_multiply
- ]
- movements_with_plane = [
- ApplyMethod(
- mobject.shift,
- func(mobject.get_center())-mobject.get_center(),
- **self.anim_config
- )
- for mobject in self.mobjects_to_move_without_molding
- ]
- self.dither()
- self.play(*reduce(op.add, [
- full_multiplications,
- movements_with_plane,
- self.additional_animations
- ]))
- self.dither()
class SuccessiveComplexMultiplications(ComplexMultiplication):
@@ -280,13 +161,6 @@ class DrawSolutionsToZToTheNEqualsW(Scene):
self.add(*plane.get_coordinate_labels())
-
-
-
-
-
-
-
class DrawComplexAngleAndMagnitude(Scene):
args_list = [
(
@@ -378,15 +252,3 @@ class DrawComplexAngleAndMagnitude(Scene):
self.add_local_mobjects()
-
-
-
-
-
-
-
-
-
-
-if __name__ == "__main__":
- command_line_create_scene(MOVIE_PREFIX)
\ No newline at end of file
diff --git a/scripts/old_scripts/counting_in_binary.py b/old_projects/counting_in_binary.py
similarity index 100%
rename from scripts/old_scripts/counting_in_binary.py
rename to old_projects/counting_in_binary.py
diff --git a/scripts/old_scripts/ecf_graph_scenes.py b/old_projects/eulers_characteristic_formula.py
similarity index 100%
rename from scripts/old_scripts/ecf_graph_scenes.py
rename to old_projects/eulers_characteristic_formula.py
diff --git a/scripts/old_scripts/generate_logo.py b/old_projects/generate_logo.py
similarity index 93%
rename from scripts/old_scripts/generate_logo.py
rename to old_projects/generate_logo.py
index 863c92fcc..76a879037 100644
--- a/scripts/old_scripts/generate_logo.py
+++ b/old_projects/generate_logo.py
@@ -11,7 +11,6 @@ from mobject import *
from constants import *
from region import *
from scene import Scene
-from script_wrapper import command_line_create_scene
class LogoGeneration(Scene):
LOGO_RADIUS = 1.5
@@ -61,6 +60,3 @@ class LogoGeneration(Scene):
print "Dragging pixels..."
self.frames = drag_pixels(self.frames)
-
-if __name__ == "__main__":
- command_line_create_scene()
diff --git a/scripts/old_scripts/inventing_math.py b/old_projects/inventing_math.py
similarity index 100%
rename from scripts/old_scripts/inventing_math.py
rename to old_projects/inventing_math.py
diff --git a/scripts/old_scripts/inventing_math_images.py b/old_projects/inventing_math_images.py
similarity index 100%
rename from scripts/old_scripts/inventing_math_images.py
rename to old_projects/inventing_math_images.py
diff --git a/scripts/old_scripts/moser_intro.py b/old_projects/moser_intro.py
similarity index 100%
rename from scripts/old_scripts/moser_intro.py
rename to old_projects/moser_intro.py
diff --git a/scripts/old_scripts/moser_main.py b/old_projects/moser_main.py
similarity index 99%
rename from scripts/old_scripts/moser_main.py
rename to old_projects/moser_main.py
index ffcca87ee..6086ae4cc 100644
--- a/scripts/old_scripts/moser_main.py
+++ b/old_projects/moser_main.py
@@ -1697,10 +1697,5 @@ class IntersectionChoppingExamples(Scene):
self.remove(*self.mobjects)
-##################################################
-
-if __name__ == "__main__":
- command_line_create_scene(MOVIE_PREFIX)
-
diff --git a/scripts/old_scripts/music_and_measure.py b/old_projects/music_and_measure.py
similarity index 100%
rename from scripts/old_scripts/music_and_measure.py
rename to old_projects/music_and_measure.py
diff --git a/scripts/old_scripts/playground_counting_in_binary.py b/old_projects/playground_counting_in_binary.py
similarity index 100%
rename from scripts/old_scripts/playground_counting_in_binary.py
rename to old_projects/playground_counting_in_binary.py
diff --git a/scripts/old_scripts/tau_poem.py b/old_projects/tau_poem.py
similarity index 100%
rename from scripts/old_scripts/tau_poem.py
rename to old_projects/tau_poem.py
diff --git a/region.py b/region.py
index bdbb76d44..def9b1300 100644
--- a/region.py
+++ b/region.py
@@ -4,9 +4,9 @@ from PIL import Image
import cv2
from copy import deepcopy
-from constants import *
-from helpers import *
+
import displayer as disp
+from helpers import *
class Region(object):
def __init__(self,
diff --git a/sample_script.py b/sample_script.py
deleted file mode 100644
index 748fc8d8f..000000000
--- a/sample_script.py
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/usr/bin/env python
-
-import numpy as np
-import itertools as it
-from copy import deepcopy
-import sys
-
-
-from animation import *
-from mobject import *
-from constants import *
-from region import *
-from scene import Scene
-from script_wrapper import command_line_create_scene
-
-
-class SampleScene(Scene):
- def construct(self):
- words = text_mobject("Hi There")
- self.paint_into_background(words.shift(UP).highlight(RED_A))
- self.paint_into_background(words.shift(DOWN).highlight(RED_E))
-
-
-
-
-
-if __name__ == "__main__":
- command_line_create_scene()
\ No newline at end of file
diff --git a/scene/__init__.py b/scene/__init__.py
index 2c2ea355f..be1fa5ea6 100644
--- a/scene/__init__.py
+++ b/scene/__init__.py
@@ -1,7 +1,3 @@
from scene import *
-from sub_scenes import *
-from arithmetic_scenes import *
-from counting_scene import *
-from pascals_triangle import *
from scene_from_video import *
-from number_line import *
\ No newline at end of file
+from tk_scene import *
\ No newline at end of file
diff --git a/scene/counting_scene.py b/scene/counting_scene.py
deleted file mode 100644
index 536967ad0..000000000
--- a/scene/counting_scene.py
+++ /dev/null
@@ -1,85 +0,0 @@
-from scene import Scene
-
-from mobject import *
-from animation import *
-from region import *
-from constants import *
-from helpers import *
-
-DEFAULT_COUNT_NUM_OFFSET = (SPACE_WIDTH - 1, SPACE_HEIGHT - 1, 0)
-DEFAULT_COUNT_RUN_TIME = 5.0
-
-class CountingScene(Scene):
- def count(self, items, item_type = "mobject", *args, **kwargs):
- if item_type == "mobject":
- self.count_mobjects(items, *args, **kwargs)
- elif item_type == "region":
- self.count_regions(items, *args, **kwargs)
- else:
- raise Exception("Unknown item_type, should be mobject or region")
- return self
-
- def count_mobjects(
- self, mobjects, mode = "highlight",
- color = "red",
- display_numbers = True,
- num_offset = DEFAULT_COUNT_NUM_OFFSET,
- run_time = DEFAULT_COUNT_RUN_TIME):
- """
- Note, leaves final number mobject as "number" attribute
-
- mode can be "highlight", "show_creation" or "show", otherwise
- a warning is given and nothing is animating during the count
- """
- if len(mobjects) > 50: #TODO
- raise Exception("I don't know if you should be counting \
- too many mobjects...")
- if len(mobjects) == 0:
- raise Exception("Counting mobject list of length 0")
- if mode not in ["highlight", "show_creation", "show"]:
- raise Warning("Unknown mode")
- frame_time = run_time / len(mobjects)
- if mode == "highlight":
- self.add(*mobjects)
- for mob, num in zip(mobjects, it.count(1)):
- if display_numbers:
- num_mob = tex_mobject(str(num))
- num_mob.center().shift(num_offset)
- self.add(num_mob)
- if mode == "highlight":
- original_color = mob.color
- mob.highlight(color)
- self.dither(frame_time)
- mob.highlight(original_color)
- if mode == "show_creation":
- self.play(ShowCreation(mob, run_time = frame_time))
- if mode == "show":
- self.add(mob)
- self.dither(frame_time)
- if display_numbers:
- self.remove(num_mob)
- if display_numbers:
- self.add(num_mob)
- self.number = num_mob
- return self
-
- def count_regions(self, regions,
- mode = "one_at_a_time",
- num_offset = DEFAULT_COUNT_NUM_OFFSET,
- run_time = DEFAULT_COUNT_RUN_TIME,
- **unused_kwargsn):
- if mode not in ["one_at_a_time", "show_all"]:
- raise Warning("Unknown mode")
- frame_time = run_time / (len(regions))
- for region, count in zip(regions, it.count(1)):
- num_mob = tex_mobject(str(count))
- num_mob.center().shift(num_offset)
- self.add(num_mob)
- self.highlight_region(region)
- self.dither(frame_time)
- if mode == "one_at_a_time":
- self.reset_background()
- self.remove(num_mob)
- self.add(num_mob)
- self.number = num_mob
- return self
\ No newline at end of file
diff --git a/scene/number_line.py b/scene/number_line.py
deleted file mode 100644
index f2cae7439..000000000
--- a/scene/number_line.py
+++ /dev/null
@@ -1,92 +0,0 @@
-import numpy as np
-import itertools as it
-
-from scene import Scene
-
-from mobject import *
-from animation import *
-from region import *
-from constants import *
-from helpers import *
-
-
-class NumberLineScene(Scene):
- def construct(self, **number_line_config):
- self.number_line = NumberLine(**number_line_config)
- self.displayed_numbers = self.number_line.default_numbers_to_display()
- self.number_mobs = self.number_line.get_number_mobjects(*self.displayed_numbers)
- self.add(self.number_line, *self.number_mobs)
-
- def zoom_in_on(self, number, zoom_factor, run_time = 2.0):
- unit_length_to_spatial_width = self.number_line.unit_length_to_spatial_width*zoom_factor
- radius = SPACE_WIDTH/unit_length_to_spatial_width
- tick_frequency = 10**(np.floor(np.log10(radius)))
- left_tick = tick_frequency*(np.ceil((number-radius)/tick_frequency))
- new_number_line = NumberLine(
- numerical_radius = radius,
- unit_length_to_spatial_width = unit_length_to_spatial_width,
- tick_frequency = tick_frequency,
- leftmost_tick = left_tick,
- number_at_center = number
- )
- new_displayed_numbers = new_number_line.default_numbers_to_display()
- new_number_mobs = new_number_line.get_number_mobjects(*new_displayed_numbers)
-
- transforms = []
- additional_mobjects = []
- squished_new_line = deepcopy(new_number_line)
- squished_new_line.scale(1.0/zoom_factor)
- squished_new_line.shift(self.number_line.number_to_point(number))
- squished_new_line.points[:,1] = self.number_line.number_to_point(0)[1]
- transforms.append(Transform(squished_new_line, new_number_line))
- for mob, num in zip(new_number_mobs, new_displayed_numbers):
- point = Point(self.number_line.number_to_point(num))
- point.shift(new_number_line.get_vertical_number_offset())
- transforms.append(Transform(point, mob))
- for mob in self.mobjects:
- if mob == self.number_line:
- new_mob = deepcopy(mob)
- new_mob.shift(-self.number_line.number_to_point(number))
- new_mob.stretch(zoom_factor, 0)
- transforms.append(Transform(mob, new_mob))
- continue
- mob_center = mob.get_center()
- number_under_center = self.number_line.point_to_number(mob_center)
- new_point = new_number_line.number_to_point(number_under_center)
- new_point += mob_center[1]*UP
- if mob in self.number_mobs:
- transforms.append(Transform(mob, Point(new_point)))
- else:
- transforms.append(ApplyMethod(mob.shift, new_point - mob_center))
- additional_mobjects.append(mob)
- line_to_hide_pixelation = Line(
- self.number_line.get_left(),
- self.number_line.get_right(),
- color = self.number_line.get_color()
- )
- self.add(line_to_hide_pixelation)
- self.play(*transforms, run_time = run_time)
- self.clear()
- self.number_line = new_number_line
- self.displayed_numbers = new_displayed_numbers
- self.number_mobs = new_number_mobs
- self.add(self.number_line, *self.number_mobs)
- self.add(*additional_mobjects)
-
- def show_multiplication(self, num, **kwargs):
- if "interpolation_function" not in kwargs:
- if num > 0:
- kwargs["interpolation_function"] = straight_path
- else:
- kwargs["interpolation_function"] = counterclockwise_path()
- self.play(*[
- ApplyMethod(self.number_line.stretch, num, 0, **kwargs)
- ]+[
- ApplyMethod(mob.shift, (num-1)*mob.get_center()[0]*RIGHT, **kwargs)
- for mob in self.number_mobs
- ])
-
-
-
-
-
diff --git a/scene/scene.py b/scene/scene.py
index d0d2da741..8d5e0f1b3 100644
--- a/scene/scene.py
+++ b/scene/scene.py
@@ -10,8 +10,7 @@ import progressbar
import inspect
from helpers import *
-from mobject import *
-from animation import *
+
import displayer as disp
from tk_scene import TkSceneRoot
@@ -199,11 +198,6 @@ class Scene(object):
self.frames = self.frames*num
return self
- def write_to_gif(self, name = None,
- end_dither_time = DEFAULT_DITHER_TIME):
- self.dither(end_dither_time)
- disp.write_to_gif(self, name or str(self))
-
def write_to_movie(self, name = None):
if len(self.frames) == 0:
print "No frames, I'll just save an image instead"
diff --git a/scene/scene_from_video.py b/scene/scene_from_video.py
index 9b17e3bd6..7d1cde3b7 100644
--- a/scene/scene_from_video.py
+++ b/scene/scene_from_video.py
@@ -2,7 +2,7 @@ import numpy as np
import cv2
import itertools as it
-from scene import *
+from scene import Scene
class SceneFromVideo(Scene):
diff --git a/scene/tk_scene.py b/scene/tk_scene.py
index dfa05b72e..ab6f7eadf 100644
--- a/scene/tk_scene.py
+++ b/scene/tk_scene.py
@@ -1,9 +1,9 @@
-from scene import *
import Tkinter
from PIL import ImageTk, Image
import itertools as it
import time
+
class TkSceneRoot(Tkinter.Tk):
def __init__(self, scene):
if scene.frames == []:
diff --git a/scripts/inventing_math.py b/scripts/inventing_math.py
deleted file mode 100644
index ebf292e50..000000000
--- a/scripts/inventing_math.py
+++ /dev/null
@@ -1,2168 +0,0 @@
-#!/usr/bin/env python
-
-import numpy as np
-import itertools as it
-from copy import deepcopy
-import sys
-import operator as op
-from random import sample
-
-
-from animation import *
-from mobject import *
-from constants import *
-from region import *
-from scene import Scene, RearrangeEquation
-from script_wrapper import command_line_create_scene
-
-# from inventing_math_images import *
-
-MOVIE_PREFIX = "inventing_math/"
-DIVERGENT_SUM_TEXT = [
- "1",
- "+2",
- "+4",
- "+8",
- "+\\cdots",
- "+2^n",
- "+\\cdots",
- "= -1",
-]
-
-CONVERGENT_SUM_TEXT = [
- "\\frac{1}{2}",
- "+\\frac{1}{4}",
- "+\\frac{1}{8}",
- "+\\frac{1}{16}",
- "+\\cdots",
- "+\\frac{1}{2^n}",
- "+\\cdots",
- "=1",
-]
-
-CONVERGENT_SUM_TERMS = [
- "\\frac{1}{2}",
- "\\frac{1}{4}",
- "\\frac{1}{8}",
- "\\frac{1}{16}",
-]
-
-PARTIAL_CONVERGENT_SUMS_TEXT = [
- "\\frac{1}{2}",
- "", "", ",\\quad",
- "\\frac{1}{2} + \\frac{1}{4}",
- "=", "\\frac{3}{4}", ",\\quad",
- "\\frac{1}{2} + \\frac{1}{4} + \\frac{1}{8}",
- "=", "\\frac{7}{8}", ",\\quad",
- "\\frac{1}{2} + \\frac{1}{4} + \\frac{1}{8} + \\frac{1}{16}",
- "=", "\\frac{15}{16}", ",\\dots"
-]
-
-def partial_sum(n):
- return sum([1.0/2**(k+1) for k in range(n)])
-
-ALT_PARTIAL_SUM_TEXT = reduce(op.add, [
- [str(partial_sum(n)), "&=", "+".join(CONVERGENT_SUM_TERMS[:n])+"\\\\"]
- for n in range(1, len(CONVERGENT_SUM_TERMS)+1)
-])+ [
- "\\vdots", "&", "\\\\",
- "1.0", "&=", "+".join(CONVERGENT_SUM_TERMS)+"+\\cdots+\\frac{1}{2^n}+\\cdots"
-]
-
-
-NUM_WRITTEN_TERMS = 4
-INTERVAL_RADIUS = 5
-NUM_INTERVAL_TICKS = 16
-
-
-def divergent_sum():
- return tex_mobject(DIVERGENT_SUM_TEXT, size = "\\large").scale(2)
-
-def convergent_sum():
- return tex_mobject(CONVERGENT_SUM_TEXT, size = "\\large").scale(2)
-
-def zero_to_one_interval():
- interval = NumberLine(
- radius = INTERVAL_RADIUS,
- interval_size = 2.0*INTERVAL_RADIUS/NUM_INTERVAL_TICKS
- )
- interval.elongate_tick_at(-INTERVAL_RADIUS, 4)
- interval.elongate_tick_at(INTERVAL_RADIUS, 4)
- zero = tex_mobject("0").shift(INTERVAL_RADIUS*LEFT+DOWN)
- one = tex_mobject("1").shift(INTERVAL_RADIUS*RIGHT+DOWN)
- return CompoundMobject(interval, zero, one)
-
-def draw_you(with_bubble = False):
- result = PiCreature()
- result.give_straight_face().highlight("grey")
- result.to_corner(LEFT+DOWN)
- result.rewire_part_attributes()
- if with_bubble:
- bubble = ThoughtBubble()
- bubble.stretch_to_fit_width(11)
- bubble.pin_to(result)
- return result, bubble
- return result
-
-def get_room_colors():
- return list(Color("yellow").range_to("red", 4))
-
-def power_of_divisor(n, d):
- result = 0
- while n%d == 0:
- result += 1
- n /= d
- return result
-
-class FlipThroughNumbers(Animation):
- def __init__(self, function = lambda x : x,
- start = 0, end = 10,
- start_center = ORIGIN,
- end_center = ORIGIN,
- **kwargs):
- self.function = function
- self.start = start
- self.end = end
- self.start_center = start_center
- self.end_center = end_center
- self.current_number = function(start)
- mobject = tex_mobject(str(self.current_number)).shift(start_center)
- Animation.__init__(self, mobject, **kwargs)
-
- def update_mobject(self, alpha):
- new_number = self.function(
- self.start + int(alpha *(self.end-self.start))
- )
- if new_number != self.current_number:
- self.current_number = new_number
- self.mobject = tex_mobject(str(new_number)).shift(self.start_center)
- if not all(self.start_center == self.end_center):
- self.mobject.center().shift(
- (1-alpha)*self.start_center + alpha*self.end_center
- )
-
-
-######################################
-
-class IntroduceDivergentSum(Scene):
- def construct(self):
- equation = divergent_sum().split()
- sum_value = None
- brace = underbrace(
- equation[0].get_boundary_point(DOWN+LEFT),
- equation[1].get_boundary_point(DOWN+RIGHT)
- ).shift(0.2*DOWN)
- min_x_coord = min(equation[0].points[:,0])
- for x in range(NUM_WRITTEN_TERMS):
- self.add(equation[x])
- if x == 0:
- self.dither(0.75)
- continue
- brace.stretch_to_fit_width(
- max(equation[x].points[:,0]) - min_x_coord
- )
- brace.to_edge(LEFT, buff = SPACE_WIDTH+min_x_coord)
- if sum_value:
- self.remove(sum_value)
- sum_value = tex_mobject(str(2**(x+1) - 1))
- sum_value.shift(brace.get_center() + 0.5*DOWN)
- self.add(brace, sum_value)
- self.dither(0.75)
- self.remove(sum_value)
- ellipses = CompoundMobject(
- *[equation[NUM_WRITTEN_TERMS + i] for i in range(3)]
- )
- end_brace = deepcopy(brace).stretch_to_fit_width(
- max(ellipses.points[:,0])-min_x_coord
- ).to_edge(LEFT, buff = SPACE_WIDTH+min_x_coord)
- kwargs = {"run_time" : 5.0, "alpha_func" : rush_into}
- flip_through = FlipThroughNumbers(
- lambda x : 2**(x+1)-1,
- start = NUM_WRITTEN_TERMS-1,
- end = 50,
- start_center = brace.get_center() + 0.5*DOWN,
- end_center = end_brace.get_center() + 0.5*DOWN,
- **kwargs
- )
- self.add(ellipses)
- self.play(
- Transform(brace, end_brace, **kwargs),
- flip_through,
- )
- self.clear()
- self.add(*equation)
- self.dither()
-
-class ClearlyNonsense(Scene):
- def construct(self):
- number_line = NumberLine().add_numbers()
- div_sum = divergent_sum()
- this_way = text_mobject("Sum goes this way...")
- this_way.to_edge(LEFT).shift(RIGHT*(SPACE_WIDTH+1) + DOWN)
- how_here = text_mobject("How does it end up here?")
- how_here.shift(1.5*UP+LEFT)
- neg_1_arrow = Arrow(
- (-1, 0.3, 0),
- tail=how_here.get_center()+0.5*DOWN
- )
- right_arrow = Arrow(
- (SPACE_WIDTH-0.5)*RIGHT + DOWN,
- tail = (max(this_way.points[:,0]), -1, 0)
- )
- how_here.highlight("red")
- neg_1_arrow.highlight("red")
- this_way.highlight("yellow")
- right_arrow.highlight("yellow")
-
- self.play(Transform(
- div_sum,
- deepcopy(div_sum).scale(0.5).shift(3*UP)
- ))
- self.play(ShowCreation(number_line))
- self.dither()
- self.add(how_here)
- self.play(ShowCreation(neg_1_arrow))
- self.dither()
- self.add(this_way)
- self.play(ShowCreation(right_arrow))
- self.dither()
-
-class OutlineOfVideo(Scene):
- def construct(self):
- conv_sum = convergent_sum().scale(0.5)
- div_sum = divergent_sum().scale(0.5)
- overbrace = underbrace(
- conv_sum.get_left(),
- conv_sum.get_right()
- ).rotate(np.pi, RIGHT).shift(0.75*UP*conv_sum.get_height())
- dots = conv_sum.split()[-2].highlight("green")
- dots.sort_points()
- arrow = Arrow(
- dots.get_bottom(),
- direction = UP+LEFT
- )
- u_brace = underbrace(div_sum.get_left(), div_sum.get_right())
- u_brace.shift(1.5*div_sum.get_bottom())
- for mob in conv_sum, overbrace, arrow, dots:
- mob.shift(2*UP)
- for mob in div_sum, u_brace:
- mob.shift(DOWN)
- texts = [
- text_mobject(words).highlight("yellow")
- for words in [
- "1. Discover this",
- "2. Clarify what this means",
- "3. Discover this",
- ["4. Invent ", "\\textbf{new math}"]
- ]
- ]
- last_one_split = texts[-1].split()
- last_one_split[1].highlight("skyblue")
- texts[-1] = CompoundMobject(*last_one_split)
- texts[0].shift(overbrace.get_top()+texts[0].get_height()*UP)
- texts[1].shift(sum([
- arrow.get_boundary_point(DOWN+RIGHT),
- texts[1].get_height()*DOWN
- ]))
- texts[2].shift(u_brace.get_bottom()+texts[3].get_height()*DOWN)
- texts[3].to_edge(DOWN)
-
- groups = [
- [texts[0], overbrace, conv_sum],
- [texts[1], arrow, dots],
- [texts[2], u_brace, div_sum],
- [texts[3]]
- ]
- for group in groups:
- self.play(*[
- DelayByOrder(FadeIn(element))
- for element in group
- ])
- self.dither()
-
-# # class ReasonsForMakingVideo(Scene):
-# # def construct(self):
-# # text = text_mobject([
-# # """
-# # \\begin{itemize}
-# # \\item Understand what ``$
-# # """,
-# # "".join(DIVERGENT_SUM_TEXT),
-# # """
-# # $'' is saying.
-# # """,
-# # """
-# # \\item Nonsense-Driven Construction
-# # \\end{itemize}
-# # """
-# # ], size = "\\Small")
-# # text.scale(1.5).to_edge(LEFT).shift(UP).highlight("white")
-# # text.highlight("green", lambda (x, y, z) : x < -SPACE_WIDTH + 1)
-# # line_one_first, equation, line_one_last, line_two = text.split()
-# # line_two.shift(2*DOWN)
-# # div_sum = divergent_sum().scale(0.5).shift(3*UP)
-
-# # self.add(div_sum)
-# # self.play(
-# # ApplyMethod(div_sum.replace, equation),
-# # FadeIn(line_one_first),
-# # FadeIn(line_one_last)
-# # )
-# # self.dither()
-# # self.add(line_two)
-# # self.dither()
-
-# class DiscoverAndDefine(Scene):
-# def construct(self):
-# sum_mob = tex_mobject("\\sum_{n = 1}^\\infty a_n")
-# discover = text_mobject("What does it feel like to discover these?")
-# define = text_mobject([
-# "What does it feel like to",
-# "\\emph{define} ",
-# "them?"
-# ])
-# sum_mob.shift(2*UP)
-# define.shift(2*DOWN)
-# define_parts = define.split()
-# define_parts[1].highlight("skyblue")
-
-# self.add(sum_mob)
-# self.play(FadeIn(discover))
-# self.dither()
-# self.play(FadeIn(CompoundMobject(*define_parts)))
-# self.dither()
-
-class YouAsMathematician(Scene):
- def construct(self):
- you, bubble = draw_you(with_bubble = True)
- explanation = text_mobject(
- "You as a (questionably accurate portrayal of a) mathematician.",
- size = "\\small"
- ).shift([2, you.get_center()[1], 0])
- arrow = Arrow(you.get_center(), direction = LEFT)
- arrow.nudge(you.get_width())
- for mob in arrow, explanation:
- mob.highlight("yellow")
- equation = convergent_sum()
- bubble.add_content(equation)
- equation_parts = equation.split()
- equation.shift(0.5*RIGHT)
- bubble.clear()
- dot_pair = [
- Dot(density = 3*DEFAULT_POINT_DENSITY_1D).shift(x+UP)
- for x in LEFT, RIGHT
- ]
- self.add(you, explanation)
- self.play(
- ShowCreation(arrow),
- BlinkPiCreature(you)
- )
- self.dither()
- self.play(ShowCreation(bubble))
- for part in equation_parts:
- self.play(DelayByOrder(FadeIn(part)), run_time = 0.5)
- self.dither()
- self.play(
- BlinkPiCreature(you),
- FadeOut(explanation),
- FadeOut(arrow)
- )
- self.remove(bubble, *equation_parts)
- self.disapproving_friend()
- self.add(bubble, equation)
- self.play(Transform(equation, CompoundMobject(*dot_pair)))
- self.remove(equation)
- self.add(*dot_pair)
- two_arrows = [
- Arrow(x, direction = x).shift(UP).nudge()
- for x in LEFT, RIGHT
- ]
- self.play(*[ShowCreation(a) for a in two_arrows])
- self.play(BlinkPiCreature(you))
- self.remove(*dot_pair+two_arrows)
- everything = CompoundMobject(*self.mobjects)
- self.clear()
- self.play(
- ApplyPointwiseFunction(
- lambda p : 3*SPACE_WIDTH*p/np.linalg.norm(p),
- everything
- ),
- *[
- Transform(dot, deepcopy(dot).shift(DOWN).scale(3))
- for dot in dot_pair
- ],
- run_time = 2.0
- )
- self.dither()
-
- def disapproving_friend(self):
- friend = Mortimer().to_corner(DOWN+RIGHT)
- bubble = SpeechBubble().pin_to(friend)
- bubble.write("It's simply not rigorous!")
- bubble.content.sort_points(lambda p : np.dot(p, DOWN+RIGHT))
-
- self.add(friend, bubble)
- self.play(DelayByOrder(FadeIn(bubble.content)))
- self.dither()
- self.remove(friend, bubble, bubble.content)
-
-
-class DotsGettingCloser(Scene):
- def construct(self):
- dots = [
- Dot(radius = 3*Dot.DEFAULT_RADIUS).shift(3*x)
- for x in LEFT, RIGHT
- ]
- self.add(*dots)
- self.dither()
- for x in range(10):
- distance = min(dots[1].points[:,0])-max(dots[0].points[:,0])
- self.play(ApplyMethod(dots[0].shift, 0.5*distance*RIGHT))
-
-
-class ZoomInOnInterval(Scene):
- def construct(self):
- number_line = NumberLine(density = 10*DEFAULT_POINT_DENSITY_1D)
- number_line.add_numbers()
- interval = zero_to_one_interval().split()
-
- new_line = deepcopy(number_line)
- new_line.highlight("black", lambda (x,y,z) : x < 0 or x > 1 or y < -0.2)
- # height = new_line.get_height()
- new_line.scale(2*INTERVAL_RADIUS)
- new_line.shift(INTERVAL_RADIUS*LEFT)
- # new_line.stretch_to_fit_height(height)
-
- self.add(number_line)
- self.dither()
- self.play(Transform(number_line, new_line))
- self.clear()
- squish = lambda p : (p[0], 0, 0)
- self.play(
- ApplyMethod(new_line.apply_function, squish),
- ApplyMethod(
- interval[0].apply_function, squish,
- alpha_func = lambda t : 1-t
- ),
- *[FadeIn(interval[x]) for x in [1, 2]]
- )
- self.clear()
- self.add(*interval)
- self.dither()
-
-class DanceDotOnInterval(Scene):
- def construct(self, mode):
- num_written_terms = NUM_WRITTEN_TERMS
- prop = 0.5
- sum_terms = [
- "\\frac{1}{2}",
- "\\frac{1}{4}",
- "\\frac{1}{8}",
- "\\frac{1}{16}",
- ]
- num_height = 1.3*DOWN
- interval = zero_to_one_interval()
- dots = [
- Dot(radius = 3*Dot.DEFAULT_RADIUS).shift(INTERVAL_RADIUS*x+UP)
- for x in LEFT, RIGHT
- ]
- color_range = Color("green").range_to("yellow", num_written_terms)
- conv_sum = tex_mobject(sum_terms, size = "\\large").split()
-
- self.add(interval)
- self.play(*[
- ApplyMethod(dot.shift, DOWN)
- for dot in dots
- ])
- self.dither()
- for count in range(num_written_terms):
- shift_val = 2*RIGHT*INTERVAL_RADIUS*(1-prop)*(prop**count)
- start = dots[0].get_center()
- line = Line(start, start + shift_val*RIGHT)
- line.highlight(color_range.next())
- self.play(
- ApplyMethod(dots[0].shift, shift_val),
- ShowCreation(line)
- )
- num = conv_sum[count]
- num.shift(RIGHT*(line.get_center()[0]-num.get_center()[0]))
- num.shift(num_height)
- arrow = Mobject()
- if num.get_width() > line.get_length():
- num.center().shift(3*DOWN+2*(count-2)*RIGHT)
- arrow = Arrow(
- line.get_center()+2*DOWN,
- tail = num.get_center()+0.5*num.get_height()*UP
- )
- self.play(
- ApplyMethod(line.shift, 2*DOWN),
- FadeIn(num),
- FadeIn(arrow),
- )
- self.dither()
- self.write_partial_sums()
- self.dither()
-
- def write_partial_sums(self):
- partial_sums = tex_mobject(PARTIAL_CONVERGENT_SUMS_TEXT, size = "\\small")
- partial_sums.scale(1.5).to_edge(UP)
- partial_sum_parts = partial_sums.split()
- partial_sum_parts[0].highlight("yellow")
-
- for x in range(0, len(partial_sum_parts), 4):
- partial_sum_parts[x+2].highlight("yellow")
- self.play(*[
- FadeIn(partial_sum_parts[y])
- for y in range(x, x+4)
- ])
- self.dither(2)
-
-class OrganizePartialSums(Scene):
- def construct(self):
- partial_sums = tex_mobject(PARTIAL_CONVERGENT_SUMS_TEXT, size = "\\small")
- partial_sums.scale(1.5).to_edge(UP)
- partial_sum_parts = partial_sums.split()
- for x in [0] + range(2, len(partial_sum_parts), 4):
- partial_sum_parts[x].highlight("yellow")
- pure_sums = [
- partial_sum_parts[x]
- for x in range(0, len(partial_sum_parts), 4)
- ]
- new_pure_sums = deepcopy(pure_sums)
- for pure_sum, count in zip(new_pure_sums, it.count(3, -1.2)):
- pure_sum.center().scale(1/1.25).highlight("white")
- pure_sum.to_edge(LEFT).shift(2*RIGHT+count*UP)
-
- self.add(*partial_sum_parts)
- self.dither()
- self.play(*[
- ClockwiseTransform(*pair)
- for pair in zip(pure_sums, new_pure_sums)
- ]+[
- FadeOut(mob)
- for mob in partial_sum_parts
- if mob not in pure_sums
- ])
- down_arrow = tex_mobject("\\downarrow")
- down_arrow.to_edge(LEFT).shift(2*RIGHT+2*DOWN)
- dots = tex_mobject("\\vdots")
- dots.shift(down_arrow.get_center()+down_arrow.get_height()*UP)
- infinite_sum = tex_mobject("".join(CONVERGENT_SUM_TEXT[:-1]), size = "\\samll")
- infinite_sum.scale(1.5/1.25)
- infinite_sum.to_corner(DOWN+LEFT).shift(2*RIGHT)
-
- self.play(ShowCreation(dots))
- self.dither()
- self.play(FadeIn(CompoundMobject(down_arrow, infinite_sum)))
- self.dither()
-
-class SeeNumbersApproachOne(Scene):
- def construct(self):
- interval = zero_to_one_interval()
- arrow = Arrow(INTERVAL_RADIUS*RIGHT, tail=ORIGIN).nudge()
- arrow.shift(DOWN).highlight("yellow")
- num_dots = 6
- colors = Color("green").range_to("yellow", num_dots)
- dots = CompoundMobject(*[
- Dot(
- density = 2*DEFAULT_POINT_DENSITY_1D
- ).scale(1+1.0/2.0**x).shift(
- INTERVAL_RADIUS*RIGHT +\
- (INTERVAL_RADIUS/2.0**x)*LEFT
- ).highlight(colors.next())
- for x in range(num_dots)
- ])
-
- self.add(interval)
- self.play(
- ShowCreation(arrow),
- ShowCreation(dots),
- run_time = 2.0
- )
- self.dither()
-
-class OneAndInfiniteSumAreTheSameThing(Scene):
- def construct(self):
- one, equals, inf_sum = tex_mobject([
- "1", "=", "\\sum_{n=1}^\\infty \\frac{1}{2^n}"
- ]).split()
- point = Point(equals.get_center()).highlight("black")
-
- self.add(one.shift(LEFT))
- self.dither()
- self.add(inf_sum.shift(RIGHT))
- self.dither()
- self.play(
- ApplyMethod(one.shift, RIGHT),
- ApplyMethod(inf_sum.shift, LEFT),
- CounterclockwiseTransform(point, equals)
- )
- self.dither()
-
-
-class HowDoYouDefineInfiniteSums(Scene):
- def construct(self):
- you = draw_you().center().rewire_part_attributes()
- text = text_mobject(
- ["How", " do", " you,\\\\", "\\emph{define}"],
- size = "\\Huge"
- ).shift(UP).split()
- text[-1].shift(3*DOWN).highlight("skyblue")
- sum_mob = tex_mobject("\\sum_{n=0}^\\infty{a_n}")
- text[-1].shift(LEFT)
- sum_mob.shift(text[-1].get_center()+2*RIGHT)
-
- self.add(you)
- self.dither()
- for mob in text[:-1]:
- self.add(mob)
- self.dither(0.1)
- self.play(BlinkPiCreature(you))
- self.dither()
- self.add(text[-1])
- self.dither()
- self.add(sum_mob)
- self.dither()
-
-
-class LessAboutNewThoughts(Scene):
- def construct(self):
- words = generating, new, thoughts, to, definitions = text_mobject([
- "Generating", " new", " thoughts", "$\\rightarrow$",
- "useful definitions"
- ], size = "\\large").split()
- gen_cross = tex_mobject("\\hline").highlight("red")
- new_cross = deepcopy(gen_cross)
- for cross, mob in [(gen_cross, generating), (new_cross, new)]:
- cross.replace(mob)
- cross.stretch_to_fit_height(0.03)
- disecting = text_mobject("Disecting").highlight("green")
- disecting.shift(generating.get_center() + 0.6*UP)
- old = text_mobject("old").highlight("green")
- old.shift(new.get_center()+0.6*UP)
-
- kwargs = {"run_time" : 0.25}
- self.add(*words)
- self.dither()
- self.play(ShowCreation(gen_cross, **kwargs))
- self.play(ShowCreation(new_cross, **kwargs))
- self.dither()
- self.add(disecting)
- self.dither(0.5)
- self.add(old)
- self.dither()
-
-class ListOfPartialSums(Scene):
- def construct(self):
- all_terms = np.array(tex_mobject(
- ALT_PARTIAL_SUM_TEXT,
- size = "\\large"
- ).split())
- numbers, equals, sums = [
- all_terms[range(k, 12, 3)]
- for k in 0, 1, 2
- ]
- dots = all_terms[12]
- one = all_terms[-3]
- last_equal = all_terms[-2]
- infinite_sum = all_terms[-1]
-
- self.count(
- numbers,
- mode = "show",
- display_numbers = False,
- run_time = 1.0
- )
- self.play(ShowCreation(dots))
- self.dither()
- self.play(
- FadeIn(CompoundMobject(*equals)),
- *[
- Transform(deepcopy(number), finite_sum)
- for number, finite_sum in zip(numbers, sums)
- ]
- )
- self.dither()
- self.play(*[
- ApplyMethod(s.highlight, "yellow", alpha_func = there_and_back)
- for s in sums
- ])
- self.dither()
- self.add(one.highlight("green"))
- self.dither()
-
-
-class ShowDecreasingDistance(Scene):
- args_list = [(1,), (2,)]
- @staticmethod
- def args_to_string(num):
- return str(num)
-
- def construct(self, num):
- number_line = NumberLine(interval_size = 1).add_numbers()
- vert_line0 = Line(0.5*UP+RIGHT, UP+RIGHT)
- vert_line1 = Line(0.5*UP+2*num*RIGHT, UP+2*num*RIGHT)
- horiz_line = Line(vert_line0.end, vert_line1.end)
- lines = [vert_line0, vert_line1, horiz_line]
- for line in lines:
- line.highlight("green")
- dots = CompoundMobject(*[
- Dot().scale(1.0/(n+1)).shift((1+partial_sum(n))*RIGHT)
- for n in range(10)
- ])
-
- self.add(dots.split()[0])
- self.add(number_line, *lines)
- self.dither()
- self.play(
- ApplyMethod(vert_line0.shift, RIGHT),
- Transform(
- horiz_line,
- Line(vert_line0.end+RIGHT, vert_line1.end).highlight("green")
- ),
- ShowCreation(dots),
- run_time = 2.5
- )
- self.dither()
-
-class CircleZoomInOnOne(Scene):
- def construct(self):
- number_line = NumberLine(interval_size = 1).add_numbers()
- dots = CompoundMobject(*[
- Dot().scale(1.0/(n+1)).shift((1+partial_sum(n))*RIGHT)
- for n in range(10)
- ])
- circle = Circle().shift(2*RIGHT)
- text = text_mobject(
- "All but finitely many dots fall inside even the tiniest circle."
- )
- numbers = map(
- lambda s : tex_mobject("\\frac{1}{%s}"%s),
- ["100", "1,000,000", "g_{g_{64}}"]
- )
- for num in numbers + [text]:
- num.shift(2*UP)
- num.sort_points(lambda p : np.dot(p, DOWN+RIGHT))
- curr_num = numbers[0]
- arrow = Arrow(2*RIGHT, direction = 1.5*(DOWN+RIGHT)).nudge()
-
- self.add(number_line, dots)
- self.play(
- Transform(circle, Point(2*RIGHT).highlight("white")),
- run_time = 5.0
- )
-
- self.play(*[
- DelayByOrder(FadeIn(mob))
- for mob in arrow, curr_num
- ])
- self.dither()
- for num in numbers[1:] + [text]:
- curr_num.points = np.array(list(reversed(curr_num.points)))
- self.play(
- ShowCreation(
- curr_num,
- alpha_func = lambda t : smooth(1-t)
- ),
- ShowCreation(num)
- )
- self.remove(curr_num)
- curr_num = num
- self.dither()
-
-class ZoomInOnOne(Scene):
- def construct(self):
- num_iterations = 8
- number_line = NumberLine(interval_size = 1, radius = SPACE_WIDTH+2)
- number_line.filter_out(lambda (x, y, z):abs(y)>0.1)
- nl_with_nums = deepcopy(number_line).add_numbers()
- self.play(ApplyMethod(nl_with_nums.shift, 2*LEFT))
- zero, one, two = [
- tex_mobject(str(n)).scale(0.5).shift(0.4*DOWN+2*(-1+n)*RIGHT)
- for n in 0, 1, 2
- ]
- self.play(
- FadeOut(nl_with_nums),
- *[Animation(mob) for mob in zero, one, two, number_line]
- )
- self.remove(nl_with_nums, number_line, zero, two)
- powers_of_10 = [10**(-n) for n in range(num_iterations+1)]
- number_pairs = [(1-epsilon, 1+epsilon) for epsilon in powers_of_10]
- for count in range(num_iterations):
- self.zoom_with_numbers(number_pairs[count], number_pairs[count+1])
- self.clear()
- self.add(one)
-
- def zoom_with_numbers(self, numbers, next_numbers):
- all_numbers = map(
- lambda (n, u): tex_mobject(str(n)).scale(0.5).shift(0.4*DOWN+2*u*RIGHT),
- zip(numbers+next_numbers, it.cycle([-1, 1]))
- )
-
- num_levels = 3
- scale_val = 10
- number_lines = [
- NumberLine(
- interval_size = 1,
- density = scale_val*DEFAULT_POINT_DENSITY_1D
- ).filter_out(
- lambda (x, y, z):abs(y)>0.1
- ).scale(1.0/scale_val**x)
- for x in range(num_levels)
- ]
- kwargs = {"alpha_func" : None}
- self.play(*[
- ApplyMethod(number_lines[x].scale, scale_val, **kwargs)
- for x in range(1, num_levels)
- ]+[
- ApplyMethod(number_lines[0].stretch, scale_val, 0, **kwargs),
- ]+[
- ApplyMethod(
- all_numbers[i].shift,
- 2*LEFT*(scale_val-1)*(-1)**i,
- **kwargs
- )
- for i in 0, 1
- ]+[
- Transform(Point(0.4*DOWN + u*0.2*RIGHT), num, **kwargs)
- for u, num in zip([-1, 1], all_numbers[2:])
- ])
- self.remove(*all_numbers)
-
-
-class DefineInfiniteSum(Scene):
- def construct(self):
- self.put_expression_in_corner()
- self.list_partial_sums()
- self.dither()
-
- def put_expression_in_corner(self):
- buff = 0.24
- define, infinite_sum = tex_mobject([
- "\\text{\\emph{Define} }",
- "\\sum_{n = 0}^\\infty a_n = X"
- ]).split()
- define.highlight("skyblue")
- expression = CompoundMobject(define, infinite_sum)
-
- self.add(expression)
- self.dither()
- self.play(ApplyFunction(
- lambda mob : mob.scale(0.5).to_corner(UP+LEFT, buff = buff),
- expression
- ))
- bottom = (min(expression.points[:,1]) - buff)*UP
- side = (max(expression.points[:,0]) + buff)*RIGHT
- lines = [
- Line(SPACE_WIDTH*LEFT+bottom, side+bottom),
- Line(SPACE_HEIGHT*UP+side, side+bottom)
- ]
- self.play(*[
- ShowCreation(line.highlight("white"))
- for line in lines
- ])
- self.dither()
-
- def list_partial_sums(self):
- num_terms = 10
- term_strings = reduce(op.add, [
- [
- "s_%d"%n,
- "&=",
- "+".join(["a_%d"%k for k in range(n+1)])+"\\\\"
- ]
- for n in range(num_terms)
- ])
- terms = tex_mobject(term_strings, size = "\\large").split()
- number_line = NumberLine()
- ex_point = 2*RIGHT
- ex = tex_mobject("X").shift(ex_point + LEFT + UP)
- arrow = Arrow(ex_point, tail = ex.points[-1]).nudge()
-
- for term, count in zip(terms, it.count()):
- self.add(term)
- self.dither(0.1)
- if count % 3 == 2:
- self.dither(0.5)
- self.dither()
- esses = np.array(terms)[range(0, len(terms), 3)]
- other_terms = filter(lambda m : m not in esses, terms)
- self.play(*[
- ApplyMethod(ess.highlight, "yellow")
- for ess in esses
- ])
-
- def move_s(s, n):
- s.center()
- s.scale(1.0/(n+1))
- s.shift(ex_point-RIGHT*2.0/2**n)
- return s
- self.play(*[
- FadeOut(term)
- for term in other_terms
- ]+[
- ApplyFunction(lambda s : move_s(s, n), ess)
- for ess, n in zip(esses, it.count())
- ]+[
- FadeIn(number_line),
- FadeIn(ex),
- FadeIn(arrow)
- ])
-
- lines = [
- Line(x+0.25*DOWN, x+0.25*UP).highlight("white")
- for y in [-1, -0.01, 1, 0.01]
- for x in [ex_point+y*RIGHT]
- ]
- self.play(*[
- Transform(lines[x], lines[x+1], run_time = 3.0)
- for x in 0, 2
- ])
-
-
-class YouJustInventedSomeMath(Scene):
- def construct(self):
- text = text_mobject([
- "You ", "just ", "invented\\\\", "some ", "math"
- ]).split()
- for mob in text[:3]:
- mob.shift(UP)
- for mob in text[3:]:
- mob.shift(1.3*DOWN)
- # you = draw_you().center().rewire_part_attributes()
- # smile = PiCreature().mouth.center().shift(you.mouth.get_center())
- you = PiCreature().highlight("grey")
- you.center().rewire_part_attributes()
-
- self.add(you)
- for mob in text:
- self.add(mob)
- self.dither(0.2)
- self.play(WaveArm(you))
- self.play(BlinkPiCreature(you))
-
-
-
-class SeekMoreGeneralTruths(Scene):
- def construct(self):
- summands = [
- "\\frac{1}{3^n}",
- "2^n",
- "\\frac{1}{n^2}",
- "\\frac{(-1)^n}{n}",
- "\\frac{(-1)^n}{(2n)!}",
- "\\frac{2\sqrt{2}}{99^2}\\frac{(4n)!}{(n!)^4} \\cdot \\frac{26390n + 1103}{396^{4k}}",
- ]
- sums = tex_mobject([
- "&\\sum_{n = 0}^\\infty" + summand + "= ? \\\\"
- for summand in summands
- ], size = "")
- sums.stretch_to_fit_height(2*SPACE_HEIGHT-1)
- sums.shift((SPACE_HEIGHT-0.5-max(sums.points[:,1]))*UP)
-
- for qsum in sums.split():
- qsum.sort_points(lambda p : np.dot(p, DOWN+RIGHT))
- self.play(DelayByOrder(FadeIn(qsum)))
- self.dither(0.5)
- self.dither()
-
-class ChopIntervalInProportions(Scene):
- args_list = [("9", ), ("p", )]
- @staticmethod
- def args_to_string(*args):
- return args[0]
-
- def construct(self, mode):
- if mode == "9":
- prop = 0.1
- num_terms = 2
- left_terms, right_terms = [
- [
- tex_mobject("\\frac{%d}{%d}"%(k, (10**(count+1))))
- for count in range(num_terms)
- ]
- for k in 9, 1
- ]
- if mode == "p":
- num_terms = 4
- prop = 0.7
- left_terms = map(tex_mobject, ["(1-p)", ["p","(1-p)"]]+[
- ["p^%d"%(count), "(1-p)"]
- for count in range(2, num_terms)
- ])
- right_terms = map(tex_mobject, ["p"] + [
- ["p", "^%d"%(count+1)]
- for count in range(1, num_terms)
- ])
- interval = zero_to_one_interval()
- left = INTERVAL_RADIUS*LEFT
- right = INTERVAL_RADIUS*RIGHT
- left_paren = tex_mobject("(")
- right_paren = tex_mobject(")").shift(right + 1.1*UP)
- curr = left.astype("float")
- brace_to_replace = None
- term_to_replace = None
-
- self.add(interval)
- additional_anims = []
- for lt, rt, count in zip(left_terms, right_terms, it.count()):
- last = deepcopy(curr)
- curr += 2*RIGHT*INTERVAL_RADIUS*(1-prop)*(prop**count)
- braces = [
- underbrace(a, b).rotate(np.pi, RIGHT)
- for a, b in [(last, curr), (curr, right)]
- ]
- for term, brace, count2 in zip([lt, rt], braces, it.count()):
- term.scale(0.75)
- term.shift(brace.get_center()+UP)
- if term.get_width() > brace.get_width():
- term.shift(UP+1.5*(count-2)*RIGHT)
- arrow = Arrow(
- brace.get_center()+0.3*UP,
- tail = term.get_center()+0.5*DOWN
- )
- arrow.points = np.array(list(reversed(arrow.points)))
- additional_anims = [ShowCreation(arrow)]
- if brace_to_replace is not None:
- if mode == "p":
- lt, rt = lt.split(), rt.split()
- if count == 1:
- new_term_to_replace = deepcopy(term_to_replace)
- new_term_to_replace.center().shift(last+UP+0.3*LEFT)
- left_paren.center().shift(last+1.1*UP)
- self.play(
- FadeIn(lt[1]),
- FadeIn(rt[0]),
- Transform(
- brace_to_replace.repeat(2),
- CompoundMobject(*braces)
- ),
- FadeIn(left_paren),
- FadeIn(right_paren),
- Transform(term_to_replace, new_term_to_replace),
- *additional_anims
- )
- self.dither()
- self.play(
- Transform(
- term_to_replace,
- CompoundMobject(lt[0], rt[1])
- ),
- FadeOut(left_paren),
- FadeOut(right_paren)
- )
- self.remove(left_paren, right_paren)
- else:
- self.play(
- FadeIn(lt[1]),
- FadeIn(rt[0]),
- Transform(
- brace_to_replace.repeat(2),
- CompoundMobject(*braces)
- ),
- Transform(
- term_to_replace,
- CompoundMobject(lt[0], rt[1])
- ),
- *additional_anims
- )
- self.remove(*lt+rt)
- lt, rt = CompoundMobject(*lt), CompoundMobject(*rt)
- self.add(lt, rt)
- else:
- self.play(
- Transform(
- brace_to_replace.repeat(2),
- CompoundMobject(*braces)
- ),
- Transform(
- term_to_replace,
- CompoundMobject(lt, rt)
- ),
- *additional_anims
- )
- self.remove(brace_to_replace, term_to_replace)
- self.add(lt, rt, *braces)
- else:
- self.play(*[
- FadeIn(mob)
- for mob in braces + [lt, rt]
- ] + additional_anims)
- self.dither()
- brace_to_replace = braces[1]
- term_to_replace = rt
- if mode == "9":
- split_100 = tex_mobject("\\frac{9}{1000}+\\frac{1}{1000}")
- split_100.scale(0.5)
- split_100.shift(right_terms[-1].get_center())
- split_100.to_edge(RIGHT)
- split_100.sort_points()
- right_terms[-1].sort_points()
- self.play(Transform(
- right_terms[-1], split_100
- ))
- self.dither()
-
-
-
-class GeometricSum(RearrangeEquation):
- def construct(self):
- start_terms = "(1-p) + p (1-p) + p^2 (1-p) + p^3 (1-p) + \\cdots = 1"
- end_terms = "1 + p + p^2 + p^3 + \\cdots = \\frac{1}{(1-p)}"
- index_map = {
- 0 : 0,
- # 0 : -1, #(1-p)
- 1 : 1, #+
- 2 : 2, #p
- # 3 : -1, #(1-p)
- 4 : 3, #+
- 5 : 4, #p^2
- # 6 : -1, #(1-p)
- 7 : 5, #+
- 8 : 6, #p^3
- # 9 : -1, #(1-p)
- 10: 7, #+
- 11: 8, #\\cdots
- 12: 9, #=
- 13: 10, #1
- }
- def start_transform(mob):
- return mob.scale(1.3).shift(2*UP)
- def end_transform(mob):
- return mob.scale(1.3).shift(DOWN)
-
- RearrangeEquation.construct(
- self,
- start_terms.split(" "), end_terms.split(" "),
- index_map, size = "\\large",
- path = counterclockwise_path(),
- start_transform = start_transform,
- end_transform = end_transform,
- leave_start_terms = True,
- transform_kwargs = {"run_time" : 2.0}
- )
-
-class PointNineRepeating(RearrangeEquation):
- def construct(self):
- start_terms = [
- "\\frac{9}{10}",
- "+",
- "\\frac{9}{100}",
- "+",
- "\\frac{9}{1000}",
- "+",
- "\\cdots=1",
- ]
- end_terms = "0 . 9 9 9 \\cdots=1".split(" ")
- index_map = {
- 0 : 2,
- 2 : 3,
- 4 : 4,
- 6 : 5,
- }
- for term in tex_mobject(start_terms).split():
- self.add(term)
- self.dither(0.5)
- self.clear()
- RearrangeEquation.construct(
- self,
- start_terms,
- end_terms,
- index_map,
- path = straight_path
- )
-
-
-class PlugNumbersIntoRightside(Scene):
- def construct(self):
- scale_factor = 1.5
- lhs, rhs = tex_mobject(
- ["1 + p + p^2 + p^3 + \\cdots = ", "\\frac{1}{1-p}"],
- size = "\\large"
- ).scale(scale_factor).split()
- rhs = tex_mobject(
- ["1 \\over 1 - ", "p"],
- size = "\\large"
- ).replace(rhs).split()
- num_strings = [
- "0.5", "3", "\pi", "(-1)", "3.7", "2",
- "0.2", "27", "i"
- ]
- nums = [
- tex_mobject(num_string, size="\\large")
- for num_string in num_strings
- ]
- for num, num_string in zip(nums, num_strings):
- num.scale(scale_factor)
- num.shift(rhs[1].get_center())
- num.shift(0.1*RIGHT + 0.08*UP)
- num.highlight("green")
- if num_string == "(-1)":
- num.shift(0.3*RIGHT)
- right_words = text_mobject(
- "This side makes sense for almost any value of $p$,"
- ).shift(2*UP)
- left_words = text_mobject(
- "even if it seems like this side will not."
- ).shift(2*DOWN)
- right_words.add(Arrow(
- rhs[0].get_center(),
- tail = right_words.get_center()+DOWN+RIGHT
- ).nudge(0.5))
- left_words.add(Arrow(
- lhs.get_center() + 0.3*DOWN,
- tail = left_words.get_center() + 0.3*UP
- ))
- right_words.highlight("green")
- left_words.highlight("yellow")
-
-
- self.add(lhs, *rhs)
- self.dither()
- self.play(FadeIn(right_words))
- curr = rhs[1]
- for num, count in zip(nums, it.count()):
- self.play(CounterclockwiseTransform(curr, num))
- self.dither()
- if count == 2:
- self.play(FadeIn(left_words))
-
-
-class PlugInNegativeOne(RearrangeEquation):
- def construct(self):
- num_written_terms = 4
- start_terms = reduce(op.add, [
- ["(-", "1", ")^%d"%n, "+"]
- for n in range(num_written_terms)
- ]) + ["\\cdots=", "\\frac{1}{1-(-1)}"]
- end_terms = "1 - 1 + 1 - 1 + \\cdots= \\frac{1}{2}".split(" ")
- index_map = dict([
- (4*n + 1, 2*n)
- for n in range(num_written_terms)
- ]+[
- (4*n + 3, 2*n + 1)
- for n in range(num_written_terms)
- ])
- index_map[-2] = -2
- index_map[-1] = -1
- RearrangeEquation.construct(
- self,
- start_terms,
- end_terms,
- index_map,
- path = straight_path,
- start_transform = lambda m : m.shift(2*UP),
- leave_start_terms = True,
- )
-
-class PlugInTwo(RearrangeEquation):
- def construct(self):
- num_written_terms = 4
- start_terms = reduce(op.add, [
- ["2", "^%d"%n, "+"]
- for n in range(num_written_terms)
- ]) + ["\\cdots=", "\\frac{1}{1-2}"]
- end_terms = "1 + 2 + 4 + 8 + \\cdots= -1".split(" ")
- index_map = dict([
- (3*n, 2*n)
- for n in range(num_written_terms)
- ]+[
- (3*n + 2, 2*n + 1)
- for n in range(num_written_terms)
- ])
- index_map[-2] = -2
- index_map[-1] = -1
- RearrangeEquation.construct(
- self,
- start_terms,
- end_terms,
- index_map,
- size = "\\Huge",
- path = straight_path,
- start_transform = lambda m : m.shift(2*UP),
- leave_start_terms = True,
- )
-
-class ListPartialDivergentSums(Scene):
- args_list = [
- (
- lambda n : "1" if n%2 == 0 else "(-1)",
- lambda n : "1" if n%2 == 0 else "0"
- ),
- (
- lambda n : "2^%d"%n if n > 1 else ("1" if n==0 else "2"),
- lambda n : str(2**(n+1)-1)
- )
- ]
- @staticmethod
- def args_to_string(*args):
- if args[0](1) == "(-1)":
- return "Negative1"
- else:
- return args[0](1)
- def construct(self, term_func, partial_sum_func):
- num_lines = 8
- rhss = [
- partial_sum_func(n)
- for n in range(num_lines)
- ]
- lhss = [
- "&=" + \
- "+".join([term_func(k) for k in range(n+1)]) + \
- "\\\\"
- for n in range(num_lines)
- ]
- terms = tex_mobject(
- list(it.chain.from_iterable(zip(rhss, lhss))) + ["\\vdots&", ""],
- size = "\\large"
- ).shift(RIGHT).split()
- words = text_mobject("These numbers don't \\\\ approach anything")
- words.to_edge(LEFT)
- arrow = Arrow(3*DOWN+2*LEFT, direction = DOWN, length = 6)
-
- for x in range(0, len(terms), 2):
- self.play(FadeIn(terms[x]), FadeIn(terms[x+1]))
- self.play(FadeIn(words), ShowCreation(arrow))
- for x in range(0, len(terms), 2):
- self.play(
- ApplyMethod(terms[x].highlight, "green"),
- run_time = 0.1
- )
- self.dither()
-
-class NotARobot(Scene):
- def construct(self):
- you = draw_you().center()
- top_words = text_mobject("You are a mathematician,")
- low_words = text_mobject("not a robot.")
- top_words.shift(1.5*UP)
- low_words.shift(1.5*DOWN)
-
- self.add(you)
- self.play(ShimmerIn(top_words))
- self.play(ShimmerIn(low_words))
-
-
-class SumPowersOfTwoAnimation(Scene):
- def construct(self):
- iterations = 5
- dot = Dot(density = 3*DEFAULT_POINT_DENSITY_1D).scale(1.5)
- dot_width = dot.get_width()*RIGHT
- dot_buff = 0.2*RIGHT
- left = (SPACE_WIDTH-1)*LEFT
- right = left + 2*dot_width + dot_buff
- top_brace_left = left+dot_width+dot_buff+0.3*DOWN
- bottom_brace_left = left + 0.3*DOWN
- circle = Circle().scale(dot_width[0]/2).shift(left+dot_width/2)
- curr_dots = deepcopy(dot).shift(left+1.5*dot_width+dot_buff)
- topbrace = underbrace(top_brace_left, right).rotate(np.pi, RIGHT)
- bottombrace = underbrace(bottom_brace_left, right)
- colors = Color("yellow").range_to("purple", iterations)
- curr_dots.highlight(colors.next())
- equation = tex_mobject(
- "1+2+4+\\cdots+2^n=2^{n+1} - 1",
- size = "\\Huge"
- ).shift(3*UP)
- full_top_sum = tex_mobject(["1", "+2", "+4", "+8", "+16"]).split()
-
- self.add(equation)
- self.dither()
- self.add(circle, curr_dots, topbrace, bottombrace)
- for n in range(1,iterations):
- bottom_num = tex_mobject(str(2**n))
- new_bottom_num = tex_mobject(str(2**(n+1)))
- bottom_num.shift(bottombrace.get_center()+0.5*DOWN)
-
- top_sum = CompoundMobject(*full_top_sum[:n]).center()
- top_sum_end = deepcopy(full_top_sum[n]).center()
- top_sum.shift(topbrace.get_center()+0.5*UP)
- new_top_sum = CompoundMobject(*full_top_sum[:(n+1)]).center()
- self.add(top_sum, bottom_num)
-
- if n == iterations:
- continue
- new_dot = deepcopy(dot).shift(circle.get_center())
- shift_val = (2**n)*(dot_width+dot_buff)
- right += shift_val
- new_dots = CompoundMobject(new_dot, curr_dots)
- new_dots.highlight(colors.next()).shift(shift_val)
- alt_bottombrace = deepcopy(bottombrace).shift(shift_val)
- alt_bottom_num = deepcopy(bottom_num).shift(shift_val)
- alt_topbrace = deepcopy(alt_bottombrace).rotate(np.pi, RIGHT)
- top_sum_end.shift(alt_topbrace.get_center()+0.5*UP)
- new_topbrace = underbrace(top_brace_left, right).rotate(np.pi, RIGHT)
- new_bottombrace = underbrace(bottom_brace_left, right)
- new_bottom_num.shift(new_bottombrace.get_center()+0.5*DOWN)
- new_top_sum.shift(new_topbrace.get_center()+0.5*UP)
- for exp, brace in [
- (top_sum, topbrace),
- (top_sum_end, alt_topbrace),
- (new_top_sum, new_topbrace),
- ]:
- if exp.get_width() > brace.get_width():
- exp.stretch_to_fit_width(brace.get_width())
- new_top_sum = new_top_sum.split()
- new_top_sum_start = CompoundMobject(*new_top_sum[:-1])
- new_top_sum_end = new_top_sum[-1]
-
- self.dither()
- self.play(*[
- FadeIn(mob)
- for mob in [
- new_dots,
- alt_topbrace,
- alt_bottombrace,
- top_sum_end,
- alt_bottom_num,
- ]
- ])
- self.dither()
- self.play(
- Transform(topbrace, new_topbrace),
- Transform(alt_topbrace, new_topbrace),
- Transform(bottombrace, new_bottombrace),
- Transform(alt_bottombrace, new_bottombrace),
- Transform(bottom_num, new_bottom_num),
- Transform(alt_bottom_num, new_bottom_num),
- Transform(top_sum, new_top_sum_start),
- Transform(top_sum_end, new_top_sum_end)
- )
- self.remove(
- bottom_num, alt_bottom_num, top_sum,
- top_sum_end, new_top_sum_end,
- alt_topbrace, alt_bottombrace
- )
- curr_dots = CompoundMobject(curr_dots, new_dots)
-
-
-class PretendTheyDoApproachNegativeOne(RearrangeEquation):
- def construct(self):
- num_lines = 6
- da = "\\downarrow"
- columns = [
- tex_mobject("\\\\".join([
- n_func(n)
- for n in range(num_lines)
- ]+last_bits), size = "\\Large").to_corner(UP+LEFT)
- for n_func, last_bits in [
- (lambda n : str(2**(n+1)-1), ["\\vdots", da, "-1"]),
- (lambda n : "+1", ["", "", "+1"]),
- (lambda n : "=", ["", "", "="]),
- (lambda n : str(2**(n+1)), ["\\vdots", da, "0"]),
- ]
- ]
- columns[-1].highlight()
- columns[2].shift(0.2*DOWN)
- shift_val = 3*RIGHT
- for column in columns:
- column.shift(shift_val)
- shift_val = shift_val + (column.get_width()+0.2)*RIGHT
- self.play(ShimmerIn(columns[0]))
- self.dither()
- self.add(columns[1])
- self.dither()
- self.play(
- DelayByOrder(Transform(deepcopy(columns[0]), columns[-1])),
- FadeIn(columns[2])
- )
- self.dither()
-
-class DistanceBetweenRationalNumbers(Scene):
- def construct(self):
- locii = [2*LEFT, 2*RIGHT]
- nums = [
- tex_mobject(s).shift(1.3*d)
- for s, d in zip(["\\frac{1}{2}", "3"], locii)
- ]
- arrows = [
- Arrow(direction, tail = ORIGIN)
- for direction in locii
- ]
- dist = tex_mobject("\\frac{5}{2}").scale(0.5).shift(0.5*UP)
- text = text_mobject("How we define distance between rational numbers")
- text.to_edge(UP)
- self.add(text, *nums)
- self.play(*[ShowCreation(arrow) for arrow in arrows])
- self.play(ShimmerIn(dist))
- self.dither()
-
-class NotTheOnlyWayToOrganize(Scene):
- def construct(self):
- self.play(ShowCreation(NumberLine().add_numbers()))
- self.dither()
- words = "Is there any other reasonable way to organize numbers?"
- self.play(FadeIn(text_mobject(words).shift(2*UP)))
- self.dither()
-
-class DistanceIsAFunction(Scene):
- args_list = [
- ("Euclidian",),
- ("Random",),
- ("2adic",),
- ]
- @staticmethod
- def args_to_string(word):
- return word
-
- def construct(self, mode):
- if mode == "Euclidian":
- dist_text = "dist"
- elif mode == "Random":
- dist_text = "random\\_dist"
- elif mode == "2adic":
- dist_text = "2\\_adic\\_dist"
- dist, r_paren, arg0, comma, arg1, l_paren, equals, result = text_mobject([
- dist_text, "(", "000", ",", "000", ")", "=", "000"
- ]).split()
- point_origin = comma.get_center()+0.2*UP
- if mode == "Random":
- examples = [
- ("2", "3", "7"),
- ("\\frac{1}{2}", "100", "\\frac{4}{5}"),
- ]
- dist.highlight("orange")
- self.add(dist)
- self.dither()
- elif mode == "Euclidian":
- examples = [
- ("1", "5", "4"),
- ("\\frac{1}{2}", "3", "\\frac{5}{2}"),
- ("-3", "3", "6"),
- ("2", "3", "1"),
- ("0", "4", "x"),
- ("1", "5", "x"),
- ("2", "6", "x"),
- ]
- elif mode == "2adic":
- examples = [
- ("2", "0", "\\frac{1}{2}"),
- ("-1", "15", "\\frac{1}{16}"),
- ("3", "7", "\\frac{1}{4}"),
- ("\\frac{3}{2}", "1", "2"),
- ]
- dist.highlight("green")
- self.add(dist)
- self.dither()
- example_mobs = [
- (
- tex_mobject(tup[0]).shift(arg0.get_center()),
- tex_mobject(tup[1]).shift(arg1.get_center()),
- tex_mobject(tup[2]).shift(result.get_center())
- )
- for tup in examples
- ]
-
- self.add(dist, r_paren, comma, l_paren, equals)
- previous = None
- kwargs = {"run_time" : 0.5}
- for mobs in example_mobs:
- if previous:
- self.play(*[
- DelayByOrder(Transform(prev, mob, **kwargs))
- for prev, mob in zip(previous, mobs)[:-1]
- ])
- self.play(DelayByOrder(Transform(
- previous[-1], mobs[-1], **kwargs
- )))
- self.remove(*previous)
- self.add(*mobs)
- previous = mobs
- self.dither()
-
-class ShiftInvarianceNumberLine(Scene):
- def construct(self):
- number_line = NumberLine().add_numbers()
- topbrace = underbrace(ORIGIN, 2*RIGHT).rotate(np.pi, RIGHT)
- dist0 = text_mobject(["dist(", "$0$", ",", "$2$",")"])
- dist1 = text_mobject(["dist(", "$2$", ",", "$4$",")"])
- for dist in dist0, dist1:
- dist.shift(topbrace.get_center()+0.3*UP)
- dist1.shift(2*RIGHT)
- footnote = text_mobject("""
- \\begin{flushleft}
- *yeah yeah, I know I'm still drawing them on a line,
- but until a few minutes from now I have no other way
- to draw them
- \\end{flushright}
- """).scale(0.5).to_corner(DOWN+RIGHT)
-
- self.add(number_line, topbrace, dist0, footnote)
- self.dither()
- self.remove(dist0)
- self.play(
- ApplyMethod(topbrace.shift, 2*RIGHT),
- *[
- Transform(*pair)
- for pair in zip(dist0.split(), dist1.split())
- ]
- )
- self.dither()
-
-class NameShiftInvarianceProperty(Scene):
- def construct(self):
- prop = text_mobject([
- "dist($A$, $B$) = dist(",
- "$A+x$, $B+x$",
- ") \\quad for all $x$"
- ])
- mid_part = prop.split()[1]
- u_brace = underbrace(
- mid_part.get_boundary_point(DOWN+LEFT),
- mid_part.get_boundary_point(DOWN+RIGHT)
- ).shift(0.3*DOWN)
- label = text_mobject("Shifted values")
- label.shift(u_brace.get_center()+0.5*DOWN)
- name = text_mobject("``Shift Invariance''")
- name.highlight("green").to_edge(UP)
- for mob in u_brace, label:
- mob.highlight("yellow")
-
- self.add(prop)
- self.play(ShimmerIn(label), ShimmerIn(u_brace))
- self.dither()
- self.play(ShimmerIn(name))
- self.dither()
-
-
-class TriangleInequality(Scene):
- def construct(self):
- symbols = ["A", "B", "C"]
- locations = [2*(DOWN+LEFT), UP, 4*RIGHT]
- ab, plus, bc, greater_than, ac = text_mobject([
- "dist($A$, $B$)",
- "$+$",
- "dist($B$, $C$)",
- "$>$",
- "dist($A$, $C$)",
- ]).to_edge(UP).split()
- all_dists = [ab, ac, bc]
- ab_line, ac_line, bc_line = all_lines = [
- Line(*pair).scale_in_place(0.8)
- for pair in it.combinations(locations, 2)
- ]
- def put_on_line(mob, line):
- result = deepcopy(mob).center().scale(0.5)
- result.rotate(np.arctan(line.get_slope()))
- result.shift(line.get_center()+0.2*UP)
- return result
- ab_copy, ac_copy, bc_copy = all_copies = [
- put_on_line(dist, line)
- for dist, line in zip(all_dists, all_lines)
- ]
- for symbol, loc in zip(symbols, locations):
- self.add(tex_mobject(symbol).shift(loc))
- self.play(ShowCreation(ac_line), FadeIn(ac_copy))
- self.dither()
- self.play(*[
- ShowCreation(line) for line in ab_line, bc_line
- ]+[
- FadeIn(dist) for dist in ab_copy, bc_copy
- ])
- self.dither()
- self.play(*[
- Transform(*pair)
- for pair in zip(all_copies, all_dists)
- ]+[
- FadeIn(mob)
- for mob in plus, greater_than
- ])
- self.dither()
-
-
-
-class StruggleToFindFrameOfMind(Scene):
- def construct(self):
- you, bubble = draw_you(with_bubble = True)
- questions = text_mobject("???", size = "\\Huge").scale(1.5)
- contents = [
- tex_mobject("2, 4, 8, 16, 32, \\dots \\rightarrow 0"),
- text_mobject("dist(0, 2) $<$ dist(0, 64)"),
- NumberLine().sort_points(lambda p : -p[1]).add(
- text_mobject("Not on a line?").shift(UP)
- ),
- ]
- kwargs = {"run_time" : 0.5}
- self.add(you, bubble)
- bubble.add_content(questions)
- for mob in contents:
- curr = bubble.content
- self.remove(curr)
- bubble.add_content(mob)
- for first, second in [(curr, questions), (questions, mob)]:
- copy = deepcopy(first)
- self.play(DelayByOrder(Transform(
- copy, second, **kwargs
- )))
- self.remove(copy)
- self.add(mob)
- self.dither()
-
-
-class RoomsAndSubrooms(Scene):
- def construct(self):
- colors = get_room_colors()
- a_set = [3*RIGHT, 3*LEFT]
- b_set = [1.5*UP, 1.5*DOWN]
- c_set = [LEFT, RIGHT]
- rectangle_groups = [
- [Rectangle(7, 12).highlight(colors[0])],
- [
- Rectangle(6, 5).shift(a).highlight(colors[1])
- for a in a_set
- ],
- [
- Rectangle(2, 4).shift(a + b).highlight(colors[2])
- for a in a_set
- for b in b_set
- ],
- [
- Rectangle(1, 1).shift(a+b+c).highlight(colors[3])
- for a in a_set
- for b in b_set
- for c in c_set
- ]
- ]
-
- for group in rectangle_groups:
- mob = CompoundMobject(*group)
- mob.sort_points(np.linalg.norm)
- self.play(ShowCreation(mob))
-
- self.dither()
-
-
-class RoomsAndSubroomsWithNumbers(Scene):
- def construct(self):
- zero_local = (SPACE_WIDTH-0.5)*LEFT
- zero_one_width = SPACE_WIDTH-0.3
-
- zero, power_mobs = self.draw_numbers(zero_local, zero_one_width)
- self.dither()
- rectangles = self.draw_first_rectangles(zero_one_width)
- rect_clusters = self.draw_remaining_rectangles(rectangles)
- self.adjust_power_mobs(zero, power_mobs, rect_clusters[-1])
- self.dither()
- num_mobs = self.draw_remaining_numbers(
- zero, power_mobs, rect_clusters
- )
- self.dither()
- self.add_negative_one(num_mobs)
- self.dither()
- self.show_distances(num_mobs, rect_clusters)
-
-
- def draw_numbers(self, zero_local, zero_one_width):
- num_numbers = 5
- zero = tex_mobject("0").shift(zero_local)
- self.add(zero)
- nums = []
- for n in range(num_numbers):
- num = tex_mobject(str(2**n))
- num.scale(1.0/(n+1))
- num.shift(
- zero_local+\
- RIGHT*zero_one_width/(2.0**n)+\
- LEFT*0.05*n+\
- (0.4*RIGHT if n == 0 else ORIGIN) #Stupid
- )
- self.play(FadeIn(num, run_time = 0.5))
- nums.append(num)
- return zero, nums
-
- def draw_first_rectangles(self, zero_one_width):
- side_buff = 0.05
- upper_buff = 0.5
- colors = get_room_colors()
- rectangles = []
- for n in range(4):
- rect = Rectangle(
- 2*SPACE_HEIGHT-(n+2)*upper_buff,
- zero_one_width/(2**n)-0.85*(n+1)*side_buff
- )
- rect.sort_points(np.linalg.norm)
- rect.to_edge(LEFT, buff = 0.2).shift(n*side_buff*RIGHT)
- rect.highlight(colors[n])
- rectangles.append(rect)
- for rect in rectangles:
- self.play(ShowCreation(rect))
- self.dither()
- return rectangles
-
- def draw_remaining_rectangles(self, rectangles):
- clusters = []
- centers = [ORIGIN] + map(Mobject.get_center, rectangles)
- shift_vals = [
- 2*(c2 - c1)[0]*RIGHT
- for c1, c2 in zip(centers[1:], centers)
- ]
- for rectangle, count in zip(rectangles, it.count(1)):
- cluster = [rectangle]
- for shift_val in shift_vals[:count]:
- cluster += map(
- lambda mob : mob.shift(shift_val),
- deepcopy(cluster)
- )
- clusters.append(cluster)
- for rect in cluster[1:]:
- self.play(FadeIn(rect, run_time = 0.6**(count-1)))
- return clusters
-
- def adjust_power_mobs(self, zero, power_mobs, small_rects):
- new_zero = deepcopy(zero)
- self.center_in_closest_rect(new_zero, small_rects)
- new_power_mobs = deepcopy(power_mobs)
- for mob, count in zip(new_power_mobs, it.count(1)):
- self.center_in_closest_rect(mob, small_rects)
- new_power_mobs[-1].shift(DOWN)
- dots = tex_mobject("\\vdots")
- dots.scale(0.5).shift(new_zero.get_center()+0.5*DOWN)
- self.play(
- Transform(zero, new_zero),
- FadeIn(dots),
- *[
- Transform(old, new)
- for old, new in zip(power_mobs, new_power_mobs)
- ]
- )
-
- def draw_remaining_numbers(self, zero, power_mobs, rect_clusters):
- small_rects = rect_clusters[-1]
- max_width = 0.8*small_rects[0].get_width()
- max_power = 4
- num_mobs = [None]*(2**max_power + 1)
- num_mobs[0] = zero
- powers = [2**k for k in range(max_power+1)]
- for p, index in zip(powers, it.count()):
- num_mobs[p] = power_mobs[index]
- for power, count in zip(powers[1:-1], it.count(1)):
- zero_copy = deepcopy(zero)
- power_mob_copy = deepcopy(num_mobs[power])
- def transform(mob):
- self.center_in_closest_rect(mob, small_rects)
- mob.shift(UP)
- return mob
- self.play(*[
- ApplyFunction(transform, mob)
- for mob in zero_copy, power_mob_copy
- ])
- last_left_mob = zero
- for n in range(power+1, 2*power):
- left_mob = num_mobs[n-power]
- shift_val = left_mob.get_center()-last_left_mob.get_center()
- self.play(*[
- ApplyMethod(mob.shift, shift_val)
- for mob in zero_copy, power_mob_copy
- ])
- num_mobs[n] = tex_mobject(str(n))
- num_mobs[n].scale(1.0/(power_of_divisor(n, 2)+1))
- width_ratio = max_width / num_mobs[n].get_width()
- if width_ratio < 1:
- num_mobs[n].scale(width_ratio)
- num_mobs[n].shift(power_mob_copy.get_center()+DOWN)
- self.center_in_closest_rect(num_mobs[n], small_rects)
- point = Point(power_mob_copy.get_center())
- self.play(Transform(point, num_mobs[n]))
- self.remove(point)
- self.add(num_mobs[n])
- last_left_mob = left_mob
- self.remove(zero_copy, power_mob_copy)
- self.dither()
- return num_mobs
-
- @staticmethod
- def center_in_closest_rect(mobject, rectangles):
- center = mobject.get_center()
- diffs = [r.get_center()-center for r in rectangles]
- mobject.shift(diffs[np.argmin(map(np.linalg.norm, diffs))])
-
- def add_negative_one(self, num_mobs):
- neg_one = tex_mobject("-1").scale(0.5)
- shift_val = num_mobs[15].get_center()-neg_one.get_center()
- neg_one.shift(UP)
- self.play(ApplyMethod(neg_one.shift, shift_val))
-
- def show_distances(self, num_mobs, rect_clusters):
- self.remove(*[r for c in rect_clusters for r in c])
- text = None
- for cluster, count in zip(rect_clusters, it.count()):
- if text is not None:
- self.remove(text)
- if count == 0:
- dist_string = "1"
- else:
- dist_string = "$\\frac{1}{%d}$"%(2**count)
- text = text_mobject(
- "Any of these pairs are considered to be a distance " +\
- dist_string +\
- " away from each other"
- ).shift(2*UP)
- self.add(text)
- self.clear_way_for_text(text, cluster)
- self.add(*cluster)
- pairs = filter(
- lambda (a, b) : (a-b)%(2**count) == 0 and (a-b)%(2**(count+1)) != 0,
- it.combinations(range(16), 2)
- )
- for pair in sample(pairs, min(10, len(pairs))):
- for index in pair:
- num_mobs[index].highlight("green")
- self.play(*[
- ApplyMethod(
- num_mobs[index].rotate_in_place, np.pi/10,
- alpha_func = wiggle
- )
- for index in pair
- ])
- self.dither()
- for index in pair:
- num_mobs[index].highlight("white")
-
- @staticmethod
- def clear_way_for_text(text, mobjects):
- right, top, null = np.max(text.points, 0)
- left, bottom, null = np.min(text.points, 0)
- def filter_func((x, y, z)):
- return x>left and x<right and y>bottom and y<top
- for mobject in mobjects:
- mobject.filter_out(filter_func)
-
-class DeduceWhereNegativeOneFalls(Scene):
- def construct(self):
- part0, arg0, part1, part2, arg1, part3 = text_mobject([
- "dist(-1, ", "0000", ") = ", "dist(0, ", "0000", ")"
- ]).scale(1.5).split()
- u_brace = underbrace(
- part2.get_boundary_point(DOWN+LEFT),
- part3.get_boundary_point(DOWN+RIGHT)
- ).shift(0.3+DOWN)
-
- colors = list(get_room_colors())
- num_labels = len(colors)
- texts = [
- CompoundMobject(parts[0], parts[1].highlight(color))
- for count, color in zip(it.count(), colors)
- for parts in [text_mobject([
- "Represented (heuristically) \\\\ by being in the same \\\\",
- (count*"sub-")+"room"
- ]).split()]
- ]
- target_text_top = u_brace.get_center()+0.5*DOWN
- for text in texts:
- text.shift(target_text_top - text.get_top())
-
- self.add(part0, part1, part2, part3, u_brace)
- last_args = [arg0, arg1]
- for n in range(1, 15):
- rest_time = 0.3 + 1.0/(n+1)
- new_args = [
- text_mobject("$%d$"%k).scale(1.5)
- for k in 2**n-1, 2**n
- ]
- for new_arg, old_arg in zip(new_args, last_args):
- new_arg.shift(old_arg.get_center())
- if last_args != [arg0, arg1]:
- self.play(*[
- DelayByOrder(Transform(*pair, run_time = 0.5*rest_time))
- for pair in zip(last_args, new_args)
- ])
- if n-1 < num_labels:
- self.add(texts[n-1])
- if n > 1:
- self.remove(texts[n-2])
- else:
- self.remove(u_brace, *texts)
- self.remove(*last_args)
- self.add(*new_args)
- self.dither(rest_time)
- last_args = new_args
-
-
-class OtherRationalNumbers(Scene):
- def construct(self):
- import random
- self.add(text_mobject("Where do other \\\\ rational numbers fall?"))
- pairs = [
- (1, 2),
- (1, 3),
- (4, 9),
- (-7, 13),
- (3, 1001),
- ]
- locii = [
- 4*LEFT+2*UP,
- 4*RIGHT,
- 5*RIGHT+UP,
- 4*LEFT+2*DOWN,
- 3*DOWN,
- ]
- for pair, locus in zip(pairs, locii):
- fraction = tex_mobject("\\frac{%d}{%d}"%pair).shift(locus)
- self.play(ShimmerIn(fraction))
- self.dither()
-
-class PAdicMetric(Scene):
- def construct(self):
- p_str, text = text_mobject(["$p$", "-adic metric"]).shift(2*UP).split()
- primes = [tex_mobject(str(p)) for p in [2, 3, 5, 7, 11, 13, 17, 19, 23]]
- p_str.highlight("yellow")
- colors = Color("green").range_to("skyblue", len(primes))
- new_numbers = text_mobject("Completely new types of numbers!")
- new_numbers.highlight("skyblue").shift(2.3*DOWN)
- arrow = Arrow(2*DOWN, tail = 1.7*UP)
-
- curr = deepcopy(p_str)
- self.add(curr, text)
- self.dither()
- for prime, count in zip(primes, it.count()):
- prime.scale(1.0).highlight(colors.next())
- prime.shift(center_of_mass([p_str.get_top(), p_str.get_center()]))
- self.play(DelayByOrder(Transform(curr, prime)))
- self.dither()
- if count == 2:
- self.spill(CompoundMobject(curr, text), arrow, new_numbers)
- self.remove(curr)
- curr = prime
- self.play(DelayByOrder(Transform(curr, p_str)))
- self.dither()
-
- def spill(self, start, arrow, end):
- start.sort_points(lambda p : p[1])
- self.play(
- ShowCreation(
- arrow,
- alpha_func = squish_alpha_func(smooth, 0.5, 1.0)
- ),
- DelayByOrder(Transform(
- start,
- Point(arrow.points[0]).highlight("white")
- ))
- )
- self.play(ShimmerIn(end))
-
-
-class FuzzyDiscoveryToNewMath(Scene):
- def construct(self):
- fuzzy = text_mobject("Fuzzy Discovery")
- fuzzy.to_edge(UP).shift(SPACE_WIDTH*LEFT/2)
- new_math = text_mobject("New Math")
- new_math.to_edge(UP).shift(SPACE_WIDTH*RIGHT/2)
- lines = CompoundMobject(
- Line(DOWN*SPACE_HEIGHT, UP*SPACE_HEIGHT),
- Line(3*UP+LEFT*SPACE_WIDTH, 3*UP+RIGHT*SPACE_WIDTH)
- )
- fuzzy_discoveries = [
- tex_mobject("a^2 + b^2 = c^2"),
- tex_mobject("".join(CONVERGENT_SUM_TEXT)),
- tex_mobject("".join(DIVERGENT_SUM_TEXT)),
- tex_mobject("e^{\pi i} = -1"),
- ]
- triangle_lines = [
- Line(ORIGIN, LEFT),
- Line(LEFT, UP),
- Line(UP, ORIGIN),
- ]
- for line, char in zip(triangle_lines, ["a", "c", "b"]):
- line.highlight("blue")
- char_mob = tex_mobject(char).scale(0.25)
- line.add(char_mob.shift(line.get_center()))
- triangle = CompoundMobject(*triangle_lines)
- triangle.center().shift(1.5*fuzzy_discoveries[0].get_right())
- how_length = text_mobject("But how is length defined?").scale(0.5)
- how_length.shift(0.75*DOWN)
- fuzzy_discoveries[0].add(triangle, how_length)
- new_maths = [
- text_mobject("""
- Define distance between points $(x_0, y_0)$ and
- $(x_1, y_1)$ as $\\sqrt{(x_1-x_0)^2 + (y_1-y_0)^2}$
- """),
- text_mobject("Define ``approach'' and infinite sums"),
- text_mobject("Discover $2$-adic numbers"),
- text_mobject(
- "Realize exponentiation is doing something much \
- different from repeated multiplication"
- )
- ]
- midpoints = []
- triplets = zip(fuzzy_discoveries, new_maths, it.count(2, -1.75))
- for disc, math, count in triplets:
- math.scale(0.65)
- for mob in disc, math:
- mob.to_edge(LEFT).shift(count*UP)
- math.shift(SPACE_WIDTH*RIGHT)
- midpoints.append(count*UP)
-
- self.add(fuzzy, lines)
- self.play(*map(ShimmerIn, fuzzy_discoveries))
- self.dither()
- self.play(DelayByOrder(Transform(
- deepcopy(fuzzy), new_math
- )))
- self.play(*[
- DelayByOrder(Transform(deepcopy(disc), math))
- for disc, math in zip(fuzzy_discoveries, new_maths)
- ])
- self.dither()
-
-
-class DiscoveryAndInvention(Scene):
- def construct(self):
- invention, vs, discovery = text_mobject([
- "Invention ", "vs. ", "Discovery"
- ]).split()
- nrd = text_mobject(
- "Non-rigorous truths"
- ).shift(2*UP)
- rt = text_mobject(
- "Rigorous terms"
- ).shift(2*DOWN)
-
- arrows = []
- self.add(discovery, vs, invention)
- self.dither()
- arrow = Arrow(
- nrd.get_bottom(),
- tail = discovery.get_top()
- )
- self.play(
- FadeIn(nrd),
- ShowCreation(arrow)
- )
- arrows.append(arrow)
- self.dither()
- arrow = Arrow(
- invention.get_top(),
- tail = nrd.get_bottom()
- )
- self.play(ShowCreation(arrow))
- arrows.append(arrow)
- self.dither()
- arrow = Arrow(
- rt.get_top(),
- tail = invention.get_bottom()
- )
- self.play(
- FadeIn(rt),
- ShowCreation(arrow)
- )
- arrows.append(arrow)
- self.dither()
- arrow = Arrow(
- discovery.get_bottom(),
- tail = rt.get_top()
- )
- self.play(ShowCreation(arrow))
- self.dither()
- arrows.append(arrow)
- for color in Color("yellow").range_to("red", 4):
- for arrow in arrows:
- self.play(
- ShowCreation(deepcopy(arrow).highlight(color)),
- run_time = 0.25
- )
-
-
-
-
-if __name__ == "__main__":
- command_line_create_scene(MOVIE_PREFIX)
-
diff --git a/tex_utils.py b/tex_utils.py
index bdceb35be..711fefab7 100644
--- a/tex_utils.py
+++ b/tex_utils.py
@@ -1,7 +1,8 @@
import os
import itertools as it
from PIL import Image
-from constants import *
+
+from helpers import *
#TODO, Cleanup and refactor this file.
diff --git a/topics/__init__.py b/topics/__init__.py
new file mode 100644
index 000000000..53ce17d3e
--- /dev/null
+++ b/topics/__init__.py
@@ -0,0 +1,11 @@
+from arithmetic import *
+from characters import *
+from combinatorics import *
+from complex_numbers import *
+from functions import *
+from geometry import *
+from graph_theory import *
+from matrix_as_transform_2d import *
+from number_line import *
+from pythagorean_proof import *
+from three_dimensions import *
\ No newline at end of file
diff --git a/scene/arithmetic_scenes.py b/topics/arithmetic.py
similarity index 76%
rename from scene/arithmetic_scenes.py
rename to topics/arithmetic.py
index 53b469866..bd2ba48f9 100644
--- a/scene/arithmetic_scenes.py
+++ b/topics/arithmetic.py
@@ -2,13 +2,7 @@ import numpy as np
import itertools as it
from scene import Scene
-from graphs import *
-
-from mobject import *
-from animation import *
-from region import *
-from constants import *
-from helpers import *
+from animation import Animation
class RearrangeEquation(Scene):
def construct(
@@ -87,7 +81,27 @@ class RearrangeEquation(Scene):
return all_mobs[:num_start_terms], all_mobs[num_start_terms:]
+class FlipThroughSymbols(Animation):
+ DEFAULT_CONFIG = {
+ "start_center" : ORIGIN,
+ "end_center" : ORIGIN,
+ }
+ def __init__(self, tex_list, **kwargs):
+ digest_config(self, FlipThroughSymbols, kwargs, locals())
+ self.curr_tex = self.tex_list[0]
+ mobject = tex_mobject(self.curr_tex).shift(start_center)
+ Animation.__init__(self, mobject, **kwargs)
+
+ def update_mobject(self, alpha):
+ new_tex = self.tex_list[np.ceil(alpha*len(self.tex_list))-1]
+ if new_tex != self.curr_tex:
+ self.curr_tex = new_tex
+ self.mobject = tex_mobject(new_tex).shift(self.start_center)
+ if not all(self.start_center == self.end_center):
+ self.mobject.center().shift(
+ (1-alpha)*self.start_center + alpha*self.end_center
+ )
diff --git a/mobject/creatures.py b/topics/characters.py
similarity index 60%
rename from mobject/creatures.py
rename to topics/characters.py
index 9ee7c3c98..a78edf60e 100644
--- a/mobject/creatures.py
+++ b/topics/characters.py
@@ -1,11 +1,7 @@
-import numpy as np
-import itertools as it
-import os
-
-from image_mobject import *
-from mobject import *
-from simple_mobjects import *
+from helpers import *
+from mobject import Mobject, CompoundMobject
+from image_mobject import ImageMobject
class PiCreature(CompoundMobject):
DEFAULT_COLOR = BLUE
@@ -169,11 +165,112 @@ class Mortimer(PiCreature):
self.rotate(np.pi, UP)
+class Bubble(Mobject):
+ DEFAULT_CONFIG = {
+ "direction" : LEFT,
+ "index_of_tip" : -1,
+ "center_point" : ORIGIN,
+ }
+ def __init__(self, **kwargs):
+ digest_config(self, Bubble, kwargs)
+ Mobject.__init__(self, **kwargs)
+ self.center_offset = self.center_point - Mobject.get_center(self)
+ if self.direction[0] > 0:
+ self.rotate(np.pi, UP)
+ self.content = Mobject()
+ def get_tip(self):
+ return self.points[self.index_of_tip]
+ def get_bubble_center(self):
+ return self.get_center()+self.center_offset
+ def move_tip_to(self, point):
+ self.shift(point - self.get_tip())
+ return self
+ def flip(self):
+ self.direction = -np.array(self.direction)
+ self.rotate(np.pi, UP)
+ return self
+ def pin_to(self, mobject):
+ mob_center = mobject.get_center()
+ if (mob_center[0] > 0) != (self.direction[0] > 0):
+ self.flip()
+ boundary_point = mobject.get_boundary_point(UP-self.direction)
+ vector_from_center = 1.5*(boundary_point-mob_center)
+ self.move_tip_to(mob_center+vector_from_center)
+ return self
+ def add_content(self, mobject):
+ scaled_width = 0.75*self.get_width()
+ if mobject.get_width() > scaled_width:
+ mobject.scale(scaled_width / mobject.get_width())
+ mobject.shift(self.get_bubble_center())
+ self.content = mobject
+ return self
+ def write(self, text):
+ self.add_content(text_mobject(text))
+ return self
+
+ def clear(self):
+ self.content = Mobject()
+ return self
+class SpeechBubble(Bubble):
+ DEFAULT_CONFIG = {
+ "initial_width" : 4,
+ "initial_height" : 2,
+ }
+ def __init__(self, **kwargs):
+ digest_config(self, SpeechBubble, kwargs)
+ Bubble.__init__(self, **kwargs)
+
+ def generate_points(self):
+ complex_power = 0.9
+ radius = self.initial_width/2
+ circle = Circle(radius = radius)
+ circle.scale(1.0/radius)
+ circle.apply_complex_function(lambda z : z**complex_power)
+ circle.scale(radius)
+ boundary_point_as_complex = radius*complex(-1)**complex_power
+ boundary_points = [
+ [
+ boundary_point_as_complex.real,
+ unit*boundary_point_as_complex.imag,
+ 0
+ ]
+ for unit in -1, 1
+ ]
+ tip = radius*(1.5*LEFT+UP)
+ self.add(
+ circle,
+ Line(boundary_points[0], tip),
+ Line(boundary_points[1], tip)
+ )
+ self.highlight("white")
+ self.rotate(np.pi/2)
+ self.points[:,1] *= float(self.initial_height)/self.initial_width
+
+class ThoughtBubble(Bubble):
+ DEFAULT_CONFIG = {
+ "num_bulges" : 7,
+ "initial_inner_radius" : 1.8,
+ "initial_width" : 6
+ }
+ def __init__(self, **kwargs):
+ digest_config(self, ThoughtBubble, kwargs)
+ Bubble.__init__(self, **kwargs)
+ self.index_of_tip = np.argmin(self.points[:,1])
+
+ def generate_points(self):
+ self.add(Circle().scale(0.15).shift(2.5*DOWN+2*LEFT))
+ self.add(Circle().scale(0.3).shift(2*DOWN+1.5*LEFT))
+ for n in range(self.num_bulges):
+ theta = 2*np.pi*n/self.num_bulges
+ self.add(Circle().shift((np.cos(theta), np.sin(theta), 0)))
+ self.filter_out(lambda p : np.linalg.norm(p) < self.initial_inner_radius)
+ self.stretch_to_fit_width(self.initial_width)
+ self.highlight("white")
diff --git a/scene/pascals_triangle.py b/topics/combinatorics.py
similarity index 50%
rename from scene/pascals_triangle.py
rename to topics/combinatorics.py
index 627781c83..3b21c2776 100644
--- a/scene/pascals_triangle.py
+++ b/topics/combinatorics.py
@@ -1,17 +1,90 @@
-import numpy as np
-import itertools as it
+from helpers import *
from scene import Scene
-from mobject import *
-from animation import *
-from region import *
-from constants import *
-from helpers import *
+
+DEFAULT_COUNT_NUM_OFFSET = (SPACE_WIDTH - 1, SPACE_HEIGHT - 1, 0)
+DEFAULT_COUNT_RUN_TIME = 5.0
+
+class CountingScene(Scene):
+ def count(self, items, item_type = "mobject", *args, **kwargs):
+ if item_type == "mobject":
+ self.count_mobjects(items, *args, **kwargs)
+ elif item_type == "region":
+ self.count_regions(items, *args, **kwargs)
+ else:
+ raise Exception("Unknown item_type, should be mobject or region")
+ return self
+
+ def count_mobjects(
+ self, mobjects, mode = "highlight",
+ color = "red",
+ display_numbers = True,
+ num_offset = DEFAULT_COUNT_NUM_OFFSET,
+ run_time = DEFAULT_COUNT_RUN_TIME):
+ """
+ Note, leaves final number mobject as "number" attribute
+
+ mode can be "highlight", "show_creation" or "show", otherwise
+ a warning is given and nothing is animating during the count
+ """
+ if len(mobjects) > 50: #TODO
+ raise Exception("I don't know if you should be counting \
+ too many mobjects...")
+ if len(mobjects) == 0:
+ raise Exception("Counting mobject list of length 0")
+ if mode not in ["highlight", "show_creation", "show"]:
+ raise Warning("Unknown mode")
+ frame_time = run_time / len(mobjects)
+ if mode == "highlight":
+ self.add(*mobjects)
+ for mob, num in zip(mobjects, it.count(1)):
+ if display_numbers:
+ num_mob = tex_mobject(str(num))
+ num_mob.center().shift(num_offset)
+ self.add(num_mob)
+ if mode == "highlight":
+ original_color = mob.color
+ mob.highlight(color)
+ self.dither(frame_time)
+ mob.highlight(original_color)
+ if mode == "show_creation":
+ self.play(ShowCreation(mob, run_time = frame_time))
+ if mode == "show":
+ self.add(mob)
+ self.dither(frame_time)
+ if display_numbers:
+ self.remove(num_mob)
+ if display_numbers:
+ self.add(num_mob)
+ self.number = num_mob
+ return self
+
+ def count_regions(self, regions,
+ mode = "one_at_a_time",
+ num_offset = DEFAULT_COUNT_NUM_OFFSET,
+ run_time = DEFAULT_COUNT_RUN_TIME,
+ **unused_kwargsn):
+ if mode not in ["one_at_a_time", "show_all"]:
+ raise Warning("Unknown mode")
+ frame_time = run_time / (len(regions))
+ for region, count in zip(regions, it.count(1)):
+ num_mob = tex_mobject(str(count))
+ num_mob.center().shift(num_offset)
+ self.add(num_mob)
+ self.highlight_region(region)
+ self.dither(frame_time)
+ if mode == "one_at_a_time":
+ self.reset_background()
+ self.remove(num_mob)
+ self.add(num_mob)
+ self.number = num_mob
+ return self
BIG_N_PASCAL_ROWS = 11
N_PASCAL_ROWS = 7
+
class PascalsTriangleScene(Scene):
args_list = [
(N_PASCAL_ROWS,),
@@ -86,3 +159,13 @@ class PascalsTriangleScene(Scene):
self.coords_to_mobs[n][k] = mob
self.add(mob)
+
+
+
+
+
+
+
+
+
+
diff --git a/topics/complex_numbers.py b/topics/complex_numbers.py
new file mode 100644
index 000000000..cbd774c23
--- /dev/null
+++ b/topics/complex_numbers.py
@@ -0,0 +1,212 @@
+from helpers import *
+
+from number_line import NumberPlane
+from animation.transform import ApplyPointwiseFunction
+from animation.animation import Homotopy
+from scene import Scene
+
+
+def complex_string(complex_num):
+ return filter(lambda c : c not in "()", str(complex_num))
+
+class ComplexPlane(NumberPlane):
+ DEFAULT_CONFIG = {
+ "color" : GREEN,
+ "unit_to_spatial_width" : 1,
+ "line_frequency" : 1,
+ "faded_line_frequency" : 0.5,
+ "number_at_center" : complex(0),
+ }
+ def __init__(self, **kwargs):
+ digest_config(self, ComplexPlane, kwargs)
+ kwargs.update({
+ "x_unit_to_spatial_width" : self.unit_to_spatial_width,
+ "y_uint_to_spatial_height" : self.unit_to_spatial_width,
+ "x_line_frequency" : self.line_frequency,
+ "x_faded_line_frequency" : self.faded_line_frequency,
+ "y_line_frequency" : self.line_frequency,
+ "y_faded_line_frequency" : self.faded_line_frequency,
+ "num_pair_at_center" : (self.number_at_center.real, self.number_at_center.imag),
+ })
+ NumberPlane.__init__(self, **kwargs)
+
+ def number_to_point(self, number):
+ number = complex(number)
+ return self.num_pair_to_point((number.real, number.imag))
+
+ def get_coordinate_labels(self, *numbers):
+ result = []
+ nudge = 0.1*(DOWN+RIGHT)
+ if len(numbers) == 0:
+ numbers = range(-int(self.x_radius), int(self.x_radius))
+ numbers += [
+ complex(0, y)
+ for y in range(-int(self.y_radius), int(self.y_radius))
+ ]
+ for number in numbers:
+ point = self.number_to_point(number)
+ if number == 0:
+ num_str = "0"
+ else:
+ num_str = str(number).replace("j", "i")
+ num = tex_mobject(num_str)
+ num.scale(self.number_scale_factor)
+ num.shift(point-num.get_corner(UP+LEFT)+nudge)
+ result.append(num)
+ return result
+
+ def add_coordinates(self, *numbers):
+ self.add(*self.get_coordinate_labels(*numbers))
+ return self
+
+ def add_spider_web(self, circle_freq = 1, angle_freq = np.pi/6):
+ self.fade(self.fade_factor)
+ config = {
+ "color" : self.color,
+ "density" : self.density,
+ }
+ for radius in np.arange(circle_freq, SPACE_WIDTH, circle_freq):
+ self.add(Circle(radius = radius, **config))
+ for angle in np.arange(0, 2*np.pi, angle_freq):
+ end_point = np.cos(angle)*RIGHT + np.sin(angle)*UP
+ end_point *= SPACE_WIDTH
+ self.add(Line(ORIGIN, end_point, **config))
+ return self
+
+
+class ComplexFunction(ApplyPointwiseFunction):
+ def __init__(self, function, mobject = ComplexPlane, **kwargs):
+ if "interpolation_function" not in kwargs:
+ self.interpolation_function = path_along_arc(
+ np.log(function(complex(1))).imag
+ )
+ ApplyPointwiseFunction.__init__(
+ self,
+ lambda (x, y, z) : complex_to_R3(function(complex(x, y))),
+ instantiate(mobject),
+ **kwargs
+ )
+
+class ComplexHomotopy(Homotopy):
+ def __init__(self, complex_homotopy, **kwargs):
+ """
+ Complex Hootopy a function (z, t) to z'
+ """
+ def homotopy((x, y, z, t)):
+ c = complex_homotopy((complex(x, y), t))
+ return (c.real, c.imag, z)
+ if len(args) > 0:
+ args = list(args)
+ mobject = args.pop(0)
+ elif "mobject" in kwargs:
+ mobject = kwargs["mobject"]
+ else:
+ mobject = Grid()
+ Homotopy.__init__(self, homotopy, mobject, *args, **kwargs)
+ self.name = "ComplexHomotopy" + \
+ to_cammel_case(complex_homotopy.__name__)
+
+class ComplexMultiplication(Scene):
+ @staticmethod
+ def args_to_string(multiplier, mark_one = False):
+ num_str = complex_string(multiplier)
+ arrow_str = "MarkOne" if mark_one else ""
+ return num_str + arrow_str
+
+ @staticmethod
+ def string_to_args(arg_string):
+ parts = arg_string.split()
+ multiplier = complex(parts[0])
+ mark_one = len(parts) > 1 and parts[1] == "MarkOne"
+ return (multiplier, mark_one)
+
+ def construct(self, multiplier, mark_one = False, **plane_config):
+ norm = np.linalg.norm(multiplier)
+ arg = np.log(multiplier).imag
+ plane_config["faded_line_frequency"] = 0
+ plane_config.update(DEFAULT_PLANE_CONFIG)
+ if norm > 1 and "density" not in plane_config:
+ plane_config["density"] = norm*DEFAULT_POINT_DENSITY_1D
+ if "radius" not in plane_config:
+ radius = SPACE_WIDTH
+ if norm > 0 and norm < 1:
+ radius /= norm
+ else:
+ radius = plane_config["radius"]
+ plane_config["x_radius"] = plane_config["y_radius"] = radius
+ plane = ComplexPlane(**plane_config)
+ self.plane = plane
+ self.add(plane)
+ # plane.add_spider_web()
+ self.anim_config = {
+ "run_time" : 2.0,
+ "interpolation_function" : path_along_arc(arg)
+ }
+
+ plane_config["faded_line_frequency"] = 0.5
+ background = ComplexPlane(color = "grey", **plane_config)
+ # background.add_spider_web()
+ labels = background.get_coordinate_labels()
+ self.paint_into_background(background, *labels)
+ self.mobjects_to_move_without_molding = []
+ if mark_one:
+ self.draw_dot("1", 1, True)
+ self.draw_dot("z", multiplier)
+
+
+ self.mobjects_to_multiply = [plane]
+
+ self.additional_animations = []
+ self.multiplier = multiplier
+ if self.__class__ == ComplexMultiplication:
+ self.apply_multiplication()
+
+ def draw_dot(self, tex_string, value, move_dot = False):
+ dot = Dot(
+ self.plane.number_to_point(value),
+ radius = 0.1*self.plane.unit_to_spatial_width,
+ color = BLUE if value == 1 else YELLOW
+ )
+ label = tex_mobject(tex_string)
+ label.shift(dot.get_center()+1.5*UP+RIGHT)
+ arrow = Arrow(label, dot)
+ self.add(label)
+ self.play(ShowCreation(arrow))
+ self.play(ShowCreation(dot))
+ self.dither()
+
+ self.remove(label, arrow)
+ if move_dot:
+ self.mobjects_to_move_without_molding.append(dot)
+ return dot
+
+
+ def apply_multiplication(self):
+ def func((x, y, z)):
+ complex_num = self.multiplier*complex(x, y)
+ return (complex_num.real, complex_num.imag, z)
+ mobjects = self.mobjects_to_multiply
+ mobjects += self.mobjects_to_move_without_molding
+ mobjects += [anim.mobject for anim in self.additional_animations]
+
+
+ self.add(*mobjects)
+ full_multiplications = [
+ ApplyMethod(mobject.apply_function, func, **self.anim_config)
+ for mobject in self.mobjects_to_multiply
+ ]
+ movements_with_plane = [
+ ApplyMethod(
+ mobject.shift,
+ func(mobject.get_center())-mobject.get_center(),
+ **self.anim_config
+ )
+ for mobject in self.mobjects_to_move_without_molding
+ ]
+ self.dither()
+ self.play(*reduce(op.add, [
+ full_multiplications,
+ movements_with_plane,
+ self.additional_animations
+ ]))
+ self.dither()
diff --git a/topics/functions.py b/topics/functions.py
new file mode 100644
index 000000000..68944d196
--- /dev/null
+++ b/topics/functions.py
@@ -0,0 +1,65 @@
+from helpers import *
+
+from helpers import *
+
+from mobject import Mobject, Mobject1D, CompoundMobject
+
+
+class FunctionGraph(Mobject1D):
+ DEFAULT_CONFIG = {
+ "color" : BLUE,
+ "x_min" : -10,
+ "x_max" : 10,
+ "spatial_radius" : SPACE_WIDTH,
+ }
+ def __init__(self, function, **kwargs):
+ digest_config(self, FunctionGraph, kwargs, locals())
+ Mobject1D.__init__(self, **kwargs)
+
+ def generate_points(self):
+ numerical_radius = (self.x_max - self.x_min)/2
+ numerical_center = (self.x_max + self.x_min)/2
+ ratio = numerical_radius / self.spatial_radius
+ epsilon = self.epsilon * ratio
+ self.add_points([
+ np.array([(x-numerical_center)/ratio, self.function(x), 0])
+ for x in np.arange(self.x_min, self.x_max, self.epsilon)
+ ])
+
+
+class ParametricFunction(Mobject):
+ DEFAULT_CONFIG = {
+ "color" : WHITE,
+ "dim" : 1,
+ "expected_measure" : 10.0,
+ "density" : None
+ }
+ def __init__(self, function, **kwargs):
+ digest_config(self, ParametricFunction, kwargs, locals())
+ if self.density:
+ self.epsilon = 1.0 / self.density
+ elif self.dim == 1:
+ self.epsilon = 1.0 / self.expected_measure / DEFAULT_POINT_DENSITY_1D
+ else:
+ self.epsilon = 1.0 / np.sqrt(self.expected_measure) / DEFAULT_POINT_DENSITY_2D
+ Mobject.__init__(self, *args, **kwargs)
+
+ def generate_points(self):
+ if self.dim == 1:
+ self.add_points([
+ self.function(t)
+ for t in np.arange(-1, 1, self.epsilon)
+ ])
+ if self.dim == 2:
+ self.add_points([
+ self.function(s, t)
+ for t in np.arange(-1, 1, self.epsilon)
+ for s in np.arange(-1, 1, self.epsilon)
+ ])
+
+
+class Axes(CompoundMobject):
+ def __init__(self, **kwargs):
+ x_axis = NumberLine(**kwargs)
+ y_axis = NumberLine(**kwargs).rotate(np.pi/2, OUT)
+ CompoundMobject.__init__(self, x_axis, y_axis)
\ No newline at end of file
diff --git a/mobject/simple_mobjects.py b/topics/geometry.py
similarity index 64%
rename from mobject/simple_mobjects.py
rename to topics/geometry.py
index 8dc67135c..14bcdc75e 100644
--- a/mobject/simple_mobjects.py
+++ b/topics/geometry.py
@@ -1,11 +1,7 @@
-import numpy as np
-import itertools as it
-
-from mobject import Mobject, Mobject1D, Mobject2D, CompoundMobject
-from image_mobject import text_mobject
-from constants import *
from helpers import *
+from mobject import Mobject, Mobject1D
+
class Point(Mobject):
DEFAULT_CONFIG = {
@@ -52,6 +48,7 @@ class Cross(Mobject1D):
])
self.shift(self.center_point)
+
class Line(Mobject1D):
DEFAULT_CONFIG = {
"min_density" : 0.1
@@ -230,129 +227,4 @@ class Square(Rectangle):
digest_config(self, Square, kwargs)
for arg in ["height", "width"]:
kwargs[arg] = self.side_length
- Rectangle.__init__(self, **kwargs)
-
-class Bubble(Mobject):
- DEFAULT_CONFIG = {
- "direction" : LEFT,
- "index_of_tip" : -1,
- "center_point" : ORIGIN,
- }
- def __init__(self, **kwargs):
- digest_config(self, Bubble, kwargs)
- Mobject.__init__(self, **kwargs)
- self.center_offset = self.center_point - Mobject.get_center(self)
- if self.direction[0] > 0:
- self.rotate(np.pi, UP)
- self.content = Mobject()
-
- def get_tip(self):
- return self.points[self.index_of_tip]
-
- def get_bubble_center(self):
- return self.get_center()+self.center_offset
-
- def move_tip_to(self, point):
- self.shift(point - self.get_tip())
- return self
-
- def flip(self):
- self.direction = -np.array(self.direction)
- self.rotate(np.pi, UP)
- return self
-
- def pin_to(self, mobject):
- mob_center = mobject.get_center()
- if (mob_center[0] > 0) != (self.direction[0] > 0):
- self.flip()
- boundary_point = mobject.get_boundary_point(UP-self.direction)
- vector_from_center = 1.5*(boundary_point-mob_center)
- self.move_tip_to(mob_center+vector_from_center)
- return self
-
- def add_content(self, mobject):
- scaled_width = 0.75*self.get_width()
- if mobject.get_width() > scaled_width:
- mobject.scale(scaled_width / mobject.get_width())
- mobject.shift(self.get_bubble_center())
- self.content = mobject
- return self
-
- def write(self, text):
- self.add_content(text_mobject(text))
- return self
-
- def clear(self):
- self.content = Mobject()
- return self
-
-class SpeechBubble(Bubble):
- DEFAULT_CONFIG = {
- "initial_width" : 4,
- "initial_height" : 2,
- }
- def __init__(self, **kwargs):
- digest_config(self, SpeechBubble, kwargs)
- Bubble.__init__(self, **kwargs)
-
- def generate_points(self):
- complex_power = 0.9
- radius = self.initial_width/2
- circle = Circle(radius = radius)
- circle.scale(1.0/radius)
- circle.apply_complex_function(lambda z : z**complex_power)
- circle.scale(radius)
- boundary_point_as_complex = radius*complex(-1)**complex_power
- boundary_points = [
- [
- boundary_point_as_complex.real,
- unit*boundary_point_as_complex.imag,
- 0
- ]
- for unit in -1, 1
- ]
- tip = radius*(1.5*LEFT+UP)
- self.add(
- circle,
- Line(boundary_points[0], tip),
- Line(boundary_points[1], tip)
- )
- self.highlight("white")
- self.rotate(np.pi/2)
- self.points[:,1] *= float(self.initial_height)/self.initial_width
-
-class ThoughtBubble(Bubble):
- DEFAULT_CONFIG = {
- "num_bulges" : 7,
- "initial_inner_radius" : 1.8,
- "initial_width" : 6
- }
- def __init__(self, **kwargs):
- digest_config(self, ThoughtBubble, kwargs)
- Bubble.__init__(self, **kwargs)
- self.index_of_tip = np.argmin(self.points[:,1])
-
- def generate_points(self):
- self.add(Circle().scale(0.15).shift(2.5*DOWN+2*LEFT))
- self.add(Circle().scale(0.3).shift(2*DOWN+1.5*LEFT))
- for n in range(self.num_bulges):
- theta = 2*np.pi*n/self.num_bulges
- self.add(Circle().shift((np.cos(theta), np.sin(theta), 0)))
- self.filter_out(lambda p : np.linalg.norm(p) < self.initial_inner_radius)
- self.stretch_to_fit_width(self.initial_width)
- self.highlight("white")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
+ Rectangle.__init__(self, **kwargs)
\ No newline at end of file
diff --git a/scene/graphs.py b/topics/graph_theory.py
similarity index 99%
rename from scene/graphs.py
rename to topics/graph_theory.py
index f4e45a318..9767cd30b 100644
--- a/scene/graphs.py
+++ b/topics/graph_theory.py
@@ -3,13 +3,10 @@ import numpy as np
import operator as op
from random import random
+from helpers import *
+
from scene import Scene
-from mobject import *
-from animation import *
-from region import *
-from constants import *
-from helpers import *
class Graph():
def __init__(self):
diff --git a/scripts/matrix_as_transform_2d.py b/topics/matrix_as_transform_2d.py
similarity index 98%
rename from scripts/matrix_as_transform_2d.py
rename to topics/matrix_as_transform_2d.py
index dac837131..1c67f30ee 100644
--- a/scripts/matrix_as_transform_2d.py
+++ b/topics/matrix_as_transform_2d.py
@@ -5,13 +5,10 @@ import itertools as it
from copy import deepcopy
import sys
+from helpers import *
-from animation import *
-from mobject import *
-from constants import *
-from region import *
-from scene import Scene, NumberLineScene
-from script_wrapper import command_line_create_scene
+from scene import Scene
+from number_line import NumberLineScene
MOVIE_PREFIX = "matrix_as_transform_2d/"
diff --git a/mobject/function_graphs.py b/topics/number_line.py
similarity index 62%
rename from mobject/function_graphs.py
rename to topics/number_line.py
index 057cecfc0..2a9070bfb 100644
--- a/mobject/function_graphs.py
+++ b/topics/number_line.py
@@ -1,63 +1,7 @@
-import numpy as np
-import itertools as it
-
-from mobject import Mobject, Mobject1D, Mobject2D, CompoundMobject
-from simple_mobjects import Arrow, Line, Circle
-from image_mobject import tex_mobject
-from constants import *
from helpers import *
-class FunctionGraph(Mobject1D):
- DEFAULT_CONFIG = {
- "color" : BLUE,
- "x_min" : -10,
- "x_max" : 10,
- "spatial_radius" : SPACE_WIDTH,
- }
- def __init__(self, function, **kwargs):
- digest_config(self, FunctionGraph, kwargs, locals())
- Mobject1D.__init__(self, **kwargs)
-
- def generate_points(self):
- numerical_radius = (self.x_max - self.x_min)/2
- numerical_center = (self.x_max + self.x_min)/2
- ratio = numerical_radius / self.spatial_radius
- epsilon = self.epsilon * ratio
- self.add_points([
- np.array([(x-numerical_center)/ratio, self.function(x), 0])
- for x in np.arange(self.x_min, self.x_max, self.epsilon)
- ])
-
-
-class ParametricFunction(Mobject):
- DEFAULT_CONFIG = {
- "color" : WHITE,
- "dim" : 1,
- "expected_measure" : 10.0,
- "density" : None
- }
- def __init__(self, function, **kwargs):
- digest_config(self, ParametricFunction, kwargs, locals())
- if self.density:
- self.epsilon = 1.0 / self.density
- elif self.dim == 1:
- self.epsilon = 1.0 / self.expected_measure / DEFAULT_POINT_DENSITY_1D
- else:
- self.epsilon = 1.0 / np.sqrt(self.expected_measure) / DEFAULT_POINT_DENSITY_2D
- Mobject.__init__(self, *args, **kwargs)
-
- def generate_points(self):
- if self.dim == 1:
- self.add_points([
- self.function(t)
- for t in np.arange(-1, 1, self.epsilon)
- ])
- if self.dim == 2:
- self.add_points([
- self.function(s, t)
- for t in np.arange(-1, 1, self.epsilon)
- for s in np.arange(-1, 1, self.epsilon)
- ])
+from mobject import Mobject1D
+from scene import Scene
class NumberLine(Mobject1D):
DEFAULT_CONFIG = {
@@ -67,7 +11,7 @@ class NumberLine(Mobject1D):
"tick_size" : 0.1,
"tick_frequency" : 0.5,
"leftmost_tick" : None,
- "number_at_center" : 0,
+ "number_at_center" : 0,
"numbers_with_elongated_ticks" : [0],
"longer_tick_multiple" : 2,
}
@@ -168,13 +112,6 @@ class UnitInterval(NumberLine):
NumberLine.__init__(self, **kwargs)
-class Axes(CompoundMobject):
- def __init__(self, **kwargs):
- x_axis = NumberLine(**kwargs)
- y_axis = NumberLine(**kwargs).rotate(np.pi/2, OUT)
- CompoundMobject.__init__(self, x_axis, y_axis)
-
-
class NumberPlane(Mobject1D):
DEFAULT_CONFIG = {
"color" : BLUE,
@@ -275,69 +212,94 @@ class NumberPlane(Mobject1D):
arrow.add_tip()
return arrow
-class ComplexPlane(NumberPlane):
- DEFAULT_CONFIG = {
- "color" : GREEN,
- "unit_to_spatial_width" : 1,
- "line_frequency" : 1,
- "faded_line_frequency" : 0.5,
- "number_at_center" : complex(0),
- }
- def __init__(self, **kwargs):
- digest_config(self, ComplexPlane, kwargs)
- kwargs.update({
- "x_unit_to_spatial_width" : self.unit_to_spatial_width,
- "y_uint_to_spatial_height" : self.unit_to_spatial_width,
- "x_line_frequency" : self.line_frequency,
- "x_faded_line_frequency" : self.faded_line_frequency,
- "y_line_frequency" : self.line_frequency,
- "y_faded_line_frequency" : self.faded_line_frequency,
- "num_pair_at_center" : (self.number_at_center.real, self.number_at_center.imag),
- })
- NumberPlane.__init__(self, **kwargs)
-
- def number_to_point(self, number):
- number = complex(number)
- return self.num_pair_to_point((number.real, number.imag))
- def get_coordinate_labels(self, *numbers):
- result = []
- nudge = 0.1*(DOWN+RIGHT)
- if len(numbers) == 0:
- numbers = range(-int(self.x_radius), int(self.x_radius))
- numbers += [
- complex(0, y)
- for y in range(-int(self.y_radius), int(self.y_radius))
- ]
- for number in numbers:
- point = self.number_to_point(number)
- if number == 0:
- num_str = "0"
+class NumberLineScene(Scene):
+ def construct(self, **number_line_config):
+ self.number_line = NumberLine(**number_line_config)
+ self.displayed_numbers = self.number_line.default_numbers_to_display()
+ self.number_mobs = self.number_line.get_number_mobjects(*self.displayed_numbers)
+ self.add(self.number_line, *self.number_mobs)
+
+ def zoom_in_on(self, number, zoom_factor, run_time = 2.0):
+ unit_length_to_spatial_width = self.number_line.unit_length_to_spatial_width*zoom_factor
+ radius = SPACE_WIDTH/unit_length_to_spatial_width
+ tick_frequency = 10**(np.floor(np.log10(radius)))
+ left_tick = tick_frequency*(np.ceil((number-radius)/tick_frequency))
+ new_number_line = NumberLine(
+ numerical_radius = radius,
+ unit_length_to_spatial_width = unit_length_to_spatial_width,
+ tick_frequency = tick_frequency,
+ leftmost_tick = left_tick,
+ number_at_center = number
+ )
+ new_displayed_numbers = new_number_line.default_numbers_to_display()
+ new_number_mobs = new_number_line.get_number_mobjects(*new_displayed_numbers)
+
+ transforms = []
+ additional_mobjects = []
+ squished_new_line = deepcopy(new_number_line)
+ squished_new_line.scale(1.0/zoom_factor)
+ squished_new_line.shift(self.number_line.number_to_point(number))
+ squished_new_line.points[:,1] = self.number_line.number_to_point(0)[1]
+ transforms.append(Transform(squished_new_line, new_number_line))
+ for mob, num in zip(new_number_mobs, new_displayed_numbers):
+ point = Point(self.number_line.number_to_point(num))
+ point.shift(new_number_line.get_vertical_number_offset())
+ transforms.append(Transform(point, mob))
+ for mob in self.mobjects:
+ if mob == self.number_line:
+ new_mob = deepcopy(mob)
+ new_mob.shift(-self.number_line.number_to_point(number))
+ new_mob.stretch(zoom_factor, 0)
+ transforms.append(Transform(mob, new_mob))
+ continue
+ mob_center = mob.get_center()
+ number_under_center = self.number_line.point_to_number(mob_center)
+ new_point = new_number_line.number_to_point(number_under_center)
+ new_point += mob_center[1]*UP
+ if mob in self.number_mobs:
+ transforms.append(Transform(mob, Point(new_point)))
else:
- num_str = str(number).replace("j", "i")
- num = tex_mobject(num_str)
- num.scale(self.number_scale_factor)
- num.shift(point-num.get_corner(UP+LEFT)+nudge)
- result.append(num)
- return result
+ transforms.append(ApplyMethod(mob.shift, new_point - mob_center))
+ additional_mobjects.append(mob)
+ line_to_hide_pixelation = Line(
+ self.number_line.get_left(),
+ self.number_line.get_right(),
+ color = self.number_line.get_color()
+ )
+ self.add(line_to_hide_pixelation)
+ self.play(*transforms, run_time = run_time)
+ self.clear()
+ self.number_line = new_number_line
+ self.displayed_numbers = new_displayed_numbers
+ self.number_mobs = new_number_mobs
+ self.add(self.number_line, *self.number_mobs)
+ self.add(*additional_mobjects)
+
+ def show_multiplication(self, num, **kwargs):
+ if "interpolation_function" not in kwargs:
+ if num > 0:
+ kwargs["interpolation_function"] = straight_path
+ else:
+ kwargs["interpolation_function"] = counterclockwise_path()
+ self.play(*[
+ ApplyMethod(self.number_line.stretch, num, 0, **kwargs)
+ ]+[
+ ApplyMethod(mob.shift, (num-1)*mob.get_center()[0]*RIGHT, **kwargs)
+ for mob in self.number_mobs
+ ])
+
+
+
+
+
+
+
+
+
+
- def add_coordinates(self, *numbers):
- self.add(*self.get_coordinate_labels(*numbers))
- return self
- def add_spider_web(self, circle_freq = 1, angle_freq = np.pi/6):
- self.fade(self.fade_factor)
- config = {
- "color" : self.color,
- "density" : self.density,
- }
- for radius in np.arange(circle_freq, SPACE_WIDTH, circle_freq):
- self.add(Circle(radius = radius, **config))
- for angle in np.arange(0, 2*np.pi, angle_freq):
- end_point = np.cos(angle)*RIGHT + np.sin(angle)*UP
- end_point *= SPACE_WIDTH
- self.add(Line(ORIGIN, end_point, **config))
- return self
diff --git a/scripts/pythagorean_proof.py b/topics/pythagorean_proof.py
similarity index 98%
rename from scripts/pythagorean_proof.py
rename to topics/pythagorean_proof.py
index bbce4cfbd..bb1c64591 100644
--- a/scripts/pythagorean_proof.py
+++ b/topics/pythagorean_proof.py
@@ -1,17 +1,13 @@
-#!/usr/bin/env python
-
import numpy as np
import itertools as it
from copy import deepcopy
import sys
+from helpers import *
-from animation import *
-from mobject import *
-from constants import *
-from region import *
from scene import Scene
-from script_wrapper import command_line_create_scene
+from geometry import Polygon
+from region import region_from_polygon_vertices, region_from_line_boundary
MOVIE_PREFIX = "pythagorean_proof"
@@ -513,14 +509,3 @@ class ShowRearrangementInBigSquareWithRegions(ShowRearrangementInBigSquare):
self.highlight_region(region_from_polygon_vertices(
RIGHT+DOWN, RIGHT+2*DOWN, 2*RIGHT+2*DOWN, 2*RIGHT+DOWN
), color = A_COLOR)
-
-
-
-
-
-
-
-
-
-if __name__ == "__main__":
- command_line_create_scene(MOVIE_PREFIX)
\ No newline at end of file
diff --git a/mobject/three_dimensional_mobjects.py b/topics/three_dimensions.py
similarity index 98%
rename from mobject/three_dimensional_mobjects.py
rename to topics/three_dimensions.py
index 0d7483390..ba707f44b 100644
--- a/mobject/three_dimensional_mobjects.py
+++ b/topics/three_dimensions.py
@@ -2,10 +2,10 @@ import numpy as np
import itertools as it
from mobject import Mobject, Mobject1D, Mobject2D, CompoundMobject
-from simple_mobjects import Line
-from constants import *
+from geometry import Line
from helpers import *
+
class Stars(Mobject):
DEFAULT_CONFIG = {
"point_thickness" : 1,