repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/directories.py
manimlib/utils/directories.py
from __future__ import annotations import os import tempfile import appdirs from manimlib.config import manim_config from manimlib.config import get_manim_dir from manimlib.utils.file_ops import guarantee_existence def get_directories() -> dict[str, str]: return manim_config.directories def get_cache_dir() -> str: return get_directories()["cache"] or appdirs.user_cache_dir("manim") def get_temp_dir() -> str: return get_directories()["temporary_storage"] or tempfile.gettempdir() def get_downloads_dir() -> str: return get_directories()["downloads"] or appdirs.user_cache_dir("manim_downloads") def get_output_dir() -> str: return guarantee_existence(get_directories()["output"]) def get_raster_image_dir() -> str: return get_directories()["raster_images"] def get_vector_image_dir() -> str: return get_directories()["vector_images"] def get_sound_dir() -> str: return get_directories()["sounds"] def get_shader_dir() -> str: return os.path.join(get_manim_dir(), "manimlib", "shaders")
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/family_ops.py
manimlib/utils/family_ops.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable, List, Set, Tuple from manimlib.mobject.mobject import Mobject def extract_mobject_family_members( mobject_list: Iterable[Mobject], exclude_pointless: bool = False ) -> list[Mobject]: return [ sm for mob in mobject_list for sm in mob.get_family() if (not exclude_pointless) or sm.has_points() ] def recursive_mobject_remove(mobjects: List[Mobject], to_remove: Set[Mobject]) -> Tuple[List[Mobject], bool]: """ Takes in a list of mobjects, together with a set of mobjects to remove. The first component of what's removed is a new list such that any mobject with one of the elements from `to_remove` in its family is no longer in the list, and in its place are its family members which aren't in `to_remove` The second component is a boolean value indicating whether any removals were made """ result = [] found_in_list = False for mob in mobjects: if mob in to_remove: found_in_list = True continue # Recursive call sub_list, found_in_submobjects = recursive_mobject_remove( mob.submobjects, to_remove ) if found_in_submobjects: result.extend(sub_list) found_in_list = True else: result.append(mob) return result, found_in_list
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/space_ops.py
manimlib/utils/space_ops.py
from __future__ import annotations from functools import reduce import math import operator as op import platform from mapbox_earcut import triangulate_float32 as earcut import numpy as np from scipy.spatial.transform import Rotation from tqdm.auto import tqdm as ProgressDisplay from manimlib.constants import DOWN, OUT, RIGHT, UP from manimlib.constants import PI, TAU from manimlib.utils.iterables import adjacent_pairs from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Sequence, List, Tuple from manimlib.typing import Vect2, Vect3, Vect4, VectN, Matrix3x3, Vect3Array, Vect2Array def cross( v1: Vect3 | List[float], v2: Vect3 | List[float], out: np.ndarray | None = None ) -> Vect3 | Vect3Array: is2d = isinstance(v1, np.ndarray) and len(v1.shape) == 2 if is2d: x1, y1, z1 = v1[:, 0], v1[:, 1], v1[:, 2] x2, y2, z2 = v2[:, 0], v2[:, 1], v2[:, 2] else: x1, y1, z1 = v1 x2, y2, z2 = v2 if out is None: out = np.empty(np.shape(v1)) out.T[:] = [ y1 * z2 - z1 * y2, z1 * x2 - x1 * z2, x1 * y2 - y1 * x2, ] return out def get_norm(vect: VectN | List[float]) -> float: return sum((x**2 for x in vect))**0.5 def get_dist(vect1: VectN, vect2: VectN): return get_norm(vect2 - vect1) def normalize( vect: VectN | List[float], fall_back: VectN | List[float] | None = None ) -> VectN: norm = get_norm(vect) if norm > 0: return np.array(vect) / norm elif fall_back is not None: return np.array(fall_back) else: return np.zeros(len(vect)) def poly_line_length(points): """ Return the sum of the lengths between adjacent points """ diffs = points[1:] - points[:-1] return np.sqrt((diffs**2).sum(1)).sum() # Operations related to rotation def quaternion_mult(*quats: Vect4) -> Vect4: """ Inputs are treated as quaternions, where the real part is the last entry, so as to follow the scipy Rotation conventions. """ if len(quats) == 0: return np.array([0, 0, 0, 1]) result = np.array(quats[0]) for next_quat in quats[1:]: x1, y1, z1, w1 = result x2, y2, z2, w2 = next_quat result[:] = [ w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2, w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2, w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, ] return result def quaternion_from_angle_axis( angle: float, axis: Vect3, ) -> Vect4: return Rotation.from_rotvec(angle * normalize(axis)).as_quat() def angle_axis_from_quaternion(quat: Vect4) -> Tuple[float, Vect3]: rot_vec = Rotation.from_quat(quat).as_rotvec() norm = get_norm(rot_vec) return norm, rot_vec / norm def quaternion_conjugate(quaternion: Vect4) -> Vect4: result = np.array(quaternion) result[:3] *= -1 return result def rotate_vector( vector: Vect3, angle: float, axis: Vect3 = OUT ) -> Vect3: rot = Rotation.from_rotvec(angle * normalize(axis)) return np.dot(vector, rot.as_matrix().T) def rotate_vector_2d(vector: Vect2, angle: float) -> Vect2: # Use complex numbers...because why not z = complex(*vector) * np.exp(complex(0, angle)) return np.array([z.real, z.imag]) def rotation_matrix_transpose_from_quaternion(quat: Vect4) -> Matrix3x3: return Rotation.from_quat(quat).as_matrix() def rotation_matrix_from_quaternion(quat: Vect4) -> Matrix3x3: return np.transpose(rotation_matrix_transpose_from_quaternion(quat)) def rotation_matrix(angle: float, axis: Vect3) -> Matrix3x3: """ Rotation in R^3 about a specified axis of rotation. """ return Rotation.from_rotvec(angle * normalize(axis)).as_matrix() def rotation_matrix_transpose(angle: float, axis: Vect3) -> Matrix3x3: return rotation_matrix(angle, axis).T def rotation_about_z(angle: float) -> Matrix3x3: cos_a = math.cos(angle) sin_a = math.sin(angle) return np.array([ [cos_a, -sin_a, 0], [sin_a, cos_a, 0], [0, 0, 1] ]) def rotation_between_vectors(v1: Vect3, v2: Vect3) -> Matrix3x3: atol = 1e-8 if get_norm(v1 - v2) < atol: return np.identity(3) axis = cross(v1, v2) if get_norm(axis) < atol: # v1 and v2 align axis = cross(v1, RIGHT) if get_norm(axis) < atol: # v1 and v2 _and_ RIGHT all align axis = cross(v1, UP) return rotation_matrix( angle=angle_between_vectors(v1, v2), axis=axis, ) def z_to_vector(vector: Vect3) -> Matrix3x3: return rotation_between_vectors(OUT, vector) def angle_of_vector(vector: Vect2 | Vect3) -> float: """ Returns polar coordinate theta when vector is project on xy plane """ return math.atan2(vector[1], vector[0]) def angle_between_vectors(v1: VectN, v2: VectN) -> float: """ Returns the angle between two 3D vectors. This angle will always be btw 0 and pi """ n1 = get_norm(v1) n2 = get_norm(v2) if n1 == 0 or n2 == 0: return 0 cos_angle = np.dot(v1, v2) / np.float64(n1 * n2) return math.acos(clip(cos_angle, -1, 1)) def project_along_vector(point: Vect3, vector: Vect3) -> Vect3: matrix = np.identity(3) - np.outer(vector, vector) return np.dot(point, matrix.T) def normalize_along_axis( array: np.ndarray, axis: int, ) -> np.ndarray: norms = np.sqrt((array * array).sum(axis)) norms[norms == 0] = 1 return array / norms[:, np.newaxis] def get_unit_normal( v1: Vect3, v2: Vect3, tol: float = 1e-6 ) -> Vect3: v1 = normalize(v1) v2 = normalize(v2) cp = cross(v1, v2) cp_norm = get_norm(cp) if cp_norm < tol: # Vectors align, so find a normal to them in the plane shared with the z-axis new_cp = cross(cross(v1, OUT), v1) new_cp_norm = get_norm(new_cp) if new_cp_norm < tol: return DOWN return new_cp / new_cp_norm return cp / cp_norm ### def thick_diagonal(dim: int, thickness: int = 2) -> np.ndarray: row_indices = np.arange(dim).repeat(dim).reshape((dim, dim)) col_indices = np.transpose(row_indices) return (np.abs(row_indices - col_indices) < thickness).astype('uint8') def compass_directions(n: int = 4, start_vect: Vect3 = RIGHT) -> Vect3: angle = TAU / n return np.array([ rotate_vector(start_vect, k * angle) for k in range(n) ]) def complex_to_R3(complex_num: complex) -> Vect3: return np.array((complex_num.real, complex_num.imag, 0)) def R3_to_complex(point: Vect3) -> complex: return complex(*point[:2]) def complex_func_to_R3_func(complex_func: Callable[[complex], complex]) -> Callable[[Vect3], Vect3]: def result(p: Vect3): return complex_to_R3(complex_func(R3_to_complex(p))) return result def center_of_mass(points: Sequence[Vect3]) -> Vect3: return np.array(points).sum(0) / len(points) def midpoint(point1: VectN, point2: VectN) -> VectN: return center_of_mass([point1, point2]) def line_intersection( line1: Tuple[Vect3, Vect3], line2: Tuple[Vect3, Vect3] ) -> Vect3: """ return intersection point of two lines, each defined with a pair of vectors determining the end points """ x_diff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) y_diff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) def det(a, b): return a[0] * b[1] - a[1] * b[0] div = det(x_diff, y_diff) if div == 0: raise Exception("Lines do not intersect") d = (det(*line1), det(*line2)) x = det(d, x_diff) / div y = det(d, y_diff) / div return np.array([x, y, 0]) def find_intersection( p0: Vect3 | Vect3Array, v0: Vect3 | Vect3Array, p1: Vect3 | Vect3Array, v1: Vect3 | Vect3Array, threshold: float = 1e-5, ) -> Vect3: """ Return the intersection of a line passing through p0 in direction v0 with one passing through p1 in direction v1. (Or array of intersections from arrays of such points/directions). For 3d values, it returns the point on the ray p0 + v0 * t closest to the ray p1 + v1 * t """ d = len(p0.shape) if d == 1: is_3d = any(arr[2] for arr in (p0, v0, p1, v1)) else: is_3d = any(z for arr in (p0, v0, p1, v1) for z in arr.T[2]) if not is_3d: numer = np.array(cross2d(v1, p1 - p0)) denom = np.array(cross2d(v1, v0)) else: cp1 = cross(v1, p1 - p0) cp2 = cross(v1, v0) numer = np.array((cp1 * cp1).sum(d - 1)) denom = np.array((cp1 * cp2).sum(d - 1)) denom[abs(denom) < threshold] = np.inf ratio = numer / denom return p0 + (ratio * v0.T).T def line_intersects_path( start: Vect2 | Vect3, end: Vect2 | Vect3, path: Vect2Array | Vect3Array, ) -> bool: """ Tests whether the line (start, end) intersects a polygonal path defined by its vertices """ n = len(path) - 1 p1 = np.empty((n, 2)) q1 = np.empty((n, 2)) p1[:] = start[:2] q1[:] = end[:2] p2 = path[:-1, :2] q2 = path[1:, :2] v1 = q1 - p1 v2 = q2 - p2 mis1 = cross2d(v1, p2 - p1) * cross2d(v1, q2 - p1) < 0 mis2 = cross2d(v2, p1 - p2) * cross2d(v2, q1 - p2) < 0 return bool((mis1 * mis2).any()) def get_closest_point_on_line(a: VectN, b: VectN, p: VectN) -> VectN: """ It returns point x such that x is on line ab and xp is perpendicular to ab. If x lies beyond ab line, then it returns nearest edge(a or b). """ # x = b + t*(a-b) = t*a + (1-t)*b t = np.dot(p - b, a - b) / np.dot(a - b, a - b) if t < 0: t = 0 if t > 1: t = 1 return ((t * a) + ((1 - t) * b)) def get_winding_number(points: Sequence[Vect2 | Vect3]) -> float: total_angle = 0 for p1, p2 in adjacent_pairs(points): d_angle = angle_of_vector(p2) - angle_of_vector(p1) d_angle = ((d_angle + PI) % TAU) - PI total_angle += d_angle return total_angle / TAU ## def cross2d(a: Vect2 | Vect2Array, b: Vect2 | Vect2Array) -> Vect2 | Vect2Array: if len(a.shape) == 2: return a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0] else: return a[0] * b[1] - b[0] * a[1] def tri_area( a: Vect2, b: Vect2, c: Vect2 ) -> float: return 0.5 * abs( a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]) ) def is_inside_triangle( p: Vect2, a: Vect2, b: Vect2, c: Vect2 ) -> bool: """ Test if point p is inside triangle abc """ crosses = np.array([ cross2d(p - a, b - p), cross2d(p - b, c - p), cross2d(p - c, a - p), ]) return bool(np.all(crosses > 0) or np.all(crosses < 0)) def norm_squared(v: VectN | List[float]) -> float: return sum(x * x for x in v) # TODO, fails for polygons drawn over themselves def earclip_triangulation(verts: Vect3Array | Vect2Array, ring_ends: list[int]) -> list[int]: """ Returns a list of indices giving a triangulation of a polygon, potentially with holes - verts is a numpy array of points - ring_ends is a list of indices indicating where the ends of new paths are """ rings = [ list(range(e0, e1)) for e0, e1 in zip([0, *ring_ends], ring_ends) ] epsilon = 1e-6 def is_in(point, ring_id): return abs(abs(get_winding_number([i - point for i in verts[rings[ring_id]]])) - 1) < epsilon def ring_area(ring_id): ring = rings[ring_id] s = 0 for i, j in zip(ring[1:], ring): s += cross2d(verts[i], verts[j]) return abs(s) / 2 # Points at the same position may cause problems for i in rings: if len(i) < 2: continue verts[i[0]] += (verts[i[1]] - verts[i[0]]) * epsilon verts[i[-1]] += (verts[i[-2]] - verts[i[-1]]) * epsilon # First, we should know which rings are directly contained in it for each ring right = [max(verts[rings[i], 0]) for i in range(len(rings))] left = [min(verts[rings[i], 0]) for i in range(len(rings))] top = [max(verts[rings[i], 1]) for i in range(len(rings))] bottom = [min(verts[rings[i], 1]) for i in range(len(rings))] area = [ring_area(i) for i in range(len(rings))] # The larger ring must be outside rings_sorted = list(range(len(rings))) rings_sorted.sort(key=lambda x: area[x], reverse=True) def is_in_fast(ring_a, ring_b): # Whether a is in b return reduce(op.and_, ( left[ring_b] <= left[ring_a] <= right[ring_a] <= right[ring_b], bottom[ring_b] <= bottom[ring_a] <= top[ring_a] <= top[ring_b], is_in(verts[rings[ring_a][0]], ring_b) )) chilren = [[] for i in rings] ringenum = ProgressDisplay( enumerate(rings_sorted), total=len(rings), leave=False, ascii=True if platform.system() == 'Windows' else None, dynamic_ncols=True, desc="SVG Triangulation", delay=3, ) for idx, i in ringenum: for j in rings_sorted[:idx][::-1]: if is_in_fast(i, j): chilren[j].append(i) break res = [] # Then, we can use earcut for each part used = [False] * len(rings) for i in rings_sorted: if used[i]: continue v = rings[i] ring_ends = [len(v)] for j in chilren[i]: used[j] = True v += rings[j] ring_ends.append(len(v)) res += [v[i] for i in earcut(verts[v, :2], ring_ends)] return res
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/__init__.py
manimlib/utils/__init__.py
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/images.py
manimlib/utils/images.py
from __future__ import annotations import numpy as np from PIL import Image from manimlib.utils.directories import get_raster_image_dir from manimlib.utils.directories import get_vector_image_dir from manimlib.utils.file_ops import find_file from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable def get_full_raster_image_path(image_file_name: str) -> str: return find_file( image_file_name, directories=[get_raster_image_dir()], extensions=[".jpg", ".jpeg", ".png", ".gif", ""] ) def get_full_vector_image_path(image_file_name: str) -> str: return find_file( image_file_name, directories=[get_vector_image_dir()], extensions=[".svg", ".xdv", ""], ) def invert_image(image: Iterable) -> Image.Image: arr = np.array(image) arr = (255 * np.ones(arr.shape)).astype(arr.dtype) - arr return Image.fromarray(arr)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/shaders.py
manimlib/utils/shaders.py
from __future__ import annotations import os import re from functools import lru_cache import moderngl from PIL import Image import numpy as np from manimlib.utils.directories import get_shader_dir from manimlib.utils.file_ops import find_file from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence, Optional # Global maps to reflect uniform status PROGRAM_UNIFORM_MIRRORS: dict[int, dict[str, float | tuple]] = dict() @lru_cache() def image_path_to_texture(path: str, ctx: moderngl.Context) -> moderngl.Texture: im = Image.open(path).convert("RGBA") return ctx.texture( size=im.size, components=len(im.getbands()), data=im.tobytes(), ) @lru_cache() def get_shader_program( ctx: moderngl.context.Context, vertex_shader: str, fragment_shader: Optional[str] = None, geometry_shader: Optional[str] = None, ) -> moderngl.Program: return ctx.program( vertex_shader=vertex_shader, fragment_shader=fragment_shader, geometry_shader=geometry_shader, ) def set_program_uniform( program: moderngl.Program, name: str, value: float | tuple | np.ndarray ) -> bool: """ Sets a program uniform, and also keeps track of a dictionary of previously set uniforms for that program so that it doesn't needlessly reset it, requiring an exchange with gpu memory, if it sees the same value again. Returns True if changed the program, False if it left it as is. """ pid = id(program) if pid not in PROGRAM_UNIFORM_MIRRORS: PROGRAM_UNIFORM_MIRRORS[pid] = dict() uniform_mirror = PROGRAM_UNIFORM_MIRRORS[pid] if type(value) is np.ndarray and value.ndim > 0: value = tuple(value.flatten()) if uniform_mirror.get(name, None) == value: return False try: program[name].value = value except KeyError: return False uniform_mirror[name] = value return True @lru_cache() def get_shader_code_from_file(filename: str) -> str | None: if not filename: return None try: filepath = find_file( filename, directories=[get_shader_dir(), "/"], extensions=[], ) except IOError: return None with open(filepath, "r") as f: result = f.read() # To share functionality between shaders, some functions are read in # from other files an inserted into the relevant strings before # passing to ctx.program for compiling # Replace "#INSERT " lines with relevant code insertions = re.findall(r"^#INSERT .*\.glsl$", result, flags=re.MULTILINE) for line in insertions: inserted_code = get_shader_code_from_file( os.path.join("inserts", line.replace("#INSERT ", "")) ) result = result.replace(line, inserted_code) return result def get_colormap_code(rgb_list: Sequence[float]) -> str: data = ",".join( "vec3({}, {}, {})".format(*rgb) for rgb in rgb_list ) return f"vec3[{len(rgb_list)}]({data})"
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/color.py
manimlib/utils/color.py
from __future__ import annotations from colour import Color from colour import hex2rgb from colour import rgb2hex import numpy as np import random from matplotlib import pyplot from manimlib.constants import COLORMAP_3B1B from manimlib.constants import WHITE from manimlib.utils.bezier import interpolate from manimlib.utils.iterables import resize_with_interpolation from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable, Sequence, Callable from manimlib.typing import ManimColor, Vect3, Vect4, Vect3Array, Vect4Array, NDArray def color_to_rgb(color: ManimColor) -> Vect3: if isinstance(color, str): return hex_to_rgb(color) elif isinstance(color, Color): return np.array(color.get_rgb()) else: raise Exception("Invalid color type") def color_to_rgba(color: ManimColor, alpha: float = 1.0) -> Vect4: return np.array([*color_to_rgb(color), alpha]) def rgb_to_color(rgb: Vect3 | Sequence[float]) -> Color: try: return Color(rgb=tuple(rgb)) except ValueError: return Color(WHITE) def rgba_to_color(rgba: Vect4) -> Color: return rgb_to_color(rgba[:3]) def rgb_to_hex(rgb: Vect3 | Sequence[float]) -> str: return rgb2hex(rgb, force_long=True).upper() def hex_to_rgb(hex_code: str) -> Vect3: return np.array(hex2rgb(hex_code)) def invert_color(color: ManimColor) -> Color: return rgb_to_color(1.0 - color_to_rgb(color)) def color_to_int_rgb(color: ManimColor) -> np.ndarray[int, np.dtype[np.uint8]]: return (255 * color_to_rgb(color)).astype('uint8') def color_to_int_rgba(color: ManimColor, opacity: float = 1.0) -> np.ndarray[int, np.dtype[np.uint8]]: alpha = int(255 * opacity) return np.array([*color_to_int_rgb(color), alpha], dtype=np.uint8) def color_to_hex(color: ManimColor) -> str: return Color(color).get_hex_l().upper() def hex_to_int(rgb_hex: str) -> int: return int(rgb_hex[1:], 16) def int_to_hex(rgb_int: int) -> str: return f"#{rgb_int:06x}".upper() def color_gradient( reference_colors: Iterable[ManimColor], length_of_output: int, interp_by_hsl: bool = False, ) -> list[Color]: if length_of_output == 0: return [] n_ref_colors = len(reference_colors) alphas = np.linspace(0, (n_ref_colors - 1), length_of_output) floors = alphas.astype('int') alphas_mod1 = alphas % 1 # End edge case alphas_mod1[-1] = 1 floors[-1] = n_ref_colors - 2 return [ interpolate_color( reference_colors[i], reference_colors[i + 1], alpha, interp_by_hsl=interp_by_hsl, ) for i, alpha in zip(floors, alphas_mod1) ] def interpolate_color( color1: ManimColor, color2: ManimColor, alpha: float, interp_by_hsl: bool = False, ) -> Color: if interp_by_hsl: hsl1 = np.array(Color(color1).get_hsl()) hsl2 = np.array(Color(color2).get_hsl()) return Color(hsl=interpolate(hsl1, hsl2, alpha)) else: rgb = np.sqrt(interpolate(color_to_rgb(color1)**2, color_to_rgb(color2)**2, alpha)) return rgb_to_color(rgb) def interpolate_color_by_hsl( color1: ManimColor, color2: ManimColor, alpha: float ) -> Color: return interpolate_color(color1, color2, alpha, interp_by_hsl=True) def average_color(*colors: ManimColor) -> Color: rgbs = np.array(list(map(color_to_rgb, colors))) return rgb_to_color(np.sqrt((rgbs**2).mean(0))) def random_color() -> Color: return Color(rgb=tuple(np.random.random(3))) def random_bright_color( hue_range: tuple[float, float] = (0.0, 1.0), saturation_range: tuple[float, float] = (0.5, 0.8), luminance_range: tuple[float, float] = (0.5, 1.0), ) -> Color: return Color(hsl=( interpolate(*hue_range, random.random()), interpolate(*saturation_range, random.random()), interpolate(*luminance_range, random.random()), )) def get_colormap_from_colors(colors: Iterable[ManimColor]) -> Callable[[Sequence[float]], Vect4Array]: """ Returns a funciton which takes in values between 0 and 1, and returns a corresponding list of rgba values """ rgbas = np.array([color_to_rgba(color) for color in colors]) def func(values): alphas = np.clip(values, 0, 1) scaled_alphas = alphas * (len(rgbas) - 1) indices = scaled_alphas.astype(int) next_indices = np.clip(indices + 1, 0, len(rgbas) - 1) inter_alphas = scaled_alphas % 1 inter_alphas = inter_alphas.repeat(4).reshape((len(indices), 4)) result = interpolate(rgbas[indices], rgbas[next_indices], inter_alphas) return result return func def get_color_map(map_name: str) -> Callable[[Sequence[float]], Vect4Array]: if map_name == "3b1b_colormap": return get_colormap_from_colors(COLORMAP_3B1B) return pyplot.get_cmap(map_name) # Delete this? def get_colormap_list( map_name: str = "viridis", n_colors: int = 9 ) -> Vect3Array: """ Options for map_name: 3b1b_colormap magma inferno plasma viridis cividis twilight twilight_shifted turbo """ from matplotlib.cm import cmaps_listed if map_name == "3b1b_colormap": rgbs = np.array([color_to_rgb(color) for color in COLORMAP_3B1B]) else: rgbs = cmaps_listed[map_name].colors # Make more general? return resize_with_interpolation(np.array(rgbs), n_colors)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/cache.py
manimlib/utils/cache.py
from __future__ import annotations import os from diskcache import Cache from contextlib import contextmanager from functools import wraps from manimlib.utils.directories import get_cache_dir from manimlib.utils.simple_functions import hash_string from typing import TYPE_CHECKING if TYPE_CHECKING: T = TypeVar('T') CACHE_SIZE = 1e9 # 1 Gig _cache = Cache(get_cache_dir(), size_limit=CACHE_SIZE) def cache_on_disk(func: Callable[..., T]) -> Callable[..., T]: @wraps(func) def wrapper(*args, **kwargs): key = hash_string(f"{func.__name__}{args}{kwargs}") value = _cache.get(key) if value is None: value = func(*args, **kwargs) _cache.set(key, value) return value return wrapper def clear_cache(): _cache.clear()
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/tex_to_symbol_count.py
manimlib/utils/tex_to_symbol_count.py
TEX_TO_SYMBOL_COUNT = { R"\!": 0, R"\,": 0, R"\-": 0, R"\/": 0, R"\:": 0, R"\;": 0, R"\>": 0, R"\aa": 0, R"\AA": 0, R"\ae": 0, R"\AE": 0, R"\arccos": 6, R"\arcsin": 6, R"\arctan": 6, R"\arg": 3, R"\author": 0, R"\bf": 0, R"\bibliography": 0, R"\bibliographystyle": 0, R"\big": 0, R"\Big": 0, R"\bigodot": 4, R"\bigoplus": 5, R"\bigskip": 0, R"\bmod": 3, R"\boldmath": 0, R"\bottomfraction": 2, R"\bowtie": 2, R"\cal": 0, R"\cdots": 3, R"\centering": 0, R"\cite": 2, R"\cong": 2, R"\contentsline": 0, R"\cos": 3, R"\cosh": 4, R"\cot": 3, R"\coth": 4, R"\csc": 3, R"\date": 0, R"\dblfloatpagefraction": 2, R"\dbltopfraction": 2, R"\ddots": 3, R"\deg": 3, R"\det": 3, R"\dim": 3, R"\displaystyle": 0, R"\div": 2, R"\doteq": 2, R"\dotfill": 0, R"\dots": 3, R"\emph": 0, R"\exp": 3, R"\fbox": 4, R"\floatpagefraction": 2, R"\flushbottom": 0, R"\footnotesize": 0, R"\footnotetext": 0, R"\frame": 2, R"\framebox": 4, R"\fussy": 0, R"\gcd": 3, R"\ghost": 0, R"\glossary": 0, R"\hfill": 0, R"\hom": 3, R"\hookleftarrow": 2, R"\hookrightarrow": 2, R"\hrulefill": 0, R"\huge": 0, R"\Huge": 0, R"\hyphenation": 0, R"\iff": 2, R"\Im": 2, R"\index": 0, R"\inf": 3, R"\it": 0, R"\ker": 3, R"\l": 0, R"\L": 0, R"\label": 0, R"\large": 0, R"\Large": 0, R"\LARGE": 0, R"\ldots": 3, R"\lefteqn": 0, R"\left": 0, R"\lg": 2, R"\lim": 3, R"\liminf": 6, R"\limsup": 6, R"\linebreak": 0, R"\ln": 2, R"\log": 3, R"\longleftarrow": 2, R"\Longleftarrow": 2, R"\longleftrightarrow": 2, R"\Longleftrightarrow": 2, R"\longmapsto": 3, R"\longrightarrow": 2, R"\Longrightarrow": 2, R"\makebox": 0, R"\mapsto": 2, R"\markright": 0, R"\mathds": 0, R"\mathcal": 0, R"\max": 3, R"\mbox": 0, R"\medskip": 0, R"\min": 3, R"\mit": 0, R"\models": 2, R"\ne": 2, R"\neq": 2, R"\newline": 0, R"\noindent": 0, R"\nolinebreak": 0, R"\nonumber": 0, R"\nopagebreak": 0, R"\normalmarginpar": 0, R"\normalsize": 0, R"\notin": 2, R"\o": 0, R"\O": 0, R"\obeycr": 0, R"\oe": 0, R"\OE": 0, R"\overbrace": 4, R"\pagebreak": 0, R"\pagenumbering": 0, R"\pageref": 2, R"\pmod": 5, R"\Pr": 2, R"\protect": 0, R"\qquad": 0, R"\quad": 0, R"\raggedbottom": 0, R"\raggedleft": 0, R"\raggedright": 0, R"\Re": 2, R"\ref": 2, R"\restorecr": 0, R"\reversemarginpar": 0, R"\right": 0, R"\rm": 0, R"\sc": 0, R"\scriptscriptstyle": 0, R"\scriptsize": 0, R"\scriptstyle": 0, R"\sec": 3, R"\sf": 0, R"\shortstack": 0, R"\sin": 3, R"\sinh": 4, R"\sl": 0, R"\sloppy": 0, R"\small": 0, R"\Small": 0, R"\smallskip": 0, R"\sqrt": 2, R"\ss": 0, R"\sup": 3, R"\tan": 3, R"\tanh": 4, R"\text": 0, R"\textbf": 0, R"\textfraction": 2, R"\textstyle": 0, R"\thicklines": 0, R"\thinlines": 0, R"\thinspace": 0, R"\tiny": 0, R"\title": 0, R"\today": 15, R"\topfraction": 2, R"\tt": 0, R"\typeout": 0, R"\unboldmath": 0, R"\underbrace": 6, R"\underline": 0, R"\value": 0, R"\vdots": 3, R"\vline": 0 }
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/bezier.py
manimlib/utils/bezier.py
from __future__ import annotations import numpy as np from scipy import linalg from fontTools.cu2qu.cu2qu import curve_to_quadratic from manimlib.logger import log from manimlib.utils.simple_functions import choose from manimlib.utils.space_ops import cross2d from manimlib.utils.space_ops import cross from manimlib.utils.space_ops import find_intersection from manimlib.utils.space_ops import midpoint from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import z_to_vector from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Sequence, TypeVar, Tuple from manimlib.typing import VectN, FloatArray, VectNArray, Vect3Array Scalable = TypeVar("Scalable", float, FloatArray) CLOSED_THRESHOLD = 0.001 def bezier( points: Sequence[float | FloatArray] | VectNArray ) -> Callable[[float], float | FloatArray]: if len(points) == 0: raise Exception("bezier cannot be calld on an empty list") n = len(points) - 1 def result(t: float) -> float | FloatArray: return sum( ((1 - t)**(n - k)) * (t**k) * choose(n, k) * point for k, point in enumerate(points) ) return result def partial_bezier_points( points: Sequence[Scalable], a: float, b: float ) -> list[Scalable]: """ Given an list of points which define a bezier curve, and two numbers 0<=a<b<=1, return an list of the same size, which describes the portion of the original bezier curve on the interval [a, b]. This algorithm is pretty nifty, and pretty dense. """ if a == 1: return [points[-1]] * len(points) a_to_1 = [ bezier(points[i:])(a) for i in range(len(points)) ] end_prop = (b - a) / (1. - a) return [ bezier(a_to_1[:i + 1])(end_prop) for i in range(len(points)) ] # Shortened version of partial_bezier_points just for quadratics, # since this is called a fair amount def partial_quadratic_bezier_points( points: Sequence[VectN] | VectNArray, a: float, b: float ) -> list[VectN]: if a == 1: return 3 * [points[-1]] def curve(t): return points[0] * (1 - t) * (1 - t) + 2 * points[1] * t * (1 - t) + points[2] * t * t # bezier(points) h0 = curve(a) if a > 0 else points[0] h2 = curve(b) if b < 1 else points[2] h1_prime = (1 - a) * points[1] + a * points[2] end_prop = (b - a) / (1. - a) h1 = (1 - end_prop) * h0 + end_prop * h1_prime return [h0, h1, h2] # Linear interpolation variants def interpolate(start: Scalable, end: Scalable, alpha: float | VectN) -> Scalable: try: return (1 - alpha) * start + alpha * end except TypeError: log.debug(f"`start` parameter with type `{type(start)}` and dtype `{start.dtype}`") log.debug(f"`end` parameter with type `{type(end)}` and dtype `{end.dtype}`") log.debug(f"`alpha` parameter with value `{alpha}`") import sys sys.exit(2) def outer_interpolate( start: Scalable, end: Scalable, alpha: Scalable, ) -> np.ndarray: result = np.outer(1 - alpha, start) + np.outer(alpha, end) return result.reshape((*np.shape(alpha), *np.shape(start))) def set_array_by_interpolation( arr: np.ndarray, arr1: np.ndarray, arr2: np.ndarray, alpha: float, interp_func: Callable[[np.ndarray, np.ndarray, float], np.ndarray] = interpolate ) -> np.ndarray: arr[:] = interp_func(arr1, arr2, alpha) return arr def integer_interpolate( start: int, end: int, alpha: float ) -> tuple[int, float]: """ alpha is a float between 0 and 1. This returns an integer between start and end (inclusive) representing appropriate interpolation between them, along with a "residue" representing a new proportion between the returned integer and the next one of the list. For example, if start=0, end=10, alpha=0.46, This would return (4, 0.6). """ if alpha >= 1: return (end - 1, 1.0) if alpha <= 0: return (start, 0) value = int(interpolate(start, end, alpha)) residue = ((end - start) * alpha) % 1 return (value, residue) def mid(start: Scalable, end: Scalable) -> Scalable: return (start + end) / 2.0 def inverse_interpolate(start: Scalable, end: Scalable, value: Scalable) -> np.ndarray: return np.true_divide(value - start, end - start) def match_interpolate( new_start: Scalable, new_end: Scalable, old_start: Scalable, old_end: Scalable, old_value: Scalable ) -> Scalable: return interpolate( new_start, new_end, inverse_interpolate(old_start, old_end, old_value) ) def quadratic_bezier_points_for_arc(angle: float, n_components: int = 8): n_points = 2 * n_components + 1 angles = np.linspace(0, angle, n_points) points = np.array([np.cos(angles), np.sin(angles), np.zeros(n_points)]).T # Adjust handles theta = angle / n_components points[1::2] /= np.cos(theta / 2) return points def approx_smooth_quadratic_bezier_handles( points: FloatArray ) -> FloatArray: """ Figuring out which bezier curves most smoothly connect a sequence of points. Given three successive points, P0, P1 and P2, you can compute that by defining h = (1/4) P0 + P1 - (1/4)P2, the bezier curve defined by (P0, h, P1) will pass through the point P2. So for a given set of four successive points, P0, P1, P2, P3, if we want to add a handle point h between P1 and P2 so that the quadratic bezier (P1, h, P2) is part of a smooth curve passing through all four points, we calculate one solution for h that would produce a parbola passing through P3, call it smooth_to_right, and another that would produce a parabola passing through P0, call it smooth_to_left, and use the midpoint between the two. """ if len(points) == 1: return points[0] elif len(points) == 2: return midpoint(*points) smooth_to_right, smooth_to_left = [ 0.25 * ps[0:-2] + ps[1:-1] - 0.25 * ps[2:] for ps in (points, points[::-1]) ] if np.isclose(points[0], points[-1]).all(): last_str = 0.25 * points[-2] + points[-1] - 0.25 * points[1] last_stl = 0.25 * points[1] + points[0] - 0.25 * points[-2] else: last_str = smooth_to_left[0] last_stl = smooth_to_right[0] handles = 0.5 * np.vstack([smooth_to_right, [last_str]]) handles += 0.5 * np.vstack([last_stl, smooth_to_left[::-1]]) return handles def smooth_quadratic_path(anchors: Vect3Array) -> Vect3Array: """ Returns a path defining a smooth quadratic bezier spline through anchors. """ if len(anchors) < 2: return anchors elif len(anchors) == 2: return np.array([anchors[0], anchors.mean(0), anchors[1]]) is_flat = (anchors[:, 2] == 0).all() if not is_flat: normal = cross(anchors[2] - anchors[1], anchors[1] - anchors[0]) rot = z_to_vector(normal) anchors = np.dot(anchors, rot) shift = anchors[0, 2] anchors[:, 2] -= shift h1s, h2s = get_smooth_cubic_bezier_handle_points(anchors) quads = [anchors[0, :2]] for cub_bs in zip(anchors[:-1], h1s, h2s, anchors[1:]): # Try to use fontTools curve_to_quadratic new_quads = curve_to_quadratic( [b[:2] for b in cub_bs], max_err=0.1 * get_norm(cub_bs[3] - cub_bs[0]) ) # Otherwise fall back on home baked solution if new_quads is None or len(new_quads) % 2 == 0: new_quads = get_quadratic_approximation_of_cubic(*cub_bs)[:, :2] quads.extend(new_quads[1:]) new_path = np.zeros((len(quads), 3)) new_path[:, :2] = quads if not is_flat: new_path[:, 2] += shift new_path = np.dot(new_path, rot.T) return new_path def get_smooth_cubic_bezier_handle_points( points: Sequence[VectN] | VectNArray ) -> tuple[FloatArray, FloatArray]: points = np.array(points) num_handles = len(points) - 1 dim = points.shape[1] if num_handles < 1: return np.zeros((0, dim)), np.zeros((0, dim)) # Must solve 2*num_handles equations to get the handles. # l and u are the number of lower an upper diagonal rows # in the matrix to solve. l, u = 2, 1 # diag is a representation of the matrix in diagonal form # See https://www.particleincell.com/2012/bezier-splines/ # for how to arrive at these equations diag = np.zeros((l + u + 1, 2 * num_handles)) diag[0, 1::2] = -1 diag[0, 2::2] = 1 diag[1, 0::2] = 2 diag[1, 1::2] = 1 diag[2, 1:-2:2] = -2 diag[3, 0:-3:2] = 1 # last diag[2, -2] = -1 diag[1, -1] = 2 # This is the b as in Ax = b, where we are solving for x, # and A is represented using diag. However, think of entries # to x and b as being points in space, not numbers b = np.zeros((2 * num_handles, dim)) b[1::2] = 2 * points[1:] b[0] = points[0] b[-1] = points[-1] def solve_func(b): return linalg.solve_banded((l, u), diag, b) use_closed_solve_function = is_closed(points) if use_closed_solve_function: # Get equations to relate first and last points matrix = diag_to_matrix((l, u), diag) # last row handles second derivative matrix[-1, [0, 1, -2, -1]] = [2, -1, 1, -2] # first row handles first derivative matrix[0, :] = np.zeros(matrix.shape[1]) matrix[0, [0, -1]] = [1, 1] b[0] = 2 * points[0] b[-1] = np.zeros(dim) def closed_curve_solve_func(b): return linalg.solve(matrix, b) handle_pairs = np.zeros((2 * num_handles, dim)) for i in range(dim): if use_closed_solve_function: handle_pairs[:, i] = closed_curve_solve_func(b[:, i]) else: handle_pairs[:, i] = solve_func(b[:, i]) return handle_pairs[0::2], handle_pairs[1::2] def diag_to_matrix( l_and_u: tuple[int, int], diag: np.ndarray ) -> np.ndarray: """ Converts array whose rows represent diagonal entries of a matrix into the matrix itself. See scipy.linalg.solve_banded """ l, u = l_and_u dim = diag.shape[1] matrix = np.zeros((dim, dim)) for i in range(l + u + 1): np.fill_diagonal( matrix[max(0, i - u):, max(0, u - i):], diag[i, max(0, u - i):] ) return matrix def is_closed(points: FloatArray) -> bool: return np.allclose(points[0], points[-1]) # Given 4 control points for a cubic bezier curve (or arrays of such) # return control points for 2 quadratics (or 2n quadratics) approximating them. def get_quadratic_approximation_of_cubic( a0: FloatArray, h0: FloatArray, h1: FloatArray, a1: FloatArray ) -> FloatArray: a0 = np.array(a0, ndmin=2) h0 = np.array(h0, ndmin=2) h1 = np.array(h1, ndmin=2) a1 = np.array(a1, ndmin=2) # Tangent vectors at the start and end. T0 = h0 - a0 T1 = a1 - h1 # Search for inflection points. If none are found, use the # midpoint as a cut point. # Based on http://www.caffeineowl.com/graphics/2d/vectorial/cubic-inflexion.html has_infl = np.ones(len(a0), dtype=bool) p = h0 - a0 q = h1 - 2 * h0 + a0 r = a1 - 3 * h1 + 3 * h0 - a0 a = cross2d(q, r) b = cross2d(p, r) c = cross2d(p, q) disc = b * b - 4 * a * c has_infl &= (disc > 0) sqrt_disc = np.sqrt(np.abs(disc)) settings = np.seterr(all='ignore') ti_bounds = [] for sgn in [-1, +1]: ti = (-b + sgn * sqrt_disc) / (2 * a) ti[a == 0] = (-c / b)[a == 0] ti[(a == 0) & (b == 0)] = 0 ti_bounds.append(ti) ti_min, ti_max = ti_bounds np.seterr(**settings) ti_min_in_range = has_infl & (0 < ti_min) & (ti_min < 1) ti_max_in_range = has_infl & (0 < ti_max) & (ti_max < 1) # Choose a value of t which starts at 0.5, # but is updated to one of the inflection points # if they lie between 0 and 1 t_mid = 0.5 * np.ones(len(a0)) t_mid[ti_min_in_range] = ti_min[ti_min_in_range] t_mid[ti_max_in_range] = ti_max[ti_max_in_range] m, n = a0.shape t_mid = t_mid.repeat(n).reshape((m, n)) # Compute bezier point and tangent at the chosen value of t mid = bezier([a0, h0, h1, a1])(t_mid) Tm = bezier([h0 - a0, h1 - h0, a1 - h1])(t_mid) # Intersection between tangent lines at end points # and tangent in the middle i0 = find_intersection(a0, T0, mid, Tm) i1 = find_intersection(a1, T1, mid, Tm) m, n = np.shape(a0) result = np.zeros((5 * m, n)) result[0::5] = a0 result[1::5] = i0 result[2::5] = mid result[3::5] = i1 result[4::5] = a1 return result def get_smooth_quadratic_bezier_path_through( points: Sequence[VectN] ) -> np.ndarray: # TODO h0, h1 = get_smooth_cubic_bezier_handle_points(points) a0 = points[:-1] a1 = points[1:] return get_quadratic_approximation_of_cubic(a0, h0, h1, a1)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/utils/sounds.py
manimlib/utils/sounds.py
from __future__ import annotations import subprocess import threading import platform from manimlib.utils.directories import get_sound_dir from manimlib.utils.file_ops import find_file def get_full_sound_file_path(sound_file_name: str) -> str: return find_file( sound_file_name, directories=[get_sound_dir()], extensions=[".wav", ".mp3", ""] ) def play_sound(sound_file): """Play a sound file using the system's audio player""" full_path = get_full_sound_file_path(sound_file) system = platform.system() if system == "Windows": # Windows subprocess.Popen( ["powershell", "-c", f"(New-Object Media.SoundPlayer '{full_path}').PlaySync()"], shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) elif system == "Darwin": # macOS subprocess.Popen( ["afplay", full_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) else: subprocess.Popen( ["aplay", full_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL )
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/mobject.py
manimlib/mobject/mobject.py
from __future__ import annotations import copy from functools import wraps import itertools as it import os import pickle import random import sys import moderngl import numbers import numpy as np from manimlib.constants import DEFAULT_MOBJECT_TO_EDGE_BUFF from manimlib.constants import DEFAULT_MOBJECT_TO_MOBJECT_BUFF from manimlib.constants import DOWN, IN, LEFT, ORIGIN, OUT, RIGHT, UP from manimlib.constants import FRAME_X_RADIUS, FRAME_Y_RADIUS from manimlib.constants import MED_SMALL_BUFF from manimlib.constants import TAU from manimlib.constants import DEFAULT_MOBJECT_COLOR from manimlib.event_handler import EVENT_DISPATCHER from manimlib.event_handler.event_listner import EventListener from manimlib.event_handler.event_type import EventType from manimlib.logger import log from manimlib.shader_wrapper import ShaderWrapper from manimlib.utils.color import color_gradient from manimlib.utils.color import color_to_rgb from manimlib.utils.color import get_colormap_list from manimlib.utils.color import rgb_to_hex from manimlib.utils.iterables import arrays_match from manimlib.utils.iterables import array_is_constant from manimlib.utils.iterables import batch_by_property from manimlib.utils.iterables import list_update from manimlib.utils.iterables import listify from manimlib.utils.iterables import resize_array from manimlib.utils.iterables import resize_preserving_order from manimlib.utils.iterables import resize_with_interpolation from manimlib.utils.bezier import integer_interpolate from manimlib.utils.bezier import interpolate from manimlib.utils.paths import straight_path from manimlib.utils.shaders import get_colormap_code from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import rotation_matrix_transpose from typing import TYPE_CHECKING from typing import TypeVar, Generic, Iterable SubmobjectType = TypeVar('SubmobjectType', bound='Mobject') if TYPE_CHECKING: from typing import Callable, Iterator, Union, Tuple, Optional, Any import numpy.typing as npt from manimlib.typing import ManimColor, Vect3, Vect4Array, Vect3Array, UniformDict, Self from moderngl.context import Context T = TypeVar('T') TimeBasedUpdater = Callable[["Mobject", float], "Mobject" | None] NonTimeUpdater = Callable[["Mobject"], "Mobject" | None] Updater = Union[TimeBasedUpdater, NonTimeUpdater] class Mobject(object): """ Mathematical Object """ dim: int = 3 shader_folder: str = "" render_primitive: int = moderngl.TRIANGLE_STRIP # Must match in attributes of vert shader data_dtype: np.dtype = np.dtype([ ('point', np.float32, (3,)), ('rgba', np.float32, (4,)), ]) aligned_data_keys = ['point'] pointlike_data_keys = ['point'] def __init__( self, color: ManimColor = DEFAULT_MOBJECT_COLOR, opacity: float = 1.0, shading: Tuple[float, float, float] = (0.0, 0.0, 0.0), # For shaders texture_paths: dict[str, str] | None = None, # If true, the mobject will not get rotated according to camera position is_fixed_in_frame: bool = False, depth_test: bool = False, z_index: int = 0, ): self.color = color self.opacity = opacity self.shading = shading self.texture_paths = texture_paths self.depth_test = depth_test self.z_index = z_index # Internal state self.submobjects: list[Mobject] = [] self.parents: list[Mobject] = [] self.family: list[Mobject] | None = [self] self.locked_data_keys: set[str] = set() self.const_data_keys: set[str] = set() self.locked_uniform_keys: set[str] = set() self.saved_state = None self.target = None self.bounding_box: Vect3Array = np.zeros((3, 3)) self.shader_wrapper: Optional[ShaderWrapper] = None self._is_animating: bool = False self._needs_new_bounding_box: bool = True self._data_has_changed: bool = True self.shader_code_replacements: dict[str, str] = dict() self.init_data() self.init_uniforms() self.init_updaters() self.init_event_listners() self.init_points() self.init_colors() if self.depth_test: self.apply_depth_test() if is_fixed_in_frame: self.fix_in_frame() def __str__(self): return self.__class__.__name__ def __add__(self, other: Mobject) -> Mobject: assert isinstance(other, Mobject) return self.get_group_class()(self, other) def __mul__(self, other: int) -> Mobject: assert isinstance(other, int) return self.replicate(other) def init_data(self, length: int = 0): self.data = np.zeros(length, dtype=self.data_dtype) self._data_defaults = np.ones(1, dtype=self.data.dtype) def init_uniforms(self): self.uniforms: UniformDict = { "is_fixed_in_frame": 0.0, "shading": np.array(self.shading, dtype=float), "clip_plane": np.zeros(4), } def init_colors(self): self.set_color(self.color, self.opacity) def init_points(self): # Typically implemented in subclass, unlpess purposefully left blank pass def set_uniforms(self, uniforms: dict) -> Self: for key, value in uniforms.items(): if isinstance(value, np.ndarray): value = value.copy() self.uniforms[key] = value return self @property def animate(self) -> _AnimationBuilder | Self: """ Methods called with Mobject.animate.method() can be passed into a Scene.play call, as if you were calling ApplyMethod(mobject.method) Borrowed from https://github.com/ManimCommunity/manim/ """ return _AnimationBuilder(self) @property def always(self) -> _UpdaterBuilder: """ Methods called with mobject.always.method(*args, **kwargs) will result in the call mobject.method(*args, **kwargs) on every frame """ return _UpdaterBuilder(self) @property def f_always(self) -> _FunctionalUpdaterBuilder: """ Similar to Mobject.always, but with the intent that arguments are functions returning the corresponding type fit for the method Methods called with mobject.f_always.method( func1, func2, ..., kwarg1=kw_func1, kwarg2=kw_func2, ... ) will result in the call mobject.method( func1(), func2(), ..., kwarg1=kw_func1(), kwarg2=kw_func2(), ... ) on every frame """ return _FunctionalUpdaterBuilder(self) def note_changed_data(self, recurse_up: bool = True) -> Self: self._data_has_changed = True if recurse_up: for mob in self.parents: mob.note_changed_data() return self @staticmethod def affects_data(func: Callable[..., T]) -> Callable[..., T]: @wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) self.note_changed_data() return result return wrapper @staticmethod def affects_family_data(func: Callable[..., T]) -> Callable[..., T]: @wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) for mob in self.family_members_with_points(): mob.note_changed_data() return result return wrapper # Only these methods should directly affect points @affects_data def set_data(self, data: np.ndarray) -> Self: assert data.dtype == self.data.dtype self.resize_points(len(data)) self.data[:] = data return self @affects_data def resize_points( self, new_length: int, resize_func: Callable[[np.ndarray, int], np.ndarray] = resize_array ) -> Self: if new_length == 0: if len(self.data) > 0: self._data_defaults[:1] = self.data[:1] elif self.get_num_points() == 0: self.data = self._data_defaults.copy() self.data = resize_func(self.data, new_length) self.refresh_bounding_box() return self @affects_data def set_points(self, points: Vect3Array | list[Vect3]) -> Self: self.resize_points(len(points), resize_func=resize_preserving_order) self.data["point"][:] = points return self @affects_data def append_points(self, new_points: Vect3Array) -> Self: n = self.get_num_points() self.resize_points(n + len(new_points)) # Have most data default to the last value self.data[n:] = self.data[n - 1] # Then read in new points self.data["point"][n:] = new_points self.refresh_bounding_box() return self @affects_family_data def reverse_points(self) -> Self: for mob in self.get_family(): mob.data[:] = mob.data[::-1] return self @affects_family_data def apply_points_function( self, func: Callable[[np.ndarray], np.ndarray], about_point: Vect3 | None = None, about_edge: Vect3 = ORIGIN, works_on_bounding_box: bool = False ) -> Self: if about_point is None and about_edge is not None: about_point = self.get_bounding_box_point(about_edge) for mob in self.get_family(): arrs = [mob.data[key] for key in mob.pointlike_data_keys if mob.has_points()] if works_on_bounding_box: arrs.append(mob.get_bounding_box()) for arr in arrs: if about_point is None: arr[:] = func(arr) else: arr[:] = func(arr - about_point) + about_point if not works_on_bounding_box: self.refresh_bounding_box(recurse_down=True) else: for parent in self.parents: parent.refresh_bounding_box() return self @affects_data def match_points(self, mobject: Mobject) -> Self: self.resize_points(len(mobject.data), resize_func=resize_preserving_order) for key in self.pointlike_data_keys: self.data[key][:] = mobject.data[key] return self # Others related to points def get_points(self) -> Vect3Array: return self.data["point"] def clear_points(self) -> Self: self.resize_points(0) return self def get_num_points(self) -> int: return len(self.get_points()) def get_all_points(self) -> Vect3Array: if self.submobjects: return np.vstack([sm.get_points() for sm in self.get_family()]) else: return self.get_points() def has_points(self) -> bool: return len(self.get_points()) > 0 def get_bounding_box(self) -> Vect3Array: if self._needs_new_bounding_box: self.bounding_box[:] = self.compute_bounding_box() self._needs_new_bounding_box = False return self.bounding_box def compute_bounding_box(self) -> Vect3Array: all_points = np.vstack([ self.get_points(), *( mob.get_bounding_box() for mob in self.get_family()[1:] if mob.has_points() ) ]) if len(all_points) == 0: return np.zeros((3, self.dim)) else: # Lower left and upper right corners mins = all_points.min(0) maxs = all_points.max(0) mids = (mins + maxs) / 2 return np.array([mins, mids, maxs]) def refresh_bounding_box( self, recurse_down: bool = False, recurse_up: bool = True ) -> Self: for mob in self.get_family(recurse_down): mob._needs_new_bounding_box = True if recurse_up: for parent in self.parents: parent.refresh_bounding_box() return self def are_points_touching( self, points: Vect3Array, buff: float = 0 ) -> np.ndarray: bb = self.get_bounding_box() mins = (bb[0] - buff) maxs = (bb[2] + buff) return ((points >= mins) * (points <= maxs)).all(1) def is_point_touching( self, point: Vect3, buff: float = 0 ) -> bool: return self.are_points_touching(np.array(point, ndmin=2), buff)[0] def is_touching(self, mobject: Mobject, buff: float = 1e-2) -> bool: bb1 = self.get_bounding_box() bb2 = mobject.get_bounding_box() return not any(( (bb2[2] < bb1[0] - buff).any(), # E.g. Right of mobject is left of self's left (bb2[0] > bb1[2] + buff).any(), # E.g. Left of mobject is right of self's right )) # Family matters def __getitem__(self, value: int | slice) -> Mobject: if isinstance(value, slice): GroupClass = self.get_group_class() return GroupClass(*self.split().__getitem__(value)) return self.split().__getitem__(value) def __iter__(self) -> Iterator[Self]: return iter(self.split()) def __len__(self) -> int: return len(self.split()) def split(self) -> list[Self]: return self.submobjects @affects_data def note_changed_family(self, only_changed_order=False) -> Self: self.family = None if not only_changed_order: self.refresh_has_updater_status() self.refresh_bounding_box() for parent in self.parents: parent.note_changed_family() return self def get_family(self, recurse: bool = True) -> list[Mobject]: if not recurse: return [self] if self.family is None: # Reconstruct and save sub_families = (sm.get_family() for sm in self.submobjects) self.family = [self, *it.chain(*sub_families)] return self.family def family_members_with_points(self) -> list[Mobject]: return [m for m in self.get_family() if len(m.data) > 0] def get_ancestors(self, extended: bool = False) -> list[Mobject]: """ Returns parents, grandparents, etc. Order of result should be from higher members of the hierarchy down. If extended is set to true, it includes the ancestors of all family members, e.g. any other parents of a submobject """ ancestors = [] to_process = list(self.get_family(recurse=extended)) excluded = set(to_process) while to_process: for p in to_process.pop().parents: if p not in excluded: ancestors.append(p) to_process.append(p) # Ensure mobjects highest in the hierarchy show up first ancestors.reverse() # Remove list redundancies while preserving order return list(dict.fromkeys(ancestors)) def add(self, *mobjects: Mobject) -> Self: if self in mobjects: raise Exception("Mobject cannot contain self") for mobject in mobjects: if mobject not in self.submobjects: self.submobjects.append(mobject) if self not in mobject.parents: mobject.parents.append(self) self.note_changed_family() return self def remove( self, *to_remove: Mobject, reassemble: bool = True, recurse: bool = True ) -> Self: for parent in self.get_family(recurse): for child in to_remove: if child in parent.submobjects: parent.submobjects.remove(child) if parent in child.parents: child.parents.remove(parent) if reassemble: parent.note_changed_family() return self def clear(self) -> Self: self.remove(*self.submobjects, recurse=False) return self def add_to_back(self, *mobjects: Mobject) -> Self: self.set_submobjects(list_update(mobjects, self.submobjects)) return self def replace_submobject(self, index: int, new_submob: Mobject) -> Self: old_submob = self.submobjects[index] if self in old_submob.parents: old_submob.parents.remove(self) self.submobjects[index] = new_submob new_submob.parents.append(self) self.note_changed_family() return self def insert_submobject(self, index: int, new_submob: Mobject) -> Self: self.submobjects.insert(index, new_submob) self.note_changed_family() return self def set_submobjects(self, submobject_list: list[Mobject]) -> Self: if self.submobjects == submobject_list: return self self.clear() self.add(*submobject_list) return self def digest_mobject_attrs(self) -> Self: """ Ensures all attributes which are mobjects are included in the submobjects list. """ mobject_attrs = [x for x in list(self.__dict__.values()) if isinstance(x, Mobject)] self.set_submobjects(list_update(self.submobjects, mobject_attrs)) return self # Submobject organization def arrange( self, direction: Vect3 = RIGHT, center: bool = True, **kwargs ) -> Self: for m1, m2 in zip(self.submobjects, self.submobjects[1:]): m2.next_to(m1, direction, **kwargs) if center: self.center() return self def arrange_in_grid( self, n_rows: int | None = None, n_cols: int | None = None, buff: float | None = None, h_buff: float | None = None, v_buff: float | None = None, buff_ratio: float | None = None, h_buff_ratio: float = 0.5, v_buff_ratio: float = 0.5, aligned_edge: Vect3 = ORIGIN, fill_rows_first: bool = True ) -> Self: submobs = self.submobjects n_submobs = len(submobs) if n_rows is None: n_rows = int(np.sqrt(n_submobs)) if n_cols is None else n_submobs // n_cols if n_cols is None: n_cols = n_submobs // n_rows if buff is not None: h_buff = buff v_buff = buff else: if buff_ratio is not None: v_buff_ratio = buff_ratio h_buff_ratio = buff_ratio if h_buff is None: h_buff = h_buff_ratio * self[0].get_width() if v_buff is None: v_buff = v_buff_ratio * self[0].get_height() x_unit = h_buff + max([sm.get_width() for sm in submobs]) y_unit = v_buff + max([sm.get_height() for sm in submobs]) for index, sm in enumerate(submobs): if fill_rows_first: x, y = index % n_cols, index // n_cols else: x, y = index // n_rows, index % n_rows sm.move_to(ORIGIN, aligned_edge) sm.shift(x * x_unit * RIGHT + y * y_unit * DOWN) self.center() return self def arrange_to_fit_dim(self, length: float, dim: int, about_edge=ORIGIN) -> Self: ref_point = self.get_bounding_box_point(about_edge) n_submobs = len(self.submobjects) if n_submobs <= 1: return total_length = sum(sm.length_over_dim(dim) for sm in self.submobjects) buff = (length - total_length) / (n_submobs - 1) vect = np.zeros(self.dim) vect[dim] = 1 x = 0 for submob in self.submobjects: submob.set_coord(x, dim, -vect) x += submob.length_over_dim(dim) + buff self.move_to(ref_point, about_edge) return self def arrange_to_fit_width(self, width: float, about_edge=ORIGIN) -> Self: return self.arrange_to_fit_dim(width, 0, about_edge) def arrange_to_fit_height(self, height: float, about_edge=ORIGIN) -> Self: return self.arrange_to_fit_dim(height, 1, about_edge) def arrange_to_fit_depth(self, depth: float, about_edge=ORIGIN) -> Self: return self.arrange_to_fit_dim(depth, 2, about_edge) def sort( self, point_to_num_func: Callable[[np.ndarray], float] = lambda p: p[0], submob_func: Callable[[Mobject]] | None = None ) -> Self: if submob_func is not None: self.submobjects.sort(key=submob_func) else: self.submobjects.sort(key=lambda m: point_to_num_func(m.get_center())) self.note_changed_family(only_changed_order=True) return self def shuffle(self, recurse: bool = False) -> Self: if recurse: for submob in self.submobjects: submob.shuffle(recurse=True) random.shuffle(self.submobjects) self.note_changed_family(only_changed_order=True) return self def reverse_submobjects(self) -> Self: self.submobjects.reverse() self.note_changed_family(only_changed_order=True) return self # Copying and serialization @staticmethod def stash_mobject_pointers(func: Callable[..., T]) -> Callable[..., T]: @wraps(func) def wrapper(self, *args, **kwargs): uncopied_attrs = ["parents", "target", "saved_state"] stash = dict() for attr in uncopied_attrs: if hasattr(self, attr): value = getattr(self, attr) stash[attr] = value null_value = [] if isinstance(value, list) else None setattr(self, attr, null_value) result = func(self, *args, **kwargs) self.__dict__.update(stash) return result return wrapper @stash_mobject_pointers def serialize(self) -> bytes: return pickle.dumps(self) def deserialize(self, data: bytes) -> Self: self.become(pickle.loads(data)) return self @stash_mobject_pointers def deepcopy(self) -> Self: return copy.deepcopy(self) def copy(self, deep: bool = False) -> Self: if deep: return self.deepcopy() result = copy.copy(self) result.parents = [] result.target = None result.saved_state = None # copy.copy is only a shallow copy, so the internal # data which are numpy arrays or other mobjects still # need to be further copied. result.uniforms = { key: value.copy() if isinstance(value, np.ndarray) else value for key, value in self.uniforms.items() } # Instead of adding using result.add, which does some checks for updating # updater statues and bounding box, just directly modify the family-related # lists result.submobjects = [sm.copy() for sm in self.submobjects] for sm in result.submobjects: sm.parents = [result] result.family = [result, *it.chain(*(sm.get_family() for sm in result.submobjects))] # Similarly, instead of calling match_updaters, since we know the status # won't have changed, just directly match. result.updaters = list(self.updaters) result._data_has_changed = True result.shader_wrapper = None family = self.get_family() for attr, value in self.__dict__.items(): if isinstance(value, Mobject) and value is not self: if value in family: setattr(result, attr, result.family[family.index(value)]) elif isinstance(value, np.ndarray): setattr(result, attr, value.copy()) return result def generate_target(self, use_deepcopy: bool = False) -> Self: self.target = self.copy(deep=use_deepcopy) self.target.saved_state = self.saved_state return self.target def save_state(self, use_deepcopy: bool = False) -> Self: self.saved_state = self.copy(deep=use_deepcopy) self.saved_state.target = self.target return self def restore(self) -> Self: if not hasattr(self, "saved_state") or self.saved_state is None: raise Exception("Trying to restore without having saved") self.become(self.saved_state) return self def become(self, mobject: Mobject, match_updaters=False) -> Self: """ Edit all data and submobjects to be idential to another mobject """ self.align_family(mobject) family1 = self.get_family() family2 = mobject.get_family() for sm1, sm2 in zip(family1, family2): sm1.set_data(sm2.data) sm1.set_uniforms(sm2.uniforms) sm1.bounding_box[:] = sm2.bounding_box sm1.shader_folder = sm2.shader_folder sm1.texture_paths = sm2.texture_paths sm1.depth_test = sm2.depth_test sm1.render_primitive = sm2.render_primitive sm1._needs_new_bounding_box = sm2._needs_new_bounding_box # Make sure named family members carry over for attr, value in list(mobject.__dict__.items()): if isinstance(value, Mobject) and value in family2: setattr(self, attr, family1[family2.index(value)]) if match_updaters: self.match_updaters(mobject) return self def looks_identical(self, mobject: Mobject) -> bool: fam1 = self.family_members_with_points() fam2 = mobject.family_members_with_points() if len(fam1) != len(fam2): return False for m1, m2 in zip(fam1, fam2): if m1.get_num_points() != m2.get_num_points(): return False if not m1.data.dtype == m2.data.dtype: return False for key in m1.data.dtype.names: if not np.isclose(m1.data[key], m2.data[key]).all(): return False if set(m1.uniforms).difference(m2.uniforms): return False for key in m1.uniforms: value1 = m1.uniforms[key] value2 = m2.uniforms[key] if isinstance(value1, np.ndarray) and isinstance(value2, np.ndarray) and not value1.size == value2.size: return False if not np.isclose(value1, value2).all(): return False return True def has_same_shape_as(self, mobject: Mobject) -> bool: # Normalize both point sets by centering and making height 1 points1, points2 = ( (m.get_all_points() - m.get_center()) / m.get_height() for m in (self, mobject) ) if len(points1) != len(points2): return False return bool(np.isclose(points1, points2, atol=self.get_width() * 1e-2).all()) # Creating new Mobjects from this one def replicate(self, n: int) -> Self: group_class = self.get_group_class() return group_class(*(self.copy() for _ in range(n))) def get_grid( self, n_rows: int, n_cols: int, height: float | None = None, width: float | None = None, group_by_rows: bool = False, group_by_cols: bool = False, **kwargs ) -> Self: """ Returns a new mobject containing multiple copies of this one arranged in a grid """ total = n_rows * n_cols grid = self.replicate(total) if group_by_cols: kwargs["fill_rows_first"] = False grid.arrange_in_grid(n_rows, n_cols, **kwargs) if height is not None: grid.set_height(height) if width is not None: grid.set_height(width) group_class = self.get_group_class() if group_by_rows: return group_class(*(grid[n:n + n_cols] for n in range(0, total, n_cols))) elif group_by_cols: return group_class(*(grid[n:n + n_rows] for n in range(0, total, n_rows))) else: return grid # Updating def init_updaters(self): self.updaters: list[Updater] = list() self._has_updaters_in_family: Optional[bool] = False self.updating_suspended: bool = False def update(self, dt: float = 0, recurse: bool = True) -> Self: if not self.has_updaters() or self.updating_suspended: return self if recurse: for submob in self.submobjects: submob.update(dt, recurse) for updater in self.updaters: # This is hacky, but if an updater takes dt as an arg, # it will be passed the change in time from here if "dt" in updater.__code__.co_varnames: updater(self, dt=dt) else: updater(self) return self def get_updaters(self) -> list[Updater]: return self.updaters def add_updater(self, update_func: Updater, call: bool = True) -> Self: self.updaters.append(update_func) if call: self.update(dt=0) self.refresh_has_updater_status() self.update() return self def insert_updater(self, update_func: Updater, index=0): self.updaters.insert(index, update_func) self.refresh_has_updater_status() return self def remove_updater(self, update_func: Updater) -> Self: while update_func in self.updaters: self.updaters.remove(update_func) self.refresh_has_updater_status() return self def clear_updaters(self, recurse: bool = True) -> Self: for mob in self.get_family(recurse): mob.updaters = [] mob._has_updaters_in_family = False for parent in self.get_ancestors(): parent._has_updaters_in_family = False return self def match_updaters(self, mobject: Mobject) -> Self: self.updaters = list(mobject.updaters) self.refresh_has_updater_status() return self def suspend_updating(self, recurse: bool = True) -> Self: self.updating_suspended = True if recurse: for submob in self.submobjects: submob.suspend_updating(recurse) return self def resume_updating(self, recurse: bool = True, call_updater: bool = True) -> Self: self.updating_suspended = False if recurse: for submob in self.submobjects: submob.resume_updating(recurse) for parent in self.parents: parent.resume_updating(recurse=False, call_updater=False) if call_updater: self.update(dt=0, recurse=recurse) return self def has_updaters(self) -> bool: if self._has_updaters_in_family is None: # Recompute and save self._has_updaters_in_family = bool(self.updaters) or any( sm.has_updaters() for sm in self.submobjects ) return self._has_updaters_in_family def refresh_has_updater_status(self) -> Self: self._has_updaters_in_family = None for parent in self.parents: parent.refresh_has_updater_status() return self # Check if mark as static or not for camera def is_changing(self) -> bool: return self._is_animating or self.has_updaters() def set_animating_status(self, is_animating: bool, recurse: bool = True) -> Self: for mob in (*self.get_family(recurse), *self.get_ancestors()): mob._is_animating = is_animating return self # Transforming operations def shift(self, vector: Vect3) -> Self: self.apply_points_function( lambda points: points + vector, about_edge=None, works_on_bounding_box=True, ) return self def scale( self, scale_factor: float | npt.ArrayLike, min_scale_factor: float = 1e-8, about_point: Vect3 | None = None, about_edge: Vect3 = ORIGIN ) -> Self: """ Default behavior is to scale about the center of the mobject. The argument about_edge can be a vector, indicating which side of the mobject to scale about, e.g., mob.scale(about_edge = RIGHT) scales about mob.get_right(). Otherwise, if about_point is given a value, scaling is done with respect to that point. """ if isinstance(scale_factor, numbers.Number):
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
true
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/matrix.py
manimlib/mobject/matrix.py
from __future__ import annotations import numpy as np from manimlib.constants import DOWN, LEFT, RIGHT, ORIGIN from manimlib.constants import DEG from manimlib.mobject.numbers import DecimalNumber from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence, Union, Optional from manimlib.typing import ManimColor, Vect3, VectNArray, Self StringMatrixType = Union[Sequence[Sequence[str]], np.ndarray[int, np.dtype[np.str_]]] FloatMatrixType = Union[Sequence[Sequence[float]], VectNArray] VMobjectMatrixType = Sequence[Sequence[VMobject]] GenericMatrixType = Union[FloatMatrixType, StringMatrixType, VMobjectMatrixType] class Matrix(VMobject): def __init__( self, matrix: GenericMatrixType, v_buff: float = 0.5, h_buff: float = 0.5, bracket_h_buff: float = 0.2, bracket_v_buff: float = 0.25, height: float | None = None, element_config: dict = dict(), element_alignment_corner: Vect3 = DOWN, ellipses_row: Optional[int] = None, ellipses_col: Optional[int] = None, ): """ Matrix can either include numbers, tex_strings, or mobjects """ super().__init__() self.mob_matrix = self.create_mobject_matrix( matrix, v_buff, h_buff, element_alignment_corner, **element_config ) # Create helpful groups for the elements n_cols = len(self.mob_matrix[0]) self.elements = [elem for row in self.mob_matrix for elem in row] self.columns = VGroup(*( VGroup(*(row[i] for row in self.mob_matrix)) for i in range(n_cols) )) self.rows = VGroup(*(VGroup(*row) for row in self.mob_matrix)) if height is not None: self.rows.set_height(height - 2 * bracket_v_buff) self.brackets = self.create_brackets(self.rows, bracket_v_buff, bracket_h_buff) self.ellipses = [] # Add elements and brackets self.add(*self.elements) self.add(*self.brackets) self.center() # Potentially add ellipses self.swap_entries_for_ellipses( ellipses_row, ellipses_col, ) def copy(self, deep: bool = False): result = super().copy(deep) self_family = self.get_family() copy_family = result.get_family() for attr in ["elements", "ellipses"]: setattr(result, attr, [ copy_family[self_family.index(mob)] for mob in getattr(self, attr) ]) return result def create_mobject_matrix( self, matrix: GenericMatrixType, v_buff: float, h_buff: float, aligned_corner: Vect3, **element_config ) -> VMobjectMatrixType: """ Creates and organizes the matrix of mobjects """ mob_matrix = [ [ self.element_to_mobject(element, **element_config) for element in row ] for row in matrix ] max_width = max(elem.get_width() for row in mob_matrix for elem in row) max_height = max(elem.get_height() for row in mob_matrix for elem in row) x_step = (max_width + h_buff) * RIGHT y_step = (max_height + v_buff) * DOWN for i, row in enumerate(mob_matrix): for j, elem in enumerate(row): elem.move_to(i * y_step + j * x_step, aligned_corner) return mob_matrix def element_to_mobject(self, element, **config) -> VMobject: if isinstance(element, VMobject): return element elif isinstance(element, float | complex): return DecimalNumber(element, **config) else: return Tex(str(element), **config) def create_brackets(self, rows, v_buff: float, h_buff: float) -> VGroup: brackets = Tex("".join(( R"\left[\begin{array}{c}", *len(rows) * [R"\quad \\"], R"\end{array}\right]", ))) brackets.set_height(rows.get_height() + v_buff) l_bracket = brackets[:len(brackets) // 2] r_bracket = brackets[len(brackets) // 2:] l_bracket.next_to(rows, LEFT, h_buff) r_bracket.next_to(rows, RIGHT, h_buff) return VGroup(l_bracket, r_bracket) def get_column(self, index: int): if not 0 <= index < len(self.columns): raise IndexError(f"Index {index} out of bound for matrix with {len(self.columns)} columns") return self.columns[index] def get_row(self, index: int): if not 0 <= index < len(self.rows): raise IndexError(f"Index {index} out of bound for matrix with {len(self.rows)} rows") return self.rows[index] def get_columns(self) -> VGroup: return self.columns def get_rows(self) -> VGroup: return self.rows def set_column_colors(self, *colors: ManimColor) -> Self: columns = self.get_columns() for color, column in zip(colors, columns): column.set_color(color) return self def add_background_to_entries(self) -> Self: for mob in self.get_entries(): mob.add_background_rectangle() return self def swap_entry_for_dots(self, entry, dots): dots.move_to(entry) entry.become(dots) if entry in self.elements: self.elements.remove(entry) if entry not in self.ellipses: self.ellipses.append(entry) def swap_entries_for_ellipses( self, row_index: Optional[int] = None, col_index: Optional[int] = None, height_ratio: float = 0.65, width_ratio: float = 0.4 ): rows = self.get_rows() cols = self.get_columns() avg_row_height = rows.get_height() / len(rows) vdots_height = height_ratio * avg_row_height avg_col_width = cols.get_width() / len(cols) hdots_width = width_ratio * avg_col_width use_vdots = row_index is not None and -len(rows) <= row_index < len(rows) use_hdots = col_index is not None and -len(cols) <= col_index < len(cols) if use_vdots: for column in cols: # Add vdots dots = Tex(R"\vdots") dots.set_height(vdots_height) self.swap_entry_for_dots(column[row_index], dots) if use_hdots: for row in rows: # Add hdots dots = Tex(R"\hdots") dots.set_width(hdots_width) self.swap_entry_for_dots(row[col_index], dots) if use_vdots and use_hdots: rows[row_index][col_index].rotate(-45 * DEG) return self def get_mob_matrix(self) -> VMobjectMatrixType: return self.mob_matrix def get_entries(self) -> VGroup: return VGroup(*self.elements) def get_brackets(self) -> VGroup: return VGroup(*self.brackets) def get_ellipses(self) -> VGroup: return VGroup(*self.ellipses) class DecimalMatrix(Matrix): def __init__( self, matrix: FloatMatrixType, num_decimal_places: int = 2, decimal_config: dict = dict(), **config ): self.float_matrix = matrix super().__init__( matrix, element_config=dict( num_decimal_places=num_decimal_places, **decimal_config ), **config ) def element_to_mobject(self, element, **decimal_config) -> DecimalNumber: return DecimalNumber(element, **decimal_config) class IntegerMatrix(DecimalMatrix): def __init__( self, matrix: FloatMatrixType, num_decimal_places: int = 0, decimal_config: dict = dict(), **config ): super().__init__(matrix, num_decimal_places, decimal_config, **config) class TexMatrix(Matrix): def __init__( self, matrix: StringMatrixType, tex_config: dict = dict(), **config, ): super().__init__( matrix, element_config=tex_config, **config ) class MobjectMatrix(Matrix): def __init__( self, group: VGroup, n_rows: int | None = None, n_cols: int | None = None, height: float = 4.0, element_alignment_corner=ORIGIN, **config, ): # Have fallback defaults of n_rows and n_cols n_mobs = len(group) if n_rows is None: n_rows = int(np.sqrt(n_mobs)) if n_cols is None else n_mobs // n_cols if n_cols is None: n_cols = n_mobs // n_rows if len(group) < n_rows * n_cols: raise Exception("Input to MobjectMatrix must have at least n_rows * n_cols entries") mob_matrix = [ [group[n * n_cols + k] for k in range(n_cols)] for n in range(n_rows) ] config.update( height=height, element_alignment_corner=element_alignment_corner, ) super().__init__(mob_matrix, **config) def element_to_mobject(self, element: VMobject, **config) -> VMobject: return element
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/boolean_ops.py
manimlib/mobject/boolean_ops.py
from __future__ import annotations import numpy as np import pathops from manimlib.mobject.types.vectorized_mobject import VMobject # Boolean operations between 2D mobjects # Borrowed from https://github.com/ManimCommunity/manim/ def _convert_vmobject_to_skia_path(vmobject: VMobject) -> pathops.Path: path = pathops.Path() for submob in vmobject.family_members_with_points(): for subpath in submob.get_subpaths(): quads = vmobject.get_bezier_tuples_from_points(subpath) start = subpath[0] path.moveTo(*start[:2]) for p0, p1, p2 in quads: path.quadTo(*p1[:2], *p2[:2]) if vmobject.consider_points_equal(subpath[0], subpath[-1]): path.close() return path def _convert_skia_path_to_vmobject( path: pathops.Path, vmobject: VMobject ) -> VMobject: PathVerb = pathops.PathVerb current_path_start = np.array([0.0, 0.0, 0.0]) for path_verb, points in path: if path_verb == PathVerb.CLOSE: vmobject.add_line_to(current_path_start) else: points = np.hstack((np.array(points), np.zeros((len(points), 1)))) if path_verb == PathVerb.MOVE: for point in points: current_path_start = point vmobject.start_new_path(point) elif path_verb == PathVerb.CUBIC: vmobject.add_cubic_bezier_curve_to(*points) elif path_verb == PathVerb.LINE: vmobject.add_line_to(points[0]) elif path_verb == PathVerb.QUAD: vmobject.add_quadratic_bezier_curve_to(*points) else: raise Exception(f"Unsupported: {path_verb}") return vmobject.reverse_points() class Union(VMobject): def __init__(self, *vmobjects: VMobject, **kwargs): if len(vmobjects) < 2: raise ValueError("At least 2 mobjects needed for Union.") super().__init__(**kwargs) outpen = pathops.Path() paths = [ _convert_vmobject_to_skia_path(vmobject) for vmobject in vmobjects ] pathops.union(paths, outpen.getPen()) _convert_skia_path_to_vmobject(outpen, self) class Difference(VMobject): def __init__(self, subject: VMobject, clip: VMobject, **kwargs): super().__init__(**kwargs) outpen = pathops.Path() pathops.difference( [_convert_vmobject_to_skia_path(subject)], [_convert_vmobject_to_skia_path(clip)], outpen.getPen(), ) _convert_skia_path_to_vmobject(outpen, self) class Intersection(VMobject): def __init__(self, *vmobjects: VMobject, **kwargs): if len(vmobjects) < 2: raise ValueError("At least 2 mobjects needed for Intersection.") super().__init__(**kwargs) outpen = pathops.Path() pathops.intersection( [_convert_vmobject_to_skia_path(vmobjects[0])], [_convert_vmobject_to_skia_path(vmobjects[1])], outpen.getPen(), ) new_outpen = outpen for _i in range(2, len(vmobjects)): new_outpen = pathops.Path() pathops.intersection( [outpen], [_convert_vmobject_to_skia_path(vmobjects[_i])], new_outpen.getPen(), ) outpen = new_outpen _convert_skia_path_to_vmobject(outpen, self) class Exclusion(VMobject): def __init__(self, *vmobjects: VMobject, **kwargs): if len(vmobjects) < 2: raise ValueError("At least 2 mobjects needed for Exclusion.") super().__init__(**kwargs) outpen = pathops.Path() pathops.xor( [_convert_vmobject_to_skia_path(vmobjects[0])], [_convert_vmobject_to_skia_path(vmobjects[1])], outpen.getPen(), ) new_outpen = outpen for _i in range(2, len(vmobjects)): new_outpen = pathops.Path() pathops.xor( [outpen], [_convert_vmobject_to_skia_path(vmobjects[_i])], new_outpen.getPen(), ) outpen = new_outpen _convert_skia_path_to_vmobject(outpen, self)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/numbers.py
manimlib/mobject/numbers.py
from __future__ import annotations from functools import lru_cache import numpy as np from manimlib.constants import DOWN, LEFT, RIGHT, UP from manimlib.constants import DEFAULT_MOBJECT_COLOR from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.paths import straight_path from manimlib.utils.bezier import interpolate from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import TypeVar, Callable from manimlib.mobject.mobject import Mobject from manimlib.typing import ManimColor, Vect3, Self T = TypeVar("T", bound=VMobject) @lru_cache() def char_to_cahced_mob(char: str, **text_config): if "\\" in char: # This is for when the "character" is a LaTeX command # like ^\circ or \dots return Tex(char, **text_config) else: return Text(char, **text_config) class DecimalNumber(VMobject): def __init__( self, number: float | complex = 0, color: ManimColor = DEFAULT_MOBJECT_COLOR, stroke_width: float = 0, fill_opacity: float = 1.0, fill_border_width: float = 0.5, num_decimal_places: int = 2, min_total_width: Optional[int] = 0, include_sign: bool = False, group_with_commas: bool = True, digit_buff_per_font_unit: float = 0.001, show_ellipsis: bool = False, unit: str | None = None, # Aligned to bottom unless it starts with "^" include_background_rectangle: bool = False, hide_zero_components_on_complex: bool = True, edge_to_fix: Vect3 = LEFT, font_size: float = 48, text_config: dict = dict(), # Do not pass in font_size here **kwargs ): self.num_decimal_places = num_decimal_places self.include_sign = include_sign self.group_with_commas = group_with_commas self.min_total_width = min_total_width self.digit_buff_per_font_unit = digit_buff_per_font_unit self.show_ellipsis = show_ellipsis self.unit = unit self.include_background_rectangle = include_background_rectangle self.hide_zero_components_on_complex = hide_zero_components_on_complex self.edge_to_fix = edge_to_fix self.font_size = font_size self.text_config = dict(text_config) super().__init__( color=color, stroke_width=stroke_width, fill_opacity=fill_opacity, fill_border_width=fill_border_width, **kwargs ) self.set_submobjects_from_number(number) self.init_colors() def set_submobjects_from_number(self, number: float | complex) -> None: # Create the submobject list self.number = number self.num_string = self.get_num_string(number) # Submob_templates will be a list of cached Tex and Text mobjects, # with the intent of calling .copy or .become on them submob_templates = list(map(self.char_to_mob, self.num_string)) if self.show_ellipsis: dots = self.char_to_mob("...") dots.arrange(RIGHT, buff=2 * dots[0].get_width()) submob_templates.append(dots) if self.unit is not None: submob_templates.append(self.char_to_mob(self.unit)) # Set internals font_size = self.get_font_size() if len(submob_templates) == len(self.submobjects): for sm, smt in zip(self.submobjects, submob_templates): sm.become(smt) sm.scale(font_size / smt.font_size) else: self.set_submobjects([ smt.copy().scale(font_size / smt.font_size) for smt in submob_templates ]) digit_buff = self.digit_buff_per_font_unit * font_size self.arrange(RIGHT, buff=digit_buff, aligned_edge=DOWN) # Handle alignment of special characters for i, c in enumerate(self.num_string): if c == "–" and len(self.num_string) > i + 1: self[i].align_to(self[i + 1], UP) self[i].shift(self[i + 1].get_height() * DOWN / 2) elif c == ",": self[i].shift(self[i].get_height() * DOWN / 2) if self.unit and self.unit.startswith("^"): self[-1].align_to(self, UP) if self.include_background_rectangle: self.add_background_rectangle() def get_num_string(self, number: float | complex) -> str: if isinstance(number, complex): if self.hide_zero_components_on_complex and number.imag == 0: number = number.real formatter = self.get_formatter() elif self.hide_zero_components_on_complex and number.real == 0: number = number.imag formatter = self.get_formatter() + "i" else: formatter = self.get_complex_formatter() else: formatter = self.get_formatter() if self.num_decimal_places == 0 and isinstance(number, float): number = int(number) num_string = formatter.format(number) rounded_num = np.round(number, self.num_decimal_places) if num_string.startswith("-") and rounded_num == 0: if self.include_sign: num_string = "+" + num_string[1:] else: num_string = num_string[1:] num_string = num_string.replace("-", "–") return num_string def char_to_mob(self, char: str) -> Text: return char_to_cahced_mob(char, **self.text_config) def interpolate( self, mobject1: Mobject, mobject2: Mobject, alpha: float, path_func: Callable[[np.ndarray, np.ndarray, float], np.ndarray] = straight_path ) -> Self: super().interpolate(mobject1, mobject2, alpha, path_func) if hasattr(mobject1, "font_size") and hasattr(mobject2, "font_size"): self.font_size = interpolate(mobject1.font_size, mobject2.font_size, alpha) def get_font_size(self) -> float: return self.font_size def get_formatter(self, **kwargs) -> str: """ Configuration is based first off instance attributes, but overwritten by any kew word argument. Relevant key words: - include_sign - group_with_commas - num_decimal_places - field_name (e.g. 0 or 0.real) """ config = dict([ (attr, getattr(self, attr)) for attr in [ "include_sign", "group_with_commas", "num_decimal_places", "min_total_width", ] ]) config.update(kwargs) ndp = config["num_decimal_places"] return "".join([ "{", config.get("field_name", ""), ":", "+" if config["include_sign"] else "", "0" + str(config.get("min_total_width", "")) if config.get("min_total_width") else "", "," if config["group_with_commas"] else "", f".{ndp}f" if ndp > 0 else "d", "}", ]) def get_complex_formatter(self, **kwargs) -> str: return "".join([ self.get_formatter(field_name="0.real"), self.get_formatter(field_name="0.imag", include_sign=True), "i" ]) def get_tex(self): return self.num_string def set_value(self, number: float | complex) -> Self: move_to_point = self.get_edge_center(self.edge_to_fix) style = self.family_members_with_points()[0].get_style() self.set_submobjects_from_number(number) self.move_to(move_to_point, self.edge_to_fix) self.set_style(**style) for submob in self.get_family(): submob.uniforms.update(self.uniforms) return self def _handle_scale_side_effects(self, scale_factor: float) -> Self: self.font_size *= scale_factor return self def get_value(self) -> float | complex: return self.number def increment_value(self, delta_t: float | complex = 1) -> Self: self.set_value(self.get_value() + delta_t) return self class Integer(DecimalNumber): def __init__( self, number: int = 0, num_decimal_places: int = 0, **kwargs, ): super().__init__(number, num_decimal_places=num_decimal_places, **kwargs) def get_value(self) -> int: return int(np.round(super().get_value()))
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/probability.py
manimlib/mobject/probability.py
from __future__ import annotations import numpy as np from manimlib.constants import BLUE, BLUE_E, GREEN_E, GREY_B, GREY_D, MAROON_B, YELLOW from manimlib.constants import DOWN, LEFT, RIGHT, UP from manimlib.constants import MED_LARGE_BUFF, MED_SMALL_BUFF, SMALL_BUFF from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.mobject import Mobject from manimlib.mobject.svg.brace import Brace from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.color import color_gradient from manimlib.utils.iterables import listify from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable from manimlib.typing import ManimColor EPSILON = 0.0001 class SampleSpace(Rectangle): def __init__( self, width: float = 3, height: float = 3, fill_color: ManimColor = GREY_D, fill_opacity: float = 1, stroke_width: float = 0.5, stroke_color: ManimColor = GREY_B, default_label_scale_val: float = 1, **kwargs, ): super().__init__( width, height, fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, stroke_color=stroke_color, **kwargs ) self.default_label_scale_val = default_label_scale_val def add_title( self, title: str = "Sample space", buff: float = MED_SMALL_BUFF ) -> None: # TODO, should this really exist in SampleSpaceScene title_mob = TexText(title) if title_mob.get_width() > self.get_width(): title_mob.set_width(self.get_width()) title_mob.next_to(self, UP, buff=buff) self.title = title_mob self.add(title_mob) def add_label(self, label: str) -> None: self.label = label def complete_p_list(self, p_list: list[float]) -> list[float]: new_p_list = listify(p_list) remainder = 1.0 - sum(new_p_list) if abs(remainder) > EPSILON: new_p_list.append(remainder) return new_p_list def get_division_along_dimension( self, p_list: list[float], dim: int, colors: Iterable[ManimColor], vect: np.ndarray ) -> VGroup: p_list = self.complete_p_list(p_list) colors = color_gradient(colors, len(p_list)) last_point = self.get_edge_center(-vect) parts = VGroup() for factor, color in zip(p_list, colors): part = SampleSpace() part.set_fill(color, 1) part.replace(self, stretch=True) part.stretch(factor, dim) part.move_to(last_point, -vect) last_point = part.get_edge_center(vect) parts.add(part) return parts def get_horizontal_division( self, p_list: list[float], colors: Iterable[ManimColor] = [GREEN_E, BLUE_E], vect: np.ndarray = DOWN ) -> VGroup: return self.get_division_along_dimension(p_list, 1, colors, vect) def get_vertical_division( self, p_list: list[float], colors: Iterable[ManimColor] = [MAROON_B, YELLOW], vect: np.ndarray = RIGHT ) -> VGroup: return self.get_division_along_dimension(p_list, 0, colors, vect) def divide_horizontally(self, *args, **kwargs) -> None: self.horizontal_parts = self.get_horizontal_division(*args, **kwargs) self.add(self.horizontal_parts) def divide_vertically(self, *args, **kwargs) -> None: self.vertical_parts = self.get_vertical_division(*args, **kwargs) self.add(self.vertical_parts) def get_subdivision_braces_and_labels( self, parts: VGroup, labels: str, direction: np.ndarray, buff: float = SMALL_BUFF, ) -> VGroup: label_mobs = VGroup() braces = VGroup() for label, part in zip(labels, parts): brace = Brace( part, direction, buff=buff ) if isinstance(label, Mobject): label_mob = label else: label_mob = Tex(label) label_mob.scale(self.default_label_scale_val) label_mob.next_to(brace, direction, buff) braces.add(brace) label_mobs.add(label_mob) parts.braces = braces parts.labels = label_mobs parts.label_kwargs = { "labels": label_mobs.copy(), "direction": direction, "buff": buff, } return VGroup(parts.braces, parts.labels) def get_side_braces_and_labels( self, labels: str, direction: np.ndarray = LEFT, **kwargs ) -> VGroup: assert hasattr(self, "horizontal_parts") parts = self.horizontal_parts return self.get_subdivision_braces_and_labels(parts, labels, direction, **kwargs) def get_top_braces_and_labels( self, labels: str, **kwargs ) -> VGroup: assert hasattr(self, "vertical_parts") parts = self.vertical_parts return self.get_subdivision_braces_and_labels(parts, labels, UP, **kwargs) def get_bottom_braces_and_labels( self, labels: str, **kwargs ) -> VGroup: assert hasattr(self, "vertical_parts") parts = self.vertical_parts return self.get_subdivision_braces_and_labels(parts, labels, DOWN, **kwargs) def add_braces_and_labels(self) -> None: for attr in "horizontal_parts", "vertical_parts": if not hasattr(self, attr): continue parts = getattr(self, attr) for subattr in "braces", "labels": if hasattr(parts, subattr): self.add(getattr(parts, subattr)) def __getitem__(self, index: int | slice) -> VGroup: if hasattr(self, "horizontal_parts"): return self.horizontal_parts[index] elif hasattr(self, "vertical_parts"): return self.vertical_parts[index] return self.split()[index] class BarChart(VGroup): def __init__( self, values: Iterable[float], height: float = 4, width: float = 6, n_ticks: int = 4, include_x_ticks: bool = False, tick_width: float = 0.2, tick_height: float = 0.15, label_y_axis: bool = True, y_axis_label_height: float = 0.25, max_value: float = 1, bar_colors: list[ManimColor] = [BLUE, YELLOW], bar_fill_opacity: float = 0.8, bar_stroke_width: float = 3, bar_names: list[str] = [], bar_label_scale_val: float = 0.75, **kwargs ): super().__init__(**kwargs) self.height = height self.width = width self.n_ticks = n_ticks self.include_x_ticks = include_x_ticks self.tick_width = tick_width self.tick_height = tick_height self.label_y_axis = label_y_axis self.y_axis_label_height = y_axis_label_height self.max_value = max_value self.bar_colors = bar_colors self.bar_fill_opacity = bar_fill_opacity self.bar_stroke_width = bar_stroke_width self.bar_names = bar_names self.bar_label_scale_val = bar_label_scale_val if self.max_value is None: self.max_value = max(values) self.n_ticks_x = len(values) self.add_axes() self.add_bars(values) self.center() def add_axes(self) -> None: x_axis = Line(self.tick_width * LEFT / 2, self.width * RIGHT) y_axis = Line(MED_LARGE_BUFF * DOWN, self.height * UP) y_ticks = VGroup() heights = np.linspace(0, self.height, self.n_ticks + 1) values = np.linspace(0, self.max_value, self.n_ticks + 1) for y, value in zip(heights, values): y_tick = Line(LEFT, RIGHT) y_tick.set_width(self.tick_width) y_tick.move_to(y * UP) y_ticks.add(y_tick) y_axis.add(y_ticks) if self.include_x_ticks == True: x_ticks = VGroup() widths = np.linspace(0, self.width, self.n_ticks_x + 1) label_values = np.linspace(0, len(self.bar_names), self.n_ticks_x + 1) for x, value in zip(widths, label_values): x_tick = Line(UP, DOWN) x_tick.set_height(self.tick_height) x_tick.move_to(x * RIGHT) x_ticks.add(x_tick) x_axis.add(x_ticks) self.add(x_axis, y_axis) self.x_axis, self.y_axis = x_axis, y_axis if self.label_y_axis: labels = VGroup() for y_tick, value in zip(y_ticks, values): label = Tex(str(np.round(value, 2))) label.set_height(self.y_axis_label_height) label.next_to(y_tick, LEFT, SMALL_BUFF) labels.add(label) self.y_axis_labels = labels self.add(labels) def add_bars(self, values: Iterable[float]) -> None: buff = float(self.width) / (2 * len(values)) bars = VGroup() for i, value in enumerate(values): bar = Rectangle( height=(value / self.max_value) * self.height, width=buff, stroke_width=self.bar_stroke_width, fill_opacity=self.bar_fill_opacity, ) bar.move_to((2 * i + 0.5) * buff * RIGHT, DOWN + LEFT * 5) bars.add(bar) bars.set_color_by_gradient(*self.bar_colors) bar_labels = VGroup() for bar, name in zip(bars, self.bar_names): label = Tex(str(name)) label.scale(self.bar_label_scale_val) label.next_to(bar, DOWN, SMALL_BUFF) bar_labels.add(label) self.add(bars, bar_labels) self.bars = bars self.bar_labels = bar_labels def change_bar_values(self, values: Iterable[float]) -> None: for bar, value in zip(self.bars, values): bar_bottom = bar.get_bottom() bar.stretch_to_fit_height( (value / self.max_value) * self.height ) bar.move_to(bar_bottom, DOWN)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/coordinate_systems.py
manimlib/mobject/coordinate_systems.py
from __future__ import annotations from abc import ABC, abstractmethod import numbers import numpy as np import itertools as it from manimlib.constants import BLACK, BLUE, BLUE_D, BLUE_E, GREEN, GREY_A, RED, DEFAULT_MOBJECT_COLOR from manimlib.constants import DEG, PI from manimlib.constants import DL, UL, DOWN, DR, LEFT, ORIGIN, OUT, RIGHT, UP from manimlib.constants import FRAME_X_RADIUS, FRAME_Y_RADIUS from manimlib.constants import MED_SMALL_BUFF, SMALL_BUFF from manimlib.mobject.functions import ParametricCurve from manimlib.mobject.geometry import Arrow from manimlib.mobject.geometry import DashedLine from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.number_line import NumberLine from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.types.dot_cloud import DotCloud from manimlib.mobject.types.surface import ParametricSurface from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import inverse_interpolate from manimlib.utils.dict_ops import merge_dicts_recursively from manimlib.utils.simple_functions import binary_search from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import rotate_vector from manimlib.utils.space_ops import normalize from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable, Sequence, Type, TypeVar, Optional from manimlib.mobject.mobject import Mobject from manimlib.typing import ManimColor, Vect3, Vect3Array, VectN, RangeSpecifier, Self T = TypeVar("T", bound=Mobject) EPSILON = 1e-8 DEFAULT_X_RANGE = (-8.0, 8.0, 1.0) DEFAULT_Y_RANGE = (-4.0, 4.0, 1.0) def full_range_specifier(range_args): if len(range_args) == 2: return (*range_args, 1) return range_args class CoordinateSystem(ABC): """ Abstract class for Axes and NumberPlane """ dimension: int = 2 def __init__( self, x_range: RangeSpecifier = DEFAULT_X_RANGE, y_range: RangeSpecifier = DEFAULT_Y_RANGE, num_sampled_graph_points_per_tick: int = 5, ): self.x_range = full_range_specifier(x_range) self.y_range = full_range_specifier(y_range) self.num_sampled_graph_points_per_tick = num_sampled_graph_points_per_tick @abstractmethod def coords_to_point(self, *coords: float | VectN) -> Vect3 | Vect3Array: raise Exception("Not implemented") @abstractmethod def point_to_coords(self, point: Vect3 | Vect3Array) -> tuple[float | VectN, ...]: raise Exception("Not implemented") def c2p(self, *coords: float) -> Vect3 | Vect3Array: """Abbreviation for coords_to_point""" return self.coords_to_point(*coords) def p2c(self, point: Vect3) -> tuple[float | VectN, ...]: """Abbreviation for point_to_coords""" return self.point_to_coords(point) def get_origin(self) -> Vect3: return self.c2p(*[0] * self.dimension) @abstractmethod def get_axes(self) -> VGroup: raise Exception("Not implemented") @abstractmethod def get_all_ranges(self) -> list[np.ndarray]: raise Exception("Not implemented") def get_axis(self, index: int) -> NumberLine: return self.get_axes()[index] def get_x_axis(self) -> NumberLine: return self.get_axis(0) def get_y_axis(self) -> NumberLine: return self.get_axis(1) def get_z_axis(self) -> NumberLine: return self.get_axis(2) def get_x_axis_label( self, label_tex: str, edge: Vect3 = RIGHT, direction: Vect3 = DL, **kwargs ) -> Tex: return self.get_axis_label( label_tex, self.get_x_axis(), edge, direction, **kwargs ) def get_y_axis_label( self, label_tex: str, edge: Vect3 = UP, direction: Vect3 = DR, **kwargs ) -> Tex: return self.get_axis_label( label_tex, self.get_y_axis(), edge, direction, **kwargs ) def get_axis_label( self, label_tex: str, axis: Vect3, edge: Vect3, direction: Vect3, buff: float = MED_SMALL_BUFF, ensure_on_screen: bool = False ) -> Tex: label = Tex(label_tex) label.next_to( axis.get_edge_center(edge), direction, buff=buff ) if ensure_on_screen: label.shift_onto_screen(buff=MED_SMALL_BUFF) return label def get_axis_labels( self, x_label_tex: str = "x", y_label_tex: str = "y" ) -> VGroup: self.axis_labels = VGroup( self.get_x_axis_label(x_label_tex), self.get_y_axis_label(y_label_tex), ) return self.axis_labels def get_line_from_axis_to_point( self, index: int, point: Vect3, line_func: Type[T] = DashedLine, color: ManimColor = GREY_A, stroke_width: float = 2 ) -> T: axis = self.get_axis(index) line = line_func(axis.get_projection(point), point) line.set_stroke(color, stroke_width) return line def get_v_line(self, point: Vect3, **kwargs): return self.get_line_from_axis_to_point(0, point, **kwargs) def get_h_line(self, point: Vect3, **kwargs): return self.get_line_from_axis_to_point(1, point, **kwargs) # Useful for graphing def get_graph( self, function: Callable[[float], float], x_range: Sequence[float] | None = None, bind: bool = False, **kwargs ) -> ParametricCurve: x_range = x_range or self.x_range t_range = np.ones(3) t_range[:len(x_range)] = x_range # For axes, the third coordinate of x_range indicates # tick frequency. But for functions, it indicates a # sample frequency t_range[2] /= self.num_sampled_graph_points_per_tick def parametric_function(t: float) -> Vect3: return self.c2p(t, function(t)) graph = ParametricCurve( parametric_function, t_range=tuple(t_range), **kwargs ) graph.underlying_function = function graph.x_range = x_range if bind: self.bind_graph_to_func(graph, function) return graph def get_parametric_curve( self, function: Callable[[float], Vect3], **kwargs ) -> ParametricCurve: dim = self.dimension graph = ParametricCurve( lambda t: self.coords_to_point(*function(t)[:dim]), **kwargs ) graph.underlying_function = function return graph def input_to_graph_point( self, x: float, graph: ParametricCurve ) -> Vect3 | None: if hasattr(graph, "underlying_function"): return self.coords_to_point(x, graph.underlying_function(x)) else: alpha = binary_search( function=lambda a: self.point_to_coords( graph.quick_point_from_proportion(a) )[0], target=x, lower_bound=self.x_range[0], upper_bound=self.x_range[1], ) if alpha is not None: return graph.quick_point_from_proportion(alpha) else: return None def i2gp(self, x: float, graph: ParametricCurve) -> Vect3 | None: """ Alias for input_to_graph_point """ return self.input_to_graph_point(x, graph) def bind_graph_to_func( self, graph: VMobject, func: Callable[[VectN], VectN], jagged: bool = False, get_discontinuities: Optional[Callable[[], Vect3]] = None ) -> VMobject: """ Use for graphing functions which might change over time, or change with conditions """ x_values = np.array([self.x_axis.p2n(p) for p in graph.get_points()]) def get_graph_points(): xs = x_values if get_discontinuities: ds = get_discontinuities() ep = 1e-6 added_xs = it.chain(*((d - ep, d + ep) for d in ds)) xs[:] = sorted([*x_values, *added_xs])[:len(x_values)] return self.c2p(xs, func(xs)) graph.add_updater( lambda g: g.set_points_as_corners(get_graph_points()) ) if not jagged: graph.add_updater(lambda g: g.make_smooth(approx=True)) return graph def get_graph_label( self, graph: ParametricCurve, label: str | Mobject = "f(x)", x: float | None = None, direction: Vect3 = RIGHT, buff: float = MED_SMALL_BUFF, color: ManimColor | None = None ) -> Tex | Mobject: if isinstance(label, str): label = Tex(label) if color is None: label.match_color(graph) if x is None: # Searching from the right, find a point # whose y value is in bounds max_y = FRAME_Y_RADIUS - label.get_height() max_x = FRAME_X_RADIUS - label.get_width() for x0 in np.arange(*self.x_range)[::-1]: pt = self.i2gp(x0, graph) if abs(pt[0]) < max_x and abs(pt[1]) < max_y: x = x0 break if x is None: x = self.x_range[1] point = self.input_to_graph_point(x, graph) angle = self.angle_of_tangent(x, graph) normal = rotate_vector(RIGHT, angle + 90 * DEG) if normal[1] < 0: normal *= -1 label.next_to(point, normal, buff=buff) label.shift_onto_screen() return label def get_v_line_to_graph(self, x: float, graph: ParametricCurve, **kwargs): return self.get_v_line(self.i2gp(x, graph), **kwargs) def get_h_line_to_graph(self, x: float, graph: ParametricCurve, **kwargs): return self.get_h_line(self.i2gp(x, graph), **kwargs) def get_scatterplot(self, x_values: Vect3Array, y_values: Vect3Array, **dot_config): return DotCloud(self.c2p(x_values, y_values), **dot_config) # For calculus def angle_of_tangent( self, x: float, graph: ParametricCurve, dx: float = EPSILON ) -> float: p0 = self.input_to_graph_point(x, graph) p1 = self.input_to_graph_point(x + dx, graph) return angle_of_vector(p1 - p0) def slope_of_tangent( self, x: float, graph: ParametricCurve, **kwargs ) -> float: return np.tan(self.angle_of_tangent(x, graph, **kwargs)) def get_tangent_line( self, x: float, graph: ParametricCurve, length: float = 5, line_func: Type[T] = Line ) -> T: line = line_func(LEFT, RIGHT) line.set_width(length) line.rotate(self.angle_of_tangent(x, graph)) line.move_to(self.input_to_graph_point(x, graph)) return line def get_riemann_rectangles( self, graph: ParametricCurve, x_range: Sequence[float] = None, dx: float | None = None, input_sample_type: str = "left", stroke_width: float = 1, stroke_color: ManimColor = BLACK, fill_opacity: float = 1, colors: Iterable[ManimColor] = (BLUE, GREEN), negative_color: ManimColor = RED, stroke_background: bool = True, show_signed_area: bool = True ) -> VGroup: if x_range is None: x_range = self.x_range[:2] if dx is None: dx = self.x_range[2] if len(x_range) < 3: x_range = [*x_range, dx] rects = [] x_range[1] = x_range[1] + dx xs = np.arange(*x_range) for x0, x1 in zip(xs, xs[1:]): if input_sample_type == "left": sample = x0 elif input_sample_type == "right": sample = x1 elif input_sample_type == "center": sample = 0.5 * x0 + 0.5 * x1 else: raise Exception("Invalid input sample type") height_vect = self.i2gp(sample, graph) - self.c2p(sample, 0) rect = Rectangle( width=self.x_axis.n2p(x1)[0] - self.x_axis.n2p(x0)[0], height=get_norm(height_vect), ) rect.positive = height_vect[1] > 0 rect.move_to(self.c2p(x0, 0), DL if rect.positive else UL) rects.append(rect) result = VGroup(*rects) result.set_submobject_colors_by_gradient(*colors) result.set_style( stroke_width=stroke_width, stroke_color=stroke_color, fill_opacity=fill_opacity, stroke_behind=stroke_background ) for rect in result: if not rect.positive: rect.set_fill(negative_color) return result def get_area_under_graph(self, graph, x_range=None, fill_color=BLUE, fill_opacity=0.5): if x_range is None: x_range = [ self.x_axis.p2n(graph.get_start()), self.x_axis.p2n(graph.get_end()), ] alpha_bounds = [ inverse_interpolate(*graph.x_range[:2], x) for x in x_range ] sub_graph = graph.copy() sub_graph.clear_updaters() sub_graph.pointwise_become_partial(graph, *alpha_bounds) sub_graph.add_line_to(self.c2p(x_range[1], 0)) sub_graph.add_line_to(self.c2p(x_range[0], 0)) sub_graph.add_line_to(sub_graph.get_start()) sub_graph.set_stroke(width=0) sub_graph.set_fill(fill_color, fill_opacity) return sub_graph class Axes(VGroup, CoordinateSystem): default_axis_config: dict = dict() default_x_axis_config: dict = dict() default_y_axis_config: dict = dict(line_to_number_direction=LEFT) def __init__( self, x_range: RangeSpecifier = DEFAULT_X_RANGE, y_range: RangeSpecifier = DEFAULT_Y_RANGE, axis_config: dict = dict(), x_axis_config: dict = dict(), y_axis_config: dict = dict(), height: float | None = None, width: float | None = None, unit_size: float = 1.0, **kwargs ): CoordinateSystem.__init__(self, x_range, y_range, **kwargs) kwargs.pop("num_sampled_graph_points_per_tick", None) VGroup.__init__(self, **kwargs) axis_config = dict(**axis_config, unit_size=unit_size) self.x_axis = self.create_axis( self.x_range, axis_config=merge_dicts_recursively( self.default_axis_config, self.default_x_axis_config, axis_config, x_axis_config ), length=width, ) self.y_axis = self.create_axis( self.y_range, axis_config=merge_dicts_recursively( self.default_axis_config, self.default_y_axis_config, axis_config, y_axis_config ), length=height, ) self.y_axis.rotate(90 * DEG, about_point=ORIGIN) # Add as a separate group in case various other # mobjects are added to self, as for example in # NumberPlane below self.axes = VGroup(self.x_axis, self.y_axis) self.add(*self.axes) self.center() def create_axis( self, range_terms: RangeSpecifier, axis_config: dict, length: float | None ) -> NumberLine: axis = NumberLine(range_terms, width=length, **axis_config) axis.shift(-axis.n2p(0)) return axis def coords_to_point(self, *coords: float | VectN) -> Vect3 | Vect3Array: origin = self.x_axis.number_to_point(0) return origin + sum( axis.number_to_point(coord) - origin for axis, coord in zip(self.get_axes(), coords) ) def point_to_coords(self, point: Vect3 | Vect3Array) -> tuple[float | VectN, ...]: return tuple([ axis.point_to_number(point) for axis in self.get_axes() ]) def get_axes(self) -> VGroup: return self.axes def get_all_ranges(self) -> list[Sequence[float]]: return [self.x_range, self.y_range] def add_coordinate_labels( self, x_values: Iterable[float] | None = None, y_values: Iterable[float] | None = None, excluding: Iterable[float] = [0], **kwargs ) -> VGroup: axes = self.get_axes() self.coordinate_labels = VGroup() for axis, values in zip(axes, [x_values, y_values]): labels = axis.add_numbers(values, excluding=excluding, **kwargs) self.coordinate_labels.add(labels) return self.coordinate_labels class ThreeDAxes(Axes): dimension: int = 3 default_z_axis_config: dict = dict() def __init__( self, x_range: RangeSpecifier = (-6.0, 6.0, 1.0), y_range: RangeSpecifier = (-5.0, 5.0, 1.0), z_range: RangeSpecifier = (-4.0, 4.0, 1.0), z_axis_config: dict = dict(), z_normal: Vect3 = DOWN, depth: float | None = None, **kwargs ): Axes.__init__(self, x_range, y_range, **kwargs) self.z_range = full_range_specifier(z_range) self.z_axis = self.create_axis( self.z_range, axis_config=merge_dicts_recursively( self.default_axis_config, self.default_z_axis_config, kwargs.get("axis_config", {}), z_axis_config ), length=depth, ) self.z_axis.rotate(-PI / 2, UP, about_point=ORIGIN) self.z_axis.rotate( angle_of_vector(z_normal), OUT, about_point=ORIGIN ) self.z_axis.shift(self.x_axis.n2p(0)) self.axes.add(self.z_axis) self.add(self.z_axis) def get_all_ranges(self) -> list[Sequence[float]]: return [self.x_range, self.y_range, self.z_range] def add_axis_labels(self, x_tex="x", y_tex="y", z_tex="z", font_size=24, buff=0.2): x_label, y_label, z_label = labels = VGroup(*( Tex(tex, font_size=font_size) for tex in [x_tex, y_tex, z_tex] )) z_label.rotate(PI / 2, RIGHT) for label, axis in zip(labels, self): label.next_to(axis, normalize(np.round(axis.get_vector()), 2), buff=buff) axis.add(label) self.axis_labels = labels def get_graph( self, func, color=BLUE_E, opacity=0.9, u_range=None, v_range=None, **kwargs ) -> ParametricSurface: xu = self.x_axis.get_unit_size() yu = self.y_axis.get_unit_size() zu = self.z_axis.get_unit_size() x0, y0, z0 = self.get_origin() u_range = u_range or self.x_range[:2] v_range = v_range or self.y_range[:2] return ParametricSurface( lambda u, v: [xu * u + x0, yu * v + y0, zu * func(u, v) + z0], u_range=u_range, v_range=v_range, color=color, opacity=opacity, **kwargs ) def get_parametric_surface( self, func, color=BLUE_E, opacity=0.9, **kwargs ) -> ParametricSurface: surface = ParametricSurface(func, color=color, opacity=opacity, **kwargs) axes = [self.x_axis, self.y_axis, self.z_axis] for dim, axis in zip(range(3), axes): surface.stretch(axis.get_unit_size(), dim, about_point=ORIGIN) surface.shift(self.get_origin()) return surface class NumberPlane(Axes): default_axis_config: dict = dict( stroke_color=DEFAULT_MOBJECT_COLOR, stroke_width=2, include_ticks=False, include_tip=False, line_to_number_buff=SMALL_BUFF, line_to_number_direction=DL, ) default_y_axis_config: dict = dict( line_to_number_direction=DL, ) def __init__( self, x_range: RangeSpecifier = (-8.0, 8.0, 1.0), y_range: RangeSpecifier = (-4.0, 4.0, 1.0), background_line_style: dict = dict( stroke_color=BLUE_D, stroke_width=2, stroke_opacity=1, ), # Defaults to a faded version of line_config faded_line_style: dict = dict( stroke_width=1, stroke_opacity=0.25, ), faded_line_ratio: int = 4, make_smooth_after_applying_functions: bool = True, **kwargs ): super().__init__(x_range, y_range, **kwargs) self.background_line_style = dict(background_line_style) self.faded_line_style = dict(faded_line_style) self.faded_line_ratio = faded_line_ratio self.make_smooth_after_applying_functions = make_smooth_after_applying_functions self.init_background_lines() def init_background_lines(self) -> None: if "stroke_color" not in self.faded_line_style: self.faded_line_style["stroke_color"] = self.background_line_style["stroke_color"] self.background_lines, self.faded_lines = self.get_lines() self.background_lines.set_style(**self.background_line_style) self.faded_lines.set_style(**self.faded_line_style) self.add_to_back( self.faded_lines, self.background_lines, ) def get_lines(self) -> tuple[VGroup, VGroup]: x_axis = self.get_x_axis() y_axis = self.get_y_axis() x_lines1, x_lines2 = self.get_lines_parallel_to_axis(x_axis, y_axis) y_lines1, y_lines2 = self.get_lines_parallel_to_axis(y_axis, x_axis) lines1 = VGroup(*x_lines1, *y_lines1) lines2 = VGroup(*x_lines2, *y_lines2) return lines1, lines2 def get_lines_parallel_to_axis( self, axis1: NumberLine, axis2: NumberLine ) -> tuple[VGroup, VGroup]: freq = axis2.x_step ratio = self.faded_line_ratio line = Line(axis1.get_start(), axis1.get_end()) dense_freq = (1 + ratio) step = (1 / dense_freq) * freq lines1 = VGroup() lines2 = VGroup() inputs = np.arange(axis2.x_min, axis2.x_max + step, step) for i, x in enumerate(inputs): if abs(x) < 1e-8: continue new_line = line.copy() new_line.shift(axis2.n2p(x) - axis2.n2p(0)) if i % (1 + ratio) == 0: lines1.add(new_line) else: lines2.add(new_line) return lines1, lines2 def get_x_unit_size(self) -> float: return self.get_x_axis().get_unit_size() def get_y_unit_size(self) -> list: return self.get_x_axis().get_unit_size() def get_axes(self) -> VGroup: return self.axes def get_vector(self, coords: Iterable[float], **kwargs) -> Arrow: kwargs["buff"] = 0 return Arrow(self.c2p(0, 0), self.c2p(*coords), **kwargs) def prepare_for_nonlinear_transform(self, num_inserted_curves: int = 50) -> Self: for mob in self.family_members_with_points(): num_curves = mob.get_num_curves() if num_inserted_curves > num_curves: mob.insert_n_curves(num_inserted_curves - num_curves) mob.make_smooth_after_applying_functions = True return self class ComplexPlane(NumberPlane): def number_to_point(self, number: complex | float | np.array) -> Vect3: return self.coords_to_point(np.real(number), np.imag(number)) def n2p(self, number: complex | float | np.array) -> Vect3: return self.number_to_point(number) def point_to_number(self, point: Vect3) -> complex: x, y = self.point_to_coords(point) return complex(x, y) def p2n(self, point: Vect3) -> complex: return self.point_to_number(point) def get_default_coordinate_values( self, skip_first: bool = True ) -> list[complex]: x_numbers = self.get_x_axis().get_tick_range()[1:] y_numbers = self.get_y_axis().get_tick_range()[1:] y_numbers = [complex(0, y) for y in y_numbers if y != 0] return [*x_numbers, *y_numbers] def add_coordinate_labels( self, numbers: list[complex] | None = None, skip_first: bool = True, font_size: int = 36, **kwargs ) -> Self: if numbers is None: numbers = self.get_default_coordinate_values(skip_first) self.coordinate_labels = VGroup() for number in numbers: z = complex(number) if abs(z.imag) > abs(z.real): axis = self.get_y_axis() value = z.imag kwargs["unit_tex"] = "i" else: axis = self.get_x_axis() value = z.real number_mob = axis.get_number_mobject(value, font_size=font_size, **kwargs) self.coordinate_labels.add(number_mob) self.add(self.coordinate_labels) return self
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/number_line.py
manimlib/mobject/number_line.py
from __future__ import annotations import numpy as np from manimlib.constants import DOWN, LEFT, RIGHT, UP from manimlib.constants import DEFAULT_LIGHT_COLOR from manimlib.constants import MED_SMALL_BUFF, SMALL_BUFF from manimlib.constants import YELLOW, DEG from manimlib.mobject.geometry import Line, ArrowTip from manimlib.mobject.numbers import DecimalNumber from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.value_tracker import ValueTracker from manimlib.utils.bezier import interpolate from manimlib.utils.bezier import outer_interpolate from manimlib.utils.dict_ops import merge_dicts_recursively from manimlib.utils.simple_functions import fdiv from manimlib.utils.space_ops import rotate_vector, angle_of_vector from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable, Optional, Tuple, Dict, Any from manimlib.typing import ManimColor, Vect3, Vect3Array, VectN, RangeSpecifier class NumberLine(Line): def __init__( self, x_range: RangeSpecifier = (-8, 8, 1), color: ManimColor = DEFAULT_LIGHT_COLOR, stroke_width: float = 2.0, # How big is one one unit of this number line in terms of absolute spacial distance unit_size: float = 1.0, width: Optional[float] = None, include_ticks: bool = True, tick_size: float = 0.1, longer_tick_multiple: float = 1.5, tick_offset: float = 0.0, # Change name big_tick_spacing: Optional[float] = None, big_tick_numbers: list[float] = [], include_numbers: bool = False, line_to_number_direction: Vect3 = DOWN, line_to_number_buff: float = MED_SMALL_BUFF, include_tip: bool = False, tip_config: dict = dict( width=0.25, length=0.25, ), decimal_number_config: dict = dict( num_decimal_places=0, font_size=36, ), numbers_to_exclude: list | None = None, **kwargs, ): self.x_range = x_range self.tick_size = tick_size self.longer_tick_multiple = longer_tick_multiple self.tick_offset = tick_offset if big_tick_spacing is not None: self.big_tick_numbers = np.arange( x_range[0], x_range[1] + big_tick_spacing, big_tick_spacing, ) else: self.big_tick_numbers = list(big_tick_numbers) self.line_to_number_direction = line_to_number_direction self.line_to_number_buff = line_to_number_buff self.include_tip = include_tip self.tip_config = dict(tip_config) self.decimal_number_config = dict(decimal_number_config) self.numbers_to_exclude = numbers_to_exclude self.x_min, self.x_max = x_range[:2] self.x_step = 1 if len(x_range) == 2 else x_range[2] super().__init__( self.x_min * RIGHT, self.x_max * RIGHT, color=color, stroke_width=stroke_width, **kwargs ) if width: self.set_width(width) else: self.scale(unit_size) self.center() if include_tip: self.add_tip() self.tip.set_stroke( self.stroke_color, self.stroke_width, ) if include_ticks: self.add_ticks() if include_numbers: self.add_numbers(excluding=self.numbers_to_exclude) def get_tick_range(self) -> np.ndarray: if self.include_tip: x_max = self.x_max else: x_max = self.x_max + self.x_step result = np.arange(self.x_min, x_max, self.x_step) return result[result <= self.x_max] def add_ticks(self) -> None: ticks = VGroup() for x in self.get_tick_range(): size = self.tick_size if np.isclose(self.big_tick_numbers, x).any(): size *= self.longer_tick_multiple ticks.add(self.get_tick(x, size)) self.add(ticks) self.ticks = ticks def get_tick(self, x: float, size: float | None = None) -> Line: if size is None: size = self.tick_size result = Line(size * DOWN, size * UP) result.rotate(self.get_angle()) result.move_to(self.number_to_point(x)) result.match_style(self) return result def get_tick_marks(self) -> VGroup: return self.ticks def number_to_point(self, number: float | VectN) -> Vect3 | Vect3Array: start = self.get_points()[0] end = self.get_points()[-1] alpha = (number - self.x_min) / (self.x_max - self.x_min) return outer_interpolate(start, end, alpha) def point_to_number(self, point: Vect3 | Vect3Array) -> float | VectN: start = self.get_points()[0] end = self.get_points()[-1] vect = end - start proportion = fdiv( np.dot(point - start, vect), np.dot(end - start, vect), ) return interpolate(self.x_min, self.x_max, proportion) def n2p(self, number: float | VectN) -> Vect3 | Vect3Array: """Abbreviation for number_to_point""" return self.number_to_point(number) def p2n(self, point: Vect3 | Vect3Array) -> float | VectN: """Abbreviation for point_to_number""" return self.point_to_number(point) def get_unit_size(self) -> float: return self.get_length() / (self.x_max - self.x_min) def get_number_mobject( self, x: float, direction: Vect3 | None = None, buff: float | None = None, unit: float = 1.0, unit_tex: str = "", **number_config ) -> DecimalNumber: number_config = merge_dicts_recursively( self.decimal_number_config, number_config, ) if direction is None: direction = self.line_to_number_direction if buff is None: buff = self.line_to_number_buff if unit_tex: number_config["unit"] = unit_tex num_mob = DecimalNumber(x / unit, **number_config) num_mob.next_to( self.number_to_point(x), direction=direction, buff=buff ) if x < 0 and direction[0] == 0: # Align without the minus sign num_mob.shift(num_mob[0].get_width() * LEFT / 2) if abs(x) == unit and unit_tex: center = num_mob.get_center() if x > 0: num_mob.remove(num_mob[0]) else: num_mob.remove(num_mob[1]) num_mob[0].next_to(num_mob[1], LEFT, buff=num_mob[0].get_width() / 4) num_mob.move_to(center) return num_mob def add_numbers( self, x_values: Iterable[float] | None = None, excluding: Iterable[float] | None = None, font_size: int = 24, **kwargs ) -> VGroup: if x_values is None: x_values = self.get_tick_range() kwargs["font_size"] = font_size if excluding is None: excluding = self.numbers_to_exclude numbers = VGroup() for x in x_values: if excluding is not None and x in excluding: continue numbers.add(self.get_number_mobject(x, **kwargs)) self.add(numbers) self.numbers = numbers return numbers class UnitInterval(NumberLine): def __init__( self, x_range: RangeSpecifier = (0, 1, 0.1), unit_size: float = 10, big_tick_numbers: list[float] = [0, 1], decimal_number_config: dict = dict( num_decimal_places=1, ), **kwargs ): super().__init__( x_range=x_range, unit_size=unit_size, big_tick_numbers=big_tick_numbers, decimal_number_config=decimal_number_config, **kwargs ) class Slider(VGroup): def __init__( self, value_tracker: ValueTracker, x_range: Tuple[float, float] = (-5, 5), var_name: Optional[str] = None, width: float = 3, unit_size: float = 1, arrow_width: float = 0.15, arrow_length: float = 0.15, arrow_color: ManimColor = YELLOW, font_size: int = 24, label_buff: float = SMALL_BUFF, num_decimal_places: int = 2, tick_size: float = 0.05, number_line_config: Dict[str, Any] = dict(), arrow_tip_config: Dict[str, Any] = dict(), decimal_config: Dict[str, Any] = dict(), angle: float = 0, label_direction: Optional[np.ndarray] = None, add_tick_labels: bool = True, tick_label_font_size: int = 16, ): get_value = value_tracker.get_value if label_direction is None: label_direction = np.round(rotate_vector(UP, angle), 2) # Initialize number line number_line_kw = dict(x_range=x_range, width=width, tick_size=tick_size) number_line_kw.update(number_line_config) number_line = NumberLine(**number_line_kw) number_line.rotate(angle) if add_tick_labels: number_line.add_numbers( font_size=tick_label_font_size, buff=2 * tick_size, direction=-label_direction ) # Initialize arrow tip arrow_tip_kw = dict( width=arrow_width, length=arrow_length, fill_color=arrow_color, angle=-180 * DEG + angle_of_vector(label_direction), ) arrow_tip_kw.update(arrow_tip_config) tip = ArrowTip(**arrow_tip_kw) tip.add_updater(lambda m: m.move_to(number_line.n2p(get_value()), -label_direction)) # Initialize label dec_string = f"{{:.{num_decimal_places}f}}".format(0) lhs = f"{var_name} = " if var_name is not None else "" label = Tex(lhs + dec_string, font_size=font_size) label[var_name].set_fill(arrow_color) decimal = label.make_number_changeable(dec_string) decimal.add_updater(lambda m: m.set_value(get_value())) label.add_updater(lambda m: m.next_to(tip, label_direction, label_buff)) # Assemble group super().__init__(number_line, tip, label) self.set_stroke(behind=True)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/shape_matchers.py
manimlib/mobject/shape_matchers.py
from __future__ import annotations from colour import Color from manimlib.config import manim_config from manimlib.constants import BLACK, RED, YELLOW, DEFAULT_MOBJECT_COLOR from manimlib.constants import DL, DOWN, DR, LEFT, RIGHT, UL, UR from manimlib.constants import SMALL_BUFF from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence from manimlib.mobject.mobject import Mobject from manimlib.typing import ManimColor, Self class SurroundingRectangle(Rectangle): def __init__( self, mobject: Mobject, buff: float = SMALL_BUFF, color: ManimColor = YELLOW, **kwargs ): super().__init__(color=color, **kwargs) self.buff = buff self.surround(mobject) if mobject.is_fixed_in_frame(): self.fix_in_frame() def surround(self, mobject, buff=None) -> Self: self.mobject = mobject self.buff = buff if buff is not None else self.buff super().surround(mobject, self.buff) return self def set_buff(self, buff) -> Self: self.buff = buff self.surround(self.mobject) return self class BackgroundRectangle(SurroundingRectangle): def __init__( self, mobject: Mobject, color: ManimColor = None, stroke_width: float = 0, stroke_opacity: float = 0, fill_opacity: float = 0.75, buff: float = 0, **kwargs ): if color is None: color = manim_config.camera.background_color super().__init__( mobject, color=color, stroke_width=stroke_width, stroke_opacity=stroke_opacity, fill_opacity=fill_opacity, buff=buff, **kwargs ) self.original_fill_opacity = fill_opacity def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self: self.set_fill(opacity=b * self.original_fill_opacity) return self def set_style( self, stroke_color: ManimColor | None = None, stroke_width: float | None = None, fill_color: ManimColor | None = None, fill_opacity: float | None = None, family: bool = True, **kwargs ) -> Self: # Unchangeable style, except for fill_opacity VMobject.set_style( self, stroke_color=BLACK, stroke_width=0, fill_color=BLACK, fill_opacity=fill_opacity ) return self def get_fill_color(self) -> Color: return Color(self.color) class Cross(VGroup): def __init__( self, mobject: Mobject, stroke_color: ManimColor = RED, stroke_width: float | Sequence[float] = [0, 6, 0], **kwargs ): super().__init__( Line(UL, DR), Line(UR, DL), ) self.insert_n_curves(20) self.replace(mobject, stretch=True) self.set_stroke(stroke_color, width=stroke_width) class Underline(Line): def __init__( self, mobject: Mobject, buff: float = SMALL_BUFF, stroke_color=DEFAULT_MOBJECT_COLOR, stroke_width: float | Sequence[float] = [0, 3, 3, 0], stretch_factor=1.2, **kwargs ): super().__init__(LEFT, RIGHT, **kwargs) if not isinstance(stroke_width, (float, int)): self.insert_n_curves(len(stroke_width) - 2) self.set_stroke(stroke_color, stroke_width) self.set_width(mobject.get_width() * stretch_factor) self.next_to(mobject, DOWN, buff=buff)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/three_dimensions.py
manimlib/mobject/three_dimensions.py
from __future__ import annotations import math import numpy as np from manimlib.constants import BLUE, BLUE_D, BLUE_E, GREY_A, BLACK from manimlib.constants import IN, ORIGIN, OUT, RIGHT from manimlib.constants import PI, TAU from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.surface import SGroup from manimlib.mobject.types.surface import Surface from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.geometry import Polygon from manimlib.mobject.geometry import Square from manimlib.utils.bezier import interpolate from manimlib.utils.iterables import adjacent_pairs from manimlib.utils.space_ops import compass_directions from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import z_to_vector from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Tuple, TypeVar from manimlib.typing import ManimColor, Vect3, Sequence T = TypeVar("T", bound=Mobject) class SurfaceMesh(VGroup): def __init__( self, uv_surface: Surface, resolution: Tuple[int, int] = (21, 11), stroke_width: float = 1, stroke_color: ManimColor = GREY_A, normal_nudge: float = 1e-2, depth_test: bool = True, joint_type: str = 'no_joint', **kwargs ): self.uv_surface = uv_surface self.resolution = resolution self.normal_nudge = normal_nudge super().__init__( stroke_color=stroke_color, stroke_width=stroke_width, depth_test=depth_test, joint_type=joint_type, **kwargs ) def init_points(self) -> None: uv_surface = self.uv_surface full_nu, full_nv = uv_surface.resolution part_nu, part_nv = self.resolution # 'indices' are treated as floats. Later, there will be # an interpolation between the floor and ceiling of these # indices u_indices = np.linspace(0, full_nu - 1, part_nu) v_indices = np.linspace(0, full_nv - 1, part_nv) points = uv_surface.get_points() normals = uv_surface.get_unit_normals() nudge = self.normal_nudge nudged_points = points + nudge * normals for ui in u_indices: path = VMobject() low_ui = full_nv * int(math.floor(ui)) high_ui = full_nv * int(math.ceil(ui)) path.set_points_smoothly(interpolate( nudged_points[low_ui:low_ui + full_nv], nudged_points[high_ui:high_ui + full_nv], ui % 1 )) self.add(path) for vi in v_indices: path = VMobject() path.set_points_smoothly(interpolate( nudged_points[int(math.floor(vi))::full_nv], nudged_points[int(math.ceil(vi))::full_nv], vi % 1 )) self.add(path) # 3D shapes class Sphere(Surface): def __init__( self, u_range: Tuple[float, float] = (0, TAU), v_range: Tuple[float, float] = (0, PI), resolution: Tuple[int, int] = (101, 51), radius: float = 1.0, true_normals: bool = True, clockwise=False, **kwargs, ): self.radius = radius self.clockwise = clockwise super().__init__( u_range=u_range, v_range=v_range, resolution=resolution, **kwargs ) # Add bespoke normal specification to avoid issue at poles if true_normals: self.data['d_normal_point'] = self.data['point'] * ((radius + self.normal_nudge) / radius) def uv_func(self, u: float, v: float) -> np.ndarray: sign = -1 if self.clockwise else +1 return self.radius * np.array([ math.cos(sign * u) * math.sin(v), math.sin(sign * u) * math.sin(v), -math.cos(v) ]) class Torus(Surface): def __init__( self, u_range: Tuple[float, float] = (0, TAU), v_range: Tuple[float, float] = (0, TAU), r1: float = 3.0, r2: float = 1.0, **kwargs, ): self.r1 = r1 self.r2 = r2 super().__init__( u_range=u_range, v_range=v_range, **kwargs, ) def uv_func(self, u: float, v: float) -> np.ndarray: P = np.array([math.cos(u), math.sin(u), 0]) return (self.r1 - self.r2 * math.cos(v)) * P - self.r2 * math.sin(v) * OUT class Cylinder(Surface): def __init__( self, u_range: Tuple[float, float] = (0, TAU), v_range: Tuple[float, float] = (-1, 1), resolution: Tuple[int, int] = (101, 11), height: float = 2, radius: float = 1, axis: Vect3 = OUT, **kwargs, ): self.height = height self.radius = radius self.axis = axis super().__init__( u_range=u_range, v_range=v_range, resolution=resolution, **kwargs ) def init_points(self): super().init_points() self.scale(self.radius) self.set_depth(self.height, stretch=True) self.apply_matrix(z_to_vector(self.axis)) def uv_func(self, u: float, v: float) -> np.ndarray: return np.array([np.cos(u), np.sin(u), v]) class Cone(Cylinder): def __init__( self, u_range: Tuple[float, float] = (0, TAU), v_range: Tuple[float, float] = (0, 1), *args, **kwargs, ): super().__init__(u_range=u_range, v_range=v_range, *args, **kwargs) def uv_func(self, u: float, v: float) -> np.ndarray: return np.array([(1 - v) * np.cos(u), (1 - v) * np.sin(u), v]) class Line3D(Cylinder): def __init__( self, start: Vect3, end: Vect3, width: float = 0.05, resolution: Tuple[int, int] = (21, 25), **kwargs ): axis = end - start super().__init__( height=get_norm(axis), radius=width / 2, axis=axis, resolution=resolution, **kwargs ) self.shift((start + end) / 2) class Disk3D(Surface): def __init__( self, radius: float = 1, u_range: Tuple[float, float] = (0, 1), v_range: Tuple[float, float] = (0, TAU), resolution: Tuple[int, int] = (2, 100), **kwargs ): super().__init__( u_range=u_range, v_range=v_range, resolution=resolution, **kwargs, ) self.scale(radius) def uv_func(self, u: float, v: float) -> np.ndarray: return np.array([ u * math.cos(v), u * math.sin(v), 0 ]) class Square3D(Surface): def __init__( self, side_length: float = 2.0, u_range: Tuple[float, float] = (-1, 1), v_range: Tuple[float, float] = (-1, 1), resolution: Tuple[int, int] = (2, 2), **kwargs, ): super().__init__( u_range=u_range, v_range=v_range, resolution=resolution, **kwargs ) self.scale(side_length / 2) def uv_func(self, u: float, v: float) -> np.ndarray: return np.array([u, v, 0]) def square_to_cube_faces(square: T) -> list[T]: radius = square.get_height() / 2 square.move_to(radius * OUT) result = [square.copy()] result.extend([ square.copy().rotate(PI / 2, axis=vect, about_point=ORIGIN) for vect in compass_directions(4) ]) result.append(square.copy().rotate(PI, RIGHT, about_point=ORIGIN)) return result class Cube(SGroup): def __init__( self, color: ManimColor = BLUE, opacity: float = 1, shading: Tuple[float, float, float] = (0.1, 0.5, 0.1), square_resolution: Tuple[int, int] = (2, 2), side_length: float = 2, **kwargs, ): face = Square3D( resolution=square_resolution, side_length=side_length, color=color, opacity=opacity, shading=shading, ) super().__init__(*square_to_cube_faces(face), **kwargs) class Prism(Cube): def __init__( self, width: float = 3.0, height: float = 2.0, depth: float = 1.0, **kwargs ): super().__init__(**kwargs) for dim, value in enumerate([width, height, depth]): self.rescale_to_fit(value, dim, stretch=True) class VGroup3D(VGroup): def __init__( self, *vmobjects: VMobject, depth_test: bool = True, shading: Tuple[float, float, float] = (0.2, 0.2, 0.2), joint_type: str = "no_joint", **kwargs ): super().__init__(*vmobjects, **kwargs) self.set_shading(*shading) self.set_joint_type(joint_type) if depth_test: self.apply_depth_test() class VCube(VGroup3D): def __init__( self, side_length: float = 2.0, fill_color: ManimColor = BLUE_D, fill_opacity: float = 1, stroke_width: float = 0, **kwargs ): style = dict( fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs ) face = Square(side_length=side_length, **style) super().__init__(*square_to_cube_faces(face), **style) class VPrism(VCube): def __init__( self, width: float = 3.0, height: float = 2.0, depth: float = 1.0, **kwargs ): super().__init__(**kwargs) for dim, value in enumerate([width, height, depth]): self.rescale_to_fit(value, dim, stretch=True) class Dodecahedron(VGroup3D): def __init__( self, fill_color: ManimColor = BLUE_E, fill_opacity: float = 1, stroke_color: ManimColor = BLUE_E, stroke_width: float = 1, shading: Tuple[float, float, float] = (0.2, 0.2, 0.2), **kwargs, ): style = dict( fill_color=fill_color, fill_opacity=fill_opacity, stroke_color=stroke_color, stroke_width=stroke_width, shading=shading, **kwargs ) # Start by creating two of the pentagons, meeting # back to back on the positive x-axis phi = (1 + math.sqrt(5)) / 2 x, y, z = np.identity(3) pentagon1 = Polygon( np.array([phi, 1 / phi, 0]), np.array([1, 1, 1]), np.array([1 / phi, 0, phi]), np.array([1, -1, 1]), np.array([phi, -1 / phi, 0]), **style ) pentagon2 = pentagon1.copy().stretch(-1, 2, about_point=ORIGIN) pentagon2.reverse_points() x_pair = VGroup(pentagon1, pentagon2) z_pair = x_pair.copy().apply_matrix(np.array([z, -x, -y]).T) y_pair = x_pair.copy().apply_matrix(np.array([y, z, x]).T) pentagons = [*x_pair, *y_pair, *z_pair] for pentagon in list(pentagons): pc = pentagon.copy() pc.apply_function(lambda p: -p) pc.reverse_points() pentagons.append(pc) super().__init__(*pentagons, **style) class Prismify(VGroup3D): def __init__(self, vmobject, depth=1.0, direction=IN, **kwargs): # At the moment, this assume stright edges vect = depth * direction pieces = [vmobject.copy()] points = vmobject.get_anchors() for p1, p2 in adjacent_pairs(points): wall = VMobject() wall.match_style(vmobject) wall.set_points_as_corners([p1, p2, p2 + vect, p1 + vect]) pieces.append(wall) top = vmobject.copy() top.shift(vect) top.reverse_points() pieces.append(top) super().__init__(*pieces, **kwargs)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/interactive.py
manimlib/mobject/interactive.py
from __future__ import annotations import numpy as np from pyglet.window import key as PygletWindowKeys from manimlib.constants import FRAME_HEIGHT, FRAME_WIDTH from manimlib.constants import DOWN, LEFT, ORIGIN, RIGHT, UP from manimlib.constants import MED_LARGE_BUFF, MED_SMALL_BUFF, SMALL_BUFF from manimlib.constants import BLACK, BLUE, GREEN, GREY_A, GREY_C, RED, WHITE, DEFAULT_MOBJECT_COLOR from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Mobject from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Dot from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import RoundedRectangle from manimlib.mobject.geometry import Square from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.value_tracker import ValueTracker from manimlib.utils.color import rgb_to_hex from manimlib.utils.space_ops import get_closest_point_on_line from manimlib.utils.space_ops import get_norm from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import ManimColor # Interactive Mobjects class MotionMobject(Mobject): """ You could hold and drag this object to any position """ def __init__(self, mobject: Mobject, **kwargs): super().__init__(**kwargs) assert isinstance(mobject, Mobject) self.mobject = mobject self.mobject.add_mouse_drag_listner(self.mob_on_mouse_drag) # To avoid locking it as static mobject self.mobject.add_updater(lambda mob: None) self.add(mobject) def mob_on_mouse_drag(self, mob: Mobject, event_data: dict[str, np.ndarray]) -> bool: mob.move_to(event_data["point"]) return False class Button(Mobject): """ Pass any mobject and register an on_click method The on_click method takes mobject as argument like updater """ def __init__(self, mobject: Mobject, on_click: Callable[[Mobject]], **kwargs): super().__init__(**kwargs) assert isinstance(mobject, Mobject) self.on_click = on_click self.mobject = mobject self.mobject.add_mouse_press_listner(self.mob_on_mouse_press) self.add(self.mobject) def mob_on_mouse_press(self, mob: Mobject, event_data) -> bool: self.on_click(mob) return False # Controls class ControlMobject(ValueTracker): def __init__(self, value: float, *mobjects: Mobject, **kwargs): super().__init__(value=value, **kwargs) self.add(*mobjects) # To avoid lock_static_mobject_data while waiting in scene self.add_updater(lambda mob: None) self.fix_in_frame() def set_value(self, value: float): self.assert_value(value) self.set_value_anim(value) return ValueTracker.set_value(self, value) def assert_value(self, value): # To be implemented in subclasses pass def set_value_anim(self, value): # To be implemented in subclasses pass class EnableDisableButton(ControlMobject): def __init__( self, value: bool = True, value_type: np.dtype = np.dtype(bool), rect_kwargs: dict = { "width": 0.5, "height": 0.5, "fill_opacity": 1.0 }, enable_color: ManimColor = GREEN, disable_color: ManimColor = RED, **kwargs ): self.value = value self.value_type = value_type self.rect_kwargs = rect_kwargs self.enable_color = enable_color self.disable_color = disable_color self.box = Rectangle(**self.rect_kwargs) super().__init__(value, self.box, **kwargs) self.add_mouse_press_listner(self.on_mouse_press) def assert_value(self, value: bool) -> None: assert isinstance(value, bool) def set_value_anim(self, value: bool) -> None: if value: self.box.set_fill(self.enable_color) else: self.box.set_fill(self.disable_color) def toggle_value(self) -> None: super().set_value(not self.get_value()) def on_mouse_press(self, mob: Mobject, event_data) -> bool: mob.toggle_value() return False class Checkbox(ControlMobject): def __init__( self, value: bool = True, value_type: np.dtype = np.dtype(bool), rect_kwargs: dict = { "width": 0.5, "height": 0.5, "fill_opacity": 0.0 }, checkmark_kwargs: dict = { "stroke_color": GREEN, "stroke_width": 6, }, cross_kwargs: dict = { "stroke_color": RED, "stroke_width": 6, }, box_content_buff: float = SMALL_BUFF, **kwargs ): self.value_type = value_type self.rect_kwargs = rect_kwargs self.checkmark_kwargs = checkmark_kwargs self.cross_kwargs = cross_kwargs self.box_content_buff = box_content_buff self.box = Rectangle(**self.rect_kwargs) self.box_content = self.get_checkmark() if value else self.get_cross() super().__init__(value, self.box, self.box_content, **kwargs) self.add_mouse_press_listner(self.on_mouse_press) def assert_value(self, value: bool) -> None: assert isinstance(value, bool) def toggle_value(self) -> None: super().set_value(not self.get_value()) def set_value_anim(self, value: bool) -> None: if value: self.box_content.become(self.get_checkmark()) else: self.box_content.become(self.get_cross()) def on_mouse_press(self, mob: Mobject, event_data) -> None: mob.toggle_value() return False # Helper methods def get_checkmark(self) -> VGroup: checkmark = VGroup( Line(UP / 2 + 2 * LEFT, DOWN + LEFT, **self.checkmark_kwargs), Line(DOWN + LEFT, UP + RIGHT, **self.checkmark_kwargs) ) checkmark.stretch_to_fit_width(self.box.get_width()) checkmark.stretch_to_fit_height(self.box.get_height()) checkmark.scale(0.5) checkmark.move_to(self.box) return checkmark def get_cross(self) -> VGroup: cross = VGroup( Line(UP + LEFT, DOWN + RIGHT, **self.cross_kwargs), Line(UP + RIGHT, DOWN + LEFT, **self.cross_kwargs) ) cross.stretch_to_fit_width(self.box.get_width()) cross.stretch_to_fit_height(self.box.get_height()) cross.scale(0.5) cross.move_to(self.box) return cross class LinearNumberSlider(ControlMobject): def __init__( self, value: float = 0, value_type: type = np.float64, min_value: float = -10.0, max_value: float = 10.0, step: float = 1.0, rounded_rect_kwargs: dict = { "height": 0.075, "width": 2, "corner_radius": 0.0375 }, circle_kwargs: dict = { "radius": 0.1, "stroke_color": GREY_A, "fill_color": GREY_A, "fill_opacity": 1.0 }, **kwargs ): self.value_type = value_type self.min_value = min_value self.max_value = max_value self.step = step self.rounded_rect_kwargs = rounded_rect_kwargs self.circle_kwargs = circle_kwargs self.bar = RoundedRectangle(**self.rounded_rect_kwargs) self.slider = Circle(**self.circle_kwargs) self.slider_axis = Line( start=self.bar.get_bounding_box_point(LEFT), end=self.bar.get_bounding_box_point(RIGHT) ) self.slider_axis.set_opacity(0.0) self.slider.move_to(self.slider_axis) self.slider.add_mouse_drag_listner(self.slider_on_mouse_drag) super().__init__(value, self.bar, self.slider, self.slider_axis, **kwargs) def assert_value(self, value: float) -> None: assert self.min_value <= value <= self.max_value def set_value_anim(self, value: float) -> None: prop = (value - self.min_value) / (self.max_value - self.min_value) self.slider.move_to(self.slider_axis.point_from_proportion(prop)) def slider_on_mouse_drag(self, mob, event_data: dict[str, np.ndarray]) -> bool: self.set_value(self.get_value_from_point(event_data["point"])) return False # Helper Methods def get_value_from_point(self, point: np.ndarray) -> float: start, end = self.slider_axis.get_start_and_end() point_on_line = get_closest_point_on_line(start, end, point) prop = get_norm(point_on_line - start) / get_norm(end - start) value = self.min_value + prop * (self.max_value - self.min_value) no_of_steps = int((value - self.min_value) / self.step) value_nearest_to_step = self.min_value + no_of_steps * self.step return value_nearest_to_step class ColorSliders(Group): def __init__( self, sliders_kwargs: dict = {}, rect_kwargs: dict = { "width": 2.0, "height": 0.5, "stroke_opacity": 1.0 }, background_grid_kwargs: dict = { "colors": [GREY_A, GREY_C], "single_square_len": 0.1 }, sliders_buff: float = MED_LARGE_BUFF, default_rgb_value: int = 255, default_a_value: int = 1, **kwargs ): self.sliders_kwargs = sliders_kwargs self.rect_kwargs = rect_kwargs self.background_grid_kwargs = background_grid_kwargs self.sliders_buff = sliders_buff self.default_rgb_value = default_rgb_value self.default_a_value = default_a_value rgb_kwargs = {"value": self.default_rgb_value, "min_value": 0, "max_value": 255, "step": 1} a_kwargs = {"value": self.default_a_value, "min_value": 0, "max_value": 1, "step": 0.04} self.r_slider = LinearNumberSlider(**self.sliders_kwargs, **rgb_kwargs) self.g_slider = LinearNumberSlider(**self.sliders_kwargs, **rgb_kwargs) self.b_slider = LinearNumberSlider(**self.sliders_kwargs, **rgb_kwargs) self.a_slider = LinearNumberSlider(**self.sliders_kwargs, **a_kwargs) self.sliders = Group( self.r_slider, self.g_slider, self.b_slider, self.a_slider ) self.sliders.arrange(DOWN, buff=self.sliders_buff) self.r_slider.slider.set_color(RED) self.g_slider.slider.set_color(GREEN) self.b_slider.slider.set_color(BLUE) self.a_slider.slider.set_color_by_gradient(BLACK, WHITE) self.selected_color_box = Rectangle(**self.rect_kwargs) self.selected_color_box.add_updater( lambda mob: mob.set_fill( self.get_picked_color(), self.get_picked_opacity() ) ) self.background = self.get_background() super().__init__( Group(self.background, self.selected_color_box).fix_in_frame(), self.sliders, **kwargs ) self.arrange(DOWN) def get_background(self) -> VGroup: single_square_len = self.background_grid_kwargs["single_square_len"] colors = self.background_grid_kwargs["colors"] width = self.rect_kwargs["width"] height = self.rect_kwargs["height"] rows = int(height / single_square_len) cols = int(width / single_square_len) cols = (cols + 1) if (cols % 2 == 0) else cols single_square = Square(single_square_len) grid = single_square.get_grid(n_rows=rows, n_cols=cols, buff=0.0) grid.stretch_to_fit_width(width) grid.stretch_to_fit_height(height) grid.move_to(self.selected_color_box) for idx, square in enumerate(grid): assert isinstance(square, Square) square.set_stroke(width=0.0, opacity=0.0) square.set_fill(colors[idx % len(colors)], 1.0) return grid def set_value(self, r: float, g: float, b: float, a: float): self.r_slider.set_value(r) self.g_slider.set_value(g) self.b_slider.set_value(b) self.a_slider.set_value(a) def get_value(self) -> np.ndarary: r = self.r_slider.get_value() / 255 g = self.g_slider.get_value() / 255 b = self.b_slider.get_value() / 255 alpha = self.a_slider.get_value() return np.array((r, g, b, alpha)) def get_picked_color(self) -> str: rgba = self.get_value() return rgb_to_hex(rgba[:3]) def get_picked_opacity(self) -> float: rgba = self.get_value() return rgba[3] class Textbox(ControlMobject): def __init__( self, value: str = "", value_type: np.dtype = np.dtype(object), box_kwargs: dict = { "width": 2.0, "height": 1.0, "fill_color": DEFAULT_MOBJECT_COLOR, "fill_opacity": 1.0, }, text_kwargs: dict = { "color": BLUE }, text_buff: float = MED_SMALL_BUFF, isInitiallyActive: bool = False, active_color: ManimColor = BLUE, deactive_color: ManimColor = RED, **kwargs ): self.value_type = value_type self.box_kwargs = box_kwargs self.text_kwargs = text_kwargs self.text_buff = text_buff self.isInitiallyActive = isInitiallyActive self.active_color = active_color self.deactive_color = deactive_color self.isActive = self.isInitiallyActive self.box = Rectangle(**self.box_kwargs) self.box.add_mouse_press_listner(self.box_on_mouse_press) self.text = Text(value, **self.text_kwargs) super().__init__(value, self.box, self.text, **kwargs) self.update_text(value) self.active_anim(self.isActive) self.add_key_press_listner(self.on_key_press) def set_value_anim(self, value: str) -> None: self.update_text(value) def update_text(self, value: str) -> None: text = self.text self.remove(text) text.__init__(value, **self.text_kwargs) height = text.get_height() text.set_width(self.box.get_width() - 2 * self.text_buff) if text.get_height() > height: text.set_height(height) text.add_updater(lambda mob: mob.move_to(self.box)) text.fix_in_frame() self.add(text) def active_anim(self, isActive: bool) -> None: if isActive: self.box.set_stroke(self.active_color) else: self.box.set_stroke(self.deactive_color) def box_on_mouse_press(self, mob, event_data) -> bool: self.isActive = not self.isActive self.active_anim(self.isActive) return False def on_key_press(self, mob: Mobject, event_data: dict[str, int]) -> bool | None: symbol = event_data["symbol"] modifiers = event_data["modifiers"] char = chr(symbol) if mob.isActive: old_value = mob.get_value() new_value = old_value if char.isalnum(): if (modifiers & PygletWindowKeys.MOD_SHIFT) or (modifiers & PygletWindowKeys.MOD_CAPSLOCK): new_value = old_value + char.upper() else: new_value = old_value + char.lower() elif symbol in [PygletWindowKeys.SPACE]: new_value = old_value + char elif symbol == PygletWindowKeys.TAB: new_value = old_value + '\t' elif symbol == PygletWindowKeys.BACKSPACE: new_value = old_value[:-1] or '' mob.set_value(new_value) return False class ControlPanel(Group): def __init__( self, *controls: ControlMobject, panel_kwargs: dict = { "width": FRAME_WIDTH / 4, "height": MED_SMALL_BUFF + FRAME_HEIGHT, "fill_color": GREY_C, "fill_opacity": 1.0, "stroke_width": 0.0 }, opener_kwargs: dict = { "width": FRAME_WIDTH / 8, "height": 0.5, "fill_color": GREY_C, "fill_opacity": 1.0 }, opener_text_kwargs: dict = { "text": "Control Panel", "font_size": 20 }, **kwargs ): self.panel_kwargs = panel_kwargs self.opener_kwargs = opener_kwargs self.opener_text_kwargs = opener_text_kwargs self.panel = Rectangle(**self.panel_kwargs) self.panel.to_corner(UP + LEFT, buff=0) self.panel.shift(self.panel.get_height() * UP) self.panel.add_mouse_scroll_listner(self.panel_on_mouse_scroll) self.panel_opener_rect = Rectangle(**self.opener_kwargs) self.panel_info_text = Text(**self.opener_text_kwargs) self.panel_info_text.move_to(self.panel_opener_rect) self.panel_opener = Group(self.panel_opener_rect, self.panel_info_text) self.panel_opener.next_to(self.panel, DOWN, aligned_edge=DOWN) self.panel_opener.add_mouse_drag_listner(self.panel_opener_on_mouse_drag) self.controls = Group(*controls) self.controls.arrange(DOWN, center=False, aligned_edge=ORIGIN) self.controls.move_to(self.panel) super().__init__( self.panel, self.panel_opener, self.controls, **kwargs ) self.move_panel_and_controls_to_panel_opener() self.fix_in_frame() def move_panel_and_controls_to_panel_opener(self) -> None: self.panel.next_to( self.panel_opener_rect, direction=UP, buff=0 ) controls_old_x = self.controls.get_x() self.controls.next_to( self.panel_opener_rect, direction=UP, buff=MED_SMALL_BUFF ) self.controls.set_x(controls_old_x) def add_controls(self, *new_controls: ControlMobject) -> None: self.controls.add(*new_controls) self.move_panel_and_controls_to_panel_opener() def remove_controls(self, *controls_to_remove: ControlMobject) -> None: self.controls.remove(*controls_to_remove) self.move_panel_and_controls_to_panel_opener() def open_panel(self): panel_opener_x = self.panel_opener.get_x() self.panel_opener.to_corner(DOWN + LEFT, buff=0.0) self.panel_opener.set_x(panel_opener_x) self.move_panel_and_controls_to_panel_opener() return self def close_panel(self): panel_opener_x = self.panel_opener.get_x() self.panel_opener.to_corner(UP + LEFT, buff=0.0) self.panel_opener.set_x(panel_opener_x) self.move_panel_and_controls_to_panel_opener() return self def panel_opener_on_mouse_drag(self, mob, event_data: dict[str, np.ndarray]) -> bool: point = event_data["point"] self.panel_opener.match_y(Dot(point)) self.move_panel_and_controls_to_panel_opener() return False def panel_on_mouse_scroll(self, mob, event_data: dict[str, np.ndarray]) -> bool: offset = event_data["offset"] factor = 10 * offset[1] self.controls.set_y(self.controls.get_y() + factor) return False
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/__init__.py
manimlib/mobject/__init__.py
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/mobject_update_utils.py
manimlib/mobject/mobject_update_utils.py
from __future__ import annotations import inspect from manimlib.constants import DEG from manimlib.constants import RIGHT from manimlib.mobject.mobject import Mobject from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable import numpy as np from manimlib.animation.animation import Animation def assert_is_mobject_method(method): assert inspect.ismethod(method) mobject = method.__self__ assert isinstance(mobject, Mobject) def always(method, *args, **kwargs): assert_is_mobject_method(method) mobject = method.__self__ func = method.__func__ mobject.add_updater(lambda m: func(m, *args, **kwargs)) return mobject def f_always(method, *arg_generators, **kwargs): """ More functional version of always, where instead of taking in args, it takes in functions which output the relevant arguments. """ assert_is_mobject_method(method) mobject = method.__self__ func = method.__func__ def updater(mob): args = [ arg_generator() for arg_generator in arg_generators ] func(mob, *args, **kwargs) mobject.add_updater(updater) return mobject def always_redraw(func: Callable[..., Mobject], *args, **kwargs) -> Mobject: mob = func(*args, **kwargs) mob.add_updater(lambda m: mob.become(func(*args, **kwargs))) return mob def always_shift( mobject: Mobject, direction: np.ndarray = RIGHT, rate: float = 0.1 ) -> Mobject: mobject.add_updater( lambda m, dt: m.shift(dt * rate * direction) ) return mobject def always_rotate( mobject: Mobject, rate: float = 20 * DEG, **kwargs ) -> Mobject: mobject.add_updater( lambda m, dt: m.rotate(dt * rate, **kwargs) ) return mobject def turn_animation_into_updater( animation: Animation, cycle: bool = False, **kwargs ) -> Mobject: """ Add an updater to the animation's mobject which applies the interpolation and update functions of the animation If cycle is True, this repeats over and over. Otherwise, the updater will be popped uplon completion """ mobject = animation.mobject animation.update_rate_info(**kwargs) animation.suspend_mobject_updating = False animation.begin() animation.total_time = 0 def update(m, dt): run_time = animation.get_run_time() time_ratio = animation.total_time / run_time if cycle: alpha = time_ratio % 1 else: alpha = clip(time_ratio, 0, 1) if alpha >= 1: animation.finish() m.remove_updater(update) return animation.interpolate(alpha) animation.update_mobjects(dt) animation.total_time += dt mobject.add_updater(update) return mobject def cycle_animation(animation: Animation, **kwargs) -> Mobject: return turn_animation_into_updater( animation, cycle=True, **kwargs )
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/value_tracker.py
manimlib/mobject/value_tracker.py
from __future__ import annotations import numpy as np from manimlib.mobject.mobject import Mobject from manimlib.utils.iterables import listify from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import Self class ValueTracker(Mobject): """ Not meant to be displayed. Instead the position encodes some number, often one which another animation or continual_animation uses for its update function, and by treating it as a mobject it can still be animated and manipulated just like anything else. """ value_type: type = np.float64 def __init__( self, value: float | complex | np.ndarray = 0, **kwargs ): self.value = value super().__init__(**kwargs) def init_uniforms(self) -> None: super().init_uniforms() self.uniforms["value"] = np.array( listify(self.value), dtype=self.value_type, ) def get_value(self) -> float | complex | np.ndarray: result = self.uniforms["value"] if len(result) == 1: return result[0] return result def set_value(self, value: float | complex | np.ndarray) -> Self: self.uniforms["value"][:] = value return self def increment_value(self, d_value: float | complex) -> None: self.set_value(self.get_value() + d_value) class ExponentialValueTracker(ValueTracker): """ Operates just like ValueTracker, except it encodes the value as the exponential of a position coordinate, which changes how interpolation behaves """ def get_value(self) -> float | complex: return np.exp(ValueTracker.get_value(self)) def set_value(self, value: float | complex): return ValueTracker.set_value(self, np.log(value)) class ComplexValueTracker(ValueTracker): value_type: type = np.complex128
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/geometry.py
manimlib/mobject/geometry.py
from __future__ import annotations import math import numpy as np from manimlib.constants import DL, DOWN, DR, LEFT, ORIGIN, OUT, RIGHT, UL, UP, UR from manimlib.constants import RED, BLACK, DEFAULT_MOBJECT_COLOR, DEFAULT_LIGHT_COLOR from manimlib.constants import MED_SMALL_BUFF, SMALL_BUFF from manimlib.constants import DEG, PI, TAU from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.vectorized_mobject import DashedVMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import quadratic_bezier_points_for_arc from manimlib.utils.iterables import adjacent_n_tuples from manimlib.utils.iterables import adjacent_pairs from manimlib.utils.simple_functions import clip from manimlib.utils.simple_functions import fdiv from manimlib.utils.space_ops import angle_between_vectors from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import cross2d from manimlib.utils.space_ops import compass_directions from manimlib.utils.space_ops import find_intersection from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import normalize from manimlib.utils.space_ops import rotate_vector from manimlib.utils.space_ops import rotation_matrix_transpose from manimlib.utils.space_ops import rotation_between_vectors from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable, Optional from manimlib.typing import ManimColor, Vect3, Vect3Array, Self DEFAULT_DOT_RADIUS = 0.08 DEFAULT_SMALL_DOT_RADIUS = 0.04 DEFAULT_DASH_LENGTH = 0.05 DEFAULT_ARROW_TIP_LENGTH = 0.35 DEFAULT_ARROW_TIP_WIDTH = 0.35 # Deprecate? class TipableVMobject(VMobject): """ Meant for shared functionality between Arc and Line. Functionality can be classified broadly into these groups: * Adding, Creating, Modifying tips - add_tip calls create_tip, before pushing the new tip into the TipableVMobject's list of submobjects - stylistic and positional configuration * Checking for tips - Boolean checks for whether the TipableVMobject has a tip and a starting tip * Getters - Straightforward accessors, returning information pertaining to the TipableVMobject instance's tip(s), its length etc """ tip_config: dict = dict( fill_opacity=1.0, stroke_width=0.0, tip_style=0.0, # triangle=0, inner_smooth=1, dot=2 ) # Adding, Creating, Modifying tips def add_tip(self, at_start: bool = False, **kwargs) -> Self: """ Adds a tip to the TipableVMobject instance, recognising that the endpoints might need to be switched if it's a 'starting tip' or not. """ tip = self.create_tip(at_start, **kwargs) self.reset_endpoints_based_on_tip(tip, at_start) self.asign_tip_attr(tip, at_start) tip.set_color(self.get_stroke_color()) self.add(tip) return self def create_tip(self, at_start: bool = False, **kwargs) -> ArrowTip: """ Stylises the tip, positions it spacially, and returns the newly instantiated tip to the caller. """ tip = self.get_unpositioned_tip(**kwargs) self.position_tip(tip, at_start) return tip def get_unpositioned_tip(self, **kwargs) -> ArrowTip: """ Returns a tip that has been stylistically configured, but has not yet been given a position in space. """ config = dict() config.update(self.tip_config) config.update(kwargs) return ArrowTip(**config) def position_tip(self, tip: ArrowTip, at_start: bool = False) -> ArrowTip: # Last two control points, defining both # the end, and the tangency direction if at_start: anchor = self.get_start() handle = self.get_first_handle() else: handle = self.get_last_handle() anchor = self.get_end() tip.rotate(angle_of_vector(handle - anchor) - PI - tip.get_angle()) tip.shift(anchor - tip.get_tip_point()) return tip def reset_endpoints_based_on_tip(self, tip: ArrowTip, at_start: bool) -> Self: if self.get_length() == 0: # Zero length, put_start_and_end_on wouldn't # work return self if at_start: start = tip.get_base() end = self.get_end() else: start = self.get_start() end = tip.get_base() self.put_start_and_end_on(start, end) return self def asign_tip_attr(self, tip: ArrowTip, at_start: bool) -> Self: if at_start: self.start_tip = tip else: self.tip = tip return self # Checking for tips def has_tip(self) -> bool: return hasattr(self, "tip") and self.tip in self def has_start_tip(self) -> bool: return hasattr(self, "start_tip") and self.start_tip in self # Getters def pop_tips(self) -> VGroup: start, end = self.get_start_and_end() result = VGroup() if self.has_tip(): result.add(self.tip) self.remove(self.tip) if self.has_start_tip(): result.add(self.start_tip) self.remove(self.start_tip) self.put_start_and_end_on(start, end) return result def get_tips(self) -> VGroup: """ Returns a VGroup (collection of VMobjects) containing the TipableVMObject instance's tips. """ result = VGroup() if hasattr(self, "tip"): result.add(self.tip) if hasattr(self, "start_tip"): result.add(self.start_tip) return result def get_tip(self) -> ArrowTip: """Returns the TipableVMobject instance's (first) tip, otherwise throws an exception.""" tips = self.get_tips() if len(tips) == 0: raise Exception("tip not found") else: return tips[0] def get_default_tip_length(self) -> float: return self.tip_length def get_first_handle(self) -> Vect3: return self.get_points()[1] def get_last_handle(self) -> Vect3: return self.get_points()[-2] def get_end(self) -> Vect3: if self.has_tip(): return self.tip.get_start() else: return VMobject.get_end(self) def get_start(self) -> Vect3: if self.has_start_tip(): return self.start_tip.get_start() else: return VMobject.get_start(self) def get_length(self) -> float: start, end = self.get_start_and_end() return get_norm(start - end) class Arc(TipableVMobject): ''' Creates an arc. Parameters ----- start_angle : float Starting angle of the arc in radians. (Angles are measured counter-clockwise) angle : float Angle subtended by the arc at its center in radians. (Angles are measured counter-clockwise) radius : float Radius of the arc arc_center : array_like Center of the arc Examples : arc = Arc(start_angle=TAU/4, angle=TAU/2, radius=3, arc_center=ORIGIN) arc = Arc(angle=TAU/4, radius=4.5, arc_center=(1,2,0), color=BLUE) Returns ----- out : Arc object An Arc object satisfying the specified parameters ''' def __init__( self, start_angle: float = 0, angle: float = TAU / 4, radius: float = 1.0, n_components: Optional[int] = None, arc_center: Vect3 = ORIGIN, **kwargs ): super().__init__(**kwargs) if n_components is None: # 16 components for a full circle n_components = int(15 * (abs(angle) / TAU)) + 1 self.set_points(quadratic_bezier_points_for_arc(angle, n_components)) self.rotate(start_angle, about_point=ORIGIN) self.scale(radius, about_point=ORIGIN) self.shift(arc_center) def get_arc_center(self) -> Vect3: """ Looks at the normals to the first two anchors, and finds their intersection points """ # First two anchors and handles a1, h, a2 = self.get_points()[:3] # Tangent vectors t1 = h - a1 t2 = h - a2 # Normals n1 = rotate_vector(t1, TAU / 4) n2 = rotate_vector(t2, TAU / 4) return find_intersection(a1, n1, a2, n2) def get_start_angle(self) -> float: angle = angle_of_vector(self.get_start() - self.get_arc_center()) return angle % TAU def get_stop_angle(self) -> float: angle = angle_of_vector(self.get_end() - self.get_arc_center()) return angle % TAU def move_arc_center_to(self, point: Vect3) -> Self: self.shift(point - self.get_arc_center()) return self class ArcBetweenPoints(Arc): ''' Creates an arc passing through the specified points with "angle" as the angle subtended at its center. Parameters ----- start : array_like Starting point of the arc end : array_like Ending point of the arc angle : float Angle subtended by the arc at its center in radians. (Angles are measured counter-clockwise) Examples : arc = ArcBetweenPoints(start=(0, 0, 0), end=(1, 2, 0), angle=TAU / 2) arc = ArcBetweenPoints(start=(-2, 3, 0), end=(1, 2, 0), angle=-TAU / 12, color=BLUE) Returns ----- out : ArcBetweenPoints object An ArcBetweenPoints object satisfying the specified parameters ''' def __init__( self, start: Vect3, end: Vect3, angle: float = TAU / 4, **kwargs ): super().__init__(angle=angle, **kwargs) if angle == 0: self.set_points_as_corners([LEFT, RIGHT]) self.put_start_and_end_on(start, end) class CurvedArrow(ArcBetweenPoints): ''' Creates a curved arrow passing through the specified points with "angle" as the angle subtended at its center. Parameters ----- start_point : array_like Starting point of the curved arrow end_point : array_like Ending point of the curved arrow angle : float Angle subtended by the curved arrow at its center in radians. (Angles are measured counter-clockwise) Examples : curvedArrow = CurvedArrow(start_point=(0, 0, 0), end_point=(1, 2, 0), angle=TAU/2) curvedArrow = CurvedArrow(start_point=(-2, 3, 0), end_point=(1, 2, 0), angle=-TAU/12, color=BLUE) Returns ----- out : CurvedArrow object A CurvedArrow object satisfying the specified parameters ''' def __init__( self, start_point: Vect3, end_point: Vect3, **kwargs ): super().__init__(start_point, end_point, **kwargs) self.add_tip() class CurvedDoubleArrow(CurvedArrow): ''' Creates a curved double arrow passing through the specified points with "angle" as the angle subtended at its center. Parameters ----- start_point : array_like Starting point of the curved double arrow end_point : array_like Ending point of the curved double arrow angle : float Angle subtended by the curved double arrow at its center in radians. (Angles are measured counter-clockwise) Examples : curvedDoubleArrow = CurvedDoubleArrow(start_point = (0, 0, 0), end_point = (1, 2, 0), angle = TAU/2) curvedDoubleArrow = CurvedDoubleArrow(start_point = (-2, 3, 0), end_point = (1, 2, 0), angle = -TAU/12, color = BLUE) Returns ----- out : CurvedDoubleArrow object A CurvedDoubleArrow object satisfying the specified parameters ''' def __init__( self, start_point: Vect3, end_point: Vect3, **kwargs ): super().__init__(start_point, end_point, **kwargs) self.add_tip(at_start=True) class Circle(Arc): ''' Creates a circle. Parameters ----- radius : float Radius of the circle arc_center : array_like Center of the circle Examples : circle = Circle(radius=2, arc_center=(1,2,0)) circle = Circle(radius=3.14, arc_center=2 * LEFT + UP, color=DARK_BLUE) Returns ----- out : Circle object A Circle object satisfying the specified parameters ''' def __init__( self, start_angle: float = 0, stroke_color: ManimColor = RED, **kwargs ): super().__init__( start_angle, TAU, stroke_color=stroke_color, **kwargs ) def surround( self, mobject: Mobject, dim_to_match: int = 0, stretch: bool = False, buff: float = MED_SMALL_BUFF ) -> Self: self.replace(mobject, dim_to_match, stretch) self.stretch((self.get_width() + 2 * buff) / self.get_width(), 0) self.stretch((self.get_height() + 2 * buff) / self.get_height(), 1) return self def point_at_angle(self, angle: float) -> Vect3: start_angle = self.get_start_angle() return self.point_from_proportion( ((angle - start_angle) % TAU) / TAU ) def get_radius(self) -> float: return get_norm(self.get_start() - self.get_center()) class Dot(Circle): ''' Creates a dot. Dot is a filled white circle with no bounary and DEFAULT_DOT_RADIUS. Parameters ----- point : array_like Coordinates of center of the dot. Examples : dot = Dot(point=(1, 2, 0)) Returns ----- out : Dot object A Dot object satisfying the specified parameters ''' def __init__( self, point: Vect3 = ORIGIN, radius: float = DEFAULT_DOT_RADIUS, stroke_color: ManimColor = BLACK, stroke_width: float = 0.0, fill_opacity: float = 1.0, fill_color: ManimColor = DEFAULT_MOBJECT_COLOR, **kwargs ): super().__init__( arc_center=point, radius=radius, stroke_color=stroke_color, stroke_width=stroke_width, fill_opacity=fill_opacity, fill_color=fill_color, **kwargs ) class SmallDot(Dot): ''' Creates a small dot. Small dot is a filled white circle with no bounary and DEFAULT_SMALL_DOT_RADIUS. Parameters ----- point : array_like Coordinates of center of the small dot. Examples : smallDot = SmallDot(point=(1, 2, 0)) Returns ----- out : SmallDot object A SmallDot object satisfying the specified parameters ''' def __init__( self, point: Vect3 = ORIGIN, radius: float = DEFAULT_SMALL_DOT_RADIUS, **kwargs ): super().__init__(point, radius=radius, **kwargs) class Ellipse(Circle): ''' Creates an ellipse. Parameters ----- width : float Width of the ellipse height : float Height of the ellipse arc_center : array_like Coordinates of center of the ellipse Examples : ellipse = Ellipse(width=4, height=1, arc_center=(3, 3, 0)) ellipse = Ellipse(width=2, height=5, arc_center=ORIGIN, color=BLUE) Returns ----- out : Ellipse object An Ellipse object satisfying the specified parameters ''' def __init__( self, width: float = 2.0, height: float = 1.0, **kwargs ): super().__init__(**kwargs) self.set_width(width, stretch=True) self.set_height(height, stretch=True) class AnnularSector(VMobject): ''' Creates an annular sector. Parameters ----- inner_radius : float Inner radius of the annular sector outer_radius : float Outer radius of the annular sector start_angle : float Starting angle of the annular sector (Angles are measured counter-clockwise) angle : float Angle subtended at the center of the annular sector (Angles are measured counter-clockwise) arc_center : array_like Coordinates of center of the annular sector Examples : annularSector = AnnularSector(inner_radius=1, outer_radius=2, angle=TAU/2, start_angle=TAU*3/4, arc_center=(1,-2,0)) Returns ----- out : AnnularSector object An AnnularSector object satisfying the specified parameters ''' def __init__( self, angle: float = TAU / 4, start_angle: float = 0.0, inner_radius: float = 1.0, outer_radius: float = 2.0, arc_center: Vect3 = ORIGIN, fill_color: ManimColor = DEFAULT_LIGHT_COLOR, fill_opacity: float = 1.0, stroke_width: float = 0.0, **kwargs, ): super().__init__( fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs, ) # Initialize points inner_arc, outer_arc = [ Arc( start_angle=start_angle, angle=angle, radius=radius, arc_center=arc_center, ) for radius in (inner_radius, outer_radius) ] self.set_points(inner_arc.get_points()[::-1]) # Reverse self.add_line_to(outer_arc.get_points()[0]) self.add_subpath(outer_arc.get_points()) self.add_line_to(inner_arc.get_points()[-1]) class Sector(AnnularSector): ''' Creates a sector. Parameters ----- outer_radius : float Radius of the sector start_angle : float Starting angle of the sector in radians. (Angles are measured counter-clockwise) angle : float Angle subtended by the sector at its center in radians. (Angles are measured counter-clockwise) arc_center : array_like Coordinates of center of the sector Examples : sector = Sector(outer_radius=1, start_angle=TAU/3, angle=TAU/2, arc_center=[0,3,0]) sector = Sector(outer_radius=3, start_angle=TAU/4, angle=TAU/4, arc_center=ORIGIN, color=PINK) Returns ----- out : Sector object An Sector object satisfying the specified parameters ''' def __init__( self, angle: float = TAU / 4, radius: float = 1.0, **kwargs ): super().__init__( angle, inner_radius=0, outer_radius=radius, **kwargs ) class Annulus(VMobject): ''' Creates an annulus. Parameters ----- inner_radius : float Inner radius of the annulus outer_radius : float Outer radius of the annulus arc_center : array_like Coordinates of center of the annulus Examples : annulus = Annulus(inner_radius=2, outer_radius=3, arc_center=(1, -1, 0)) annulus = Annulus(inner_radius=2, outer_radius=3, stroke_width=20, stroke_color=RED, fill_color=BLUE, arc_center=ORIGIN) Returns ----- out : Annulus object An Annulus object satisfying the specified parameters ''' def __init__( self, inner_radius: float = 1.0, outer_radius: float = 2.0, fill_opacity: float = 1.0, stroke_width: float = 0.0, fill_color: ManimColor = DEFAULT_LIGHT_COLOR, center: Vect3 = ORIGIN, **kwargs, ): super().__init__( fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs, ) self.radius = outer_radius outer_path = outer_radius * quadratic_bezier_points_for_arc(TAU) inner_path = inner_radius * quadratic_bezier_points_for_arc(-TAU) self.add_subpath(outer_path) self.add_subpath(inner_path) self.shift(center) class Line(TipableVMobject): ''' Creates a line joining the points "start" and "end". Parameters ----- start : array_like Starting point of the line end : array_like Ending point of the line Examples : line = Line((0, 0, 0), (3, 0, 0)) line = Line((1, 2, 0), (-2, -3, 0), color=BLUE) Returns ----- out : Line object A Line object satisfying the specified parameters ''' def __init__( self, start: Vect3 | Mobject = LEFT, end: Vect3 | Mobject = RIGHT, buff: float = 0.0, path_arc: float = 0.0, **kwargs ): super().__init__(**kwargs) self.path_arc = path_arc self.buff = buff self.set_start_and_end_attrs(start, end) self.set_points_by_ends(self.start, self.end, buff, path_arc) def set_points_by_ends( self, start: Vect3, end: Vect3, buff: float = 0, path_arc: float = 0 ) -> Self: self.clear_points() self.start_new_path(start) self.add_arc_to(end, path_arc) # Apply buffer if buff > 0: length = self.get_arc_length() alpha = min(buff / length, 0.5) self.pointwise_become_partial(self, alpha, 1 - alpha) return self def set_path_arc(self, new_value: float) -> Self: self.path_arc = new_value self.init_points() return self def set_start_and_end_attrs(self, start: Vect3 | Mobject, end: Vect3 | Mobject): # If either start or end are Mobjects, this # gives their centers rough_start = self.pointify(start) rough_end = self.pointify(end) vect = normalize(rough_end - rough_start) # Now that we know the direction between them, # we can find the appropriate boundary point from # start and end, if they're mobjects self.start = self.pointify(start, vect) self.end = self.pointify(end, -vect) def pointify( self, mob_or_point: Mobject | Vect3, direction: Vect3 | None = None ) -> Vect3: """ Take an argument passed into Line (or subclass) and turn it into a 3d point. """ if isinstance(mob_or_point, Mobject): mob = mob_or_point if direction is None: return mob.get_center() else: return mob.get_continuous_bounding_box_point(direction) else: point = mob_or_point result = np.zeros(self.dim) result[:len(point)] = point return result def put_start_and_end_on(self, start: Vect3, end: Vect3) -> Self: curr_start, curr_end = self.get_start_and_end() if np.isclose(curr_start, curr_end).all(): # Handle null lines more gracefully self.set_points_by_ends(start, end, buff=0, path_arc=self.path_arc) return self return super().put_start_and_end_on(start, end) def get_vector(self) -> Vect3: return self.get_end() - self.get_start() def get_unit_vector(self) -> Vect3: return normalize(self.get_vector()) def get_angle(self) -> float: return angle_of_vector(self.get_vector()) def get_projection(self, point: Vect3) -> Vect3: """ Return projection of a point onto the line """ unit_vect = self.get_unit_vector() start = self.get_start() return start + np.dot(point - start, unit_vect) * unit_vect def get_slope(self) -> float: return np.tan(self.get_angle()) def set_angle(self, angle: float, about_point: Optional[Vect3] = None) -> Self: if about_point is None: about_point = self.get_start() self.rotate( angle - self.get_angle(), about_point=about_point, ) return self def set_length(self, length: float, **kwargs): self.scale(length / self.get_length(), **kwargs) return self def get_arc_length(self) -> float: arc_len = get_norm(self.get_vector()) if self.path_arc > 0: arc_len *= self.path_arc / (2 * math.sin(self.path_arc / 2)) return arc_len class DashedLine(Line): ''' Creates a dashed line joining the points "start" and "end". Parameters ----- start : array_like Starting point of the dashed line end : array_like Ending point of the dashed line dash_length : float length of each dash Examples : line = DashedLine((0, 0, 0), (3, 0, 0)) line = DashedLine((1, 2, 3), (4, 5, 6), dash_length=0.01) Returns ----- out : DashedLine object A DashedLine object satisfying the specified parameters ''' def __init__( self, start: Vect3 = LEFT, end: Vect3 = RIGHT, dash_length: float = DEFAULT_DASH_LENGTH, positive_space_ratio: float = 0.5, **kwargs ): super().__init__(start, end, **kwargs) num_dashes = self.calculate_num_dashes(dash_length, positive_space_ratio) dashes = DashedVMobject( self, num_dashes=num_dashes, positive_space_ratio=positive_space_ratio ) self.clear_points() self.add(*dashes) def calculate_num_dashes(self, dash_length: float, positive_space_ratio: float) -> int: try: full_length = dash_length / positive_space_ratio return int(np.ceil(self.get_length() / full_length)) except ZeroDivisionError: return 1 def get_start(self) -> Vect3: if len(self.submobjects) > 0: return self.submobjects[0].get_start() else: return Line.get_start(self) def get_end(self) -> Vect3: if len(self.submobjects) > 0: return self.submobjects[-1].get_end() else: return Line.get_end(self) def get_start_and_end(self) -> Tuple[Vect3, Vect3]: return self.get_start(), self.get_end() def get_first_handle(self) -> Vect3: return self.submobjects[0].get_points()[1] def get_last_handle(self) -> Vect3: return self.submobjects[-1].get_points()[-2] class TangentLine(Line): ''' Creates a tangent line to the specified vectorized math object. Parameters ----- vmob : VMobject object Vectorized math object which the line will be tangent to alpha : float Point on the perimeter of the vectorized math object. It takes value between 0 and 1 both inclusive. length : float Length of the tangent line Examples : circle = Circle(arc_center=ORIGIN, radius=3, color=GREEN) tangentLine = TangentLine(vmob=circle, alpha=1/3, length=6, color=BLUE) Returns ----- out : TangentLine object A TangentLine object satisfying the specified parameters ''' def __init__( self, vmob: VMobject, alpha: float, length: float = 2, d_alpha: float = 1e-6, **kwargs ): a1 = clip(alpha - d_alpha, 0, 1) a2 = clip(alpha + d_alpha, 0, 1) super().__init__(vmob.pfp(a1), vmob.pfp(a2), **kwargs) self.scale(length / self.get_length()) class Elbow(VMobject): ''' Creates an elbow. Elbow is an L-shaped shaped object. Parameters ----- width : float Width of the elbow angle : float Angle of the elbow in radians with the horizontal. (Angles are measured counter-clockwise) Examples : line = Elbow(width=2, angle=TAU/16) Returns ----- out : Elbow object A Elbow object satisfying the specified parameters ''' def __init__( self, width: float = 0.2, angle: float = 0, **kwargs ): super().__init__(**kwargs) self.set_points_as_corners([UP, UR, RIGHT]) self.set_width(width, about_point=ORIGIN) self.rotate(angle, about_point=ORIGIN) class StrokeArrow(Line): def __init__( self, start: Vect3 | Mobject, end: Vect3 | Mobject, stroke_color: ManimColor = DEFAULT_LIGHT_COLOR, stroke_width: float = 5, buff: float = 0.25, tip_width_ratio: float = 5, tip_len_to_width: float = 0.0075, max_tip_length_to_length_ratio: float = 0.3, max_width_to_length_ratio: float = 8.0, **kwargs, ): self.tip_width_ratio = tip_width_ratio self.tip_len_to_width = tip_len_to_width self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio self.max_width_to_length_ratio = max_width_to_length_ratio self.n_tip_points = 3 self.original_stroke_width = stroke_width super().__init__( start, end, stroke_color=stroke_color, stroke_width=stroke_width, buff=buff, **kwargs ) def set_points_by_ends( self, start: Vect3, end: Vect3, buff: float = 0, path_arc: float = 0 ) -> Self: super().set_points_by_ends(start, end, buff, path_arc) self.insert_tip_anchor() self.create_tip_with_stroke_width() return self def insert_tip_anchor(self) -> Self: prev_end = self.get_end() arc_len = self.get_arc_length() tip_len = self.get_stroke_width() * self.tip_width_ratio * self.tip_len_to_width if tip_len >= self.max_tip_length_to_length_ratio * arc_len or arc_len == 0: alpha = self.max_tip_length_to_length_ratio else: alpha = tip_len / arc_len if self.path_arc > 0 and self.buff > 0: self.insert_n_curves(10) # Is this needed? self.pointwise_become_partial(self, 0.0, 1.0 - alpha) self.add_line_to(self.get_end()) self.add_line_to(prev_end) self.n_tip_points = 3 return self @Mobject.affects_data def create_tip_with_stroke_width(self) -> Self: if self.get_num_points() < 3: return self stroke_width = min( self.original_stroke_width, self.max_width_to_length_ratio * self.get_length(), ) tip_width = self.tip_width_ratio * stroke_width ntp = self.n_tip_points self.data['stroke_width'][:-ntp] = self.data['stroke_width'][0] self.data['stroke_width'][-ntp:, 0] = tip_width * np.linspace(1, 0, ntp) return self def reset_tip(self) -> Self: self.set_points_by_ends( self.get_start(), self.get_end(), path_arc=self.path_arc ) return self def set_stroke( self, color: ManimColor | Iterable[ManimColor] | None = None, width: float | Iterable[float] | None = None, *args, **kwargs ) -> Self: super().set_stroke(color=color, width=width, *args, **kwargs) self.original_stroke_width = self.get_stroke_width() if self.has_points(): self.reset_tip() return self def _handle_scale_side_effects(self, scale_factor: float) -> Self: if scale_factor != 1.0: self.reset_tip() return self class Arrow(Line): ''' Creates an arrow. Parameters ---------- start : array_like Starting point of the arrow end : array_like Ending point of the arrow buff : float, optional Buffer distance from the start and end points. Default is MED_SMALL_BUFF. path_arc : float, optional If set to a non-zero value, the arrow will be curved to subtend a circle by this angle. Default is 0 (straight arrow). thickness : float, optional How wide should the base of the arrow be. This affects the shaft width. Default is 3.0. tip_width_ratio : float, optional Ratio of the tip width to the shaft width. Default is 5. tip_angle : float, optional Angle of the arrow tip in radians. Default is PI/3 (60 degrees). max_tip_length_to_length_ratio : float, optional Maximum ratio of tip length to total arrow length. Prevents tips from being too large relative to the arrow. Default is 0.5. max_width_to_length_ratio : float, optional Maximum ratio of arrow width to total arrow length. Prevents arrows from being too wide relative to their length. Default is 0.1. **kwargs Additional keyword arguments passed to the parent Line class. Examples --------
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
true
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/changing.py
manimlib/mobject/changing.py
from __future__ import annotations import numpy as np from manimlib.constants import BLUE_B, BLUE_D, BLUE_E, GREY_BROWN, DEFAULT_MOBJECT_COLOR from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.rate_functions import smooth from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, List, Iterable from manimlib.typing import ManimColor, Vect3, Self class AnimatedBoundary(VGroup): def __init__( self, vmobject: VMobject, colors: List[ManimColor] = [BLUE_D, BLUE_B, BLUE_E, GREY_BROWN], max_stroke_width: float = 3.0, cycle_rate: float = 0.5, back_and_forth: bool = True, draw_rate_func: Callable[[float], float] = smooth, fade_rate_func: Callable[[float], float] = smooth, **kwargs ): super().__init__(**kwargs) self.vmobject: VMobject = vmobject self.colors = colors self.max_stroke_width = max_stroke_width self.cycle_rate = cycle_rate self.back_and_forth = back_and_forth self.draw_rate_func = draw_rate_func self.fade_rate_func = fade_rate_func self.boundary_copies: list[VMobject] = [ vmobject.copy().set_style( stroke_width=0, fill_opacity=0 ) for x in range(2) ] self.add(*self.boundary_copies) self.total_time: float = 0 self.add_updater( lambda m, dt: self.update_boundary_copies(dt) ) def update_boundary_copies(self, dt: float) -> Self: # Not actual time, but something which passes at # an altered rate to make the implementation below # cleaner time = self.total_time * self.cycle_rate growing, fading = self.boundary_copies colors = self.colors msw = self.max_stroke_width vmobject = self.vmobject index = int(time % len(colors)) alpha = time % 1 draw_alpha = self.draw_rate_func(alpha) fade_alpha = self.fade_rate_func(alpha) if self.back_and_forth and int(time) % 2 == 1: bounds = (1 - draw_alpha, 1) else: bounds = (0, draw_alpha) self.full_family_become_partial(growing, vmobject, *bounds) growing.set_stroke(colors[index], width=msw) if time >= 1: self.full_family_become_partial(fading, vmobject, 0, 1) fading.set_stroke( color=colors[index - 1], width=(1 - fade_alpha) * msw ) self.total_time += dt return self def full_family_become_partial( self, mob1: VMobject, mob2: VMobject, a: float, b: float ) -> Self: family1 = mob1.family_members_with_points() family2 = mob2.family_members_with_points() for sm1, sm2 in zip(family1, family2): sm1.pointwise_become_partial(sm2, a, b) return self class TracedPath(VMobject): def __init__( self, traced_point_func: Callable[[], Vect3], time_traced: float = np.inf, time_per_anchor: float = 1.0 / 15, stroke_color: ManimColor = DEFAULT_MOBJECT_COLOR, stroke_width: float | Iterable[float] = 2.0, stroke_opacity: float = 1.0, **kwargs ): self.stroke_config = dict( color=stroke_color, width=stroke_width, opacity=stroke_opacity, ) super().__init__(**kwargs) self.traced_point_func = traced_point_func self.time_traced = time_traced self.time_per_anchor = time_per_anchor self.time: float = 0 self.traced_points: list[np.ndarray] = [] self.add_updater(lambda m, dt: m.update_path(dt)) def update_path(self, dt: float) -> Self: if dt == 0: return self point = self.traced_point_func().copy() self.traced_points.append(point) if self.time_traced < np.inf: n_relevant_points = int(self.time_traced / dt + 0.5) n_tps = len(self.traced_points) if n_tps < n_relevant_points: points = self.traced_points + [point] * (n_relevant_points - n_tps) else: points = self.traced_points[n_tps - n_relevant_points:] # Every now and then refresh the list if n_tps > 10 * n_relevant_points: self.traced_points = self.traced_points[-n_relevant_points:] else: points = self.traced_points if points: self.set_points_smoothly(points) self.set_stroke(**self.stroke_config) self.time += dt return self class TracingTail(TracedPath): def __init__( self, mobject_or_func: Mobject | Callable[[], np.ndarray], time_traced: float = 1.0, stroke_color: ManimColor = DEFAULT_MOBJECT_COLOR, stroke_width: float | Iterable[float] = (0, 3), stroke_opacity: float | Iterable[float] = (0, 1), **kwargs ): if isinstance(mobject_or_func, Mobject): func = mobject_or_func.get_center else: func = mobject_or_func super().__init__( func, time_traced=time_traced, stroke_color=stroke_color, stroke_width=stroke_width, stroke_opacity=stroke_opacity, **kwargs ) curr_point = self.traced_point_func() n_points = int(self.time_traced / self.time_per_anchor) self.traced_points: list[np.ndarray] = n_points * [curr_point]
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/functions.py
manimlib/mobject/functions.py
from __future__ import annotations from isosurfaces import plot_isoline import numpy as np from manimlib.constants import FRAME_X_RADIUS, FRAME_Y_RADIUS from manimlib.constants import YELLOW from manimlib.mobject.types.vectorized_mobject import VMobject from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Sequence, Tuple from manimlib.typing import ManimColor, Vect3 class ParametricCurve(VMobject): def __init__( self, t_func: Callable[[float], Sequence[float] | Vect3], t_range: Tuple[float, float, float] = (0, 1, 0.1), epsilon: float = 1e-8, # TODO, automatically figure out discontinuities discontinuities: Sequence[float] = [], use_smoothing: bool = True, **kwargs ): self.t_func = t_func self.t_range = t_range self.epsilon = epsilon self.discontinuities = discontinuities self.use_smoothing = use_smoothing super().__init__(**kwargs) def get_point_from_function(self, t: float) -> Vect3: return np.array(self.t_func(t)) def init_points(self): t_min, t_max, step = self.t_range jumps = np.array(self.discontinuities) jumps = jumps[(jumps > t_min) & (jumps < t_max)] boundary_times = [t_min, t_max, *(jumps - self.epsilon), *(jumps + self.epsilon)] boundary_times.sort() for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]): t_range = [*np.arange(t1, t2, step), t2] points = np.array([self.t_func(t) for t in t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if self.use_smoothing: self.make_smooth(approx=True) if not self.has_points(): self.set_points(np.array([self.t_func(t_min)])) return self def get_t_func(self): return self.t_func def get_function(self): if hasattr(self, "underlying_function"): return self.underlying_function if hasattr(self, "function"): return self.function def get_x_range(self): if hasattr(self, "x_range"): return self.x_range class FunctionGraph(ParametricCurve): def __init__( self, function: Callable[[float], float], x_range: Tuple[float, float, float] = (-8, 8, 0.25), color: ManimColor = YELLOW, **kwargs ): self.function = function self.x_range = x_range def parametric_function(t): return [t, function(t), 0] super().__init__(parametric_function, self.x_range, **kwargs) class ImplicitFunction(VMobject): def __init__( self, func: Callable[[float, float], float], x_range: Tuple[float, float] = (-FRAME_X_RADIUS, FRAME_X_RADIUS), y_range: Tuple[float, float] = (-FRAME_Y_RADIUS, FRAME_Y_RADIUS), min_depth: int = 5, max_quads: int = 1500, use_smoothing: bool = False, joint_type: str = 'no_joint', **kwargs ): super().__init__(joint_type=joint_type, **kwargs) p_min, p_max = ( np.array([x_range[0], y_range[0]]), np.array([x_range[1], y_range[1]]), ) curves = plot_isoline( fn=lambda u: func(u[0], u[1]), pmin=p_min, pmax=p_max, min_depth=min_depth, max_quads=max_quads, ) # returns a list of lists of 2D points curves = [ np.pad(curve, [(0, 0), (0, 1)]) for curve in curves if curve != [] ] # add z coord as 0 for curve in curves: self.start_new_path(curve[0]) self.add_points_as_corners(curve[1:]) if use_smoothing: self.make_smooth()
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/frame.py
manimlib/mobject/frame.py
from __future__ import annotations from manimlib.constants import BLACK, GREY_E from manimlib.constants import FRAME_HEIGHT from manimlib.mobject.geometry import Rectangle from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor class ScreenRectangle(Rectangle): def __init__( self, aspect_ratio: float = 16.0 / 9.0, height: float = 4, **kwargs ): super().__init__( width=aspect_ratio * height, height=height, **kwargs ) class FullScreenRectangle(ScreenRectangle): def __init__( self, height: float = FRAME_HEIGHT, fill_color: ManimColor = GREY_E, fill_opacity: float = 1, stroke_width: float = 0, **kwargs, ): super().__init__( height=height, fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs ) class FullScreenFadeRectangle(FullScreenRectangle): def __init__( self, stroke_width: float = 0.0, fill_color: ManimColor = BLACK, fill_opacity: float = 0.7, **kwargs, ): super().__init__( stroke_width=stroke_width, fill_color=fill_color, fill_opacity=fill_opacity, )
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/vector_field.py
manimlib/mobject/vector_field.py
from __future__ import annotations import itertools as it import numpy as np from scipy.integrate import solve_ivp from manimlib.constants import FRAME_HEIGHT, FRAME_WIDTH from manimlib.constants import DEFAULT_MOBJECT_COLOR from manimlib.animation.indication import VShowPassingFlash from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import interpolate from manimlib.utils.bezier import inverse_interpolate from manimlib.utils.color import get_colormap_list from manimlib.utils.color import get_color_map from manimlib.utils.iterables import cartesian_product from manimlib.utils.rate_functions import linear from manimlib.utils.space_ops import get_norm from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable, Sequence, TypeVar, Tuple, Optional from manimlib.typing import ManimColor, Vect3, VectN, VectArray, Vect3Array, Vect4Array from manimlib.mobject.coordinate_systems import CoordinateSystem from manimlib.mobject.mobject import Mobject T = TypeVar("T") #### Delete these two ### def get_vectorized_rgb_gradient_function( min_value: T, max_value: T, color_map: str ) -> Callable[[VectN], Vect3Array]: rgbs = np.array(get_colormap_list(color_map)) def func(values): alphas = inverse_interpolate( min_value, max_value, np.array(values) ) alphas = np.clip(alphas, 0, 1) scaled_alphas = alphas * (len(rgbs) - 1) indices = scaled_alphas.astype(int) next_indices = np.clip(indices + 1, 0, len(rgbs) - 1) inter_alphas = scaled_alphas % 1 inter_alphas = inter_alphas.repeat(3).reshape((len(indices), 3)) result = interpolate(rgbs[indices], rgbs[next_indices], inter_alphas) return result return func def get_rgb_gradient_function( min_value: T, max_value: T, color_map: str ) -> Callable[[float], Vect3]: vectorized_func = get_vectorized_rgb_gradient_function(min_value, max_value, color_map) return lambda value: vectorized_func(np.array([value]))[0] #### def ode_solution_points(function, state0, time, dt=0.01): solution = solve_ivp( lambda t, state: function(state), t_span=(0, time), y0=state0, t_eval=np.arange(0, time, dt) ) return solution.y.T def move_along_vector_field( mobject: Mobject, func: Callable[[Vect3], Vect3] ) -> Mobject: mobject.add_updater( lambda m, dt: m.shift( func(m.get_center()) * dt ) ) return mobject def move_submobjects_along_vector_field( mobject: Mobject, func: Callable[[Vect3], Vect3] ) -> Mobject: def apply_nudge(mob, dt): for submob in mob: x, y = submob.get_center()[:2] if abs(x) < FRAME_WIDTH and abs(y) < FRAME_HEIGHT: submob.shift(func(submob.get_center()) * dt) mobject.add_updater(apply_nudge) return mobject def move_points_along_vector_field( mobject: Mobject, func: Callable[[float, float], Iterable[float]], coordinate_system: CoordinateSystem ) -> Mobject: cs = coordinate_system origin = cs.get_origin() def apply_nudge(mob, dt): mob.apply_function( lambda p: p + (cs.c2p(*func(*cs.p2c(p))) - origin) * dt ) mobject.add_updater(apply_nudge) return mobject def get_sample_coords( coordinate_system: CoordinateSystem, density: float = 1.0 ) -> it.product[tuple[Vect3, ...]]: ranges = [] for range_args in coordinate_system.get_all_ranges(): _min, _max, step = range_args step /= density ranges.append(np.arange(_min, _max + step, step)) return np.array(list(it.product(*ranges))) def vectorize(pointwise_function: Callable[[Tuple], Tuple]): def v_func(coords_array: VectArray) -> VectArray: return np.array([pointwise_function(*coords) for coords in coords_array]) return v_func # Mobjects class VectorField(VMobject): def __init__( self, # Vectorized function: Takes in an array of coordinates, returns an array of outputs. func: Callable[[VectArray], VectArray], # Typically a set of Axes or NumberPlane coordinate_system: CoordinateSystem, sample_coords: Optional[VectArray] = None, density: float = 2.0, magnitude_range: Optional[Tuple[float, float]] = None, color: Optional[ManimColor] = None, color_map_name: Optional[str] = "3b1b_colormap", color_map: Optional[Callable[[Sequence[float]], Vect4Array]] = None, stroke_opacity: float = 1.0, stroke_width: float = 3, tip_width_ratio: float = 4, tip_len_to_width: float = 0.01, max_vect_len: float | None = None, max_vect_len_to_step_size: float = 0.8, flat_stroke: bool = False, norm_to_opacity_func=None, # TODO, check on this **kwargs ): self.func = func self.coordinate_system = coordinate_system self.stroke_width = stroke_width self.tip_width_ratio = tip_width_ratio self.tip_len_to_width = tip_len_to_width self.norm_to_opacity_func = norm_to_opacity_func # Search for sample_points if sample_coords is not None: self.sample_coords = sample_coords else: self.sample_coords = get_sample_coords(coordinate_system, density) self.update_sample_points() if max_vect_len is None: step_size = get_norm(self.sample_points[1] - self.sample_points[0]) self.max_displayed_vect_len = max_vect_len_to_step_size * step_size else: self.max_displayed_vect_len = max_vect_len * coordinate_system.x_axis.get_unit_size() # Prepare the color map if magnitude_range is None: max_value = max(map(get_norm, func(self.sample_coords))) magnitude_range = (0, max_value) self.magnitude_range = magnitude_range if color is not None: self.color_map = None else: self.color_map = color_map or get_color_map(color_map_name) self.init_base_stroke_width_array(len(self.sample_coords)) super().__init__( stroke_opacity=stroke_opacity, flat_stroke=flat_stroke, **kwargs ) self.set_stroke(color, stroke_width) self.update_vectors() def init_points(self): n_samples = len(self.sample_coords) self.set_points(np.zeros((8 * n_samples - 1, 3))) self.set_joint_type('no_joint') def get_sample_points( self, center: np.ndarray, width: float, height: float, depth: float, x_density: float, y_density: float, z_density: float ) -> np.ndarray: to_corner = np.array([width / 2, height / 2, depth / 2]) spacings = 1.0 / np.array([x_density, y_density, z_density]) to_corner = spacings * (to_corner / spacings).astype(int) lower_corner = center - to_corner upper_corner = center + to_corner + spacings return cartesian_product(*( np.arange(low, high, space) for low, high, space in zip(lower_corner, upper_corner, spacings) )) def init_base_stroke_width_array(self, n_sample_points): arr = np.ones(8 * n_sample_points - 1) arr[4::8] = self.tip_width_ratio arr[5::8] = self.tip_width_ratio * 0.5 arr[6::8] = 0 arr[7::8] = 0 self.base_stroke_width_array = arr def set_sample_coords(self, sample_coords: VectArray): self.sample_coords = sample_coords return self def set_stroke(self, color=None, width=None, opacity=None, behind=None, flat=None, recurse=True): super().set_stroke(color, None, opacity, behind, flat, recurse) if width is not None: self.set_stroke_width(float(width)) return self def set_stroke_width(self, width: float): if self.get_num_points() > 0: self.get_stroke_widths()[:] = width * self.base_stroke_width_array self.stroke_width = width return self def update_sample_points(self): self.sample_points = self.coordinate_system.c2p(*self.sample_coords.T) def update_vectors(self): tip_width = self.tip_width_ratio * self.stroke_width tip_len = self.tip_len_to_width * tip_width # Outputs in the coordinate system outputs = self.func(self.sample_coords) output_norms = np.linalg.norm(outputs, axis=1)[:, np.newaxis] # Corresponding vector values in global coordinates out_vects = self.coordinate_system.c2p(*outputs.T) - self.coordinate_system.get_origin() out_vect_norms = np.linalg.norm(out_vects, axis=1)[:, np.newaxis] unit_outputs = np.zeros_like(out_vects) np.true_divide(out_vects, out_vect_norms, out=unit_outputs, where=(out_vect_norms > 0)) # How long should the arrows be drawn, in global coordinates max_len = self.max_displayed_vect_len if max_len < np.inf: drawn_norms = max_len * np.tanh(out_vect_norms / max_len) else: drawn_norms = out_vect_norms # What's the distance from the base of an arrow to # the base of its head? dist_to_head_base = np.clip(drawn_norms - tip_len, 0, np.inf) # Mixing units! # Set all points points = self.get_points() points[0::8] = self.sample_points points[2::8] = self.sample_points + dist_to_head_base * unit_outputs points[4::8] = points[2::8] points[6::8] = self.sample_points + drawn_norms * unit_outputs for i in (1, 3, 5): points[i::8] = 0.5 * (points[i - 1::8] + points[i + 1::8]) points[7::8] = points[6:-1:8] # Adjust stroke widths width_arr = self.stroke_width * self.base_stroke_width_array width_scalars = np.clip(drawn_norms / tip_len, 0, 1) width_scalars = np.repeat(width_scalars, 8)[:-1] self.get_stroke_widths()[:] = width_scalars * width_arr # Potentially adjust opacity and color if self.color_map is not None: self.get_stroke_colors() # Ensures the array is updated to appropriate length low, high = self.magnitude_range self.data['stroke_rgba'][:, :3] = self.color_map( inverse_interpolate(low, high, np.repeat(output_norms, 8)[:-1]) )[:, :3] if self.norm_to_opacity_func is not None: self.get_stroke_opacities()[:] = self.norm_to_opacity_func( np.repeat(output_norms, 8)[:-1] ) self.note_changed_data() return self class TimeVaryingVectorField(VectorField): def __init__( self, # Takes in an array of points and a float for time time_func: Callable[[VectArray, float], VectArray], coordinate_system: CoordinateSystem, **kwargs ): self.time = 0 def func(coords): return time_func(coords, self.time) super().__init__(func, coordinate_system, **kwargs) self.add_updater(lambda m, dt: m.increment_time(dt)) self.always.update_vectors() def increment_time(self, dt): self.time += dt class StreamLines(VGroup): def __init__( self, func: Callable[[VectArray], VectArray], coordinate_system: CoordinateSystem, density: float = 1.0, n_repeats: int = 1, noise_factor: float | None = None, # Config for drawing lines solution_time: float = 3, dt: float = 0.05, arc_len: float = 3, max_time_steps: int = 200, n_samples_per_line: int = 10, cutoff_norm: float = 15, # Style info stroke_width: float = 1.0, stroke_color: ManimColor = DEFAULT_MOBJECT_COLOR, stroke_opacity: float = 1, color_by_magnitude: bool = True, magnitude_range: Tuple[float, float] = (0, 2.0), taper_stroke_width: bool = False, color_map: str = "3b1b_colormap", **kwargs ): super().__init__(**kwargs) self.func = func self.coordinate_system = coordinate_system self.density = density self.n_repeats = n_repeats self.noise_factor = noise_factor self.solution_time = solution_time self.dt = dt self.arc_len = arc_len self.max_time_steps = max_time_steps self.n_samples_per_line = n_samples_per_line self.cutoff_norm = cutoff_norm self.stroke_width = stroke_width self.stroke_color = stroke_color self.stroke_opacity = stroke_opacity self.color_by_magnitude = color_by_magnitude self.magnitude_range = magnitude_range self.taper_stroke_width = taper_stroke_width self.color_map = color_map self.draw_lines() self.init_style() def point_func(self, points: Vect3Array) -> Vect3: in_coords = np.array(self.coordinate_system.p2c(points)).T out_coords = self.func(in_coords) origin = self.coordinate_system.get_origin() return self.coordinate_system.c2p(*out_coords.T) - origin def draw_lines(self) -> None: lines = [] # Todo, it feels like coordinate system should just have # the ODE solver built into it, no? lines = [] for coords in self.get_sample_coords(): solution_coords = ode_solution_points(self.func, coords, self.solution_time, self.dt) line = VMobject() line.set_points_smoothly(self.coordinate_system.c2p(*solution_coords.T)) # TODO, account for arc length somehow? line.virtual_time = self.solution_time lines.append(line) self.set_submobjects(lines) def get_sample_coords(self): cs = self.coordinate_system sample_coords = get_sample_coords(cs, self.density) noise_factor = self.noise_factor if noise_factor is None: noise_factor = (cs.x_axis.get_unit_size() / self.density) * 0.5 return np.array([ coords + noise_factor * np.random.random(coords.shape) for n in range(self.n_repeats) for coords in sample_coords ]) def init_style(self) -> None: if self.color_by_magnitude: values_to_rgbs = get_vectorized_rgb_gradient_function( *self.magnitude_range, self.color_map, ) cs = self.coordinate_system for line in self.submobjects: norms = [ get_norm(self.func(cs.p2c(point))) for point in line.get_points() ] rgbs = values_to_rgbs(norms) rgbas = np.zeros((len(rgbs), 4)) rgbas[:, :3] = rgbs rgbas[:, 3] = self.stroke_opacity line.set_rgba_array(rgbas, "stroke_rgba") else: self.set_stroke(self.stroke_color, opacity=self.stroke_opacity) if self.taper_stroke_width: width = [0, self.stroke_width, 0] else: width = self.stroke_width self.set_stroke(width=width) class AnimatedStreamLines(VGroup): def __init__( self, stream_lines: StreamLines, lag_range: float = 4, rate_multiple: float = 1.0, line_anim_config: dict = dict( rate_func=linear, time_width=1.0, ), **kwargs ): super().__init__(**kwargs) self.stream_lines = stream_lines for line in stream_lines: line.anim = VShowPassingFlash( line, run_time=line.virtual_time / rate_multiple, **line_anim_config, ) line.anim.begin() line.time = -lag_range * np.random.random() self.add(line.anim.mobject) self.add_updater(lambda m, dt: m.update(dt)) def update(self, dt: float = 0) -> None: stream_lines = self.stream_lines for line in stream_lines: line.time += dt adjusted_time = max(line.time, 0) % line.anim.run_time line.anim.update(adjusted_time / line.anim.run_time)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/types/point_cloud_mobject.py
manimlib/mobject/types/point_cloud_mobject.py
from __future__ import annotations import numpy as np from manimlib.mobject.mobject import Mobject from manimlib.utils.color import color_gradient from manimlib.utils.color import color_to_rgba from manimlib.utils.iterables import resize_with_interpolation from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import ManimColor, Vect3, Vect3Array, Vect4Array, Self class PMobject(Mobject): def set_points(self, points: Vect3Array): if len(points) == 0: points = np.zeros((0, 3)) super().set_points(points) self.resize_points(len(points)) return self def add_points( self, points: Vect3Array, rgbas: Vect4Array | None = None, color: ManimColor | None = None, opacity: float | None = None ) -> Self: """ points must be a Nx3 numpy array, as must rgbas if it is not None """ self.append_points(points) # rgbas array will have been resized with points if color is not None: if opacity is None: opacity = self.data["rgba"][-1, 3] rgbas = np.repeat( [color_to_rgba(color, opacity)], len(points), axis=0 ) if rgbas is not None: self.data["rgba"][-len(rgbas):] = rgbas return self def add_point(self, point: Vect3, rgba=None, color=None, opacity=None) -> Self: rgbas = None if rgba is None else [rgba] self.add_points([point], rgbas, color, opacity) return self @Mobject.affects_data def set_color_by_gradient(self, *colors: ManimColor) -> Self: self.data["rgba"][:] = np.array(list(map( color_to_rgba, color_gradient(colors, self.get_num_points()) ))) return self @Mobject.affects_data def match_colors(self, pmobject: PMobject) -> Self: self.data["rgba"][:] = resize_with_interpolation( pmobject.data["rgba"], self.get_num_points() ) return self @Mobject.affects_data def filter_out(self, condition: Callable[[np.ndarray], bool]) -> Self: for mob in self.family_members_with_points(): mob.data = mob.data[~np.apply_along_axis(condition, 1, mob.get_points())] return self @Mobject.affects_data def sort_points(self, function: Callable[[Vect3], None] = lambda p: p[0]) -> Self: """ function is any map from R^3 to R """ for mob in self.family_members_with_points(): indices = np.argsort( np.apply_along_axis(function, 1, mob.get_points()) ) mob.data[:] = mob.data[indices] return self @Mobject.affects_data def ingest_submobjects(self) -> Self: self.data = np.vstack([ sm.data for sm in self.get_family() ]) return self def point_from_proportion(self, alpha: float) -> np.ndarray: index = alpha * (self.get_num_points() - 1) return self.get_points()[int(index)] @Mobject.affects_data def pointwise_become_partial(self, pmobject: PMobject, a: float, b: float) -> Self: lower_index = int(a * pmobject.get_num_points()) upper_index = int(b * pmobject.get_num_points()) self.data = pmobject.data[lower_index:upper_index].copy() return self class PGroup(PMobject): def __init__(self, *pmobs: PMobject, **kwargs): if not all([isinstance(m, PMobject) for m in pmobs]): raise Exception("All submobjects must be of type PMobject") super().__init__(**kwargs) self.add(*pmobs)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/types/vectorized_mobject.py
manimlib/mobject/types/vectorized_mobject.py
from __future__ import annotations from functools import wraps import numpy as np from manimlib.constants import GREY_A, GREY_C, GREY_E from manimlib.constants import DEFAULT_VMOBJECT_FILL_COLOR, DEFAULT_VMOBJECT_STROKE_COLOR from manimlib.constants import BLACK from manimlib.constants import DEFAULT_STROKE_WIDTH from manimlib.constants import DEG from manimlib.constants import ORIGIN, OUT from manimlib.constants import PI from manimlib.constants import TAU from manimlib.mobject.mobject import Mobject from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Point from manimlib.utils.bezier import bezier from manimlib.utils.bezier import get_quadratic_approximation_of_cubic from manimlib.utils.bezier import approx_smooth_quadratic_bezier_handles from manimlib.utils.bezier import smooth_quadratic_path from manimlib.utils.bezier import interpolate from manimlib.utils.bezier import integer_interpolate from manimlib.utils.bezier import inverse_interpolate from manimlib.utils.bezier import find_intersection from manimlib.utils.bezier import outer_interpolate from manimlib.utils.bezier import partial_quadratic_bezier_points from manimlib.utils.bezier import quadratic_bezier_points_for_arc from manimlib.utils.color import color_gradient from manimlib.utils.color import rgb_to_hex from manimlib.utils.iterables import make_even from manimlib.utils.iterables import resize_array from manimlib.utils.iterables import resize_with_interpolation from manimlib.utils.iterables import resize_preserving_order from manimlib.utils.space_ops import angle_between_vectors from manimlib.utils.space_ops import cross2d from manimlib.utils.space_ops import earclip_triangulation from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import get_unit_normal from manimlib.utils.space_ops import line_intersects_path from manimlib.utils.space_ops import midpoint from manimlib.utils.space_ops import rotation_between_vectors from manimlib.utils.space_ops import rotation_matrix_transpose from manimlib.utils.space_ops import poly_line_length from manimlib.utils.space_ops import z_to_vector from manimlib.shader_wrapper import VShaderWrapper from typing import TYPE_CHECKING from typing import Generic, TypeVar, Iterable SubVmobjectType = TypeVar('SubVmobjectType', bound='VMobject') if TYPE_CHECKING: from typing import Callable, Tuple, Any, Optional from manimlib.typing import ManimColor, Vect3, Vect4, Vect3Array, Self from moderngl.context import Context class VMobject(Mobject): data_dtype: np.dtype = np.dtype([ ('point', np.float32, (3,)), ('stroke_rgba', np.float32, (4,)), ('stroke_width', np.float32, (1,)), ('joint_angle', np.float32, (1,)), ('fill_rgba', np.float32, (4,)), ('base_normal', np.float32, (3,)), # Base points and unit normal vectors are interleaved in this array ('fill_border_width', np.float32, (1,)), ]) pre_function_handle_to_anchor_scale_factor: float = 0.01 make_smooth_after_applying_functions: bool = False # TODO, do we care about accounting for varying zoom levels? tolerance_for_point_equality: float = 1e-8 joint_type_map: dict = { "no_joint": 0, "auto": 1, "bevel": 2, "miter": 3, } def __init__( self, color: ManimColor = None, # If set, this will override stroke_color and fill_color fill_color: ManimColor = None, fill_opacity: float | Iterable[float] | None = 0.0, stroke_color: ManimColor = None, stroke_opacity: float | Iterable[float] | None = 1.0, stroke_width: float | Iterable[float] | None = DEFAULT_STROKE_WIDTH, stroke_behind: bool = False, background_image_file: str | None = None, long_lines: bool = False, # Could also be "no_joint", "bevel", "miter" joint_type: str = "auto", flat_stroke: bool = False, scale_stroke_with_zoom: bool = False, use_simple_quadratic_approx: bool = False, # Measured in pixel widths anti_alias_width: float = 1.5, fill_border_width: float = 0.0, **kwargs ): self.fill_color = fill_color or color or DEFAULT_VMOBJECT_FILL_COLOR self.fill_opacity = fill_opacity self.stroke_color = stroke_color or color or DEFAULT_VMOBJECT_STROKE_COLOR self.stroke_opacity = stroke_opacity self.stroke_width = stroke_width self.stroke_behind = stroke_behind self.background_image_file = background_image_file self.long_lines = long_lines self.joint_type = joint_type self.flat_stroke = flat_stroke self.scale_stroke_with_zoom = scale_stroke_with_zoom self.use_simple_quadratic_approx = use_simple_quadratic_approx self.anti_alias_width = anti_alias_width self.fill_border_width = fill_border_width self.needs_new_joint_angles = True self.needs_new_unit_normal = True self.subpath_end_indices = None self.outer_vert_indices = np.zeros(0, dtype=int) super().__init__(**kwargs) def get_group_class(self): return VGroup def init_uniforms(self): super().init_uniforms() self.uniforms.update( anti_alias_width=self.anti_alias_width, joint_type=self.joint_type_map[self.joint_type], flat_stroke=float(self.flat_stroke), scale_stroke_with_zoom=float(self.scale_stroke_with_zoom) ) def add(self, *vmobjects: VMobject) -> Self: if not all((isinstance(m, VMobject) for m in vmobjects)): raise Exception("All submobjects must be of type VMobject") return super().add(*vmobjects) # Colors def init_colors(self): self.set_stroke( color=self.stroke_color, width=self.stroke_width, opacity=self.stroke_opacity, behind=self.stroke_behind, ) self.set_fill( color=self.fill_color, opacity=self.fill_opacity, border_width=self.fill_border_width, ) self.set_shading(*self.shading) self.set_flat_stroke(self.flat_stroke) self.color = self.get_color() return self def set_fill( self, color: ManimColor | Iterable[ManimColor] = None, opacity: float | Iterable[float] | None = None, border_width: float | None = None, recurse: bool = True ) -> Self: self.set_rgba_array_by_color(color, opacity, 'fill_rgba', recurse) if border_width is not None: self.border_width = border_width for mob in self.get_family(recurse): data = mob.data if mob.has_points() > 0 else mob._data_defaults data["fill_border_width"] = border_width return self def set_stroke( self, color: ManimColor | Iterable[ManimColor] = None, width: float | Iterable[float] | None = None, opacity: float | Iterable[float] | None = None, behind: bool | None = None, flat: bool | None = None, recurse: bool = True ) -> Self: self.set_rgba_array_by_color(color, opacity, 'stroke_rgba', recurse) if width is not None: for mob in self.get_family(recurse): data = mob.data if mob.get_num_points() > 0 else mob._data_defaults if isinstance(width, (float, int, np.floating)): data['stroke_width'][:, 0] = width else: data['stroke_width'][:, 0] = resize_with_interpolation( np.array(width), len(data) ).flatten() if behind is not None: for mob in self.get_family(recurse): if mob.stroke_behind != behind: mob.stroke_behind = behind mob.refresh_shader_wrapper_id() if flat is not None: self.set_flat_stroke(flat) return self def set_backstroke( self, color: ManimColor | Iterable[ManimColor] = BLACK, width: float | Iterable[float] = 3, ) -> Self: self.set_stroke(color, width, behind=True) return self @Mobject.affects_family_data def set_style( self, fill_color: ManimColor | Iterable[ManimColor] | None = None, fill_opacity: float | Iterable[float] | None = None, fill_rgba: Vect4 | None = None, fill_border_width: float | None = None, stroke_color: ManimColor | Iterable[ManimColor] | None = None, stroke_opacity: float | Iterable[float] | None = None, stroke_rgba: Vect4 | None = None, stroke_width: float | Iterable[float] | None = None, stroke_behind: bool | None = None, flat_stroke: Optional[bool] = None, shading: Tuple[float, float, float] | None = None, recurse: bool = True ) -> Self: for mob in self.get_family(recurse): if fill_rgba is not None: mob.data['fill_rgba'][:] = resize_with_interpolation(fill_rgba, len(mob.data['fill_rgba'])) else: mob.set_fill( color=fill_color, opacity=fill_opacity, border_width=fill_border_width, recurse=False ) if stroke_rgba is not None: mob.data['stroke_rgba'][:] = resize_with_interpolation(stroke_rgba, len(mob.data['stroke_rgba'])) mob.set_stroke( width=stroke_width, behind=stroke_behind, flat=flat_stroke, recurse=False, ) else: mob.set_stroke( color=stroke_color, width=stroke_width, opacity=stroke_opacity, flat=flat_stroke, behind=stroke_behind, recurse=False, ) if shading is not None: mob.set_shading(*shading, recurse=False) return self def get_style(self) -> dict[str, Any]: data = self.data if self.get_num_points() > 0 else self._data_defaults return { "fill_rgba": data['fill_rgba'].copy(), "fill_border_width": data['fill_border_width'].copy(), "stroke_rgba": data['stroke_rgba'].copy(), "stroke_width": data['stroke_width'].copy(), "stroke_behind": self.stroke_behind, "flat_stroke": self.get_flat_stroke(), "shading": self.get_shading(), } def match_style(self, vmobject: VMobject, recurse: bool = True) -> Self: self.set_style(**vmobject.get_style(), recurse=False) if recurse: # Does its best to match up submobject lists, and # match styles accordingly submobs1, submobs2 = self.submobjects, vmobject.submobjects if len(submobs1) == 0: return self elif len(submobs2) == 0: submobs2 = [vmobject] for sm1, sm2 in zip(*make_even(submobs1, submobs2)): sm1.match_style(sm2) return self def set_color( self, color: ManimColor | Iterable[ManimColor] | None, opacity: float | Iterable[float] | None = None, recurse: bool = True ) -> Self: self.set_fill(color, opacity=opacity, recurse=recurse) self.set_stroke(color, opacity=opacity, recurse=recurse) return self def set_opacity( self, opacity: float | Iterable[float] | None, recurse: bool = True ) -> Self: self.set_fill(opacity=opacity, recurse=recurse) self.set_stroke(opacity=opacity, recurse=recurse) return self def set_color_by_proportion(self, prop_to_color: Callable[[float], Color]) -> Self: colors = list(map(prop_to_color, np.linspace(0, 1, self.get_num_points()))) self.set_stroke(color=colors) return self def set_anti_alias_width(self, anti_alias_width: float, recurse: bool = True) -> Self: self.set_uniform(recurse, anti_alias_width=anti_alias_width) return self def fade(self, darkness: float = 0.5, recurse: bool = True) -> Self: mobs = self.get_family() if recurse else [self] for mob in mobs: factor = 1.0 - darkness mob.set_fill( opacity=factor * mob.get_fill_opacity(), recurse=False, ) mob.set_stroke( opacity=factor * mob.get_stroke_opacity(), recurse=False, ) return self def get_fill_colors(self) -> list[str]: return [ rgb_to_hex(rgba[:3]) for rgba in self.data['fill_rgba'] ] def get_fill_opacities(self) -> np.ndarray: return self.data['fill_rgba'][:, 3] def get_stroke_colors(self) -> list[str]: return [ rgb_to_hex(rgba[:3]) for rgba in self.data['stroke_rgba'] ] def get_stroke_opacities(self) -> np.ndarray: return self.data['stroke_rgba'][:, 3] def get_stroke_widths(self) -> np.ndarray: return self.data['stroke_width'][:, 0] # TODO, it's weird for these to return the first of various lists # rather than the full information def get_fill_color(self) -> str: """ If there are multiple colors (for gradient) this returns the first one """ data = self.data if self.has_points() else self._data_defaults return rgb_to_hex(data["fill_rgba"][0, :3]) def get_fill_opacity(self) -> float: """ If there are multiple opacities, this returns the first """ data = self.data if self.has_points() else self._data_defaults return data["fill_rgba"][0, 3] def get_stroke_color(self) -> str: data = self.data if self.has_points() else self._data_defaults return rgb_to_hex(data["stroke_rgba"][0, :3]) def get_stroke_width(self) -> float: data = self.data if self.has_points() else self._data_defaults return data["stroke_width"][0, 0] def get_stroke_opacity(self) -> float: data = self.data if self.has_points() else self._data_defaults return data["stroke_rgba"][0, 3] def get_color(self) -> str: if self.has_fill(): return self.get_fill_color() return self.get_stroke_color() def get_anti_alias_width(self): return self.uniforms["anti_alias_width"] def has_stroke(self) -> bool: data = self.data if len(self.data) > 0 else self._data_defaults return any(data['stroke_width']) and any(data['stroke_rgba'][:, 3]) def has_fill(self) -> bool: data = self.data if len(self.data) > 0 else self._data_defaults return any(data['fill_rgba'][:, 3]) def get_opacity(self) -> float: if self.has_fill(): return self.get_fill_opacity() return self.get_stroke_opacity() def set_flat_stroke(self, flat_stroke: bool = True, recurse: bool = True) -> Self: self.set_uniform(recurse, flat_stroke=float(flat_stroke)) return self def get_flat_stroke(self) -> bool: return self.uniforms["flat_stroke"] == 1.0 def set_scale_stroke_with_zoom(self, scale_stroke_with_zoom: bool = True, recurse: bool = True) -> Self: self.set_uniform(recurse, scale_stroke_with_zoom=float(scale_stroke_with_zoom)) pass def get_scale_stroke_with_zoom(self) -> bool: return self.uniforms["flat_stroke"] == 1.0 def set_joint_type(self, joint_type: str, recurse: bool = True) -> Self: for mob in self.get_family(recurse): mob.uniforms["joint_type"] = self.joint_type_map[joint_type] return self def get_joint_type(self) -> float: return self.uniforms["joint_type"] def apply_depth_test( self, anti_alias_width: float = 0, recurse: bool = True ) -> Self: super().apply_depth_test(recurse) self.set_anti_alias_width(anti_alias_width) return self def deactivate_depth_test( self, anti_alias_width: float = 1.0, recurse: bool = True ) -> Self: super().deactivate_depth_test(recurse) self.set_anti_alias_width(anti_alias_width) return self def use_winding_fill(self, value: bool = True, recurse: bool = True) -> Self: # Only keeping this here because some old scene call it return self # Points def set_anchors_and_handles( self, anchors: Vect3Array, handles: Vect3Array, ) -> Self: if len(anchors) == 0: self.clear_points() return self assert len(anchors) == len(handles) + 1 points = resize_array(self.get_points(), 2 * len(anchors) - 1) points[0::2] = anchors points[1::2] = handles self.set_points(points) return self def start_new_path(self, point: Vect3) -> Self: # Path ends are signaled by a handle point sitting directly # on top of the previous anchor if self.has_points(): self.append_points([self.get_last_point(), point]) else: self.set_points([point]) return self def add_cubic_bezier_curve( self, anchor1: Vect3, handle1: Vect3, handle2: Vect3, anchor2: Vect3 ) -> Self: self.start_new_path(anchor1) self.add_cubic_bezier_curve_to(handle1, handle2, anchor2) return self def add_cubic_bezier_curve_to( self, handle1: Vect3, handle2: Vect3, anchor: Vect3, ) -> Self: """ Add cubic bezier curve to the path. """ self.throw_error_if_no_points() last = self.get_last_point() # Note, this assumes all points are on the xy-plane v1 = handle1 - last v2 = anchor - handle2 angle = angle_between_vectors(v1, v2) if self.use_simple_quadratic_approx and angle < 45 * DEG: quad_approx = [last, find_intersection(last, v1, anchor, -v2), anchor] else: quad_approx = get_quadratic_approximation_of_cubic( last, handle1, handle2, anchor ) if self.consider_points_equal(quad_approx[1], last): # This is to prevent subpaths from accidentally being marked closed quad_approx[1] = midpoint(*quad_approx[1:3]) self.append_points(quad_approx[1:]) return self def add_quadratic_bezier_curve_to(self, handle: Vect3, anchor: Vect3, allow_null_curve=True) -> Self: self.throw_error_if_no_points() last_point = self.get_last_point() if not allow_null_curve and self.consider_points_equal(last_point, anchor): return self if self.consider_points_equal(handle, last_point): # This is to prevent subpaths from accidentally being marked closed handle = midpoint(handle, anchor) self.append_points([handle, anchor]) return self def add_line_to(self, point: Vect3, allow_null_line: bool = True) -> Self: self.throw_error_if_no_points() last_point = self.get_last_point() if not allow_null_line and self.consider_points_equal(last_point, point): return self alphas = np.linspace(0, 1, 5 if self.long_lines else 3) self.append_points(outer_interpolate(last_point, point, alphas[1:])) return self def add_smooth_curve_to(self, point: Vect3) -> Self: if self.has_new_path_started(): self.add_line_to(point) else: self.throw_error_if_no_points() new_handle = self.get_reflection_of_last_handle() self.add_quadratic_bezier_curve_to(new_handle, point) return self def add_smooth_cubic_curve_to(self, handle: Vect3, point: Vect3) -> Self: self.throw_error_if_no_points() if self.get_num_points() == 1: new_handle = handle else: new_handle = self.get_reflection_of_last_handle() self.add_cubic_bezier_curve_to(new_handle, handle, point) return self def add_arc_to(self, point: Vect3, angle: float, n_components: int | None = None, threshold: float = 1e-3) -> Self: self.throw_error_if_no_points() if abs(angle) < threshold: self.add_line_to(point) return self # Assign default value for n_components if n_components is None: n_components = int(np.ceil(8 * abs(angle) / TAU)) arc_points = quadratic_bezier_points_for_arc(angle, n_components) target_vect = point - self.get_end() curr_vect = arc_points[-1] - arc_points[0] arc_points = arc_points @ rotation_between_vectors(curr_vect, target_vect).T arc_points *= get_norm(target_vect) / get_norm(curr_vect) arc_points += (self.get_end() - arc_points[0]) self.append_points(arc_points[1:]) return self def has_new_path_started(self) -> bool: points = self.get_points() if len(points) == 0: return False elif len(points) == 1: return True return self.consider_points_equal(points[-3], points[-2]) def get_last_point(self) -> Vect3: return self.get_points()[-1] def get_reflection_of_last_handle(self) -> Vect3: points = self.get_points() return 2 * points[-1] - points[-2] def close_path(self, smooth: bool = False) -> Self: if self.is_closed(): return self ends = self.get_subpath_end_indices() last_path_start = self.get_points()[0 if len(ends) == 1 else ends[-2] + 2] if smooth: self.add_smooth_curve_to(last_path_start) else: self.add_line_to(last_path_start) return self def is_closed(self) -> bool: points = self.get_points() ends = self.get_subpath_end_indices() last_path_start = points[0 if len(ends) == 1 else ends[-2] + 2] return self.consider_points_equal(last_path_start, points[-1]) def subdivide_curves_by_condition( self, tuple_to_subdivisions: Callable, recurse: bool = True ) -> Self: for vmob in self.get_family(recurse): if not vmob.has_points(): continue new_points = [vmob.get_points()[0]] for tup in vmob.get_bezier_tuples(): n_divisions = tuple_to_subdivisions(*tup) if n_divisions > 0: alphas = np.linspace(0, 1, n_divisions + 2) new_points.extend([ partial_quadratic_bezier_points(tup, a1, a2)[1:] for a1, a2 in zip(alphas, alphas[1:]) ]) else: new_points.append(tup[1:]) vmob.set_points(np.vstack(new_points)) return self def subdivide_sharp_curves( self, angle_threshold: float = 30 * DEG, recurse: bool = True ) -> Self: def tuple_to_subdivisions(b0, b1, b2): angle = angle_between_vectors(b1 - b0, b2 - b1) return int(angle / angle_threshold) self.subdivide_curves_by_condition(tuple_to_subdivisions, recurse) return self def subdivide_intersections(self, recurse: bool = True, n_subdivisions: int = 1) -> Self: path = self.get_anchors() def tuple_to_subdivisions(b0, b1, b2): if line_intersects_path(b0, b1, path): return n_subdivisions return 0 self.subdivide_curves_by_condition(tuple_to_subdivisions, recurse) return self def add_points_as_corners(self, points: Iterable[Vect3]) -> Self: for point in points: self.add_line_to(point) return self def set_points_as_corners(self, points: Iterable[Vect3]) -> Self: anchors = np.array(points) handles = 0.5 * (anchors[:-1] + anchors[1:]) self.set_anchors_and_handles(anchors, handles) return self def set_points_smoothly( self, points: Iterable[Vect3], approx: bool = True ) -> Self: self.set_points_as_corners(points) self.make_smooth(approx=approx) return self def is_smooth(self, angle_tol=1 * DEG) -> bool: angles = np.abs(self.get_joint_angles()[0::2]) return (angles < angle_tol).all() def change_anchor_mode(self, mode: str) -> Self: assert mode in ("jagged", "approx_smooth", "true_smooth") if self.get_num_points() == 0: return self subpaths = self.get_subpaths() self.clear_points() for subpath in subpaths: anchors = subpath[::2] new_subpath = np.array(subpath) if mode == "jagged": new_subpath[1::2] = 0.5 * (anchors[:-1] + anchors[1:]) elif mode == "approx_smooth": new_subpath[1::2] = approx_smooth_quadratic_bezier_handles(anchors) elif mode == "true_smooth": new_subpath = smooth_quadratic_path(anchors) # Shift any handles which ended up on top of # the previous anchor a0 = new_subpath[0:-1:2] h = new_subpath[1::2] a1 = new_subpath[2::2] false_ends = np.equal(a0, h).all(1) h[false_ends] = 0.5 * (a0[false_ends] + a1[false_ends]) self.add_subpath(new_subpath) return self def make_smooth(self, approx=True, recurse=True) -> Self: """ Edits the path so as to pass smoothly through all the current anchor points. If approx is False, this may increase the total number of points. """ mode = "approx_smooth" if approx else "true_smooth" for submob in self.get_family(recurse): if submob.is_smooth(): continue submob.change_anchor_mode(mode) return self def make_approximately_smooth(self, recurse=True) -> Self: self.make_smooth(approx=True, recurse=recurse) return self def make_jagged(self, recurse=True) -> Self: for submob in self.get_family(recurse): submob.change_anchor_mode("jagged") return self def add_subpath(self, points: Vect3Array) -> Self: assert len(points) % 2 == 1 or len(points) == 0 if not self.has_points(): self.set_points(points) return self if not self.consider_points_equal(points[0], self.get_points()[-1]): self.start_new_path(points[0]) self.append_points(points[1:]) return self def append_vectorized_mobject(self, vmobject: VMobject) -> Self: self.add_subpath(vmobject.get_points()) n = vmobject.get_num_points() self.data[-n:] = vmobject.data return self # def consider_points_equal(self, p0: Vect3, p1: Vect3) -> bool: return all(abs(p1 - p0) < self.tolerance_for_point_equality) # Information about the curve def get_bezier_tuples_from_points(self, points: Vect3Array) -> Iterable[Vect3Array]: n_curves = (len(points) - 1) // 2 return (points[2 * i:2 * i + 3] for i in range(n_curves)) def get_bezier_tuples(self) -> Iterable[Vect3Array]: return self.get_bezier_tuples_from_points(self.get_points()) def get_subpath_end_indices_from_points(self, points: Vect3Array) -> np.ndarray: atol = 1e-4 # TODO, this is too unsystematic a0, h, a1 = points[0:-1:2], points[1::2], points[2::2] # An anchor point is considered the end of a path # if its following handle is sitting on top of it. # To disambiguate this from cases with many null # curves in a row, we also check that the following # anchor is genuinely distinct is_end = (a0 == h).all(1) & (abs(h - a1) > atol).any(1) end_indices = (2 * n for n, end in enumerate(is_end) if end) return np.array([*end_indices, len(points) - 1]) def get_subpath_end_indices(self) -> np.ndarray: if self.subpath_end_indices is None: self.subpath_end_indices = self.get_subpath_end_indices_from_points(self.get_points()) return self.subpath_end_indices def get_subpaths_from_points(self, points: Vect3Array) -> list[Vect3Array]: if len(points) == 0: return [] end_indices = self.get_subpath_end_indices_from_points(points) start_indices = [0, *(end_indices[:-1] + 2)] return [points[i1:i2 + 1] for i1, i2 in zip(start_indices, end_indices)] def get_subpaths(self) -> list[Vect3Array]: return self.get_subpaths_from_points(self.get_points()) def get_nth_curve_points(self, n: int) -> Vect3Array: assert n < self.get_num_curves() return self.get_points()[2 * n:2 * n + 3] def get_nth_curve_function(self, n: int) -> Callable[[float], Vect3]: return bezier(self.get_nth_curve_points(n)) def get_num_curves(self) -> int: return self.get_num_points() // 2 def quick_point_from_proportion(self, alpha: float) -> Vect3: # Assumes all curves have the same length, so is inaccurate num_curves = self.get_num_curves() if num_curves == 0: return self.get_center() n, residue = integer_interpolate(0, num_curves, alpha) curve_func = self.get_nth_curve_function(n) return curve_func(residue) def curve_and_prop_of_partial_point(self, alpha) -> Tuple[int, float]: """ If you want a point a proportion alpha along the curve, this gives you the index of the appropriate bezier curve, together with the proportion along that curve you'd need to travel """ if alpha == 0: return (0, 0.0) partials: list[float] = [0] for tup in self.get_bezier_tuples(): if self.consider_points_equal(tup[0], tup[1]): # Don't consider null curves arclen = 0 else: # Approximate length with straight line from start to end arclen = get_norm(tup[2] - tup[0]) partials.append(partials[-1] + arclen) full = partials[-1] if full == 0: return len(partials), 1.0 # First index where the partial length is more than alpha times the full length index = next( (i for i, x in enumerate(partials) if x >= full * alpha), len(partials) - 1 # Default ) residue = float(inverse_interpolate( partials[index - 1] / full, partials[index] / full, alpha )) return index - 1, residue def point_from_proportion(self, alpha: float) -> Vect3: if alpha <= 0: return self.get_start() elif alpha >= 1: return self.get_end() if self.get_num_points() == 0: return self.get_center() index, residue = self.curve_and_prop_of_partial_point(alpha) return self.get_nth_curve_function(index)(residue) def get_anchors_and_handles(self) -> list[Vect3]: """ returns anchors1, handles, anchors2, where (anchors1[i], handles[i], anchors2[i]) will be three points defining a quadratic bezier curve for any i in range(0, len(anchors1)) """ points = self.get_points() return [points[0:-1:2], points[1::2], points[2::2]] def get_start_anchors(self) -> Vect3Array: return self.get_points()[0:-1:2] def get_end_anchors(self) -> Vect3: return self.get_points()[2::2] def get_anchors(self) -> Vect3Array: return self.get_points()[::2] def get_points_without_null_curves(self, atol: float = 1e-9) -> Vect3Array: new_points = [self.get_points()[0]] for tup in self.get_bezier_tuples(): if get_norm(tup[1] - tup[0]) > atol or get_norm(tup[2] - tup[0]) > atol: new_points.append(tup[1:]) return np.vstack(new_points) def get_arc_length(self, n_sample_points: int | None = None) -> float: if n_sample_points is not None: points = np.array([ self.quick_point_from_proportion(a) for a in np.linspace(0, 1, n_sample_points) ]) return poly_line_length(points)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
true
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/types/image_mobject.py
manimlib/mobject/types/image_mobject.py
from __future__ import annotations import numpy as np import moderngl from PIL import Image from manimlib.constants import DL, DR, UL, UR from manimlib.mobject.mobject import Mobject from manimlib.utils.bezier import inverse_interpolate from manimlib.utils.images import get_full_raster_image_path from manimlib.utils.iterables import listify from manimlib.utils.iterables import resize_with_interpolation from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence, Tuple from manimlib.typing import Vect3 class ImageMobject(Mobject): shader_folder: str = "image" data_dtype: Sequence[Tuple[str, type, Tuple[int]]] = [ ('point', np.float32, (3,)), ('im_coords', np.float32, (2,)), ('opacity', np.float32, (1,)), ] render_primitive: int = moderngl.TRIANGLES def __init__( self, filename: str, height: float = 4.0, **kwargs ): self.height = height self.image_path = get_full_raster_image_path(filename) self.image = Image.open(self.image_path) super().__init__(texture_paths={"Texture": self.image_path}, **kwargs) def init_data(self) -> None: super().init_data(length=6) self.data["point"][:] = [UL, DL, UR, DR, UR, DL] self.data["im_coords"][:] = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 0), (0, 1)] self.data["opacity"][:] = self.opacity def init_points(self) -> None: size = self.image.size self.set_width(2 * size[0] / size[1], stretch=True) self.set_height(self.height) @Mobject.affects_data def set_opacity(self, opacity: float, recurse: bool = True): self.data["opacity"][:, 0] = resize_with_interpolation( np.array(listify(opacity)), self.get_num_points() ) return self def set_color(self, color, opacity=None, recurse=None): return self def point_to_rgb(self, point: Vect3) -> Vect3: x0, y0 = self.get_corner(UL)[:2] x1, y1 = self.get_corner(DR)[:2] x_alpha = inverse_interpolate(x0, x1, point[0]) y_alpha = inverse_interpolate(y0, y1, point[1]) if not (0 <= x_alpha <= 1) and (0 <= y_alpha <= 1): # TODO, raise smarter exception raise Exception("Cannot sample color from outside an image") pw, ph = self.image.size rgb = self.image.getpixel(( int((pw - 1) * x_alpha), int((ph - 1) * y_alpha), ))[:3] return np.array(rgb) / 255
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/types/__init__.py
manimlib/mobject/types/__init__.py
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/types/dot_cloud.py
manimlib/mobject/types/dot_cloud.py
from __future__ import annotations import moderngl import numpy as np from manimlib.constants import GREY_C, YELLOW from manimlib.constants import ORIGIN, NULL_POINTS from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.point_cloud_mobject import PMobject from manimlib.utils.iterables import resize_with_interpolation from typing import TYPE_CHECKING if TYPE_CHECKING: import numpy.typing as npt from typing import Sequence, Tuple from manimlib.typing import ManimColor, Vect3, Vect3Array, Self DEFAULT_DOT_RADIUS = 0.05 DEFAULT_GLOW_DOT_RADIUS = 0.2 DEFAULT_GRID_HEIGHT = 6 DEFAULT_BUFF_RATIO = 0.5 class DotCloud(PMobject): shader_folder: str = "true_dot" render_primitive: int = moderngl.POINTS data_dtype: Sequence[Tuple[str, type, Tuple[int]]] = [ ('point', np.float32, (3,)), ('radius', np.float32, (1,)), ('rgba', np.float32, (4,)), ] def __init__( self, points: Vect3Array = NULL_POINTS, color: ManimColor = GREY_C, opacity: float = 1.0, radius: float = DEFAULT_DOT_RADIUS, glow_factor: float = 0.0, anti_alias_width: float = 2.0, **kwargs ): self.radius = radius self.glow_factor = glow_factor self.anti_alias_width = anti_alias_width super().__init__( color=color, opacity=opacity, **kwargs ) self.set_radius(self.radius) if points is not None: self.set_points(points) def init_uniforms(self) -> None: super().init_uniforms() self.uniforms["glow_factor"] = self.glow_factor self.uniforms["anti_alias_width"] = self.anti_alias_width def to_grid( self, n_rows: int, n_cols: int, n_layers: int = 1, buff_ratio: float | None = None, h_buff_ratio: float = 1.0, v_buff_ratio: float = 1.0, d_buff_ratio: float = 1.0, height: float = DEFAULT_GRID_HEIGHT, ) -> Self: n_points = n_rows * n_cols * n_layers points = np.repeat(range(n_points), 3, axis=0).reshape((n_points, 3)) points[:, 0] = points[:, 0] % n_cols points[:, 1] = (points[:, 1] // n_cols) % n_rows points[:, 2] = points[:, 2] // (n_rows * n_cols) self.set_points(points.astype(float)) if buff_ratio is not None: v_buff_ratio = buff_ratio h_buff_ratio = buff_ratio d_buff_ratio = buff_ratio radius = self.get_radius() ns = [n_cols, n_rows, n_layers] brs = [h_buff_ratio, v_buff_ratio, d_buff_ratio] self.set_radius(0) for n, br, dim in zip(ns, brs, range(3)): self.rescale_to_fit(2 * radius * (1 + br) * (n - 1), dim, stretch=True) self.set_radius(radius) if height is not None: self.set_height(height) self.center() return self @Mobject.affects_data def set_radii(self, radii: npt.ArrayLike) -> Self: n_points = self.get_num_points() radii = np.array(radii).reshape((len(radii), 1)) self.data["radius"][:] = resize_with_interpolation(radii, n_points) self.refresh_bounding_box() return self def get_radii(self) -> np.ndarray: return self.data["radius"] @Mobject.affects_data def set_radius(self, radius: float) -> Self: data = self.data if self.get_num_points() > 0 else self._data_defaults data["radius"][:] = radius self.refresh_bounding_box() return self def get_radius(self) -> float: return self.get_radii().max() def scale_radii(self, scale_factor: float) -> Self: self.set_radius(scale_factor * self.get_radii()) return self def set_glow_factor(self, glow_factor: float) -> Self: self.uniforms["glow_factor"] = glow_factor return self def get_glow_factor(self) -> float: return self.uniforms["glow_factor"] def compute_bounding_box(self) -> Vect3Array: bb = super().compute_bounding_box() radius = self.get_radius() bb[0] += np.full((3,), -radius) bb[2] += np.full((3,), radius) return bb def scale( self, scale_factor: float | npt.ArrayLike, scale_radii: bool = True, **kwargs ) -> Self: super().scale(scale_factor, **kwargs) if scale_radii: self.set_radii(scale_factor * self.get_radii()) return self def make_3d( self, reflectiveness: float = 0.5, gloss: float = 0.1, shadow: float = 0.2 ) -> Self: self.set_shading(reflectiveness, gloss, shadow) self.apply_depth_test() return self class TrueDot(DotCloud): def __init__(self, center: Vect3 = ORIGIN, **kwargs): super().__init__(points=np.array([center]), **kwargs) class GlowDots(DotCloud): def __init__( self, points: Vect3Array = NULL_POINTS, color: ManimColor = YELLOW, radius: float = DEFAULT_GLOW_DOT_RADIUS, glow_factor: float = 2.0, **kwargs, ): super().__init__( points, color=color, radius=radius, glow_factor=glow_factor, **kwargs, ) class GlowDot(GlowDots): def __init__(self, center: Vect3 = ORIGIN, **kwargs): super().__init__(points=np.array([center]), **kwargs)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/types/surface.py
manimlib/mobject/types/surface.py
from __future__ import annotations import moderngl import numpy as np from manimlib.constants import GREY from manimlib.constants import OUT from manimlib.mobject.mobject import Mobject from manimlib.utils.bezier import integer_interpolate from manimlib.utils.bezier import interpolate from manimlib.utils.bezier import inverse_interpolate from manimlib.utils.images import get_full_raster_image_path from manimlib.utils.iterables import listify from manimlib.utils.iterables import resize_with_interpolation from manimlib.utils.simple_functions import clip from manimlib.utils.space_ops import normalize_along_axis from manimlib.utils.space_ops import cross from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Iterable, Sequence, Tuple from manimlib.camera.camera import Camera from manimlib.typing import ManimColor, Vect3, Vect3Array, Self class Surface(Mobject): render_primitive: int = moderngl.TRIANGLES shader_folder: str = "surface" data_dtype: np.dtype = np.dtype([ ('point', np.float32, (3,)), ('d_normal_point', np.float32, (3,)), ('rgba', np.float32, (4,)), ]) pointlike_data_keys = ['point', 'd_normal_point'] def __init__( self, color: ManimColor = GREY, shading: Tuple[float, float, float] = (0.3, 0.2, 0.4), depth_test: bool = True, u_range: Tuple[float, float] = (0.0, 1.0), v_range: Tuple[float, float] = (0.0, 1.0), # Resolution counts number of points sampled, which for # each coordinate is one more than the the number of # rows/columns of approximating squares resolution: Tuple[int, int] = (101, 101), prefered_creation_axis: int = 1, # For du and dv steps. epsilon: float = 1e-3, # Step off the surface to a new point which will # be used to determine the normal direction normal_nudge: float = 1e-3, **kwargs ): self.u_range = u_range self.v_range = v_range self.resolution = resolution self.prefered_creation_axis = prefered_creation_axis self.epsilon = epsilon self.normal_nudge = normal_nudge super().__init__( **kwargs, color=color, shading=shading, depth_test=depth_test, ) self.compute_triangle_indices() def uv_func(self, u: float, v: float) -> tuple[float, float, float]: # To be implemented in subclasses return (u, v, 0.0) @Mobject.affects_data def init_points(self): # Get three lists: # - Points generated by pure uv values # - Those generated by values nudged by du # - Those generated by values nudged by dv nu, nv = self.resolution uv_grid = self.get_uv_grid() uv_plus_du = uv_grid.copy() uv_plus_du[:, :, 0] += self.epsilon uv_plus_dv = uv_grid.copy() uv_plus_dv[:, :, 1] += self.epsilon points, du_points, dv_points = [ np.apply_along_axis( lambda p: self.uv_func(*p), 2, grid ).reshape((nu * nv, self.dim)) for grid in (uv_grid, uv_plus_du, uv_plus_dv) ] crosses = cross(du_points - points, dv_points - points) normals = normalize_along_axis(crosses, 1) self.set_points(points) self.data['d_normal_point'] = points + self.normal_nudge * normals def get_uv_grid(self) -> np.array: """ Returns an (nu, nv, 2) array of all pairs of u, v values, where (nu, nv) is the resolution """ nu, nv = self.resolution u_range = np.linspace(*self.u_range, nu) v_range = np.linspace(*self.v_range, nv) U, V = np.meshgrid(u_range, v_range, indexing='ij') return np.stack([U, V], axis=-1) def uv_to_point(self, u, v): nu, nv = self.resolution verts_by_uv = np.reshape(self.get_points(), (nu, nv, self.dim)) alpha1 = clip(inverse_interpolate(*self.u_range[:2], u), 0, 1) alpha2 = clip(inverse_interpolate(*self.v_range[:2], v), 0, 1) scaled_u = alpha1 * (nu - 1) scaled_v = alpha2 * (nv - 1) u_int = int(scaled_u) v_int = int(scaled_v) u_int_plus = min(u_int + 1, nu - 1) v_int_plus = min(v_int + 1, nv - 1) a = verts_by_uv[u_int, v_int, :] b = verts_by_uv[u_int, v_int_plus, :] c = verts_by_uv[u_int_plus, v_int, :] d = verts_by_uv[u_int_plus, v_int_plus, :] u_res = scaled_u % 1 v_res = scaled_v % 1 return interpolate( interpolate(a, b, v_res), interpolate(c, d, v_res), u_res ) def apply_points_function(self, *args, **kwargs) -> Self: super().apply_points_function(*args, **kwargs) self.get_unit_normals() return self def compute_triangle_indices(self) -> np.ndarray: # TODO, if there is an event which changes # the resolution of the surface, make sure # this is called. nu, nv = self.resolution if nu == 0 or nv == 0: self.triangle_indices = np.zeros(0, dtype=int) return self.triangle_indices index_grid = np.arange(nu * nv).reshape((nu, nv)) indices = np.zeros(6 * (nu - 1) * (nv - 1), dtype=int) indices[0::6] = index_grid[:-1, :-1].flatten() # Top left indices[1::6] = index_grid[+1:, :-1].flatten() # Bottom left indices[2::6] = index_grid[:-1, +1:].flatten() # Top right indices[3::6] = index_grid[:-1, +1:].flatten() # Top right indices[4::6] = index_grid[+1:, :-1].flatten() # Bottom left indices[5::6] = index_grid[+1:, +1:].flatten() # Bottom right self.triangle_indices = indices return self.triangle_indices def get_triangle_indices(self) -> np.ndarray: return self.triangle_indices def get_unit_normals(self) -> Vect3Array: # TOOD, I could try a more resiliant way to compute this using the neighboring grid values return normalize_along_axis(self.data['d_normal_point'] - self.data['point'], 1) @Mobject.affects_data def pointwise_become_partial( self, smobject: "Surface", a: float, b: float, axis: int | None = None ) -> Self: assert isinstance(smobject, Surface) if axis is None: axis = self.prefered_creation_axis if a <= 0 and b >= 1: self.match_points(smobject) return self nu, nv = smobject.resolution self.data['point'][:] = self.get_partial_points_array( smobject.data['point'], a, b, (nu, nv, 3), axis=axis ) return self def get_partial_points_array( self, points: Vect3Array, a: float, b: float, resolution: Sequence[int], axis: int ) -> Vect3Array: if len(points) == 0: return points nu, nv = resolution[:2] points = points.reshape(resolution).copy() max_index = resolution[axis] - 1 lower_index, lower_residue = integer_interpolate(0, max_index, a) upper_index, upper_residue = integer_interpolate(0, max_index, b) if axis == 0: points[:lower_index] = interpolate( points[lower_index], points[lower_index + 1], lower_residue ) points[upper_index + 1:] = interpolate( points[upper_index], points[upper_index + 1], upper_residue ) else: shape = (nu, 1, resolution[2]) points[:, :lower_index] = interpolate( points[:, lower_index], points[:, lower_index + 1], lower_residue ).reshape(shape) points[:, upper_index + 1:] = interpolate( points[:, upper_index], points[:, upper_index + 1], upper_residue ).reshape(shape) return points.reshape((nu * nv, *resolution[2:])) @Mobject.affects_data def sort_faces_back_to_front(self, vect: Vect3 = OUT) -> Self: tri_is = self.triangle_indices points = self.get_points() dots = (points[tri_is[::3]] * vect).sum(1) indices = np.argsort(dots) for k in range(3): tri_is[k::3] = tri_is[k::3][indices] return self def always_sort_to_camera(self, camera: Camera) -> Self: def updater(surface: Surface): vect = camera.get_location() - surface.get_center() surface.sort_faces_back_to_front(vect) self.add_updater(updater) return self def color_by_uv_function(self, uv_to_color: Callable[[Vect2], Color]): uv_grid = self.get_uv_grid() self.set_rgba_array_by_color([ uv_to_color(u, v) for u, v in uv_grid.reshape(-1, 2) ]) return self def get_shader_vert_indices(self) -> np.ndarray: return self.get_triangle_indices() class ParametricSurface(Surface): def __init__( self, uv_func: Callable[[float, float], Iterable[float]], u_range: tuple[float, float] = (0, 1), v_range: tuple[float, float] = (0, 1), **kwargs ): self.passed_uv_func = uv_func super().__init__(u_range=u_range, v_range=v_range, **kwargs) def uv_func(self, u, v): return self.passed_uv_func(u, v) class SGroup(Surface): def __init__( self, *parametric_surfaces: Surface, **kwargs ): super().__init__(resolution=(0, 0), **kwargs) self.add(*parametric_surfaces) def init_points(self): pass # Needed? class TexturedSurface(Surface): shader_folder: str = "textured_surface" data_dtype: Sequence[Tuple[str, type, Tuple[int]]] = [ ('point', np.float32, (3,)), ('d_normal_point', np.float32, (3,)), ('im_coords', np.float32, (2,)), ('opacity', np.float32, (1,)), ] def __init__( self, uv_surface: Surface, image_file: str, dark_image_file: str | None = None, **kwargs ): if not isinstance(uv_surface, Surface): raise Exception("uv_surface must be of type Surface") # Set texture information if dark_image_file is None: dark_image_file = image_file self.num_textures = 1 else: self.num_textures = 2 texture_paths = { "LightTexture": get_full_raster_image_path(image_file), "DarkTexture": get_full_raster_image_path(dark_image_file), } self.uv_surface = uv_surface self.uv_func = uv_surface.uv_func self.u_range: Tuple[float, float] = uv_surface.u_range self.v_range: Tuple[float, float] = uv_surface.v_range self.resolution: Tuple[int, int] = uv_surface.resolution super().__init__( texture_paths=texture_paths, shading=tuple(uv_surface.shading), **kwargs ) @Mobject.affects_data def init_points(self): surf = self.uv_surface nu, nv = surf.resolution self.resize_points(surf.get_num_points()) self.resolution = surf.resolution self.data['point'][:] = surf.data['point'] self.data['d_normal_point'][:] = surf.data['d_normal_point'] self.data['opacity'][:, 0] = surf.data["rgba"][:, 3] self.data["im_coords"] = np.array([ [u, v] for u in np.linspace(0, 1, nu) for v in np.linspace(1, 0, nv) # Reverse y-direction ]) def init_uniforms(self): super().init_uniforms() self.uniforms["num_textures"] = self.num_textures @Mobject.affects_data def set_opacity(self, opacity: float | Iterable[float], recurse=True) -> Self: op_arr = np.array(listify(opacity)) self.data["opacity"][:, 0] = resize_with_interpolation(op_arr, len(self.data)) return self def set_color( self, color: ManimColor | Iterable[ManimColor] | None, opacity: float | Iterable[float] | None = None, recurse: bool = True ) -> Self: if opacity is not None: self.set_opacity(opacity) return self def pointwise_become_partial( self, tsmobject: "TexturedSurface", a: float, b: float, axis: int = 1 ) -> Self: super().pointwise_become_partial(tsmobject, a, b, axis) im_coords = self.data["im_coords"] im_coords[:] = tsmobject.data["im_coords"] if a <= 0 and b >= 1: return self nu, nv = tsmobject.resolution im_coords[:] = self.get_partial_points_array( im_coords, a, b, (nu, nv, 2), axis ) return self
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/svg/tex_mobject.py
manimlib/mobject/svg/tex_mobject.py
from __future__ import annotations import re from pathlib import Path from manimlib.mobject.svg.string_mobject import StringMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.color import color_to_hex from manimlib.utils.color import hex_to_int from manimlib.utils.tex_file_writing import latex_to_svg from manimlib.utils.tex import num_tex_symbols from manimlib.logger import log from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor, Span, Selector, Self TEX_MOB_SCALE_FACTOR = 0.001 class Tex(StringMobject): tex_environment: str = "align*" def __init__( self, *tex_strings: str, font_size: int = 48, alignment: str = R"\centering", template: str = "", additional_preamble: str = "", tex_to_color_map: dict = dict(), t2c: dict = dict(), isolate: Selector = [], use_labelled_svg: bool = True, **kwargs ): # Combine multi-string arg, but mark them to isolate if len(tex_strings) > 1: if isinstance(isolate, (str, re.Pattern, tuple)): isolate = [isolate] isolate = [*isolate, *tex_strings] tex_string = (" ".join(tex_strings)).strip() # Prevent from passing an empty string. if not tex_string.strip(): tex_string = R"\\" self.tex_string = tex_string self.alignment = alignment self.template = template self.additional_preamble = additional_preamble self.tex_to_color_map = dict(**t2c, **tex_to_color_map) super().__init__( tex_string, use_labelled_svg=use_labelled_svg, isolate=isolate, **kwargs ) self.set_color_by_tex_to_color_map(self.tex_to_color_map) self.scale(TEX_MOB_SCALE_FACTOR * font_size) self.font_size = font_size # Important for this to go after the scale call def get_svg_string_by_content(self, content: str) -> str: return latex_to_svg(content, self.template, self.additional_preamble, short_tex=self.tex_string) def _handle_scale_side_effects(self, scale_factor: float) -> Self: if hasattr(self, "font_size"): self.font_size *= scale_factor return self # Parsing @staticmethod def get_command_matches(string: str) -> list[re.Match]: # Lump together adjacent brace pairs pattern = re.compile(r""" (?P<command>\\(?:[a-zA-Z]+|.)) |(?P<open>{+) |(?P<close>}+) """, flags=re.X | re.S) result = [] open_stack = [] for match_obj in pattern.finditer(string): if match_obj.group("open"): open_stack.append((match_obj.span(), len(result))) elif match_obj.group("close"): close_start, close_end = match_obj.span() while True: if not open_stack: raise ValueError("Missing '{' inserted") (open_start, open_end), index = open_stack.pop() n = min(open_end - open_start, close_end - close_start) result.insert(index, pattern.fullmatch( string, pos=open_end - n, endpos=open_end )) result.append(pattern.fullmatch( string, pos=close_start, endpos=close_start + n )) close_start += n if close_start < close_end: continue open_end -= n if open_start < open_end: open_stack.append(((open_start, open_end), index)) break else: result.append(match_obj) if open_stack: raise ValueError("Missing '}' inserted") return result @staticmethod def get_command_flag(match_obj: re.Match) -> int: if match_obj.group("open"): return 1 if match_obj.group("close"): return -1 return 0 @staticmethod def replace_for_content(match_obj: re.Match) -> str: return match_obj.group() @staticmethod def replace_for_matching(match_obj: re.Match) -> str: if match_obj.group("command"): return match_obj.group() return "" @staticmethod def get_attr_dict_from_command_pair( open_command: re.Match, close_command: re.Match ) -> dict[str, str] | None: if len(open_command.group()) >= 2: return {} return None def get_configured_items(self) -> list[tuple[Span, dict[str, str]]]: return [ (span, {}) for selector in self.tex_to_color_map for span in self.find_spans_by_selector(selector) ] @staticmethod def get_color_command(rgb_hex: str) -> str: rgb = hex_to_int(rgb_hex) rg, b = divmod(rgb, 256) r, g = divmod(rg, 256) return f"\\color[RGB]{{{r}, {g}, {b}}}" @staticmethod def get_command_string( attr_dict: dict[str, str], is_end: bool, label_hex: str | None ) -> str: if label_hex is None: return "" if is_end: return "}}" return "{{" + Tex.get_color_command(label_hex) def get_content_prefix_and_suffix( self, is_labelled: bool ) -> tuple[str, str]: prefix_lines = [] suffix_lines = [] if not is_labelled: prefix_lines.append(self.get_color_command( color_to_hex(self.base_color) )) if self.alignment: prefix_lines.append(self.alignment) if self.tex_environment: prefix_lines.append(f"\\begin{{{self.tex_environment}}}") suffix_lines.append(f"\\end{{{self.tex_environment}}}") return ( "".join([line + "\n" for line in prefix_lines]), "".join(["\n" + line for line in suffix_lines]) ) # Method alias def get_parts_by_tex(self, selector: Selector) -> VGroup: return self.select_parts(selector) def get_part_by_tex(self, selector: Selector, index: int = 0) -> VMobject: return self.select_part(selector, index) def set_color_by_tex(self, selector: Selector, color: ManimColor): return self.set_parts_color(selector, color) def set_color_by_tex_to_color_map( self, color_map: dict[Selector, ManimColor] ): return self.set_parts_color_by_dict(color_map) def get_tex(self) -> str: return self.get_string() # Specific to Tex def substr_to_path_count(self, substr: str) -> int: tex = self.get_tex() if len(self) != num_tex_symbols(tex): log.warning(f"Estimated size of {tex} does not match true size") return num_tex_symbols(substr) def get_symbol_substrings(self): pattern = "|".join(( # Tex commands r"\\[a-zA-Z]+", # And most single characters, with these exceptions r"[^\^\{\}\s\_\$\\\&]", )) return re.findall(pattern, self.string) def make_number_changeable( self, value: float | int | str, index: int = 0, replace_all: bool = False, **config, ) -> VMobject: substr = str(value) parts = self.select_parts(substr) if len(parts) == 0: log.warning(f"{value} not found in Tex.make_number_changeable call") return VMobject() if index > len(parts) - 1: log.warning(f"Requested {index}th occurance of {value}, but only {len(parts)} exist") return VMobject() if not replace_all: parts = [parts[index]] from manimlib.mobject.numbers import DecimalNumber decimal_mobs = [] for part in parts: if "num_decimal_places" not in config: ndp = len(substr.split(".")[1]) if "." in substr else 0 config["num_decimal_places"] = ndp decimal_mob = DecimalNumber(float(value), **config) decimal_mob.replace(part) decimal_mob.match_style(part) if len(part) > 1: self.remove(*part[1:]) self.replace_submobject(self.submobjects.index(part[0]), decimal_mob) decimal_mobs.append(decimal_mob) # Replace substr with something that looks like a tex command. This # is to ensure Tex.substr_to_path_count counts it correctly. self.string = self.string.replace(substr, R"\decimalmob", 1) if replace_all: return VGroup(*decimal_mobs) return decimal_mobs[index] class TexText(Tex): tex_environment: str = ""
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/svg/text_mobject.py
manimlib/mobject/svg/text_mobject.py
from __future__ import annotations from contextlib import contextmanager import os from pathlib import Path import re import tempfile from functools import lru_cache import manimpango import pygments import pygments.formatters import pygments.lexers from manimlib.config import manim_config from manimlib.constants import DEFAULT_PIXEL_WIDTH, FRAME_WIDTH from manimlib.constants import NORMAL from manimlib.logger import log from manimlib.mobject.svg.string_mobject import StringMobject from manimlib.utils.cache import cache_on_disk from manimlib.utils.color import color_to_hex from manimlib.utils.color import int_to_hex from manimlib.utils.simple_functions import hash_string from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.typing import ManimColor, Span, Selector TEXT_MOB_SCALE_FACTOR = 0.0076 DEFAULT_LINE_SPACING_SCALE = 0.6 # Ensure the canvas is large enough to hold all glyphs. DEFAULT_CANVAS_WIDTH = 16384 DEFAULT_CANVAS_HEIGHT = 16384 # Temporary handler class _Alignment: VAL_DICT = { "LEFT": 0, "CENTER": 1, "RIGHT": 2 } def __init__(self, s: str): self.value = _Alignment.VAL_DICT[s.upper()] @lru_cache(maxsize=128) @cache_on_disk def markup_to_svg( markup_str: str, justify: bool = False, indent: float = 0, alignment: str = "CENTER", line_width: float | None = None, ) -> str: validate_error = manimpango.MarkupUtils.validate(markup_str) if validate_error: raise ValueError( f"Invalid markup string \"{markup_str}\"\n" + \ f"{validate_error}" ) # `manimpango` is under construction, # so the following code is intended to suit its interface alignment = _Alignment(alignment) if line_width is None: pango_width = -1 else: pango_width = line_width / FRAME_WIDTH * DEFAULT_PIXEL_WIDTH # Write the result to a temporary svg file, and return it's contents. temp_file = Path(tempfile.gettempdir(), hash_string(markup_str)).with_suffix(".svg") manimpango.MarkupUtils.text2svg( text=markup_str, font="", # Already handled slant="NORMAL", # Already handled weight="NORMAL", # Already handled size=1, # Already handled _=0, # Empty parameter disable_liga=False, file_name=str(temp_file), START_X=0, START_Y=0, width=DEFAULT_CANVAS_WIDTH, height=DEFAULT_CANVAS_HEIGHT, justify=justify, indent=indent, line_spacing=None, # Already handled alignment=alignment, pango_width=pango_width ) result = temp_file.read_text() os.remove(temp_file) return result class MarkupText(StringMobject): # See https://docs.gtk.org/Pango/pango_markup.html MARKUP_TAGS = { "b": {"font_weight": "bold"}, "big": {"font_size": "larger"}, "i": {"font_style": "italic"}, "s": {"strikethrough": "true"}, "sub": {"baseline_shift": "subscript", "font_scale": "subscript"}, "sup": {"baseline_shift": "superscript", "font_scale": "superscript"}, "small": {"font_size": "smaller"}, "tt": {"font_family": "monospace"}, "u": {"underline": "single"}, } MARKUP_ENTITY_DICT = { "<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;", "'": "&apos;" } def __init__( self, text: str, font_size: int = 48, height: float | None = None, justify: bool = False, indent: float = 0, alignment: str = "", line_width: float | None = None, font: str = "", slant: str = NORMAL, weight: str = NORMAL, gradient: Iterable[ManimColor] | None = None, line_spacing_height: float | None = None, text2color: dict = {}, text2font: dict = {}, text2gradient: dict = {}, text2slant: dict = {}, text2weight: dict = {}, # For convenience, one can use shortened names lsh: float | None = None, # Overrides line_spacing_height t2c: dict = {}, # Overrides text2color if nonempty t2f: dict = {}, # Overrides text2font if nonempty t2g: dict = {}, # Overrides text2gradient if nonempty t2s: dict = {}, # Overrides text2slant if nonempty t2w: dict = {}, # Overrides text2weight if nonempty global_config: dict = {}, local_configs: dict = {}, disable_ligatures: bool = True, isolate: Selector = re.compile(r"\w+", re.U), **kwargs ): text_config = manim_config.text self.text = text self.font_size = font_size self.justify = justify self.indent = indent self.alignment = alignment or text_config.alignment self.line_width = line_width self.font = font or text_config.font self.slant = slant self.weight = weight self.lsh = line_spacing_height or lsh self.t2c = text2color or t2c self.t2f = text2font or t2f self.t2g = text2gradient or t2g self.t2s = text2slant or t2s self.t2w = text2weight or t2w self.global_config = global_config self.local_configs = local_configs self.disable_ligatures = disable_ligatures self.isolate = isolate super().__init__(text, height=height, **kwargs) if self.t2g: log.warning(""" Manim currently cannot parse gradient from svg. Please set gradient via `set_color_by_gradient`. """) if gradient: self.set_color_by_gradient(*gradient) if self.t2c: self.set_color_by_text_to_color_map(self.t2c) if height is None: self.scale(TEXT_MOB_SCALE_FACTOR) def get_svg_string_by_content(self, content: str) -> str: self.content = content return markup_to_svg( content, justify=self.justify, indent=self.indent, alignment=self.alignment, line_width=self.line_width ) # Toolkits @staticmethod def escape_markup_char(substr: str) -> str: return MarkupText.MARKUP_ENTITY_DICT.get(substr, substr) @staticmethod def unescape_markup_char(substr: str) -> str: return { v: k for k, v in MarkupText.MARKUP_ENTITY_DICT.items() }.get(substr, substr) # Parsing @staticmethod def get_command_matches(string: str) -> list[re.Match]: pattern = re.compile(r""" (?P<tag> < (?P<close_slash>/)? (?P<tag_name>\w+)\s* (?P<attr_list>(?:\w+\s*\=\s*(?P<quot>["']).*?(?P=quot)\s*)*) (?P<elision_slash>/)? > ) |(?P<passthrough> <\?.*?\?>|<!--.*?-->|<!\[CDATA\[.*?\]\]>|<!DOCTYPE.*?> ) |(?P<entity>&(?P<unicode>\#(?P<hex>x)?)?(?P<content>.*?);) |(?P<char>[>"']) """, flags=re.X | re.S) return list(pattern.finditer(string)) @staticmethod def get_command_flag(match_obj: re.Match) -> int: if match_obj.group("tag"): if match_obj.group("close_slash"): return -1 if not match_obj.group("elision_slash"): return 1 return 0 @staticmethod def replace_for_content(match_obj: re.Match) -> str: if match_obj.group("tag"): return "" if match_obj.group("char"): return MarkupText.escape_markup_char(match_obj.group("char")) return match_obj.group() @staticmethod def replace_for_matching(match_obj: re.Match) -> str: if match_obj.group("tag") or match_obj.group("passthrough"): return "" if match_obj.group("entity"): if match_obj.group("unicode"): base = 10 if match_obj.group("hex"): base = 16 return chr(int(match_obj.group("content"), base)) return MarkupText.unescape_markup_char(match_obj.group("entity")) return match_obj.group() @staticmethod def get_attr_dict_from_command_pair( open_command: re.Match, close_command: re.Match ) -> dict[str, str] | None: pattern = r""" (?P<attr_name>\w+) \s*\=\s* (?P<quot>["'])(?P<attr_val>.*?)(?P=quot) """ tag_name = open_command.group("tag_name") if tag_name == "span": return { match_obj.group("attr_name"): match_obj.group("attr_val") for match_obj in re.finditer( pattern, open_command.group("attr_list"), re.S | re.X ) } return MarkupText.MARKUP_TAGS.get(tag_name, {}) def get_configured_items(self) -> list[tuple[Span, dict[str, str]]]: return [ *( (span, {key: val}) for t2x_dict, key in ( (self.t2c, "foreground"), (self.t2f, "font_family"), (self.t2s, "font_style"), (self.t2w, "font_weight") ) for selector, val in t2x_dict.items() for span in self.find_spans_by_selector(selector) ), *( (span, local_config) for selector, local_config in self.local_configs.items() for span in self.find_spans_by_selector(selector) ) ] @staticmethod def get_command_string( attr_dict: dict[str, str], is_end: bool, label_hex: str | None ) -> str: if is_end: return "</span>" if label_hex is not None: converted_attr_dict = {"foreground": label_hex} for key, val in attr_dict.items(): if key in ( "background", "bgcolor", "underline_color", "overline_color", "strikethrough_color" ): converted_attr_dict[key] = "black" elif key not in ("foreground", "fgcolor", "color"): converted_attr_dict[key] = val else: converted_attr_dict = attr_dict.copy() attrs_str = " ".join([ f"{key}='{val}'" for key, val in converted_attr_dict.items() ]) return f"<span {attrs_str}>" def get_content_prefix_and_suffix( self, is_labelled: bool ) -> tuple[str, str]: global_attr_dict = { "foreground": color_to_hex(self.base_color), "font_family": self.font, "font_style": self.slant, "font_weight": self.weight, "font_size": str(round(self.font_size * 1024)), } # `line_height` attribute is supported since Pango 1.50. pango_version = manimpango.pango_version() if tuple(map(int, pango_version.split("."))) < (1, 50): if self.lsh is not None: log.warning( "Pango version %s found (< 1.50), " "unable to set `line_height` attribute", pango_version ) else: line_spacing_scale = self.lsh or DEFAULT_LINE_SPACING_SCALE global_attr_dict["line_height"] = str( ((line_spacing_scale) + 1) * 0.6 ) if self.disable_ligatures: global_attr_dict["font_features"] = "liga=0,dlig=0,clig=0,hlig=0" global_attr_dict.update(self.global_config) return tuple( self.get_command_string( global_attr_dict, is_end=is_end, label_hex=int_to_hex(0) if is_labelled else None ) for is_end in (False, True) ) # Method alias def get_parts_by_text(self, selector: Selector) -> VGroup: return self.select_parts(selector) def get_part_by_text(self, selector: Selector, **kwargs) -> VGroup: return self.select_part(selector, **kwargs) def set_color_by_text(self, selector: Selector, color: ManimColor): return self.set_parts_color(selector, color) def set_color_by_text_to_color_map( self, color_map: dict[Selector, ManimColor] ): return self.set_parts_color_by_dict(color_map) def get_text(self) -> str: return self.get_string() class Text(MarkupText): def __init__( self, text: str, # For backward compatibility isolate: Selector = (re.compile(r"\w+", re.U), re.compile(r"\S+", re.U)), use_labelled_svg: bool = True, path_string_config: dict = dict( use_simple_quadratic_approx=True, ), **kwargs ): super().__init__( text, isolate=isolate, use_labelled_svg=use_labelled_svg, path_string_config=path_string_config, **kwargs ) @staticmethod def get_command_matches(string: str) -> list[re.Match]: pattern = re.compile(r"""[<>&"']""") return list(pattern.finditer(string)) @staticmethod def get_command_flag(match_obj: re.Match) -> int: return 0 @staticmethod def replace_for_content(match_obj: re.Match) -> str: return Text.escape_markup_char(match_obj.group()) @staticmethod def replace_for_matching(match_obj: re.Match) -> str: return match_obj.group() class Code(MarkupText): def __init__( self, code: str, font: str = "Consolas", font_size: int = 24, lsh: float = 1.0, fill_color: ManimColor = None, stroke_color: ManimColor = None, language: str = "python", # Visit https://pygments.org/demo/ to have a preview of more styles. code_style: str = "monokai", **kwargs ): lexer = pygments.lexers.get_lexer_by_name(language) formatter = pygments.formatters.PangoMarkupFormatter( style=code_style ) markup = pygments.highlight(code, lexer, formatter) markup = re.sub(r"</?tt>", "", markup) super().__init__( markup, font=font, font_size=font_size, lsh=lsh, stroke_color=stroke_color, fill_color=fill_color, **kwargs ) @contextmanager def register_font(font_file: str | Path): """Temporarily add a font file to Pango's search path. This searches for the font_file at various places. The order it searches it described below. 1. Absolute path. 2. Downloads dir. Parameters ---------- font_file : The font file to add. Examples -------- Use ``with register_font(...)`` to add a font file to search path. .. code-block:: python with register_font("path/to/font_file.ttf"): a = Text("Hello", font="Custom Font Name") Raises ------ FileNotFoundError: If the font doesn't exists. AttributeError: If this method is used on macOS. Notes ----- This method of adding font files also works with :class:`CairoText`. .. important :: This method is available for macOS for ``ManimPango>=v0.2.3``. Using this method with previous releases will raise an :class:`AttributeError` on macOS. """ file_path = Path(font_file).resolve() if not file_path.exists(): error = f"Can't find {font_file}." raise FileNotFoundError(error) try: assert manimpango.register_font(str(file_path)) yield finally: manimpango.unregister_font(str(file_path))
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/svg/special_tex.py
manimlib/mobject/svg/special_tex.py
from __future__ import annotations from manimlib.constants import MED_SMALL_BUFF, DEFAULT_MOBJECT_COLOR, GREY_C from manimlib.constants import DOWN, LEFT, RIGHT, UP from manimlib.constants import FRAME_WIDTH from manimlib.constants import MED_LARGE_BUFF, SMALL_BUFF from manimlib.mobject.geometry import Line from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.svg.tex_mobject import TexText from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor, Vect3 class BulletedList(VGroup): def __init__( self, *items: str, buff: float = MED_LARGE_BUFF, aligned_edge: Vect3 = LEFT, **kwargs ): labelled_content = [R"\item " + item for item in items] tex_string = "\n".join([ R"\begin{itemize}", *labelled_content, R"\end{itemize}" ]) tex_text = TexText(tex_string, isolate=labelled_content, **kwargs) lines = (tex_text.select_part(part) for part in labelled_content) super().__init__(*lines) self.arrange(DOWN, buff=buff, aligned_edge=aligned_edge) def fade_all_but(self, index: int, opacity: float = 0.25, scale_factor=0.7) -> None: max_dot_height = max([item[0].get_height() for item in self.submobjects]) for i, part in enumerate(self.submobjects): trg_dot_height = (1.0 if i == index else scale_factor) * max_dot_height part.set_fill(opacity=(1.0 if i == index else opacity)) part.scale(trg_dot_height / part[0].get_height(), about_edge=LEFT) class TexTextFromPresetString(TexText): tex: str = "" default_color: ManimColor = DEFAULT_MOBJECT_COLOR def __init__(self, **kwargs): super().__init__( self.tex, color=kwargs.pop("color", self.default_color), **kwargs ) class Title(TexText): def __init__( self, *text_parts: str, font_size: int = 72, include_underline: bool = True, underline_width: float = FRAME_WIDTH - 2, # This will override underline_width match_underline_width_to_text: bool = False, underline_buff: float = SMALL_BUFF, underline_style: dict = dict(stroke_width=2, stroke_color=GREY_C), **kwargs ): super().__init__(*text_parts, font_size=font_size, **kwargs) self.to_edge(UP, buff=MED_SMALL_BUFF) if include_underline: underline = Line(LEFT, RIGHT, **underline_style) underline.next_to(self, DOWN, buff=underline_buff) if match_underline_width_to_text: underline.match_width(self) else: underline.set_width(underline_width) self.add(underline) self.underline = underline
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/svg/drawings.py
manimlib/mobject/svg/drawings.py
from __future__ import annotations import numpy as np import itertools as it import random from manimlib.animation.composition import AnimationGroup from manimlib.animation.rotation import Rotating from manimlib.constants import BLACK from manimlib.constants import BLUE_A from manimlib.constants import BLUE_B from manimlib.constants import BLUE_C from manimlib.constants import BLUE_D from manimlib.constants import DOWN from manimlib.constants import DOWN from manimlib.constants import FRAME_WIDTH from manimlib.constants import GREEN from manimlib.constants import GREEN_SCREEN from manimlib.constants import GREEN_E from manimlib.constants import GREY from manimlib.constants import GREY_A from manimlib.constants import GREY_B from manimlib.constants import GREY_E from manimlib.constants import LEFT from manimlib.constants import LEFT from manimlib.constants import MED_LARGE_BUFF from manimlib.constants import MED_SMALL_BUFF from manimlib.constants import ORIGIN from manimlib.constants import OUT from manimlib.constants import PI from manimlib.constants import RED from manimlib.constants import RED_E from manimlib.constants import RIGHT from manimlib.constants import SMALL_BUFF from manimlib.constants import SMALL_BUFF from manimlib.constants import UP from manimlib.constants import UL from manimlib.constants import UR from manimlib.constants import DL from manimlib.constants import DR from manimlib.constants import WHITE from manimlib.constants import YELLOW from manimlib.constants import TAU from manimlib.mobject.boolean_ops import Difference from manimlib.mobject.boolean_ops import Union from manimlib.mobject.geometry import Arc from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Dot from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Polygon from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import Square from manimlib.mobject.geometry import AnnularSector from manimlib.mobject.numbers import Integer from manimlib.mobject.shape_matchers import SurroundingRectangle from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.svg.special_tex import TexTextFromPresetString from manimlib.mobject.three_dimensions import Prismify from manimlib.mobject.three_dimensions import VCube from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.svg.text_mobject import Text from manimlib.utils.bezier import interpolate from manimlib.utils.iterables import adjacent_pairs from manimlib.utils.rate_functions import linear from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import compass_directions from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import midpoint from manimlib.utils.space_ops import rotate_vector from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Tuple, Sequence, Callable from manimlib.typing import ManimColor, Vect3 class Checkmark(TexTextFromPresetString): tex: str = R"\ding{51}" default_color: ManimColor = GREEN class Exmark(TexTextFromPresetString): tex: str = R"\ding{55}" default_color: ManimColor = RED class Lightbulb(SVGMobject): file_name = "lightbulb" def __init__( self, height: float = 1.0, color: ManimColor = YELLOW, stroke_width: float = 3.0, fill_opacity: float = 0.0, **kwargs ): super().__init__( height=height, color=color, stroke_width=stroke_width, fill_opacity=fill_opacity, **kwargs ) self.insert_n_curves(25) class Speedometer(VMobject): def __init__( self, arc_angle: float = 4 * PI / 3, num_ticks: int = 8, tick_length: float = 0.2, needle_width: float = 0.1, needle_height: float = 0.8, needle_color: ManimColor = YELLOW, **kwargs, ): super().__init__(**kwargs) self.arc_angle = arc_angle self.num_ticks = num_ticks self.tick_length = tick_length self.needle_width = needle_width self.needle_height = needle_height self.needle_color = needle_color start_angle = PI / 2 + arc_angle / 2 end_angle = PI / 2 - arc_angle / 2 self.arc = Arc( start_angle=start_angle, angle=-self.arc_angle ) self.add(self.arc) tick_angle_range = np.linspace(start_angle, end_angle, num_ticks) for index, angle in enumerate(tick_angle_range): vect = rotate_vector(RIGHT, angle) tick = Line((1 - tick_length) * vect, vect) label = Integer(10 * index) label.set_height(tick_length) label.shift((1 + tick_length) * vect) self.add(tick, label) needle = Polygon( LEFT, UP, RIGHT, stroke_width=0, fill_opacity=1, fill_color=self.needle_color ) needle.stretch_to_fit_width(needle_width) needle.stretch_to_fit_height(needle_height) needle.rotate(start_angle - np.pi / 2, about_point=ORIGIN) self.add(needle) self.needle = needle self.center_offset = self.get_center() def get_center(self): result = VMobject.get_center(self) if hasattr(self, "center_offset"): result -= self.center_offset return result def get_needle_tip(self): return self.needle.get_anchors()[1] def get_needle_angle(self): return angle_of_vector( self.get_needle_tip() - self.get_center() ) def rotate_needle(self, angle): self.needle.rotate(angle, about_point=self.arc.get_arc_center()) return self def move_needle_to_velocity(self, velocity): max_velocity = 10 * (self.num_ticks - 1) proportion = float(velocity) / max_velocity start_angle = np.pi / 2 + self.arc_angle / 2 target_angle = start_angle - self.arc_angle * proportion self.rotate_needle(target_angle - self.get_needle_angle()) return self class Laptop(VGroup): def __init__( self, width: float = 3, body_dimensions: Tuple[float, float, float] = (4.0, 3.0, 0.05), screen_thickness: float = 0.01, keyboard_width_to_body_width: float = 0.9, keyboard_height_to_body_height: float = 0.5, screen_width_to_screen_plate_width: float = 0.9, key_color_kwargs: dict = dict( stroke_width=0, fill_color=BLACK, fill_opacity=1, ), fill_opacity: float = 1.0, stroke_width: float = 0.0, body_color: ManimColor = GREY_B, shaded_body_color: ManimColor = GREY, open_angle: float = np.pi / 4, **kwargs ): super().__init__(**kwargs) body = VCube(side_length=1) for dim, scale_factor in enumerate(body_dimensions): body.stretch(scale_factor, dim=dim) body.set_width(width) body.set_fill(shaded_body_color, opacity=1) body.sort(lambda p: p[2]) body[-1].set_fill(body_color) screen_plate = body.copy() keyboard = VGroup(*[ VGroup(*[ Square(**key_color_kwargs) for x in range(12 - y % 2) ]).arrange(RIGHT, buff=SMALL_BUFF) for y in range(4) ]).arrange(DOWN, buff=MED_SMALL_BUFF) keyboard.stretch_to_fit_width( keyboard_width_to_body_width * body.get_width(), ) keyboard.stretch_to_fit_height( keyboard_height_to_body_height * body.get_height(), ) keyboard.next_to(body, OUT, buff=0.1 * SMALL_BUFF) keyboard.shift(MED_SMALL_BUFF * UP) body.add(keyboard) screen_plate.stretch(screen_thickness / body_dimensions[2], dim=2) screen = Rectangle( stroke_width=0, fill_color=BLACK, fill_opacity=1, ) screen.replace(screen_plate, stretch=True) screen.scale(screen_width_to_screen_plate_width) screen.next_to(screen_plate, OUT, buff=0.1 * SMALL_BUFF) screen_plate.add(screen) screen_plate.next_to(body, UP, buff=0) screen_plate.rotate( open_angle, RIGHT, about_point=screen_plate.get_bottom() ) self.screen_plate = screen_plate self.screen = screen axis = Line( body.get_corner(UP + LEFT + OUT), body.get_corner(UP + RIGHT + OUT), color=BLACK, stroke_width=2 ) self.axis = axis self.add(body, screen_plate, axis) class VideoIcon(SVGMobject): file_name: str = "video_icon" def __init__( self, width: float = 1.2, color=BLUE_A, **kwargs ): super().__init__(color=color, **kwargs) self.set_width(width) class VideoSeries(VGroup): def __init__( self, num_videos: int = 11, gradient_colors: Sequence[ManimColor] = [BLUE_B, BLUE_D], width: float = FRAME_WIDTH - MED_LARGE_BUFF, **kwargs ): super().__init__( *(VideoIcon() for x in range(num_videos)), **kwargs ) self.arrange(RIGHT) self.set_width(width) self.set_color_by_gradient(*gradient_colors) class Clock(VGroup): def __init__( self, stroke_color: ManimColor = WHITE, stroke_width: float = 3.0, hour_hand_height: float = 0.3, minute_hand_height: float = 0.6, tick_length: float = 0.1, **kwargs, ): style = dict(stroke_color=stroke_color, stroke_width=stroke_width) circle = Circle(**style) ticks = [] for x, point in enumerate(compass_directions(12, UP)): length = tick_length if x % 3 == 0: length *= 2 ticks.append(Line(point, (1 - length) * point, **style)) self.hour_hand = Line(ORIGIN, hour_hand_height * UP, **style) self.minute_hand = Line(ORIGIN, minute_hand_height * UP, **style) super().__init__( circle, self.hour_hand, self.minute_hand, *ticks ) class ClockPassesTime(AnimationGroup): def __init__( self, clock: Clock, run_time: float = 5.0, hours_passed: float = 12.0, rate_func: Callable[[float], float] = linear, **kwargs ): rot_kwargs = dict( axis=OUT, about_point=clock.get_center() ) hour_radians = -hours_passed * 2 * PI / 12 super().__init__( Rotating( clock.hour_hand, angle=hour_radians, **rot_kwargs ), Rotating( clock.minute_hand, angle=12 * hour_radians, **rot_kwargs ), group=clock, run_time=run_time, **kwargs ) class Bubble(VGroup): file_name: str = "Bubbles_speech.svg" bubble_center_adjustment_factor = 0.125 def __init__( self, content: str | VMobject | None = None, buff: float = 1.0, filler_shape: Tuple[float, float] = (3.0, 2.0), pin_point: Vect3 | None = None, direction: Vect3 = LEFT, add_content: bool = True, fill_color: ManimColor = BLACK, fill_opacity: float = 0.8, stroke_color: ManimColor = WHITE, stroke_width: float = 3.0, **kwargs ): super().__init__(**kwargs) self.direction = direction if content is None: content = Rectangle(*filler_shape) content.set_fill(opacity=0) content.set_stroke(width=0) elif isinstance(content, str): content = Text(content) self.content = content self.body = self.get_body(content, direction, buff) self.body.set_fill(fill_color, fill_opacity) self.body.set_stroke(stroke_color, stroke_width) self.add(self.body) if add_content: self.add(self.content) if pin_point is not None: self.pin_to(pin_point) def get_body(self, content: VMobject, direction: Vect3, buff: float) -> VMobject: body = SVGMobject(self.file_name) if direction[0] > 0: body.flip() # Resize width = content.get_width() height = content.get_height() target_width = width + min(buff, height) target_height = 1.35 * (height + buff) # Magic number? body.set_shape(target_width, target_height) body.move_to(content) body.shift(self.bubble_center_adjustment_factor * body.get_height() * DOWN) return body def get_tip(self): return self.get_corner(DOWN + self.direction) def get_bubble_center(self): factor = self.bubble_center_adjustment_factor return self.get_center() + factor * self.get_height() * UP def move_tip_to(self, point): self.shift(point - self.get_tip()) return self def flip(self, axis=UP, only_body=True, **kwargs): super().flip(axis=axis, **kwargs) if only_body: # Flip in place, don't use kwargs self.content.flip(axis=axis) if abs(axis[1]) > 0: self.direction = -np.array(self.direction) return self def pin_to(self, mobject, auto_flip=False): mob_center = mobject.get_center() want_to_flip = np.sign(mob_center[0]) != np.sign(self.direction[0]) if want_to_flip and auto_flip: self.flip() boundary_point = mobject.get_bounding_box_point(UP - self.direction) vector_from_center = 1.0 * (boundary_point - mob_center) self.move_tip_to(mob_center + vector_from_center) return self def position_mobject_inside(self, mobject, buff=MED_LARGE_BUFF): mobject.set_max_width(self.body.get_width() - 2 * buff) mobject.set_max_height(self.body.get_height() / 1.5 - 2 * buff) mobject.shift(self.get_bubble_center() - mobject.get_center()) return mobject def add_content(self, mobject): self.position_mobject_inside(mobject) self.content = mobject return self.content def write(self, text): self.add_content(Text(text)) return self def resize_to_content(self, buff=1.0): # TODO self.body.match_points(self.get_body( self.content, self.direction, buff )) def clear(self): self.remove(self.content) return self class SpeechBubble(Bubble): def __init__( self, content: str | VMobject | None = None, buff: float = MED_SMALL_BUFF, filler_shape: Tuple[float, float] = (2.0, 1.0), stem_height_to_bubble_height: float = 0.5, stem_top_x_props: Tuple[float, float] = (0.2, 0.3), **kwargs ): self.stem_height_to_bubble_height = stem_height_to_bubble_height self.stem_top_x_props = stem_top_x_props super().__init__(content, buff, filler_shape, **kwargs) def get_body(self, content: VMobject, direction: Vect3, buff: float) -> VMobject: rect = SurroundingRectangle(content, buff=buff) rect.round_corners() lp = rect.get_corner(DL) rp = rect.get_corner(DR) stem_height = self.stem_height_to_bubble_height * rect.get_height() low_prop, high_prop = self.stem_top_x_props triangle = Polygon( interpolate(lp, rp, low_prop), interpolate(lp, rp, high_prop), lp + stem_height * DOWN, ) result = Union(rect, triangle) result.insert_n_curves(20) if direction[0] > 0: result.flip() return result class ThoughtBubble(Bubble): def __init__( self, content: str | VMobject | None = None, buff: float = SMALL_BUFF, filler_shape: Tuple[float, float] = (2.0, 1.0), bulge_radius: float = 0.35, bulge_overlap: float = 0.25, noise_factor: float = 0.1, circle_radii: list[float] = [0.1, 0.15, 0.2], **kwargs ): self.bulge_radius = bulge_radius self.bulge_overlap = bulge_overlap self.noise_factor = noise_factor self.circle_radii = circle_radii super().__init__(content, buff, filler_shape, **kwargs) def get_body(self, content: VMobject, direction: Vect3, buff: float) -> VMobject: rect = SurroundingRectangle(content, buff) perimeter = rect.get_arc_length() radius = self.bulge_radius step = (1 - self.bulge_overlap) * (2 * radius) nf = self.noise_factor corners = [rect.get_corner(v) for v in [DL, UL, UR, DR]] points = [] for c1, c2 in adjacent_pairs(corners): n_alphas = int(get_norm(c1 - c2) / step) + 1 for alpha in np.linspace(0, 1, n_alphas): points.append(interpolate( c1, c2, alpha + nf * (step / n_alphas) * (random.random() - 0.5) )) cloud = Union(rect, *( # Add bulges Circle(radius=radius * (1 + nf * random.random())).move_to(point) for point in points )) cloud.set_stroke(WHITE, 2) circles = VGroup(Circle(radius=radius) for radius in self.circle_radii) circ_buff = 0.25 * self.circle_radii[0] circles.arrange(UR, buff=circ_buff) circles[1].shift(circ_buff * DR) circles.next_to(cloud, DOWN, 4 * circ_buff, aligned_edge=LEFT) circles.set_stroke(WHITE, 2) result = VGroup(*circles, cloud) if direction[0] > 0: result.flip() return result class OldSpeechBubble(Bubble): file_name: str = "Bubbles_speech.svg" class DoubleSpeechBubble(Bubble): file_name: str = "Bubbles_double_speech.svg" class OldThoughtBubble(Bubble): file_name: str = "Bubbles_thought.svg" def get_body(self, content: VMobject, direction: Vect3, buff: float) -> VMobject: body = super().get_body(content, direction, buff) body.sort(lambda p: p[1]) return body def make_green_screen(self): self.body[-1].set_fill(GREEN_SCREEN, opacity=1) return self class VectorizedEarth(SVGMobject): file_name: str = "earth" def __init__( self, height: float = 2.0, **kwargs ): super().__init__(height=height, **kwargs) self.insert_n_curves(20) circle = Circle( stroke_width=3, stroke_color=GREEN, fill_opacity=1, fill_color=BLUE_C, ) circle.replace(self) self.add_to_back(circle) class Piano(VGroup): def __init__( self, n_white_keys = 52, black_pattern = [0, 2, 3, 5, 6], white_keys_per_octave = 7, white_key_dims = (0.15, 1.0), black_key_dims = (0.1, 0.66), key_buff = 0.02, white_key_color = WHITE, black_key_color = GREY_E, total_width = 13, **kwargs ): self.n_white_keys = n_white_keys self.black_pattern = black_pattern self.white_keys_per_octave = white_keys_per_octave self.white_key_dims = white_key_dims self.black_key_dims = black_key_dims self.key_buff = key_buff self.white_key_color = white_key_color self.black_key_color = black_key_color self.total_width = total_width super().__init__(**kwargs) self.add_white_keys() self.add_black_keys() self.sort_keys() self[:-1].reverse_points() self.set_width(self.total_width) def add_white_keys(self): key = Rectangle(*self.white_key_dims) key.set_fill(self.white_key_color, 1) key.set_stroke(width=0) self.white_keys = key.get_grid(1, self.n_white_keys, buff=self.key_buff) self.add(*self.white_keys) def add_black_keys(self): key = Rectangle(*self.black_key_dims) key.set_fill(self.black_key_color, 1) key.set_stroke(width=0) self.black_keys = VGroup() for i in range(len(self.white_keys) - 1): if i % self.white_keys_per_octave not in self.black_pattern: continue wk1 = self.white_keys[i] wk2 = self.white_keys[i + 1] bk = key.copy() bk.move_to(midpoint(wk1.get_top(), wk2.get_top()), UP) big_bk = bk.copy() big_bk.stretch((bk.get_width() + self.key_buff) / bk.get_width(), 0) big_bk.stretch((bk.get_height() + self.key_buff) / bk.get_height(), 1) big_bk.move_to(bk, UP) for wk in wk1, wk2: wk.become(Difference(wk, big_bk).match_style(wk)) self.black_keys.add(bk) self.add(*self.black_keys) def sort_keys(self): self.sort(lambda p: p[0]) class Piano3D(VGroup): def __init__( self, shading: Tuple[float, float, float] = (1.0, 0.2, 0.2), stroke_width: float = 0.25, stroke_color: ManimColor = BLACK, key_depth: float = 0.1, black_key_shift: float = 0.05, piano_2d_config: dict = dict( white_key_color=GREY_A, key_buff=0.001 ), **kwargs ): piano_2d = Piano(**piano_2d_config) super().__init__(*( Prismify(key, key_depth) for key in piano_2d )) self.set_stroke(stroke_color, stroke_width) self.set_shading(*shading) self.apply_depth_test() # Elevate black keys for i, key in enumerate(self): if piano_2d[i] in piano_2d.black_keys: key.shift(black_key_shift * OUT) key.set_color(BLACK) class DieFace(VGroup): def __init__( self, value: int, side_length: float = 1.0, corner_radius: float = 0.15, stroke_color: ManimColor = WHITE, stroke_width: float = 2.0, fill_color: ManimColor = GREY_E, dot_radius: float = 0.08, dot_color: ManimColor = WHITE, dot_coalesce_factor: float = 0.5 ): dot = Dot(radius=dot_radius, fill_color=dot_color) square = Square( side_length=side_length, stroke_color=stroke_color, stroke_width=stroke_width, fill_color=fill_color, fill_opacity=1.0, ) square.round_corners(corner_radius) if not (1 <= value <= 6): raise Exception("DieFace only accepts integer inputs between 1 and 6") edge_group = [ (ORIGIN,), (UL, DR), (UL, ORIGIN, DR), (UL, UR, DL, DR), (UL, UR, ORIGIN, DL, DR), (UL, UR, LEFT, RIGHT, DL, DR), ][value - 1] arrangement = VGroup(*( dot.copy().move_to(square.get_bounding_box_point(vect)) for vect in edge_group )) arrangement.space_out_submobjects(dot_coalesce_factor) super().__init__(square, arrangement) self.dots = arrangement self.value = value self.index = value class Dartboard(VGroup): radius = 3 n_sectors = 20 def __init__(self, **kwargs): super().__init__(**kwargs) n_sectors = self.n_sectors angle = TAU / n_sectors segments = VGroup(*[ VGroup(*[ AnnularSector( inner_radius=in_r, outer_radius=out_r, start_angle=n * angle, angle=angle, fill_color=color, ) for n, color in zip( range(n_sectors), it.cycle(colors) ) ]) for colors, in_r, out_r in [ ([GREY_B, GREY_E], 0, 1), ([GREEN_E, RED_E], 0.5, 0.55), ([GREEN_E, RED_E], 0.95, 1), ] ]) segments.rotate(-angle / 2) bullseyes = VGroup(*[ Circle(radius=r) for r in [0.07, 0.035] ]) bullseyes.set_fill(opacity=1) bullseyes.set_stroke(width=0) bullseyes[0].set_color(GREEN_E) bullseyes[1].set_color(RED_E) self.bullseye = bullseyes[1] self.add(*segments, *bullseyes) self.scale(self.radius)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/svg/svg_mobject.py
manimlib/mobject/svg/svg_mobject.py
from __future__ import annotations from xml.etree import ElementTree as ET import numpy as np import svgelements as se import io from pathlib import Path from manimlib.constants import RIGHT from manimlib.constants import TAU from manimlib.logger import log from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Polygon from manimlib.mobject.geometry import Polyline from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import RoundedRectangle from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import quadratic_bezier_points_for_arc from manimlib.utils.images import get_full_vector_image_path from manimlib.utils.iterables import hash_obj from manimlib.utils.space_ops import rotation_about_z from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor, Vect3Array SVG_HASH_TO_MOB_MAP: dict[int, list[VMobject]] = {} PATH_TO_POINTS: dict[str, Vect3Array] = {} def _convert_point_to_3d(x: float, y: float) -> np.ndarray: return np.array([x, y, 0.0]) class SVGMobject(VMobject): file_name: str = "" height: float | None = 2.0 width: float | None = None def __init__( self, file_name: str = "", svg_string: str = "", should_center: bool = True, height: float | None = None, width: float | None = None, # Style that overrides the original svg color: ManimColor = None, fill_color: ManimColor = None, fill_opacity: float | None = None, stroke_width: float | None = 0.0, stroke_color: ManimColor = None, stroke_opacity: float | None = None, # Style that fills only when not specified # If None, regarded as default values from svg standard svg_default: dict = dict( color=None, opacity=None, fill_color=None, fill_opacity=None, stroke_width=None, stroke_color=None, stroke_opacity=None, ), path_string_config: dict = dict(), **kwargs ): if svg_string != "": self.svg_string = svg_string elif file_name != "": self.svg_string = self.file_name_to_svg_string(file_name) elif self.file_name != "": self.svg_string = self.file_name_to_svg_string(self.file_name) else: raise Exception("Must specify either a file_name or svg_string SVGMobject") self.svg_default = dict(svg_default) self.path_string_config = dict(path_string_config) super().__init__(**kwargs) self.init_svg_mobject() self.ensure_positive_orientation() # Rather than passing style into super().__init__ # do it after svg has been taken in self.set_style( fill_color=color or fill_color, fill_opacity=fill_opacity, stroke_color=color or stroke_color, stroke_width=stroke_width, stroke_opacity=stroke_opacity, ) # Initialize position height = height or self.height width = width or self.width if should_center: self.center() if height is not None: self.set_height(height) if width is not None: self.set_width(width) def init_svg_mobject(self) -> None: hash_val = hash_obj(self.hash_seed) if hash_val in SVG_HASH_TO_MOB_MAP: submobs = [sm.copy() for sm in SVG_HASH_TO_MOB_MAP[hash_val]] else: submobs = self.mobjects_from_svg_string(self.svg_string) SVG_HASH_TO_MOB_MAP[hash_val] = [sm.copy() for sm in submobs] self.add(*submobs) self.flip(RIGHT) # Flip y @property def hash_seed(self) -> tuple: # Returns data which can uniquely represent the result of `init_points`. # The hashed value of it is stored as a key in `SVG_HASH_TO_MOB_MAP`. return ( self.__class__.__name__, self.svg_default, self.path_string_config, self.svg_string ) def mobjects_from_svg_string(self, svg_string: str) -> list[VMobject]: element_tree = ET.ElementTree(ET.fromstring(svg_string)) new_tree = self.modify_xml_tree(element_tree) # New svg based on tree contents data_stream = io.BytesIO() new_tree.write(data_stream) data_stream.seek(0) svg = se.SVG.parse(data_stream) data_stream.close() return self.mobjects_from_svg(svg) def file_name_to_svg_string(self, file_name: str) -> str: return Path(get_full_vector_image_path(file_name)).read_text() def modify_xml_tree(self, element_tree: ET.ElementTree) -> ET.ElementTree: config_style_attrs = self.generate_config_style_dict() style_keys = ( "fill", "fill-opacity", "stroke", "stroke-opacity", "stroke-width", "style" ) root = element_tree.getroot() style_attrs = { k: v for k, v in root.attrib.items() if k in style_keys } # Ignore other attributes in case that svgelements cannot parse them SVG_XMLNS = "{http://www.w3.org/2000/svg}" new_root = ET.Element("svg") config_style_node = ET.SubElement(new_root, f"{SVG_XMLNS}g", config_style_attrs) root_style_node = ET.SubElement(config_style_node, f"{SVG_XMLNS}g", style_attrs) root_style_node.extend(root) return ET.ElementTree(new_root) def generate_config_style_dict(self) -> dict[str, str]: keys_converting_dict = { "fill": ("color", "fill_color"), "fill-opacity": ("opacity", "fill_opacity"), "stroke": ("color", "stroke_color"), "stroke-opacity": ("opacity", "stroke_opacity"), "stroke-width": ("stroke_width",) } svg_default_dict = self.svg_default result = {} for svg_key, style_keys in keys_converting_dict.items(): for style_key in style_keys: if svg_default_dict[style_key] is None: continue result[svg_key] = str(svg_default_dict[style_key]) return result def mobjects_from_svg(self, svg: se.SVG) -> list[VMobject]: result = [] for shape in svg.elements(): if isinstance(shape, (se.Group, se.Use)): continue elif isinstance(shape, se.Path): mob = self.path_to_mobject(shape) elif isinstance(shape, se.SimpleLine): mob = self.line_to_mobject(shape) elif isinstance(shape, se.Rect): mob = self.rect_to_mobject(shape) elif isinstance(shape, (se.Circle, se.Ellipse)): mob = self.ellipse_to_mobject(shape) elif isinstance(shape, se.Polygon): mob = self.polygon_to_mobject(shape) elif isinstance(shape, se.Polyline): mob = self.polyline_to_mobject(shape) # elif isinstance(shape, se.Text): # mob = self.text_to_mobject(shape) elif type(shape) == se.SVGElement: continue else: log.warning("Unsupported element type: %s", type(shape)) continue if not mob.has_points(): continue if isinstance(shape, se.GraphicObject): self.apply_style_to_mobject(mob, shape) if isinstance(shape, se.Transformable) and shape.apply: self.handle_transform(mob, shape.transform) result.append(mob) return result @staticmethod def handle_transform(mob: VMobject, matrix: se.Matrix) -> VMobject: mat = np.array([ [matrix.a, matrix.c], [matrix.b, matrix.d] ]) vec = np.array([matrix.e, matrix.f, 0.0]) mob.apply_matrix(mat) mob.shift(vec) return mob @staticmethod def apply_style_to_mobject( mob: VMobject, shape: se.GraphicObject ) -> VMobject: mob.set_style( stroke_width=shape.stroke_width, stroke_color=shape.stroke.hexrgb, stroke_opacity=shape.stroke.opacity, fill_color=shape.fill.hexrgb, fill_opacity=shape.fill.opacity ) return mob def path_to_mobject(self, path: se.Path) -> VMobjectFromSVGPath: return VMobjectFromSVGPath(path, **self.path_string_config) def line_to_mobject(self, line: se.SimpleLine) -> Line: return Line( start=_convert_point_to_3d(line.x1, line.y1), end=_convert_point_to_3d(line.x2, line.y2) ) def rect_to_mobject(self, rect: se.Rect) -> Rectangle: if rect.rx == 0 or rect.ry == 0: mob = Rectangle( width=rect.width, height=rect.height, ) else: mob = RoundedRectangle( width=rect.width, height=rect.height * rect.rx / rect.ry, corner_radius=rect.rx ) mob.stretch_to_fit_height(rect.height) mob.shift(_convert_point_to_3d( rect.x + rect.width / 2, rect.y + rect.height / 2 )) return mob def ellipse_to_mobject(self, ellipse: se.Circle | se.Ellipse) -> Circle: mob = Circle(radius=ellipse.rx) mob.stretch_to_fit_height(2 * ellipse.ry) mob.shift(_convert_point_to_3d( ellipse.cx, ellipse.cy )) return mob def polygon_to_mobject(self, polygon: se.Polygon) -> Polygon: points = [ _convert_point_to_3d(*point) for point in polygon ] return Polygon(*points) def polyline_to_mobject(self, polyline: se.Polyline) -> Polyline: points = [ _convert_point_to_3d(*point) for point in polyline ] return Polyline(*points) def text_to_mobject(self, text: se.Text): pass class VMobjectFromSVGPath(VMobject): def __init__( self, path_obj: se.Path, **kwargs ): # caches (transform.inverse(), rot, shift) self.transform_cache: tuple[se.Matrix, np.ndarray, np.ndarray] | None = None self.path_obj = path_obj super().__init__(**kwargs) def init_points(self) -> None: # After a given svg_path has been converted into points, the result # will be saved so that future calls for the same pathdon't need to # retrace the same computation. path_string = self.path_obj.d() if path_string not in PATH_TO_POINTS: self.handle_commands() # Save for future use PATH_TO_POINTS[path_string] = self.get_points().copy() else: points = PATH_TO_POINTS[path_string] self.set_points(points) def handle_commands(self) -> None: segment_class_to_func_map = { se.Move: (self.start_new_path, ("end",)), se.Close: (self.close_path, ()), se.Line: (lambda p: self.add_line_to(p, allow_null_line=False), ("end",)), se.QuadraticBezier: (lambda c, e: self.add_quadratic_bezier_curve_to(c, e, allow_null_curve=False), ("control", "end")), se.CubicBezier: (self.add_cubic_bezier_curve_to, ("control1", "control2", "end")) } for segment in self.path_obj: segment_class = segment.__class__ if segment_class is se.Arc: self.handle_arc(segment) else: func, attr_names = segment_class_to_func_map[segment_class] points = [ _convert_point_to_3d(*segment.__getattribute__(attr_name)) for attr_name in attr_names ] func(*points) # Get rid of the side effect of trailing "Z M" commands. if self.has_new_path_started(): self.resize_points(self.get_num_points() - 2) def handle_arc(self, arc: se.Arc) -> None: if self.transform_cache is not None: transform, rot, shift = self.transform_cache else: # The transform obtained in this way considers the combined effect # of all parent group transforms in the SVG. # Therefore, the arc can be transformed inversely using this transform # to correctly compute the arc path before transforming it back. transform = se.Matrix(self.path_obj.values.get('transform', '')) rot = np.array([ [transform.a, transform.c], [transform.b, transform.d] ]) shift = np.array([transform.e, transform.f, 0]) transform.inverse() self.transform_cache = (transform, rot, shift) # Apply inverse transformation to the arc so that its path can be correctly computed arc *= transform # The value of n_components is chosen based on the implementation of VMobject.arc_to n_components = int(np.ceil(8 * abs(arc.sweep) / TAU)) # Obtain the required angular segments on the unit circle arc_points = quadratic_bezier_points_for_arc(arc.sweep, n_components) arc_points @= np.array(rotation_about_z(arc.get_start_t())).T # Transform to an ellipse, considering rotation and translating the ellipse center arc_points[:, 0] *= arc.rx arc_points[:, 1] *= arc.ry arc_points @= np.array(rotation_about_z(arc.get_rotation().as_radians)).T arc_points += [*arc.center, 0] # Transform back arc_points[:, :2] @= rot.T arc_points += shift self.append_points(arc_points[1:])
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/svg/old_tex_mobject.py
manimlib/mobject/svg/old_tex_mobject.py
from __future__ import annotations from functools import reduce import operator as op import re from manimlib.constants import BLACK, DEFAULT_MOBJECT_COLOR from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.tex_file_writing import latex_to_svg from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable, List, Dict from manimlib.typing import ManimColor SCALE_FACTOR_PER_FONT_POINT = 0.001 class SingleStringTex(SVGMobject): height: float | None = None def __init__( self, tex_string: str, height: float | None = None, fill_color: ManimColor = DEFAULT_MOBJECT_COLOR, fill_opacity: float = 1.0, stroke_width: float = 0, svg_default: dict = dict(fill_color=DEFAULT_MOBJECT_COLOR), path_string_config: dict = dict(), font_size: int = 48, alignment: str = R"\centering", math_mode: bool = True, organize_left_to_right: bool = False, template: str = "", additional_preamble: str = "", **kwargs ): self.tex_string = tex_string self.svg_default = dict(svg_default) self.path_string_config = dict(path_string_config) self.font_size = font_size self.alignment = alignment self.math_mode = math_mode self.organize_left_to_right = organize_left_to_right self.template = template self.additional_preamble = additional_preamble super().__init__( height=height, fill_color=fill_color, fill_opacity=fill_opacity, stroke_width=stroke_width, path_string_config=path_string_config, **kwargs ) if self.height is None: self.scale(SCALE_FACTOR_PER_FONT_POINT * self.font_size) if self.organize_left_to_right: self.organize_submobjects_left_to_right() @property def hash_seed(self) -> tuple: return ( self.__class__.__name__, self.svg_default, self.path_string_config, self.tex_string, self.alignment, self.math_mode, self.template, self.additional_preamble ) def get_svg_string_by_content(self, content: str) -> str: return latex_to_svg(content, self.template, self.additional_preamble) def get_tex_file_body(self, tex_string: str) -> str: new_tex = self.get_modified_expression(tex_string) if self.math_mode: new_tex = "\\begin{align*}\n" + new_tex + "\n\\end{align*}" return self.alignment + "\n" + new_tex def get_modified_expression(self, tex_string: str) -> str: return self.modify_special_strings(tex_string.strip()) def modify_special_strings(self, tex: str) -> str: tex = tex.strip() should_add_filler = reduce(op.or_, [ # Fraction line needs something to be over tex == "\\over", tex == "\\overline", # Makesure sqrt has overbar tex == "\\sqrt", tex == "\\sqrt{", # Need to add blank subscript or superscript tex.endswith("_"), tex.endswith("^"), tex.endswith("dot"), ]) if should_add_filler: filler = "{\\quad}" tex += filler should_add_double_filler = reduce(op.or_, [ tex == "\\overset", # TODO: these can't be used since they change # the latex draw order. # tex == "\\frac", # you can use \\over as a alternative # tex == "\\dfrac", # tex == "\\binom", ]) if should_add_double_filler: filler = "{\\quad}{\\quad}" tex += filler if tex == "\\substack": tex = "\\quad" if tex == "": tex = "\\quad" # To keep files from starting with a line break if tex.startswith("\\\\"): tex = tex.replace("\\\\", "\\quad\\\\") tex = self.balance_braces(tex) # Handle imbalanced \left and \right num_lefts, num_rights = [ len([ s for s in tex.split(substr)[1:] if s and s[0] in "(){}[]|.\\" ]) for substr in ("\\left", "\\right") ] if num_lefts != num_rights: tex = tex.replace("\\left", "\\big") tex = tex.replace("\\right", "\\big") for context in ["array"]: begin_in = ("\\begin{%s}" % context) in tex end_in = ("\\end{%s}" % context) in tex if begin_in ^ end_in: # Just turn this into a blank string, # which means caller should leave a # stray \\begin{...} with other symbols tex = "" return tex def balance_braces(self, tex: str) -> str: """ Makes Tex resiliant to unmatched braces """ num_unclosed_brackets = 0 for i in range(len(tex)): if i > 0 and tex[i - 1] == "\\": # So as to not count '\{' type expressions continue char = tex[i] if char == "{": num_unclosed_brackets += 1 elif char == "}": if num_unclosed_brackets == 0: tex = "{" + tex else: num_unclosed_brackets -= 1 tex += num_unclosed_brackets * "}" return tex def get_tex(self) -> str: return self.tex_string def organize_submobjects_left_to_right(self): self.sort(lambda p: p[0]) return self class OldTex(SingleStringTex): def __init__( self, *tex_strings: str, arg_separator: str = "", isolate: List[str] = [], tex_to_color_map: Dict[str, ManimColor] = {}, **kwargs ): self.tex_strings = self.break_up_tex_strings( tex_strings, substrings_to_isolate=[*isolate, *tex_to_color_map.keys()] ) full_string = arg_separator.join(self.tex_strings) super().__init__(full_string, **kwargs) self.break_up_by_substrings(self.tex_strings) self.set_color_by_tex_to_color_map(tex_to_color_map) if self.organize_left_to_right: self.organize_submobjects_left_to_right() def break_up_tex_strings(self, tex_strings: Iterable[str], substrings_to_isolate: List[str] = []) -> Iterable[str]: # Separate out any strings specified in the isolate # or tex_to_color_map lists. if len(substrings_to_isolate) == 0: return tex_strings patterns = ( "({})".format(re.escape(ss)) for ss in substrings_to_isolate ) pattern = "|".join(patterns) pieces = [] for s in tex_strings: if pattern: pieces.extend(re.split(pattern, s)) else: pieces.append(s) return list(filter(lambda s: s, pieces)) def break_up_by_substrings(self, tex_strings: Iterable[str]): """ Reorganize existing submojects one layer deeper based on the structure of tex_strings (as a list of tex_strings) """ if len(list(tex_strings)) == 1: submob = self.copy() self.set_submobjects([submob]) return self new_submobjects = [] curr_index = 0 for tex_string in tex_strings: tex_string = tex_string.strip() if len(tex_string) == 0: continue sub_tex_mob = SingleStringTex(tex_string, math_mode=self.math_mode) num_submobs = len(sub_tex_mob) if num_submobs == 0: continue new_index = curr_index + num_submobs sub_tex_mob.set_submobjects(self.submobjects[curr_index:new_index]) new_submobjects.append(sub_tex_mob) curr_index = new_index self.set_submobjects(new_submobjects) return self def get_parts_by_tex( self, tex: str, substring: bool = True, case_sensitive: bool = True ) -> VGroup: def test(tex1, tex2): if not case_sensitive: tex1 = tex1.lower() tex2 = tex2.lower() if substring: return tex1 in tex2 else: return tex1 == tex2 return VGroup(*filter( lambda m: isinstance(m, SingleStringTex) and test(tex, m.get_tex()), self.submobjects )) def get_part_by_tex(self, tex: str, **kwargs) -> SingleStringTex | None: all_parts = self.get_parts_by_tex(tex, **kwargs) return all_parts[0] if all_parts else None def set_color_by_tex(self, tex: str, color: ManimColor, **kwargs): self.get_parts_by_tex(tex, **kwargs).set_color(color) return self def set_color_by_tex_to_color_map( self, tex_to_color_map: dict[str, ManimColor], **kwargs ): for tex, color in list(tex_to_color_map.items()): self.set_color_by_tex(tex, color, **kwargs) return self def index_of_part(self, part: SingleStringTex, start: int = 0) -> int: return self.submobjects.index(part, start) def index_of_part_by_tex(self, tex: str, start: int = 0, **kwargs) -> int: part = self.get_part_by_tex(tex, **kwargs) return self.index_of_part(part, start) def slice_by_tex( self, start_tex: str | None = None, stop_tex: str | None = None, **kwargs ) -> VGroup: if start_tex is None: start_index = 0 else: start_index = self.index_of_part_by_tex(start_tex, **kwargs) if stop_tex is None: return self[start_index:] else: stop_index = self.index_of_part_by_tex(stop_tex, start=start_index, **kwargs) return self[start_index:stop_index] def sort_alphabetically(self) -> None: self.submobjects.sort(key=lambda m: m.get_tex()) def set_bstroke(self, color: ManimColor = BLACK, width: float = 4): self.set_stroke(color, width, background=True) return self class OldTexText(OldTex): def __init__( self, *tex_strings: str, math_mode: bool = False, arg_separator: str = "", **kwargs ): super().__init__( *tex_strings, math_mode=math_mode, arg_separator=arg_separator, **kwargs )
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/svg/__init__.py
manimlib/mobject/svg/__init__.py
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/svg/string_mobject.py
manimlib/mobject/svg/string_mobject.py
from __future__ import annotations from abc import ABC, abstractmethod import itertools as it import re from scipy.optimize import linear_sum_assignment from scipy.spatial.distance import cdist from manimlib.constants import DEFAULT_MOBJECT_COLOR from manimlib.logger import log from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.color import color_to_hex from manimlib.utils.color import hex_to_int from manimlib.utils.color import int_to_hex from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import ManimColor, Span, Selector class StringMobject(SVGMobject, ABC): """ An abstract base class for `Tex` and `MarkupText` This class aims to optimize the logic of "slicing submobjects via substrings". This could be much clearer and more user-friendly than slicing through numerical indices explicitly. Users are expected to specify substrings in `isolate` parameter if they want to do anything with their corresponding submobjects. `isolate` parameter can be either a string, a `re.Pattern` object, or a 2-tuple containing integers or None, or a collection of the above. Note, substrings specified cannot *partly* overlap with each other. Each instance of `StringMobject` may generate 2 svg files. The additional one is generated with some color commands inserted, so that each submobject of the original `SVGMobject` will be labelled by the color of its paired submobject from the additional `SVGMobject`. """ height = None def __init__( self, string: str, fill_color: ManimColor = DEFAULT_MOBJECT_COLOR, fill_border_width: float = 0.5, stroke_color: ManimColor = DEFAULT_MOBJECT_COLOR, stroke_width: float = 0, base_color: ManimColor = DEFAULT_MOBJECT_COLOR, isolate: Selector = (), protect: Selector = (), # When set to true, only the labelled svg is # rendered, and its contents are used directly # for the body of this String Mobject use_labelled_svg: bool = False, **kwargs ): self.string = string self.base_color = base_color or DEFAULT_MOBJECT_COLOR self.isolate = isolate self.protect = protect self.use_labelled_svg = use_labelled_svg self.parse() svg_string = self.get_svg_string() super().__init__(svg_string=svg_string, **kwargs) self.set_stroke(stroke_color, stroke_width) self.set_fill(fill_color, border_width=fill_border_width) self.labels = [submob.label for submob in self.submobjects] def get_svg_string(self, is_labelled: bool = False) -> str: content = self.get_content(is_labelled or self.use_labelled_svg) return self.get_svg_string_by_content(content) @abstractmethod def get_svg_string_by_content(self, content: str) -> str: return "" def assign_labels_by_color(self, mobjects: list[VMobject]) -> None: """ Assuming each mobject in the list `mobjects` has a fill color meant to represent a numerical label, this assigns those those numerical labels to each mobject as an attribute """ labels_count = len(self.labelled_spans) if labels_count == 1: for mob in mobjects: mob.label = 0 return unrecognizable_colors = [] for mob in mobjects: label = hex_to_int(color_to_hex(mob.get_fill_color())) if label >= labels_count: unrecognizable_colors.append(label) label = 0 mob.label = label if unrecognizable_colors: log.warning( "Unrecognizable color labels detected (%s). " + \ "The result could be unexpected.", ", ".join( int_to_hex(color) for color in unrecognizable_colors ) ) def mobjects_from_svg_string(self, svg_string: str) -> list[VMobject]: submobs = super().mobjects_from_svg_string(svg_string) if self.use_labelled_svg: # This means submobjects are colored according to spans self.assign_labels_by_color(submobs) return submobs # Otherwise, submobs are not colored, so generate a new list # of submobject which are and use those for labels unlabelled_submobs = submobs labelled_content = self.get_content(is_labelled=True) labelled_file = self.get_svg_string_by_content(labelled_content) labelled_submobs = super().mobjects_from_svg_string(labelled_file) self.labelled_submobs = labelled_submobs self.unlabelled_submobs = unlabelled_submobs self.assign_labels_by_color(labelled_submobs) self.rearrange_submobjects_by_positions(labelled_submobs, unlabelled_submobs) for usm, lsm in zip(unlabelled_submobs, labelled_submobs): usm.label = lsm.label if len(unlabelled_submobs) != len(labelled_submobs): log.warning( "Cannot align submobjects of the labelled svg " + \ "to the original svg. Skip the labelling process." ) for usm in unlabelled_submobs: usm.label = 0 return unlabelled_submobs return unlabelled_submobs def rearrange_submobjects_by_positions( self, labelled_submobs: list[VMobject], unlabelled_submobs: list[VMobject], ) -> None: """ Rearrange `labeleled_submobjects` so that each submobject is labelled by the nearest one of `unlabelled_submobs`. The correctness cannot be ensured, since the svg may change significantly after inserting color commands. """ if len(labelled_submobs) == 0: return labelled_svg = VGroup(*labelled_submobs) labelled_svg.replace(VGroup(*unlabelled_submobs)) distance_matrix = cdist( [submob.get_center() for submob in unlabelled_submobs], [submob.get_center() for submob in labelled_submobs] ) _, indices = linear_sum_assignment(distance_matrix) labelled_submobs[:] = [labelled_submobs[index] for index in indices] # Toolkits def find_spans_by_selector(self, selector: Selector) -> list[Span]: def find_spans_by_single_selector(sel): if isinstance(sel, str): return [ match_obj.span() for match_obj in re.finditer(re.escape(sel), self.string) ] if isinstance(sel, re.Pattern): return [ match_obj.span() for match_obj in sel.finditer(self.string) ] if isinstance(sel, tuple) and len(sel) == 2 and all( isinstance(index, int) or index is None for index in sel ): l = len(self.string) span = tuple( default_index if index is None else min(index, l) if index >= 0 else max(index + l, 0) for index, default_index in zip(sel, (0, l)) ) return [span] return None result = find_spans_by_single_selector(selector) if result is None: result = [] for sel in selector: spans = find_spans_by_single_selector(sel) if spans is None: raise TypeError(f"Invalid selector: '{sel}'") result.extend(spans) return list(filter(lambda span: span[0] <= span[1], result)) @staticmethod def span_contains(span_0: Span, span_1: Span) -> bool: return span_0[0] <= span_1[0] and span_0[1] >= span_1[1] # Parsing def parse(self) -> None: def get_substr(span: Span) -> str: return self.string[slice(*span)] configured_items = self.get_configured_items() isolated_spans = self.find_spans_by_selector(self.isolate) protected_spans = self.find_spans_by_selector(self.protect) command_matches = self.get_command_matches(self.string) def get_key(category, i, flag): def get_span_by_category(category, i): if category == 0: return configured_items[i][0] if category == 1: return isolated_spans[i] if category == 2: return protected_spans[i] return command_matches[i].span() index, paired_index = get_span_by_category(category, i)[::flag] return ( index, flag * (2 if index != paired_index else -1), -paired_index, flag * category, flag * i ) index_items = sorted([ (category, i, flag) for category, item_length in enumerate(( len(configured_items), len(isolated_spans), len(protected_spans), len(command_matches) )) for i in range(item_length) for flag in (1, -1) ], key=lambda t: get_key(*t)) inserted_items = [] labelled_items = [] overlapping_spans = [] level_mismatched_spans = [] label = 1 protect_level = 0 bracket_stack = [0] bracket_count = 0 open_command_stack = [] open_stack = [] for category, i, flag in index_items: if category >= 2: protect_level += flag if flag == 1 or category == 2: continue inserted_items.append((i, 0)) command_match = command_matches[i] command_flag = self.get_command_flag(command_match) if command_flag == 1: bracket_count += 1 bracket_stack.append(bracket_count) open_command_stack.append((len(inserted_items), i)) continue if command_flag == 0: continue pos, i_ = open_command_stack.pop() bracket_stack.pop() open_command_match = command_matches[i_] attr_dict = self.get_attr_dict_from_command_pair( open_command_match, command_match ) if attr_dict is None: continue span = (open_command_match.end(), command_match.start()) labelled_items.append((span, attr_dict)) inserted_items.insert(pos, (label, 1)) inserted_items.insert(-1, (label, -1)) label += 1 continue if flag == 1: open_stack.append(( len(inserted_items), category, i, protect_level, bracket_stack.copy() )) continue span, attr_dict = configured_items[i] \ if category == 0 else (isolated_spans[i], {}) pos, category_, i_, protect_level_, bracket_stack_ \ = open_stack.pop() if category_ != category or i_ != i: overlapping_spans.append(span) continue if protect_level_ or protect_level: continue if bracket_stack_ != bracket_stack: level_mismatched_spans.append(span) continue labelled_items.append((span, attr_dict)) inserted_items.insert(pos, (label, 1)) inserted_items.append((label, -1)) label += 1 labelled_items.insert(0, ((0, len(self.string)), {})) inserted_items.insert(0, (0, 1)) inserted_items.append((0, -1)) if overlapping_spans: log.warning( "Partly overlapping substrings detected: %s", ", ".join( f"'{get_substr(span)}'" for span in overlapping_spans ) ) if level_mismatched_spans: log.warning( "Cannot handle substrings: %s", ", ".join( f"'{get_substr(span)}'" for span in level_mismatched_spans ) ) def reconstruct_string( start_item: tuple[int, int], end_item: tuple[int, int], command_replace_func: Callable[[re.Match], str], command_insert_func: Callable[[int, int, dict[str, str]], str] ) -> str: def get_edge_item(i: int, flag: int) -> tuple[Span, str]: if flag == 0: match_obj = command_matches[i] return ( match_obj.span(), command_replace_func(match_obj) ) span, attr_dict = labelled_items[i] index = span[flag < 0] return ( (index, index), command_insert_func(i, flag, attr_dict) ) items = [ get_edge_item(i, flag) for i, flag in inserted_items[slice( inserted_items.index(start_item), inserted_items.index(end_item) + 1 )] ] pieces = [ get_substr((start, end)) for start, end in zip( [interval_end for (_, interval_end), _ in items[:-1]], [interval_start for (interval_start, _), _ in items[1:]] ) ] interval_pieces = [piece for _, piece in items[1:-1]] return "".join(it.chain(*zip(pieces, (*interval_pieces, "")))) self.labelled_spans = [span for span, _ in labelled_items] self.reconstruct_string = reconstruct_string def get_content(self, is_labelled: bool) -> str: content = self.reconstruct_string( (0, 1), (0, -1), self.replace_for_content, lambda label, flag, attr_dict: self.get_command_string( attr_dict, is_end=flag < 0, label_hex=int_to_hex(label) if is_labelled else None ) ) prefix, suffix = self.get_content_prefix_and_suffix( is_labelled=is_labelled ) return "".join((prefix, content, suffix)) @staticmethod @abstractmethod def get_command_matches(string: str) -> list[re.Match]: return [] @staticmethod @abstractmethod def get_command_flag(match_obj: re.Match) -> int: return 0 @staticmethod @abstractmethod def replace_for_content(match_obj: re.Match) -> str: return "" @staticmethod @abstractmethod def replace_for_matching(match_obj: re.Match) -> str: return "" @staticmethod @abstractmethod def get_attr_dict_from_command_pair( open_command: re.Match, close_command: re.Match, ) -> dict[str, str] | None: return None @abstractmethod def get_configured_items(self) -> list[tuple[Span, dict[str, str]]]: return [] @staticmethod @abstractmethod def get_command_string( attr_dict: dict[str, str], is_end: bool, label_hex: str | None ) -> str: return "" @abstractmethod def get_content_prefix_and_suffix( self, is_labelled: bool ) -> tuple[str, str]: return "", "" # Selector def get_submob_indices_list_by_span( self, arbitrary_span: Span ) -> list[int]: return [ submob_index for submob_index, label in enumerate(self.labels) if self.span_contains(arbitrary_span, self.labelled_spans[label]) ] def get_specified_part_items(self) -> list[tuple[str, list[int]]]: return [ ( self.string[slice(*span)], self.get_submob_indices_list_by_span(span) ) for span in self.labelled_spans[1:] ] def get_specified_substrings(self) -> list[str]: substrs = [ self.string[slice(*span)] for span in self.labelled_spans[1:] ] # Use dict.fromkeys to remove duplicates while retaining order return list(dict.fromkeys(substrs).keys()) def get_group_part_items(self) -> list[tuple[str, list[int]]]: if not self.labels: return [] def get_neighbouring_pairs(vals): return list(zip(vals[:-1], vals[1:])) range_lens, group_labels = zip(*( (len(list(grouper)), val) for val, grouper in it.groupby(self.labels) )) submob_indices_lists = [ list(range(*submob_range)) for submob_range in get_neighbouring_pairs( [0, *it.accumulate(range_lens)] ) ] labelled_spans = self.labelled_spans start_items = [ (group_labels[0], 1), *( (curr_label, 1) if self.span_contains( labelled_spans[prev_label], labelled_spans[curr_label] ) else (prev_label, -1) for prev_label, curr_label in get_neighbouring_pairs( group_labels ) ) ] end_items = [ *( (curr_label, -1) if self.span_contains( labelled_spans[next_label], labelled_spans[curr_label] ) else (next_label, 1) for curr_label, next_label in get_neighbouring_pairs( group_labels ) ), (group_labels[-1], -1) ] group_substrs = [ re.sub(r"\s+", "", self.reconstruct_string( start_item, end_item, self.replace_for_matching, lambda label, flag, attr_dict: "" )) for start_item, end_item in zip(start_items, end_items) ] return list(zip(group_substrs, submob_indices_lists)) def get_submob_indices_lists_by_selector( self, selector: Selector ) -> list[list[int]]: return list(filter( lambda indices_list: indices_list, [ self.get_submob_indices_list_by_span(span) for span in self.find_spans_by_selector(selector) ] )) def build_parts_from_indices_lists( self, indices_lists: list[list[int]] ) -> VGroup: return VGroup(*( VGroup(*( self.submobjects[submob_index] for submob_index in indices_list )) for indices_list in indices_lists )) def build_groups(self) -> VGroup: return self.build_parts_from_indices_lists([ indices_list for _, indices_list in self.get_group_part_items() ]) def select_parts(self, selector: Selector) -> VGroup: specified_substrings = self.get_specified_substrings() if isinstance(selector, (str, re.Pattern)) and selector not in specified_substrings: return self.select_unisolated_substring(selector) indices_list = self.get_submob_indices_lists_by_selector(selector) return self.build_parts_from_indices_lists(indices_list) def __getitem__(self, value: int | slice | Selector) -> VMobject: if isinstance(value, (int, slice)): return super().__getitem__(value) return self.select_parts(value) def select_part(self, selector: Selector, index: int = 0) -> VMobject: return self.select_parts(selector)[index] def substr_to_path_count(self, substr: str) -> int: return len(re.sub(r"\s", "", substr)) def get_symbol_substrings(self): return list(re.sub(r"\s", "", self.string)) def select_unisolated_substring(self, pattern: str | re.Pattern) -> VGroup: if isinstance(pattern, str): pattern = re.compile(re.escape(pattern)) result = [] for match in re.finditer(pattern, self.string): index = match.start() start = self.substr_to_path_count(self.string[:index]) substr = match.group() end = start + self.substr_to_path_count(substr) result.append(self[start:end]) return VGroup(*result) def set_parts_color(self, selector: Selector, color: ManimColor): self.select_parts(selector).set_color(color) return self def set_parts_color_by_dict(self, color_map: dict[Selector, ManimColor]): for selector, color in color_map.items(): self.set_parts_color(selector, color) return self def get_string(self) -> str: return self.string
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/mobject/svg/brace.py
manimlib/mobject/svg/brace.py
from __future__ import annotations import math import copy import numpy as np from manimlib.constants import DEFAULT_MOBJECT_TO_MOBJECT_BUFF, SMALL_BUFF from manimlib.constants import DOWN, LEFT, ORIGIN, RIGHT, DL, DR, UL, UP from manimlib.constants import PI from manimlib.animation.composition import AnimationGroup from manimlib.animation.fading import FadeIn from manimlib.animation.growing import GrowFromCenter from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.iterables import listify from manimlib.utils.space_ops import get_norm from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable from manimlib.animation.animation import Animation from manimlib.mobject.mobject import Mobject from manimlib.typing import Vect3 class Brace(Tex): def __init__( self, mobject: Mobject, direction: Vect3 = DOWN, buff: float = 0.2, tex_string: str = R"\underbrace{\qquad}", **kwargs ): super().__init__(tex_string, **kwargs) angle = -math.atan2(*direction[:2]) + PI mobject.rotate(-angle, about_point=ORIGIN) left = mobject.get_corner(DL) right = mobject.get_corner(DR) target_width = right[0] - left[0] self.tip_point_index = np.argmin(self.get_all_points()[:, 1]) self.set_initial_width(target_width) self.shift(left - self.get_corner(UL) + buff * DOWN) for mob in mobject, self: mob.rotate(angle, about_point=ORIGIN) def set_initial_width(self, width: float): width_diff = width - self.get_width() if width_diff > 0: for tip, rect, vect in [(self[0], self[1], RIGHT), (self[5], self[4], LEFT)]: rect.set_width( width_diff / 2 + rect.get_width(), about_edge=vect, stretch=True ) tip.shift(-width_diff / 2 * vect) else: self.set_width(width, stretch=True) return self def put_at_tip( self, mob: Mobject, use_next_to: bool = True, **kwargs ): if use_next_to: mob.next_to( self.get_tip(), np.round(self.get_direction()), **kwargs ) else: mob.move_to(self.get_tip()) buff = kwargs.get("buff", DEFAULT_MOBJECT_TO_MOBJECT_BUFF) shift_distance = mob.get_width() / 2.0 + buff mob.shift(self.get_direction() * shift_distance) return self def get_text(self, text: str, **kwargs) -> Text: buff = kwargs.pop("buff", SMALL_BUFF) text_mob = Text(text, **kwargs) self.put_at_tip(text_mob, buff=buff) return text_mob def get_tex(self, *tex: str, **kwargs) -> Tex: buff = kwargs.pop("buff", SMALL_BUFF) tex_mob = Tex(*tex, **kwargs) self.put_at_tip(tex_mob, buff=buff) return tex_mob def get_tip(self) -> np.ndarray: # Very specific to the LaTeX representation # of a brace, but it's the only way I can think # of to get the tip regardless of orientation. return self.get_all_points()[self.tip_point_index] def get_direction(self) -> np.ndarray: vect = self.get_tip() - self.get_center() return vect / get_norm(vect) class BraceLabel(VMobject): label_constructor: type = Tex def __init__( self, obj: VMobject | list[VMobject], text: str | Iterable[str], brace_direction: np.ndarray = DOWN, label_scale: float = 1.0, label_buff: float = DEFAULT_MOBJECT_TO_MOBJECT_BUFF, **kwargs ) -> None: super().__init__(**kwargs) self.brace_direction = brace_direction self.label_scale = label_scale self.label_buff = label_buff if isinstance(obj, list): obj = VGroup(*obj) self.brace = Brace(obj, brace_direction, **kwargs) self.label = self.label_constructor(*listify(text), **kwargs) self.label.scale(self.label_scale) self.brace.put_at_tip(self.label, buff=self.label_buff) self.set_submobjects([self.brace, self.label]) def creation_anim( self, label_anim: Animation = FadeIn, brace_anim: Animation = GrowFromCenter ) -> AnimationGroup: return AnimationGroup(brace_anim(self.brace), label_anim(self.label)) def shift_brace(self, obj: VMobject | list[VMobject], **kwargs): if isinstance(obj, list): obj = VMobject(*obj) self.brace = Brace(obj, self.brace_direction, **kwargs) self.brace.put_at_tip(self.label) self.submobjects[0] = self.brace return self def change_label(self, *text: str, **kwargs): self.label = self.label_constructor(*text, **kwargs) if self.label_scale != 1: self.label.scale(self.label_scale) self.brace.put_at_tip(self.label) self.submobjects[1] = self.label return self def change_brace_label(self, obj: VMobject | list[VMobject], *text: str): self.shift_brace(obj) self.change_label(*text) return self def copy(self): copy_mobject = copy.copy(self) copy_mobject.brace = self.brace.copy() copy_mobject.label = self.label.copy() copy_mobject.set_submobjects([copy_mobject.brace, copy_mobject.label]) return copy_mobject class BraceText(BraceLabel): label_constructor: type = TexText class LineBrace(Brace): def __init__(self, line: Line, direction=UP, **kwargs): angle = line.get_angle() line.rotate(-angle) super().__init__(line, direction, **kwargs) line.rotate(angle) self.rotate(angle, about_point=line.get_center())
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/indication.py
manimlib/animation/indication.py
from __future__ import annotations import numpy as np from manimlib.animation.animation import Animation from manimlib.animation.composition import AnimationGroup from manimlib.animation.composition import Succession from manimlib.animation.creation import ShowCreation from manimlib.animation.creation import ShowPartial from manimlib.animation.fading import FadeOut from manimlib.animation.fading import FadeIn from manimlib.animation.movement import Homotopy from manimlib.animation.transform import Transform from manimlib.constants import FRAME_X_RADIUS, FRAME_Y_RADIUS from manimlib.constants import ORIGIN, RIGHT, UP from manimlib.constants import SMALL_BUFF from manimlib.constants import DEG from manimlib.constants import TAU from manimlib.constants import GREY, YELLOW from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Dot from manimlib.mobject.geometry import Line from manimlib.mobject.shape_matchers import SurroundingRectangle from manimlib.mobject.shape_matchers import Underline from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.utils.bezier import interpolate from manimlib.utils.rate_functions import smooth from manimlib.utils.rate_functions import squish_rate_func from manimlib.utils.rate_functions import there_and_back from manimlib.utils.rate_functions import wiggle from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import ManimColor from manimlib.mobject.mobject import Mobject class FocusOn(Transform): def __init__( self, focus_point: np.ndarray | Mobject, opacity: float = 0.2, color: ManimColor = GREY, run_time: float = 2, remover: bool = True, **kwargs ): self.focus_point = focus_point self.opacity = opacity self.color = color # Initialize with blank mobject, while create_target # and create_starting_mobject handle the meat super().__init__(VMobject(), run_time=run_time, remover=remover, **kwargs) def create_target(self) -> Dot: little_dot = Dot(radius=0) little_dot.set_fill(self.color, opacity=self.opacity) little_dot.add_updater(lambda d: d.move_to(self.focus_point)) return little_dot def create_starting_mobject(self) -> Dot: return Dot( radius=FRAME_X_RADIUS + FRAME_Y_RADIUS, stroke_width=0, fill_color=self.color, fill_opacity=0, ) class Indicate(Transform): def __init__( self, mobject: Mobject, scale_factor: float = 1.2, color: ManimColor = YELLOW, rate_func: Callable[[float], float] = there_and_back, **kwargs ): self.scale_factor = scale_factor self.color = color super().__init__(mobject, rate_func=rate_func, **kwargs) def create_target(self) -> Mobject: target = self.mobject.copy() target.scale(self.scale_factor) target.set_color(self.color) return target class Flash(AnimationGroup): def __init__( self, point: np.ndarray | Mobject, color: ManimColor = YELLOW, line_length: float = 0.2, num_lines: int = 12, flash_radius: float = 0.3, line_stroke_width: float = 3.0, run_time: float = 1.0, **kwargs ): self.point = point self.color = color self.line_length = line_length self.num_lines = num_lines self.flash_radius = flash_radius self.line_stroke_width = line_stroke_width self.lines = self.create_lines() animations = self.create_line_anims() super().__init__( *animations, group=self.lines, run_time=run_time, **kwargs, ) def create_lines(self) -> VGroup: lines = VGroup() for angle in np.arange(0, TAU, TAU / self.num_lines): line = Line(ORIGIN, self.line_length * RIGHT) line.shift((self.flash_radius - self.line_length) * RIGHT) line.rotate(angle, about_point=ORIGIN) lines.add(line) lines.set_stroke( color=self.color, width=self.line_stroke_width ) lines.add_updater(lambda l: l.move_to(self.point)) return lines def create_line_anims(self) -> list[Animation]: return [ ShowCreationThenDestruction(line) for line in self.lines ] class CircleIndicate(Transform): def __init__( self, mobject: Mobject, scale_factor: float = 1.2, rate_func: Callable[[float], float] = there_and_back, stroke_color: ManimColor = YELLOW, stroke_width: float = 3.0, remover: bool = True, **kwargs ): circle = Circle(stroke_color=stroke_color, stroke_width=stroke_width) circle.surround(mobject) pre_circle = circle.copy().set_stroke(width=0) pre_circle.scale(1 / scale_factor) super().__init__( pre_circle, circle, rate_func=rate_func, remover=remover, **kwargs ) class ShowPassingFlash(ShowPartial): def __init__( self, mobject: Mobject, time_width: float = 0.1, remover: bool = True, **kwargs ): self.time_width = time_width super().__init__( mobject, remover=remover, **kwargs ) def get_bounds(self, alpha: float) -> tuple[float, float]: tw = self.time_width upper = interpolate(0, 1 + tw, alpha) lower = upper - tw upper = min(upper, 1) lower = max(lower, 0) return (lower, upper) def finish(self) -> None: super().finish() for submob, start in self.get_all_families_zipped(): submob.pointwise_become_partial(start, 0, 1) class VShowPassingFlash(Animation): def __init__( self, vmobject: VMobject, time_width: float = 0.3, taper_width: float = 0.05, remover: bool = True, **kwargs ): self.time_width = time_width self.taper_width = taper_width super().__init__(vmobject, remover=remover, **kwargs) self.mobject = vmobject def taper_kernel(self, x): if x < self.taper_width: return x elif x > 1 - self.taper_width: return 1.0 - x return 1.0 def begin(self) -> None: # Compute an array of stroke widths for each submobject # which tapers out at either end self.submob_to_widths = dict() for sm in self.mobject.get_family(): widths = sm.get_stroke_widths() self.submob_to_widths[hash(sm)] = np.array([ width * self.taper_kernel(x) for width, x in zip(widths, np.linspace(0, 1, len(widths))) ]) super().begin() def interpolate_submobject( self, submobject: VMobject, starting_sumobject: None, alpha: float ) -> None: widths = self.submob_to_widths[hash(submobject)] # Create a gaussian such that 3 sigmas out on either side # will equals time_width tw = self.time_width sigma = tw / 6 mu = interpolate(-tw / 2, 1 + tw / 2, alpha) xs = np.linspace(0, 1, len(widths)) zs = (xs - mu) / sigma gaussian = np.exp(-0.5 * zs * zs) gaussian[abs(xs - mu) > 3 * sigma] = 0 if len(widths * gaussian) !=0: submobject.set_stroke(width=widths * gaussian) def finish(self) -> None: super().finish() for submob, start in self.get_all_families_zipped(): submob.match_style(start) class FlashAround(VShowPassingFlash): def __init__( self, mobject: Mobject, time_width: float = 1.0, taper_width: float = 0.0, stroke_width: float = 4.0, color: ManimColor = YELLOW, buff: float = SMALL_BUFF, n_inserted_curves: int = 100, **kwargs ): path = self.get_path(mobject, buff) if mobject.is_fixed_in_frame(): path.fix_in_frame() path.insert_n_curves(n_inserted_curves) path.set_points(path.get_points_without_null_curves()) path.set_stroke(color, stroke_width) super().__init__(path, time_width=time_width, taper_width=taper_width, **kwargs) def get_path(self, mobject: Mobject, buff: float) -> SurroundingRectangle: return SurroundingRectangle(mobject, buff=buff) class FlashUnder(FlashAround): def get_path(self, mobject: Mobject, buff: float) -> Underline: return Underline(mobject, buff=buff, stretch_factor=1.0) class ShowCreationThenDestruction(ShowPassingFlash): def __init__(self, vmobject: VMobject, time_width: float = 2.0, **kwargs): super().__init__(vmobject, time_width=time_width, **kwargs) class ShowCreationThenFadeOut(Succession): def __init__(self, mobject: Mobject, remover: bool = True, **kwargs): super().__init__( ShowCreation(mobject), FadeOut(mobject), remover=remover, **kwargs ) class AnimationOnSurroundingRectangle(AnimationGroup): RectAnimationType: type = Animation def __init__( self, mobject: Mobject, stroke_width: float = 2.0, stroke_color: ManimColor = YELLOW, buff: float = SMALL_BUFF, **kwargs ): rect = SurroundingRectangle( mobject, stroke_width=stroke_width, stroke_color=stroke_color, buff=buff, ) rect.add_updater(lambda r: r.move_to(mobject)) super().__init__(self.RectAnimationType(rect, **kwargs)) class ShowPassingFlashAround(AnimationOnSurroundingRectangle): RectAnimationType = ShowPassingFlash class ShowCreationThenDestructionAround(AnimationOnSurroundingRectangle): RectAnimationType = ShowCreationThenDestruction class ShowCreationThenFadeAround(AnimationOnSurroundingRectangle): RectAnimationType = ShowCreationThenFadeOut class ApplyWave(Homotopy): def __init__( self, mobject: Mobject, direction: np.ndarray = UP, amplitude: float = 0.2, run_time: float = 1.0, **kwargs ): left_x = mobject.get_left()[0] right_x = mobject.get_right()[0] vect = amplitude * direction def homotopy(x, y, z, t): alpha = (x - left_x) / (right_x - left_x) power = np.exp(2.0 * (alpha - 0.5)) nudge = there_and_back(t**power) return np.array([x, y, z]) + nudge * vect super().__init__(homotopy, mobject, **kwargs) class WiggleOutThenIn(Animation): def __init__( self, mobject: Mobject, scale_value: float = 1.1, rotation_angle: float = 0.01 * TAU, n_wiggles: int = 6, scale_about_point: np.ndarray | None = None, rotate_about_point: np.ndarray | None = None, run_time: float = 2, **kwargs ): self.scale_value = scale_value self.rotation_angle = rotation_angle self.n_wiggles = n_wiggles self.scale_about_point = scale_about_point self.rotate_about_point = rotate_about_point super().__init__(mobject, run_time=run_time, **kwargs) def get_scale_about_point(self) -> np.ndarray: return self.scale_about_point or self.mobject.get_center() def get_rotate_about_point(self) -> np.ndarray: return self.rotate_about_point or self.mobject.get_center() def interpolate_submobject( self, submobject: Mobject, starting_sumobject: Mobject, alpha: float ) -> None: submobject.match_points(starting_sumobject) submobject.scale( interpolate(1, self.scale_value, there_and_back(alpha)), about_point=self.get_scale_about_point() ) submobject.rotate( wiggle(alpha, self.n_wiggles) * self.rotation_angle, about_point=self.get_rotate_about_point() ) class TurnInsideOut(Transform): def __init__(self, mobject: Mobject, path_arc: float = 90 * DEG, **kwargs): super().__init__(mobject, path_arc=path_arc, **kwargs) def create_target(self) -> Mobject: result = self.mobject.copy().reverse_points() if isinstance(result, VMobject): result.refresh_triangulation() return result class FlashyFadeIn(AnimationGroup): def __init__(self, vmobject: VMobject, stroke_width: float = 2.0, fade_lag: float = 0.0, time_width: float = 1.0, **kwargs ): outline = vmobject.copy() outline.set_fill(opacity=0) outline.set_stroke(width=stroke_width, opacity=1) rate_func = kwargs.get("rate_func", smooth) super().__init__( FadeIn(vmobject, rate_func=squish_rate_func(rate_func, fade_lag, 1)), VShowPassingFlash(outline, time_width=time_width), **kwargs )
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/rotation.py
manimlib/animation/rotation.py
from __future__ import annotations from manimlib.animation.animation import Animation from manimlib.constants import ORIGIN, OUT from manimlib.constants import PI, TAU from manimlib.utils.rate_functions import linear from manimlib.utils.rate_functions import smooth from typing import TYPE_CHECKING if TYPE_CHECKING: import numpy as np from typing import Callable from manimlib.mobject.mobject import Mobject class Rotating(Animation): def __init__( self, mobject: Mobject, angle: float = TAU, axis: np.ndarray = OUT, about_point: np.ndarray | None = None, about_edge: np.ndarray | None = None, run_time: float = 5.0, rate_func: Callable[[float], float] = linear, suspend_mobject_updating: bool = False, **kwargs ): self.angle = angle self.axis = axis self.about_point = about_point self.about_edge = about_edge super().__init__( mobject, run_time=run_time, rate_func=rate_func, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_mobject(self, alpha: float) -> None: pairs = zip( self.mobject.family_members_with_points(), self.starting_mobject.family_members_with_points(), ) for sm1, sm2 in pairs: for key in sm1.pointlike_data_keys: sm1.data[key][:] = sm2.data[key] self.mobject.rotate( self.rate_func(self.time_spanned_alpha(alpha)) * self.angle, axis=self.axis, about_point=self.about_point, about_edge=self.about_edge, ) class Rotate(Rotating): def __init__( self, mobject: Mobject, angle: float = PI, axis: np.ndarray = OUT, run_time: float = 1, rate_func: Callable[[float], float] = smooth, about_edge: np.ndarray = ORIGIN, **kwargs ): super().__init__( mobject, angle, axis, run_time=run_time, rate_func=rate_func, about_edge=about_edge, **kwargs )
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/transform.py
manimlib/animation/transform.py
from __future__ import annotations import inspect import numpy as np from manimlib.animation.animation import Animation from manimlib.constants import DEG from manimlib.constants import OUT from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Mobject from manimlib.utils.paths import path_along_arc from manimlib.utils.paths import straight_path from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable import numpy.typing as npt from manimlib.scene.scene import Scene from manimlib.typing import ManimColor class Transform(Animation): replace_mobject_with_target_in_scene: bool = False def __init__( self, mobject: Mobject, target_mobject: Mobject | None = None, path_arc: float = 0.0, path_arc_axis: np.ndarray = OUT, path_func: Callable | None = None, **kwargs ): self.target_mobject = target_mobject self.path_arc = path_arc self.path_arc_axis = path_arc_axis self.path_func = path_func super().__init__(mobject, **kwargs) self.init_path_func() def init_path_func(self) -> None: if self.path_func is not None: return elif self.path_arc == 0: self.path_func = straight_path else: self.path_func = path_along_arc( self.path_arc, self.path_arc_axis, ) def begin(self) -> None: self.target_mobject = self.create_target() self.check_target_mobject_validity() if self.mobject.is_aligned_with(self.target_mobject): self.target_copy = self.target_mobject else: # Use a copy of target_mobject for the align_data_and_family # call so that the actual target_mobject stays # preserved, since calling align_data will potentially # change the structure of both arguments self.target_copy = self.target_mobject.copy() self.mobject.align_data_and_family(self.target_copy) super().begin() if not self.mobject.has_updaters(): self.mobject.lock_matching_data( self.starting_mobject, self.target_copy, ) def finish(self) -> None: super().finish() self.mobject.unlock_data() def create_target(self) -> Mobject: # Has no meaningful effect here, but may be useful # in subclasses return self.target_mobject def check_target_mobject_validity(self) -> None: if self.target_mobject is None: raise Exception( f"{self.__class__.__name__}.create_target not properly implemented" ) def clean_up_from_scene(self, scene: Scene) -> None: super().clean_up_from_scene(scene) if self.replace_mobject_with_target_in_scene: scene.remove(self.mobject) scene.add(self.target_mobject) def update_config(self, **kwargs) -> None: Animation.update_config(self, **kwargs) if "path_arc" in kwargs: self.path_func = path_along_arc( kwargs["path_arc"], kwargs.get("path_arc_axis", OUT) ) def get_all_mobjects(self) -> list[Mobject]: return [ self.mobject, self.starting_mobject, self.target_mobject, self.target_copy, ] def get_all_families_zipped(self) -> zip[tuple[Mobject]]: return zip(*[ mob.get_family() for mob in [ self.mobject, self.starting_mobject, self.target_copy, ] ]) def interpolate_submobject( self, submob: Mobject, start: Mobject, target_copy: Mobject, alpha: float ): submob.interpolate(start, target_copy, alpha, self.path_func) return self class ReplacementTransform(Transform): replace_mobject_with_target_in_scene: bool = True class TransformFromCopy(Transform): replace_mobject_with_target_in_scene: bool = True def __init__(self, mobject: Mobject, target_mobject: Mobject, **kwargs): super().__init__(mobject.copy(), target_mobject, **kwargs) class MoveToTarget(Transform): def __init__(self, mobject: Mobject, **kwargs): self.check_validity_of_input(mobject) super().__init__(mobject, mobject.target, **kwargs) def check_validity_of_input(self, mobject: Mobject) -> None: if not hasattr(mobject, "target"): raise Exception( "MoveToTarget called on mobject without attribute 'target'" ) class _MethodAnimation(MoveToTarget): def __init__(self, mobject: Mobject, methods: list[Callable], **kwargs): self.methods = methods super().__init__(mobject, **kwargs) class ApplyMethod(Transform): def __init__(self, method: Callable, *args, **kwargs): """ method is a method of Mobject, *args are arguments for that method. Key word arguments should be passed in as the last arg, as a dict, since **kwargs is for configuration of the transform itself Relies on the fact that mobject methods return the mobject """ self.check_validity_of_input(method) self.method = method self.method_args = args super().__init__(method.__self__, **kwargs) def check_validity_of_input(self, method: Callable) -> None: if not inspect.ismethod(method): raise Exception( "Whoops, looks like you accidentally invoked " "the method you want to animate" ) assert isinstance(method.__self__, Mobject) def create_target(self) -> Mobject: method = self.method # Make sure it's a list so that args.pop() works args = list(self.method_args) if len(args) > 0 and isinstance(args[-1], dict): method_kwargs = args.pop() else: method_kwargs = {} target = method.__self__.copy() method.__func__(target, *args, **method_kwargs) return target class ApplyPointwiseFunction(ApplyMethod): def __init__( self, function: Callable[[np.ndarray], np.ndarray], mobject: Mobject, run_time: float = 3.0, **kwargs ): super().__init__(mobject.apply_function, function, run_time=run_time, **kwargs) class ApplyPointwiseFunctionToCenter(Transform): def __init__( self, function: Callable[[np.ndarray], np.ndarray], mobject: Mobject, **kwargs ): self.function = function super().__init__(mobject, **kwargs) def create_target(self) -> Mobject: return self.mobject.copy().move_to(self.function(self.mobject.get_center())) class FadeToColor(ApplyMethod): def __init__( self, mobject: Mobject, color: ManimColor, **kwargs ): super().__init__(mobject.set_color, color, **kwargs) class ScaleInPlace(ApplyMethod): def __init__( self, mobject: Mobject, scale_factor: npt.ArrayLike, **kwargs ): super().__init__(mobject.scale, scale_factor, **kwargs) class ShrinkToCenter(ScaleInPlace): def __init__(self, mobject: Mobject, **kwargs): super().__init__(mobject, 0, **kwargs) class Restore(Transform): def __init__(self, mobject: Mobject, **kwargs): if not hasattr(mobject, "saved_state") or mobject.saved_state is None: raise Exception("Trying to restore without having saved") super().__init__(mobject, mobject.saved_state, **kwargs) class ApplyFunction(Transform): def __init__( self, function: Callable[[Mobject], Mobject], mobject: Mobject, **kwargs ): self.function = function super().__init__(mobject, **kwargs) def create_target(self) -> Mobject: target = self.function(self.mobject.copy()) if not isinstance(target, Mobject): raise Exception("Functions passed to ApplyFunction must return object of type Mobject") return target class ApplyMatrix(ApplyPointwiseFunction): def __init__( self, matrix: npt.ArrayLike, mobject: Mobject, **kwargs ): matrix = self.initialize_matrix(matrix) def func(p): return np.dot(p, matrix.T) super().__init__(func, mobject, **kwargs) def initialize_matrix(self, matrix: npt.ArrayLike) -> np.ndarray: matrix = np.array(matrix) if matrix.shape == (2, 2): new_matrix = np.identity(3) new_matrix[:2, :2] = matrix matrix = new_matrix elif matrix.shape != (3, 3): raise Exception("Matrix has bad dimensions") return matrix class ApplyComplexFunction(ApplyMethod): def __init__( self, function: Callable[[complex], complex], mobject: Mobject, **kwargs ): self.function = function method = mobject.apply_complex_function super().__init__(method, function, **kwargs) def init_path_func(self) -> None: func1 = self.function(complex(1)) self.path_arc = np.log(func1).imag super().init_path_func() ### class CyclicReplace(Transform): def __init__(self, *mobjects: Mobject, path_arc=90 * DEG, **kwargs): super().__init__(Group(*mobjects), path_arc=path_arc, **kwargs) def create_target(self) -> Mobject: group = self.mobject target = group.copy() cycled_targets = [target[-1], *target[:-1]] for m1, m2 in zip(cycled_targets, group): m1.move_to(m2) return target class Swap(CyclicReplace): """Alternate name for CyclicReplace""" pass
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/numbers.py
manimlib/animation/numbers.py
from __future__ import annotations from manimlib.animation.animation import Animation from manimlib.mobject.numbers import DecimalNumber from manimlib.utils.bezier import interpolate from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable class ChangingDecimal(Animation): def __init__( self, decimal_mob: DecimalNumber, number_update_func: Callable[[float], float], suspend_mobject_updating: bool = False, **kwargs ): assert isinstance(decimal_mob, DecimalNumber) self.number_update_func = number_update_func super().__init__( decimal_mob, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) self.mobject = decimal_mob def interpolate_mobject(self, alpha: float) -> None: true_alpha = self.time_spanned_alpha(alpha) new_value = self.number_update_func(true_alpha) self.mobject.set_value(new_value) class ChangeDecimalToValue(ChangingDecimal): def __init__( self, decimal_mob: DecimalNumber, target_number: float | complex, **kwargs ): start_number = decimal_mob.number super().__init__( decimal_mob, lambda a: interpolate(start_number, target_number, a), **kwargs ) class CountInFrom(ChangingDecimal): def __init__( self, decimal_mob: DecimalNumber, source_number: float | complex = 0, **kwargs ): start_number = decimal_mob.get_value() super().__init__( decimal_mob, lambda a: interpolate(source_number, start_number, clip(a, 0, 1)), **kwargs )
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/creation.py
manimlib/animation/creation.py
from __future__ import annotations from abc import ABC, abstractmethod import numpy as np from manimlib.animation.animation import Animation from manimlib.mobject.svg.string_mobject import StringMobject from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import integer_interpolate from manimlib.utils.rate_functions import linear from manimlib.utils.rate_functions import double_smooth from manimlib.utils.rate_functions import smooth from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.mobject.mobject import Mobject from manimlib.scene.scene import Scene from manimlib.typing import ManimColor class ShowPartial(Animation, ABC): """ Abstract class for ShowCreation and ShowPassingFlash """ def __init__(self, mobject: Mobject, should_match_start: bool = False, **kwargs): self.should_match_start = should_match_start super().__init__(mobject, **kwargs) def interpolate_submobject( self, submob: VMobject, start_submob: VMobject, alpha: float ) -> None: submob.pointwise_become_partial( start_submob, *self.get_bounds(alpha) ) @abstractmethod def get_bounds(self, alpha: float) -> tuple[float, float]: raise Exception("Not Implemented") class ShowCreation(ShowPartial): def __init__(self, mobject: Mobject, lag_ratio: float = 1.0, **kwargs): super().__init__(mobject, lag_ratio=lag_ratio, **kwargs) def get_bounds(self, alpha: float) -> tuple[float, float]: return (0, alpha) class Uncreate(ShowCreation): def __init__( self, mobject: Mobject, rate_func: Callable[[float], float] = lambda t: smooth(1 - t), remover: bool = True, should_match_start: bool = True, **kwargs, ): super().__init__( mobject, rate_func=rate_func, remover=remover, should_match_start=should_match_start, **kwargs, ) class DrawBorderThenFill(Animation): def __init__( self, vmobject: VMobject, run_time: float = 2.0, rate_func: Callable[[float], float] = double_smooth, stroke_width: float = 2.0, stroke_color: ManimColor = None, draw_border_animation_config: dict = {}, fill_animation_config: dict = {}, **kwargs ): assert isinstance(vmobject, VMobject) self.sm_to_index = {hash(sm): 0 for sm in vmobject.get_family()} self.stroke_width = stroke_width self.stroke_color = stroke_color self.draw_border_animation_config = draw_border_animation_config self.fill_animation_config = fill_animation_config super().__init__( vmobject, run_time=run_time, rate_func=rate_func, **kwargs ) self.mobject = vmobject def begin(self) -> None: self.mobject.set_animating_status(True) self.outline = self.get_outline() super().begin() self.mobject.match_style(self.outline) def finish(self) -> None: super().finish() self.mobject.refresh_joint_angles() def get_outline(self) -> VMobject: outline = self.mobject.copy() outline.set_fill(opacity=0) for sm in outline.family_members_with_points(): sm.set_stroke( color=self.stroke_color or sm.get_stroke_color(), width=self.stroke_width, behind=self.mobject.stroke_behind, ) return outline def get_all_mobjects(self) -> list[Mobject]: return [*super().get_all_mobjects(), self.outline] def interpolate_submobject( self, submob: VMobject, start: VMobject, outline: VMobject, alpha: float ) -> None: index, subalpha = integer_interpolate(0, 2, alpha) if index == 1 and self.sm_to_index[hash(submob)] == 0: # First time crossing over submob.set_data(outline.data) self.sm_to_index[hash(submob)] = 1 if index == 0: submob.pointwise_become_partial(outline, 0, subalpha) else: submob.interpolate(outline, start, subalpha) class Write(DrawBorderThenFill): def __init__( self, vmobject: VMobject, run_time: float = -1, # If negative, this will be reassigned lag_ratio: float = -1, # If negative, this will be reassigned rate_func: Callable[[float], float] = linear, stroke_color: ManimColor = None, **kwargs ): if stroke_color is None: stroke_color = vmobject.get_color() family_size = len(vmobject.family_members_with_points()) super().__init__( vmobject, run_time=self.compute_run_time(family_size, run_time), lag_ratio=self.compute_lag_ratio(family_size, lag_ratio), rate_func=rate_func, stroke_color=stroke_color, **kwargs ) def compute_run_time(self, family_size: int, run_time: float): if run_time < 0: return 1 if family_size < 15 else 2 return run_time def compute_lag_ratio(self, family_size: int, lag_ratio: float): if lag_ratio < 0: return min(4.0 / (family_size + 1.0), 0.2) return lag_ratio class ShowIncreasingSubsets(Animation): def __init__( self, group: Mobject, int_func: Callable[[float], float] = np.round, suspend_mobject_updating: bool = False, **kwargs ): self.all_submobs = list(group.submobjects) self.int_func = int_func super().__init__( group, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_mobject(self, alpha: float) -> None: n_submobs = len(self.all_submobs) alpha = self.rate_func(alpha) index = int(self.int_func(alpha * n_submobs)) self.update_submobject_list(index) def update_submobject_list(self, index: int) -> None: self.mobject.set_submobjects(self.all_submobs[:index]) class ShowSubmobjectsOneByOne(ShowIncreasingSubsets): def __init__( self, group: Mobject, int_func: Callable[[float], float] = np.ceil, **kwargs ): super().__init__(group, int_func=int_func, **kwargs) def update_submobject_list(self, index: int) -> None: index = int(clip(index, 0, len(self.all_submobs) - 1)) if index == 0: self.mobject.set_submobjects([]) else: self.mobject.set_submobjects([self.all_submobs[index - 1]]) class AddTextWordByWord(ShowIncreasingSubsets): def __init__( self, string_mobject: StringMobject, time_per_word: float = 0.2, run_time: float = -1.0, # If negative, it will be recomputed with time_per_word rate_func: Callable[[float], float] = linear, **kwargs ): assert isinstance(string_mobject, StringMobject) grouped_mobject = string_mobject.build_groups() if run_time < 0: run_time = time_per_word * len(grouped_mobject) super().__init__( grouped_mobject, run_time=run_time, rate_func=rate_func, **kwargs ) self.string_mobject = string_mobject def clean_up_from_scene(self, scene: Scene) -> None: scene.remove(self.mobject) if not self.is_remover(): scene.add(self.string_mobject)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/update.py
manimlib/animation/update.py
from __future__ import annotations from manimlib.animation.animation import Animation from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.mobject.mobject import Mobject class UpdateFromFunc(Animation): """ update_function of the form func(mobject), presumably to be used when the state of one mobject is dependent on another simultaneously animated mobject """ def __init__( self, mobject: Mobject, update_function: Callable[[Mobject], Mobject | None], suspend_mobject_updating: bool = False, **kwargs ): self.update_function = update_function super().__init__( mobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_mobject(self, alpha: float) -> None: self.update_function(self.mobject) class UpdateFromAlphaFunc(Animation): def __init__( self, mobject: Mobject, update_function: Callable[[Mobject, float], Mobject | None], suspend_mobject_updating: bool = False, **kwargs ): self.update_function = update_function super().__init__(mobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs) def interpolate_mobject(self, alpha: float) -> None: true_alpha = self.rate_func(self.time_spanned_alpha(alpha)) self.update_function(self.mobject, true_alpha) class MaintainPositionRelativeTo(Animation): def __init__( self, mobject: Mobject, tracked_mobject: Mobject, **kwargs ): self.tracked_mobject = tracked_mobject self.diff = mobject.get_center() - tracked_mobject.get_center() super().__init__(mobject, **kwargs) def interpolate_mobject(self, alpha: float) -> None: target = self.tracked_mobject.get_center() location = self.mobject.get_center() self.mobject.shift(target - location + self.diff)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/growing.py
manimlib/animation/growing.py
from __future__ import annotations from manimlib.animation.transform import Transform from typing import TYPE_CHECKING if TYPE_CHECKING: import numpy as np from manimlib.mobject.geometry import Arrow from manimlib.mobject.mobject import Mobject from manimlib.typing import ManimColor class GrowFromPoint(Transform): def __init__( self, mobject: Mobject, point: np.ndarray, point_color: ManimColor = None, **kwargs ): self.point = point self.point_color = point_color super().__init__(mobject, **kwargs) def create_target(self) -> Mobject: return self.mobject.copy() def create_starting_mobject(self) -> Mobject: start = super().create_starting_mobject() start.scale(0) start.move_to(self.point) if self.point_color is not None: start.set_color(self.point_color) return start class GrowFromCenter(GrowFromPoint): def __init__(self, mobject: Mobject, **kwargs): point = mobject.get_center() super().__init__(mobject, point, **kwargs) class GrowFromEdge(GrowFromPoint): def __init__(self, mobject: Mobject, edge: np.ndarray, **kwargs): point = mobject.get_bounding_box_point(edge) super().__init__(mobject, point, **kwargs) class GrowArrow(GrowFromPoint): def __init__(self, arrow: Arrow, **kwargs): point = arrow.get_start() super().__init__(arrow, point, **kwargs)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/specialized.py
manimlib/animation/specialized.py
from __future__ import annotations from manimlib.animation.composition import LaggedStart from manimlib.animation.transform import Restore from manimlib.constants import BLACK, WHITE from manimlib.mobject.geometry import Circle from manimlib.mobject.types.vectorized_mobject import VGroup from typing import TYPE_CHECKING if TYPE_CHECKING: import numpy as np from manimlib.typing import ManimColor class Broadcast(LaggedStart): def __init__( self, focal_point: np.ndarray, small_radius: float = 0.0, big_radius: float = 5.0, n_circles: int = 5, start_stroke_width: float = 8.0, color: ManimColor = WHITE, run_time: float = 3.0, lag_ratio: float = 0.2, remover: bool = True, **kwargs ): self.focal_point = focal_point self.small_radius = small_radius self.big_radius = big_radius self.n_circles = n_circles self.start_stroke_width = start_stroke_width self.color = color circles = VGroup() for x in range(n_circles): circle = Circle( radius=big_radius, stroke_color=BLACK, stroke_width=0, ) circle.add_updater(lambda c: c.move_to(focal_point)) circle.save_state() circle.set_width(small_radius * 2) circle.set_stroke(color, start_stroke_width) circles.add(circle) super().__init__( *map(Restore, circles), run_time=run_time, lag_ratio=lag_ratio, remover=remover, **kwargs )
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/__init__.py
manimlib/animation/__init__.py
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/animation.py
manimlib/animation/animation.py
from __future__ import annotations from copy import deepcopy from manimlib.mobject.mobject import _AnimationBuilder from manimlib.mobject.mobject import Mobject from manimlib.utils.iterables import remove_list_redundancies from manimlib.utils.rate_functions import smooth from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.scene.scene import Scene DEFAULT_ANIMATION_RUN_TIME = 1.0 DEFAULT_ANIMATION_LAG_RATIO = 0 class Animation(object): def __init__( self, mobject: Mobject, run_time: float = DEFAULT_ANIMATION_RUN_TIME, # Tuple of times, between which the animation will run time_span: tuple[float, float] | None = None, # If 0, the animation is applied to all submobjects at the same time # If 1, it is applied to each successively. # If 0 < lag_ratio < 1, its applied to each with lagged start times lag_ratio: float = DEFAULT_ANIMATION_LAG_RATIO, rate_func: Callable[[float], float] = smooth, name: str = "", # Does this animation add or remove a mobject from the screen remover: bool = False, # What to enter into the update function upon completion final_alpha_value: float = 1.0, # If set to True, the mobject itself will have its internal updaters called, # but the start or target mobjects would not be suspended. To completely suspend # updating, call mobject.suspend_updating() before the animation suspend_mobject_updating: bool = False, ): self._validate_input_type(mobject) self.mobject = mobject self.run_time = run_time self.time_span = time_span self.rate_func = rate_func self.name = name or self.__class__.__name__ + str(self.mobject) self.remover = remover self.final_alpha_value = final_alpha_value self.lag_ratio = lag_ratio self.suspend_mobject_updating = suspend_mobject_updating def _validate_input_type(self, mobject: Mobject) -> None: if not isinstance(mobject, Mobject): raise TypeError("Animation only works for Mobjects.") def __str__(self) -> str: return self.name def begin(self) -> None: # This is called right as an animation is being # played. As much initialization as possible, # especially any mobject copying, should live in # this method if self.time_span is not None: start, end = self.time_span self.run_time = max(end, self.run_time) self.mobject.set_animating_status(True) self.starting_mobject = self.create_starting_mobject() if self.suspend_mobject_updating: self.mobject_was_updating = not self.mobject.updating_suspended self.mobject.suspend_updating() self.families = list(self.get_all_families_zipped()) self.interpolate(0) def finish(self) -> None: self.interpolate(self.final_alpha_value) self.mobject.set_animating_status(False) if self.suspend_mobject_updating and self.mobject_was_updating: self.mobject.resume_updating() def clean_up_from_scene(self, scene: Scene) -> None: if self.is_remover(): scene.remove(self.mobject) def create_starting_mobject(self) -> Mobject: # Keep track of where the mobject starts return self.mobject.copy() def get_all_mobjects(self) -> tuple[Mobject, Mobject]: """ Ordering must match the ording of arguments to interpolate_submobject """ return self.mobject, self.starting_mobject def get_all_families_zipped(self) -> zip[tuple[Mobject]]: return zip(*[ mob.get_family() for mob in self.get_all_mobjects() ]) def update_mobjects(self, dt: float) -> None: """ Updates things like starting_mobject, and (for Transforms) target_mobject. """ for mob in self.get_all_mobjects_to_update(): mob.update(dt) def get_all_mobjects_to_update(self) -> list[Mobject]: # The surrounding scene typically handles # updating of self.mobject. items = list(filter( lambda m: m is not self.mobject, self.get_all_mobjects() )) items = remove_list_redundancies(items) return items def copy(self): return deepcopy(self) def update_rate_info( self, run_time: float | None = None, rate_func: Callable[[float], float] | None = None, lag_ratio: float | None = None, ): self.run_time = run_time or self.run_time self.rate_func = rate_func or self.rate_func self.lag_ratio = lag_ratio or self.lag_ratio return self # Methods for interpolation, the mean of an Animation def interpolate(self, alpha: float) -> None: self.interpolate_mobject(alpha) def update(self, alpha: float) -> None: """ This method shouldn't exist, but it's here to keep many old scenes from breaking """ self.interpolate(alpha) def time_spanned_alpha(self, alpha: float) -> float: if self.time_span is not None: start, end = self.time_span return clip(alpha * self.run_time - start, 0, end - start) / (end - start) return alpha def interpolate_mobject(self, alpha: float) -> None: for i, mobs in enumerate(self.families): sub_alpha = self.get_sub_alpha(self.time_spanned_alpha(alpha), i, len(self.families)) self.interpolate_submobject(*mobs, sub_alpha) def interpolate_submobject( self, submobject: Mobject, starting_submobject: Mobject, alpha: float ): # Typically ipmlemented by subclass pass def get_sub_alpha( self, alpha: float, index: int, num_submobjects: int ) -> float: # TODO, make this more understanable, and/or combine # its functionality with AnimationGroup's method # build_animations_with_timings lag_ratio = self.lag_ratio full_length = (num_submobjects - 1) * lag_ratio + 1 value = alpha * full_length lower = index * lag_ratio raw_sub_alpha = clip((value - lower), 0, 1) return self.rate_func(raw_sub_alpha) # Getters and setters def set_run_time(self, run_time: float): self.run_time = run_time return self def get_run_time(self) -> float: if self.time_span: return max(self.run_time, self.time_span[1]) return self.run_time def set_rate_func(self, rate_func: Callable[[float], float]): self.rate_func = rate_func return self def get_rate_func(self) -> Callable[[float], float]: return self.rate_func def set_name(self, name: str): self.name = name return self def is_remover(self) -> bool: return self.remover def prepare_animation(anim: Animation | _AnimationBuilder): if isinstance(anim, _AnimationBuilder): return anim.build() if isinstance(anim, Animation): return anim raise TypeError(f"Object {anim} cannot be converted to an animation")
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/movement.py
manimlib/animation/movement.py
from __future__ import annotations from manimlib.animation.animation import Animation from manimlib.utils.rate_functions import linear from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable, Sequence import numpy as np from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.vectorized_mobject import VMobject class Homotopy(Animation): apply_function_config: dict = dict() def __init__( self, homotopy: Callable[[float, float, float, float], Sequence[float]], mobject: Mobject, run_time: float = 3.0, **kwargs ): """ Homotopy is a function from (x, y, z, t) to (x', y', z') """ self.homotopy = homotopy super().__init__(mobject, run_time=run_time, **kwargs) def function_at_time_t(self, t: float) -> Callable[[np.ndarray], Sequence[float]]: def result(p): return self.homotopy(*p, t) return result def interpolate_submobject( self, submob: Mobject, start: Mobject, alpha: float ) -> None: submob.match_points(start) submob.apply_function( self.function_at_time_t(alpha), **self.apply_function_config ) class SmoothedVectorizedHomotopy(Homotopy): apply_function_config: dict = dict(make_smooth=True) class ComplexHomotopy(Homotopy): def __init__( self, complex_homotopy: Callable[[complex, float], complex], mobject: Mobject, **kwargs ): """ Given a function form (z, t) -> w, where z and w are complex numbers and t is time, this animates the state over time """ def homotopy(x, y, z, t): c = complex_homotopy(complex(x, y), t) return (c.real, c.imag, z) super().__init__(homotopy, mobject, **kwargs) class PhaseFlow(Animation): def __init__( self, function: Callable[[np.ndarray], np.ndarray], mobject: Mobject, virtual_time: float | None = None, suspend_mobject_updating: bool = False, rate_func: Callable[[float], float] = linear, run_time: float =3.0, **kwargs ): self.function = function self.virtual_time = virtual_time or run_time super().__init__( mobject, rate_func=rate_func, run_time=run_time, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_mobject(self, alpha: float) -> None: if hasattr(self, "last_alpha"): dt = self.virtual_time * (alpha - self.last_alpha) self.mobject.apply_function( lambda p: p + dt * self.function(p) ) self.last_alpha = alpha class MoveAlongPath(Animation): def __init__( self, mobject: Mobject, path: VMobject, suspend_mobject_updating: bool = False, **kwargs ): self.path = path super().__init__(mobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs) def interpolate_mobject(self, alpha: float) -> None: point = self.path.quick_point_from_proportion(self.rate_func(alpha)) self.mobject.move_to(point)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/composition.py
manimlib/animation/composition.py
from __future__ import annotations from manimlib.animation.animation import Animation from manimlib.animation.animation import prepare_animation from manimlib.mobject.mobject import _AnimationBuilder from manimlib.mobject.mobject import Group from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import integer_interpolate from manimlib.utils.bezier import interpolate from manimlib.utils.iterables import remove_list_redundancies from manimlib.utils.simple_functions import clip from typing import TYPE_CHECKING, Union, Iterable AnimationType = Union[Animation, _AnimationBuilder] if TYPE_CHECKING: from typing import Callable, Optional from manimlib.mobject.mobject import Mobject from manimlib.scene.scene import Scene DEFAULT_LAGGED_START_LAG_RATIO = 0.05 class AnimationGroup(Animation): def __init__( self, *args: AnimationType | Iterable[AnimationType], run_time: float = -1, # If negative, default to sum of inputed animation runtimes lag_ratio: float = 0.0, group: Optional[Mobject] = None, group_type: Optional[type] = None, **kwargs ): animations = args[0] if isinstance(args[0], Iterable) else args self.animations = [prepare_animation(anim) for anim in animations] self.build_animations_with_timings(lag_ratio) self.max_end_time = max((awt[2] for awt in self.anims_with_timings), default=0) self.run_time = self.max_end_time if run_time < 0 else run_time self.lag_ratio = lag_ratio mobs = remove_list_redundancies([a.mobject for a in self.animations]) if group is not None: self.group = group elif group_type is not None: self.group = group_type(*mobs) elif all(isinstance(anim.mobject, VMobject) for anim in animations): self.group = VGroup(*mobs) else: self.group = Group(*mobs) super().__init__( self.group, run_time=self.run_time, lag_ratio=lag_ratio, **kwargs ) def get_all_mobjects(self) -> Mobject: return self.group def begin(self) -> None: self.group.set_animating_status(True) for anim in self.animations: anim.begin() # self.init_run_time() def finish(self) -> None: self.group.set_animating_status(False) for anim in self.animations: anim.finish() def clean_up_from_scene(self, scene: Scene) -> None: for anim in self.animations: anim.clean_up_from_scene(scene) def update_mobjects(self, dt: float) -> None: for anim in self.animations: anim.update_mobjects(dt) def calculate_max_end_time(self) -> None: self.max_end_time = max( (awt[2] for awt in self.anims_with_timings), default=0, ) if self.run_time < 0: self.run_time = self.max_end_time def build_animations_with_timings(self, lag_ratio: float) -> None: """ Creates a list of triplets of the form (anim, start_time, end_time) """ self.anims_with_timings = [] curr_time = 0 for anim in self.animations: start_time = curr_time end_time = start_time + anim.get_run_time() self.anims_with_timings.append( (anim, start_time, end_time) ) # Start time of next animation is based on the lag_ratio curr_time = interpolate( start_time, end_time, lag_ratio ) def interpolate(self, alpha: float) -> None: # Note, if the run_time of AnimationGroup has been # set to something other than its default, these # times might not correspond to actual times, # e.g. of the surrounding scene. Instead they'd # be a rescaled version. But that's okay! time = alpha * self.max_end_time for anim, start_time, end_time in self.anims_with_timings: anim_time = end_time - start_time if anim_time == 0: sub_alpha = 0 else: sub_alpha = clip((time - start_time) / anim_time, 0, 1) anim.interpolate(sub_alpha) class Succession(AnimationGroup): def __init__( self, *animations: Animation, lag_ratio: float = 1.0, **kwargs ): super().__init__(*animations, lag_ratio=lag_ratio, **kwargs) def begin(self) -> None: assert len(self.animations) > 0 self.active_animation = self.animations[0] self.active_animation.begin() def finish(self) -> None: self.active_animation.finish() def update_mobjects(self, dt: float) -> None: self.active_animation.update_mobjects(dt) def interpolate(self, alpha: float) -> None: index, subalpha = integer_interpolate( 0, len(self.animations), alpha ) animation = self.animations[index] if animation is not self.active_animation: self.active_animation.finish() animation.begin() self.active_animation = animation animation.interpolate(subalpha) class LaggedStart(AnimationGroup): def __init__( self, *animations, lag_ratio: float = DEFAULT_LAGGED_START_LAG_RATIO, **kwargs ): super().__init__(*animations, lag_ratio=lag_ratio, **kwargs) class LaggedStartMap(LaggedStart): def __init__( self, anim_func: Callable[[Mobject], Animation], group: Mobject, run_time: float = 2.0, lag_ratio: float = DEFAULT_LAGGED_START_LAG_RATIO, **kwargs ): anim_kwargs = dict(kwargs) anim_kwargs.pop("lag_ratio", None) super().__init__( *(anim_func(submob, **anim_kwargs) for submob in group), run_time=run_time, lag_ratio=lag_ratio, group=group )
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/fading.py
manimlib/animation/fading.py
from __future__ import annotations import numpy as np from manimlib.animation.animation import Animation from manimlib.animation.transform import Transform from manimlib.constants import ORIGIN from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.mobject import Group from manimlib.utils.bezier import interpolate from manimlib.utils.rate_functions import there_and_back from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.mobject.mobject import Mobject from manimlib.scene.scene import Scene from manimlib.typing import Vect3 class Fade(Transform): def __init__( self, mobject: Mobject, shift: np.ndarray = ORIGIN, scale: float = 1, **kwargs ): self.shift_vect = shift self.scale_factor = scale super().__init__(mobject, **kwargs) class FadeIn(Fade): def create_target(self) -> Mobject: return self.mobject.copy() def create_starting_mobject(self) -> Mobject: start = super().create_starting_mobject() start.set_opacity(0) start.scale(1.0 / self.scale_factor) start.shift(-self.shift_vect) return start class FadeOut(Fade): def __init__( self, mobject: Mobject, shift: Vect3 = ORIGIN, remover: bool = True, final_alpha_value: float = 0.0, # Put it back in original state when done, **kwargs ): super().__init__( mobject, shift, remover=remover, final_alpha_value=final_alpha_value, **kwargs ) def create_target(self) -> Mobject: result = self.mobject.copy() result.set_opacity(0) result.shift(self.shift_vect) result.scale(self.scale_factor) return result class FadeInFromPoint(FadeIn): def __init__(self, mobject: Mobject, point: Vect3, **kwargs): super().__init__( mobject, shift=mobject.get_center() - point, scale=np.inf, **kwargs, ) class FadeOutToPoint(FadeOut): def __init__(self, mobject: Mobject, point: Vect3, **kwargs): super().__init__( mobject, shift=point - mobject.get_center(), scale=0, **kwargs, ) class FadeTransform(Transform): def __init__( self, mobject: Mobject, target_mobject: Mobject, stretch: bool = True, dim_to_match: int = 1, **kwargs ): self.to_add_on_completion = target_mobject self.stretch = stretch self.dim_to_match = dim_to_match mobject.save_state() super().__init__(Group(mobject, target_mobject.copy()), **kwargs) def begin(self) -> None: self.ending_mobject = self.mobject.copy() Animation.begin(self) # Both 'start' and 'end' consists of the source and target mobjects. # At the start, the traget should be faded replacing the source, # and at the end it should be the other way around. start, end = self.starting_mobject, self.ending_mobject for m0, m1 in ((start[1], start[0]), (end[0], end[1])): self.ghost_to(m0, m1) def ghost_to(self, source: Mobject, target: Mobject) -> None: source.replace(target, stretch=self.stretch, dim_to_match=self.dim_to_match) source.set_uniform(**target.get_uniforms()) source.set_opacity(0) def get_all_mobjects(self) -> list[Mobject]: return [ self.mobject, self.starting_mobject, self.ending_mobject, ] def get_all_families_zipped(self) -> zip[tuple[Mobject]]: return Animation.get_all_families_zipped(self) def clean_up_from_scene(self, scene: Scene) -> None: Animation.clean_up_from_scene(self, scene) scene.remove(self.mobject) self.mobject[0].restore() if not self.remover: scene.add(self.to_add_on_completion) class FadeTransformPieces(FadeTransform): def begin(self) -> None: self.mobject[0].align_family(self.mobject[1]) super().begin() def ghost_to(self, source: Mobject, target: Mobject) -> None: for sm0, sm1 in zip(source.get_family(), target.get_family()): super().ghost_to(sm0, sm1) class VFadeIn(Animation): """ VFadeIn and VFadeOut only work for VMobjects, """ def __init__(self, vmobject: VMobject, suspend_mobject_updating: bool = False, **kwargs): super().__init__( vmobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs ) def interpolate_submobject( self, submob: VMobject, start: VMobject, alpha: float ) -> None: submob.set_stroke( opacity=interpolate(0, start.get_stroke_opacity(), alpha) ) submob.set_fill( opacity=interpolate(0, start.get_fill_opacity(), alpha) ) class VFadeOut(VFadeIn): def __init__( self, vmobject: VMobject, remover: bool = True, final_alpha_value: float = 0.0, **kwargs ): super().__init__( vmobject, remover=remover, final_alpha_value=final_alpha_value, **kwargs ) def interpolate_submobject( self, submob: VMobject, start: VMobject, alpha: float ) -> None: super().interpolate_submobject(submob, start, 1 - alpha) class VFadeInThenOut(VFadeIn): def __init__( self, vmobject: VMobject, rate_func: Callable[[float], float] = there_and_back, remover: bool = True, final_alpha_value: float = 0.5, **kwargs ): super().__init__( vmobject, rate_func=rate_func, remover=remover, final_alpha_value=final_alpha_value, **kwargs )
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/manimlib/animation/transform_matching_parts.py
manimlib/animation/transform_matching_parts.py
from __future__ import annotations import itertools as it from difflib import SequenceMatcher from manimlib.animation.composition import AnimationGroup from manimlib.animation.fading import FadeInFromPoint from manimlib.animation.fading import FadeOutToPoint from manimlib.animation.transform import Transform from manimlib.mobject.mobject import Mobject from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.svg.string_mobject import StringMobject from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable from manimlib.scene.scene import Scene class TransformMatchingParts(AnimationGroup): def __init__( self, source: Mobject, target: Mobject, matched_pairs: Iterable[tuple[Mobject, Mobject]] = [], match_animation: type = Transform, mismatch_animation: type = Transform, run_time: float = 2, lag_ratio: float = 0, **kwargs, ): self.source = source self.target = target self.match_animation = match_animation self.mismatch_animation = mismatch_animation self.anim_config = dict(**kwargs) # We will progressively build up a list of transforms # from pieces in source to those in target. These # two lists keep track of which pieces are accounted # for so far self.source_pieces = source.family_members_with_points() self.target_pieces = target.family_members_with_points() self.anims = [] for pair in matched_pairs: self.add_transform(*pair) # Match any pairs with the same shape for pair in self.find_pairs_with_matching_shapes(self.source_pieces, self.target_pieces): self.add_transform(*pair) # Finally, account for mismatches for source_piece in self.source_pieces: if any([source_piece in anim.mobject.get_family() for anim in self.anims]): continue self.anims.append(FadeOutToPoint( source_piece, target.get_center(), **self.anim_config )) for target_piece in self.target_pieces: if any([target_piece in anim.mobject.get_family() for anim in self.anims]): continue self.anims.append(FadeInFromPoint( target_piece, source.get_center(), **self.anim_config )) super().__init__( *self.anims, run_time=run_time, lag_ratio=lag_ratio, ) def add_transform( self, source: Mobject, target: Mobject, ): new_source_pieces = source.family_members_with_points() new_target_pieces = target.family_members_with_points() if len(new_source_pieces) == 0 or len(new_target_pieces) == 0: # Don't animate null sorces or null targets return source_is_new = all(char in self.source_pieces for char in new_source_pieces) target_is_new = all(char in self.target_pieces for char in new_target_pieces) if not source_is_new or not target_is_new: return transform_type = self.mismatch_animation if source.has_same_shape_as(target): transform_type = self.match_animation self.anims.append(transform_type(source, target, **self.anim_config)) for char in new_source_pieces: self.source_pieces.remove(char) for char in new_target_pieces: self.target_pieces.remove(char) def find_pairs_with_matching_shapes( self, chars1: list[Mobject], chars2: list[Mobject] ) -> list[tuple[Mobject, Mobject]]: result = [] for char1, char2 in it.product(chars1, chars2): if char1.has_same_shape_as(char2): result.append((char1, char2)) return result def clean_up_from_scene(self, scene: Scene) -> None: super().clean_up_from_scene(scene) scene.remove(self.mobject) scene.add(self.target) class TransformMatchingShapes(TransformMatchingParts): """Alias for TransformMatchingParts""" pass class TransformMatchingStrings(TransformMatchingParts): def __init__( self, source: StringMobject, target: StringMobject, matched_keys: Iterable[str] = [], key_map: dict[str, str] = dict(), matched_pairs: Iterable[tuple[VMobject, VMobject]] = [], **kwargs, ): matched_pairs = [ *matched_pairs, *self.matching_blocks(source, target, matched_keys, key_map), ] super().__init__( source, target, matched_pairs=matched_pairs, **kwargs, ) def matching_blocks( self, source: StringMobject, target: StringMobject, matched_keys: Iterable[str], key_map: dict[str, str] ) -> list[tuple[VMobject, VMobject]]: syms1 = source.get_symbol_substrings() syms2 = target.get_symbol_substrings() counts1 = list(map(source.substr_to_path_count, syms1)) counts2 = list(map(target.substr_to_path_count, syms2)) # Start with user specified matches blocks = [(source[key1], target[key2]) for key1, key2 in key_map.items()] blocks += [(source[key], target[key]) for key in matched_keys] # Nullify any intersections with those matches in the two symbol lists for sub_source, sub_target in blocks: for i in range(len(syms1)): if i < len(source) and source[i] in sub_source.family_members_with_points(): syms1[i] = "Null1" for j in range(len(syms2)): if j < len(target) and target[j] in sub_target.family_members_with_points(): syms2[j] = "Null2" # Group together longest matching substrings while True: matcher = SequenceMatcher(None, syms1, syms2) match = matcher.find_longest_match(0, len(syms1), 0, len(syms2)) if match.size == 0: break i1 = sum(counts1[:match.a]) i2 = sum(counts2[:match.b]) size = sum(counts1[match.a:match.a + match.size]) blocks.append((source[i1:i1 + size], target[i2:i2 + size])) for i in range(match.size): syms1[match.a + i] = "Null1" syms2[match.b + i] = "Null2" return blocks class TransformMatchingTex(TransformMatchingStrings): """Alias for TransformMatchingStrings""" pass
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/docs/example.py
docs/example.py
from manimlib import * class SquareToCircle(Scene): def construct(self): circle = Circle() circle.set_fill(BLUE, opacity=0.5) circle.set_stroke(BLUE_E, width=4) square = Square() self.play(ShowCreation(square)) self.wait() self.play(ReplacementTransform(square, circle)) self.wait() # Try typing the following lines # self.play(circle.animate.stretch(4, dim=0)) # self.play(Rotate(circle, TAU / 4)) # self.play(circle.animate.shift(2 * RIGHT), circle.animate.scale(0.25)) # circle.insert_n_curves(10) # self.play(circle.animate.apply_complex_function(lambda z: z**2)) class SquareToCircleEmbed(Scene): def construct(self): circle = Circle() circle.set_fill(BLUE, opacity=0.5) circle.set_stroke(BLUE_E, width=4) self.add(circle) self.wait() self.play(circle.animate.stretch(4, dim=0)) self.wait(1.5) self.play(Rotate(circle, TAU / 4)) self.wait(1.5) self.play(circle.animate.shift(2 * RIGHT), circle.animate.scale(0.25)) self.wait(1.5) circle.insert_n_curves(10) self.play(circle.animate.apply_complex_function(lambda z: z**2)) self.wait(2)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/docs/source/manim_example_ext.py
docs/source/manim_example_ext.py
from docutils import nodes from docutils.parsers.rst import directives, Directive import jinja2 import os class skip_manim_node(nodes.Admonition, nodes.Element): pass def visit(self, node, name=""): self.visit_admonition(node, name) def depart(self, node): self.depart_admonition(node) class ManimExampleDirective(Directive): has_content = True required_arguments = 1 optional_arguments = 0 option_spec = { "hide_code": bool, "media": str, } final_argument_whitespace = True def run(self): hide_code = "hide_code" in self.options scene_name = self.arguments[0] media_file_name = self.options["media"] source_block = [ ".. code-block:: python", "", *[" " + line for line in self.content], ] source_block = "\n".join(source_block) state_machine = self.state_machine document = state_machine.document if any(media_file_name.endswith(ext) for ext in [".png", ".jpg", ".gif"]): is_video = False else: is_video = True rendered_template = jinja2.Template(TEMPLATE).render( scene_name=scene_name, scene_name_lowercase=scene_name.lower(), hide_code=hide_code, is_video=is_video, media_file_name=media_file_name, source_block=source_block, ) state_machine.insert_input( rendered_template.split("\n"), source=document.attributes["source"] ) return [] def setup(app): app.add_node(skip_manim_node, html=(visit, depart)) setup.app = app setup.config = app.config setup.confdir = app.confdir app.add_directive("manim-example", ManimExampleDirective) metadata = {"parallel_read_safe": False, "parallel_write_safe": True} return metadata TEMPLATE = r""" {% if not hide_code %} .. raw:: html <div class="manim-example"> {% endif %} {% if is_video %} .. raw:: html <video id="{{ scene_name_lowercase }}" class="manim-video" controls loop autoplay src="{{ media_file_name }}"></video> {% else %} .. image:: {{ media_file_name }} :align: center :name: {{ scene_name_lowercase }} {% endif %} {% if not hide_code %} .. raw:: html <h5 class="example-header">{{ scene_name }}<a class="headerlink" href="#{{ scene_name_lowercase }}">¶</a></h5> {{ source_block }} {% endif %} .. raw:: html </div> """
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/docs/source/conf.py
docs/source/conf.py
import os import sys sys.path.insert(0, os.path.abspath(".")) sys.path.insert(0, os.path.abspath('../../')) project = 'manim' copyright = '- This document has been placed in the public domain.' author = 'TonyCrane' release = '' extensions = [ 'sphinx.ext.todo', 'sphinx.ext.githubpages', 'sphinx.ext.mathjax', 'sphinx.ext.intersphinx', 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.napoleon', 'sphinx_copybutton', 'manim_example_ext' ] autoclass_content = 'both' mathjax_path = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' pygments_style = 'default' html_static_path = ["_static"] html_css_files = [ "https://cdn.jsdelivr.net/gh/manim-kindergarten/CDN@master/manimgl_assets/custom.css", "https://cdn.jsdelivr.net/gh/manim-kindergarten/CDN@master/manimgl_assets/colors.css" ] html_theme = 'furo' # pip install furo==2020.10.5b9 html_favicon = '_static/icon.png' html_logo = '../../logo/transparent_graph.png' html_theme_options = { "sidebar_hide_name": True, }
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
3b1b/manim
https://github.com/3b1b/manim/blob/e5298385edabb34a09cf63743c1a4ec983f1ab11/logo/logo.py
logo/logo.py
from manimlib.imports import * NEW_BLUE = "#68a8e1" class Thumbnail(GraphScene): CONFIG = { "y_max": 8, "y_axis_height": 5, } def construct(self): self.show_function_graph() def show_function_graph(self): self.setup_axes(animate=False) def func(x): return 0.1 * (x + 3-5) * (x - 3-5) * (x-5) + 5 def rect(x): return 2.775*(x-1.5)+3.862 recta = self.get_graph(rect,x_min=-1,x_max=5) graph = self.get_graph(func,x_min=0.2,x_max=9) graph.set_color(NEW_BLUE) input_tracker_p1 = ValueTracker(1.5) input_tracker_p2 = ValueTracker(3.5) def get_x_value(input_tracker): return input_tracker.get_value() def get_y_value(input_tracker): return graph.underlying_function(get_x_value(input_tracker)) def get_x_point(input_tracker): return self.coords_to_point(get_x_value(input_tracker), 0) def get_y_point(input_tracker): return self.coords_to_point(0, get_y_value(input_tracker)) def get_graph_point(input_tracker): return self.coords_to_point(get_x_value(input_tracker), get_y_value(input_tracker)) def get_v_line(input_tracker): return DashedLine(get_x_point(input_tracker), get_graph_point(input_tracker), stroke_width=2) def get_h_line(input_tracker): return DashedLine(get_graph_point(input_tracker), get_y_point(input_tracker), stroke_width=2) # input_triangle_p1 = RegularPolygon(n=3, start_angle=TAU / 4) output_triangle_p1 = RegularPolygon(n=3, start_angle=0) for triangle in input_triangle_p1, output_triangle_p1: triangle.set_fill(WHITE, 1) triangle.set_stroke(width=0) triangle.scale(0.1) # input_triangle_p2 = RegularPolygon(n=3, start_angle=TAU / 4) output_triangle_p2 = RegularPolygon(n=3, start_angle=0) for triangle in input_triangle_p2, output_triangle_p2: triangle.set_fill(WHITE, 1) triangle.set_stroke(width=0) triangle.scale(0.1) # x_label_p1 = Tex("a") output_label_p1 = Tex("f(a)") x_label_p2 = Tex("b") output_label_p2 = Tex("f(b)") v_line_p1 = get_v_line(input_tracker_p1) v_line_p2 = get_v_line(input_tracker_p2) h_line_p1 = get_h_line(input_tracker_p1) h_line_p2 = get_h_line(input_tracker_p2) graph_dot_p1 = Dot(color=WHITE) graph_dot_p2 = Dot(color=WHITE) # reposition mobjects x_label_p1.next_to(v_line_p1, DOWN) x_label_p2.next_to(v_line_p2, DOWN) output_label_p1.next_to(h_line_p1, LEFT) output_label_p2.next_to(h_line_p2, LEFT) input_triangle_p1.next_to(v_line_p1, DOWN, buff=0) input_triangle_p2.next_to(v_line_p2, DOWN, buff=0) output_triangle_p1.next_to(h_line_p1, LEFT, buff=0) output_triangle_p2.next_to(h_line_p2, LEFT, buff=0) graph_dot_p1.move_to(get_graph_point(input_tracker_p1)) graph_dot_p2.move_to(get_graph_point(input_tracker_p2)) # self.play( ShowCreation(graph), ) # Animacion del punto a self.add_foreground_mobject(graph_dot_p1) self.add_foreground_mobject(graph_dot_p2) self.play( DrawBorderThenFill(input_triangle_p1), Write(x_label_p1), ShowCreation(v_line_p1), GrowFromCenter(graph_dot_p1), ShowCreation(h_line_p1), Write(output_label_p1), DrawBorderThenFill(output_triangle_p1), DrawBorderThenFill(input_triangle_p2), Write(x_label_p2), ShowCreation(v_line_p2), GrowFromCenter(graph_dot_p2), ShowCreation(h_line_p2), Write(output_label_p2), DrawBorderThenFill(output_triangle_p2), run_time=0.5 ) self.add( input_triangle_p2, x_label_p2, graph_dot_p2, v_line_p2, h_line_p2, output_triangle_p2, output_label_p2, ) ################### pendiente_recta = self.get_secant_slope_group( 1.9, recta, dx = 1.4, df_label = None, dx_label = None, dx_line_color = PURPLE, df_line_color= ORANGE, ) grupo_secante = self.get_secant_slope_group( 1.5, graph, dx = 2, df_label = None, dx_label = None, dx_line_color = "#942357", df_line_color= "#3f7d5c", secant_line_color = RED, ) self.add( input_triangle_p2, graph_dot_p2, v_line_p2, h_line_p2, output_triangle_p2, ) self.play(FadeIn(grupo_secante)) kwargs = { "x_min" : 4, "x_max" : 9, "fill_opacity" : 0.75, "stroke_width" : 0.25, } self.graph=graph iteraciones=6 self.rect_list = self.get_riemann_rectangles_list( graph, iteraciones,start_color=PURPLE,end_color=ORANGE, **kwargs ) flat_rects = self.get_riemann_rectangles( self.get_graph(lambda x : 0), dx = 0.5,start_color=invert_color(PURPLE),end_color=invert_color(ORANGE),**kwargs ) rects = self.rect_list[0] self.transform_between_riemann_rects( flat_rects, rects, replace_mobject_with_target_in_scene = True, run_time=0.9 ) # adding manim picture = Group(*self.mobjects) picture.scale(0.6).to_edge(LEFT, buff=SMALL_BUFF) manim = TexText("Manim").set_height(1.5) \ .next_to(picture, RIGHT) \ .shift(DOWN * 0.7) self.add(manim)
python
MIT
e5298385edabb34a09cf63743c1a4ec983f1ab11
2026-01-04T14:38:15.512738Z
false
github/spec-kit
https://github.com/github/spec-kit/blob/9111699cd27879e3e6301651a03e502ecb6dd65d/src/specify_cli/__init__.py
src/specify_cli/__init__.py
#!/usr/bin/env python3 # /// script # requires-python = ">=3.11" # dependencies = [ # "typer", # "rich", # "platformdirs", # "readchar", # "httpx", # ] # /// """ Specify CLI - Setup tool for Specify projects Usage: uvx specify-cli.py init <project-name> uvx specify-cli.py init . uvx specify-cli.py init --here Or install globally: uv tool install --from specify-cli.py specify-cli specify init <project-name> specify init . specify init --here """ import os import subprocess import sys import zipfile import tempfile import shutil import shlex import json from pathlib import Path from typing import Optional, Tuple import typer import httpx from rich.console import Console from rich.panel import Panel from rich.progress import Progress, SpinnerColumn, TextColumn from rich.text import Text from rich.live import Live from rich.align import Align from rich.table import Table from rich.tree import Tree from typer.core import TyperGroup # For cross-platform keyboard input import readchar import ssl import truststore from datetime import datetime, timezone ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) client = httpx.Client(verify=ssl_context) def _github_token(cli_token: str | None = None) -> str | None: """Return sanitized GitHub token (cli arg takes precedence) or None.""" return ((cli_token or os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN") or "").strip()) or None def _github_auth_headers(cli_token: str | None = None) -> dict: """Return Authorization header dict only when a non-empty token exists.""" token = _github_token(cli_token) return {"Authorization": f"Bearer {token}"} if token else {} def _parse_rate_limit_headers(headers: httpx.Headers) -> dict: """Extract and parse GitHub rate-limit headers.""" info = {} # Standard GitHub rate-limit headers if "X-RateLimit-Limit" in headers: info["limit"] = headers.get("X-RateLimit-Limit") if "X-RateLimit-Remaining" in headers: info["remaining"] = headers.get("X-RateLimit-Remaining") if "X-RateLimit-Reset" in headers: reset_epoch = int(headers.get("X-RateLimit-Reset", "0")) if reset_epoch: reset_time = datetime.fromtimestamp(reset_epoch, tz=timezone.utc) info["reset_epoch"] = reset_epoch info["reset_time"] = reset_time info["reset_local"] = reset_time.astimezone() # Retry-After header (seconds or HTTP-date) if "Retry-After" in headers: retry_after = headers.get("Retry-After") try: info["retry_after_seconds"] = int(retry_after) except ValueError: # HTTP-date format - not implemented, just store as string info["retry_after"] = retry_after return info def _format_rate_limit_error(status_code: int, headers: httpx.Headers, url: str) -> str: """Format a user-friendly error message with rate-limit information.""" rate_info = _parse_rate_limit_headers(headers) lines = [f"GitHub API returned status {status_code} for {url}"] lines.append("") if rate_info: lines.append("[bold]Rate Limit Information:[/bold]") if "limit" in rate_info: lines.append(f" • Rate Limit: {rate_info['limit']} requests/hour") if "remaining" in rate_info: lines.append(f" • Remaining: {rate_info['remaining']}") if "reset_local" in rate_info: reset_str = rate_info["reset_local"].strftime("%Y-%m-%d %H:%M:%S %Z") lines.append(f" • Resets at: {reset_str}") if "retry_after_seconds" in rate_info: lines.append(f" • Retry after: {rate_info['retry_after_seconds']} seconds") lines.append("") # Add troubleshooting guidance lines.append("[bold]Troubleshooting Tips:[/bold]") lines.append(" • If you're on a shared CI or corporate environment, you may be rate-limited.") lines.append(" • Consider using a GitHub token via --github-token or the GH_TOKEN/GITHUB_TOKEN") lines.append(" environment variable to increase rate limits.") lines.append(" • Authenticated requests have a limit of 5,000/hour vs 60/hour for unauthenticated.") return "\n".join(lines) # Agent configuration with name, folder, install URL, and CLI tool requirement AGENT_CONFIG = { "copilot": { "name": "GitHub Copilot", "folder": ".github/", "install_url": None, # IDE-based, no CLI check needed "requires_cli": False, }, "claude": { "name": "Claude Code", "folder": ".claude/", "install_url": "https://docs.anthropic.com/en/docs/claude-code/setup", "requires_cli": True, }, "gemini": { "name": "Gemini CLI", "folder": ".gemini/", "install_url": "https://github.com/google-gemini/gemini-cli", "requires_cli": True, }, "cursor-agent": { "name": "Cursor", "folder": ".cursor/", "install_url": None, # IDE-based "requires_cli": False, }, "qwen": { "name": "Qwen Code", "folder": ".qwen/", "install_url": "https://github.com/QwenLM/qwen-code", "requires_cli": True, }, "opencode": { "name": "opencode", "folder": ".opencode/", "install_url": "https://opencode.ai", "requires_cli": True, }, "codex": { "name": "Codex CLI", "folder": ".codex/", "install_url": "https://github.com/openai/codex", "requires_cli": True, }, "windsurf": { "name": "Windsurf", "folder": ".windsurf/", "install_url": None, # IDE-based "requires_cli": False, }, "kilocode": { "name": "Kilo Code", "folder": ".kilocode/", "install_url": None, # IDE-based "requires_cli": False, }, "auggie": { "name": "Auggie CLI", "folder": ".augment/", "install_url": "https://docs.augmentcode.com/cli/setup-auggie/install-auggie-cli", "requires_cli": True, }, "codebuddy": { "name": "CodeBuddy", "folder": ".codebuddy/", "install_url": "https://www.codebuddy.ai/cli", "requires_cli": True, }, "qoder": { "name": "Qoder CLI", "folder": ".qoder/", "install_url": "https://qoder.com/cli", "requires_cli": True, }, "roo": { "name": "Roo Code", "folder": ".roo/", "install_url": None, # IDE-based "requires_cli": False, }, "q": { "name": "Amazon Q Developer CLI", "folder": ".amazonq/", "install_url": "https://aws.amazon.com/developer/learning/q-developer-cli/", "requires_cli": True, }, "amp": { "name": "Amp", "folder": ".agents/", "install_url": "https://ampcode.com/manual#install", "requires_cli": True, }, "shai": { "name": "SHAI", "folder": ".shai/", "install_url": "https://github.com/ovh/shai", "requires_cli": True, }, "bob": { "name": "IBM Bob", "folder": ".bob/", "install_url": None, # IDE-based "requires_cli": False, }, } SCRIPT_TYPE_CHOICES = {"sh": "POSIX Shell (bash/zsh)", "ps": "PowerShell"} CLAUDE_LOCAL_PATH = Path.home() / ".claude" / "local" / "claude" BANNER = """ ███████╗██████╗ ███████╗ ██████╗██╗███████╗██╗ ██╗ ██╔════╝██╔══██╗██╔════╝██╔════╝██║██╔════╝╚██╗ ██╔╝ ███████╗██████╔╝█████╗ ██║ ██║█████╗ ╚████╔╝ ╚════██║██╔═══╝ ██╔══╝ ██║ ██║██╔══╝ ╚██╔╝ ███████║██║ ███████╗╚██████╗██║██║ ██║ ╚══════╝╚═╝ ╚══════╝ ╚═════╝╚═╝╚═╝ ╚═╝ """ TAGLINE = "GitHub Spec Kit - Spec-Driven Development Toolkit" class StepTracker: """Track and render hierarchical steps without emojis, similar to Claude Code tree output. Supports live auto-refresh via an attached refresh callback. """ def __init__(self, title: str): self.title = title self.steps = [] # list of dicts: {key, label, status, detail} self.status_order = {"pending": 0, "running": 1, "done": 2, "error": 3, "skipped": 4} self._refresh_cb = None # callable to trigger UI refresh def attach_refresh(self, cb): self._refresh_cb = cb def add(self, key: str, label: str): if key not in [s["key"] for s in self.steps]: self.steps.append({"key": key, "label": label, "status": "pending", "detail": ""}) self._maybe_refresh() def start(self, key: str, detail: str = ""): self._update(key, status="running", detail=detail) def complete(self, key: str, detail: str = ""): self._update(key, status="done", detail=detail) def error(self, key: str, detail: str = ""): self._update(key, status="error", detail=detail) def skip(self, key: str, detail: str = ""): self._update(key, status="skipped", detail=detail) def _update(self, key: str, status: str, detail: str): for s in self.steps: if s["key"] == key: s["status"] = status if detail: s["detail"] = detail self._maybe_refresh() return self.steps.append({"key": key, "label": key, "status": status, "detail": detail}) self._maybe_refresh() def _maybe_refresh(self): if self._refresh_cb: try: self._refresh_cb() except Exception: pass def render(self): tree = Tree(f"[cyan]{self.title}[/cyan]", guide_style="grey50") for step in self.steps: label = step["label"] detail_text = step["detail"].strip() if step["detail"] else "" status = step["status"] if status == "done": symbol = "[green]●[/green]" elif status == "pending": symbol = "[green dim]○[/green dim]" elif status == "running": symbol = "[cyan]○[/cyan]" elif status == "error": symbol = "[red]●[/red]" elif status == "skipped": symbol = "[yellow]○[/yellow]" else: symbol = " " if status == "pending": # Entire line light gray (pending) if detail_text: line = f"{symbol} [bright_black]{label} ({detail_text})[/bright_black]" else: line = f"{symbol} [bright_black]{label}[/bright_black]" else: # Label white, detail (if any) light gray in parentheses if detail_text: line = f"{symbol} [white]{label}[/white] [bright_black]({detail_text})[/bright_black]" else: line = f"{symbol} [white]{label}[/white]" tree.add(line) return tree def get_key(): """Get a single keypress in a cross-platform way using readchar.""" key = readchar.readkey() if key == readchar.key.UP or key == readchar.key.CTRL_P: return 'up' if key == readchar.key.DOWN or key == readchar.key.CTRL_N: return 'down' if key == readchar.key.ENTER: return 'enter' if key == readchar.key.ESC: return 'escape' if key == readchar.key.CTRL_C: raise KeyboardInterrupt return key def select_with_arrows(options: dict, prompt_text: str = "Select an option", default_key: str = None) -> str: """ Interactive selection using arrow keys with Rich Live display. Args: options: Dict with keys as option keys and values as descriptions prompt_text: Text to show above the options default_key: Default option key to start with Returns: Selected option key """ option_keys = list(options.keys()) if default_key and default_key in option_keys: selected_index = option_keys.index(default_key) else: selected_index = 0 selected_key = None def create_selection_panel(): """Create the selection panel with current selection highlighted.""" table = Table.grid(padding=(0, 2)) table.add_column(style="cyan", justify="left", width=3) table.add_column(style="white", justify="left") for i, key in enumerate(option_keys): if i == selected_index: table.add_row("▶", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]") else: table.add_row(" ", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]") table.add_row("", "") table.add_row("", "[dim]Use ↑/↓ to navigate, Enter to select, Esc to cancel[/dim]") return Panel( table, title=f"[bold]{prompt_text}[/bold]", border_style="cyan", padding=(1, 2) ) console.print() def run_selection_loop(): nonlocal selected_key, selected_index with Live(create_selection_panel(), console=console, transient=True, auto_refresh=False) as live: while True: try: key = get_key() if key == 'up': selected_index = (selected_index - 1) % len(option_keys) elif key == 'down': selected_index = (selected_index + 1) % len(option_keys) elif key == 'enter': selected_key = option_keys[selected_index] break elif key == 'escape': console.print("\n[yellow]Selection cancelled[/yellow]") raise typer.Exit(1) live.update(create_selection_panel(), refresh=True) except KeyboardInterrupt: console.print("\n[yellow]Selection cancelled[/yellow]") raise typer.Exit(1) run_selection_loop() if selected_key is None: console.print("\n[red]Selection failed.[/red]") raise typer.Exit(1) return selected_key console = Console() class BannerGroup(TyperGroup): """Custom group that shows banner before help.""" def format_help(self, ctx, formatter): # Show banner before help show_banner() super().format_help(ctx, formatter) app = typer.Typer( name="specify", help="Setup tool for Specify spec-driven development projects", add_completion=False, invoke_without_command=True, cls=BannerGroup, ) def show_banner(): """Display the ASCII art banner.""" banner_lines = BANNER.strip().split('\n') colors = ["bright_blue", "blue", "cyan", "bright_cyan", "white", "bright_white"] styled_banner = Text() for i, line in enumerate(banner_lines): color = colors[i % len(colors)] styled_banner.append(line + "\n", style=color) console.print(Align.center(styled_banner)) console.print(Align.center(Text(TAGLINE, style="italic bright_yellow"))) console.print() @app.callback() def callback(ctx: typer.Context): """Show banner when no subcommand is provided.""" if ctx.invoked_subcommand is None and "--help" not in sys.argv and "-h" not in sys.argv: show_banner() console.print(Align.center("[dim]Run 'specify --help' for usage information[/dim]")) console.print() def run_command(cmd: list[str], check_return: bool = True, capture: bool = False, shell: bool = False) -> Optional[str]: """Run a shell command and optionally capture output.""" try: if capture: result = subprocess.run(cmd, check=check_return, capture_output=True, text=True, shell=shell) return result.stdout.strip() else: subprocess.run(cmd, check=check_return, shell=shell) return None except subprocess.CalledProcessError as e: if check_return: console.print(f"[red]Error running command:[/red] {' '.join(cmd)}") console.print(f"[red]Exit code:[/red] {e.returncode}") if hasattr(e, 'stderr') and e.stderr: console.print(f"[red]Error output:[/red] {e.stderr}") raise return None def check_tool(tool: str, tracker: StepTracker = None) -> bool: """Check if a tool is installed. Optionally update tracker. Args: tool: Name of the tool to check tracker: Optional StepTracker to update with results Returns: True if tool is found, False otherwise """ # Special handling for Claude CLI after `claude migrate-installer` # See: https://github.com/github/spec-kit/issues/123 # The migrate-installer command REMOVES the original executable from PATH # and creates an alias at ~/.claude/local/claude instead # This path should be prioritized over other claude executables in PATH if tool == "claude": if CLAUDE_LOCAL_PATH.exists() and CLAUDE_LOCAL_PATH.is_file(): if tracker: tracker.complete(tool, "available") return True found = shutil.which(tool) is not None if tracker: if found: tracker.complete(tool, "available") else: tracker.error(tool, "not found") return found def is_git_repo(path: Path = None) -> bool: """Check if the specified path is inside a git repository.""" if path is None: path = Path.cwd() if not path.is_dir(): return False try: # Use git command to check if inside a work tree subprocess.run( ["git", "rev-parse", "--is-inside-work-tree"], check=True, capture_output=True, cwd=path, ) return True except (subprocess.CalledProcessError, FileNotFoundError): return False def init_git_repo(project_path: Path, quiet: bool = False) -> Tuple[bool, Optional[str]]: """Initialize a git repository in the specified path. Args: project_path: Path to initialize git repository in quiet: if True suppress console output (tracker handles status) Returns: Tuple of (success: bool, error_message: Optional[str]) """ try: original_cwd = Path.cwd() os.chdir(project_path) if not quiet: console.print("[cyan]Initializing git repository...[/cyan]") subprocess.run(["git", "init"], check=True, capture_output=True, text=True) subprocess.run(["git", "add", "."], check=True, capture_output=True, text=True) subprocess.run(["git", "commit", "-m", "Initial commit from Specify template"], check=True, capture_output=True, text=True) if not quiet: console.print("[green]✓[/green] Git repository initialized") return True, None except subprocess.CalledProcessError as e: error_msg = f"Command: {' '.join(e.cmd)}\nExit code: {e.returncode}" if e.stderr: error_msg += f"\nError: {e.stderr.strip()}" elif e.stdout: error_msg += f"\nOutput: {e.stdout.strip()}" if not quiet: console.print(f"[red]Error initializing git repository:[/red] {e}") return False, error_msg finally: os.chdir(original_cwd) def handle_vscode_settings(sub_item, dest_file, rel_path, verbose=False, tracker=None) -> None: """Handle merging or copying of .vscode/settings.json files.""" def log(message, color="green"): if verbose and not tracker: console.print(f"[{color}]{message}[/] {rel_path}") try: with open(sub_item, 'r', encoding='utf-8') as f: new_settings = json.load(f) if dest_file.exists(): merged = merge_json_files(dest_file, new_settings, verbose=verbose and not tracker) with open(dest_file, 'w', encoding='utf-8') as f: json.dump(merged, f, indent=4) f.write('\n') log("Merged:", "green") else: shutil.copy2(sub_item, dest_file) log("Copied (no existing settings.json):", "blue") except Exception as e: log(f"Warning: Could not merge, copying instead: {e}", "yellow") shutil.copy2(sub_item, dest_file) def merge_json_files(existing_path: Path, new_content: dict, verbose: bool = False) -> dict: """Merge new JSON content into existing JSON file. Performs a deep merge where: - New keys are added - Existing keys are preserved unless overwritten by new content - Nested dictionaries are merged recursively - Lists and other values are replaced (not merged) Args: existing_path: Path to existing JSON file new_content: New JSON content to merge in verbose: Whether to print merge details Returns: Merged JSON content as dict """ try: with open(existing_path, 'r', encoding='utf-8') as f: existing_content = json.load(f) except (FileNotFoundError, json.JSONDecodeError): # If file doesn't exist or is invalid, just use new content return new_content def deep_merge(base: dict, update: dict) -> dict: """Recursively merge update dict into base dict.""" result = base.copy() for key, value in update.items(): if key in result and isinstance(result[key], dict) and isinstance(value, dict): # Recursively merge nested dictionaries result[key] = deep_merge(result[key], value) else: # Add new key or replace existing value result[key] = value return result merged = deep_merge(existing_content, new_content) if verbose: console.print(f"[cyan]Merged JSON file:[/cyan] {existing_path.name}") return merged def download_template_from_github(ai_assistant: str, download_dir: Path, *, script_type: str = "sh", verbose: bool = True, show_progress: bool = True, client: httpx.Client = None, debug: bool = False, github_token: str = None) -> Tuple[Path, dict]: repo_owner = "github" repo_name = "spec-kit" if client is None: client = httpx.Client(verify=ssl_context) if verbose: console.print("[cyan]Fetching latest release information...[/cyan]") api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest" try: response = client.get( api_url, timeout=30, follow_redirects=True, headers=_github_auth_headers(github_token), ) status = response.status_code if status != 200: # Format detailed error message with rate-limit info error_msg = _format_rate_limit_error(status, response.headers, api_url) if debug: error_msg += f"\n\n[dim]Response body (truncated 500):[/dim]\n{response.text[:500]}" raise RuntimeError(error_msg) try: release_data = response.json() except ValueError as je: raise RuntimeError(f"Failed to parse release JSON: {je}\nRaw (truncated 400): {response.text[:400]}") except Exception as e: console.print(f"[red]Error fetching release information[/red]") console.print(Panel(str(e), title="Fetch Error", border_style="red")) raise typer.Exit(1) assets = release_data.get("assets", []) pattern = f"spec-kit-template-{ai_assistant}-{script_type}" matching_assets = [ asset for asset in assets if pattern in asset["name"] and asset["name"].endswith(".zip") ] asset = matching_assets[0] if matching_assets else None if asset is None: console.print(f"[red]No matching release asset found[/red] for [bold]{ai_assistant}[/bold] (expected pattern: [bold]{pattern}[/bold])") asset_names = [a.get('name', '?') for a in assets] console.print(Panel("\n".join(asset_names) or "(no assets)", title="Available Assets", border_style="yellow")) raise typer.Exit(1) download_url = asset["browser_download_url"] filename = asset["name"] file_size = asset["size"] if verbose: console.print(f"[cyan]Found template:[/cyan] {filename}") console.print(f"[cyan]Size:[/cyan] {file_size:,} bytes") console.print(f"[cyan]Release:[/cyan] {release_data['tag_name']}") zip_path = download_dir / filename if verbose: console.print(f"[cyan]Downloading template...[/cyan]") try: with client.stream( "GET", download_url, timeout=60, follow_redirects=True, headers=_github_auth_headers(github_token), ) as response: if response.status_code != 200: # Handle rate-limiting on download as well error_msg = _format_rate_limit_error(response.status_code, response.headers, download_url) if debug: error_msg += f"\n\n[dim]Response body (truncated 400):[/dim]\n{response.text[:400]}" raise RuntimeError(error_msg) total_size = int(response.headers.get('content-length', 0)) with open(zip_path, 'wb') as f: if total_size == 0: for chunk in response.iter_bytes(chunk_size=8192): f.write(chunk) else: if show_progress: with Progress( SpinnerColumn(), TextColumn("[progress.description]{task.description}"), TextColumn("[progress.percentage]{task.percentage:>3.0f}%"), console=console, ) as progress: task = progress.add_task("Downloading...", total=total_size) downloaded = 0 for chunk in response.iter_bytes(chunk_size=8192): f.write(chunk) downloaded += len(chunk) progress.update(task, completed=downloaded) else: for chunk in response.iter_bytes(chunk_size=8192): f.write(chunk) except Exception as e: console.print(f"[red]Error downloading template[/red]") detail = str(e) if zip_path.exists(): zip_path.unlink() console.print(Panel(detail, title="Download Error", border_style="red")) raise typer.Exit(1) if verbose: console.print(f"Downloaded: {filename}") metadata = { "filename": filename, "size": file_size, "release": release_data["tag_name"], "asset_url": download_url } return zip_path, metadata def download_and_extract_template(project_path: Path, ai_assistant: str, script_type: str, is_current_dir: bool = False, *, verbose: bool = True, tracker: StepTracker | None = None, client: httpx.Client = None, debug: bool = False, github_token: str = None) -> Path: """Download the latest release and extract it to create a new project. Returns project_path. Uses tracker if provided (with keys: fetch, download, extract, cleanup) """ current_dir = Path.cwd() if tracker: tracker.start("fetch", "contacting GitHub API") try: zip_path, meta = download_template_from_github( ai_assistant, current_dir, script_type=script_type, verbose=verbose and tracker is None, show_progress=(tracker is None), client=client, debug=debug, github_token=github_token ) if tracker: tracker.complete("fetch", f"release {meta['release']} ({meta['size']:,} bytes)") tracker.add("download", "Download template") tracker.complete("download", meta['filename']) except Exception as e: if tracker: tracker.error("fetch", str(e)) else: if verbose: console.print(f"[red]Error downloading template:[/red] {e}") raise if tracker: tracker.add("extract", "Extract template") tracker.start("extract") elif verbose: console.print("Extracting template...") try: if not is_current_dir: project_path.mkdir(parents=True) with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_contents = zip_ref.namelist() if tracker: tracker.start("zip-list") tracker.complete("zip-list", f"{len(zip_contents)} entries") elif verbose: console.print(f"[cyan]ZIP contains {len(zip_contents)} items[/cyan]") if is_current_dir: with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) zip_ref.extractall(temp_path) extracted_items = list(temp_path.iterdir()) if tracker: tracker.start("extracted-summary") tracker.complete("extracted-summary", f"temp {len(extracted_items)} items") elif verbose: console.print(f"[cyan]Extracted {len(extracted_items)} items to temp location[/cyan]") source_dir = temp_path if len(extracted_items) == 1 and extracted_items[0].is_dir(): source_dir = extracted_items[0] if tracker: tracker.add("flatten", "Flatten nested directory") tracker.complete("flatten") elif verbose: console.print(f"[cyan]Found nested directory structure[/cyan]") for item in source_dir.iterdir(): dest_path = project_path / item.name if item.is_dir(): if dest_path.exists(): if verbose and not tracker: console.print(f"[yellow]Merging directory:[/yellow] {item.name}") for sub_item in item.rglob('*'): if sub_item.is_file(): rel_path = sub_item.relative_to(item) dest_file = dest_path / rel_path dest_file.parent.mkdir(parents=True, exist_ok=True) # Special handling for .vscode/settings.json - merge instead of overwrite if dest_file.name == "settings.json" and dest_file.parent.name == ".vscode": handle_vscode_settings(sub_item, dest_file, rel_path, verbose, tracker) else: shutil.copy2(sub_item, dest_file) else: shutil.copytree(item, dest_path) else: if dest_path.exists() and verbose and not tracker: console.print(f"[yellow]Overwriting file:[/yellow] {item.name}") shutil.copy2(item, dest_path) if verbose and not tracker: console.print(f"[cyan]Template files merged into current directory[/cyan]") else: zip_ref.extractall(project_path) extracted_items = list(project_path.iterdir()) if tracker: tracker.start("extracted-summary") tracker.complete("extracted-summary", f"{len(extracted_items)} top-level items") elif verbose: console.print(f"[cyan]Extracted {len(extracted_items)} items to {project_path}:[/cyan]") for item in extracted_items:
python
MIT
9111699cd27879e3e6301651a03e502ecb6dd65d
2026-01-04T14:38:38.693097Z
true
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/conftest.py
conftest.py
try: # When using torch and tensorflow, torch needs to be imported first, # otherwise it will segfault upon import. This should force the torch # import to happen first for all tests. import torch # noqa: F401 except ImportError: torch = None import pytest # noqa: E402 from keras.src.backend import backend # noqa: E402 def pytest_configure(config): config.addinivalue_line( "markers", "requires_trainable_backend: mark test for trainable backend only", ) def pytest_collection_modifyitems(config, items): openvino_skipped_tests = [] if backend() == "openvino": with open( "keras/src/backend/openvino/excluded_concrete_tests.txt", "r" ) as file: openvino_skipped_tests = file.readlines() # it is necessary to check if stripped line is not empty # and exclude such lines openvino_skipped_tests = [ line.strip() for line in openvino_skipped_tests if line.strip() ] tpu_skipped_tests = [] if backend() == "jax": try: with open( "keras/src/backend/jax/excluded_tpu_tests.txt", "r" ) as file: tpu_skipped_tests = file.readlines() # it is necessary to check if stripped line is not empty # and exclude such lines tpu_skipped_tests = [ line.strip() for line in tpu_skipped_tests if line.strip() ] except FileNotFoundError: pass # File doesn't exist, no tests to skip requires_trainable_backend = pytest.mark.skipif( backend() in ["numpy", "openvino"], reason="Trainer not implemented for NumPy and OpenVINO backend.", ) for item in items: if "requires_trainable_backend" in item.keywords: item.add_marker(requires_trainable_backend) # also, skip concrete tests for openvino, listed in the special file # this is more granular mechanism to exclude tests rather # than using --ignore option for skipped_test in openvino_skipped_tests: if skipped_test in item.nodeid: item.add_marker( skip_if_backend( "openvino", "Not supported operation by openvino backend", ) ) # also, skip concrete tests for TPU when using JAX backend for skipped_test in tpu_skipped_tests: if skipped_test in item.nodeid: item.add_marker( pytest.mark.skip( reason="Known TPU test failure", ) ) def skip_if_backend(given_backend, reason): return pytest.mark.skipif(backend() == given_backend, reason=reason)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/api_gen.py
api_gen.py
"""Script to generate keras public API in `keras/api` directory. Usage: Run via `./shell/api_gen.sh`. It generates API and formats user and generated APIs. """ import os import re import shutil import namex PACKAGE = "keras" BUILD_DIR_NAME = "tmp_build_dir" def ignore_files(_, filenames): return [f for f in filenames if f.endswith("_test.py")] def copy_source_to_build_directory(root_path): # Copy sources (`keras/` directory and setup files) to build dir build_dir = os.path.join(root_path, BUILD_DIR_NAME) build_package_dir = os.path.join(build_dir, PACKAGE) build_src_dir = os.path.join(build_package_dir, "src") root_src_dir = os.path.join(root_path, PACKAGE, "src") if os.path.exists(build_dir): shutil.rmtree(build_dir) os.makedirs(build_package_dir) shutil.copytree(root_src_dir, build_src_dir) return build_dir def create_legacy_directory(package_dir): src_dir = os.path.join(package_dir, "src") # Make keras/_tf_keras/ by copying keras/ tf_keras_dirpath_parent = os.path.join(package_dir, "_tf_keras") tf_keras_dirpath = os.path.join(tf_keras_dirpath_parent, "keras") os.makedirs(tf_keras_dirpath, exist_ok=True) with open(os.path.join(tf_keras_dirpath_parent, "__init__.py"), "w") as f: f.write("from keras._tf_keras import keras\n") with open(os.path.join(package_dir, "__init__.py")) as f: init_file = f.read() init_file = init_file.replace( "from keras import _legacy as _legacy", "from keras import _tf_keras as _tf_keras", ) with open(os.path.join(package_dir, "__init__.py"), "w") as f: f.write(init_file) # Remove the import of `_tf_keras` in `keras/_tf_keras/keras/__init__.py` init_file = init_file.replace("from keras import _tf_keras\n", "\n") with open(os.path.join(tf_keras_dirpath, "__init__.py"), "w") as f: f.write(init_file) for dirname in os.listdir(package_dir): dirpath = os.path.join(package_dir, dirname) if os.path.isdir(dirpath) and dirname not in ( "_legacy", "_tf_keras", "src", ): destpath = os.path.join(tf_keras_dirpath, dirname) if os.path.exists(destpath): shutil.rmtree(destpath) shutil.copytree( dirpath, destpath, ignore=ignore_files, ) # Copy keras/_legacy/ file contents to keras/_tf_keras/keras legacy_submodules = [ path[:-3] for path in os.listdir(os.path.join(src_dir, "legacy")) if path.endswith(".py") ] legacy_submodules += [ path for path in os.listdir(os.path.join(src_dir, "legacy")) if os.path.isdir(os.path.join(src_dir, "legacy", path)) ] for root, _, fnames in os.walk(os.path.join(package_dir, "_legacy")): for fname in fnames: if fname.endswith(".py"): legacy_fpath = os.path.join(root, fname) tf_keras_root = root.replace( os.path.join(os.path.sep, "_legacy"), os.path.join(os.path.sep, "_tf_keras", "keras"), ) core_api_fpath = os.path.join( root.replace(os.path.join(os.path.sep, "_legacy"), ""), fname, ) if not os.path.exists(tf_keras_root): os.makedirs(tf_keras_root) tf_keras_fpath = os.path.join(tf_keras_root, fname) with open(legacy_fpath) as f: legacy_contents = f.read() legacy_contents = legacy_contents.replace( "keras._legacy", "keras._tf_keras.keras" ) if os.path.exists(core_api_fpath): with open(core_api_fpath) as f: core_api_contents = f.read() core_api_contents = core_api_contents.replace( "from keras import _tf_keras as _tf_keras\n", "" ) for legacy_submodule in legacy_submodules: core_api_contents = core_api_contents.replace( f"from keras import {legacy_submodule} as {legacy_submodule}\n", # noqa: E501 "", ) core_api_contents = core_api_contents.replace( f"keras.{legacy_submodule}", f"keras._tf_keras.keras.{legacy_submodule}", ) # Remove duplicate generated comments string. legacy_contents = re.sub(r"\n", r"\\n", legacy_contents) legacy_contents = re.sub('""".*"""', "", legacy_contents) legacy_contents = re.sub(r"\\n", r"\n", legacy_contents) # If the same module is in legacy and core_api, use legacy legacy_imports = re.findall( r"import (\w+)", legacy_contents ) for import_name in legacy_imports: core_api_contents = re.sub( f"\n.* import {import_name} as {import_name}\n", r"\n", core_api_contents, ) legacy_contents = f"{core_api_contents}\n{legacy_contents}" with open(tf_keras_fpath, "w") as f: f.write(legacy_contents) # Delete keras/api/_legacy/ shutil.rmtree(os.path.join(package_dir, "_legacy")) def export_version_string(api_init_fname): with open(api_init_fname) as f: contents = f.read() with open(api_init_fname, "w") as f: contents += "from keras.src.version import __version__ as __version__\n" f.write(contents) def build(): root_path = os.path.dirname(os.path.abspath(__file__)) code_api_dir = os.path.join(root_path, PACKAGE, "api") # Create temp build dir build_dir = copy_source_to_build_directory(root_path) build_api_dir = os.path.join(build_dir, PACKAGE) build_src_dir = os.path.join(build_api_dir, "src") build_api_init_fname = os.path.join(build_api_dir, "__init__.py") try: os.chdir(build_dir) open(build_api_init_fname, "w").close() namex.generate_api_files( "keras", code_directory="src", exclude_directories=[ os.path.join("src", "backend", "jax"), os.path.join("src", "backend", "openvino"), os.path.join("src", "backend", "tensorflow"), os.path.join("src", "backend", "torch"), ], ) # Add __version__ to `api/`. export_version_string(build_api_init_fname) # Creates `_tf_keras` with full keras API create_legacy_directory(package_dir=os.path.join(build_dir, PACKAGE)) # Copy back the keras/api and keras/__init__.py from build directory if os.path.exists(build_src_dir): shutil.rmtree(build_src_dir) if os.path.exists(code_api_dir): shutil.rmtree(code_api_dir) shutil.copytree( build_api_dir, code_api_dir, ignore=shutil.ignore_patterns("src/") ) finally: # Clean up: remove the build directory (no longer needed) shutil.rmtree(build_dir) if __name__ == "__main__": build()
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/pip_build.py
pip_build.py
"""Script to create (and optionally install) a `.whl` archive for Keras 3. Usage: 1. Create a `.whl` file in `dist/`: ``` python3 pip_build.py ``` 2. Also install the new package immediately after: ``` python3 pip_build.py --install ``` """ import argparse import datetime import glob import os import pathlib import re import shutil # Needed because importing torch after TF causes the runtime to crash try: import torch # noqa: F401 except ImportError: pass package = "keras" build_directory = "tmp_build_dir" dist_directory = "dist" to_copy = ["pyproject.toml", "README.md"] def export_version_string(version, is_nightly=False, rc_index=None): """Export Version and Package Name.""" if is_nightly: date = datetime.datetime.now() version += f".dev{date:%Y%m%d%H}" # Update `name = "keras"` with "keras-nightly" pyproj_pth = pathlib.Path("pyproject.toml") pyproj_str = pyproj_pth.read_text().replace( 'name = "keras"', 'name = "keras-nightly"' ) pyproj_pth.write_text(pyproj_str) elif rc_index is not None: version += f"rc{str(rc_index)}" # Make sure to export the __version__ string with open(os.path.join(package, "src", "version.py")) as f: init_contents = f.read() with open(os.path.join(package, "src", "version.py"), "w") as f: init_contents = re.sub( "\n__version__ = .*\n", f'\n__version__ = "{version}"\n', init_contents, ) f.write(init_contents) def ignore_files(_, filenames): return [f for f in filenames if f.endswith("_test.py")] def copy_source_to_build_directory(root_path): # Copy sources (`keras/` directory and setup files) to build # directory os.chdir(root_path) os.mkdir(build_directory) shutil.copytree( package, os.path.join(build_directory, package), ignore=ignore_files ) for fname in to_copy: shutil.copy(fname, os.path.join(f"{build_directory}", fname)) os.chdir(build_directory) def build(root_path, is_nightly=False, rc_index=None): if os.path.exists(build_directory): raise ValueError(f"Directory already exists: {build_directory}") try: copy_source_to_build_directory(root_path) from keras.src.version import __version__ # noqa: E402 export_version_string(__version__, is_nightly, rc_index) return build_and_save_output(root_path, __version__) finally: # Clean up: remove the build directory (no longer needed) shutil.rmtree(build_directory) def build_and_save_output(root_path, __version__): # Build the package os.system("python3 -m build") # Save the dist files generated by the build process os.chdir(root_path) if not os.path.exists(dist_directory): os.mkdir(dist_directory) for fpath in glob.glob( os.path.join(build_directory, dist_directory, "*.*") ): shutil.copy(fpath, dist_directory) # Find the .whl file path whl_path = None for fname in os.listdir(dist_directory): if __version__ in fname and fname.endswith(".whl"): whl_path = os.path.abspath(os.path.join(dist_directory, fname)) if whl_path: print(f"Build successful. Wheel file available at {whl_path}") else: print("Build failed.") return whl_path def install_whl(whl_fpath): print(f"Installing wheel file: {whl_fpath}") os.system(f"pip3 install {whl_fpath} --force-reinstall --no-dependencies") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--install", action="store_true", help="Whether to install the generated wheel file.", ) parser.add_argument( "--nightly", action="store_true", help="Whether to generate nightly wheel file.", ) parser.add_argument( "--rc", type=int, help="Specify `[0-9] when generating RC wheels.", ) args = parser.parse_args() root_path = pathlib.Path(__file__).parent.resolve() whl_path = build(root_path, args.nightly, args.rc) if whl_path and args.install: install_whl(whl_path)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/__init__.py
benchmarks/__init__.py
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/rnn_benchmark.py
benchmarks/layer_benchmark/rnn_benchmark.py
"""Benchmark rnn layers. To run benchmarks, see the following command for an example, please change the flag to your custom value: ``` python3 -m benchmarks.layer_benchmark.rnn_benchmark \ --benchmark_name=benchmark_lstm \ --num_samples=2048 \ --batch_size=256 \ --jit_compile=True ``` """ import tensorflow as tf from absl import app from absl import flags import keras from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_conv_lstm1d( num_samples, batch_size, jit_compile=True, ): layer_name = "ConvLSTM1D" init_args = { "filters": 16, "kernel_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[32, 256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_conv_lstm2d( num_samples, batch_size, jit_compile=True, ): layer_name = "ConvLSTM2D" init_args = { "filters": 16, "kernel_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[32, 32, 32, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_conv_lstm3d( num_samples, batch_size, jit_compile=True, ): layer_name = "ConvLSTM3D" init_args = { "filters": 8, "kernel_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[8, 16, 16, 16, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_gru( num_samples, batch_size, jit_compile=True, ): layer_name = "GRU" init_args = { "units": 32, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_lstm( num_samples, batch_size, jit_compile=True, ): layer_name = "LSTM" init_args = { "units": 32, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_simple_rnn( num_samples, batch_size, jit_compile=True, ): layer_name = "SimpleRNN" init_args = { "units": 32, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_bidirectional( num_samples, batch_size, jit_compile=True, ): layer_name = "Bidirectional" init_args = {} keras_layer = keras.layers.Bidirectional(keras.layers.LSTM(32)) tf_keras_layer = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)) benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, keras_layer=keras_layer, tf_keras_layer=tf_keras_layer, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_time_distributed( num_samples, batch_size, jit_compile=True, ): layer_name = "TimeDistributed" init_args = {} keras_layer = keras.layers.TimeDistributed(keras.layers.Conv2D(16, (3, 3))) tf_keras_layer = tf.keras.layers.TimeDistributed( tf.keras.layers.Conv2D(16, (3, 3)) ) benchmark = LayerBenchmark( layer_name, init_args, input_shape=[10, 32, 32, 3], jit_compile=jit_compile, keras_layer=keras_layer, tf_keras_layer=tf_keras_layer, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) BENCHMARK_NAMES = { "benchmark_conv_lstm1d": benchmark_conv_lstm1d, "benchmark_conv_lstm2d": benchmark_conv_lstm2d, "benchmark_conv_lstm3d": benchmark_conv_lstm3d, "benchmark_gru": benchmark_gru, "benchmark_lstm": benchmark_lstm, "benchmark_simple_rnn": benchmark_simple_rnn, "benchmark_bidirectional": benchmark_bidirectional, "benchmark_time_distributed": benchmark_time_distributed, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for name, benchmark_fn in BENCHMARK_NAMES.items(): benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must " f"be one of {BENCHMARK_NAMES.keys()}" ) benchmark_fn = BENCHMARK_NAMES[benchmark_name] benchmark_fn(num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/pooling_benchmark.py
benchmarks/layer_benchmark/pooling_benchmark.py
"""Benchmark pooling layers. To run benchmarks, see the following command for an example, please change the flag to your custom value: ``` python3 -m benchmarks.layer_benchmark.pooling_benchmark \ --benchmark_name=benchmark_max_pooling1d \ --num_samples=2048 \ --batch_size=256 \ --jit_compile=True ``` """ from absl import app from absl import flags from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_average_pooling1d( num_samples, batch_size, jit_compile=True, ): layer_name = "AveragePooling1D" init_args = { "pool_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[1024, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_average_pooling2d( num_samples, batch_size, jit_compile=True, ): layer_name = "AveragePooling2D" init_args = { "pool_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_average_pooling3d( num_samples, batch_size, jit_compile=True, ): layer_name = "AveragePooling3D" init_args = { "pool_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[64, 64, 32, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_max_pooling1d( num_samples, batch_size, jit_compile=True, ): layer_name = "MaxPooling1D" init_args = { "pool_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[1024, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_max_pooling2d( num_samples, batch_size, jit_compile=True, ): layer_name = "MaxPooling2D" init_args = { "pool_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_max_pooling3d( num_samples, batch_size, jit_compile=True, ): layer_name = "MaxPooling3D" init_args = { "pool_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[64, 64, 32, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_global_average_pooling1d( num_samples, batch_size, jit_compile=True, ): layer_name = "GlobalAveragePooling1D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[1024, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_global_average_pooling2d( num_samples, batch_size, jit_compile=True, ): layer_name = "GlobalAveragePooling2D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_global_average_pooling3d( num_samples, batch_size, jit_compile=True, ): layer_name = "GlobalAveragePooling3D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[64, 64, 32, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_global_max_pooling1d( num_samples, batch_size, jit_compile=True, ): layer_name = "GlobalMaxPooling1D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[1024, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_global_max_pooling2d( num_samples, batch_size, jit_compile=True, ): layer_name = "GlobalMaxPooling2D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_global_max_pooling3d( num_samples, batch_size, jit_compile=True, ): layer_name = "GlobalMaxPooling3D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[64, 64, 32, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) BENCHMARK_NAMES = { "benchmark_average_pooling1d": benchmark_average_pooling1d, "benchmark_average_pooling2d": benchmark_average_pooling2d, "benchmark_average_pooling3d": benchmark_average_pooling3d, "benchmark_max_pooling1d": benchmark_max_pooling1d, "benchmark_max_pooling2d": benchmark_max_pooling2d, "benchmark_max_pooling3d": benchmark_max_pooling3d, "benchmark_global_average_pooling1d": benchmark_global_average_pooling1d, "benchmark_global_average_pooling2d": benchmark_global_average_pooling2d, "benchmark_global_average_pooling3d": benchmark_global_average_pooling3d, "benchmark_global_max_pooling1d": benchmark_global_max_pooling1d, "benchmark_global_max_pooling2d": benchmark_global_max_pooling2d, "benchmark_global_max_pooling3d": benchmark_global_max_pooling3d, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for name, benchmark_fn in BENCHMARK_NAMES.items(): benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must " f"be one of {BENCHMARK_NAMES.keys()}" ) benchmark_fn = BENCHMARK_NAMES[benchmark_name] benchmark_fn(num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/activation_benchmark.py
benchmarks/layer_benchmark/activation_benchmark.py
"""Benchmark activation layers. To run benchmarks, see the following command for an example, please change the flag to your custom value: ``` python3 -m benchmarks.layer_benchmark.activation_benchmark \ --benchmark_name=benchmark_elu \ --num_samples=2048 \ --batch_size=256 \ --jit_compile=True ``` """ from absl import app from absl import flags from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_elu( num_samples, batch_size, jit_compile=True, ): layer_name = "ELU" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_prelu( num_samples, batch_size, jit_compile=True, ): layer_name = "PReLU" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_relu( num_samples, batch_size, jit_compile=True, ): layer_name = "ReLU" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_leaky_relu( num_samples, batch_size, jit_compile=True, ): layer_name = "LeakyReLU" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_softmax( num_samples, batch_size, jit_compile=True, ): layer_name = "Softmax" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) BENCHMARK_NAMES = { "benchmark_elu": benchmark_elu, "benchmark_relu": benchmark_relu, "benchmark_leaky_relu": benchmark_leaky_relu, "benchmark_prelu": benchmark_prelu, "benchmark_softmax": benchmark_softmax, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for name, benchmark_fn in BENCHMARK_NAMES.items(): benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must " f"be one of {BENCHMARK_NAMES.keys()}" ) benchmark_fn = BENCHMARK_NAMES[benchmark_name] benchmark_fn(num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/conv_benchmark.py
benchmarks/layer_benchmark/conv_benchmark.py
"""Benchmark conv layers. To run benchmarks, see the following command for an example, please change the flag to your custom value: ``` python3 -m benchmarks.layer_benchmark.conv_benchmark \ --benchmark_name=benchmark_conv2D \ --num_samples=2046 \ --batch_size=256 \ --jit_compile=True ``` """ from absl import app from absl import flags from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_conv1D( num_samples, batch_size, jit_compile=True, ): layer_name = "Conv1D" init_args = { "filters": 64, "kernel_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[1024, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_conv2D( num_samples, batch_size, jit_compile=True, ): layer_name = "Conv2D" init_args = { "filters": 16, "kernel_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[128, 128, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_conv3D( num_samples, batch_size, jit_compile=True, ): layer_name = "Conv3D" init_args = { "filters": 16, "kernel_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[32, 32, 32, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_depthwise_conv1D( num_samples, batch_size, jit_compile=True, ): layer_name = "DepthwiseConv1D" init_args = { "kernel_size": 16, "depth_multiplier": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 64], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_depthwise_conv2D( num_samples, batch_size, jit_compile=True, ): layer_name = "DepthwiseConv2D" init_args = { "kernel_size": 16, "depth_multiplier": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[128, 128, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_separable_conv1D( num_samples, batch_size, jit_compile=True, ): layer_name = "SeparableConv1D" init_args = { "kernel_size": 16, "depth_multiplier": 2, "filters": 3, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 64], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_separable_conv2D( num_samples, batch_size, jit_compile=True, ): layer_name = "SeparableConv2D" init_args = { "kernel_size": 16, "depth_multiplier": 2, "filters": 3, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[128, 128, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_conv1D_transpose( num_samples, batch_size, jit_compile=True, ): layer_name = "Conv1DTranspose" init_args = { "filters": 32, "kernel_size": 4, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_conv2D_transpose( num_samples, batch_size, jit_compile=True, ): layer_name = "Conv2DTranspose" init_args = { "filters": 16, "kernel_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[128, 128, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_conv3D_transpose( num_samples, batch_size, jit_compile=True, ): layer_name = "Conv3DTranspose" init_args = { "filters": 16, "kernel_size": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[32, 32, 32, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) BENCHMARK_NAMES = { "benchmark_conv1D": benchmark_conv1D, "benchmark_conv2D": benchmark_conv2D, "benchmark_conv3D": benchmark_conv3D, "benchmark_depthwise_conv1D": benchmark_depthwise_conv1D, "benchmark_depthwise_conv2D": benchmark_depthwise_conv2D, "benchmark_separable_conv1D": benchmark_separable_conv1D, "benchmark_separable_conv2D": benchmark_separable_conv2D, "benchmark_conv1D_transpose": benchmark_conv1D_transpose, "benchmark_conv2D_transpose": benchmark_conv2D_transpose, "benchmark_conv3D_transpose": benchmark_conv3D_transpose, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for name, benchmark_fn in BENCHMARK_NAMES: benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must " f"be one of {BENCHMARK_NAMES.keys()}" ) benchmark_fn = BENCHMARK_NAMES[benchmark_name] benchmark_fn(num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/normalization_benchmark.py
benchmarks/layer_benchmark/normalization_benchmark.py
"""Benchmark normalization layers. To run benchmarks, see the following command for an example, please change the flag to your custom value: ``` python3 -m benchmarks.layer_benchmark.normalization_benchmark \ --benchmark_name=benchmark_batch_normalization \ --num_samples=2048 \ --batch_size=256 \ --jit_compile=True ``` """ from absl import app from absl import flags from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_batch_normalization( num_samples, batch_size, jit_compile=True, ): layer_name = "BatchNormalization" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_group_normalization( num_samples, batch_size, jit_compile=True, ): layer_name = "GroupNormalization" init_args = { "groups": 2, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_layer_normalization( num_samples, batch_size, jit_compile=True, ): layer_name = "LayerNormalization" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 128, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_unit_normalization( num_samples, batch_size, jit_compile=True, ): layer_name = "UnitNormalization" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 128, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) BENCHMARK_NAMES = { "benchmark_batch_normalization": benchmark_batch_normalization, "benchmark_group_normalization": benchmark_group_normalization, "benchmark_layer_normalization": benchmark_layer_normalization, "benchmark_unit_normalization": benchmark_unit_normalization, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for name, benchmark_fn in BENCHMARK_NAMES.items(): benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must " f"be one of {BENCHMARK_NAMES.keys()}" ) benchmark_fn = BENCHMARK_NAMES[benchmark_name] benchmark_fn(num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/base_benchmark.py
benchmarks/layer_benchmark/base_benchmark.py
import time import numpy as np import tensorflow as tf from absl import flags import keras FLAGS = flags.FLAGS flags.DEFINE_string( "benchmark_name", None, "The name of benchmark to run. If None, all benchmarks in the file will be " "run.", ) flags.DEFINE_integer( "num_samples", 1000, "Number of input data samples.", ) flags.DEFINE_integer( "batch_size", 20, "Batch size of data.", ) flags.DEFINE_bool( "jit_compile", True, "If True, the benchmark will run with XLA compilation.", ) class BenchmarkMetricsCallback: def __init__(self, start_batch=1, stop_batch=None): self.start_batch = start_batch self.stop_batch = stop_batch self.state = {} def on_train_batch_begin(self, batch, logs=None): if batch == self.start_batch: self.state["benchmark_begin"] = time.time() def on_train_batch_end(self, batch, logs=None): if batch == self.stop_batch: self.state["benchmark_end"] = time.time() throughput = (self.stop_batch - self.start_batch + 1) / ( self.state["benchmark_end"] - self.state["benchmark_begin"] ) self.state["throughput"] = throughput def on_predict_batch_begin(self, batch, logs=None): if batch == self.start_batch: self.state["benchmark_begin"] = time.time() def on_predict_batch_end(self, batch, logs=None): if batch == self.stop_batch: self.state["benchmark_end"] = time.time() throughput = (self.stop_batch - self.start_batch + 1) / ( self.state["benchmark_end"] - self.state["benchmark_begin"] ) self.state["throughput"] = throughput class KerasCoreBenchmarkMetricsCallback(keras.callbacks.Callback): def __init__(self, start_batch=1, stop_batch=None): self._callback = BenchmarkMetricsCallback(start_batch, stop_batch) def on_train_batch_begin(self, batch, logs=None): self._callback.on_train_batch_begin(batch, logs) def on_train_batch_end(self, batch, logs=None): self._callback.on_train_batch_end(batch, logs) def on_predict_batch_begin(self, batch, logs=None): self._callback.on_predict_batch_begin(batch, logs) def on_predict_batch_end(self, batch, logs=None): self._callback.on_predict_batch_end(batch, logs) class TFKerasBenchmarkMetricsCallback(tf.keras.callbacks.Callback): def __init__(self, start_batch=1, stop_batch=None): self._callback = BenchmarkMetricsCallback(start_batch, stop_batch) def on_train_batch_begin(self, batch, logs=None): self._callback.on_train_batch_begin(batch, logs) def on_train_batch_end(self, batch, logs=None): self._callback.on_train_batch_end(batch, logs) def on_predict_batch_begin(self, batch, logs=None): self._callback.on_predict_batch_begin(batch, logs) def on_predict_batch_end(self, batch, logs=None): self._callback.on_predict_batch_end(batch, logs) class LayerBenchmark: def __init__( self, layer_name, init_args, input_shape, flat_call_inputs=True, jit_compile=True, keras_layer=None, tf_keras_layer=None, ): self.layer_name = layer_name _keras_layer_class = getattr(keras.layers, layer_name) _tf_keras_layer_class = getattr(tf.keras.layers, layer_name) if keras_layer is None: # Sometimes you want to initialize the keras layer and tf_keras # layer in a different way. For example, `Bidirectional` layer, # which takes in `keras.layers.Layer` and # `tf.keras.layer.Layer` separately. self._keras_layer = _keras_layer_class(**init_args) else: self._keras_layer = keras_layer if tf_keras_layer is None: self._tf_keras_layer = _tf_keras_layer_class(**init_args) else: self._tf_keras_layer = tf_keras_layer self.input_shape = input_shape self._keras_model = self._build_keras_model( input_shape, flat_call_inputs ) self._tf_keras_model = self._build_tf_keras_model( input_shape, flat_call_inputs ) self._keras_model.compile( loss="mse", optimizer="sgd", jit_compile=jit_compile ) self._tf_keras_model.compile( loss="mse", optimizer="sgd", jit_compile=jit_compile ) self.flat_call_inputs = flat_call_inputs self.jit_compile = jit_compile self.input_shape = input_shape def _build_keras_model(self, input_shape, flat_call_inputs=True): inputs = [] if not isinstance(input_shape[0], (tuple, list)): input_shape = [input_shape] for shape in input_shape: inputs.append(keras.Input(shape=shape)) if flat_call_inputs: outputs = self._keras_layer(*inputs) else: outputs = self._keras_layer(inputs) return keras.Model(inputs=inputs, outputs=outputs) def _build_tf_keras_model(self, input_shape, flat_call_inputs=True): inputs = [] if not isinstance(input_shape[0], (tuple, list)): input_shape = [input_shape] for shape in input_shape: inputs.append(tf.keras.Input(shape=shape)) if flat_call_inputs: outputs = self._tf_keras_layer(*inputs) else: outputs = self._tf_keras_layer(inputs) return tf.keras.Model(inputs=inputs, outputs=outputs) def benchmark_predict(self, num_samples, batch_size, data=None): if data is None: # Generate default data if not provided. if isinstance(self.input_shape[0], (tuple, list)): # The layer has multiple inputs. data = [] for data_shape in self.input_shape: data_shape = [num_samples] + list(data_shape) data.append(np.random.normal(size=data_shape)) else: data_shape = [num_samples] + list(self.input_shape) data = np.random.normal(size=data_shape) num_iterations = num_samples // batch_size - 1 callback = KerasCoreBenchmarkMetricsCallback(stop_batch=num_iterations) tf_keras_callback = TFKerasBenchmarkMetricsCallback( stop_batch=num_iterations ) self._keras_model.predict( data, batch_size=batch_size, callbacks=[callback], ) self._tf_keras_model.predict( data, batch_size=batch_size, callbacks=[tf_keras_callback], ) keras_throughput = callback._callback.state["throughput"] * batch_size tf_keras_throughput = ( tf_keras_callback._callback.state["throughput"] * batch_size ) print( f"Keras 3 throughput of forward pass of {self.layer_name}: " f"{keras_throughput:.2f} samples/sec." ) print( f"TF Keras throughput of forward pass of {self.layer_name}: " f"{tf_keras_throughput:.2f} samples/sec." ) def benchmark_train(self, num_samples, batch_size, data=None, label=None): if data is None: # Generate default data if not provided. if isinstance(self.input_shape[0], (tuple, list)): # The layer has multiple inputs. data = [] for data_shape in self.input_shape: data_shape = [num_samples] + list(data_shape) data.append(np.random.normal(size=data_shape)) else: data_shape = [num_samples] + list(self.input_shape) data = [np.random.normal(size=data_shape)] if label is None: # Generate default label if not provided. if self.flat_call_inputs: # Scale by a small factor to avoid zero gradients. label = ( keras.backend.convert_to_numpy(self._keras_layer(*data)) * 1.001 ) else: label = ( keras.backend.convert_to_numpy(self._keras_layer(data)) * 1.001 ) num_iterations = num_samples // batch_size - 1 callback = KerasCoreBenchmarkMetricsCallback(stop_batch=num_iterations) tf_keras_callback = TFKerasBenchmarkMetricsCallback( stop_batch=num_iterations ) self._keras_model.fit( data, label, batch_size=batch_size, callbacks=[callback], ) self._tf_keras_model.fit( data, label, batch_size=batch_size, callbacks=[tf_keras_callback], ) keras_throughput = callback._callback.state["throughput"] * batch_size tf_keras_throughput = ( tf_keras_callback._callback.state["throughput"] * batch_size ) print( f"Keras 3 throughput of forward & backward pass of " f"{self.layer_name}: {keras_throughput:.2f} samples/sec." ) print( f"TF Keras throughput of forward & backward pass of " f"{self.layer_name}: {tf_keras_throughput:.2f} samples/sec." )
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/__init__.py
benchmarks/layer_benchmark/__init__.py
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/regularization_benchmark.py
benchmarks/layer_benchmark/regularization_benchmark.py
"""Benchmark regularization layers. To run benchmarks, see the following command for an example, please change the flag to your custom value: ``` python3 -m benchmarks.layer_benchmark.regularization_benchmark \ --benchmark_name=benchmark_dropout\ --num_samples=2048 \ --batch_size=256 \ --jit_compile=True ``` """ from absl import app from absl import flags from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_dropout( num_samples, batch_size, jit_compile=True, ): layer_name = "Dropout" init_args = { "rate": 0.5, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_gaussian_dropout( num_samples, batch_size, jit_compile=True, ): layer_name = "GaussianDropout" init_args = { "rate": 0.5, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_gaussian_noise( num_samples, batch_size, jit_compile=True, ): layer_name = "GaussianNoise" init_args = { "stddev": 0.5, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 4], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_spatial_dropout1D( num_samples, batch_size, jit_compile=True, ): layer_name = "SpatialDropout1D" init_args = { "rate": 0.5, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_spatial_dropout2D( num_samples, batch_size, jit_compile=True, ): layer_name = "SpatialDropout2D" init_args = { "rate": 0.5, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_spatial_dropout3D( num_samples, batch_size, jit_compile=True, ): layer_name = "SpatialDropout3D" init_args = { "rate": 0.5, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[32, 32, 32, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) BENCHMARK_NAMES = { "benchmark_dropout": benchmark_dropout, "benchmark_gaussian_dropout": benchmark_gaussian_dropout, "benchmark_gaussian_noise": benchmark_gaussian_noise, "benchmark_spatial_dropout1D": benchmark_spatial_dropout1D, "benchmark_spatial_dropout2D": benchmark_spatial_dropout2D, "benchmark_spatial_dropout3D": benchmark_spatial_dropout3D, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for name, benchmark_fn in BENCHMARK_NAMES.items(): benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must " f"be one of {BENCHMARK_NAMES.keys()}" ) benchmark_fn = BENCHMARK_NAMES[benchmark_name] benchmark_fn(num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/merge_benchmark.py
benchmarks/layer_benchmark/merge_benchmark.py
"""Benchmark merge layers. To run benchmarks, see the following command for an example, please change the flag to your custom value: ``` python3 -m benchmarks.layer_benchmark.merge_benchmark \ --benchmark_name=benchmark_add \ --num_samples=2048 \ --batch_size=256 \ --jit_compile=True ``` """ from absl import app from absl import flags from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_add( num_samples, batch_size, jit_compile=True, ): layer_name = "Add" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 256], [256, 256]], flat_call_inputs=False, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_average( num_samples, batch_size, jit_compile=True, ): layer_name = "Average" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 256], [256, 256]], flat_call_inputs=False, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_concatenate( num_samples, batch_size, jit_compile=True, ): layer_name = "Concatenate" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 256], [256, 256]], flat_call_inputs=False, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_dot( num_samples, batch_size, jit_compile=True, ): layer_name = "Dot" init_args = {"axes": [2, 1]} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 32], [32, 64]], flat_call_inputs=False, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_maximum( num_samples, batch_size, jit_compile=True, ): layer_name = "Maximum" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 256], [256, 256]], flat_call_inputs=False, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_minimum( num_samples, batch_size, jit_compile=True, ): layer_name = "Minimum" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 256], [256, 256]], flat_call_inputs=False, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_multiply( num_samples, batch_size, jit_compile=True, ): layer_name = "Multiply" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 64], [256, 64]], flat_call_inputs=False, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_subtract( num_samples, batch_size, jit_compile=True, ): layer_name = "Subtract" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 256], [256, 256]], flat_call_inputs=False, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) BENCHMARK_NAMES = { "benchmark_add": benchmark_add, "benchmark_average": benchmark_average, "benchmark_concatenate": benchmark_concatenate, "benchmark_dot": benchmark_dot, "benchmark_maximum": benchmark_maximum, "benchmark_minimum": benchmark_minimum, "benchmark_multiply": benchmark_multiply, "benchmark_subtract": benchmark_subtract, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for name, benchmark_fn in BENCHMARK_NAMES.items(): benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must " f"be one of {BENCHMARK_NAMES.keys()}" ) benchmark_fn = BENCHMARK_NAMES[benchmark_name] benchmark_fn(num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/reshaping_benchmark.py
benchmarks/layer_benchmark/reshaping_benchmark.py
"""Benchmark reshaping layers. To run benchmarks, see the following command for an example, please change the flag to your custom value: ``` python3 -m benchmarks.layer_benchmark.reshaping_benchmark \ --benchmark_name=benchmark_cropping2d \ --num_samples=2048 \ --batch_size=256 \ --jit_compile=True ``` """ from absl import app from absl import flags from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_cropping1d( num_samples, batch_size, jit_compile=True, ): layer_name = "Cropping1D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[1024, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_cropping2d( num_samples, batch_size, jit_compile=True, ): layer_name = "Cropping2D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_cropping3d( num_samples, batch_size, jit_compile=True, ): layer_name = "Cropping3D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[32, 32, 32, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_flatten( num_samples, batch_size, jit_compile=True, ): layer_name = "Flatten" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_permute( num_samples, batch_size, jit_compile=True, ): layer_name = "Permute" init_args = { "dims": (2, 1), } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_up_sampling1d( num_samples, batch_size, jit_compile=True, ): layer_name = "UpSampling1D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_up_sampling2d( num_samples, batch_size, jit_compile=True, ): layer_name = "UpSampling2D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[128, 128, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_up_sampling3d( num_samples, batch_size, jit_compile=True, ): layer_name = "UpSampling3D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[32, 16, 16, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_zero_padding1d( num_samples, batch_size, jit_compile=True, ): layer_name = "ZeroPadding1D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_zero_padding2d( num_samples, batch_size, jit_compile=True, ): layer_name = "ZeroPadding2D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_zero_padding3d( num_samples, batch_size, jit_compile=True, ): layer_name = "ZeroPadding3D" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[32, 32, 32, 3], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) BENCHMARK_NAMES = { "benchmark_cropping1d": benchmark_cropping1d, "benchmark_cropping2d": benchmark_cropping2d, "benchmark_cropping3d": benchmark_cropping3d, "benchmark_flatten": benchmark_flatten, "benchmark_permute": benchmark_permute, "benchmark_up_sampling1d": benchmark_up_sampling1d, "benchmark_up_sampling2d": benchmark_up_sampling2d, "benchmark_up_sampling3d": benchmark_up_sampling3d, "benchmark_zero_padding1d": benchmark_zero_padding1d, "benchmark_zero_padding2d": benchmark_zero_padding2d, "benchmark_zero_padding3d": benchmark_zero_padding3d, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for name, benchmark_fn in BENCHMARK_NAMES.items(): benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must " f"be one of {BENCHMARK_NAMES.keys()}" ) benchmark_fn = BENCHMARK_NAMES[benchmark_name] benchmark_fn(num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/attention_benchmark.py
benchmarks/layer_benchmark/attention_benchmark.py
"""Benchmark attention layers. To run benchmarks, see the following command for an example, please change the flag to your custom value: ``` python3 -m benchmarks.layer_benchmark.attention_benchmark \ --benchmark_name=benchmark_attention \ --num_samples=2048 \ --batch_size=256 \ --jit_compile=True ``` """ from absl import app from absl import flags from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_attention( num_samples, batch_size, jit_compile=True, ): layer_name = "Attention" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 64], [256, 64]], flat_call_inputs=False, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_multi_head_attention( num_samples, batch_size, jit_compile=True, ): layer_name = "MultiHeadAttention" init_args = { "num_heads": 4, "key_dim": 16, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 64], [256, 64], [256, 64]], flat_call_inputs=True, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_additive_attention( num_samples, batch_size, jit_compile=True, ): layer_name = "AdditiveAttention" init_args = {} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[[256, 64], [256, 64], [256, 64]], flat_call_inputs=False, jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) BENCHMARK_NAMES = { "benchmark_attention": benchmark_attention, "benchmark_multi_head_attention": benchmark_multi_head_attention, "benchmark_additive_attention": benchmark_additive_attention, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for name, benchmark_fn in BENCHMARK_NAMES.items(): benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must " f"be one of {BENCHMARK_NAMES.keys()}" ) benchmark_fn = BENCHMARK_NAMES[benchmark_name] benchmark_fn(num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/layer_benchmark/core_benchmark.py
benchmarks/layer_benchmark/core_benchmark.py
"""Benchmark core layers. To run benchmarks, see the following command for an example, please change the flag to your custom value: ``` python3 -m benchmarks.layer_benchmark.core_benchmark \ --benchmark_name=benchmark_dense \ --num_samples=2048 \ --batch_size=256 \ --jit_compile=True ``` """ import numpy as np from absl import app from absl import flags from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_dense( num_samples, batch_size, jit_compile=True, ): layer_name = "Dense" init_args = {"units": 256} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_einsum_dense( num_samples, batch_size, jit_compile=True, ): layer_name = "EinsumDense" init_args = { "equation": "abc,cd->abd", "output_shape": (None, 256), } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[256, 256], jit_compile=jit_compile, ) benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) def benchmark_embedding( num_samples, batch_size, jit_compile=True, ): layer_name = "Embedding" init_args = { "input_dim": 128, "output_dim": 256, } benchmark = LayerBenchmark( layer_name, init_args, input_shape=[ 256, ], jit_compile=jit_compile, ) data = [np.random.randint(30, size=(num_samples, 256))] benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, data=data, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, data=data, ) BENCHMARK_NAMES = { "benchmark_dense": benchmark_dense, "benchmark_einsum_dense": benchmark_einsum_dense, "benchmark_embedding": benchmark_embedding, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for name, benchmark_fn in BENCHMARK_NAMES.items(): benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must " f"be one of {BENCHMARK_NAMES.keys()}" ) benchmark_fn = BENCHMARK_NAMES[benchmark_name] benchmark_fn(num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/model_benchmark/bert_benchmark.py
benchmarks/model_benchmark/bert_benchmark.py
"""Benchmark BERT model on GLUE/MRPC task. To run the script, make sure you are in benchmarks/ directory, abd run the command below: ``` python3 -m model_benchmark.bert_benchmark \ --epochs 2 \ --batch_size 32 ``` """ import time import keras_nlp import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from absl import app from absl import flags from absl import logging from model_benchmark.benchmark_utils import BenchmarkMetricsCallback import keras flags.DEFINE_string("model_size", "small", "The size of model to benchmark.") flags.DEFINE_string( "mixed_precision_policy", "mixed_float16", "The global precision policy to use, e.g., 'mixed_float16' or 'float32'.", ) flags.DEFINE_integer("epochs", 2, "The number of epochs.") flags.DEFINE_integer("batch_size", 8, "Batch Size.") FLAGS = flags.FLAGS MODEL_SIZE_MAP = { "tiny": "bert_tiny_en_uncased", "small": "bert_small_en_uncased", "base": "bert_base_en_uncased", "large": "bert_large_en_uncased", } def load_data(): """Load data. Load GLUE/MRPC dataset, and convert the dictionary format to (features, label), where `features` is a tuple of all input sentences. """ feature_names = ("sentence1", "sentence2") def split_features(x): # GLUE comes with dictionary data, we convert it to a uniform format # (features, label), where features is a tuple consisting of all # features. This format is necessary for using KerasNLP preprocessors. features = tuple([x[name] for name in feature_names]) label = x["label"] return (features, label) train_ds, test_ds, validation_ds = tfds.load( "glue/mrpc", split=["train", "test", "validation"], ) train_ds = ( train_ds.map(split_features, num_parallel_calls=tf.data.AUTOTUNE) .batch(FLAGS.batch_size) .prefetch(tf.data.AUTOTUNE) ) test_ds = ( test_ds.map(split_features, num_parallel_calls=tf.data.AUTOTUNE) .batch(FLAGS.batch_size) .prefetch(tf.data.AUTOTUNE) ) validation_ds = ( validation_ds.map(split_features, num_parallel_calls=tf.data.AUTOTUNE) .batch(FLAGS.batch_size) .prefetch(tf.data.AUTOTUNE) ) return train_ds, test_ds, validation_ds def load_model(): if FLAGS.model_size not in MODEL_SIZE_MAP.keys(): raise KeyError( f"`model_size` must be one of {MODEL_SIZE_MAP.keys()}, but " f"received {FLAGS.model_size}." ) return keras_nlp.models.BertClassifier.from_preset( MODEL_SIZE_MAP[FLAGS.model_size], num_classes=2 ) def main(_): keras.mixed_precision.set_dtype_policy(FLAGS.mixed_precision_policy) logging.info( "Benchmarking configs...\n" "=========================\n" f"MODEL: BERT {FLAGS.model_size}\n" f"TASK: glue/mrpc \n" f"BATCH_SIZE: {FLAGS.batch_size}\n" f"EPOCHS: {FLAGS.epochs}\n" "=========================\n" ) # Load datasets. train_ds, test_ds, validation_ds = load_data() # Load the model. model = load_model() # Set loss and metrics. loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True) metrics = [keras.metrics.SparseCategoricalAccuracy()] # Configure optimizer. lr = keras.optimizers.schedules.PolynomialDecay( 5e-4, decay_steps=train_ds.cardinality() * FLAGS.epochs, end_learning_rate=0.0, ) optimizer = keras.optimizers.AdamW(lr, weight_decay=0.01) optimizer.exclude_from_weight_decay( var_names=["LayerNorm", "layer_norm", "bias"] ) model.compile(optimizer=optimizer, loss=loss, metrics=metrics) benchmark_metrics_callback = BenchmarkMetricsCallback( start_batch=1, stop_batch=train_ds.cardinality().numpy() - 1, ) # Start training. logging.info("Starting Training...") st = time.time() history = model.fit( train_ds, validation_data=validation_ds, epochs=FLAGS.epochs, callbacks=[benchmark_metrics_callback], ) wall_time = time.time() - st validation_accuracy = history.history["val_sparse_categorical_accuracy"][-1] examples_per_second = ( np.mean(np.array(benchmark_metrics_callback.state["throughput"])) * FLAGS.batch_size ) logging.info("Training Finished!") logging.info(f"Wall Time: {wall_time:.4f} seconds.") logging.info(f"Validation Accuracy: {validation_accuracy:.4f}") logging.info(f"examples_per_second: {examples_per_second:.4f}") if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/model_benchmark/image_classification_benchmark.py
benchmarks/model_benchmark/image_classification_benchmark.py
"""Image classification benchmark. This script runs image classification benchmark with "dogs vs cats" datasets. It supports the following 3 models: - EfficientNetV2B0 - Xception - ResNet50V2 To run the benchmark, make sure you are in model_benchmark/ directory, and run the command below: python3 -m model_benchmark.image_classification_benchmark \ --model="EfficientNetV2B0" \ --epochs=2 \ --batch_size=32 \ --mixed_precision_policy="mixed_float16" """ import time import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from absl import app from absl import flags from absl import logging from model_benchmark.benchmark_utils import BenchmarkMetricsCallback import keras flags.DEFINE_string("model", "EfficientNetV2B0", "The model to benchmark.") flags.DEFINE_integer("epochs", 1, "The number of epochs.") flags.DEFINE_integer("batch_size", 4, "Batch Size.") flags.DEFINE_string( "mixed_precision_policy", "mixed_float16", "The global precision policy to use, e.g., 'mixed_float16' or 'float32'.", ) FLAGS = flags.FLAGS BATCH_SIZE = 32 IMAGE_SIZE = (224, 224) CHANNELS = 3 MODEL_MAP = { "EfficientNetV2B0": keras.applications.EfficientNetV2B0, "Xception": keras.applications.Xception, "ResNet50V2": keras.applications.ResNet50V2, } def load_data(): # Load cats vs dogs dataset, and split into train and validation sets. train_dataset, val_dataset = tfds.load( "cats_vs_dogs", split=["train[:90%]", "train[90%:]"], as_supervised=True ) resizing = keras.layers.Resizing( IMAGE_SIZE[0], IMAGE_SIZE[1], crop_to_aspect_ratio=True ) def preprocess_inputs(image, label): image = tf.cast(image, "float32") return resizing(image), label train_dataset = ( train_dataset.map( preprocess_inputs, num_parallel_calls=tf.data.AUTOTUNE ) .batch(FLAGS.batch_size) .prefetch(tf.data.AUTOTUNE) ) val_dataset = ( val_dataset.map(preprocess_inputs, num_parallel_calls=tf.data.AUTOTUNE) .batch(FLAGS.batch_size) .cache() .prefetch(tf.data.AUTOTUNE) ) return train_dataset, val_dataset def load_model(): model_class = MODEL_MAP[FLAGS.model] # Load the EfficientNetV2B0 model and add a classification head. model = model_class(include_top=False, weights="imagenet") classifier = keras.models.Sequential( [ keras.Input([IMAGE_SIZE[0], IMAGE_SIZE[1], CHANNELS]), model, keras.layers.GlobalAveragePooling2D(), keras.layers.Dense(2), ] ) return classifier def main(_): keras.mixed_precision.set_dtype_policy(FLAGS.mixed_precision_policy) logging.info( "Benchmarking configs...\n" "=========================\n" f"MODEL: {FLAGS.model}\n" f"TASK: image classification/dogs-vs-cats \n" f"BATCH_SIZE: {FLAGS.batch_size}\n" f"EPOCHS: {FLAGS.epochs}\n" "=========================\n" ) # Load datasets. train_ds, validation_ds = load_data() # Load the model. classifier = load_model() lr = keras.optimizers.schedules.PolynomialDecay( 5e-4, decay_steps=train_ds.cardinality() * FLAGS.epochs, end_learning_rate=0.0, ) optimizer = keras.optimizers.Adam(lr) loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True) benchmark_metrics_callback = BenchmarkMetricsCallback( start_batch=1, stop_batch=train_ds.cardinality().numpy() - 1, ) classifier.compile( optimizer=optimizer, loss=loss, metrics=["sparse_categorical_accuracy"], ) # Start training. logging.info("Starting Training...") st = time.time() history = classifier.fit( train_ds, validation_data=validation_ds, epochs=FLAGS.epochs, callbacks=[benchmark_metrics_callback], ) wall_time = time.time() - st validation_accuracy = history.history["val_sparse_categorical_accuracy"][-1] examples_per_second = ( np.mean(np.array(benchmark_metrics_callback.state["throughput"])) * FLAGS.batch_size ) logging.info("Training Finished!") logging.info(f"Wall Time: {wall_time:.4f} seconds.") logging.info(f"Validation Accuracy: {validation_accuracy:.4f}") logging.info(f"examples_per_second: {examples_per_second:.4f}") if __name__ == "__main__": app.run(main)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/model_benchmark/__init__.py
benchmarks/model_benchmark/__init__.py
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/model_benchmark/benchmark_utils.py
benchmarks/model_benchmark/benchmark_utils.py
import time import keras class BenchmarkMetricsCallback(keras.callbacks.Callback): def __init__(self, start_batch=1, stop_batch=None): self.start_batch = start_batch self.stop_batch = stop_batch # Store the throughput of each epoch. self.state = {"throughput": []} def on_train_batch_begin(self, batch, logs=None): if batch == self.start_batch: self.state["epoch_begin_time"] = time.time() def on_train_batch_end(self, batch, logs=None): if batch == self.stop_batch: epoch_end_time = time.time() throughput = (self.stop_batch - self.start_batch + 1) / ( epoch_end_time - self.state["epoch_begin_time"] ) self.state["throughput"].append(throughput)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/torch_ctl_benchmark/conv_model_benchmark.py
benchmarks/torch_ctl_benchmark/conv_model_benchmark.py
"""Benchmark Keras performance with torch custom training loop. In this file we use a convolution model. Training loop is written in the vanilla torch way, and we compare the performance between building model with Keras and torch. """ import numpy as np import torch import torch.nn as nn import torch.optim as optim import keras from benchmarks.torch_ctl_benchmark.benchmark_utils import train_loop from keras import layers num_classes = 2 input_shape = (3, 256, 256) batch_size = 128 num_batches = 20 num_epochs = 1 x_train = np.random.normal( size=(num_batches * batch_size, *input_shape) ).astype(np.float32) y_train = np.random.randint(0, num_classes, size=(num_batches * batch_size,)) # Create a TensorDataset dataset = torch.utils.data.TensorDataset( torch.from_numpy(x_train), torch.from_numpy(y_train) ) # Create a DataLoader train_loader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, shuffle=False ) class TorchModel(torch.nn.Module): def __init__(self): super().__init__() self.conv = torch.nn.Conv2d(3, 32, kernel_size=(3, 3)) self.activation = torch.nn.ReLU() self.max_pool = torch.nn.MaxPool2d((2, 2)) self.flatten = torch.nn.Flatten() self.dense = torch.nn.LazyLinear(num_classes) self.softmax = torch.nn.Softmax(dim=1) def forward(self, x): x = self.conv(x) x = self.activation(x) x = self.max_pool(x) x = self.flatten(x) x = self.dense(x) x = self.softmax(x) return x def run_keras_custom_training_loop(): keras_model = keras.Sequential( [ layers.Input(shape=input_shape), layers.Conv2D(32, kernel_size=(3, 3), activation="relu"), layers.MaxPooling2D(pool_size=(2, 2)), layers.Flatten(), layers.Dense(num_classes), layers.Softmax(), ] ) optimizer = optim.Adam(keras_model.parameters(), lr=0.001) loss_fn = nn.CrossEntropyLoss() train_loop( keras_model, train_loader, num_epochs=num_epochs, optimizer=optimizer, loss_fn=loss_fn, framework="keras", ) def run_torch_custom_training_loop(): torch_model = TorchModel() optimizer = optim.Adam(torch_model.parameters(), lr=0.001) loss_fn = nn.CrossEntropyLoss() train_loop( torch_model, train_loader, num_epochs=num_epochs, optimizer=optimizer, loss_fn=loss_fn, framework="torch", ) if __name__ == "__main__": run_keras_custom_training_loop() run_torch_custom_training_loop()
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/torch_ctl_benchmark/dense_model_benchmark.py
benchmarks/torch_ctl_benchmark/dense_model_benchmark.py
"""Benchmark Keras performance with torch custom training loop. In this file we use a model with 3 dense layers. Training loop is written in the vanilla torch way, and we compare the performance between building model with Keras and torch. """ import numpy as np import torch import torch.nn as nn import torch.optim as optim import keras from benchmarks.torch_ctl_benchmark.benchmark_utils import train_loop from keras import layers num_classes = 2 input_shape = (8192,) batch_size = 4096 num_batches = 20 num_epochs = 1 x_train = np.random.normal( size=(num_batches * batch_size, *input_shape) ).astype(np.float32) y_train = np.random.randint(0, num_classes, size=(num_batches * batch_size,)) # Create a TensorDataset dataset = torch.utils.data.TensorDataset( torch.from_numpy(x_train), torch.from_numpy(y_train) ) # Create a DataLoader train_loader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, shuffle=False ) class TorchModel(torch.nn.Module): def __init__(self): super().__init__() self.dense1 = torch.nn.Linear(8192, 64) self.activation1 = torch.nn.ReLU() self.dense2 = torch.nn.Linear(64, 8) self.activation2 = torch.nn.ReLU() self.dense3 = torch.nn.Linear(8, num_classes) self.softmax = torch.nn.Softmax(dim=1) def forward(self, x): x = self.dense1(x) x = self.activation1(x) x = self.dense2(x) x = self.activation2(x) x = self.dense3(x) x = self.softmax(x) return x def run_keras_custom_training_loop(): keras_model = keras.Sequential( [ layers.Input(shape=input_shape), layers.Dense(64, activation="relu"), layers.Dense(8, activation="relu"), layers.Dense(num_classes), layers.Softmax(), ] ) optimizer = optim.Adam(keras_model.parameters(), lr=0.001) loss_fn = nn.CrossEntropyLoss() train_loop( keras_model, train_loader, num_epochs=num_epochs, optimizer=optimizer, loss_fn=loss_fn, framework="keras", ) def run_torch_custom_training_loop(): torch_model = TorchModel() optimizer = optim.Adam(torch_model.parameters(), lr=0.001) loss_fn = nn.CrossEntropyLoss() train_loop( torch_model, train_loader, num_epochs=num_epochs, optimizer=optimizer, loss_fn=loss_fn, framework="torch", ) if __name__ == "__main__": run_keras_custom_training_loop() run_torch_custom_training_loop()
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/torch_ctl_benchmark/__init__.py
benchmarks/torch_ctl_benchmark/__init__.py
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/benchmarks/torch_ctl_benchmark/benchmark_utils.py
benchmarks/torch_ctl_benchmark/benchmark_utils.py
import time import numpy as np import torch def train_loop(model, train_loader, num_epochs, optimizer, loss_fn, framework): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model.to(device) start = None average_batch_time_per_epoch = [] for _ in range(num_epochs): running_loss = 0.0 for batch_idx, (inputs, targets) in enumerate(train_loader): if batch_idx == 1: start = time.time() inputs = inputs.to(device) targets = targets.to(device) # Forward pass outputs = model(inputs) loss = loss_fn(outputs, targets) # Backward and optimize optimizer.zero_grad() loss.backward() optimizer.step() running_loss += loss.item() end = time.time() average_batch_time_per_epoch.append( (end - start) / (len(train_loader) - 1) ) average_time = np.mean(average_batch_time_per_epoch) print(f"Time per batch in {framework}: {average_time:.2f}")
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/import_test.py
integration_tests/import_test.py
import os import re import subprocess from keras.src import backend from keras.src.backend import config # For torch, use index url to avoid installing nvidia drivers for the test. BACKEND_REQ = { "tensorflow": ("tensorflow-cpu", ""), "torch": ( "torch", "--extra-index-url https://download.pytorch.org/whl/cpu ", ), "jax": ("jax[cpu]", ""), "openvino": ("openvino", ""), } def setup_package(): subprocess.run("rm -rf tmp_build_dir", shell=True) build_process = subprocess.run( "python3 pip_build.py", capture_output=True, text=True, shell=True, ) print(build_process.stdout) whl_path = re.findall( r"[^\s]*\.whl", build_process.stdout, ) if not whl_path: print(build_process.stdout) print(build_process.stderr) raise ValueError("Installing Keras package unsuccessful. ") return whl_path[-1] def create_virtualenv(): env_setup = [ # Create virtual environment "python3 -m venv test_env", ] os.environ["PATH"] = os.pathsep.join( ( os.path.join(os.getcwd(), "test_env", "bin"), os.environ.get("PATH", ""), ) ) if os.name == "nt": os.environ["PATH"] = os.pathsep.join( ( os.path.join(os.getcwd(), "test_env", "Scripts"), os.environ["PATH"], ) ) run_commands_local(env_setup) def manage_venv_installs(whl_path): other_backends = list(set(BACKEND_REQ.keys()) - {backend.backend()}) backend_pkg, backend_extra_url = BACKEND_REQ[backend.backend()] install_setup = [ # Installs the backend's package and common requirements f"pip install {backend_extra_url}{backend_pkg}", "pip install -r requirements-common.txt", "pip install pytest", # Ensure other backends are uninstalled "pip uninstall -y {0} {1} {2}".format( BACKEND_REQ[other_backends[0]][0], BACKEND_REQ[other_backends[1]][0], BACKEND_REQ[other_backends[2]][0], ), # Install `.whl` package f"pip install {whl_path}", ] # Install flax for JAX when NNX is enabled if backend.backend() == "jax" and config.is_nnx_enabled(): install_setup.append("pip install flax>=0.10.1") run_commands_venv(install_setup) def run_keras_flow(): test_script = [ # Runs the example script "python -m pytest integration_tests/basic_full_flow.py", ] run_commands_venv(test_script) def cleanup(): cleanup_script = [ # Exits virtual environment, deletes files, and any # miscellaneous install logs "exit", "rm -rf test_env", "rm -rf tmp_build_dir", "rm -f *+cpu", ] run_commands_local(cleanup_script) def run_commands_local(commands): for command in commands: print(f"Running command: {command}") subprocess.run(command, shell=True) def run_commands_venv(commands): for command in commands: print(f"Running command: {command}") cmd_with_args = command.split(" ") cmd_with_args[0] = os.path.join( "test_env", "Scripts" if os.name == "nt" else "bin", cmd_with_args[0], ) p = subprocess.Popen(cmd_with_args) assert p.wait() == 0 def test_keras_imports(): try: # Ensures packages from all backends are installed. # Builds Keras core package and returns package file path. whl_path = setup_package() # Creates and activates a virtual environment. create_virtualenv() # Ensures the backend's package is installed # and the other backends are uninstalled. manage_venv_installs(whl_path) # Runs test of basic flow in Keras Core. # Tests for backend-specific imports and `model.fit()`. run_keras_flow() # Removes virtual environment and associated files finally: cleanup() if __name__ == "__main__": test_keras_imports()
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/torch_workflow_test.py
integration_tests/torch_workflow_test.py
import torch from keras.src import layers from keras.src import testing from keras.src.backend.common import KerasVariable class Net(torch.nn.Module): def __init__(self): super().__init__() self.fc1 = layers.Dense(1) def forward(self, x): x = self.fc1(x) return x class TorchWorkflowTest(testing.TestCase): def test_keras_layer_in_nn_module(self): net = Net() # Test using Keras layer in a nn.Module. # Test forward pass self.assertAllEqual(list(net(torch.empty(100, 10)).shape), [100, 1]) # Test KerasVariables are added as nn.Parameter. self.assertLen(list(net.parameters()), 2) # Test using KerasVariable as a torch tensor for torch ops. kernel = net.fc1.kernel transposed_kernel = torch.transpose(kernel, 0, 1) self.assertIsInstance(kernel, KerasVariable) self.assertIsInstance( torch.mul(kernel, transposed_kernel), torch.Tensor )
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/torch_custom_fit_test.py
integration_tests/torch_custom_fit_test.py
import numpy as np import torch import keras def test_custom_fit(): class CustomModel(keras.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.loss_tracker = keras.metrics.Mean(name="loss") self.mae_metric = keras.metrics.MeanAbsoluteError(name="mae") self.loss_fn = keras.losses.MeanSquaredError() def train_step(self, data): x, y = data self.zero_grad() y_pred = self(x, training=True) loss = self.loss_fn(y, y_pred) loss.backward() trainable_weights = [v for v in self.trainable_weights] gradients = [v.value.grad for v in trainable_weights] with torch.no_grad(): self.optimizer.apply(gradients, trainable_weights) self.loss_tracker.update_state(loss) self.mae_metric.update_state(y, y_pred) return { "loss": self.loss_tracker.result(), "mae": self.mae_metric.result(), } @property def metrics(self): return [self.loss_tracker, self.mae_metric] inputs = keras.Input(shape=(32,)) outputs = keras.layers.Dense(1)(inputs) model = CustomModel(inputs, outputs) model.compile(optimizer="adam") x = np.random.random((64, 32)) y = np.random.random((64, 1)) history = model.fit(x, y, epochs=1) assert "loss" in history.history assert "mae" in history.history print("History:") print(history.history) if __name__ == "__main__": test_custom_fit()
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/basic_full_flow.py
integration_tests/basic_full_flow.py
import numpy as np import pytest import keras from keras.src import layers from keras.src import losses from keras.src import metrics from keras.src import optimizers from keras.src import testing class MyModel(keras.Model): def __init__(self, hidden_dim, output_dim, **kwargs): super().__init__(**kwargs) self.hidden_dim = hidden_dim self.output_dim = output_dim self.dense1 = layers.Dense(hidden_dim, activation="relu") self.dense2 = layers.Dense(hidden_dim, activation="relu") self.dense3 = layers.Dense(output_dim) def call(self, x): x = self.dense1(x) x = self.dense2(x) return self.dense3(x) class BasicFlowTest(testing.TestCase): @pytest.mark.requires_trainable_backend def test_basic_fit(self): model = MyModel(hidden_dim=2, output_dim=1) x = np.random.random((128, 4)) y = np.random.random((128, 4)) batch_size = 32 epochs = 3 model.compile( optimizer=optimizers.SGD(learning_rate=0.001), loss=losses.MeanSquaredError(), metrics=[metrics.MeanSquaredError()], ) output_before_fit = model(x) model.fit( x, y, batch_size=batch_size, epochs=epochs, validation_split=0.2 ) output_after_fit = model(x) self.assertNotAllClose(output_before_fit, output_after_fit) def test_basic_fit_no_training(self): model = MyModel(hidden_dim=2, output_dim=1) x = np.random.random((128, 4)) model.predict(x) model(x)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/model_visualization_test.py
integration_tests/model_visualization_test.py
import re import keras from keras.src import testing from keras.src.utils import model_to_dot from keras.src.utils import plot_model class SubclassModel(keras.models.Model): def __init__(self, name): super().__init__(name=name) def call(self, x): return x def parse_text_from_html(html): pattern = r"<font[^>]*>(.*?)</font>" matches = re.findall(pattern, html) for match in matches: clean_text = re.sub(r"<[^>]*>", "", match) return clean_text return "" def get_node_text(node): attributes = node.get_attributes() if "label" in attributes: html = node.get_attributes()["label"] return parse_text_from_html(html) else: return None def get_edge_dict(dot): def get_node_dict(graph, path=""): nodes = { node.get_name(): path + get_node_text(node) for node in graph.get_nodes() if node.get_name() != "node" # Dummy node inserted by pydot? } for subgraph in graph.get_subgraphs(): sub_nodes = get_node_dict( subgraph, path=f"{path}{subgraph.get_label()} > " ) nodes.update(sub_nodes) return nodes node_dict = get_node_dict(dot) def get_edges(graph): edges = list(graph.get_edges()) for subgraph in graph.get_subgraphs(): edges.extend(get_edges(subgraph)) return edges edge_dict = dict() dangling_edges = [] for edge in get_edges(dot): source_node = node_dict.get(edge.get_source(), None) destination_node = node_dict.get(edge.get_destination(), None) if source_node is None or destination_node is None: dangling_edges.append( f"from '{source_node}'/'{edge.get_source()}' " f"to '{destination_node}'/'{edge.get_destination()}'" ) if source_node in edge_dict: destination_nodes = edge_dict[source_node] if not isinstance(destination_nodes, set): destination_nodes = set([destination_nodes]) edge_dict[source_node] = destination_nodes destination_nodes.add(destination_node) else: edge_dict[source_node] = destination_node if dangling_edges: raise ValueError(f"Dangling edges found: {dangling_edges}") return edge_dict class ModelVisualizationTest(testing.TestCase): def multi_plot_model(self, model, name, expand_nested=False): if expand_nested: name = f"{name}-expand_nested" TEST_CASES = [ {}, { "show_shapes": True, }, { "show_shapes": True, "show_dtype": True, }, { "show_shapes": True, "show_dtype": True, "show_layer_names": True, }, { "show_shapes": True, "show_dtype": True, "show_layer_names": True, "show_layer_activations": True, }, { "show_shapes": True, "show_dtype": True, "show_layer_names": True, "show_layer_activations": True, "show_trainable": True, }, { "show_shapes": True, "show_dtype": True, "show_layer_names": True, "show_layer_activations": True, "show_trainable": True, "rankdir": "LR", }, { "show_layer_activations": True, "show_trainable": True, }, ] for test_case in TEST_CASES: tags = [v if k == "rankdir" else k for k, v in test_case.items()] file_name = f"{'-'.join([name] + tags)}.png" plot_model( model, file_name, expand_nested=expand_nested, **test_case ) self.assertFileExists(file_name) def test_plot_sequential_model(self): model = keras.Sequential( [ keras.Input((3,), name="input"), keras.layers.Dense(4, activation="relu", name="dense"), keras.layers.Dense(1, activation="sigmoid", name="dense_1"), ] ) edge_dict = get_edge_dict(model_to_dot(model)) self.assertEqual( edge_dict, { "dense (Dense)": "dense_1 (Dense)", }, ) self.multi_plot_model(model, "sequential") def test_plot_functional_model(self): inputs = keras.Input((3,), name="input") x = keras.layers.Dense( 4, activation="relu", trainable=False, name="dense" )(inputs) residual = x x = keras.layers.Dense(4, activation="relu", name="dense_1")(x) x = keras.layers.Dense(4, activation="relu", name="dense_2")(x) x = keras.layers.Dense(4, activation="relu", name="dense_3")(x) x += residual residual = x x = keras.layers.Dense(4, activation="relu", name="dense_4")(x) x = keras.layers.Dense(4, activation="relu", name="dense_5")(x) x = keras.layers.Dense(4, activation="relu", name="dense_6")(x) x += residual x = keras.layers.Dropout(0.5, name="dropout")(x) outputs = keras.layers.Dense(1, activation="sigmoid", name="dense_7")(x) model = keras.Model(inputs, outputs) edge_dict = get_edge_dict(model_to_dot(model)) self.assertEqual( edge_dict, { "input (InputLayer)": "dense (Dense)", "dense (Dense)": {"dense_1 (Dense)", "add (Add)"}, "dense_1 (Dense)": "dense_2 (Dense)", "dense_2 (Dense)": "dense_3 (Dense)", "dense_3 (Dense)": "add (Add)", "add (Add)": {"dense_4 (Dense)", "add_1 (Add)"}, "dense_4 (Dense)": "dense_5 (Dense)", "dense_5 (Dense)": "dense_6 (Dense)", "dense_6 (Dense)": "add_1 (Add)", "add_1 (Add)": "dropout (Dropout)", "dropout (Dropout)": "dense_7 (Dense)", }, ) self.multi_plot_model(model, "functional") def test_plot_subclassed_model(self): model = SubclassModel(name="subclass") model.build((None, 3)) self.multi_plot_model(model, "subclassed") def test_plot_nested_functional_model(self): inputs = keras.Input((3,), name="input") x = keras.layers.Dense(4, activation="relu", name="dense")(inputs) x = keras.layers.Dense(4, activation="relu", name="dense_1")(x) outputs = keras.layers.Dense(3, activation="relu", name="dense_2")(x) inner_model = keras.Model(inputs, outputs, name="inner_model") inputs = keras.Input((3,), name="input_1") x = keras.layers.Dense( 3, activation="relu", trainable=False, name="dense_3" )(inputs) residual = x x = inner_model(x) x = keras.layers.Add(name="add")([x, residual]) residual = x x = keras.layers.Dense(4, activation="relu", name="dense_4")(x) x = keras.layers.Dense(4, activation="relu", name="dense_5")(x) x = keras.layers.Dense(3, activation="relu", name="dense_6")(x) x = keras.layers.Add(name="add_1")([x, residual]) x = keras.layers.Dropout(0.5, name="dropout")(x) outputs = keras.layers.Dense(1, activation="sigmoid", name="dense_7")(x) model = keras.Model(inputs, outputs) edge_dict = get_edge_dict(model_to_dot(model)) self.assertEqual( edge_dict, { "input_1 (InputLayer)": "dense_3 (Dense)", "dense_3 (Dense)": {"inner_model (Functional)", "add (Add)"}, "inner_model (Functional)": "add (Add)", "add (Add)": {"dense_4 (Dense)", "add_1 (Add)"}, "dense_4 (Dense)": "dense_5 (Dense)", "dense_5 (Dense)": "dense_6 (Dense)", "dense_6 (Dense)": "add_1 (Add)", "add_1 (Add)": "dropout (Dropout)", "dropout (Dropout)": "dense_7 (Dense)", }, ) self.multi_plot_model(model, "nested-functional") edge_dict = get_edge_dict(model_to_dot(model, expand_nested=True)) self.assertEqual( edge_dict, { "input_1 (InputLayer)": "dense_3 (Dense)", "dense_3 (Dense)": { "inner_model > input (InputLayer)", "add (Add)", }, "inner_model > input (InputLayer)": "inner_model > dense (Dense)", # noqa: E501 "inner_model > dense (Dense)": "inner_model > dense_1 (Dense)", # noqa: E501 "inner_model > dense_1 (Dense)": "inner_model > dense_2 (Dense)", # noqa: E501 "inner_model > dense_2 (Dense)": "add (Add)", "add (Add)": {"dense_4 (Dense)", "add_1 (Add)"}, "dense_4 (Dense)": "dense_5 (Dense)", "dense_5 (Dense)": "dense_6 (Dense)", "dense_6 (Dense)": "add_1 (Add)", "add_1 (Add)": "dropout (Dropout)", "dropout (Dropout)": "dense_7 (Dense)", }, ) self.multi_plot_model(model, "nested-functional", expand_nested=True) def test_plot_functional_model_with_splits_and_merges(self): class SplitLayer(keras.Layer): def call(self, x): return list(keras.ops.split(x, 2, axis=1)) class ConcatLayer(keras.Layer): def call(self, xs): return keras.ops.concatenate(xs, axis=1) inputs = keras.Input((2,), name="input") a, b = SplitLayer()(inputs) a = keras.layers.Dense(2, name="dense")(a) b = keras.layers.Dense(2, name="dense_1")(b) outputs = ConcatLayer(name="concat_layer")([a, b]) model = keras.Model(inputs, outputs) edge_dict = get_edge_dict(model_to_dot(model)) self.assertEqual( edge_dict, { "input (InputLayer)": "split_layer (SplitLayer)", "split_layer (SplitLayer)": { "dense (Dense)", "dense_1 (Dense)", }, "dense (Dense)": "concat_layer (ConcatLayer)", "dense_1 (Dense)": "concat_layer (ConcatLayer)", }, ) self.multi_plot_model(model, "split-functional") def test_plot_sequential_in_sequential(self): inner_model = keras.models.Sequential( [ keras.layers.Dense(10, name="dense2"), keras.layers.Dense(10, name="dense3"), ], name="sub", ) model = keras.models.Sequential( [ keras.layers.Dense(10, name="dense1"), inner_model, ], ) model.build((1, 10)) # # +-------------------------+ # | dense1 (Dense) | # +-------------------------+ # | # v # +-------------------------+ # | sub (Sequential) | # +-------------------------+ # edge_dict = get_edge_dict(model_to_dot(model)) self.assertEqual( edge_dict, { "dense1 (Dense)": "sub (Sequential)", }, ) self.multi_plot_model(model, "sequential_in_sequential") # # +-------------------------+ # | dense1 (Dense) | # +-------------------------+ # | # +--------------|--------------+ # | sub v | # | +-------------------------+ | # | | dense2 (Dense) | | # | +-------------------------+ | # | | | # | v | # | +-------------------------+ | # | | dense3 (Dense) | | # | +-------------------------+ | # +-----------------------------+ # edge_dict = get_edge_dict(model_to_dot(model, expand_nested=True)) self.assertEqual( edge_dict, { "dense1 (Dense)": "sub > dense2 (Dense)", "sub > dense2 (Dense)": "sub > dense3 (Dense)", }, ) self.multi_plot_model( model, "sequential_in_sequential", expand_nested=True ) def test_plot_functional_in_functional(self): inner_input = keras.layers.Input((10,), name="inner_input") x = keras.layers.Dense(10, name="dense1")(inner_input) x = keras.layers.Dense(10, name="dense2")(x) inner_model = keras.models.Model(inner_input, x, name="inner") outer_input = keras.layers.Input((10,), name="outer_input") model = keras.models.Model(outer_input, inner_model(outer_input)) # # +-------------------------+ # |outer_input (InputLayer) | # +-------------------------+ # | # v # +-------------------------+ # | inner (Functional) | # +-------------------------+ # edge_dict = get_edge_dict(model_to_dot(model)) self.assertEqual( edge_dict, { "outer_input (InputLayer)": "inner (Functional)", }, ) self.multi_plot_model(model, "functional_in_functional") # # +-------------------------+ # |outer_input (InputLayer) | # +-------------------------+ # | # +--------------|--------------+ # | inner v | # | +-------------------------+ | # | |inner_input (InputLayer) | | # | +-------------------------+ | # | | | # | v | # | +-------------------------+ | # | | dense1 (Dense) | | # | +-------------------------+ | # | | | # | v | # | +-------------------------+ | # | | dense2 (Dense) | | # | +-------------------------+ | # +-----------------------------+ # edge_dict = get_edge_dict(model_to_dot(model, expand_nested=True)) self.assertEqual( edge_dict, { "outer_input (InputLayer)": "inner > inner_input (InputLayer)", "inner > inner_input (InputLayer)": "inner > dense1 (Dense)", "inner > dense1 (Dense)": "inner > dense2 (Dense)", }, ) self.multi_plot_model( model, "functional_in_functional", expand_nested=True ) def test_plot_sequential_in_sequential_in_sequential(self): inner_model = keras.models.Sequential( [ keras.layers.Dense(10, name="dense2"), keras.layers.Dense(10, name="dense3"), ], name="inner", ) mid_model = keras.models.Sequential( [ inner_model, ], name="mid", ) model = keras.models.Sequential( [ keras.layers.Dense(10, name="dense1"), mid_model, keras.layers.Dense(10, name="dense4"), ], ) model.build((1, 10)) # # +-------------------------+ # | dense1 (Dense) | # +-------------------------+ # | # v # +-------------------------+ # | mid (Sequential) | # +-------------------------+ # | # v # +-------------------------+ # | dense4 (Dense) | # +-------------------------+ # edge_dict = get_edge_dict(model_to_dot(model)) self.assertEqual( edge_dict, { "dense1 (Dense)": "mid (Sequential)", "mid (Sequential)": "dense4 (Dense)", }, ) self.multi_plot_model(model, "sequential_in_sequential_in_sequential") # # +-------------------------+ # | dense1 (Dense) | # +-------------------------+ # | # +----------------|----------------+ # | mid | | # | +--------------|--------------+ | # | | inner v | | # | | +-------------------------+ | | # | | | dense2 (Dense) | | | # | | +-------------------------+ | | # | | | | | # | | v | | # | | +-------------------------+ | | # | | | dense3 (Dense) | | | # | | +-------------------------+ | | # | +--------------|--------------+ | # +----------------|----------------+ # v # +-------------------------+ # | dense4 (Dense) | # +-------------------------+ # edge_dict = get_edge_dict(model_to_dot(model, expand_nested=True)) self.assertEqual( edge_dict, { "dense1 (Dense)": "mid > inner > dense2 (Dense)", "mid > inner > dense2 (Dense)": "mid > inner > dense3 (Dense)", "mid > inner > dense3 (Dense)": "dense4 (Dense)", }, ) self.multi_plot_model( model, "sequential_in_sequential_in_sequential", expand_nested=True ) def test_plot_functional_in_sequential_in_sequential(self): input1 = keras.layers.Input((10,), name="input1") x = keras.layers.Dense(10, name="dense2")(input1) inner_model = keras.models.Model(input1, x, name="inner") mid_model = keras.models.Sequential( [ inner_model, ], name="mid", ) model = keras.models.Sequential( [ keras.layers.Dense(10, name="dense1"), mid_model, keras.layers.Dense(10, name="dense3"), ], ) model.build((1, 10)) # # +-------------------------+ # | dense1 (Dense) | # +-------------------------+ # | # v # +-------------------------+ # | mid (Sequential) | # +-------------------------+ # | # v # +-------------------------+ # | dense3 (Dense) | # +-------------------------+ # edge_dict = get_edge_dict(model_to_dot(model)) self.assertEqual( edge_dict, { "dense1 (Dense)": "mid (Sequential)", "mid (Sequential)": "dense3 (Dense)", }, ) self.multi_plot_model(model, "functional_in_sequential_in_sequential") # # +-------------------------+ # | dense1 (Dense) | # +-------------------------+ # | # +----------------|----------------+ # | mid | | # | +--------------|--------------+ | # | | inner v | | # | | +-------------------------+ | | # | | | input1 (Inputlayer) | | | # | | +-------------------------+ | | # | | | | | # | | v | | # | | +-------------------------+ | | # | | | dense2 (Dense) | | | # | | +-------------------------+ | | # | +--------------|--------------+ | # +----------------|----------------+ # v # +-------------------------+ # | dense3 (Dense) | # +-------------------------+ # edge_dict = get_edge_dict(model_to_dot(model, expand_nested=True)) self.assertEqual( edge_dict, { "dense1 (Dense)": "mid > inner > input1 (InputLayer)", "mid > inner > input1 (InputLayer)": "mid > inner > dense2 (Dense)", # noqa: E501 "mid > inner > dense2 (Dense)": "dense3 (Dense)", }, ) self.multi_plot_model( model, "functional_in_sequential_in_sequential", expand_nested=True ) def test_plot_functional_in_functional_in_functional(self): # From https://github.com/keras-team/keras/issues/21119 inner_input = keras.layers.Input((10,), name="inner_input") x = keras.layers.Dense(10, name="dense1")(inner_input) inner_model = keras.models.Model(inner_input, x, name="inner") mid_input = keras.layers.Input((10,), name="mid_input") mid_output = inner_model(mid_input) mid_model = keras.models.Model(mid_input, mid_output, name="mid") outer_input = keras.layers.Input((10,), name="outer_input") x = mid_model(outer_input) x = keras.layers.Dense(10, name="dense2")(x) model = keras.models.Model(outer_input, x) # # +-------------------------+ # |outer_input (InputLayer) | # +-------------------------+ # | # v # +-------------------------+ # | mid (Functional) | # +-------------------------+ # | # v # +-------------------------+ # | dense2 (Dense) | # +-------------------------+ # edge_dict = get_edge_dict(model_to_dot(model)) self.assertEqual( edge_dict, { "outer_input (InputLayer)": "mid (Functional)", "mid (Functional)": "dense2 (Dense)", }, ) self.multi_plot_model(model, "functional_in_functional_in_functional") # # +-------------------------+ # |outer_input (InputLayer) | # +-------------------------+ # | # +----------------|----------------+ # | mid | | # | +-------------------------+ | # | | mid_input (Inputlayer) | | # | +-------------------------+ | # | +--------------|--------------+ | # | | inner v | | # | | +-------------------------+ | | # | | |inner_input (Inputlayer) | | | # | | +-------------------------+ | | # | | | | | # | | v | | # | | +-------------------------+ | | # | | | dense1 (Dense) | | | # | | +-------------------------+ | | # | +--------------|--------------+ | # +----------------|----------------+ # v # +-------------------------+ # | dense2 (Dense) | # +-------------------------+ # edge_dict = get_edge_dict(model_to_dot(model, expand_nested=True)) self.assertEqual( edge_dict, { "outer_input (InputLayer)": "mid > mid_input (InputLayer)", "mid > mid_input (InputLayer)": "mid > inner > inner_input (InputLayer)", # noqa: E501 "mid > inner > inner_input (InputLayer)": "mid > inner > dense1 (Dense)", # noqa: E501 "mid > inner > dense1 (Dense)": "dense2 (Dense)", }, ) self.multi_plot_model( model, "functional_in_functional_in_functional", expand_nested=True ) def test_plot_complex(self): # Note: this test exercises the case when `output_index` is not 0 and # changes when going deeply in nested models to resolve the destination # of an edge. inner_inpt1 = keras.layers.Input(shape=(10,), name="inner_inpt1") inner_inpt2 = keras.layers.Input(shape=(10,), name="inner_inpt2") inner_model = keras.models.Model( [inner_inpt1, inner_inpt2], [ keras.layers.Dense(10, name="dense1")(inner_inpt1), keras.layers.Dense(10, name="dense2")(inner_inpt2), ], name="inner", ) input0 = keras.layers.Input(shape=(10,), name="input0") input1 = keras.layers.Input(shape=(10,), name="input1") input2 = keras.layers.Input(shape=(10,), name="input2") input3 = keras.layers.Input(shape=(10,), name="input3") mid_sequential = keras.models.Sequential( [ keras.layers.Dense(10, name="dense0"), SubclassModel(name="subclass0"), ], name="seq", ) mid_subclass = SubclassModel(name="subclass3") mid_model = keras.models.Model( [input0, input1, input2, input3], [ mid_sequential(input0), *inner_model([input1, input2]), mid_subclass(input3), ], name="mid", ) outer_input = keras.layers.Input((10,), name="outer_input") mid_outputs = mid_model( [outer_input, outer_input, outer_input, outer_input] ) model = keras.models.Model( outer_input, [ keras.layers.Add(name="add1")([mid_outputs[0], mid_outputs[1]]), keras.layers.Add(name="add2")([mid_outputs[2], mid_outputs[3]]), ], ) # # +-------------------------+ # |outer_input (InputLayer) | # +-------------------------+ # | # v # +-------------------------+ # | mid (Functional) | # +-------------------------+ # | | # v v # +-------------------------+ +-------------------------+ # | add1 (Add) | | add2 (Add) | # +-------------------------+ +-------------------------+ # edge_dict = get_edge_dict(model_to_dot(model)) self.assertEqual( edge_dict, { "outer_input (InputLayer)": "mid (Functional)", "mid (Functional)": {"add1 (Add)", "add2 (Add)"}, }, ) self.multi_plot_model(model, "complex") # # +-----------+ # +------------------|outer_input|-----------------+ # | +-----------+ | # | | | | # +---------|-------------------|---------|------------------|-------+ # | mid v v v v | # | +-----------+ +-----------+ +-----------+ +-----------+ | # | | input0 | | input1 | | input2 | | input3 | | # | +-----------+ +-----------+ +-----------+ +-----------+ | # | +-------|-------+ +-------|-------------|-------+ | | # | | seq v | | inner v v | | | # | | +-----------+ | | +-----------+ +-----------+ | +-----------+ | # | | | dense0 | | | |inner_inp1t| |inner_inp2t| | | subclass3 | | # | | +-----------+ | | +-----------+ +-----------+ | +-----------+ | # | | | | | | | | | | # | | v | | v v | | | # | | +-----------+ | | +-----------+ +-----------+ | | | # | | | subclass0 | | | | dense1 | | dense2 | | | | # | | +-----------+ | | +-----------+ +-----------+ | | | # | +-----------|---+ +---|---------------------|---+ | | # +-------------|---------|---------------------|--------|-----------+ # v v v v # +-----------+ +-----------+ # | add1 | | add2 | # +-----------+ +-----------+ # edge_dict = get_edge_dict(model_to_dot(model, expand_nested=True)) self.assertEqual( edge_dict, { # 1st row "outer_input (InputLayer)": { "mid > input0 (InputLayer)", "mid > input1 (InputLayer)", "mid > input2 (InputLayer)", "mid > input3 (InputLayer)", }, # 2nd row "mid > input0 (InputLayer)": "mid > seq > dense0 (Dense)", "mid > input1 (InputLayer)": "mid > inner > inner_inpt1 (InputLayer)", # noqa: E501 "mid > input2 (InputLayer)": "mid > inner > inner_inpt2 (InputLayer)", # noqa: E501 "mid > input3 (InputLayer)": "mid > subclass3 (SubclassModel)", # 3rd row "mid > seq > dense0 (Dense)": "mid > seq > subclass0 (SubclassModel)", # noqa: E501 "mid > inner > inner_inpt1 (InputLayer)": "mid > inner > dense1 (Dense)", # noqa: E501 "mid > inner > inner_inpt2 (InputLayer)": "mid > inner > dense2 (Dense)", # noqa: E501 # 4th row "mid > seq > subclass0 (SubclassModel)": "add1 (Add)", "mid > inner > dense1 (Dense)": "add1 (Add)", "mid > inner > dense2 (Dense)": "add2 (Add)", "mid > subclass3 (SubclassModel)": "add2 (Add)", }, ) self.multi_plot_model(model, "complex", expand_nested=True)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/jax_custom_fit_test.py
integration_tests/jax_custom_fit_test.py
import jax import numpy as np import keras def test_custom_fit(): class CustomModel(keras.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.loss_tracker = keras.metrics.Mean(name="loss") self.mae_metric = keras.metrics.MeanAbsoluteError(name="mae") self.loss_fn = keras.losses.MeanSquaredError() def compute_loss_and_updates( self, trainable_variables, non_trainable_variables, x, y, training=False, ): y_pred, non_trainable_variables = self.stateless_call( trainable_variables, non_trainable_variables, x, training=training, ) loss = self.loss_fn(y, y_pred) return loss, (y_pred, non_trainable_variables) def train_step(self, state, data): ( trainable_variables, non_trainable_variables, optimizer_variables, metrics_variables, ) = state x, y = data grad_fn = jax.value_and_grad( self.compute_loss_and_updates, has_aux=True ) (loss, (y_pred, non_trainable_variables)), grads = grad_fn( trainable_variables, non_trainable_variables, x, y, training=True, ) ( trainable_variables, optimizer_variables, ) = self.optimizer.stateless_apply( optimizer_variables, grads, trainable_variables ) loss_tracker_vars = metrics_variables[ : len(self.loss_tracker.variables) ] mae_metric_vars = metrics_variables[ len(self.loss_tracker.variables) : ] loss_tracker_vars = self.loss_tracker.stateless_update_state( loss_tracker_vars, loss ) mae_metric_vars = self.mae_metric.stateless_update_state( mae_metric_vars, y, y_pred ) logs = {} logs[self.loss_tracker.name] = self.loss_tracker.stateless_result( loss_tracker_vars ) logs[self.mae_metric.name] = self.mae_metric.stateless_result( mae_metric_vars ) new_metrics_vars = loss_tracker_vars + mae_metric_vars state = ( trainable_variables, non_trainable_variables, optimizer_variables, new_metrics_vars, ) return logs, state @property def metrics(self): return [self.loss_tracker, self.mae_metric] inputs = keras.Input(shape=(32,)) outputs = keras.layers.Dense(1)(inputs) model = CustomModel(inputs, outputs) model.compile(optimizer="adam") x = np.random.random((64, 32)) y = np.random.random((64, 1)) history = model.fit(x, y, epochs=1) assert "loss" in history.history assert "mae" in history.history print("History:") print(history.history) if __name__ == "__main__": test_custom_fit()
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/tf_custom_fit_test.py
integration_tests/tf_custom_fit_test.py
import numpy as np import tensorflow as tf import keras def test_custom_fit(): class CustomModel(keras.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.loss_tracker = keras.metrics.Mean(name="loss") self.mae_metric = keras.metrics.MeanAbsoluteError(name="mae") self.loss_fn = keras.losses.MeanSquaredError() def train_step(self, data): x, y = data with tf.GradientTape() as tape: y_pred = self(x, training=True) loss = self.loss_fn(y, y_pred) trainable_vars = self.trainable_variables gradients = tape.gradient(loss, trainable_vars) self.optimizer.apply(gradients, trainable_vars) self.loss_tracker.update_state(loss) self.mae_metric.update_state(y, y_pred) return { "loss": self.loss_tracker.result(), "mae": self.mae_metric.result(), } @property def metrics(self): return [self.loss_tracker, self.mae_metric] inputs = keras.Input(shape=(32,)) outputs = keras.layers.Dense(1)(inputs) model = CustomModel(inputs, outputs) model.compile(optimizer="adam") x = np.random.random((64, 32)) y = np.random.random((64, 1)) history = model.fit(x, y, epochs=1) assert "loss" in history.history assert "mae" in history.history print("History:") print(history.history) if __name__ == "__main__": test_custom_fit()
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/numerical_test.py
integration_tests/numerical_test.py
import keras # isort: skip, keep it on top for torch test import sys import numpy as np import tf_keras keras.backend.set_image_data_format("channels_last") tf_keras.backend.set_image_data_format("channels_last") NUM_CLASSES = 10 BATCH_SIZE = 32 EPOCHS = 1 def build_mnist_data(num_classes): (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() # Scale images to the [0, 1] range x_train = x_train.astype("float32") / 255 x_test = x_test.astype("float32") / 255 # Make sure images have shape (28, 28, 1) x_train = np.expand_dims(x_train, -1) x_test = np.expand_dims(x_test, -1) # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) return x_train[:100], y_train[:100] def build_keras_model(keras_module, num_classes): input_shape = (28, 28, 1) model = keras_module.Sequential( [ keras_module.Input(shape=input_shape), keras_module.layers.Conv2D( 32, kernel_size=(3, 3), activation="relu" ), keras_module.layers.BatchNormalization(), keras_module.layers.MaxPooling2D(pool_size=(2, 2)), keras_module.layers.Conv2D( 64, kernel_size=(3, 3), activation="relu" ), keras_module.layers.BatchNormalization(scale=False, center=True), keras_module.layers.MaxPooling2D(pool_size=(2, 2)), keras_module.layers.Flatten(), keras_module.layers.Dense(num_classes, activation="softmax"), ] ) return model def compile_model(model): model.compile( loss="categorical_crossentropy", optimizer="adam", metrics=["mae", "accuracy"], jit_compile=False, run_eagerly=True, ) def train_model(model, x, y): return model.fit( x, y, batch_size=BATCH_SIZE, epochs=EPOCHS, shuffle=False, verbose=0, ) def eval_model(model, x, y): score = model.evaluate(x, y, verbose=0, batch_size=BATCH_SIZE) print(score) return score def check_history(h1, h2): for key in h1.history.keys(): print(f"{key}:") print(h1.history[key]) print(h2.history[key]) np.testing.assert_allclose( h1.history[key], h2.history[key], atol=1e-3, ) def predict_model(model, x): return model.predict(x, batch_size=BATCH_SIZE, verbose=0) def numerical_test(): x_train, y_train = build_mnist_data(NUM_CLASSES) keras_model = build_keras_model(keras, NUM_CLASSES) tf_keras_model = build_keras_model(tf_keras, NUM_CLASSES) # Make sure both model have same weights before training weights = [weight.numpy() for weight in keras_model.weights] tf_keras_model.set_weights(weights) for kw, kcw in zip(keras_model.weights, tf_keras_model.weights): np.testing.assert_allclose(kw.numpy(), kcw.numpy()) compile_model(keras_model) compile_model(tf_keras_model) print("Checking training histories:") keras_history = train_model(keras_model, x_train, y_train) tf_keras_history = train_model(tf_keras_model, x_train, y_train) check_history(keras_history, tf_keras_history) print("Training histories match.") print() print("Checking trained weights:") for kw, kcw in zip(keras_model.weights, tf_keras_model.weights): np.testing.assert_allclose(kw.numpy(), kcw.numpy(), atol=1e-3) print("Trained weights match.") print() print("Checking predict:") outputs1 = predict_model(keras_model, x_train) outputs2 = predict_model(tf_keras_model, x_train) np.testing.assert_allclose(outputs1, outputs2, atol=1e-3) print("Predict results match.") print() print("Checking evaluate:") score1 = eval_model(keras_model, x_train, y_train) score2 = eval_model(tf_keras_model, x_train, y_train) np.testing.assert_allclose(score1, score2, atol=1e-3) print("Evaluate results match.") if __name__ == "__main__": if keras.backend.backend() == "openvino": # this test requires trainable backend sys.exit(0) keras.utils.set_random_seed(1337) tf_keras.utils.set_random_seed(1337) numerical_test()
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/tf_distribute_training_test.py
integration_tests/tf_distribute_training_test.py
import numpy as np import tensorflow as tf import keras from keras.src import layers from keras.src import losses from keras.src import metrics from keras.src import models from keras.src import optimizers from keras.src.callbacks import LearningRateScheduler def test_model_fit(): cpus = tf.config.list_physical_devices("CPU") tf.config.set_logical_device_configuration( cpus[0], [ tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration(), ], ) keras.utils.set_random_seed(1337) strategy = tf.distribute.MirroredStrategy(["CPU:0", "CPU:1"]) with strategy.scope(): inputs = layers.Input((100,), batch_size=32) x = layers.Dense(256, activation="relu")(inputs) x = layers.Dense(256, activation="relu")(x) x = layers.Dense(256, activation="relu")(x) x = layers.BatchNormalization()(x) outputs = layers.Dense(16)(x) model = models.Model(inputs, outputs) callbacks = [LearningRateScheduler(lambda _: 0.1)] model.summary() x = np.random.random((5000, 100)) y = np.random.random((5000, 16)) batch_size = 32 epochs = 2 # Fit from numpy arrays: with strategy.scope(): model.compile( optimizer=optimizers.LossScaleOptimizer( optimizers.SGD(learning_rate=0.001, momentum=0.01) ), loss=losses.MeanSquaredError(), metrics=[metrics.MeanSquaredError()], ) history = model.fit( x, y, batch_size=batch_size, epochs=epochs, validation_split=0.2, callbacks=callbacks, ) print("History:") print(history.history) # Fit again from distributed dataset: with strategy.scope(): dataset = tf.data.Dataset.from_tensor_slices((x, y)).batch(batch_size) dataset = strategy.experimental_distribute_dataset(dataset) history = model.fit(dataset, epochs=epochs, callbacks=callbacks) print("History:") print(history.history) if __name__ == "__main__": test_model_fit()
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/dataset_tests/cifar100_test.py
integration_tests/dataset_tests/cifar100_test.py
import numpy as np from keras.src import testing from keras.src.datasets import cifar100 class Cifar100LoadDataTest(testing.TestCase): def test_shapes_fine_label_mode(self): (x_train, y_train), (x_test, y_test) = cifar100.load_data( label_mode="fine" ) self.assertEqual(x_train.shape, (50000, 32, 32, 3)) self.assertEqual(y_train.shape, (50000, 1)) self.assertEqual(x_test.shape, (10000, 32, 32, 3)) self.assertEqual(y_test.shape, (10000, 1)) def test_shapes_coarse_label_mode(self): (x_train, y_train), (x_test, y_test) = cifar100.load_data( label_mode="coarse" ) self.assertEqual(x_train.shape, (50000, 32, 32, 3)) self.assertEqual(y_train.shape, (50000, 1)) self.assertEqual(x_test.shape, (10000, 32, 32, 3)) self.assertEqual(y_test.shape, (10000, 1)) def test_dtypes(self): (x_train, y_train), (x_test, y_test) = cifar100.load_data() self.assertEqual(x_train.dtype, np.uint8) self.assertEqual(y_train.dtype, np.int64) self.assertEqual(x_test.dtype, np.uint8) self.assertEqual(y_test.dtype, np.int64) def test_invalid_label_mode(self): with self.assertRaises(ValueError): cifar100.load_data(label_mode="invalid")
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/dataset_tests/reuters_test.py
integration_tests/dataset_tests/reuters_test.py
import numpy as np from keras.src import testing from keras.src.datasets import reuters class ReutersLoadDataTest(testing.TestCase): def test_load_data_default(self): (x_train, y_train), (x_test, y_test) = reuters.load_data() # Check types self.assertIsInstance(x_train, np.ndarray) self.assertIsInstance(y_train, np.ndarray) self.assertIsInstance(x_test, np.ndarray) self.assertIsInstance(y_test, np.ndarray) # Check shapes self.assertGreater(len(x_train), 0) self.assertEqual(len(x_train), len(y_train)) self.assertGreater(len(x_test), 0) self.assertEqual(len(x_test), len(y_test)) def test_num_words(self): # Only consider the top 1000 words (x_train, _), _ = reuters.load_data(num_words=1000) # Ensure no word index exceeds 999 (0-based indexing) max_index = max(max(sequence) for sequence in x_train if sequence) self.assertLessEqual(max_index, 999) def test_skip_top(self): # Skip the top 10 most frequent words (x_train, _), _ = reuters.load_data(skip_top=10, num_words=1000) # Assuming 1 is among top 10, check if it's skipped self.assertNotIn(1, x_train[0]) def test_maxlen(self): # Only consider sequences shorter than 50 (x_train, _), _ = reuters.load_data(maxlen=50) self.assertTrue(all(len(seq) <= 50 for seq in x_train)) def test_get_word_index(self): word_index = reuters.get_word_index() self.assertIsInstance(word_index, dict) # Check if word_index contains specific known words self.assertIn("the", word_index) def test_get_label_names(self): label_names = reuters.get_label_names() self.assertIsInstance(label_names, tuple) # Check if the tuple contains specific known labels self.assertIn("earn", label_names) self.assertIn("acq", label_names)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/dataset_tests/mnist_test.py
integration_tests/dataset_tests/mnist_test.py
import numpy as np from keras.src import testing from keras.src.datasets import mnist class MnistLoadDataTest(testing.TestCase): def test_x_train_shape(self): (x_train, _), _ = mnist.load_data() self.assertEqual(x_train.shape, (60000, 28, 28)) def test_y_train_shape(self): (_, y_train), _ = mnist.load_data() self.assertEqual(y_train.shape, (60000,)) def test_x_test_shape(self): _, (x_test, _) = mnist.load_data() self.assertEqual(x_test.shape, (10000, 28, 28)) def test_y_test_shape(self): _, (_, y_test) = mnist.load_data() self.assertEqual(y_test.shape, (10000,)) def test_x_train_dtype(self): (x_train, _), _ = mnist.load_data() self.assertEqual(x_train.dtype, np.uint8) def test_y_train_dtype(self): (_, y_train), _ = mnist.load_data() self.assertEqual(y_train.dtype, np.uint8) def test_x_test_dtype(self): _, (x_test, _) = mnist.load_data() self.assertEqual(x_test.dtype, np.uint8) def test_y_test_dtype(self): _, (_, y_test) = mnist.load_data() self.assertEqual(y_test.dtype, np.uint8)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false
keras-team/keras
https://github.com/keras-team/keras/blob/c67eddb4ff8b615886893ca996dc216bc923d598/integration_tests/dataset_tests/imdb_test.py
integration_tests/dataset_tests/imdb_test.py
import numpy as np from keras.src import testing from keras.src.datasets import imdb class ImdbLoadDataTest(testing.TestCase): def test_load_data_default(self): (x_train, y_train), (x_test, y_test) = imdb.load_data() self.assertIsInstance(x_train, np.ndarray) self.assertIsInstance(y_train, np.ndarray) self.assertIsInstance(x_test, np.ndarray) self.assertIsInstance(y_test, np.ndarray) # Check lengths self.assertEqual(len(x_train), 25000) self.assertEqual(len(y_train), 25000) self.assertEqual(len(x_test), 25000) self.assertEqual(len(y_test), 25000) # Check types within lists for x self.assertIsInstance(x_train[0], list) self.assertIsInstance(x_test[0], list) def test_num_words(self): # Only consider the top 1000 words (x_train, _), _ = imdb.load_data(num_words=1000) # Ensure that no word index exceeds 999 (0-based indexing) max_index = max(max(sequence) for sequence in x_train if sequence) self.assertLessEqual(max_index, 999) def test_skip_top(self): # Skip the top 10 most frequent words (x_train, _), _ = imdb.load_data(skip_top=10, num_words=1000) # Check if top 10 words are skipped properly self.assertNotIn(1, x_train[0]) # Assuming 1 is among top 10 def test_maxlen(self): # Only consider sequences shorter than 100 (x_train, _), _ = imdb.load_data(maxlen=100) self.assertTrue(all(len(seq) <= 100 for seq in x_train)) def test_get_word_index(self): word_index = imdb.get_word_index() self.assertIsInstance(word_index, dict) # Check if word_index contains specific known words self.assertIn("the", word_index) self.assertIn("and", word_index)
python
Apache-2.0
c67eddb4ff8b615886893ca996dc216bc923d598
2026-01-04T14:38:29.819962Z
false