A community-maintained Python framework for creating mathematical animations.
Moser Intro animations complete
Grant Sanderson398b92406c8e
diff --git a/Tex/template.tex b/Tex/template.texindex a6d202951..406517326 100644--- a/Tex/template.tex+++ b/Tex/template.tex@@ -7,7 +7,7 @@{\usetheme{default} % or try Darmstadt, Madrid, Warsaw, ...\usecolortheme{default} % or try albatross, beaver, crane, ...- \usefonttheme[onlymath]{serif} % or try serif, structurebold, ...+ \usefonttheme{serif} % or try serif, structurebold, ...\setbeamertemplate{navigation symbols}{}\setbeamertemplate{caption}[numbered]}@@ -15,6 +15,8 @@\begin{frame}\centeringSizeHere- $YourTextHere$+ \begin{align*}+ YourTextHere+ \end{align*}\end{frame}\end{document}\ No newline at end of filediff --git a/animation.py b/animation.pynew file mode 100644index 000000000..bbed9f4e4--- /dev/null+++ b/animation.py@@ -0,0 +1,344 @@+from PIL import Image+from colour import Color+import numpy as np+import warnings+import time+import os+import copy+import progressbar+import inspect+from images2gif import writeGif++from helpers import *+from mobject import Mobject++class Animation(object):+ def __init__(self,+ mobject,+ run_time = DEFAULT_ANIMATION_RUN_TIME,+ alpha_func = high_inflection_0_to_1,+ name = None):+ if isinstance(mobject, type) and issubclass(mobject, Mobject):+ self.mobject = mobject()+ elif isinstance(mobject, Mobject):+ self.mobject = mobject+ else:+ raise Exception("Invalid mobject parameter, must be \+ subclass or instance of Mobject")+ self.starting_mobject = copy.deepcopy(self.mobject)+ self.reference_mobjects = [self.starting_mobject]+ self.alpha_func = alpha_func or (lambda x : x)+ self.run_time = run_time+ #TODO, Adress the idea of filtering the animation+ self.filter_functions = []+ self.restricted_height = SPACE_HEIGHT+ self.restricted_width = SPACE_WIDTH+ self.spacial_center = np.zeros(3)+ self.name = name or self.__class__.__name__ + str(self.mobject)++ def __str__(self):+ return self.name++ def get_points_and_rgbs(self):+ """+ It is the responsibility of this class to only emit points within+ the space. Returns np array of points and corresponding np array+ of rgbs+ """+ #TODO, I don't think this should be necessary. This should happen+ #under the individual mobjects.+ points = self.mobject.points+ rgbs = self.mobject.rgbs+ #Filters out what is out of bounds.+ admissibles = (abs(points[:,0]) < self.restricted_width) * \+ (abs(points[:,1]) < self.restricted_height)+ for filter_function in self.filter_functions:+ admissibles *= ~filter_function(points)+ if any(self.spacial_center):+ points += self.spacial_center+ #Filter out points pushed off the edge+ admissibles *= (abs(points[:,0]) < SPACE_WIDTH) * \+ (abs(points[:,1]) < SPACE_HEIGHT)+ if rgbs.shape[0] < points.shape[0]:+ #TODO, this shouldn't be necessary, find what's happening.+ points = points[:rgbs.shape[0], :]+ admissibles = admissibles[:rgbs.shape[0]]+ return points[admissibles, :], rgbs[admissibles, :]++ def update(self, alpha):+ if alpha < 0:+ alpha = 0+ if alpha > 1:+ alpha = 1+ self.update_mobject(self.alpha_func(alpha))++ def filter_out(self, *filter_functions):+ self.filter_functions += filter_functions+ return self++ def restrict_height(self, height):+ self.restricted_height = min(height, SPACE_HEIGHT)+ return self++ def restrict_width(self, width):+ self.restricted_width = min(width, SPACE_WIDTH)+ return self++ def shift(self, vector):+ self.spacial_center += vector+ return self++ def set_run_time(self, time):+ self.run_time = time+ return self++ def set_alpha_func(self, alpha_func):+ if alpha_func is None:+ alpha_func = lambda x : x+ self.alpha_func = alpha_func+ return self++ def set_name(self, name):+ self.name = name+ return self++ # def drag_pixels(self):+ # self.frames = drag_pixels(self.get_frames())+ # return self++ # def reverse(self):+ # self.get_frames().reverse()+ # self.name = 'Reversed' + str(self)+ # return self++ def update_mobject(self, alpha):+ #Typically ipmlemented by subclass+ pass++ def clean_up(self):+ pass+++###### Concrete Animation ########++class Rotating(Animation):+ def __init__(self,+ mobject,+ axis = None,+ axes = [[0, 0, 1], [0, 1, 0]],+ radians = 2 * np.pi,+ run_time = 20.0,+ alpha_func = None,+ *args, **kwargs):+ Animation.__init__(+ self, mobject,+ run_time = run_time,+ alpha_func = alpha_func,+ *args, **kwargs+ )+ self.axes = [axis] if axis else axes+ self.radians = radians++ def update_mobject(self, alpha):+ self.mobject.points = self.starting_mobject.points+ for axis in self.axes:+ self.mobject.rotate(+ self.radians * alpha,+ axis+ )++class RotationAsTransform(Rotating):+ def __init__(self, mobject, radians, axis = (0, 0, 1), axes = None,+ run_time = DEFAULT_ANIMATION_RUN_TIME,+ alpha_func = high_inflection_0_to_1,+ *args, **kwargs):+ Rotating.__init__(+ self,+ mobject,+ axis = axis,+ axes = axes,+ run_time = run_time,+ radians = radians,+ alpha_func = alpha_func,+ )++class FadeOut(Animation):+ def update_mobject(self, alpha):+ self.mobject.rgbs = self.starting_mobject.rgbs * (1 - alpha)++class FadeIn(Animation):+ def update_mobject(self, alpha):+ self.mobject.rgbs = self.starting_mobject.rgbs * alpha+ if self.mobject.points.shape != self.starting_mobject.points.shape:+ self.mobject.points = self.starting_mobject.points+ #TODO, Why do you need to do this? Shouldn't points always align?++class Transform(Animation):+ def __init__(self, mobject1, mobject2,+ run_time = DEFAULT_TRANSFORM_RUN_TIME,+ *args, **kwargs):+ count1, count2 = mobject1.get_num_points(), mobject2.get_num_points()+ Mobject.align_data(mobject1, mobject2)+ Animation.__init__(self, mobject1, run_time = run_time, *args, **kwargs)+ self.ending_mobject = mobject2+ self.mobject.SHOULD_BUFF_POINTS = \+ mobject1.SHOULD_BUFF_POINTS and mobject2.SHOULD_BUFF_POINTS+ self.reference_mobjects.append(mobject2)+ self.name += "To" + str(mobject2)++ if count2 < count1:+ #Ensure redundant pixels fade to black+ indices = self.non_redundant_m2_indices = \+ np.arange(0, count1-1, float(count1) / count2).astype('int')+ temp = np.zeros(mobject2.points.shape)+ temp[indices] = mobject2.rgbs[indices]+ mobject2.rgbs = temp++ def update_mobject(self, alpha):+ Mobject.interpolate(+ self.starting_mobject,+ self.ending_mobject,+ self.mobject,+ alpha+ )++ def clean_up(self):+ if hasattr(self, "non_redundant_m2_indices"):+ #Reduce mobject (which has become identical to mobject2), as+ #well as mobject2 itself+ for mobject in [self.mobject, self.ending_mobject]:+ for attr in ['points', 'rgbs']:+ setattr(+ mobject, attr,+ getattr(+ self.ending_mobject,+ attr+ )[self.non_redundant_m2_indices]+ )++class ApplyMethod(Transform):+ def __init__(self, method, mobject, *args, **kwargs):+ """+ Method is a method of Mobject+ """+ method_args = ()+ if isinstance(method, tuple):+ method, method_args = method[0], method[1:]+ if not inspect.ismethod(method):+ raise "Not a valid Mobject method"+ Transform.__init__(+ self,+ mobject,+ method(copy.deepcopy(mobject), *method_args),+ *args, **kwargs+ )++class ApplyFunction(Transform):+ def __init__(self, function, mobject, run_time = DEFAULT_ANIMATION_RUN_TIME,+ *args, **kwargs):+ map_image = copy.deepcopy(mobject)+ map_image.points = np.array(map(function, map_image.points))+ Transform.__init__(self, mobject, map_image, run_time = run_time,+ *args, **kwargs)+ self.name = "".join([+ "Apply",+ "".join([s.capitalize() for s in function.__name__.split("_")]),+ "To" + str(mobject)+ ])++class ComplexFunction(ApplyFunction):+ def __init__(self, function, *args, **kwargs):+ def point_map(point):+ x, y, z = point+ c = np.complex(x, y)+ c = function(c)+ return c.real, c.imag, z+ if len(args) > 0:+ args = list(args)+ mobject = args.pop(0)+ elif "mobject" in kwargs:+ mobject = kwargs.pop("mobject")+ else:+ mobject = Grid()+ ApplyFunction.__init__(self, point_map, mobject, *args, **kwargs)+ self.name = "ComplexFunction" + to_cammel_case(function.__name__)+ #Todo, abstract away function naming'++class Homotopy(Animation):+ def __init__(self, homotopy, *args, **kwargs):+ """+ Homotopy a function from (x, y, z, t) to (x', y', z')+ """+ self.homotopy = homotopy+ Animation.__init__(self, *args, **kwargs)++ def update_mobject(self, alpha):+ self.mobject.points = np.array([+ self.homotopy((x, y, z, alpha))+ for x, y, z in self.starting_mobject.points+ ])++class ComplexHomotopy(Homotopy):+ def __init__(self, complex_homotopy, *args, **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 ShowCreation(Animation):+ def update_mobject(self, alpha):+ #TODO, shoudl I make this more efficient?+ new_num_points = int(alpha * self.starting_mobject.points.shape[0])+ for attr in ["points", "rgbs"]:+ setattr(+ self.mobject,+ attr,+ getattr(self.starting_mobject, attr)[:new_num_points, :]+ )++class Flash(Animation):+ def __init__(self, mobject, color = "white", slow_factor = 0.01,+ run_time = 0.1, alpha_func = None,+ *args, **kwargs):+ Animation.__init__(self, mobject, run_time = run_time,+ alpha_func = alpha_func,+ *args, **kwargs)+ self.intermediate = Mobject(color = color)+ self.intermediate.add_points([+ point + (x, y, 0)+ for point in self.mobject.points+ for x in [-1, 1]+ for y in [-1, 1]+ ])+ self.reference_mobjects.append(self.intermediate)+ self.slow_factor = slow_factor++ def update_mobject(self, alpha):+ #Makes alpha go from 0 to slow_factor to 0 instead of 0 to 1+ alpha = self.slow_factor * (1.0 - 4 * (alpha - 0.5)**2)+ Mobject.interpolate(+ self.starting_mobject,+ self.intermediate,+ self.mobject,+ alpha+ )+++++++diff --git a/constants.py b/constants.pyindex 00b1e0ae4..c6caffa2b 100644--- a/constants.py+++ b/constants.py@@ -1,27 +1,25 @@import os-PRODUCTION_QUALITY = False+PRODUCTION_QUALITY = True+GENERALLY_BUFF_POINTS = FalseDEFAULT_POINT_DENSITY_2D = 25 #if PRODUCTION_QUALITY else 20DEFAULT_POINT_DENSITY_1D = 200 #if PRODUCTION_QUALITY else 50-DEFAULT_HEIGHT = 1440 #if PRODUCTION_QUALITY else 480-DEFAULT_WIDTH = 2560 #if PRODUCTION_QUALITY else 640+DEFAULT_HEIGHT = 1440 if PRODUCTION_QUALITY else 480+DEFAULT_WIDTH = 2560 if PRODUCTION_QUALITY else 640#All in seconds-DEFAULT_FRAME_DURATION = 0.04 if PRODUCTION_QUALITY else 0.1+DEFAULT_FRAME_DURATION = 0.04 #if PRODUCTION_QUALITY else 0.1DEFAULT_ANIMATION_RUN_TIME = 3.0DEFAULT_TRANSFORM_RUN_TIME = 1.0DEFAULT_DITHER_TIME = 1.0-GENERALLY_BUFF_POINTS = PRODUCTION_QUALITYDEFAULT_NUM_STARS = 1000SPACE_HEIGHT = 4.0SPACE_WIDTH = DEFAULT_WIDTH * SPACE_HEIGHT / DEFAULT_HEIGHT--THIS_DIR = os.path.dirname(os.path.realpath(__file__))IMAGE_DIR = os.path.join(THIS_DIR, "images")GIF_DIR = os.path.join(THIS_DIR, "gifs")@@ -33,7 +31,7 @@ for folder in [IMAGE_DIR, GIF_DIR, MOVIE_DIR, TEX_DIR, TMP_IMAGE_DIR, TEX_IMAGE_if not os.path.exists(folder):os.mkdir(folder)-PDF_DENSITY = 400+PDF_DENSITY = 800SIZE_TO_REPLACE = "SizeHere"TEX_TEXT_TO_REPLACE = "YourTextHere"TEMPLATE_TEX_FILE = os.path.join(TEX_DIR, "template.tex")diff --git a/displayer.py b/displayer.pyindex 1c4256a24..d74f5a81c 100644--- a/displayer.py+++ b/displayer.py@@ -5,8 +5,9 @@ from PIL import Imageimport subprocessimport cv2from colour import Color+import progressbar-from mobject_movement import *+from mobject import *def get_pixels(image_array):if image_array is None:@@ -38,6 +39,7 @@ def paint_mobject(mobject, image_array = None):#TODO, Let z add a depth componenet?points = np.array(mobject.points[:, :2])+ rgbs = np.array(mobject.rgbs)#Flips y-axispoints[:,1] *= -1#Map points to pixel space, then create pixel array first in terms@@ -53,12 +55,20 @@ def paint_mobject(mobject, image_array = None):flattener = np.array([1, width], dtype = 'int').reshape((2, 1))indices = np.dot(points, flattener)indices = indices.reshape(indices.size)+ if mobject.should_buffer_points():#Is this alright?+ for tweak in [+ indices + 1,+ indices + width,+ indices + width + 1+ ]:+ indices = np.append(indices, tweak)+ rgbs = np.array(list(rgbs) * 4)admissibles = (indices < height * width) * (indices > 0)indices = indices[admissibles]- rgbs = mobject.rgbs[admissibles]+ rgbs = rgbs[admissibles]rgbs = (rgbs * 255).astype(int)pixels = pixels.reshape((height * width, 3))- pixels[indices] = rgbs+ pixels[indices] = rgbs.reshape((rgbs.size/3), 3)#WHY?pixels = pixels.reshape((height, width, 3)).astype('uint8')return pixelsdiff --git a/generate_logo.py b/generate_logo.pyindex ad0ffbd62..4567d4c06 100644--- a/generate_logo.py+++ b/generate_logo.py@@ -1,7 +1,7 @@#!/usr/bin/env pythonfrom PIL import Image-from animate import *+from animation import *from mobject import *from constants import *from helpers import *@@ -15,30 +15,32 @@ DARK_BLUE = "#236B8E"DARK_BROWN = "#8B4513"LIGHT_BROWN = "#CD853F"-size = 1.5-circle = Circle(color = 'skyblue').repeat(4).scale(size)-sphere = Sphere(density = 100, color = DARK_BLUE).scale(size)-sphere.rotate(-np.pi / 7, [1, 0, 0])-sphere.rotate(-np.pi / 7)-alpha = 0.3-iris = Mobject()-Mobject.interpolate(circle, sphere, iris, alpha)-for mob, color in [(iris, LIGHT_BROWN), (circle, DARK_BROWN)]:- mob.highlight(color, lambda (x, y, z) : x < 0 and y > 0)- mob.highlight("black", lambda point: np.linalg.norm(point) < size/2)-name = ImageMobject(NAME_TO_IMAGE_FILE["3Blue1Brown"]).center()-name.highlight("gray")-# name.highlight(DARK_BROWN, lambda (x, y, z) : x < 0 and y > 0)-name.shift((0, -2, 0))+if __name__ == '__main__':+ size = 1.5+ circle = Circle(color = 'skyblue').repeat(4).scale(size)+ sphere = Sphere(density = 100, color = DARK_BLUE).scale(size)+ sphere.rotate(-np.pi / 7, [1, 0, 0])+ sphere.rotate(-np.pi / 7)+ alpha = 0.3+ iris = Mobject()+ Mobject.interpolate(circle, sphere, iris, alpha)+ for mob, color in [(iris, LIGHT_BROWN), (circle, DARK_BROWN)]:+ mob.highlight(color, lambda (x, y, z) : x < 0 and y > 0)+ mob.highlight("black", lambda point: np.linalg.norm(point) < size/2)-create_eye = Transform(- circle, iris,- run_time = DEFAULT_ANIMATION_RUN_TIME,- name = "LogoGeneration"-).then(- Animation(name, dither_time = 0)-).drag_pixels()-create_eye.write_to_movie()-index = int(DEFAULT_ANIMATION_RUN_TIME / DEFAULT_ANIMATION_PAUSE_TIME)-create_eye.frames[index].save(LOGO_PATH)+ #TODO, reimplement all of this.+ name = tex_mobject("3Blue1Brown").center()+ name.highlight("gray")+ # name.highlight(DARK_BROWN, lambda (x, y, z) : x < 0 and y > 0)+ name.shift((0, -2, 0))+ create_eye = Transform(+ circle, iris,+ run_time = DEFAULT_ANIMATION_RUN_TIME,+ name = "LogoGeneration"+ ).then(+ Animation(name, dither_time = 0)+ ).drag_pixels()+ create_eye.write_to_movie()+ index = int(DEFAULT_ANIMATION_RUN_TIME / DEFAULT_ANIMATION_PAUSE_TIME)+ create_eye.frames[index].save(LOGO_PATH)diff --git a/image_mobject.py b/image_mobject.pynew file mode 100644index 000000000..b3cdd0725--- /dev/null+++ b/image_mobject.py@@ -0,0 +1,104 @@+import numpy as np+import itertools as it+import os+from PIL import Image+from random import random++from tex_utils import *+from mobject import *++class ImageMobject(Mobject2D):+ """+ Automatically filters out black pixels+ """+# SHOULD_BUFF_POINTS = False+ def __init__(self,+ image,+ filter_color = "black",+ invert = True,+ *args, **kwargs):+ #TODO, Make sure you always convert to RGB+ self.filter_rgb = 255 * np.array(Color(filter_color).get_rgb()).astype('uint8')+ if isinstance(image, str):+ self.name = to_cammel_case(+ os.path.split(image)[-1].split(".")[0]+ )+ possible_paths = [+ image,+ os.path.join(IMAGE_DIR, image),+ os.path.join(IMAGE_DIR, image + ".jpg"),+ os.path.join(IMAGE_DIR, image + ".png"),+ ]+ found = False+ for path in possible_paths:+ if os.path.exists(path):+ image = Image.open(path).convert('RGB')+ found = True+ if not found:+ raise IOError("File not Found")+ if invert:+ image = invert_image(image)+ self.image_array = np.array(image)+ Mobject2D.__init__(self, *args, **kwargs)++ def generate_points(self):+ height, width = self.image_array.shape[:2]+ #Flatten array, and find indices where rgb is not filter_rgb+ array = self.image_array.reshape((height * width, 3))+ ones = np.ones(height * width, dtype = 'bool')+ for i in range(3):+ ones *= (array[:,i] != self.filter_rgb[i])+ indices = np.arange(height * width, dtype = 'int')[ones]+ rgbs = array[indices, :].astype('float') / 255.0++ points = np.zeros((indices.size, 3), dtype = 'float64')+ points[:,0] = indices%width - width/2+ points[:,1] = -indices/width + height/2++ height, width = map(float, (height, width))+ if height / width > float(DEFAULT_HEIGHT) / DEFAULT_WIDTH:+ points *= 2 * SPACE_HEIGHT / height+ else:+ points *= 2 * SPACE_WIDTH / width+ self.add_points(points, rgbs = rgbs)++ def should_buffer_points(self):+ # potentially changed in subclasses+ return False++class SpeechBubble(ImageMobject):+ def __init__(self, *args, **kwargs):+ ImageMobject.__init__(self, "speech_bubble", *args, **kwargs)+ self.scale(0.25)++class ThoughtBubble(ImageMobject):+ def __init__(self, *args, **kwargs):+ ImageMobject.__init__(self, "thought_bubble", *args, **kwargs)+ self.scale(0.5)++class SimpleFace(ImageMobject):+ def __init__(self, *args, **kwargs):+ ImageMobject.__init__(self, "simple_face", *args, **kwargs)+ self.scale(0.5)++class VideoIcon(ImageMobject):+ def __init__(self, *args, **kwargs):+ ImageMobject.__init__(self, "video_icon", *args, **kwargs)+ self.scale(0.3)+++def tex_mobject(expression, size = "\HUGE"):+ return tex_mobjects(expression, size)++def tex_mobjects(expression, size = "\HUGE"):+ images = tex_to_image(expression, size)+ if isinstance(images, list):+ #TODO, is checking listiness really the best here?+ return [ImageMobject(im).scale(2) for im in images]+ else:+ return ImageMobject(images).scale(2)+++++diff --git a/mobject.py b/mobject.pyindex d849396eb..9cec9f933 100644--- a/mobject.py+++ b/mobject.py@@ -3,9 +3,10 @@ import itertools as itimport osfrom PIL import Imagefrom random import random+from copy import deepcopy-from mobject_movement import *-from tex_utils import *+from constants import *+from helpers import *import displayer as disp@@ -99,6 +100,13 @@ class Mobject(object):self.add_points(mobject.points, mobject.rgbs)return self+ def repeat(self, count):+ #Can make transition animations nicer+ points, rgbs = deepcopy(self.points), deepcopy(self.rgbs)+ for x in range(count - 1):+ self.add_points(points, rgbs)+ return self+def get_num_points(self):return self.points.shape[0]@@ -136,6 +144,10 @@ class Mobject(object):self.rgbs = self.rgbs[to_eliminate]return self+ def should_buffer_points(self):+ # potentially changed in subclasses+ return GENERALLY_BUFF_POINTS+def generate_points(self):#Typically implemented in subclass, unless purposefully left blankpass@@ -249,7 +261,7 @@ class Vector(Arrow):length = length, tip_length = 0.2 * length,*args, **kwargs)-class Dot(Mobject1D):+class Dot(Mobject1D): #Use 1D density, even though 2DDEFAULT_COLOR = "white"def __init__(self, center = (0, 0, 0), radius = 0.05, *args, **kwargs):self.center = center@@ -335,12 +347,6 @@ class Circle(Mobject1D):for theta in np.arange(0, 2 * np.pi, self.epsilon)])- def repeat(self, count):- #Can make transition animations quite pretty- for x in range(count - 1):- self.add_points(self.points)- return self-class FunctionGraph(Mobject1D):DEFAULT_COLOR = "lightblue"def __init__(self, function, x_range = [-10, 10], *args, **kwargs):@@ -465,81 +471,6 @@ class NumberLine(Mobject1D):# Grid.__init__(self, *args, **kwargs)# self.add(Dot())----class ImageMobject(Mobject2D):- """- Automatically filters out black pixels- """-# SHOULD_BUFF_POINTS = False- def __init__(self,- image,- filter_color = "black",- invert = True,- *args, **kwargs):- #TODO, Make sure you always convert to RGB- self.filter_rgb = 255 * np.array(Color(filter_color).get_rgb()).astype('uint8')- if isinstance(image, str):- self.name = to_cammel_case(- os.path.split(image)[-1].split(".")[0]- )- possible_paths = [- image,- os.path.join(IMAGE_DIR, image),- os.path.join(IMAGE_DIR, image + ".jpg"),- os.path.join(IMAGE_DIR, image + ".png"),- ]- found = False- for path in possible_paths:- if os.path.exists(path):- image = Image.open(path).convert('RGB')- found = True- if not found:- raise IOError("File not Found")- if invert:- image = invert_image(image)- self.image_array = np.array(image)- Mobject2D.__init__(self, *args, **kwargs)-- def generate_points(self):- height, width = self.image_array.shape[:2]- #Flatten array, and find indices where rgb is not filter_rgb- array = self.image_array.reshape((height * width, 3))- ones = np.ones(height * width, dtype = 'bool')- for i in range(3):- ones *= (array[:,i] != self.filter_rgb[i])- indices = np.arange(height * width, dtype = 'int')[ones]- rgbs = array[indices, :].astype('float') / 255.0-- points = np.array([- (- i%width - (width / 2.0),- -i/width + (height / 2.0), #flip y-axis- 0- )- for i in indices- ], dtype = 'float64')- height, width = map(float, (height, width))- if height / width > float(DEFAULT_HEIGHT) / DEFAULT_WIDTH:- points *= 2 * SPACE_HEIGHT / height- else:- points *= 2 * SPACE_WIDTH / width- self.add_points(points, rgbs = rgbs)---def tex_mobjects(expression, size = "\HUGE"):- images = tex_to_image(expression, size)- if isinstance(images, list):- #TODO, is checking listiness really the best here?- return [ImageMobject(im) for im in images]- else:- return ImageMobject(images)-----diff --git a/moser/intro.py b/moser/intro.pynew file mode 100644index 000000000..1c5d14262--- /dev/null+++ b/moser/intro.py@@ -0,0 +1,304 @@+#!/usr/bin/env python++import numpy as np+import itertools as it+import operator as op+from copy import deepcopy+++from animation import *+from mobject import *+from image_mobject import *+from constants import *+from region import *+from scene import Scene++RADIUS = SPACE_HEIGHT - 0.1+CIRCLE_DENSITY = DEFAULT_POINT_DENSITY_1D*RADIUS+++####+def moser_function(n):+ return choose(n, 4) + choose(n, 2) + 1++def choose(n, r):+ if n < r: return 0+ r = min(r, n-r)+ if r == 0: return 1+ numer = reduce(op.mul, xrange(n, n-r, -1), 1)+ denom = reduce(op.mul, xrange(1, r+1), 1)+ return numer//denom+####+++def logo_to_circle():+ from generate_logo import LIGHT_BROWN+ sc = Scene()+ small_circle = Circle(+ density = CIRCLE_DENSITY,+ color = 'skyblue'+ ).highlight(LIGHT_BROWN, lambda (x, y, z) : x < 0 and y > 0)+ big_circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS)+ sc.add(small_circle)+ sc.dither()+ sc.animate(Transform(small_circle, big_circle))+ return sc++def count_sections(*radians):+ sc = Scene()+ circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS)+ sc.add(circle)+ points = [+ (RADIUS * np.cos(angle), RADIUS * np.sin(angle), 0)+ for angle in radians+ ]+ dots = [Dot(point) for point in points]+ interior = Region(lambda x, y : x**2 + y**2 < RADIUS**2)+ for x in xrange(1, len(points)):+ if x == 1:+ sc.animate(ShowCreation(dots[0]), ShowCreation(dots[1]))+ sc.add(dots[0], dots[1])+ else:+ sc.animate(ShowCreation(dots[x]))+ sc.add(dots[x])+ new_lines = CompoundMobject(*[+ Line(points[x], points[y]) for y in xrange(x)+ ])+ sc.animate(Transform(deepcopy(dots[x]), new_lines, run_time = 2.0))+ sc.add(new_lines)+ sc.dither()+ regions = plane_partition_from_points(*points[:x+1])+ for reg in regions:+ reg.intersect(interior)+ regions = filter(lambda reg : reg.bool_grid.any(), regions)++ last_num = None+ for reg, count in zip(regions, it.count(1)):+ number = tex_mobject(str(count)).shift((RADIUS, 3, 0))+ sc.highlight_region(reg)+ rt = 1.0 / (x**0.8)+ sc.add(number)+ sc.remove(last_num)+ last_num = number+ sc.dither(rt)+ sc.reset_background()+ sc.remove(last_num)+ sc.animate(Transform(last_num, deepcopy(last_num).center()))+ sc.dither()+ sc.remove(last_num)+ return sc++def summarize_pattern(*radians):+ sc = Scene()+ circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS)+ sc.add(circle)+ points = [+ (RADIUS * np.cos(angle), RADIUS * np.sin(angle), 0)+ for angle in radians+ ]+ dots = [Dot(point) for point in points]+ last_num = None+ for x in xrange(len(points)):+ new_lines = CompoundMobject(*[+ Line(points[x], points[y]) for y in xrange(x)+ ])+ num = tex_mobject(str(moser_function(x + 1)))+ sc.animate(+ Transform(last_num, num) if last_num else ShowCreation(num),+ FadeIn(new_lines),+ FadeIn(dots[x]),+ run_time = 0.5,+ )+ sc.remove(last_num)+ last_num = num+ sc.add(num, dots[x], new_lines)+ sc.dither()+ return sc++def connect_points(*radians):+ sc = Scene()+ circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS)+ sc.add(circle)+ points = [+ (RADIUS * np.cos(angle), RADIUS * np.sin(angle), 0)+ for angle in radians+ ]+ dots = [Dot(point) for point in points]+ sc.add(*dots)+ anims = []+ all_lines = []+ for x in xrange(len(points)):+ lines = [Line(points[x], points[y]) for y in range(len(points))]+ lines = CompoundMobject(*lines)+ anims.append(Transform(deepcopy(dots[x]), lines, run_time = 3.0))+ all_lines.append(lines)+ sc.animate(*anims)+ sc.add(*all_lines)+ sc.dither()+ return sc++def interesting_problems():+ sc = Scene()+ locales = [(6, 2, 0), (6, -2, 0), (-5, -2, 0)]+ fermat = CompoundMobject(*tex_mobjects(["x^n","+","y^n","=","z^n"]))+ fermat.scale(0.5).shift((-2.5, 0.7, 0))+ face = SimpleFace()+ tb = ThoughtBubble().shift((-1.5, 1, 0))+ sb = SpeechBubble().shift((-2.4, 1.3, 0))+ fermat_copies, face_copies, tb_copies, sb_copies = (+ CompoundMobject(*[+ deepcopy(mob).scale(0.5).shift(locale)+ for locale in locales+ ])+ for mob in [fermat, face, tb, sb]+ )++ sc.add(face, tb)+ sc.animate(ShowCreation(fermat, run_time = 1))+ sc.add(fermat)+ sc.dither()+ sc.animate(+ Transform(+ deepcopy(fermat).repeat(len(locales)),+ fermat_copies+ ),+ FadeIn(face_copies, run_time = 1.0)+ )+ sc.animate(FadeIn(tb_copies))+ sc.dither()+ sc.animate(+ Transform(tb, sb),+ Transform(tb_copies, sb_copies)+ )+ return sc++def response_invitation():+ sc = Scene()+ video_icon = VideoIcon()+ mini_videos = CompoundMobject(*[+ deepcopy(video_icon).scale(0.5).shift((3, y, 0))+ for y in [-2, 0, 2]+ ])+ comments = CompoundMobject(*[+ Line((-1.2, y, 0), (1.2, y, 0), color = 'white')+ for y in [-1.5, -1.75, -2]+ ])++ sc.add(video_icon)+ sc.dither()+ sc.animate(Transform(deepcopy(video_icon).repeat(3), mini_videos))+ sc.add(mini_videos)+ sc.dither()+ sc.animate(ShowCreation(comments, run_time = 1.0))+ return sc++def different_points(radians1, radians2):+ sc = Scene()+ circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS)+ sc.add(circle)+ points1, points2 = (+ [+ (RADIUS * np.cos(angle), RADIUS * np.sin(angle), 0)+ for angle in radians+ ]+ for radians in (radians1, radians2)+ )+ dots1, dots2 = (+ CompoundMobject(*[Dot(point) for point in points])+ for points in (points1, points2)+ )+ lines1, lines2 = (+ [+ Line(point1, point2)+ for point1, point2 in it.combinations(points, 2)+ ]+ for points in (points1, points2)+ )+ sc.add(dots1, *lines1)+ sc.animate(+ Transform(dots1, dots2, run_time = 3),+ *[+ Transform(line1, line2, run_time = 3)+ for line1, line2 in zip(lines1, lines2)+ ]+ )+ sc.dither()+ return sc++def next_few_videos(*radians):+ sc = Scene()+ circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS)+ points = [+ (RADIUS * np.cos(angle), RADIUS * np.sin(angle), 0)+ for angle in radians+ ]+ dots = CompoundMobject(*[+ Dot(point) for point in points+ ])+ lines = CompoundMobject(*[+ Line(point1, point2)+ for point1, point2 in it.combinations(points, 2)+ ])+ thumbnail = CompoundMobject(circle, dots, lines)+ frame = VideoIcon().highlight(+ "black",+ lambda point : np.linalg.norm(point) < 0.5+ )+ big_frame = deepcopy(frame).scale(SPACE_WIDTH)+ frame.shift((-5, 0, 0))++ sc.add(thumbnail)+ sc.dither()+ sc.animate(+ Transform(big_frame, frame),+ Transform(+ thumbnail,+ deepcopy(thumbnail).scale(0.15).shift((-5, 0, 0))+ )+ )+ sc.add(frame, thumbnail)+ sc.dither()+ last = frame+ for x in [-2, 1, 4]:+ vi = VideoIcon().shift((x, 0, 0))+ sc.animate(+ Transform(deepcopy(last), vi),+ Animation(thumbnail)#Keeps it from getting burried+ )+ sc.add(vi)+ last = vi+ return sc+++if __name__ == '__main__':+ radians = [1, 3, 5, 2, 4, 6]+ more_radians = radians + [10, 13, 20, 17, 15, 21, 18.5]+ different_radians = [1.7, 4.8, 3.2, 3.5, 2.1, 5.5]+ # logo_to_circle().write_to_movie("moser/LogoToCircle")+ # count_sections(*radians).write_to_movie("moser/CountingSections")+ # summarize_pattern(*radians).write_to_movie("moser/SummarizePattern")+ # interesting_problems().write_to_movie("moser/InterestingProblems")+ # summarize_pattern(*more_radians).write_to_movie("moser/ExtendedPattern")+ # connect_points(*radians).write_to_movie("moser/ConnectPoints")+ # response_invitation().write_to_movie("moser/ResponseInvitation")+ # different_points(radians, different_radians).write_to_movie("moser/DifferentPoints")+ next_few_videos(*radians).write_to_movie("moser/NextFewVideos")+++ #Images+ # tex_mobject(r"""+ # \underbrace{1, 2, 4, 8, 16, 31, \dots}_\text{What?}+ # """).save_image("moser/NumberList")+++++++++++++diff --git a/region.py b/region.pyindex f84bb2e7c..a04a8dcab 100644--- a/region.py+++ b/region.py@@ -9,7 +9,7 @@ import displayer as dispclass Region(object):def __init__(self,- condition = lambda x, y : True,+ condition = None,shape = (DEFAULT_HEIGHT, DEFAULT_WIDTH)):"""@@ -26,6 +26,7 @@ class Region(object):scalar = 2*SPACE_HEIGHT / hxs = scalar*np.arange(-w/2, w/2)ys = -scalar*np.arange(-h/2, h/2)+ #TODO, do xs and ys really need to be saved in self?self.xs = np.dot(np.ones((h, 1)),xs.reshape((1, w))@@ -34,7 +35,10 @@ class Region(object):ys.reshape(h, 1),np.ones((1, w)))- self.bool_grid = condition(self.xs, self.ys)+ if condition:+ self.bool_grid = condition(self.xs, self.ys)+ else:+ self.bool_grid = np.ones(self.shape, dtype = 'bool')def show(self, color = None):Image.fromarray(disp.paint_region(self, color = color)).show()@@ -58,7 +62,7 @@ class Region(object):class HalfPlane(Region):def __init__(self, point_pair, upper_left = True, *args, **kwargs):"""- point_pair of the form [(x_0, y_0), (x_1, y_1)]+ point_pair of the form [(x_0, y_0,...), (x_1, y_1,...)]Pf upper_left is True, the side of the region will beeverything on the upper left side of the line through@@ -67,14 +71,14 @@ class HalfPlane(Region):if not upper_left:point_pair = list(point_pair)point_pair.reverse()- (x0, y0), (x1, y1) = point_pair+ (x0, y0), (x1, y1) = point_pair[0][:2], point_pair[1][:2]def condition(x, y):return (x1 - x0)*(y - y0) > (y1 - y0)*(x - x0)Region.__init__(self, condition, *args, **kwargs)def plane_partition(*lines):"""- A 'line' is a pair of points [(x0, y0), (x1, y1)]+ A 'line' is a pair of points [(x0, y0,...), (x1, y1,...)]Returns the list of regions of the plane cut out bythese linesdiff --git a/scene.py b/scene.pyindex ec01c389d..da1ca609c 100644--- a/scene.py+++ b/scene.py@@ -12,7 +12,7 @@ import inspectfrom helpers import *from mobject import *-from mobject_movement import *+from animation import *import displayer as dispclass Scene(object):@@ -21,7 +21,8 @@ class Scene(object):frame_duration = DEFAULT_FRAME_DURATION,background = None,height = DEFAULT_HEIGHT,- width = DEFAULT_WIDTH,):+ width = DEFAULT_WIDTH,+ start_dither_time = DEFAULT_DITHER_TIME):self.frame_duration = frame_durationself.frames = []self.mobjects = []@@ -29,7 +30,10 @@ class Scene(object):self.original_background = np.array(background)#TODO, Error checking?else:- self.original_background = np.zeros((height, width, 3))+ self.original_background = np.zeros(+ (height, width, 3),+ dtype = 'uint8'+ )self.background = self.original_backgroundself.shape = self.background.shape[:2]self.name = name@@ -37,6 +41,9 @@ class Scene(object):def __str__(self):return self.name or "Babadinook" #TODO+ def set_name(self, name):+ self.name = name+def add(self, *mobjects):"""Mobjects will be displayed, from background to foreground,@@ -63,26 +70,30 @@ class Scene(object):def reset_background(self):self.background = self.original_background- def animate(self, *mobmovs):- #Runtime is determined by the first mobmov- run_time = mobmovs[0].run_time- moving_mobjects = [a.mobject for a in mobmovs]+ def animate(self, *animations, **kwargs):+ if "run_time" in kwargs:+ run_time = kwargs["run_time"]+ else:+ run_time = animations[0].run_time+ for animation in animations:+ animation.set_run_time(run_time)+ moving_mobjects = [anim.mobject for anim in animations]self.remove(*moving_mobjects)background = self.get_frame()- print "Generating mobject movements..."+ print "Generating " + ", ".join(map(str, animations))progress_bar = progressbar.ProgressBar(maxval=run_time)progress_bar.start()for t in np.arange(0, run_time, self.frame_duration):progress_bar.update(t)new_frame = background- for mobmov in mobmovs:- mobmov.update(t / mobmov.run_time)- new_frame = disp.paint_mobject(mobmov.mobject, new_frame)+ for animation in animations:+ animation.update(t / animation.run_time)+ new_frame = disp.paint_mobject(animation.mobject, new_frame)self.frames.append(new_frame)- for mobmov in mobmovs:- mobmov.clean_up()+ for animation in animations:+ animation.clean_up()self.add(*moving_mobjects)progress_bar.finish()@@ -103,6 +114,9 @@ class Scene(object):self.dither(end_dither_time)disp.write_to_movie(self, name or str(self))+ def show_frame(self):+ Image.fromarray(self.get_frame()).show()+