3b1b-manim/topics/number_line.py

430 lines
14 KiB
Python
Raw Normal View History

2015-06-10 22:00:35 -07:00
from helpers import *
from mobject import Mobject1D
2016-10-27 22:54:12 -07:00
from mobject.vectorized_mobject import VMobject, VGroup
from mobject.tex_mobject import TexMobject
2016-04-19 00:20:19 -07:00
from topics.geometry import Line, Arrow
2018-01-18 16:46:38 -08:00
from topics.functions import ParametricFunction
from scene import Scene
2015-06-10 22:00:35 -07:00
2016-04-19 00:20:19 -07:00
class NumberLine(VMobject):
2016-02-27 16:32:53 -08:00
CONFIG = {
2016-04-19 00:20:19 -07:00
"color" : BLUE,
"x_min" : -SPACE_WIDTH,
"x_max" : SPACE_WIDTH,
"unit_size" : 1,
2016-04-19 00:20:19 -07:00
"tick_size" : 0.1,
2016-08-17 16:14:15 -07:00
"tick_frequency" : 1,
"leftmost_tick" : None, #Defaults to value near x_min s.t. 0 is a tick
"numbers_with_elongated_ticks" : [0],
"numbers_to_show" : None,
2016-04-19 00:20:19 -07:00
"longer_tick_multiple" : 2,
"number_at_center" : 0,
"number_scale_val" : 0.75,
"label_direction" : DOWN,
2017-08-07 16:17:35 -07:00
"line_to_number_buff" : MED_SMALL_BUFF,
2017-08-24 23:10:53 -07:00
"include_tip" : False,
2018-01-15 18:16:50 -08:00
"propagate_style_to_family" : True,
}
def __init__(self, **kwargs):
digest_config(self, kwargs)
if self.leftmost_tick is None:
tf = self.tick_frequency
self.leftmost_tick = tf*np.ceil(self.x_min/tf)
2016-04-19 00:20:19 -07:00
VMobject.__init__(self, **kwargs)
2017-08-24 23:10:53 -07:00
if self.include_tip:
self.add_tip()
2015-06-10 22:00:35 -07:00
def generate_points(self):
2016-04-19 00:20:19 -07:00
self.main_line = Line(self.x_min*RIGHT, self.x_max*RIGHT)
self.tick_marks = VGroup()
self.add(self.main_line, self.tick_marks)
2018-01-18 13:33:48 -08:00
rounding_value = int(-np.log10(0.1*self.tick_frequency))
rounded_numbers_with_elongated_ticks = np.round(
self.numbers_with_elongated_ticks,
rounding_value
)
2016-04-19 00:20:19 -07:00
for x in self.get_tick_numbers():
2018-01-18 13:33:48 -08:00
rounded_x = np.round(x, rounding_value)
if rounded_x in rounded_numbers_with_elongated_ticks:
tick_size_used = self.longer_tick_multiple*self.tick_size
else:
tick_size_used = self.tick_size
self.add_tick(x, tick_size_used)
self.stretch(self.unit_size, 0)
2016-04-19 00:20:19 -07:00
self.shift(-self.number_to_point(self.number_at_center))
2017-08-07 16:17:35 -07:00
def add_tick(self, x, size = None):
self.tick_marks.add(self.get_tick(x, size))
2016-04-19 00:20:19 -07:00
return self
2017-08-07 16:17:35 -07:00
def get_tick(self, x, size = None):
if size is None: size = self.tick_size
result = Line(size*DOWN, size*UP)
result.rotate(self.main_line.get_angle())
result.move_to(self.number_to_point(x))
return result
def get_tick_marks(self):
return self.tick_marks
def get_tick_numbers(self):
2017-04-18 18:37:15 -07:00
epsilon = 0.001
return np.arange(
2017-04-18 18:37:15 -07:00
self.leftmost_tick, self.x_max+epsilon,
self.tick_frequency
)
def number_to_point(self, number):
2016-11-11 11:18:41 -08:00
alpha = float(number-self.x_min)/(self.x_max - self.x_min)
return interpolate(
2016-11-11 11:18:41 -08:00
self.main_line.get_start(),
self.main_line.get_end(),
alpha
)
def point_to_number(self, point):
left_point, right_point = self.main_line.get_start_and_end()
full_vect = right_point-left_point
def distance_from_left(p):
return np.dot(p-left_point, full_vect)/np.linalg.norm(full_vect)
return interpolate(
self.x_min, self.x_max,
distance_from_left(point)/distance_from_left(right_point)
)
def default_numbers_to_display(self):
if self.numbers_to_show is not None:
return self.numbers_to_show
2017-08-07 16:17:35 -07:00
return np.arange(int(self.leftmost_tick), int(self.x_max)+1)
def get_number_mobjects(self, *numbers, **kwargs):
#TODO, handle decimals
if len(numbers) == 0:
numbers = self.default_numbers_to_display()
if "force_integers" in kwargs and kwargs["force_integers"]:
numbers = map(int, numbers)
2016-10-27 22:54:12 -07:00
result = VGroup()
for number in numbers:
mob = TexMobject(str(number))
2017-08-07 16:17:35 -07:00
mob.scale(self.number_scale_val)
mob.next_to(
2016-04-19 00:20:19 -07:00
self.number_to_point(number),
self.label_direction,
2017-08-07 16:17:35 -07:00
self.line_to_number_buff,
2016-04-19 00:20:19 -07:00
)
2016-10-27 22:54:12 -07:00
result.add(mob)
return result
def add_numbers(self, *numbers, **kwargs):
self.numbers = self.get_number_mobjects(
*numbers, **kwargs
)
self.add(*self.numbers)
return self
2015-06-10 22:00:35 -07:00
2017-08-24 23:10:53 -07:00
def add_tip(self):
start, end = self.main_line.get_start_and_end()
vect = (end - start)/np.linalg.norm(end-start)
arrow = Arrow(start, end + MED_SMALL_BUFF*vect, buff = 0)
2017-08-24 23:10:53 -07:00
tip = arrow.tip
tip.highlight(self.color)
self.tip = tip
self.add(tip)
class UnitInterval(NumberLine):
2016-02-27 16:32:53 -08:00
CONFIG = {
2016-04-19 00:20:19 -07:00
"x_min" : 0,
"x_max" : 1,
"unit_size" : 6,
2016-04-19 00:20:19 -07:00
"tick_frequency" : 0.1,
"numbers_with_elongated_ticks" : [0, 1],
2016-04-19 00:20:19 -07:00
"number_at_center" : 0.5,
}
2016-12-29 14:31:01 -08:00
class Axes(VGroup):
2016-04-30 15:08:53 -07:00
CONFIG = {
2018-01-15 18:16:50 -08:00
"propagate_style_to_family" : True,
2017-08-24 23:10:53 -07:00
"three_d" : False,
"number_line_config" : {
"color" : LIGHT_GREY,
"include_tip" : True,
},
"x_axis_config" : {},
"y_axis_config" : {},
"z_axis_config" : {},
"x_min" : -SPACE_WIDTH,
"x_max" : SPACE_WIDTH,
"y_min" : -SPACE_HEIGHT,
"y_max" : SPACE_HEIGHT,
"z_min" : -3.5,
"z_max" : 3.5,
"z_normal" : DOWN,
2018-01-18 16:46:38 -08:00
"default_num_graph_points" : 100,
2016-04-30 15:08:53 -07:00
}
2016-12-29 14:31:01 -08:00
def __init__(self, **kwargs):
2017-08-24 23:10:53 -07:00
VGroup.__init__(self, **kwargs)
self.x_axis = self.get_axis(self.x_min, self.x_max, self.x_axis_config)
self.y_axis = self.get_axis(self.y_min, self.y_max, self.y_axis_config)
self.y_axis.rotate(np.pi/2, about_point = ORIGIN)
2017-08-24 23:10:53 -07:00
self.add(self.x_axis, self.y_axis)
2017-08-24 19:06:48 -07:00
if self.three_d:
self.z_axis = self.get_axis(self.z_min, self.z_max, self.z_axis_config)
self.z_axis.rotate(-np.pi/2, UP, about_point = ORIGIN)
self.z_axis.rotate(
angle_of_vector(self.z_normal), OUT,
about_point = ORIGIN
)
2017-08-24 23:10:53 -07:00
self.add(self.z_axis)
def get_axis(self, min_val, max_val, extra_config):
config = dict(self.number_line_config)
config.update(extra_config)
return NumberLine(x_min = min_val, x_max = max_val, **config)
def coords_to_point(self, x, y):
origin = self.x_axis.number_to_point(0)
x_axis_projection = self.x_axis.number_to_point(x)
y_axis_projection = self.y_axis.number_to_point(y)
return x_axis_projection + y_axis_projection - origin
2018-01-16 09:44:51 -08:00
def point_to_coords(self, point):
return (
self.x_axis.point_to_number(point),
self.y_axis.point_to_number(point),
)
2018-01-24 16:09:37 -08:00
def get_graph(
self, function, num_graph_points = None,
x_min = None,
x_max = None,
**kwargs
):
kwargs["fill_opacity"] = kwargs.get("fill_opacity", 0)
2018-01-18 16:46:38 -08:00
kwargs["num_anchor_points"] = \
num_graph_points or self.default_num_graph_points
2018-01-24 16:09:37 -08:00
x_min = x_min or self.x_min
x_max = x_max or self.x_max
2018-01-18 16:46:38 -08:00
graph = ParametricFunction(
lambda t : self.coords_to_point(t, function(t)),
2018-01-24 16:09:37 -08:00
t_min = x_min,
t_max = x_max,
2018-01-18 16:46:38 -08:00
**kwargs
)
2018-01-12 12:37:38 -08:00
graph.underlying_function = function
return graph
2018-01-16 09:44:51 -08:00
def input_to_graph_point(self, x, graph):
if hasattr(graph, "underlying_function"):
return self.coords_to_point(x, graph.underlying_function(x))
else:
#binary search
lh, rh = 0, 1
while abs(lh - rh) > 0.001:
mh = np.mean([lh, rh])
hands = [lh, mh, rh]
points = map(graph.point_from_proportion, hands)
lx, mx, rx = map(self.x_axis.point_to_number, points)
if lx <= x and rx >= x:
if mx > x:
rh = mh
else:
lh = mh
elif lx <= x and rx <= x:
return points[2]
elif lx >= x and rx >= x:
return points[0]
elif lx > x and rx < x:
lh, rh = rh, lh
return points[1]
2018-01-16 09:44:51 -08:00
2017-08-24 23:10:53 -07:00
class ThreeDAxes(Axes):
CONFIG = {
"x_min" : -5.5,
"x_max" : 5.5,
"y_min" : -4.5,
"y_max" : 4.5,
2017-08-24 23:10:53 -07:00
"three_d" : True,
}
2016-04-19 00:20:19 -07:00
class NumberPlane(VMobject):
2016-02-27 16:32:53 -08:00
CONFIG = {
2016-04-19 00:20:19 -07:00
"color" : BLUE_D,
"secondary_color" : BLUE_E,
"axes_color" : WHITE,
2016-07-22 11:22:31 -07:00
"secondary_stroke_width" : 1,
"x_radius": None,
"y_radius": None,
"x_unit_size" : 1,
"y_unit_size" : 1,
"center_point" : ORIGIN,
2016-04-19 00:20:19 -07:00
"x_line_frequency" : 1,
"y_line_frequency" : 1,
"secondary_line_ratio" : 1,
2016-04-30 15:08:53 -07:00
"written_coordinate_height" : 0.2,
2018-01-15 18:16:50 -08:00
"propagate_style_to_family" : False,
"make_smooth_after_applying_functions" : True,
2015-10-06 15:27:40 -07:00
}
def generate_points(self):
if self.x_radius is None:
center_to_edge = (SPACE_WIDTH + abs(self.center_point[0]))
self.x_radius = center_to_edge / self.x_unit_size
if self.y_radius is None:
center_to_edge = (SPACE_HEIGHT + abs(self.center_point[1]))
self.y_radius = center_to_edge / self.y_unit_size
2016-04-19 00:20:19 -07:00
self.axes = VMobject()
self.main_lines = VMobject()
self.secondary_lines = VMobject()
tuples = [
(
self.x_radius,
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,
),
2015-10-06 18:41:26 -07:00
]
2016-04-19 00:20:19 -07:00
for radius, freq, start, end, unit in tuples:
main_range = np.arange(0, radius, freq)
step = freq/float(freq + self.secondary_line_ratio)
for v in np.arange(0, radius, step):
line1 = Line(start+v*unit, end+v*unit)
line2 = Line(start-v*unit, end-v*unit)
if v == 0:
self.axes.add(line1)
elif v in main_range:
self.main_lines.add(line1, line2)
else:
self.secondary_lines.add(line1, line2)
self.add(self.secondary_lines, self.main_lines, self.axes)
self.stretch(self.x_unit_size, 0)
self.stretch(self.y_unit_size, 1)
self.shift(self.center_point)
#Put x_axis before y_axis
y_axis, x_axis = self.axes.split()
self.axes = VMobject(x_axis, y_axis)
2016-04-19 00:20:19 -07:00
def init_colors(self):
VMobject.init_colors(self)
2016-07-22 11:22:31 -07:00
self.axes.set_stroke(self.axes_color, self.stroke_width)
self.main_lines.set_stroke(self.color, self.stroke_width)
self.secondary_lines.set_stroke(
self.secondary_color, self.secondary_stroke_width
)
2016-04-19 00:20:19 -07:00
return self
2015-10-20 21:55:46 -07:00
2015-10-06 15:27:40 -07:00
def get_center_point(self):
return self.coords_to_point(0, 0)
2015-10-06 15:27:40 -07:00
def coords_to_point(self, x, y):
x, y = np.array([x, y])
result = self.axes.get_center()
result += x*self.get_x_unit_size()*RIGHT
result += y*self.get_y_unit_size()*UP
return result
def point_to_coords(self, point):
new_point = point - self.axes.get_center()
x = new_point[0]/self.get_x_unit_size()
y = new_point[1]/self.get_y_unit_size()
return x, y
2015-10-06 15:27:40 -07:00
# Does not recompute center, unit_sizes for each call; useful for
# iterating over large lists of points, but does assume these
# attributes are kept accurate. (Could alternatively have a method
# which returns a function dynamically created after a single
# call to each of get_center(), get_x_unit_size(), etc.)
def point_to_coords_cheap(self, point):
new_point = point - self.center_point
x = new_point[0]/self.x_unit_size
y = new_point[1]/self.y_unit_size
return x, y
def get_x_unit_size(self):
return self.axes.get_width() / (2.0*self.x_radius)
def get_y_unit_size(self):
return self.axes.get_height() / (2.0*self.y_radius)
2015-10-06 15:27:40 -07:00
def get_coordinate_labels(self, x_vals = None, y_vals = None):
2017-08-05 20:47:06 -07:00
coordinate_labels = VGroup()
if x_vals == None:
x_vals = range(-int(self.x_radius), int(self.x_radius)+1)
if y_vals == None:
y_vals = range(-int(self.y_radius), int(self.y_radius)+1)
2016-04-19 00:20:19 -07:00
for index, vals in enumerate([x_vals, y_vals]):
2015-10-06 15:27:40 -07:00
num_pair = [0, 0]
for val in vals:
if val == 0:
continue
2015-10-06 15:27:40 -07:00
num_pair[index] = val
point = self.coords_to_point(*num_pair)
num = TexMobject(str(val))
num.add_background_rectangle()
2016-04-19 00:20:19 -07:00
num.scale_to_fit_height(
self.written_coordinate_height
)
2017-08-05 20:47:06 -07:00
num.next_to(point, DOWN+LEFT, buff = SMALL_BUFF)
coordinate_labels.add(num)
self.coordinate_labels = coordinate_labels
return coordinate_labels
2015-10-06 15:27:40 -07:00
def get_axes(self):
return self.axes
def get_axis_labels(self, x_label = "x", y_label = "y"):
x_axis, y_axis = self.get_axes().split()
quads = [
(x_axis, x_label, UP, RIGHT),
(y_axis, y_label, RIGHT, UP),
]
labels = VGroup()
for axis, tex, vect, edge in quads:
label = TexMobject(tex)
label.add_background_rectangle()
label.next_to(axis, vect)
label.to_edge(edge)
labels.add(label)
2017-03-14 15:50:16 -07:00
self.axis_labels = labels
return labels
2015-10-06 15:27:40 -07:00
def add_coordinates(self, x_vals = None, y_vals = None):
self.add(*self.get_coordinate_labels(x_vals, y_vals))
return self
2015-06-27 04:49:10 -07:00
2015-10-12 19:39:46 -07:00
def get_vector(self, coords, **kwargs):
2016-04-19 00:20:19 -07:00
point = coords[0]*RIGHT + coords[1]*UP
2015-10-12 19:39:46 -07:00
arrow = Arrow(ORIGIN, coords, **kwargs)
return arrow
def prepare_for_nonlinear_transform(self, num_inserted_anchor_points = 50):
for mob in self.family_members_with_points():
2016-12-01 15:15:54 -08:00
num_anchors = mob.get_num_anchor_points()
if num_inserted_anchor_points > num_anchors:
mob.insert_n_anchor_points(num_inserted_anchor_points-num_anchors)
mob.make_smooth()
return self
2015-10-12 19:39:46 -07:00
2015-10-20 21:55:46 -07:00
2015-06-27 04:49:10 -07:00
2015-06-10 22:00:35 -07:00