diff --git a/.gitignore b/.gitignore index fffdd8af..ae612633 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ .DS_Store homeless.py playground.py +cairo_test.py +mayavi_test.py random_scenes/ files/ ben_playground.py diff --git a/active_projects/eola2/cramer.py b/active_projects/eola2/cramer.py index a296e777..b5e12ed5 100644 --- a/active_projects/eola2/cramer.py +++ b/active_projects/eola2/cramer.py @@ -1031,8 +1031,8 @@ class LookAtDotProducts(SetupSimpleSystemOfEquations): output_vect = self.output_vect_mob.get_end() c1 = self.basis_vectors[0].get_end() c2 = self.basis_vectors[1].get_end() - x_point = c1 * np.dot(output_vect, c1) / (np.linalg.norm(c1)**2) - y_point = c2 * np.dot(output_vect, c2) / (np.linalg.norm(c2)**2) + x_point = c1 * np.dot(output_vect, c1) / (get_norm(c1)**2) + y_point = c2 * np.dot(output_vect, c2) / (get_norm(c2)**2) dashed_line_to_x = DashedLine(self.output_vect_mob.get_end(), x_point) dashed_line_to_y = DashedLine(self.output_vect_mob.get_end(), y_point) diff --git a/active_projects/eop/combinations.py b/active_projects/eop/combinations.py index 868b4065..d2ebc580 100644 --- a/active_projects/eop/combinations.py +++ b/active_projects/eop/combinations.py @@ -547,7 +547,7 @@ class SixChooseThreeInOtherContext(Scene): self.add(dots) self.dots = dots - self.dot_to_dot_distance = np.linalg.norm( + self.dot_to_dot_distance = get_norm( dots[1].get_center() - dots[0].get_center() ) diff --git a/active_projects/eop/independence.py b/active_projects/eop/independence.py index 5560347d..5003db5b 100644 --- a/active_projects/eop/independence.py +++ b/active_projects/eop/independence.py @@ -3086,8 +3086,8 @@ class CorrectForDependence(NameBinomial): mob.generate_target() c = mob.get_center() start, end = arrow.target.get_start_and_end() - to_end = np.linalg.norm(c - end) - to_start = np.linalg.norm(c - start) + to_end = get_norm(c - end) + to_start = get_norm(c - start) if to_end < to_start: mob.target.set_fill(opacity = 1) else: diff --git a/animation/numbers.py b/animation/numbers.py index 0b900642..7bc22157 100644 --- a/animation/numbers.py +++ b/animation/numbers.py @@ -21,6 +21,7 @@ class ChangingDecimal(Animation): dmc = decimal_number_mobject.get_center() tmc = self.tracked_mobject.get_center() self.diff_from_tracked_mobject = dmc - tmc + self.diff_from_tracked_mobject = dmc - tmc Animation.__init__(self, decimal_number_mobject, **kwargs) def update_mobject(self, alpha): diff --git a/animation/specialized.py b/animation/specialized.py index 5b43dbd3..162f9df3 100644 --- a/animation/specialized.py +++ b/animation/specialized.py @@ -10,6 +10,7 @@ from mobject.svg.drawings import Car from mobject.types.vectorized_mobject import VGroup from mobject.geometry import Circle from utils.config_ops import digest_config +from utils.space_ops import get_norm class MoveCar(ApplyMethod): @@ -21,7 +22,7 @@ class MoveCar(ApplyMethod): assert isinstance(car, Car) ApplyMethod.__init__(self, car.move_to, target_point, **kwargs) displacement = self.target_mobject.get_right() - self.starting_mobject.get_right() - distance = np.linalg.norm(displacement) + distance = get_norm(displacement) if not self.moving_forward: distance *= -1 tire_radius = car.get_tires()[0].get_width() / 2 diff --git a/camera/camera.py b/camera/camera.py index 701dd64f..e92d7ed7 100644 --- a/camera/camera.py +++ b/camera/camera.py @@ -27,6 +27,7 @@ from utils.iterables import list_difference_update from utils.iterables import remove_list_redundancies from utils.simple_functions import fdiv from utils.space_ops import angle_of_vector +from utils.space_ops import get_norm from functools import reduce @@ -264,7 +265,7 @@ class Camera(object): (VMobject, self.display_multiple_vectorized_mobjects), (PMobject, self.display_multiple_point_cloud_mobjects), (AbstractImageMobject, self.display_multiple_image_mobjects), - (Mobject, lambda batch: batch), # Do nothing + (Mobject, lambda batch, pa: batch), # Do nothing ] def get_mobject_type(mobject): @@ -301,6 +302,7 @@ class Camera(object): ph = self.get_pixel_height() fw = self.get_frame_width() fh = self.get_frame_height() + fc = self.get_frame_center() surface = cairo.ImageSurface.create_for_data( pixel_array, cairo.FORMAT_ARGB32, @@ -311,7 +313,8 @@ class Camera(object): ctx.set_matrix(cairo.Matrix( fdiv(pw, fw), 0, 0, -fdiv(ph, fh), - pw / 2, ph / 2, + (pw / 2) + fc[0] * fdiv(pw, fw), + (ph / 2) + fc[1] * fdiv(ph, fh), )) self.cache_cairo_context(pixel_array, ctx) return ctx @@ -368,10 +371,12 @@ class Camera(object): ) else: points = vmobject.get_gradient_start_and_end_points() + points = self.transform_points_pre_display(points) pat = cairo.LinearGradient(*it.chain(*[ point[:2] for point in points ])) - offsets = np.linspace(1, 0, len(rgbas)) + step = 1.0 / (len(rgbas) - 1) + offsets = np.arange(0, 1 + step, step) for rgba, offset in zip(rgbas, offsets): pat.add_color_stop_rgba( offset, *rgba[2::-1], rgba[3] @@ -442,7 +447,7 @@ class Camera(object): rgbas = (self.rgb_max_val * rgbas).astype(self.pixel_array_dtype) target_len = len(pixel_coords) - factor = target_len / len(rgbas) + factor = target_len // len(rgbas) rgbas = np.array([rgbas] * factor).reshape((target_len, rgba_len)) on_screen_indices = self.on_screen_pixels(pixel_coords) @@ -459,7 +464,7 @@ class Camera(object): new_pa = pixel_array.reshape((ph * pw, rgba_len)) new_pa[indices] = rgbas - pixel_array[:, :] = new_pa + pixel_array[:, :] = new_pa.reshape((ph, pw, rgba_len)) def display_multiple_image_mobjects(self, image_mobjects, pixel_array): for image_mobject in image_mobjects: @@ -531,7 +536,7 @@ class Camera(object): def adjust_out_of_range_points(self, points): if not np.any(points > self.max_allowable_norm): return points - norms = np.apply_along_axis(np.linalg.norm, 1, points) + norms = np.apply_along_axis(get_norm, 1, points) violator_indices = norms > self.max_allowable_norm violators = points[violator_indices, :] violator_norms = norms[violator_indices] @@ -590,7 +595,8 @@ class Camera(object): return 1 + (thickness - 1) / factor def get_thickening_nudges(self, thickness): - _range = list(range(-thickness / 2 + 1, thickness / 2 + 1)) + thickness = int(thickness) + _range = list(range(-thickness // 2 + 1, thickness // 2 + 1)) return np.array(list(it.product(_range, _range))) def thickened_coordinates(self, pixel_coords, thickness): @@ -600,7 +606,7 @@ class Camera(object): for nudge in nudges ]) size = pixel_coords.size - return pixel_coords.reshape((size / 2, 2)) + return pixel_coords.reshape((size // 2, 2)) # TODO, reimplement using cairo matrix def get_coords_of_all_pixels(self): diff --git a/camera/three_d_camera.py b/camera/three_d_camera.py index c899c6cc..bd3a72f1 100644 --- a/camera/three_d_camera.py +++ b/camera/three_d_camera.py @@ -4,61 +4,74 @@ import numpy as np from constants import * -from camera.moving_camera import MovingCamera -from mobject.types.vectorized_mobject import VectorizedPoint -from mobject.three_dimensions import should_shade_in_3d +from camera.camera import Camera +from mobject.types.point_cloud_mobject import Point +from mobject.three_dimensions import ThreeDVMobject +from mobject.value_tracker import ValueTracker -from utils.bezier import interpolate +from utils.color import get_shaded_rgb from utils.space_ops import rotation_about_z from utils.space_ops import rotation_matrix -# TODO: Make sure this plays well with latest camera updates - -# class CameraWithPerspective(Camera): -# CONFIG = { -# "camera_distance": 20, -# } - -# def points_to_pixel_coords(self, points): -# distance_ratios = np.divide( -# self.camera_distance, -# self.camera_distance - points[:, 2] -# ) -# scale_factors = interpolate(0, 1, distance_ratios) -# adjusted_points = np.array(points) -# for i in 0, 1: -# adjusted_points[:, i] *= scale_factors - -# return Camera.points_to_pixel_coords(self, adjusted_points) - - -class ThreeDCamera(MovingCamera): +class ThreeDCamera(Camera): CONFIG = { "sun_vect": 5 * UP + LEFT, "shading_factor": 0.2, - "distance": 5.0, + "distance": 20.0, "default_distance": 5.0, "phi": 0, # Angle off z axis - "theta": -TAU / 4, # Rotation about z axis + "theta": -90 * DEGREES, # Rotation about z axis + "gamma": 0, # Rotation about normal vector to camera + "light_source_start_point": 9 * DOWN + 7 * LEFT + 10 * OUT, + "frame_center": ORIGIN, } def __init__(self, *args, **kwargs): - MovingCamera.__init__(self, *args, **kwargs) - self.unit_sun_vect = self.sun_vect / np.linalg.norm(self.sun_vect) - # rotation_mobject lives in the phi-theta-distance space - # TODO, use ValueTracker for this instead - self.rotation_mobject = VectorizedPoint() - # Moving_center lives in the x-y-z space - # It representes the center of rotation - self.moving_center = VectorizedPoint(self.frame_center) - self.set_position(self.phi, self.theta, self.distance) + Camera.__init__(self, *args, **kwargs) + self.phi_tracker = ValueTracker(self.phi) + self.theta_tracker = ValueTracker(self.theta) + self.distance_tracker = ValueTracker(self.distance) + self.gamma_tracker = ValueTracker(self.gamma) + self.light_source = Point(self.light_source_start_point) + self.frame_center = Point(self.frame_center) + self.reset_rotation_matrix() + + def capture_mobjects(self, mobjects, **kwargs): + self.reset_rotation_matrix() + Camera.capture_mobjects(self, mobjects, **kwargs) + + def get_value_trackers(self): + return [ + self.phi_tracker, + self.theta_tracker, + self.distance_tracker, + self.gamma_tracker, + ] def modified_rgbas(self, vmobject, rgbas): - if should_shade_in_3d(vmobject): - return self.get_shaded_rgbas(rgbas, self.get_unit_normal_vect(vmobject)) - else: - return rgbas + is_3d = isinstance(vmobject, ThreeDVMobject) + has_points = (vmobject.get_num_points() > 0) + if is_3d and has_points: + light_source_point = self.light_source.points[0] + if len(rgbas) < 2: + shaded_rgbas = rgbas.repeat(2, axis=0) + else: + shaded_rgbas = np.array(rgbas[:2]) + shaded_rgbas[0, :3] = get_shaded_rgb( + shaded_rgbas[0, :3], + vmobject.get_start_corner(), + vmobject.get_start_corner_unit_normal(), + light_source_point, + ) + shaded_rgbas[1, :3] = get_shaded_rgb( + shaded_rgbas[1, :3], + vmobject.get_end_corner(), + vmobject.get_end_corner_unit_normal(), + light_source_point, + ) + return shaded_rgbas + return rgbas def get_stroke_rgbas(self, vmobject, background=False): return self.modified_rgbas( @@ -70,111 +83,81 @@ class ThreeDCamera(MovingCamera): vmobject, vmobject.get_fill_rgbas() ) - def get_shaded_rgbas(self, rgbas, normal_vect): - brightness = np.dot(normal_vect, self.unit_sun_vect)**2 - target = np.ones(rgbas.shape) - target[:, 3] = rgbas[:, 3] - if brightness > 0: - alpha = self.shading_factor * brightness - return interpolate(rgbas, target, alpha) - else: - target[:, :3] = 0 - alpha = -self.shading_factor * brightness - return interpolate(rgbas, target, alpha) - - def get_unit_normal_vect(self, vmobject): - anchors = vmobject.get_anchors() - if len(anchors) < 3: - return OUT - normal = np.cross(anchors[1] - anchors[0], anchors[2] - anchors[1]) - if normal[2] < 0: - normal = -normal - length = np.linalg.norm(normal) - if length == 0: - return OUT - return normal / length - def display_multiple_vectorized_mobjects(self, vmobjects, pixel_array): - # camera_point = self.spherical_coords_to_point( - # *self.get_spherical_coords() - # ) + rot_matrix = self.get_rotation_matrix() def z_key(vmob): # Assign a number to a three dimensional mobjects # based on how close it is to the camera - three_d_status = should_shade_in_3d(vmob) - has_points = vmob.get_num_points() > 0 - if three_d_status and has_points: - return vmob.get_center()[2] + if isinstance(vmob, ThreeDVMobject): + return np.dot( + vmob.get_center(), + rot_matrix.T + )[2] else: - return 0 - MovingCamera.display_multiple_vectorized_mobjects( + return np.inf + Camera.display_multiple_vectorized_mobjects( self, sorted(vmobjects, key=z_key), pixel_array ) - def get_spherical_coords(self, phi=None, theta=None, distance=None): - curr_phi, curr_theta, curr_d = self.rotation_mobject.points[0] - if phi is None: - phi = curr_phi - if theta is None: - theta = curr_theta - if distance is None: - distance = curr_d - return np.array([phi, theta, distance]) - - def get_cartesian_coords(self, phi=None, theta=None, distance=None): - spherical_coords_array = self.get_spherical_coords( - phi, theta, distance) - phi2 = spherical_coords_array[0] - theta2 = spherical_coords_array[1] - d2 = spherical_coords_array[2] - return self.spherical_coords_to_point(phi2, theta2, d2) - def get_phi(self): - return self.get_spherical_coords()[0] + return self.phi_tracker.get_value() def get_theta(self): - return self.get_spherical_coords()[1] + return self.theta_tracker.get_value() def get_distance(self): - return self.get_spherical_coords()[2] + return self.distance_tracker.get_value() - def spherical_coords_to_point(self, phi, theta, distance): - return distance * np.array([ - np.sin(phi) * np.cos(theta), - np.sin(phi) * np.sin(theta), - np.cos(phi) - ]) - - def get_center_of_rotation(self, x=None, y=None, z=None): - curr_x, curr_y, curr_z = self.moving_center.points[0] - if x is None: - x = curr_x - if y is None: - y = curr_y - if z is None: - z = curr_z - return np.array([x, y, z]) - - def set_position(self, phi=None, theta=None, distance=None, - center_x=None, center_y=None, center_z=None): - point = self.get_spherical_coords(phi, theta, distance) - self.rotation_mobject.move_to(point) - self.phi, self.theta, self.distance = point - center_of_rotation = self.get_center_of_rotation( - center_x, center_y, center_z) - self.moving_center.move_to(center_of_rotation) - self.frame_center = self.moving_center.points[0] - - def get_view_transformation_matrix(self): - return (self.default_distance / self.get_distance()) * np.dot( - rotation_matrix(self.get_phi(), LEFT), - rotation_about_z(-self.get_theta() - np.pi / 2), - ) - - def transform_points_pre_display(self, points): - matrix = self.get_view_transformation_matrix() - return np.dot(points, matrix.T) + def get_gamma(self): + return self.gamma_tracker.get_value() def get_frame_center(self): - return self.moving_center.points[0] \ No newline at end of file + return self.frame_center.points[0] + + def set_phi(self, value): + self.phi_tracker.set_value(value) + + def set_theta(self, value): + self.theta_tracker.set_value(value) + + def set_distance(self, value): + self.distance_tracker.set_value(value) + + def set_gamma(self, value): + self.gamma_tracker.set_value(value) + + def set_frame_center(self, point): + self.frame_center.move_to(point) + + def reset_rotation_matrix(self): + self.rotation_matrix = self.generate_rotation_matrix() + + def get_rotation_matrix(self): + return self.rotation_matrix + + def generate_rotation_matrix(self): + phi = self.get_phi() + theta = self.get_theta() + gamma = self.get_gamma() + matrices = [ + rotation_about_z(-theta - 90 * DEGREES), + rotation_matrix(-phi, RIGHT), + rotation_about_z(gamma), + ] + result = np.identity(3) + for matrix in matrices: + result = np.dot(matrix, result) + return result + + def transform_points_pre_display(self, points): + fc = self.get_frame_center() + distance = self.get_distance() + points -= fc + rot_matrix = self.get_rotation_matrix() + points = np.dot(points, rot_matrix.T) + zs = points[:, 2] + points[:, 0] *= (distance + zs) / distance + points[:, 1] *= (distance + zs) / distance + points += fc + return points diff --git a/constants.py b/constants.py index 1e7ef223..215c3b5c 100644 --- a/constants.py +++ b/constants.py @@ -135,12 +135,13 @@ for folder in [FILE_DIR, RASTER_IMAGE_DIR, SVG_IMAGE_DIR, ANIMATIONS_DIR, TEX_DI os.makedirs(folder) TEX_TEXT_TO_REPLACE = "YourTextHere" -TEMPLATE_TEX_FILE = os.path.join(THIS_DIR, "template.tex") -TEMPLATE_TEXT_FILE = os.path.join(THIS_DIR, "text_template.tex") +TEMPLATE_TEX_FILE = os.path.join(THIS_DIR, "tex_template.tex") with open(TEMPLATE_TEX_FILE, "r") as infile: - TEMPLATE_TEX_FILE_BODY = infile.read() -with open(TEMPLATE_TEXT_FILE, "r") as infile: TEMPLATE_TEXT_FILE_BODY = infile.read() + TEMPLATE_TEX_FILE_BODY = TEMPLATE_TEXT_FILE_BODY.replace( + TEX_TEXT_TO_REPLACE, + "$${}$$".format(TEX_TEXT_TO_REPLACE) + ) FFMPEG_BIN = "ffmpeg" diff --git a/continual_animation/update.py b/continual_animation/update.py index a72d471a..8db3f871 100644 --- a/continual_animation/update.py +++ b/continual_animation/update.py @@ -5,7 +5,7 @@ from animation.update import MaintainPositionRelativeTo from mobject.value_tracker import ValueTracker -class ContinualUpdateFromFunc(ContinualAnimation): +class ContinualUpdate(ContinualAnimation): CONFIG = { "function_depends_on_dt": False } @@ -21,7 +21,7 @@ class ContinualUpdateFromFunc(ContinualAnimation): self.func(self.mobject) -class ContinualUpdateFromTimeFunc(ContinualUpdateFromFunc): +class ContinualUpdateFromTimeFunc(ContinualUpdate): CONFIG = { "function_depends_on_dt": True } diff --git a/for_3b1b_videos/common_scenes.py b/for_3b1b_videos/common_scenes.py index a2155415..ab3f1d66 100644 --- a/for_3b1b_videos/common_scenes.py +++ b/for_3b1b_videos/common_scenes.py @@ -255,6 +255,7 @@ class LogoGenerationTemplate(MovingCameraScene): name = TextMobject("3Blue1Brown") name.scale(2.5) name.next_to(self.logo, DOWN, buff=MED_LARGE_BUFF) + name.set_sheen(-0.2, DR) self.channel_name = name def construct(self): diff --git a/for_3b1b_videos/pi_creature.py b/for_3b1b_videos/pi_creature.py index 18613ea7..8c45e1e0 100644 --- a/for_3b1b_videos/pi_creature.py +++ b/for_3b1b_videos/pi_creature.py @@ -15,6 +15,7 @@ from animation.transform import Transform from utils.config_ops import digest_config from utils.rate_functions import squish_rate_func from utils.rate_functions import there_and_back +from utils.space_ops import get_norm PI_CREATURE_DIR = os.path.join(MEDIA_DIR, "designs", "PiCreature") PI_CREATURE_SCALE_FACTOR = 0.5 @@ -144,7 +145,7 @@ class PiCreature(SVGMobject): return self.mode def look(self, direction): - norm = np.linalg.norm(direction) + norm = get_norm(direction) if norm == 0: return direction /= norm @@ -154,7 +155,7 @@ class PiCreature(SVGMobject): right = eye.get_right() - c up = eye.get_top() - c vect = direction[0] * right + direction[1] * up - v_norm = np.linalg.norm(vect) + v_norm = get_norm(vect) p_radius = 0.5 * pupil.get_width() vect *= (v_norm - 0.75 * p_radius) / v_norm pupil.move_to(c + vect) diff --git a/for_3b1b_videos/pi_creature_scene.py b/for_3b1b_videos/pi_creature_scene.py index bcef0735..da846f74 100644 --- a/for_3b1b_videos/pi_creature_scene.py +++ b/for_3b1b_videos/pi_creature_scene.py @@ -24,6 +24,7 @@ from for_3b1b_videos.pi_creature_animations import RemovePiCreatureBubble from scene.scene import Scene from utils.rate_functions import squish_rate_func from utils.rate_functions import there_and_back +from utils.space_ops import get_norm class PiCreatureScene(Scene): @@ -353,7 +354,7 @@ class TeacherStudentsScene(PiCreatureScene): def func(point): centered = point + vect - return radius * centered / np.linalg.norm(centered) + return radius * centered / get_norm(centered) self.play(*[ ApplyPointwiseFunction(func, mob) for mob in self.get_mobjects() diff --git a/mobject/geometry.py b/mobject/geometry.py index c3d4ac85..132aea98 100644 --- a/mobject/geometry.py +++ b/mobject/geometry.py @@ -16,6 +16,7 @@ from utils.space_ops import angle_of_vector from utils.space_ops import center_of_mass from utils.space_ops import compass_directions from utils.space_ops import rotate_vector +from utils.space_ops import get_norm class Arc(VMobject): @@ -115,7 +116,7 @@ class ArcBetweenPoints(Arc): midpoint = 0.5 * (start_point + end_point) distance_vector = end_point - start_point normal_vector = np.array([-distance_vector[1], distance_vector[0], 0]) - distance = np.linalg.norm(normal_vector) + distance = get_norm(normal_vector) normal_vector /= distance if angle < 0: normal_vector *= -1 @@ -249,7 +250,7 @@ class AnnularSector(VMobject): first_point = self.points[0] last_point = self.points[-2] v = last_point - first_point - radial_unit_vector = v / np.linalg.norm(v) + radial_unit_vector = v / get_norm(v) arc_center = first_point - self.inner_radius * radial_unit_vector return arc_center @@ -350,13 +351,13 @@ class Line(VMobject): def get_length(self): start, end = self.get_start_and_end() - return np.linalg.norm(start - end) + return get_norm(start - end) def get_arc_length(self): if self.path_arc: anchors = self.get_anchors() return sum([ - np.linalg.norm(a2 - a1) + get_norm(a2 - a1) for a1, a2 in zip(anchors, anchors[1:]) ]) else: @@ -370,7 +371,7 @@ class Line(VMobject): def get_unit_vector(self): vect = self.get_vector() - norm = np.linalg.norm(vect) + norm = get_norm(vect) if norm == 0: # TODO, is this the behavior I want? return np.array(ORIGIN) @@ -409,11 +410,11 @@ class Line(VMobject): def put_start_and_end_on_with_projection(self, new_start, new_end): target_vect = np.array(new_end) - np.array(new_start) curr_vect = self.get_vector() - curr_norm = np.linalg.norm(curr_vect) + curr_norm = get_norm(curr_vect) if curr_norm == 0: self.put_start_and_end_on(new_start, new_end) return - target_norm = np.linalg.norm(target_vect) + target_norm = get_norm(target_vect) if target_norm == 0: epsilon = 0.001 self.scale(epsilon / curr_norm) @@ -422,7 +423,7 @@ class Line(VMobject): unit_target = target_vect / target_norm unit_curr = curr_vect / curr_norm normal = np.cross(unit_target, unit_curr) - if np.linalg.norm(normal) == 0: + if get_norm(normal) == 0: if unit_curr[0] == 0 and unit_curr[1] == 0: normal = UP else: @@ -446,7 +447,7 @@ class DashedLine(Line): Line.__init__(self, *args, **kwargs) def generate_points(self): - length = np.linalg.norm(self.end - self.start) + length = get_norm(self.end - self.start) if length == 0: self.add(Line(self.start, self.end)) return self @@ -541,7 +542,7 @@ class Arrow(Line): tip_base = center_of_mass(tip_base_points) tbp1, tbp2 = tip_base_points perp_vect = tbp2 - tbp1 - tip_base_width = np.linalg.norm(perp_vect) + tip_base_width = get_norm(perp_vect) if tip_base_width > 0: perp_vect /= tip_base_width width = min( @@ -573,7 +574,7 @@ class Arrow(Line): normal_vector = self.get_normal_vector() else: normal_vector = self.normal_vector - line_length = np.linalg.norm(self.points[-1] - self.points[0]) + line_length = get_norm(self.points[-1] - self.points[0]) tip_length = min( tip_length, self.max_tip_length_to_length_ratio * line_length ) @@ -586,9 +587,9 @@ class Arrow(Line): vect = end_point - pre_end_point perp_vect = np.cross(vect, normal_vector) for v in vect, perp_vect: - if np.linalg.norm(v) == 0: + if get_norm(v) == 0: v[0] = 1 - v *= tip_length / np.linalg.norm(v) + v *= tip_length / get_norm(v) ratio = self.tip_width_to_length_ratio tip.set_points_as_corners([ end_point, @@ -601,7 +602,7 @@ class Arrow(Line): def get_normal_vector(self): p0, p1, p2 = self.tip[0].get_anchors() result = np.cross(p2 - p1, p1 - p0) - norm = np.linalg.norm(result) + norm = get_norm(result) if norm == 0: return self.normal_vector else: diff --git a/mobject/mobject.py b/mobject/mobject.py index 75232f96..2bb4327c 100644 --- a/mobject/mobject.py +++ b/mobject/mobject.py @@ -21,6 +21,7 @@ from utils.space_ops import angle_of_vector from utils.space_ops import complex_to_R3 from utils.space_ops import rotation_matrix from utils.simple_functions import get_num_args +from utils.space_ops import get_norm from functools import reduce @@ -398,7 +399,7 @@ class Mobject(Container): target_point = mob.get_critical_point(direction) else: target_point = mobject_or_point - direction_norm = np.linalg.norm(direction) + direction_norm = get_norm(direction) if direction_norm > 0: alignment_vect = np.array(direction) / direction_norm reference_point = self.get_critical_point(direction) @@ -506,7 +507,7 @@ class Mobject(Container): if np.all(curr_vect == 0): raise Exception("Cannot position endpoints of closed loop") target_vect = end - start - self.scale(np.linalg.norm(target_vect) / np.linalg.norm(curr_vect)) + self.scale(get_norm(target_vect) / get_norm(curr_vect)) self.rotate( angle_of_vector(target_vect) - angle_of_vector(curr_vect) @@ -599,7 +600,7 @@ class Mobject(Container): center = self.get_center() for mob in self.family_members_with_points(): - t = np.linalg.norm(mob.get_center() - center) / radius + t = get_norm(mob.get_center() - center) / radius t = min(t, 1) mob_color = interpolate_color(inner_color, outer_color, t) mob.set_color(mob_color, family=False) @@ -681,12 +682,13 @@ class Mobject(Container): ] def get_merged_array(self, array_attr): - result = None - for mob in self.family_members_with_points(): - if result is None: - result = getattr(mob, array_attr) - else: - result = np.append(result, getattr(mob, array_attr), 0) + result = getattr(self, array_attr) + for submob in self.submobjects: + result = np.append( + result, submob.get_merged_array(array_attr), + axis=0 + ) + submob.get_merged_array(array_attr) return result def get_all_points(self): @@ -702,18 +704,19 @@ class Mobject(Container): def get_critical_point(self, direction): result = np.zeros(self.dim) + all_points = self.get_all_points() for dim in range(self.dim): if direction[dim] <= 0: - min_point = self.reduce_across_dimension(np.min, np.min, dim) + min_val = np.min(all_points[:, dim]) if direction[dim] >= 0: - max_point = self.reduce_across_dimension(np.max, np.max, dim) + max_val = np.max(all_points[:, dim]) if direction[dim] == 0: - result[dim] = (max_point + min_point) / 2 + result[dim] = (max_val + min_val) / 2 elif direction[dim] < 0: - result[dim] = min_point + result[dim] = min_val else: - result[dim] = max_point + result[dim] = max_val return result # Pseudonyms for more general get_critical_point method @@ -816,11 +819,11 @@ class Mobject(Container): if n_rows is not None: v1 = RIGHT v2 = DOWN - n = len(submobs) / n_rows + n = len(submobs) // n_rows elif n_cols is not None: v1 = DOWN v2 = RIGHT - n = len(submobs) / n_cols + n = len(submobs) // n_cols Group(*[ Group(*submobs[i:i + n]).arrange_submobjects(v1, **kwargs) for i in range(0, len(submobs), n) @@ -829,7 +832,7 @@ class Mobject(Container): def sort_submobjects(self, point_to_num_func=lambda p: p[0]): self.submobjects.sort( - key=lambda m: point_to_num_func(mob.get_center()) + key=lambda m: point_to_num_func(m.get_center()) ) return self diff --git a/mobject/number_line.py b/mobject/number_line.py index eae38b99..c28868b9 100644 --- a/mobject/number_line.py +++ b/mobject/number_line.py @@ -9,6 +9,7 @@ from mobject.geometry import Arrow from mobject.geometry import Line from utils.bezier import interpolate from utils.config_ops import digest_config +from utils.space_ops import get_norm class NumberLine(VMobject): @@ -99,7 +100,7 @@ class NumberLine(VMobject): 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 np.dot(p - left_point, full_vect) / get_norm(full_vect) return interpolate( self.x_min, self.x_max, @@ -141,7 +142,7 @@ class NumberLine(VMobject): def add_tip(self): start, end = self.main_line.get_start_and_end() - vect = (end - start) / np.linalg.norm(end - start) + vect = (end - start) / get_norm(end - start) arrow = Arrow(start, end + MED_SMALL_BUFF * vect, buff=0) tip = arrow.tip tip.set_color(self.color) diff --git a/mobject/svg/brace.py b/mobject/svg/brace.py index 02ac8947..2c2a4551 100644 --- a/mobject/svg/brace.py +++ b/mobject/svg/brace.py @@ -11,6 +11,7 @@ from mobject.svg.tex_mobject import TexMobject from mobject.svg.tex_mobject import TextMobject from mobject.types.vectorized_mobject import VMobject from utils.config_ops import digest_config +from utils.space_ops import get_norm class Brace(TexMobject): @@ -75,7 +76,7 @@ class Brace(TexMobject): def get_direction(self): vect = self.get_tip() - self.get_center() - return vect / np.linalg.norm(vect) + return vect / get_norm(vect) class BraceLabel(VMobject): diff --git a/mobject/three_dimensions.py b/mobject/three_dimensions.py index a7a9bf4f..bdfd6e2a 100644 --- a/mobject/three_dimensions.py +++ b/mobject/three_dimensions.py @@ -3,34 +3,171 @@ from constants import * from mobject.types.vectorized_mobject import VMobject +from mobject.types.vectorized_mobject import VGroup from mobject.geometry import Square +from utils.config_ops import digest_config from utils.space_ops import z_to_vector +from utils.space_ops import get_unit_normal ############## -def should_shade_in_3d(mobject): - return hasattr(mobject, "shade_in_3d") and mobject.shade_in_3d +class ThreeDVMobject(VMobject): + CONFIG = {} + + def __init__(self, vmobject=None, **kwargs): + VMobject.__init__(self, **kwargs) + if vmobject is not None: + self.points = np.array(vmobject.points) + self.match_style(vmobject) + self.submobjects = map( + ThreeDVMobject, vmobject.submobjects + ) + + def get_gradient_start_and_end_points(self): + return self.get_start_corner(), self.get_end_corner() + + def get_start_corner_index(self): + return 0 + + def get_end_corner_index(self): + return ((len(self.points) - 1) // 6) * 3 + # return ((len(self.points) - 1) // 12) * 3 + + def get_start_corner(self): + if self.get_num_points() == 0: + return np.array(ORIGIN) + return self.points[self.get_start_corner_index()] + + def get_end_corner(self): + if self.get_num_points() == 0: + return np.array(ORIGIN) + return self.points[self.get_end_corner_index()] + + def get_unit_normal(self, point_index): + n_points = self.get_num_points() + if self.get_num_points() == 0: + return np.array(ORIGIN) + i = point_index + im1 = i - 1 if i > 0 else (n_points - 2) + ip1 = i + 1 if i < (n_points - 1) else 1 + return get_unit_normal( + self.points[ip1] - self.points[i], + self.points[im1] - self.points[i], + ) + + def get_start_corner_unit_normal(self): + return self.get_unit_normal( + self.get_start_corner_index() + ) + + def get_end_corner_unit_normal(self): + return self.get_unit_normal( + self.get_end_corner_index() + ) -def shade_in_3d(mobject): - for submob in mobject.submobject_family(): - submob.shade_in_3d = True +class ParametricSurface(VGroup): + CONFIG = { + "u_min": 0, + "u_max": 1, + "v_min": 0, + "v_max": 1, + "resolution": 32, + "u_resolution": None, + "v_resolution": None, + "surface_piece_config": {}, + "fill_color": BLUE_D, + "fill_opacity": 1.0, + "checkerboard_colors": [BLUE_D, BLUE_E], + "stroke_color": LIGHT_GREY, + "stroke_width": 0.5, + "should_make_jagged": False, + } + + def __init__(self, func, **kwargs): + VGroup.__init__(self, **kwargs) + self.setup_in_uv_space() + self.apply_function(lambda p: func(p[0], p[1])) + if self.should_make_jagged: + self.make_jagged() + + def setup_in_uv_space(self): + u_min = self.u_min + u_max = self.u_max + u_res = self.u_resolution or self.resolution + v_min = self.v_min + v_max = self.v_max + v_res = self.v_resolution or self.resolution + + u_values = np.linspace(u_min, u_max, u_res + 1) + v_values = np.linspace(v_min, v_max, v_res + 1) + faces = VGroup() + for u1, u2 in zip(u_values[:-1], u_values[1:]): + for v1, v2 in zip(v_values[:-1], v_values[1:]): + piece = ThreeDVMobject() + piece.set_points_as_corners([ + [u1, v1, 0], + [u2, v1, 0], + [u2, v2, 0], + [u1, v2, 0], + [u1, v1, 0], + ]) + faces.add(piece) + faces.set_fill( + color=self.fill_color, + opacity=self.fill_opacity + ) + faces.set_stroke( + color=self.stroke_color, + width=self.stroke_width, + opacity=self.stroke_opacity, + ) + self.add(*faces) + if self.checkerboard_colors: + self.set_fill_by_checkerboard(*self.checkerboard_colors) + + def set_fill_by_checkerboard(self, color1, color2): + u_res = self.u_resolution or self.resolution + v_res = self.v_resolution or self.resolution + for i in range(u_res): + for j in range(v_res): + face = self[i * v_res + j] + if (i + j) % 2 == 0: + face.set_fill(color1) + else: + face.set_fill(color2) -def turn_off_3d_shading(mobject): - for submob in mobject.submobject_family(): - submob.shade_in_3d = False +# Specific shapes -class ThreeDMobject(VMobject): - def __init__(self, *args, **kwargs): - VMobject.__init__(self, *args, **kwargs) - shade_in_3d(self) +class Sphere(ParametricSurface): + CONFIG = { + "resolution": 12, + "radius": 3, + "u_min": 0.001, + } + + def __init__(self, **kwargs): + digest_config(self, kwargs) + kwargs["u_resolution"] = self.u_resolution or self.resolution + kwargs["v_resolution"] = self.u_resolution or 2 * self.resolution + ParametricSurface.__init__( + self, self.func, **kwargs + ) + self.scale(self.radius) + + def func(self, u, v): + return np.array([ + np.cos(TAU * v) * np.sin(PI * u), + np.sin(TAU * v) * np.sin(PI * u), + np.cos(PI * u) + ]) -class Cube(ThreeDMobject): +class Cube(VGroup): CONFIG = { "fill_opacity": 0.75, "fill_color": BLUE, @@ -41,9 +178,13 @@ class Cube(ThreeDMobject): def generate_points(self): for vect in IN, OUT, LEFT, RIGHT, UP, DOWN: - face = Square(side_length=self.side_length) + face = ThreeDVMobject( + Square(side_length=self.side_length) + ) + face.make_jagged() + face.flip() face.shift(self.side_length * OUT / 2.0) - face.apply_function(lambda p: np.dot(p, z_to_vector(vect).T)) + face.apply_matrix(z_to_vector(vect)) self.add(face) diff --git a/mobject/types/point_cloud_mobject.py b/mobject/types/point_cloud_mobject.py index 6677501c..148dd940 100644 --- a/mobject/types/point_cloud_mobject.py +++ b/mobject/types/point_cloud_mobject.py @@ -9,6 +9,7 @@ from utils.color import color_to_rgba from utils.color import rgba_to_color from utils.config_ops import digest_config from utils.iterables import stretch_array_to_length +from utils.space_ops import get_norm class PMobject(Mobject): @@ -185,7 +186,7 @@ class Mobject1D(PMobject): def add_line(self, start, end, color=None): start, end = list(map(np.array, [start, end])) - length = np.linalg.norm(end - start) + length = get_norm(end - start) if length == 0: points = [start] else: diff --git a/mobject/types/vectorized_mobject.py b/mobject/types/vectorized_mobject.py index f62df6a9..0a277713 100644 --- a/mobject/types/vectorized_mobject.py +++ b/mobject/types/vectorized_mobject.py @@ -67,17 +67,14 @@ class VMobject(Mobject): opacity=self.background_stroke_opacity, family=self.propagate_style_to_family, ) - self.set_sheen_direction( - self.sheen_direction, - family=self.propagate_style_to_family - ) self.set_sheen( - self.sheen, + factor=self.sheen, + direction=self.sheen_direction, family=self.propagate_style_to_family ) return self - def get_rgbas_array(self, color, opacity): + def generate_rgbas_array(self, color, opacity): """ First arg can be either a color, or a tuple/list of colors. Likewise, opacity can either be a float, or a tuple of floats. @@ -103,7 +100,7 @@ class VMobject(Mobject): def update_rgbas_array(self, array_name, color=None, opacity=None): passed_color = color or BLACK passed_opacity = opacity or 0 - rgbas = self.get_rgbas_array(passed_color, passed_opacity) + rgbas = self.generate_rgbas_array(passed_color, passed_opacity) if not hasattr(self, array_name): setattr(self, array_name, rgbas) return self @@ -111,10 +108,12 @@ class VMobject(Mobject): # one. 99% of the time they'll be the same. curr_rgbas = getattr(self, array_name) if len(curr_rgbas) < len(rgbas): - curr_rgbas = stretch_array_to_length(len(rgbas)) + curr_rgbas = stretch_array_to_length( + curr_rgbas, len(rgbas) + ) setattr(self, array_name, curr_rgbas) elif len(rgbas) < len(curr_rgbas): - rgbas = stretch_array_to_length(len(curr_rgbas)) + rgbas = stretch_array_to_length(rgbas, len(curr_rgbas)) # Only update rgb if color was not None, and only # update alpha channel if opacity was passed in if color is not None: @@ -257,14 +256,19 @@ class VMobject(Mobject): self.sheen_direction = direction return self - def set_sheen(self, factor, family=True): + def set_sheen(self, factor, direction=None, family=True): if family: - for submob in self.submobject_family(): - submob.sheen = factor - else: - self.sheen = factor - self.set_stroke(self.get_stroke_color(), family=family) - self.set_fill(self.get_fill_color(), family=family) + for submob in self.submobjects: + submob.set_sheen(factor, direction, family) + self.sheen = factor + if direction is not None: + # family set to false because recursion will + # already be handled above + self.set_sheen_direction(direction, family=False) + # Reset color to put sheen into effect + if factor != 0: + self.set_stroke(self.get_stroke_color(), family=family) + self.set_fill(self.get_fill_color(), family=family) return self def get_sheen_direction(self): @@ -281,7 +285,7 @@ class VMobject(Mobject): for vect in [RIGHT, UP, OUT] ]).transpose() offset = np.dot(bases, direction) - return (c + offset, c - offset) + return (c - offset, c + offset) def color_using_background_image(self, background_image_file): self.background_image_file = background_image_file @@ -363,7 +367,7 @@ class VMobject(Mobject): def change_anchor_mode(self, mode): for submob in self.family_members_with_points(): - anchors, h1, h2 = submob.get_anchors_and_handles() + anchors = submob.get_anchors() submob.set_anchor_points(anchors, mode=mode) return self @@ -423,15 +427,14 @@ class VMobject(Mobject): handles closer to their anchors, apply the function then push them out again. """ - if self.get_num_points() == 0: - return - anchors, handles1, handles2 = self.get_anchors_and_handles() - # print len(anchors), len(handles1), len(handles2) - a_to_h1 = handles1 - anchors[:-1] - a_to_h2 = handles2 - anchors[1:] - handles1 = anchors[:-1] + factor * a_to_h1 - handles2 = anchors[1:] + factor * a_to_h2 - self.set_anchors_and_handles(anchors, handles1, handles2) + for submob in self.family_members_with_points(): + anchors, handles1, handles2 = submob.get_anchors_and_handles() + # print len(anchors), len(handles1), len(handles2) + a_to_h1 = handles1 - anchors[:-1] + a_to_h2 = handles2 - anchors[1:] + handles1 = anchors[:-1] + factor * a_to_h1 + handles2 = anchors[1:] + factor * a_to_h2 + submob.set_anchors_and_handles(anchors, handles1, handles2) # Information about line diff --git a/mobject/value_tracker.py b/mobject/value_tracker.py index 7c8ee584..18450868 100644 --- a/mobject/value_tracker.py +++ b/mobject/value_tracker.py @@ -1,15 +1,11 @@ - import numpy as np -from constants import * - -from mobject.types.vectorized_mobject import VectorizedPoint - -# TODO: Rather than using VectorizedPoint, there should be some UndisplayedPointSet type +from mobject.mobject import Mobject +from utils.bezier import interpolate -class ValueTracker(VectorizedPoint): +class ValueTracker(Mobject): """ Note meant to be displayed. Instead the position encodes some number, often one which another animation or continual_animation @@ -18,14 +14,15 @@ class ValueTracker(VectorizedPoint): """ def __init__(self, value=0, **kwargs): - VectorizedPoint.__init__(self, **kwargs) + Mobject.__init__(self, **kwargs) + self.points = np.zeros((1, 3)) self.set_value(value) def get_value(self): - return self.get_center()[0] + return self.points[0, 0] def set_value(self, value): - self.move_to(value * RIGHT) + self.points[0, 0] = value return self def increment_value(self, d_value): @@ -40,8 +37,7 @@ class ExponentialValueTracker(ValueTracker): """ def get_value(self): - return np.exp(self.get_center()[0]) + return np.exp(ValueTracker.get_value(self)) def set_value(self, value): - self.move_to(np.log(value) * RIGHT) - return self + return ValueTracker.set_value(self, np.log(value)) diff --git a/old_projects/256.py b/old_projects/256.py index e62bf871..f7caecd2 100644 --- a/old_projects/256.py +++ b/old_projects/256.py @@ -819,7 +819,7 @@ class QAndA(PiCreatureScene): dots = VGroup(*it.chain(*dots)) top = dots.get_top() dots.sort_submobjects( - lambda p : np.linalg.norm(p-top) + lambda p : get_norm(p-top) ) powers_of_two = VGroup(*[ diff --git a/old_projects/WindingNumber_G.py b/old_projects/WindingNumber_G.py index c9ce16ce..769b55dd 100644 --- a/old_projects/WindingNumber_G.py +++ b/old_projects/WindingNumber_G.py @@ -722,7 +722,7 @@ class InputOutputScene(Scene): def func(self, coord_pair): out_coords = np.array(self.non_renormalized_func(coord_pair)) - out_norm = np.linalg.norm(out_coords) + out_norm = get_norm(out_coords) if out_norm > 1: angle = angle_of_vector(out_coords) factor = 0.5-0.1*np.cos(4*angle) @@ -964,7 +964,7 @@ class IntroduceInputOutputScene(InputOutputScene): return dots def get_output_dot_continual_update(self, input_dot, output_dot): - return ContinualUpdateFromFunc( + return ContinualUpdate( output_dot, lambda od : od.move_to(self.point_function(input_dot.get_center())) ) @@ -992,7 +992,7 @@ class IntroduceVectorField(IntroduceInputOutputScene): color = out_dot.get_color(), ) out_vector.set_stroke(BLACK, 1) - continual_out_vector_update = ContinualUpdateFromFunc( + continual_out_vector_update = ContinualUpdate( out_vector, lambda ov : ov.put_start_and_end_on( output_plane.coords_to_point(0, 0), out_dot.get_center(), @@ -1004,7 +1004,7 @@ class IntroduceVectorField(IntroduceInputOutputScene): Transform(in_vector, out_vector).update(1) in_vector.scale(0.5) in_vector.shift(in_dot.get_center() - in_vector.get_start()) - continual_in_vector_update = ContinualUpdateFromFunc( + continual_in_vector_update = ContinualUpdate( in_vector, update_in_vector ) continual_updates = [ @@ -2305,7 +2305,7 @@ class TransitionFromPathsToBoundaries(ColorMappedObjectsScene): #Setup dot, arrow and label dot = self.dot = Dot(radius = 0.1) dot.set_stroke(WHITE, self.dot_stroke_width) - update_dot_color = ContinualUpdateFromFunc( + update_dot_color = ContinualUpdate( dot, lambda d : d.set_fill( get_output_color(), self.dot_fill_opacity @@ -2327,7 +2327,7 @@ class TransitionFromPathsToBoundaries(ColorMappedObjectsScene): arrow.scale(arrow_length/arrow.get_length()) arrow.shift(dot.get_center() - arrow.get_start()) return arrow - update_arrow = ContinualUpdateFromFunc(arrow, arrow_update_func) + update_arrow = ContinualUpdate(arrow, arrow_update_func) if self.include_walkers: self.add(update_arrow, update_dot_color, label_upadte) @@ -2796,27 +2796,27 @@ class WindingNumbersInInputOutputContext(PathContainingZero): out_loop = in_loop.copy() out_loop.match_background_image_file(self.output_coloring) - update_out_loop = ContinualUpdateFromFunc( + update_out_loop = ContinualUpdate( out_loop, lambda m : m.set_points(in_loop.points).apply_function(self.point_function) ) # self.add(update_out_loop) in_dot = Dot(radius = 0.04) - update_in_dot = ContinualUpdateFromFunc( + update_in_dot = ContinualUpdate( in_dot, lambda d : d.move_to(in_loop.point_from_proportion(1)) ) self.add(update_in_dot) out_arrow = Arrow(LEFT, RIGHT) - update_out_arrow = ContinualUpdateFromFunc( + update_out_arrow = ContinualUpdate( out_arrow, lambda a : a.put_start_and_end_on( self.output_plane.coords_to_point(0, 0), out_loop.point_from_proportion(1) ) ) - update_out_arrow_color = ContinualUpdateFromFunc( + update_out_arrow_color = ContinualUpdate( out_arrow, lambda a : a.set_color(rev_to_color(a.get_angle()/TAU)) ) @@ -2974,7 +2974,7 @@ class TickingClock(Scene): line.set_color(rev_to_color(rev)) for line in lines: - self.add(ContinualUpdateFromFunc(line, update_line)) + self.add(ContinualUpdate(line, update_line)) run_time = self.run_time self.play(ClockPassesTime( @@ -3199,7 +3199,7 @@ class PatreonScroll(Scene): patrons.remove(patron) alpha = smooth(np.clip(2.5 - y, 0, 1)) patron.set_fill(opacity = alpha) - opacity_update = ContinualUpdateFromFunc(patrons, patrons_opacity_update) + opacity_update = ContinualUpdate(patrons, patrons_opacity_update) self.add(scroll, opacity_update) self.wait(55) diff --git a/old_projects/alt_calc.py b/old_projects/alt_calc.py index 57a14682..4e505573 100644 --- a/old_projects/alt_calc.py +++ b/old_projects/alt_calc.py @@ -707,14 +707,14 @@ class StartingCalc101(PiCreatureScene): tracker.get_value() + dt ) ), - ContinualUpdateFromFunc( + ContinualUpdate( spring, lambda s: s.stretch_to_fit_height( 1.5 + 0.5 * np.cos(3 * t_tracker.get_value()), about_edge=UP ) ), - ContinualUpdateFromFunc( + ContinualUpdate( weight, lambda w: w.move_to(spring.points[-1]) ) @@ -934,7 +934,7 @@ class ChangingVectorField(Scene): self.add(ContinualGrowValue(time_tracker)) vectors = self.get_vectors() - self.add(ContinualUpdateFromFunc( + self.add(ContinualUpdate( vectors, lambda vs: self.update_vectors(vs) )) @@ -957,7 +957,7 @@ class ChangingVectorField(Scene): for vector in vectors: point = vector.get_start() out_point = self.func(point, time) - norm = np.linalg.norm(out_point) + norm = get_norm(out_point) if norm == 0: out_point = RIGHT # Fake it vector.set_fill(opacity=0) @@ -1111,36 +1111,36 @@ class StandardDerivativeVisual(GraphScene): triangle.set_stroke(width=0) triangle.scale(0.1) - input_triangle_update = ContinualUpdateFromFunc( + input_triangle_update = ContinualUpdate( input_triangle, lambda m: m.move_to(get_x_point(), UP) ) - output_triangle_update = ContinualUpdateFromFunc( + output_triangle_update = ContinualUpdate( output_triangle, lambda m: m.move_to(get_y_point(), RIGHT) ) x_label = TexMobject("x") - x_label_update = ContinualUpdateFromFunc( + x_label_update = ContinualUpdate( x_label, lambda m: m.next_to(input_triangle, DOWN, SMALL_BUFF) ) output_label = TexMobject("f(x)") - output_label_update = ContinualUpdateFromFunc( + output_label_update = ContinualUpdate( output_label, lambda m: m.next_to( output_triangle, LEFT, SMALL_BUFF) ) v_line = get_v_line() - v_line_update = ContinualUpdateFromFunc( + v_line_update = ContinualUpdate( v_line, lambda vl: Transform(vl, get_v_line()).update(1) ) h_line = get_h_line() - h_line_update = ContinualUpdateFromFunc( + h_line_update = ContinualUpdate( h_line, lambda hl: Transform(hl, get_h_line()).update(1) ) graph_dot = Dot(color=YELLOW) - graph_dot_update = ContinualUpdateFromFunc( + graph_dot_update = ContinualUpdate( graph_dot, lambda m: m.move_to(get_graph_point()) ) @@ -1192,7 +1192,7 @@ class StandardDerivativeVisual(GraphScene): ).secant_line slope_line = get_slope_line() - slope_line_update = ContinualUpdateFromFunc( + slope_line_update = ContinualUpdate( slope_line, lambda sg: Transform(sg, get_slope_line()).update(1) ) @@ -1203,7 +1203,7 @@ class StandardDerivativeVisual(GraphScene): "\\frac{df}{dx}(x) =", "\\text{Slope}", "=" ) deriv_label.get_part_by_tex("Slope").match_color(slope_line) - deriv_label_update = ContinualUpdateFromFunc( + deriv_label_update = ContinualUpdate( deriv_label, position_deriv_label ) @@ -2999,7 +2999,7 @@ class AnalyzeFunctionWithTransformations(NumberlineTransformationScene): tip_length=0.15 ) for point in sample_points - if np.linalg.norm(point - input_zero_point) > 0.3 + if get_norm(point - input_zero_point) > 0.3 ]) for func in (point_func, alt_point_func) ] @@ -3241,7 +3241,7 @@ class StabilityAndInstability(AnalyzeFunctionWithTransformations): arrow_groups = VGroup() for point in phi_point, phi_bro_point: - arrows = VGroup(*[a for a in self.all_arrows if np.linalg.norm(a.get_start() - point) < 0.75]).copy() + arrows = VGroup(*[a for a in self.all_arrows if get_norm(a.get_start() - point) < 0.75]).copy() arrows.set_fill(PINK, 1) arrows.set_stroke(PINK, 3) arrows.second_anim = LaggedStart( @@ -3556,7 +3556,7 @@ class PrinciplesOverlay(PiCreatureScene): q_marks.next_to(morty, UP) q_marks.shift_onto_screen() q_marks.sort_submobjects( - lambda p: np.linalg.norm(p - morty.get_top()) + lambda p: get_norm(p - morty.get_top()) ) self.play(morty.change, "pondering") diff --git a/old_projects/basel/basel.py b/old_projects/basel/basel.py index 280b72e9..d0271542 100644 --- a/old_projects/basel/basel.py +++ b/old_projects/basel/basel.py @@ -141,7 +141,7 @@ class LightIndicator(VMobject): def measured_intensity(self): - distance = np.linalg.norm(self.get_measurement_point() - + distance = get_norm(self.get_measurement_point() - self.light_source.get_source_point()) intensity = self.light_source.opacity_function(distance) / self.opacity_for_unit_intensity return intensity @@ -1914,9 +1914,9 @@ class TwoLightSourcesScene(PiCreatureScene): SwitchOn(ls2.ambient_light) ) - distance1 = np.linalg.norm(C - ls1.get_source_point()) + distance1 = get_norm(C - ls1.get_source_point()) intensity = ls1.ambient_light.opacity_function(distance1) / indicator.opacity_for_unit_intensity - distance2 = np.linalg.norm(C - ls2.get_source_point()) + distance2 = get_norm(C - ls2.get_source_point()) intensity += ls2.ambient_light.opacity_function(distance2) / indicator.opacity_for_unit_intensity self.play( @@ -3051,9 +3051,9 @@ class PondScene(ThreeDScene): def right_angle(pointA, pointB, pointC, size = 1): v1 = pointA - pointB - v1 = size * v1/np.linalg.norm(v1) + v1 = size * v1/get_norm(v1) v2 = pointC - pointB - v2 = size * v2/np.linalg.norm(v2) + v2 = size * v2/get_norm(v2) P = pointB Q = pointB + v1 @@ -4473,9 +4473,9 @@ class RightAnglesOverlay(Scene): def right_angle(pointA, pointB, pointC, size = 1): v1 = pointA - pointB - v1 = size * v1/np.linalg.norm(v1) + v1 = size * v1/get_norm(v1) v2 = pointC - pointB - v2 = size * v2/np.linalg.norm(v2) + v2 = size * v2/get_norm(v2) P = pointB Q = pointB + v1 diff --git a/old_projects/basel/basel2.py b/old_projects/basel/basel2.py index cd01d8d9..af810076 100644 --- a/old_projects/basel/basel2.py +++ b/old_projects/basel/basel2.py @@ -120,7 +120,7 @@ class LightIndicator(Mobject): return self.get_center() def measured_intensity(self): - distance = np.linalg.norm( + distance = get_norm( self.get_measurement_point() - self.light_source.get_source_point() ) @@ -217,7 +217,7 @@ class ThreeDSpotlight(VGroup): corners = screen.get_anchors() self.submobjects = [VGroup() for a in screen.get_anchors()] - distance = np.linalg.norm( + distance = get_norm( screen.get_center() - source_point ) n_parts = np.ceil(distance/dr) @@ -1322,13 +1322,13 @@ class IntroduceScreen(Scene): def rotate_screen(self): self.add( - ContinualUpdateFromFunc( + ContinualUpdate( self.light_source, lambda m : m.update() ), ) self.add( - ContinualUpdateFromFunc( + ContinualUpdate( self.angle_indicator, lambda m : m.set_stroke(width = 0).set_fill(opacity = 1) ) @@ -1631,8 +1631,8 @@ class InverseSquareLaw(ThreeDScene): def update_spotlight(spotlight): spotlight.update_sectors() - spotlight_update = ContinualUpdateFromFunc(spotlight, update_spotlight) - shadow_update = ContinualUpdateFromFunc( + spotlight_update = ContinualUpdate(spotlight, update_spotlight) + shadow_update = ContinualUpdate( shadow, lambda m : light_source.update_shadow() ) @@ -1641,10 +1641,10 @@ class InverseSquareLaw(ThreeDScene): opacity_for_unit_intensity = 0.5, ) def update_light_indicator(light_indicator): - distance = np.linalg.norm(screen.get_reference_point() - source_point) + distance = get_norm(screen.get_reference_point() - source_point) light_indicator.set_intensity(1.0/(distance/unit_distance)**2) light_indicator.next_to(morty, UP, MED_LARGE_BUFF) - light_indicator_update = ContinualUpdateFromFunc( + light_indicator_update = ContinualUpdate( light_indicator, update_light_indicator ) light_indicator_update.update(0) @@ -1947,7 +1947,7 @@ class ManipulateLightsourceSetups(PiCreatureScene): ) light_indicator.move_to(bubble.get_bubble_center()) def update_light_indicator(light_indicator): - distance = np.linalg.norm(light_source.get_source_point()-observer_point) + distance = get_norm(light_source.get_source_point()-observer_point) light_indicator.set_intensity((unit_distance/distance)**2) #Light source @@ -1966,7 +1966,7 @@ class ManipulateLightsourceSetups(PiCreatureScene): self.add(light_source) self.add_foreground_mobjects(morty, bubble, light_indicator) - self.add(ContinualUpdateFromFunc(light_indicator, update_light_indicator)) + self.add(ContinualUpdate(light_indicator, update_light_indicator)) self.play( ApplyMethod( light_source.shift, 0.66*unit_distance*LEFT, @@ -2159,7 +2159,7 @@ class TwoLightSourcesScene(ManipulateLightsourceSetups): intensity = 0 for ls in lsA, lsB, lsC: if ls in self.mobjects: - distance = np.linalg.norm(ls.get_source_point() - origin_point) + distance = get_norm(ls.get_source_point() - origin_point) d_indensity = fdiv( 3./(distance**2), indicator.opacity_for_unit_intensity @@ -2167,16 +2167,16 @@ class TwoLightSourcesScene(ManipulateLightsourceSetups): d_indensity *= ls.ambient_light.submobjects[1].get_fill_opacity() intensity += d_indensity indicator.set_intensity(intensity) - indicator_update_anim = ContinualUpdateFromFunc(indicator, update_indicator) + indicator_update_anim = ContinualUpdate(indicator, update_indicator) new_indicator = indicator.copy() new_indicator.light_source = lsC new_indicator.measurement_point = C #Note sure what this is... - distance1 = np.linalg.norm(origin_point - lsA.get_source_point()) + distance1 = get_norm(origin_point - lsA.get_source_point()) intensity = lsA.ambient_light.opacity_function(distance1) / indicator.opacity_for_unit_intensity - distance2 = np.linalg.norm(origin_point - lsB.get_source_point()) + distance2 = get_norm(origin_point - lsB.get_source_point()) intensity += lsB.ambient_light.opacity_function(distance2) / indicator.opacity_for_unit_intensity # IPT Theorem @@ -2352,7 +2352,7 @@ class SimpleIPTProof(Scene): C = ORIGIN #Dumb and inefficient alphas = np.linspace(0, 1, 500) - i = np.argmin([np.linalg.norm(interpolate(A, B, a)) for a in alphas]) + i = np.argmin([get_norm(interpolate(A, B, a)) for a in alphas]) H = interpolate(A, B, alphas[i]) triangle = VGroup( Line(C, A, color = BLUE), @@ -2364,7 +2364,7 @@ class SimpleIPTProof(Scene): label = TexMobject(char) label.match_color(line) vect = line.get_center() - triangle.get_center() - vect /= np.linalg.norm(vect) + vect /= get_norm(vect) label.next_to(line.get_center(), vect) triangle.add(label) if char == "h": @@ -2581,8 +2581,8 @@ class IPTScene(TwoLightSourcesScene, ZoomedScene): source_point = spotlight.get_source_point() c1, c2 = spotlight.screen.get_start(), spotlight.screen.get_end() distance = max( - np.linalg.norm(c1 - source_point), - np.linalg.norm(c2 - source_point), + get_norm(c1 - source_point), + get_norm(c2 - source_point), ) n_parts = np.ceil(distance/dr) alphas = np.linspace(0, 1, n_parts+1) @@ -2613,7 +2613,7 @@ class IPTScene(TwoLightSourcesScene, ZoomedScene): ) spotlights = VGroup(spotlight_a, spotlight_b) - spotlights_update_anim = ContinualUpdateFromFunc( + spotlights_update_anim = ContinualUpdate( spotlights, update_spotlights ) @@ -2761,7 +2761,7 @@ class DiameterTheorem(TeacherStudentsScene): circle.get_left(), circle.get_right(), point.get_center(), circle.get_left(), ]) - triangle_update_anim = ContinualUpdateFromFunc( + triangle_update_anim = ContinualUpdate( triangle, update_triangle ) triangle_update_anim.update(0) @@ -2826,7 +2826,7 @@ class InscribedeAngleThreorem(TeacherStudentsScene): circle.point_from_proportion(1./8), point.get_center(), ]) - shape_update_anim = ContinualUpdateFromFunc( + shape_update_anim = ContinualUpdate( shape, update_shape ) shape_update_anim.update(0) @@ -2912,9 +2912,9 @@ class PondScene(ThreeDScene): def right_angle(pointA, pointB, pointC, size = 1): v1 = pointA - pointB - v1 = size * v1/np.linalg.norm(v1) + v1 = size * v1/get_norm(v1) v2 = pointC - pointB - v2 = size * v2/np.linalg.norm(v2) + v2 = size * v2/get_norm(v2) P = pointB Q = pointB + v1 @@ -3854,7 +3854,7 @@ class ThinkBackToHowAmazingThisIs(ThreeDScene): z = self.camera.rotation_mobject.get_center()[2] decimal.set_height(0.07*z) decimal.move_to(0.7*z*UP) - scale_decimal = ContinualUpdateFromFunc(decimal, update_decimal) + scale_decimal = ContinualUpdate(decimal, update_decimal) self.add(number_line, *dot_pairs) diff --git a/old_projects/bell.py b/old_projects/bell.py index d7cb1218..2cae31a5 100644 --- a/old_projects/bell.py +++ b/old_projects/bell.py @@ -291,7 +291,7 @@ class MoreFiltersMoreLight(FilterScene): def build_color_map(self, pfs): phi, theta = self.camera.get_phi(), self.camera.get_theta() - self.set_camera_position(np.pi/2, -np.pi) + self.set_camera_orientation(np.pi/2, -np.pi) self.original_rgbas = [(255, 255, 255)] self.new_rgbas = [self.arrow_rgb] @@ -317,7 +317,7 @@ class MoreFiltersMoreLight(FilterScene): self.new_rgbas.append(new_rgb) self.camera.reset() - self.set_camera_position(phi, theta) + self.set_camera_orientation(phi, theta) def update_frame(self, mobjects = None, image = None): FilterScene.update_frame(self, mobjects) @@ -1584,7 +1584,7 @@ class VennDiagramProofByContradiction(Scene): B_center = B.target.get_center() photons.sort_submobjects( - lambda p : np.linalg.norm(p-B_center) + lambda p : get_norm(p-B_center) ) in_B = VGroup(*photons[:85]) out_of_B = VGroup(*photons[85:]) @@ -1663,7 +1663,7 @@ class VennDiagramProofByContradiction(Scene): ) in_B.sort_submobjects( - lambda p : np.linalg.norm(p - C_center) + lambda p : get_norm(p - C_center) ) in_C = VGroup(*in_B[:-11]) out_of_C = VGroup(*in_B[-11:]) diff --git a/old_projects/brachistochrone/curves.py b/old_projects/brachistochrone/curves.py index 19cd05d5..79348ca7 100644 --- a/old_projects/brachistochrone/curves.py +++ b/old_projects/brachistochrone/curves.py @@ -139,7 +139,7 @@ class PathSlidingScene(Scene): self.slider, curr_index, points ) if roll: - distance = np.linalg.norm( + distance = get_norm( points[curr_index] - points[last_index] ) self.roll(mobject, distance) @@ -163,7 +163,7 @@ class PathSlidingScene(Scene): def get_time_slices(self, points, ceiling = None): dt_list = np.zeros(len(points)) ds_list = np.apply_along_axis( - np.linalg.norm, + get_norm, 1, points[1:]-points[:-1] ) @@ -471,7 +471,7 @@ class WhatGovernsSpeed(PathSlidingScene): path = Mobject().add_points(points) vect = points[-1] - points[-2] magnitude = np.sqrt(ceiling - points[-1, 1]) - vect = magnitude*vect/np.linalg.norm(vect) + vect = magnitude*vect/get_norm(vect) slider = self.slide(randy, path, ceiling = ceiling) vector = Vector(slider.get_center(), vect) self.add(slider, vector) @@ -584,7 +584,7 @@ class ThetaTInsteadOfXY(Scene): index = cycloid.get_num_points()/3 point = cycloid.points[index] vect = cycloid.points[index+1]-point - vect /= np.linalg.norm(vect) + vect /= get_norm(vect) vect *= 3 vect_mob = Vector(point, vect) dot = Dot(point) diff --git a/old_projects/brachistochrone/cycloid.py b/old_projects/brachistochrone/cycloid.py index ef624126..3867e4dc 100644 --- a/old_projects/brachistochrone/cycloid.py +++ b/old_projects/brachistochrone/cycloid.py @@ -7,7 +7,7 @@ class RollAlongVector(Animation): } def __init__(self, mobject, vector, **kwargs): radius = mobject.get_width()/2 - radians = np.linalg.norm(vector)/radius + radians = get_norm(vector)/radius last_alpha = 0 digest_config(self, kwargs, locals()) Animation.__init__(self, mobject, **kwargs) diff --git a/old_projects/brachistochrone/drawing_images.py b/old_projects/brachistochrone/drawing_images.py index 663a5dfa..848c2469 100644 --- a/old_projects/brachistochrone/drawing_images.py +++ b/old_projects/brachistochrone/drawing_images.py @@ -41,7 +41,7 @@ def thicken(nparray): def sort_by_color(mob): indices = np.argsort(np.apply_along_axis( - lambda p : -np.linalg.norm(p), + lambda p : -get_norm(p), 1, mob.rgbas )) @@ -211,7 +211,7 @@ class JohannThinksHeIsBetter(Scene): upper_point = Point(comparitive_johann.get_corner(UP+RIGHT)) lightbulb = ImageMobject("Lightbulb", invert = False) lightbulb.scale(0.1) - lightbulb.sort_points(np.linalg.norm) + lightbulb.sort_points(get_norm) lightbulb.next_to(upper_point, RIGHT) self.add(johann) diff --git a/old_projects/brachistochrone/light.py b/old_projects/brachistochrone/light.py index 9a2fe60c..b675e30a 100644 --- a/old_projects/brachistochrone/light.py +++ b/old_projects/brachistochrone/light.py @@ -31,7 +31,7 @@ class PhotonScene(Scene): result.ingest_submobjects() tangent_vectors = result.points[1:]-result.points[:-1] lengths = np.apply_along_axis( - np.linalg.norm, 1, tangent_vectors + get_norm, 1, tangent_vectors ) thick_lengths = lengths.repeat(3).reshape((len(lengths), 3)) unit_tangent_vectors = tangent_vectors/thick_lengths @@ -568,7 +568,7 @@ class Spring(Line): def generate_points(self): ## self.start, self.end - length = np.linalg.norm(self.end-self.start) + length = get_norm(self.end-self.start) angle = angle_of_vector(self.end-self.start) micro_radius = self.loop_radius/length m = 2*np.pi*(self.num_loops+0.5) diff --git a/old_projects/brachistochrone/wordplay.py b/old_projects/brachistochrone/wordplay.py index acc7e8b3..ca49a7fe 100644 --- a/old_projects/brachistochrone/wordplay.py +++ b/old_projects/brachistochrone/wordplay.py @@ -22,7 +22,7 @@ class Intro(Scene): self.wait() with_word, steve = new_text.split() steve_copy = steve.copy().center().to_edge(UP) - # logo.sort_points(lambda p : -np.linalg.norm(p)) + # logo.sort_points(lambda p : -get_norm(p)) sort_by_color(logo) self.play( Transform(steve, steve_copy), @@ -307,7 +307,7 @@ class FermatsPrincipleStatement(Scene): angle_of_vector, 1, everything.points ) norms = np.apply_along_axis( - np.linalg.norm, 1, everything.points + get_norm, 1, everything.points ) norms -= np.min(norms) norms /= np.max(norms) @@ -316,7 +316,7 @@ class FermatsPrincipleStatement(Scene): Mobject(everything, words).show() - everything.sort_points(np.linalg.norm) + everything.sort_points(get_norm) self.add(words) self.play( DelayByOrder(FadeIn(everything, run_time = 3)), diff --git a/old_projects/complex_multiplication_article.py b/old_projects/complex_multiplication_article.py index 656411d8..5fff8bbe 100644 --- a/old_projects/complex_multiplication_article.py +++ b/old_projects/complex_multiplication_article.py @@ -236,7 +236,7 @@ class DrawComplexAngleAndMagnitude(Scene): # label.set_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) + norm = get_norm(point) brace = Underbrace(ORIGIN, ORIGIN+norm*RIGHT) if point[1] > 0: brace.rotate(np.pi, RIGHT) diff --git a/old_projects/crypto.py b/old_projects/crypto.py index 809ad78b..4fd62b93 100644 --- a/old_projects/crypto.py +++ b/old_projects/crypto.py @@ -2324,7 +2324,7 @@ class YouListeningToBroadcasts(LedgerScene): self.add(you) for payment, corner in zip(payments, corners): - vect = corner/np.linalg.norm(corner) + vect = corner/get_norm(corner) payment.next_to(corner, vect) self.play( Broadcast(corner), @@ -2886,7 +2886,7 @@ class ShowSomeBroadcasting(DistributedLedgerScene): outgoing_lines = [] for line in lines: vect = line.get_start() - pi.get_center() - dist = np.linalg.norm(vect) + dist = get_norm(vect) if dist < 2: outgoing_lines.append(line) dots = VGroup() @@ -2897,7 +2897,7 @@ class ShowSomeBroadcasting(DistributedLedgerScene): dot.target.move_to(line.get_end()) for alt_pi in self.pi_creatures: vect = line.get_end() - alt_pi.get_center() - dist = np.linalg.norm(vect) + dist = get_norm(vect) if dist < 2: dot.ledger = alt_pi.ledger dots.add(dot) diff --git a/old_projects/dandelin.py b/old_projects/dandelin.py index 05a7f9dc..9aaf8acf 100644 --- a/old_projects/dandelin.py +++ b/old_projects/dandelin.py @@ -546,7 +546,7 @@ class EccentricityInThumbtackCase(ShowArrayOfEccentricities): focus_distance.set_color(GREEN) focus_distance.next_to(inner_brace_update.mobject, DOWN, SMALL_BUFF) focus_distance.add_to_back(focus_distance.copy().set_stroke(BLACK, 5)) - focus_distance_update = ContinualUpdateFromFunc( + focus_distance_update = ContinualUpdate( focus_distance, lambda m: m.set_width( inner_brace_update.mobject.get_width(), @@ -565,7 +565,7 @@ class EccentricityInThumbtackCase(ShowArrayOfEccentricities): fraction.set_color_by_tex("Diameter", RED) fraction.move_to(2 * UP) fraction.to_edge(RIGHT, buff=MED_LARGE_BUFF) - numerator_update = ContinualUpdateFromFunc( + numerator_update = ContinualUpdate( numerator, lambda m: m.set_width(focus_distance.get_width()).next_to( fraction[1], UP, MED_SMALL_BUFF @@ -631,7 +631,7 @@ class EccentricityInThumbtackCase(ShowArrayOfEccentricities): thumbtack.move_to(focus, DR) return thumbtacks - return ContinualUpdateFromFunc(thumbtacks, update_thumbtacks) + return ContinualUpdate(thumbtacks, update_thumbtacks) def get_ellipse_point_update(self, ellipse): dot = Dot(color=RED) @@ -652,10 +652,10 @@ class EccentricityInThumbtackCase(ShowArrayOfEccentricities): line.put_start_and_end_on(focus, Q) return lines - return ContinualUpdateFromFunc(lines, update_lines) + return ContinualUpdate(lines, update_lines) def get_focus_to_focus_line_update(self, ellipse): - return ContinualUpdateFromFunc( + return ContinualUpdate( Line(LEFT, RIGHT, color=WHITE), lambda m: m.put_start_and_end_on(*self.get_foci(ellipse)) ) @@ -663,7 +663,7 @@ class EccentricityInThumbtackCase(ShowArrayOfEccentricities): def get_focus_line_to_focus_line_brace_update(self, line): brace = Brace(Line(LEFT, RIGHT)) brace.add_to_back(brace.copy().set_stroke(BLACK, 5)) - return ContinualUpdateFromFunc( + return ContinualUpdate( brace, lambda b: b.match_width(line, stretch=True).next_to( line, DOWN, buff=SMALL_BUFF @@ -1408,7 +1408,7 @@ class CreativeConstruction(PiCreatureScene): lightbulb.generate_target() q_marks = VGroup() for submob in lightbulb.target.family_members_with_points(): - if True or np.linalg.norm(submob.get_center() - lightbulb.get_center()) > 0.25: + if True or get_norm(submob.get_center() - lightbulb.get_center()) > 0.25: q_mark = TexMobject("?") q_mark.set_height(0.25) q_mark.move_to(submob) @@ -1607,14 +1607,14 @@ class EllipseLengthsLinedUp(EccentricityInThumbtackCase): def update_lines(lines): for line, focus in zip(lines, foci): - d = np.linalg.norm(point.get_center() - focus) + d = get_norm(point.get_center() - focus) line.put_start_and_end_on( ORIGIN, d * UP ) lines.arrange_submobjects(DOWN, buff=0) lines.next_to(arrow, RIGHT) h_line.move_to(lines[0].get_bottom()) - lines_animation = ContinualUpdateFromFunc( + lines_animation = ContinualUpdate( lines, update_lines ) diff --git a/old_projects/div_curl.py b/old_projects/div_curl.py index 7645b7d4..27ec77c5 100644 --- a/old_projects/div_curl.py +++ b/old_projects/div_curl.py @@ -91,7 +91,7 @@ def cylinder_flow_vector_field(point, R=1, U=1): def cylinder_flow_magnitude_field(point): - return np.linalg.norm(cylinder_flow_vector_field(point)) + return get_norm(cylinder_flow_vector_field(point)) def get_colored_background_image(scalar_field_func, @@ -173,7 +173,7 @@ def four_swirls_function(point): x, y = point[:2] result = (y**3 - 4 * y) * RIGHT + (x**3 - 16 * x) * UP result *= 0.05 - norm = np.linalg.norm(result) + norm = get_norm(result) if norm == 0: return result # result *= 2 * sigmoid(norm) / norm @@ -187,7 +187,7 @@ def get_force_field_func(*point_strength_pairs, **kwargs): result = np.array(ORIGIN) for center, strength in point_strength_pairs: to_center = center - point - norm = np.linalg.norm(to_center) + norm = get_norm(to_center) if norm == 0: continue elif norm < radius: @@ -269,7 +269,7 @@ class StreamLines(VGroup): for t in np.arange(0, self.virtual_time, dt): last_point = points[-1] points.append(last_point + dt * func(last_point)) - if np.linalg.norm(last_point) > self.cutoff_norm: + if get_norm(last_point) > self.cutoff_norm: break line = VMobject() step = max(1, len(points) / self.n_anchors_per_line) @@ -280,7 +280,7 @@ class StreamLines(VGroup): if self.color_lines_by_magnitude: image_file = get_color_field_image_file( - lambda p: np.linalg.norm(func(p)), + lambda p: get_norm(func(p)), min_value=self.min_magnitude, max_value=self.max_magnitude, colors=self.colors, @@ -323,7 +323,7 @@ class VectorField(VGroup): def get_vector(self, point, **kwargs): output = np.array(self.func(point)) - norm = np.linalg.norm(output) + norm = get_norm(output) if norm == 0: output *= 0 else: @@ -841,7 +841,7 @@ class CylinderModel(Scene): def apply_joukowsky_map(self): shift_val = 0.1 * LEFT + 0.2 * UP - scale_factor = np.linalg.norm(RIGHT - shift_val) + scale_factor = get_norm(RIGHT - shift_val) movers = VGroup(self.warped_grid, self.unit_circle) self.unit_circle.insert_n_anchor_points(50) @@ -1042,7 +1042,7 @@ class ElectricField(CylinderModel, MovingCameraScene): # New vector field def new_electric_field(point): - if np.linalg.norm(point) < 1: + if get_norm(point) < 1: return ORIGIN vect = cylinder_flow_vector_field(point) return rotate_vector(vect, 90 * DEGREES) @@ -1587,7 +1587,7 @@ class ChangingElectricField(Scene): particle.shift(particle.velocity * dt) self.add( - ContinualUpdateFromFunc(vector_field, update_vector_field), + ContinualUpdate(vector_field, update_vector_field), ContinualUpdateFromTimeFunc(particles, update_particles), ) self.wait(20) @@ -1822,7 +1822,7 @@ class DefineDivergence(ChangingElectricField): "\\text{div} \\, \\textbf{F}(x, y) = " ) div_tex.add_background_rectangle() - div_tex_update = ContinualUpdateFromFunc( + div_tex_update = ContinualUpdate( div_tex, lambda m: m.next_to(circle, UP, SMALL_BUFF) ) @@ -2066,7 +2066,7 @@ class DivergenceAsNewFunction(Scene): ) self.add(func_tex, rhs) - # self.add(ContinualUpdateFromFunc( + # self.add(ContinualUpdate( # rhs, lambda m: m.next_to(func_tex, RIGHT) # )) @@ -2090,7 +2090,7 @@ class DivergenceAsNewFunction(Scene): out_vect.move_to(rhs) out_vect.set_fill(opacity=0) self.play(out_vect.restore) - self.out_vect_update = ContinualUpdateFromFunc( + self.out_vect_update = ContinualUpdate( out_vect, lambda ov: Transform(ov, get_out_vect()).update(1) ) @@ -2098,7 +2098,7 @@ class DivergenceAsNewFunction(Scene): self.add(self.out_vect_update) self.add(out_x_update, out_y_update) - self.add(ContinualUpdateFromFunc( + self.add(ContinualUpdate( VGroup(out_x, out_y), lambda m: m.match_style(out_vect) )) @@ -2167,7 +2167,7 @@ class DivergenceAsNewFunction(Scene): )) vector_ring = get_vector_ring() - vector_ring_update = ContinualUpdateFromFunc( + vector_ring_update = ContinualUpdate( vector_ring, lambda vr: Transform(vr, get_vector_ring()).update(1) ) @@ -2195,7 +2195,7 @@ class DivergenceAsNewFunction(Scene): ) # This line is a dumb hack around a Scene bug self.add(*[ - ContinualUpdateFromFunc( + ContinualUpdate( mob, lambda m: m.set_fill(None, 0) ) for mob in (out_x, out_y) @@ -2261,7 +2261,7 @@ class PureCylinderFlow(Scene): cylinder_flow_vector_field, ) for vector in vector_field: - if np.linalg.norm(vector.get_start()) < 1: + if get_norm(vector.get_start()) < 1: vector_field.remove(vector) vector_field.set_fill(opacity=0.75) self.modify_vector_field(vector_field) @@ -2279,7 +2279,7 @@ class PureCylinderFlow(Scene): ) self.add(stream_lines) for stream_line in stream_lines: - if np.linalg.norm(stream_line.points[0]) < 1: + if get_norm(stream_line.points[0]) < 1: stream_lines.remove(stream_line) self.modify_flow(stream_lines) @@ -2309,7 +2309,7 @@ class PureCylinderFlow(Scene): class PureAirfoilFlow(PureCylinderFlow): def modify_flow(self, mobject): vect = 0.1 * LEFT + 0.2 * UP - mobject.scale(np.linalg.norm(vect - RIGHT)) + mobject.scale(get_norm(vect - RIGHT)) mobject.shift(vect) mobject.apply_complex_function(joukowsky_map) return mobject @@ -2566,7 +2566,7 @@ class ShowCurlAtVariousPoints(IntroduceCurl): dot = Dot() circle = Circle(radius=0.25, color=WHITE) circle.move_to(dot) - circle_update = ContinualUpdateFromFunc( + circle_update = ContinualUpdate( circle, lambda m: m.move_to(dot) ) @@ -2575,7 +2575,7 @@ class ShowCurlAtVariousPoints(IntroduceCurl): "\\text{curl} \\, \\textbf{F}(x, y) = " ) curl_tex.add_background_rectangle(buff=0.025) - curl_tex_update = ContinualUpdateFromFunc( + curl_tex_update = ContinualUpdate( curl_tex, lambda m: m.next_to(circle, UP, SMALL_BUFF) ) @@ -2962,7 +2962,7 @@ class IllustrateGaussMagnetic(IllustrateGaussLaw): x, y = point[:2] top_part = np.array([(y - 1.0), -x, 0]) bottom_part = np.array([-(y + 1.0), x, 0]) - norm = np.linalg.norm + norm = get_norm return 1 * op.add( top_part / (norm(top_part) * norm(point - UP) + 0.1), bottom_part / (norm(bottom_part) * norm(point - DOWN) + 0.1), @@ -3083,10 +3083,10 @@ class ShowTwoPopulations(Scene): return update - self.add(ContinualUpdateFromFunc( + self.add(ContinualUpdate( foxes, get_updater(get_num_foxes) )) - self.add(ContinualUpdateFromFunc( + self.add(ContinualUpdate( rabbits, get_updater(get_num_rabbits) )) @@ -3105,7 +3105,7 @@ class ShowTwoPopulations(Scene): )) for count in num_foxes, num_rabbits: - self.add(ContinualUpdateFromFunc( + self.add(ContinualUpdate( count, self.update_count_color, )) @@ -3254,7 +3254,7 @@ class PhaseSpaceOfPopulationModel(ShowTwoPopulations, PiCreatureScene, MovingCam position_update_func=lambda m: m.move_to(tens[i]) ) coord_pair.add_background_rectangle() - coord_pair_update = ContinualUpdateFromFunc( + coord_pair_update = ContinualUpdate( coord_pair, lambda m: m.next_to(dot, UR, SMALL_BUFF) ) pop_sizes_updates = [get_pop_size_update(i) for i in (0, 1)] @@ -3803,7 +3803,7 @@ class ShowCrossProduct(ShowDotProduct): } def get_product(self, v1, v2): - return np.linalg.norm( + return get_norm( np.cross(v1.get_vector(), v2.get_vector()) ) @@ -3815,7 +3815,7 @@ class ShowCrossProduct(ShowDotProduct): fill_opacity=0.2, ) - self.add(ContinualUpdateFromFunc( + self.add(ContinualUpdate( square, lambda s: s.set_points_as_corners([ ORIGIN, @@ -3851,7 +3851,7 @@ class DivergenceTinyNudgesView(MovingCameraScene): np.cos(2 * y), 0 ]) - result /= (np.linalg.norm(result)**0.5 + 1) + result /= (get_norm(result)**0.5 + 1) return result vector_field = self.vector_field = VectorField( @@ -4025,7 +4025,7 @@ class DivergenceTinyNudgesView(MovingCameraScene): moving_step_vector.get_end(), moving_step_vector.get_end() + diff, ) - self.moving_diff_vector_update = ContinualUpdateFromFunc( + self.moving_diff_vector_update = ContinualUpdate( moving_diff_vector, update_moving_diff_vector ) diff --git a/old_projects/efvgt.py b/old_projects/efvgt.py index c73929c8..44bf0297 100644 --- a/old_projects/efvgt.py +++ b/old_projects/efvgt.py @@ -4,7 +4,7 @@ ADDER_COLOR = GREEN MULTIPLIER_COLOR = YELLOW def normalize(vect): - norm = np.linalg.norm(vect) + norm = get_norm(vect) if norm == 0: return OUT else: @@ -548,7 +548,7 @@ class SymmetriesOfSquare(ThreeDScene): ) def get_rotation_arcs(self, square, angle, angle_buff = SMALL_BUFF): - square_radius = np.linalg.norm( + square_radius = get_norm( square.points[0] - square.get_center() ) arc = Arc( @@ -1010,7 +1010,7 @@ class AddCubeSymmetries(GroupOfCubeSymmetries): maintain_smoothness = False ) arrows.move_to(cube) - arrows.shift(-axis*cube.get_height()/2/np.linalg.norm(axis)) + arrows.shift(-axis*cube.get_height()/2/get_norm(axis)) anims += list(map(ShowCreation, arrows)) anims.append( Rotate( diff --git a/old_projects/eoc/chapter2.py b/old_projects/eoc/chapter2.py index 49cfe575..377c480e 100644 --- a/old_projects/eoc/chapter2.py +++ b/old_projects/eoc/chapter2.py @@ -268,7 +268,7 @@ class IntroduceCar(Scene): graph_scene = GraphCarTrajectory(skip_animations = True) origin = graph_scene.graph_origin top = graph_scene.coords_to_point(0, 100) - new_length = np.linalg.norm(top-origin) + new_length = get_norm(top-origin) new_point_B = point_A + new_length*RIGHT car_line_group = VGroup(car, A, B, line) for mob in car_line_group: diff --git a/old_projects/eoc/chapter6.py b/old_projects/eoc/chapter6.py index bdb0337c..7023ee79 100644 --- a/old_projects/eoc/chapter6.py +++ b/old_projects/eoc/chapter6.py @@ -121,7 +121,7 @@ class SlopeOfCircleExample(ZoomedScene): full_group = VGroup(dot, lines, labels) start_angle = angle_of_vector(point) end_angle = np.pi/12 - spatial_radius = np.linalg.norm(point) + spatial_radius = get_norm(point) def update_full_group(group, alpha): dot, lines, labels = group angle = interpolate(start_angle, end_angle, alpha) @@ -233,7 +233,7 @@ class SlopeOfCircleExample(ZoomedScene): point = dot.get_center() step_vect = rotate_vector(point, np.pi/2) step_length = 1./self.zoom_factor - step_vect *= step_length/np.linalg.norm(step_vect) + step_vect *= step_length/get_norm(step_vect) step_line = Line(ORIGIN, LEFT) step_line.set_color(WHITE) @@ -1203,7 +1203,7 @@ class RelatedRatesExample(ThreeDScene): return np.arctan(self.start_x/self.start_y) def get_ladder_length(self): - return np.linalg.norm([self.start_x, self.start_y]) + return get_norm([self.start_x, self.start_y]) class LightweightLadderScene(RelatedRatesExample): CONFIG = { @@ -1444,7 +1444,7 @@ class TwoVariableFunctionAndDerivative(SlopeOfCircleExample): new_s_expression = self.get_s_expression(*self.example_point) new_s_expression.next_to(dot, UP+RIGHT, buff = 0) new_s_expression.set_color(self.example_color) - equals_25 = TexMobject("=%d"%int(np.linalg.norm(self.example_point)**2)) + equals_25 = TexMobject("=%d"%int(get_norm(self.example_point)**2)) equals_25.set_color(YELLOW) equals_25.next_to(new_s_expression, RIGHT, align_using_submobjects = True) equals_25.add_background_rectangle() @@ -1704,7 +1704,7 @@ class TwoVariableFunctionAndDerivative(SlopeOfCircleExample): randy = self.randy point = dot.get_center() - step_vect = rotate_vector(point, np.pi/2)/np.linalg.norm(point) + step_vect = rotate_vector(point, np.pi/2)/get_norm(point) new_point = point + step_vect/self.zoom_factor interim_point = point[0]*RIGHT + new_point[1]*UP new_dot = dot.copy().move_to(new_point) @@ -1914,7 +1914,7 @@ class AlternateExample(ZoomedScene): def update_label(label): point = dot.get_center() - vect = np.array(point)/np.linalg.norm(point) + vect = np.array(point)/get_norm(point) vect[0] *= 2 vect[1] *= -1 label.move_to( @@ -2293,7 +2293,7 @@ class DerivativeOfNaturalLog(ZoomedScene): def update_label(label): point = dot.get_center() vect = point - FRAME_Y_RADIUS*(DOWN+RIGHT) - vect = vect/np.linalg.norm(vect) + vect = vect/get_norm(vect) label.move_to( point + vect*0.5*label.get_width() ) diff --git a/old_projects/eoc/chapter9.py b/old_projects/eoc/chapter9.py index 4349123b..0ac34dbc 100644 --- a/old_projects/eoc/chapter9.py +++ b/old_projects/eoc/chapter9.py @@ -1448,7 +1448,7 @@ class GeneralAverage(AverageOfContinuousVariable): labels = list(map(TexMobject, "ab")) for line, label in zip(v_lines, labels): vect = line.get_start()-line.get_end() - label.next_to(line, vect/np.linalg.norm(vect)) + label.next_to(line, vect/get_norm(vect)) label.set_color(line.get_color()) self.y_axis_label_mob.shift(0.7*LEFT) diff --git a/old_projects/eoc/footnote.py b/old_projects/eoc/footnote.py index b4c2c454..f6656c45 100644 --- a/old_projects/eoc/footnote.py +++ b/old_projects/eoc/footnote.py @@ -845,7 +845,7 @@ class SecondDerivativeAsAcceleration(Scene): ########## def show_car_movement(self, *added_anims, **kwargs): - distance = np.linalg.norm( + distance = get_norm( self.car.get_center() - self.start_car_copy.get_center() ) if distance > 1: diff --git a/old_projects/eoc/old_chapter1.py b/old_projects/eoc/old_chapter1.py index 2c593564..ba02890f 100644 --- a/old_projects/eoc/old_chapter1.py +++ b/old_projects/eoc/old_chapter1.py @@ -1559,7 +1559,7 @@ class DerivativeAsTangentLine(ZoomedScene): graph_points = list(map(self.graph.point_from_proportion, alphas)) curr_graph_point = self.graph_point(R) self.last_alpha = alphas[np.argmin([ - np.linalg.norm(point - curr_graph_point) + get_norm(point - curr_graph_point) for point in graph_points ])] def shift_everything_to_alpha(alpha, run_time = 3): diff --git a/old_projects/eola/chapter0.py b/old_projects/eola/chapter0.py index 354e159d..c1e17182 100644 --- a/old_projects/eola/chapter0.py +++ b/old_projects/eola/chapter0.py @@ -587,7 +587,7 @@ class PhysicsExample(Scene): p1 = parabola.point_from_proportion(alpha) p2 = parabola.point_from_proportion(alpha + d_alpha) - vector = vector_length*(p2-p1)/np.linalg.norm(p2-p1) + vector = vector_length*(p2-p1)/get_norm(p2-p1) v_mob = Vector(vector, color = YELLOW) vx = Vector(vector[0]*RIGHT, color = GREEN_B) vy = Vector(vector[1]*UP, color = RED) diff --git a/old_projects/eola/chapter1.py b/old_projects/eola/chapter1.py index 128e47ec..821768ef 100644 --- a/old_projects/eola/chapter1.py +++ b/old_projects/eola/chapter1.py @@ -5,7 +5,7 @@ import random def plane_wave_homotopy(x, y, z, t): - norm = np.linalg.norm([x, y]) + norm = get_norm([x, y]) tau = interpolate(5, -5, t) + norm/FRAME_X_RADIUS alpha = sigmoid(tau) return [x, y + 0.5*np.sin(2*np.pi*alpha)-t*SMALL_BUFF/2, z] @@ -687,7 +687,7 @@ class VectorAddition(VectorScene): new_v_sum.rotate( angle_of_vector(alt_vect_sum) - new_v_sum.get_angle() ) - new_v_sum.scale(np.linalg.norm(alt_vect_sum)/new_v_sum.get_length()) + new_v_sum.scale(get_norm(alt_vect_sum)/new_v_sum.get_length()) new_v_sum.shift(v1.get_end()) new_v_sum.submobjects.reverse()#No idea why I have to do this original_v_sum = v_sum.copy() diff --git a/old_projects/eola/chapter11.py b/old_projects/eola/chapter11.py index 0e2f6633..42279fa7 100644 --- a/old_projects/eola/chapter11.py +++ b/old_projects/eola/chapter11.py @@ -2155,7 +2155,7 @@ class MathematicianSpeakingToAll(Scene): vect = -bubble.get_bubble_center() def func(point): centered = point+vect - return 10*centered/np.linalg.norm(centered) + return 10*centered/get_norm(centered) self.play(*[ ApplyPointwiseFunction(func, mob) for mob in self.get_mobjects() diff --git a/old_projects/eola/chapter2.py b/old_projects/eola/chapter2.py index ba585cd7..d38cb905 100644 --- a/old_projects/eola/chapter2.py +++ b/old_projects/eola/chapter2.py @@ -256,7 +256,7 @@ class ShowVaryingLinearCombinations(VectorScene): def get_scalar_anims(self, v1, v2, v1_label, v2_label): def get_val_func(vect): original_vect = np.array(vect.get_end()-vect.get_start()) - square_norm = np.linalg.norm(original_vect)**2 + square_norm = get_norm(original_vect)**2 return lambda a : np.dot( original_vect, vect.get_end()-vect.get_start() )/square_norm diff --git a/old_projects/eola/chapter3.py b/old_projects/eola/chapter3.py index 786d39a5..70342012 100644 --- a/old_projects/eola/chapter3.py +++ b/old_projects/eola/chapter3.py @@ -50,7 +50,7 @@ class Introduction(TeacherStudentsScene): everything = VMobject(*self.get_mobjects()) def spread_out(p): p = p + 2*DOWN - return (FRAME_X_RADIUS+FRAME_Y_RADIUS)*p/np.linalg.norm(p) + return (FRAME_X_RADIUS+FRAME_Y_RADIUS)*p/get_norm(p) self.play( ApplyPointwiseFunction(spread_out, everything), ApplyFunction( diff --git a/old_projects/eola/chapter4.py b/old_projects/eola/chapter4.py index c0d727c2..dde908b3 100644 --- a/old_projects/eola/chapter4.py +++ b/old_projects/eola/chapter4.py @@ -730,7 +730,7 @@ class NeverForget(TeacherStudentsScene): self.student_thinks("", student_index = 0) def warp(point): point += 2*DOWN+RIGHT - return 20*point/np.linalg.norm(point) + return 20*point/get_norm(point) self.play(ApplyPointwiseFunction( warp, VMobject(*self.get_mobjects()) diff --git a/old_projects/eola/chapter5.py b/old_projects/eola/chapter5.py index a79c481e..a4e88d75 100644 --- a/old_projects/eola/chapter5.py +++ b/old_projects/eola/chapter5.py @@ -21,7 +21,7 @@ class Blob(Circle): def probably_contains(self, point): border_points = np.array(self.get_anchors_and_handles()[0]) - distances = [np.linalg.norm(p-point) for p in border_points] + distances = [get_norm(p-point) for p in border_points] min3 = border_points[np.argsort(distances)[:3]] center_direction = self.get_center() - point in_center_direction = [np.dot(p-point, center_direction) > 0 for p in min3] diff --git a/old_projects/eola/chapter7.py b/old_projects/eola/chapter7.py index ef415e17..7a742d11 100644 --- a/old_projects/eola/chapter7.py +++ b/old_projects/eola/chapter7.py @@ -9,7 +9,7 @@ SUM_COLOR = PINK def get_projection(vector_to_project, stable_vector): v1, v2 = stable_vector, vector_to_project - return v1*np.dot(v1, v2)/(np.linalg.norm(v1)**2) + return v1*np.dot(v1, v2)/(get_norm(v1)**2) def get_vect_mob_projection(vector_to_project, stable_vector): return Vector( @@ -303,7 +303,7 @@ class GeometricInterpretation(VectorScene): def project(self): dot_product = np.dot(self.v.get_end(), self.w.get_end()) v_norm, w_norm = [ - np.linalg.norm(vect.get_end()) + get_norm(vect.get_end()) for vect in (self.v, self.w) ] projected = Vector( @@ -671,7 +671,7 @@ class LurkingQuestion(TeacherStudentsScene): self.teacher_thinks("") everything = VMobject(*self.get_mobjects()) self.play(ApplyPointwiseFunction( - lambda p : 10*(p+2*DOWN)/np.linalg.norm(p+2*DOWN), + lambda p : 10*(p+2*DOWN)/get_norm(p+2*DOWN), everything )) diff --git a/old_projects/eola/footnote2.py b/old_projects/eola/footnote2.py index 3a23de09..47763e4f 100644 --- a/old_projects/eola/footnote2.py +++ b/old_projects/eola/footnote2.py @@ -571,7 +571,7 @@ class DotProductPreview(VectorScene): def project_w(self): dot_product = np.dot(self.v.get_end(), self.w.get_end()) v_norm, w_norm = [ - np.linalg.norm(vect.get_end()) + get_norm(vect.get_end()) for vect in (self.v, self.w) ] projected_w = Vector( diff --git a/old_projects/eulers_characteristic_formula.py b/old_projects/eulers_characteristic_formula.py index 1c35d768..3a680bf5 100644 --- a/old_projects/eulers_characteristic_formula.py +++ b/old_projects/eulers_characteristic_formula.py @@ -783,7 +783,7 @@ class DrawDualGraph(GraphScene): self.wait() self.reset_background() self.play(ApplyFunction( - lambda p : (FRAME_X_RADIUS + FRAME_Y_RADIUS)*p/np.linalg.norm(p), + lambda p : (FRAME_X_RADIUS + FRAME_Y_RADIUS)*p/get_norm(p), outer_region_mob )) self.wait() @@ -1038,7 +1038,7 @@ class MortimerCannotTraverseCycle(GraphScene): ) all_lines.append(line) center = line.get_center() - distances = [np.linalg.norm(center - e.get_center()) for e in self.edges] + distances = [get_norm(center - e.get_center()) for e in self.edges] matching_edges.append( self.edges[distances.index(min(distances))] ) diff --git a/old_projects/fourier.py b/old_projects/fourier.py index 2817af0c..40d2ed9a 100644 --- a/old_projects/fourier.py +++ b/old_projects/fourier.py @@ -698,12 +698,12 @@ class UnmixMixedPaint(Scene): def update_quadrant(quadrant, alpha): points = quadrant.get_anchors() dt = 0.03 #Hmm, this has no dependency on frame rate... - norms = np.apply_along_axis(np.linalg.norm, 1, points) + norms = np.apply_along_axis(get_norm, 1, points) points[:,0] -= dt*points[:,1]/np.clip(norms, 0.1, np.inf) points[:,1] += dt*points[:,0]/np.clip(norms, 0.1, np.inf) - new_norms = np.apply_along_axis(np.linalg.norm, 1, points) + new_norms = np.apply_along_axis(get_norm, 1, points) new_norms = np.clip(new_norms, 0.001, np.inf) radius = np.max(norms) multiplier = norms/new_norms @@ -2660,7 +2660,7 @@ class WriteComplexExponentialExpression(DrawFrequencyPlot): v_line.put_start_and_end_on( plane.coords_to_point(x, 0), point ) - lines_update_anim = ContinualUpdateFromFunc(lines, lines_update) + lines_update_anim = ContinualUpdate(lines, lines_update) lines_update_anim.update(0) self.add(lines_update_anim) @@ -2758,12 +2758,12 @@ class WriteComplexExponentialExpression(DrawFrequencyPlot): exp_base.get_corner(UP+RIGHT), DOWN+LEFT ) ) - exp_base_update = ContinualUpdateFromFunc( + exp_base_update = ContinualUpdate( exp_base, lambda e : e.move_to(get_circle_point( scalar = 1.1, t_shift = 0.01*TAU )) ) - vector_update = ContinualUpdateFromFunc( + vector_update = ContinualUpdate( vector, lambda v : v.put_start_and_end_on( plane.number_to_point(0), get_circle_point() ) @@ -4004,7 +4004,7 @@ class ShowUncertaintyPrinciple(Scene): )) self.wait(2) self.add(*[ - ContinualUpdateFromFunc(graph, get_update_func(axes)) + ContinualUpdate(graph, get_update_func(axes)) for graph, axes in [(top_graph, top_axes), (bottom_graph, bottom_axes)] ]) for factor in factors: diff --git a/old_projects/generate_logo.py b/old_projects/generate_logo.py index 833d919d..7b763a5c 100644 --- a/old_projects/generate_logo.py +++ b/old_projects/generate_logo.py @@ -46,7 +46,7 @@ class LogoGeneration(Scene): mob.set_color(color, lambda x_y_z : x_y_z[0] < 0 and x_y_z[1] > 0) mob.set_color( "black", - lambda point: np.linalg.norm(point) < \ + lambda point: get_norm(point) < \ self.inner_radius_ratio*self.radius ) self.name_mob = TextMobject("3Blue1Brown").center() diff --git a/old_projects/hanoi.py b/old_projects/hanoi.py index 8bebbcca..ae464043 100644 --- a/old_projects/hanoi.py +++ b/old_projects/hanoi.py @@ -2893,7 +2893,7 @@ class SierpinskiGraphScene(Scene): towers_scene.move_disk(disk_index, run_time = 0) def distance_between_nodes(self, i, j): - return np.linalg.norm( + return get_norm( self.nodes[i].get_center()-\ self.nodes[j].get_center() ) @@ -2908,7 +2908,7 @@ class SierpinskiGraphScene(Scene): center1 = self.nodes[i].get_center() center2 = self.nodes[j].get_center() vect = center1-center2 - distance = np.linalg.norm(center1 - center2) + distance = get_norm(center1 - center2) if distance < min_distance: edge = Line( center1 - (vect/distance)*node_radius, diff --git a/old_projects/highD.py b/old_projects/highD.py index f877024f..6da534cd 100644 --- a/old_projects/highD.py +++ b/old_projects/highD.py @@ -165,7 +165,7 @@ class SliderScene(Scene): def update_sliders(sliders): curr_vect = self.get_vector() curr_vect -= self.center_point - curr_vect *= radius/np.linalg.norm(curr_vect) + curr_vect *= radius/get_norm(curr_vect) curr_vect += self.center_point self.set_to_vector(curr_vect) return sliders @@ -190,14 +190,14 @@ class SliderScene(Scene): else: unspecified_indices.append(i) unspecified_vector[i] = curr_vector[i] - used_re = np.linalg.norm(target_vector - self.center_point)**2 + used_re = get_norm(target_vector - self.center_point)**2 left_over_re = self.total_real_estate - used_re if left_over_re < -0.001: raise Exception("Overspecified reset") - uv_norm = np.linalg.norm(unspecified_vector - self.center_point) + uv_norm = get_norm(unspecified_vector - self.center_point) if uv_norm == 0 and left_over_re > 0: unspecified_vector[unspecified_indices] = 1 - uv_norm = np.linalg.norm(unspecified_vector - self.center_point) + uv_norm = get_norm(unspecified_vector - self.center_point) if uv_norm > 0: unspecified_vector -= self.center_point unspecified_vector *= np.sqrt(left_over_re)/uv_norm @@ -273,7 +273,7 @@ class SliderScene(Scene): center_point = self.get_center_point() target_vector = self.get_vector() - center_point - if np.linalg.norm(target_vector) == 0: + if get_norm(target_vector) == 0: return vectors_and_magnitudes = [ (self.ambient_acceleration, self.ambient_acceleration_magnitude), @@ -285,9 +285,9 @@ class SliderScene(Scene): for vect, mag in vectors_and_magnitudes: vect += self.frame_duration*deriv if vect is self.ambient_velocity: - unit_r_vect = target_vector / np.linalg.norm(target_vector) + unit_r_vect = target_vector / get_norm(target_vector) vect -= np.dot(vect, unit_r_vect)*unit_r_vect - vect *= mag/np.linalg.norm(vect) + vect *= mag/get_norm(vect) deriv = vect self.set_to_vector(target_vector + center_point) @@ -295,7 +295,7 @@ class SliderScene(Scene): def get_random_vector(self, magnitude): result = 2*np.random.random(len(self.sliders)) - 1 - result *= magnitude / np.linalg.norm(result) + result *= magnitude / get_norm(result) return result def update_frame(self, *args, **kwargs): @@ -1481,7 +1481,7 @@ class FourDCase(SliderScene, TeacherStudentsScene): self.wind_down_ambient_movement(wait = False) self.play(self.teacher.change, "speaking") self.sliders.remove(x_slider) - self.total_real_estate = np.linalg.norm(self.get_vector())**2 + self.total_real_estate = get_norm(self.get_vector())**2 self.initialize_ambiant_slider_movement() arrow = Arrow(LEFT, RIGHT, color = GREEN) arrow.next_to(dial, LEFT) @@ -2058,7 +2058,7 @@ class TwoDBoxWithSliders(TwoDimensionalCase): def show_center_circle(self): origin = self.plane.coords_to_point(0, 0) - radius = np.linalg.norm( + radius = get_norm( self.plane.coords_to_point(np.sqrt(2)-1, 0) - origin ) circle = Circle(radius = radius, color = GREEN) @@ -2077,7 +2077,7 @@ class TwoDBoxWithSliders(TwoDimensionalCase): h_line = Line(point[1]*UP + origin[0]*RIGHT, point) v_line = Line(point[0]*RIGHT+origin[1]*UP, point) - while np.linalg.norm(self.get_vector()-target_vector) > 0.5: + while get_norm(self.get_vector()-target_vector) > 0.5: self.wait() self.wind_down_ambient_movement(0) self.reset_dials(target_vector) @@ -2210,7 +2210,7 @@ class TwoDBoxWithSliders(TwoDimensionalCase): half.next_to(half_line, LEFT, SMALL_BUFF) target_vector = np.array(2*[1-np.sqrt(0.5)]) - while np.linalg.norm(target_vector - self.get_vector()) > 0.5: + while get_norm(target_vector - self.get_vector()) > 0.5: self.wait() self.wind_down_ambient_movement(0) self.reset_dials(target_vector) @@ -3598,7 +3598,7 @@ class Thumbnail(SliderScene): self.remove(slider.label) slider.remove(slider.label) vect = np.random.random(10) - 0.5 - vect /= np.linalg.norm(vect) + vect /= get_norm(vect) self.set_to_vector(vect) title = TextMobject("10D Sphere?") diff --git a/old_projects/hilbert/section1.py b/old_projects/hilbert/section1.py index d8ccdc2b..b40a72ed 100644 --- a/old_projects/hilbert/section1.py +++ b/old_projects/hilbert/section1.py @@ -64,7 +64,7 @@ class AboutSpaceFillingCurves(TransformOverIncreasingOrders): list(locals().values()), )) for mob in local_mobjects: - mob.sort_points(np.linalg.norm) + mob.sort_points(get_norm) self.play(ShimmerIn(infinity)) self.wait() @@ -160,8 +160,8 @@ class ImageToSound(Scene): picture = ImageMobject("lion", invert = False) picture.scale(0.8) picture_copy = picture.copy() - picture.sort_points(np.linalg.norm) - string.mobject.sort_points(lambda p : -np.linalg.norm(p)) + picture.sort_points(get_norm) + string.mobject.sort_points(lambda p : -get_norm(p)) self.add(picture) self.wait() @@ -174,7 +174,7 @@ class ImageToSound(Scene): self.play(string) for mob in picture_copy, string.mobject: - mob.sort_points(lambda p : np.linalg.norm(p)%1) + mob.sort_points(lambda p : get_norm(p)%1) self.play(Transform( string.mobject, picture_copy, @@ -239,7 +239,7 @@ class SoundDataIsOneDimensional(Scene): freq_line = get_freq_line() freq_line.shift(floor) - freq_line.sort_points(np.linalg.norm) + freq_line.sort_points(get_norm) brace = Brace(freq_line, UP) words = TextMobject("Range of frequency values") words.next_to(brace, UP) @@ -303,7 +303,7 @@ class GridOfPixels(Scene): ) self.wait() for mob in grid, high_res: - mob.sort_points(np.linalg.norm) + mob.sort_points(get_norm) self.play(DelayByOrder(Transform(high_res, grid))) self.wait() @@ -394,7 +394,7 @@ class AssociatePixelWithFrequency(Scene): class ListenToAllPixels(Scene): def construct(self): grid = get_grid() - grid.sort_points(np.linalg.norm) + grid.sort_points(get_norm) freq_line = get_freq_line() freq_line.sort_points(lambda p : p[0]) red, blue = Color(RED), Color(BLUE) @@ -607,7 +607,7 @@ class WeaveLineThroughPixels(Scene): for square in squares.submobjects: center = square.get_center() distances = np.apply_along_axis( - lambda p : np.linalg.norm(p-center), + lambda p : get_norm(p-center), 1, curve.points ) @@ -700,7 +700,7 @@ class TellMathematicianFriend(Scene): self.wait(2) self.play( ApplyPointwiseFunction( - lambda p : 15*p/np.linalg.norm(p), + lambda p : 15*p/get_norm(p), bubble ), ApplyMethod(mathy.shift, 5*(DOWN+LEFT)), diff --git a/old_projects/hilbert/section2.py b/old_projects/hilbert/section2.py index 67979514..f1007a20 100644 --- a/old_projects/hilbert/section2.py +++ b/old_projects/hilbert/section2.py @@ -82,7 +82,7 @@ class AskMathematicianFriend(Scene): self.play( ApplyMethod(mathy.shift, 3*(DOWN+LEFT)), ApplyPointwiseFunction( - lambda p : 15*p/np.linalg.norm(p), + lambda p : 15*p/get_norm(p), bubble ), run_time = 3 @@ -147,7 +147,7 @@ class NotPixelatedSpace(Scene): line = Line(5*LEFT, 5*RIGHT) line.set_color_by_gradient(curve.start_color, curve.end_color) for mob in grid, space_mobject: - mob.sort_points(np.linalg.norm) + mob.sort_points(get_norm) infinitely = TextMobject("Infinitely") detailed = TextMobject("detailed") extending = TextMobject("extending") @@ -510,7 +510,7 @@ class FormalDefinitionOfContinuity(Scene): for num in (min_input, max_input) ] input_circle = Circle( - radius = np.linalg.norm(input_left-input_right)/2, + radius = get_norm(input_left-input_right)/2, color = WHITE ) input_circle.shift((input_left+input_right)/2) @@ -525,7 +525,7 @@ class FormalDefinitionOfContinuity(Scene): self.output.points[int(min_input*n):int(max_input*n)] ) output_center = output_points.points[int(0.5*output_points.get_num_points())] - max_distance = np.linalg.norm(output_center-output_points.points[-1]) + max_distance = get_norm(output_center-output_points.points[-1]) output_circle = Circle( radius = max_distance, color = WHITE diff --git a/old_projects/hilbert/section3.py b/old_projects/hilbert/section3.py index 40d86416..d175f918 100644 --- a/old_projects/hilbert/section3.py +++ b/old_projects/hilbert/section3.py @@ -96,7 +96,7 @@ class InfiniteResultsFiniteWorld(Scene): ] ] for mob in ex, middle: - mob.sort_points(np.linalg.norm) + mob.sort_points(get_norm) self.play(GrowFromCenter(ex)) self.wait() @@ -133,7 +133,7 @@ class InfiniteResultsFiniteWorld(Scene): )*RIGHT ) for mob in arrow, words: - mob.sort_points(np.linalg.norm) + mob.sort_points(get_norm) self.play( ApplyMethod(left_mob.shift, RIGHT), diff --git a/old_projects/inventing_math.py b/old_projects/inventing_math.py index 677d0f81..3a507343 100644 --- a/old_projects/inventing_math.py +++ b/old_projects/inventing_math.py @@ -386,7 +386,7 @@ class YouAsMathematician(Scene): self.clear() self.play( ApplyPointwiseFunction( - lambda p : 3*FRAME_X_RADIUS*p/np.linalg.norm(p), + lambda p : 3*FRAME_X_RADIUS*p/get_norm(p), everything ), *[ @@ -1721,7 +1721,7 @@ class RoomsAndSubrooms(Scene): for group in rectangle_groups: mob = Mobject(*group) - mob.sort_points(np.linalg.norm) + mob.sort_points(get_norm) self.play(ShowCreation(mob)) self.wait() @@ -1775,7 +1775,7 @@ class RoomsAndSubroomsWithNumbers(Scene): FRAME_HEIGHT-(n+2)*upper_buff, zero_one_width/(2**n)-0.85*(n+1)*side_buff ) - rect.sort_points(np.linalg.norm) + rect.sort_points(get_norm) rect.to_edge(LEFT, buff = 0.2).shift(n*side_buff*RIGHT) rect.set_color(colors[n]) rectangles.append(rect) @@ -1866,7 +1866,7 @@ class RoomsAndSubroomsWithNumbers(Scene): def center_in_closest_rect(mobject, rectangles): center = mobject.get_center() diffs = [r.get_center()-center for r in rectangles] - mobject.shift(diffs[np.argmin(list(map(np.linalg.norm, diffs)))]) + mobject.shift(diffs[np.argmin(list(map(get_norm, diffs)))]) def add_negative_one(self, num_mobs): neg_one = TexMobject("-1").scale(0.5) diff --git a/old_projects/leibniz.py b/old_projects/leibniz.py index 50aeca5f..a5cbe015 100644 --- a/old_projects/leibniz.py +++ b/old_projects/leibniz.py @@ -57,7 +57,7 @@ class LatticePointScene(Scene): dot.r_squared = r_squared self.lattice_points.add(dot) self.lattice_points.sort_submobjects( - lambda p : np.linalg.norm(p - self.plane_center) + lambda p : get_norm(p - self.plane_center) ) def get_circle(self, radius = None, color = None): @@ -298,7 +298,7 @@ class ShowSum(TeacherStudentsScene): arrows = [ Arrow( p1, p2, - tip_length = 0.2*min(1, np.linalg.norm(p1-p2)), + tip_length = 0.2*min(1, get_norm(p1-p2)), buff = 0 ) for p1, p2 in zip(points, points[1:]) @@ -556,7 +556,7 @@ class Outline(PiCreatureScene): plane.to_edge(LEFT) circle = Circle( color = YELLOW, - radius = np.linalg.norm( + radius = get_norm( plane.coords_to_point(10, 0) - \ plane.coords_to_point(0, 0) ) @@ -574,7 +574,7 @@ class Outline(PiCreatureScene): if a**2 + b**2 <= 10**2 ]) lattice_points.sort_submobjects( - lambda p : np.linalg.norm(p - plane_center) + lambda p : get_norm(p - plane_center) ) lattice_group = VGroup(plane, circle, lattice_points) @@ -4173,7 +4173,7 @@ class CountLatticePointsInBigCircle(LatticePointScene): if (x**2 + y**2) > self.max_lattice_point_radius**2 if (x**2 + y**2) < new_max**2 ]) - new_dots.sort_submobjects(np.linalg.norm) + new_dots.sort_submobjects(get_norm) self.play(*list(map(ShowCreation, [circle, arrow]))) self.play(*list(map(FadeOut, [circle, arrow]))) diff --git a/old_projects/lost_lecture.py b/old_projects/lost_lecture.py index 211f5f44..2f13b2df 100644 --- a/old_projects/lost_lecture.py +++ b/old_projects/lost_lecture.py @@ -31,11 +31,11 @@ class Orbiting(ContinualAnimation): rate = self.rate radius_vector = planet.get_center() - star.get_center() - rate *= 1.0 / np.linalg.norm(radius_vector) + rate *= 1.0 / get_norm(radius_vector) prop = self.proportion d_prop = 0.001 - ds = np.linalg.norm(op.add( + ds = get_norm(op.add( ellipse.point_from_proportion((prop + d_prop) % 1), -ellipse.point_from_proportion(prop), )) @@ -280,7 +280,7 @@ class ShowEmergingEllipse(Scene): # Ellipse parameters a = radius / 2 - c = np.linalg.norm(e_point - center) / 2 + c = get_norm(e_point - center) / 2 b = np.sqrt(a**2 - c**2) result = Circle(radius=b, color=self.ellipse_color) @@ -750,7 +750,7 @@ class AskAboutEllipses(TheMotionOfPlanets): l2.put_start_and_end_on(f2, P) return lines - animation = ContinualUpdateFromFunc( + animation = ContinualUpdate( lines, update_lines ) self.add(animation) @@ -785,7 +785,7 @@ class AskAboutEllipses(TheMotionOfPlanets): ) Transform(measurement, new_decimal).update(1) - radius_measurement_animation = ContinualUpdateFromFunc( + radius_measurement_animation = ContinualUpdate( radius_measurement, update_radial_measurement ) @@ -943,7 +943,7 @@ class AskAboutEllipses(TheMotionOfPlanets): arrow.shift( radial_line.get_end() - arrow.get_start() ) - force_arrow_animation = ContinualUpdateFromFunc( + force_arrow_animation = ContinualUpdate( force_arrow, update_force_arrow ) @@ -952,7 +952,7 @@ class AskAboutEllipses(TheMotionOfPlanets): def get_radial_line_and_update(self, comet): line = Line(LEFT, RIGHT) line.set_stroke(LIGHT_GREY, 1) - line_update = ContinualUpdateFromFunc( + line_update = ContinualUpdate( line, lambda l: l.put_start_and_end_on( self.sun.get_center(), comet.get_center(), @@ -1207,7 +1207,7 @@ class ShowEllipseDefiningProperty(Scene): dot = Dot() dot.scale(0.5) position_tracker = ValueTracker(0.125) - dot_update = ContinualUpdateFromFunc( + dot_update = ContinualUpdate( dot, lambda d: d.move_to( self.ellipse.point_from_proportion( @@ -1378,7 +1378,7 @@ class ShowEllipseDefiningProperty(Scene): focus, focal_sum_point.get_center() ) lines[1].rotate(np.pi) - lines_update_animation = ContinualUpdateFromFunc( + lines_update_animation = ContinualUpdate( lines, update_lines ) return lines, lines_update_animation @@ -1413,7 +1413,7 @@ class ShowEllipseDefiningProperty(Scene): ) label.submobjects = list(new_decimal.submobjects) - distance_labels_animation = ContinualUpdateFromFunc( + distance_labels_animation = ContinualUpdate( distance_labels, update_distance_labels ) @@ -1791,7 +1791,7 @@ class ProveEllipse(ShowEmergingEllipse, ShowEllipseDefiningProperty): if line.get_end()[0] > line.get_start()[0]: vect = label.get_center() - line.get_center() label.shift(-2 * vect) - distance_label_shift_update_animation = ContinualUpdateFromFunc( + distance_label_shift_update_animation = ContinualUpdate( self.distance_labels[0], distance_label_shift_update ) @@ -1802,7 +1802,7 @@ class ProveEllipse(ShowEmergingEllipse, ShowEllipseDefiningProperty): # Define QP line QP_line = Line(LEFT, RIGHT) QP_line.match_style(self.focal_lines) - QP_line_update = ContinualUpdateFromFunc( + QP_line_update = ContinualUpdate( QP_line, lambda l: l.put_start_and_end_on( Q_dot.get_center(), P_dot.get_center(), ) @@ -1810,7 +1810,7 @@ class ProveEllipse(ShowEmergingEllipse, ShowEllipseDefiningProperty): QE_line = Line(LEFT, RIGHT) QE_line.set_stroke(YELLOW, 3) - QE_line_update = ContinualUpdateFromFunc( + QE_line_update = ContinualUpdate( QE_line, lambda l: l.put_start_and_end_on( Q_dot.get_center(), self.get_eccentricity_point() @@ -1840,7 +1840,7 @@ class ProveEllipse(ShowEmergingEllipse, ShowEllipseDefiningProperty): label.rotate(angle, about_point=Q_dot.get_center()) return label - distance_label_rotate_update_animation = ContinualUpdateFromFunc( + distance_label_rotate_update_animation = ContinualUpdate( self.distance_labels[0], distance_label_rotate_update ) @@ -2066,7 +2066,7 @@ class ProveEllipse(ShowEmergingEllipse, ShowEllipseDefiningProperty): [self.circle.get_center(), gl.get_end()], line.get_start_and_end() ) - distance = np.linalg.norm( + distance = get_norm( intersection - planet.get_center() ) if distance < 0.025: @@ -2075,7 +2075,7 @@ class ProveEllipse(ShowEmergingEllipse, ShowEllipseDefiningProperty): else: line.set_stroke(WHITE, 1) - lines_update_animation = ContinualUpdateFromFunc( + lines_update_animation = ContinualUpdate( lines, update_lines ) @@ -2356,7 +2356,7 @@ class NonEllipticalKeplersLaw(KeplersSecondLaw): arrow, arrow_update = self.get_force_arrow_and_update( comet ) - alt_arrow_update = ContinualUpdateFromFunc( + alt_arrow_update = ContinualUpdate( arrow, lambda a: a.scale( 1.0 / a.get_length(), about_point=a.get_start() @@ -2596,7 +2596,7 @@ class AngularMomentumArgument(KeplersSecondLaw): ) vector_field.set_fill(opacity=0.8) vector_field.sort_submobjects( - lambda p: -np.linalg.norm(p - sun_center) + lambda p: -get_norm(p - sun_center) ) stays_constant = TextMobject("Stays constant") @@ -2918,7 +2918,7 @@ class IntroduceShapeOfVelocities(AskAboutEllipses, MovingCameraScene): # Helpers def get_velocity_vector(self, alpha, d_alpha=0.01, scalar=3.0): - norm = np.linalg.norm + norm = get_norm ellipse = self.ellipse sun_center = self.sun.get_center() @@ -2963,7 +2963,7 @@ class IntroduceShapeOfVelocities(AskAboutEllipses, MovingCameraScene): ) Transform(vector, new_vector).update(1) - moving_vector_animation = ContinualUpdateFromFunc( + moving_vector_animation = ContinualUpdate( moving_vector, update_moving_vector ) return moving_vector, moving_vector_animation @@ -3016,8 +3016,8 @@ class ShowEqualAngleSlices(IntroduceShapeOfVelocities): def get_cos_angle_diff(v1, v2): return np.dot( - v1 / np.linalg.norm(v1), - v2 / np.linalg.norm(v2), + v1 / get_norm(v1), + v2 / get_norm(v2), ) lines = VGroup() @@ -4000,7 +4000,7 @@ class UseVelocityDiagramToDeduceCurve(ShowEqualAngleSlices): circle.get_center(), ] a = circle.get_width() / 4 - c = np.linalg.norm(foci[1] - foci[0]) / 2 + c = get_norm(foci[1] - foci[0]) / 2 b = np.sqrt(a**2 - c**2) little_ellipse = Circle(radius=a) little_ellipse.stretch(b / a, 1) @@ -4127,7 +4127,7 @@ class ShowSunVectorField(Scene): ) vector_field.set_fill(opacity=0.8) vector_field.sort_submobjects( - lambda p: -np.linalg.norm(p - sun_center) + lambda p: -get_norm(p - sun_center) ) for vector in vector_field: diff --git a/old_projects/matrix_as_transform_2d.py b/old_projects/matrix_as_transform_2d.py index bf03ea97..9022d7b2 100644 --- a/old_projects/matrix_as_transform_2d.py +++ b/old_projects/matrix_as_transform_2d.py @@ -260,7 +260,7 @@ class ShowMatrixTransform(TransformScene2D): def get_density_factor(self, matrix): max_norm = max([ - abs(np.linalg.norm(column)) + abs(get_norm(column)) for column in np.transpose(matrix) ]) return max(max_norm, 1) @@ -516,14 +516,14 @@ class ShowMatrixTransformWithDot(TransformScene2D): def get_density_factor(self, matrix): max_norm = max([ - abs(np.linalg.norm(column)) + abs(get_norm(column)) for column in np.transpose(matrix) ]) return max(max_norm, 1) def get_path_func(self, matrix): rotational_components = [ - sign*np.arccos(matrix[i,i]/np.linalg.norm(matrix[:,i])) + sign*np.arccos(matrix[i,i]/get_norm(matrix[:,i])) for i in [0, 1] for sign in [((-1)**i)*np.sign(matrix[1-i, i])] ] diff --git a/old_projects/moser_intro.py b/old_projects/moser_intro.py index e2047861..920754fc 100644 --- a/old_projects/moser_intro.py +++ b/old_projects/moser_intro.py @@ -225,7 +225,7 @@ def next_few_videos(*radians): thumbnail = Mobject(circle, dots, lines) frame = VideoIcon().set_color( "black", - lambda point : np.linalg.norm(point) < 0.5 + lambda point : get_norm(point) < 0.5 ) big_frame = deepcopy(frame).scale(FRAME_X_RADIUS) frame.shift((-5, 0, 0)) diff --git a/old_projects/mug.py b/old_projects/mug.py index b58bc072..76e6e5aa 100644 --- a/old_projects/mug.py +++ b/old_projects/mug.py @@ -1683,7 +1683,7 @@ class FiveRegionsFourEdgesEachGraph(Scene): for e1 in r1.edges: for e2 in r2.edges: diff = e1.get_center()-e2.get_center() - if np.linalg.norm(diff) < 0.01: + if get_norm(diff) < 0.01: edge_region_pair_groups.append(VGroup( e1, r1, r2 )) diff --git a/old_projects/music_and_measure.py b/old_projects/music_and_measure.py index 848cc99c..f074979c 100644 --- a/old_projects/music_and_measure.py +++ b/old_projects/music_and_measure.py @@ -238,7 +238,7 @@ class IntervalScene(NumberLineScene): center_point+spatial_width*LEFT/2, center_point+spatial_width*RIGHT/2 ) - interval_line.do_in_place(interval_line.sort_points, np.linalg.norm) + interval_line.do_in_place(interval_line.sort_points, get_norm) interval_line.set_color(color) if run_time > 0: squished_interval = deepcopy(open_interval).stretch_to_fit_width(0) @@ -877,7 +877,7 @@ class AllValuesBetween1And2(NumberLineScene): ) self.wait(0.5) points = list(map(self.number_line.number_to_point, [approx, irrational])) - distance = np.linalg.norm(points[1]-points[0]) + distance = get_norm(points[1]-points[0]) if distance < 0.3*FRAME_X_RADIUS and num_zooms < max_num_zooms: num_zooms += 1 new_distance = 0.75*FRAME_X_RADIUS diff --git a/old_projects/nn/network.py b/old_projects/nn/network.py index 392ad01d..7da8f66a 100644 --- a/old_projects/nn/network.py +++ b/old_projects/nn/network.py @@ -255,13 +255,13 @@ def maximizing_input(network, layer_index, layer_vect, n_steps = 100, seed_guess np.array(layer_vect).reshape((1, len(layer_vect))), jacobian ).flatten() - norm = np.linalg.norm(gradient) + norm = get_norm(gradient) if norm == 0: break norms.append(norm) old_pre_sig_guess = np.array(pre_sig_guess) pre_sig_guess += 0.1*gradient - print(np.linalg.norm(old_pre_sig_guess - pre_sig_guess)) + print(get_norm(old_pre_sig_guess - pre_sig_guess)) print("") return sigmoid(pre_sig_guess) diff --git a/old_projects/nn/part2.py b/old_projects/nn/part2.py index 6d96943c..cbc68241 100644 --- a/old_projects/nn/part2.py +++ b/old_projects/nn/part2.py @@ -569,7 +569,7 @@ class FunctionMinmization(GraphScene): dot.move_to(self.input_to_graph_point(x, graph)) self.add(*[ - ContinualUpdateFromFunc(dot, update_dot) + ContinualUpdate(dot, update_dot) for dot in dots ]) self.wait(10) @@ -1752,8 +1752,8 @@ class SingleVariableCostFunction(GraphScene): new_ball.point = point balls.add(new_ball) updates += [ - ContinualUpdateFromFunc(point, update_point), - ContinualUpdateFromFunc(new_ball, update_ball) + ContinualUpdate(point, update_point), + ContinualUpdate(new_ball, update_ball) ] balls.set_color_by_gradient(BLUE, GREEN) diff --git a/old_projects/nn/part3.py b/old_projects/nn/part3.py index 89fc73b1..918b0a48 100644 --- a/old_projects/nn/part3.py +++ b/old_projects/nn/part3.py @@ -650,7 +650,7 @@ class WalkThroughTwoExample(ShowAveragingCost): c1 = n1.get_center() c2 = n2.get_center() vect = c2 - c1 - norm = np.linalg.norm(vect) + norm = get_norm(vect) unit_vect = vect / norm edge.target.put_start_and_end_on( diff --git a/old_projects/pi_day.py b/old_projects/pi_day.py index fb4850c0..d45863f5 100644 --- a/old_projects/pi_day.py +++ b/old_projects/pi_day.py @@ -42,7 +42,7 @@ class LabelTracksLine(Animation): line_center = self.line.get_center() line_end = self.line.points[-1] v = line_end - line_center - v = v/np.linalg.norm(v) + v = v/get_norm(v) w = np.array([-v[1],v[0],0]) self.mobject.move_to(line_center + self.buff * w) @@ -230,7 +230,7 @@ def get_circle_drawing_terms(radius = 1, positioning_func = lambda m : m.center( decimal.scale(0.75) def reposition_decimal(decimal): vect = radius.get_vector() - unit_vect = vect/np.linalg.norm(vect) + unit_vect = vect/get_norm(vect) angle = radius.get_angle() alpha = (-np.cos(2*angle) + 1)/2 interp_length = interpolate(decimal.get_width(), decimal.get_height(), alpha) @@ -691,7 +691,7 @@ class UsingTheta(Scene): theta = TexMobject("\\theta", "=") theta[0].match_color(arc) theta.add_background_rectangle() - update_theta = ContinualUpdateFromFunc( + update_theta = ContinualUpdate( theta, lambda m : m.shift( rotate_vector(0.9*RIGHT, radius.get_angle()/2) \ - m[1][0].get_center() diff --git a/old_projects/putnam.py b/old_projects/putnam.py index 51fa345d..272c906a 100644 --- a/old_projects/putnam.py +++ b/old_projects/putnam.py @@ -664,7 +664,7 @@ class TwoDCase(Scene): for point_mob, label in zip(point_mobs, labels): label.move_to(point_mob) vect = point_mob.get_center() - self.center - vect /= np.linalg.norm(vect) + vect /= get_norm(vect) label.shift(MED_LARGE_BUFF*vect) return labels return UpdateFromFunc(labels, update_labels) diff --git a/old_projects/pythagorean_proof.py b/old_projects/pythagorean_proof.py index 8b13654c..067c4b3f 100644 --- a/old_projects/pythagorean_proof.py +++ b/old_projects/pythagorean_proof.py @@ -59,7 +59,7 @@ class Triangle(Polygon): 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) + normal_dir /= get_norm(normal_dir) mob.shift(nudge*normal_dir) self.add(mob) return self @@ -69,7 +69,7 @@ class Triangle(Polygon): start1, start2 = self.get_vertices()[[1, 2]] target_vect = np.array(point2)-np.array(point1) curr_vect = start2-start1 - self.scale(np.linalg.norm(target_vect)/np.linalg.norm(curr_vect)) + self.scale(get_norm(target_vect)/get_norm(curr_vect)) self.rotate(angle_of_vector(target_vect)-angle_of_vector(curr_vect)) self.shift(point1-self.get_vertices()[1]) return self diff --git a/old_projects/tau_poem.py b/old_projects/tau_poem.py index fbb4111e..38be7303 100644 --- a/old_projects/tau_poem.py +++ b/old_projects/tau_poem.py @@ -280,7 +280,7 @@ class TauPoem(Scene): def line6(self): bubble = ThoughtBubble() self.play(ApplyFunction( - lambda p : 2 * p / np.linalg.norm(p), + lambda p : 2 * p / get_norm(p), bubble, rate_func = wiggle, run_time = 3.0, @@ -291,7 +291,7 @@ class TauPoem(Scene): heart = ImageMobject("heart") heart.scale(0.5).shift(DOWN).set_color("red") for mob in bubble, heart: - mob.sort_points(np.linalg.norm) + mob.sort_points(get_norm) self.add(bubble) self.wait() @@ -478,7 +478,7 @@ class TauPoem(Scene): circle.rgbas def trianglify(xxx_todo_changeme): (x, y, z) = xxx_todo_changeme - norm = np.linalg.norm((x, y, z)) + norm = get_norm((x, y, z)) comp = complex(x, y)*complex(0, 1) return ( norm * np.log(comp).imag, diff --git a/old_projects/three_dimensions.py b/old_projects/three_dimensions.py index 8c69a1e1..453657ad 100644 --- a/old_projects/three_dimensions.py +++ b/old_projects/three_dimensions.py @@ -108,6 +108,6 @@ class Sphere(Mobject2D): self.set_color(BLUE) def unit_normal(self, coords): - return np.array(coords) / np.linalg.norm(coords) + return np.array(coords) / get_norm(coords) \ No newline at end of file diff --git a/old_projects/triangle_of_power/triangle.py b/old_projects/triangle_of_power/triangle.py index c8eea676..8c1de616 100644 --- a/old_projects/triangle_of_power/triangle.py +++ b/old_projects/triangle_of_power/triangle.py @@ -643,7 +643,7 @@ class RightStaysConstantQ(Scene): Transform(triangle, equation), FadeOut(eight), ApplyPointwiseFunction( - lambda p : (p+2*DOWN)*15/np.linalg.norm(p+2*DOWN), + lambda p : (p+2*DOWN)*15/get_norm(p+2*DOWN), bubble ), FadeIn(old_style_eq1), diff --git a/old_projects/triples.py b/old_projects/triples.py index 8ab09044..a5b81c02 100644 --- a/old_projects/triples.py +++ b/old_projects/triples.py @@ -861,7 +861,7 @@ class ReframeOnLattice(PiCreatureScene): tex_mob.add_background_rectangle() point = arc_mob.point_from_proportion(0.5) tex_mob.move_to(point) - tex_mob.shift(tex_mob.get_width()*point/np.linalg.norm(point)) + tex_mob.shift(tex_mob.get_width()*point/get_norm(point)) self.play(self.pi_creature.change, "happy", arc) @@ -1635,7 +1635,7 @@ class VisualizeZSquared(Scene): vect = RIGHT else: vect = point - self.plane_center - vect /= np.linalg.norm(vect) + vect /= get_norm(vect) if abs(vect[1]) < 0.1: vect[1] = -1 label.next_to(point, vect) @@ -1906,7 +1906,7 @@ class PointsWeMiss(VisualizeZSquared): ) for z in z_list ]) - dots.sort_submobjects(np.linalg.norm) + dots.sort_submobjects(get_norm) self.add(dots) self.dots = dots @@ -2424,7 +2424,7 @@ class ProjectPointsOntoUnitCircle(DrawRadialLines): dots = self.dots dots.add(*self.new_dots) dots.sort_submobjects( - lambda p : np.linalg.norm(p - self.plane_center) + lambda p : get_norm(p - self.plane_center) ) unit_length = self.unit_circle.get_width()/2.0 for dot in dots: @@ -2434,7 +2434,7 @@ class ProjectPointsOntoUnitCircle(DrawRadialLines): if np.round(vect[0], 3) == 0 and abs(vect[1]) > 2*unit_length: dot.target.set_fill(opacity = 0) continue - distance = np.linalg.norm(vect) + distance = get_norm(vect) dot.target.scale( unit_length/distance, about_point = self.plane_center diff --git a/old_projects/uncertainty.py b/old_projects/uncertainty.py index 4aea680d..b6382218 100644 --- a/old_projects/uncertainty.py +++ b/old_projects/uncertainty.py @@ -159,7 +159,7 @@ class RadarPulseSingleton(ContinualAnimation): } def __init__(self, radar_dish, target, **kwargs): digest_config(self, kwargs) - self.direction = self.direction/np.linalg.norm(self.direction) + self.direction = self.direction/get_norm(self.direction) self.radar_dish = radar_dish self.target = target self.reflection_distance = None @@ -338,7 +338,7 @@ class MentionUncertaintyPrinciple(TeacherStudentsScene): brace.next_to(gdw, vect) text.next_to(brace, vect, buff = SMALL_BUFF) group.set_color(color) - return ContinualUpdateFromFunc(group, update_group) + return ContinualUpdate(group, update_group) dot_brace_anim = get_brace_text_group_update( dot_cloud.gaussian_distribution_wrapper, @@ -1647,7 +1647,7 @@ class LongAndShortSignalsInWindingMachine(FourierRecapScene): dot.scale(0.5) dots.add(dot) vect = point - axis_point - vect *= 1.3/np.linalg.norm(vect) + vect *= 1.3/get_norm(vect) arrow = Arrow(vect, ORIGIN, buff = SMALL_BUFF) arrow.set_color(YELLOW) arrow.shift(point) @@ -1705,7 +1705,7 @@ class MentionDopplerRadar(TeacherStudentsScene): plane.flip() pulse = RadarPulse(dish, plane) look_at_anims = [ - ContinualUpdateFromFunc( + ContinualUpdate( pi, lambda pi : pi.look_at(pulse.mobject) ) for pi in self.get_pi_creatures() @@ -1807,7 +1807,7 @@ class IntroduceDopplerRadar(Scene): run_time = 0.97*axes.x_max ) ) - randy_look_at = ContinualUpdateFromFunc( + randy_look_at = ContinualUpdate( randy, lambda pi : pi.look_at(pulse.mobject) ) axes_anim = ContinualAnimation(axes) @@ -2659,8 +2659,8 @@ class AmbiguityInLongEchos(IntroduceDopplerRadar, PiCreatureScene): movements = self.object_movements = [ ContinualMovement( obj, - direction = v/np.linalg.norm(v), - rate = np.linalg.norm(v) + direction = v/get_norm(v), + rate = get_norm(v) ) for v, obj in zip(object_velocities, objects) ] @@ -2860,11 +2860,11 @@ class SummarizeFourierTradeoffForDoppler(Scene): top_graphs = get_top_graphs() bottom_graphs = get_bottom_graphs() - update_top_graphs = ContinualUpdateFromFunc( + update_top_graphs = ContinualUpdate( top_graphs, lambda g : Transform(g, get_top_graphs()).update(1) ) - update_bottom_graphs = ContinualUpdateFromFunc( + update_bottom_graphs = ContinualUpdate( bottom_graphs, lambda g : Transform(g, get_bottom_graphs()).update(1) ) @@ -3360,7 +3360,7 @@ class SortOfDopplerEffect(PiCreatureScene): ]) return wave = get_wave() - wave_update = ContinualUpdateFromFunc( + wave_update = ContinualUpdate( wave, lambda w : Transform(w, get_wave()).update(1) ) @@ -3369,7 +3369,7 @@ class SortOfDopplerEffect(PiCreatureScene): rect_movement = ContinualMovement(rect, direction = LEFT, rate = 1) randy = self.pi_creature - randy_look_at = ContinualUpdateFromFunc( + randy_look_at = ContinualUpdate( randy, lambda r : r.look_at(rect) ) @@ -3379,7 +3379,7 @@ class SortOfDopplerEffect(PiCreatureScene): ref_frame2 = TextMobject("Reference frame 2") ref_frame2.next_to(rect, UP) # ref_frame2.set_fill(opacity = 0) - ref_frame2_follow = ContinualUpdateFromFunc( + ref_frame2_follow = ContinualUpdate( ref_frame2, lambda m : m.next_to(rect, UP) ) ref_frame_1_continual_anim = ContinualAnimation(ref_frame1) @@ -3502,7 +3502,7 @@ class HangingWeightsScene(MovingCameraScene): d_height = A*np.cos(TAU*f*t - k*x) new_spring = get_spring(spring.alpha, 2+d_height) Transform(spring, new_spring).update(1) - spring_update_anim = ContinualUpdateFromFunc(springs, update_springs) + spring_update_anim = ContinualUpdate(springs, update_springs) self.spring_update_anim = spring_update_anim spring_update_anim.update(0) @@ -3521,7 +3521,7 @@ class HangingWeightsScene(MovingCameraScene): weight.start_radius = 0.15 weight.target_radius = 0.25*mass #For future update weight.spring = spring - weight_anim = ContinualUpdateFromFunc( + weight_anim = ContinualUpdate( weight, lambda w : w.move_to(w.spring.get_bottom()) ) weight_anim.update(0) @@ -3665,7 +3665,7 @@ class HangingWeightsScene(MovingCameraScene): de_broglie.set_height(6) de_broglie.next_to(4*DOWN, DOWN) self.add( - ContinualUpdateFromFunc( + ContinualUpdate( randy, lambda m : m.next_to( rect.get_corner(DOWN+LEFT), UP+RIGHT, MED_LARGE_BUFF, ).look_at(weights) @@ -4101,7 +4101,7 @@ class ProbabalisticDetection(FourierTransformOfWaveFunction): rect.save_state() rect.stretch(0, 0) - gdw_anim = ContinualUpdateFromFunc( + gdw_anim = ContinualUpdate( gdw, lambda m : m.set_width( 2.0/(self.a_tracker.get_value()**(0.5)) ).move_to(rect) @@ -4123,7 +4123,7 @@ class ProbabalisticDetection(FourierTransformOfWaveFunction): answer.submobjects = [yes] else: answer.submobjects = [no] - answer_anim = ContinualUpdateFromFunc(answer, update_answer) + answer_anim = ContinualUpdate(answer, update_answer) self.add(gdw_anim, particle) self.play( @@ -4339,13 +4339,13 @@ class ThinkOfHeisenbergUncertainty(PiCreatureScene): freq = 1 continual_anims = [ ContinualMovement(time_tracker, direction = RIGHT, rate = 1), - ContinualUpdateFromFunc( + ContinualUpdate( dot_gdw, lambda d : d.set_width( (np.cos(freq*time_tracker.get_value()) + 1.1)/2 ) ), - ContinualUpdateFromFunc( + ContinualUpdate( vector_gdw, lambda d : d.set_width( (-np.cos(freq*time_tracker.get_value()) + 1.1)/2 diff --git a/old_projects/wallis.py b/old_projects/wallis.py index b35e1959..ffdd88b2 100644 --- a/old_projects/wallis.py +++ b/old_projects/wallis.py @@ -891,7 +891,7 @@ class DistanceProductScene(MovingCameraScene): d_label = TexMobject("d_%d" % i) d_label.set_height(self.d_label_height) vect = rotate_vector(line.get_vector(), 90 * DEGREES) - vect *= 2.5 * SMALL_BUFF / np.linalg.norm(vect) + vect *= 2.5 * SMALL_BUFF / get_norm(vect) d_label.move_to(line.get_center() + vect) self.d_labels.add(d_label) return self.d_labels @@ -1004,7 +1004,7 @@ class DistanceProductScene(MovingCameraScene): radius = self.get_radius() observer_point = self.get_observer_point(fraction) distances = [ - np.linalg.norm(point - observer_point) / radius + get_norm(point - observer_point) / radius for point in self.get_lh_points() ] return reduce(op.mul, distances, 1.0) @@ -1959,7 +1959,7 @@ class PlugObserverIntoPolynomial(DistanceProductScene): def add_circle_group(self): self.circle.set_color(RED) self.circle.set_width( - 2 * np.linalg.norm(self.plane.number_to_point(1) - self.origin) + 2 * get_norm(self.plane.number_to_point(1) - self.origin) ) self.circle.move_to(self.origin) @@ -2015,7 +2015,7 @@ class PlugObserverIntoPolynomial(DistanceProductScene): dot.match_color(observer) vect = 2 * DOWN + LEFT - vect /= np.linalg.norm(vect) + vect /= get_norm(vect) arrow = self.arrow = Vector(0.5 * vect) arrow.next_to(observer, -vect, buff=SMALL_BUFF) arrow.set_color(WHITE) @@ -3848,7 +3848,7 @@ class KeeperAndSailor(DistanceProductScene, PiCreatureScene): return fraction_tracker.get_value() def get_ks_distance(): - return np.linalg.norm(keeper.dot.get_center() - sailor.dot.get_center()) + return get_norm(keeper.dot.get_center() - sailor.dot.get_center()) def update_title_heights(*titles): for title in titles: @@ -3987,7 +3987,7 @@ class KeeperAndSailor(DistanceProductScene, PiCreatureScene): for light, label in zip(self.lights, labels): point = light[0].get_center() vect = (point - center) - norm = np.linalg.norm(vect) + norm = get_norm(vect) buff = label.get_height() vect *= (norm + buff) / norm label.move_to(center + vect) @@ -4592,7 +4592,7 @@ class KeeperAndSailorForSineProduct(KeeperAndSailor): def warp_func(point): vect = point - center - norm = np.linalg.norm(vect) + norm = get_norm(vect) new_norm = norm + 0.5 * (radius - norm) return center + new_norm * vect / norm brace1.apply_function(warp_func) diff --git a/old_projects/waves.py b/old_projects/waves.py index cb05c5ff..b3c9ee51 100644 --- a/old_projects/waves.py +++ b/old_projects/waves.py @@ -103,7 +103,7 @@ class EMWave(ContinualAnimationGroup): self.E_vects = VGroup() self.M_vects = VGroup() - self.A_vect = np.array(self.A_vect)/np.linalg.norm(self.A_vect) + self.A_vect = np.array(self.A_vect)/get_norm(self.A_vect) self.A_vect *= self.amplitude for alpha in np.linspace(0, 1, self.n_vectors): @@ -151,7 +151,7 @@ class EMWave(ContinualAnimationGroup): new_amplitude = np.clip( new_smooth(middle_alpha - alpha), epsilon, 1 ) - norm = np.linalg.norm(ov.A_vect) + norm = get_norm(ov.A_vect) if norm != 0: ov.A_vect = new_amplitude * np.array(ov.A_vect) / norm @@ -216,7 +216,7 @@ class WavePacket(Animation): em_wave.propogation_direction ) A = em_wave.amplitude*self.E_func(distance_from_packet) - distance_from_start = np.linalg.norm(tail - em_wave.start_point) + distance_from_start = get_norm(tail - em_wave.start_point) if self.get_filtered and distance_from_start > self.filter_distance: A = 0 epsilon = 0.05 @@ -305,7 +305,7 @@ class FilterScene(ThreeDScene): self.add(self.pol_filters) self.pol_filter = self.pol_filters[0] - self.set_camera_position(self.start_phi, self.start_theta) + self.set_camera_orientation(self.start_phi, self.start_theta) if self.ambient_rotation_rate > 0: self.begin_ambient_camera_rotation(self.ambient_rotation_rate) @@ -693,7 +693,7 @@ class IntroduceElectricField(PiCreatureScene): ) VGroup(*shading_list).set_color_by_gradient(*self.vector_field_colors) result.set_fill(opacity = 0.75) - result.sort_submobjects(np.linalg.norm) + result.sort_submobjects(get_norm) return result @@ -706,7 +706,7 @@ class IntroduceElectricField(PiCreatureScene): return self.normalized(result) def normalized(self, vector): - norm = np.linalg.norm(vector) or 1 + norm = get_norm(vector) or 1 target_length = self.max_vector_length * sigmoid(0.1*norm) return target_length * vector/norm @@ -719,7 +719,7 @@ class IntroduceMagneticField(IntroduceElectricField, ThreeDScene): self.remove(self.pi_creature) def construct(self): - self.set_camera_position(0.1, -np.pi/2) + self.set_camera_orientation(0.1, -np.pi/2) self.add_title() self.add_vector_field() self.introduce_moving_charge() @@ -974,7 +974,7 @@ class IntroduceEMWave(ThreeDScene): self.add(self.axes) self.em_wave = EMWave(**self.EMWave_config) self.add(self.em_wave) - self.set_camera_position(0.8*np.pi/2, -0.7*np.pi) + self.set_camera_orientation(0.8*np.pi/2, -0.7*np.pi) self.begin_ambient_camera_rotation() def construct(self): @@ -1066,7 +1066,7 @@ class DirectWaveOutOfScreen(IntroduceEMWave): self.remove(self.axes) for ov in self.em_wave.continual_animations: ov.vector.normal_vector = RIGHT - self.set_camera_position(0.9*np.pi/2, -0.3*np.pi) + self.set_camera_orientation(0.9*np.pi/2, -0.3*np.pi) def construct(self): self.move_into_position() @@ -1199,10 +1199,10 @@ class ShowVectorEquation(Scene): ) brace.next_to(self.vector.get_center(), DOWN, SMALL_BUFF) return brace - moving_brace = ContinualUpdateFromFunc( + moving_brace = ContinualUpdate( Brace(Line(LEFT, RIGHT), DOWN), update_brace ) - moving_x_without_phi = ContinualUpdateFromFunc( + moving_x_without_phi = ContinualUpdate( x_without_phi.copy().add_background_rectangle(), lambda m : m.next_to(moving_brace.mobject, DOWN, SMALL_BUFF) ) @@ -1548,7 +1548,7 @@ class ChangeFromHorizontalToVerticallyPolarized(DirectionOfPolarizationScene): vect.set_fill(opacity = 0.5) self.em_wave.E_vects[-1].set_fill(opacity = 1) - self.set_camera_position(0.9*np.pi/2, -0.05*np.pi) + self.set_camera_orientation(0.9*np.pi/2, -0.05*np.pi) def construct(self): self.wait(3) @@ -1584,7 +1584,7 @@ class SumOfTwoWaves(ChangeFromHorizontalToVerticallyPolarized): self.add(axes, em_wave) self.side_em_waves.append(em_wave) - self.set_camera_position(0.95*np.pi/2, -0.03*np.pi) + self.set_camera_orientation(0.95*np.pi/2, -0.03*np.pi) def construct(self): plus, equals = pe = VGroup(*list(map(TexMobject, "+="))) @@ -1621,7 +1621,7 @@ class ShowTipToTailSum(ShowVectorEquation): self.v_oscillating_vector.A_vect = [0, 2, 0] self.v_oscillating_vector.update(0) - self.d_oscillating_vector = ContinualUpdateFromFunc( + self.d_oscillating_vector = ContinualUpdate( Vector(UP+RIGHT, color = E_COLOR), lambda v : v.put_start_and_end_on( ORIGIN, @@ -1696,8 +1696,8 @@ class ShowTipToTailSum(ShowVectorEquation): self.h_oscillating_vector, self.v_oscillating_vector, self.d_oscillating_vector, - ContinualUpdateFromFunc(h_line, h_line.update), - ContinualUpdateFromFunc(v_line, v_line.update), + ContinualUpdate(h_line, h_line.update), + ContinualUpdate(v_line, v_line.update), ) self.wait(4) @@ -2163,10 +2163,10 @@ class ShowPolarizingFilter(DirectionOfPolarizationScene): return update_decimal continual_updates = [ - ContinualUpdateFromFunc( + ContinualUpdate( A_x, generate_decimal_update(np.sin), ), - ContinualUpdateFromFunc( + ContinualUpdate( A_y, generate_decimal_update(np.cos), ), ] @@ -2404,7 +2404,7 @@ class DescribePhoton(ThreeDScene): self.axes = ThreeDAxes() self.add(self.axes) - self.set_camera_position(phi = 0.8*np.pi/2, theta = -np.pi/4) + self.set_camera_orientation(phi = 0.8*np.pi/2, theta = -np.pi/4) em_wave = EMWave( start_point = FRAME_X_RADIUS*LEFT, A_vect = [0, 1, 1], @@ -2964,7 +2964,7 @@ class ShootPhotonThroughFilter(DirectionOfPolarizationScene): self.pol_filter.save_state() self.pol_filter.shift(5*OUT) - self.set_camera_position(theta = -0.9*np.pi) + self.set_camera_orientation(theta = -0.9*np.pi) self.play(self.pol_filter.restore) self.move_camera( theta = -0.6*np.pi, @@ -4013,7 +4013,7 @@ class CircularPhotons(ShootPhotonThroughFilter): "apply_filter" : False, } def construct(self): - self.set_camera_position(theta = -0.75*np.pi) + self.set_camera_orientation(theta = -0.75*np.pi) self.setup_filter() self.show_phase_difference() self.shoot_circular_photons() diff --git a/old_projects/wcat.py b/old_projects/wcat.py index 30b670c9..fda29ef0 100644 --- a/old_projects/wcat.py +++ b/old_projects/wcat.py @@ -122,7 +122,7 @@ class ClosedLoopScene(Scene): loop_points = np.array(list(map(self.loop.point_from_proportion, alpha_range))) for dot in dots: vects = loop_points - dot.get_center() - norms = np.apply_along_axis(np.linalg.norm, 1, vects) + norms = np.apply_along_axis(get_norm, 1, vects) index = np.argmin(norms) alphas.append(alpha_range[index]) return alphas @@ -197,13 +197,13 @@ class ClosedLoopScene(Scene): def square_scores(self, all_quads): midpoint_diffs = np.apply_along_axis( - np.linalg.norm, 1, + get_norm, 1, 0.5*(all_quads[:,0] + all_quads[:,2]) - 0.5*(all_quads[:,1] + all_quads[:,3]) ) vects1 = all_quads[:,0] - all_quads[:,2] vects2 = all_quads[:,1] - all_quads[:,3] - distances1 = np.apply_along_axis(np.linalg.norm, 1, vects1) - distances2 = np.apply_along_axis(np.linalg.norm, 1, vects2) + distances1 = np.apply_along_axis(get_norm, 1, vects1) + distances2 = np.apply_along_axis(get_norm, 1, vects2) distance_diffs = np.abs(distances1 - distances2) midpoint_diffs /= distances1 distance_diffs /= distances2 diff --git a/old_projects/zeta.py b/old_projects/zeta.py index c0fa195d..f3a091d6 100644 --- a/old_projects/zeta.py +++ b/old_projects/zeta.py @@ -41,7 +41,7 @@ class ZetaTransformationScene(ComplexTransformationScene): continue p1 = line.get_start()+LEFT p2 = line.get_end()+LEFT - t = (-np.dot(p1, p2-p1))/(np.linalg.norm(p2-p1)**2) + t = (-np.dot(p1, p2-p1))/(get_norm(p2-p1)**2) closest_to_one = interpolate( line.get_start(), line.get_end(), t ) @@ -2327,7 +2327,7 @@ class IntroduceAnglePreservation(VisualizingSSquared): vect = arc.point_from_proportion(0.5)-interpolate( arc.points[0], arc.points[-1], 0.5 ) - unit_vect = vect/np.linalg.norm(vect) + unit_vect = vect/get_norm(vect) angle_tex.move_to(arc.get_center() + 1.7*unit_vect) def get_right_angle_bracket(self, input_z): diff --git a/once_useful_constructs/fractals.py b/once_useful_constructs/fractals.py index 0bb29d45..51310d41 100644 --- a/once_useful_constructs/fractals.py +++ b/once_useful_constructs/fractals.py @@ -49,11 +49,11 @@ def fractalification_iteration(vmobject, dimension=1.05, num_inserted_anchors_ra ] mass_scaling_factor = 1. / (num_inserts + 1) length_scaling_factor = mass_scaling_factor**(1. / dimension) - target_length = np.linalg.norm(p1 - p2) * length_scaling_factor - curr_length = np.linalg.norm(p1 - p2) * mass_scaling_factor + target_length = get_norm(p1 - p2) * length_scaling_factor + curr_length = get_norm(p1 - p2) * mass_scaling_factor # offset^2 + curr_length^2 = target_length^2 offset_len = np.sqrt(target_length**2 - curr_length**2) - unit_vect = (p1 - p2) / np.linalg.norm(p1 - p2) + unit_vect = (p1 - p2) / get_norm(p1 - p2) offset_unit_vect = rotate_vector(unit_vect, np.pi / 2) inserted_points = [ point + u * offset_len * offset_unit_vect diff --git a/once_useful_constructs/graph_theory.py b/once_useful_constructs/graph_theory.py index 81a5fc36..0fb9650f 100644 --- a/once_useful_constructs/graph_theory.py +++ b/once_useful_constructs/graph_theory.py @@ -408,7 +408,7 @@ class DiscreteGraphScene(Scene): self.points[pair[0]], self.points[pair[1]] ]) - new_point - new_point += FRAME_X_RADIUS * vect / np.linalg.norm(vect) + new_point += FRAME_X_RADIUS * vect / get_norm(vect) dual_point_pair[i] = new_point self.dual_edges.append( Line(*dual_point_pair).set_color() diff --git a/once_useful_constructs/light.py b/once_useful_constructs/light.py index 71d8be9c..f3694613 100644 --- a/once_useful_constructs/light.py +++ b/once_useful_constructs/light.py @@ -177,7 +177,7 @@ class Spotlight(VMobject): [phi, theta, r] = self.camera_mob.get_center() v = np.array([np.sin(phi) * np.cos(theta), np.sin(phi) * np.sin(theta), np.cos(phi)]) - return v # /np.linalg.norm(v) + return v # /get_norm(v) def project(self, point): v = self.projection_direction() @@ -260,7 +260,7 @@ class Spotlight(VMobject): lower_angle, upper_angle = self.viewing_angles(screen) projected_RIGHT = self.project( - RIGHT) / np.linalg.norm(self.project(RIGHT)) + RIGHT) / get_norm(self.project(RIGHT)) lower_ray = rotate_vector( projected_RIGHT, lower_angle, axis=self.projection_direction()) upper_ray = rotate_vector( @@ -582,10 +582,10 @@ class LightSource(VMobject): return ray1 = anchors[source_index - 1] - projected_source - ray1 = ray1 / np.linalg.norm(ray1) * 100 + ray1 = ray1 / get_norm(ray1) * 100 ray2 = anchors[source_index] - projected_source - ray2 = ray2 / np.linalg.norm(ray2) * 100 + ray2 = ray2 / get_norm(ray2) * 100 outpoint1 = anchors[source_index - 1] + ray1 outpoint2 = anchors[source_index] + ray2 diff --git a/scene/scene.py b/scene/scene.py index 1f9f072f..3210a6ea 100644 --- a/scene/scene.py +++ b/scene/scene.py @@ -216,6 +216,9 @@ class Scene(Container): return num_families == 1 return list(filter(is_top_level, mobjects)) + def get_mobject_family_members(self): + return self.camera.extract_mobject_family_members(self.mobjects) + def separate_mobjects_and_continual_animations(self, mobjects_or_continual_animations): mobjects = [] continual_animations = [] @@ -461,7 +464,7 @@ class Scene(Container): animation.update_config(**kwargs) # Anything animated that's not already in the # scene gets added to the scene - if animation.mobject not in self.mobjects: + if animation.mobject not in self.get_mobject_family_members(): self.add(animation.mobject) moving_mobjects = self.get_moving_mobjects(*animations) diff --git a/scene/three_d_scene.py b/scene/three_d_scene.py index 58f79051..4c4323e7 100644 --- a/scene/three_d_scene.py +++ b/scene/three_d_scene.py @@ -1,14 +1,10 @@ - - from constants import * -from continual_animation.continual_animation import ContinualMovement +from continual_animation.update import ContinualGrowValue from animation.transform import ApplyMethod from camera.three_d_camera import ThreeDCamera from scene.scene import Scene -from utils.iterables import list_update - class ThreeDScene(Scene): CONFIG = { @@ -16,17 +12,19 @@ class ThreeDScene(Scene): "ambient_camera_rotation": None, } - def set_camera_position(self, phi=None, theta=None, distance=None, - center_x=None, center_y=None, center_z=None): - self.camera.set_position( - phi, theta, distance, - center_x, center_y, center_z - ) + def set_camera_orientation(self, phi=None, theta=None, distance=None, gamma=None): + if phi is not None: + self.camera.set_phi(phi) + if theta is not None: + self.camera.set_theta(theta) + if distance is not None: + self.camera.set_distance(distance) + if gamma is not None: + self.camera.set_gamma(gamma) - def begin_ambient_camera_rotation(self, rate=0.01): - self.ambient_camera_rotation = ContinualMovement( - self.camera.rotation_mobject, - direction=UP, + def begin_ambient_camera_rotation(self, rate=0.1): + self.ambient_camera_rotation = ContinualGrowValue( + self.camera.theta_tracker, rate=rate ) self.add(self.ambient_camera_rotation) @@ -36,36 +34,41 @@ class ThreeDScene(Scene): self.remove(self.ambient_camera_rotation) self.ambient_camera_rotation = None - def move_camera( - self, - phi=None, theta=None, distance=None, - center_x=None, center_y=None, center_z=None, - added_anims=[], - **kwargs - ): - target_point = self.camera.get_spherical_coords(phi, theta, distance) - movement = ApplyMethod( - self.camera.rotation_mobject.move_to, - target_point, - **kwargs - ) - target_center = self.camera.get_center_of_rotation( - center_x, center_y, center_z) - movement_center = ApplyMethod( - self.camera.moving_center.move_to, - target_center, - **kwargs - ) + def move_camera(self, + phi=None, + theta=None, + distance=None, + gamma=None, + frame_center=None, + added_anims=[], + **kwargs): + anims = [] + value_tracker_pairs = [ + (phi, self.camera.phi_tracker), + (theta, self.camera.theta_tracker), + (distance, self.camera.distance_tracker), + (gamma, self.camera.gamma_tracker), + ] + for value, tracker in value_tracker_pairs: + if value is not None: + anims.append( + ApplyMethod(tracker.set_value, value, **kwargs) + ) + if frame_center is not None: + anims.append(ApplyMethod( + self.camera.frame_center.move_to, + frame_center + )) is_camera_rotating = self.ambient_camera_rotation in self.continual_animations if is_camera_rotating: self.remove(self.ambient_camera_rotation) - self.play(movement, movement_center, *added_anims) - target_point = self.camera.get_spherical_coords(phi, theta, distance) + self.play(*anims + added_anims) if is_camera_rotating: self.add(self.ambient_camera_rotation) def get_moving_mobjects(self, *animations): moving_mobjects = Scene.get_moving_mobjects(self, *animations) - if self.camera.rotation_mobject in moving_mobjects: - return list_update(self.mobjects, moving_mobjects) + camera_mobjects = self.camera.get_value_trackers() + if any([cm in moving_mobjects for cm in camera_mobjects]): + return self.mobjects return moving_mobjects diff --git a/scene/vector_space_scene.py b/scene/vector_space_scene.py index 32645885..6b210e39 100644 --- a/scene/vector_space_scene.py +++ b/scene/vector_space_scene.py @@ -32,6 +32,7 @@ from mobject.matrix import vector_coordinate_label from utils.rate_functions import rush_from from utils.rate_functions import rush_into from utils.space_ops import angle_of_vector +from utils.space_ops import get_norm X_COLOR = GREEN_C Y_COLOR = RED_C @@ -138,7 +139,7 @@ class VectorScene(Scene): if at_tip: vect = vector.get_vector() - vect /= np.linalg.norm(vect) + vect /= get_norm(vect) label.next_to(vector.get_end(), vect, buff=SMALL_BUFF) else: angle = vector.get_angle() @@ -453,7 +454,7 @@ class LinearTransformationScene(VectorScene): def get_vector_movement(self, func): for v in self.moving_vectors: v.target = Vector(func(v.get_end()), color=v.get_color()) - norm = np.linalg.norm(v.target.get_end()) + norm = get_norm(v.target.get_end()) if norm < 0.1: v.target.get_tip().scale_in_place(norm) return self.get_piece_movement(self.moving_vectors) diff --git a/template.tex b/template.tex deleted file mode 100644 index d12a9151..00000000 --- a/template.tex +++ /dev/null @@ -1,24 +0,0 @@ -\documentclass[preview]{standalone} - -\usepackage[english]{babel} -% \usepackage[utf8x]{inputenc} -\usepackage{amsmath} -\usepackage{amssymb} -\usepackage{dsfont} -\usepackage{setspace} -\usepackage{tipa} -\usepackage{relsize} -\usepackage{mathrsfs} -\usepackage{calligra} -\usepackage{wasysym} -\usepackage{textcomp} -%\usepackage[UTF8]{ctex} - -\begin{document} -\centering - -\begin{align*} - YourTextHere -\end{align*} - -\end{document} \ No newline at end of file diff --git a/text_template.tex b/tex_template.tex similarity index 86% rename from text_template.tex rename to tex_template.tex index 7c319f2e..17195880 100644 --- a/text_template.tex +++ b/tex_template.tex @@ -1,7 +1,6 @@ \documentclass[preview]{standalone} \usepackage[english]{babel} -% \usepackage[utf8x]{inputenc} \usepackage{amsmath} \usepackage{amssymb} \usepackage{dsfont} @@ -16,6 +15,8 @@ \usepackage{physics} \usepackage{xcolor} \usepackage{textcomp} +\usepackage{microtype} +\DisableLigatures{encoding = *, family = * } %\usepackage[UTF8]{ctex} \linespread{1} diff --git a/utils/bezier.py b/utils/bezier.py index e4a4a2a0..acf18533 100644 --- a/utils/bezier.py +++ b/utils/bezier.py @@ -2,6 +2,7 @@ import numpy as np from scipy import linalg from utils.simple_functions import choose +from utils.space_ops import get_norm CLOSED_THRESHOLD = 0.001 @@ -133,4 +134,4 @@ def diag_to_matrix(l_and_u, diag): def is_closed(points): - return np.linalg.norm(points[0] - points[-1]) < CLOSED_THRESHOLD + return get_norm(points[0] - points[-1]) < CLOSED_THRESHOLD diff --git a/utils/color.py b/utils/color.py index b5f308ba..ecb8962c 100644 --- a/utils/color.py +++ b/utils/color.py @@ -6,14 +6,17 @@ from constants import WHITE from constants import PALETTE from utils.bezier import interpolate +from utils.space_ops import normalize def color_to_rgb(color): - return np.array(Color(color).get_rgb()) + if not isinstance(color, Color): + color = Color(color) + return np.array(color.get_rgb()) def color_to_rgba(color, alpha=1): - return np.append(color_to_rgb(color), [alpha]) + return np.array([*color_to_rgb(color), alpha]) def rgb_to_color(rgb): @@ -82,3 +85,11 @@ def random_bright_color(): def random_color(): return random.choice(PALETTE) + + +def get_shaded_rgb(rgb, point, unit_normal_vect, light_source): + to_sun = normalize(light_source - point) + factor = 0.5 * np.dot(unit_normal_vect, to_sun)**3 + if factor < 0: + factor *= 0.5 + return np.clip(rgb + factor, 0, 1) diff --git a/utils/paths.py b/utils/paths.py index 229960a7..b45faa9a 100644 --- a/utils/paths.py +++ b/utils/paths.py @@ -3,6 +3,7 @@ import numpy as np from constants import OUT from utils.bezier import interpolate from utils.space_ops import rotation_matrix +from utils.space_ops import get_norm STRAIGHT_PATH_THRESHOLD = 0.01 @@ -24,9 +25,9 @@ def path_along_arc(arc_angle, axis=OUT): """ if abs(arc_angle) < STRAIGHT_PATH_THRESHOLD: return straight_path - if np.linalg.norm(axis) == 0: + if get_norm(axis) == 0: axis = OUT - unit_axis = axis / np.linalg.norm(axis) + unit_axis = axis / get_norm(axis) def path(start_points, end_points, alpha): vects = end_points - start_points diff --git a/utils/space_ops.py b/utils/space_ops.py index 46573c39..cc8f5039 100644 --- a/utils/space_ops.py +++ b/utils/space_ops.py @@ -6,6 +6,9 @@ from functools import reduce # Matrix operations +def get_norm(vect): + return sum([x**2 for x in vect])**0.5 + def thick_diagonal(dim, thickness=2): row_indices = np.arange(dim).repeat(dim).reshape((dim, dim)) @@ -36,14 +39,14 @@ def z_to_vector(vector): Returns some matrix in SO(3) which takes the z-axis to the (normalized) vector provided as an argument """ - norm = np.linalg.norm(vector) + norm = get_norm(vector) if norm == 0: return np.identity(3) v = np.array(vector) / norm phi = np.arccos(v[2]) if any(v[:2]): # projection of vector to unit circle - axis_proj = v[:2] / np.linalg.norm(v[:2]) + axis_proj = v[:2] / get_norm(v[:2]) theta = np.arccos(axis_proj[0]) if axis_proj[1] < 0: theta = -theta @@ -63,8 +66,8 @@ def rotate_vector(vector, angle, axis=OUT): def angle_between(v1, v2): return np.arccos(np.dot( - v1 / np.linalg.norm(v1), - v2 / np.linalg.norm(v2) + v1 / get_norm(v1), + v2 / get_norm(v2) )) @@ -83,8 +86,8 @@ def angle_between_vectors(v1, v2): Returns the angle between two 3D vectors. This angle will always be btw 0 and TAU/2. """ - l1 = np.linalg.norm(v1) - l2 = np.linalg.norm(v2) + l1 = get_norm(v1) + l2 = get_norm(v2) return np.arccos(np.dot(v1, v2) / (l1 * l2)) @@ -92,6 +95,27 @@ def project_along_vector(point, vector): matrix = np.identity(3) - np.outer(vector, vector) return np.dot(point, matrix.T) + +def normalize(vect): + norm = get_norm(vect) + if norm > 0: + return vect / norm + else: + return np.zeros(len(vect)) + + +def cross(v1, v2): + return np.array([ + v1[1] * v2[2] - v1[2] * v2[1], + v1[2] * v2[0] - v1[0] * v2[2], + v1[0] * v2[1] - v1[1] * v2[0] + ]) + + +def get_unit_normal(v1, v2): + return normalize(cross(v1, v2)) + + ###