Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Finished first Khan Articles

Grant Sanderson096c5c1890e3
diff --git a/animation/animation.py b/animation/animation.py
index ea4fa798a..ff13d6948 100644
--- a/animation/animation.py
+++ b/animation/animation.py
@@ -20,11 +20,8 @@ class Animation(object):
"name" : None,
}
def __init__(self, mobject, **kwargs):
- if isinstance(mobject, type) and issubclass(mobject, Mobject):
- mobject = mobject()
- elif not isinstance(mobject, Mobject):
- raise Exception("Invalid mobject parameter, must be \
- subclass or instance of Mobject")
+ mobject = instantiate(mobject)
+ assert(isinstance(mobject, Mobject))
digest_config(self, Animation, kwargs, locals())
self.starting_mobject = copy.deepcopy(self.mobject)
if self.alpha_func is None:
diff --git a/animation/transform.py b/animation/transform.py
index a47998cbc..169cc5360 100644
--- a/animation/transform.py
+++ b/animation/transform.py
@@ -12,40 +12,39 @@ from helpers import *
def straight_path(start_points, end_points, alpha):
return (1-alpha)*start_points + alpha*end_points
-def semi_circular_path(start_points, end_points, alpha, axis):
- midpoints = (start_points + end_points) / 2
- angle = alpha * np.pi
- rot_matrix = rotation_matrix(angle, axis)[:2, :2]
- result = np.zeros(start_points.shape)
- result[:,:2] = np.dot(
- (start_points - midpoints)[:,:2],
- np.transpose(rot_matrix)
- ) + midpoints[:,:2]
- result[:,2] = (1-alpha)*start_points[:,2] + alpha*end_points[:,2]
- return result
-
-def clockwise_path(start_points, end_points, alpha):
- return semi_circular_path(start_points, end_points, alpha, IN)
-
-def counterclockwise_path(start_points, end_points, alpha):
- return semi_circular_path(start_points, end_points, alpha, OUT)
-
-def get_best_interpolation_function(angle):
- angle = (angle + np.pi)%(2*np.pi) - np.pi
- if abs(angle) < np.pi/2:
+def path_along_arc(arc_angle):
+ """
+ If vect is vector from start to end, [vect[:,1], -vect[:,0]] is
+ perpendicualr to vect in the left direction.
+ """
+ if arc_angle == 0:
return straight_path
- elif angle > 0:
- return counterclockwise_path
- else:
- return clockwise_path
+ def path(start_points, end_points, alpha):
+ vects = end_points - start_points
+ centers = start_points + 0.5*vects
+ if arc_angle != np.pi:
+ for i, b in [(0, -1), (1, 1)]:
+ centers[:,i] += 0.5*b*vects[:,1-i]/np.tan(arc_angle/2)
+ return centers + np.dot(
+ start_points-centers,
+ np.transpose(rotation_about_z(alpha*arc_angle))
+ )
+ return path
+
+def clockwise_path():
+ return path_along_arc(np.pi)
+
+def counterclockwise_path():
+ return path_along_arc(-np.pi)
+
class Transform(Animation):
DEFAULT_CONFIG = {
- "run_time" : DEFAULT_TRANSFORM_RUN_TIME,
"interpolation_function" : straight_path,
"should_black_out_extra_points" : False
}
def __init__(self, mobject, ending_mobject, **kwargs):
+ mobject, ending_mobject = map(instantiate, [mobject, ending_mobject])
digest_config(self, Transform, kwargs, locals())
count1, count2 = mobject.get_num_points(), ending_mobject.get_num_points()
if count2 == 0:
@@ -99,7 +98,7 @@ class Transform(Animation):
class ClockwiseTransform(Transform):
DEFAULT_CONFIG = {
- "interpolation_function" : clockwise_path
+ "interpolation_function" : clockwise_path()
}
def __init__(self, *args, **kwargs):
digest_config(self, ClockwiseTransform, kwargs)
@@ -107,7 +106,7 @@ class ClockwiseTransform(Transform):
class CounterclockwiseTransform(Transform):
DEFAULT_CONFIG = {
- "interpolation_function" : counterclockwise_path
+ "interpolation_function" : counterclockwise_path()
}
def __init__(self, *args, **kwargs):
digest_config(self, ClockwiseTransform, kwargs)
@@ -115,7 +114,7 @@ class CounterclockwiseTransform(Transform):
class SpinInFromNothing(Transform):
DEFAULT_CONFIG = {
- "interpolation_function" : counterclockwise_path
+ "interpolation_function" : counterclockwise_path()
}
def __init__(self, mob, **kwargs):
digest_config(self, SpinInFromNothing, kwargs)
@@ -129,9 +128,8 @@ class ApplyMethod(Transform):
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"
+ assert(inspect.ismethod(method))
+ assert(isinstance(method.im_self, Mobject))
Transform.__init__(
self,
method.im_self,
@@ -139,6 +137,30 @@ class ApplyMethod(Transform):
**kwargs
)
+class ApplyPointwiseFunction(ApplyMethod):
+ DEFAULT_CONFIG = {
+ "run_time" : DEFAULT_POINTWISE_FUNCTION_RUN_TIME
+ }
+ def __init__(self, function, mobject, **kwargs):
+ digest_config(self, ApplyPointwiseFunction, kwargs)
+ ApplyMethod.__init__(
+ self, mobject.apply_function, function, **kwargs
+ )
+
+
+class ComplexFunction(ApplyPointwiseFunction):
+ def __init__(self, function, mobject = ComplexPlane, **kwargs):
+ if "interpolation_function" not in kwargs:
+ self.interpolation_function = path_along_arc(
+ np.log(function(complex(1))).imag
+ )
+ ApplyPointwiseFunction.__init__(
+ self,
+ lambda (x, y, z) : complex_to_R3(function(complex(x, y))),
+ instantiate(mobject),
+ **kwargs
+ )
+
class FadeToColor(ApplyMethod):
def __init__(self, mobject, color, **kwargs):
ApplyMethod.__init__(self, mobject.highlight, color, **kwargs)
@@ -177,32 +199,6 @@ class ApplyMatrix(Animation):
np.transpose(matrix)
)
-class ApplyPointwiseFunction(Transform):
- DEFAULT_CONFIG = {
- "run_time" : DEFAULT_ANIMATION_RUN_TIME
- }
- def __init__(self, function, mobject, **kwargs):
- digest_config(self, ApplyPointwiseFunction, kwargs)
- map_image = copy.deepcopy(mobject)
- map_image.points = np.array(map(function, map_image.points))
- Transform.__init__(self, mobject, map_image, **kwargs)
- self.name = "".join([
- "Apply",
- "".join([s.capitalize() for s in function.__name__.split("_")]),
- "To" + str(mobject)
- ])
-
-class ComplexFunction(ApplyPointwiseFunction):
- def __init__(self, function, mobject = ComplexPlane, **kwargs):
- def point_map(point):
- x, y, z = point
- c = np.complex(x, y)
- c = function(c)
- return c.real, c.imag, z
- ApplyPointwiseFunction.__init__(self, mobject, point_map, *args, **kwargs)
- self.name = "ComplexFunction" + to_cammel_case(function.__name__)
- #Todo, abstract away function naming'
-
class TransformAnimations(Transform):
DEFAULT_CONFIG = {
diff --git a/constants.py b/constants.py
index 2749d1c82..b70cdcf55 100644
--- a/constants.py
+++ b/constants.py
@@ -7,6 +7,12 @@ PRODUCTION_QUALITY_DISPLAY_CONFIG = {
"frame_duration" : 0.04,
}
+MEDIUM_QUALITY_DISPLAY_CONFIG = {
+ "height" : 720,
+ "width" : 1280,
+ "frame_duration" : 0.04,
+}
+
LOW_QUALITY_DISPLAY_CONFIG = {
"height" : 480,
"width" : 840,
@@ -17,7 +23,7 @@ LOW_QUALITY_DISPLAY_CONFIG = {
DEFAULT_POINT_DENSITY_2D = 25
DEFAULT_POINT_DENSITY_1D = 200
-DEFAULT_POINT_THICKNESS = 4
+DEFAULT_POINT_THICKNESS = 3
#TODO, Make sure these are not needd
DEFAULT_HEIGHT = PRODUCTION_QUALITY_DISPLAY_CONFIG["height"]
@@ -33,7 +39,7 @@ DEFAULT_MOBJECT_TO_MOBJECT_BUFFER = 0.2
#All in seconds
DEFAULT_FRAME_DURATION = 0.04
DEFAULT_ANIMATION_RUN_TIME = 1.0
-DEFAULT_TRANSFORM_RUN_TIME = 1.0
+DEFAULT_POINTWISE_FUNCTION_RUN_TIME = 3.0
DEFAULT_DITHER_TIME = 1.0
@@ -74,9 +80,6 @@ MAX_LEN_FOR_HUGE_TEX_FONT = 25
LOGO_PATH = os.path.join(IMAGE_DIR, "logo.png")
-DARK_BLUE = "#236B8E"
-DARK_BROWN = "#8B4513"
-LIGHT_BROWN = "#CD853F"
PI_CREATURE_DIR = os.path.join(IMAGE_DIR, "PiCreature")
PI_CREATURE_PART_NAME_TO_DIR = lambda name : os.path.join(PI_CREATURE_DIR, "pi_creature_"+name) + ".png"
@@ -84,13 +87,63 @@ PI_CREATURE_SCALE_VAL = 0.5
PI_CREATURE_MOUTH_TO_EYES_DISTANCE = 0.25
-
-
-
-
-
-
-
+### Colors ###
+
+
+COLOR_MAP = {
+ "DARK_BLUE" : "#236B8E",
+ "DARK_BROWN" : "#8B4513",
+ "LIGHT_BROWN" : "#CD853F",
+ "BLUE_A" : "#1C758A",
+ "BLUE_B" : "#29ABCA",
+ "BLUE_C" : "#58C4DD",
+ "BLUE_D" : "#9CDCEB",
+ "BLUE_E" : "#C7E9F1",
+ "TEAL_A" : "#49A88F",
+ "TEAL_B" : "#55C1A7",
+ "TEAL_C" : "#5CD0B3",
+ "TEAL_D" : "#76DDC0",
+ "TEAL_E" : "#ACEAD7",
+ "GREEN_A" : "#699C52",
+ "GREEN_B" : "#77B05D",
+ "GREEN_C" : "#83C167",
+ "GREEN_D" : "#A6CF8C",
+ "GREEN_E" : "#C9E2AE",
+ "YELLOW_A" : "#E8C11C",
+ "YELLOW_B" : "#F4D345",
+ "YELLOW_C" : "#FCE15B",
+ "YELLOW_D" : "#FFEA94",
+ "YELLOW_E" : "#FFF1B6",
+ "GOLD_A" : "#C78D46",
+ "GOLD_B" : "#E1A158",
+ "GOLD_C" : "#F0AC5F",
+ "GOLD_D" : "#F9B775",
+ "GOLD_E" : "#F7C797",
+ "RED_A" : "#CF5044",
+ "RED_B" : "#E65A4C",
+ "RED_C" : "#FC6255",
+ "RED_D" : "#FF8080",
+ "RED_E" : "#F7A1A3",
+ "MAROON_A" : "#94424F",
+ "MAROON_B" : "#A24D61",
+ "MAROON_C" : "#C55F73",
+ "MAROON_D" : "#EC92AB",
+ "MAROON_E" : "#ECABC1",
+ "PURPLE_A" : "#644172",
+ "PURPLE_B" : "#715582",
+ "PURPLE_C" : "#9A72AC",
+ "PURPLE_D" : "#B189C6",
+ "PURPLE_E" : "#CAA3E8",
+ "WHITE" : "#FFFFFF",
+ "BLACK" : "#000000",
+}
+PALETTE = COLOR_MAP.values()
+global_dict = globals()
+global_dict.update(COLOR_MAP)
+for name in ["BLUE", "TEAL", "GREEN",
+ "YELLOW", "GOLD", "RED",
+ "MAROON", "PURPLE"]:
+ global_dict[name] = global_dict[name + "_C"]
diff --git a/displayer.py b/displayer.py
index 17b893b67..690e35ec8 100644
--- a/displayer.py
+++ b/displayer.py
@@ -44,11 +44,12 @@ def paint_mobjects(mobjects, image_array = None):
width = pixels.shape[1]
space_height = SPACE_HEIGHT
space_width = SPACE_HEIGHT * width / height
- pixels = pixels.reshape((pixels.size/3, 3))
+ pixels = pixels.reshape((pixels.size/3, 3)).astype('uint8')
for mobject in mobjects:
if mobject.get_num_points() == 0:
continue
+ #bunch these together so rgbs never get lost from points
points_and_rgbs = np.append(
mobject.points,
255*mobject.rgbs,
@@ -74,8 +75,7 @@ def paint_mobjects(mobjects, image_array = None):
indices = np.dot(points, flattener)[:,0]
pixels[indices] = rgbs.astype('uint8')
- pixels = pixels.reshape((height, width, 3)).astype('uint8')
- return pixels
+ return pixels.reshape((height, width, 3))
def add_thickness(pixel_indices_and_rgbs, thickness, width, height):
"""
diff --git a/helpers.py b/helpers.py
index a1354dd3b..0ce0e318c 100644
--- a/helpers.py
+++ b/helpers.py
@@ -9,6 +9,21 @@ import operator as op
from constants import *
+def adjascent_pairs(objects):
+ return zip(objects, list(objects[1:])+[objects[0]])
+
+def complex_to_R3(complex_num):
+ return np.array((complex_num.real, complex_num.imag, 0))
+
+def instantiate(obj):
+ """
+ Useful so that classes or instance of those classes can be
+ included in configuration, which can prevent defaults from
+ getting created during compilation/importing
+ """
+ return obj() if isinstance(obj, type) else obj
+
+
def digest_config(obj, Class, kwargs, local_args = {}):
"""
To be used in initializing most-to-all objects.
diff --git a/mobject/creatures.py b/mobject/creatures.py
index 283afdb9d..9ee7c3c98 100644
--- a/mobject/creatures.py
+++ b/mobject/creatures.py
@@ -8,7 +8,7 @@ from simple_mobjects import *
class PiCreature(CompoundMobject):
- DEFAULT_COLOR = "blue"
+ DEFAULT_COLOR = BLUE
PART_NAMES = [
'arm',
'body',
diff --git a/mobject/function_graphs.py b/mobject/function_graphs.py
index ba768f638..057cecfc0 100644
--- a/mobject/function_graphs.py
+++ b/mobject/function_graphs.py
@@ -2,14 +2,14 @@ import numpy as np
import itertools as it
from mobject import Mobject, Mobject1D, Mobject2D, CompoundMobject
-from simple_mobjects import Arrow, Line
+from simple_mobjects import Arrow, Line, Circle
from image_mobject import tex_mobject
from constants import *
from helpers import *
class FunctionGraph(Mobject1D):
DEFAULT_CONFIG = {
- "color" : "lightblue",
+ "color" : BLUE,
"x_min" : -10,
"x_max" : 10,
"spatial_radius" : SPACE_WIDTH,
@@ -31,7 +31,7 @@ class FunctionGraph(Mobject1D):
class ParametricFunction(Mobject):
DEFAULT_CONFIG = {
- "color" : "white",
+ "color" : WHITE,
"dim" : 1,
"expected_measure" : 10.0,
"density" : None
@@ -61,7 +61,7 @@ class ParametricFunction(Mobject):
class NumberLine(Mobject1D):
DEFAULT_CONFIG = {
- "color" : "skyblue",
+ "color" : BLUE,
"numerical_radius" : SPACE_WIDTH,
"unit_length_to_spatial_width" : 1,
"tick_size" : 0.1,
@@ -177,7 +177,7 @@ class Axes(CompoundMobject):
class NumberPlane(Mobject1D):
DEFAULT_CONFIG = {
- "color" : "skyblue",
+ "color" : BLUE,
"x_radius" : SPACE_WIDTH,
"y_radius" : SPACE_HEIGHT,
"x_unit_to_spatial_width" : 1,
@@ -195,45 +195,55 @@ class NumberPlane(Mobject1D):
Mobject1D.__init__(self, **kwargs)
def generate_points(self):
+ #TODO, clean this
color = self.color
faded = Color(rgb = self.fade_factor*np.array(color.get_rgb()))
- #Vertical Lines
- freq_color_pairs = [
- (self.x_faded_line_frequency, faded),
- (self.x_line_frequency, color)
- ]
- for freq, color in freq_color_pairs:
- if not freq:
- continue
- self.add_points([
- (sgns[0]*self.x_unit_to_spatial_width*x, sgns[1]*y, 0)
- for x in np.arange(0, self.x_radius, freq)
- for y in np.arange(0, self.y_radius, self.epsilon)
- for sgns in it.product([-1, 1], [-1, 1])
- ], color = color)
- #Horizontal lines
- freq_color_pairs = [
- (self.y_faded_line_frequency, faded),
- (self.y_line_frequency, color)
+
+ freq_color_tuples = [
+ (self.x_line_frequency, self.y_line_frequency, color),
+ (self.x_faded_line_frequency, self.y_faded_line_frequency, faded),
]
- for freq, color in freq_color_pairs:
- if not freq:
+ x_vals = []
+ y_vals = []
+ for x_freq, y_freq, color in freq_color_tuples:
+ if not x_freq or not y_freq:
continue
- self.add_points([
- (sgns[0]*x, sgns[1]*self.y_uint_to_spatial_height*y, 0)
- for x in np.arange(0, self.x_radius, self.epsilon)
- for y in np.arange(0, self.y_radius, freq)
- for sgns in it.product([-1, 1], [-1, 1])
- ], color = color)
+ x_vals = np.array(filter(lambda x : x not in x_vals, np.arange(
+ 0, self.x_radius,
+ self.x_unit_to_spatial_width*x_freq
+ )))
+ y_vals = np.array(filter(lambda y : y not in y_vals, np.arange(
+ 0, self.y_radius,
+ self.y_uint_to_spatial_height*y_freq
+ )))
+ x_cont_vals = np.arange(
+ 0, self.x_radius,
+ self.epsilon/self.x_unit_to_spatial_width
+ )
+ y_cont_vals = np.arange(
+ 0, self.y_radius,
+ self.epsilon/self.y_uint_to_spatial_height
+ )
+ for x_sgn, y_sgn in it.product([-1, 1], [-1, 1]):
+ self.add_points(
+ list(it.product(x_sgn*x_vals, y_sgn*y_cont_vals, [0])) + \
+ list(it.product(x_sgn*x_cont_vals, y_sgn*y_vals, [0])),
+ color = color
+ )
self.shift(self.get_center_point())
+
+
def get_center_point(self):
return self.num_pair_to_point(self.num_pair_at_center)
def num_pair_to_point(self, pair):
pair = pair + self.num_pair_at_center
- return pair[0]*self.x_unit_to_spatial_width*RIGHT + \
- pair[1]*self.y_uint_to_spatial_height*UP
+ return np.array([
+ pair[0]*self.x_unit_to_spatial_width,
+ pair[1]*self.y_uint_to_spatial_height,
+ 0
+ ])
def get_coordinate_labels(self, x_vals = None, y_vals = None):
result = []
@@ -267,7 +277,7 @@ class NumberPlane(Mobject1D):
class ComplexPlane(NumberPlane):
DEFAULT_CONFIG = {
- "color" : "lightgreen",
+ "color" : GREEN,
"unit_to_spatial_width" : 1,
"line_frequency" : 1,
"faded_line_frequency" : 0.5,
@@ -315,6 +325,20 @@ class ComplexPlane(NumberPlane):
self.add(*self.get_coordinate_labels(*numbers))
return self
+ def add_spider_web(self, circle_freq = 1, angle_freq = np.pi/6):
+ self.fade(self.fade_factor)
+ config = {
+ "color" : self.color,
+ "density" : self.density,
+ }
+ for radius in np.arange(circle_freq, SPACE_WIDTH, circle_freq):
+ self.add(Circle(radius = radius, **config))
+ for angle in np.arange(0, 2*np.pi, angle_freq):
+ end_point = np.cos(angle)*RIGHT + np.sin(angle)*UP
+ end_point *= SPACE_WIDTH
+ self.add(Line(ORIGIN, end_point, **config))
+ return self
+
diff --git a/mobject/image_mobject.py b/mobject/image_mobject.py
index 8d3dcfdc2..af581e3f0 100644
--- a/mobject/image_mobject.py
+++ b/mobject/image_mobject.py
@@ -148,10 +148,10 @@ def tex_mobject(expression,
return result.center().highlight("white")
-def underbrace(left, right):
+def underbrace(left, right, buff = 0.2):
result = tex_mobject("\\underbrace{%s}"%(14*"\\quad"))
result.stretch_to_fit_width(right[0]-left[0])
- result.shift(left - result.points[0])
+ result.shift(left - result.points[0] + buff*DOWN)
return result
diff --git a/mobject/mobject.py b/mobject/mobject.py
index 485061263..3fb3eee4a 100644
--- a/mobject/mobject.py
+++ b/mobject/mobject.py
@@ -20,7 +20,7 @@ class Mobject(object):
"""
#Number of numbers used to describe a point (3 for pos, 3 for normal vector)
DEFAULT_CONFIG = {
- "color" : "white",
+ "color" : WHITE,
"point_thickness" : DEFAULT_POINT_THICKNESS,
"name" : None,
}
@@ -153,6 +153,7 @@ class Mobject(object):
direction = RIGHT,
buff = DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
aligned_edge = None):
+ direction = direction / np.linalg.norm(direction)
if aligned_edge is not None:
anchor_point = self.get_corner(aligned_edge-direction)
target_point = mobject.get_corner(aligned_edge+direction)
@@ -191,6 +192,12 @@ class Mobject(object):
def stretch_to_fit_height(self, height):
return self.stretch_to_fit(height, 1)
+ def scale_to_fit_width(self, width):
+ return self.scale(width/self.get_width())
+
+ def scale_to_fit_height(self, height):
+ return self.scale(height/self.get_height())
+
def pose_at_angle(self):
self.rotate(np.pi / 7)
self.rotate(np.pi / 7, [1, 0, 0])
@@ -213,10 +220,9 @@ class Mobject(object):
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)
+ return self.apply_function(
+ lambda (x, y, z) : complex_to_R3(function(complex(x, y)))
+ )
def highlight(self, color = "yellow", condition = None):
"""
@@ -244,7 +250,7 @@ class Mobject(object):
return self
def fade(self, brightness = 0.5):
- self.fade_to("black", brightness)
+ self.rgbs *= brightness
return self
def filter_out(self, condition):
@@ -271,6 +277,8 @@ class Mobject(object):
return len(self.points)
def get_center(self):
+ if self.get_num_points() == 0:
+ return ORIGIN
return (np.max(self.points, 0) + np.min(self.points, 0))/2.0
def get_center_of_mass(self):
diff --git a/mobject/simple_mobjects.py b/mobject/simple_mobjects.py
index ef39b04f7..8dc67135c 100644
--- a/mobject/simple_mobjects.py
+++ b/mobject/simple_mobjects.py
@@ -9,7 +9,7 @@ from helpers import *
class Point(Mobject):
DEFAULT_CONFIG = {
- "color" : "black",
+ "color" : BLACK,
}
def __init__(self, location = ORIGIN, **kwargs):
digest_config(self, Point, kwargs, locals())
@@ -37,7 +37,7 @@ class Dot(Mobject1D): #Use 1D density, even though 2D
class Cross(Mobject1D):
DEFAULT_CONFIG = {
- "color" : "yellow",
+ "color" : YELLOW,
"radius" : 0.3
}
def __init__(self, center_point = ORIGIN, **kwargs):
@@ -92,7 +92,7 @@ class Line(Mobject1D):
class Arrow(Line):
DEFAULT_CONFIG = {
- "color" : "white",
+ "color" : WHITE,
"tip_length" : 0.25
}
def __init__(self, *args, **kwargs):
@@ -145,24 +145,39 @@ class CurvedLine(Line):
for t in np.arange(0, 1, self.epsilon)
])
-class Circle(Mobject1D):
+
+
+class PartialCircle(Mobject1D):
DEFAULT_CONFIG = {
- "color" : "red",
- "radius" : 1.0
+ "radius" : 1.0,
+ "start_angle" : 0
}
- def __init__(self, **kwargs):
- digest_config(self, Circle, kwargs)
+ def __init__(self, angle, **kwargs):
+ digest_config(self, PartialCircle, kwargs, locals())
Mobject1D.__init__(self, **kwargs)
def generate_points(self):
+ sign = 1 if self.angle >= 0 else -1
self.add_points([
(self.radius*np.cos(theta), self.radius*np.sin(theta), 0)
- for theta in np.arange(0, 2 * np.pi, self.epsilon/self.radius)
+ for theta in np.arange(
+ self.start_angle,
+ self.start_angle+self.angle,
+ sign*self.epsilon/self.radius
+ )
])
+class Circle(PartialCircle):
+ DEFAULT_CONFIG = {
+ "color" : RED,
+ }
+ def __init__(self, **kwargs):
+ digest_config(self, Circle, kwargs)
+ PartialCircle.__init__(self, angle = 2*np.pi, **kwargs)
+
class Polygon(Mobject1D):
DEFAULT_CONFIG = {
- "color" : "limegreen",
+ "color" : GREEN_D,
"edge_colors" : None
}
def __init__(self, *points, **kwargs):
@@ -190,7 +205,7 @@ class Polygon(Mobject1D):
class Rectangle(Mobject1D):
DEFAULT_CONFIG = {
- "color" : "yellow",
+ "color" : YELLOW,
"height" : 2.0,
"width" : 4.0
}
diff --git a/mobject/three_dimensional_mobjects.py b/mobject/three_dimensional_mobjects.py
index 372bccac5..0d7483390 100644
--- a/mobject/three_dimensional_mobjects.py
+++ b/mobject/three_dimensional_mobjects.py
@@ -41,7 +41,7 @@ class CubeWithFaces(Mobject2D):
for sgn in [-1, 1]
])
self.pose_at_angle()
- self.set_color("skyblue")
+ self.set_color(BLUE)
def unit_normal(self, coords):
return np.array(map(lambda x : 1 if abs(x) == 1 else 0, coords))
@@ -54,7 +54,7 @@ class Cube(Mobject1D):
for a, b, c in it.product([-1, 1], [-1, 1], np.arange(-1, 1, self.epsilon))
])
self.pose_at_angle()
- self.set_color("yellow")
+ self.set_color(YELLOW)
class Octohedron(Mobject1D):
def generate_points(self):
@@ -71,7 +71,7 @@ class Octohedron(Mobject1D):
Line(pair[0], pair[1], density = 1/self.epsilon).points
)
self.pose_at_angle()
- self.set_color("pink")
+ self.set_color(MAROON_D)
class Dodecahedron(Mobject1D):
def generate_points(self):
@@ -98,7 +98,7 @@ class Dodecahedron(Mobject1D):
matrix = b*np.array([x[perm], y[perm], z[perm]])
self.add_points(np.dot(five_lines_points, matrix))
self.pose_at_angle()
- self.set_color("limegreen")
+ self.set_color(GREEN)
class Sphere(Mobject2D):
def generate_points(self):
@@ -111,7 +111,7 @@ class Sphere(Mobject2D):
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))
])
- self.set_color("blue")
+ self.set_color(BLUE)
def unit_normal(self, coords):
return np.array(coords) / np.linalg.norm(coords)
diff --git a/region.py b/region.py
index fc4e030b5..bdbb76d44 100644
--- a/region.py
+++ b/region.py
@@ -5,6 +5,7 @@ import cv2
from copy import deepcopy
from constants import *
+from helpers import *
import displayer as disp
class Region(object):
@@ -85,9 +86,7 @@ def region_from_line_boundary(*lines, **kwargs):
return reg
def region_from_polygon_vertices(*vertices, **kwargs):
- points = list(vertices)
- points.append(points[0])
- return region_from_line_boundary(*zip(points, points[1:]), **kwargs)
+ return region_from_line_boundary(*adjascent_pairs(vertices), **kwargs)
def plane_partition(*lines, **kwargs):
diff --git a/sample_script.py b/sample_script.py
index 8452ed394..748fc8d8f 100644
--- a/sample_script.py
+++ b/sample_script.py
@@ -16,9 +16,11 @@ from script_wrapper import command_line_create_scene
class SampleScene(Scene):
def construct(self):
- c = ComplexPlane().add_coordinates()
+ words = text_mobject("Hi There")
+ self.paint_into_background(words.shift(UP).highlight(RED_A))
+ self.paint_into_background(words.shift(DOWN).highlight(RED_E))
+
- self.add_local_mobjects()
diff --git a/scene/arithmetic_scenes.py b/scene/arithmetic_scenes.py
index 84c32d19b..53b469866 100644
--- a/scene/arithmetic_scenes.py
+++ b/scene/arithmetic_scenes.py
@@ -17,7 +17,7 @@ class RearrangeEquation(Scene):
end_terms,
index_map,
size = None,
- path = counterclockwise_path,
+ path = counterclockwise_path(),
start_transform = None,
end_transform = None,
leave_start_terms = False,
diff --git a/scene/number_line.py b/scene/number_line.py
index 9b1a3c1a3..f2cae7439 100644
--- a/scene/number_line.py
+++ b/scene/number_line.py
@@ -78,7 +78,7 @@ class NumberLineScene(Scene):
if num > 0:
kwargs["interpolation_function"] = straight_path
else:
- kwargs["interpolation_function"] = counterclockwise_path
+ kwargs["interpolation_function"] = counterclockwise_path()
self.play(*[
ApplyMethod(self.number_line.stretch, num, 0, **kwargs)
]+[
diff --git a/script_wrapper.py b/script_wrapper.py
index 55a63f404..cf7db0324 100644
--- a/script_wrapper.py
+++ b/script_wrapper.py
@@ -20,13 +20,17 @@ HELP_MESSAGE = """
SCENE_NOT_FOUND_MESSAGE = """
That scene is not in the script
"""
-CHOOSE_NUMBER_MESSAGE = "Choose number corresponding to desired scene arguments: "
+CHOOSE_NUMBER_MESSAGE = """
+Choose number corresponding to desired scene arguments.
+(Use comma separated list for multiple entries)
+
+Choice(s):"""
INVALID_NUMBER_MESSAGE = "Fine then, if you don't want to give a valid number I'll just quit"
def get_configuration(sys_argv):
try:
- opts, args = getopt.getopt(sys_argv[1:], 'hlpwsqa')
+ opts, args = getopt.getopt(sys_argv[1:], 'hlmpwsqa')
except getopt.GetoptError as err:
print str(err)
sys.exit(2)
@@ -46,6 +50,8 @@ def get_configuration(sys_argv):
return
elif opt == '-l':
config["display_config"] = LOW_QUALITY_DISPLAY_CONFIG
+ elif opt == '-m':
+ config["display_config"] = MEDIUM_QUALITY_DISPLAY_CONFIG
elif opt == '-p':
config["display_config"] = LOW_QUALITY_DISPLAY_CONFIG
config["preview"] = True
@@ -90,17 +96,6 @@ def handle_scene(scene, **config):
sys.stdout.close()
sys.stdout = curr_stdout
-def prompt_user_for_args(SceneClass):
- num_to_args = {}
- for count, args in zip(it.count(1), SceneClass.args_list):
- print "%d: %s"%(count, SceneClass.args_to_string(*args))
- num_to_args[count] = args
- try:
- return num_to_args[input(CHOOSE_NUMBER_MESSAGE)]
- except:
- print INVALID_NUMBER_MESSAGE
- sys.exit()
-
def is_scene(obj):
if not inspect.isclass(obj):
return False
@@ -110,6 +105,47 @@ def is_scene(obj):
return False
return True
+def prompt_user_for_args(args_list, args_to_string):
+ num_to_args = {}
+ for count, args in zip(it.count(1), args_list):
+ print "%d: %s"%(count, args_to_string(*args))
+ num_to_args[count] = args
+ try:
+ choice = raw_input(CHOOSE_NUMBER_MESSAGE)
+ return [
+ num_to_args[int(num_str)]
+ for num_str in choice.split(",")
+ ]
+ except:
+ print INVALID_NUMBER_MESSAGE
+ sys.exit()
+
+def get_args(SceneClass, config):
+ tuplify = lambda x : x if type(x) == tuple else (x,)
+ args_list = map(tuplify, SceneClass.args_list)
+ preset_extensions = [
+ SceneClass.args_to_string(*args)
+ for args in args_list
+ ]
+ if len(args_list) > 0:
+ num_args = len(args_list[0])
+ else:
+ num_args = len(inspect.getargspec(SceneClass.construct).args) - 1
+
+ if num_args == 0:
+ return [()]
+ elif config["write_all"]:
+ return args_list
+ elif config["args_extension"] in preset_extensions:
+ index = preset_extensions.index(config["args_extension"])
+ return [args_list[index]]
+ elif len(args_list) == 1:
+ return [args_list[0]]
+ elif config["args_extension"] == "" :
+ return prompt_user_for_args(args_list, SceneClass.args_to_string)
+ else:
+ return [SceneClass.string_to_args(config["args_extension"])]
+
def command_line_create_scene(movie_prefix = ""):
script = sys.modules["__main__"]
scene_names_to_classes = dict(inspect.getmembers(script, is_scene))
@@ -128,23 +164,7 @@ def command_line_create_scene(movie_prefix = ""):
"announce_construction" : True
}
for SceneClass in scene_classes:
- args_list = SceneClass.args_list
- preset_extensions = [
- SceneClass.args_to_string(*args)
- for args in args_list
- ]
- if config["write_all"]:
- args_to_run = args_list or [()]
- elif config["args_extension"] in preset_extensions:
- index = preset_extensions.index(config["args_extension"])
- args_to_run = [args_list[index]]
- elif config["args_extension"] == "":
- args_to_run = [prompt_user_for_args(SceneClass)]
- else:
- args_to_run = [SceneClass.string_to_args(config["args_extension"])]
- for args in args_to_run:
- if type(args) is not tuple:
- args = (args,)
+ for args in get_args(SceneClass, config):
scene_kwargs["construct_args"] = args
try:
handle_scene(SceneClass(**scene_kwargs), **config)
diff --git a/scripts/complex_actions.py b/scripts/complex_actions.py
index e2222f536..0cf143bc5 100644
--- a/scripts/complex_actions.py
+++ b/scripts/complex_actions.py
@@ -15,58 +15,105 @@ from script_wrapper import command_line_create_scene
MOVIE_PREFIX = "complex_actions/"
+DEFAULT_PLANE_CONFIG = {
+ "point_thickness" : 2*DEFAULT_POINT_THICKNESS
+}
+
+def complex_string(complex_num):
+ return filter(lambda c : c not in "()", str(complex_num))
+
class ComplexMultiplication(Scene):
+ args_list = [
+ complex(np.sqrt(3), 1),
+ complex(1,-1)/3,
+ complex(-2, 0),
+ (complex(np.sqrt(3), 1), True),
+ (complex(1,-1)/3, True),
+ (complex(-2, 0), True),
+ ]
@staticmethod
- def args_to_string(multiplier):
- return filter(lambda c : c not in "()", str(multiplier))
+ def args_to_string(multiplier, mark_one = False):
+ num_str = complex_string(multiplier)
+ arrow_str = "MarkOne" if mark_one else ""
+ return num_str + arrow_str
@staticmethod
- def string_to_args(num_string):
- return complex(num_string)
+ def string_to_args(arg_string):
+ parts = arg_string.split()
+ multiplier = complex(parts[0])
+ mark_one = len(parts) > 1 and parts[1] == "MarkOne"
+ return (multiplier, mark_one)
- def construct(self, multiplier):
+ def construct(self, multiplier, mark_one = False, **plane_config):
norm = np.linalg.norm(multiplier)
arg = np.log(multiplier).imag
- plane_config = {
- "faded_line_frequency" : 0
- }
- if norm > 1:
+ plane_config["faded_line_frequency"] = 0
+ plane_config.update(DEFAULT_PLANE_CONFIG)
+ if norm > 1 and "density" not in plane_config:
plane_config["density"] = norm*DEFAULT_POINT_DENSITY_1D
- radius = SPACE_WIDTH
- if norm > 0 and norm < 1:
- radius /= norm
- plane_config["x_radius"] = plane_config["y_radius"] = radius
+ if "radius" not in plane_config:
+ radius = SPACE_WIDTH
+ if norm > 0 and norm < 1:
+ radius /= norm
+ else:
+ radius = plane_config["radius"]
+ plane_config["x_radius"] = plane_config["y_radius"] = radius
plane = ComplexPlane(**plane_config)
+ self.plane = plane
+ self.add(plane)
+ # plane.add_spider_web()
self.anim_config = {
"run_time" : 2.0,
- "interpolation_function" : get_best_interpolation_function(arg)
+ "interpolation_function" : path_along_arc(arg)
}
- background = ComplexPlane(color = "grey")
+ plane_config["faded_line_frequency"] = 0.5
+ background = ComplexPlane(color = "grey", **plane_config)
+ # background.add_spider_web()
labels = background.get_coordinate_labels()
self.paint_into_background(background, *labels)
- arrow, new_arrow = [
- plane.get_vector(plane.number_to_point(z), color = "skyblue")
- for z in [1, multiplier]
- ]
- self.add(arrow)
- self.additional_animations = [Transform(
- arrow, new_arrow, **self.anim_config
- )]
+ self.mobjects_to_move_without_molding = []
+ if mark_one:
+ self.draw_dot("1", 1, True)
+ self.draw_dot("z", multiplier)
+
self.mobjects_to_multiply = [plane]
- self.mobjects_to_move_without_molding = []
+
+ self.additional_animations = []
self.multiplier = multiplier
- self.plane = plane
if self.__class__ == ComplexMultiplication:
self.apply_multiplication()
+ def draw_dot(self, tex_string, value, move_dot = False):
+ dot = Dot(
+ self.plane.number_to_point(value),
+ radius = 0.1*self.plane.unit_to_spatial_width,
+ color = BLUE if value == 1 else YELLOW
+ )
+ label = tex_mobject(tex_string)
+ label.shift(dot.get_center()+1.5*UP+RIGHT)
+ arrow = Arrow(label, dot)
+ self.add(label)
+ self.play(ShowCreation(arrow))
+ self.play(ShowCreation(dot))
+ self.dither()
+
+ self.remove(label, arrow)
+ if move_dot:
+ self.mobjects_to_move_without_molding.append(dot)
+ return dot
+
+
def apply_multiplication(self):
def func((x, y, z)):
complex_num = self.multiplier*complex(x, y)
return (complex_num.real, complex_num.imag, z)
- mobjects = self.mobjects_to_multiply+self.mobjects_to_move_without_molding
- mobjects += [anim.mobject for anim in self.additional_animations]
+ mobjects = self.mobjects_to_multiply
+ mobjects += self.mobjects_to_move_without_molding
+ mobjects += [anim.mobject for anim in self.additional_animations]
+
+
self.add(*mobjects)
full_multiplications = [
ApplyMethod(mobject.apply_function, func, **self.anim_config)
@@ -88,31 +135,65 @@ class ComplexMultiplication(Scene):
]))
self.dither()
-class MultiplicationWithDot(ComplexMultiplication):
+
+class SuccessiveComplexMultiplications(ComplexMultiplication):
+ args_list = [
+ (complex(1, 2), complex(1, -2)),
+ (complex(-2, 1), complex(-2, -1)),
+ ]
+
@staticmethod
- def args_to_string(multiplier, dot_coords):
- start = ComplexMultiplication.args_to_string(multiplier)
- return start + "WithDotAt%d-%d"%dot_coords[:2]
+ def args_to_string(*multipliers):
+ return "_".join([str(m)[1:-1] for m in multipliers])
@staticmethod
def string_to_args(arg_string):
- parts = arg_string.split()
- if len(parts) < 2 or len(parts) > 3:
- raise Exception("Invalid arguments")
- multiplier = complex(parts[0])
- tup_string = filter(lambda c : c not in "()", parts[1])
- nums = tuple(map(int, tup_string.split(",")))[:2]
- return multiplier, nums
-
- def construct(self, multiplier, dot_coords):
- ComplexMultiplication.construct(self, multiplier)
- self.mobjects_to_move_without_molding.append(
- Dot().shift(dot_coords)
- )
- self.apply_multiplication()
+ args_string.replac("i", "j")
+ return map(copmlex, arg_string.split())
+
+ def construct(self, *multipliers):
+ norm = abs(reduce(op.mul, multipliers, 1))
+ shrink_factor = SPACE_WIDTH/max(SPACE_WIDTH, norm)
+ plane_config = {
+ "density" : norm*DEFAULT_POINT_DENSITY_1D,
+ "unit_to_spatial_width" : shrink_factor,
+ "x_radius" : shrink_factor*SPACE_WIDTH,
+ "y_radius" : shrink_factor*SPACE_HEIGHT,
+ }
+ ComplexMultiplication.construct(self, multipliers[0], **plane_config)
+
+ one_dot = self.draw_dot("1", 1, True)
+ one_dot_copy = deepcopy(one_dot)
+
+ for multiplier, count in zip(multipliers, it.count()):
+ if multiplier == multipliers[0]:
+ tex = "z"
+ elif np.conj(multiplier) == multipliers[0]:
+ tex = "\\bar z"
+ else:
+ tex = "z_%d"%count
+ self.draw_dot(tex, multiplier)
+
+ for multiplier in multipliers:
+ self.multiplier = multiplier
+ self.apply_multiplication()
+ new_one = deepcopy(one_dot_copy)
+ self.mobjects_to_move_without_molding.append(new_one)
+
-class ShowComplexPower(ComplexMultiplication):
+class ShowComplexPower(SuccessiveComplexMultiplications):
+ args_list = [
+ (complex(0, 1), 1),
+ (complex(0, 1), 2),
+ (np.exp(complex(0, 2*np.pi/5)), 1),
+ (np.exp(complex(0, 2*np.pi/5)), 5),
+ (np.exp(complex(0, 4*np.pi/5)), 5),
+ (np.exp(complex(0, -2*np.pi/5)), 5),
+ (complex(1, np.sqrt(3)), 1),
+ (complex(1, np.sqrt(3)), 3),
+ ]
+
@staticmethod
def args_to_string(multiplier, num_repeats):
start = ComplexMultiplication.args_to_string(multiplier)
@@ -128,19 +209,75 @@ class ShowComplexPower(ComplexMultiplication):
return multiplier, num_repeats
def construct(self, multiplier, num_repeats):
- ComplexMultiplication.construct(self, multiplier)
- for x in range(num_repeats):
- arrow_transform = Transform(*[
- self.plane.get_vector(point, color = "skyblue")
- for z in [multiplier**(x), multiplier**(x+1)]
- for point in [self.plane.number_to_point(z)]
- ], **self.anim_config)
- self.remove(*[anim.mobject for anim in self.additional_animations])
- self.additional_animations = [arrow_transform]
- self.apply_multiplication()
+ SuccessiveComplexMultiplications.construct(
+ [multiplier]*num_repeats
+ )
+
+
+class ComplexDivision(ComplexMultiplication):
+ args_list = [
+ complex(np.sqrt(3), 1),
+ complex(1./3, -1./3),
+ complex(1, 2),
+ ]
+
+ def construct(self, num):
+ ComplexMultiplication.construct(self, 1./num)
+ self.draw_dot("1", 1, False),
+ self.draw_dot("z", num, True)
+ self.apply_multiplication()
+
+class ConjugateDivisionExample(ComplexMultiplication):
+ args_list = [
+ complex(1, 2),
+ ]
+
+ def construct(self, num):
+ ComplexMultiplication.construct(self, np.conj(num), radius = 2.5*SPACE_WIDTH)
+ self.draw_dot("1", 1, True)
+ self.draw_dot("\\bar z", self.multiplier)
+ self.apply_multiplication()
+ self.multiplier = 1./(abs(num)**2)
+ self.anim_config["interpolation_function"] = straight_path
+ self.apply_multiplication()
+ self.dither()
+class DrawSolutionsToZToTheNEqualsW(Scene):
+ @staticmethod
+ def args_to_string(n, w):
+ return str(n) + "_" + complex_string(w)
+ @staticmethod
+ def string_to_args(args_string):
+ parts = args_string.split()
+ return int(parts[0]), complex(parts[1])
+
+ def construct(self, n, w):
+ w = complex(w)
+ plane_config = DEFAULT_PLANE_CONFIG.copy()
+ norm = abs(w)
+ theta = np.log(w).imag
+ radius = norm**(1./n)
+ zoom_value = (SPACE_HEIGHT-0.5)/radius
+ plane_config["unit_to_spatial_width"] = zoom_value
+ plane = ComplexPlane(**plane_config)
+ circle = Circle(
+ radius = radius*zoom_value,
+ point_thickness = plane.point_thickness
+ )
+ solutions = [
+ radius*np.exp(complex(0, 1)*(2*np.pi*k + theta)/n)
+ for k in range(n)
+ ]
+ points = map(plane.number_to_point, solutions)
+ dots = [
+ Dot(point, color = BLUE_B, radius = 0.1)
+ for point in points
+ ]
+ lines = [Line(*pair) for pair in adjascent_pairs(points)]
+ self.add(plane, circle, *dots+lines)
+ self.add(*plane.get_coordinate_labels())
@@ -150,6 +287,104 @@ class ShowComplexPower(ComplexMultiplication):
+class DrawComplexAngleAndMagnitude(Scene):
+ args_list = [
+ (
+ ("1+i\\sqrt{3}", complex(1, np.sqrt(3)) ),
+ ("\\frac{\\sqrt{3}}{2} - \\frac{1}{2}i", complex(np.sqrt(3)/2, -1./2)),
+ ),
+ (("1+i", complex(1, 1)),),
+ ]
+ @staticmethod
+ def args_to_string(*reps_and_nums):
+ return "--".join([
+ complex_string(num)
+ for rep, num in reps_and_nums
+ ])
+
+ def construct(self, *reps_and_nums):
+ radius = max([abs(n.imag) for r, n in reps_and_nums]) + 1
+ plane_config = {
+ "color" : "grey",
+ "unit_to_spatial_width" : SPACE_HEIGHT / radius,
+ }
+ plane_config.update(DEFAULT_PLANE_CONFIG)
+ self.plane = ComplexPlane(**plane_config)
+ coordinates = self.plane.get_coordinate_labels()
+ # self.plane.add_spider_web()
+ self.add(self.plane, *coordinates)
+ for rep, num in reps_and_nums:
+ self.draw_number(rep, num)
+ self.add_angle_label(num)
+ self.add_lines(rep, num)
+
+ def draw_number(self, tex_representation, number):
+ point = self.plane.number_to_point(number)
+ dot = Dot(point)
+ label = tex_mobject(tex_representation)
+ max_width = 0.8*self.plane.unit_to_spatial_width
+ if label.get_width() > max_width:
+ label.scale_to_fit_width(max_width)
+ dot_to_label_dir = RIGHT if point[0] > 0 else LEFT
+ edge = label.get_edge_center(-dot_to_label_dir)
+ buff = 0.1
+ label.shift(point - edge + buff*dot_to_label_dir)
+ label.highlight(YELLOW)
+
+ self.add_local_mobjects()
+
+
+ def add_angle_label(self, number):
+ arc = PartialCircle(
+ np.log(number).imag,
+ radius = 0.2
+ )
+
+ self.add_local_mobjects()
+
+ def add_lines(self, tex_representation, number):
+ point = self.plane.number_to_point(number)
+ x_line, y_line, num_line = [
+ Line(
+ start, end,
+ color = color,
+ point_thickness = self.plane.point_thickness
+ )
+ for start, end, color in zip(
+ [ORIGIN, point[0]*RIGHT, ORIGIN],
+ [point[0]*RIGHT, point, point],
+ [BLUE_D, GOLD_E, WHITE]
+ )
+ ]
+ # tex_representation.replace("i", "")
+ # if "+" in tex_representation:
+ # tex_parts = tex_representation.split("+")
+ # elif "-" in tex_representation:
+ # tex_parts = tex_representation.split("-")
+ # x_label, y_label = map(tex_mobject, tex_parts)
+ # for label in x_label, y_label:
+ # label.scale_to_fit_height(0.5)
+ # x_label.next_to(x_line, point[1]*DOWN/abs(point[1]))
+ # y_label.next_to(y_line, point[0]*RIGHT/abs(point[0]))
+ norm = np.linalg.norm(point)
+ brace = underbrace(ORIGIN, ORIGIN+norm*RIGHT)
+ if point[1] > 0:
+ brace.rotate(np.pi, RIGHT)
+ brace.rotate(np.log(number).imag)
+ norm_label = tex_mobject("%.1f"%abs(number))
+ norm_label.scale(0.5)
+ axis = OUT if point[1] > 0 else IN
+ norm_label.next_to(brace, rotate_vector(point, np.pi/2, axis))
+
+ self.add_local_mobjects()
+
+
+
+
+
+
+
+
diff --git a/scripts/inventing_math.py b/scripts/inventing_math.py
index 5ac3d5803..ebf292e50 100644
--- a/scripts/inventing_math.py
+++ b/scripts/inventing_math.py
@@ -1135,7 +1135,7 @@ class GeometricSum(RearrangeEquation):
self,
start_terms.split(" "), end_terms.split(" "),
index_map, size = "\\large",
- path = counterclockwise_path,
+ path = counterclockwise_path(),
start_transform = start_transform,
end_transform = end_transform,
leave_start_terms = True,
diff --git a/scripts/matrix_as_transform_2d.py b/scripts/matrix_as_transform_2d.py
index bb78e7d3b..dac837131 100644
--- a/scripts/matrix_as_transform_2d.py
+++ b/scripts/matrix_as_transform_2d.py
@@ -16,7 +16,7 @@ from script_wrapper import command_line_create_scene
MOVIE_PREFIX = "matrix_as_transform_2d/"
ARROW_CONFIG = {"point_thickness" : 2*DEFAULT_POINT_THICKNESS}
-LIGHT_RED = "#F40"
+LIGHT_RED = RED_E
def matrix_to_string(matrix):
return "--".join(["-".join(map(str, row)) for row in matrix])
@@ -36,9 +36,9 @@ def matrix_mobject(matrix):
class ShowMultiplication(NumberLineScene):
args_list = [
- (2, False),
- (0.5, False),
- (-3, False),
+ (2, True),
+ (0.5, True),
+ (-3, True),
(-3, True),
(2, True),
(6, True),
@@ -59,7 +59,7 @@ class ShowMultiplication(NumberLineScene):
def construct(self, num, show_original_line):
config = {
- "density" : abs(num)*DEFAULT_POINT_DENSITY_1D,
+ "density" : max(abs(num), 1)*DEFAULT_POINT_DENSITY_1D,
"point_thickness" : 2*DEFAULT_POINT_THICKNESS
}
if abs(num) < 1:
@@ -94,8 +94,9 @@ class ExamplesOfOneDimensionalLinearTransforms(ShowMultiplication):
def construct(self):
for num in [2, 0.5, -3]:
+ self.clear()
ShowMultiplication.construct(self, num, False)
- self.clear()
+
class ExamplesOfNonlinearOneDimensionalTransforms(NumberLineScene):
@@ -111,14 +112,17 @@ class ExamplesOfNonlinearOneDimensionalTransforms(NumberLineScene):
(shift_zero, "zero does not remain fixed")
]
for func, explanation in pairs:
- self.dither()
self.run_function(func, explanation)
- self.dither()
+ self.dither(3)
def run_function(self, function, explanation):
self.clear()
self.add(self.nonlinear)
- NumberLineScene.construct(self)
+ config = {
+ "point_thickness" : 2*DEFAULT_POINT_THICKNESS,
+ "density" : 5*DEFAULT_POINT_DENSITY_1D,
+ }
+ NumberLineScene.construct(self, **config)
words = text_mobject(explanation).highlight(LIGHT_RED)
words.next_to(self.nonlinear, DOWN, buff = 0.5)
self.add(words)
@@ -143,7 +147,11 @@ class ShowTwoThenThree(ShowMultiplication):
return ""
def construct(self):
- NumberLineScene.construct(self, density = 10*DEFAULT_POINT_DENSITY_1D)
+ config = {
+ "point_thickness" : 2*DEFAULT_POINT_THICKNESS,
+ "density" : 6*DEFAULT_POINT_DENSITY_1D,
+ }
+ NumberLineScene.construct(self, **config)
self.copy_original_line()
self.show_multiplication(2)
self.dither()
@@ -157,7 +165,7 @@ class TransformScene2D(Scene):
def add_number_plane(self, density_factor = 1, use_faded_lines = True):
config = {
"x_radius" : 2*SPACE_WIDTH,
- "y_radius" : 2*SPACE_HEIGHT,
+ "y_radius" : 2*SPACE_WIDTH,
"density" : DEFAULT_POINT_DENSITY_1D*density_factor,
"point_thickness" : 2*DEFAULT_POINT_THICKNESS
}
@@ -205,6 +213,7 @@ class ShowMatrixTransform(TransformScene2D):
([[-1, 0], [0, -1]], True, False),
([[0, 1], [1, 0]], True, False),
([[-2, 0], [-1, -1]], True, False),
+ ([[0, -1], [1, 0]], True, False),
]
@staticmethod
def args_to_string(matrix, with_background, show_matrix):
@@ -261,20 +270,12 @@ class ShowMatrixTransform(TransformScene2D):
return max(max_norm, 1)
def get_interpolation_function(self, matrix):
- def toggled_sign(n, i):
- return int(i%2 == 0)^int(n >= 0)
- rotational_components = [
- sign*np.arccos(matrix[i,i]/np.linalg.norm(matrix[:,i]))
- for i in [0, 1]
- for sign in [toggled_sign(matrix[1-i, i], i)]
- ]
- average_rotation = sum(rotational_components)/2
- if abs(average_rotation) < np.pi / 2:
- return straight_path
- elif average_rotation > 0:
- return counterclockwise_path
- else:
- return clockwise_path
+ rotational_components = np.array([
+ np.log(multiplier*complex(*matrix[:,i])).imag
+ for i, multiplier in [(0, 1), (1, complex(0, -1))]
+ ])
+ rotational_components[rotational_components == -np.pi] = np.pi
+ return path_along_arc(np.mean(rotational_components))
class ExamplesOfTwoDimensionalLinearTransformations(ShowMatrixTransform):
@@ -305,27 +306,33 @@ class ExamplesOfNonlinearTwoDimensionalTransformations(Scene):
def shift_zero((x, y, z)):
return (2*x + 3*y + 4, -1*x+y+2, z)
self.nonlinear = text_mobject("Nonlinear Transform")
- self.nonlinear.highlight(LIGHT_RED).to_edge(UP, buff = 1.5)
+ self.nonlinear.highlight(LIGHT_RED)
+ self.nonlinear.to_edge(UP, buff = 1.5)
pairs = [
- (squiggle, "lines to not remain straight"),
+ (squiggle, "lines do not remain straight"),
(shift_zero, "the origin does not remain fixed")
]
+ self.get_blackness()
for function, explanation in pairs:
self.apply_function(function, explanation)
def apply_function(self, function, explanation):
self.clear()
- number_plane = NumberPlane(
- x_radius = 1.5*SPACE_WIDTH,
- y_radius = 1.5*SPACE_HEIGHT,
- density = 3*DEFAULT_POINT_DENSITY_1D,
- )
+ config = {
+ "x_radius" : 2*SPACE_WIDTH,
+ "y_radius" : 2*SPACE_WIDTH,
+ "density" : 3*DEFAULT_POINT_DENSITY_1D,
+ "point_thickness" : 2*DEFAULT_POINT_THICKNESS
+ }
+ number_plane = NumberPlane(**config)
numbers = number_plane.get_coordinate_labels()
- words = text_mobject(explanation).highlight(LIGHT_RED)
+ words = text_mobject(explanation)
+ words.highlight(LIGHT_RED)
words.next_to(self.nonlinear, DOWN, buff = 0.5)
- self.add(number_plane, self.nonlinear, words, *numbers)
+ self.add(number_plane, *numbers)
+ self.add(self.blackness, self.nonlinear, words)
self.dither()
self.play(
ApplyPointwiseFunction(function, number_plane),
@@ -335,15 +342,44 @@ class ExamplesOfNonlinearTwoDimensionalTransformations(Scene):
function(mob.get_center())-mob.get_center()
)
for mob in numbers
+ ] + [
+ Animation(self.blackness),
+ Animation(words),
+ Animation(self.nonlinear)
],
run_time = 2.0
)
- self.dither(2)
+ self.dither(3)
+
+ def get_blackness(self):
+ vertices = [
+ 3.5*LEFT+1.05*UP,
+ 3.5*RIGHT+1.05*UP,
+ 3.5*RIGHT+2.75*UP,
+ 3.5*LEFT+2.75*UP,
+ ]
+
+ region = region_from_polygon_vertices(*vertices)
+ image = disp.paint_region(region, color = WHITE)
+ self.blackness = text_mobject("")
+ ImageMobject.generate_points_from_image_array(self.blackness, image)
+ self.blackness.highlight(BLACK)
+ rectangle = Rectangle(width = 7, height=1.7)
+ rectangle.highlight(WHITE)
+ rectangle.shift(self.blackness.get_center())
+ self.blackness.add(rectangle)
+ self.blackness.scale_in_place(0.95)
class TrickyExamplesOfNonlinearTwoDimensionalTransformations(Scene):
def construct(self):
- number_plane = NumberPlane()
+ config = {
+ "x_radius" : 1.2*SPACE_WIDTH,
+ "y_radius" : 1.2*SPACE_WIDTH,
+ "density" : 10*DEFAULT_POINT_DENSITY_1D,
+ "point_thickness" : 2*DEFAULT_POINT_THICKNESS
+ }
+ number_plane = NumberPlane(**config)
phrase1, phrase2 = text_mobject([
"These might look like they keep lines straight...",
"but diagonal lines get curved"
@@ -351,7 +387,8 @@ class TrickyExamplesOfNonlinearTwoDimensionalTransformations(Scene):
phrase2.highlight(LIGHT_RED)
diagonal = Line(
DOWN*SPACE_HEIGHT+LEFT*SPACE_WIDTH,
- UP*SPACE_HEIGHT+RIGHT*SPACE_WIDTH
+ UP*SPACE_HEIGHT+RIGHT*SPACE_WIDTH,
+ density = 10*DEFAULT_POINT_DENSITY_1D
)
def sunrise((x, y, z)):
return ((SPACE_HEIGHT+y)*x, y, z)
@@ -359,24 +396,50 @@ class TrickyExamplesOfNonlinearTwoDimensionalTransformations(Scene):
def squished((x, y, z)):
return (x + np.sin(x), y+np.sin(y), z)
+ self.get_blackness()
+
+ self.run_function(sunrise, number_plane, phrase1)
+ self.run_function(squished, number_plane, phrase1)
+ phrase1.add(phrase2)
self.add(phrase1)
- self.run_function(sunrise, number_plane)
- self.run_function(squished, number_plane)
- self.add(phrase2)
self.play(ShowCreation(diagonal))
self.remove(diagonal)
number_plane.add(diagonal)
- self.run_function(sunrise, number_plane)
- self.run_function(squished, number_plane)
+ self.run_function(sunrise, number_plane, phrase1)
+ self.run_function(squished, number_plane, phrase1, False)
- def run_function(self, function, plane):
+ def run_function(self, function, plane, phrase, remove_plane = True):
number_plane = deepcopy(plane)
- self.add(number_plane)
+ self.add(number_plane, self.blackness, phrase)
self.dither()
- self.play(ApplyPointwiseFunction(function, number_plane, run_time = 2.0))
+ self.play(
+ ApplyPointwiseFunction(function, number_plane, run_time = 2.0),
+ Animation(self.blackness),
+ Animation(phrase),
+ )
self.dither(3)
- self.remove(number_plane)
+ if remove_plane:
+ self.remove(number_plane)
+
+ def get_blackness(self):
+ vertices = [
+ 4.5*LEFT+1.25*UP,
+ 4.5*RIGHT+1.25*UP,
+ 4.5*RIGHT+2.75*UP,
+ 4.5*LEFT+2.75*UP,
+ ]
+
+ region = region_from_polygon_vertices(*vertices)
+ image = disp.paint_region(region, color = WHITE)
+ self.blackness = text_mobject("")
+ ImageMobject.generate_points_from_image_array(self.blackness, image)
+ self.blackness.highlight(BLACK)
+ rectangle = Rectangle(width = 9, height=1.5)
+ rectangle.highlight(WHITE)
+ rectangle.shift(self.blackness.get_center())
+ self.blackness.add(rectangle)
+ self.blackness.scale_in_place(0.95)
############# HORRIBLE! ##########################
@@ -393,7 +456,7 @@ class ShowMatrixTransformWithDot(TransformScene2D):
def construct(self, matrix, with_background, show_matrix):
matrix = np.array(matrix)
number_plane_config = {
- "density_factor" : self.get_density_factor(matrix)
+ "density_factor" : self.get_density_factor(matrix),
}
if with_background:
self.add_background()
@@ -408,10 +471,10 @@ class ShowMatrixTransformWithDot(TransformScene2D):
mobject.points[:, :2] = np.dot(mobject.points[:, :2], np.transpose(matrix))
return mobject
dot = Dot((-1, 2, 0), color = "yellow")
+ self.add(dot)
x_arrow_copy = deepcopy(self.x_arrow)
y_arrow_copy = Arrow(LEFT, LEFT+2*UP, color = LIGHT_RED, **ARROW_CONFIG)
- self.number_plane.add(dot)
self.play(ApplyMethod(x_arrow_copy.rotate, np.pi))
self.play(ShowCreation(y_arrow_copy))
self.dither()
@@ -420,7 +483,10 @@ class ShowMatrixTransformWithDot(TransformScene2D):
"run_time" : 2.0,
"interpolation_function" : self.get_interpolation_function(matrix)
}
- anims = [ApplyFunction(func, self.number_plane, **kwargs)]
+ anims = [
+ ApplyFunction(func, self.number_plane, **kwargs),
+ ApplyMethod(dot.shift, func(deepcopy(dot)).get_center()-dot.get_center(), **kwargs),
+ ]
if hasattr(self, "x_arrow") and hasattr(self, "y_arrow"):
for arrow, index in (self.x_arrow, 0), (self.y_arrow, 1):
new_arrow = Arrow(
@@ -442,8 +508,8 @@ class ShowMatrixTransformWithDot(TransformScene2D):
y_arrow_copy = Arrow(LEFT+2*UP, 5*RIGHT+2*UP, color = LIGHT_RED, **ARROW_CONFIG)
self.play(ApplyMethod(x_arrow_copy.rotate, np.pi))
self.play(ShowCreation(y_arrow_copy))
- self.remove(x_arrow_copy, y_arrow_copy)
self.dither(3)
+ self.remove(x_arrow_copy, y_arrow_copy)
def get_density_factor(self, matrix):
max_norm = max([
@@ -462,9 +528,9 @@ class ShowMatrixTransformWithDot(TransformScene2D):
if abs(average_rotation) < np.pi / 2:
return straight_path
elif average_rotation > 0:
- return counterclockwise_path
+ return counterclockwise_path()
else:
- return clockwise_path
+ return clockwise_path()
class Show90DegreeRotation(TransformScene2D):
diff --git a/scripts/old_scripts/inventing_math.py b/scripts/old_scripts/inventing_math.py
index edf945ca1..323049406 100644
--- a/scripts/old_scripts/inventing_math.py
+++ b/scripts/old_scripts/inventing_math.py
@@ -1141,7 +1141,7 @@ class GeometricSum(RearrangeEquation):
self,
start_terms.split(" "), end_terms.split(" "),
index_map, size = "\\large",
- path = counterclockwise_path,
+ path = counterclockwise_path(),
start_transform = start_transform,
end_transform = end_transform,
leave_start_terms = True,
diff --git a/scripts/pythagorean_proof.py b/scripts/pythagorean_proof.py
index bca5fdf12..bbce4cfbd 100644
--- a/scripts/pythagorean_proof.py
+++ b/scripts/pythagorean_proof.py
@@ -15,9 +15,10 @@ from script_wrapper import command_line_create_scene
MOVIE_PREFIX = "pythagorean_proof"
-A_COLOR = "skyblue"
-B_COLOR = "pink"
-C_COLOR = "yellow"
+A_COLOR = BLUE
+B_COLOR = MAROON_D
+C_COLOR = YELLOW
+
TEX_MOB_SCALE_VAL = 0.5
POINTS = np.array([
DOWN,
@@ -43,7 +44,7 @@ class Triangle(Polygon):
nudge = 0.2
target = POINTS[0]+nudge*(UP+RIGHT)
for direction in UP, RIGHT:
- self.add_line(POINTS[0]+nudge*direction, target, color = "white")
+ self.add_line(POINTS[0]+nudge*direction, target, color = WHITE)
def add_all_letters(self):
@@ -51,7 +52,7 @@ class Triangle(Polygon):
self.add_letter(char)
return self
- def add_letter(self, char, nudge = 0.2):
+ def add_letter(self, char, nudge = 0.3):
mob = tex_mobject(char).scale(TEX_MOB_SCALE_VAL)
if char == "a":
points = self.get_vertices()[[0, 2, 1]]
@@ -61,7 +62,9 @@ class Triangle(Polygon):
points = self.get_vertices()[[2, 1, 0]]
center = 0.5*sum(points[:2]) #average of first two points
mob.shift(center)
- normal_dir = center-points[2]
+ normal_dir = rotate_vector(points[1] - points[0], np.pi/2, OUT)
+ if np.dot(normal_dir, points[2]-center) > 0:
+ normal_dir = -normal_dir
normal_dir /= np.linalg.norm(normal_dir)
mob.shift(nudge*normal_dir)
self.add(mob)
@@ -131,9 +134,9 @@ class AddParallelLines(DrawAllThreeSquares):
(3*LEFT, 2*DOWN)
]
for side_shift, vert_shift in shift_pairs[:num]:
- line1 = Line(BOTTOM, TOP, color = "white")
+ line1 = Line(BOTTOM, TOP, color = WHITE)
line1.shift(side_shift)
- line2 = Line(LEFT_SIDE, RIGHT_SIDE, color = "white")
+ line2 = Line(LEFT_SIDE, RIGHT_SIDE, color = WHITE)
line2.shift(vert_shift)
self.add(line1, line2)
if trim:
@@ -156,7 +159,7 @@ class HighlightEmergentTriangles(AddParallelLines):
for triplet in triplets:
self.highlight_region(
region_from_polygon_vertices(*triplet),
- color = "green"
+ color = "DARK_BLUE"
)
class IndicateTroublePointFromParallelLines(AddParallelLines):
@@ -216,14 +219,14 @@ class DrawAllThreeSquaresWithMoreTriangles(DrawAllThreeSquares):
if fill:
self.highlight_region(
region_from_polygon_vertices(*vertices),
- color = "green"
+ color = DARK_BLUE
)
class IndicateBigRectangleTroublePoint(DrawAllThreeSquaresWithMoreTriangles):
args_list = [(10, False)]
def construct(self, *args):
DrawAllThreeSquaresWithMoreTriangles.construct(self, *args)
- circle = Circle(radius = 0.25, color = "white")
+ circle = Circle(radius = 0.25, color = WHITE)
circle.shift(4*RIGHT)
vect = DOWN+RIGHT
arrow = Arrow(circle.get_center()+vect, circle.get_boundary_point(vect))
@@ -288,7 +291,7 @@ class AddTriangleCopyToABSquares(DrawOnlyABSquares):
for x in range(2):
self.highlight_region(region_from_polygon_vertices(
*vertices
- ), color = "green")
+ ), color = DARK_BLUE)
vertices.reverse()#silly hack
class AddAllTrianglesToABSquares(AddTriangleCopyToABSquares):
@@ -351,12 +354,12 @@ class HighlightCSquareInBigSquare(DrawCSquareWithAllTraingles):
DrawCSquareWithAllTraingles.construct(self, *args)
self.highlight_region(region_from_polygon_vertices(
*c_square().center().get_vertices()
- ), color = "yellow")
+ ), color = YELLOW)
class IndicateCSquareTroublePoint(DrawCSquareWithAllTraingles):
def construct(self, *toggle_vector):
DrawCSquareWithAllTraingles.construct(self, *toggle_vector)
- circle = Circle(color = "white")
+ circle = Circle(color = WHITE)
circle.scale(0.25)
vertex = self.c_square.get_vertices()[1]
circle.shift(vertex)
@@ -385,9 +388,9 @@ class ZoomInOnTroublePoint(Scene):
triangle = Triangle(density = density)
triangle.place_hypotenuse_on(vertices[index], vertices[index+1])
self.add(triangle)
- circle = Circle(radius = 2.5, color = "white")
- angle1_arc = Circle(color = "white")
- angle2_arc = Circle(color = "white").scale(0.5)
+ circle = Circle(radius = 2.5, color = WHITE)
+ angle1_arc = Circle(color = WHITE)
+ angle2_arc = Circle(color = WHITE).scale(0.5)
angle1_arc.filter_out(lambda (x, y, z) : not (x > 0 and y > 0 and y < x/3))
angle2_arc.filter_out(lambda (x, y, z) : not (x < 0 and y > 0 and y < -3*x))
@@ -414,8 +417,8 @@ class ZoomInOnTroublePoint(Scene):
p1 = c*LEFT + 3*c*UP
p2 = 3*c*RIGHT + c*UP
p3 = 2*c*RIGHT + 4*c*UP
- self.add(Line(p1, p3, color = "white"))
- self.add(Line(p2, p3, color = "white"))
+ self.add(Line(p1, p3, color = WHITE))
+ self.add(Line(p2, p3, color = WHITE))
class DrawTriangleWithAngles(Scene):
@@ -423,7 +426,7 @@ class DrawTriangleWithAngles(Scene):
triangle = Triangle(density = 2*DEFAULT_POINT_DENSITY_1D)
triangle.scale(2).center().add_all_letters()
vertices = triangle.get_vertices()
- kwargs = {"color" : "white"}
+ kwargs = {"color" : WHITE}
angle1_arc = Circle(radius = 0.4, **kwargs).filter_out(
lambda (x, y, z) : not(x > 0 and y < 0 and y < -3*x)
).shift(vertices[1])
@@ -460,7 +463,7 @@ class CompletelyFillLargeSquare(LabelLargeSquare):
vertices = [2*(DOWN+LEFT), 2*(DOWN+RIGHT), 2*(UP+RIGHT), 2*(UP+LEFT)]
vertices.append(vertices[0])
pairs = zip(vertices, vertices[1:])
- self.highlight_region(region_from_line_boundary(*pairs), color = "blue")
+ self.highlight_region(region_from_line_boundary(*pairs), color = BLUE)
class FillComponentsOfLargeSquare(LabelLargeSquare):
@@ -481,17 +484,17 @@ class FillComponentsOfLargeSquare(LabelLargeSquare):
self.highlight_region(region_from_line_boundary(*[
[points[i], points[j]]
for i, j in zip(triplet, triplet[1:])
- ]), color = "green")
+ ]), color = DARK_BLUE)
vertices = points[[1, 3, 5, 7, 1]]
self.highlight_region(region_from_line_boundary(*[
[p1, p2]
for p1, p2 in zip(vertices, vertices[1:])
- ]), color = "yellow")
+ ]), color = YELLOW)
class ShowRearrangementInBigSquare(DrawCSquareWithAllTraingles):
args_list = []
def construct(self):
- self.add(Square(side_length = 4, color = "white"))
+ self.add(Square(side_length = 4, color = WHITE))
DrawCSquareWithAllTraingles.construct(self)
self.remove(self.c_square)
self.triangles[1].shift(LEFT)