More vectorizations conversions

This commit is contained in:
Grant Sanderson 2016-04-19 00:20:19 -07:00
parent e4c73306db
commit cb3fff7da5
7 changed files with 171 additions and 283 deletions

View file

@ -32,13 +32,24 @@ class Rotating(Animation):
class ShowPartial(Animation): class ShowPartial(Animation):
CONFIG = {
"one_submobject_at_a_time" : False
}
def update_mobject(self, alpha): def update_mobject(self, alpha):
pairs = zip( pairs = zip(
self.starting_mobject.submobject_family(), self.starting_mobject.submobject_family(),
self.mobject.submobject_family() self.mobject.submobject_family()
) )
for start, mob in pairs: for i, (start, mob) in enumerate(pairs):
mob.become_partial(start, *self.get_bounds(alpha)) if self.one_submobject_at_a_time:
lower = float(i)/len(pairs)
upper = float(i+1)/len(pairs)
sub_alpha = (alpha-lower)/(upper-lower)
sub_alpha = max(0, sub_alpha)
sub_alpha = min(1, sub_alpha)
else:
sub_alpha = alpha
mob.become_partial(start, *self.get_bounds(sub_alpha))
def get_bounds(self, alpha): def get_bounds(self, alpha):
raise Exception("Not Implemented") raise Exception("Not Implemented")
@ -48,6 +59,12 @@ class ShowCreation(ShowPartial):
def get_bounds(self, alpha): def get_bounds(self, alpha):
return (0, alpha) return (0, alpha)
class ShowCreationPerSubmobject(ShowCreation):
CONFIG = {
"one_submobject_at_a_time" : True,
"run_time" : 3
}
class ShowPassingFlash(ShowPartial): class ShowPassingFlash(ShowPartial):
CONFIG = { CONFIG = {
"time_width" : 0.1 "time_width" : 0.1

View file

@ -11,7 +11,6 @@ from scipy import linalg
from constants import * from constants import *
def get_smooth_handle_points(points): def get_smooth_handle_points(points):
num_handles = len(points) - 1 num_handles = len(points) - 1
dim = points.shape[1] dim = points.shape[1]

View file

@ -184,6 +184,7 @@ class VMobjectFromSVGPathstring(VMobject):
if not is_closed(points): if not is_closed(points):
#Both handles and new anchor are the start #Both handles and new anchor are the start
new_points = points[[0, 0, 0]] new_points = points[[0, 0, 0]]
self.mark_paths_closed = True
self.growing_path.add_control_points(new_points) self.growing_path.add_control_points(new_points)
def string_to_points(self, coord_string): def string_to_points(self, coord_string):

View file

@ -11,7 +11,7 @@ class VMobject(Mobject):
#Indicates that it will not be displayed, but #Indicates that it will not be displayed, but
#that it should count in parent mobject's path #that it should count in parent mobject's path
"is_subpath" : False, "is_subpath" : False,
"close_new_points" : True, "close_new_points" : False,
"mark_paths_closed" : False, "mark_paths_closed" : False,
} }
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):

View file

@ -1,56 +1,51 @@
from scipy import integrate from scipy import integrate
from mobject import Mobject, Mobject1D, Mobject from mobject.vectorized_mobject import VMobject
from helpers import * from helpers import *
class FunctionGraph(Mobject1D): class FunctionGraph(VMobject):
CONFIG = { CONFIG = {
"color" : BLUE, "color" : BLUE_D,
"x_min" : -10, "x_min" : -SPACE_WIDTH,
"x_max" : 10, "x_max" : SPACE_WIDTH,
"spatial_radius" : SPACE_WIDTH, "space_unit_to_num" : 1,
"epsilon" : 0.5,
} }
def __init__(self, function, **kwargs): def __init__(self, function, **kwargs):
self.function = function self.function = function
Mobject1D.__init__(self, **kwargs) VMobject.__init__(self, **kwargs)
def generate_points(self): def generate_points(self):
numerical_radius = (self.x_max - self.x_min)/2 self.set_anchor_points([
numerical_center = (self.x_max + self.x_min)/2 x*RIGHT + self.function(x)*UP
ratio = numerical_radius / self.spatial_radius for pre_x in np.arange(self.x_min, self.x_max, self.epsilon)
epsilon = self.epsilon * ratio for x in [self.space_unit_to_num*pre_x]
self.add_points([ ], mode = "smooth")
np.array([(x-numerical_center)/ratio, self.function(x), 0])
for x in np.arange(self.x_min, self.x_max, self.epsilon)
])
class ParametricFunction(Mobject1D): class ParametricFunction(VMobject):
CONFIG = { CONFIG = {
"start" : 0, "t_min" : 0,
"end" : 1, "t_max" : 1,
"epsilon" : 0.1,
} }
def __init__(self, function, **kwargs): def __init__(self, function, **kwargs):
self.function = function self.function = function
Mobject1D.__init__(self, **kwargs) VMobject.__init__(self, **kwargs)
def generate_points(self): def generate_points(self):
integral = integrate.quad( self.set_anchor_points([
lambda t : np.linalg.norm(self.function(t)), self.function(t)
self.start, self.end for t in np.arange(self.t_min, self.t_max, self.epsilon)
) ], mode = "smooth")
length = np.linalg.norm(integral)
epsilon = self.epsilon / length
t_range = np.arange(self.start, self.end, epsilon)
self.add_points([self.function(t) for t in t_range])
class Axes(Mobject): class Axes(VMobject):
def __init__(self, **kwargs): def generate_points(self):
x_axis = NumberLine(**kwargs) self.x_axis = NumberLine(**kwargs)
y_axis = NumberLine(**kwargs).rotate(np.pi/2, OUT) self.y_axis = NumberLine(**kwargs).rotate(np.pi/2)
Mobject.__init__(self, x_axis, y_axis) self.add(self.x_axis, self.y_axis)

View file

@ -1,13 +1,12 @@
from helpers import * from helpers import *
from mobject import Mobject, Mobject1D, Point from mobject import Mobject
from mobject.vectorized_mobject import VMobject from mobject.vectorized_mobject import VMobject
class Arc(VMobject): class Arc(VMobject):
CONFIG = { CONFIG = {
"radius" : 1.0, "radius" : 1.0,
"start_angle" : 0, "start_angle" : 0,
"close_new_points" : False,
"num_anchors" : 8, "num_anchors" : 8,
"anchors_span_full_range" : True "anchors_span_full_range" : True
} }
@ -59,7 +58,6 @@ class Dot(Circle): #Use 1D density, even though 2D
class Line(VMobject): class Line(VMobject):
CONFIG = { CONFIG = {
"buff" : 0, "buff" : 0,
"close_new_points" : False,
} }
def __init__(self, start, end, **kwargs): def __init__(self, start, end, **kwargs):
digest_config(self, kwargs) digest_config(self, kwargs)
@ -171,7 +169,8 @@ class CubicBezier(VMobject):
class Polygon(VMobject): class Polygon(VMobject):
CONFIG = { CONFIG = {
"color" : GREEN_D, "color" : GREEN_D,
"mark_paths_closed" : True "mark_paths_closed" : True,
"close_new_points" : True,
} }
def __init__(self, *vertices, **kwargs): def __init__(self, *vertices, **kwargs):
assert len(vertices) > 1 assert len(vertices) > 1
@ -190,7 +189,8 @@ class Rectangle(VMobject):
"color" : YELLOW, "color" : YELLOW,
"height" : 2.0, "height" : 2.0,
"width" : 4.0, "width" : 4.0,
"mark_paths_closed" : True "mark_paths_closed" : True,
"close_new_points" : True,
} }
def generate_points(self): def generate_points(self):
y, x = self.height/2, self.width/2 y, x = self.height/2, self.width/2

View file

@ -1,74 +1,61 @@
from helpers import * from helpers import *
from mobject import Mobject1D from mobject import Mobject1D
from mobject.vectorized_mobject import VMobject
from mobject.tex_mobject import TexMobject from mobject.tex_mobject import TexMobject
from topics.geometry import Line, Arrow
from scene import Scene from scene import Scene
class NumberLine(Mobject1D): class NumberLine(VMobject):
CONFIG = { CONFIG = {
"color" : BLUE, "color" : BLUE,
"numerical_radius" : SPACE_WIDTH, "x_min" : -SPACE_WIDTH,
"number_at_center" : 0, "x_max" : SPACE_WIDTH,
"unit_length_to_spatial_width" : 1, "space_unit_to_num" : 1,
"tick_size" : 0.1, "tick_size" : 0.1,
"tick_frequency" : 0.5, "tick_frequency" : 0.5,
"leftmost_tick" : None, "leftmost_tick" : None, #Defaults to ceil(x_min)
"numbers_with_elongated_ticks" : [0], "numbers_with_elongated_ticks" : [0],
"longer_tick_multiple" : 2, "longer_tick_multiple" : 2,
"number_at_center" : 0,
} }
def __init__(self, **kwargs): def __init__(self, **kwargs):
digest_config(self, kwargs) digest_config(self, kwargs)
if self.leftmost_tick is None: if self.leftmost_tick is None:
self.leftmost_tick = -int(self.numerical_radius-self.number_at_center) self.leftmost_tick = np.ceil(self.x_min)
self.left_num = self.number_at_center - self.numerical_radius VMobject.__init__(self, **kwargs)
self.right_num = self.number_at_center + self.numerical_radius
Mobject1D.__init__(self, **kwargs)
def generate_points(self): def generate_points(self):
spatial_radius = self.numerical_radius*self.unit_length_to_spatial_width self.main_line = Line(self.x_min*RIGHT, self.x_max*RIGHT)
self.add_points([ self.add(self.main_line)
(b*x, 0, 0) for x in self.get_tick_numbers():
for x in np.arange(0, spatial_radius, self.epsilon) self.add_tick(x, self.tick_size)
for b in [-1, 1] for x in self.numbers_with_elongated_ticks:
]) self.add_tick(x, self.longer_tick_multiple*self.tick_size)
self.index_of_left = np.argmin(self.points[:,0]) self.stretch(self.space_unit_to_num, 0)
self.index_of_right = np.argmax(self.points[:,0]) self.shift(-self.number_to_point(self.number_at_center))
spatial_tick_frequency = self.tick_frequency*self.unit_length_to_spatial_width
self.add_points([ def add_tick(self, x, size):
(x, y, 0) self.add(Line(
for num in self.get_tick_numbers() x*RIGHT+size*DOWN,
for y in np.arange(-self.tick_size, self.tick_size, self.epsilon) x*RIGHT+size*UP,
for x in [self.number_to_point(num)[0]] ))
]) return self
for number in self.numbers_with_elongated_ticks:
self.elongate_tick_at(number, self.longer_tick_multiple)
self.number_of_points_without_numbers = self.get_num_points()
def get_tick_numbers(self): def get_tick_numbers(self):
return np.arange(self.leftmost_tick, self.right_num, self.tick_frequency) return np.arange(self.leftmost_tick, self.x_max, self.tick_frequency)
def elongate_tick_at(self, number, multiple = 2):
x = self.number_to_point(number)[0]
self.add_points([
[x, y, 0]
for y in np.arange(
-multiple*self.tick_size,
multiple*self.tick_size,
self.epsilon
)
])
return self
def number_to_point(self, number): def number_to_point(self, number):
return interpolate( return interpolate(
self.get_left(), self.main_line.get_left(),
self.get_right(), self.main_line.get_right(),
float(number-self.left_num)/(self.right_num - self.left_num) float(number-self.x_min)/(self.x_max - self.x_min)
) )
def point_to_number(self, point): def point_to_number(self, point):
new_point = point-self.get_center() dist_from_left = (point[0]-self.main_line.get_left()[0])
return self.number_at_center + new_point[0]/self.unit_length_to_spatial_width num_dist_from_left = num_dist_from_left/self.space_unit_to_num
return self.x_min + dist_from_left
def default_numbers_to_display(self): def default_numbers_to_display(self):
return self.get_tick_numbers()[::2] return self.get_tick_numbers()[::2]
@ -83,11 +70,11 @@ class NumberLine(Mobject1D):
result = [] result = []
for number in numbers: for number in numbers:
mob = TexMobject(str(int(number))) mob = TexMobject(str(int(number)))
vert_scale = 2*self.tick_size/mob.get_height() mob.scale_to_fit_height(2*self.tick_size)
hori_scale = self.tick_frequency*self.unit_length_to_spatial_width/mob.get_width() mob.shift(
mob.scale(min(vert_scale, hori_scale)) self.number_to_point(number),
mob.shift(self.number_to_point(number)) self.get_vertical_number_offset(**kwargs)
mob.shift(self.get_vertical_number_offset(**kwargs)) )
result.append(mob) result.append(mob)
return result return result
@ -100,102 +87,110 @@ class NumberLine(Mobject1D):
class UnitInterval(NumberLine): class UnitInterval(NumberLine):
CONFIG = { CONFIG = {
"numerical_radius" : 0.5, "x_min" : 0,
"unit_length_to_spatial_width" : 2*(SPACE_WIDTH-1), "x_max" : 1,
"space_unit_to_num" : 6,
"tick_frequency" : 0.1, "tick_frequency" : 0.1,
"leftmost_tick" : 0,
"number_at_center" : 0.5,
"numbers_with_elongated_ticks" : [0, 1], "numbers_with_elongated_ticks" : [0, 1],
"number_at_center" : 0.5,
} }
class NumberPlane(Mobject1D): class NumberPlane(VMobject):
CONFIG = { CONFIG = {
"color" : BLUE, "color" : BLUE_D,
"secondary_color" : BLUE_E,
"axes_color" : WHITE,
"x_radius": SPACE_WIDTH, "x_radius": SPACE_WIDTH,
"y_radius": SPACE_HEIGHT, "y_radius": SPACE_HEIGHT,
"x_unit_to_spatial_width" : 1, "space_unit_to_x_unit" : 1,
"y_unit_to_spatial_height" : 1, "space_unit_to_y_unit" : 1,
"x_line_frequency" : 1, "x_line_frequency" : 1,
"x_faded_line_frequency" : 0.5,
"y_line_frequency" : 1, "y_line_frequency" : 1,
"y_faded_line_frequency" : 0.5, "secondary_line_ratio" : 1,
"fade_factor" : 0.3, "written_coordinate_height" : 0.5,
"number_scale_factor" : 0.25, "written_coordinate_nudge" : 0.1*(DOWN+RIGHT),
"num_pair_at_center" : np.array((0, 0)), "num_pair_at_center" : (0, 0),
} }
def generate_points(self): def generate_points(self):
#TODO, clean this self.axes = VMobject()
color = self.color self.main_lines = VMobject()
faded = Color(rgb = self.fade_factor*np.array(color.get_rgb())) self.secondary_lines = VMobject()
tuples = [
freq_color_tuples = [ (
(self.x_line_frequency, self.y_line_frequency, color), self.x_radius,
(self.x_faded_line_frequency, self.y_faded_line_frequency, faded), self.x_line_frequency,
self.y_radius*DOWN,
self.y_radius*UP,
RIGHT
),
(
self.y_radius,
self.y_line_frequency,
self.x_radius*LEFT,
self.x_radius*RIGHT,
UP,
),
] ]
x_vals = [] for radius, freq, start, end, unit in tuples:
y_vals = [] main_range = np.arange(0, radius, freq)
for x_freq, y_freq, color in freq_color_tuples: step = freq/float(freq + self.secondary_line_ratio)
if not x_freq or not y_freq: for v in np.arange(0, radius, step):
continue line1 = Line(start+v*unit, end+v*unit)
x_vals = np.array(filter(lambda x : x not in x_vals, np.arange( line2 = Line(start-v*unit, end-v*unit)
0, self.x_radius, if v == 0:
self.x_unit_to_spatial_width*x_freq self.axes.add(line1)
))) elif v in main_range:
y_vals = np.array(filter(lambda y : y not in y_vals, np.arange( self.main_lines.add(line1, line2)
0, self.y_radius, else:
self.y_unit_to_spatial_height*y_freq self.secondary_lines.add(line1, line2)
))) self.add(self.axes, self.main_lines, self.secondary_lines)
x_cont_vals = np.arange( self.stretch(self.space_unit_to_x_unit, 0)
0, self.x_radius, self.stretch(self.space_unit_to_y_unit, 1)
self.epsilon/self.x_unit_to_spatial_width
)
y_cont_vals = np.arange(
0, self.y_radius,
self.epsilon/self.y_unit_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 init_colors(self):
VMobject.init_colors(self)
self.axes.set_stroke(self.axes_color)
# self.main_lines.set_stroke(self.color)
self.secondary_lines.set_stroke(self.secondary_color, 1)
return self
def get_center_point(self): def get_center_point(self):
return self.num_pair_to_point(self.num_pair_at_center) return self.num_pair_to_point(self.num_pair_at_center)
def num_pair_to_point(self, pair): def num_pair_to_point(self, pair):
pair = pair + self.num_pair_at_center pair = np.array(pair) + self.num_pair_at_center
result = self.get_center() result = self.get_center()
result[0] += pair[0]*self.x_unit_to_spatial_width result[0] += pair[0]*self.space_unit_to_x_unit
result[1] += pair[1]*self.y_unit_to_spatial_height result[1] += pair[1]*self.space_unit_to_y_unit
return result return result
def point_to_num_pair(self, point): def point_to_num_pair(self, point):
new_point = point-self.get_center() new_point = point-self.get_center()
center_x, center_y = self.num_pair_at_center center_x, center_y = self.num_pair_at_center
x = center_x + point[0]/self.x_unit_to_spatial_width x = center_x + point[0]/self.space_unit_to_x_unit
y = center_y + point[1]/self.y_unit_to_spatial_height y = center_y + point[1]/self.space_unit_to_y_unit
return x, y return x, y
def get_coordinate_labels(self, x_vals = None, y_vals = None): def get_coordinate_labels(self, x_vals = None, y_vals = None):
result = [] result = []
nudge = 0.1*(DOWN+RIGHT)
if x_vals == None and y_vals == None: if x_vals == None and y_vals == None:
x_vals = range(-int(self.x_radius), int(self.x_radius)) x_vals = range(-int(self.x_radius), int(self.x_radius))
y_vals = range(-int(self.y_radius), int(self.y_radius)) y_vals = range(-int(self.y_radius), int(self.y_radius))
for index, vals in zip([0, 1], [x_vals, y_vals]): for index, vals in enumerate([x_vals, y_vals]):
num_pair = [0, 0] num_pair = [0, 0]
for val in vals: for val in vals:
num_pair[index] = val num_pair[index] = val
point = self.num_pair_to_point(num_pair) point = self.num_pair_to_point(num_pair)
num = TexMobject(str(val)) num = TexMobject(str(val))
num.scale(self.number_scale_factor) num.scale_to_fit_height(
num.shift(point-num.get_corner(UP+LEFT)+nudge) self.written_coordinate_height
)
num.shift(
point-num.get_corner(UP+LEFT),
self.written_coordinate_nudge
)
result.append(num) result.append(num)
return result return result
@ -204,134 +199,15 @@ class NumberPlane(Mobject1D):
return self return self
def get_vector(self, coords, **kwargs): def get_vector(self, coords, **kwargs):
if len(coords) == 2: point = coords[0]*RIGHT + coords[1]*UP
coords = tuple(list(coords) + [0])
arrow = Arrow(ORIGIN, coords, **kwargs) arrow = Arrow(ORIGIN, coords, **kwargs)
arrow.remove_tip()
arrow.align_data(Line(ORIGIN, SPACE_WIDTH*LEFT))
arrow.add_tip()
return arrow return arrow
def prepare_for_nonlinear_transform(self):
class XYZAxes(Mobject1D): for mob in self.submobject_family():
CONFIG = { if mob.get_num_points() > 0:
"color" : TEAL, mob.insert_n_anchor_points(20)
"radius" : SPACE_HEIGHT, mob.change_anchor_mode("smooth")
"tick_frequency" : 1,
}
def generate_points(self):
self.x_axis = NumberLine(
numerical_radius = self.radius,
tick_frequency = self.tick_frequency
)
self.y_axis = self.x_axis.copy().rotate(np.pi/2, OUT)
self.z_axis = self.x_axis.copy().rotate(np.pi/2, DOWN)
self.digest_mobject_attrs()
class SpaceGrid(Mobject1D):
CONFIG = {
"color" : GREEN,
"radius" : SPACE_HEIGHT,
"unit_to_spatial_length" : 1,
"line_frequency" : 2,
}
def generate_points(self):
line_range = range(-int(self.radius), int(self.radius)+1, self.line_frequency)
for i in range(3):
perm = np.arange(i, i+3) % 3
for a, b in it.product(line_range, line_range):
start = np.array([a, b, -self.radius])[perm]
end = np.array([a, b, self.radius])[perm]
self.add_line(start, end)
self.pose_at_angle()
class NumberLineScene(Scene):
def construct(self, **number_line_config):
self.number_line = NumberLine(**number_line_config)
self.displayed_numbers = self.number_line.default_numbers_to_display()
self.number_mobs = self.number_line.get_number_mobjects(*self.displayed_numbers)
self.add(self.number_line, *self.number_mobs)
def zoom_in_on(self, number, zoom_factor, run_time = 2.0):
unit_length_to_spatial_width = self.number_line.unit_length_to_spatial_width*zoom_factor
radius = SPACE_WIDTH/unit_length_to_spatial_width
tick_frequency = 10**(np.floor(np.log10(radius)))
left_tick = tick_frequency*(np.ceil((number-radius)/tick_frequency))
new_number_line = NumberLine(
numerical_radius = radius,
unit_length_to_spatial_width = unit_length_to_spatial_width,
tick_frequency = tick_frequency,
leftmost_tick = left_tick,
number_at_center = number
)
new_displayed_numbers = new_number_line.default_numbers_to_display()
new_number_mobs = new_number_line.get_number_mobjects(*new_displayed_numbers)
transforms = []
additional_mobjects = []
squished_new_line = new_number_line.copy()
squished_new_line.scale(1.0/zoom_factor)
squished_new_line.shift(self.number_line.number_to_point(number))
squished_new_line.points[:,1] = self.number_line.number_to_point(0)[1]
transforms.append(Transform(squished_new_line, new_number_line))
for mob, num in zip(new_number_mobs, new_displayed_numbers):
point = Point(self.number_line.number_to_point(num))
point.shift(new_number_line.get_vertical_number_offset())
transforms.append(Transform(point, mob))
for mob in self.mobjects:
if mob == self.number_line:
new_mob = mob.copy()
new_mob.shift(-self.number_line.number_to_point(number))
new_mob.stretch(zoom_factor, 0)
transforms.append(Transform(mob, new_mob))
continue
mob_center = mob.get_center()
number_under_center = self.number_line.point_to_number(mob_center)
new_point = new_number_line.number_to_point(number_under_center)
new_point += mob_center[1]*UP
if mob in self.number_mobs:
transforms.append(Transform(mob, Point(new_point)))
else:
transforms.append(ApplyMethod(mob.shift, new_point - mob_center))
additional_mobjects.append(mob)
line_to_hide_pixelation = Line(
self.number_line.get_left(),
self.number_line.get_right(),
color = self.number_line.get_color()
)
self.add(line_to_hide_pixelation)
self.play(*transforms, run_time = run_time)
self.clear()
self.number_line = new_number_line
self.displayed_numbers = new_displayed_numbers
self.number_mobs = new_number_mobs
self.add(self.number_line, *self.number_mobs)
self.add(*additional_mobjects)
def show_multiplication(self, num, **kwargs):
if "path_func" not in kwargs:
if num > 0:
kwargs["path_func"] = straight_path
else:
kwargs["path_func"] = counterclockwise_path()
self.play(*[
ApplyMethod(self.number_line.stretch, num, 0, **kwargs)
]+[
ApplyMethod(mob.shift, (num-1)*mob.get_center()[0]*RIGHT, **kwargs)
for mob in self.number_mobs
])