Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Beginnings of organization

Grant Sandersone47f24084013
diff --git a/Images/logo.png b/Images/logo.png
deleted file mode 100644
index 58d941a61..000000000
Binary files a/Images/logo.png and /dev/null differ
diff --git a/Images/simple_face.png b/Images/simple_face.png
deleted file mode 100644
index 4646e4678..000000000
Binary files a/Images/simple_face.png and /dev/null differ
diff --git a/Images/speech_bubble.png b/Images/speech_bubble.png
deleted file mode 100644
index 10dc0cbe0..000000000
Binary files a/Images/speech_bubble.png and /dev/null differ
diff --git a/Images/thought_bubble.png b/Images/thought_bubble.png
deleted file mode 100644
index f939c2c2f..000000000
Binary files a/Images/thought_bubble.png and /dev/null differ
diff --git a/Images/video_icon.png b/Images/video_icon.png
deleted file mode 100644
index 9c1aa35a0..000000000
Binary files a/Images/video_icon.png and /dev/null differ
diff --git a/Tex/template.tex b/Tex/template.tex
deleted file mode 100644
index e86ad4e87..000000000
--- a/Tex/template.tex
+++ /dev/null
@@ -1,25 +0,0 @@
-\documentclass[12pt]{beamer}
-
-\usepackage[english]{babel}
-\usepackage[utf8x]{inputenc}
-\usepackage{amsmath}
-\usepackage{amssymb}
-\usepackage{dsfont}
-
-\mode<presentation>
-{
- \usetheme{default} % or try Darmstadt, Madrid, Warsaw, ...
- \usecolortheme{default} % or try albatross, beaver, crane, ...
- \usefonttheme{serif} % or try serif, structurebold, ...
- \setbeamertemplate{navigation symbols}{}
- \setbeamertemplate{caption}[numbered]
-}
-\begin{document}
-\begin{frame}
- \centering
- SizeHere
- \begin{align*}
- YourTextHere
- \end{align*}
-\end{frame}
-\end{document}
\ No newline at end of file
diff --git a/animation.py b/animation.py
deleted file mode 100644
index 1de5902b0..000000000
--- a/animation.py
+++ /dev/null
@@ -1,411 +0,0 @@
-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 constants import *
-from mobject import Mobject, Point
-
-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,
- black_out_extra_points = True,
- *args, **kwargs):
- count1, count2 = mobject1.get_num_points(), mobject2.get_num_points()
- if count2 == 0:
- mobject2 = Point((SPACE_WIDTH, SPACE_HEIGHT, 0))
- count2 = 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 black_out_extra_points and count2 < count1:
- #Ensure redundant pixels fade to black
- 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
- self.non_redundant_m2_indices = indices
-
- 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 SemiCircleTransform(Transform):
- def update_mobject(self, alpha):
- sm, em = self.starting_mobject, self.ending_mobject
- midpoints = (sm.points + em.points) / 2
- angle = alpha * np.pi
- rotation_matrix = np.matrix([
- [np.cos(angle), np.sin(angle), 0],
- [-np.sin(angle), np.cos(angle), 0],
- [0, 0, 1],
- ])
- self.mobject.points = np.dot(
- sm.points - midpoints,
- np.transpose(rotation_matrix)
- ) + midpoints
- self.mobject.rgbs = (1-alpha)*sm.rgbs + alpha*em.rgbs
-
-class FadeToColor(Transform):
- def __init__(self, mobject, color, *args, **kwargs):
- target = copy.deepcopy(mobject).highlight(color)
- Transform.__init__(self, mobject, target, *args, **kwargs)
-
-class Highlight(FadeToColor):
- def __init__(self, mobject, color = "red",
- run_time = DEFAULT_ANIMATION_RUN_TIME,
- alpha_func = there_and_back, *args, **kwargs):
- FadeToColor.__init__(
- self, mobject, color,
- run_time = run_time,
- alpha_func = alpha_func,
- *args, **kwargs
- )
-
-class ScaleInPlace(Transform):
- def __init__(self, mobject, scale_factor, *args, **kwargs):
- target = copy.deepcopy(mobject)
- center = mobject.get_center()
- target.shift(-center).scale(scale_factor).shift(center)
- Transform.__init__(self, mobject, target, *args, **kwargs)
-
-class ApplyMethod(Transform):
- def __init__(self, method, *args, **kwargs):
- """
- Method is a method of Mobject. *args is for the method,
- **kwargs is for the transform itself.
-
- Relies on the fact that mobject methods return the mobject
- """
- if not inspect.ismethod(method) or \
- not isinstance(method.im_self, Mobject):
- raise "Not a valid Mobject method"
- Transform.__init__(
- self,
- method.im_self,
- copy.deepcopy(method)(*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
- )
-
-#Fuck this is cool!
-class TransformAnimations(Transform):
- def __init__(self, start_anim, end_anim,
- alpha_func = squish_alpha_func(high_inflection_0_to_1),
- **kwargs):
- self.start_anim, self.end_anim = start_anim, end_anim
- Transform.__init__(
- self,
- start_anim.mobject,
- end_anim.mobject,
- run_time = max(start_anim.run_time, end_anim.run_time),
- alpha_func = alpha_func,
- **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/animation/__init__.py b/animation/__init__.py
new file mode 100644
index 000000000..598695687
--- /dev/null
+++ b/animation/__init__.py
@@ -0,0 +1,3 @@
+from animation import *
+from transform import *
+from simple_animations import *
\ No newline at end of file
diff --git a/animation/animation.py b/animation/animation.py
new file mode 100644
index 000000000..6935864f6
--- /dev/null
+++ b/animation/animation.py
@@ -0,0 +1,139 @@
+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 constants import *
+from mobject import Mobject, Point
+
+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 update_mobject(self, alpha):
+ #Typically ipmlemented by subclass
+ pass
+
+ def clean_up(self):
+ pass
+
+
+#Fuck this is cool!
+class TransformAnimations(Transform):
+ def __init__(self, start_anim, end_anim,
+ alpha_func = squish_alpha_func(high_inflection_0_to_1),
+ **kwargs):
+ self.start_anim, self.end_anim = start_anim, end_anim
+ Transform.__init__(
+ self,
+ start_anim.mobject,
+ end_anim.mobject,
+ run_time = max(start_anim.run_time, end_anim.run_time),
+ alpha_func = alpha_func,
+ **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/animation/simple_animations.py b/animation/simple_animations.py
new file mode 100644
index 000000000..2995eb64b
--- /dev/null
+++ b/animation/simple_animations.py
@@ -0,0 +1,136 @@
+import numpy as np
+import itertools as it
+
+from animation import Animation
+from constants import *
+from helpers import *
+
+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 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
+ )
+
+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__)
+
+
+
+
+
+
+
diff --git a/animation/transform.py b/animation/transform.py
new file mode 100644
index 000000000..64defdd7e
--- /dev/null
+++ b/animation/transform.py
@@ -0,0 +1,155 @@
+import numpy as np
+import itertools as it
+import inspect
+import copy
+import warnings
+
+from animation import Animation
+from mobject import Mobject
+from constants import *
+from helpers import *
+
+class Transform(Animation):
+ def __init__(self, mobject1, mobject2,
+ run_time = DEFAULT_TRANSFORM_RUN_TIME,
+ black_out_extra_points = True,
+ *args, **kwargs):
+ count1, count2 = mobject1.get_num_points(), mobject2.get_num_points()
+ if count2 == 0:
+ mobject2 = Point((SPACE_WIDTH, SPACE_HEIGHT, 0))
+ count2 = 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 black_out_extra_points and count2 < count1:
+ #Ensure redundant pixels fade to black
+ 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
+ self.non_redundant_m2_indices = indices
+
+ 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 SemiCircleTransform(Transform):
+ def update_mobject(self, alpha):
+ sm, em = self.starting_mobject, self.ending_mobject
+ midpoints = (sm.points + em.points) / 2
+ angle = alpha * np.pi
+ rotation_matrix = np.matrix([
+ [np.cos(angle), np.sin(angle), 0],
+ [-np.sin(angle), np.cos(angle), 0],
+ [0, 0, 1],
+ ])
+ self.mobject.points = np.dot(
+ sm.points - midpoints,
+ np.transpose(rotation_matrix)
+ ) + midpoints
+ self.mobject.rgbs = (1-alpha)*sm.rgbs + alpha*em.rgbs
+
+class FadeToColor(Transform):
+ def __init__(self, mobject, color, *args, **kwargs):
+ target = copy.deepcopy(mobject).highlight(color)
+ Transform.__init__(self, mobject, target, *args, **kwargs)
+
+class Highlight(FadeToColor):
+ def __init__(self, mobject, color = "red",
+ run_time = DEFAULT_ANIMATION_RUN_TIME,
+ alpha_func = there_and_back, *args, **kwargs):
+ FadeToColor.__init__(
+ self, mobject, color,
+ run_time = run_time,
+ alpha_func = alpha_func,
+ *args, **kwargs
+ )
+
+class ScaleInPlace(Transform):
+ def __init__(self, mobject, scale_factor, *args, **kwargs):
+ target = copy.deepcopy(mobject)
+ center = mobject.get_center()
+ target.shift(-center).scale(scale_factor).shift(center)
+ Transform.__init__(self, mobject, target, *args, **kwargs)
+
+class ApplyMethod(Transform):
+ def __init__(self, method, *args, **kwargs):
+ """
+ Method is a method of Mobject. *args is for the method,
+ **kwargs is for the transform itself.
+
+ Relies on the fact that mobject methods return the mobject
+ """
+ if not inspect.ismethod(method) or \
+ not isinstance(method.im_self, Mobject):
+ raise "Not a valid Mobject method"
+ Transform.__init__(
+ self,
+ method.im_self,
+ copy.deepcopy(method)(*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'
+
+
+
+
+
+
+
+
diff --git a/constants.py b/constants.py
index b2609ec6b..ec5e732c3 100644
--- a/constants.py
+++ b/constants.py
@@ -36,10 +36,11 @@ SPACE_WIDTH = SPACE_HEIGHT * DEFAULT_WIDTH / DEFAULT_HEIGHT
ORIGIN = (0, 0, 0)
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")
-MOVIE_DIR = os.path.join(THIS_DIR, "movies")
-TEX_DIR = os.path.join(THIS_DIR, "Tex")
+FILE_DIR = os.path.join(THIS_DIR, "files")
+IMAGE_DIR = os.path.join(FILE_DIR, "images")
+GIF_DIR = os.path.join(FILE_DIR, "gifs")
+MOVIE_DIR = os.path.join(FILE_DIR, "movies")
+TEX_DIR = os.path.join(FILE_DIR, "Tex")
TEX_IMAGE_DIR = os.path.join(IMAGE_DIR, "Tex")
TMP_IMAGE_DIR = "/tmp/animation_images/"
for folder in [IMAGE_DIR, GIF_DIR, MOVIE_DIR, TEX_DIR, TMP_IMAGE_DIR, TEX_IMAGE_DIR]:
diff --git a/displayer.py b/displayer.py
index dde79c305..090403920 100644
--- a/displayer.py
+++ b/displayer.py
@@ -8,6 +8,7 @@ from colour import Color
import progressbar
from mobject import *
+from constants import *
def get_pixels(image_array):
if image_array is None:
diff --git a/helpers.py b/helpers.py
index 0d66d44ea..8c6ce1283 100644
--- a/helpers.py
+++ b/helpers.py
@@ -5,9 +5,48 @@ from colour import Color
from random import random
import string
import re
+import operator as op
from constants import *
+def choose(n, r):
+ if n < r: return 0
+ if r == 0: return 1
+ denom = reduce(op.mul, xrange(1, r+1), 1)
+ numer = reduce(op.mul, xrange(n, n-r, -1), 1)
+ return numer//denom
+
+def is_on_line(p0, p1, p2, threshold = 0.01):
+ """
+ Returns true of p0 is on the line between p1 and p2
+ """
+ p0, p1, p2 = map(lambda tup : np.array(tup[:2]), [p0, p1, p2])
+ p1 -= p0
+ p2 -= p0
+ return abs((p1[0] / p1[1]) - (p2[0] / p2[1])) < threshold
+
+
+def intersection(line1, line2):
+ """
+ A "line" should come in the form [(x0, y0), (x1, y1)] for two
+ points it runs through
+ """
+ p0, p1, p2, p3 = map(
+ lambda tup : np.array(tup[:2]),
+ [line1[0], line1[1], line2[0], line2[1]]
+ )
+ p1, p2, p3 = map(lambda x : x - p0, [p1, p2, p3])
+ transform = np.zeros((2, 2))
+ transform[:,0], transform[:,1] = p1, p2
+ if np.linalg.det(transform) == 0: return
+ inv = np.linalg.inv(transform)
+ new_p3 = np.dot(inv, p3.reshape((2, 1)))
+ #Where does line connecting (0, 1) to new_p3 hit x axis
+ x_intercept = new_p3[0] / (1 - new_p3[1])
+ result = np.dot(transform, [[x_intercept], [0]])
+ result = result.reshape((2,)) + p0
+ return result
+
def random_color():
color = Color()
color.set_rgb([1 - 0.5 * random() for x in range(3)])
diff --git a/mobject.py b/mobject.py
deleted file mode 100644
index 7e283795f..000000000
--- a/mobject.py
+++ /dev/null
@@ -1,568 +0,0 @@
-import numpy as np
-import itertools as it
-import os
-from PIL import Image
-from random import random
-from copy import deepcopy
-from colour import Color
-
-from constants import *
-from helpers import *
-import displayer as disp
-
-
-class Mobject(object):
- """
- Mathematical Object
- """
- #Number of numbers used to describe a point (3 for pos, 3 for normal vector)
- DIM = 3
-
- DEFAULT_COLOR = Color("skyblue")
-
- SHOULD_BUFF_POINTS = GENERALLY_BUFF_POINTS
-
- def __init__(self,
- color = None,
- name = None,
- center = None,
- ):
- self.color = Color(color) if color else Color(self.DEFAULT_COLOR)
- if not hasattr(self, "name"):
- self.name = name or self.__class__.__name__
- self.has_normals = hasattr(self, 'unit_normal')
- self.points = np.zeros((0, 3))
- self.rgbs = np.zeros((0, 3))
- if self.has_normals:
- self.unit_normals = np.zeros((0, 3))
- self.generate_points()
- if center:
- self.center().shift(center)
-
- def __str__(self):
- return self.name
-
- def show(self):
- Image.fromarray(disp.paint_mobject(self)).show()
-
- def save_image(self, name = None):
- Image.fromarray(disp.paint_mobject(self)).save(
- os.path.join(MOVIE_DIR, (name or str(self)) + ".png")
- )
-
- def add_points(self, points, rgbs = None, color = None):
- """
- points must be a Nx3 numpy array, as must rgbs if it is not None
- """
- points = np.array(points)
- num_new_points = points.shape[0]
- self.points = np.append(self.points, points)
- self.points = self.points.reshape((self.points.size / 3, 3))
- if rgbs is None:
- color = Color(color) if color else self.color
- rgbs = np.array([color.get_rgb()] * num_new_points)
- else:
- if rgbs.shape != points.shape:
- raise Exception("points and rgbs must have same shape")
- self.rgbs = np.append(self.rgbs, rgbs).reshape(self.points.shape)
- if self.has_normals:
- self.unit_normals = np.append(
- self.unit_normals,
- np.array([self.unit_normal(point) for point in points])
- ).reshape(self.points.shape)
- return self
-
- def rotate(self, angle, axis = [0, 0, 1]):
- t_rotation_matrix = np.transpose(rotation_matrix(angle, axis))
- self.points = np.dot(self.points, t_rotation_matrix)
- if self.has_normals:
- self.unit_normals = np.dot(self.unit_normals, t_rotation_matrix)
- return self
-
- def rotate_in_place(self, angle, axis = [0, 0, 1]):
- center = self.get_center()
- self.shift(-center)
- self.rotate(angle, axis)
- self.shift(center)
- return self
-
- def shift(self, vector):
- cycle = it.cycle(vector)
- v = np.array([cycle.next() for x in range(self.points.size)]).reshape(self.points.shape)
- self.points += v
- return self
-
- def center(self):
- self.shift(-self.get_center())
- return self
-
- def scale(self, scale_factor):
- self.points *= scale_factor
- return self
-
- def scale_in_place(self, scale_factor):
- center = self.get_center()
- return self.center().scale(scale_factor).shift(center)
-
- def add(self, *mobjects):
- for mobject in mobjects:
- 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]
-
- def pose_at_angle(self):
- self.rotate(np.pi / 7)
- self.rotate(np.pi / 7, [1, 0, 0])
- return self
-
- def apply_function(self, function):
- self.points = np.apply_along_axis(function, 1, self.points)
- return self
-
- def apply_complex_function(self, function):
- def point_map((x, y, z)):
- result = function(complex(x, y))
- return (result.real, result.imag, 0)
- return self.apply_function(point_map)
-
- def highlight(self, color = "red", condition = lambda x : True):
- """
- Condition is function which takes in one arguments, (x, y, z).
- """
- #TODO, Should self.color change?
- to_change = np.apply_along_axis(condition, 1, self.points)
- self.rgbs[to_change, :] *= 0
- self.rgbs[to_change, :] += Color(color).get_rgb()
- return self
-
- def fade(self, amount = 0.5):
- self.rgbs *= amount
- return self
-
- def filter_out(self, condition):
- to_eliminate = ~np.apply_along_axis(condition, 1, self.points)
- self.points = self.points[to_eliminate]
- self.rgbs = self.rgbs[to_eliminate]
- return self
-
- ### Getters ###
- def get_center(self):
- return np.apply_along_axis(np.mean, 0, self.points)
-
- def get_width(self):
- return np.max(self.points[:, 0]) - np.min(self.points[:, 0])
-
- def get_height(self):
- return np.max(self.points[:, 1]) - np.min(self.points[:, 1])
-
- ### Stuff subclasses should deal with ###
- def should_buffer_points(self):
- # potentially changed in subclasses
- return GENERALLY_BUFF_POINTS
-
- def generate_points(self):
- #Typically implemented in subclass, unless purposefully left blank
- pass
-
- ### Static Methods ###
- def align_data(mobject1, mobject2):
- count1, count2 = mobject1.get_num_points(), mobject2.get_num_points()
- if count1 == 0:
- mobject1.add_points([(0, 0, 0)])
- if count2 == 0:
- mobject2.add_points([(0, 0, 0)])
- if count1 == count2:
- return
- for attr in ['points', 'rgbs']:
- new_arrays = make_even(getattr(mobject1, attr), getattr(mobject2, attr))
- for array, mobject in zip(new_arrays, [mobject1, mobject2]):
- setattr(mobject, attr, np.array(array))
-
- def interpolate(mobject1, mobject2, target_mobject, alpha):
- """
- Turns target_mobject into an interpolation between mobject1
- and mobject2.
- """
- Mobject.align_data(mobject1, mobject2)
- for attr in ['points', 'rgbs']:
- new_array = (1 - alpha) * getattr(mobject1, attr) + \
- alpha * getattr(mobject2, attr)
- setattr(target_mobject, attr, new_array)
-
-class Mobject1D(Mobject):
- def __init__(self, density = DEFAULT_POINT_DENSITY_1D, *args, **kwargs):
- self.epsilon = 1.0 / density
- Mobject.__init__(self, *args, **kwargs)
-
-class Mobject2D(Mobject):
- def __init__(self, density = DEFAULT_POINT_DENSITY_2D, *args, **kwargs):
- self.epsilon = 1.0 / density
- Mobject.__init__(self, *args, **kwargs)
-
-class CompoundMobject(Mobject):
- def __init__(self, *mobjects):
- Mobject.__init__(self)
- self.original_mobs_num_points = []
- for mobject in mobjects:
- self.original_mobs_num_points.append(mobject.points.shape[0])
- self.add_points(mobject.points, mobject.rgbs)
-
- def split(self):
- result = []
- curr = 0
- for num_points in self.original_mobs_num_points:
- result.append(Mobject().add_points(
- self.points[curr:curr+num_points, :],
- self.rgbs[curr:curr+num_points, :]
- ))
- curr += num_points
- return result
-
-###### Concrete Mobjects ########
-
-class Stars(Mobject):
- DEFAULT_COLOR = "white"
- SHOULD_BUFF_POINTS = False
- def __init__(self, num_points = DEFAULT_NUM_STARS,
- *args, **kwargs):
- self.num_points = num_points
- Mobject.__init__(self, *args, **kwargs)
-
- def generate_points(self):
- self.add_points([
- (
- r * np.sin(phi)*np.cos(theta),
- r * np.sin(phi)*np.sin(theta),
- r * np.cos(phi)
- )
- for x in range(self.num_points)
- for r, phi, theta in [[
- max(SPACE_HEIGHT, SPACE_WIDTH) * random(),
- np.pi * random(),
- 2 * np.pi * random(),
- ]]
- ])
-
-class Point(Mobject):
- def __init__(self, point = (0, 0, 0), *args, **kwargs):
- Mobject.__init__(self, *args, **kwargs)
- self.points = np.array(point).reshape(1, 3)
- self.rgbs = np.array(self.color.get_rgb()).reshape(1, 3)
-
-class Arrow(Mobject1D):
- DEFAULT_COLOR = "white"
- NUNGE_DISTANCE = 0.1
- def __init__(self, point = (0, 0, 0), direction = (-1, 1, 0),
- length = 1, tip_length = 0.25,
- normal = (0, 0, 1), *args, **kwargs):
- self.point = np.array(point)
- self.direction = np.array(direction) / np.linalg.norm(direction)
- self.normal = np.array(normal)
- self.length = length
- self.tip_length = tip_length
- Mobject1D.__init__(self, *args, **kwargs)
-
- def generate_points(self):
- self.add_points([
- [x, x, x] * self.direction + self.point
- for x in np.arange(-self.length, 0, self.epsilon)
- ])
- tips_dir = [np.array(-self.direction), np.array(-self.direction)]
- for i, sgn in zip([0, 1], [-1, 1]):
- tips_dir[i] = rotate_vector(tips_dir[i], sgn * np.pi / 4, self.normal)
- self.add_points([
- [x, x, x] * tips_dir[i] + self.point
- for x in np.arange(0, self.tip_length, self.epsilon)
- for i in [0, 1]
- ])
-
- def nudge(self):
- return self.shift(-self.direction * self.NUNGE_DISTANCE)
-
-class Vector(Arrow):
- def __init__(self, point = (1, 0, 0), *args, **kwargs):
- length = np.linalg.norm(point)
- Arrow.__init__(self, point = point, direction = point,
- length = length, tip_length = 0.2 * length,
- *args, **kwargs)
-
-class Dot(Mobject1D): #Use 1D density, even though 2D
- DEFAULT_COLOR = "white"
- DEFAULT_RADIUS = 0.05
- def __init__(self, center = (0, 0, 0), radius = DEFAULT_RADIUS, *args, **kwargs):
- center = np.array(center)
- if center.size == 1:
- raise Exception("Center must have 2 or 3 coordinates!")
- elif center.size == 2:
- center = np.append(center, [0])
- self.center_point = center
- self.radius = radius
- Mobject1D.__init__(self, *args, **kwargs)
-
- def generate_points(self):
- self.add_points([
- np.array((t*np.cos(theta), t*np.sin(theta), 0)) + self.center_point
- for t in np.arange(self.epsilon, self.radius, self.epsilon)
- for new_epsilon in [2*np.pi*self.epsilon*self.radius/t]
- for theta in np.arange(0, 2 * np.pi, new_epsilon)
- ])
-
-class Cross(Mobject1D):
- RADIUS = 0.3
- DEFAULT_COLOR = "white"
- def generate_points(self):
- self.add_points([
- (sgn * x, x, 0)
- for x in np.arange(-self.RADIUS / 2, self.RADIUS/2, self.epsilon)
- for sgn in [-1, 1]
- ])
-
-class Line(Mobject1D):
- def __init__(self, start, end, density = DEFAULT_POINT_DENSITY_1D, *args, **kwargs):
- self.start = np.array(start)
- self.end = np.array(end)
- density *= np.linalg.norm(self.start - self.end)
- Mobject1D.__init__(self, density = density, *args, **kwargs)
-
- def generate_points(self):
- self.add_points([
- t * self.end + (1 - t) * self.start
- for t in np.arange(0, 1, self.epsilon)
- ])
-
-class CurvedLine(Line):
- def generate_points(self):
- equidistant_point = rotate_vector(
- self.end - self.start,
- np.pi/3, [0,0,1]
- ) + self.start
- self.add_points([
- (1 - t*(1-t))*(t*self.end + (1-t)*self.start) \
- + t*(1-t)*equidistant_point
- for t in np.arange(0, 1, self.epsilon)
- ])
- self.ep = equidistant_point
-
-class CubeWithFaces(Mobject2D):
- def generate_points(self):
- self.add_points([
- sgn * np.array(coords)
- for x in np.arange(-1, 1, self.epsilon)
- for y in np.arange(x, 1, self.epsilon)
- for coords in it.permutations([x, y, 1])
- for sgn in [-1, 1]
- ])
- self.pose_at_angle()
-
- def unit_normal(self, coords):
- return np.array(map(lambda x : 1 if abs(x) == 1 else 0, coords))
-
-class Cube(Mobject1D):
- DEFAULT_COLOR = "yellow"
- def generate_points(self):
- self.add_points([
- ([a, b, c][p[0]], [a, b, c][p[1]], [a, b, c][p[2]])
- for p in [(0, 1, 2), (2, 0, 1), (1, 2, 0)]
- for a, b, c in it.product([-1, 1], [-1, 1], np.arange(-1, 1, self.epsilon))
- ])
- self.pose_at_angle()
-
-class Octohedron(Mobject1D):
- DEFAULT_COLOR = "pink"
- def generate_points(self):
- x = np.array([1, 0, 0])
- y = np.array([0, 1, 0])
- z = np.array([0, 0, 1])
- vertex_pairs = [(x+y, x-y), (x+y,-x+y), (-x-y,-x+y), (-x-y,x-y)]
- vertex_pairs += [
- (b[0]*x+b[1]*y, b[2]*np.sqrt(2)*z)
- for b in it.product(*[(-1, 1)]*3)
- ]
- for pair in vertex_pairs:
- self.add_points(
- Line(pair[0], pair[1], density = 1/self.epsilon).points
- )
- self.pose_at_angle()
-
-class Dodecahedron(Mobject1D):
- DEFAULT_COLOR = "limegreen"
- def generate_points(self):
- phi = (1 + np.sqrt(5)) / 2
- x = np.array([1, 0, 0])
- y = np.array([0, 1, 0])
- z = np.array([0, 0, 1])
- v1, v2 = (phi, 1/phi, 0), (phi, -1/phi, 0)
- vertex_pairs = [
- (v1, v2),
- (x+y+z, v1),
- (x+y-z, v1),
- (x-y+z, v2),
- (x-y-z, v2),
- ]
- five_lines_points = CompoundMobject(*[
- Line(pair[0], pair[1], density = 1.0/self.epsilon)
- for pair in vertex_pairs
- ]).points
- #Rotate those 5 edges into all 30.
- for i in range(3):
- perm = map(lambda j : j%3, range(i, i+3))
- for b in [-1, 1]:
- matrix = b*np.array([x[perm], y[perm], z[perm]])
- self.add_points(np.dot(five_lines_points, matrix))
- self.pose_at_angle()
-
-class Sphere(Mobject2D):
- def generate_points(self):
- self.add_points([
- (
- np.sin(phi) * np.cos(theta),
- np.sin(phi) * np.sin(theta),
- np.cos(phi)
- )
- for phi in np.arange(self.epsilon, np.pi, self.epsilon)
- for theta in np.arange(0, 2 * np.pi, 2 * self.epsilon / np.sin(phi))
- ])
-
- def unit_normal(self, coords):
- return np.array(coords) / np.linalg.norm(coords)
-
-class Circle(Mobject1D):
- DEFAULT_COLOR = "red"
- def generate_points(self):
- self.add_points([
- (np.cos(theta), np.sin(theta), 0)
- for theta in np.arange(0, 2 * np.pi, self.epsilon)
- ])
-
-class FunctionGraph(Mobject1D):
- DEFAULT_COLOR = "lightblue"
- def __init__(self, function, x_range = [-10, 10], *args, **kwargs):
- self.function = function
- self.x_min = x_range[0] / SPACE_WIDTH
- self.x_max = x_range[1] / SPACE_WIDTH
- Mobject1D.__init__(self, *args, **kwargs)
-
- def generate_points(self):
- scale_factor = 2.0 * SPACE_WIDTH / (self.x_max - self.x_min)
- self.epsilon /= scale_factor
- self.add_points([
- np.array([x, self.function(x), 0])
- for x in np.arange(self.x_min, self.x_max, self.epsilon)
- ])
- self.scale(scale_factor)
-
-
-class ParametricFunction(Mobject):
- DEFAULT_COLOR = "white"
- def __init__(self,
- function,
- dim = 1,
- expected_measure = 10.0,
- density = None,
- *args,
- **kwargs):
- self.function = function
- self.dim = dim
- self.expected_measure = expected_measure
- if density:
- self.epsilon = 1.0 / density
- elif self.dim == 1:
- self.epsilon = 1.0 / expected_measure / DEFAULT_POINT_DENSITY_1D
- else:
- self.epsilon = 1.0 / np.sqrt(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 Grid(Mobject1D):
- DEFAULT_COLOR = "green"
- def __init__(self,
- radius = max(SPACE_HEIGHT, SPACE_WIDTH),
- interval_size = 1.0,
- subinterval_size = 0.5,
- *args, **kwargs):
- self.radius = radius
- self.interval_size = interval_size
- self.subinterval_size = subinterval_size
- Mobject1D.__init__(self, *args, **kwargs)
-
- def generate_points(self):
- self.add_points([
- (sgns[0] * x, sgns[1] * y, 0)
- for beta in np.arange(0, self.radius, self.interval_size)
- for alpha in np.arange(0, self.radius, self.epsilon)
- for sgns in it.product((-1, 1), (-1, 1))
- for x, y in [(alpha, beta), (beta, alpha)]
- ])
- if self.subinterval_size:
- si = self.subinterval_size
- color = Color(self.color)
- color.set_rgb([x/2 for x in color.get_rgb()])
- self.add_points([
- (sgns[0] * x, sgns[1] * y, 0)
- for beta in np.arange(0, self.radius, si)
- if abs(beta % self.interval_size) > self.epsilon
- for alpha in np.arange(0, self.radius, self.epsilon)
- for sgns in it.product((-1, 1), (-1, 1))
- for x, y in [(alpha, beta), (beta, alpha)]
- ], color = color)
-
-class NumberLine(Mobject1D):
- def __init__(self,
- radius = SPACE_WIDTH,
- interval_size = 0.5, tick_size = 0.1,
- with_numbers = False, *args, **kwargs):
- self.radius = int(radius) + 1
- self.interval_size = interval_size
- self.tick_size = tick_size
- self.with_numbers = with_numbers
- Mobject1D.__init__(self, *args, **kwargs)
-
- def generate_points(self):
- self.add_points([
- (x, 0, 0)
- for x in np.arange(-self.radius, self.radius, self.epsilon)
- ])
- self.add_points([
- (0, y, 0)
- for y in np.arange(-2*self.tick_size, 2*self.tick_size, self.epsilon)
- ])
- self.add_points([
- (x, y, 0)
- for x in np.arange(-self.radius, self.radius, self.interval_size)
- for y in np.arange(-self.tick_size, self.tick_size, self.epsilon)
- ])
- if self.with_numbers:
- #TODO, test
- vertical_displacement = -0.3
- nums = range(-self.radius, self.radius)
- nums = map(lambda x : x / self.interval_size, nums)
- mobs = tex_mobjects(*[str(num) for num in nums])
- for num, mob in zip(nums, mobs):
- mob.center().shift([num, vertical_displacement, 0])
- self.add(*mobs)
-
-# class ComplexPlane(Grid):
-# def __init__(self, *args, **kwargs):
-# Grid.__init__(self, *args, **kwargs)
-# self.add(Dot())
\ No newline at end of file
diff --git a/mobject/__init__.py b/mobject/__init__.py
new file mode 100644
index 000000000..8e05c0100
--- /dev/null
+++ b/mobject/__init__.py
@@ -0,0 +1,5 @@
+from mobject import *
+from image_mobject import *
+from simple_mobjects import *
+from three_dimensional_mobjects import *
+from function_graphs import *
diff --git a/mobject/function_graphs.py b/mobject/function_graphs.py
new file mode 100644
index 000000000..8884ead54
--- /dev/null
+++ b/mobject/function_graphs.py
@@ -0,0 +1,118 @@
+import numpy as np
+import itertools as it
+
+from mobject import Mobject, Mobject1D, Mobject2D, CompoundMobject
+from constants import *
+from helpers import *
+
+class FunctionGraph(Mobject1D):
+ DEFAULT_COLOR = "lightblue"
+ def __init__(self, function, x_range = [-10, 10], *args, **kwargs):
+ self.function = function
+ self.x_min = x_range[0] / SPACE_WIDTH
+ self.x_max = x_range[1] / SPACE_WIDTH
+ Mobject1D.__init__(self, *args, **kwargs)
+
+ def generate_points(self):
+ scale_factor = 2.0 * SPACE_WIDTH / (self.x_max - self.x_min)
+ self.epsilon /= scale_factor
+ self.add_points([
+ np.array([x, self.function(x), 0])
+ for x in np.arange(self.x_min, self.x_max, self.epsilon)
+ ])
+ self.scale(scale_factor)
+
+
+class ParametricFunction(Mobject):
+ DEFAULT_COLOR = "white"
+ def __init__(self,
+ function,
+ dim = 1,
+ expected_measure = 10.0,
+ density = None,
+ *args,
+ **kwargs):
+ self.function = function
+ self.dim = dim
+ self.expected_measure = expected_measure
+ if density:
+ self.epsilon = 1.0 / density
+ elif self.dim == 1:
+ self.epsilon = 1.0 / expected_measure / DEFAULT_POINT_DENSITY_1D
+ else:
+ self.epsilon = 1.0 / np.sqrt(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 Grid(Mobject1D):
+ DEFAULT_COLOR = "green"
+ def __init__(self,
+ radius = max(SPACE_HEIGHT, SPACE_WIDTH),
+ interval_size = 1.0,
+ subinterval_size = 0.5,
+ *args, **kwargs):
+ self.radius = radius
+ self.interval_size = interval_size
+ self.subinterval_size = subinterval_size
+ Mobject1D.__init__(self, *args, **kwargs)
+
+ def generate_points(self):
+ self.add_points([
+ (sgns[0] * x, sgns[1] * y, 0)
+ for beta in np.arange(0, self.radius, self.interval_size)
+ for alpha in np.arange(0, self.radius, self.epsilon)
+ for sgns in it.product((-1, 1), (-1, 1))
+ for x, y in [(alpha, beta), (beta, alpha)]
+ ])
+ if self.subinterval_size:
+ si = self.subinterval_size
+ color = Color(self.color)
+ color.set_rgb([x/2 for x in color.get_rgb()])
+ self.add_points([
+ (sgns[0] * x, sgns[1] * y, 0)
+ for beta in np.arange(0, self.radius, si)
+ if abs(beta % self.interval_size) > self.epsilon
+ for alpha in np.arange(0, self.radius, self.epsilon)
+ for sgns in it.product((-1, 1), (-1, 1))
+ for x, y in [(alpha, beta), (beta, alpha)]
+ ], color = color)
+
+class NumberLine(Mobject1D):
+ def __init__(self,
+ radius = SPACE_WIDTH,
+ interval_size = 0.5, tick_size = 0.1,
+ *args, **kwargs):
+ self.radius = int(radius) + 1
+ self.interval_size = interval_size
+ self.tick_size = tick_size
+ Mobject1D.__init__(self, *args, **kwargs)
+
+ def generate_points(self):
+ self.add_points([
+ (x, 0, 0)
+ for x in np.arange(-self.radius, self.radius, self.epsilon)
+ ])
+ self.add_points([
+ (0, y, 0)
+ for y in np.arange(-2*self.tick_size, 2*self.tick_size, self.epsilon)
+ ])
+ self.add_points([
+ (x, y, 0)
+ for x in np.arange(-self.radius, self.radius, self.interval_size)
+ for y in np.arange(-self.tick_size, self.tick_size, self.epsilon)
+ ])
+
+
+
diff --git a/image_mobject.py b/mobject/image_mobject.py
similarity index 92%
rename from image_mobject.py
rename to mobject/image_mobject.py
index 0ac933e72..763db82b3 100644
--- a/image_mobject.py
+++ b/mobject/image_mobject.py
@@ -86,24 +86,21 @@ class VideoIcon(ImageMobject):
ImageMobject.__init__(self, "video_icon", *args, **kwargs)
self.scale(0.3)
-def text_mobject(text, size = r"\Large"):
+def text_mobject(text, size = "\\Large"):
image = tex_to_image(text, size, TEMPLATE_TEXT_FILE)
assert(not isinstance(image, list))
return ImageMobject(image).center()
#Purely redundant function to make singulars and plurals sensible
-def tex_mobject(expression, size = r"\Huge"):
+def tex_mobject(expression, size = "\\Huge"):
return tex_mobjects(expression, size)
-def tex_mobjects(expression, size = r"\Huge"):
+def tex_mobjects(expression, size = "\\Huge"):
images = tex_to_image(expression, size)
if isinstance(images, list):
#TODO, is checking listiness really the best here?
result = [ImageMobject(im) for im in images]
- center = CompoundMobject(*result).get_center()
- for mob in result:
- mob.shift(-center)
- return result
+ return CompoundMobject(*result).center().split()
else:
return ImageMobject(images).center()
diff --git a/mobject/mobject.py b/mobject/mobject.py
new file mode 100644
index 000000000..be7bb12d1
--- /dev/null
+++ b/mobject/mobject.py
@@ -0,0 +1,231 @@
+import numpy as np
+import itertools as it
+import os
+from PIL import Image
+from random import random
+from copy import deepcopy
+from colour import Color
+
+from constants import *
+from helpers import *
+import displayer as disp
+
+
+class Mobject(object):
+ """
+ Mathematical Object
+ """
+ #Number of numbers used to describe a point (3 for pos, 3 for normal vector)
+ DIM = 3
+
+ DEFAULT_COLOR = Color("skyblue")
+
+ SHOULD_BUFF_POINTS = GENERALLY_BUFF_POINTS
+
+ def __init__(self,
+ color = None,
+ name = None,
+ center = None,
+ ):
+ self.color = Color(color) if color else Color(self.DEFAULT_COLOR)
+ if not hasattr(self, "name"):
+ self.name = name or self.__class__.__name__
+ self.has_normals = hasattr(self, 'unit_normal')
+ self.points = np.zeros((0, 3))
+ self.rgbs = np.zeros((0, 3))
+ if self.has_normals:
+ self.unit_normals = np.zeros((0, 3))
+ self.generate_points()
+ if center:
+ self.center().shift(center)
+
+ def __str__(self):
+ return self.name
+
+ def show(self):
+ Image.fromarray(disp.paint_mobject(self)).show()
+
+ def save_image(self, name = None):
+ Image.fromarray(disp.paint_mobject(self)).save(
+ os.path.join(MOVIE_DIR, (name or str(self)) + ".png")
+ )
+
+ def add_points(self, points, rgbs = None, color = None):
+ """
+ points must be a Nx3 numpy array, as must rgbs if it is not None
+ """
+ points = np.array(points)
+ num_new_points = points.shape[0]
+ self.points = np.append(self.points, points)
+ self.points = self.points.reshape((self.points.size / 3, 3))
+ if rgbs is None:
+ color = Color(color) if color else self.color
+ rgbs = np.array([color.get_rgb()] * num_new_points)
+ else:
+ if rgbs.shape != points.shape:
+ raise Exception("points and rgbs must have same shape")
+ self.rgbs = np.append(self.rgbs, rgbs).reshape(self.points.shape)
+ if self.has_normals:
+ self.unit_normals = np.append(
+ self.unit_normals,
+ np.array([self.unit_normal(point) for point in points])
+ ).reshape(self.points.shape)
+ return self
+
+ def rotate(self, angle, axis = [0, 0, 1]):
+ t_rotation_matrix = np.transpose(rotation_matrix(angle, axis))
+ self.points = np.dot(self.points, t_rotation_matrix)
+ if self.has_normals:
+ self.unit_normals = np.dot(self.unit_normals, t_rotation_matrix)
+ return self
+
+ def rotate_in_place(self, angle, axis = [0, 0, 1]):
+ center = self.get_center()
+ self.shift(-center)
+ self.rotate(angle, axis)
+ self.shift(center)
+ return self
+
+ def shift(self, vector):
+ cycle = it.cycle(vector)
+ v = np.array([cycle.next() for x in range(self.points.size)]).reshape(self.points.shape)
+ self.points += v
+ return self
+
+ def center(self):
+ self.shift(-self.get_center())
+ return self
+
+ def scale(self, scale_factor):
+ self.points *= scale_factor
+ return self
+
+ def scale_in_place(self, scale_factor):
+ center = self.get_center()
+ return self.center().scale(scale_factor).shift(center)
+
+ def add(self, *mobjects):
+ for mobject in mobjects:
+ 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]
+
+ def pose_at_angle(self):
+ self.rotate(np.pi / 7)
+ self.rotate(np.pi / 7, [1, 0, 0])
+ return self
+
+ def apply_function(self, function):
+ self.points = np.apply_along_axis(function, 1, self.points)
+ return self
+
+ def apply_complex_function(self, function):
+ def point_map((x, y, z)):
+ result = function(complex(x, y))
+ return (result.real, result.imag, 0)
+ return self.apply_function(point_map)
+
+ def highlight(self, color = "red", condition = lambda x : True):
+ """
+ Condition is function which takes in one arguments, (x, y, z).
+ """
+ #TODO, Should self.color change?
+ to_change = np.apply_along_axis(condition, 1, self.points)
+ self.rgbs[to_change, :] *= 0
+ self.rgbs[to_change, :] += Color(color).get_rgb()
+ return self
+
+ def fade(self, amount = 0.5):
+ self.rgbs *= amount
+ return self
+
+ def filter_out(self, condition):
+ to_eliminate = ~np.apply_along_axis(condition, 1, self.points)
+ self.points = self.points[to_eliminate]
+ self.rgbs = self.rgbs[to_eliminate]
+ return self
+
+ ### Getters ###
+ def get_center(self):
+ return np.apply_along_axis(np.mean, 0, self.points)
+
+ def get_width(self):
+ return np.max(self.points[:, 0]) - np.min(self.points[:, 0])
+
+ def get_height(self):
+ return np.max(self.points[:, 1]) - np.min(self.points[:, 1])
+
+ ### Stuff subclasses should deal with ###
+ def should_buffer_points(self):
+ # potentially changed in subclasses
+ return GENERALLY_BUFF_POINTS
+
+ def generate_points(self):
+ #Typically implemented in subclass, unless purposefully left blank
+ pass
+
+ ### Static Methods ###
+ def align_data(mobject1, mobject2):
+ count1, count2 = mobject1.get_num_points(), mobject2.get_num_points()
+ if count1 == 0:
+ mobject1.add_points([(0, 0, 0)])
+ if count2 == 0:
+ mobject2.add_points([(0, 0, 0)])
+ if count1 == count2:
+ return
+ for attr in ['points', 'rgbs']:
+ new_arrays = make_even(getattr(mobject1, attr), getattr(mobject2, attr))
+ for array, mobject in zip(new_arrays, [mobject1, mobject2]):
+ setattr(mobject, attr, np.array(array))
+
+ def interpolate(mobject1, mobject2, target_mobject, alpha):
+ """
+ Turns target_mobject into an interpolation between mobject1
+ and mobject2.
+ """
+ Mobject.align_data(mobject1, mobject2)
+ for attr in ['points', 'rgbs']:
+ new_array = (1 - alpha) * getattr(mobject1, attr) + \
+ alpha * getattr(mobject2, attr)
+ setattr(target_mobject, attr, new_array)
+
+class Mobject1D(Mobject):
+ def __init__(self, density = DEFAULT_POINT_DENSITY_1D, *args, **kwargs):
+ self.epsilon = 1.0 / density
+
+ Mobject.__init__(self, *args, **kwargs)
+
+class Mobject2D(Mobject):
+ def __init__(self, density = DEFAULT_POINT_DENSITY_2D, *args, **kwargs):
+ self.epsilon = 1.0 / density
+ Mobject.__init__(self, *args, **kwargs)
+
+class CompoundMobject(Mobject):
+ def __init__(self, *mobjects):
+ Mobject.__init__(self)
+ self.original_mobs_num_points = []
+ for mobject in mobjects:
+ self.original_mobs_num_points.append(mobject.points.shape[0])
+ self.add_points(mobject.points, mobject.rgbs)
+
+ def split(self):
+ result = []
+ curr = 0
+ for num_points in self.original_mobs_num_points:
+ result.append(Mobject().add_points(
+ self.points[curr:curr+num_points, :],
+ self.rgbs[curr:curr+num_points, :]
+ ))
+ curr += num_points
+ return result
+
+
diff --git a/mobject/simple_mobjects.py b/mobject/simple_mobjects.py
new file mode 100644
index 000000000..124deb23c
--- /dev/null
+++ b/mobject/simple_mobjects.py
@@ -0,0 +1,124 @@
+import numpy as np
+import itertools as it
+
+from mobject import Mobject, Mobject1D, Mobject2D, CompoundMobject
+from constants import *
+from helpers import *
+
+class Point(Mobject):
+ def __init__(self, point = (0, 0, 0), *args, **kwargs):
+ Mobject.__init__(self, *args, **kwargs)
+ self.points = np.array(point).reshape(1, 3)
+ self.rgbs = np.array(self.color.get_rgb()).reshape(1, 3)
+
+class Arrow(Mobject1D):
+ DEFAULT_COLOR = "white"
+ NUNGE_DISTANCE = 0.1
+ def __init__(self, point = (0, 0, 0), direction = (-1, 1, 0),
+ length = 1, tip_length = 0.25,
+ normal = (0, 0, 1), *args, **kwargs):
+ self.point = np.array(point)
+ self.direction = np.array(direction) / np.linalg.norm(direction)
+ self.normal = np.array(normal)
+ self.length = length
+ self.tip_length = tip_length
+ Mobject1D.__init__(self, *args, **kwargs)
+
+ def generate_points(self):
+ self.add_points([
+ [x, x, x] * self.direction + self.point
+ for x in np.arange(-self.length, 0, self.epsilon)
+ ])
+ tips_dir = [np.array(-self.direction), np.array(-self.direction)]
+ for i, sgn in zip([0, 1], [-1, 1]):
+ tips_dir[i] = rotate_vector(tips_dir[i], sgn * np.pi / 4, self.normal)
+ self.add_points([
+ [x, x, x] * tips_dir[i] + self.point
+ for x in np.arange(0, self.tip_length, self.epsilon)
+ for i in [0, 1]
+ ])
+
+ def nudge(self):
+ return self.shift(-self.direction * self.NUNGE_DISTANCE)
+
+class Vector(Arrow):
+ def __init__(self, point = (1, 0, 0), *args, **kwargs):
+ length = np.linalg.norm(point)
+ Arrow.__init__(self, point = point, direction = point,
+ length = length, tip_length = 0.2 * length,
+ *args, **kwargs)
+
+class Dot(Mobject1D): #Use 1D density, even though 2D
+ DEFAULT_COLOR = "white"
+ DEFAULT_RADIUS = 0.05
+ def __init__(self, center = (0, 0, 0), radius = DEFAULT_RADIUS, *args, **kwargs):
+ center = np.array(center)
+ if center.size == 1:
+ raise Exception("Center must have 2 or 3 coordinates!")
+ elif center.size == 2:
+ center = np.append(center, [0])
+ self.center_point = center
+ self.radius = radius
+ Mobject1D.__init__(self, *args, **kwargs)
+
+ def generate_points(self):
+ self.add_points([
+ np.array((t*np.cos(theta), t*np.sin(theta), 0)) + self.center_point
+ for t in np.arange(self.epsilon, self.radius, self.epsilon)
+ for new_epsilon in [2*np.pi*self.epsilon*self.radius/t]
+ for theta in np.arange(0, 2 * np.pi, new_epsilon)
+ ])
+
+class Cross(Mobject1D):
+ RADIUS = 0.3
+ DEFAULT_COLOR = "white"
+ def generate_points(self):
+ self.add_points([
+ (sgn * x, x, 0)
+ for x in np.arange(-self.RADIUS / 2, self.RADIUS/2, self.epsilon)
+ for sgn in [-1, 1]
+ ])
+
+class Line(Mobject1D):
+ def __init__(self, start, end, density = DEFAULT_POINT_DENSITY_1D, *args, **kwargs):
+ self.start = np.array(start)
+ self.end = np.array(end)
+ density *= np.linalg.norm(self.start - self.end)
+ Mobject1D.__init__(self, density = density, *args, **kwargs)
+
+ def generate_points(self):
+ self.add_points([
+ t * self.end + (1 - t) * self.start
+ for t in np.arange(0, 1, self.epsilon)
+ ])
+
+class CurvedLine(Line):
+ def generate_points(self):
+ equidistant_point = rotate_vector(
+ self.end - self.start,
+ np.pi/3, [0,0,1]
+ ) + self.start
+ self.add_points([
+ (1 - t*(1-t))*(t*self.end + (1-t)*self.start) \
+ + t*(1-t)*equidistant_point
+ for t in np.arange(0, 1, self.epsilon)
+ ])
+ self.ep = equidistant_point
+
+class Circle(Mobject1D):
+ DEFAULT_COLOR = "red"
+ def generate_points(self):
+ self.add_points([
+ (np.cos(theta), np.sin(theta), 0)
+ for theta in np.arange(0, 2 * np.pi, self.epsilon)
+ ])
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/mobject/three_dimensional_mobjects.py b/mobject/three_dimensional_mobjects.py
new file mode 100644
index 000000000..4382c5f9e
--- /dev/null
+++ b/mobject/three_dimensional_mobjects.py
@@ -0,0 +1,113 @@
+import numpy as np
+import itertools as it
+
+from mobject import Mobject, Mobject1D, Mobject2D, CompoundMobject
+from simple_mobjects import Line
+from constants import *
+from helpers import *
+
+class Stars(Mobject):
+ DEFAULT_COLOR = "white"
+ SHOULD_BUFF_POINTS = False
+ def __init__(self, num_points = DEFAULT_NUM_STARS,
+ *args, **kwargs):
+ self.num_points = num_points
+ Mobject.__init__(self, *args, **kwargs)
+
+ def generate_points(self):
+ self.add_points([
+ (
+ r * np.sin(phi)*np.cos(theta),
+ r * np.sin(phi)*np.sin(theta),
+ r * np.cos(phi)
+ )
+ for x in range(self.num_points)
+ for r, phi, theta in [[
+ max(SPACE_HEIGHT, SPACE_WIDTH) * random(),
+ np.pi * random(),
+ 2 * np.pi * random(),
+ ]]
+ ])
+
+class CubeWithFaces(Mobject2D):
+ def generate_points(self):
+ self.add_points([
+ sgn * np.array(coords)
+ for x in np.arange(-1, 1, self.epsilon)
+ for y in np.arange(x, 1, self.epsilon)
+ for coords in it.permutations([x, y, 1])
+ for sgn in [-1, 1]
+ ])
+ self.pose_at_angle()
+
+ def unit_normal(self, coords):
+ return np.array(map(lambda x : 1 if abs(x) == 1 else 0, coords))
+
+class Cube(Mobject1D):
+ DEFAULT_COLOR = "yellow"
+ def generate_points(self):
+ self.add_points([
+ ([a, b, c][p[0]], [a, b, c][p[1]], [a, b, c][p[2]])
+ for p in [(0, 1, 2), (2, 0, 1), (1, 2, 0)]
+ for a, b, c in it.product([-1, 1], [-1, 1], np.arange(-1, 1, self.epsilon))
+ ])
+ self.pose_at_angle()
+
+class Octohedron(Mobject1D):
+ DEFAULT_COLOR = "pink"
+ def generate_points(self):
+ x = np.array([1, 0, 0])
+ y = np.array([0, 1, 0])
+ z = np.array([0, 0, 1])
+ vertex_pairs = [(x+y, x-y), (x+y,-x+y), (-x-y,-x+y), (-x-y,x-y)]
+ vertex_pairs += [
+ (b[0]*x+b[1]*y, b[2]*np.sqrt(2)*z)
+ for b in it.product(*[(-1, 1)]*3)
+ ]
+ for pair in vertex_pairs:
+ self.add_points(
+ Line(pair[0], pair[1], density = 1/self.epsilon).points
+ )
+ self.pose_at_angle()
+
+class Dodecahedron(Mobject1D):
+ DEFAULT_COLOR = "limegreen"
+ def generate_points(self):
+ phi = (1 + np.sqrt(5)) / 2
+ x = np.array([1, 0, 0])
+ y = np.array([0, 1, 0])
+ z = np.array([0, 0, 1])
+ v1, v2 = (phi, 1/phi, 0), (phi, -1/phi, 0)
+ vertex_pairs = [
+ (v1, v2),
+ (x+y+z, v1),
+ (x+y-z, v1),
+ (x-y+z, v2),
+ (x-y-z, v2),
+ ]
+ five_lines_points = CompoundMobject(*[
+ Line(pair[0], pair[1], density = 1.0/self.epsilon)
+ for pair in vertex_pairs
+ ]).points
+ #Rotate those 5 edges into all 30.
+ for i in range(3):
+ perm = map(lambda j : j%3, range(i, i+3))
+ for b in [-1, 1]:
+ matrix = b*np.array([x[perm], y[perm], z[perm]])
+ self.add_points(np.dot(five_lines_points, matrix))
+ self.pose_at_angle()
+
+class Sphere(Mobject2D):
+ def generate_points(self):
+ self.add_points([
+ (
+ np.sin(phi) * np.cos(theta),
+ np.sin(phi) * np.sin(theta),
+ np.cos(phi)
+ )
+ for phi in np.arange(self.epsilon, np.pi, self.epsilon)
+ for theta in np.arange(0, 2 * np.pi, 2 * self.epsilon / np.sin(phi))
+ ])
+
+ def unit_normal(self, coords):
+ return np.array(coords) / np.linalg.norm(coords)
\ No newline at end of file
diff --git a/moser/main.py~ b/moser/main.py~
deleted file mode 100644
index e3b901079..000000000
--- a/moser/main.py~
+++ /dev/null
@@ -1,518 +0,0 @@
-#!/usr/bin/env python
-
-import numpy as np
-import itertools as it
-import operator as op
-from copy import deepcopy
-from random import random
-
-
-from animation import *
-from mobject import *
-from image_mobject import *
-from constants import *
-from region import *
-from scene import Scene
-
-from moser_helpers import *
-from graphs import *
-
-RADIUS = SPACE_HEIGHT - 0.1
-CIRCLE_DENSITY = DEFAULT_POINT_DENSITY_1D*RADIUS
-
-movie_prefix = "moser/"
-
-############################################
-
-class CircleScene(Scene):
- def __init__(self, radians, *args, **kwargs):
- Scene.__init__(self, *args, **kwargs)
- self.radius = RADIUS
- self.circle = Circle(density = CIRCLE_DENSITY).scale(self.radius)
- self.points = [
- (self.radius * np.cos(angle), self.radius * np.sin(angle), 0)
- for angle in radians
- ]
- self.dots = [Dot(point) for point in self.points]
- self.lines = [Line(p1, p2) for p1, p2 in it.combinations(self.points, 2)]
- self.add(self.circle, *self.dots + self.lines)
-
-class GraphScene(Scene):
- #Note, the placement of vertices in this is pretty hard coded, be
- #warned if you want to change it.
- def __init__(self, graph, *args, **kwargs):
- Scene.__init__(self, *args, **kwargs)
- #See CUBE_GRAPH above for format of graph
- self.graph = graph
- self.points = map(np.array, graph["vertices"])
- self.vertices = self.dots = [Dot(p) for p in self.points]
- self.edges = [
- Line(self.points[i], self.points[j])
- for i, j in graph["edges"]
- ]
- self.add(*self.dots + self.edges)
-
- def generate_regions(self):
- regions = [
- region_from_line_boundary(*[
- [
- self.points[rc[i]],
- self.points[rc[(i+1)%len(rc)]]
- ]
- for i in range(len(rc))
- ])
- for rc in self.graph["region_cycles"]
- ]
- regions[-1].complement()#Outer region painted outwardly...
- self.regions = regions
-
-##################################################
-
-def count_lines(*radians):
- #TODO, Count things explicitly?
- sc = CircleScene(radians)
- text_center = (sc.radius + 1, sc.radius -1, 0)
- scale_factor = 0.4
- text = tex_mobject(r"\text{How Many Lines?}", size = r"\large")
- n = len(radians)
- formula, answer = tex_mobject([
- r"{%d \choose 2} = \frac{%d(%d - 1)}{2} = "%(n, n, n),
- str(choose(n, 2))
- ])
- text.scale(scale_factor).shift(text_center)
- x = text_center[0]
- new_lines = [
- Line((x-1, y, 0), (x+1, y, 0))
- for y in np.arange(
- -(sc.radius - 1),
- sc.radius - 1,
- (2*sc.radius - 2)/len(sc.lines)
- )
- ]
- sc.add(text)
- sc.dither()
- sc.animate(*[
- Transform(line1, line2, run_time = 2)
- for line1, line2 in zip(sc.lines, new_lines)
- ])
- sc.dither()
- sc.remove(text)
- sc.count(new_lines)
- anims = [FadeIn(formula)]
- for mob in sc.mobjects:
- if mob == sc.number: #put in during animate_count
- anims.append(Transform(mob, answer))
- else:
- anims.append(FadeOut(mob))
- sc.animate(*anims, run_time = 1)
- sc.write_to_movie(movie_prefix + "CountLines%dPoints"%len(radians))
-
-
-def count_intersection_points(*radians):
- radians = [r % (2*np.pi) for r in radians]
- radians.sort()
- sc = CircleScene(radians)
- intersection_points = [
- intersection((p[0], p[2]), (p[1], p[3]))
- for p in it.combinations(sc.points, 4)
- ]
- intersection_dots = [Dot(point) for point in intersection_points]
- text_center = (sc.radius + 0.5, sc.radius -0.5, 0)
- size = r"\large"
- scale_factor = 0.4
- text = tex_mobject(r"\text{How Many Intersection Points?}", size = size)
- n = len(radians)
- formula, answer = tex_mobjects([
- r"{%d \choose 4} = \frac{%d(%d - 1)(%d - 2)(%d-3)}{1\cdot 2\cdot 3 \cdot 4}="%(n, n, n, n, n),
- str(choose(n, 4))
- ])
- text.scale(scale_factor).shift(text_center)
- # new_points = [
- # (text_center[0], y, 0)
- # for y in np.arange(
- # -(sc.radius - 1),
- # sc.radius - 1,
- # (2*sc.radius - 2)/choose(len(sc.points), 4)
- # )
- # ]
- # new_dots = CompoundMobject(*[
- # Dot(point) for point in new_points
- # ])
-
- sc.add(text)
- sc.count(intersection_dots, "show", num_offset = (0, 0, 0))
- sc.dither()
- # sc.animate(Transform(intersection_dots, new_dots))
- anims = []
- for mob in sc.mobjects:
- if mob == sc.number: #put in during animate_count
- anims.append(Transform(mob, answer))
- else:
- anims.append(FadeOut(mob))
- anims.append(Animation(formula))
- sc.animate(*anims, run_time = 1)
-
- name = "CountIntersectionPoints%dPoints"%len(radians)
- sc.write_to_movie(movie_prefix + name)
-
-def non_general_position():
- radians = np.arange(1, 7)
- new_radians = (np.pi/3)*radians
- sc1 = CircleScene(radians)
- sc2 = CircleScene(new_radians)
- center_region = reduce(
- Region.intersect,
- [
- HalfPlane((sc1.points[x], sc1.points[(x+3)%6]))
- for x in [0, 4, 2]#Ya know, trust it
- ]
- )
- center_region
- text = tex_mobject(r"\text{This region disappears}", size = r"\large")
- text.center().scale(0.5).shift((-sc1.radius, sc1.radius-0.3, 0))
- arrow = Arrow(
- point = (-0.35, -0.1, 0),
- direction = (1, -1, 0),
- length = sc1.radius + 1,
- color = "white",
- )
-
- sc1.highlight_region(center_region, "green")
- sc1.add(text, arrow)
- sc1.dither(2)
- sc1.remove(text, arrow)
- sc1.reset_background()
- sc1.animate(*[
- Transform(mob1, mob2, run_time = DEFAULT_ANIMATION_RUN_TIME)
- for mob1, mob2 in zip(sc1.mobjects, sc2.mobjects)
- ])
- sc1.write_to_movie(movie_prefix + "NonGeneralPosition")
-
-def line_corresponds_with_pair(radians, r1, r2):
- sc = CircleScene(radians)
- #Remove from sc.lines list, so they won't be faded out
- assert r1 in radians and r2 in radians
- line_index = list(it.combinations(radians, 2)).index((r1, r2))
- radians = list(radians)
- dot0_index, dot1_index = radians.index(r1), radians.index(r2)
- line, dot0, dot1 = sc.lines[line_index], sc.dots[dot0_index], sc.dots[dot1_index]
- sc.lines.remove(line)
- sc.dots.remove(dot0)
- sc.dots.remove(dot1)
- sc.dither()
- sc.animate(*[
- FadeOut(mob, alpha_func = not_quite_there)
- for mob in sc.lines + sc.dots
- ])
- sc.add(sc.circle)
- sc.animate(*[
- ScaleInPlace(mob, 3, alpha_func = there_and_back)
- for mob in (dot0, dot1)
- ])
- sc.animate(Transform(line, dot0))
- name = "LineCorrspondsWithPair%d%d"%(dot0_index, dot1_index)
- sc.write_to_movie(movie_prefix + name)
-
-def illustrate_n_choose_k(n, k):
- sc = Scene()
- nrange = range(1, n+1)
- tuples = list(it.combinations(nrange, k))
- nrange_mobs = tex_mobjects([str(n) + r'\;' for n in nrange])
- tuple_mobs = tex_mobjects(
- [
- (r'\\&' if c%(20//k) == 0 else r'\;\;') + str(p)
- for p, c in zip(tuples, it.count())
- ],
- size = r"\small"
- )
- tuple_terms = {
- 2 : "pairs",
- 3 : "triplets",
- 4 : "quadruplets",
- }
- tuple_term = tuple_terms[k] if k in tuple_terms else "tuples"
- form1, count, form2 = tex_mobject([
- r"{%d \choose %d} = "%(n, k),
- "%d"%choose(n, k),
- r" \text{ total %s}"%tuple_term
- ])
- for mob in nrange_mobs:
- mob.shift((0, 2, 0))
- for mob in form1, count, form2:
- mob.shift((0, -SPACE_HEIGHT + 1, 0))
- count_center = count.get_center()
- for mob in tuple_mobs:
- mob.scale(0.6)
-
- sc.add(*nrange_mobs)
- sc.dither()
- run_time = 6.0
- frame_time = run_time / len(tuples)
- for tup, count in zip(tuples, it.count()):
- count_mob = tex_mobject(str(count+1))
- count_mob.center().shift(count_center)
- sc.add(count_mob)
- tuple_copy = CompoundMobject(*[nrange_mobs[index-1] for index in tup])
- tuple_copy.highlight()
- sc.add(tuple_copy)
- sc.add(tuple_mobs[count])
- sc.dither(frame_time)
- sc.remove(count_mob)
- sc.remove(tuple_copy)
- sc.add(count_mob)
- sc.animate(FadeIn(CompoundMobject(form1, form2)))
- sc.write_to_movie(movie_prefix + "Illustrate%dChoose%d"%(n, k))
-
-def intersection_point_correspondances(radians, indices):
- assert(len(indices) == 4)
- indices.sort()
- sc = CircleScene(radians)
- intersection_point = intersection(
- (sc.points[indices[0]], sc.points[indices[2]]),
- (sc.points[indices[1]], sc.points[indices[3]])
- )
- intersection_point = tuple(list(intersection_point) + [0])
- intersection_dot = Dot(intersection_point)
- intersection_dot_arrow = Arrow(intersection_point).nudge()
- sc.add(intersection_dot)
- pairs = list(it.combinations(range(len(radians)), 2))
- lines_to_save = [
- sc.lines[pairs.index((indices[p0], indices[p1]))]
- for p0, p1 in [(0, 2), (1, 3)]
- ]
- dots_to_save = [
- sc.dots[p]
- for p in indices
- ]
- line_statement = tex_mobject(r"\text{Pair of Lines}")
- dots_statement = tex_mobject(r"&\text{Quadruplet of} \\ &\text{outer dots}")
- for mob in line_statement, dots_statement:
- mob.center()
- mob.scale(0.7)
- mob.shift((SPACE_WIDTH-2, SPACE_HEIGHT - 1, 0))
- fade_outs = []
- line_highlights = []
- dot_highlights = []
- dot_pointers = []
- for mob in sc.mobjects:
- if mob in lines_to_save:
- line_highlights.append(Highlight(mob))
- elif mob in dots_to_save:
- dot_highlights.append(Highlight(mob))
- dot_pointers.append(Arrow(mob.get_center()).nudge())
- elif mob != intersection_dot:
- fade_outs.append(FadeOut(mob, alpha_func = not_quite_there))
-
- sc.add(intersection_dot_arrow)
- sc.animate(Highlight(intersection_dot))
- sc.remove(intersection_dot_arrow)
- sc.animate(*fade_outs)
- sc.dither()
- sc.add(line_statement)
- sc.animate(*line_highlights)
- sc.remove(line_statement)
- sc.dither()
- sc.add(dots_statement, *dot_pointers)
- sc.animate(*dot_highlights)
- sc.remove(dots_statement, *dot_pointers)
-
- name = "IntersectionPointCorrespondances"
- for ind in indices:
- name += str(ind)
- sc.write_to_movie(movie_prefix + name)
-
-def lines_intersect_outside(radians, indices):
- assert(len(indices) == 4)
- indices.sort()
- sc = CircleScene(radians)
- intersection_point = intersection(
- (sc.points[indices[0]], sc.points[indices[1]]),
- (sc.points[indices[2]], sc.points[indices[3]])
- )
- intersection_point = tuple(list(intersection_point) + [0])
- intersection_dot = Dot(intersection_point)
- pairs = list(it.combinations(range(len(radians)), 2))
- lines_to_save = [
- sc.lines[pairs.index((indices[p0], indices[p1]))]
- for p0, p1 in [(0, 1), (2, 3)]
- ]
- sc.animate(*[
- FadeOut(mob, alpha_func = not_quite_there)
- for mob in sc.mobjects if mob not in lines_to_save
- ])
- sc.animate(*[
- Transform(
- Line(sc.points[indices[p0]], sc.points[indices[p1]]),
- Line(sc.points[indices[p0]], intersection_point))
- for p0, p1 in [(0, 1), (3, 2)]
- ] + [ShowCreation(intersection_dot)])
-
- name = "LinesIntersectOutside"
- for ind in indices:
- name += str(ind)
- sc.write_to_movie(movie_prefix + name)
-
-def quadruplets_to_intersections(*radians):
- sc = CircleScene(radians)
- quadruplets = it.combinations(range(len(radians)), 4)
- frame_time = 1.0
- for quad in quadruplets:
- intersection_dot = Dot(intersection(
- (sc.points[quad[0]], sc.points[quad[2]]),
- (sc.points[quad[1]], sc.points[quad[3]])
- )).repeat(3)
- dot_quad = [deepcopy(sc.dots[i]) for i in quad]
- for dot in dot_quad:
- dot.scale_in_place(2)
- # arrows = [Arrow(d.get_center()) for d in dot_quad]
- dot_quad = CompoundMobject(*dot_quad)
- # arrows = CompoundMobject(*arrows)
- dot_quad.highlight()
- # sc.add(arrows)
- sc.add(dot_quad)
- sc.dither(frame_time / 3)
- sc.animate(Transform(
- dot_quad,
- intersection_dot,
- run_time = 3*frame_time/2
- ))
- # sc.remove(arrows)
-
- name = "QuadrupletsToIntersections" + str(len(radians))
- sc.write_to_movie(movie_prefix + name)
-
-def defining_graph(graph):
- gs = GraphScene(graph)
- dots, lines = gs.vertices, gs.edges
- gs.remove(*dots + lines)
- all_dots = CompoundMobject(*dots)
- gs.animate(ShowCreation(all_dots))
- gs.remove(all_dots)
- gs.add(*dots)
- gs.dither()
- gs.animate(*[
- ShowCreation(line) for line in lines
- ])
-
- #Move to new graph
- new_graph = deepcopy(graph)
- new_graph["vertices"] = [
- (v[0] + 3*random(), v[1] + 3*random(), 0)
- for v in new_graph["vertices"]
- ]
- ngs = GraphScene(new_graph)
- gs.animate(*[
- Transform(m[0], m[1])
- for m in zip(gs.mobjects, ngs.mobjects)
- ], run_time = 7.0)
-
- name = "DefiningGraph" + graph["name"]
- gs.write_to_movie(movie_prefix + name)
-
-def doubled_edges(graph):
- gs = GraphScene(graph)
- lines_to_double = gs.edges[:9:3]
- crazy_lines = [
- (
- line,
- Line(line.end, line.start),
- CurvedLine(line.start, line.end) ,
- CurvedLine(line.end, line.start)
- )
- for line in lines_to_double
- ]
- anims = []
- outward_curved_lines = []
- kwargs = {"run_time" : 3.0}
- for straight, backwards, inward, outward in crazy_lines:
- anims += [
- Transform(straight, inward, **kwargs),
- Transform(backwards, outward, **kwargs),
- ]
- outward_curved_lines.append(outward)
- gs.animate(*anims)
- gs.dither()
- gs.remove(*outward_curved_lines)
-
- name = "DoubledEdges" + graph["name"]
- gs.write_to_movie(movie_prefix + name)
-
-
-def eulers_formula(graph):
- gs = GraphScene(graph)
- terms = "V - E + F =2".split(" ")
- form = dict([
- (key, mob)
- for key, mob in zip(terms, tex_mobjects(terms))
- ])
- for mob in form.values():
- mob.shift((0, SPACE_HEIGHT-1.5, 0))
- formula = CompoundMobject(*form.values())
- new_form = dict([
- (key, deepcopy(mob).shift((0, -0.7, 0)))
- for key, mob in zip(form.keys(), form.values())
- ])
- gs.add(formula)
- colored_dots = [
- deepcopy(d).scale_in_place(1.5).highlight("red")
- for d in gs.dots
- ]
- colored_edges = [
- deepcopy(e).highlight("red")
- for e in gs.edges
- ]
- frame_time = 0.3
-
- gs.generate_regions()
- parameters = [
- (colored_dots, "V", "mobject", "-", "show_creation"),
- (colored_edges, "E", "mobject", "+", "show_creation"),
- (gs.regions, "F", "region", "=2", "show_all")
- ]
- for items, letter, item_type, symbol, mode in parameters:
- gs.count(
- items,
- item_type = item_type,
- mode = mode,
- num_offset = new_form[letter].get_center(),
- run_time = frame_time*len(items)
- )
- gs.dither()
- if item_type == "mobject":
- gs.remove(*items)
- gs.add(new_form[symbol])
- gs.reset_background()
-
- name = "EulersFormula" + graph["name"]
- gs.write_to_movie(movie_prefix + name)
-
-
-##################################################
-
-if __name__ == '__main__':
- radians = np.arange(0, 6, 6.0/7)
- # count_lines(*radians)
- # count_lines(*radians[:4])
- # count_intersection_points(*radians[:4])
- # count_intersection_points(*radians[:6])
- # count_intersection_points(*radians)
- # non_general_position()
- # line_corresponds_with_pair(radians, radians[3], radians[4])
- # line_corresponds_with_pair(radians, radians[2], radians[5])
- # illustrate_n_choose_k(7, 2)
- # illustrate_n_choose_k(6, 4)
- # intersection_point_correspondances(radians, range(0, 7, 2))
- # lines_intersect_outside(radians, [2, 4, 5, 6])
- quadruplets_to_intersections(*radians[:6])
- # defining_graph(SAMPLE_GRAPH)
- # doubled_edges(CUBE_GRAPH)
- # eulers_formula(CUBE_GRAPH)
- # eulers_formula(SAMPLE_GRAPH)
- # eulers_formula(OCTOHEDRON_GRAPH)
-
-
-
-
-
-
-
diff --git a/moser/moser_helpers.py b/moser/moser_helpers.py
index 433426933..4d6a4fa92 100644
--- a/moser/moser_helpers.py
+++ b/moser/moser_helpers.py
@@ -1,8 +1,8 @@
import numpy as np
-import operator as op
import itertools as it
from constants import *
+from helpers import *
from image_mobject import *
from region import *
from scene import Scene
@@ -115,163 +115,14 @@ class CircleScene(Scene):
map(lambda r : r.intersect(interior), self.regions)
self.exterior = interior.complement()
-class GraphScene(Scene):
- args_list = [
- (CUBE_GRAPH,),
- (SAMPLE_GRAPH,),
- (OCTOHEDRON_GRAPH,),
- ]
- @staticmethod
- def args_to_string(*args):
- return args[0]["name"]
-
- def __init__(self, graph, *args, **kwargs):
- Scene.__init__(self, *args, **kwargs)
- #See CUBE_GRAPH above for format of graph
- self.graph = graph
- self.points = map(np.array, graph["vertices"])
- self.vertices = self.dots = [Dot(p) for p in self.points]
- self.edges = [
- Line(self.points[i], self.points[j])
- for i, j in graph["edges"]
- ]
- self.add(*self.dots + self.edges)
-
- def generate_regions(self):
- regions = [
- region_from_line_boundary(*[
- [
- self.points[rc[i]],
- self.points[rc[(i+1)%len(rc)]]
- ]
- for i in range(len(rc))
- ])
- for rc in self.graph["region_cycles"]
- ]
- regions[-1].complement()#Outer region painted outwardly...
- self.regions = regions
-
-class PascalsTriangleScene(Scene):
- args_list = [
- (N_PASCAL_ROWS,),
- (BIG_N_PASCAL_ROWS,),
- ]
- @staticmethod
- def args_to_string(*args):
- return str(args[0])
-
- def __init__(self, nrows, *args, **kwargs):
- Scene.__init__(self, *args, **kwargs)
- self.nrows = nrows
- self.diagram_height = 2*SPACE_HEIGHT - 1
- self.diagram_width = 1.5*SPACE_WIDTH
- self.cell_height = self.diagram_height / nrows
- self.cell_width = self.diagram_width / nrows
- self.portion_to_fill = 0.7
- self.bottom_left = np.array(
- (-self.cell_width * nrows / 2.0, -self.cell_height * nrows / 2.0, 0)
- )
- num_to_num_mob = {}
- self.coords_to_mobs = {}
- self.coords = [(n, k) for n in range(nrows) for k in range(n+1)]
- for n, k in self.coords:
- num = choose(n, k)
- center = self.coords_to_center(n, k)
- if num not in num_to_num_mob:
- num_to_num_mob[num] = tex_mobject(str(num))
- num_mob = deepcopy(num_to_num_mob[num])
- scale_factor = min(
- 1,
- self.portion_to_fill * self.cell_height / num_mob.get_height(),
- self.portion_to_fill * self.cell_width / num_mob.get_width(),
- )
- num_mob.center().scale(scale_factor).shift(center)
- if n not in self.coords_to_mobs:
- self.coords_to_mobs[n] = {}
- self.coords_to_mobs[n][k] = num_mob
- self.add(*[self.coords_to_mobs[n][k] for n, k in self.coords])
-
- def coords_to_center(self, n, k):
- return self.bottom_left + (
- self.cell_width * (k+self.nrows/2.0 - n/2.0),
- self.cell_height * (self.nrows - n),
- 0
- )
-
- def generate_n_choose_k_mobs(self):
- self.coords_to_n_choose_k = {}
- for n, k in self.coords:
- nck_mob = tex_mobject(r"{%d \choose %d}"%(n, k))
- scale_factor = min(
- 1,
- self.portion_to_fill * self.cell_height / nck_mob.get_height(),
- self.portion_to_fill * self.cell_width / nck_mob.get_width(),
- )
- center = self.coords_to_mobs[n][k].get_center()
- nck_mob.center().scale(scale_factor).shift(center)
- if n not in self.coords_to_n_choose_k:
- self.coords_to_n_choose_k[n] = {}
- self.coords_to_n_choose_k[n][k] = nck_mob
-
- def generate_sea_of_zeros(self):
- zero = tex_mobject("0")
- self.sea_of_zeros = []
- for n in range(self.nrows):
- for a in range((self.nrows - n)/2 + 1):
- for k in (n + a + 1, -a -1):
- self.coords.append((n, k))
- mob = deepcopy(zero)
- mob.shift(self.coords_to_center(n, k))
- self.coords_to_mobs[n][k] = mob
- self.add(mob)
-
-
##################################################
def int_list_to_string(int_list):
return "-".join(map(str, int_list))
-def choose(n, r):
- if n < r: return 0
- if r == 0: return 1
- denom = reduce(op.mul, xrange(1, r+1), 1)
- numer = reduce(op.mul, xrange(n, n-r, -1), 1)
- return numer//denom
-
def moser_function(n):
return choose(n, 4) + choose(n, 2) + 1
-def is_on_line(p0, p1, p2, threshold = 0.01):
- """
- Returns true of p0 is on the line between p1 and p2
- """
- p0, p1, p2 = map(lambda tup : np.array(tup[:2]), [p0, p1, p2])
- p1 -= p0
- p2 -= p0
- return abs((p1[0] / p1[1]) - (p2[0] / p2[1])) < threshold
-
-
-def intersection(line1, line2):
- """
- A "line" should come in the form [(x0, y0), (x1, y1)] for two
- points it runs through
- """
- p0, p1, p2, p3 = map(
- lambda tup : np.array(tup[:2]),
- [line1[0], line1[1], line2[0], line2[1]]
- )
- p1, p2, p3 = map(lambda x : x - p0, [p1, p2, p3])
- transform = np.zeros((2, 2))
- transform[:,0], transform[:,1] = p1, p2
- if np.linalg.det(transform) == 0: return
- inv = np.linalg.inv(transform)
- new_p3 = np.dot(inv, p3.reshape((2, 1)))
- #Where does line connecting (0, 1) to new_p3 hit x axis
- x_intercept = new_p3[0] / (1 - new_p3[1])
- result = np.dot(transform, [[x_intercept], [0]])
- result = result.reshape((2,)) + p0
- return result
-
diff --git a/sample_script.py b/sample_script.py
new file mode 100644
index 000000000..1bf9bd9d4
--- /dev/null
+++ b/sample_script.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+
+import numpy as np
+import itertools as it
+import operator as op
+from copy import deepcopy
+from random import random, randint
+import sys
+import inspect
+
+
+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):
+ mob = Mobject()
+ circle9 = Circle().repeat(9).scale(3)
+ Mobject.interpolate(Circle().scale(3), circle9, mob, 0.8)
+ self.animate(Transform(
+ mob,
+ circle9,
+ run_time = 3.0,
+ alpha_func = there_and_back,
+ ))
+
+
+if __name__ == "__main__":
+ command_line_create_scene(sys.argv[1:])
\ No newline at end of file
diff --git a/scene/__init__.py b/scene/__init__.py
new file mode 100644
index 000000000..8e51a1587
--- /dev/null
+++ b/scene/__init__.py
@@ -0,0 +1,2 @@
+from scene import *
+from sub_scenes import *
\ No newline at end of file
diff --git a/moser/graphs.py b/scene/graphs.py
similarity index 81%
rename from moser/graphs.py
rename to scene/graphs.py
index 3fc2093bf..634ec7590 100644
--- a/moser/graphs.py
+++ b/scene/graphs.py
@@ -3,10 +3,10 @@ import numpy as np
CUBE_GRAPH = {
"name" : "CubeGraph",
- # 5 7
- # 12
- # 03
- # 4 6
+ # 5 7
+ # 12
+ # 03
+ # 4 6
"vertices" : [
(x, y, 0)
for r in (1, 2)
@@ -38,10 +38,10 @@ CUBE_GRAPH = {
SAMPLE_GRAPH = {
"name" : "SampleGraph",
- # 4 2 3
- # 0 1
- #
- # 5
+ # 4 2 3
+ # 0 1
+ #
+ # 5
"vertices" :[
( 0, 0, 0),
( 2, 0, 0),
@@ -75,11 +75,11 @@ SAMPLE_GRAPH = {
OCTOHEDRON_GRAPH = {
"name" : "OctohedronGraph",
- # 3
- #
- # 1 0
- # 2
- #4 5
+ # 3
+ #
+ # 1 0
+ # 2
+ #4 5
"vertices" : [
(r*np.cos(angle), r*np.sin(angle)-1, 0)
for r, s in [(1, 0), (3, 3)]
diff --git a/scene.py b/scene/scene.py
similarity index 97%
rename from scene.py
rename to scene/scene.py
index 73ce8046d..fd381fb88 100644
--- a/scene.py
+++ b/scene/scene.py
@@ -9,10 +9,8 @@ import copy
import progressbar
import inspect
-
from helpers import *
from mobject import *
-from image_mobject import *
from animation import *
import displayer as disp
from tk_scene import TkSceneRoot
@@ -40,6 +38,10 @@ class Scene(object):
self.background = self.original_background
self.shape = self.background.shape[:2]
#TODO, space shape
+ self.construct()
+
+ def construct(self):
+ pass #To be implemented in subclasses
def __str__(self):
return self.__class__.__name__
@@ -68,6 +70,10 @@ class Scene(object):
self.mobjects.remove(mobject)
return self
+ def clear(self):
+ self.reset_background()
+ self.remove(*self.mobjects)
+ return self
def highlight_region(self, region, color = None):
self.background = disp.paint_region(
@@ -79,6 +85,7 @@ class Scene(object):
def reset_background(self):
self.background = self.original_background
+ return self
def animate(self, *animations, **kwargs):
if "run_time" in kwargs:
@@ -203,7 +210,6 @@ class Scene(object):
Image.fromarray(self.get_frame()).show()
def preview(self):
- self.dither()
TkSceneRoot(self)
def save_image(self, path):
diff --git a/scene/sub_scenes.py b/scene/sub_scenes.py
new file mode 100644
index 000000000..cf6bef514
--- /dev/null
+++ b/scene/sub_scenes.py
@@ -0,0 +1,122 @@
+import numpy as np
+import itertools as it
+
+from scene import Scene
+from graphs import *
+
+from mobject import *
+from animation import *
+from constants import *
+from helpers import *
+
+class GraphScene(Scene):
+ args_list = [
+ (CUBE_GRAPH,),
+ (SAMPLE_GRAPH,),
+ (OCTOHEDRON_GRAPH,),
+ ]
+ @staticmethod
+ def args_to_string(*args):
+ return args[0]["name"]
+
+ def __init__(self, graph, *args, **kwargs):
+ Scene.__init__(self, *args, **kwargs)
+ #See CUBE_GRAPH above for format of graph
+ self.graph = graph
+ self.points = map(np.array, graph["vertices"])
+ self.vertices = self.dots = [Dot(p) for p in self.points]
+ self.edges = [
+ Line(self.points[i], self.points[j])
+ for i, j in graph["edges"]
+ ]
+ self.add(*self.dots + self.edges)
+
+ def generate_regions(self):
+ regions = [
+ region_from_line_boundary(*[
+ [
+ self.points[rc[i]],
+ self.points[rc[(i+1)%len(rc)]]
+ ]
+ for i in range(len(rc))
+ ])
+ for rc in self.graph["region_cycles"]
+ ]
+ regions[-1].complement()#Outer region painted outwardly...
+ self.regions = regions
+
+BIG_N_PASCAL_ROWS = 11
+N_PASCAL_ROWS = 7
+class PascalsTriangleScene(Scene):
+ args_list = [
+ (N_PASCAL_ROWS,),
+ (BIG_N_PASCAL_ROWS,),
+ ]
+ @staticmethod
+ def args_to_string(*args):
+ return str(args[0])
+
+ def __init__(self, nrows, *args, **kwargs):
+ Scene.__init__(self, *args, **kwargs)
+ self.nrows = nrows
+ self.diagram_height = 2*SPACE_HEIGHT - 1
+ self.diagram_width = 1.5*SPACE_WIDTH
+ self.cell_height = self.diagram_height / nrows
+ self.cell_width = self.diagram_width / nrows
+ self.portion_to_fill = 0.7
+ self.bottom_left = np.array(
+ (-self.cell_width * nrows / 2.0, -self.cell_height * nrows / 2.0, 0)
+ )
+ num_to_num_mob = {}
+ self.coords_to_mobs = {}
+ self.coords = [(n, k) for n in range(nrows) for k in range(n+1)]
+ for n, k in self.coords:
+ num = choose(n, k)
+ center = self.coords_to_center(n, k)
+ if num not in num_to_num_mob:
+ num_to_num_mob[num] = tex_mobject(str(num))
+ num_mob = deepcopy(num_to_num_mob[num])
+ scale_factor = min(
+ 1,
+ self.portion_to_fill * self.cell_height / num_mob.get_height(),
+ self.portion_to_fill * self.cell_width / num_mob.get_width(),
+ )
+ num_mob.center().scale(scale_factor).shift(center)
+ if n not in self.coords_to_mobs:
+ self.coords_to_mobs[n] = {}
+ self.coords_to_mobs[n][k] = num_mob
+ self.add(*[self.coords_to_mobs[n][k] for n, k in self.coords])
+
+ def coords_to_center(self, n, k):
+ return self.bottom_left + (
+ self.cell_width * (k+self.nrows/2.0 - n/2.0),
+ self.cell_height * (self.nrows - n),
+ 0
+ )
+
+ def generate_n_choose_k_mobs(self):
+ self.coords_to_n_choose_k = {}
+ for n, k in self.coords:
+ nck_mob = tex_mobject(r"{%d \choose %d}"%(n, k))
+ scale_factor = min(
+ 1,
+ self.portion_to_fill * self.cell_height / nck_mob.get_height(),
+ self.portion_to_fill * self.cell_width / nck_mob.get_width(),
+ )
+ center = self.coords_to_mobs[n][k].get_center()
+ nck_mob.center().scale(scale_factor).shift(center)
+ if n not in self.coords_to_n_choose_k:
+ self.coords_to_n_choose_k[n] = {}
+ self.coords_to_n_choose_k[n][k] = nck_mob
+
+ def generate_sea_of_zeros(self):
+ zero = tex_mobject("0")
+ self.sea_of_zeros = []
+ for n in range(self.nrows):
+ for a in range((self.nrows - n)/2 + 1):
+ for k in (n + a + 1, -a -1):
+ self.coords.append((n, k))
+ mob = deepcopy(zero)
+ mob.shift(self.coords_to_center(n, k))
+ self.coords_to_mobs[n][k] = mob
+ self.add(mob)
\ No newline at end of file
diff --git a/tk_scene.py b/scene/tk_scene.py
similarity index 76%
rename from tk_scene.py
rename to scene/tk_scene.py
index 1446ddfba..639395430 100644
--- a/tk_scene.py
+++ b/scene/tk_scene.py
@@ -8,24 +8,23 @@ class TkSceneRoot(Tkinter.Tk):
def __init__(self, scene):
if scene.frames == []:
raise str(scene) + " has no frames!"
- self.scene = scene
Tkinter.Tk.__init__(self)
- self.height, self.width = scene.shape
- kwargs = {"height" : self.height, "width" : self.width}
+ height, width = scene.shape
+ kwargs = {"height" : height, "width" : width}
self.frame = Tkinter.Frame(self, **kwargs)
self.frame.pack()
self.canvas = Tkinter.Canvas(self.frame, **kwargs)
self.canvas.configure(background='black')
- self.canvas.place(x=-2,y=-2)
+ self.canvas.place(x=0,y=0)
last_time = time.time()
- for frame in it.cycle(self.scene.frames):
+ for frame in it.cycle(scene.frames):
try:
self.show_new_image(frame)
except:
break
- sleep_time = self.scene.frame_duration
+ sleep_time = scene.frame_duration
sleep_time -= time.time() - last_time
time.sleep(max(0, sleep_time))
last_time = time.time()
@@ -40,5 +39,4 @@ class TkSceneRoot(Tkinter.Tk):
0, 0,
image = photo, anchor = Tkinter.NW
)
- # self.after(self.frame_duration_in_ms, self.show_new_image)
self.update()
diff --git a/script_wrapper.py b/script_wrapper.py
index b086e1333..1e3968d5d 100644
--- a/script_wrapper.py
+++ b/script_wrapper.py
@@ -2,12 +2,14 @@ import sys
import getopt
import imp
import itertools as it
+import inspect
from helpers import cammel_case_initials
+from scene import Scene
from constants import *
HELP_MESSAGE = """
- <script name> [-s <scene name or initials> -a <arg_string>]
+ <script name> [<scene name or initials>] [<arg_string>]
"""
SCENE_NOT_FOUND_MESSAGE = """
No scene name or ititials \"%s\" and arg string \"%s\"
@@ -61,24 +63,31 @@ def find_scene_class_and_args(scene_string, args_extension,
sys.exit(0)
return possible_results[index]
-def command_line_create_scene(sys_argv, scene_classes, movie_prefix = ""):
+def command_line_create_scene(sys_argv, movie_prefix = ""):
+ scene_classes = [
+ pair[1]
+ for pair in inspect.getmembers(
+ sys.modules["__main__"],
+ lambda obj : inspect.isclass(obj) and \
+ issubclass(obj, Scene) and \
+ obj != Scene
+ )
+ ]
try:
- opts, args = getopt.getopt(sys_argv, "h:s:a:l:p")
+ opts, args = getopt.getopt(sys_argv, "h:l:p")
except getopt.GetoptError as err:
print str(err)
sys.exit(2)
+
scene_string = ""
args_extension = ""
display_config = PRODUCTION_QUALITY_DISPLAY_CONFIG
preview = False
+
for opt, arg in opts:
if opt == '-h':
print HELP_MESSAGE
return
- elif opt == '-s':
- scene_string = arg
- elif opt == '-a':
- args_extension = arg
elif opt == '-l':
display_config = LOW_QUALITY_DISPLAY_CONFIG
elif opt == '-p':
diff --git a/moser/intro.py b/scripts/moser_intro.py
similarity index 100%
rename from moser/intro.py
rename to scripts/moser_intro.py
diff --git a/moser/main.py b/scripts/moser_main.py
similarity index 99%
rename from moser/main.py
rename to scripts/moser_main.py
index 475cefd8e..c3873cb28 100644
--- a/moser/main.py
+++ b/scripts/moser_main.py
@@ -1585,14 +1585,7 @@ class IntersectionChoppingExamples(Scene):
##################################################
if __name__ == "__main__":
- scene_classes = [
- pair[1]
- for pair in inspect.getmembers(
- sys.modules[__name__],
- lambda obj : inspect.isclass(obj) and issubclass(obj, Scene)
- )
- ]
- command_line_create_scene(sys.argv[1:], scene_classes, MOVIE_PREFIX)
+ command_line_create_scene(sys.argv[1:], MOVIE_PREFIX)